]> Git Repo - qemu.git/blob - gdbstub.c
gdbstub: Change gdbserver_fork() to accept cpu instead of env
[qemu.git] / gdbstub.c
1 /*
2  * gdb server stub
3  *
4  * Copyright (c) 2003-2005 Fabrice Bellard
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 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, see <http://www.gnu.org/licenses/>.
18  */
19 #include "config.h"
20 #include "qemu-common.h"
21 #ifdef CONFIG_USER_ONLY
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <stdarg.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29
30 #include "qemu.h"
31 #else
32 #include "monitor/monitor.h"
33 #include "sysemu/char.h"
34 #include "sysemu/sysemu.h"
35 #include "exec/gdbstub.h"
36 #endif
37
38 #define MAX_PACKET_LENGTH 4096
39
40 #include "cpu.h"
41 #include "qemu/sockets.h"
42 #include "sysemu/kvm.h"
43 #include "exec/semihost.h"
44
45 #ifdef CONFIG_USER_ONLY
46 #define GDB_ATTACHED "0"
47 #else
48 #define GDB_ATTACHED "1"
49 #endif
50
51 static inline int target_memory_rw_debug(CPUState *cpu, target_ulong addr,
52                                          uint8_t *buf, int len, bool is_write)
53 {
54     CPUClass *cc = CPU_GET_CLASS(cpu);
55
56     if (cc->memory_rw_debug) {
57         return cc->memory_rw_debug(cpu, addr, buf, len, is_write);
58     }
59     return cpu_memory_rw_debug(cpu, addr, buf, len, is_write);
60 }
61
62 enum {
63     GDB_SIGNAL_0 = 0,
64     GDB_SIGNAL_INT = 2,
65     GDB_SIGNAL_QUIT = 3,
66     GDB_SIGNAL_TRAP = 5,
67     GDB_SIGNAL_ABRT = 6,
68     GDB_SIGNAL_ALRM = 14,
69     GDB_SIGNAL_IO = 23,
70     GDB_SIGNAL_XCPU = 24,
71     GDB_SIGNAL_UNKNOWN = 143
72 };
73
74 #ifdef CONFIG_USER_ONLY
75
76 /* Map target signal numbers to GDB protocol signal numbers and vice
77  * versa.  For user emulation's currently supported systems, we can
78  * assume most signals are defined.
79  */
80
81 static int gdb_signal_table[] = {
82     0,
83     TARGET_SIGHUP,
84     TARGET_SIGINT,
85     TARGET_SIGQUIT,
86     TARGET_SIGILL,
87     TARGET_SIGTRAP,
88     TARGET_SIGABRT,
89     -1, /* SIGEMT */
90     TARGET_SIGFPE,
91     TARGET_SIGKILL,
92     TARGET_SIGBUS,
93     TARGET_SIGSEGV,
94     TARGET_SIGSYS,
95     TARGET_SIGPIPE,
96     TARGET_SIGALRM,
97     TARGET_SIGTERM,
98     TARGET_SIGURG,
99     TARGET_SIGSTOP,
100     TARGET_SIGTSTP,
101     TARGET_SIGCONT,
102     TARGET_SIGCHLD,
103     TARGET_SIGTTIN,
104     TARGET_SIGTTOU,
105     TARGET_SIGIO,
106     TARGET_SIGXCPU,
107     TARGET_SIGXFSZ,
108     TARGET_SIGVTALRM,
109     TARGET_SIGPROF,
110     TARGET_SIGWINCH,
111     -1, /* SIGLOST */
112     TARGET_SIGUSR1,
113     TARGET_SIGUSR2,
114 #ifdef TARGET_SIGPWR
115     TARGET_SIGPWR,
116 #else
117     -1,
118 #endif
119     -1, /* SIGPOLL */
120     -1,
121     -1,
122     -1,
123     -1,
124     -1,
125     -1,
126     -1,
127     -1,
128     -1,
129     -1,
130     -1,
131 #ifdef __SIGRTMIN
132     __SIGRTMIN + 1,
133     __SIGRTMIN + 2,
134     __SIGRTMIN + 3,
135     __SIGRTMIN + 4,
136     __SIGRTMIN + 5,
137     __SIGRTMIN + 6,
138     __SIGRTMIN + 7,
139     __SIGRTMIN + 8,
140     __SIGRTMIN + 9,
141     __SIGRTMIN + 10,
142     __SIGRTMIN + 11,
143     __SIGRTMIN + 12,
144     __SIGRTMIN + 13,
145     __SIGRTMIN + 14,
146     __SIGRTMIN + 15,
147     __SIGRTMIN + 16,
148     __SIGRTMIN + 17,
149     __SIGRTMIN + 18,
150     __SIGRTMIN + 19,
151     __SIGRTMIN + 20,
152     __SIGRTMIN + 21,
153     __SIGRTMIN + 22,
154     __SIGRTMIN + 23,
155     __SIGRTMIN + 24,
156     __SIGRTMIN + 25,
157     __SIGRTMIN + 26,
158     __SIGRTMIN + 27,
159     __SIGRTMIN + 28,
160     __SIGRTMIN + 29,
161     __SIGRTMIN + 30,
162     __SIGRTMIN + 31,
163     -1, /* SIGCANCEL */
164     __SIGRTMIN,
165     __SIGRTMIN + 32,
166     __SIGRTMIN + 33,
167     __SIGRTMIN + 34,
168     __SIGRTMIN + 35,
169     __SIGRTMIN + 36,
170     __SIGRTMIN + 37,
171     __SIGRTMIN + 38,
172     __SIGRTMIN + 39,
173     __SIGRTMIN + 40,
174     __SIGRTMIN + 41,
175     __SIGRTMIN + 42,
176     __SIGRTMIN + 43,
177     __SIGRTMIN + 44,
178     __SIGRTMIN + 45,
179     __SIGRTMIN + 46,
180     __SIGRTMIN + 47,
181     __SIGRTMIN + 48,
182     __SIGRTMIN + 49,
183     __SIGRTMIN + 50,
184     __SIGRTMIN + 51,
185     __SIGRTMIN + 52,
186     __SIGRTMIN + 53,
187     __SIGRTMIN + 54,
188     __SIGRTMIN + 55,
189     __SIGRTMIN + 56,
190     __SIGRTMIN + 57,
191     __SIGRTMIN + 58,
192     __SIGRTMIN + 59,
193     __SIGRTMIN + 60,
194     __SIGRTMIN + 61,
195     __SIGRTMIN + 62,
196     __SIGRTMIN + 63,
197     __SIGRTMIN + 64,
198     __SIGRTMIN + 65,
199     __SIGRTMIN + 66,
200     __SIGRTMIN + 67,
201     __SIGRTMIN + 68,
202     __SIGRTMIN + 69,
203     __SIGRTMIN + 70,
204     __SIGRTMIN + 71,
205     __SIGRTMIN + 72,
206     __SIGRTMIN + 73,
207     __SIGRTMIN + 74,
208     __SIGRTMIN + 75,
209     __SIGRTMIN + 76,
210     __SIGRTMIN + 77,
211     __SIGRTMIN + 78,
212     __SIGRTMIN + 79,
213     __SIGRTMIN + 80,
214     __SIGRTMIN + 81,
215     __SIGRTMIN + 82,
216     __SIGRTMIN + 83,
217     __SIGRTMIN + 84,
218     __SIGRTMIN + 85,
219     __SIGRTMIN + 86,
220     __SIGRTMIN + 87,
221     __SIGRTMIN + 88,
222     __SIGRTMIN + 89,
223     __SIGRTMIN + 90,
224     __SIGRTMIN + 91,
225     __SIGRTMIN + 92,
226     __SIGRTMIN + 93,
227     __SIGRTMIN + 94,
228     __SIGRTMIN + 95,
229     -1, /* SIGINFO */
230     -1, /* UNKNOWN */
231     -1, /* DEFAULT */
232     -1,
233     -1,
234     -1,
235     -1,
236     -1,
237     -1
238 #endif
239 };
240 #else
241 /* In system mode we only need SIGINT and SIGTRAP; other signals
242    are not yet supported.  */
243
244 enum {
245     TARGET_SIGINT = 2,
246     TARGET_SIGTRAP = 5
247 };
248
249 static int gdb_signal_table[] = {
250     -1,
251     -1,
252     TARGET_SIGINT,
253     -1,
254     -1,
255     TARGET_SIGTRAP
256 };
257 #endif
258
259 #ifdef CONFIG_USER_ONLY
260 static int target_signal_to_gdb (int sig)
261 {
262     int i;
263     for (i = 0; i < ARRAY_SIZE (gdb_signal_table); i++)
264         if (gdb_signal_table[i] == sig)
265             return i;
266     return GDB_SIGNAL_UNKNOWN;
267 }
268 #endif
269
270 static int gdb_signal_to_target (int sig)
271 {
272     if (sig < ARRAY_SIZE (gdb_signal_table))
273         return gdb_signal_table[sig];
274     else
275         return -1;
276 }
277
278 //#define DEBUG_GDB
279
280 typedef struct GDBRegisterState {
281     int base_reg;
282     int num_regs;
283     gdb_reg_cb get_reg;
284     gdb_reg_cb set_reg;
285     const char *xml;
286     struct GDBRegisterState *next;
287 } GDBRegisterState;
288
289 enum RSState {
290     RS_INACTIVE,
291     RS_IDLE,
292     RS_GETLINE,
293     RS_CHKSUM1,
294     RS_CHKSUM2,
295 };
296 typedef struct GDBState {
297     CPUState *c_cpu; /* current CPU for step/continue ops */
298     CPUState *g_cpu; /* current CPU for other ops */
299     CPUState *query_cpu; /* for q{f|s}ThreadInfo */
300     enum RSState state; /* parsing state */
301     char line_buf[MAX_PACKET_LENGTH];
302     int line_buf_index;
303     int line_csum;
304     uint8_t last_packet[MAX_PACKET_LENGTH + 4];
305     int last_packet_len;
306     int signal;
307 #ifdef CONFIG_USER_ONLY
308     int fd;
309     int running_state;
310 #else
311     CharDriverState *chr;
312     CharDriverState *mon_chr;
313 #endif
314     char syscall_buf[256];
315     gdb_syscall_complete_cb current_syscall_cb;
316 } GDBState;
317
318 /* By default use no IRQs and no timers while single stepping so as to
319  * make single stepping like an ICE HW step.
320  */
321 static int sstep_flags = SSTEP_ENABLE|SSTEP_NOIRQ|SSTEP_NOTIMER;
322
323 static GDBState *gdbserver_state;
324
325 bool gdb_has_xml;
326
327 #ifdef CONFIG_USER_ONLY
328 /* XXX: This is not thread safe.  Do we care?  */
329 static int gdbserver_fd = -1;
330
331 static int get_char(GDBState *s)
332 {
333     uint8_t ch;
334     int ret;
335
336     for(;;) {
337         ret = qemu_recv(s->fd, &ch, 1, 0);
338         if (ret < 0) {
339             if (errno == ECONNRESET)
340                 s->fd = -1;
341             if (errno != EINTR && errno != EAGAIN)
342                 return -1;
343         } else if (ret == 0) {
344             close(s->fd);
345             s->fd = -1;
346             return -1;
347         } else {
348             break;
349         }
350     }
351     return ch;
352 }
353 #endif
354
355 static enum {
356     GDB_SYS_UNKNOWN,
357     GDB_SYS_ENABLED,
358     GDB_SYS_DISABLED,
359 } gdb_syscall_mode;
360
361 /* Decide if either remote gdb syscalls or native file IO should be used. */
362 int use_gdb_syscalls(void)
363 {
364     SemihostingTarget target = semihosting_get_target();
365     if (target == SEMIHOSTING_TARGET_NATIVE) {
366         /* -semihosting-config target=native */
367         return false;
368     } else if (target == SEMIHOSTING_TARGET_GDB) {
369         /* -semihosting-config target=gdb */
370         return true;
371     }
372
373     /* -semihosting-config target=auto */
374     /* On the first call check if gdb is connected and remember. */
375     if (gdb_syscall_mode == GDB_SYS_UNKNOWN) {
376         gdb_syscall_mode = (gdbserver_state ? GDB_SYS_ENABLED
377                                             : GDB_SYS_DISABLED);
378     }
379     return gdb_syscall_mode == GDB_SYS_ENABLED;
380 }
381
382 /* Resume execution.  */
383 static inline void gdb_continue(GDBState *s)
384 {
385 #ifdef CONFIG_USER_ONLY
386     s->running_state = 1;
387 #else
388     if (!runstate_needs_reset()) {
389         vm_start();
390     }
391 #endif
392 }
393
394 static void put_buffer(GDBState *s, const uint8_t *buf, int len)
395 {
396 #ifdef CONFIG_USER_ONLY
397     int ret;
398
399     while (len > 0) {
400         ret = send(s->fd, buf, len, 0);
401         if (ret < 0) {
402             if (errno != EINTR && errno != EAGAIN)
403                 return;
404         } else {
405             buf += ret;
406             len -= ret;
407         }
408     }
409 #else
410     qemu_chr_fe_write(s->chr, buf, len);
411 #endif
412 }
413
414 static inline int fromhex(int v)
415 {
416     if (v >= '0' && v <= '9')
417         return v - '0';
418     else if (v >= 'A' && v <= 'F')
419         return v - 'A' + 10;
420     else if (v >= 'a' && v <= 'f')
421         return v - 'a' + 10;
422     else
423         return 0;
424 }
425
426 static inline int tohex(int v)
427 {
428     if (v < 10)
429         return v + '0';
430     else
431         return v - 10 + 'a';
432 }
433
434 static void memtohex(char *buf, const uint8_t *mem, int len)
435 {
436     int i, c;
437     char *q;
438     q = buf;
439     for(i = 0; i < len; i++) {
440         c = mem[i];
441         *q++ = tohex(c >> 4);
442         *q++ = tohex(c & 0xf);
443     }
444     *q = '\0';
445 }
446
447 static void hextomem(uint8_t *mem, const char *buf, int len)
448 {
449     int i;
450
451     for(i = 0; i < len; i++) {
452         mem[i] = (fromhex(buf[0]) << 4) | fromhex(buf[1]);
453         buf += 2;
454     }
455 }
456
457 /* return -1 if error, 0 if OK */
458 static int put_packet_binary(GDBState *s, const char *buf, int len)
459 {
460     int csum, i;
461     uint8_t *p;
462
463     for(;;) {
464         p = s->last_packet;
465         *(p++) = '$';
466         memcpy(p, buf, len);
467         p += len;
468         csum = 0;
469         for(i = 0; i < len; i++) {
470             csum += buf[i];
471         }
472         *(p++) = '#';
473         *(p++) = tohex((csum >> 4) & 0xf);
474         *(p++) = tohex((csum) & 0xf);
475
476         s->last_packet_len = p - s->last_packet;
477         put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
478
479 #ifdef CONFIG_USER_ONLY
480         i = get_char(s);
481         if (i < 0)
482             return -1;
483         if (i == '+')
484             break;
485 #else
486         break;
487 #endif
488     }
489     return 0;
490 }
491
492 /* return -1 if error, 0 if OK */
493 static int put_packet(GDBState *s, const char *buf)
494 {
495 #ifdef DEBUG_GDB
496     printf("reply='%s'\n", buf);
497 #endif
498
499     return put_packet_binary(s, buf, strlen(buf));
500 }
501
502 /* Encode data using the encoding for 'x' packets.  */
503 static int memtox(char *buf, const char *mem, int len)
504 {
505     char *p = buf;
506     char c;
507
508     while (len--) {
509         c = *(mem++);
510         switch (c) {
511         case '#': case '$': case '*': case '}':
512             *(p++) = '}';
513             *(p++) = c ^ 0x20;
514             break;
515         default:
516             *(p++) = c;
517             break;
518         }
519     }
520     return p - buf;
521 }
522
523 static const char *get_feature_xml(const char *p, const char **newp,
524                                    CPUClass *cc)
525 {
526     size_t len;
527     int i;
528     const char *name;
529     static char target_xml[1024];
530
531     len = 0;
532     while (p[len] && p[len] != ':')
533         len++;
534     *newp = p + len;
535
536     name = NULL;
537     if (strncmp(p, "target.xml", len) == 0) {
538         /* Generate the XML description for this CPU.  */
539         if (!target_xml[0]) {
540             GDBRegisterState *r;
541             CPUState *cpu = first_cpu;
542
543             snprintf(target_xml, sizeof(target_xml),
544                      "<?xml version=\"1.0\"?>"
545                      "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
546                      "<target>"
547                      "<xi:include href=\"%s\"/>",
548                      cc->gdb_core_xml_file);
549
550             for (r = cpu->gdb_regs; r; r = r->next) {
551                 pstrcat(target_xml, sizeof(target_xml), "<xi:include href=\"");
552                 pstrcat(target_xml, sizeof(target_xml), r->xml);
553                 pstrcat(target_xml, sizeof(target_xml), "\"/>");
554             }
555             pstrcat(target_xml, sizeof(target_xml), "</target>");
556         }
557         return target_xml;
558     }
559     for (i = 0; ; i++) {
560         name = xml_builtin[i][0];
561         if (!name || (strncmp(name, p, len) == 0 && strlen(name) == len))
562             break;
563     }
564     return name ? xml_builtin[i][1] : NULL;
565 }
566
567 static int gdb_read_register(CPUState *cpu, uint8_t *mem_buf, int reg)
568 {
569     CPUClass *cc = CPU_GET_CLASS(cpu);
570     CPUArchState *env = cpu->env_ptr;
571     GDBRegisterState *r;
572
573     if (reg < cc->gdb_num_core_regs) {
574         return cc->gdb_read_register(cpu, mem_buf, reg);
575     }
576
577     for (r = cpu->gdb_regs; r; r = r->next) {
578         if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
579             return r->get_reg(env, mem_buf, reg - r->base_reg);
580         }
581     }
582     return 0;
583 }
584
585 static int gdb_write_register(CPUState *cpu, uint8_t *mem_buf, int reg)
586 {
587     CPUClass *cc = CPU_GET_CLASS(cpu);
588     CPUArchState *env = cpu->env_ptr;
589     GDBRegisterState *r;
590
591     if (reg < cc->gdb_num_core_regs) {
592         return cc->gdb_write_register(cpu, mem_buf, reg);
593     }
594
595     for (r = cpu->gdb_regs; r; r = r->next) {
596         if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
597             return r->set_reg(env, mem_buf, reg - r->base_reg);
598         }
599     }
600     return 0;
601 }
602
603 /* Register a supplemental set of CPU registers.  If g_pos is nonzero it
604    specifies the first register number and these registers are included in
605    a standard "g" packet.  Direction is relative to gdb, i.e. get_reg is
606    gdb reading a CPU register, and set_reg is gdb modifying a CPU register.
607  */
608
609 void gdb_register_coprocessor(CPUState *cpu,
610                               gdb_reg_cb get_reg, gdb_reg_cb set_reg,
611                               int num_regs, const char *xml, int g_pos)
612 {
613     GDBRegisterState *s;
614     GDBRegisterState **p;
615
616     p = &cpu->gdb_regs;
617     while (*p) {
618         /* Check for duplicates.  */
619         if (strcmp((*p)->xml, xml) == 0)
620             return;
621         p = &(*p)->next;
622     }
623
624     s = g_new0(GDBRegisterState, 1);
625     s->base_reg = cpu->gdb_num_regs;
626     s->num_regs = num_regs;
627     s->get_reg = get_reg;
628     s->set_reg = set_reg;
629     s->xml = xml;
630
631     /* Add to end of list.  */
632     cpu->gdb_num_regs += num_regs;
633     *p = s;
634     if (g_pos) {
635         if (g_pos != s->base_reg) {
636             fprintf(stderr, "Error: Bad gdb register numbering for '%s'\n"
637                     "Expected %d got %d\n", xml, g_pos, s->base_reg);
638         } else {
639             cpu->gdb_num_g_regs = cpu->gdb_num_regs;
640         }
641     }
642 }
643
644 #ifndef CONFIG_USER_ONLY
645 /* Translate GDB watchpoint type to a flags value for cpu_watchpoint_* */
646 static inline int xlat_gdb_type(CPUState *cpu, int gdbtype)
647 {
648     static const int xlat[] = {
649         [GDB_WATCHPOINT_WRITE]  = BP_GDB | BP_MEM_WRITE,
650         [GDB_WATCHPOINT_READ]   = BP_GDB | BP_MEM_READ,
651         [GDB_WATCHPOINT_ACCESS] = BP_GDB | BP_MEM_ACCESS,
652     };
653
654     CPUClass *cc = CPU_GET_CLASS(cpu);
655     int cputype = xlat[gdbtype];
656
657     if (cc->gdb_stop_before_watchpoint) {
658         cputype |= BP_STOP_BEFORE_ACCESS;
659     }
660     return cputype;
661 }
662 #endif
663
664 static int gdb_breakpoint_insert(target_ulong addr, target_ulong len, int type)
665 {
666     CPUState *cpu;
667     int err = 0;
668
669     if (kvm_enabled()) {
670         return kvm_insert_breakpoint(gdbserver_state->c_cpu, addr, len, type);
671     }
672
673     switch (type) {
674     case GDB_BREAKPOINT_SW:
675     case GDB_BREAKPOINT_HW:
676         CPU_FOREACH(cpu) {
677             err = cpu_breakpoint_insert(cpu, addr, BP_GDB, NULL);
678             if (err) {
679                 break;
680             }
681         }
682         return err;
683 #ifndef CONFIG_USER_ONLY
684     case GDB_WATCHPOINT_WRITE:
685     case GDB_WATCHPOINT_READ:
686     case GDB_WATCHPOINT_ACCESS:
687         CPU_FOREACH(cpu) {
688             err = cpu_watchpoint_insert(cpu, addr, len,
689                                         xlat_gdb_type(cpu, type), NULL);
690             if (err) {
691                 break;
692             }
693         }
694         return err;
695 #endif
696     default:
697         return -ENOSYS;
698     }
699 }
700
701 static int gdb_breakpoint_remove(target_ulong addr, target_ulong len, int type)
702 {
703     CPUState *cpu;
704     int err = 0;
705
706     if (kvm_enabled()) {
707         return kvm_remove_breakpoint(gdbserver_state->c_cpu, addr, len, type);
708     }
709
710     switch (type) {
711     case GDB_BREAKPOINT_SW:
712     case GDB_BREAKPOINT_HW:
713         CPU_FOREACH(cpu) {
714             err = cpu_breakpoint_remove(cpu, addr, BP_GDB);
715             if (err) {
716                 break;
717             }
718         }
719         return err;
720 #ifndef CONFIG_USER_ONLY
721     case GDB_WATCHPOINT_WRITE:
722     case GDB_WATCHPOINT_READ:
723     case GDB_WATCHPOINT_ACCESS:
724         CPU_FOREACH(cpu) {
725             err = cpu_watchpoint_remove(cpu, addr, len,
726                                         xlat_gdb_type(cpu, type));
727             if (err)
728                 break;
729         }
730         return err;
731 #endif
732     default:
733         return -ENOSYS;
734     }
735 }
736
737 static void gdb_breakpoint_remove_all(void)
738 {
739     CPUState *cpu;
740
741     if (kvm_enabled()) {
742         kvm_remove_all_breakpoints(gdbserver_state->c_cpu);
743         return;
744     }
745
746     CPU_FOREACH(cpu) {
747         cpu_breakpoint_remove_all(cpu, BP_GDB);
748 #ifndef CONFIG_USER_ONLY
749         cpu_watchpoint_remove_all(cpu, BP_GDB);
750 #endif
751     }
752 }
753
754 static void gdb_set_cpu_pc(GDBState *s, target_ulong pc)
755 {
756     CPUState *cpu = s->c_cpu;
757     CPUClass *cc = CPU_GET_CLASS(cpu);
758
759     cpu_synchronize_state(cpu);
760     if (cc->set_pc) {
761         cc->set_pc(cpu, pc);
762     }
763 }
764
765 static CPUState *find_cpu(uint32_t thread_id)
766 {
767     CPUState *cpu;
768
769     CPU_FOREACH(cpu) {
770         if (cpu_index(cpu) == thread_id) {
771             return cpu;
772         }
773     }
774
775     return NULL;
776 }
777
778 static int is_query_packet(const char *p, const char *query, char separator)
779 {
780     unsigned int query_len = strlen(query);
781
782     return strncmp(p, query, query_len) == 0 &&
783         (p[query_len] == '\0' || p[query_len] == separator);
784 }
785
786 static int gdb_handle_packet(GDBState *s, const char *line_buf)
787 {
788     CPUState *cpu;
789     CPUClass *cc;
790     const char *p;
791     uint32_t thread;
792     int ch, reg_size, type, res;
793     char buf[MAX_PACKET_LENGTH];
794     uint8_t mem_buf[MAX_PACKET_LENGTH];
795     uint8_t *registers;
796     target_ulong addr, len;
797
798 #ifdef DEBUG_GDB
799     printf("command='%s'\n", line_buf);
800 #endif
801     p = line_buf;
802     ch = *p++;
803     switch(ch) {
804     case '?':
805         /* TODO: Make this return the correct value for user-mode.  */
806         snprintf(buf, sizeof(buf), "T%02xthread:%02x;", GDB_SIGNAL_TRAP,
807                  cpu_index(s->c_cpu));
808         put_packet(s, buf);
809         /* Remove all the breakpoints when this query is issued,
810          * because gdb is doing and initial connect and the state
811          * should be cleaned up.
812          */
813         gdb_breakpoint_remove_all();
814         break;
815     case 'c':
816         if (*p != '\0') {
817             addr = strtoull(p, (char **)&p, 16);
818             gdb_set_cpu_pc(s, addr);
819         }
820         s->signal = 0;
821         gdb_continue(s);
822         return RS_IDLE;
823     case 'C':
824         s->signal = gdb_signal_to_target (strtoul(p, (char **)&p, 16));
825         if (s->signal == -1)
826             s->signal = 0;
827         gdb_continue(s);
828         return RS_IDLE;
829     case 'v':
830         if (strncmp(p, "Cont", 4) == 0) {
831             int res_signal, res_thread;
832
833             p += 4;
834             if (*p == '?') {
835                 put_packet(s, "vCont;c;C;s;S");
836                 break;
837             }
838             res = 0;
839             res_signal = 0;
840             res_thread = 0;
841             while (*p) {
842                 int action, signal;
843
844                 if (*p++ != ';') {
845                     res = 0;
846                     break;
847                 }
848                 action = *p++;
849                 signal = 0;
850                 if (action == 'C' || action == 'S') {
851                     signal = gdb_signal_to_target(strtoul(p, (char **)&p, 16));
852                     if (signal == -1) {
853                         signal = 0;
854                     }
855                 } else if (action != 'c' && action != 's') {
856                     res = 0;
857                     break;
858                 }
859                 thread = 0;
860                 if (*p == ':') {
861                     thread = strtoull(p+1, (char **)&p, 16);
862                 }
863                 action = tolower(action);
864                 if (res == 0 || (res == 'c' && action == 's')) {
865                     res = action;
866                     res_signal = signal;
867                     res_thread = thread;
868                 }
869             }
870             if (res) {
871                 if (res_thread != -1 && res_thread != 0) {
872                     cpu = find_cpu(res_thread);
873                     if (cpu == NULL) {
874                         put_packet(s, "E22");
875                         break;
876                     }
877                     s->c_cpu = cpu;
878                 }
879                 if (res == 's') {
880                     cpu_single_step(s->c_cpu, sstep_flags);
881                 }
882                 s->signal = res_signal;
883                 gdb_continue(s);
884                 return RS_IDLE;
885             }
886             break;
887         } else {
888             goto unknown_command;
889         }
890     case 'k':
891         /* Kill the target */
892         fprintf(stderr, "\nQEMU: Terminated via GDBstub\n");
893         exit(0);
894     case 'D':
895         /* Detach packet */
896         gdb_breakpoint_remove_all();
897         gdb_syscall_mode = GDB_SYS_DISABLED;
898         gdb_continue(s);
899         put_packet(s, "OK");
900         break;
901     case 's':
902         if (*p != '\0') {
903             addr = strtoull(p, (char **)&p, 16);
904             gdb_set_cpu_pc(s, addr);
905         }
906         cpu_single_step(s->c_cpu, sstep_flags);
907         gdb_continue(s);
908         return RS_IDLE;
909     case 'F':
910         {
911             target_ulong ret;
912             target_ulong err;
913
914             ret = strtoull(p, (char **)&p, 16);
915             if (*p == ',') {
916                 p++;
917                 err = strtoull(p, (char **)&p, 16);
918             } else {
919                 err = 0;
920             }
921             if (*p == ',')
922                 p++;
923             type = *p;
924             if (s->current_syscall_cb) {
925                 s->current_syscall_cb(s->c_cpu, ret, err);
926                 s->current_syscall_cb = NULL;
927             }
928             if (type == 'C') {
929                 put_packet(s, "T02");
930             } else {
931                 gdb_continue(s);
932             }
933         }
934         break;
935     case 'g':
936         cpu_synchronize_state(s->g_cpu);
937         len = 0;
938         for (addr = 0; addr < s->g_cpu->gdb_num_g_regs; addr++) {
939             reg_size = gdb_read_register(s->g_cpu, mem_buf + len, addr);
940             len += reg_size;
941         }
942         memtohex(buf, mem_buf, len);
943         put_packet(s, buf);
944         break;
945     case 'G':
946         cpu_synchronize_state(s->g_cpu);
947         registers = mem_buf;
948         len = strlen(p) / 2;
949         hextomem((uint8_t *)registers, p, len);
950         for (addr = 0; addr < s->g_cpu->gdb_num_g_regs && len > 0; addr++) {
951             reg_size = gdb_write_register(s->g_cpu, registers, addr);
952             len -= reg_size;
953             registers += reg_size;
954         }
955         put_packet(s, "OK");
956         break;
957     case 'm':
958         addr = strtoull(p, (char **)&p, 16);
959         if (*p == ',')
960             p++;
961         len = strtoull(p, NULL, 16);
962         if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len, false) != 0) {
963             put_packet (s, "E14");
964         } else {
965             memtohex(buf, mem_buf, len);
966             put_packet(s, buf);
967         }
968         break;
969     case 'M':
970         addr = strtoull(p, (char **)&p, 16);
971         if (*p == ',')
972             p++;
973         len = strtoull(p, (char **)&p, 16);
974         if (*p == ':')
975             p++;
976         hextomem(mem_buf, p, len);
977         if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len,
978                                    true) != 0) {
979             put_packet(s, "E14");
980         } else {
981             put_packet(s, "OK");
982         }
983         break;
984     case 'p':
985         /* Older gdb are really dumb, and don't use 'g' if 'p' is avaialable.
986            This works, but can be very slow.  Anything new enough to
987            understand XML also knows how to use this properly.  */
988         if (!gdb_has_xml)
989             goto unknown_command;
990         addr = strtoull(p, (char **)&p, 16);
991         reg_size = gdb_read_register(s->g_cpu, mem_buf, addr);
992         if (reg_size) {
993             memtohex(buf, mem_buf, reg_size);
994             put_packet(s, buf);
995         } else {
996             put_packet(s, "E14");
997         }
998         break;
999     case 'P':
1000         if (!gdb_has_xml)
1001             goto unknown_command;
1002         addr = strtoull(p, (char **)&p, 16);
1003         if (*p == '=')
1004             p++;
1005         reg_size = strlen(p) / 2;
1006         hextomem(mem_buf, p, reg_size);
1007         gdb_write_register(s->g_cpu, mem_buf, addr);
1008         put_packet(s, "OK");
1009         break;
1010     case 'Z':
1011     case 'z':
1012         type = strtoul(p, (char **)&p, 16);
1013         if (*p == ',')
1014             p++;
1015         addr = strtoull(p, (char **)&p, 16);
1016         if (*p == ',')
1017             p++;
1018         len = strtoull(p, (char **)&p, 16);
1019         if (ch == 'Z')
1020             res = gdb_breakpoint_insert(addr, len, type);
1021         else
1022             res = gdb_breakpoint_remove(addr, len, type);
1023         if (res >= 0)
1024              put_packet(s, "OK");
1025         else if (res == -ENOSYS)
1026             put_packet(s, "");
1027         else
1028             put_packet(s, "E22");
1029         break;
1030     case 'H':
1031         type = *p++;
1032         thread = strtoull(p, (char **)&p, 16);
1033         if (thread == -1 || thread == 0) {
1034             put_packet(s, "OK");
1035             break;
1036         }
1037         cpu = find_cpu(thread);
1038         if (cpu == NULL) {
1039             put_packet(s, "E22");
1040             break;
1041         }
1042         switch (type) {
1043         case 'c':
1044             s->c_cpu = cpu;
1045             put_packet(s, "OK");
1046             break;
1047         case 'g':
1048             s->g_cpu = cpu;
1049             put_packet(s, "OK");
1050             break;
1051         default:
1052              put_packet(s, "E22");
1053              break;
1054         }
1055         break;
1056     case 'T':
1057         thread = strtoull(p, (char **)&p, 16);
1058         cpu = find_cpu(thread);
1059
1060         if (cpu != NULL) {
1061             put_packet(s, "OK");
1062         } else {
1063             put_packet(s, "E22");
1064         }
1065         break;
1066     case 'q':
1067     case 'Q':
1068         /* parse any 'q' packets here */
1069         if (!strcmp(p,"qemu.sstepbits")) {
1070             /* Query Breakpoint bit definitions */
1071             snprintf(buf, sizeof(buf), "ENABLE=%x,NOIRQ=%x,NOTIMER=%x",
1072                      SSTEP_ENABLE,
1073                      SSTEP_NOIRQ,
1074                      SSTEP_NOTIMER);
1075             put_packet(s, buf);
1076             break;
1077         } else if (is_query_packet(p, "qemu.sstep", '=')) {
1078             /* Display or change the sstep_flags */
1079             p += 10;
1080             if (*p != '=') {
1081                 /* Display current setting */
1082                 snprintf(buf, sizeof(buf), "0x%x", sstep_flags);
1083                 put_packet(s, buf);
1084                 break;
1085             }
1086             p++;
1087             type = strtoul(p, (char **)&p, 16);
1088             sstep_flags = type;
1089             put_packet(s, "OK");
1090             break;
1091         } else if (strcmp(p,"C") == 0) {
1092             /* "Current thread" remains vague in the spec, so always return
1093              *  the first CPU (gdb returns the first thread). */
1094             put_packet(s, "QC1");
1095             break;
1096         } else if (strcmp(p,"fThreadInfo") == 0) {
1097             s->query_cpu = first_cpu;
1098             goto report_cpuinfo;
1099         } else if (strcmp(p,"sThreadInfo") == 0) {
1100         report_cpuinfo:
1101             if (s->query_cpu) {
1102                 snprintf(buf, sizeof(buf), "m%x", cpu_index(s->query_cpu));
1103                 put_packet(s, buf);
1104                 s->query_cpu = CPU_NEXT(s->query_cpu);
1105             } else
1106                 put_packet(s, "l");
1107             break;
1108         } else if (strncmp(p,"ThreadExtraInfo,", 16) == 0) {
1109             thread = strtoull(p+16, (char **)&p, 16);
1110             cpu = find_cpu(thread);
1111             if (cpu != NULL) {
1112                 cpu_synchronize_state(cpu);
1113                 len = snprintf((char *)mem_buf, sizeof(mem_buf),
1114                                "CPU#%d [%s]", cpu->cpu_index,
1115                                cpu->halted ? "halted " : "running");
1116                 memtohex(buf, mem_buf, len);
1117                 put_packet(s, buf);
1118             }
1119             break;
1120         }
1121 #ifdef CONFIG_USER_ONLY
1122         else if (strcmp(p, "Offsets") == 0) {
1123             TaskState *ts = s->c_cpu->opaque;
1124
1125             snprintf(buf, sizeof(buf),
1126                      "Text=" TARGET_ABI_FMT_lx ";Data=" TARGET_ABI_FMT_lx
1127                      ";Bss=" TARGET_ABI_FMT_lx,
1128                      ts->info->code_offset,
1129                      ts->info->data_offset,
1130                      ts->info->data_offset);
1131             put_packet(s, buf);
1132             break;
1133         }
1134 #else /* !CONFIG_USER_ONLY */
1135         else if (strncmp(p, "Rcmd,", 5) == 0) {
1136             int len = strlen(p + 5);
1137
1138             if ((len % 2) != 0) {
1139                 put_packet(s, "E01");
1140                 break;
1141             }
1142             hextomem(mem_buf, p + 5, len);
1143             len = len / 2;
1144             mem_buf[len++] = 0;
1145             qemu_chr_be_write(s->mon_chr, mem_buf, len);
1146             put_packet(s, "OK");
1147             break;
1148         }
1149 #endif /* !CONFIG_USER_ONLY */
1150         if (is_query_packet(p, "Supported", ':')) {
1151             snprintf(buf, sizeof(buf), "PacketSize=%x", MAX_PACKET_LENGTH);
1152             cc = CPU_GET_CLASS(first_cpu);
1153             if (cc->gdb_core_xml_file != NULL) {
1154                 pstrcat(buf, sizeof(buf), ";qXfer:features:read+");
1155             }
1156             put_packet(s, buf);
1157             break;
1158         }
1159         if (strncmp(p, "Xfer:features:read:", 19) == 0) {
1160             const char *xml;
1161             target_ulong total_len;
1162
1163             cc = CPU_GET_CLASS(first_cpu);
1164             if (cc->gdb_core_xml_file == NULL) {
1165                 goto unknown_command;
1166             }
1167
1168             gdb_has_xml = true;
1169             p += 19;
1170             xml = get_feature_xml(p, &p, cc);
1171             if (!xml) {
1172                 snprintf(buf, sizeof(buf), "E00");
1173                 put_packet(s, buf);
1174                 break;
1175             }
1176
1177             if (*p == ':')
1178                 p++;
1179             addr = strtoul(p, (char **)&p, 16);
1180             if (*p == ',')
1181                 p++;
1182             len = strtoul(p, (char **)&p, 16);
1183
1184             total_len = strlen(xml);
1185             if (addr > total_len) {
1186                 snprintf(buf, sizeof(buf), "E00");
1187                 put_packet(s, buf);
1188                 break;
1189             }
1190             if (len > (MAX_PACKET_LENGTH - 5) / 2)
1191                 len = (MAX_PACKET_LENGTH - 5) / 2;
1192             if (len < total_len - addr) {
1193                 buf[0] = 'm';
1194                 len = memtox(buf + 1, xml + addr, len);
1195             } else {
1196                 buf[0] = 'l';
1197                 len = memtox(buf + 1, xml + addr, total_len - addr);
1198             }
1199             put_packet_binary(s, buf, len + 1);
1200             break;
1201         }
1202         if (is_query_packet(p, "Attached", ':')) {
1203             put_packet(s, GDB_ATTACHED);
1204             break;
1205         }
1206         /* Unrecognised 'q' command.  */
1207         goto unknown_command;
1208
1209     default:
1210     unknown_command:
1211         /* put empty packet */
1212         buf[0] = '\0';
1213         put_packet(s, buf);
1214         break;
1215     }
1216     return RS_IDLE;
1217 }
1218
1219 void gdb_set_stop_cpu(CPUState *cpu)
1220 {
1221     gdbserver_state->c_cpu = cpu;
1222     gdbserver_state->g_cpu = cpu;
1223 }
1224
1225 #ifndef CONFIG_USER_ONLY
1226 static void gdb_vm_state_change(void *opaque, int running, RunState state)
1227 {
1228     GDBState *s = gdbserver_state;
1229     CPUState *cpu = s->c_cpu;
1230     char buf[256];
1231     const char *type;
1232     int ret;
1233
1234     if (running || s->state == RS_INACTIVE) {
1235         return;
1236     }
1237     /* Is there a GDB syscall waiting to be sent?  */
1238     if (s->current_syscall_cb) {
1239         put_packet(s, s->syscall_buf);
1240         return;
1241     }
1242     switch (state) {
1243     case RUN_STATE_DEBUG:
1244         if (cpu->watchpoint_hit) {
1245             switch (cpu->watchpoint_hit->flags & BP_MEM_ACCESS) {
1246             case BP_MEM_READ:
1247                 type = "r";
1248                 break;
1249             case BP_MEM_ACCESS:
1250                 type = "a";
1251                 break;
1252             default:
1253                 type = "";
1254                 break;
1255             }
1256             snprintf(buf, sizeof(buf),
1257                      "T%02xthread:%02x;%swatch:" TARGET_FMT_lx ";",
1258                      GDB_SIGNAL_TRAP, cpu_index(cpu), type,
1259                      (target_ulong)cpu->watchpoint_hit->vaddr);
1260             cpu->watchpoint_hit = NULL;
1261             goto send_packet;
1262         }
1263         tb_flush(cpu);
1264         ret = GDB_SIGNAL_TRAP;
1265         break;
1266     case RUN_STATE_PAUSED:
1267         ret = GDB_SIGNAL_INT;
1268         break;
1269     case RUN_STATE_SHUTDOWN:
1270         ret = GDB_SIGNAL_QUIT;
1271         break;
1272     case RUN_STATE_IO_ERROR:
1273         ret = GDB_SIGNAL_IO;
1274         break;
1275     case RUN_STATE_WATCHDOG:
1276         ret = GDB_SIGNAL_ALRM;
1277         break;
1278     case RUN_STATE_INTERNAL_ERROR:
1279         ret = GDB_SIGNAL_ABRT;
1280         break;
1281     case RUN_STATE_SAVE_VM:
1282     case RUN_STATE_RESTORE_VM:
1283         return;
1284     case RUN_STATE_FINISH_MIGRATE:
1285         ret = GDB_SIGNAL_XCPU;
1286         break;
1287     default:
1288         ret = GDB_SIGNAL_UNKNOWN;
1289         break;
1290     }
1291     snprintf(buf, sizeof(buf), "T%02xthread:%02x;", ret, cpu_index(cpu));
1292
1293 send_packet:
1294     put_packet(s, buf);
1295
1296     /* disable single step if it was enabled */
1297     cpu_single_step(cpu, 0);
1298 }
1299 #endif
1300
1301 /* Send a gdb syscall request.
1302    This accepts limited printf-style format specifiers, specifically:
1303     %x  - target_ulong argument printed in hex.
1304     %lx - 64-bit argument printed in hex.
1305     %s  - string pointer (target_ulong) and length (int) pair.  */
1306 void gdb_do_syscall(gdb_syscall_complete_cb cb, const char *fmt, ...)
1307 {
1308     va_list va;
1309     char *p;
1310     char *p_end;
1311     target_ulong addr;
1312     uint64_t i64;
1313     GDBState *s;
1314
1315     s = gdbserver_state;
1316     if (!s)
1317         return;
1318     s->current_syscall_cb = cb;
1319 #ifndef CONFIG_USER_ONLY
1320     vm_stop(RUN_STATE_DEBUG);
1321 #endif
1322     va_start(va, fmt);
1323     p = s->syscall_buf;
1324     p_end = &s->syscall_buf[sizeof(s->syscall_buf)];
1325     *(p++) = 'F';
1326     while (*fmt) {
1327         if (*fmt == '%') {
1328             fmt++;
1329             switch (*fmt++) {
1330             case 'x':
1331                 addr = va_arg(va, target_ulong);
1332                 p += snprintf(p, p_end - p, TARGET_FMT_lx, addr);
1333                 break;
1334             case 'l':
1335                 if (*(fmt++) != 'x')
1336                     goto bad_format;
1337                 i64 = va_arg(va, uint64_t);
1338                 p += snprintf(p, p_end - p, "%" PRIx64, i64);
1339                 break;
1340             case 's':
1341                 addr = va_arg(va, target_ulong);
1342                 p += snprintf(p, p_end - p, TARGET_FMT_lx "/%x",
1343                               addr, va_arg(va, int));
1344                 break;
1345             default:
1346             bad_format:
1347                 fprintf(stderr, "gdbstub: Bad syscall format string '%s'\n",
1348                         fmt - 1);
1349                 break;
1350             }
1351         } else {
1352             *(p++) = *(fmt++);
1353         }
1354     }
1355     *p = 0;
1356     va_end(va);
1357 #ifdef CONFIG_USER_ONLY
1358     put_packet(s, s->syscall_buf);
1359     gdb_handlesig(s->c_cpu, 0);
1360 #else
1361     /* In this case wait to send the syscall packet until notification that
1362        the CPU has stopped.  This must be done because if the packet is sent
1363        now the reply from the syscall request could be received while the CPU
1364        is still in the running state, which can cause packets to be dropped
1365        and state transition 'T' packets to be sent while the syscall is still
1366        being processed.  */
1367     cpu_exit(s->c_cpu);
1368 #endif
1369 }
1370
1371 static void gdb_read_byte(GDBState *s, int ch)
1372 {
1373     int i, csum;
1374     uint8_t reply;
1375
1376 #ifndef CONFIG_USER_ONLY
1377     if (s->last_packet_len) {
1378         /* Waiting for a response to the last packet.  If we see the start
1379            of a new command then abandon the previous response.  */
1380         if (ch == '-') {
1381 #ifdef DEBUG_GDB
1382             printf("Got NACK, retransmitting\n");
1383 #endif
1384             put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
1385         }
1386 #ifdef DEBUG_GDB
1387         else if (ch == '+')
1388             printf("Got ACK\n");
1389         else
1390             printf("Got '%c' when expecting ACK/NACK\n", ch);
1391 #endif
1392         if (ch == '+' || ch == '$')
1393             s->last_packet_len = 0;
1394         if (ch != '$')
1395             return;
1396     }
1397     if (runstate_is_running()) {
1398         /* when the CPU is running, we cannot do anything except stop
1399            it when receiving a char */
1400         vm_stop(RUN_STATE_PAUSED);
1401     } else
1402 #endif
1403     {
1404         switch(s->state) {
1405         case RS_IDLE:
1406             if (ch == '$') {
1407                 s->line_buf_index = 0;
1408                 s->state = RS_GETLINE;
1409             }
1410             break;
1411         case RS_GETLINE:
1412             if (ch == '#') {
1413             s->state = RS_CHKSUM1;
1414             } else if (s->line_buf_index >= sizeof(s->line_buf) - 1) {
1415                 s->state = RS_IDLE;
1416             } else {
1417             s->line_buf[s->line_buf_index++] = ch;
1418             }
1419             break;
1420         case RS_CHKSUM1:
1421             s->line_buf[s->line_buf_index] = '\0';
1422             s->line_csum = fromhex(ch) << 4;
1423             s->state = RS_CHKSUM2;
1424             break;
1425         case RS_CHKSUM2:
1426             s->line_csum |= fromhex(ch);
1427             csum = 0;
1428             for(i = 0; i < s->line_buf_index; i++) {
1429                 csum += s->line_buf[i];
1430             }
1431             if (s->line_csum != (csum & 0xff)) {
1432                 reply = '-';
1433                 put_buffer(s, &reply, 1);
1434                 s->state = RS_IDLE;
1435             } else {
1436                 reply = '+';
1437                 put_buffer(s, &reply, 1);
1438                 s->state = gdb_handle_packet(s, s->line_buf);
1439             }
1440             break;
1441         default:
1442             abort();
1443         }
1444     }
1445 }
1446
1447 /* Tell the remote gdb that the process has exited.  */
1448 void gdb_exit(CPUArchState *env, int code)
1449 {
1450   GDBState *s;
1451   char buf[4];
1452
1453   s = gdbserver_state;
1454   if (!s) {
1455       return;
1456   }
1457 #ifdef CONFIG_USER_ONLY
1458   if (gdbserver_fd < 0 || s->fd < 0) {
1459       return;
1460   }
1461 #else
1462   if (!s->chr) {
1463       return;
1464   }
1465 #endif
1466
1467   snprintf(buf, sizeof(buf), "W%02x", (uint8_t)code);
1468   put_packet(s, buf);
1469
1470 #ifndef CONFIG_USER_ONLY
1471   qemu_chr_delete(s->chr);
1472 #endif
1473 }
1474
1475 #ifdef CONFIG_USER_ONLY
1476 int
1477 gdb_queuesig (void)
1478 {
1479     GDBState *s;
1480
1481     s = gdbserver_state;
1482
1483     if (gdbserver_fd < 0 || s->fd < 0)
1484         return 0;
1485     else
1486         return 1;
1487 }
1488
1489 int
1490 gdb_handlesig(CPUState *cpu, int sig)
1491 {
1492     GDBState *s;
1493     char buf[256];
1494     int n;
1495
1496     s = gdbserver_state;
1497     if (gdbserver_fd < 0 || s->fd < 0) {
1498         return sig;
1499     }
1500
1501     /* disable single step if it was enabled */
1502     cpu_single_step(cpu, 0);
1503     tb_flush(cpu);
1504
1505     if (sig != 0) {
1506         snprintf(buf, sizeof(buf), "S%02x", target_signal_to_gdb(sig));
1507         put_packet(s, buf);
1508     }
1509     /* put_packet() might have detected that the peer terminated the
1510        connection.  */
1511     if (s->fd < 0) {
1512         return sig;
1513     }
1514
1515     sig = 0;
1516     s->state = RS_IDLE;
1517     s->running_state = 0;
1518     while (s->running_state == 0) {
1519         n = read(s->fd, buf, 256);
1520         if (n > 0) {
1521             int i;
1522
1523             for (i = 0; i < n; i++) {
1524                 gdb_read_byte(s, buf[i]);
1525             }
1526         } else if (n == 0 || errno != EAGAIN) {
1527             /* XXX: Connection closed.  Should probably wait for another
1528                connection before continuing.  */
1529             return sig;
1530         }
1531     }
1532     sig = s->signal;
1533     s->signal = 0;
1534     return sig;
1535 }
1536
1537 /* Tell the remote gdb that the process has exited due to SIG.  */
1538 void gdb_signalled(CPUArchState *env, int sig)
1539 {
1540     GDBState *s;
1541     char buf[4];
1542
1543     s = gdbserver_state;
1544     if (gdbserver_fd < 0 || s->fd < 0) {
1545         return;
1546     }
1547
1548     snprintf(buf, sizeof(buf), "X%02x", target_signal_to_gdb(sig));
1549     put_packet(s, buf);
1550 }
1551
1552 static void gdb_accept(void)
1553 {
1554     GDBState *s;
1555     struct sockaddr_in sockaddr;
1556     socklen_t len;
1557     int fd;
1558
1559     for(;;) {
1560         len = sizeof(sockaddr);
1561         fd = accept(gdbserver_fd, (struct sockaddr *)&sockaddr, &len);
1562         if (fd < 0 && errno != EINTR) {
1563             perror("accept");
1564             return;
1565         } else if (fd >= 0) {
1566 #ifndef _WIN32
1567             fcntl(fd, F_SETFD, FD_CLOEXEC);
1568 #endif
1569             break;
1570         }
1571     }
1572
1573     /* set short latency */
1574     socket_set_nodelay(fd);
1575
1576     s = g_malloc0(sizeof(GDBState));
1577     s->c_cpu = first_cpu;
1578     s->g_cpu = first_cpu;
1579     s->fd = fd;
1580     gdb_has_xml = false;
1581
1582     gdbserver_state = s;
1583
1584     fcntl(fd, F_SETFL, O_NONBLOCK);
1585 }
1586
1587 static int gdbserver_open(int port)
1588 {
1589     struct sockaddr_in sockaddr;
1590     int fd, ret;
1591
1592     fd = socket(PF_INET, SOCK_STREAM, 0);
1593     if (fd < 0) {
1594         perror("socket");
1595         return -1;
1596     }
1597 #ifndef _WIN32
1598     fcntl(fd, F_SETFD, FD_CLOEXEC);
1599 #endif
1600
1601     socket_set_fast_reuse(fd);
1602
1603     sockaddr.sin_family = AF_INET;
1604     sockaddr.sin_port = htons(port);
1605     sockaddr.sin_addr.s_addr = 0;
1606     ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
1607     if (ret < 0) {
1608         perror("bind");
1609         close(fd);
1610         return -1;
1611     }
1612     ret = listen(fd, 0);
1613     if (ret < 0) {
1614         perror("listen");
1615         close(fd);
1616         return -1;
1617     }
1618     return fd;
1619 }
1620
1621 int gdbserver_start(int port)
1622 {
1623     gdbserver_fd = gdbserver_open(port);
1624     if (gdbserver_fd < 0)
1625         return -1;
1626     /* accept connections */
1627     gdb_accept();
1628     return 0;
1629 }
1630
1631 /* Disable gdb stub for child processes.  */
1632 void gdbserver_fork(CPUState *cpu)
1633 {
1634     GDBState *s = gdbserver_state;
1635
1636     if (gdbserver_fd < 0 || s->fd < 0) {
1637         return;
1638     }
1639     close(s->fd);
1640     s->fd = -1;
1641     cpu_breakpoint_remove_all(cpu, BP_GDB);
1642     cpu_watchpoint_remove_all(cpu, BP_GDB);
1643 }
1644 #else
1645 static int gdb_chr_can_receive(void *opaque)
1646 {
1647   /* We can handle an arbitrarily large amount of data.
1648    Pick the maximum packet size, which is as good as anything.  */
1649   return MAX_PACKET_LENGTH;
1650 }
1651
1652 static void gdb_chr_receive(void *opaque, const uint8_t *buf, int size)
1653 {
1654     int i;
1655
1656     for (i = 0; i < size; i++) {
1657         gdb_read_byte(gdbserver_state, buf[i]);
1658     }
1659 }
1660
1661 static void gdb_chr_event(void *opaque, int event)
1662 {
1663     switch (event) {
1664     case CHR_EVENT_OPENED:
1665         vm_stop(RUN_STATE_PAUSED);
1666         gdb_has_xml = false;
1667         break;
1668     default:
1669         break;
1670     }
1671 }
1672
1673 static void gdb_monitor_output(GDBState *s, const char *msg, int len)
1674 {
1675     char buf[MAX_PACKET_LENGTH];
1676
1677     buf[0] = 'O';
1678     if (len > (MAX_PACKET_LENGTH/2) - 1)
1679         len = (MAX_PACKET_LENGTH/2) - 1;
1680     memtohex(buf + 1, (uint8_t *)msg, len);
1681     put_packet(s, buf);
1682 }
1683
1684 static int gdb_monitor_write(CharDriverState *chr, const uint8_t *buf, int len)
1685 {
1686     const char *p = (const char *)buf;
1687     int max_sz;
1688
1689     max_sz = (sizeof(gdbserver_state->last_packet) - 2) / 2;
1690     for (;;) {
1691         if (len <= max_sz) {
1692             gdb_monitor_output(gdbserver_state, p, len);
1693             break;
1694         }
1695         gdb_monitor_output(gdbserver_state, p, max_sz);
1696         p += max_sz;
1697         len -= max_sz;
1698     }
1699     return len;
1700 }
1701
1702 #ifndef _WIN32
1703 static void gdb_sigterm_handler(int signal)
1704 {
1705     if (runstate_is_running()) {
1706         vm_stop(RUN_STATE_PAUSED);
1707     }
1708 }
1709 #endif
1710
1711 int gdbserver_start(const char *device)
1712 {
1713     GDBState *s;
1714     char gdbstub_device_name[128];
1715     CharDriverState *chr = NULL;
1716     CharDriverState *mon_chr;
1717
1718     if (!device)
1719         return -1;
1720     if (strcmp(device, "none") != 0) {
1721         if (strstart(device, "tcp:", NULL)) {
1722             /* enforce required TCP attributes */
1723             snprintf(gdbstub_device_name, sizeof(gdbstub_device_name),
1724                      "%s,nowait,nodelay,server", device);
1725             device = gdbstub_device_name;
1726         }
1727 #ifndef _WIN32
1728         else if (strcmp(device, "stdio") == 0) {
1729             struct sigaction act;
1730
1731             memset(&act, 0, sizeof(act));
1732             act.sa_handler = gdb_sigterm_handler;
1733             sigaction(SIGINT, &act, NULL);
1734         }
1735 #endif
1736         chr = qemu_chr_new("gdb", device, NULL);
1737         if (!chr)
1738             return -1;
1739
1740         qemu_chr_fe_claim_no_fail(chr);
1741         qemu_chr_add_handlers(chr, gdb_chr_can_receive, gdb_chr_receive,
1742                               gdb_chr_event, NULL);
1743     }
1744
1745     s = gdbserver_state;
1746     if (!s) {
1747         s = g_malloc0(sizeof(GDBState));
1748         gdbserver_state = s;
1749
1750         qemu_add_vm_change_state_handler(gdb_vm_state_change, NULL);
1751
1752         /* Initialize a monitor terminal for gdb */
1753         mon_chr = qemu_chr_alloc();
1754         mon_chr->chr_write = gdb_monitor_write;
1755         monitor_init(mon_chr, 0);
1756     } else {
1757         if (s->chr)
1758             qemu_chr_delete(s->chr);
1759         mon_chr = s->mon_chr;
1760         memset(s, 0, sizeof(GDBState));
1761     }
1762     s->c_cpu = first_cpu;
1763     s->g_cpu = first_cpu;
1764     s->chr = chr;
1765     s->state = chr ? RS_IDLE : RS_INACTIVE;
1766     s->mon_chr = mon_chr;
1767     s->current_syscall_cb = NULL;
1768
1769     return 0;
1770 }
1771 #endif
This page took 0.122598 seconds and 4 git commands to generate.