gdbserver: Remove duplicate functions to find any thread of process
[deliverable/binutils-gdb.git] / gdb / gdbserver / server.c
1 /* Main code for remote server for GDB.
2 Copyright (C) 1989-2017 Free Software Foundation, Inc.
3
4 This file is part of GDB.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
10
11 This program 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
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
18
19 #include "server.h"
20 #include "gdbthread.h"
21 #include "agent.h"
22 #include "notif.h"
23 #include "tdesc.h"
24 #include "rsp-low.h"
25 #include "signals-state-save-restore.h"
26 #include <ctype.h>
27 #include <unistd.h>
28 #if HAVE_SIGNAL_H
29 #include <signal.h>
30 #endif
31 #include "gdb_vecs.h"
32 #include "gdb_wait.h"
33 #include "btrace-common.h"
34 #include "filestuff.h"
35 #include "tracepoint.h"
36 #include "dll.h"
37 #include "hostio.h"
38 #include <vector>
39 #include "common-inferior.h"
40 #include "job-control.h"
41 #include "environ.h"
42
43 #include "common/selftest.h"
44
45 /* The environment to pass to the inferior when creating it. */
46
47 static gdb_environ our_environ;
48
49 /* Start the inferior using a shell. */
50
51 /* We always try to start the inferior using a shell. */
52
53 int startup_with_shell = 1;
54
55 /* The thread set with an `Hc' packet. `Hc' is deprecated in favor of
56 `vCont'. Note the multi-process extensions made `vCont' a
57 requirement, so `Hc pPID.TID' is pretty much undefined. So
58 CONT_THREAD can be null_ptid for no `Hc' thread, minus_one_ptid for
59 resuming all threads of the process (again, `Hc' isn't used for
60 multi-process), or a specific thread ptid_t. */
61 ptid_t cont_thread;
62
63 /* The thread set with an `Hg' packet. */
64 ptid_t general_thread;
65
66 int server_waiting;
67
68 static int extended_protocol;
69 static int response_needed;
70 static int exit_requested;
71
72 /* --once: Exit after the first connection has closed. */
73 int run_once;
74
75 int multi_process;
76 int report_fork_events;
77 int report_vfork_events;
78 int report_exec_events;
79 int report_thread_events;
80
81 /* Whether to report TARGET_WAITKING_NO_RESUMED events. */
82 static int report_no_resumed;
83
84 int non_stop;
85 int swbreak_feature;
86 int hwbreak_feature;
87
88 /* True if the "vContSupported" feature is active. In that case, GDB
89 wants us to report whether single step is supported in the reply to
90 "vCont?" packet. */
91 static int vCont_supported;
92
93 /* Whether we should attempt to disable the operating system's address
94 space randomization feature before starting an inferior. */
95 int disable_randomization = 1;
96
97 static char *program_name = NULL;
98 static std::vector<char *> program_args;
99 static std::string wrapper_argv;
100
101 int pass_signals[GDB_SIGNAL_LAST];
102 int program_signals[GDB_SIGNAL_LAST];
103 int program_signals_p;
104
105 /* The PID of the originally created or attached inferior. Used to
106 send signals to the process when GDB sends us an asynchronous interrupt
107 (user hitting Control-C in the client), and to wait for the child to exit
108 when no longer debugging it. */
109
110 unsigned long signal_pid;
111
112 /* Set if you want to disable optional thread related packets support
113 in gdbserver, for the sake of testing GDB against stubs that don't
114 support them. */
115 int disable_packet_vCont;
116 int disable_packet_Tthread;
117 int disable_packet_qC;
118 int disable_packet_qfThreadInfo;
119
120 /* Last status reported to GDB. */
121 struct target_waitstatus last_status;
122 ptid_t last_ptid;
123
124 char *own_buf;
125 static unsigned char *mem_buf;
126
127 /* A sub-class of 'struct notif_event' for stop, holding information
128 relative to a single stop reply. We keep a queue of these to
129 push to GDB in non-stop mode. */
130
131 struct vstop_notif
132 {
133 struct notif_event base;
134
135 /* Thread or process that got the event. */
136 ptid_t ptid;
137
138 /* Event info. */
139 struct target_waitstatus status;
140 };
141
142 /* The current btrace configuration. This is gdbserver's mirror of GDB's
143 btrace configuration. */
144 static struct btrace_config current_btrace_conf;
145
146 DEFINE_QUEUE_P (notif_event_p);
147
148 /* Put a stop reply to the stop reply queue. */
149
150 static void
151 queue_stop_reply (ptid_t ptid, struct target_waitstatus *status)
152 {
153 struct vstop_notif *new_notif = XNEW (struct vstop_notif);
154
155 new_notif->ptid = ptid;
156 new_notif->status = *status;
157
158 notif_event_enque (&notif_stop, (struct notif_event *) new_notif);
159 }
160
161 static int
162 remove_all_on_match_ptid (QUEUE (notif_event_p) *q,
163 QUEUE_ITER (notif_event_p) *iter,
164 struct notif_event *event,
165 void *data)
166 {
167 ptid_t filter_ptid = *(ptid_t *) data;
168 struct vstop_notif *vstop_event = (struct vstop_notif *) event;
169
170 if (ptid_match (vstop_event->ptid, filter_ptid))
171 {
172 if (q->free_func != NULL)
173 q->free_func (event);
174
175 QUEUE_remove_elem (notif_event_p, q, iter);
176 }
177
178 return 1;
179 }
180
181 /* See server.h. */
182
183 void
184 discard_queued_stop_replies (ptid_t ptid)
185 {
186 QUEUE_iterate (notif_event_p, notif_stop.queue,
187 remove_all_on_match_ptid, &ptid);
188 }
189
190 static void
191 vstop_notif_reply (struct notif_event *event, char *own_buf)
192 {
193 struct vstop_notif *vstop = (struct vstop_notif *) event;
194
195 prepare_resume_reply (own_buf, vstop->ptid, &vstop->status);
196 }
197
198 /* QUEUE_iterate callback helper for in_queued_stop_replies. */
199
200 static int
201 in_queued_stop_replies_ptid (QUEUE (notif_event_p) *q,
202 QUEUE_ITER (notif_event_p) *iter,
203 struct notif_event *event,
204 void *data)
205 {
206 ptid_t filter_ptid = *(ptid_t *) data;
207 struct vstop_notif *vstop_event = (struct vstop_notif *) event;
208
209 if (ptid_match (vstop_event->ptid, filter_ptid))
210 return 0;
211
212 /* Don't resume fork children that GDB does not know about yet. */
213 if ((vstop_event->status.kind == TARGET_WAITKIND_FORKED
214 || vstop_event->status.kind == TARGET_WAITKIND_VFORKED)
215 && ptid_match (vstop_event->status.value.related_pid, filter_ptid))
216 return 0;
217
218 return 1;
219 }
220
221 /* See server.h. */
222
223 int
224 in_queued_stop_replies (ptid_t ptid)
225 {
226 return !QUEUE_iterate (notif_event_p, notif_stop.queue,
227 in_queued_stop_replies_ptid, &ptid);
228 }
229
230 struct notif_server notif_stop =
231 {
232 "vStopped", "Stop", NULL, vstop_notif_reply,
233 };
234
235 static int
236 target_running (void)
237 {
238 return get_first_thread () != NULL;
239 }
240
241 /* See common/common-inferior.h. */
242
243 const char *
244 get_exec_wrapper ()
245 {
246 return !wrapper_argv.empty () ? wrapper_argv.c_str () : NULL;
247 }
248
249 /* See common/common-inferior.h. */
250
251 char *
252 get_exec_file (int err)
253 {
254 if (err && program_name == NULL)
255 error (_("No executable file specified."));
256
257 return program_name;
258 }
259
260 /* See server.h. */
261
262 gdb_environ *
263 get_environ ()
264 {
265 return &our_environ;
266 }
267
268 static int
269 attach_inferior (int pid)
270 {
271 /* myattach should return -1 if attaching is unsupported,
272 0 if it succeeded, and call error() otherwise. */
273
274 if (myattach (pid) != 0)
275 return -1;
276
277 fprintf (stderr, "Attached; pid = %d\n", pid);
278 fflush (stderr);
279
280 /* FIXME - It may be that we should get the SIGNAL_PID from the
281 attach function, so that it can be the main thread instead of
282 whichever we were told to attach to. */
283 signal_pid = pid;
284
285 if (!non_stop)
286 {
287 last_ptid = mywait (pid_to_ptid (pid), &last_status, 0, 0);
288
289 /* GDB knows to ignore the first SIGSTOP after attaching to a running
290 process using the "attach" command, but this is different; it's
291 just using "target remote". Pretend it's just starting up. */
292 if (last_status.kind == TARGET_WAITKIND_STOPPED
293 && last_status.value.sig == GDB_SIGNAL_STOP)
294 last_status.value.sig = GDB_SIGNAL_TRAP;
295
296 current_thread->last_resume_kind = resume_stop;
297 current_thread->last_status = last_status;
298 }
299
300 return 0;
301 }
302
303 extern int remote_debug;
304
305 /* Decode a qXfer read request. Return 0 if everything looks OK,
306 or -1 otherwise. */
307
308 static int
309 decode_xfer_read (char *buf, CORE_ADDR *ofs, unsigned int *len)
310 {
311 /* After the read marker and annex, qXfer looks like a
312 traditional 'm' packet. */
313 decode_m_packet (buf, ofs, len);
314
315 return 0;
316 }
317
318 static int
319 decode_xfer (char *buf, char **object, char **rw, char **annex, char **offset)
320 {
321 /* Extract and NUL-terminate the object. */
322 *object = buf;
323 while (*buf && *buf != ':')
324 buf++;
325 if (*buf == '\0')
326 return -1;
327 *buf++ = 0;
328
329 /* Extract and NUL-terminate the read/write action. */
330 *rw = buf;
331 while (*buf && *buf != ':')
332 buf++;
333 if (*buf == '\0')
334 return -1;
335 *buf++ = 0;
336
337 /* Extract and NUL-terminate the annex. */
338 *annex = buf;
339 while (*buf && *buf != ':')
340 buf++;
341 if (*buf == '\0')
342 return -1;
343 *buf++ = 0;
344
345 *offset = buf;
346 return 0;
347 }
348
349 /* Write the response to a successful qXfer read. Returns the
350 length of the (binary) data stored in BUF, corresponding
351 to as much of DATA/LEN as we could fit. IS_MORE controls
352 the first character of the response. */
353 static int
354 write_qxfer_response (char *buf, const gdb_byte *data, int len, int is_more)
355 {
356 int out_len;
357
358 if (is_more)
359 buf[0] = 'm';
360 else
361 buf[0] = 'l';
362
363 return remote_escape_output (data, len, 1, (unsigned char *) buf + 1,
364 &out_len, PBUFSIZ - 2) + 1;
365 }
366
367 /* Handle btrace enabling in BTS format. */
368
369 static const char *
370 handle_btrace_enable_bts (struct thread_info *thread)
371 {
372 if (thread->btrace != NULL)
373 return "E.Btrace already enabled.";
374
375 current_btrace_conf.format = BTRACE_FORMAT_BTS;
376 thread->btrace = target_enable_btrace (thread->entry.id,
377 &current_btrace_conf);
378 if (thread->btrace == NULL)
379 return "E.Could not enable btrace.";
380
381 return NULL;
382 }
383
384 /* Handle btrace enabling in Intel Processor Trace format. */
385
386 static const char *
387 handle_btrace_enable_pt (struct thread_info *thread)
388 {
389 if (thread->btrace != NULL)
390 return "E.Btrace already enabled.";
391
392 current_btrace_conf.format = BTRACE_FORMAT_PT;
393 thread->btrace = target_enable_btrace (thread->entry.id,
394 &current_btrace_conf);
395 if (thread->btrace == NULL)
396 return "E.Could not enable btrace.";
397
398 return NULL;
399 }
400
401 /* Handle btrace disabling. */
402
403 static const char *
404 handle_btrace_disable (struct thread_info *thread)
405 {
406
407 if (thread->btrace == NULL)
408 return "E.Branch tracing not enabled.";
409
410 if (target_disable_btrace (thread->btrace) != 0)
411 return "E.Could not disable branch tracing.";
412
413 thread->btrace = NULL;
414 return NULL;
415 }
416
417 /* Handle the "Qbtrace" packet. */
418
419 static int
420 handle_btrace_general_set (char *own_buf)
421 {
422 struct thread_info *thread;
423 const char *err;
424 char *op;
425
426 if (!startswith (own_buf, "Qbtrace:"))
427 return 0;
428
429 op = own_buf + strlen ("Qbtrace:");
430
431 if (ptid_equal (general_thread, null_ptid)
432 || ptid_equal (general_thread, minus_one_ptid))
433 {
434 strcpy (own_buf, "E.Must select a single thread.");
435 return -1;
436 }
437
438 thread = find_thread_ptid (general_thread);
439 if (thread == NULL)
440 {
441 strcpy (own_buf, "E.No such thread.");
442 return -1;
443 }
444
445 err = NULL;
446
447 if (strcmp (op, "bts") == 0)
448 err = handle_btrace_enable_bts (thread);
449 else if (strcmp (op, "pt") == 0)
450 err = handle_btrace_enable_pt (thread);
451 else if (strcmp (op, "off") == 0)
452 err = handle_btrace_disable (thread);
453 else
454 err = "E.Bad Qbtrace operation. Use bts, pt, or off.";
455
456 if (err != 0)
457 strcpy (own_buf, err);
458 else
459 write_ok (own_buf);
460
461 return 1;
462 }
463
464 /* Handle the "Qbtrace-conf" packet. */
465
466 static int
467 handle_btrace_conf_general_set (char *own_buf)
468 {
469 struct thread_info *thread;
470 char *op;
471
472 if (!startswith (own_buf, "Qbtrace-conf:"))
473 return 0;
474
475 op = own_buf + strlen ("Qbtrace-conf:");
476
477 if (ptid_equal (general_thread, null_ptid)
478 || ptid_equal (general_thread, minus_one_ptid))
479 {
480 strcpy (own_buf, "E.Must select a single thread.");
481 return -1;
482 }
483
484 thread = find_thread_ptid (general_thread);
485 if (thread == NULL)
486 {
487 strcpy (own_buf, "E.No such thread.");
488 return -1;
489 }
490
491 if (startswith (op, "bts:size="))
492 {
493 unsigned long size;
494 char *endp = NULL;
495
496 errno = 0;
497 size = strtoul (op + strlen ("bts:size="), &endp, 16);
498 if (endp == NULL || *endp != 0 || errno != 0 || size > UINT_MAX)
499 {
500 strcpy (own_buf, "E.Bad size value.");
501 return -1;
502 }
503
504 current_btrace_conf.bts.size = (unsigned int) size;
505 }
506 else if (strncmp (op, "pt:size=", strlen ("pt:size=")) == 0)
507 {
508 unsigned long size;
509 char *endp = NULL;
510
511 errno = 0;
512 size = strtoul (op + strlen ("pt:size="), &endp, 16);
513 if (endp == NULL || *endp != 0 || errno != 0 || size > UINT_MAX)
514 {
515 strcpy (own_buf, "E.Bad size value.");
516 return -1;
517 }
518
519 current_btrace_conf.pt.size = (unsigned int) size;
520 }
521 else
522 {
523 strcpy (own_buf, "E.Bad Qbtrace configuration option.");
524 return -1;
525 }
526
527 write_ok (own_buf);
528 return 1;
529 }
530
531 /* Handle all of the extended 'Q' packets. */
532
533 static void
534 handle_general_set (char *own_buf)
535 {
536 if (startswith (own_buf, "QPassSignals:"))
537 {
538 int numsigs = (int) GDB_SIGNAL_LAST, i;
539 const char *p = own_buf + strlen ("QPassSignals:");
540 CORE_ADDR cursig;
541
542 p = decode_address_to_semicolon (&cursig, p);
543 for (i = 0; i < numsigs; i++)
544 {
545 if (i == cursig)
546 {
547 pass_signals[i] = 1;
548 if (*p == '\0')
549 /* Keep looping, to clear the remaining signals. */
550 cursig = -1;
551 else
552 p = decode_address_to_semicolon (&cursig, p);
553 }
554 else
555 pass_signals[i] = 0;
556 }
557 strcpy (own_buf, "OK");
558 return;
559 }
560
561 if (startswith (own_buf, "QProgramSignals:"))
562 {
563 int numsigs = (int) GDB_SIGNAL_LAST, i;
564 const char *p = own_buf + strlen ("QProgramSignals:");
565 CORE_ADDR cursig;
566
567 program_signals_p = 1;
568
569 p = decode_address_to_semicolon (&cursig, p);
570 for (i = 0; i < numsigs; i++)
571 {
572 if (i == cursig)
573 {
574 program_signals[i] = 1;
575 if (*p == '\0')
576 /* Keep looping, to clear the remaining signals. */
577 cursig = -1;
578 else
579 p = decode_address_to_semicolon (&cursig, p);
580 }
581 else
582 program_signals[i] = 0;
583 }
584 strcpy (own_buf, "OK");
585 return;
586 }
587
588 if (startswith (own_buf, "QCatchSyscalls:"))
589 {
590 const char *p = own_buf + sizeof ("QCatchSyscalls:") - 1;
591 int enabled = -1;
592 CORE_ADDR sysno;
593 struct process_info *process;
594
595 if (!target_running () || !target_supports_catch_syscall ())
596 {
597 write_enn (own_buf);
598 return;
599 }
600
601 if (strcmp (p, "0") == 0)
602 enabled = 0;
603 else if (p[0] == '1' && (p[1] == ';' || p[1] == '\0'))
604 enabled = 1;
605 else
606 {
607 fprintf (stderr, "Unknown catch-syscalls mode requested: %s\n",
608 own_buf);
609 write_enn (own_buf);
610 return;
611 }
612
613 process = current_process ();
614 VEC_truncate (int, process->syscalls_to_catch, 0);
615
616 if (enabled)
617 {
618 p += 1;
619 if (*p == ';')
620 {
621 p += 1;
622 while (*p != '\0')
623 {
624 p = decode_address_to_semicolon (&sysno, p);
625 VEC_safe_push (int, process->syscalls_to_catch, (int) sysno);
626 }
627 }
628 else
629 VEC_safe_push (int, process->syscalls_to_catch, ANY_SYSCALL);
630 }
631
632 write_ok (own_buf);
633 return;
634 }
635
636 if (strcmp (own_buf, "QEnvironmentReset") == 0)
637 {
638 our_environ = gdb_environ::from_host_environ ();
639
640 write_ok (own_buf);
641 return;
642 }
643
644 if (startswith (own_buf, "QEnvironmentHexEncoded:"))
645 {
646 const char *p = own_buf + sizeof ("QEnvironmentHexEncoded:") - 1;
647 /* The final form of the environment variable. FINAL_VAR will
648 hold the 'VAR=VALUE' format. */
649 std::string final_var = hex2str (p);
650 std::string var_name, var_value;
651
652 if (remote_debug)
653 {
654 debug_printf (_("[QEnvironmentHexEncoded received '%s']\n"), p);
655 debug_printf (_("[Environment variable to be set: '%s']\n"),
656 final_var.c_str ());
657 debug_flush ();
658 }
659
660 size_t pos = final_var.find ('=');
661 if (pos == std::string::npos)
662 {
663 warning (_("Unexpected format for environment variable: '%s'"),
664 final_var.c_str ());
665 write_enn (own_buf);
666 return;
667 }
668
669 var_name = final_var.substr (0, pos);
670 var_value = final_var.substr (pos + 1, std::string::npos);
671
672 our_environ.set (var_name.c_str (), var_value.c_str ());
673
674 write_ok (own_buf);
675 return;
676 }
677
678 if (startswith (own_buf, "QEnvironmentUnset:"))
679 {
680 const char *p = own_buf + sizeof ("QEnvironmentUnset:") - 1;
681 std::string varname = hex2str (p);
682
683 if (remote_debug)
684 {
685 debug_printf (_("[QEnvironmentUnset received '%s']\n"), p);
686 debug_printf (_("[Environment variable to be unset: '%s']\n"),
687 varname.c_str ());
688 debug_flush ();
689 }
690
691 our_environ.unset (varname.c_str ());
692
693 write_ok (own_buf);
694 return;
695 }
696
697 if (strcmp (own_buf, "QStartNoAckMode") == 0)
698 {
699 if (remote_debug)
700 {
701 debug_printf ("[noack mode enabled]\n");
702 debug_flush ();
703 }
704
705 noack_mode = 1;
706 write_ok (own_buf);
707 return;
708 }
709
710 if (startswith (own_buf, "QNonStop:"))
711 {
712 char *mode = own_buf + 9;
713 int req = -1;
714 const char *req_str;
715
716 if (strcmp (mode, "0") == 0)
717 req = 0;
718 else if (strcmp (mode, "1") == 0)
719 req = 1;
720 else
721 {
722 /* We don't know what this mode is, so complain to
723 GDB. */
724 fprintf (stderr, "Unknown non-stop mode requested: %s\n",
725 own_buf);
726 write_enn (own_buf);
727 return;
728 }
729
730 req_str = req ? "non-stop" : "all-stop";
731 if (start_non_stop (req) != 0)
732 {
733 fprintf (stderr, "Setting %s mode failed\n", req_str);
734 write_enn (own_buf);
735 return;
736 }
737
738 non_stop = req;
739
740 if (remote_debug)
741 debug_printf ("[%s mode enabled]\n", req_str);
742
743 write_ok (own_buf);
744 return;
745 }
746
747 if (startswith (own_buf, "QDisableRandomization:"))
748 {
749 char *packet = own_buf + strlen ("QDisableRandomization:");
750 ULONGEST setting;
751
752 unpack_varlen_hex (packet, &setting);
753 disable_randomization = setting;
754
755 if (remote_debug)
756 {
757 debug_printf (disable_randomization
758 ? "[address space randomization disabled]\n"
759 : "[address space randomization enabled]\n");
760 }
761
762 write_ok (own_buf);
763 return;
764 }
765
766 if (target_supports_tracepoints ()
767 && handle_tracepoint_general_set (own_buf))
768 return;
769
770 if (startswith (own_buf, "QAgent:"))
771 {
772 char *mode = own_buf + strlen ("QAgent:");
773 int req = 0;
774
775 if (strcmp (mode, "0") == 0)
776 req = 0;
777 else if (strcmp (mode, "1") == 0)
778 req = 1;
779 else
780 {
781 /* We don't know what this value is, so complain to GDB. */
782 sprintf (own_buf, "E.Unknown QAgent value");
783 return;
784 }
785
786 /* Update the flag. */
787 use_agent = req;
788 if (remote_debug)
789 debug_printf ("[%s agent]\n", req ? "Enable" : "Disable");
790 write_ok (own_buf);
791 return;
792 }
793
794 if (handle_btrace_general_set (own_buf))
795 return;
796
797 if (handle_btrace_conf_general_set (own_buf))
798 return;
799
800 if (startswith (own_buf, "QThreadEvents:"))
801 {
802 char *mode = own_buf + strlen ("QThreadEvents:");
803 enum tribool req = TRIBOOL_UNKNOWN;
804
805 if (strcmp (mode, "0") == 0)
806 req = TRIBOOL_FALSE;
807 else if (strcmp (mode, "1") == 0)
808 req = TRIBOOL_TRUE;
809 else
810 {
811 char *mode_copy = xstrdup (mode);
812
813 /* We don't know what this mode is, so complain to GDB. */
814 sprintf (own_buf, "E.Unknown thread-events mode requested: %s\n",
815 mode_copy);
816 xfree (mode_copy);
817 return;
818 }
819
820 report_thread_events = (req == TRIBOOL_TRUE);
821
822 if (remote_debug)
823 {
824 const char *req_str = report_thread_events ? "enabled" : "disabled";
825
826 debug_printf ("[thread events are now %s]\n", req_str);
827 }
828
829 write_ok (own_buf);
830 return;
831 }
832
833 if (startswith (own_buf, "QStartupWithShell:"))
834 {
835 const char *value = own_buf + strlen ("QStartupWithShell:");
836
837 if (strcmp (value, "1") == 0)
838 startup_with_shell = true;
839 else if (strcmp (value, "0") == 0)
840 startup_with_shell = false;
841 else
842 {
843 /* Unknown value. */
844 fprintf (stderr, "Unknown value to startup-with-shell: %s\n",
845 own_buf);
846 write_enn (own_buf);
847 return;
848 }
849
850 if (remote_debug)
851 debug_printf (_("[Inferior will %s started with shell]"),
852 startup_with_shell ? "be" : "not be");
853
854 write_ok (own_buf);
855 return;
856 }
857
858 /* Otherwise we didn't know what packet it was. Say we didn't
859 understand it. */
860 own_buf[0] = 0;
861 }
862
863 static const char *
864 get_features_xml (const char *annex)
865 {
866 const struct target_desc *desc = current_target_desc ();
867
868 /* `desc->xmltarget' defines what to return when looking for the
869 "target.xml" file. Its contents can either be verbatim XML code
870 (prefixed with a '@') or else the name of the actual XML file to
871 be used in place of "target.xml".
872
873 This variable is set up from the auto-generated
874 init_registers_... routine for the current target. */
875
876 if (strcmp (annex, "target.xml") == 0)
877 {
878 const char *ret = tdesc_get_features_xml ((target_desc*) desc);
879
880 if (*ret == '@')
881 return ret + 1;
882 else
883 annex = ret;
884 }
885
886 #ifdef USE_XML
887 {
888 extern const char *const xml_builtin[][2];
889 int i;
890
891 /* Look for the annex. */
892 for (i = 0; xml_builtin[i][0] != NULL; i++)
893 if (strcmp (annex, xml_builtin[i][0]) == 0)
894 break;
895
896 if (xml_builtin[i][0] != NULL)
897 return xml_builtin[i][1];
898 }
899 #endif
900
901 return NULL;
902 }
903
904 static void
905 monitor_show_help (void)
906 {
907 monitor_output ("The following monitor commands are supported:\n");
908 monitor_output (" set debug <0|1>\n");
909 monitor_output (" Enable general debugging messages\n");
910 monitor_output (" set debug-hw-points <0|1>\n");
911 monitor_output (" Enable h/w breakpoint/watchpoint debugging messages\n");
912 monitor_output (" set remote-debug <0|1>\n");
913 monitor_output (" Enable remote protocol debugging messages\n");
914 monitor_output (" set debug-format option1[,option2,...]\n");
915 monitor_output (" Add additional information to debugging messages\n");
916 monitor_output (" Options: all, none");
917 monitor_output (", timestamp");
918 monitor_output ("\n");
919 monitor_output (" exit\n");
920 monitor_output (" Quit GDBserver\n");
921 }
922
923 /* Read trace frame or inferior memory. Returns the number of bytes
924 actually read, zero when no further transfer is possible, and -1 on
925 error. Return of a positive value smaller than LEN does not
926 indicate there's no more to be read, only the end of the transfer.
927 E.g., when GDB reads memory from a traceframe, a first request may
928 be served from a memory block that does not cover the whole request
929 length. A following request gets the rest served from either
930 another block (of the same traceframe) or from the read-only
931 regions. */
932
933 static int
934 gdb_read_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
935 {
936 int res;
937
938 if (current_traceframe >= 0)
939 {
940 ULONGEST nbytes;
941 ULONGEST length = len;
942
943 if (traceframe_read_mem (current_traceframe,
944 memaddr, myaddr, len, &nbytes))
945 return -1;
946 /* Data read from trace buffer, we're done. */
947 if (nbytes > 0)
948 return nbytes;
949 if (!in_readonly_region (memaddr, length))
950 return -1;
951 /* Otherwise we have a valid readonly case, fall through. */
952 /* (assume no half-trace half-real blocks for now) */
953 }
954
955 res = prepare_to_access_memory ();
956 if (res == 0)
957 {
958 if (set_desired_thread (1))
959 res = read_inferior_memory (memaddr, myaddr, len);
960 else
961 res = 1;
962 done_accessing_memory ();
963
964 return res == 0 ? len : -1;
965 }
966 else
967 return -1;
968 }
969
970 /* Write trace frame or inferior memory. Actually, writing to trace
971 frames is forbidden. */
972
973 static int
974 gdb_write_memory (CORE_ADDR memaddr, const unsigned char *myaddr, int len)
975 {
976 if (current_traceframe >= 0)
977 return EIO;
978 else
979 {
980 int ret;
981
982 ret = prepare_to_access_memory ();
983 if (ret == 0)
984 {
985 if (set_desired_thread (1))
986 ret = write_inferior_memory (memaddr, myaddr, len);
987 else
988 ret = EIO;
989 done_accessing_memory ();
990 }
991 return ret;
992 }
993 }
994
995 /* Subroutine of handle_search_memory to simplify it. */
996
997 static int
998 handle_search_memory_1 (CORE_ADDR start_addr, CORE_ADDR search_space_len,
999 gdb_byte *pattern, unsigned pattern_len,
1000 gdb_byte *search_buf,
1001 unsigned chunk_size, unsigned search_buf_size,
1002 CORE_ADDR *found_addrp)
1003 {
1004 /* Prime the search buffer. */
1005
1006 if (gdb_read_memory (start_addr, search_buf, search_buf_size)
1007 != search_buf_size)
1008 {
1009 warning ("Unable to access %ld bytes of target "
1010 "memory at 0x%lx, halting search.",
1011 (long) search_buf_size, (long) start_addr);
1012 return -1;
1013 }
1014
1015 /* Perform the search.
1016
1017 The loop is kept simple by allocating [N + pattern-length - 1] bytes.
1018 When we've scanned N bytes we copy the trailing bytes to the start and
1019 read in another N bytes. */
1020
1021 while (search_space_len >= pattern_len)
1022 {
1023 gdb_byte *found_ptr;
1024 unsigned nr_search_bytes = (search_space_len < search_buf_size
1025 ? search_space_len
1026 : search_buf_size);
1027
1028 found_ptr = (gdb_byte *) memmem (search_buf, nr_search_bytes, pattern,
1029 pattern_len);
1030
1031 if (found_ptr != NULL)
1032 {
1033 CORE_ADDR found_addr = start_addr + (found_ptr - search_buf);
1034 *found_addrp = found_addr;
1035 return 1;
1036 }
1037
1038 /* Not found in this chunk, skip to next chunk. */
1039
1040 /* Don't let search_space_len wrap here, it's unsigned. */
1041 if (search_space_len >= chunk_size)
1042 search_space_len -= chunk_size;
1043 else
1044 search_space_len = 0;
1045
1046 if (search_space_len >= pattern_len)
1047 {
1048 unsigned keep_len = search_buf_size - chunk_size;
1049 CORE_ADDR read_addr = start_addr + chunk_size + keep_len;
1050 int nr_to_read;
1051
1052 /* Copy the trailing part of the previous iteration to the front
1053 of the buffer for the next iteration. */
1054 memcpy (search_buf, search_buf + chunk_size, keep_len);
1055
1056 nr_to_read = (search_space_len - keep_len < chunk_size
1057 ? search_space_len - keep_len
1058 : chunk_size);
1059
1060 if (gdb_read_memory (read_addr, search_buf + keep_len,
1061 nr_to_read) != search_buf_size)
1062 {
1063 warning ("Unable to access %ld bytes of target memory "
1064 "at 0x%lx, halting search.",
1065 (long) nr_to_read, (long) read_addr);
1066 return -1;
1067 }
1068
1069 start_addr += chunk_size;
1070 }
1071 }
1072
1073 /* Not found. */
1074
1075 return 0;
1076 }
1077
1078 /* Handle qSearch:memory packets. */
1079
1080 static void
1081 handle_search_memory (char *own_buf, int packet_len)
1082 {
1083 CORE_ADDR start_addr;
1084 CORE_ADDR search_space_len;
1085 gdb_byte *pattern;
1086 unsigned int pattern_len;
1087 /* NOTE: also defined in find.c testcase. */
1088 #define SEARCH_CHUNK_SIZE 16000
1089 const unsigned chunk_size = SEARCH_CHUNK_SIZE;
1090 /* Buffer to hold memory contents for searching. */
1091 gdb_byte *search_buf;
1092 unsigned search_buf_size;
1093 int found;
1094 CORE_ADDR found_addr;
1095 int cmd_name_len = sizeof ("qSearch:memory:") - 1;
1096
1097 pattern = (gdb_byte *) malloc (packet_len);
1098 if (pattern == NULL)
1099 {
1100 error ("Unable to allocate memory to perform the search");
1101 strcpy (own_buf, "E00");
1102 return;
1103 }
1104 if (decode_search_memory_packet (own_buf + cmd_name_len,
1105 packet_len - cmd_name_len,
1106 &start_addr, &search_space_len,
1107 pattern, &pattern_len) < 0)
1108 {
1109 free (pattern);
1110 error ("Error in parsing qSearch:memory packet");
1111 strcpy (own_buf, "E00");
1112 return;
1113 }
1114
1115 search_buf_size = chunk_size + pattern_len - 1;
1116
1117 /* No point in trying to allocate a buffer larger than the search space. */
1118 if (search_space_len < search_buf_size)
1119 search_buf_size = search_space_len;
1120
1121 search_buf = (gdb_byte *) malloc (search_buf_size);
1122 if (search_buf == NULL)
1123 {
1124 free (pattern);
1125 error ("Unable to allocate memory to perform the search");
1126 strcpy (own_buf, "E00");
1127 return;
1128 }
1129
1130 found = handle_search_memory_1 (start_addr, search_space_len,
1131 pattern, pattern_len,
1132 search_buf, chunk_size, search_buf_size,
1133 &found_addr);
1134
1135 if (found > 0)
1136 sprintf (own_buf, "1,%lx", (long) found_addr);
1137 else if (found == 0)
1138 strcpy (own_buf, "0");
1139 else
1140 strcpy (own_buf, "E00");
1141
1142 free (search_buf);
1143 free (pattern);
1144 }
1145
1146 #define require_running(BUF) \
1147 if (!target_running ()) \
1148 { \
1149 write_enn (BUF); \
1150 return; \
1151 }
1152
1153 /* Parse options to --debug-format= and "monitor set debug-format".
1154 ARG is the text after "--debug-format=" or "monitor set debug-format".
1155 IS_MONITOR is non-zero if we're invoked via "monitor set debug-format".
1156 This triggers calls to monitor_output.
1157 The result is NULL if all options were parsed ok, otherwise an error
1158 message which the caller must free.
1159
1160 N.B. These commands affect all debug format settings, they are not
1161 cumulative. If a format is not specified, it is turned off.
1162 However, we don't go to extra trouble with things like
1163 "monitor set debug-format all,none,timestamp".
1164 Instead we just parse them one at a time, in order.
1165
1166 The syntax for "monitor set debug" we support here is not identical
1167 to gdb's "set debug foo on|off" because we also use this function to
1168 parse "--debug-format=foo,bar". */
1169
1170 static char *
1171 parse_debug_format_options (const char *arg, int is_monitor)
1172 {
1173 VEC (char_ptr) *options;
1174 int ix;
1175 char *option;
1176
1177 /* First turn all debug format options off. */
1178 debug_timestamp = 0;
1179
1180 /* First remove leading spaces, for "monitor set debug-format". */
1181 while (isspace (*arg))
1182 ++arg;
1183
1184 options = delim_string_to_char_ptr_vec (arg, ',');
1185
1186 for (ix = 0; VEC_iterate (char_ptr, options, ix, option); ++ix)
1187 {
1188 if (strcmp (option, "all") == 0)
1189 {
1190 debug_timestamp = 1;
1191 if (is_monitor)
1192 monitor_output ("All extra debug format options enabled.\n");
1193 }
1194 else if (strcmp (option, "none") == 0)
1195 {
1196 debug_timestamp = 0;
1197 if (is_monitor)
1198 monitor_output ("All extra debug format options disabled.\n");
1199 }
1200 else if (strcmp (option, "timestamp") == 0)
1201 {
1202 debug_timestamp = 1;
1203 if (is_monitor)
1204 monitor_output ("Timestamps will be added to debug output.\n");
1205 }
1206 else if (*option == '\0')
1207 {
1208 /* An empty option, e.g., "--debug-format=foo,,bar", is ignored. */
1209 continue;
1210 }
1211 else
1212 {
1213 char *msg = xstrprintf ("Unknown debug-format argument: \"%s\"\n",
1214 option);
1215
1216 free_char_ptr_vec (options);
1217 return msg;
1218 }
1219 }
1220
1221 free_char_ptr_vec (options);
1222 return NULL;
1223 }
1224
1225 /* Handle monitor commands not handled by target-specific handlers. */
1226
1227 static void
1228 handle_monitor_command (char *mon, char *own_buf)
1229 {
1230 if (strcmp (mon, "set debug 1") == 0)
1231 {
1232 debug_threads = 1;
1233 monitor_output ("Debug output enabled.\n");
1234 }
1235 else if (strcmp (mon, "set debug 0") == 0)
1236 {
1237 debug_threads = 0;
1238 monitor_output ("Debug output disabled.\n");
1239 }
1240 else if (strcmp (mon, "set debug-hw-points 1") == 0)
1241 {
1242 show_debug_regs = 1;
1243 monitor_output ("H/W point debugging output enabled.\n");
1244 }
1245 else if (strcmp (mon, "set debug-hw-points 0") == 0)
1246 {
1247 show_debug_regs = 0;
1248 monitor_output ("H/W point debugging output disabled.\n");
1249 }
1250 else if (strcmp (mon, "set remote-debug 1") == 0)
1251 {
1252 remote_debug = 1;
1253 monitor_output ("Protocol debug output enabled.\n");
1254 }
1255 else if (strcmp (mon, "set remote-debug 0") == 0)
1256 {
1257 remote_debug = 0;
1258 monitor_output ("Protocol debug output disabled.\n");
1259 }
1260 else if (startswith (mon, "set debug-format "))
1261 {
1262 char *error_msg
1263 = parse_debug_format_options (mon + sizeof ("set debug-format ") - 1,
1264 1);
1265
1266 if (error_msg != NULL)
1267 {
1268 monitor_output (error_msg);
1269 monitor_show_help ();
1270 write_enn (own_buf);
1271 xfree (error_msg);
1272 }
1273 }
1274 else if (strcmp (mon, "help") == 0)
1275 monitor_show_help ();
1276 else if (strcmp (mon, "exit") == 0)
1277 exit_requested = 1;
1278 else
1279 {
1280 monitor_output ("Unknown monitor command.\n\n");
1281 monitor_show_help ();
1282 write_enn (own_buf);
1283 }
1284 }
1285
1286 /* Associates a callback with each supported qXfer'able object. */
1287
1288 struct qxfer
1289 {
1290 /* The object this handler handles. */
1291 const char *object;
1292
1293 /* Request that the target transfer up to LEN 8-bit bytes of the
1294 target's OBJECT. The OFFSET, for a seekable object, specifies
1295 the starting point. The ANNEX can be used to provide additional
1296 data-specific information to the target.
1297
1298 Return the number of bytes actually transfered, zero when no
1299 further transfer is possible, -1 on error, -2 when the transfer
1300 is not supported, and -3 on a verbose error message that should
1301 be preserved. Return of a positive value smaller than LEN does
1302 not indicate the end of the object, only the end of the transfer.
1303
1304 One, and only one, of readbuf or writebuf must be non-NULL. */
1305 int (*xfer) (const char *annex,
1306 gdb_byte *readbuf, const gdb_byte *writebuf,
1307 ULONGEST offset, LONGEST len);
1308 };
1309
1310 /* Handle qXfer:auxv:read. */
1311
1312 static int
1313 handle_qxfer_auxv (const char *annex,
1314 gdb_byte *readbuf, const gdb_byte *writebuf,
1315 ULONGEST offset, LONGEST len)
1316 {
1317 if (the_target->read_auxv == NULL || writebuf != NULL)
1318 return -2;
1319
1320 if (annex[0] != '\0' || current_thread == NULL)
1321 return -1;
1322
1323 return (*the_target->read_auxv) (offset, readbuf, len);
1324 }
1325
1326 /* Handle qXfer:exec-file:read. */
1327
1328 static int
1329 handle_qxfer_exec_file (const char *const_annex,
1330 gdb_byte *readbuf, const gdb_byte *writebuf,
1331 ULONGEST offset, LONGEST len)
1332 {
1333 char *file;
1334 ULONGEST pid;
1335 int total_len;
1336
1337 if (the_target->pid_to_exec_file == NULL || writebuf != NULL)
1338 return -2;
1339
1340 if (const_annex[0] == '\0')
1341 {
1342 if (current_thread == NULL)
1343 return -1;
1344
1345 pid = pid_of (current_thread);
1346 }
1347 else
1348 {
1349 char *annex = (char *) alloca (strlen (const_annex) + 1);
1350
1351 strcpy (annex, const_annex);
1352 annex = unpack_varlen_hex (annex, &pid);
1353
1354 if (annex[0] != '\0')
1355 return -1;
1356 }
1357
1358 if (pid <= 0)
1359 return -1;
1360
1361 file = (*the_target->pid_to_exec_file) (pid);
1362 if (file == NULL)
1363 return -1;
1364
1365 total_len = strlen (file);
1366
1367 if (offset > total_len)
1368 return -1;
1369
1370 if (offset + len > total_len)
1371 len = total_len - offset;
1372
1373 memcpy (readbuf, file + offset, len);
1374 return len;
1375 }
1376
1377 /* Handle qXfer:features:read. */
1378
1379 static int
1380 handle_qxfer_features (const char *annex,
1381 gdb_byte *readbuf, const gdb_byte *writebuf,
1382 ULONGEST offset, LONGEST len)
1383 {
1384 const char *document;
1385 size_t total_len;
1386
1387 if (writebuf != NULL)
1388 return -2;
1389
1390 if (!target_running ())
1391 return -1;
1392
1393 /* Grab the correct annex. */
1394 document = get_features_xml (annex);
1395 if (document == NULL)
1396 return -1;
1397
1398 total_len = strlen (document);
1399
1400 if (offset > total_len)
1401 return -1;
1402
1403 if (offset + len > total_len)
1404 len = total_len - offset;
1405
1406 memcpy (readbuf, document + offset, len);
1407 return len;
1408 }
1409
1410 /* Worker routine for handle_qxfer_libraries.
1411 Add to the length pointed to by ARG a conservative estimate of the
1412 length needed to transmit the file name of INF. */
1413
1414 static void
1415 accumulate_file_name_length (struct inferior_list_entry *inf, void *arg)
1416 {
1417 struct dll_info *dll = (struct dll_info *) inf;
1418 unsigned int *total_len = (unsigned int *) arg;
1419
1420 /* Over-estimate the necessary memory. Assume that every character
1421 in the library name must be escaped. */
1422 *total_len += 128 + 6 * strlen (dll->name);
1423 }
1424
1425 /* Worker routine for handle_qxfer_libraries.
1426 Emit the XML to describe the library in INF. */
1427
1428 static void
1429 emit_dll_description (struct inferior_list_entry *inf, void *arg)
1430 {
1431 struct dll_info *dll = (struct dll_info *) inf;
1432 char **p_ptr = (char **) arg;
1433 char *p = *p_ptr;
1434 char *name;
1435
1436 strcpy (p, " <library name=\"");
1437 p = p + strlen (p);
1438 name = xml_escape_text (dll->name);
1439 strcpy (p, name);
1440 free (name);
1441 p = p + strlen (p);
1442 strcpy (p, "\"><segment address=\"");
1443 p = p + strlen (p);
1444 sprintf (p, "0x%lx", (long) dll->base_addr);
1445 p = p + strlen (p);
1446 strcpy (p, "\"/></library>\n");
1447 p = p + strlen (p);
1448
1449 *p_ptr = p;
1450 }
1451
1452 /* Handle qXfer:libraries:read. */
1453
1454 static int
1455 handle_qxfer_libraries (const char *annex,
1456 gdb_byte *readbuf, const gdb_byte *writebuf,
1457 ULONGEST offset, LONGEST len)
1458 {
1459 unsigned int total_len;
1460 char *document, *p;
1461
1462 if (writebuf != NULL)
1463 return -2;
1464
1465 if (annex[0] != '\0' || current_thread == NULL)
1466 return -1;
1467
1468 total_len = 64;
1469 for_each_inferior_with_data (&all_dlls, accumulate_file_name_length,
1470 &total_len);
1471
1472 document = (char *) malloc (total_len);
1473 if (document == NULL)
1474 return -1;
1475
1476 strcpy (document, "<library-list version=\"1.0\">\n");
1477 p = document + strlen (document);
1478
1479 for_each_inferior_with_data (&all_dlls, emit_dll_description, &p);
1480
1481 strcpy (p, "</library-list>\n");
1482
1483 total_len = strlen (document);
1484
1485 if (offset > total_len)
1486 {
1487 free (document);
1488 return -1;
1489 }
1490
1491 if (offset + len > total_len)
1492 len = total_len - offset;
1493
1494 memcpy (readbuf, document + offset, len);
1495 free (document);
1496 return len;
1497 }
1498
1499 /* Handle qXfer:libraries-svr4:read. */
1500
1501 static int
1502 handle_qxfer_libraries_svr4 (const char *annex,
1503 gdb_byte *readbuf, const gdb_byte *writebuf,
1504 ULONGEST offset, LONGEST len)
1505 {
1506 if (writebuf != NULL)
1507 return -2;
1508
1509 if (current_thread == NULL || the_target->qxfer_libraries_svr4 == NULL)
1510 return -1;
1511
1512 return the_target->qxfer_libraries_svr4 (annex, readbuf, writebuf, offset, len);
1513 }
1514
1515 /* Handle qXfer:osadata:read. */
1516
1517 static int
1518 handle_qxfer_osdata (const char *annex,
1519 gdb_byte *readbuf, const gdb_byte *writebuf,
1520 ULONGEST offset, LONGEST len)
1521 {
1522 if (the_target->qxfer_osdata == NULL || writebuf != NULL)
1523 return -2;
1524
1525 return (*the_target->qxfer_osdata) (annex, readbuf, NULL, offset, len);
1526 }
1527
1528 /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
1529
1530 static int
1531 handle_qxfer_siginfo (const char *annex,
1532 gdb_byte *readbuf, const gdb_byte *writebuf,
1533 ULONGEST offset, LONGEST len)
1534 {
1535 if (the_target->qxfer_siginfo == NULL)
1536 return -2;
1537
1538 if (annex[0] != '\0' || current_thread == NULL)
1539 return -1;
1540
1541 return (*the_target->qxfer_siginfo) (annex, readbuf, writebuf, offset, len);
1542 }
1543
1544 /* Handle qXfer:spu:read and qXfer:spu:write. */
1545
1546 static int
1547 handle_qxfer_spu (const char *annex,
1548 gdb_byte *readbuf, const gdb_byte *writebuf,
1549 ULONGEST offset, LONGEST len)
1550 {
1551 if (the_target->qxfer_spu == NULL)
1552 return -2;
1553
1554 if (current_thread == NULL)
1555 return -1;
1556
1557 return (*the_target->qxfer_spu) (annex, readbuf, writebuf, offset, len);
1558 }
1559
1560 /* Handle qXfer:statictrace:read. */
1561
1562 static int
1563 handle_qxfer_statictrace (const char *annex,
1564 gdb_byte *readbuf, const gdb_byte *writebuf,
1565 ULONGEST offset, LONGEST len)
1566 {
1567 ULONGEST nbytes;
1568
1569 if (writebuf != NULL)
1570 return -2;
1571
1572 if (annex[0] != '\0' || current_thread == NULL || current_traceframe == -1)
1573 return -1;
1574
1575 if (traceframe_read_sdata (current_traceframe, offset,
1576 readbuf, len, &nbytes))
1577 return -1;
1578 return nbytes;
1579 }
1580
1581 /* Helper for handle_qxfer_threads_proper.
1582 Emit the XML to describe the thread of INF. */
1583
1584 static void
1585 handle_qxfer_threads_worker (struct inferior_list_entry *inf, void *arg)
1586 {
1587 struct thread_info *thread = (struct thread_info *) inf;
1588 struct buffer *buffer = (struct buffer *) arg;
1589 ptid_t ptid = thread_to_gdb_id (thread);
1590 char ptid_s[100];
1591 int core = target_core_of_thread (ptid);
1592 char core_s[21];
1593 const char *name = target_thread_name (ptid);
1594
1595 write_ptid (ptid_s, ptid);
1596
1597 buffer_xml_printf (buffer, "<thread id=\"%s\"", ptid_s);
1598
1599 if (core != -1)
1600 {
1601 sprintf (core_s, "%d", core);
1602 buffer_xml_printf (buffer, " core=\"%s\"", core_s);
1603 }
1604
1605 if (name != NULL)
1606 buffer_xml_printf (buffer, " name=\"%s\"", name);
1607
1608 buffer_xml_printf (buffer, "/>\n");
1609 }
1610
1611 /* Helper for handle_qxfer_threads. */
1612
1613 static void
1614 handle_qxfer_threads_proper (struct buffer *buffer)
1615 {
1616 buffer_grow_str (buffer, "<threads>\n");
1617
1618 for_each_inferior_with_data (&all_threads, handle_qxfer_threads_worker,
1619 buffer);
1620
1621 buffer_grow_str0 (buffer, "</threads>\n");
1622 }
1623
1624 /* Handle qXfer:threads:read. */
1625
1626 static int
1627 handle_qxfer_threads (const char *annex,
1628 gdb_byte *readbuf, const gdb_byte *writebuf,
1629 ULONGEST offset, LONGEST len)
1630 {
1631 static char *result = 0;
1632 static unsigned int result_length = 0;
1633
1634 if (writebuf != NULL)
1635 return -2;
1636
1637 if (annex[0] != '\0')
1638 return -1;
1639
1640 if (offset == 0)
1641 {
1642 struct buffer buffer;
1643 /* When asked for data at offset 0, generate everything and store into
1644 'result'. Successive reads will be served off 'result'. */
1645 if (result)
1646 free (result);
1647
1648 buffer_init (&buffer);
1649
1650 handle_qxfer_threads_proper (&buffer);
1651
1652 result = buffer_finish (&buffer);
1653 result_length = strlen (result);
1654 buffer_free (&buffer);
1655 }
1656
1657 if (offset >= result_length)
1658 {
1659 /* We're out of data. */
1660 free (result);
1661 result = NULL;
1662 result_length = 0;
1663 return 0;
1664 }
1665
1666 if (len > result_length - offset)
1667 len = result_length - offset;
1668
1669 memcpy (readbuf, result + offset, len);
1670
1671 return len;
1672 }
1673
1674 /* Handle qXfer:traceframe-info:read. */
1675
1676 static int
1677 handle_qxfer_traceframe_info (const char *annex,
1678 gdb_byte *readbuf, const gdb_byte *writebuf,
1679 ULONGEST offset, LONGEST len)
1680 {
1681 static char *result = 0;
1682 static unsigned int result_length = 0;
1683
1684 if (writebuf != NULL)
1685 return -2;
1686
1687 if (!target_running () || annex[0] != '\0' || current_traceframe == -1)
1688 return -1;
1689
1690 if (offset == 0)
1691 {
1692 struct buffer buffer;
1693
1694 /* When asked for data at offset 0, generate everything and
1695 store into 'result'. Successive reads will be served off
1696 'result'. */
1697 free (result);
1698
1699 buffer_init (&buffer);
1700
1701 traceframe_read_info (current_traceframe, &buffer);
1702
1703 result = buffer_finish (&buffer);
1704 result_length = strlen (result);
1705 buffer_free (&buffer);
1706 }
1707
1708 if (offset >= result_length)
1709 {
1710 /* We're out of data. */
1711 free (result);
1712 result = NULL;
1713 result_length = 0;
1714 return 0;
1715 }
1716
1717 if (len > result_length - offset)
1718 len = result_length - offset;
1719
1720 memcpy (readbuf, result + offset, len);
1721 return len;
1722 }
1723
1724 /* Handle qXfer:fdpic:read. */
1725
1726 static int
1727 handle_qxfer_fdpic (const char *annex, gdb_byte *readbuf,
1728 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
1729 {
1730 if (the_target->read_loadmap == NULL)
1731 return -2;
1732
1733 if (current_thread == NULL)
1734 return -1;
1735
1736 return (*the_target->read_loadmap) (annex, offset, readbuf, len);
1737 }
1738
1739 /* Handle qXfer:btrace:read. */
1740
1741 static int
1742 handle_qxfer_btrace (const char *annex,
1743 gdb_byte *readbuf, const gdb_byte *writebuf,
1744 ULONGEST offset, LONGEST len)
1745 {
1746 static struct buffer cache;
1747 struct thread_info *thread;
1748 enum btrace_read_type type;
1749 int result;
1750
1751 if (the_target->read_btrace == NULL || writebuf != NULL)
1752 return -2;
1753
1754 if (ptid_equal (general_thread, null_ptid)
1755 || ptid_equal (general_thread, minus_one_ptid))
1756 {
1757 strcpy (own_buf, "E.Must select a single thread.");
1758 return -3;
1759 }
1760
1761 thread = find_thread_ptid (general_thread);
1762 if (thread == NULL)
1763 {
1764 strcpy (own_buf, "E.No such thread.");
1765 return -3;
1766 }
1767
1768 if (thread->btrace == NULL)
1769 {
1770 strcpy (own_buf, "E.Btrace not enabled.");
1771 return -3;
1772 }
1773
1774 if (strcmp (annex, "all") == 0)
1775 type = BTRACE_READ_ALL;
1776 else if (strcmp (annex, "new") == 0)
1777 type = BTRACE_READ_NEW;
1778 else if (strcmp (annex, "delta") == 0)
1779 type = BTRACE_READ_DELTA;
1780 else
1781 {
1782 strcpy (own_buf, "E.Bad annex.");
1783 return -3;
1784 }
1785
1786 if (offset == 0)
1787 {
1788 buffer_free (&cache);
1789
1790 result = target_read_btrace (thread->btrace, &cache, type);
1791 if (result != 0)
1792 {
1793 memcpy (own_buf, cache.buffer, cache.used_size);
1794 return -3;
1795 }
1796 }
1797 else if (offset > cache.used_size)
1798 {
1799 buffer_free (&cache);
1800 return -3;
1801 }
1802
1803 if (len > cache.used_size - offset)
1804 len = cache.used_size - offset;
1805
1806 memcpy (readbuf, cache.buffer + offset, len);
1807
1808 return len;
1809 }
1810
1811 /* Handle qXfer:btrace-conf:read. */
1812
1813 static int
1814 handle_qxfer_btrace_conf (const char *annex,
1815 gdb_byte *readbuf, const gdb_byte *writebuf,
1816 ULONGEST offset, LONGEST len)
1817 {
1818 static struct buffer cache;
1819 struct thread_info *thread;
1820 int result;
1821
1822 if (the_target->read_btrace_conf == NULL || writebuf != NULL)
1823 return -2;
1824
1825 if (annex[0] != '\0')
1826 return -1;
1827
1828 if (ptid_equal (general_thread, null_ptid)
1829 || ptid_equal (general_thread, minus_one_ptid))
1830 {
1831 strcpy (own_buf, "E.Must select a single thread.");
1832 return -3;
1833 }
1834
1835 thread = find_thread_ptid (general_thread);
1836 if (thread == NULL)
1837 {
1838 strcpy (own_buf, "E.No such thread.");
1839 return -3;
1840 }
1841
1842 if (thread->btrace == NULL)
1843 {
1844 strcpy (own_buf, "E.Btrace not enabled.");
1845 return -3;
1846 }
1847
1848 if (offset == 0)
1849 {
1850 buffer_free (&cache);
1851
1852 result = target_read_btrace_conf (thread->btrace, &cache);
1853 if (result != 0)
1854 {
1855 memcpy (own_buf, cache.buffer, cache.used_size);
1856 return -3;
1857 }
1858 }
1859 else if (offset > cache.used_size)
1860 {
1861 buffer_free (&cache);
1862 return -3;
1863 }
1864
1865 if (len > cache.used_size - offset)
1866 len = cache.used_size - offset;
1867
1868 memcpy (readbuf, cache.buffer + offset, len);
1869
1870 return len;
1871 }
1872
1873 static const struct qxfer qxfer_packets[] =
1874 {
1875 { "auxv", handle_qxfer_auxv },
1876 { "btrace", handle_qxfer_btrace },
1877 { "btrace-conf", handle_qxfer_btrace_conf },
1878 { "exec-file", handle_qxfer_exec_file},
1879 { "fdpic", handle_qxfer_fdpic},
1880 { "features", handle_qxfer_features },
1881 { "libraries", handle_qxfer_libraries },
1882 { "libraries-svr4", handle_qxfer_libraries_svr4 },
1883 { "osdata", handle_qxfer_osdata },
1884 { "siginfo", handle_qxfer_siginfo },
1885 { "spu", handle_qxfer_spu },
1886 { "statictrace", handle_qxfer_statictrace },
1887 { "threads", handle_qxfer_threads },
1888 { "traceframe-info", handle_qxfer_traceframe_info },
1889 };
1890
1891 static int
1892 handle_qxfer (char *own_buf, int packet_len, int *new_packet_len_p)
1893 {
1894 int i;
1895 char *object;
1896 char *rw;
1897 char *annex;
1898 char *offset;
1899
1900 if (!startswith (own_buf, "qXfer:"))
1901 return 0;
1902
1903 /* Grab the object, r/w and annex. */
1904 if (decode_xfer (own_buf + 6, &object, &rw, &annex, &offset) < 0)
1905 {
1906 write_enn (own_buf);
1907 return 1;
1908 }
1909
1910 for (i = 0;
1911 i < sizeof (qxfer_packets) / sizeof (qxfer_packets[0]);
1912 i++)
1913 {
1914 const struct qxfer *q = &qxfer_packets[i];
1915
1916 if (strcmp (object, q->object) == 0)
1917 {
1918 if (strcmp (rw, "read") == 0)
1919 {
1920 unsigned char *data;
1921 int n;
1922 CORE_ADDR ofs;
1923 unsigned int len;
1924
1925 /* Grab the offset and length. */
1926 if (decode_xfer_read (offset, &ofs, &len) < 0)
1927 {
1928 write_enn (own_buf);
1929 return 1;
1930 }
1931
1932 /* Read one extra byte, as an indicator of whether there is
1933 more. */
1934 if (len > PBUFSIZ - 2)
1935 len = PBUFSIZ - 2;
1936 data = (unsigned char *) malloc (len + 1);
1937 if (data == NULL)
1938 {
1939 write_enn (own_buf);
1940 return 1;
1941 }
1942 n = (*q->xfer) (annex, data, NULL, ofs, len + 1);
1943 if (n == -2)
1944 {
1945 free (data);
1946 return 0;
1947 }
1948 else if (n == -3)
1949 {
1950 /* Preserve error message. */
1951 }
1952 else if (n < 0)
1953 write_enn (own_buf);
1954 else if (n > len)
1955 *new_packet_len_p = write_qxfer_response (own_buf, data, len, 1);
1956 else
1957 *new_packet_len_p = write_qxfer_response (own_buf, data, n, 0);
1958
1959 free (data);
1960 return 1;
1961 }
1962 else if (strcmp (rw, "write") == 0)
1963 {
1964 int n;
1965 unsigned int len;
1966 CORE_ADDR ofs;
1967 unsigned char *data;
1968
1969 strcpy (own_buf, "E00");
1970 data = (unsigned char *) malloc (packet_len - (offset - own_buf));
1971 if (data == NULL)
1972 {
1973 write_enn (own_buf);
1974 return 1;
1975 }
1976 if (decode_xfer_write (offset, packet_len - (offset - own_buf),
1977 &ofs, &len, data) < 0)
1978 {
1979 free (data);
1980 write_enn (own_buf);
1981 return 1;
1982 }
1983
1984 n = (*q->xfer) (annex, NULL, data, ofs, len);
1985 if (n == -2)
1986 {
1987 free (data);
1988 return 0;
1989 }
1990 else if (n == -3)
1991 {
1992 /* Preserve error message. */
1993 }
1994 else if (n < 0)
1995 write_enn (own_buf);
1996 else
1997 sprintf (own_buf, "%x", n);
1998
1999 free (data);
2000 return 1;
2001 }
2002
2003 return 0;
2004 }
2005 }
2006
2007 return 0;
2008 }
2009
2010 /* Compute 32 bit CRC from inferior memory.
2011
2012 On success, return 32 bit CRC.
2013 On failure, return (unsigned long long) -1. */
2014
2015 static unsigned long long
2016 crc32 (CORE_ADDR base, int len, unsigned int crc)
2017 {
2018 while (len--)
2019 {
2020 unsigned char byte = 0;
2021
2022 /* Return failure if memory read fails. */
2023 if (read_inferior_memory (base, &byte, 1) != 0)
2024 return (unsigned long long) -1;
2025
2026 crc = xcrc32 (&byte, 1, crc);
2027 base++;
2028 }
2029 return (unsigned long long) crc;
2030 }
2031
2032 /* Add supported btrace packets to BUF. */
2033
2034 static void
2035 supported_btrace_packets (char *buf)
2036 {
2037 int btrace_supported = 0;
2038
2039 if (target_supports_btrace (BTRACE_FORMAT_BTS))
2040 {
2041 strcat (buf, ";Qbtrace:bts+");
2042 strcat (buf, ";Qbtrace-conf:bts:size+");
2043
2044 btrace_supported = 1;
2045 }
2046
2047 if (target_supports_btrace (BTRACE_FORMAT_PT))
2048 {
2049 strcat (buf, ";Qbtrace:pt+");
2050 strcat (buf, ";Qbtrace-conf:pt:size+");
2051
2052 btrace_supported = 1;
2053 }
2054
2055 if (!btrace_supported)
2056 return;
2057
2058 strcat (buf, ";Qbtrace:off+");
2059 strcat (buf, ";qXfer:btrace:read+");
2060 strcat (buf, ";qXfer:btrace-conf:read+");
2061 }
2062
2063 /* Handle all of the extended 'q' packets. */
2064
2065 static void
2066 handle_query (char *own_buf, int packet_len, int *new_packet_len_p)
2067 {
2068 static struct inferior_list_entry *thread_ptr;
2069
2070 /* Reply the current thread id. */
2071 if (strcmp ("qC", own_buf) == 0 && !disable_packet_qC)
2072 {
2073 ptid_t gdb_id;
2074 require_running (own_buf);
2075
2076 if (!ptid_equal (general_thread, null_ptid)
2077 && !ptid_equal (general_thread, minus_one_ptid))
2078 gdb_id = general_thread;
2079 else
2080 {
2081 thread_ptr = get_first_inferior (&all_threads);
2082 gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
2083 }
2084
2085 sprintf (own_buf, "QC");
2086 own_buf += 2;
2087 write_ptid (own_buf, gdb_id);
2088 return;
2089 }
2090
2091 if (strcmp ("qSymbol::", own_buf) == 0)
2092 {
2093 struct thread_info *save_thread = current_thread;
2094
2095 /* For qSymbol, GDB only changes the current thread if the
2096 previous current thread was of a different process. So if
2097 the previous thread is gone, we need to pick another one of
2098 the same process. This can happen e.g., if we followed an
2099 exec in a non-leader thread. */
2100 if (current_thread == NULL)
2101 {
2102 current_thread
2103 = find_any_thread_of_pid (ptid_get_pid (general_thread));
2104
2105 /* Just in case, if we didn't find a thread, then bail out
2106 instead of crashing. */
2107 if (current_thread == NULL)
2108 {
2109 write_enn (own_buf);
2110 current_thread = save_thread;
2111 return;
2112 }
2113 }
2114
2115 /* GDB is suggesting new symbols have been loaded. This may
2116 mean a new shared library has been detected as loaded, so
2117 take the opportunity to check if breakpoints we think are
2118 inserted, still are. Note that it isn't guaranteed that
2119 we'll see this when a shared library is loaded, and nor will
2120 we see this for unloads (although breakpoints in unloaded
2121 libraries shouldn't trigger), as GDB may not find symbols for
2122 the library at all. We also re-validate breakpoints when we
2123 see a second GDB breakpoint for the same address, and or when
2124 we access breakpoint shadows. */
2125 validate_breakpoints ();
2126
2127 if (target_supports_tracepoints ())
2128 tracepoint_look_up_symbols ();
2129
2130 if (current_thread != NULL && the_target->look_up_symbols != NULL)
2131 (*the_target->look_up_symbols) ();
2132
2133 current_thread = save_thread;
2134
2135 strcpy (own_buf, "OK");
2136 return;
2137 }
2138
2139 if (!disable_packet_qfThreadInfo)
2140 {
2141 if (strcmp ("qfThreadInfo", own_buf) == 0)
2142 {
2143 ptid_t gdb_id;
2144
2145 require_running (own_buf);
2146 thread_ptr = get_first_inferior (&all_threads);
2147
2148 *own_buf++ = 'm';
2149 gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
2150 write_ptid (own_buf, gdb_id);
2151 thread_ptr = thread_ptr->next;
2152 return;
2153 }
2154
2155 if (strcmp ("qsThreadInfo", own_buf) == 0)
2156 {
2157 ptid_t gdb_id;
2158
2159 require_running (own_buf);
2160 if (thread_ptr != NULL)
2161 {
2162 *own_buf++ = 'm';
2163 gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
2164 write_ptid (own_buf, gdb_id);
2165 thread_ptr = thread_ptr->next;
2166 return;
2167 }
2168 else
2169 {
2170 sprintf (own_buf, "l");
2171 return;
2172 }
2173 }
2174 }
2175
2176 if (the_target->read_offsets != NULL
2177 && strcmp ("qOffsets", own_buf) == 0)
2178 {
2179 CORE_ADDR text, data;
2180
2181 require_running (own_buf);
2182 if (the_target->read_offsets (&text, &data))
2183 sprintf (own_buf, "Text=%lX;Data=%lX;Bss=%lX",
2184 (long)text, (long)data, (long)data);
2185 else
2186 write_enn (own_buf);
2187
2188 return;
2189 }
2190
2191 /* Protocol features query. */
2192 if (startswith (own_buf, "qSupported")
2193 && (own_buf[10] == ':' || own_buf[10] == '\0'))
2194 {
2195 char *p = &own_buf[10];
2196 int gdb_supports_qRelocInsn = 0;
2197
2198 /* Process each feature being provided by GDB. The first
2199 feature will follow a ':', and latter features will follow
2200 ';'. */
2201 if (*p == ':')
2202 {
2203 char **qsupported = NULL;
2204 int count = 0;
2205 int unknown = 0;
2206 int i;
2207
2208 /* Two passes, to avoid nested strtok calls in
2209 target_process_qsupported. */
2210 for (p = strtok (p + 1, ";");
2211 p != NULL;
2212 p = strtok (NULL, ";"))
2213 {
2214 count++;
2215 qsupported = XRESIZEVEC (char *, qsupported, count);
2216 qsupported[count - 1] = xstrdup (p);
2217 }
2218
2219 for (i = 0; i < count; i++)
2220 {
2221 p = qsupported[i];
2222 if (strcmp (p, "multiprocess+") == 0)
2223 {
2224 /* GDB supports and wants multi-process support if
2225 possible. */
2226 if (target_supports_multi_process ())
2227 multi_process = 1;
2228 }
2229 else if (strcmp (p, "qRelocInsn+") == 0)
2230 {
2231 /* GDB supports relocate instruction requests. */
2232 gdb_supports_qRelocInsn = 1;
2233 }
2234 else if (strcmp (p, "swbreak+") == 0)
2235 {
2236 /* GDB wants us to report whether a trap is caused
2237 by a software breakpoint and for us to handle PC
2238 adjustment if necessary on this target. */
2239 if (target_supports_stopped_by_sw_breakpoint ())
2240 swbreak_feature = 1;
2241 }
2242 else if (strcmp (p, "hwbreak+") == 0)
2243 {
2244 /* GDB wants us to report whether a trap is caused
2245 by a hardware breakpoint. */
2246 if (target_supports_stopped_by_hw_breakpoint ())
2247 hwbreak_feature = 1;
2248 }
2249 else if (strcmp (p, "fork-events+") == 0)
2250 {
2251 /* GDB supports and wants fork events if possible. */
2252 if (target_supports_fork_events ())
2253 report_fork_events = 1;
2254 }
2255 else if (strcmp (p, "vfork-events+") == 0)
2256 {
2257 /* GDB supports and wants vfork events if possible. */
2258 if (target_supports_vfork_events ())
2259 report_vfork_events = 1;
2260 }
2261 else if (strcmp (p, "exec-events+") == 0)
2262 {
2263 /* GDB supports and wants exec events if possible. */
2264 if (target_supports_exec_events ())
2265 report_exec_events = 1;
2266 }
2267 else if (strcmp (p, "vContSupported+") == 0)
2268 vCont_supported = 1;
2269 else if (strcmp (p, "QThreadEvents+") == 0)
2270 ;
2271 else if (strcmp (p, "no-resumed+") == 0)
2272 {
2273 /* GDB supports and wants TARGET_WAITKIND_NO_RESUMED
2274 events. */
2275 report_no_resumed = 1;
2276 }
2277 else
2278 {
2279 /* Move the unknown features all together. */
2280 qsupported[i] = NULL;
2281 qsupported[unknown] = p;
2282 unknown++;
2283 }
2284 }
2285
2286 /* Give the target backend a chance to process the unknown
2287 features. */
2288 target_process_qsupported (qsupported, unknown);
2289
2290 for (i = 0; i < count; i++)
2291 free (qsupported[i]);
2292 free (qsupported);
2293 }
2294
2295 sprintf (own_buf,
2296 "PacketSize=%x;QPassSignals+;QProgramSignals+;"
2297 "QStartupWithShell+;QEnvironmentHexEncoded+;"
2298 "QEnvironmentReset+;QEnvironmentUnset+",
2299 PBUFSIZ - 1);
2300
2301 if (target_supports_catch_syscall ())
2302 strcat (own_buf, ";QCatchSyscalls+");
2303
2304 if (the_target->qxfer_libraries_svr4 != NULL)
2305 strcat (own_buf, ";qXfer:libraries-svr4:read+"
2306 ";augmented-libraries-svr4-read+");
2307 else
2308 {
2309 /* We do not have any hook to indicate whether the non-SVR4 target
2310 backend supports qXfer:libraries:read, so always report it. */
2311 strcat (own_buf, ";qXfer:libraries:read+");
2312 }
2313
2314 if (the_target->read_auxv != NULL)
2315 strcat (own_buf, ";qXfer:auxv:read+");
2316
2317 if (the_target->qxfer_spu != NULL)
2318 strcat (own_buf, ";qXfer:spu:read+;qXfer:spu:write+");
2319
2320 if (the_target->qxfer_siginfo != NULL)
2321 strcat (own_buf, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
2322
2323 if (the_target->read_loadmap != NULL)
2324 strcat (own_buf, ";qXfer:fdpic:read+");
2325
2326 /* We always report qXfer:features:read, as targets may
2327 install XML files on a subsequent call to arch_setup.
2328 If we reported to GDB on startup that we don't support
2329 qXfer:feature:read at all, we will never be re-queried. */
2330 strcat (own_buf, ";qXfer:features:read+");
2331
2332 if (transport_is_reliable)
2333 strcat (own_buf, ";QStartNoAckMode+");
2334
2335 if (the_target->qxfer_osdata != NULL)
2336 strcat (own_buf, ";qXfer:osdata:read+");
2337
2338 if (target_supports_multi_process ())
2339 strcat (own_buf, ";multiprocess+");
2340
2341 if (target_supports_fork_events ())
2342 strcat (own_buf, ";fork-events+");
2343
2344 if (target_supports_vfork_events ())
2345 strcat (own_buf, ";vfork-events+");
2346
2347 if (target_supports_exec_events ())
2348 strcat (own_buf, ";exec-events+");
2349
2350 if (target_supports_non_stop ())
2351 strcat (own_buf, ";QNonStop+");
2352
2353 if (target_supports_disable_randomization ())
2354 strcat (own_buf, ";QDisableRandomization+");
2355
2356 strcat (own_buf, ";qXfer:threads:read+");
2357
2358 if (target_supports_tracepoints ())
2359 {
2360 strcat (own_buf, ";ConditionalTracepoints+");
2361 strcat (own_buf, ";TraceStateVariables+");
2362 strcat (own_buf, ";TracepointSource+");
2363 strcat (own_buf, ";DisconnectedTracing+");
2364 if (gdb_supports_qRelocInsn && target_supports_fast_tracepoints ())
2365 strcat (own_buf, ";FastTracepoints+");
2366 strcat (own_buf, ";StaticTracepoints+");
2367 strcat (own_buf, ";InstallInTrace+");
2368 strcat (own_buf, ";qXfer:statictrace:read+");
2369 strcat (own_buf, ";qXfer:traceframe-info:read+");
2370 strcat (own_buf, ";EnableDisableTracepoints+");
2371 strcat (own_buf, ";QTBuffer:size+");
2372 strcat (own_buf, ";tracenz+");
2373 }
2374
2375 if (target_supports_hardware_single_step ()
2376 || target_supports_software_single_step () )
2377 {
2378 strcat (own_buf, ";ConditionalBreakpoints+");
2379 }
2380 strcat (own_buf, ";BreakpointCommands+");
2381
2382 if (target_supports_agent ())
2383 strcat (own_buf, ";QAgent+");
2384
2385 supported_btrace_packets (own_buf);
2386
2387 if (target_supports_stopped_by_sw_breakpoint ())
2388 strcat (own_buf, ";swbreak+");
2389
2390 if (target_supports_stopped_by_hw_breakpoint ())
2391 strcat (own_buf, ";hwbreak+");
2392
2393 if (the_target->pid_to_exec_file != NULL)
2394 strcat (own_buf, ";qXfer:exec-file:read+");
2395
2396 strcat (own_buf, ";vContSupported+");
2397
2398 strcat (own_buf, ";QThreadEvents+");
2399
2400 strcat (own_buf, ";no-resumed+");
2401
2402 /* Reinitialize components as needed for the new connection. */
2403 hostio_handle_new_gdb_connection ();
2404 target_handle_new_gdb_connection ();
2405
2406 return;
2407 }
2408
2409 /* Thread-local storage support. */
2410 if (the_target->get_tls_address != NULL
2411 && startswith (own_buf, "qGetTLSAddr:"))
2412 {
2413 char *p = own_buf + 12;
2414 CORE_ADDR parts[2], address = 0;
2415 int i, err;
2416 ptid_t ptid = null_ptid;
2417
2418 require_running (own_buf);
2419
2420 for (i = 0; i < 3; i++)
2421 {
2422 char *p2;
2423 int len;
2424
2425 if (p == NULL)
2426 break;
2427
2428 p2 = strchr (p, ',');
2429 if (p2)
2430 {
2431 len = p2 - p;
2432 p2++;
2433 }
2434 else
2435 {
2436 len = strlen (p);
2437 p2 = NULL;
2438 }
2439
2440 if (i == 0)
2441 ptid = read_ptid (p, NULL);
2442 else
2443 decode_address (&parts[i - 1], p, len);
2444 p = p2;
2445 }
2446
2447 if (p != NULL || i < 3)
2448 err = 1;
2449 else
2450 {
2451 struct thread_info *thread = find_thread_ptid (ptid);
2452
2453 if (thread == NULL)
2454 err = 2;
2455 else
2456 err = the_target->get_tls_address (thread, parts[0], parts[1],
2457 &address);
2458 }
2459
2460 if (err == 0)
2461 {
2462 strcpy (own_buf, paddress(address));
2463 return;
2464 }
2465 else if (err > 0)
2466 {
2467 write_enn (own_buf);
2468 return;
2469 }
2470
2471 /* Otherwise, pretend we do not understand this packet. */
2472 }
2473
2474 /* Windows OS Thread Information Block address support. */
2475 if (the_target->get_tib_address != NULL
2476 && startswith (own_buf, "qGetTIBAddr:"))
2477 {
2478 char *annex;
2479 int n;
2480 CORE_ADDR tlb;
2481 ptid_t ptid = read_ptid (own_buf + 12, &annex);
2482
2483 n = (*the_target->get_tib_address) (ptid, &tlb);
2484 if (n == 1)
2485 {
2486 strcpy (own_buf, paddress(tlb));
2487 return;
2488 }
2489 else if (n == 0)
2490 {
2491 write_enn (own_buf);
2492 return;
2493 }
2494 return;
2495 }
2496
2497 /* Handle "monitor" commands. */
2498 if (startswith (own_buf, "qRcmd,"))
2499 {
2500 char *mon = (char *) malloc (PBUFSIZ);
2501 int len = strlen (own_buf + 6);
2502
2503 if (mon == NULL)
2504 {
2505 write_enn (own_buf);
2506 return;
2507 }
2508
2509 if ((len % 2) != 0
2510 || hex2bin (own_buf + 6, (gdb_byte *) mon, len / 2) != len / 2)
2511 {
2512 write_enn (own_buf);
2513 free (mon);
2514 return;
2515 }
2516 mon[len / 2] = '\0';
2517
2518 write_ok (own_buf);
2519
2520 if (the_target->handle_monitor_command == NULL
2521 || (*the_target->handle_monitor_command) (mon) == 0)
2522 /* Default processing. */
2523 handle_monitor_command (mon, own_buf);
2524
2525 free (mon);
2526 return;
2527 }
2528
2529 if (startswith (own_buf, "qSearch:memory:"))
2530 {
2531 require_running (own_buf);
2532 handle_search_memory (own_buf, packet_len);
2533 return;
2534 }
2535
2536 if (strcmp (own_buf, "qAttached") == 0
2537 || startswith (own_buf, "qAttached:"))
2538 {
2539 struct process_info *process;
2540
2541 if (own_buf[sizeof ("qAttached") - 1])
2542 {
2543 int pid = strtoul (own_buf + sizeof ("qAttached:") - 1, NULL, 16);
2544 process = (struct process_info *)
2545 find_inferior_id (&all_processes, pid_to_ptid (pid));
2546 }
2547 else
2548 {
2549 require_running (own_buf);
2550 process = current_process ();
2551 }
2552
2553 if (process == NULL)
2554 {
2555 write_enn (own_buf);
2556 return;
2557 }
2558
2559 strcpy (own_buf, process->attached ? "1" : "0");
2560 return;
2561 }
2562
2563 if (startswith (own_buf, "qCRC:"))
2564 {
2565 /* CRC check (compare-section). */
2566 char *comma;
2567 ULONGEST base;
2568 int len;
2569 unsigned long long crc;
2570
2571 require_running (own_buf);
2572 comma = unpack_varlen_hex (own_buf + 5, &base);
2573 if (*comma++ != ',')
2574 {
2575 write_enn (own_buf);
2576 return;
2577 }
2578 len = strtoul (comma, NULL, 16);
2579 crc = crc32 (base, len, 0xffffffff);
2580 /* Check for memory failure. */
2581 if (crc == (unsigned long long) -1)
2582 {
2583 write_enn (own_buf);
2584 return;
2585 }
2586 sprintf (own_buf, "C%lx", (unsigned long) crc);
2587 return;
2588 }
2589
2590 if (handle_qxfer (own_buf, packet_len, new_packet_len_p))
2591 return;
2592
2593 if (target_supports_tracepoints () && handle_tracepoint_query (own_buf))
2594 return;
2595
2596 /* Otherwise we didn't know what packet it was. Say we didn't
2597 understand it. */
2598 own_buf[0] = 0;
2599 }
2600
2601 static void gdb_wants_all_threads_stopped (void);
2602 static void resume (struct thread_resume *actions, size_t n);
2603
2604 /* The callback that is passed to visit_actioned_threads. */
2605 typedef int (visit_actioned_threads_callback_ftype)
2606 (const struct thread_resume *, struct thread_info *);
2607
2608 /* Struct to pass data to visit_actioned_threads. */
2609
2610 struct visit_actioned_threads_data
2611 {
2612 const struct thread_resume *actions;
2613 size_t num_actions;
2614 visit_actioned_threads_callback_ftype *callback;
2615 };
2616
2617 /* Call CALLBACK for any thread to which ACTIONS applies to. Returns
2618 true if CALLBACK returns true. Returns false if no matching thread
2619 is found or CALLBACK results false.
2620 Note: This function is itself a callback for find_inferior. */
2621
2622 static int
2623 visit_actioned_threads (struct inferior_list_entry *entry, void *datap)
2624 {
2625 struct visit_actioned_threads_data *data
2626 = (struct visit_actioned_threads_data *) datap;
2627 const struct thread_resume *actions = data->actions;
2628 size_t num_actions = data->num_actions;
2629 visit_actioned_threads_callback_ftype *callback = data->callback;
2630 size_t i;
2631
2632 for (i = 0; i < num_actions; i++)
2633 {
2634 const struct thread_resume *action = &actions[i];
2635
2636 if (ptid_equal (action->thread, minus_one_ptid)
2637 || ptid_equal (action->thread, entry->id)
2638 || ((ptid_get_pid (action->thread)
2639 == ptid_get_pid (entry->id))
2640 && ptid_get_lwp (action->thread) == -1))
2641 {
2642 struct thread_info *thread = (struct thread_info *) entry;
2643
2644 if ((*callback) (action, thread))
2645 return 1;
2646 }
2647 }
2648
2649 return 0;
2650 }
2651
2652 /* Callback for visit_actioned_threads. If the thread has a pending
2653 status to report, report it now. */
2654
2655 static int
2656 handle_pending_status (const struct thread_resume *resumption,
2657 struct thread_info *thread)
2658 {
2659 if (thread->status_pending_p)
2660 {
2661 thread->status_pending_p = 0;
2662
2663 last_status = thread->last_status;
2664 last_ptid = thread->entry.id;
2665 prepare_resume_reply (own_buf, last_ptid, &last_status);
2666 return 1;
2667 }
2668 return 0;
2669 }
2670
2671 /* Parse vCont packets. */
2672 static void
2673 handle_v_cont (char *own_buf)
2674 {
2675 char *p, *q;
2676 int n = 0, i = 0;
2677 struct thread_resume *resume_info;
2678 struct thread_resume default_action { null_ptid };
2679
2680 /* Count the number of semicolons in the packet. There should be one
2681 for every action. */
2682 p = &own_buf[5];
2683 while (p)
2684 {
2685 n++;
2686 p++;
2687 p = strchr (p, ';');
2688 }
2689
2690 resume_info = (struct thread_resume *) malloc (n * sizeof (resume_info[0]));
2691 if (resume_info == NULL)
2692 goto err;
2693
2694 p = &own_buf[5];
2695 while (*p)
2696 {
2697 p++;
2698
2699 memset (&resume_info[i], 0, sizeof resume_info[i]);
2700
2701 if (p[0] == 's' || p[0] == 'S')
2702 resume_info[i].kind = resume_step;
2703 else if (p[0] == 'r')
2704 resume_info[i].kind = resume_step;
2705 else if (p[0] == 'c' || p[0] == 'C')
2706 resume_info[i].kind = resume_continue;
2707 else if (p[0] == 't')
2708 resume_info[i].kind = resume_stop;
2709 else
2710 goto err;
2711
2712 if (p[0] == 'S' || p[0] == 'C')
2713 {
2714 int sig;
2715 sig = strtol (p + 1, &q, 16);
2716 if (p == q)
2717 goto err;
2718 p = q;
2719
2720 if (!gdb_signal_to_host_p ((enum gdb_signal) sig))
2721 goto err;
2722 resume_info[i].sig = gdb_signal_to_host ((enum gdb_signal) sig);
2723 }
2724 else if (p[0] == 'r')
2725 {
2726 ULONGEST addr;
2727
2728 p = unpack_varlen_hex (p + 1, &addr);
2729 resume_info[i].step_range_start = addr;
2730
2731 if (*p != ',')
2732 goto err;
2733
2734 p = unpack_varlen_hex (p + 1, &addr);
2735 resume_info[i].step_range_end = addr;
2736 }
2737 else
2738 {
2739 p = p + 1;
2740 }
2741
2742 if (p[0] == 0)
2743 {
2744 resume_info[i].thread = minus_one_ptid;
2745 default_action = resume_info[i];
2746
2747 /* Note: we don't increment i here, we'll overwrite this entry
2748 the next time through. */
2749 }
2750 else if (p[0] == ':')
2751 {
2752 ptid_t ptid = read_ptid (p + 1, &q);
2753
2754 if (p == q)
2755 goto err;
2756 p = q;
2757 if (p[0] != ';' && p[0] != 0)
2758 goto err;
2759
2760 resume_info[i].thread = ptid;
2761
2762 i++;
2763 }
2764 }
2765
2766 if (i < n)
2767 resume_info[i] = default_action;
2768
2769 resume (resume_info, n);
2770 free (resume_info);
2771 return;
2772
2773 err:
2774 write_enn (own_buf);
2775 free (resume_info);
2776 return;
2777 }
2778
2779 /* Resume target with ACTIONS, an array of NUM_ACTIONS elements. */
2780
2781 static void
2782 resume (struct thread_resume *actions, size_t num_actions)
2783 {
2784 if (!non_stop)
2785 {
2786 /* Check if among the threads that GDB wants actioned, there's
2787 one with a pending status to report. If so, skip actually
2788 resuming/stopping and report the pending event
2789 immediately. */
2790 struct visit_actioned_threads_data data;
2791
2792 data.actions = actions;
2793 data.num_actions = num_actions;
2794 data.callback = handle_pending_status;
2795 if (find_inferior (&all_threads, visit_actioned_threads, &data) != NULL)
2796 return;
2797
2798 enable_async_io ();
2799 }
2800
2801 (*the_target->resume) (actions, num_actions);
2802
2803 if (non_stop)
2804 write_ok (own_buf);
2805 else
2806 {
2807 last_ptid = mywait (minus_one_ptid, &last_status, 0, 1);
2808
2809 if (last_status.kind == TARGET_WAITKIND_NO_RESUMED
2810 && !report_no_resumed)
2811 {
2812 /* The client does not support this stop reply. At least
2813 return error. */
2814 sprintf (own_buf, "E.No unwaited-for children left.");
2815 disable_async_io ();
2816 return;
2817 }
2818
2819 if (last_status.kind != TARGET_WAITKIND_EXITED
2820 && last_status.kind != TARGET_WAITKIND_SIGNALLED
2821 && last_status.kind != TARGET_WAITKIND_NO_RESUMED)
2822 current_thread->last_status = last_status;
2823
2824 /* From the client's perspective, all-stop mode always stops all
2825 threads implicitly (and the target backend has already done
2826 so by now). Tag all threads as "want-stopped", so we don't
2827 resume them implicitly without the client telling us to. */
2828 gdb_wants_all_threads_stopped ();
2829 prepare_resume_reply (own_buf, last_ptid, &last_status);
2830 disable_async_io ();
2831
2832 if (last_status.kind == TARGET_WAITKIND_EXITED
2833 || last_status.kind == TARGET_WAITKIND_SIGNALLED)
2834 target_mourn_inferior (last_ptid);
2835 }
2836 }
2837
2838 /* Attach to a new program. Return 1 if successful, 0 if failure. */
2839 static int
2840 handle_v_attach (char *own_buf)
2841 {
2842 int pid;
2843
2844 pid = strtol (own_buf + 8, NULL, 16);
2845 if (pid != 0 && attach_inferior (pid) == 0)
2846 {
2847 /* Don't report shared library events after attaching, even if
2848 some libraries are preloaded. GDB will always poll the
2849 library list. Avoids the "stopped by shared library event"
2850 notice on the GDB side. */
2851 dlls_changed = 0;
2852
2853 if (non_stop)
2854 {
2855 /* In non-stop, we don't send a resume reply. Stop events
2856 will follow up using the normal notification
2857 mechanism. */
2858 write_ok (own_buf);
2859 }
2860 else
2861 prepare_resume_reply (own_buf, last_ptid, &last_status);
2862
2863 return 1;
2864 }
2865 else
2866 {
2867 write_enn (own_buf);
2868 return 0;
2869 }
2870 }
2871
2872 /* Run a new program. Return 1 if successful, 0 if failure. */
2873 static int
2874 handle_v_run (char *own_buf)
2875 {
2876 char *p, *next_p;
2877 std::vector<char *> new_argv;
2878 char *new_program_name = NULL;
2879 int i, new_argc;
2880
2881 new_argc = 0;
2882 for (p = own_buf + strlen ("vRun;"); p && *p; p = strchr (p, ';'))
2883 {
2884 p++;
2885 new_argc++;
2886 }
2887
2888 for (i = 0, p = own_buf + strlen ("vRun;"); *p; p = next_p, ++i)
2889 {
2890 next_p = strchr (p, ';');
2891 if (next_p == NULL)
2892 next_p = p + strlen (p);
2893
2894 if (i == 0 && p == next_p)
2895 {
2896 /* No program specified. */
2897 new_program_name = NULL;
2898 }
2899 else if (p == next_p)
2900 {
2901 /* Empty argument. */
2902 new_argv.push_back (xstrdup ("''"));
2903 }
2904 else
2905 {
2906 size_t len = (next_p - p) / 2;
2907 /* ARG is the unquoted argument received via the RSP. */
2908 char *arg = (char *) xmalloc (len + 1);
2909 /* FULL_ARGS will contain the quoted version of ARG. */
2910 char *full_arg = (char *) xmalloc ((len + 1) * 2);
2911 /* These are pointers used to navigate the strings above. */
2912 char *tmp_arg = arg;
2913 char *tmp_full_arg = full_arg;
2914 int need_quote = 0;
2915
2916 hex2bin (p, (gdb_byte *) arg, len);
2917 arg[len] = '\0';
2918
2919 while (*tmp_arg != '\0')
2920 {
2921 switch (*tmp_arg)
2922 {
2923 case '\n':
2924 /* Quote \n. */
2925 *tmp_full_arg = '\'';
2926 ++tmp_full_arg;
2927 need_quote = 1;
2928 break;
2929
2930 case '\'':
2931 /* Quote single quote. */
2932 *tmp_full_arg = '\\';
2933 ++tmp_full_arg;
2934 break;
2935
2936 default:
2937 break;
2938 }
2939
2940 *tmp_full_arg = *tmp_arg;
2941 ++tmp_full_arg;
2942 ++tmp_arg;
2943 }
2944
2945 if (need_quote)
2946 *tmp_full_arg++ = '\'';
2947
2948 /* Finish FULL_ARG and push it into the vector containing
2949 the argv. */
2950 *tmp_full_arg = '\0';
2951 if (i == 0)
2952 new_program_name = full_arg;
2953 else
2954 new_argv.push_back (full_arg);
2955 xfree (arg);
2956 }
2957 if (*next_p)
2958 next_p++;
2959 }
2960 new_argv.push_back (NULL);
2961
2962 if (new_program_name == NULL)
2963 {
2964 /* GDB didn't specify a program to run. Use the program from the
2965 last run with the new argument list. */
2966 if (program_name == NULL)
2967 {
2968 write_enn (own_buf);
2969 free_vector_argv (new_argv);
2970 return 0;
2971 }
2972 }
2973 else
2974 {
2975 xfree (program_name);
2976 program_name = new_program_name;
2977 }
2978
2979 /* Free the old argv and install the new one. */
2980 free_vector_argv (program_args);
2981 program_args = new_argv;
2982
2983 create_inferior (program_name, program_args);
2984
2985 if (last_status.kind == TARGET_WAITKIND_STOPPED)
2986 {
2987 prepare_resume_reply (own_buf, last_ptid, &last_status);
2988
2989 /* In non-stop, sending a resume reply doesn't set the general
2990 thread, but GDB assumes a vRun sets it (this is so GDB can
2991 query which is the main thread of the new inferior. */
2992 if (non_stop)
2993 general_thread = last_ptid;
2994
2995 return 1;
2996 }
2997 else
2998 {
2999 write_enn (own_buf);
3000 return 0;
3001 }
3002 }
3003
3004 /* Kill process. Return 1 if successful, 0 if failure. */
3005 static int
3006 handle_v_kill (char *own_buf)
3007 {
3008 int pid;
3009 char *p = &own_buf[6];
3010 if (multi_process)
3011 pid = strtol (p, NULL, 16);
3012 else
3013 pid = signal_pid;
3014 if (pid != 0 && kill_inferior (pid) == 0)
3015 {
3016 last_status.kind = TARGET_WAITKIND_SIGNALLED;
3017 last_status.value.sig = GDB_SIGNAL_KILL;
3018 last_ptid = pid_to_ptid (pid);
3019 discard_queued_stop_replies (last_ptid);
3020 write_ok (own_buf);
3021 return 1;
3022 }
3023 else
3024 {
3025 write_enn (own_buf);
3026 return 0;
3027 }
3028 }
3029
3030 /* Handle all of the extended 'v' packets. */
3031 void
3032 handle_v_requests (char *own_buf, int packet_len, int *new_packet_len)
3033 {
3034 if (!disable_packet_vCont)
3035 {
3036 if (strcmp (own_buf, "vCtrlC") == 0)
3037 {
3038 (*the_target->request_interrupt) ();
3039 write_ok (own_buf);
3040 return;
3041 }
3042
3043 if (startswith (own_buf, "vCont;"))
3044 {
3045 handle_v_cont (own_buf);
3046 return;
3047 }
3048
3049 if (startswith (own_buf, "vCont?"))
3050 {
3051 strcpy (own_buf, "vCont;c;C;t");
3052
3053 if (target_supports_hardware_single_step ()
3054 || target_supports_software_single_step ()
3055 || !vCont_supported)
3056 {
3057 /* If target supports single step either by hardware or by
3058 software, add actions s and S to the list of supported
3059 actions. On the other hand, if GDB doesn't request the
3060 supported vCont actions in qSupported packet, add s and
3061 S to the list too. */
3062 own_buf = own_buf + strlen (own_buf);
3063 strcpy (own_buf, ";s;S");
3064 }
3065
3066 if (target_supports_range_stepping ())
3067 {
3068 own_buf = own_buf + strlen (own_buf);
3069 strcpy (own_buf, ";r");
3070 }
3071 return;
3072 }
3073 }
3074
3075 if (startswith (own_buf, "vFile:")
3076 && handle_vFile (own_buf, packet_len, new_packet_len))
3077 return;
3078
3079 if (startswith (own_buf, "vAttach;"))
3080 {
3081 if ((!extended_protocol || !multi_process) && target_running ())
3082 {
3083 fprintf (stderr, "Already debugging a process\n");
3084 write_enn (own_buf);
3085 return;
3086 }
3087 handle_v_attach (own_buf);
3088 return;
3089 }
3090
3091 if (startswith (own_buf, "vRun;"))
3092 {
3093 if ((!extended_protocol || !multi_process) && target_running ())
3094 {
3095 fprintf (stderr, "Already debugging a process\n");
3096 write_enn (own_buf);
3097 return;
3098 }
3099 handle_v_run (own_buf);
3100 return;
3101 }
3102
3103 if (startswith (own_buf, "vKill;"))
3104 {
3105 if (!target_running ())
3106 {
3107 fprintf (stderr, "No process to kill\n");
3108 write_enn (own_buf);
3109 return;
3110 }
3111 handle_v_kill (own_buf);
3112 return;
3113 }
3114
3115 if (handle_notif_ack (own_buf, packet_len))
3116 return;
3117
3118 /* Otherwise we didn't know what packet it was. Say we didn't
3119 understand it. */
3120 own_buf[0] = 0;
3121 return;
3122 }
3123
3124 /* Resume thread and wait for another event. In non-stop mode,
3125 don't really wait here, but return immediatelly to the event
3126 loop. */
3127 static void
3128 myresume (char *own_buf, int step, int sig)
3129 {
3130 struct thread_resume resume_info[2];
3131 int n = 0;
3132 int valid_cont_thread;
3133
3134 valid_cont_thread = (!ptid_equal (cont_thread, null_ptid)
3135 && !ptid_equal (cont_thread, minus_one_ptid));
3136
3137 if (step || sig || valid_cont_thread)
3138 {
3139 resume_info[0].thread = current_ptid;
3140 if (step)
3141 resume_info[0].kind = resume_step;
3142 else
3143 resume_info[0].kind = resume_continue;
3144 resume_info[0].sig = sig;
3145 n++;
3146 }
3147
3148 if (!valid_cont_thread)
3149 {
3150 resume_info[n].thread = minus_one_ptid;
3151 resume_info[n].kind = resume_continue;
3152 resume_info[n].sig = 0;
3153 n++;
3154 }
3155
3156 resume (resume_info, n);
3157 }
3158
3159 /* Callback for for_each_inferior. Make a new stop reply for each
3160 stopped thread. */
3161
3162 static int
3163 queue_stop_reply_callback (struct inferior_list_entry *entry, void *arg)
3164 {
3165 struct thread_info *thread = (struct thread_info *) entry;
3166
3167 /* For now, assume targets that don't have this callback also don't
3168 manage the thread's last_status field. */
3169 if (the_target->thread_stopped == NULL)
3170 {
3171 struct vstop_notif *new_notif = XNEW (struct vstop_notif);
3172
3173 new_notif->ptid = entry->id;
3174 new_notif->status = thread->last_status;
3175 /* Pass the last stop reply back to GDB, but don't notify
3176 yet. */
3177 notif_event_enque (&notif_stop,
3178 (struct notif_event *) new_notif);
3179 }
3180 else
3181 {
3182 if (thread_stopped (thread))
3183 {
3184 if (debug_threads)
3185 {
3186 std::string status_string
3187 = target_waitstatus_to_string (&thread->last_status);
3188
3189 debug_printf ("Reporting thread %s as already stopped with %s\n",
3190 target_pid_to_str (entry->id),
3191 status_string.c_str ());
3192 }
3193
3194 gdb_assert (thread->last_status.kind != TARGET_WAITKIND_IGNORE);
3195
3196 /* Pass the last stop reply back to GDB, but don't notify
3197 yet. */
3198 queue_stop_reply (entry->id, &thread->last_status);
3199 }
3200 }
3201
3202 return 0;
3203 }
3204
3205 /* Set this inferior threads's state as "want-stopped". We won't
3206 resume this thread until the client gives us another action for
3207 it. */
3208
3209 static void
3210 gdb_wants_thread_stopped (struct inferior_list_entry *entry)
3211 {
3212 struct thread_info *thread = (struct thread_info *) entry;
3213
3214 thread->last_resume_kind = resume_stop;
3215
3216 if (thread->last_status.kind == TARGET_WAITKIND_IGNORE)
3217 {
3218 /* Most threads are stopped implicitly (all-stop); tag that with
3219 signal 0. */
3220 thread->last_status.kind = TARGET_WAITKIND_STOPPED;
3221 thread->last_status.value.sig = GDB_SIGNAL_0;
3222 }
3223 }
3224
3225 /* Set all threads' states as "want-stopped". */
3226
3227 static void
3228 gdb_wants_all_threads_stopped (void)
3229 {
3230 for_each_inferior (&all_threads, gdb_wants_thread_stopped);
3231 }
3232
3233 /* Clear the gdb_detached flag of every process. */
3234
3235 static void
3236 gdb_reattached_process (struct inferior_list_entry *entry)
3237 {
3238 struct process_info *process = (struct process_info *) entry;
3239
3240 process->gdb_detached = 0;
3241 }
3242
3243 /* Callback for for_each_inferior. Clear the thread's pending status
3244 flag. */
3245
3246 static void
3247 clear_pending_status_callback (struct inferior_list_entry *entry)
3248 {
3249 struct thread_info *thread = (struct thread_info *) entry;
3250
3251 thread->status_pending_p = 0;
3252 }
3253
3254 /* Callback for for_each_inferior. If the thread is stopped with an
3255 interesting event, mark it as having a pending event. */
3256
3257 static void
3258 set_pending_status_callback (struct inferior_list_entry *entry)
3259 {
3260 struct thread_info *thread = (struct thread_info *) entry;
3261
3262 if (thread->last_status.kind != TARGET_WAITKIND_STOPPED
3263 || (thread->last_status.value.sig != GDB_SIGNAL_0
3264 /* A breakpoint, watchpoint or finished step from a previous
3265 GDB run isn't considered interesting for a new GDB run.
3266 If we left those pending, the new GDB could consider them
3267 random SIGTRAPs. This leaves out real async traps. We'd
3268 have to peek into the (target-specific) siginfo to
3269 distinguish those. */
3270 && thread->last_status.value.sig != GDB_SIGNAL_TRAP))
3271 thread->status_pending_p = 1;
3272 }
3273
3274 /* Callback for find_inferior. Return true if ENTRY (a thread) has a
3275 pending status to report to GDB. */
3276
3277 static int
3278 find_status_pending_thread_callback (struct inferior_list_entry *entry, void *data)
3279 {
3280 struct thread_info *thread = (struct thread_info *) entry;
3281
3282 return thread->status_pending_p;
3283 }
3284
3285 /* Status handler for the '?' packet. */
3286
3287 static void
3288 handle_status (char *own_buf)
3289 {
3290 /* GDB is connected, don't forward events to the target anymore. */
3291 for_each_inferior (&all_processes, gdb_reattached_process);
3292
3293 /* In non-stop mode, we must send a stop reply for each stopped
3294 thread. In all-stop mode, just send one for the first stopped
3295 thread we find. */
3296
3297 if (non_stop)
3298 {
3299 find_inferior (&all_threads, queue_stop_reply_callback, NULL);
3300
3301 /* The first is sent immediatly. OK is sent if there is no
3302 stopped thread, which is the same handling of the vStopped
3303 packet (by design). */
3304 notif_write_event (&notif_stop, own_buf);
3305 }
3306 else
3307 {
3308 struct inferior_list_entry *thread = NULL;
3309
3310 pause_all (0);
3311 stabilize_threads ();
3312 gdb_wants_all_threads_stopped ();
3313
3314 /* We can only report one status, but we might be coming out of
3315 non-stop -- if more than one thread is stopped with
3316 interesting events, leave events for the threads we're not
3317 reporting now pending. They'll be reported the next time the
3318 threads are resumed. Start by marking all interesting events
3319 as pending. */
3320 for_each_inferior (&all_threads, set_pending_status_callback);
3321
3322 /* Prefer the last thread that reported an event to GDB (even if
3323 that was a GDB_SIGNAL_TRAP). */
3324 if (last_status.kind != TARGET_WAITKIND_IGNORE
3325 && last_status.kind != TARGET_WAITKIND_EXITED
3326 && last_status.kind != TARGET_WAITKIND_SIGNALLED)
3327 thread = find_inferior_id (&all_threads, last_ptid);
3328
3329 /* If the last event thread is not found for some reason, look
3330 for some other thread that might have an event to report. */
3331 if (thread == NULL)
3332 thread = find_inferior (&all_threads,
3333 find_status_pending_thread_callback, NULL);
3334
3335 /* If we're still out of luck, simply pick the first thread in
3336 the thread list. */
3337 if (thread == NULL)
3338 thread = get_first_inferior (&all_threads);
3339
3340 if (thread != NULL)
3341 {
3342 struct thread_info *tp = (struct thread_info *) thread;
3343
3344 /* We're reporting this event, so it's no longer
3345 pending. */
3346 tp->status_pending_p = 0;
3347
3348 /* GDB assumes the current thread is the thread we're
3349 reporting the status for. */
3350 general_thread = thread->id;
3351 set_desired_thread (1);
3352
3353 gdb_assert (tp->last_status.kind != TARGET_WAITKIND_IGNORE);
3354 prepare_resume_reply (own_buf, tp->entry.id, &tp->last_status);
3355 }
3356 else
3357 strcpy (own_buf, "W00");
3358 }
3359 }
3360
3361 static void
3362 gdbserver_version (void)
3363 {
3364 printf ("GNU gdbserver %s%s\n"
3365 "Copyright (C) 2017 Free Software Foundation, Inc.\n"
3366 "gdbserver is free software, covered by the "
3367 "GNU General Public License.\n"
3368 "This gdbserver was configured as \"%s\"\n",
3369 PKGVERSION, version, host_name);
3370 }
3371
3372 static void
3373 gdbserver_usage (FILE *stream)
3374 {
3375 fprintf (stream, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
3376 "\tgdbserver [OPTIONS] --attach COMM PID\n"
3377 "\tgdbserver [OPTIONS] --multi COMM\n"
3378 "\n"
3379 "COMM may either be a tty device (for serial debugging),\n"
3380 "HOST:PORT to listen for a TCP connection, or '-' or 'stdio' to use \n"
3381 "stdin/stdout of gdbserver.\n"
3382 "PROG is the executable program. ARGS are arguments passed to inferior.\n"
3383 "PID is the process ID to attach to, when --attach is specified.\n"
3384 "\n"
3385 "Operating modes:\n"
3386 "\n"
3387 " --attach Attach to running process PID.\n"
3388 " --multi Start server without a specific program, and\n"
3389 " only quit when explicitly commanded.\n"
3390 " --once Exit after the first connection has closed.\n"
3391 " --help Print this message and then exit.\n"
3392 " --version Display version information and exit.\n"
3393 "\n"
3394 "Other options:\n"
3395 "\n"
3396 " --wrapper WRAPPER -- Run WRAPPER to start new programs.\n"
3397 " --disable-randomization\n"
3398 " Run PROG with address space randomization disabled.\n"
3399 " --no-disable-randomization\n"
3400 " Don't disable address space randomization when\n"
3401 " starting PROG.\n"
3402 " --startup-with-shell\n"
3403 " Start PROG using a shell. I.e., execs a shell that\n"
3404 " then execs PROG. (default)\n"
3405 " --no-startup-with-shell\n"
3406 " Exec PROG directly instead of using a shell.\n"
3407 " Disables argument globbing and variable substitution\n"
3408 " on UNIX-like systems.\n"
3409 "\n"
3410 "Debug options:\n"
3411 "\n"
3412 " --debug Enable general debugging output.\n"
3413 " --debug-format=opt1[,opt2,...]\n"
3414 " Specify extra content in debugging output.\n"
3415 " Options:\n"
3416 " all\n"
3417 " none\n"
3418 " timestamp\n"
3419 " --remote-debug Enable remote protocol debugging output.\n"
3420 " --disable-packet=opt1[,opt2,...]\n"
3421 " Disable support for RSP packets or features.\n"
3422 " Options:\n"
3423 " vCont, Tthread, qC, qfThreadInfo and \n"
3424 " threads (disable all threading packets).\n"
3425 "\n"
3426 "For more information, consult the GDB manual (available as on-line \n"
3427 "info or a printed manual).\n");
3428 if (REPORT_BUGS_TO[0] && stream == stdout)
3429 fprintf (stream, "Report bugs to \"%s\".\n", REPORT_BUGS_TO);
3430 }
3431
3432 static void
3433 gdbserver_show_disableable (FILE *stream)
3434 {
3435 fprintf (stream, "Disableable packets:\n"
3436 " vCont \tAll vCont packets\n"
3437 " qC \tQuerying the current thread\n"
3438 " qfThreadInfo\tThread listing\n"
3439 " Tthread \tPassing the thread specifier in the "
3440 "T stop reply packet\n"
3441 " threads \tAll of the above\n");
3442 }
3443
3444
3445 #undef require_running
3446 #define require_running(BUF) \
3447 if (!target_running ()) \
3448 { \
3449 write_enn (BUF); \
3450 break; \
3451 }
3452
3453 static void
3454 kill_inferior_callback (struct inferior_list_entry *entry)
3455 {
3456 struct process_info *process = (struct process_info *) entry;
3457 int pid = ptid_get_pid (process->entry.id);
3458
3459 kill_inferior (pid);
3460 discard_queued_stop_replies (pid_to_ptid (pid));
3461 }
3462
3463 /* Callback for for_each_inferior to detach or kill the inferior,
3464 depending on whether we attached to it or not.
3465 We inform the user whether we're detaching or killing the process
3466 as this is only called when gdbserver is about to exit. */
3467
3468 static void
3469 detach_or_kill_inferior_callback (struct inferior_list_entry *entry)
3470 {
3471 struct process_info *process = (struct process_info *) entry;
3472 int pid = ptid_get_pid (process->entry.id);
3473
3474 if (process->attached)
3475 detach_inferior (pid);
3476 else
3477 kill_inferior (pid);
3478
3479 discard_queued_stop_replies (pid_to_ptid (pid));
3480 }
3481
3482 /* for_each_inferior callback for detach_or_kill_for_exit to print
3483 the pids of started inferiors. */
3484
3485 static void
3486 print_started_pid (struct inferior_list_entry *entry)
3487 {
3488 struct process_info *process = (struct process_info *) entry;
3489
3490 if (! process->attached)
3491 {
3492 int pid = ptid_get_pid (process->entry.id);
3493 fprintf (stderr, " %d", pid);
3494 }
3495 }
3496
3497 /* for_each_inferior callback for detach_or_kill_for_exit to print
3498 the pids of attached inferiors. */
3499
3500 static void
3501 print_attached_pid (struct inferior_list_entry *entry)
3502 {
3503 struct process_info *process = (struct process_info *) entry;
3504
3505 if (process->attached)
3506 {
3507 int pid = ptid_get_pid (process->entry.id);
3508 fprintf (stderr, " %d", pid);
3509 }
3510 }
3511
3512 /* Call this when exiting gdbserver with possible inferiors that need
3513 to be killed or detached from. */
3514
3515 static void
3516 detach_or_kill_for_exit (void)
3517 {
3518 /* First print a list of the inferiors we will be killing/detaching.
3519 This is to assist the user, for example, in case the inferior unexpectedly
3520 dies after we exit: did we screw up or did the inferior exit on its own?
3521 Having this info will save some head-scratching. */
3522
3523 if (have_started_inferiors_p ())
3524 {
3525 fprintf (stderr, "Killing process(es):");
3526 for_each_inferior (&all_processes, print_started_pid);
3527 fprintf (stderr, "\n");
3528 }
3529 if (have_attached_inferiors_p ())
3530 {
3531 fprintf (stderr, "Detaching process(es):");
3532 for_each_inferior (&all_processes, print_attached_pid);
3533 fprintf (stderr, "\n");
3534 }
3535
3536 /* Now we can kill or detach the inferiors. */
3537
3538 for_each_inferior (&all_processes, detach_or_kill_inferior_callback);
3539 }
3540
3541 /* Value that will be passed to exit(3) when gdbserver exits. */
3542 static int exit_code;
3543
3544 /* Cleanup version of detach_or_kill_for_exit. */
3545
3546 static void
3547 detach_or_kill_for_exit_cleanup (void *ignore)
3548 {
3549
3550 TRY
3551 {
3552 detach_or_kill_for_exit ();
3553 }
3554
3555 CATCH (exception, RETURN_MASK_ALL)
3556 {
3557 fflush (stdout);
3558 fprintf (stderr, "Detach or kill failed: %s\n", exception.message);
3559 exit_code = 1;
3560 }
3561 END_CATCH
3562 }
3563
3564 /* Main function. This is called by the real "main" function,
3565 wrapped in a TRY_CATCH that handles any uncaught exceptions. */
3566
3567 static void ATTRIBUTE_NORETURN
3568 captured_main (int argc, char *argv[])
3569 {
3570 int bad_attach;
3571 int pid;
3572 char *arg_end;
3573 const char *port = NULL;
3574 char **next_arg = &argv[1];
3575 volatile int multi_mode = 0;
3576 volatile int attach = 0;
3577 int was_running;
3578 bool selftest = false;
3579
3580 while (*next_arg != NULL && **next_arg == '-')
3581 {
3582 if (strcmp (*next_arg, "--version") == 0)
3583 {
3584 gdbserver_version ();
3585 exit (0);
3586 }
3587 else if (strcmp (*next_arg, "--help") == 0)
3588 {
3589 gdbserver_usage (stdout);
3590 exit (0);
3591 }
3592 else if (strcmp (*next_arg, "--attach") == 0)
3593 attach = 1;
3594 else if (strcmp (*next_arg, "--multi") == 0)
3595 multi_mode = 1;
3596 else if (strcmp (*next_arg, "--wrapper") == 0)
3597 {
3598 char **tmp;
3599
3600 next_arg++;
3601
3602 tmp = next_arg;
3603 while (*next_arg != NULL && strcmp (*next_arg, "--") != 0)
3604 {
3605 wrapper_argv += *next_arg;
3606 wrapper_argv += ' ';
3607 next_arg++;
3608 }
3609
3610 if (!wrapper_argv.empty ())
3611 {
3612 /* Erase the last whitespace. */
3613 wrapper_argv.erase (wrapper_argv.end () - 1);
3614 }
3615
3616 if (next_arg == tmp || *next_arg == NULL)
3617 {
3618 gdbserver_usage (stderr);
3619 exit (1);
3620 }
3621
3622 /* Consume the "--". */
3623 *next_arg = NULL;
3624 }
3625 else if (strcmp (*next_arg, "--debug") == 0)
3626 debug_threads = 1;
3627 else if (startswith (*next_arg, "--debug-format="))
3628 {
3629 char *error_msg
3630 = parse_debug_format_options ((*next_arg)
3631 + sizeof ("--debug-format=") - 1, 0);
3632
3633 if (error_msg != NULL)
3634 {
3635 fprintf (stderr, "%s", error_msg);
3636 exit (1);
3637 }
3638 }
3639 else if (strcmp (*next_arg, "--remote-debug") == 0)
3640 remote_debug = 1;
3641 else if (strcmp (*next_arg, "--disable-packet") == 0)
3642 {
3643 gdbserver_show_disableable (stdout);
3644 exit (0);
3645 }
3646 else if (startswith (*next_arg, "--disable-packet="))
3647 {
3648 char *packets, *tok;
3649
3650 packets = *next_arg += sizeof ("--disable-packet=") - 1;
3651 for (tok = strtok (packets, ",");
3652 tok != NULL;
3653 tok = strtok (NULL, ","))
3654 {
3655 if (strcmp ("vCont", tok) == 0)
3656 disable_packet_vCont = 1;
3657 else if (strcmp ("Tthread", tok) == 0)
3658 disable_packet_Tthread = 1;
3659 else if (strcmp ("qC", tok) == 0)
3660 disable_packet_qC = 1;
3661 else if (strcmp ("qfThreadInfo", tok) == 0)
3662 disable_packet_qfThreadInfo = 1;
3663 else if (strcmp ("threads", tok) == 0)
3664 {
3665 disable_packet_vCont = 1;
3666 disable_packet_Tthread = 1;
3667 disable_packet_qC = 1;
3668 disable_packet_qfThreadInfo = 1;
3669 }
3670 else
3671 {
3672 fprintf (stderr, "Don't know how to disable \"%s\".\n\n",
3673 tok);
3674 gdbserver_show_disableable (stderr);
3675 exit (1);
3676 }
3677 }
3678 }
3679 else if (strcmp (*next_arg, "-") == 0)
3680 {
3681 /* "-" specifies a stdio connection and is a form of port
3682 specification. */
3683 port = STDIO_CONNECTION_NAME;
3684 next_arg++;
3685 break;
3686 }
3687 else if (strcmp (*next_arg, "--disable-randomization") == 0)
3688 disable_randomization = 1;
3689 else if (strcmp (*next_arg, "--no-disable-randomization") == 0)
3690 disable_randomization = 0;
3691 else if (strcmp (*next_arg, "--startup-with-shell") == 0)
3692 startup_with_shell = true;
3693 else if (strcmp (*next_arg, "--no-startup-with-shell") == 0)
3694 startup_with_shell = false;
3695 else if (strcmp (*next_arg, "--once") == 0)
3696 run_once = 1;
3697 else if (strcmp (*next_arg, "--selftest") == 0)
3698 selftest = true;
3699 else
3700 {
3701 fprintf (stderr, "Unknown argument: %s\n", *next_arg);
3702 exit (1);
3703 }
3704
3705 next_arg++;
3706 continue;
3707 }
3708
3709 if (port == NULL)
3710 {
3711 port = *next_arg;
3712 next_arg++;
3713 }
3714 if ((port == NULL || (!attach && !multi_mode && *next_arg == NULL))
3715 && !selftest)
3716 {
3717 gdbserver_usage (stderr);
3718 exit (1);
3719 }
3720
3721 /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
3722 opened by remote_prepare. */
3723 notice_open_fds ();
3724
3725 save_original_signals_state ();
3726
3727 /* We need to know whether the remote connection is stdio before
3728 starting the inferior. Inferiors created in this scenario have
3729 stdin,stdout redirected. So do this here before we call
3730 start_inferior. */
3731 if (port != NULL)
3732 remote_prepare (port);
3733
3734 bad_attach = 0;
3735 pid = 0;
3736
3737 /* --attach used to come after PORT, so allow it there for
3738 compatibility. */
3739 if (*next_arg != NULL && strcmp (*next_arg, "--attach") == 0)
3740 {
3741 attach = 1;
3742 next_arg++;
3743 }
3744
3745 if (attach
3746 && (*next_arg == NULL
3747 || (*next_arg)[0] == '\0'
3748 || (pid = strtoul (*next_arg, &arg_end, 0)) == 0
3749 || *arg_end != '\0'
3750 || next_arg[1] != NULL))
3751 bad_attach = 1;
3752
3753 if (bad_attach)
3754 {
3755 gdbserver_usage (stderr);
3756 exit (1);
3757 }
3758
3759 /* Gather information about the environment. */
3760 our_environ = gdb_environ::from_host_environ ();
3761
3762 initialize_async_io ();
3763 initialize_low ();
3764 have_job_control ();
3765 initialize_event_loop ();
3766 if (target_supports_tracepoints ())
3767 initialize_tracepoint ();
3768 initialize_notif ();
3769
3770 own_buf = (char *) xmalloc (PBUFSIZ + 1);
3771 mem_buf = (unsigned char *) xmalloc (PBUFSIZ);
3772
3773 if (selftest)
3774 {
3775 selftests::run_tests ();
3776 throw_quit ("Quit");
3777 }
3778
3779 if (pid == 0 && *next_arg != NULL)
3780 {
3781 int i, n;
3782
3783 n = argc - (next_arg - argv);
3784 program_name = xstrdup (next_arg[0]);
3785 for (i = 1; i < n; i++)
3786 program_args.push_back (xstrdup (next_arg[i]));
3787 program_args.push_back (NULL);
3788
3789 /* Wait till we are at first instruction in program. */
3790 create_inferior (program_name, program_args);
3791
3792 /* We are now (hopefully) stopped at the first instruction of
3793 the target process. This assumes that the target process was
3794 successfully created. */
3795 }
3796 else if (pid != 0)
3797 {
3798 if (attach_inferior (pid) == -1)
3799 error ("Attaching not supported on this target");
3800
3801 /* Otherwise succeeded. */
3802 }
3803 else
3804 {
3805 last_status.kind = TARGET_WAITKIND_EXITED;
3806 last_status.value.integer = 0;
3807 last_ptid = minus_one_ptid;
3808 }
3809 make_cleanup (detach_or_kill_for_exit_cleanup, NULL);
3810
3811 /* Don't report shared library events on the initial connection,
3812 even if some libraries are preloaded. Avoids the "stopped by
3813 shared library event" notice on gdb side. */
3814 dlls_changed = 0;
3815
3816 if (last_status.kind == TARGET_WAITKIND_EXITED
3817 || last_status.kind == TARGET_WAITKIND_SIGNALLED)
3818 was_running = 0;
3819 else
3820 was_running = 1;
3821
3822 if (!was_running && !multi_mode)
3823 error ("No program to debug");
3824
3825 while (1)
3826 {
3827
3828 noack_mode = 0;
3829 multi_process = 0;
3830 report_fork_events = 0;
3831 report_vfork_events = 0;
3832 report_exec_events = 0;
3833 /* Be sure we're out of tfind mode. */
3834 current_traceframe = -1;
3835 cont_thread = null_ptid;
3836 swbreak_feature = 0;
3837 hwbreak_feature = 0;
3838 vCont_supported = 0;
3839
3840 remote_open (port);
3841
3842 TRY
3843 {
3844 /* Wait for events. This will return when all event sources
3845 are removed from the event loop. */
3846 start_event_loop ();
3847
3848 /* If an exit was requested (using the "monitor exit"
3849 command), terminate now. */
3850 if (exit_requested)
3851 throw_quit ("Quit");
3852
3853 /* The only other way to get here is for getpkt to fail:
3854
3855 - If --once was specified, we're done.
3856
3857 - If not in extended-remote mode, and we're no longer
3858 debugging anything, simply exit: GDB has disconnected
3859 after processing the last process exit.
3860
3861 - Otherwise, close the connection and reopen it at the
3862 top of the loop. */
3863 if (run_once || (!extended_protocol && !target_running ()))
3864 throw_quit ("Quit");
3865
3866 fprintf (stderr,
3867 "Remote side has terminated connection. "
3868 "GDBserver will reopen the connection.\n");
3869
3870 /* Get rid of any pending statuses. An eventual reconnection
3871 (by the same GDB instance or another) will refresh all its
3872 state from scratch. */
3873 discard_queued_stop_replies (minus_one_ptid);
3874 for_each_inferior (&all_threads,
3875 clear_pending_status_callback);
3876
3877 if (tracing)
3878 {
3879 if (disconnected_tracing)
3880 {
3881 /* Try to enable non-stop/async mode, so we we can
3882 both wait for an async socket accept, and handle
3883 async target events simultaneously. There's also
3884 no point either in having the target always stop
3885 all threads, when we're going to pass signals
3886 down without informing GDB. */
3887 if (!non_stop)
3888 {
3889 if (start_non_stop (1))
3890 non_stop = 1;
3891
3892 /* Detaching implicitly resumes all threads;
3893 simply disconnecting does not. */
3894 }
3895 }
3896 else
3897 {
3898 fprintf (stderr,
3899 "Disconnected tracing disabled; "
3900 "stopping trace run.\n");
3901 stop_tracing ();
3902 }
3903 }
3904 }
3905 CATCH (exception, RETURN_MASK_ERROR)
3906 {
3907 fflush (stdout);
3908 fprintf (stderr, "gdbserver: %s\n", exception.message);
3909
3910 if (response_needed)
3911 {
3912 write_enn (own_buf);
3913 putpkt (own_buf);
3914 }
3915
3916 if (run_once)
3917 throw_quit ("Quit");
3918 }
3919 END_CATCH
3920 }
3921 }
3922
3923 /* Main function. */
3924
3925 int
3926 main (int argc, char *argv[])
3927 {
3928
3929 TRY
3930 {
3931 captured_main (argc, argv);
3932 }
3933 CATCH (exception, RETURN_MASK_ALL)
3934 {
3935 if (exception.reason == RETURN_ERROR)
3936 {
3937 fflush (stdout);
3938 fprintf (stderr, "%s\n", exception.message);
3939 fprintf (stderr, "Exiting\n");
3940 exit_code = 1;
3941 }
3942
3943 exit (exit_code);
3944 }
3945 END_CATCH
3946
3947 gdb_assert_not_reached ("captured_main should never return");
3948 }
3949
3950 /* Process options coming from Z packets for a breakpoint. PACKET is
3951 the packet buffer. *PACKET is updated to point to the first char
3952 after the last processed option. */
3953
3954 static void
3955 process_point_options (struct gdb_breakpoint *bp, char **packet)
3956 {
3957 char *dataptr = *packet;
3958 int persist;
3959
3960 /* Check if data has the correct format. */
3961 if (*dataptr != ';')
3962 return;
3963
3964 dataptr++;
3965
3966 while (*dataptr)
3967 {
3968 if (*dataptr == ';')
3969 ++dataptr;
3970
3971 if (*dataptr == 'X')
3972 {
3973 /* Conditional expression. */
3974 if (debug_threads)
3975 debug_printf ("Found breakpoint condition.\n");
3976 if (!add_breakpoint_condition (bp, &dataptr))
3977 dataptr = strchrnul (dataptr, ';');
3978 }
3979 else if (startswith (dataptr, "cmds:"))
3980 {
3981 dataptr += strlen ("cmds:");
3982 if (debug_threads)
3983 debug_printf ("Found breakpoint commands %s.\n", dataptr);
3984 persist = (*dataptr == '1');
3985 dataptr += 2;
3986 if (add_breakpoint_commands (bp, &dataptr, persist))
3987 dataptr = strchrnul (dataptr, ';');
3988 }
3989 else
3990 {
3991 fprintf (stderr, "Unknown token %c, ignoring.\n",
3992 *dataptr);
3993 /* Skip tokens until we find one that we recognize. */
3994 dataptr = strchrnul (dataptr, ';');
3995 }
3996 }
3997 *packet = dataptr;
3998 }
3999
4000 /* Event loop callback that handles a serial event. The first byte in
4001 the serial buffer gets us here. We expect characters to arrive at
4002 a brisk pace, so we read the rest of the packet with a blocking
4003 getpkt call. */
4004
4005 static int
4006 process_serial_event (void)
4007 {
4008 char ch;
4009 int i = 0;
4010 int signal;
4011 unsigned int len;
4012 int res;
4013 CORE_ADDR mem_addr;
4014 int pid;
4015 unsigned char sig;
4016 int packet_len;
4017 int new_packet_len = -1;
4018
4019 disable_async_io ();
4020
4021 response_needed = 0;
4022 packet_len = getpkt (own_buf);
4023 if (packet_len <= 0)
4024 {
4025 remote_close ();
4026 /* Force an event loop break. */
4027 return -1;
4028 }
4029 response_needed = 1;
4030
4031 i = 0;
4032 ch = own_buf[i++];
4033 switch (ch)
4034 {
4035 case 'q':
4036 handle_query (own_buf, packet_len, &new_packet_len);
4037 break;
4038 case 'Q':
4039 handle_general_set (own_buf);
4040 break;
4041 case 'D':
4042 require_running (own_buf);
4043
4044 if (multi_process)
4045 {
4046 i++; /* skip ';' */
4047 pid = strtol (&own_buf[i], NULL, 16);
4048 }
4049 else
4050 pid = ptid_get_pid (current_ptid);
4051
4052 if ((tracing && disconnected_tracing) || any_persistent_commands ())
4053 {
4054 struct process_info *process = find_process_pid (pid);
4055
4056 if (process == NULL)
4057 {
4058 write_enn (own_buf);
4059 break;
4060 }
4061
4062 if (tracing && disconnected_tracing)
4063 fprintf (stderr,
4064 "Disconnected tracing in effect, "
4065 "leaving gdbserver attached to the process\n");
4066
4067 if (any_persistent_commands ())
4068 fprintf (stderr,
4069 "Persistent commands are present, "
4070 "leaving gdbserver attached to the process\n");
4071
4072 /* Make sure we're in non-stop/async mode, so we we can both
4073 wait for an async socket accept, and handle async target
4074 events simultaneously. There's also no point either in
4075 having the target stop all threads, when we're going to
4076 pass signals down without informing GDB. */
4077 if (!non_stop)
4078 {
4079 if (debug_threads)
4080 debug_printf ("Forcing non-stop mode\n");
4081
4082 non_stop = 1;
4083 start_non_stop (1);
4084 }
4085
4086 process->gdb_detached = 1;
4087
4088 /* Detaching implicitly resumes all threads. */
4089 target_continue_no_signal (minus_one_ptid);
4090
4091 write_ok (own_buf);
4092 break; /* from switch/case */
4093 }
4094
4095 fprintf (stderr, "Detaching from process %d\n", pid);
4096 stop_tracing ();
4097 if (detach_inferior (pid) != 0)
4098 write_enn (own_buf);
4099 else
4100 {
4101 discard_queued_stop_replies (pid_to_ptid (pid));
4102 write_ok (own_buf);
4103
4104 if (extended_protocol || target_running ())
4105 {
4106 /* There is still at least one inferior remaining or
4107 we are in extended mode, so don't terminate gdbserver,
4108 and instead treat this like a normal program exit. */
4109 last_status.kind = TARGET_WAITKIND_EXITED;
4110 last_status.value.integer = 0;
4111 last_ptid = pid_to_ptid (pid);
4112
4113 current_thread = NULL;
4114 }
4115 else
4116 {
4117 putpkt (own_buf);
4118 remote_close ();
4119
4120 /* If we are attached, then we can exit. Otherwise, we
4121 need to hang around doing nothing, until the child is
4122 gone. */
4123 join_inferior (pid);
4124 exit (0);
4125 }
4126 }
4127 break;
4128 case '!':
4129 extended_protocol = 1;
4130 write_ok (own_buf);
4131 break;
4132 case '?':
4133 handle_status (own_buf);
4134 break;
4135 case 'H':
4136 if (own_buf[1] == 'c' || own_buf[1] == 'g' || own_buf[1] == 's')
4137 {
4138 ptid_t gdb_id, thread_id;
4139 int pid;
4140
4141 require_running (own_buf);
4142
4143 gdb_id = read_ptid (&own_buf[2], NULL);
4144
4145 pid = ptid_get_pid (gdb_id);
4146
4147 if (ptid_equal (gdb_id, null_ptid)
4148 || ptid_equal (gdb_id, minus_one_ptid))
4149 thread_id = null_ptid;
4150 else if (pid != 0
4151 && ptid_equal (pid_to_ptid (pid),
4152 gdb_id))
4153 {
4154 thread_info *thread = find_any_thread_of_pid (pid);
4155
4156 if (thread == NULL)
4157 {
4158 write_enn (own_buf);
4159 break;
4160 }
4161
4162 thread_id = thread->entry.id;
4163 }
4164 else
4165 {
4166 thread_id = gdb_id_to_thread_id (gdb_id);
4167 if (ptid_equal (thread_id, null_ptid))
4168 {
4169 write_enn (own_buf);
4170 break;
4171 }
4172 }
4173
4174 if (own_buf[1] == 'g')
4175 {
4176 if (ptid_equal (thread_id, null_ptid))
4177 {
4178 /* GDB is telling us to choose any thread. Check if
4179 the currently selected thread is still valid. If
4180 it is not, select the first available. */
4181 struct thread_info *thread =
4182 (struct thread_info *) find_inferior_id (&all_threads,
4183 general_thread);
4184 if (thread == NULL)
4185 thread = get_first_thread ();
4186 thread_id = thread->entry.id;
4187 }
4188
4189 general_thread = thread_id;
4190 set_desired_thread (1);
4191 gdb_assert (current_thread != NULL);
4192 }
4193 else if (own_buf[1] == 'c')
4194 cont_thread = thread_id;
4195
4196 write_ok (own_buf);
4197 }
4198 else
4199 {
4200 /* Silently ignore it so that gdb can extend the protocol
4201 without compatibility headaches. */
4202 own_buf[0] = '\0';
4203 }
4204 break;
4205 case 'g':
4206 require_running (own_buf);
4207 if (current_traceframe >= 0)
4208 {
4209 struct regcache *regcache
4210 = new_register_cache (current_target_desc ());
4211
4212 if (fetch_traceframe_registers (current_traceframe,
4213 regcache, -1) == 0)
4214 registers_to_string (regcache, own_buf);
4215 else
4216 write_enn (own_buf);
4217 free_register_cache (regcache);
4218 }
4219 else
4220 {
4221 struct regcache *regcache;
4222
4223 if (!set_desired_thread (1))
4224 write_enn (own_buf);
4225 else
4226 {
4227 regcache = get_thread_regcache (current_thread, 1);
4228 registers_to_string (regcache, own_buf);
4229 }
4230 }
4231 break;
4232 case 'G':
4233 require_running (own_buf);
4234 if (current_traceframe >= 0)
4235 write_enn (own_buf);
4236 else
4237 {
4238 struct regcache *regcache;
4239
4240 if (!set_desired_thread (1))
4241 write_enn (own_buf);
4242 else
4243 {
4244 regcache = get_thread_regcache (current_thread, 1);
4245 registers_from_string (regcache, &own_buf[1]);
4246 write_ok (own_buf);
4247 }
4248 }
4249 break;
4250 case 'm':
4251 require_running (own_buf);
4252 decode_m_packet (&own_buf[1], &mem_addr, &len);
4253 res = gdb_read_memory (mem_addr, mem_buf, len);
4254 if (res < 0)
4255 write_enn (own_buf);
4256 else
4257 bin2hex (mem_buf, own_buf, res);
4258 break;
4259 case 'M':
4260 require_running (own_buf);
4261 decode_M_packet (&own_buf[1], &mem_addr, &len, &mem_buf);
4262 if (gdb_write_memory (mem_addr, mem_buf, len) == 0)
4263 write_ok (own_buf);
4264 else
4265 write_enn (own_buf);
4266 break;
4267 case 'X':
4268 require_running (own_buf);
4269 if (decode_X_packet (&own_buf[1], packet_len - 1,
4270 &mem_addr, &len, &mem_buf) < 0
4271 || gdb_write_memory (mem_addr, mem_buf, len) != 0)
4272 write_enn (own_buf);
4273 else
4274 write_ok (own_buf);
4275 break;
4276 case 'C':
4277 require_running (own_buf);
4278 hex2bin (own_buf + 1, &sig, 1);
4279 if (gdb_signal_to_host_p ((enum gdb_signal) sig))
4280 signal = gdb_signal_to_host ((enum gdb_signal) sig);
4281 else
4282 signal = 0;
4283 myresume (own_buf, 0, signal);
4284 break;
4285 case 'S':
4286 require_running (own_buf);
4287 hex2bin (own_buf + 1, &sig, 1);
4288 if (gdb_signal_to_host_p ((enum gdb_signal) sig))
4289 signal = gdb_signal_to_host ((enum gdb_signal) sig);
4290 else
4291 signal = 0;
4292 myresume (own_buf, 1, signal);
4293 break;
4294 case 'c':
4295 require_running (own_buf);
4296 signal = 0;
4297 myresume (own_buf, 0, signal);
4298 break;
4299 case 's':
4300 require_running (own_buf);
4301 signal = 0;
4302 myresume (own_buf, 1, signal);
4303 break;
4304 case 'Z': /* insert_ ... */
4305 /* Fallthrough. */
4306 case 'z': /* remove_ ... */
4307 {
4308 char *dataptr;
4309 ULONGEST addr;
4310 int kind;
4311 char type = own_buf[1];
4312 int res;
4313 const int insert = ch == 'Z';
4314 char *p = &own_buf[3];
4315
4316 p = unpack_varlen_hex (p, &addr);
4317 kind = strtol (p + 1, &dataptr, 16);
4318
4319 if (insert)
4320 {
4321 struct gdb_breakpoint *bp;
4322
4323 bp = set_gdb_breakpoint (type, addr, kind, &res);
4324 if (bp != NULL)
4325 {
4326 res = 0;
4327
4328 /* GDB may have sent us a list of *point parameters to
4329 be evaluated on the target's side. Read such list
4330 here. If we already have a list of parameters, GDB
4331 is telling us to drop that list and use this one
4332 instead. */
4333 clear_breakpoint_conditions_and_commands (bp);
4334 process_point_options (bp, &dataptr);
4335 }
4336 }
4337 else
4338 res = delete_gdb_breakpoint (type, addr, kind);
4339
4340 if (res == 0)
4341 write_ok (own_buf);
4342 else if (res == 1)
4343 /* Unsupported. */
4344 own_buf[0] = '\0';
4345 else
4346 write_enn (own_buf);
4347 break;
4348 }
4349 case 'k':
4350 response_needed = 0;
4351 if (!target_running ())
4352 /* The packet we received doesn't make sense - but we can't
4353 reply to it, either. */
4354 return 0;
4355
4356 fprintf (stderr, "Killing all inferiors\n");
4357 for_each_inferior (&all_processes, kill_inferior_callback);
4358
4359 /* When using the extended protocol, we wait with no program
4360 running. The traditional protocol will exit instead. */
4361 if (extended_protocol)
4362 {
4363 last_status.kind = TARGET_WAITKIND_EXITED;
4364 last_status.value.sig = GDB_SIGNAL_KILL;
4365 return 0;
4366 }
4367 else
4368 exit (0);
4369
4370 case 'T':
4371 {
4372 ptid_t gdb_id, thread_id;
4373
4374 require_running (own_buf);
4375
4376 gdb_id = read_ptid (&own_buf[1], NULL);
4377 thread_id = gdb_id_to_thread_id (gdb_id);
4378 if (ptid_equal (thread_id, null_ptid))
4379 {
4380 write_enn (own_buf);
4381 break;
4382 }
4383
4384 if (mythread_alive (thread_id))
4385 write_ok (own_buf);
4386 else
4387 write_enn (own_buf);
4388 }
4389 break;
4390 case 'R':
4391 response_needed = 0;
4392
4393 /* Restarting the inferior is only supported in the extended
4394 protocol. */
4395 if (extended_protocol)
4396 {
4397 if (target_running ())
4398 for_each_inferior (&all_processes,
4399 kill_inferior_callback);
4400 fprintf (stderr, "GDBserver restarting\n");
4401
4402 /* Wait till we are at 1st instruction in prog. */
4403 if (program_name != NULL)
4404 {
4405 create_inferior (program_name, program_args);
4406
4407 if (last_status.kind == TARGET_WAITKIND_STOPPED)
4408 {
4409 /* Stopped at the first instruction of the target
4410 process. */
4411 general_thread = last_ptid;
4412 }
4413 else
4414 {
4415 /* Something went wrong. */
4416 general_thread = null_ptid;
4417 }
4418 }
4419 else
4420 {
4421 last_status.kind = TARGET_WAITKIND_EXITED;
4422 last_status.value.sig = GDB_SIGNAL_KILL;
4423 }
4424 return 0;
4425 }
4426 else
4427 {
4428 /* It is a request we don't understand. Respond with an
4429 empty packet so that gdb knows that we don't support this
4430 request. */
4431 own_buf[0] = '\0';
4432 break;
4433 }
4434 case 'v':
4435 /* Extended (long) request. */
4436 handle_v_requests (own_buf, packet_len, &new_packet_len);
4437 break;
4438
4439 default:
4440 /* It is a request we don't understand. Respond with an empty
4441 packet so that gdb knows that we don't support this
4442 request. */
4443 own_buf[0] = '\0';
4444 break;
4445 }
4446
4447 if (new_packet_len != -1)
4448 putpkt_binary (own_buf, new_packet_len);
4449 else
4450 putpkt (own_buf);
4451
4452 response_needed = 0;
4453
4454 if (exit_requested)
4455 return -1;
4456
4457 return 0;
4458 }
4459
4460 /* Event-loop callback for serial events. */
4461
4462 int
4463 handle_serial_event (int err, gdb_client_data client_data)
4464 {
4465 if (debug_threads)
4466 debug_printf ("handling possible serial event\n");
4467
4468 /* Really handle it. */
4469 if (process_serial_event () < 0)
4470 return -1;
4471
4472 /* Be sure to not change the selected thread behind GDB's back.
4473 Important in the non-stop mode asynchronous protocol. */
4474 set_desired_thread (1);
4475
4476 return 0;
4477 }
4478
4479 /* Push a stop notification on the notification queue. */
4480
4481 static void
4482 push_stop_notification (ptid_t ptid, struct target_waitstatus *status)
4483 {
4484 struct vstop_notif *vstop_notif = XNEW (struct vstop_notif);
4485
4486 vstop_notif->status = *status;
4487 vstop_notif->ptid = ptid;
4488 /* Push Stop notification. */
4489 notif_push (&notif_stop, (struct notif_event *) vstop_notif);
4490 }
4491
4492 /* Event-loop callback for target events. */
4493
4494 int
4495 handle_target_event (int err, gdb_client_data client_data)
4496 {
4497 if (debug_threads)
4498 debug_printf ("handling possible target event\n");
4499
4500 last_ptid = mywait (minus_one_ptid, &last_status,
4501 TARGET_WNOHANG, 1);
4502
4503 if (last_status.kind == TARGET_WAITKIND_NO_RESUMED)
4504 {
4505 if (gdb_connected () && report_no_resumed)
4506 push_stop_notification (null_ptid, &last_status);
4507 }
4508 else if (last_status.kind != TARGET_WAITKIND_IGNORE)
4509 {
4510 int pid = ptid_get_pid (last_ptid);
4511 struct process_info *process = find_process_pid (pid);
4512 int forward_event = !gdb_connected () || process->gdb_detached;
4513
4514 if (last_status.kind == TARGET_WAITKIND_EXITED
4515 || last_status.kind == TARGET_WAITKIND_SIGNALLED)
4516 {
4517 mark_breakpoints_out (process);
4518 target_mourn_inferior (last_ptid);
4519 }
4520 else if (last_status.kind == TARGET_WAITKIND_THREAD_EXITED)
4521 ;
4522 else
4523 {
4524 /* We're reporting this thread as stopped. Update its
4525 "want-stopped" state to what the client wants, until it
4526 gets a new resume action. */
4527 current_thread->last_resume_kind = resume_stop;
4528 current_thread->last_status = last_status;
4529 }
4530
4531 if (forward_event)
4532 {
4533 if (!target_running ())
4534 {
4535 /* The last process exited. We're done. */
4536 exit (0);
4537 }
4538
4539 if (last_status.kind == TARGET_WAITKIND_EXITED
4540 || last_status.kind == TARGET_WAITKIND_SIGNALLED
4541 || last_status.kind == TARGET_WAITKIND_THREAD_EXITED)
4542 ;
4543 else
4544 {
4545 /* A thread stopped with a signal, but gdb isn't
4546 connected to handle it. Pass it down to the
4547 inferior, as if it wasn't being traced. */
4548 enum gdb_signal signal;
4549
4550 if (debug_threads)
4551 debug_printf ("GDB not connected; forwarding event %d for"
4552 " [%s]\n",
4553 (int) last_status.kind,
4554 target_pid_to_str (last_ptid));
4555
4556 if (last_status.kind == TARGET_WAITKIND_STOPPED)
4557 signal = last_status.value.sig;
4558 else
4559 signal = GDB_SIGNAL_0;
4560 target_continue (last_ptid, signal);
4561 }
4562 }
4563 else
4564 push_stop_notification (last_ptid, &last_status);
4565 }
4566
4567 /* Be sure to not change the selected thread behind GDB's back.
4568 Important in the non-stop mode asynchronous protocol. */
4569 set_desired_thread (1);
4570
4571 return 0;
4572 }
4573
4574 #if GDB_SELF_TEST
4575 namespace selftests
4576 {
4577
4578 void
4579 reset ()
4580 {}
4581
4582 } // namespace selftests
4583 #endif /* GDB_SELF_TEST */
This page took 0.148355 seconds and 5 git commands to generate.