]> Git Repo - qemu.git/blob - gdbstub.c
slirp: add unregister_poll_fd() callback
[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 "qemu/osdep.h"
20 #include "qapi/error.h"
21 #include "qemu/error-report.h"
22 #include "qemu/cutils.h"
23 #include "trace-root.h"
24 #ifdef CONFIG_USER_ONLY
25 #include "qemu.h"
26 #else
27 #include "monitor/monitor.h"
28 #include "chardev/char.h"
29 #include "chardev/char-fe.h"
30 #include "sysemu/sysemu.h"
31 #include "exec/gdbstub.h"
32 #include "hw/cpu/cluster.h"
33 #endif
34
35 #define MAX_PACKET_LENGTH 4096
36
37 #include "qemu/sockets.h"
38 #include "sysemu/hw_accel.h"
39 #include "sysemu/kvm.h"
40 #include "exec/semihost.h"
41 #include "exec/exec-all.h"
42
43 #ifdef CONFIG_USER_ONLY
44 #define GDB_ATTACHED "0"
45 #else
46 #define GDB_ATTACHED "1"
47 #endif
48
49 static inline int target_memory_rw_debug(CPUState *cpu, target_ulong addr,
50                                          uint8_t *buf, int len, bool is_write)
51 {
52     CPUClass *cc = CPU_GET_CLASS(cpu);
53
54     if (cc->memory_rw_debug) {
55         return cc->memory_rw_debug(cpu, addr, buf, len, is_write);
56     }
57     return cpu_memory_rw_debug(cpu, addr, buf, len, is_write);
58 }
59
60 /* Return the GDB index for a given vCPU state.
61  *
62  * For user mode this is simply the thread id. In system mode GDB
63  * numbers CPUs from 1 as 0 is reserved as an "any cpu" index.
64  */
65 static inline int cpu_gdb_index(CPUState *cpu)
66 {
67 #if defined(CONFIG_USER_ONLY)
68     TaskState *ts = (TaskState *) cpu->opaque;
69     return ts->ts_tid;
70 #else
71     return cpu->cpu_index + 1;
72 #endif
73 }
74
75 enum {
76     GDB_SIGNAL_0 = 0,
77     GDB_SIGNAL_INT = 2,
78     GDB_SIGNAL_QUIT = 3,
79     GDB_SIGNAL_TRAP = 5,
80     GDB_SIGNAL_ABRT = 6,
81     GDB_SIGNAL_ALRM = 14,
82     GDB_SIGNAL_IO = 23,
83     GDB_SIGNAL_XCPU = 24,
84     GDB_SIGNAL_UNKNOWN = 143
85 };
86
87 #ifdef CONFIG_USER_ONLY
88
89 /* Map target signal numbers to GDB protocol signal numbers and vice
90  * versa.  For user emulation's currently supported systems, we can
91  * assume most signals are defined.
92  */
93
94 static int gdb_signal_table[] = {
95     0,
96     TARGET_SIGHUP,
97     TARGET_SIGINT,
98     TARGET_SIGQUIT,
99     TARGET_SIGILL,
100     TARGET_SIGTRAP,
101     TARGET_SIGABRT,
102     -1, /* SIGEMT */
103     TARGET_SIGFPE,
104     TARGET_SIGKILL,
105     TARGET_SIGBUS,
106     TARGET_SIGSEGV,
107     TARGET_SIGSYS,
108     TARGET_SIGPIPE,
109     TARGET_SIGALRM,
110     TARGET_SIGTERM,
111     TARGET_SIGURG,
112     TARGET_SIGSTOP,
113     TARGET_SIGTSTP,
114     TARGET_SIGCONT,
115     TARGET_SIGCHLD,
116     TARGET_SIGTTIN,
117     TARGET_SIGTTOU,
118     TARGET_SIGIO,
119     TARGET_SIGXCPU,
120     TARGET_SIGXFSZ,
121     TARGET_SIGVTALRM,
122     TARGET_SIGPROF,
123     TARGET_SIGWINCH,
124     -1, /* SIGLOST */
125     TARGET_SIGUSR1,
126     TARGET_SIGUSR2,
127 #ifdef TARGET_SIGPWR
128     TARGET_SIGPWR,
129 #else
130     -1,
131 #endif
132     -1, /* SIGPOLL */
133     -1,
134     -1,
135     -1,
136     -1,
137     -1,
138     -1,
139     -1,
140     -1,
141     -1,
142     -1,
143     -1,
144 #ifdef __SIGRTMIN
145     __SIGRTMIN + 1,
146     __SIGRTMIN + 2,
147     __SIGRTMIN + 3,
148     __SIGRTMIN + 4,
149     __SIGRTMIN + 5,
150     __SIGRTMIN + 6,
151     __SIGRTMIN + 7,
152     __SIGRTMIN + 8,
153     __SIGRTMIN + 9,
154     __SIGRTMIN + 10,
155     __SIGRTMIN + 11,
156     __SIGRTMIN + 12,
157     __SIGRTMIN + 13,
158     __SIGRTMIN + 14,
159     __SIGRTMIN + 15,
160     __SIGRTMIN + 16,
161     __SIGRTMIN + 17,
162     __SIGRTMIN + 18,
163     __SIGRTMIN + 19,
164     __SIGRTMIN + 20,
165     __SIGRTMIN + 21,
166     __SIGRTMIN + 22,
167     __SIGRTMIN + 23,
168     __SIGRTMIN + 24,
169     __SIGRTMIN + 25,
170     __SIGRTMIN + 26,
171     __SIGRTMIN + 27,
172     __SIGRTMIN + 28,
173     __SIGRTMIN + 29,
174     __SIGRTMIN + 30,
175     __SIGRTMIN + 31,
176     -1, /* SIGCANCEL */
177     __SIGRTMIN,
178     __SIGRTMIN + 32,
179     __SIGRTMIN + 33,
180     __SIGRTMIN + 34,
181     __SIGRTMIN + 35,
182     __SIGRTMIN + 36,
183     __SIGRTMIN + 37,
184     __SIGRTMIN + 38,
185     __SIGRTMIN + 39,
186     __SIGRTMIN + 40,
187     __SIGRTMIN + 41,
188     __SIGRTMIN + 42,
189     __SIGRTMIN + 43,
190     __SIGRTMIN + 44,
191     __SIGRTMIN + 45,
192     __SIGRTMIN + 46,
193     __SIGRTMIN + 47,
194     __SIGRTMIN + 48,
195     __SIGRTMIN + 49,
196     __SIGRTMIN + 50,
197     __SIGRTMIN + 51,
198     __SIGRTMIN + 52,
199     __SIGRTMIN + 53,
200     __SIGRTMIN + 54,
201     __SIGRTMIN + 55,
202     __SIGRTMIN + 56,
203     __SIGRTMIN + 57,
204     __SIGRTMIN + 58,
205     __SIGRTMIN + 59,
206     __SIGRTMIN + 60,
207     __SIGRTMIN + 61,
208     __SIGRTMIN + 62,
209     __SIGRTMIN + 63,
210     __SIGRTMIN + 64,
211     __SIGRTMIN + 65,
212     __SIGRTMIN + 66,
213     __SIGRTMIN + 67,
214     __SIGRTMIN + 68,
215     __SIGRTMIN + 69,
216     __SIGRTMIN + 70,
217     __SIGRTMIN + 71,
218     __SIGRTMIN + 72,
219     __SIGRTMIN + 73,
220     __SIGRTMIN + 74,
221     __SIGRTMIN + 75,
222     __SIGRTMIN + 76,
223     __SIGRTMIN + 77,
224     __SIGRTMIN + 78,
225     __SIGRTMIN + 79,
226     __SIGRTMIN + 80,
227     __SIGRTMIN + 81,
228     __SIGRTMIN + 82,
229     __SIGRTMIN + 83,
230     __SIGRTMIN + 84,
231     __SIGRTMIN + 85,
232     __SIGRTMIN + 86,
233     __SIGRTMIN + 87,
234     __SIGRTMIN + 88,
235     __SIGRTMIN + 89,
236     __SIGRTMIN + 90,
237     __SIGRTMIN + 91,
238     __SIGRTMIN + 92,
239     __SIGRTMIN + 93,
240     __SIGRTMIN + 94,
241     __SIGRTMIN + 95,
242     -1, /* SIGINFO */
243     -1, /* UNKNOWN */
244     -1, /* DEFAULT */
245     -1,
246     -1,
247     -1,
248     -1,
249     -1,
250     -1
251 #endif
252 };
253 #else
254 /* In system mode we only need SIGINT and SIGTRAP; other signals
255    are not yet supported.  */
256
257 enum {
258     TARGET_SIGINT = 2,
259     TARGET_SIGTRAP = 5
260 };
261
262 static int gdb_signal_table[] = {
263     -1,
264     -1,
265     TARGET_SIGINT,
266     -1,
267     -1,
268     TARGET_SIGTRAP
269 };
270 #endif
271
272 #ifdef CONFIG_USER_ONLY
273 static int target_signal_to_gdb (int sig)
274 {
275     int i;
276     for (i = 0; i < ARRAY_SIZE (gdb_signal_table); i++)
277         if (gdb_signal_table[i] == sig)
278             return i;
279     return GDB_SIGNAL_UNKNOWN;
280 }
281 #endif
282
283 static int gdb_signal_to_target (int sig)
284 {
285     if (sig < ARRAY_SIZE (gdb_signal_table))
286         return gdb_signal_table[sig];
287     else
288         return -1;
289 }
290
291 typedef struct GDBRegisterState {
292     int base_reg;
293     int num_regs;
294     gdb_reg_cb get_reg;
295     gdb_reg_cb set_reg;
296     const char *xml;
297     struct GDBRegisterState *next;
298 } GDBRegisterState;
299
300 typedef struct GDBProcess {
301     uint32_t pid;
302     bool attached;
303
304     char target_xml[1024];
305 } GDBProcess;
306
307 enum RSState {
308     RS_INACTIVE,
309     RS_IDLE,
310     RS_GETLINE,
311     RS_GETLINE_ESC,
312     RS_GETLINE_RLE,
313     RS_CHKSUM1,
314     RS_CHKSUM2,
315 };
316 typedef struct GDBState {
317     CPUState *c_cpu; /* current CPU for step/continue ops */
318     CPUState *g_cpu; /* current CPU for other ops */
319     CPUState *query_cpu; /* for q{f|s}ThreadInfo */
320     enum RSState state; /* parsing state */
321     char line_buf[MAX_PACKET_LENGTH];
322     int line_buf_index;
323     int line_sum; /* running checksum */
324     int line_csum; /* checksum at the end of the packet */
325     uint8_t last_packet[MAX_PACKET_LENGTH + 4];
326     int last_packet_len;
327     int signal;
328 #ifdef CONFIG_USER_ONLY
329     int fd;
330     int running_state;
331 #else
332     CharBackend chr;
333     Chardev *mon_chr;
334 #endif
335     bool multiprocess;
336     GDBProcess *processes;
337     int process_num;
338     char syscall_buf[256];
339     gdb_syscall_complete_cb current_syscall_cb;
340 } GDBState;
341
342 /* By default use no IRQs and no timers while single stepping so as to
343  * make single stepping like an ICE HW step.
344  */
345 static int sstep_flags = SSTEP_ENABLE|SSTEP_NOIRQ|SSTEP_NOTIMER;
346
347 static GDBState *gdbserver_state;
348
349 bool gdb_has_xml;
350
351 #ifdef CONFIG_USER_ONLY
352 /* XXX: This is not thread safe.  Do we care?  */
353 static int gdbserver_fd = -1;
354
355 static int get_char(GDBState *s)
356 {
357     uint8_t ch;
358     int ret;
359
360     for(;;) {
361         ret = qemu_recv(s->fd, &ch, 1, 0);
362         if (ret < 0) {
363             if (errno == ECONNRESET)
364                 s->fd = -1;
365             if (errno != EINTR)
366                 return -1;
367         } else if (ret == 0) {
368             close(s->fd);
369             s->fd = -1;
370             return -1;
371         } else {
372             break;
373         }
374     }
375     return ch;
376 }
377 #endif
378
379 static enum {
380     GDB_SYS_UNKNOWN,
381     GDB_SYS_ENABLED,
382     GDB_SYS_DISABLED,
383 } gdb_syscall_mode;
384
385 /* Decide if either remote gdb syscalls or native file IO should be used. */
386 int use_gdb_syscalls(void)
387 {
388     SemihostingTarget target = semihosting_get_target();
389     if (target == SEMIHOSTING_TARGET_NATIVE) {
390         /* -semihosting-config target=native */
391         return false;
392     } else if (target == SEMIHOSTING_TARGET_GDB) {
393         /* -semihosting-config target=gdb */
394         return true;
395     }
396
397     /* -semihosting-config target=auto */
398     /* On the first call check if gdb is connected and remember. */
399     if (gdb_syscall_mode == GDB_SYS_UNKNOWN) {
400         gdb_syscall_mode = (gdbserver_state ? GDB_SYS_ENABLED
401                                             : GDB_SYS_DISABLED);
402     }
403     return gdb_syscall_mode == GDB_SYS_ENABLED;
404 }
405
406 /* Resume execution.  */
407 static inline void gdb_continue(GDBState *s)
408 {
409
410 #ifdef CONFIG_USER_ONLY
411     s->running_state = 1;
412     trace_gdbstub_op_continue();
413 #else
414     if (!runstate_needs_reset()) {
415         trace_gdbstub_op_continue();
416         vm_start();
417     }
418 #endif
419 }
420
421 /*
422  * Resume execution, per CPU actions. For user-mode emulation it's
423  * equivalent to gdb_continue.
424  */
425 static int gdb_continue_partial(GDBState *s, char *newstates)
426 {
427     CPUState *cpu;
428     int res = 0;
429 #ifdef CONFIG_USER_ONLY
430     /*
431      * This is not exactly accurate, but it's an improvement compared to the
432      * previous situation, where only one CPU would be single-stepped.
433      */
434     CPU_FOREACH(cpu) {
435         if (newstates[cpu->cpu_index] == 's') {
436             trace_gdbstub_op_stepping(cpu->cpu_index);
437             cpu_single_step(cpu, sstep_flags);
438         }
439     }
440     s->running_state = 1;
441 #else
442     int flag = 0;
443
444     if (!runstate_needs_reset()) {
445         if (vm_prepare_start()) {
446             return 0;
447         }
448
449         CPU_FOREACH(cpu) {
450             switch (newstates[cpu->cpu_index]) {
451             case 0:
452             case 1:
453                 break; /* nothing to do here */
454             case 's':
455                 trace_gdbstub_op_stepping(cpu->cpu_index);
456                 cpu_single_step(cpu, sstep_flags);
457                 cpu_resume(cpu);
458                 flag = 1;
459                 break;
460             case 'c':
461                 trace_gdbstub_op_continue_cpu(cpu->cpu_index);
462                 cpu_resume(cpu);
463                 flag = 1;
464                 break;
465             default:
466                 res = -1;
467                 break;
468             }
469         }
470     }
471     if (flag) {
472         qemu_clock_enable(QEMU_CLOCK_VIRTUAL, true);
473     }
474 #endif
475     return res;
476 }
477
478 static void put_buffer(GDBState *s, const uint8_t *buf, int len)
479 {
480 #ifdef CONFIG_USER_ONLY
481     int ret;
482
483     while (len > 0) {
484         ret = send(s->fd, buf, len, 0);
485         if (ret < 0) {
486             if (errno != EINTR)
487                 return;
488         } else {
489             buf += ret;
490             len -= ret;
491         }
492     }
493 #else
494     /* XXX this blocks entire thread. Rewrite to use
495      * qemu_chr_fe_write and background I/O callbacks */
496     qemu_chr_fe_write_all(&s->chr, buf, len);
497 #endif
498 }
499
500 static inline int fromhex(int v)
501 {
502     if (v >= '0' && v <= '9')
503         return v - '0';
504     else if (v >= 'A' && v <= 'F')
505         return v - 'A' + 10;
506     else if (v >= 'a' && v <= 'f')
507         return v - 'a' + 10;
508     else
509         return 0;
510 }
511
512 static inline int tohex(int v)
513 {
514     if (v < 10)
515         return v + '0';
516     else
517         return v - 10 + 'a';
518 }
519
520 /* writes 2*len+1 bytes in buf */
521 static void memtohex(char *buf, const uint8_t *mem, int len)
522 {
523     int i, c;
524     char *q;
525     q = buf;
526     for(i = 0; i < len; i++) {
527         c = mem[i];
528         *q++ = tohex(c >> 4);
529         *q++ = tohex(c & 0xf);
530     }
531     *q = '\0';
532 }
533
534 static void hextomem(uint8_t *mem, const char *buf, int len)
535 {
536     int i;
537
538     for(i = 0; i < len; i++) {
539         mem[i] = (fromhex(buf[0]) << 4) | fromhex(buf[1]);
540         buf += 2;
541     }
542 }
543
544 static void hexdump(const char *buf, int len,
545                     void (*trace_fn)(size_t ofs, char const *text))
546 {
547     char line_buffer[3 * 16 + 4 + 16 + 1];
548
549     size_t i;
550     for (i = 0; i < len || (i & 0xF); ++i) {
551         size_t byte_ofs = i & 15;
552
553         if (byte_ofs == 0) {
554             memset(line_buffer, ' ', 3 * 16 + 4 + 16);
555             line_buffer[3 * 16 + 4 + 16] = 0;
556         }
557
558         size_t col_group = (i >> 2) & 3;
559         size_t hex_col = byte_ofs * 3 + col_group;
560         size_t txt_col = 3 * 16 + 4 + byte_ofs;
561
562         if (i < len) {
563             char value = buf[i];
564
565             line_buffer[hex_col + 0] = tohex((value >> 4) & 0xF);
566             line_buffer[hex_col + 1] = tohex((value >> 0) & 0xF);
567             line_buffer[txt_col + 0] = (value >= ' ' && value < 127)
568                     ? value
569                     : '.';
570         }
571
572         if (byte_ofs == 0xF)
573             trace_fn(i & -16, line_buffer);
574     }
575 }
576
577 /* return -1 if error, 0 if OK */
578 static int put_packet_binary(GDBState *s, const char *buf, int len, bool dump)
579 {
580     int csum, i;
581     uint8_t *p;
582
583     if (dump && trace_event_get_state_backends(TRACE_GDBSTUB_IO_BINARYREPLY)) {
584         hexdump(buf, len, trace_gdbstub_io_binaryreply);
585     }
586
587     for(;;) {
588         p = s->last_packet;
589         *(p++) = '$';
590         memcpy(p, buf, len);
591         p += len;
592         csum = 0;
593         for(i = 0; i < len; i++) {
594             csum += buf[i];
595         }
596         *(p++) = '#';
597         *(p++) = tohex((csum >> 4) & 0xf);
598         *(p++) = tohex((csum) & 0xf);
599
600         s->last_packet_len = p - s->last_packet;
601         put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
602
603 #ifdef CONFIG_USER_ONLY
604         i = get_char(s);
605         if (i < 0)
606             return -1;
607         if (i == '+')
608             break;
609 #else
610         break;
611 #endif
612     }
613     return 0;
614 }
615
616 /* return -1 if error, 0 if OK */
617 static int put_packet(GDBState *s, const char *buf)
618 {
619     trace_gdbstub_io_reply(buf);
620
621     return put_packet_binary(s, buf, strlen(buf), false);
622 }
623
624 /* Encode data using the encoding for 'x' packets.  */
625 static int memtox(char *buf, const char *mem, int len)
626 {
627     char *p = buf;
628     char c;
629
630     while (len--) {
631         c = *(mem++);
632         switch (c) {
633         case '#': case '$': case '*': case '}':
634             *(p++) = '}';
635             *(p++) = c ^ 0x20;
636             break;
637         default:
638             *(p++) = c;
639             break;
640         }
641     }
642     return p - buf;
643 }
644
645 static uint32_t gdb_get_cpu_pid(const GDBState *s, CPUState *cpu)
646 {
647     /* TODO: In user mode, we should use the task state PID */
648     if (cpu->cluster_index == UNASSIGNED_CLUSTER_INDEX) {
649         /* Return the default process' PID */
650         return s->processes[s->process_num - 1].pid;
651     }
652     return cpu->cluster_index + 1;
653 }
654
655 static GDBProcess *gdb_get_process(const GDBState *s, uint32_t pid)
656 {
657     int i;
658
659     if (!pid) {
660         /* 0 means any process, we take the first one */
661         return &s->processes[0];
662     }
663
664     for (i = 0; i < s->process_num; i++) {
665         if (s->processes[i].pid == pid) {
666             return &s->processes[i];
667         }
668     }
669
670     return NULL;
671 }
672
673 static GDBProcess *gdb_get_cpu_process(const GDBState *s, CPUState *cpu)
674 {
675     return gdb_get_process(s, gdb_get_cpu_pid(s, cpu));
676 }
677
678 static CPUState *find_cpu(uint32_t thread_id)
679 {
680     CPUState *cpu;
681
682     CPU_FOREACH(cpu) {
683         if (cpu_gdb_index(cpu) == thread_id) {
684             return cpu;
685         }
686     }
687
688     return NULL;
689 }
690
691 static CPUState *get_first_cpu_in_process(const GDBState *s,
692                                           GDBProcess *process)
693 {
694     CPUState *cpu;
695
696     CPU_FOREACH(cpu) {
697         if (gdb_get_cpu_pid(s, cpu) == process->pid) {
698             return cpu;
699         }
700     }
701
702     return NULL;
703 }
704
705 static CPUState *gdb_next_cpu_in_process(const GDBState *s, CPUState *cpu)
706 {
707     uint32_t pid = gdb_get_cpu_pid(s, cpu);
708     cpu = CPU_NEXT(cpu);
709
710     while (cpu) {
711         if (gdb_get_cpu_pid(s, cpu) == pid) {
712             break;
713         }
714
715         cpu = CPU_NEXT(cpu);
716     }
717
718     return cpu;
719 }
720
721 /* Return the cpu following @cpu, while ignoring unattached processes. */
722 static CPUState *gdb_next_attached_cpu(const GDBState *s, CPUState *cpu)
723 {
724     cpu = CPU_NEXT(cpu);
725
726     while (cpu) {
727         if (gdb_get_cpu_process(s, cpu)->attached) {
728             break;
729         }
730
731         cpu = CPU_NEXT(cpu);
732     }
733
734     return cpu;
735 }
736
737 /* Return the first attached cpu */
738 static CPUState *gdb_first_attached_cpu(const GDBState *s)
739 {
740     CPUState *cpu = first_cpu;
741     GDBProcess *process = gdb_get_cpu_process(s, cpu);
742
743     if (!process->attached) {
744         return gdb_next_attached_cpu(s, cpu);
745     }
746
747     return cpu;
748 }
749
750 static CPUState *gdb_get_cpu(const GDBState *s, uint32_t pid, uint32_t tid)
751 {
752     GDBProcess *process;
753     CPUState *cpu;
754
755     if (!pid && !tid) {
756         /* 0 means any process/thread, we take the first attached one */
757         return gdb_first_attached_cpu(s);
758     } else if (pid && !tid) {
759         /* any thread in a specific process */
760         process = gdb_get_process(s, pid);
761
762         if (process == NULL) {
763             return NULL;
764         }
765
766         if (!process->attached) {
767             return NULL;
768         }
769
770         return get_first_cpu_in_process(s, process);
771     } else {
772         /* a specific thread */
773         cpu = find_cpu(tid);
774
775         if (cpu == NULL) {
776             return NULL;
777         }
778
779         process = gdb_get_cpu_process(s, cpu);
780
781         if (pid && process->pid != pid) {
782             return NULL;
783         }
784
785         if (!process->attached) {
786             return NULL;
787         }
788
789         return cpu;
790     }
791 }
792
793 static const char *get_feature_xml(const GDBState *s, const char *p,
794                                    const char **newp, GDBProcess *process)
795 {
796     size_t len;
797     int i;
798     const char *name;
799     CPUState *cpu = get_first_cpu_in_process(s, process);
800     CPUClass *cc = CPU_GET_CLASS(cpu);
801
802     len = 0;
803     while (p[len] && p[len] != ':')
804         len++;
805     *newp = p + len;
806
807     name = NULL;
808     if (strncmp(p, "target.xml", len) == 0) {
809         char *buf = process->target_xml;
810         const size_t buf_sz = sizeof(process->target_xml);
811
812         /* Generate the XML description for this CPU.  */
813         if (!buf[0]) {
814             GDBRegisterState *r;
815
816             pstrcat(buf, buf_sz,
817                     "<?xml version=\"1.0\"?>"
818                     "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
819                     "<target>");
820             if (cc->gdb_arch_name) {
821                 gchar *arch = cc->gdb_arch_name(cpu);
822                 pstrcat(buf, buf_sz, "<architecture>");
823                 pstrcat(buf, buf_sz, arch);
824                 pstrcat(buf, buf_sz, "</architecture>");
825                 g_free(arch);
826             }
827             pstrcat(buf, buf_sz, "<xi:include href=\"");
828             pstrcat(buf, buf_sz, cc->gdb_core_xml_file);
829             pstrcat(buf, buf_sz, "\"/>");
830             for (r = cpu->gdb_regs; r; r = r->next) {
831                 pstrcat(buf, buf_sz, "<xi:include href=\"");
832                 pstrcat(buf, buf_sz, r->xml);
833                 pstrcat(buf, buf_sz, "\"/>");
834             }
835             pstrcat(buf, buf_sz, "</target>");
836         }
837         return buf;
838     }
839     if (cc->gdb_get_dynamic_xml) {
840         char *xmlname = g_strndup(p, len);
841         const char *xml = cc->gdb_get_dynamic_xml(cpu, xmlname);
842
843         g_free(xmlname);
844         if (xml) {
845             return xml;
846         }
847     }
848     for (i = 0; ; i++) {
849         name = xml_builtin[i][0];
850         if (!name || (strncmp(name, p, len) == 0 && strlen(name) == len))
851             break;
852     }
853     return name ? xml_builtin[i][1] : NULL;
854 }
855
856 static int gdb_read_register(CPUState *cpu, uint8_t *mem_buf, int reg)
857 {
858     CPUClass *cc = CPU_GET_CLASS(cpu);
859     CPUArchState *env = cpu->env_ptr;
860     GDBRegisterState *r;
861
862     if (reg < cc->gdb_num_core_regs) {
863         return cc->gdb_read_register(cpu, mem_buf, reg);
864     }
865
866     for (r = cpu->gdb_regs; r; r = r->next) {
867         if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
868             return r->get_reg(env, mem_buf, reg - r->base_reg);
869         }
870     }
871     return 0;
872 }
873
874 static int gdb_write_register(CPUState *cpu, uint8_t *mem_buf, int reg)
875 {
876     CPUClass *cc = CPU_GET_CLASS(cpu);
877     CPUArchState *env = cpu->env_ptr;
878     GDBRegisterState *r;
879
880     if (reg < cc->gdb_num_core_regs) {
881         return cc->gdb_write_register(cpu, mem_buf, reg);
882     }
883
884     for (r = cpu->gdb_regs; r; r = r->next) {
885         if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
886             return r->set_reg(env, mem_buf, reg - r->base_reg);
887         }
888     }
889     return 0;
890 }
891
892 /* Register a supplemental set of CPU registers.  If g_pos is nonzero it
893    specifies the first register number and these registers are included in
894    a standard "g" packet.  Direction is relative to gdb, i.e. get_reg is
895    gdb reading a CPU register, and set_reg is gdb modifying a CPU register.
896  */
897
898 void gdb_register_coprocessor(CPUState *cpu,
899                               gdb_reg_cb get_reg, gdb_reg_cb set_reg,
900                               int num_regs, const char *xml, int g_pos)
901 {
902     GDBRegisterState *s;
903     GDBRegisterState **p;
904
905     p = &cpu->gdb_regs;
906     while (*p) {
907         /* Check for duplicates.  */
908         if (strcmp((*p)->xml, xml) == 0)
909             return;
910         p = &(*p)->next;
911     }
912
913     s = g_new0(GDBRegisterState, 1);
914     s->base_reg = cpu->gdb_num_regs;
915     s->num_regs = num_regs;
916     s->get_reg = get_reg;
917     s->set_reg = set_reg;
918     s->xml = xml;
919
920     /* Add to end of list.  */
921     cpu->gdb_num_regs += num_regs;
922     *p = s;
923     if (g_pos) {
924         if (g_pos != s->base_reg) {
925             error_report("Error: Bad gdb register numbering for '%s', "
926                          "expected %d got %d", xml, g_pos, s->base_reg);
927         } else {
928             cpu->gdb_num_g_regs = cpu->gdb_num_regs;
929         }
930     }
931 }
932
933 #ifndef CONFIG_USER_ONLY
934 /* Translate GDB watchpoint type to a flags value for cpu_watchpoint_* */
935 static inline int xlat_gdb_type(CPUState *cpu, int gdbtype)
936 {
937     static const int xlat[] = {
938         [GDB_WATCHPOINT_WRITE]  = BP_GDB | BP_MEM_WRITE,
939         [GDB_WATCHPOINT_READ]   = BP_GDB | BP_MEM_READ,
940         [GDB_WATCHPOINT_ACCESS] = BP_GDB | BP_MEM_ACCESS,
941     };
942
943     CPUClass *cc = CPU_GET_CLASS(cpu);
944     int cputype = xlat[gdbtype];
945
946     if (cc->gdb_stop_before_watchpoint) {
947         cputype |= BP_STOP_BEFORE_ACCESS;
948     }
949     return cputype;
950 }
951 #endif
952
953 static int gdb_breakpoint_insert(target_ulong addr, target_ulong len, int type)
954 {
955     CPUState *cpu;
956     int err = 0;
957
958     if (kvm_enabled()) {
959         return kvm_insert_breakpoint(gdbserver_state->c_cpu, addr, len, type);
960     }
961
962     switch (type) {
963     case GDB_BREAKPOINT_SW:
964     case GDB_BREAKPOINT_HW:
965         CPU_FOREACH(cpu) {
966             err = cpu_breakpoint_insert(cpu, addr, BP_GDB, NULL);
967             if (err) {
968                 break;
969             }
970         }
971         return err;
972 #ifndef CONFIG_USER_ONLY
973     case GDB_WATCHPOINT_WRITE:
974     case GDB_WATCHPOINT_READ:
975     case GDB_WATCHPOINT_ACCESS:
976         CPU_FOREACH(cpu) {
977             err = cpu_watchpoint_insert(cpu, addr, len,
978                                         xlat_gdb_type(cpu, type), NULL);
979             if (err) {
980                 break;
981             }
982         }
983         return err;
984 #endif
985     default:
986         return -ENOSYS;
987     }
988 }
989
990 static int gdb_breakpoint_remove(target_ulong addr, target_ulong len, int type)
991 {
992     CPUState *cpu;
993     int err = 0;
994
995     if (kvm_enabled()) {
996         return kvm_remove_breakpoint(gdbserver_state->c_cpu, addr, len, type);
997     }
998
999     switch (type) {
1000     case GDB_BREAKPOINT_SW:
1001     case GDB_BREAKPOINT_HW:
1002         CPU_FOREACH(cpu) {
1003             err = cpu_breakpoint_remove(cpu, addr, BP_GDB);
1004             if (err) {
1005                 break;
1006             }
1007         }
1008         return err;
1009 #ifndef CONFIG_USER_ONLY
1010     case GDB_WATCHPOINT_WRITE:
1011     case GDB_WATCHPOINT_READ:
1012     case GDB_WATCHPOINT_ACCESS:
1013         CPU_FOREACH(cpu) {
1014             err = cpu_watchpoint_remove(cpu, addr, len,
1015                                         xlat_gdb_type(cpu, type));
1016             if (err)
1017                 break;
1018         }
1019         return err;
1020 #endif
1021     default:
1022         return -ENOSYS;
1023     }
1024 }
1025
1026 static inline void gdb_cpu_breakpoint_remove_all(CPUState *cpu)
1027 {
1028     cpu_breakpoint_remove_all(cpu, BP_GDB);
1029 #ifndef CONFIG_USER_ONLY
1030     cpu_watchpoint_remove_all(cpu, BP_GDB);
1031 #endif
1032 }
1033
1034 static void gdb_process_breakpoint_remove_all(const GDBState *s, GDBProcess *p)
1035 {
1036     CPUState *cpu = get_first_cpu_in_process(s, p);
1037
1038     while (cpu) {
1039         gdb_cpu_breakpoint_remove_all(cpu);
1040         cpu = gdb_next_cpu_in_process(s, cpu);
1041     }
1042 }
1043
1044 static void gdb_breakpoint_remove_all(void)
1045 {
1046     CPUState *cpu;
1047
1048     if (kvm_enabled()) {
1049         kvm_remove_all_breakpoints(gdbserver_state->c_cpu);
1050         return;
1051     }
1052
1053     CPU_FOREACH(cpu) {
1054         gdb_cpu_breakpoint_remove_all(cpu);
1055     }
1056 }
1057
1058 static void gdb_set_cpu_pc(GDBState *s, target_ulong pc)
1059 {
1060     CPUState *cpu = s->c_cpu;
1061
1062     cpu_synchronize_state(cpu);
1063     cpu_set_pc(cpu, pc);
1064 }
1065
1066 static char *gdb_fmt_thread_id(const GDBState *s, CPUState *cpu,
1067                            char *buf, size_t buf_size)
1068 {
1069     if (s->multiprocess) {
1070         snprintf(buf, buf_size, "p%02x.%02x",
1071                  gdb_get_cpu_pid(s, cpu), cpu_gdb_index(cpu));
1072     } else {
1073         snprintf(buf, buf_size, "%02x", cpu_gdb_index(cpu));
1074     }
1075
1076     return buf;
1077 }
1078
1079 typedef enum GDBThreadIdKind {
1080     GDB_ONE_THREAD = 0,
1081     GDB_ALL_THREADS,     /* One process, all threads */
1082     GDB_ALL_PROCESSES,
1083     GDB_READ_THREAD_ERR
1084 } GDBThreadIdKind;
1085
1086 static GDBThreadIdKind read_thread_id(const char *buf, const char **end_buf,
1087                                       uint32_t *pid, uint32_t *tid)
1088 {
1089     unsigned long p, t;
1090     int ret;
1091
1092     if (*buf == 'p') {
1093         buf++;
1094         ret = qemu_strtoul(buf, &buf, 16, &p);
1095
1096         if (ret) {
1097             return GDB_READ_THREAD_ERR;
1098         }
1099
1100         /* Skip '.' */
1101         buf++;
1102     } else {
1103         p = 1;
1104     }
1105
1106     ret = qemu_strtoul(buf, &buf, 16, &t);
1107
1108     if (ret) {
1109         return GDB_READ_THREAD_ERR;
1110     }
1111
1112     *end_buf = buf;
1113
1114     if (p == -1) {
1115         return GDB_ALL_PROCESSES;
1116     }
1117
1118     if (pid) {
1119         *pid = p;
1120     }
1121
1122     if (t == -1) {
1123         return GDB_ALL_THREADS;
1124     }
1125
1126     if (tid) {
1127         *tid = t;
1128     }
1129
1130     return GDB_ONE_THREAD;
1131 }
1132
1133 static int is_query_packet(const char *p, const char *query, char separator)
1134 {
1135     unsigned int query_len = strlen(query);
1136
1137     return strncmp(p, query, query_len) == 0 &&
1138         (p[query_len] == '\0' || p[query_len] == separator);
1139 }
1140
1141 /**
1142  * gdb_handle_vcont - Parses and handles a vCont packet.
1143  * returns -ENOTSUP if a command is unsupported, -EINVAL or -ERANGE if there is
1144  *         a format error, 0 on success.
1145  */
1146 static int gdb_handle_vcont(GDBState *s, const char *p)
1147 {
1148     int res, signal = 0;
1149     char cur_action;
1150     char *newstates;
1151     unsigned long tmp;
1152     uint32_t pid, tid;
1153     GDBProcess *process;
1154     CPUState *cpu;
1155 #ifdef CONFIG_USER_ONLY
1156     int max_cpus = 1; /* global variable max_cpus exists only in system mode */
1157
1158     CPU_FOREACH(cpu) {
1159         max_cpus = max_cpus <= cpu->cpu_index ? cpu->cpu_index + 1 : max_cpus;
1160     }
1161 #endif
1162     /* uninitialised CPUs stay 0 */
1163     newstates = g_new0(char, max_cpus);
1164
1165     /* mark valid CPUs with 1 */
1166     CPU_FOREACH(cpu) {
1167         newstates[cpu->cpu_index] = 1;
1168     }
1169
1170     /*
1171      * res keeps track of what error we are returning, with -ENOTSUP meaning
1172      * that the command is unknown or unsupported, thus returning an empty
1173      * packet, while -EINVAL and -ERANGE cause an E22 packet, due to invalid,
1174      *  or incorrect parameters passed.
1175      */
1176     res = 0;
1177     while (*p) {
1178         if (*p++ != ';') {
1179             res = -ENOTSUP;
1180             goto out;
1181         }
1182
1183         cur_action = *p++;
1184         if (cur_action == 'C' || cur_action == 'S') {
1185             cur_action = qemu_tolower(cur_action);
1186             res = qemu_strtoul(p + 1, &p, 16, &tmp);
1187             if (res) {
1188                 goto out;
1189             }
1190             signal = gdb_signal_to_target(tmp);
1191         } else if (cur_action != 'c' && cur_action != 's') {
1192             /* unknown/invalid/unsupported command */
1193             res = -ENOTSUP;
1194             goto out;
1195         }
1196
1197         if (*p++ != ':') {
1198             res = -ENOTSUP;
1199             goto out;
1200         }
1201
1202         switch (read_thread_id(p, &p, &pid, &tid)) {
1203         case GDB_READ_THREAD_ERR:
1204             res = -EINVAL;
1205             goto out;
1206
1207         case GDB_ALL_PROCESSES:
1208             cpu = gdb_first_attached_cpu(s);
1209             while (cpu) {
1210                 if (newstates[cpu->cpu_index] == 1) {
1211                     newstates[cpu->cpu_index] = cur_action;
1212                 }
1213
1214                 cpu = gdb_next_attached_cpu(s, cpu);
1215             }
1216             break;
1217
1218         case GDB_ALL_THREADS:
1219             process = gdb_get_process(s, pid);
1220
1221             if (!process->attached) {
1222                 res = -EINVAL;
1223                 goto out;
1224             }
1225
1226             cpu = get_first_cpu_in_process(s, process);
1227             while (cpu) {
1228                 if (newstates[cpu->cpu_index] == 1) {
1229                     newstates[cpu->cpu_index] = cur_action;
1230                 }
1231
1232                 cpu = gdb_next_cpu_in_process(s, cpu);
1233             }
1234             break;
1235
1236         case GDB_ONE_THREAD:
1237             cpu = gdb_get_cpu(s, pid, tid);
1238
1239             /* invalid CPU/thread specified */
1240             if (!cpu) {
1241                 res = -EINVAL;
1242                 goto out;
1243             }
1244
1245             /* only use if no previous match occourred */
1246             if (newstates[cpu->cpu_index] == 1) {
1247                 newstates[cpu->cpu_index] = cur_action;
1248             }
1249             break;
1250         }
1251     }
1252     s->signal = signal;
1253     gdb_continue_partial(s, newstates);
1254
1255 out:
1256     g_free(newstates);
1257
1258     return res;
1259 }
1260
1261 static int gdb_handle_packet(GDBState *s, const char *line_buf)
1262 {
1263     CPUState *cpu;
1264     GDBProcess *process;
1265     CPUClass *cc;
1266     const char *p;
1267     uint32_t pid, tid;
1268     int ch, reg_size, type, res;
1269     uint8_t mem_buf[MAX_PACKET_LENGTH];
1270     char buf[sizeof(mem_buf) + 1 /* trailing NUL */];
1271     char thread_id[16];
1272     uint8_t *registers;
1273     target_ulong addr, len;
1274     GDBThreadIdKind thread_kind;
1275
1276     trace_gdbstub_io_command(line_buf);
1277
1278     p = line_buf;
1279     ch = *p++;
1280     switch(ch) {
1281     case '!':
1282         put_packet(s, "OK");
1283         break;
1284     case '?':
1285         /* TODO: Make this return the correct value for user-mode.  */
1286         snprintf(buf, sizeof(buf), "T%02xthread:%s;", GDB_SIGNAL_TRAP,
1287                  gdb_fmt_thread_id(s, s->c_cpu, thread_id, sizeof(thread_id)));
1288         put_packet(s, buf);
1289         /* Remove all the breakpoints when this query is issued,
1290          * because gdb is doing and initial connect and the state
1291          * should be cleaned up.
1292          */
1293         gdb_breakpoint_remove_all();
1294         break;
1295     case 'c':
1296         if (*p != '\0') {
1297             addr = strtoull(p, (char **)&p, 16);
1298             gdb_set_cpu_pc(s, addr);
1299         }
1300         s->signal = 0;
1301         gdb_continue(s);
1302         return RS_IDLE;
1303     case 'C':
1304         s->signal = gdb_signal_to_target (strtoul(p, (char **)&p, 16));
1305         if (s->signal == -1)
1306             s->signal = 0;
1307         gdb_continue(s);
1308         return RS_IDLE;
1309     case 'v':
1310         if (strncmp(p, "Cont", 4) == 0) {
1311             p += 4;
1312             if (*p == '?') {
1313                 put_packet(s, "vCont;c;C;s;S");
1314                 break;
1315             }
1316
1317             res = gdb_handle_vcont(s, p);
1318
1319             if (res) {
1320                 if ((res == -EINVAL) || (res == -ERANGE)) {
1321                     put_packet(s, "E22");
1322                     break;
1323                 }
1324                 goto unknown_command;
1325             }
1326             break;
1327         } else if (strncmp(p, "Attach;", 7) == 0) {
1328             unsigned long pid;
1329
1330             p += 7;
1331
1332             if (qemu_strtoul(p, &p, 16, &pid)) {
1333                 put_packet(s, "E22");
1334                 break;
1335             }
1336
1337             process = gdb_get_process(s, pid);
1338
1339             if (process == NULL) {
1340                 put_packet(s, "E22");
1341                 break;
1342             }
1343
1344             cpu = get_first_cpu_in_process(s, process);
1345
1346             if (cpu == NULL) {
1347                 /* Refuse to attach an empty process */
1348                 put_packet(s, "E22");
1349                 break;
1350             }
1351
1352             process->attached = true;
1353
1354             s->g_cpu = cpu;
1355             s->c_cpu = cpu;
1356
1357             snprintf(buf, sizeof(buf), "T%02xthread:%s;", GDB_SIGNAL_TRAP,
1358                      gdb_fmt_thread_id(s, cpu, thread_id, sizeof(thread_id)));
1359
1360             put_packet(s, buf);
1361             break;
1362         } else if (strncmp(p, "Kill;", 5) == 0) {
1363             /* Kill the target */
1364             error_report("QEMU: Terminated via GDBstub");
1365             exit(0);
1366         } else {
1367             goto unknown_command;
1368         }
1369     case 'k':
1370         /* Kill the target */
1371         error_report("QEMU: Terminated via GDBstub");
1372         exit(0);
1373     case 'D':
1374         /* Detach packet */
1375         pid = 1;
1376
1377         if (s->multiprocess) {
1378             unsigned long lpid;
1379             if (*p != ';') {
1380                 put_packet(s, "E22");
1381                 break;
1382             }
1383
1384             if (qemu_strtoul(p + 1, &p, 16, &lpid)) {
1385                 put_packet(s, "E22");
1386                 break;
1387             }
1388
1389             pid = lpid;
1390         }
1391
1392         process = gdb_get_process(s, pid);
1393         gdb_process_breakpoint_remove_all(s, process);
1394         process->attached = false;
1395
1396         if (pid == gdb_get_cpu_pid(s, s->c_cpu)) {
1397             s->c_cpu = gdb_first_attached_cpu(s);
1398         }
1399
1400         if (pid == gdb_get_cpu_pid(s, s->g_cpu)) {
1401             s->g_cpu = gdb_first_attached_cpu(s);
1402         }
1403
1404         if (s->c_cpu == NULL) {
1405             /* No more process attached */
1406             gdb_syscall_mode = GDB_SYS_DISABLED;
1407             gdb_continue(s);
1408         }
1409         put_packet(s, "OK");
1410         break;
1411     case 's':
1412         if (*p != '\0') {
1413             addr = strtoull(p, (char **)&p, 16);
1414             gdb_set_cpu_pc(s, addr);
1415         }
1416         cpu_single_step(s->c_cpu, sstep_flags);
1417         gdb_continue(s);
1418         return RS_IDLE;
1419     case 'F':
1420         {
1421             target_ulong ret;
1422             target_ulong err;
1423
1424             ret = strtoull(p, (char **)&p, 16);
1425             if (*p == ',') {
1426                 p++;
1427                 err = strtoull(p, (char **)&p, 16);
1428             } else {
1429                 err = 0;
1430             }
1431             if (*p == ',')
1432                 p++;
1433             type = *p;
1434             if (s->current_syscall_cb) {
1435                 s->current_syscall_cb(s->c_cpu, ret, err);
1436                 s->current_syscall_cb = NULL;
1437             }
1438             if (type == 'C') {
1439                 put_packet(s, "T02");
1440             } else {
1441                 gdb_continue(s);
1442             }
1443         }
1444         break;
1445     case 'g':
1446         cpu_synchronize_state(s->g_cpu);
1447         len = 0;
1448         for (addr = 0; addr < s->g_cpu->gdb_num_g_regs; addr++) {
1449             reg_size = gdb_read_register(s->g_cpu, mem_buf + len, addr);
1450             len += reg_size;
1451         }
1452         memtohex(buf, mem_buf, len);
1453         put_packet(s, buf);
1454         break;
1455     case 'G':
1456         cpu_synchronize_state(s->g_cpu);
1457         registers = mem_buf;
1458         len = strlen(p) / 2;
1459         hextomem((uint8_t *)registers, p, len);
1460         for (addr = 0; addr < s->g_cpu->gdb_num_g_regs && len > 0; addr++) {
1461             reg_size = gdb_write_register(s->g_cpu, registers, addr);
1462             len -= reg_size;
1463             registers += reg_size;
1464         }
1465         put_packet(s, "OK");
1466         break;
1467     case 'm':
1468         addr = strtoull(p, (char **)&p, 16);
1469         if (*p == ',')
1470             p++;
1471         len = strtoull(p, NULL, 16);
1472
1473         /* memtohex() doubles the required space */
1474         if (len > MAX_PACKET_LENGTH / 2) {
1475             put_packet (s, "E22");
1476             break;
1477         }
1478
1479         if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len, false) != 0) {
1480             put_packet (s, "E14");
1481         } else {
1482             memtohex(buf, mem_buf, len);
1483             put_packet(s, buf);
1484         }
1485         break;
1486     case 'M':
1487         addr = strtoull(p, (char **)&p, 16);
1488         if (*p == ',')
1489             p++;
1490         len = strtoull(p, (char **)&p, 16);
1491         if (*p == ':')
1492             p++;
1493
1494         /* hextomem() reads 2*len bytes */
1495         if (len > strlen(p) / 2) {
1496             put_packet (s, "E22");
1497             break;
1498         }
1499         hextomem(mem_buf, p, len);
1500         if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len,
1501                                    true) != 0) {
1502             put_packet(s, "E14");
1503         } else {
1504             put_packet(s, "OK");
1505         }
1506         break;
1507     case 'p':
1508         /* Older gdb are really dumb, and don't use 'g' if 'p' is avaialable.
1509            This works, but can be very slow.  Anything new enough to
1510            understand XML also knows how to use this properly.  */
1511         if (!gdb_has_xml)
1512             goto unknown_command;
1513         addr = strtoull(p, (char **)&p, 16);
1514         reg_size = gdb_read_register(s->g_cpu, mem_buf, addr);
1515         if (reg_size) {
1516             memtohex(buf, mem_buf, reg_size);
1517             put_packet(s, buf);
1518         } else {
1519             put_packet(s, "E14");
1520         }
1521         break;
1522     case 'P':
1523         if (!gdb_has_xml)
1524             goto unknown_command;
1525         addr = strtoull(p, (char **)&p, 16);
1526         if (*p == '=')
1527             p++;
1528         reg_size = strlen(p) / 2;
1529         hextomem(mem_buf, p, reg_size);
1530         gdb_write_register(s->g_cpu, mem_buf, addr);
1531         put_packet(s, "OK");
1532         break;
1533     case 'Z':
1534     case 'z':
1535         type = strtoul(p, (char **)&p, 16);
1536         if (*p == ',')
1537             p++;
1538         addr = strtoull(p, (char **)&p, 16);
1539         if (*p == ',')
1540             p++;
1541         len = strtoull(p, (char **)&p, 16);
1542         if (ch == 'Z')
1543             res = gdb_breakpoint_insert(addr, len, type);
1544         else
1545             res = gdb_breakpoint_remove(addr, len, type);
1546         if (res >= 0)
1547              put_packet(s, "OK");
1548         else if (res == -ENOSYS)
1549             put_packet(s, "");
1550         else
1551             put_packet(s, "E22");
1552         break;
1553     case 'H':
1554         type = *p++;
1555
1556         thread_kind = read_thread_id(p, &p, &pid, &tid);
1557         if (thread_kind == GDB_READ_THREAD_ERR) {
1558             put_packet(s, "E22");
1559             break;
1560         }
1561
1562         if (thread_kind != GDB_ONE_THREAD) {
1563             put_packet(s, "OK");
1564             break;
1565         }
1566         cpu = gdb_get_cpu(s, pid, tid);
1567         if (cpu == NULL) {
1568             put_packet(s, "E22");
1569             break;
1570         }
1571         switch (type) {
1572         case 'c':
1573             s->c_cpu = cpu;
1574             put_packet(s, "OK");
1575             break;
1576         case 'g':
1577             s->g_cpu = cpu;
1578             put_packet(s, "OK");
1579             break;
1580         default:
1581              put_packet(s, "E22");
1582              break;
1583         }
1584         break;
1585     case 'T':
1586         thread_kind = read_thread_id(p, &p, &pid, &tid);
1587         if (thread_kind == GDB_READ_THREAD_ERR) {
1588             put_packet(s, "E22");
1589             break;
1590         }
1591         cpu = gdb_get_cpu(s, pid, tid);
1592
1593         if (cpu != NULL) {
1594             put_packet(s, "OK");
1595         } else {
1596             put_packet(s, "E22");
1597         }
1598         break;
1599     case 'q':
1600     case 'Q':
1601         /* parse any 'q' packets here */
1602         if (!strcmp(p,"qemu.sstepbits")) {
1603             /* Query Breakpoint bit definitions */
1604             snprintf(buf, sizeof(buf), "ENABLE=%x,NOIRQ=%x,NOTIMER=%x",
1605                      SSTEP_ENABLE,
1606                      SSTEP_NOIRQ,
1607                      SSTEP_NOTIMER);
1608             put_packet(s, buf);
1609             break;
1610         } else if (is_query_packet(p, "qemu.sstep", '=')) {
1611             /* Display or change the sstep_flags */
1612             p += 10;
1613             if (*p != '=') {
1614                 /* Display current setting */
1615                 snprintf(buf, sizeof(buf), "0x%x", sstep_flags);
1616                 put_packet(s, buf);
1617                 break;
1618             }
1619             p++;
1620             type = strtoul(p, (char **)&p, 16);
1621             sstep_flags = type;
1622             put_packet(s, "OK");
1623             break;
1624         } else if (strcmp(p,"C") == 0) {
1625             /*
1626              * "Current thread" remains vague in the spec, so always return
1627              * the first thread of the current process (gdb returns the
1628              * first thread).
1629              */
1630             cpu = get_first_cpu_in_process(s, gdb_get_cpu_process(s, s->g_cpu));
1631             snprintf(buf, sizeof(buf), "QC%s",
1632                      gdb_fmt_thread_id(s, cpu, thread_id, sizeof(thread_id)));
1633             put_packet(s, buf);
1634             break;
1635         } else if (strcmp(p,"fThreadInfo") == 0) {
1636             s->query_cpu = gdb_first_attached_cpu(s);
1637             goto report_cpuinfo;
1638         } else if (strcmp(p,"sThreadInfo") == 0) {
1639         report_cpuinfo:
1640             if (s->query_cpu) {
1641                 snprintf(buf, sizeof(buf), "m%s",
1642                          gdb_fmt_thread_id(s, s->query_cpu,
1643                                        thread_id, sizeof(thread_id)));
1644                 put_packet(s, buf);
1645                 s->query_cpu = gdb_next_attached_cpu(s, s->query_cpu);
1646             } else
1647                 put_packet(s, "l");
1648             break;
1649         } else if (strncmp(p,"ThreadExtraInfo,", 16) == 0) {
1650             if (read_thread_id(p + 16, &p, &pid, &tid) == GDB_READ_THREAD_ERR) {
1651                 put_packet(s, "E22");
1652                 break;
1653             }
1654             cpu = gdb_get_cpu(s, pid, tid);
1655             if (cpu != NULL) {
1656                 cpu_synchronize_state(cpu);
1657
1658                 if (s->multiprocess && (s->process_num > 1)) {
1659                     /* Print the CPU model and name in multiprocess mode */
1660                     ObjectClass *oc = object_get_class(OBJECT(cpu));
1661                     const char *cpu_model = object_class_get_name(oc);
1662                     char *cpu_name =
1663                         object_get_canonical_path_component(OBJECT(cpu));
1664                     len = snprintf((char *)mem_buf, sizeof(buf) / 2,
1665                                    "%s %s [%s]", cpu_model, cpu_name,
1666                                    cpu->halted ? "halted " : "running");
1667                     g_free(cpu_name);
1668                 } else {
1669                     /* memtohex() doubles the required space */
1670                     len = snprintf((char *)mem_buf, sizeof(buf) / 2,
1671                                    "CPU#%d [%s]", cpu->cpu_index,
1672                                    cpu->halted ? "halted " : "running");
1673                 }
1674                 trace_gdbstub_op_extra_info((char *)mem_buf);
1675                 memtohex(buf, mem_buf, len);
1676                 put_packet(s, buf);
1677             }
1678             break;
1679         }
1680 #ifdef CONFIG_USER_ONLY
1681         else if (strcmp(p, "Offsets") == 0) {
1682             TaskState *ts = s->c_cpu->opaque;
1683
1684             snprintf(buf, sizeof(buf),
1685                      "Text=" TARGET_ABI_FMT_lx ";Data=" TARGET_ABI_FMT_lx
1686                      ";Bss=" TARGET_ABI_FMT_lx,
1687                      ts->info->code_offset,
1688                      ts->info->data_offset,
1689                      ts->info->data_offset);
1690             put_packet(s, buf);
1691             break;
1692         }
1693 #else /* !CONFIG_USER_ONLY */
1694         else if (strncmp(p, "Rcmd,", 5) == 0) {
1695             int len = strlen(p + 5);
1696
1697             if ((len % 2) != 0) {
1698                 put_packet(s, "E01");
1699                 break;
1700             }
1701             len = len / 2;
1702             hextomem(mem_buf, p + 5, len);
1703             mem_buf[len++] = 0;
1704             qemu_chr_be_write(s->mon_chr, mem_buf, len);
1705             put_packet(s, "OK");
1706             break;
1707         }
1708 #endif /* !CONFIG_USER_ONLY */
1709         if (is_query_packet(p, "Supported", ':')) {
1710             snprintf(buf, sizeof(buf), "PacketSize=%x", MAX_PACKET_LENGTH);
1711             cc = CPU_GET_CLASS(first_cpu);
1712             if (cc->gdb_core_xml_file != NULL) {
1713                 pstrcat(buf, sizeof(buf), ";qXfer:features:read+");
1714             }
1715
1716             if (strstr(p, "multiprocess+")) {
1717                 s->multiprocess = true;
1718             }
1719             pstrcat(buf, sizeof(buf), ";multiprocess+");
1720
1721             put_packet(s, buf);
1722             break;
1723         }
1724         if (strncmp(p, "Xfer:features:read:", 19) == 0) {
1725             const char *xml;
1726             target_ulong total_len;
1727
1728             process = gdb_get_cpu_process(s, s->g_cpu);
1729             cc = CPU_GET_CLASS(s->g_cpu);
1730             if (cc->gdb_core_xml_file == NULL) {
1731                 goto unknown_command;
1732             }
1733
1734             gdb_has_xml = true;
1735             p += 19;
1736             xml = get_feature_xml(s, p, &p, process);
1737             if (!xml) {
1738                 snprintf(buf, sizeof(buf), "E00");
1739                 put_packet(s, buf);
1740                 break;
1741             }
1742
1743             if (*p == ':')
1744                 p++;
1745             addr = strtoul(p, (char **)&p, 16);
1746             if (*p == ',')
1747                 p++;
1748             len = strtoul(p, (char **)&p, 16);
1749
1750             total_len = strlen(xml);
1751             if (addr > total_len) {
1752                 snprintf(buf, sizeof(buf), "E00");
1753                 put_packet(s, buf);
1754                 break;
1755             }
1756             if (len > (MAX_PACKET_LENGTH - 5) / 2)
1757                 len = (MAX_PACKET_LENGTH - 5) / 2;
1758             if (len < total_len - addr) {
1759                 buf[0] = 'm';
1760                 len = memtox(buf + 1, xml + addr, len);
1761             } else {
1762                 buf[0] = 'l';
1763                 len = memtox(buf + 1, xml + addr, total_len - addr);
1764             }
1765             put_packet_binary(s, buf, len + 1, true);
1766             break;
1767         }
1768         if (is_query_packet(p, "Attached", ':')) {
1769             put_packet(s, GDB_ATTACHED);
1770             break;
1771         }
1772         /* Unrecognised 'q' command.  */
1773         goto unknown_command;
1774
1775     default:
1776     unknown_command:
1777         /* put empty packet */
1778         buf[0] = '\0';
1779         put_packet(s, buf);
1780         break;
1781     }
1782     return RS_IDLE;
1783 }
1784
1785 void gdb_set_stop_cpu(CPUState *cpu)
1786 {
1787     GDBProcess *p = gdb_get_cpu_process(gdbserver_state, cpu);
1788
1789     if (!p->attached) {
1790         /*
1791          * Having a stop CPU corresponding to a process that is not attached
1792          * confuses GDB. So we ignore the request.
1793          */
1794         return;
1795     }
1796
1797     gdbserver_state->c_cpu = cpu;
1798     gdbserver_state->g_cpu = cpu;
1799 }
1800
1801 #ifndef CONFIG_USER_ONLY
1802 static void gdb_vm_state_change(void *opaque, int running, RunState state)
1803 {
1804     GDBState *s = gdbserver_state;
1805     CPUState *cpu = s->c_cpu;
1806     char buf[256];
1807     char thread_id[16];
1808     const char *type;
1809     int ret;
1810
1811     if (running || s->state == RS_INACTIVE) {
1812         return;
1813     }
1814     /* Is there a GDB syscall waiting to be sent?  */
1815     if (s->current_syscall_cb) {
1816         put_packet(s, s->syscall_buf);
1817         return;
1818     }
1819
1820     if (cpu == NULL) {
1821         /* No process attached */
1822         return;
1823     }
1824
1825     gdb_fmt_thread_id(s, cpu, thread_id, sizeof(thread_id));
1826
1827     switch (state) {
1828     case RUN_STATE_DEBUG:
1829         if (cpu->watchpoint_hit) {
1830             switch (cpu->watchpoint_hit->flags & BP_MEM_ACCESS) {
1831             case BP_MEM_READ:
1832                 type = "r";
1833                 break;
1834             case BP_MEM_ACCESS:
1835                 type = "a";
1836                 break;
1837             default:
1838                 type = "";
1839                 break;
1840             }
1841             trace_gdbstub_hit_watchpoint(type, cpu_gdb_index(cpu),
1842                     (target_ulong)cpu->watchpoint_hit->vaddr);
1843             snprintf(buf, sizeof(buf),
1844                      "T%02xthread:%s;%swatch:" TARGET_FMT_lx ";",
1845                      GDB_SIGNAL_TRAP, thread_id, type,
1846                      (target_ulong)cpu->watchpoint_hit->vaddr);
1847             cpu->watchpoint_hit = NULL;
1848             goto send_packet;
1849         } else {
1850             trace_gdbstub_hit_break();
1851         }
1852         tb_flush(cpu);
1853         ret = GDB_SIGNAL_TRAP;
1854         break;
1855     case RUN_STATE_PAUSED:
1856         trace_gdbstub_hit_paused();
1857         ret = GDB_SIGNAL_INT;
1858         break;
1859     case RUN_STATE_SHUTDOWN:
1860         trace_gdbstub_hit_shutdown();
1861         ret = GDB_SIGNAL_QUIT;
1862         break;
1863     case RUN_STATE_IO_ERROR:
1864         trace_gdbstub_hit_io_error();
1865         ret = GDB_SIGNAL_IO;
1866         break;
1867     case RUN_STATE_WATCHDOG:
1868         trace_gdbstub_hit_watchdog();
1869         ret = GDB_SIGNAL_ALRM;
1870         break;
1871     case RUN_STATE_INTERNAL_ERROR:
1872         trace_gdbstub_hit_internal_error();
1873         ret = GDB_SIGNAL_ABRT;
1874         break;
1875     case RUN_STATE_SAVE_VM:
1876     case RUN_STATE_RESTORE_VM:
1877         return;
1878     case RUN_STATE_FINISH_MIGRATE:
1879         ret = GDB_SIGNAL_XCPU;
1880         break;
1881     default:
1882         trace_gdbstub_hit_unknown(state);
1883         ret = GDB_SIGNAL_UNKNOWN;
1884         break;
1885     }
1886     gdb_set_stop_cpu(cpu);
1887     snprintf(buf, sizeof(buf), "T%02xthread:%s;", ret, thread_id);
1888
1889 send_packet:
1890     put_packet(s, buf);
1891
1892     /* disable single step if it was enabled */
1893     cpu_single_step(cpu, 0);
1894 }
1895 #endif
1896
1897 /* Send a gdb syscall request.
1898    This accepts limited printf-style format specifiers, specifically:
1899     %x  - target_ulong argument printed in hex.
1900     %lx - 64-bit argument printed in hex.
1901     %s  - string pointer (target_ulong) and length (int) pair.  */
1902 void gdb_do_syscallv(gdb_syscall_complete_cb cb, const char *fmt, va_list va)
1903 {
1904     char *p;
1905     char *p_end;
1906     target_ulong addr;
1907     uint64_t i64;
1908     GDBState *s;
1909
1910     s = gdbserver_state;
1911     if (!s)
1912         return;
1913     s->current_syscall_cb = cb;
1914 #ifndef CONFIG_USER_ONLY
1915     vm_stop(RUN_STATE_DEBUG);
1916 #endif
1917     p = s->syscall_buf;
1918     p_end = &s->syscall_buf[sizeof(s->syscall_buf)];
1919     *(p++) = 'F';
1920     while (*fmt) {
1921         if (*fmt == '%') {
1922             fmt++;
1923             switch (*fmt++) {
1924             case 'x':
1925                 addr = va_arg(va, target_ulong);
1926                 p += snprintf(p, p_end - p, TARGET_FMT_lx, addr);
1927                 break;
1928             case 'l':
1929                 if (*(fmt++) != 'x')
1930                     goto bad_format;
1931                 i64 = va_arg(va, uint64_t);
1932                 p += snprintf(p, p_end - p, "%" PRIx64, i64);
1933                 break;
1934             case 's':
1935                 addr = va_arg(va, target_ulong);
1936                 p += snprintf(p, p_end - p, TARGET_FMT_lx "/%x",
1937                               addr, va_arg(va, int));
1938                 break;
1939             default:
1940             bad_format:
1941                 error_report("gdbstub: Bad syscall format string '%s'",
1942                              fmt - 1);
1943                 break;
1944             }
1945         } else {
1946             *(p++) = *(fmt++);
1947         }
1948     }
1949     *p = 0;
1950 #ifdef CONFIG_USER_ONLY
1951     put_packet(s, s->syscall_buf);
1952     /* Return control to gdb for it to process the syscall request.
1953      * Since the protocol requires that gdb hands control back to us
1954      * using a "here are the results" F packet, we don't need to check
1955      * gdb_handlesig's return value (which is the signal to deliver if
1956      * execution was resumed via a continue packet).
1957      */
1958     gdb_handlesig(s->c_cpu, 0);
1959 #else
1960     /* In this case wait to send the syscall packet until notification that
1961        the CPU has stopped.  This must be done because if the packet is sent
1962        now the reply from the syscall request could be received while the CPU
1963        is still in the running state, which can cause packets to be dropped
1964        and state transition 'T' packets to be sent while the syscall is still
1965        being processed.  */
1966     qemu_cpu_kick(s->c_cpu);
1967 #endif
1968 }
1969
1970 void gdb_do_syscall(gdb_syscall_complete_cb cb, const char *fmt, ...)
1971 {
1972     va_list va;
1973
1974     va_start(va, fmt);
1975     gdb_do_syscallv(cb, fmt, va);
1976     va_end(va);
1977 }
1978
1979 static void gdb_read_byte(GDBState *s, int ch)
1980 {
1981     uint8_t reply;
1982
1983 #ifndef CONFIG_USER_ONLY
1984     if (s->last_packet_len) {
1985         /* Waiting for a response to the last packet.  If we see the start
1986            of a new command then abandon the previous response.  */
1987         if (ch == '-') {
1988             trace_gdbstub_err_got_nack();
1989             put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
1990         } else if (ch == '+') {
1991             trace_gdbstub_io_got_ack();
1992         } else {
1993             trace_gdbstub_io_got_unexpected((uint8_t)ch);
1994         }
1995
1996         if (ch == '+' || ch == '$')
1997             s->last_packet_len = 0;
1998         if (ch != '$')
1999             return;
2000     }
2001     if (runstate_is_running()) {
2002         /* when the CPU is running, we cannot do anything except stop
2003            it when receiving a char */
2004         vm_stop(RUN_STATE_PAUSED);
2005     } else
2006 #endif
2007     {
2008         switch(s->state) {
2009         case RS_IDLE:
2010             if (ch == '$') {
2011                 /* start of command packet */
2012                 s->line_buf_index = 0;
2013                 s->line_sum = 0;
2014                 s->state = RS_GETLINE;
2015             } else {
2016                 trace_gdbstub_err_garbage((uint8_t)ch);
2017             }
2018             break;
2019         case RS_GETLINE:
2020             if (ch == '}') {
2021                 /* start escape sequence */
2022                 s->state = RS_GETLINE_ESC;
2023                 s->line_sum += ch;
2024             } else if (ch == '*') {
2025                 /* start run length encoding sequence */
2026                 s->state = RS_GETLINE_RLE;
2027                 s->line_sum += ch;
2028             } else if (ch == '#') {
2029                 /* end of command, start of checksum*/
2030                 s->state = RS_CHKSUM1;
2031             } else if (s->line_buf_index >= sizeof(s->line_buf) - 1) {
2032                 trace_gdbstub_err_overrun();
2033                 s->state = RS_IDLE;
2034             } else {
2035                 /* unescaped command character */
2036                 s->line_buf[s->line_buf_index++] = ch;
2037                 s->line_sum += ch;
2038             }
2039             break;
2040         case RS_GETLINE_ESC:
2041             if (ch == '#') {
2042                 /* unexpected end of command in escape sequence */
2043                 s->state = RS_CHKSUM1;
2044             } else if (s->line_buf_index >= sizeof(s->line_buf) - 1) {
2045                 /* command buffer overrun */
2046                 trace_gdbstub_err_overrun();
2047                 s->state = RS_IDLE;
2048             } else {
2049                 /* parse escaped character and leave escape state */
2050                 s->line_buf[s->line_buf_index++] = ch ^ 0x20;
2051                 s->line_sum += ch;
2052                 s->state = RS_GETLINE;
2053             }
2054             break;
2055         case RS_GETLINE_RLE:
2056             if (ch < ' ') {
2057                 /* invalid RLE count encoding */
2058                 trace_gdbstub_err_invalid_repeat((uint8_t)ch);
2059                 s->state = RS_GETLINE;
2060             } else {
2061                 /* decode repeat length */
2062                 int repeat = (unsigned char)ch - ' ' + 3;
2063                 if (s->line_buf_index + repeat >= sizeof(s->line_buf) - 1) {
2064                     /* that many repeats would overrun the command buffer */
2065                     trace_gdbstub_err_overrun();
2066                     s->state = RS_IDLE;
2067                 } else if (s->line_buf_index < 1) {
2068                     /* got a repeat but we have nothing to repeat */
2069                     trace_gdbstub_err_invalid_rle();
2070                     s->state = RS_GETLINE;
2071                 } else {
2072                     /* repeat the last character */
2073                     memset(s->line_buf + s->line_buf_index,
2074                            s->line_buf[s->line_buf_index - 1], repeat);
2075                     s->line_buf_index += repeat;
2076                     s->line_sum += ch;
2077                     s->state = RS_GETLINE;
2078                 }
2079             }
2080             break;
2081         case RS_CHKSUM1:
2082             /* get high hex digit of checksum */
2083             if (!isxdigit(ch)) {
2084                 trace_gdbstub_err_checksum_invalid((uint8_t)ch);
2085                 s->state = RS_GETLINE;
2086                 break;
2087             }
2088             s->line_buf[s->line_buf_index] = '\0';
2089             s->line_csum = fromhex(ch) << 4;
2090             s->state = RS_CHKSUM2;
2091             break;
2092         case RS_CHKSUM2:
2093             /* get low hex digit of checksum */
2094             if (!isxdigit(ch)) {
2095                 trace_gdbstub_err_checksum_invalid((uint8_t)ch);
2096                 s->state = RS_GETLINE;
2097                 break;
2098             }
2099             s->line_csum |= fromhex(ch);
2100
2101             if (s->line_csum != (s->line_sum & 0xff)) {
2102                 trace_gdbstub_err_checksum_incorrect(s->line_sum, s->line_csum);
2103                 /* send NAK reply */
2104                 reply = '-';
2105                 put_buffer(s, &reply, 1);
2106                 s->state = RS_IDLE;
2107             } else {
2108                 /* send ACK reply */
2109                 reply = '+';
2110                 put_buffer(s, &reply, 1);
2111                 s->state = gdb_handle_packet(s, s->line_buf);
2112             }
2113             break;
2114         default:
2115             abort();
2116         }
2117     }
2118 }
2119
2120 /* Tell the remote gdb that the process has exited.  */
2121 void gdb_exit(CPUArchState *env, int code)
2122 {
2123   GDBState *s;
2124   char buf[4];
2125
2126   s = gdbserver_state;
2127   if (!s) {
2128       return;
2129   }
2130 #ifdef CONFIG_USER_ONLY
2131   if (gdbserver_fd < 0 || s->fd < 0) {
2132       return;
2133   }
2134 #endif
2135
2136   trace_gdbstub_op_exiting((uint8_t)code);
2137
2138   snprintf(buf, sizeof(buf), "W%02x", (uint8_t)code);
2139   put_packet(s, buf);
2140
2141 #ifndef CONFIG_USER_ONLY
2142   qemu_chr_fe_deinit(&s->chr, true);
2143 #endif
2144 }
2145
2146 /*
2147  * Create the process that will contain all the "orphan" CPUs (that are not
2148  * part of a CPU cluster). Note that if this process contains no CPUs, it won't
2149  * be attachable and thus will be invisible to the user.
2150  */
2151 static void create_default_process(GDBState *s)
2152 {
2153     GDBProcess *process;
2154     int max_pid = 0;
2155
2156     if (s->process_num) {
2157         max_pid = s->processes[s->process_num - 1].pid;
2158     }
2159
2160     s->processes = g_renew(GDBProcess, s->processes, ++s->process_num);
2161     process = &s->processes[s->process_num - 1];
2162
2163     /* We need an available PID slot for this process */
2164     assert(max_pid < UINT32_MAX);
2165
2166     process->pid = max_pid + 1;
2167     process->attached = false;
2168     process->target_xml[0] = '\0';
2169 }
2170
2171 #ifdef CONFIG_USER_ONLY
2172 int
2173 gdb_handlesig(CPUState *cpu, int sig)
2174 {
2175     GDBState *s;
2176     char buf[256];
2177     int n;
2178
2179     s = gdbserver_state;
2180     if (gdbserver_fd < 0 || s->fd < 0) {
2181         return sig;
2182     }
2183
2184     /* disable single step if it was enabled */
2185     cpu_single_step(cpu, 0);
2186     tb_flush(cpu);
2187
2188     if (sig != 0) {
2189         snprintf(buf, sizeof(buf), "S%02x", target_signal_to_gdb(sig));
2190         put_packet(s, buf);
2191     }
2192     /* put_packet() might have detected that the peer terminated the
2193        connection.  */
2194     if (s->fd < 0) {
2195         return sig;
2196     }
2197
2198     sig = 0;
2199     s->state = RS_IDLE;
2200     s->running_state = 0;
2201     while (s->running_state == 0) {
2202         n = read(s->fd, buf, 256);
2203         if (n > 0) {
2204             int i;
2205
2206             for (i = 0; i < n; i++) {
2207                 gdb_read_byte(s, buf[i]);
2208             }
2209         } else {
2210             /* XXX: Connection closed.  Should probably wait for another
2211                connection before continuing.  */
2212             if (n == 0) {
2213                 close(s->fd);
2214             }
2215             s->fd = -1;
2216             return sig;
2217         }
2218     }
2219     sig = s->signal;
2220     s->signal = 0;
2221     return sig;
2222 }
2223
2224 /* Tell the remote gdb that the process has exited due to SIG.  */
2225 void gdb_signalled(CPUArchState *env, int sig)
2226 {
2227     GDBState *s;
2228     char buf[4];
2229
2230     s = gdbserver_state;
2231     if (gdbserver_fd < 0 || s->fd < 0) {
2232         return;
2233     }
2234
2235     snprintf(buf, sizeof(buf), "X%02x", target_signal_to_gdb(sig));
2236     put_packet(s, buf);
2237 }
2238
2239 static bool gdb_accept(void)
2240 {
2241     GDBState *s;
2242     struct sockaddr_in sockaddr;
2243     socklen_t len;
2244     int fd;
2245
2246     for(;;) {
2247         len = sizeof(sockaddr);
2248         fd = accept(gdbserver_fd, (struct sockaddr *)&sockaddr, &len);
2249         if (fd < 0 && errno != EINTR) {
2250             perror("accept");
2251             return false;
2252         } else if (fd >= 0) {
2253             qemu_set_cloexec(fd);
2254             break;
2255         }
2256     }
2257
2258     /* set short latency */
2259     if (socket_set_nodelay(fd)) {
2260         perror("setsockopt");
2261         close(fd);
2262         return false;
2263     }
2264
2265     s = g_malloc0(sizeof(GDBState));
2266     create_default_process(s);
2267     s->processes[0].attached = true;
2268     s->c_cpu = gdb_first_attached_cpu(s);
2269     s->g_cpu = s->c_cpu;
2270     s->fd = fd;
2271     gdb_has_xml = false;
2272
2273     gdbserver_state = s;
2274     return true;
2275 }
2276
2277 static int gdbserver_open(int port)
2278 {
2279     struct sockaddr_in sockaddr;
2280     int fd, ret;
2281
2282     fd = socket(PF_INET, SOCK_STREAM, 0);
2283     if (fd < 0) {
2284         perror("socket");
2285         return -1;
2286     }
2287     qemu_set_cloexec(fd);
2288
2289     socket_set_fast_reuse(fd);
2290
2291     sockaddr.sin_family = AF_INET;
2292     sockaddr.sin_port = htons(port);
2293     sockaddr.sin_addr.s_addr = 0;
2294     ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
2295     if (ret < 0) {
2296         perror("bind");
2297         close(fd);
2298         return -1;
2299     }
2300     ret = listen(fd, 1);
2301     if (ret < 0) {
2302         perror("listen");
2303         close(fd);
2304         return -1;
2305     }
2306     return fd;
2307 }
2308
2309 int gdbserver_start(int port)
2310 {
2311     gdbserver_fd = gdbserver_open(port);
2312     if (gdbserver_fd < 0)
2313         return -1;
2314     /* accept connections */
2315     if (!gdb_accept()) {
2316         close(gdbserver_fd);
2317         gdbserver_fd = -1;
2318         return -1;
2319     }
2320     return 0;
2321 }
2322
2323 /* Disable gdb stub for child processes.  */
2324 void gdbserver_fork(CPUState *cpu)
2325 {
2326     GDBState *s = gdbserver_state;
2327
2328     if (gdbserver_fd < 0 || s->fd < 0) {
2329         return;
2330     }
2331     close(s->fd);
2332     s->fd = -1;
2333     cpu_breakpoint_remove_all(cpu, BP_GDB);
2334     cpu_watchpoint_remove_all(cpu, BP_GDB);
2335 }
2336 #else
2337 static int gdb_chr_can_receive(void *opaque)
2338 {
2339   /* We can handle an arbitrarily large amount of data.
2340    Pick the maximum packet size, which is as good as anything.  */
2341   return MAX_PACKET_LENGTH;
2342 }
2343
2344 static void gdb_chr_receive(void *opaque, const uint8_t *buf, int size)
2345 {
2346     int i;
2347
2348     for (i = 0; i < size; i++) {
2349         gdb_read_byte(gdbserver_state, buf[i]);
2350     }
2351 }
2352
2353 static void gdb_chr_event(void *opaque, int event)
2354 {
2355     int i;
2356     GDBState *s = (GDBState *) opaque;
2357
2358     switch (event) {
2359     case CHR_EVENT_OPENED:
2360         /* Start with first process attached, others detached */
2361         for (i = 0; i < s->process_num; i++) {
2362             s->processes[i].attached = !i;
2363         }
2364
2365         s->c_cpu = gdb_first_attached_cpu(s);
2366         s->g_cpu = s->c_cpu;
2367
2368         vm_stop(RUN_STATE_PAUSED);
2369         gdb_has_xml = false;
2370         break;
2371     default:
2372         break;
2373     }
2374 }
2375
2376 static void gdb_monitor_output(GDBState *s, const char *msg, int len)
2377 {
2378     char buf[MAX_PACKET_LENGTH];
2379
2380     buf[0] = 'O';
2381     if (len > (MAX_PACKET_LENGTH/2) - 1)
2382         len = (MAX_PACKET_LENGTH/2) - 1;
2383     memtohex(buf + 1, (uint8_t *)msg, len);
2384     put_packet(s, buf);
2385 }
2386
2387 static int gdb_monitor_write(Chardev *chr, const uint8_t *buf, int len)
2388 {
2389     const char *p = (const char *)buf;
2390     int max_sz;
2391
2392     max_sz = (sizeof(gdbserver_state->last_packet) - 2) / 2;
2393     for (;;) {
2394         if (len <= max_sz) {
2395             gdb_monitor_output(gdbserver_state, p, len);
2396             break;
2397         }
2398         gdb_monitor_output(gdbserver_state, p, max_sz);
2399         p += max_sz;
2400         len -= max_sz;
2401     }
2402     return len;
2403 }
2404
2405 #ifndef _WIN32
2406 static void gdb_sigterm_handler(int signal)
2407 {
2408     if (runstate_is_running()) {
2409         vm_stop(RUN_STATE_PAUSED);
2410     }
2411 }
2412 #endif
2413
2414 static void gdb_monitor_open(Chardev *chr, ChardevBackend *backend,
2415                              bool *be_opened, Error **errp)
2416 {
2417     *be_opened = false;
2418 }
2419
2420 static void char_gdb_class_init(ObjectClass *oc, void *data)
2421 {
2422     ChardevClass *cc = CHARDEV_CLASS(oc);
2423
2424     cc->internal = true;
2425     cc->open = gdb_monitor_open;
2426     cc->chr_write = gdb_monitor_write;
2427 }
2428
2429 #define TYPE_CHARDEV_GDB "chardev-gdb"
2430
2431 static const TypeInfo char_gdb_type_info = {
2432     .name = TYPE_CHARDEV_GDB,
2433     .parent = TYPE_CHARDEV,
2434     .class_init = char_gdb_class_init,
2435 };
2436
2437 static int find_cpu_clusters(Object *child, void *opaque)
2438 {
2439     if (object_dynamic_cast(child, TYPE_CPU_CLUSTER)) {
2440         GDBState *s = (GDBState *) opaque;
2441         CPUClusterState *cluster = CPU_CLUSTER(child);
2442         GDBProcess *process;
2443
2444         s->processes = g_renew(GDBProcess, s->processes, ++s->process_num);
2445
2446         process = &s->processes[s->process_num - 1];
2447
2448         /*
2449          * GDB process IDs -1 and 0 are reserved. To avoid subtle errors at
2450          * runtime, we enforce here that the machine does not use a cluster ID
2451          * that would lead to PID 0.
2452          */
2453         assert(cluster->cluster_id != UINT32_MAX);
2454         process->pid = cluster->cluster_id + 1;
2455         process->attached = false;
2456         process->target_xml[0] = '\0';
2457
2458         return 0;
2459     }
2460
2461     return object_child_foreach(child, find_cpu_clusters, opaque);
2462 }
2463
2464 static int pid_order(const void *a, const void *b)
2465 {
2466     GDBProcess *pa = (GDBProcess *) a;
2467     GDBProcess *pb = (GDBProcess *) b;
2468
2469     if (pa->pid < pb->pid) {
2470         return -1;
2471     } else if (pa->pid > pb->pid) {
2472         return 1;
2473     } else {
2474         return 0;
2475     }
2476 }
2477
2478 static void create_processes(GDBState *s)
2479 {
2480     object_child_foreach(object_get_root(), find_cpu_clusters, s);
2481
2482     if (s->processes) {
2483         /* Sort by PID */
2484         qsort(s->processes, s->process_num, sizeof(s->processes[0]), pid_order);
2485     }
2486
2487     create_default_process(s);
2488 }
2489
2490 static void cleanup_processes(GDBState *s)
2491 {
2492     g_free(s->processes);
2493     s->process_num = 0;
2494     s->processes = NULL;
2495 }
2496
2497 int gdbserver_start(const char *device)
2498 {
2499     trace_gdbstub_op_start(device);
2500
2501     GDBState *s;
2502     char gdbstub_device_name[128];
2503     Chardev *chr = NULL;
2504     Chardev *mon_chr;
2505
2506     if (!first_cpu) {
2507         error_report("gdbstub: meaningless to attach gdb to a "
2508                      "machine without any CPU.");
2509         return -1;
2510     }
2511
2512     if (!device)
2513         return -1;
2514     if (strcmp(device, "none") != 0) {
2515         if (strstart(device, "tcp:", NULL)) {
2516             /* enforce required TCP attributes */
2517             snprintf(gdbstub_device_name, sizeof(gdbstub_device_name),
2518                      "%s,nowait,nodelay,server", device);
2519             device = gdbstub_device_name;
2520         }
2521 #ifndef _WIN32
2522         else if (strcmp(device, "stdio") == 0) {
2523             struct sigaction act;
2524
2525             memset(&act, 0, sizeof(act));
2526             act.sa_handler = gdb_sigterm_handler;
2527             sigaction(SIGINT, &act, NULL);
2528         }
2529 #endif
2530         /*
2531          * FIXME: it's a bit weird to allow using a mux chardev here
2532          * and implicitly setup a monitor. We may want to break this.
2533          */
2534         chr = qemu_chr_new_noreplay("gdb", device, true);
2535         if (!chr)
2536             return -1;
2537     }
2538
2539     s = gdbserver_state;
2540     if (!s) {
2541         s = g_malloc0(sizeof(GDBState));
2542         gdbserver_state = s;
2543
2544         qemu_add_vm_change_state_handler(gdb_vm_state_change, NULL);
2545
2546         /* Initialize a monitor terminal for gdb */
2547         mon_chr = qemu_chardev_new(NULL, TYPE_CHARDEV_GDB,
2548                                    NULL, &error_abort);
2549         monitor_init(mon_chr, 0);
2550     } else {
2551         qemu_chr_fe_deinit(&s->chr, true);
2552         mon_chr = s->mon_chr;
2553         cleanup_processes(s);
2554         memset(s, 0, sizeof(GDBState));
2555         s->mon_chr = mon_chr;
2556     }
2557
2558     create_processes(s);
2559
2560     if (chr) {
2561         qemu_chr_fe_init(&s->chr, chr, &error_abort);
2562         qemu_chr_fe_set_handlers(&s->chr, gdb_chr_can_receive, gdb_chr_receive,
2563                                  gdb_chr_event, NULL, s, NULL, true);
2564     }
2565     s->state = chr ? RS_IDLE : RS_INACTIVE;
2566     s->mon_chr = mon_chr;
2567     s->current_syscall_cb = NULL;
2568
2569     return 0;
2570 }
2571
2572 void gdbserver_cleanup(void)
2573 {
2574     if (gdbserver_state) {
2575         put_packet(gdbserver_state, "W00");
2576     }
2577 }
2578
2579 static void register_types(void)
2580 {
2581     type_register_static(&char_gdb_type_info);
2582 }
2583
2584 type_init(register_types);
2585 #endif
This page took 0.161178 seconds and 4 git commands to generate.