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