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