winedbg/gdbproxy: Use the WINEDEBUG interface for debugging winedbg.
[wine.git] / programs / winedbg / gdbproxy.c
blob0135cfcdafe19e41f4c88dc8adecff05003ffbc0
1 /*
2 * A Win32 based proxy implementing the GBD remote protocol.
3 * This makes it possible to debug Wine (and any "emulated"
4 * program) under Linux using GDB.
6 * Copyright (c) Eric Pouech 2002-2004
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 /* Protocol specification can be found here:
24 * http://sources.redhat.com/gdb/onlinedocs/gdb/Maintenance-Commands.html
27 #include "config.h"
28 #include "wine/port.h"
30 #include <assert.h>
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <signal.h>
34 #include <stdarg.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #ifdef HAVE_SYS_POLL_H
38 # include <sys/poll.h>
39 #endif
40 #ifdef HAVE_SYS_WAIT_H
41 # include <sys/wait.h>
42 #endif
43 #ifdef HAVE_SYS_SOCKET_H
44 # include <sys/socket.h>
45 #endif
46 #ifdef HAVE_NETINET_IN_H
47 # include <netinet/in.h>
48 #endif
49 #ifdef HAVE_NETINET_TCP_H
50 # include <netinet/tcp.h>
51 #endif
52 #ifdef HAVE_UNISTD_H
53 # include <unistd.h>
54 #endif
56 /* if we don't have poll support on this system
57 * we won't provide gdb proxy support here...
59 #ifdef HAVE_POLL
61 #include "debugger.h"
63 #include "windef.h"
64 #include "winbase.h"
65 #include "tlhelp32.h"
66 #include "wine/debug.h"
68 WINE_DEFAULT_DEBUG_CHANNEL(winedbg);
70 struct gdb_context
72 /* gdb information */
73 int sock;
74 /* incoming buffer */
75 char* in_buf;
76 int in_buf_alloc;
77 int in_len;
78 /* split into individual packet */
79 char* in_packet;
80 int in_packet_len;
81 /* outgoing buffer */
82 char* out_buf;
83 int out_buf_alloc;
84 int out_len;
85 int out_curr_packet;
86 /* generic GDB thread information */
87 struct dbg_thread* exec_thread; /* thread used in step & continue */
88 struct dbg_thread* other_thread; /* thread to be used in any other operation */
89 /* current Win32 trap env */
90 unsigned last_sig;
91 BOOL in_trap;
92 dbg_ctx_t context;
93 /* Win32 information */
94 struct dbg_process* process;
95 /* Unix environment */
96 unsigned long wine_segs[3]; /* load addresses of the ELF wine exec segments (text, bss and data) */
99 static BOOL tgt_process_gdbproxy_read(HANDLE hProcess, const void* addr,
100 void* buffer, SIZE_T len, SIZE_T* rlen)
102 return ReadProcessMemory( hProcess, addr, buffer, len, rlen );
105 static BOOL tgt_process_gdbproxy_write(HANDLE hProcess, void* addr,
106 const void* buffer, SIZE_T len, SIZE_T* wlen)
108 return WriteProcessMemory( hProcess, addr, buffer, len, wlen );
111 static struct be_process_io be_process_gdbproxy_io =
113 NULL, /* we shouldn't use close_process() in gdbproxy */
114 tgt_process_gdbproxy_read,
115 tgt_process_gdbproxy_write
118 /* =============================================== *
119 * B A S I C M A N I P U L A T I O N S *
120 * =============================================== *
123 static inline int hex_from0(char ch)
125 if (ch >= '0' && ch <= '9') return ch - '0';
126 if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10;
127 if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10;
129 assert(0);
130 return 0;
133 static inline unsigned char hex_to0(int x)
135 assert(x >= 0 && x < 16);
136 return "0123456789abcdef"[x];
139 static int hex_to_int(const char* src, size_t len)
141 unsigned int returnval = 0;
142 while (len--)
144 returnval <<= 4;
145 returnval |= hex_from0(*src++);
147 return returnval;
150 static void hex_from(void* dst, const char* src, size_t len)
152 unsigned char *p = dst;
153 while (len--)
155 *p++ = (hex_from0(src[0]) << 4) | hex_from0(src[1]);
156 src += 2;
160 static void hex_to(char* dst, const void* src, size_t len)
162 const unsigned char *p = src;
163 while (len--)
165 *dst++ = hex_to0(*p >> 4);
166 *dst++ = hex_to0(*p & 0x0F);
167 p++;
171 static unsigned char checksum(const char* ptr, int len)
173 unsigned cksum = 0;
175 while (len-- > 0)
176 cksum += (unsigned char)*ptr++;
177 return cksum;
180 #ifdef __i386__
181 static const char target_xml[] = "";
182 #elif defined(__powerpc__)
183 static const char target_xml[] = "";
184 #elif defined(__x86_64__)
185 static const char target_xml[] = "";
186 #elif defined(__arm__)
187 static const char target_xml[] =
188 "l <target><architecture>arm</architecture>\n"
189 "<feature name=\"org.gnu.gdb.arm.core\">\n"
190 " <reg name=\"r0\" bitsize=\"32\" type=\"uint32\"/>\n"
191 " <reg name=\"r1\" bitsize=\"32\" type=\"uint32\"/>\n"
192 " <reg name=\"r2\" bitsize=\"32\" type=\"uint32\"/>\n"
193 " <reg name=\"r3\" bitsize=\"32\" type=\"uint32\"/>\n"
194 " <reg name=\"r4\" bitsize=\"32\" type=\"uint32\"/>\n"
195 " <reg name=\"r5\" bitsize=\"32\" type=\"uint32\"/>\n"
196 " <reg name=\"r6\" bitsize=\"32\" type=\"uint32\"/>\n"
197 " <reg name=\"r7\" bitsize=\"32\" type=\"uint32\"/>\n"
198 " <reg name=\"r8\" bitsize=\"32\" type=\"uint32\"/>\n"
199 " <reg name=\"r9\" bitsize=\"32\" type=\"uint32\"/>\n"
200 " <reg name=\"r10\" bitsize=\"32\" type=\"uint32\"/>\n"
201 " <reg name=\"r11\" bitsize=\"32\" type=\"uint32\"/>\n"
202 " <reg name=\"r12\" bitsize=\"32\" type=\"uint32\"/>\n"
203 " <reg name=\"sp\" bitsize=\"32\" type=\"data_ptr\"/>\n"
204 " <reg name=\"lr\" bitsize=\"32\"/>\n"
205 " <reg name=\"pc\" bitsize=\"32\" type=\"code_ptr\"/>\n"
206 " <reg name=\"cpsr\" bitsize=\"32\"/>\n"
207 "</feature></target>\n";
208 #elif defined(__aarch64__)
209 static const char target_xml[] = "";
210 #else
211 # error Define the registers map for your CPU
212 #endif
214 static inline void* cpu_register_ptr(struct gdb_context *gdbctx,
215 dbg_ctx_t *ctx, unsigned idx)
217 assert(idx < gdbctx->process->be_cpu->gdb_num_regs);
218 return (char*)ctx + gdbctx->process->be_cpu->gdb_register_map[idx].ctx_offset;
221 static inline DWORD64 cpu_register(struct gdb_context *gdbctx,
222 dbg_ctx_t *ctx, unsigned idx)
224 switch (gdbctx->process->be_cpu->gdb_register_map[idx].ctx_length)
226 case 1: return *(BYTE*)cpu_register_ptr(gdbctx, ctx, idx);
227 case 2: return *(WORD*)cpu_register_ptr(gdbctx, ctx, idx);
228 case 4: return *(DWORD*)cpu_register_ptr(gdbctx, ctx, idx);
229 case 8: return *(DWORD64*)cpu_register_ptr(gdbctx, ctx, idx);
230 default:
231 ERR("got unexpected size: %u\n",
232 (unsigned)gdbctx->process->be_cpu->gdb_register_map[idx].ctx_length);
233 assert(0);
234 return 0;
238 static inline void cpu_register_hex_from(struct gdb_context *gdbctx,
239 dbg_ctx_t* ctx, unsigned idx, const char **phex)
241 const struct gdb_register *cpu_register_map = gdbctx->process->be_cpu->gdb_register_map;
243 if (cpu_register_map[idx].gdb_length == cpu_register_map[idx].ctx_length)
244 hex_from(cpu_register_ptr(gdbctx, ctx, idx), *phex, cpu_register_map[idx].gdb_length);
245 else
247 DWORD64 val = 0;
248 unsigned i;
249 BYTE b;
251 for (i = 0; i < cpu_register_map[idx].gdb_length; i++)
253 hex_from(&b, *phex, 1);
254 *phex += 2;
255 val += (DWORD64)b << (8 * i);
257 switch (cpu_register_map[idx].ctx_length)
259 case 1: *(BYTE*)cpu_register_ptr(gdbctx, ctx, idx) = (BYTE)val; break;
260 case 2: *(WORD*)cpu_register_ptr(gdbctx, ctx, idx) = (WORD)val; break;
261 case 4: *(DWORD*)cpu_register_ptr(gdbctx, ctx, idx) = (DWORD)val; break;
262 case 8: *(DWORD64*)cpu_register_ptr(gdbctx, ctx, idx) = val; break;
263 default: assert(0);
268 /* =============================================== *
269 * W I N 3 2 D E B U G I N T E R F A C E *
270 * =============================================== *
273 static BOOL fetch_context(struct gdb_context *gdbctx, HANDLE h, dbg_ctx_t *ctx)
275 if (!gdbctx->process->be_cpu->get_context(h, ctx))
277 ERR("Failed to get context, error %u\n", GetLastError());
278 return FALSE;
280 return TRUE;
283 static BOOL handle_exception(struct gdb_context* gdbctx, EXCEPTION_DEBUG_INFO* exc)
285 EXCEPTION_RECORD* rec = &exc->ExceptionRecord;
286 BOOL ret = FALSE;
288 switch (rec->ExceptionCode)
290 case EXCEPTION_ACCESS_VIOLATION:
291 case EXCEPTION_PRIV_INSTRUCTION:
292 case EXCEPTION_STACK_OVERFLOW:
293 case EXCEPTION_GUARD_PAGE:
294 gdbctx->last_sig = SIGSEGV;
295 ret = TRUE;
296 break;
297 case EXCEPTION_DATATYPE_MISALIGNMENT:
298 gdbctx->last_sig = SIGBUS;
299 ret = TRUE;
300 break;
301 case EXCEPTION_SINGLE_STEP:
302 /* fall through */
303 case EXCEPTION_BREAKPOINT:
304 gdbctx->last_sig = SIGTRAP;
305 ret = TRUE;
306 break;
307 case EXCEPTION_FLT_DENORMAL_OPERAND:
308 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
309 case EXCEPTION_FLT_INEXACT_RESULT:
310 case EXCEPTION_FLT_INVALID_OPERATION:
311 case EXCEPTION_FLT_OVERFLOW:
312 case EXCEPTION_FLT_STACK_CHECK:
313 case EXCEPTION_FLT_UNDERFLOW:
314 gdbctx->last_sig = SIGFPE;
315 ret = TRUE;
316 break;
317 case EXCEPTION_INT_DIVIDE_BY_ZERO:
318 case EXCEPTION_INT_OVERFLOW:
319 gdbctx->last_sig = SIGFPE;
320 ret = TRUE;
321 break;
322 case EXCEPTION_ILLEGAL_INSTRUCTION:
323 gdbctx->last_sig = SIGILL;
324 ret = TRUE;
325 break;
326 case CONTROL_C_EXIT:
327 gdbctx->last_sig = SIGINT;
328 ret = TRUE;
329 break;
330 case STATUS_POSSIBLE_DEADLOCK:
331 gdbctx->last_sig = SIGALRM;
332 ret = TRUE;
333 /* FIXME: we could also add here a O packet with additional information */
334 break;
335 case EXCEPTION_NAME_THREAD:
337 const THREADNAME_INFO *threadname = (const THREADNAME_INFO *)rec->ExceptionInformation;
338 struct dbg_thread *thread;
339 char name[9];
340 SIZE_T read;
342 if (threadname->dwThreadID == -1)
343 thread = dbg_curr_thread;
344 else
345 thread = dbg_get_thread(gdbctx->process, threadname->dwThreadID);
346 if (thread)
348 if (gdbctx->process->process_io->read( gdbctx->process->handle,
349 threadname->szName, name, sizeof(name), &read) && read == sizeof(name))
351 fprintf(stderr, "Thread ID=%04x renamed to \"%.9s\"\n",
352 threadname->dwThreadID, name);
355 else
356 ERR("Cannot set name of thread %04x\n", threadname->dwThreadID);
357 return DBG_CONTINUE;
359 default:
360 fprintf(stderr, "Unhandled exception code 0x%08x\n", rec->ExceptionCode);
361 gdbctx->last_sig = SIGABRT;
362 ret = TRUE;
363 break;
365 return ret;
368 static void handle_debug_event(struct gdb_context* gdbctx, DEBUG_EVENT* de)
370 union {
371 char bufferA[256];
372 WCHAR buffer[256];
373 } u;
375 dbg_curr_thread = dbg_get_thread(gdbctx->process, de->dwThreadId);
377 switch (de->dwDebugEventCode)
379 case CREATE_PROCESS_DEBUG_EVENT:
380 gdbctx->process = dbg_add_process(&be_process_gdbproxy_io, de->dwProcessId,
381 de->u.CreateProcessInfo.hProcess);
382 if (!gdbctx->process) break;
383 memory_get_string_indirect(gdbctx->process,
384 de->u.CreateProcessInfo.lpImageName,
385 de->u.CreateProcessInfo.fUnicode,
386 u.buffer, ARRAY_SIZE(u.buffer));
387 dbg_set_process_name(gdbctx->process, u.buffer);
389 fprintf(stderr, "%04x:%04x: create process '%s'/%p @%p (%u<%u>)\n",
390 de->dwProcessId, de->dwThreadId,
391 dbg_W2A(u.buffer, -1),
392 de->u.CreateProcessInfo.lpImageName,
393 de->u.CreateProcessInfo.lpStartAddress,
394 de->u.CreateProcessInfo.dwDebugInfoFileOffset,
395 de->u.CreateProcessInfo.nDebugInfoSize);
397 /* de->u.CreateProcessInfo.lpStartAddress; */
398 if (!dbg_init(gdbctx->process->handle, u.buffer, TRUE))
399 ERR("Couldn't initiate DbgHelp\n");
401 fprintf(stderr, "%04x:%04x: create thread I @%p\n", de->dwProcessId,
402 de->dwThreadId, de->u.CreateProcessInfo.lpStartAddress);
404 assert(dbg_curr_thread == NULL); /* shouldn't be there */
405 dbg_add_thread(gdbctx->process, de->dwThreadId,
406 de->u.CreateProcessInfo.hThread,
407 de->u.CreateProcessInfo.lpThreadLocalBase);
408 break;
410 case LOAD_DLL_DEBUG_EVENT:
411 assert(dbg_curr_thread);
412 memory_get_string_indirect(gdbctx->process,
413 de->u.LoadDll.lpImageName,
414 de->u.LoadDll.fUnicode,
415 u.buffer, ARRAY_SIZE(u.buffer));
416 fprintf(stderr, "%04x:%04x: loads DLL %s @%p (%u<%u>)\n",
417 de->dwProcessId, de->dwThreadId,
418 dbg_W2A(u.buffer, -1),
419 de->u.LoadDll.lpBaseOfDll,
420 de->u.LoadDll.dwDebugInfoFileOffset,
421 de->u.LoadDll.nDebugInfoSize);
422 dbg_load_module(gdbctx->process->handle, de->u.LoadDll.hFile, u.buffer,
423 (DWORD_PTR)de->u.LoadDll.lpBaseOfDll, 0);
424 break;
426 case UNLOAD_DLL_DEBUG_EVENT:
427 fprintf(stderr, "%08x:%08x: unload DLL @%p\n",
428 de->dwProcessId, de->dwThreadId, de->u.UnloadDll.lpBaseOfDll);
429 SymUnloadModule(gdbctx->process->handle,
430 (DWORD_PTR)de->u.UnloadDll.lpBaseOfDll);
431 break;
433 case EXCEPTION_DEBUG_EVENT:
434 assert(dbg_curr_thread);
435 fprintf(stderr, "%08x:%08x: exception code=0x%08x\n", de->dwProcessId,
436 de->dwThreadId, de->u.Exception.ExceptionRecord.ExceptionCode);
438 if (fetch_context(gdbctx, dbg_curr_thread->handle, &gdbctx->context))
440 gdbctx->in_trap = handle_exception(gdbctx, &de->u.Exception);
442 break;
444 case CREATE_THREAD_DEBUG_EVENT:
445 fprintf(stderr, "%08x:%08x: create thread D @%p\n", de->dwProcessId,
446 de->dwThreadId, de->u.CreateThread.lpStartAddress);
448 dbg_add_thread(gdbctx->process,
449 de->dwThreadId,
450 de->u.CreateThread.hThread,
451 de->u.CreateThread.lpThreadLocalBase);
452 break;
454 case EXIT_THREAD_DEBUG_EVENT:
455 fprintf(stderr, "%08x:%08x: exit thread (%u)\n",
456 de->dwProcessId, de->dwThreadId, de->u.ExitThread.dwExitCode);
458 assert(dbg_curr_thread);
459 if (dbg_curr_thread == gdbctx->exec_thread) gdbctx->exec_thread = NULL;
460 if (dbg_curr_thread == gdbctx->other_thread) gdbctx->other_thread = NULL;
461 dbg_del_thread(dbg_curr_thread);
462 break;
464 case EXIT_PROCESS_DEBUG_EVENT:
465 fprintf(stderr, "%08x:%08x: exit process (%u)\n",
466 de->dwProcessId, de->dwThreadId, de->u.ExitProcess.dwExitCode);
468 dbg_del_process(gdbctx->process);
469 gdbctx->process = NULL;
470 /* now signal gdb that we're done */
471 gdbctx->last_sig = SIGTERM;
472 gdbctx->in_trap = TRUE;
473 break;
475 case OUTPUT_DEBUG_STRING_EVENT:
476 assert(dbg_curr_thread);
477 memory_get_string(gdbctx->process,
478 de->u.DebugString.lpDebugStringData, TRUE,
479 de->u.DebugString.fUnicode, u.bufferA, sizeof(u.bufferA));
480 fprintf(stderr, "%08x:%08x: output debug string (%s)\n",
481 de->dwProcessId, de->dwThreadId, debugstr_a(u.bufferA));
482 break;
484 case RIP_EVENT:
485 fprintf(stderr, "%08x:%08x: rip error=%u type=%u\n", de->dwProcessId,
486 de->dwThreadId, de->u.RipInfo.dwError, de->u.RipInfo.dwType);
487 break;
489 default:
490 FIXME("%08x:%08x: unknown event (%u)\n",
491 de->dwProcessId, de->dwThreadId, de->dwDebugEventCode);
495 static void resume_debuggee(struct gdb_context* gdbctx, DWORD cont)
497 if (dbg_curr_thread)
499 if (!gdbctx->process->be_cpu->set_context(dbg_curr_thread->handle, &gdbctx->context))
500 ERR("Failed to set context for thread %04x, error %u\n",
501 dbg_curr_thread->tid, GetLastError());
502 if (!ContinueDebugEvent(gdbctx->process->pid, dbg_curr_thread->tid, cont))
503 ERR("Failed to continue thread %04x, error %u\n",
504 dbg_curr_thread->tid, GetLastError());
506 else
507 ERR("Cannot find last thread\n");
511 static void resume_debuggee_thread(struct gdb_context* gdbctx, DWORD cont, unsigned int threadid)
514 if (dbg_curr_thread)
516 if(dbg_curr_thread->tid == threadid){
517 /* Windows debug and GDB don't seem to work well here, windows only likes ContinueDebugEvent being used on the reporter of the event */
518 if (!gdbctx->process->be_cpu->set_context(dbg_curr_thread->handle, &gdbctx->context))
519 ERR("Failed to set context for thread %04x, error %u\n",
520 dbg_curr_thread->tid, GetLastError());
521 if (!ContinueDebugEvent(gdbctx->process->pid, dbg_curr_thread->tid, cont))
522 ERR("Failed to continue thread %04x, error %u\n",
523 dbg_curr_thread->tid, GetLastError());
526 else
527 ERR("Cannot find last thread\n");
530 static BOOL check_for_interrupt(struct gdb_context* gdbctx)
532 struct pollfd pollfd;
533 int ret;
534 char pkt;
536 pollfd.fd = gdbctx->sock;
537 pollfd.events = POLLIN;
538 pollfd.revents = 0;
540 if ((ret = poll(&pollfd, 1, 0)) == 1) {
541 ret = read(gdbctx->sock, &pkt, 1);
542 if (ret != 1) {
543 ERR("read failed\n");
544 return FALSE;
546 if (pkt != '\003') {
547 ERR("Unexpected break packet %#02x\n", pkt);
548 return FALSE;
550 return TRUE;
551 } else if (ret == -1) {
552 ERR("poll failed\n");
554 return FALSE;
557 static void wait_for_debuggee(struct gdb_context* gdbctx)
559 DEBUG_EVENT de;
561 gdbctx->in_trap = FALSE;
562 for (;;)
564 if (!WaitForDebugEvent(&de, 10))
566 if (GetLastError() == ERROR_SEM_TIMEOUT)
568 if (check_for_interrupt(gdbctx)) {
569 if (!DebugBreakProcess(gdbctx->process->handle)) {
570 ERR("Failed to break into debugee\n");
571 break;
573 WaitForDebugEvent(&de, INFINITE);
574 } else {
575 continue;
577 } else {
578 break;
581 handle_debug_event(gdbctx, &de);
582 assert(!gdbctx->process ||
583 gdbctx->process->pid == 0 ||
584 de.dwProcessId == gdbctx->process->pid);
585 assert(!dbg_curr_thread || de.dwThreadId == dbg_curr_thread->tid);
586 if (gdbctx->in_trap) break;
587 ContinueDebugEvent(de.dwProcessId, de.dwThreadId, DBG_CONTINUE);
591 static void detach_debuggee(struct gdb_context* gdbctx, BOOL kill)
593 assert(gdbctx->process->be_cpu);
594 gdbctx->process->be_cpu->single_step(&gdbctx->context, FALSE);
595 resume_debuggee(gdbctx, DBG_CONTINUE);
596 if (!kill)
597 DebugActiveProcessStop(gdbctx->process->pid);
598 dbg_del_process(gdbctx->process);
599 gdbctx->process = NULL;
602 static void get_process_info(struct gdb_context* gdbctx, char* buffer, size_t len)
604 DWORD status;
606 if (!GetExitCodeProcess(gdbctx->process->handle, &status))
608 strcpy(buffer, "Unknown process");
609 return;
611 if (status == STILL_ACTIVE)
613 strcpy(buffer, "Running");
615 else
616 snprintf(buffer, len, "Terminated (%u)", status);
618 switch (GetPriorityClass(gdbctx->process->handle))
620 case 0: break;
621 #ifdef ABOVE_NORMAL_PRIORITY_CLASS
622 case ABOVE_NORMAL_PRIORITY_CLASS: strcat(buffer, ", above normal priority"); break;
623 #endif
624 #ifdef BELOW_NORMAL_PRIORITY_CLASS
625 case BELOW_NORMAL_PRIORITY_CLASS: strcat(buffer, ", below normal priotity"); break;
626 #endif
627 case HIGH_PRIORITY_CLASS: strcat(buffer, ", high priority"); break;
628 case IDLE_PRIORITY_CLASS: strcat(buffer, ", idle priority"); break;
629 case NORMAL_PRIORITY_CLASS: strcat(buffer, ", normal priority"); break;
630 case REALTIME_PRIORITY_CLASS: strcat(buffer, ", realtime priority"); break;
632 strcat(buffer, "\n");
635 static void get_thread_info(struct gdb_context* gdbctx, unsigned tid,
636 char* buffer, size_t len)
638 struct dbg_thread* thd;
639 DWORD status;
640 int prio;
642 /* FIXME: use the size of buffer */
643 thd = dbg_get_thread(gdbctx->process, tid);
644 if (thd == NULL)
646 strcpy(buffer, "No information");
647 return;
649 if (GetExitCodeThread(thd->handle, &status))
651 if (status == STILL_ACTIVE)
653 /* FIXME: this is a bit brutal... some nicer way shall be found */
654 switch (status = SuspendThread(thd->handle))
656 case -1: break;
657 case 0: strcpy(buffer, "Running"); break;
658 default: snprintf(buffer, len, "Suspended (%u)", status - 1);
660 ResumeThread(thd->handle);
662 else
663 snprintf(buffer, len, "Terminated (exit code = %u)", status);
665 else
667 strcpy(buffer, "Unknown threadID");
669 switch (prio = GetThreadPriority(thd->handle))
671 case THREAD_PRIORITY_ERROR_RETURN: break;
672 case THREAD_PRIORITY_ABOVE_NORMAL: strcat(buffer, ", priority +1 above normal"); break;
673 case THREAD_PRIORITY_BELOW_NORMAL: strcat(buffer, ", priority -1 below normal"); break;
674 case THREAD_PRIORITY_HIGHEST: strcat(buffer, ", priority +2 above normal"); break;
675 case THREAD_PRIORITY_LOWEST: strcat(buffer, ", priority -2 below normal"); break;
676 case THREAD_PRIORITY_IDLE: strcat(buffer, ", priority idle"); break;
677 case THREAD_PRIORITY_NORMAL: strcat(buffer, ", priority normal"); break;
678 case THREAD_PRIORITY_TIME_CRITICAL: strcat(buffer, ", priority time-critical"); break;
679 default: snprintf(buffer + strlen(buffer), len - strlen(buffer), ", priority = %d", prio);
681 assert(strlen(buffer) < len);
684 /* =============================================== *
685 * P A C K E T U T I L S *
686 * =============================================== *
689 enum packet_return {packet_error = 0x00, packet_ok = 0x01, packet_done = 0x02,
690 packet_last_f = 0x80};
692 static char* packet_realloc(char* buf, int size)
694 if (!buf)
695 return HeapAlloc(GetProcessHeap(), 0, size);
696 return HeapReAlloc(GetProcessHeap(), 0, buf, size);
700 static void packet_reply_grow(struct gdb_context* gdbctx, size_t size)
702 if (gdbctx->out_buf_alloc < gdbctx->out_len + size)
704 gdbctx->out_buf_alloc = ((gdbctx->out_len + size) / 32 + 1) * 32;
705 gdbctx->out_buf = packet_realloc(gdbctx->out_buf, gdbctx->out_buf_alloc);
709 static void packet_reply_hex_to(struct gdb_context* gdbctx, const void* src, int len)
711 packet_reply_grow(gdbctx, len * 2);
712 hex_to(&gdbctx->out_buf[gdbctx->out_len], src, len);
713 gdbctx->out_len += len * 2;
716 static inline void packet_reply_hex_to_str(struct gdb_context* gdbctx, const char* src)
718 packet_reply_hex_to(gdbctx, src, strlen(src));
721 static void packet_reply_val(struct gdb_context* gdbctx, unsigned long val, int len)
723 int i, shift;
725 shift = (len - 1) * 8;
726 packet_reply_grow(gdbctx, len * 2);
727 for (i = 0; i < len; i++, shift -= 8)
729 gdbctx->out_buf[gdbctx->out_len++] = hex_to0((val >> (shift + 4)) & 0x0F);
730 gdbctx->out_buf[gdbctx->out_len++] = hex_to0((val >> shift ) & 0x0F);
734 static inline void packet_reply_add(struct gdb_context* gdbctx, const char* str, int len)
736 packet_reply_grow(gdbctx, len);
737 memcpy(&gdbctx->out_buf[gdbctx->out_len], str, len);
738 gdbctx->out_len += len;
741 static inline void packet_reply_cat(struct gdb_context* gdbctx, const char* str)
743 packet_reply_add(gdbctx, str, strlen(str));
746 static inline void packet_reply_catc(struct gdb_context* gdbctx, char ch)
748 packet_reply_add(gdbctx, &ch, 1);
751 static void packet_reply_open(struct gdb_context* gdbctx)
753 assert(gdbctx->out_curr_packet == -1);
754 packet_reply_catc(gdbctx, '$');
755 gdbctx->out_curr_packet = gdbctx->out_len;
758 static void packet_reply_close(struct gdb_context* gdbctx)
760 unsigned char cksum;
761 int plen;
763 plen = gdbctx->out_len - gdbctx->out_curr_packet;
764 packet_reply_catc(gdbctx, '#');
765 cksum = checksum(&gdbctx->out_buf[gdbctx->out_curr_packet], plen);
766 packet_reply_hex_to(gdbctx, &cksum, 1);
767 gdbctx->out_curr_packet = -1;
770 static enum packet_return packet_reply(struct gdb_context* gdbctx, const char* packet, int len)
772 packet_reply_open(gdbctx);
774 if (len == -1) len = strlen(packet);
775 assert(memchr(packet, '$', len) == NULL && memchr(packet, '#', len) == NULL);
777 packet_reply_add(gdbctx, packet, len);
779 packet_reply_close(gdbctx);
781 return packet_done;
784 static enum packet_return packet_reply_error(struct gdb_context* gdbctx, int error)
786 packet_reply_open(gdbctx);
788 packet_reply_add(gdbctx, "E", 1);
789 packet_reply_val(gdbctx, error, 1);
791 packet_reply_close(gdbctx);
793 return packet_done;
796 static inline void packet_reply_register_hex_to(struct gdb_context* gdbctx, unsigned idx)
798 const struct gdb_register *cpu_register_map = gdbctx->process->be_cpu->gdb_register_map;
800 if (cpu_register_map[idx].gdb_length == cpu_register_map[idx].ctx_length)
801 packet_reply_hex_to(gdbctx, cpu_register_ptr(gdbctx, &gdbctx->context, idx),
802 cpu_register_map[idx].gdb_length);
803 else
805 DWORD64 val = cpu_register(gdbctx, &gdbctx->context, idx);
806 unsigned i;
808 for (i = 0; i < cpu_register_map[idx].gdb_length; i++)
810 BYTE b = val;
811 packet_reply_hex_to(gdbctx, &b, 1);
812 val >>= 8;
817 /* =============================================== *
818 * P A C K E T H A N D L E R S *
819 * =============================================== *
822 static enum packet_return packet_reply_status(struct gdb_context* gdbctx)
824 enum packet_return ret = packet_done;
826 packet_reply_open(gdbctx);
828 if (gdbctx->process != NULL)
830 unsigned char sig;
831 unsigned i;
833 packet_reply_catc(gdbctx, 'T');
834 sig = gdbctx->last_sig;
835 packet_reply_val(gdbctx, sig, 1);
836 packet_reply_add(gdbctx, "thread:", 7);
837 packet_reply_val(gdbctx, dbg_curr_thread->tid, 4);
838 packet_reply_catc(gdbctx, ';');
840 for (i = 0; i < gdbctx->process->be_cpu->gdb_num_regs; i++)
842 /* FIXME: this call will also grow the buffer...
843 * unneeded, but not harmful
845 packet_reply_val(gdbctx, i, 1);
846 packet_reply_catc(gdbctx, ':');
847 packet_reply_register_hex_to(gdbctx, i);
848 packet_reply_catc(gdbctx, ';');
851 else
853 /* Try to put an exit code
854 * Cannot use GetExitCodeProcess, wouldn't fit in a 8 bit value, so
855 * just indicate the end of process and exit */
856 packet_reply_add(gdbctx, "W00", 3);
857 /*if (!gdbctx->extended)*/ ret |= packet_last_f;
860 packet_reply_close(gdbctx);
862 return ret;
865 #if 0
866 static enum packet_return packet_extended(struct gdb_context* gdbctx)
868 gdbctx->extended = 1;
869 return packet_ok;
871 #endif
873 static enum packet_return packet_last_signal(struct gdb_context* gdbctx)
875 assert(gdbctx->in_packet_len == 0);
876 return packet_reply_status(gdbctx);
879 static enum packet_return packet_continue(struct gdb_context* gdbctx)
881 /* FIXME: add support for address in packet */
882 assert(gdbctx->in_packet_len == 0);
883 if (dbg_curr_thread != gdbctx->exec_thread && gdbctx->exec_thread)
884 FIXME("Can't continue thread %04x while on thread %04x\n",
885 gdbctx->exec_thread->tid, dbg_curr_thread->tid);
886 resume_debuggee(gdbctx, DBG_CONTINUE);
887 wait_for_debuggee(gdbctx);
888 return packet_reply_status(gdbctx);
891 static enum packet_return packet_verbose_cont(struct gdb_context* gdbctx)
893 int i;
894 int defaultAction = -1; /* magic non action */
895 unsigned char sig;
896 int actions =0;
897 int actionIndex[20]; /* allow for up to 20 actions */
898 int threadIndex[20];
899 int threadCount = 0;
900 unsigned int threadIDs[100]; /* TODO: Should make this dynamic */
901 unsigned int threadID = 0;
902 struct dbg_thread* thd;
904 /* OK we have vCont followed by..
905 * ? for query
906 * c for packet_continue
907 * Csig for packet_continue_signal
908 * s for step
909 * Ssig for step signal
910 * and then an optional thread ID at the end..
911 * *******************************************/
913 /* Query */
914 if (gdbctx->in_packet[4] == '?')
917 Reply:
918 `vCont[;action]...'
919 The vCont packet is supported. Each action is a supported command in the vCont packet.
921 The vCont packet is not supported. (this didn't seem to be obeyed!)
923 packet_reply_open(gdbctx);
924 packet_reply_add(gdbctx, "vCont", 5);
925 /* add all the supported actions to the reply (all of them for now) */
926 packet_reply_add(gdbctx, ";c", 2);
927 packet_reply_add(gdbctx, ";C", 2);
928 packet_reply_add(gdbctx, ";s", 2);
929 packet_reply_add(gdbctx, ";S", 2);
930 packet_reply_close(gdbctx);
931 return packet_done;
934 /* go through the packet and identify where all the actions start at */
935 for (i = 4; i < gdbctx->in_packet_len - 1; i++)
937 if (gdbctx->in_packet[i] == ';')
939 threadIndex[actions] = 0;
940 actionIndex[actions++] = i;
942 else if (gdbctx->in_packet[i] == ':')
944 threadIndex[actions - 1] = i;
948 /* now look up the default action */
949 for (i = 0 ; i < actions; i++)
951 if (threadIndex[i] == 0)
953 if (defaultAction != -1)
955 fprintf(stderr,"Too many default actions specified\n");
956 return packet_error;
958 defaultAction = i;
962 /* Now, I have this default action thing that needs to be applied to all non counted threads */
964 /* go through all the threads and stick their ids in the to be done list. */
965 LIST_FOR_EACH_ENTRY(thd, &gdbctx->process->threads, struct dbg_thread, entry)
967 threadIDs[threadCount++] = thd->tid;
968 /* check to see if we have more threads than I counted on, and tell the user what to do
969 * (they're running winedbg, so I'm sure they can fix the problem from the error message!) */
970 if (threadCount == 100)
972 fprintf(stderr, "Wow, that's a lot of threads, change threadIDs in wine/programs/winedbg/gdbproxy.c to be higher\n");
973 break;
977 /* Ok, now we have... actionIndex full of actions and we know what threads there are, so all
978 * that remains is to apply the actions to the threads and the default action to any threads
979 * left */
980 if (dbg_curr_thread != gdbctx->exec_thread && gdbctx->exec_thread)
981 FIXME("Can't continue thread %04x while on thread %04x\n",
982 gdbctx->exec_thread->tid, dbg_curr_thread->tid);
984 /* deal with the threaded stuff first */
985 for (i = 0; i < actions ; i++)
987 if (threadIndex[i] != 0)
989 int j, idLength = 0;
990 if (i < actions - 1)
992 idLength = (actionIndex[i+1] - threadIndex[i]) - 1;
994 else
996 idLength = (gdbctx->in_packet_len - threadIndex[i]) - 1;
999 threadID = hex_to_int(gdbctx->in_packet + threadIndex[i] + 1 , idLength);
1000 /* process the action */
1001 switch (gdbctx->in_packet[actionIndex[i] + 1])
1003 case 's': /* step */
1004 gdbctx->process->be_cpu->single_step(&gdbctx->context, TRUE);
1005 /* fall through*/
1006 case 'c': /* continue */
1007 resume_debuggee_thread(gdbctx, DBG_CONTINUE, threadID);
1008 break;
1009 case 'S': /* step Sig, */
1010 gdbctx->process->be_cpu->single_step(&gdbctx->context, TRUE);
1011 /* fall through */
1012 case 'C': /* continue sig */
1013 hex_from(&sig, gdbctx->in_packet + actionIndex[i] + 2, 1);
1014 /* cannot change signals on the fly */
1015 TRACE("sigs: %u %u\n", sig, gdbctx->last_sig);
1016 if (sig != gdbctx->last_sig)
1017 return packet_error;
1018 resume_debuggee_thread(gdbctx, DBG_EXCEPTION_NOT_HANDLED, threadID);
1019 break;
1021 for (j = 0 ; j < threadCount; j++)
1023 if (threadIDs[j] == threadID)
1025 threadIDs[j] = 0;
1026 break;
1030 } /* for i=0 ; i< actions */
1032 /* now we have manage the default action */
1033 if (defaultAction >= 0)
1035 for (i = 0 ; i< threadCount; i++)
1037 /* check to see if we've already done something to the thread*/
1038 if (threadIDs[i] != 0)
1040 /* if not apply the default action*/
1041 threadID = threadIDs[i];
1042 /* process the action (yes this is almost identical to the one above!) */
1043 switch (gdbctx->in_packet[actionIndex[defaultAction] + 1])
1045 case 's': /* step */
1046 gdbctx->process->be_cpu->single_step(&gdbctx->context, TRUE);
1047 /* fall through */
1048 case 'c': /* continue */
1049 resume_debuggee_thread(gdbctx, DBG_CONTINUE, threadID);
1050 break;
1051 case 'S':
1052 gdbctx->process->be_cpu->single_step(&gdbctx->context, TRUE);
1053 /* fall through */
1054 case 'C': /* continue sig */
1055 hex_from(&sig, gdbctx->in_packet + actionIndex[defaultAction] + 2, 1);
1056 /* cannot change signals on the fly */
1057 TRACE("sigs: %u %u\n", sig, gdbctx->last_sig);
1058 if (sig != gdbctx->last_sig)
1059 return packet_error;
1060 resume_debuggee_thread(gdbctx, DBG_EXCEPTION_NOT_HANDLED, threadID);
1061 break;
1065 } /* if(defaultAction >=0) */
1067 wait_for_debuggee(gdbctx);
1068 gdbctx->process->be_cpu->single_step(&gdbctx->context, FALSE);
1069 return packet_reply_status(gdbctx);
1072 struct verbose_defail
1074 const char* name;
1075 unsigned len;
1076 enum packet_return (*handler)(struct gdb_context*);
1077 } verbose_details[] =
1079 /* {"Attach", 6}, */
1080 {"Cont", 4, packet_verbose_cont},
1081 /* {"File", 4},
1082 {"FlashErase", 10},
1083 {"FlashWrite", 10},
1084 {"FlashDone", 9},
1085 {"Kill", 4},
1086 {"Run", 3},
1087 {"Stopped", 7},*/
1090 static enum packet_return packet_verbose(struct gdb_context* gdbctx)
1092 unsigned i;
1093 unsigned klen;
1095 for (klen = 0; ; klen++)
1097 if (klen == gdbctx->in_packet_len ||
1098 gdbctx->in_packet[klen] == ';' ||
1099 gdbctx->in_packet[klen] == ':' ||
1100 gdbctx->in_packet[klen] == '?')
1102 TRACE("Trying to process verbose packet %s\n",
1103 debugstr_an(gdbctx->in_packet, gdbctx->in_packet_len));
1104 for (i = 0; i < ARRAY_SIZE(verbose_details); i++)
1106 if (klen == verbose_details[i].len &&
1107 !memcmp(gdbctx->in_packet, verbose_details[i].name, verbose_details[i].len))
1109 return verbose_details[i].handler(gdbctx);
1112 /* no matching handler found, abort */
1113 break;
1117 WARN("No support for verbose packet %s\n",
1118 debugstr_an(gdbctx->in_packet, gdbctx->in_packet_len));
1119 return packet_error;
1122 static enum packet_return packet_continue_signal(struct gdb_context* gdbctx)
1124 unsigned char sig;
1126 /* FIXME: add support for address in packet */
1127 assert(gdbctx->in_packet_len == 2);
1128 if (dbg_curr_thread != gdbctx->exec_thread && gdbctx->exec_thread)
1129 FIXME("Can't continue thread %04x while on thread %04x\n",
1130 gdbctx->exec_thread->tid, dbg_curr_thread->tid);
1131 hex_from(&sig, gdbctx->in_packet, 1);
1132 /* cannot change signals on the fly */
1133 TRACE("sigs: %u %u\n", sig, gdbctx->last_sig);
1134 if (sig != gdbctx->last_sig)
1135 return packet_error;
1136 resume_debuggee(gdbctx, DBG_EXCEPTION_NOT_HANDLED);
1137 wait_for_debuggee(gdbctx);
1138 return packet_reply_status(gdbctx);
1141 static enum packet_return packet_detach(struct gdb_context* gdbctx)
1143 detach_debuggee(gdbctx, FALSE);
1144 return packet_ok | packet_last_f;
1147 static enum packet_return packet_read_registers(struct gdb_context* gdbctx)
1149 int i;
1150 dbg_ctx_t ctx;
1152 assert(gdbctx->in_trap);
1154 if (dbg_curr_thread != gdbctx->other_thread && gdbctx->other_thread)
1156 if (!fetch_context(gdbctx, gdbctx->other_thread->handle, &ctx))
1157 return packet_error;
1160 packet_reply_open(gdbctx);
1161 for (i = 0; i < gdbctx->process->be_cpu->gdb_num_regs; i++)
1162 packet_reply_register_hex_to(gdbctx, i);
1164 packet_reply_close(gdbctx);
1165 return packet_done;
1168 static enum packet_return packet_write_registers(struct gdb_context* gdbctx)
1170 const size_t cpu_num_regs = gdbctx->process->be_cpu->gdb_num_regs;
1171 unsigned i;
1172 dbg_ctx_t ctx;
1173 dbg_ctx_t *pctx = &gdbctx->context;
1174 const char* ptr;
1176 assert(gdbctx->in_trap);
1177 if (dbg_curr_thread != gdbctx->other_thread && gdbctx->other_thread)
1179 if (!fetch_context(gdbctx, gdbctx->other_thread->handle, pctx = &ctx))
1180 return packet_error;
1182 if (gdbctx->in_packet_len < cpu_num_regs * 2) return packet_error;
1184 ptr = gdbctx->in_packet;
1185 for (i = 0; i < cpu_num_regs; i++)
1186 cpu_register_hex_from(gdbctx, pctx, i, &ptr);
1188 if (pctx != &gdbctx->context &&
1189 !gdbctx->process->be_cpu->set_context(gdbctx->other_thread->handle, pctx))
1191 ERR("Failed to set context for tid %04x, error %u\n",
1192 gdbctx->other_thread->tid, GetLastError());
1193 return packet_error;
1195 return packet_ok;
1198 static enum packet_return packet_kill(struct gdb_context* gdbctx)
1200 detach_debuggee(gdbctx, TRUE);
1201 #if 0
1202 if (!gdbctx->extended)
1203 /* dunno whether GDB cares or not */
1204 #endif
1205 wait(NULL);
1206 exit(0);
1207 /* assume we can't really answer something here */
1208 /* return packet_done; */
1211 static enum packet_return packet_thread(struct gdb_context* gdbctx)
1213 char* end;
1214 unsigned thread;
1216 switch (gdbctx->in_packet[0])
1218 case 'c':
1219 case 'g':
1220 if (gdbctx->in_packet[1] == '-')
1221 thread = -strtol(gdbctx->in_packet + 2, &end, 16);
1222 else
1223 thread = strtol(gdbctx->in_packet + 1, &end, 16);
1224 if (end == NULL || end > gdbctx->in_packet + gdbctx->in_packet_len)
1226 ERR("Failed to parse %s\n",
1227 debugstr_an(gdbctx->in_packet, gdbctx->in_packet_len));
1228 return packet_error;
1230 if (gdbctx->in_packet[0] == 'c')
1231 gdbctx->exec_thread = dbg_get_thread(gdbctx->process, thread);
1232 else
1233 gdbctx->other_thread = dbg_get_thread(gdbctx->process, thread);
1234 return packet_ok;
1235 default:
1236 FIXME("Unknown thread sub-command %c\n", gdbctx->in_packet[0]);
1237 return packet_error;
1241 static enum packet_return packet_read_memory(struct gdb_context* gdbctx)
1243 char *addr;
1244 unsigned int len, blk_len, nread;
1245 char buffer[32];
1246 SIZE_T r = 0;
1248 assert(gdbctx->in_trap);
1249 /* FIXME:check in_packet_len for reading %p,%x */
1250 if (sscanf(gdbctx->in_packet, "%p,%x", &addr, &len) != 2) return packet_error;
1251 if (len <= 0) return packet_error;
1252 TRACE("Read %u bytes at %p\n", len, addr);
1253 for (nread = 0; nread < len; nread += r, addr += r)
1255 blk_len = min(sizeof(buffer), len - nread);
1256 if (!gdbctx->process->process_io->read(gdbctx->process->handle, addr,
1257 buffer, blk_len, &r) || r == 0)
1259 /* fail at first address, return error */
1260 if (nread == 0) return packet_reply_error(gdbctx, EFAULT);
1261 /* something has already been read, return partial information */
1262 break;
1264 if (nread == 0) packet_reply_open(gdbctx);
1265 packet_reply_hex_to(gdbctx, buffer, r);
1267 packet_reply_close(gdbctx);
1268 return packet_done;
1271 static enum packet_return packet_write_memory(struct gdb_context* gdbctx)
1273 char* addr;
1274 unsigned int len, blk_len;
1275 char* ptr;
1276 char buffer[32];
1277 SIZE_T w;
1279 assert(gdbctx->in_trap);
1280 ptr = memchr(gdbctx->in_packet, ':', gdbctx->in_packet_len);
1281 if (ptr == NULL)
1283 ERR("Cannot find ':' in %s\n", debugstr_an(gdbctx->in_packet, gdbctx->in_packet_len));
1284 return packet_error;
1286 *ptr++ = '\0';
1288 if (sscanf(gdbctx->in_packet, "%p,%x", &addr, &len) != 2)
1290 ERR("Failed to parse %s\n", debugstr_a(gdbctx->in_packet));
1291 return packet_error;
1293 if (ptr - gdbctx->in_packet + len * 2 != gdbctx->in_packet_len)
1295 ERR("Length %u does not match packet length %u\n",
1296 (int)(ptr - gdbctx->in_packet) + len * 2, gdbctx->in_packet_len);
1297 return packet_error;
1299 TRACE("Write %u bytes at %p\n", len, addr);
1300 while (len > 0)
1302 blk_len = min(sizeof(buffer), len);
1303 hex_from(buffer, ptr, blk_len);
1304 if (!gdbctx->process->process_io->write(gdbctx->process->handle, addr, buffer, blk_len, &w) ||
1305 w != blk_len)
1306 break;
1307 addr += blk_len;
1308 len -= blk_len;
1309 ptr += blk_len;
1311 return packet_ok; /* FIXME: error while writing ? */
1314 static enum packet_return packet_read_register(struct gdb_context* gdbctx)
1316 unsigned reg;
1317 dbg_ctx_t ctx;
1318 dbg_ctx_t *pctx = &gdbctx->context;
1320 assert(gdbctx->in_trap);
1321 reg = hex_to_int(gdbctx->in_packet, gdbctx->in_packet_len);
1322 if (reg >= gdbctx->process->be_cpu->gdb_num_regs)
1324 FIXME("Unhandled register %u\n", reg);
1325 return packet_error;
1327 if (dbg_curr_thread != gdbctx->other_thread && gdbctx->other_thread)
1329 if (!fetch_context(gdbctx, gdbctx->other_thread->handle, pctx = &ctx))
1330 return packet_error;
1333 TRACE("%u => %s\n", reg, wine_dbgstr_longlong(cpu_register(gdbctx, pctx, reg)));
1335 packet_reply_open(gdbctx);
1336 packet_reply_register_hex_to(gdbctx, reg);
1337 packet_reply_close(gdbctx);
1338 return packet_done;
1341 static enum packet_return packet_write_register(struct gdb_context* gdbctx)
1343 unsigned reg;
1344 char* ptr;
1345 dbg_ctx_t ctx;
1346 dbg_ctx_t *pctx = &gdbctx->context;
1348 assert(gdbctx->in_trap);
1350 reg = strtoul(gdbctx->in_packet, &ptr, 16);
1351 if (ptr == NULL || reg >= gdbctx->process->be_cpu->gdb_num_regs || *ptr++ != '=')
1353 FIXME("Unhandled register %s\n",
1354 debugstr_an(gdbctx->in_packet, gdbctx->in_packet_len));
1355 /* FIXME: if just the reg is above cpu_num_regs, don't tell gdb
1356 * it wouldn't matter too much, and it fakes our support for all regs
1358 return (ptr == NULL) ? packet_error : packet_ok;
1361 TRACE("%u <= %s\n", reg,
1362 debugstr_an(ptr, (int)(gdbctx->in_packet_len - (ptr - gdbctx->in_packet))));
1364 if (dbg_curr_thread != gdbctx->other_thread && gdbctx->other_thread)
1366 if (!fetch_context(gdbctx, gdbctx->other_thread->handle, pctx = &ctx))
1367 return packet_error;
1370 cpu_register_hex_from(gdbctx, pctx, reg, (const char**)&ptr);
1371 if (pctx != &gdbctx->context &&
1372 !gdbctx->process->be_cpu->set_context(gdbctx->other_thread->handle, pctx))
1374 ERR("Failed to set context for tid %04x, error %u\n",
1375 gdbctx->other_thread->tid, GetLastError());
1376 return packet_error;
1379 return packet_ok;
1382 static void packet_query_monitor_wnd_helper(struct gdb_context* gdbctx, HWND hWnd, int indent)
1384 char buffer[128];
1385 char clsName[128];
1386 char wndName[128];
1387 HWND child;
1389 do {
1390 if (!GetClassNameA(hWnd, clsName, sizeof(clsName)))
1391 strcpy(clsName, "-- Unknown --");
1392 if (!GetWindowTextA(hWnd, wndName, sizeof(wndName)))
1393 strcpy(wndName, "-- Empty --");
1395 packet_reply_open(gdbctx);
1396 packet_reply_catc(gdbctx, 'O');
1397 snprintf(buffer, sizeof(buffer),
1398 "%*s%04lx%*s%-17.17s %08x %0*lx %.14s\n",
1399 indent, "", (ULONG_PTR)hWnd, 13 - indent, "",
1400 clsName, GetWindowLongW(hWnd, GWL_STYLE),
1401 ADDRWIDTH, (ULONG_PTR)GetWindowLongPtrW(hWnd, GWLP_WNDPROC),
1402 wndName);
1403 packet_reply_hex_to_str(gdbctx, buffer);
1404 packet_reply_close(gdbctx);
1406 if ((child = GetWindow(hWnd, GW_CHILD)) != 0)
1407 packet_query_monitor_wnd_helper(gdbctx, child, indent + 1);
1408 } while ((hWnd = GetWindow(hWnd, GW_HWNDNEXT)) != 0);
1411 static void packet_query_monitor_wnd(struct gdb_context* gdbctx, int len, const char* str)
1413 char buffer[128];
1415 /* we do the output in several 'O' packets, with the last one being just OK for
1416 * marking the end of the output */
1417 packet_reply_open(gdbctx);
1418 packet_reply_catc(gdbctx, 'O');
1419 snprintf(buffer, sizeof(buffer),
1420 "%-16.16s %-17.17s %-8.8s %s\n",
1421 "hwnd", "Class Name", " Style", " WndProc Text");
1422 packet_reply_hex_to_str(gdbctx, buffer);
1423 packet_reply_close(gdbctx);
1425 /* FIXME: could also add a pmt to this command in str... */
1426 packet_query_monitor_wnd_helper(gdbctx, GetDesktopWindow(), 0);
1427 packet_reply(gdbctx, "OK", 2);
1430 static void packet_query_monitor_process(struct gdb_context* gdbctx, int len, const char* str)
1432 HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
1433 char buffer[31+MAX_PATH];
1434 char deco;
1435 PROCESSENTRY32 entry;
1436 BOOL ok;
1438 if (snap == INVALID_HANDLE_VALUE)
1439 return;
1441 entry.dwSize = sizeof(entry);
1442 ok = Process32First(snap, &entry);
1444 /* we do the output in several 'O' packets, with the last one being just OK for
1445 * marking the end of the output */
1447 packet_reply_open(gdbctx);
1448 packet_reply_catc(gdbctx, 'O');
1449 snprintf(buffer, sizeof(buffer),
1450 " %-8.8s %-8.8s %-8.8s %s\n",
1451 "pid", "threads", "parent", "executable");
1452 packet_reply_hex_to_str(gdbctx, buffer);
1453 packet_reply_close(gdbctx);
1455 while (ok)
1457 deco = ' ';
1458 if (entry.th32ProcessID == gdbctx->process->pid) deco = '>';
1459 packet_reply_open(gdbctx);
1460 packet_reply_catc(gdbctx, 'O');
1461 snprintf(buffer, sizeof(buffer),
1462 "%c%08x %-8d %08x '%s'\n",
1463 deco, entry.th32ProcessID, entry.cntThreads,
1464 entry.th32ParentProcessID, entry.szExeFile);
1465 packet_reply_hex_to_str(gdbctx, buffer);
1466 packet_reply_close(gdbctx);
1467 ok = Process32Next(snap, &entry);
1469 CloseHandle(snap);
1470 packet_reply(gdbctx, "OK", 2);
1473 static void packet_query_monitor_mem(struct gdb_context* gdbctx, int len, const char* str)
1475 MEMORY_BASIC_INFORMATION mbi;
1476 char* addr = 0;
1477 const char* state;
1478 const char* type;
1479 char prot[3+1];
1480 char buffer[128];
1482 /* we do the output in several 'O' packets, with the last one being just OK for
1483 * marking the end of the output */
1484 packet_reply_open(gdbctx);
1485 packet_reply_catc(gdbctx, 'O');
1486 packet_reply_hex_to_str(gdbctx, "Address Size State Type RWX\n");
1487 packet_reply_close(gdbctx);
1489 while (VirtualQueryEx(gdbctx->process->handle, addr, &mbi, sizeof(mbi)) >= sizeof(mbi))
1491 switch (mbi.State)
1493 case MEM_COMMIT: state = "commit "; break;
1494 case MEM_FREE: state = "free "; break;
1495 case MEM_RESERVE: state = "reserve"; break;
1496 default: state = "??? "; break;
1498 if (mbi.State != MEM_FREE)
1500 switch (mbi.Type)
1502 case MEM_IMAGE: type = "image "; break;
1503 case MEM_MAPPED: type = "mapped "; break;
1504 case MEM_PRIVATE: type = "private"; break;
1505 case 0: type = " "; break;
1506 default: type = "??? "; break;
1508 memset(prot, ' ' , sizeof(prot)-1);
1509 prot[sizeof(prot)-1] = '\0';
1510 if (mbi.AllocationProtect & (PAGE_READONLY|PAGE_READWRITE|PAGE_EXECUTE_READ|PAGE_EXECUTE_READWRITE))
1511 prot[0] = 'R';
1512 if (mbi.AllocationProtect & (PAGE_READWRITE|PAGE_EXECUTE_READWRITE))
1513 prot[1] = 'W';
1514 if (mbi.AllocationProtect & (PAGE_WRITECOPY|PAGE_EXECUTE_WRITECOPY))
1515 prot[1] = 'C';
1516 if (mbi.AllocationProtect & (PAGE_EXECUTE|PAGE_EXECUTE_READ|PAGE_EXECUTE_READWRITE))
1517 prot[2] = 'X';
1519 else
1521 type = "";
1522 prot[0] = '\0';
1524 packet_reply_open(gdbctx);
1525 snprintf(buffer, sizeof(buffer), "%0*lx %0*lx %s %s %s\n",
1526 (unsigned)sizeof(void*), (DWORD_PTR)addr,
1527 (unsigned)sizeof(void*), mbi.RegionSize, state, type, prot);
1528 packet_reply_catc(gdbctx, 'O');
1529 packet_reply_hex_to_str(gdbctx, buffer);
1530 packet_reply_close(gdbctx);
1532 if (addr + mbi.RegionSize < addr) /* wrap around ? */
1533 break;
1534 addr += mbi.RegionSize;
1536 packet_reply(gdbctx, "OK", 2);
1539 struct query_detail
1541 int with_arg;
1542 const char* name;
1543 size_t len;
1544 void (*handler)(struct gdb_context*, int, const char*);
1545 } query_details[] =
1547 {0, "wnd", 3, packet_query_monitor_wnd},
1548 {0, "window", 6, packet_query_monitor_wnd},
1549 {0, "proc", 4, packet_query_monitor_process},
1550 {0, "process", 7, packet_query_monitor_process},
1551 {0, "mem", 3, packet_query_monitor_mem},
1552 {0, NULL, 0, NULL},
1555 static enum packet_return packet_query_remote_command(struct gdb_context* gdbctx,
1556 const char* hxcmd, size_t len)
1558 char buffer[128];
1559 struct query_detail* qd;
1561 assert((len & 1) == 0 && len < 2 * sizeof(buffer));
1562 len /= 2;
1563 hex_from(buffer, hxcmd, len);
1565 for (qd = query_details; qd->name != NULL; qd++)
1567 if (len < qd->len || strncmp(buffer, qd->name, qd->len) != 0) continue;
1568 if (!qd->with_arg && len != qd->len) continue;
1570 (qd->handler)(gdbctx, len - qd->len, buffer + qd->len);
1571 return packet_done;
1573 return packet_reply_error(gdbctx, EINVAL);
1576 static enum packet_return packet_query(struct gdb_context* gdbctx)
1578 switch (gdbctx->in_packet[0])
1580 case 'f':
1581 if (strncmp(gdbctx->in_packet + 1, "ThreadInfo", gdbctx->in_packet_len - 1) == 0)
1583 struct dbg_thread* thd;
1585 packet_reply_open(gdbctx);
1586 packet_reply_add(gdbctx, "m", 1);
1587 LIST_FOR_EACH_ENTRY(thd, &gdbctx->process->threads, struct dbg_thread, entry)
1589 packet_reply_val(gdbctx, thd->tid, 4);
1590 if (list_next(&gdbctx->process->threads, &thd->entry) != NULL)
1591 packet_reply_add(gdbctx, ",", 1);
1593 packet_reply_close(gdbctx);
1594 return packet_done;
1596 else if (strncmp(gdbctx->in_packet + 1, "ProcessInfo", gdbctx->in_packet_len - 1) == 0)
1598 char result[128];
1600 packet_reply_open(gdbctx);
1601 packet_reply_catc(gdbctx, 'O');
1602 get_process_info(gdbctx, result, sizeof(result));
1603 packet_reply_hex_to_str(gdbctx, result);
1604 packet_reply_close(gdbctx);
1605 return packet_done;
1607 break;
1608 case 's':
1609 if (strncmp(gdbctx->in_packet + 1, "ThreadInfo", gdbctx->in_packet_len - 1) == 0)
1611 packet_reply(gdbctx, "l", 1);
1612 return packet_done;
1614 else if (strncmp(gdbctx->in_packet + 1, "ProcessInfo", gdbctx->in_packet_len - 1) == 0)
1616 packet_reply(gdbctx, "l", 1);
1617 return packet_done;
1619 break;
1620 case 'A':
1621 if (strncmp(gdbctx->in_packet, "Attached", gdbctx->in_packet_len) == 0)
1623 char buf[2];
1625 buf[0] = '1';
1626 buf[1] = 0;
1627 return packet_reply(gdbctx, buf, -1);
1629 break;
1630 case 'C':
1631 if (gdbctx->in_packet_len == 1)
1633 struct dbg_thread* thd;
1634 /* FIXME: doc says 16 bit val ??? */
1635 /* grab first created thread, aka last in list */
1636 assert(gdbctx->process && !list_empty(&gdbctx->process->threads));
1637 thd = LIST_ENTRY(list_tail(&gdbctx->process->threads), struct dbg_thread, entry);
1638 packet_reply_open(gdbctx);
1639 packet_reply_add(gdbctx, "QC", 2);
1640 packet_reply_val(gdbctx, thd->tid, 4);
1641 packet_reply_close(gdbctx);
1642 return packet_done;
1644 break;
1645 case 'O':
1646 if (strncmp(gdbctx->in_packet, "Offsets", gdbctx->in_packet_len) == 0)
1648 char buf[64];
1650 snprintf(buf, sizeof(buf),
1651 "Text=%08lx;Data=%08lx;Bss=%08lx",
1652 gdbctx->wine_segs[0], gdbctx->wine_segs[1],
1653 gdbctx->wine_segs[2]);
1654 return packet_reply(gdbctx, buf, -1);
1656 break;
1657 case 'R':
1658 if (gdbctx->in_packet_len > 5 && strncmp(gdbctx->in_packet, "Rcmd,", 5) == 0)
1660 return packet_query_remote_command(gdbctx, gdbctx->in_packet + 5,
1661 gdbctx->in_packet_len - 5);
1663 break;
1664 case 'S':
1665 if (strncmp(gdbctx->in_packet, "Symbol::", gdbctx->in_packet_len) == 0)
1666 return packet_ok;
1667 if (strncmp(gdbctx->in_packet, "Supported", 9) == 0)
1669 if (strlen(target_xml))
1670 return packet_reply(gdbctx, "PacketSize=400;qXfer:features:read+", -1);
1671 else
1673 /* no features supported */
1674 packet_reply_open(gdbctx);
1675 packet_reply_close(gdbctx);
1676 return packet_done;
1679 break;
1680 case 'T':
1681 if (gdbctx->in_packet_len > 15 &&
1682 strncmp(gdbctx->in_packet, "ThreadExtraInfo", 15) == 0 &&
1683 gdbctx->in_packet[15] == ',')
1685 unsigned tid;
1686 char* end;
1687 char result[128];
1689 tid = strtol(gdbctx->in_packet + 16, &end, 16);
1690 if (end == NULL) break;
1691 get_thread_info(gdbctx, tid, result, sizeof(result));
1692 packet_reply_open(gdbctx);
1693 packet_reply_hex_to_str(gdbctx, result);
1694 packet_reply_close(gdbctx);
1695 return packet_done;
1697 if (strncmp(gdbctx->in_packet, "TStatus", 7) == 0)
1699 /* Tracepoints not supported */
1700 packet_reply_open(gdbctx);
1701 packet_reply_close(gdbctx);
1702 return packet_done;
1704 break;
1705 case 'X':
1706 if (strlen(target_xml) && strncmp(gdbctx->in_packet, "Xfer:features:read:target.xml", 29) == 0)
1707 return packet_reply(gdbctx, target_xml, -1);
1708 break;
1710 ERR("Unhandled query %s\n", debugstr_an(gdbctx->in_packet, gdbctx->in_packet_len));
1711 return packet_error;
1714 static enum packet_return packet_step(struct gdb_context* gdbctx)
1716 /* FIXME: add support for address in packet */
1717 assert(gdbctx->in_packet_len == 0);
1718 if (dbg_curr_thread != gdbctx->exec_thread && gdbctx->exec_thread)
1719 FIXME("Can't single-step thread %04x while on thread %04x\n",
1720 gdbctx->exec_thread->tid, dbg_curr_thread->tid);
1721 gdbctx->process->be_cpu->single_step(&gdbctx->context, TRUE);
1722 resume_debuggee(gdbctx, DBG_CONTINUE);
1723 wait_for_debuggee(gdbctx);
1724 gdbctx->process->be_cpu->single_step(&gdbctx->context, FALSE);
1725 return packet_reply_status(gdbctx);
1728 #if 0
1729 static enum packet_return packet_step_signal(struct gdb_context* gdbctx)
1731 unsigned char sig;
1733 /* FIXME: add support for address in packet */
1734 assert(gdbctx->in_packet_len == 2);
1735 if (dbg_curr_thread->tid != gdbctx->exec_thread && gdbctx->exec_thread)
1736 if (gdbctx->trace & GDBPXY_TRC_COMMAND_ERROR)
1737 fprintf(stderr, "NIY: step/sig on %u, while last thread is %u\n",
1738 gdbctx->exec_thread, DEBUG_CurrThread->tid);
1739 hex_from(&sig, gdbctx->in_packet, 1);
1740 /* cannot change signals on the fly */
1741 if (gdbctx->trace & GDBPXY_TRC_COMMAND)
1742 fprintf(stderr, "sigs: %u %u\n", sig, gdbctx->last_sig);
1743 if (sig != gdbctx->last_sig)
1744 return packet_error;
1745 resume_debuggee(gdbctx, DBG_EXCEPTION_NOT_HANDLED);
1746 wait_for_debuggee(gdbctx);
1747 return packet_reply_status(gdbctx);
1749 #endif
1751 static enum packet_return packet_thread_alive(struct gdb_context* gdbctx)
1753 char* end;
1754 unsigned tid;
1756 tid = strtol(gdbctx->in_packet, &end, 16);
1757 if (tid == -1 || tid == 0)
1758 return packet_reply_error(gdbctx, EINVAL);
1759 if (dbg_get_thread(gdbctx->process, tid) != NULL)
1760 return packet_ok;
1761 return packet_reply_error(gdbctx, ESRCH);
1764 /* =============================================== *
1765 * P A C K E T I N F R A S T R U C T U R E *
1766 * =============================================== *
1769 struct packet_entry
1771 char key;
1772 enum packet_return (*handler)(struct gdb_context* gdbctx);
1775 static struct packet_entry packet_entries[] =
1777 /*{'!', packet_extended}, */
1778 {'?', packet_last_signal},
1779 {'c', packet_continue},
1780 {'C', packet_continue_signal},
1781 {'D', packet_detach},
1782 {'g', packet_read_registers},
1783 {'G', packet_write_registers},
1784 {'k', packet_kill},
1785 {'H', packet_thread},
1786 {'m', packet_read_memory},
1787 {'M', packet_write_memory},
1788 {'p', packet_read_register},
1789 {'P', packet_write_register},
1790 {'q', packet_query},
1791 /* {'Q', packet_set}, */
1792 /* {'R', packet,restart}, only in extended mode ! */
1793 {'s', packet_step},
1794 /*{'S', packet_step_signal}, hard(er) to implement */
1795 {'T', packet_thread_alive},
1796 {'v', packet_verbose},
1799 static BOOL extract_packets(struct gdb_context* gdbctx)
1801 char* end;
1802 int plen;
1803 unsigned char in_cksum, loc_cksum;
1804 char* ptr;
1805 enum packet_return ret = packet_error;
1806 int num_packet = 0;
1808 while ((ret & packet_last_f) == 0)
1810 TRACE("Packet: %s\n", debugstr_an(gdbctx->in_buf, gdbctx->in_len));
1811 ptr = memchr(gdbctx->in_buf, '$', gdbctx->in_len);
1812 if (ptr == NULL) return FALSE;
1813 if (ptr != gdbctx->in_buf)
1815 int glen = ptr - gdbctx->in_buf; /* garbage len */
1816 WARN("Removing garbage: %s\n", debugstr_an(gdbctx->in_buf, glen));
1817 gdbctx->in_len -= glen;
1818 memmove(gdbctx->in_buf, ptr, gdbctx->in_len);
1820 end = memchr(gdbctx->in_buf + 1, '#', gdbctx->in_len);
1821 if (end == NULL) return FALSE;
1822 /* no checksum yet */
1823 if (end + 3 > gdbctx->in_buf + gdbctx->in_len) return FALSE;
1824 plen = end - gdbctx->in_buf - 1;
1825 hex_from(&in_cksum, end + 1, 1);
1826 loc_cksum = checksum(gdbctx->in_buf + 1, plen);
1827 if (loc_cksum == in_cksum)
1829 if (num_packet == 0) {
1830 int i;
1832 ret = packet_error;
1834 write(gdbctx->sock, "+", 1);
1835 assert(plen);
1837 /* FIXME: should use bsearch if packet_entries was sorted */
1838 for (i = 0; i < ARRAY_SIZE(packet_entries); i++)
1840 if (packet_entries[i].key == gdbctx->in_buf[1]) break;
1842 if (i == ARRAY_SIZE(packet_entries))
1843 WARN("Unhandled packet %s\n", debugstr_an(&gdbctx->in_buf[1], plen));
1844 else
1846 gdbctx->in_packet = gdbctx->in_buf + 2;
1847 gdbctx->in_packet_len = plen - 1;
1848 ret = (packet_entries[i].handler)(gdbctx);
1850 switch (ret & ~packet_last_f)
1852 case packet_error: packet_reply(gdbctx, "", 0); break;
1853 case packet_ok: packet_reply(gdbctx, "OK", 2); break;
1854 case packet_done: break;
1856 TRACE("Reply: %s\n", debugstr_an(gdbctx->out_buf, gdbctx->out_len));
1857 i = write(gdbctx->sock, gdbctx->out_buf, gdbctx->out_len);
1858 assert(i == gdbctx->out_len);
1859 /* if this fails, we'll have to use POLLOUT...
1861 gdbctx->out_len = 0;
1862 num_packet++;
1864 else
1866 /* FIXME: If we have more than one packet in our input buffer,
1867 * it's very likely that we took too long to answer to a given packet
1868 * and gdb is sending us the same packet again.
1869 * So we simply drop the second packet. This will lower the risk of error,
1870 * but there are still some race conditions here.
1871 * A better fix (yet not perfect) would be to have two threads:
1872 * - one managing the packets for gdb
1873 * - the second one managing the commands...
1874 * This would allow us to send the reply with the '+' character (Ack of
1875 * the command) way sooner than we do now.
1877 ERR("Dropping packet; I was too slow to respond\n");
1880 else
1882 write(gdbctx->sock, "+", 1);
1883 ERR("Dropping packet; invalid checksum %d <> %d\n", in_cksum, loc_cksum);
1885 gdbctx->in_len -= plen + 4;
1886 memmove(gdbctx->in_buf, end + 3, gdbctx->in_len);
1888 return TRUE;
1891 static int fetch_data(struct gdb_context* gdbctx)
1893 int len, in_len = gdbctx->in_len;
1895 assert(gdbctx->in_len <= gdbctx->in_buf_alloc);
1896 for (;;)
1898 #define STEP 128
1899 if (gdbctx->in_len + STEP > gdbctx->in_buf_alloc)
1900 gdbctx->in_buf = packet_realloc(gdbctx->in_buf, gdbctx->in_buf_alloc += STEP);
1901 #undef STEP
1902 len = read(gdbctx->sock, gdbctx->in_buf + gdbctx->in_len, gdbctx->in_buf_alloc - gdbctx->in_len);
1903 if (len <= 0) break;
1904 gdbctx->in_len += len;
1905 assert(gdbctx->in_len <= gdbctx->in_buf_alloc);
1906 if (len < gdbctx->in_buf_alloc - gdbctx->in_len) break;
1908 return gdbctx->in_len - in_len;
1911 #define FLAG_NO_START 1
1912 #define FLAG_WITH_XTERM 2
1914 static BOOL gdb_exec(const char* wine_path, unsigned port, unsigned flags)
1916 char buf[MAX_PATH];
1917 int fd;
1918 const char *gdb_path, *tmp_path;
1919 FILE* f;
1921 if (!(gdb_path = getenv("WINE_GDB"))) gdb_path = "gdb";
1922 if (!(tmp_path = getenv("TMPDIR"))) tmp_path = "/tmp";
1923 strcpy(buf, tmp_path);
1924 strcat(buf, "/winegdb.XXXXXX");
1925 fd = mkstemps(buf, 0);
1926 if (fd == -1) return FALSE;
1927 if ((f = fdopen(fd, "w+")) == NULL) return FALSE;
1928 fprintf(f, "file %s\n", wine_path);
1929 fprintf(f, "target remote localhost:%d\n", ntohs(port));
1930 fprintf(f, "set prompt Wine-gdb>\\ \n");
1931 /* gdb 5.1 seems to require it, won't hurt anyway */
1932 fprintf(f, "sharedlibrary\n");
1933 /* This is needed (but not a decent & final fix)
1934 * Without this, gdb would skip our inter-DLL relay code (because
1935 * we don't have any line number information for the relay code)
1936 * With this, we will stop on first instruction of the stub, and
1937 * reusing step, will get us through the relay stub at the actual
1938 * function we're looking at.
1940 fprintf(f, "set step-mode on\n");
1941 /* tell gdb to delete this file when done handling it... */
1942 fprintf(f, "shell rm -f \"%s\"\n", buf);
1943 fclose(f);
1944 if (flags & FLAG_WITH_XTERM)
1945 execlp("xterm", "xterm", "-e", gdb_path, "-x", buf, NULL);
1946 else
1947 execlp(gdb_path, gdb_path, "-x", buf, NULL);
1948 assert(0); /* never reached */
1949 return TRUE;
1952 static BOOL gdb_startup(struct gdb_context* gdbctx, DEBUG_EVENT* de, unsigned flags, unsigned port)
1954 int sock;
1955 struct sockaddr_in s_addrs = {0};
1956 socklen_t s_len = sizeof(s_addrs);
1957 struct pollfd pollfd;
1958 IMAGEHLP_MODULE64 imh_mod;
1959 BOOL ret = FALSE;
1961 /* step 1: create socket for gdb connection request */
1962 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
1964 ERR("Failed to create socket: %s\n", strerror(errno));
1965 return FALSE;
1968 s_addrs.sin_family = AF_INET;
1969 s_addrs.sin_addr.s_addr = INADDR_ANY;
1970 s_addrs.sin_port = htons(port);
1971 if (bind(sock, (struct sockaddr *)&s_addrs, sizeof(s_addrs)) == -1)
1972 goto cleanup;
1974 if (listen(sock, 1) == -1 || getsockname(sock, (struct sockaddr*)&s_addrs, &s_len) == -1)
1975 goto cleanup;
1977 /* step 2: do the process internal creation */
1978 handle_debug_event(gdbctx, de);
1980 /* step3: get the wine loader name */
1981 if (!dbg_get_debuggee_info(gdbctx->process->handle, &imh_mod))
1982 goto cleanup;
1984 /* step 4: fire up gdb (if requested) */
1985 if (flags & FLAG_NO_START)
1986 fprintf(stderr, "target remote localhost:%d\n", ntohs(s_addrs.sin_port));
1987 else
1988 switch (fork())
1990 case -1: /* error in parent... */
1991 ERR("Failed to start gdb: fork: %s\n", strerror(errno));
1992 goto cleanup;
1993 default: /* in parent... success */
1994 signal(SIGINT, SIG_IGN);
1995 break;
1996 case 0: /* in child... and alive */
1997 gdb_exec(imh_mod.LoadedImageName, s_addrs.sin_port, flags);
1998 /* if we're here, exec failed, so report failure */
1999 goto cleanup;
2002 /* step 5: wait for gdb to connect actually */
2003 pollfd.fd = sock;
2004 pollfd.events = POLLIN;
2005 pollfd.revents = 0;
2007 switch (poll(&pollfd, 1, -1))
2009 case 1:
2010 if (pollfd.revents & POLLIN)
2012 int dummy = 1;
2013 gdbctx->sock = accept(sock, (struct sockaddr*)&s_addrs, &s_len);
2014 if (gdbctx->sock == -1)
2015 break;
2016 ret = TRUE;
2017 TRACE("connected on %d\n", gdbctx->sock);
2018 /* don't keep our small packets too long: send them ASAP back to GDB
2019 * without this, GDB really crawls
2021 setsockopt(gdbctx->sock, IPPROTO_TCP, TCP_NODELAY, (char*)&dummy, sizeof(dummy));
2023 break;
2024 case 0:
2025 ERR("Timed out connecting to gdb\n");
2026 break;
2027 case -1:
2028 ERR("Failed to connect to gdb: poll: %s\n", strerror(errno));
2029 break;
2030 default:
2031 assert(0);
2034 cleanup:
2035 close(sock);
2036 return ret;
2039 static BOOL gdb_init_context(struct gdb_context* gdbctx, unsigned flags, unsigned port)
2041 DEBUG_EVENT de;
2042 int i;
2044 gdbctx->sock = -1;
2045 gdbctx->in_buf = NULL;
2046 gdbctx->in_buf_alloc = 0;
2047 gdbctx->in_len = 0;
2048 gdbctx->out_buf = NULL;
2049 gdbctx->out_buf_alloc = 0;
2050 gdbctx->out_len = 0;
2051 gdbctx->out_curr_packet = -1;
2053 gdbctx->exec_thread = gdbctx->other_thread = NULL;
2054 gdbctx->last_sig = 0;
2055 gdbctx->in_trap = FALSE;
2056 gdbctx->process = NULL;
2057 for (i = 0; i < ARRAY_SIZE(gdbctx->wine_segs); i++)
2058 gdbctx->wine_segs[i] = 0;
2060 /* wait for first trap */
2061 while (WaitForDebugEvent(&de, INFINITE))
2063 if (de.dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT)
2065 /* this should be the first event we get,
2066 * and the only one of this type */
2067 assert(gdbctx->process == NULL && de.dwProcessId == dbg_curr_pid);
2068 /* gdbctx->dwProcessId = pid; */
2069 if (!gdb_startup(gdbctx, &de, flags, port)) return FALSE;
2070 assert(!gdbctx->in_trap);
2072 else
2074 handle_debug_event(gdbctx, &de);
2075 if (gdbctx->in_trap) break;
2077 ContinueDebugEvent(de.dwProcessId, de.dwThreadId, DBG_CONTINUE);
2079 return TRUE;
2082 static int gdb_remote(unsigned flags, unsigned port)
2084 struct pollfd pollfd;
2085 struct gdb_context gdbctx;
2086 BOOL doLoop;
2088 for (doLoop = gdb_init_context(&gdbctx, flags, port); doLoop;)
2090 pollfd.fd = gdbctx.sock;
2091 pollfd.events = POLLIN;
2092 pollfd.revents = 0;
2094 switch (poll(&pollfd, 1, -1))
2096 case 1:
2097 /* got something */
2098 if (pollfd.revents & (POLLHUP | POLLERR))
2100 ERR("gdb hung up\n");
2101 /* kill also debuggee process - questionnable - */
2102 detach_debuggee(&gdbctx, TRUE);
2103 doLoop = FALSE;
2104 break;
2106 if ((pollfd.revents & POLLIN) && fetch_data(&gdbctx) > 0)
2108 if (extract_packets(&gdbctx)) doLoop = FALSE;
2110 break;
2111 case 0:
2112 /* timeout, should never happen (infinite timeout) */
2113 break;
2114 case -1:
2115 ERR("poll failed: %s\n", strerror(errno));
2116 doLoop = FALSE;
2117 break;
2120 wait(NULL);
2121 return 0;
2123 #endif
2125 int gdb_main(int argc, char* argv[])
2127 #ifdef HAVE_POLL
2128 unsigned gdb_flags = 0, port = 0;
2129 char *port_end;
2131 argc--; argv++;
2132 while (argc > 0 && argv[0][0] == '-')
2134 if (strcmp(argv[0], "--no-start") == 0)
2136 gdb_flags |= FLAG_NO_START;
2137 argc--; argv++;
2138 continue;
2140 if (strcmp(argv[0], "--with-xterm") == 0)
2142 gdb_flags |= FLAG_WITH_XTERM;
2143 argc--; argv++;
2144 continue;
2146 if (strcmp(argv[0], "--port") == 0 && argc > 1)
2148 port = strtoul(argv[1], &port_end, 10);
2149 if (*port_end)
2151 fprintf(stderr, "Invalid port: %s\n", argv[1]);
2152 return -1;
2154 argc -= 2; argv += 2;
2155 continue;
2157 return -1;
2159 if (dbg_active_attach(argc, argv) == start_ok ||
2160 dbg_active_launch(argc, argv) == start_ok)
2161 return gdb_remote(gdb_flags, port);
2162 #else
2163 fprintf(stderr, "GdbProxy mode not supported on this platform\n");
2164 #endif
2165 return -1;