kernel32: Declare and add stubs for GetLogicalProcessorInformation(Ex).
[wine] / dlls / kernel32 / debugger.c
1 /*
2  * Win32 debugger functions
3  *
4  * Copyright (C) 1999 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include <stdio.h>
22 #include <string.h>
23
24 #include "ntstatus.h"
25 #define WIN32_NO_STATUS
26 #include "winerror.h"
27 #include "wine/server.h"
28 #include "kernel_private.h"
29 #include "wine/debug.h"
30
31 WINE_DEFAULT_DEBUG_CHANNEL(debugstr);
32
33
34 /******************************************************************************
35  *           WaitForDebugEvent   (KERNEL32.@)
36  *
37  *  Waits for a debugging event to occur in a process being debugged before
38  *  filling out the debug event structure.
39  *
40  * PARAMS
41  *  event   [O] Address of structure for event information.
42  *  timeout [I] Number of milliseconds to wait for event.
43  *
44  * RETURNS
45  *
46  *  Returns true if a debug event occurred and false if the call timed out.
47  */
48 BOOL WINAPI WaitForDebugEvent(
49     LPDEBUG_EVENT event,
50     DWORD         timeout)
51 {
52     BOOL ret;
53     DWORD i, res;
54
55     for (;;)
56     {
57         HANDLE wait = 0;
58         debug_event_t data;
59         SERVER_START_REQ( wait_debug_event )
60         {
61             req->get_handle = (timeout != 0);
62             wine_server_set_reply( req, &data, sizeof(data) );
63             if (!(ret = !wine_server_call_err( req ))) goto done;
64
65             if (!wine_server_reply_size(reply))  /* timeout */
66             {
67                 wait = wine_server_ptr_handle( reply->wait );
68                 ret = FALSE;
69                 goto done;
70             }
71             event->dwDebugEventCode = data.code;
72             event->dwProcessId      = (DWORD)reply->pid;
73             event->dwThreadId       = (DWORD)reply->tid;
74             switch(data.code)
75             {
76             case EXCEPTION_DEBUG_EVENT:
77                 event->u.Exception.dwFirstChance = data.exception.first;
78                 event->u.Exception.ExceptionRecord.ExceptionCode    = data.exception.exc_code;
79                 event->u.Exception.ExceptionRecord.ExceptionFlags   = data.exception.flags;
80                 event->u.Exception.ExceptionRecord.ExceptionRecord  = wine_server_get_ptr( data.exception.record );
81                 event->u.Exception.ExceptionRecord.ExceptionAddress = wine_server_get_ptr( data.exception.address );
82                 event->u.Exception.ExceptionRecord.NumberParameters = data.exception.nb_params;
83                 for (i = 0; i < data.exception.nb_params; i++)
84                     event->u.Exception.ExceptionRecord.ExceptionInformation[i] = data.exception.params[i];
85                 break;
86             case CREATE_THREAD_DEBUG_EVENT:
87                 event->u.CreateThread.hThread           = wine_server_ptr_handle( data.create_thread.handle );
88                 event->u.CreateThread.lpThreadLocalBase = wine_server_get_ptr( data.create_thread.teb );
89                 event->u.CreateThread.lpStartAddress    = wine_server_get_ptr( data.create_thread.start );
90                 break;
91             case CREATE_PROCESS_DEBUG_EVENT:
92                 event->u.CreateProcessInfo.hFile                 = wine_server_ptr_handle( data.create_process.file );
93                 event->u.CreateProcessInfo.hProcess              = wine_server_ptr_handle( data.create_process.process );
94                 event->u.CreateProcessInfo.hThread               = wine_server_ptr_handle( data.create_process.thread );
95                 event->u.CreateProcessInfo.lpBaseOfImage         = wine_server_get_ptr( data.create_process.base );
96                 event->u.CreateProcessInfo.dwDebugInfoFileOffset = data.create_process.dbg_offset;
97                 event->u.CreateProcessInfo.nDebugInfoSize        = data.create_process.dbg_size;
98                 event->u.CreateProcessInfo.lpThreadLocalBase     = wine_server_get_ptr( data.create_process.teb );
99                 event->u.CreateProcessInfo.lpStartAddress        = wine_server_get_ptr( data.create_process.start );
100                 event->u.CreateProcessInfo.lpImageName           = wine_server_get_ptr( data.create_process.name );
101                 event->u.CreateProcessInfo.fUnicode              = data.create_process.unicode;
102                 break;
103             case EXIT_THREAD_DEBUG_EVENT:
104                 event->u.ExitThread.dwExitCode = data.exit.exit_code;
105                 break;
106             case EXIT_PROCESS_DEBUG_EVENT:
107                 event->u.ExitProcess.dwExitCode = data.exit.exit_code;
108                 break;
109             case LOAD_DLL_DEBUG_EVENT:
110                 event->u.LoadDll.hFile                 = wine_server_ptr_handle( data.load_dll.handle );
111                 event->u.LoadDll.lpBaseOfDll           = wine_server_get_ptr( data.load_dll.base );
112                 event->u.LoadDll.dwDebugInfoFileOffset = data.load_dll.dbg_offset;
113                 event->u.LoadDll.nDebugInfoSize        = data.load_dll.dbg_size;
114                 event->u.LoadDll.lpImageName           = wine_server_get_ptr( data.load_dll.name );
115                 event->u.LoadDll.fUnicode              = data.load_dll.unicode;
116                 break;
117             case UNLOAD_DLL_DEBUG_EVENT:
118                 event->u.UnloadDll.lpBaseOfDll = wine_server_get_ptr( data.unload_dll.base );
119                 break;
120             case OUTPUT_DEBUG_STRING_EVENT:
121                 event->u.DebugString.lpDebugStringData  = wine_server_get_ptr( data.output_string.string );
122                 event->u.DebugString.fUnicode           = FALSE;
123                 event->u.DebugString.nDebugStringLength = data.output_string.length;
124                 break;
125             case RIP_EVENT:
126                 event->u.RipInfo.dwError = data.rip_info.error;
127                 event->u.RipInfo.dwType  = data.rip_info.type;
128                 break;
129             }
130         done:
131             /* nothing */ ;
132         }
133         SERVER_END_REQ;
134         if (ret) return TRUE;
135         if (!wait) break;
136         res = WaitForSingleObject( wait, timeout );
137         CloseHandle( wait );
138         if (res != STATUS_WAIT_0) break;
139     }
140     SetLastError( ERROR_SEM_TIMEOUT );
141     return FALSE;
142 }
143
144
145 /**********************************************************************
146  *           ContinueDebugEvent   (KERNEL32.@)
147  *
148  *  Enables a thread that previously produced a debug event to continue.
149  *
150  * PARAMS
151  *  pid    [I] The id of the process to continue.
152  *  tid    [I] The id of the thread to continue.
153  *  status [I] The rule to apply to unhandled exeptions.
154  *
155  * RETURNS
156  *
157  *  True if the debugger is listed as the processes owner and the process
158  *  and thread are valid.
159  */
160 BOOL WINAPI ContinueDebugEvent(
161     DWORD pid,
162     DWORD tid,
163     DWORD status)
164 {
165     BOOL ret;
166     SERVER_START_REQ( continue_debug_event )
167     {
168         req->pid    = pid;
169         req->tid    = tid;
170         req->status = status;
171         ret = !wine_server_call_err( req );
172     }
173     SERVER_END_REQ;
174     return ret;
175 }
176
177
178 /**********************************************************************
179  *           DebugActiveProcess   (KERNEL32.@)
180  *
181  *  Attempts to attach the debugger to a process.
182  *
183  * PARAMS
184  *  pid [I] The process to be debugged.
185  *
186  * RETURNS
187  *
188  *  True if the debugger was attached to process.
189  */
190 BOOL WINAPI DebugActiveProcess( DWORD pid )
191 {
192     BOOL ret;
193     SERVER_START_REQ( debug_process )
194     {
195         req->pid = pid;
196         req->attach = 1;
197         ret = !wine_server_call_err( req );
198     }
199     SERVER_END_REQ;
200     return ret;
201 }
202
203 /**********************************************************************
204  *           DebugActiveProcessStop   (KERNEL32.@)
205  *
206  *  Attempts to detach the debugger from a process.
207  *
208  * PARAMS
209  *  pid [I] The process to be detached.
210  *
211  * RETURNS
212  *
213  *  True if the debugger was detached from the process.
214  */
215 BOOL WINAPI DebugActiveProcessStop( DWORD pid )
216 {
217     BOOL ret;
218     SERVER_START_REQ( debug_process )
219     {
220         req->pid = pid;
221         req->attach = 0;
222         ret = !wine_server_call_err( req );
223     }
224     SERVER_END_REQ;
225     return ret;
226 }
227
228
229 /***********************************************************************
230  *           OutputDebugStringA   (KERNEL32.@)
231  *
232  *  Output by an application of an ascii string to a debugger (if attached)
233  *  and program log.
234  *
235  * PARAMS
236  *  str [I] The message to be logged and given to the debugger.
237  *
238  * RETURNS
239  *
240  *  Nothing.
241  */
242 void WINAPI OutputDebugStringA( LPCSTR str )
243 {
244     static HANDLE DBWinMutex = NULL;
245     static BOOL mutex_inited = FALSE;
246
247     /* send string to attached debugger */
248     SERVER_START_REQ( output_debug_string )
249     {
250         req->string  = wine_server_client_ptr( str );
251         req->length  = strlen(str) + 1;
252         wine_server_call( req );
253     }
254     SERVER_END_REQ;
255
256     WARN("%s\n", str);
257
258     /* send string to a system-wide monitor */
259     /* FIXME should only send to monitor if no debuggers are attached */
260
261     if (!mutex_inited)
262     {
263         /* first call to OutputDebugString, initialize mutex handle */
264         static const WCHAR mutexname[] = {'D','B','W','i','n','M','u','t','e','x',0};
265         HANDLE mutex = CreateMutexExW( NULL, mutexname, 0, SYNCHRONIZE );
266         if (mutex)
267         {
268             if (InterlockedCompareExchangePointer( &DBWinMutex, mutex, 0 ) != 0)
269             {
270                 /* someone beat us here... */
271                 CloseHandle( mutex );
272             }
273         }
274         mutex_inited = TRUE;
275     }
276
277     if (DBWinMutex)
278     {
279         static const WCHAR shmname[] = {'D','B','W','I','N','_','B','U','F','F','E','R',0};
280         static const WCHAR eventbuffername[] = {'D','B','W','I','N','_','B','U','F','F','E','R','_','R','E','A','D','Y',0};
281         static const WCHAR eventdataname[] = {'D','B','W','I','N','_','D','A','T','A','_','R','E','A','D','Y',0};
282         HANDLE mapping;
283
284         mapping = OpenFileMappingW( FILE_MAP_WRITE, FALSE, shmname );
285         if (mapping)
286         {
287             LPVOID buffer;
288             HANDLE eventbuffer, eventdata;
289
290             buffer = MapViewOfFile( mapping, FILE_MAP_WRITE, 0, 0, 0 );
291             eventbuffer = OpenEventW( SYNCHRONIZE, FALSE, eventbuffername );
292             eventdata = OpenEventW( EVENT_MODIFY_STATE, FALSE, eventdataname );
293
294             if (buffer && eventbuffer && eventdata)
295             {
296                 /* monitor is present, synchronize with other OutputDebugString invokations */
297                 WaitForSingleObject( DBWinMutex, INFINITE );
298
299                 /* acquire control over the buffer */
300                 if (WaitForSingleObject( eventbuffer, 10000 ) == WAIT_OBJECT_0)
301                 {
302                     int str_len;
303                     struct _mon_buffer_t {
304                         DWORD pid;
305                         char buffer[1];
306                     } *mon_buffer = (struct _mon_buffer_t*) buffer;
307
308                     str_len = strlen( str );
309                     if (str_len > (4096 - sizeof(DWORD) - 1))
310                         str_len = 4096 - sizeof(DWORD) - 1;
311
312                     mon_buffer->pid = GetCurrentProcessId();
313                     memcpy( mon_buffer->buffer, str, str_len );
314                     mon_buffer->buffer[str_len] = 0;
315
316                     /* signal data ready */
317                     SetEvent( eventdata );
318                 }
319                 ReleaseMutex( DBWinMutex );
320             }
321
322             if (buffer)
323                 UnmapViewOfFile( buffer );
324             if (eventbuffer)
325                 CloseHandle( eventbuffer );
326             if (eventdata)
327                 CloseHandle( eventdata );
328             CloseHandle( mapping );
329         }
330     }
331 }
332
333
334 /***********************************************************************
335  *           OutputDebugStringW   (KERNEL32.@)
336  *
337  *  Output by an application of a unicode string to a debugger (if attached)
338  *  and program log.
339  *
340  * PARAMS
341  *  str [I] The message to be logged and given to the debugger.
342  *
343  * RETURNS
344  *
345  *  Nothing.
346  */
347 void WINAPI OutputDebugStringW( LPCWSTR str )
348 {
349     UNICODE_STRING strW;
350     STRING strA;
351
352     RtlInitUnicodeString( &strW, str );
353     if (!RtlUnicodeStringToAnsiString( &strA, &strW, TRUE ))
354     {
355         OutputDebugStringA( strA.Buffer );
356         RtlFreeAnsiString( &strA );
357     }
358 }
359
360
361 /***********************************************************************
362  *           DebugBreak   (KERNEL32.@)
363  *
364  *  Raises an exception so that a debugger (if attached)
365  *  can take some action.
366  *
367  * PARAMS
368  *
369  * RETURNS
370  */
371 void WINAPI DebugBreak(void)
372 {
373     DbgBreakPoint();
374 }
375
376 /***********************************************************************
377  *           DebugBreakProcess   (KERNEL32.@)
378  *
379  *  Raises an exception so that a debugger (if attached)
380  *  can take some action. Same as DebugBreak, but applies to any process.
381  *
382  * PARAMS
383  *  hProc [I] Process to break into.
384  *
385  * RETURNS
386  *
387  *  True if successful.
388  */
389 BOOL WINAPI DebugBreakProcess(HANDLE hProc)
390 {
391     BOOL ret, self;
392
393     TRACE("(%p)\n", hProc);
394
395     SERVER_START_REQ( debug_break )
396     {
397         req->handle = wine_server_obj_handle( hProc );
398         ret = !wine_server_call_err( req );
399         self = ret && reply->self;
400     }
401     SERVER_END_REQ;
402     if (self) DbgBreakPoint();
403     return ret;
404 }
405
406
407 /***********************************************************************
408  *           IsDebuggerPresent   (KERNEL32.@)
409  *
410  *  Allows a process to determine if there is a debugger attached.
411  *
412  * PARAMS
413  *
414  * RETURNS
415  *
416  *  True if there is a debugger attached.
417  */
418 BOOL WINAPI IsDebuggerPresent(void)
419 {
420     return NtCurrentTeb()->Peb->BeingDebugged;
421 }
422
423 /***********************************************************************
424  *           CheckRemoteDebuggerPresent   (KERNEL32.@)
425  *
426  *  Allows a process to determine if there is a remote debugger
427  *  attached.
428  *
429  * PARAMS
430  *
431  * RETURNS
432  *
433  *  TRUE because it is a stub.
434  */
435 BOOL WINAPI CheckRemoteDebuggerPresent(HANDLE process, PBOOL DebuggerPresent)
436 {
437     NTSTATUS status;
438     DWORD_PTR port;
439
440     if(!process || !DebuggerPresent)
441     {
442         SetLastError(ERROR_INVALID_PARAMETER);
443         return FALSE;
444     }
445
446     status = NtQueryInformationProcess(process, ProcessDebugPort, &port, sizeof(port), NULL);
447     if (status != STATUS_SUCCESS)
448     {
449         SetLastError(RtlNtStatusToDosError(status));
450         return FALSE;
451     }
452
453     *DebuggerPresent = !!port;
454     return TRUE;
455 }
456
457 /***********************************************************************
458  *           DebugSetProcessKillOnExit                    (KERNEL32.@)
459  *
460  * Let a debugger decide whether a debuggee will be killed upon debugger
461  * termination.
462  *
463  * PARAMS
464  *  kill [I] If set to true then kill the process on exit.
465  *
466  * RETURNS
467  *  True if successful, false otherwise.
468  */
469 BOOL WINAPI DebugSetProcessKillOnExit(BOOL kill)
470 {
471     BOOL ret = FALSE;
472
473     SERVER_START_REQ( set_debugger_kill_on_exit )
474     {
475         req->kill_on_exit = kill;
476         ret = !wine_server_call_err( req );
477     }
478     SERVER_END_REQ;
479     return ret;
480 }