Implement the ability to set/unset environment variables to GDBserver when starting...
[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 (desc->xmltarget != NULL && strcmp (annex, "target.xml") == 0)
877 {
878 if (*desc->xmltarget == '@')
879 return desc->xmltarget + 1;
880 else
881 annex = desc->xmltarget;
882 }
883
884 #ifdef USE_XML
885 {
886 extern const char *const xml_builtin[][2];
887 int i;
888
889 /* Look for the annex. */
890 for (i = 0; xml_builtin[i][0] != NULL; i++)
891 if (strcmp (annex, xml_builtin[i][0]) == 0)
892 break;
893
894 if (xml_builtin[i][0] != NULL)
895 return xml_builtin[i][1];
896 }
897 #endif
898
899 return NULL;
900 }
901
902 static void
903 monitor_show_help (void)
904 {
905 monitor_output ("The following monitor commands are supported:\n");
906 monitor_output (" set debug <0|1>\n");
907 monitor_output (" Enable general debugging messages\n");
908 monitor_output (" set debug-hw-points <0|1>\n");
909 monitor_output (" Enable h/w breakpoint/watchpoint debugging messages\n");
910 monitor_output (" set remote-debug <0|1>\n");
911 monitor_output (" Enable remote protocol debugging messages\n");
912 monitor_output (" set debug-format option1[,option2,...]\n");
913 monitor_output (" Add additional information to debugging messages\n");
914 monitor_output (" Options: all, none");
915 monitor_output (", timestamp");
916 monitor_output ("\n");
917 monitor_output (" exit\n");
918 monitor_output (" Quit GDBserver\n");
919 }
920
921 /* Read trace frame or inferior memory. Returns the number of bytes
922 actually read, zero when no further transfer is possible, and -1 on
923 error. Return of a positive value smaller than LEN does not
924 indicate there's no more to be read, only the end of the transfer.
925 E.g., when GDB reads memory from a traceframe, a first request may
926 be served from a memory block that does not cover the whole request
927 length. A following request gets the rest served from either
928 another block (of the same traceframe) or from the read-only
929 regions. */
930
931 static int
932 gdb_read_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
933 {
934 int res;
935
936 if (current_traceframe >= 0)
937 {
938 ULONGEST nbytes;
939 ULONGEST length = len;
940
941 if (traceframe_read_mem (current_traceframe,
942 memaddr, myaddr, len, &nbytes))
943 return -1;
944 /* Data read from trace buffer, we're done. */
945 if (nbytes > 0)
946 return nbytes;
947 if (!in_readonly_region (memaddr, length))
948 return -1;
949 /* Otherwise we have a valid readonly case, fall through. */
950 /* (assume no half-trace half-real blocks for now) */
951 }
952
953 res = prepare_to_access_memory ();
954 if (res == 0)
955 {
956 if (set_desired_thread (1))
957 res = read_inferior_memory (memaddr, myaddr, len);
958 else
959 res = 1;
960 done_accessing_memory ();
961
962 return res == 0 ? len : -1;
963 }
964 else
965 return -1;
966 }
967
968 /* Write trace frame or inferior memory. Actually, writing to trace
969 frames is forbidden. */
970
971 static int
972 gdb_write_memory (CORE_ADDR memaddr, const unsigned char *myaddr, int len)
973 {
974 if (current_traceframe >= 0)
975 return EIO;
976 else
977 {
978 int ret;
979
980 ret = prepare_to_access_memory ();
981 if (ret == 0)
982 {
983 if (set_desired_thread (1))
984 ret = write_inferior_memory (memaddr, myaddr, len);
985 else
986 ret = EIO;
987 done_accessing_memory ();
988 }
989 return ret;
990 }
991 }
992
993 /* Subroutine of handle_search_memory to simplify it. */
994
995 static int
996 handle_search_memory_1 (CORE_ADDR start_addr, CORE_ADDR search_space_len,
997 gdb_byte *pattern, unsigned pattern_len,
998 gdb_byte *search_buf,
999 unsigned chunk_size, unsigned search_buf_size,
1000 CORE_ADDR *found_addrp)
1001 {
1002 /* Prime the search buffer. */
1003
1004 if (gdb_read_memory (start_addr, search_buf, search_buf_size)
1005 != search_buf_size)
1006 {
1007 warning ("Unable to access %ld bytes of target "
1008 "memory at 0x%lx, halting search.",
1009 (long) search_buf_size, (long) start_addr);
1010 return -1;
1011 }
1012
1013 /* Perform the search.
1014
1015 The loop is kept simple by allocating [N + pattern-length - 1] bytes.
1016 When we've scanned N bytes we copy the trailing bytes to the start and
1017 read in another N bytes. */
1018
1019 while (search_space_len >= pattern_len)
1020 {
1021 gdb_byte *found_ptr;
1022 unsigned nr_search_bytes = (search_space_len < search_buf_size
1023 ? search_space_len
1024 : search_buf_size);
1025
1026 found_ptr = (gdb_byte *) memmem (search_buf, nr_search_bytes, pattern,
1027 pattern_len);
1028
1029 if (found_ptr != NULL)
1030 {
1031 CORE_ADDR found_addr = start_addr + (found_ptr - search_buf);
1032 *found_addrp = found_addr;
1033 return 1;
1034 }
1035
1036 /* Not found in this chunk, skip to next chunk. */
1037
1038 /* Don't let search_space_len wrap here, it's unsigned. */
1039 if (search_space_len >= chunk_size)
1040 search_space_len -= chunk_size;
1041 else
1042 search_space_len = 0;
1043
1044 if (search_space_len >= pattern_len)
1045 {
1046 unsigned keep_len = search_buf_size - chunk_size;
1047 CORE_ADDR read_addr = start_addr + chunk_size + keep_len;
1048 int nr_to_read;
1049
1050 /* Copy the trailing part of the previous iteration to the front
1051 of the buffer for the next iteration. */
1052 memcpy (search_buf, search_buf + chunk_size, keep_len);
1053
1054 nr_to_read = (search_space_len - keep_len < chunk_size
1055 ? search_space_len - keep_len
1056 : chunk_size);
1057
1058 if (gdb_read_memory (read_addr, search_buf + keep_len,
1059 nr_to_read) != search_buf_size)
1060 {
1061 warning ("Unable to access %ld bytes of target memory "
1062 "at 0x%lx, halting search.",
1063 (long) nr_to_read, (long) read_addr);
1064 return -1;
1065 }
1066
1067 start_addr += chunk_size;
1068 }
1069 }
1070
1071 /* Not found. */
1072
1073 return 0;
1074 }
1075
1076 /* Handle qSearch:memory packets. */
1077
1078 static void
1079 handle_search_memory (char *own_buf, int packet_len)
1080 {
1081 CORE_ADDR start_addr;
1082 CORE_ADDR search_space_len;
1083 gdb_byte *pattern;
1084 unsigned int pattern_len;
1085 /* NOTE: also defined in find.c testcase. */
1086 #define SEARCH_CHUNK_SIZE 16000
1087 const unsigned chunk_size = SEARCH_CHUNK_SIZE;
1088 /* Buffer to hold memory contents for searching. */
1089 gdb_byte *search_buf;
1090 unsigned search_buf_size;
1091 int found;
1092 CORE_ADDR found_addr;
1093 int cmd_name_len = sizeof ("qSearch:memory:") - 1;
1094
1095 pattern = (gdb_byte *) malloc (packet_len);
1096 if (pattern == NULL)
1097 {
1098 error ("Unable to allocate memory to perform the search");
1099 strcpy (own_buf, "E00");
1100 return;
1101 }
1102 if (decode_search_memory_packet (own_buf + cmd_name_len,
1103 packet_len - cmd_name_len,
1104 &start_addr, &search_space_len,
1105 pattern, &pattern_len) < 0)
1106 {
1107 free (pattern);
1108 error ("Error in parsing qSearch:memory packet");
1109 strcpy (own_buf, "E00");
1110 return;
1111 }
1112
1113 search_buf_size = chunk_size + pattern_len - 1;
1114
1115 /* No point in trying to allocate a buffer larger than the search space. */
1116 if (search_space_len < search_buf_size)
1117 search_buf_size = search_space_len;
1118
1119 search_buf = (gdb_byte *) malloc (search_buf_size);
1120 if (search_buf == NULL)
1121 {
1122 free (pattern);
1123 error ("Unable to allocate memory to perform the search");
1124 strcpy (own_buf, "E00");
1125 return;
1126 }
1127
1128 found = handle_search_memory_1 (start_addr, search_space_len,
1129 pattern, pattern_len,
1130 search_buf, chunk_size, search_buf_size,
1131 &found_addr);
1132
1133 if (found > 0)
1134 sprintf (own_buf, "1,%lx", (long) found_addr);
1135 else if (found == 0)
1136 strcpy (own_buf, "0");
1137 else
1138 strcpy (own_buf, "E00");
1139
1140 free (search_buf);
1141 free (pattern);
1142 }
1143
1144 #define require_running(BUF) \
1145 if (!target_running ()) \
1146 { \
1147 write_enn (BUF); \
1148 return; \
1149 }
1150
1151 /* Parse options to --debug-format= and "monitor set debug-format".
1152 ARG is the text after "--debug-format=" or "monitor set debug-format".
1153 IS_MONITOR is non-zero if we're invoked via "monitor set debug-format".
1154 This triggers calls to monitor_output.
1155 The result is NULL if all options were parsed ok, otherwise an error
1156 message which the caller must free.
1157
1158 N.B. These commands affect all debug format settings, they are not
1159 cumulative. If a format is not specified, it is turned off.
1160 However, we don't go to extra trouble with things like
1161 "monitor set debug-format all,none,timestamp".
1162 Instead we just parse them one at a time, in order.
1163
1164 The syntax for "monitor set debug" we support here is not identical
1165 to gdb's "set debug foo on|off" because we also use this function to
1166 parse "--debug-format=foo,bar". */
1167
1168 static char *
1169 parse_debug_format_options (const char *arg, int is_monitor)
1170 {
1171 VEC (char_ptr) *options;
1172 int ix;
1173 char *option;
1174
1175 /* First turn all debug format options off. */
1176 debug_timestamp = 0;
1177
1178 /* First remove leading spaces, for "monitor set debug-format". */
1179 while (isspace (*arg))
1180 ++arg;
1181
1182 options = delim_string_to_char_ptr_vec (arg, ',');
1183
1184 for (ix = 0; VEC_iterate (char_ptr, options, ix, option); ++ix)
1185 {
1186 if (strcmp (option, "all") == 0)
1187 {
1188 debug_timestamp = 1;
1189 if (is_monitor)
1190 monitor_output ("All extra debug format options enabled.\n");
1191 }
1192 else if (strcmp (option, "none") == 0)
1193 {
1194 debug_timestamp = 0;
1195 if (is_monitor)
1196 monitor_output ("All extra debug format options disabled.\n");
1197 }
1198 else if (strcmp (option, "timestamp") == 0)
1199 {
1200 debug_timestamp = 1;
1201 if (is_monitor)
1202 monitor_output ("Timestamps will be added to debug output.\n");
1203 }
1204 else if (*option == '\0')
1205 {
1206 /* An empty option, e.g., "--debug-format=foo,,bar", is ignored. */
1207 continue;
1208 }
1209 else
1210 {
1211 char *msg = xstrprintf ("Unknown debug-format argument: \"%s\"\n",
1212 option);
1213
1214 free_char_ptr_vec (options);
1215 return msg;
1216 }
1217 }
1218
1219 free_char_ptr_vec (options);
1220 return NULL;
1221 }
1222
1223 /* Handle monitor commands not handled by target-specific handlers. */
1224
1225 static void
1226 handle_monitor_command (char *mon, char *own_buf)
1227 {
1228 if (strcmp (mon, "set debug 1") == 0)
1229 {
1230 debug_threads = 1;
1231 monitor_output ("Debug output enabled.\n");
1232 }
1233 else if (strcmp (mon, "set debug 0") == 0)
1234 {
1235 debug_threads = 0;
1236 monitor_output ("Debug output disabled.\n");
1237 }
1238 else if (strcmp (mon, "set debug-hw-points 1") == 0)
1239 {
1240 show_debug_regs = 1;
1241 monitor_output ("H/W point debugging output enabled.\n");
1242 }
1243 else if (strcmp (mon, "set debug-hw-points 0") == 0)
1244 {
1245 show_debug_regs = 0;
1246 monitor_output ("H/W point debugging output disabled.\n");
1247 }
1248 else if (strcmp (mon, "set remote-debug 1") == 0)
1249 {
1250 remote_debug = 1;
1251 monitor_output ("Protocol debug output enabled.\n");
1252 }
1253 else if (strcmp (mon, "set remote-debug 0") == 0)
1254 {
1255 remote_debug = 0;
1256 monitor_output ("Protocol debug output disabled.\n");
1257 }
1258 else if (startswith (mon, "set debug-format "))
1259 {
1260 char *error_msg
1261 = parse_debug_format_options (mon + sizeof ("set debug-format ") - 1,
1262 1);
1263
1264 if (error_msg != NULL)
1265 {
1266 monitor_output (error_msg);
1267 monitor_show_help ();
1268 write_enn (own_buf);
1269 xfree (error_msg);
1270 }
1271 }
1272 else if (strcmp (mon, "help") == 0)
1273 monitor_show_help ();
1274 else if (strcmp (mon, "exit") == 0)
1275 exit_requested = 1;
1276 else
1277 {
1278 monitor_output ("Unknown monitor command.\n\n");
1279 monitor_show_help ();
1280 write_enn (own_buf);
1281 }
1282 }
1283
1284 /* Associates a callback with each supported qXfer'able object. */
1285
1286 struct qxfer
1287 {
1288 /* The object this handler handles. */
1289 const char *object;
1290
1291 /* Request that the target transfer up to LEN 8-bit bytes of the
1292 target's OBJECT. The OFFSET, for a seekable object, specifies
1293 the starting point. The ANNEX can be used to provide additional
1294 data-specific information to the target.
1295
1296 Return the number of bytes actually transfered, zero when no
1297 further transfer is possible, -1 on error, -2 when the transfer
1298 is not supported, and -3 on a verbose error message that should
1299 be preserved. Return of a positive value smaller than LEN does
1300 not indicate the end of the object, only the end of the transfer.
1301
1302 One, and only one, of readbuf or writebuf must be non-NULL. */
1303 int (*xfer) (const char *annex,
1304 gdb_byte *readbuf, const gdb_byte *writebuf,
1305 ULONGEST offset, LONGEST len);
1306 };
1307
1308 /* Handle qXfer:auxv:read. */
1309
1310 static int
1311 handle_qxfer_auxv (const char *annex,
1312 gdb_byte *readbuf, const gdb_byte *writebuf,
1313 ULONGEST offset, LONGEST len)
1314 {
1315 if (the_target->read_auxv == NULL || writebuf != NULL)
1316 return -2;
1317
1318 if (annex[0] != '\0' || current_thread == NULL)
1319 return -1;
1320
1321 return (*the_target->read_auxv) (offset, readbuf, len);
1322 }
1323
1324 /* Handle qXfer:exec-file:read. */
1325
1326 static int
1327 handle_qxfer_exec_file (const char *const_annex,
1328 gdb_byte *readbuf, const gdb_byte *writebuf,
1329 ULONGEST offset, LONGEST len)
1330 {
1331 char *file;
1332 ULONGEST pid;
1333 int total_len;
1334
1335 if (the_target->pid_to_exec_file == NULL || writebuf != NULL)
1336 return -2;
1337
1338 if (const_annex[0] == '\0')
1339 {
1340 if (current_thread == NULL)
1341 return -1;
1342
1343 pid = pid_of (current_thread);
1344 }
1345 else
1346 {
1347 char *annex = (char *) alloca (strlen (const_annex) + 1);
1348
1349 strcpy (annex, const_annex);
1350 annex = unpack_varlen_hex (annex, &pid);
1351
1352 if (annex[0] != '\0')
1353 return -1;
1354 }
1355
1356 if (pid <= 0)
1357 return -1;
1358
1359 file = (*the_target->pid_to_exec_file) (pid);
1360 if (file == NULL)
1361 return -1;
1362
1363 total_len = strlen (file);
1364
1365 if (offset > total_len)
1366 return -1;
1367
1368 if (offset + len > total_len)
1369 len = total_len - offset;
1370
1371 memcpy (readbuf, file + offset, len);
1372 return len;
1373 }
1374
1375 /* Handle qXfer:features:read. */
1376
1377 static int
1378 handle_qxfer_features (const char *annex,
1379 gdb_byte *readbuf, const gdb_byte *writebuf,
1380 ULONGEST offset, LONGEST len)
1381 {
1382 const char *document;
1383 size_t total_len;
1384
1385 if (writebuf != NULL)
1386 return -2;
1387
1388 if (!target_running ())
1389 return -1;
1390
1391 /* Grab the correct annex. */
1392 document = get_features_xml (annex);
1393 if (document == NULL)
1394 return -1;
1395
1396 total_len = strlen (document);
1397
1398 if (offset > total_len)
1399 return -1;
1400
1401 if (offset + len > total_len)
1402 len = total_len - offset;
1403
1404 memcpy (readbuf, document + offset, len);
1405 return len;
1406 }
1407
1408 /* Worker routine for handle_qxfer_libraries.
1409 Add to the length pointed to by ARG a conservative estimate of the
1410 length needed to transmit the file name of INF. */
1411
1412 static void
1413 accumulate_file_name_length (struct inferior_list_entry *inf, void *arg)
1414 {
1415 struct dll_info *dll = (struct dll_info *) inf;
1416 unsigned int *total_len = (unsigned int *) arg;
1417
1418 /* Over-estimate the necessary memory. Assume that every character
1419 in the library name must be escaped. */
1420 *total_len += 128 + 6 * strlen (dll->name);
1421 }
1422
1423 /* Worker routine for handle_qxfer_libraries.
1424 Emit the XML to describe the library in INF. */
1425
1426 static void
1427 emit_dll_description (struct inferior_list_entry *inf, void *arg)
1428 {
1429 struct dll_info *dll = (struct dll_info *) inf;
1430 char **p_ptr = (char **) arg;
1431 char *p = *p_ptr;
1432 char *name;
1433
1434 strcpy (p, " <library name=\"");
1435 p = p + strlen (p);
1436 name = xml_escape_text (dll->name);
1437 strcpy (p, name);
1438 free (name);
1439 p = p + strlen (p);
1440 strcpy (p, "\"><segment address=\"");
1441 p = p + strlen (p);
1442 sprintf (p, "0x%lx", (long) dll->base_addr);
1443 p = p + strlen (p);
1444 strcpy (p, "\"/></library>\n");
1445 p = p + strlen (p);
1446
1447 *p_ptr = p;
1448 }
1449
1450 /* Handle qXfer:libraries:read. */
1451
1452 static int
1453 handle_qxfer_libraries (const char *annex,
1454 gdb_byte *readbuf, const gdb_byte *writebuf,
1455 ULONGEST offset, LONGEST len)
1456 {
1457 unsigned int total_len;
1458 char *document, *p;
1459
1460 if (writebuf != NULL)
1461 return -2;
1462
1463 if (annex[0] != '\0' || current_thread == NULL)
1464 return -1;
1465
1466 total_len = 64;
1467 for_each_inferior_with_data (&all_dlls, accumulate_file_name_length,
1468 &total_len);
1469
1470 document = (char *) malloc (total_len);
1471 if (document == NULL)
1472 return -1;
1473
1474 strcpy (document, "<library-list version=\"1.0\">\n");
1475 p = document + strlen (document);
1476
1477 for_each_inferior_with_data (&all_dlls, emit_dll_description, &p);
1478
1479 strcpy (p, "</library-list>\n");
1480
1481 total_len = strlen (document);
1482
1483 if (offset > total_len)
1484 {
1485 free (document);
1486 return -1;
1487 }
1488
1489 if (offset + len > total_len)
1490 len = total_len - offset;
1491
1492 memcpy (readbuf, document + offset, len);
1493 free (document);
1494 return len;
1495 }
1496
1497 /* Handle qXfer:libraries-svr4:read. */
1498
1499 static int
1500 handle_qxfer_libraries_svr4 (const char *annex,
1501 gdb_byte *readbuf, const gdb_byte *writebuf,
1502 ULONGEST offset, LONGEST len)
1503 {
1504 if (writebuf != NULL)
1505 return -2;
1506
1507 if (current_thread == NULL || the_target->qxfer_libraries_svr4 == NULL)
1508 return -1;
1509
1510 return the_target->qxfer_libraries_svr4 (annex, readbuf, writebuf, offset, len);
1511 }
1512
1513 /* Handle qXfer:osadata:read. */
1514
1515 static int
1516 handle_qxfer_osdata (const char *annex,
1517 gdb_byte *readbuf, const gdb_byte *writebuf,
1518 ULONGEST offset, LONGEST len)
1519 {
1520 if (the_target->qxfer_osdata == NULL || writebuf != NULL)
1521 return -2;
1522
1523 return (*the_target->qxfer_osdata) (annex, readbuf, NULL, offset, len);
1524 }
1525
1526 /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
1527
1528 static int
1529 handle_qxfer_siginfo (const char *annex,
1530 gdb_byte *readbuf, const gdb_byte *writebuf,
1531 ULONGEST offset, LONGEST len)
1532 {
1533 if (the_target->qxfer_siginfo == NULL)
1534 return -2;
1535
1536 if (annex[0] != '\0' || current_thread == NULL)
1537 return -1;
1538
1539 return (*the_target->qxfer_siginfo) (annex, readbuf, writebuf, offset, len);
1540 }
1541
1542 /* Handle qXfer:spu:read and qXfer:spu:write. */
1543
1544 static int
1545 handle_qxfer_spu (const char *annex,
1546 gdb_byte *readbuf, const gdb_byte *writebuf,
1547 ULONGEST offset, LONGEST len)
1548 {
1549 if (the_target->qxfer_spu == NULL)
1550 return -2;
1551
1552 if (current_thread == NULL)
1553 return -1;
1554
1555 return (*the_target->qxfer_spu) (annex, readbuf, writebuf, offset, len);
1556 }
1557
1558 /* Handle qXfer:statictrace:read. */
1559
1560 static int
1561 handle_qxfer_statictrace (const char *annex,
1562 gdb_byte *readbuf, const gdb_byte *writebuf,
1563 ULONGEST offset, LONGEST len)
1564 {
1565 ULONGEST nbytes;
1566
1567 if (writebuf != NULL)
1568 return -2;
1569
1570 if (annex[0] != '\0' || current_thread == NULL || current_traceframe == -1)
1571 return -1;
1572
1573 if (traceframe_read_sdata (current_traceframe, offset,
1574 readbuf, len, &nbytes))
1575 return -1;
1576 return nbytes;
1577 }
1578
1579 /* Helper for handle_qxfer_threads_proper.
1580 Emit the XML to describe the thread of INF. */
1581
1582 static void
1583 handle_qxfer_threads_worker (struct inferior_list_entry *inf, void *arg)
1584 {
1585 struct thread_info *thread = (struct thread_info *) inf;
1586 struct buffer *buffer = (struct buffer *) arg;
1587 ptid_t ptid = thread_to_gdb_id (thread);
1588 char ptid_s[100];
1589 int core = target_core_of_thread (ptid);
1590 char core_s[21];
1591 const char *name = target_thread_name (ptid);
1592
1593 write_ptid (ptid_s, ptid);
1594
1595 buffer_xml_printf (buffer, "<thread id=\"%s\"", ptid_s);
1596
1597 if (core != -1)
1598 {
1599 sprintf (core_s, "%d", core);
1600 buffer_xml_printf (buffer, " core=\"%s\"", core_s);
1601 }
1602
1603 if (name != NULL)
1604 buffer_xml_printf (buffer, " name=\"%s\"", name);
1605
1606 buffer_xml_printf (buffer, "/>\n");
1607 }
1608
1609 /* Helper for handle_qxfer_threads. */
1610
1611 static void
1612 handle_qxfer_threads_proper (struct buffer *buffer)
1613 {
1614 buffer_grow_str (buffer, "<threads>\n");
1615
1616 for_each_inferior_with_data (&all_threads, handle_qxfer_threads_worker,
1617 buffer);
1618
1619 buffer_grow_str0 (buffer, "</threads>\n");
1620 }
1621
1622 /* Handle qXfer:threads:read. */
1623
1624 static int
1625 handle_qxfer_threads (const char *annex,
1626 gdb_byte *readbuf, const gdb_byte *writebuf,
1627 ULONGEST offset, LONGEST len)
1628 {
1629 static char *result = 0;
1630 static unsigned int result_length = 0;
1631
1632 if (writebuf != NULL)
1633 return -2;
1634
1635 if (annex[0] != '\0')
1636 return -1;
1637
1638 if (offset == 0)
1639 {
1640 struct buffer buffer;
1641 /* When asked for data at offset 0, generate everything and store into
1642 'result'. Successive reads will be served off 'result'. */
1643 if (result)
1644 free (result);
1645
1646 buffer_init (&buffer);
1647
1648 handle_qxfer_threads_proper (&buffer);
1649
1650 result = buffer_finish (&buffer);
1651 result_length = strlen (result);
1652 buffer_free (&buffer);
1653 }
1654
1655 if (offset >= result_length)
1656 {
1657 /* We're out of data. */
1658 free (result);
1659 result = NULL;
1660 result_length = 0;
1661 return 0;
1662 }
1663
1664 if (len > result_length - offset)
1665 len = result_length - offset;
1666
1667 memcpy (readbuf, result + offset, len);
1668
1669 return len;
1670 }
1671
1672 /* Handle qXfer:traceframe-info:read. */
1673
1674 static int
1675 handle_qxfer_traceframe_info (const char *annex,
1676 gdb_byte *readbuf, const gdb_byte *writebuf,
1677 ULONGEST offset, LONGEST len)
1678 {
1679 static char *result = 0;
1680 static unsigned int result_length = 0;
1681
1682 if (writebuf != NULL)
1683 return -2;
1684
1685 if (!target_running () || annex[0] != '\0' || current_traceframe == -1)
1686 return -1;
1687
1688 if (offset == 0)
1689 {
1690 struct buffer buffer;
1691
1692 /* When asked for data at offset 0, generate everything and
1693 store into 'result'. Successive reads will be served off
1694 'result'. */
1695 free (result);
1696
1697 buffer_init (&buffer);
1698
1699 traceframe_read_info (current_traceframe, &buffer);
1700
1701 result = buffer_finish (&buffer);
1702 result_length = strlen (result);
1703 buffer_free (&buffer);
1704 }
1705
1706 if (offset >= result_length)
1707 {
1708 /* We're out of data. */
1709 free (result);
1710 result = NULL;
1711 result_length = 0;
1712 return 0;
1713 }
1714
1715 if (len > result_length - offset)
1716 len = result_length - offset;
1717
1718 memcpy (readbuf, result + offset, len);
1719 return len;
1720 }
1721
1722 /* Handle qXfer:fdpic:read. */
1723
1724 static int
1725 handle_qxfer_fdpic (const char *annex, gdb_byte *readbuf,
1726 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
1727 {
1728 if (the_target->read_loadmap == NULL)
1729 return -2;
1730
1731 if (current_thread == NULL)
1732 return -1;
1733
1734 return (*the_target->read_loadmap) (annex, offset, readbuf, len);
1735 }
1736
1737 /* Handle qXfer:btrace:read. */
1738
1739 static int
1740 handle_qxfer_btrace (const char *annex,
1741 gdb_byte *readbuf, const gdb_byte *writebuf,
1742 ULONGEST offset, LONGEST len)
1743 {
1744 static struct buffer cache;
1745 struct thread_info *thread;
1746 enum btrace_read_type type;
1747 int result;
1748
1749 if (the_target->read_btrace == NULL || writebuf != NULL)
1750 return -2;
1751
1752 if (ptid_equal (general_thread, null_ptid)
1753 || ptid_equal (general_thread, minus_one_ptid))
1754 {
1755 strcpy (own_buf, "E.Must select a single thread.");
1756 return -3;
1757 }
1758
1759 thread = find_thread_ptid (general_thread);
1760 if (thread == NULL)
1761 {
1762 strcpy (own_buf, "E.No such thread.");
1763 return -3;
1764 }
1765
1766 if (thread->btrace == NULL)
1767 {
1768 strcpy (own_buf, "E.Btrace not enabled.");
1769 return -3;
1770 }
1771
1772 if (strcmp (annex, "all") == 0)
1773 type = BTRACE_READ_ALL;
1774 else if (strcmp (annex, "new") == 0)
1775 type = BTRACE_READ_NEW;
1776 else if (strcmp (annex, "delta") == 0)
1777 type = BTRACE_READ_DELTA;
1778 else
1779 {
1780 strcpy (own_buf, "E.Bad annex.");
1781 return -3;
1782 }
1783
1784 if (offset == 0)
1785 {
1786 buffer_free (&cache);
1787
1788 result = target_read_btrace (thread->btrace, &cache, type);
1789 if (result != 0)
1790 {
1791 memcpy (own_buf, cache.buffer, cache.used_size);
1792 return -3;
1793 }
1794 }
1795 else if (offset > cache.used_size)
1796 {
1797 buffer_free (&cache);
1798 return -3;
1799 }
1800
1801 if (len > cache.used_size - offset)
1802 len = cache.used_size - offset;
1803
1804 memcpy (readbuf, cache.buffer + offset, len);
1805
1806 return len;
1807 }
1808
1809 /* Handle qXfer:btrace-conf:read. */
1810
1811 static int
1812 handle_qxfer_btrace_conf (const char *annex,
1813 gdb_byte *readbuf, const gdb_byte *writebuf,
1814 ULONGEST offset, LONGEST len)
1815 {
1816 static struct buffer cache;
1817 struct thread_info *thread;
1818 int result;
1819
1820 if (the_target->read_btrace_conf == NULL || writebuf != NULL)
1821 return -2;
1822
1823 if (annex[0] != '\0')
1824 return -1;
1825
1826 if (ptid_equal (general_thread, null_ptid)
1827 || ptid_equal (general_thread, minus_one_ptid))
1828 {
1829 strcpy (own_buf, "E.Must select a single thread.");
1830 return -3;
1831 }
1832
1833 thread = find_thread_ptid (general_thread);
1834 if (thread == NULL)
1835 {
1836 strcpy (own_buf, "E.No such thread.");
1837 return -3;
1838 }
1839
1840 if (thread->btrace == NULL)
1841 {
1842 strcpy (own_buf, "E.Btrace not enabled.");
1843 return -3;
1844 }
1845
1846 if (offset == 0)
1847 {
1848 buffer_free (&cache);
1849
1850 result = target_read_btrace_conf (thread->btrace, &cache);
1851 if (result != 0)
1852 {
1853 memcpy (own_buf, cache.buffer, cache.used_size);
1854 return -3;
1855 }
1856 }
1857 else if (offset > cache.used_size)
1858 {
1859 buffer_free (&cache);
1860 return -3;
1861 }
1862
1863 if (len > cache.used_size - offset)
1864 len = cache.used_size - offset;
1865
1866 memcpy (readbuf, cache.buffer + offset, len);
1867
1868 return len;
1869 }
1870
1871 static const struct qxfer qxfer_packets[] =
1872 {
1873 { "auxv", handle_qxfer_auxv },
1874 { "btrace", handle_qxfer_btrace },
1875 { "btrace-conf", handle_qxfer_btrace_conf },
1876 { "exec-file", handle_qxfer_exec_file},
1877 { "fdpic", handle_qxfer_fdpic},
1878 { "features", handle_qxfer_features },
1879 { "libraries", handle_qxfer_libraries },
1880 { "libraries-svr4", handle_qxfer_libraries_svr4 },
1881 { "osdata", handle_qxfer_osdata },
1882 { "siginfo", handle_qxfer_siginfo },
1883 { "spu", handle_qxfer_spu },
1884 { "statictrace", handle_qxfer_statictrace },
1885 { "threads", handle_qxfer_threads },
1886 { "traceframe-info", handle_qxfer_traceframe_info },
1887 };
1888
1889 static int
1890 handle_qxfer (char *own_buf, int packet_len, int *new_packet_len_p)
1891 {
1892 int i;
1893 char *object;
1894 char *rw;
1895 char *annex;
1896 char *offset;
1897
1898 if (!startswith (own_buf, "qXfer:"))
1899 return 0;
1900
1901 /* Grab the object, r/w and annex. */
1902 if (decode_xfer (own_buf + 6, &object, &rw, &annex, &offset) < 0)
1903 {
1904 write_enn (own_buf);
1905 return 1;
1906 }
1907
1908 for (i = 0;
1909 i < sizeof (qxfer_packets) / sizeof (qxfer_packets[0]);
1910 i++)
1911 {
1912 const struct qxfer *q = &qxfer_packets[i];
1913
1914 if (strcmp (object, q->object) == 0)
1915 {
1916 if (strcmp (rw, "read") == 0)
1917 {
1918 unsigned char *data;
1919 int n;
1920 CORE_ADDR ofs;
1921 unsigned int len;
1922
1923 /* Grab the offset and length. */
1924 if (decode_xfer_read (offset, &ofs, &len) < 0)
1925 {
1926 write_enn (own_buf);
1927 return 1;
1928 }
1929
1930 /* Read one extra byte, as an indicator of whether there is
1931 more. */
1932 if (len > PBUFSIZ - 2)
1933 len = PBUFSIZ - 2;
1934 data = (unsigned char *) malloc (len + 1);
1935 if (data == NULL)
1936 {
1937 write_enn (own_buf);
1938 return 1;
1939 }
1940 n = (*q->xfer) (annex, data, NULL, ofs, len + 1);
1941 if (n == -2)
1942 {
1943 free (data);
1944 return 0;
1945 }
1946 else if (n == -3)
1947 {
1948 /* Preserve error message. */
1949 }
1950 else if (n < 0)
1951 write_enn (own_buf);
1952 else if (n > len)
1953 *new_packet_len_p = write_qxfer_response (own_buf, data, len, 1);
1954 else
1955 *new_packet_len_p = write_qxfer_response (own_buf, data, n, 0);
1956
1957 free (data);
1958 return 1;
1959 }
1960 else if (strcmp (rw, "write") == 0)
1961 {
1962 int n;
1963 unsigned int len;
1964 CORE_ADDR ofs;
1965 unsigned char *data;
1966
1967 strcpy (own_buf, "E00");
1968 data = (unsigned char *) malloc (packet_len - (offset - own_buf));
1969 if (data == NULL)
1970 {
1971 write_enn (own_buf);
1972 return 1;
1973 }
1974 if (decode_xfer_write (offset, packet_len - (offset - own_buf),
1975 &ofs, &len, data) < 0)
1976 {
1977 free (data);
1978 write_enn (own_buf);
1979 return 1;
1980 }
1981
1982 n = (*q->xfer) (annex, NULL, data, ofs, len);
1983 if (n == -2)
1984 {
1985 free (data);
1986 return 0;
1987 }
1988 else if (n == -3)
1989 {
1990 /* Preserve error message. */
1991 }
1992 else if (n < 0)
1993 write_enn (own_buf);
1994 else
1995 sprintf (own_buf, "%x", n);
1996
1997 free (data);
1998 return 1;
1999 }
2000
2001 return 0;
2002 }
2003 }
2004
2005 return 0;
2006 }
2007
2008 /* Compute 32 bit CRC from inferior memory.
2009
2010 On success, return 32 bit CRC.
2011 On failure, return (unsigned long long) -1. */
2012
2013 static unsigned long long
2014 crc32 (CORE_ADDR base, int len, unsigned int crc)
2015 {
2016 while (len--)
2017 {
2018 unsigned char byte = 0;
2019
2020 /* Return failure if memory read fails. */
2021 if (read_inferior_memory (base, &byte, 1) != 0)
2022 return (unsigned long long) -1;
2023
2024 crc = xcrc32 (&byte, 1, crc);
2025 base++;
2026 }
2027 return (unsigned long long) crc;
2028 }
2029
2030 /* Add supported btrace packets to BUF. */
2031
2032 static void
2033 supported_btrace_packets (char *buf)
2034 {
2035 int btrace_supported = 0;
2036
2037 if (target_supports_btrace (BTRACE_FORMAT_BTS))
2038 {
2039 strcat (buf, ";Qbtrace:bts+");
2040 strcat (buf, ";Qbtrace-conf:bts:size+");
2041
2042 btrace_supported = 1;
2043 }
2044
2045 if (target_supports_btrace (BTRACE_FORMAT_PT))
2046 {
2047 strcat (buf, ";Qbtrace:pt+");
2048 strcat (buf, ";Qbtrace-conf:pt:size+");
2049
2050 btrace_supported = 1;
2051 }
2052
2053 if (!btrace_supported)
2054 return;
2055
2056 strcat (buf, ";Qbtrace:off+");
2057 strcat (buf, ";qXfer:btrace:read+");
2058 strcat (buf, ";qXfer:btrace-conf:read+");
2059 }
2060
2061 /* Handle all of the extended 'q' packets. */
2062
2063 static void
2064 handle_query (char *own_buf, int packet_len, int *new_packet_len_p)
2065 {
2066 static struct inferior_list_entry *thread_ptr;
2067
2068 /* Reply the current thread id. */
2069 if (strcmp ("qC", own_buf) == 0 && !disable_packet_qC)
2070 {
2071 ptid_t gdb_id;
2072 require_running (own_buf);
2073
2074 if (!ptid_equal (general_thread, null_ptid)
2075 && !ptid_equal (general_thread, minus_one_ptid))
2076 gdb_id = general_thread;
2077 else
2078 {
2079 thread_ptr = get_first_inferior (&all_threads);
2080 gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
2081 }
2082
2083 sprintf (own_buf, "QC");
2084 own_buf += 2;
2085 write_ptid (own_buf, gdb_id);
2086 return;
2087 }
2088
2089 if (strcmp ("qSymbol::", own_buf) == 0)
2090 {
2091 struct thread_info *save_thread = current_thread;
2092
2093 /* For qSymbol, GDB only changes the current thread if the
2094 previous current thread was of a different process. So if
2095 the previous thread is gone, we need to pick another one of
2096 the same process. This can happen e.g., if we followed an
2097 exec in a non-leader thread. */
2098 if (current_thread == NULL)
2099 {
2100 current_thread
2101 = find_any_thread_of_pid (ptid_get_pid (general_thread));
2102
2103 /* Just in case, if we didn't find a thread, then bail out
2104 instead of crashing. */
2105 if (current_thread == NULL)
2106 {
2107 write_enn (own_buf);
2108 current_thread = save_thread;
2109 return;
2110 }
2111 }
2112
2113 /* GDB is suggesting new symbols have been loaded. This may
2114 mean a new shared library has been detected as loaded, so
2115 take the opportunity to check if breakpoints we think are
2116 inserted, still are. Note that it isn't guaranteed that
2117 we'll see this when a shared library is loaded, and nor will
2118 we see this for unloads (although breakpoints in unloaded
2119 libraries shouldn't trigger), as GDB may not find symbols for
2120 the library at all. We also re-validate breakpoints when we
2121 see a second GDB breakpoint for the same address, and or when
2122 we access breakpoint shadows. */
2123 validate_breakpoints ();
2124
2125 if (target_supports_tracepoints ())
2126 tracepoint_look_up_symbols ();
2127
2128 if (current_thread != NULL && the_target->look_up_symbols != NULL)
2129 (*the_target->look_up_symbols) ();
2130
2131 current_thread = save_thread;
2132
2133 strcpy (own_buf, "OK");
2134 return;
2135 }
2136
2137 if (!disable_packet_qfThreadInfo)
2138 {
2139 if (strcmp ("qfThreadInfo", own_buf) == 0)
2140 {
2141 ptid_t gdb_id;
2142
2143 require_running (own_buf);
2144 thread_ptr = get_first_inferior (&all_threads);
2145
2146 *own_buf++ = 'm';
2147 gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
2148 write_ptid (own_buf, gdb_id);
2149 thread_ptr = thread_ptr->next;
2150 return;
2151 }
2152
2153 if (strcmp ("qsThreadInfo", own_buf) == 0)
2154 {
2155 ptid_t gdb_id;
2156
2157 require_running (own_buf);
2158 if (thread_ptr != NULL)
2159 {
2160 *own_buf++ = 'm';
2161 gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
2162 write_ptid (own_buf, gdb_id);
2163 thread_ptr = thread_ptr->next;
2164 return;
2165 }
2166 else
2167 {
2168 sprintf (own_buf, "l");
2169 return;
2170 }
2171 }
2172 }
2173
2174 if (the_target->read_offsets != NULL
2175 && strcmp ("qOffsets", own_buf) == 0)
2176 {
2177 CORE_ADDR text, data;
2178
2179 require_running (own_buf);
2180 if (the_target->read_offsets (&text, &data))
2181 sprintf (own_buf, "Text=%lX;Data=%lX;Bss=%lX",
2182 (long)text, (long)data, (long)data);
2183 else
2184 write_enn (own_buf);
2185
2186 return;
2187 }
2188
2189 /* Protocol features query. */
2190 if (startswith (own_buf, "qSupported")
2191 && (own_buf[10] == ':' || own_buf[10] == '\0'))
2192 {
2193 char *p = &own_buf[10];
2194 int gdb_supports_qRelocInsn = 0;
2195
2196 /* Process each feature being provided by GDB. The first
2197 feature will follow a ':', and latter features will follow
2198 ';'. */
2199 if (*p == ':')
2200 {
2201 char **qsupported = NULL;
2202 int count = 0;
2203 int unknown = 0;
2204 int i;
2205
2206 /* Two passes, to avoid nested strtok calls in
2207 target_process_qsupported. */
2208 for (p = strtok (p + 1, ";");
2209 p != NULL;
2210 p = strtok (NULL, ";"))
2211 {
2212 count++;
2213 qsupported = XRESIZEVEC (char *, qsupported, count);
2214 qsupported[count - 1] = xstrdup (p);
2215 }
2216
2217 for (i = 0; i < count; i++)
2218 {
2219 p = qsupported[i];
2220 if (strcmp (p, "multiprocess+") == 0)
2221 {
2222 /* GDB supports and wants multi-process support if
2223 possible. */
2224 if (target_supports_multi_process ())
2225 multi_process = 1;
2226 }
2227 else if (strcmp (p, "qRelocInsn+") == 0)
2228 {
2229 /* GDB supports relocate instruction requests. */
2230 gdb_supports_qRelocInsn = 1;
2231 }
2232 else if (strcmp (p, "swbreak+") == 0)
2233 {
2234 /* GDB wants us to report whether a trap is caused
2235 by a software breakpoint and for us to handle PC
2236 adjustment if necessary on this target. */
2237 if (target_supports_stopped_by_sw_breakpoint ())
2238 swbreak_feature = 1;
2239 }
2240 else if (strcmp (p, "hwbreak+") == 0)
2241 {
2242 /* GDB wants us to report whether a trap is caused
2243 by a hardware breakpoint. */
2244 if (target_supports_stopped_by_hw_breakpoint ())
2245 hwbreak_feature = 1;
2246 }
2247 else if (strcmp (p, "fork-events+") == 0)
2248 {
2249 /* GDB supports and wants fork events if possible. */
2250 if (target_supports_fork_events ())
2251 report_fork_events = 1;
2252 }
2253 else if (strcmp (p, "vfork-events+") == 0)
2254 {
2255 /* GDB supports and wants vfork events if possible. */
2256 if (target_supports_vfork_events ())
2257 report_vfork_events = 1;
2258 }
2259 else if (strcmp (p, "exec-events+") == 0)
2260 {
2261 /* GDB supports and wants exec events if possible. */
2262 if (target_supports_exec_events ())
2263 report_exec_events = 1;
2264 }
2265 else if (strcmp (p, "vContSupported+") == 0)
2266 vCont_supported = 1;
2267 else if (strcmp (p, "QThreadEvents+") == 0)
2268 ;
2269 else if (strcmp (p, "no-resumed+") == 0)
2270 {
2271 /* GDB supports and wants TARGET_WAITKIND_NO_RESUMED
2272 events. */
2273 report_no_resumed = 1;
2274 }
2275 else
2276 {
2277 /* Move the unknown features all together. */
2278 qsupported[i] = NULL;
2279 qsupported[unknown] = p;
2280 unknown++;
2281 }
2282 }
2283
2284 /* Give the target backend a chance to process the unknown
2285 features. */
2286 target_process_qsupported (qsupported, unknown);
2287
2288 for (i = 0; i < count; i++)
2289 free (qsupported[i]);
2290 free (qsupported);
2291 }
2292
2293 sprintf (own_buf,
2294 "PacketSize=%x;QPassSignals+;QProgramSignals+;"
2295 "QStartupWithShell+;QEnvironmentHexEncoded+;"
2296 "QEnvironmentReset+;QEnvironmentUnset+",
2297 PBUFSIZ - 1);
2298
2299 if (target_supports_catch_syscall ())
2300 strcat (own_buf, ";QCatchSyscalls+");
2301
2302 if (the_target->qxfer_libraries_svr4 != NULL)
2303 strcat (own_buf, ";qXfer:libraries-svr4:read+"
2304 ";augmented-libraries-svr4-read+");
2305 else
2306 {
2307 /* We do not have any hook to indicate whether the non-SVR4 target
2308 backend supports qXfer:libraries:read, so always report it. */
2309 strcat (own_buf, ";qXfer:libraries:read+");
2310 }
2311
2312 if (the_target->read_auxv != NULL)
2313 strcat (own_buf, ";qXfer:auxv:read+");
2314
2315 if (the_target->qxfer_spu != NULL)
2316 strcat (own_buf, ";qXfer:spu:read+;qXfer:spu:write+");
2317
2318 if (the_target->qxfer_siginfo != NULL)
2319 strcat (own_buf, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
2320
2321 if (the_target->read_loadmap != NULL)
2322 strcat (own_buf, ";qXfer:fdpic:read+");
2323
2324 /* We always report qXfer:features:read, as targets may
2325 install XML files on a subsequent call to arch_setup.
2326 If we reported to GDB on startup that we don't support
2327 qXfer:feature:read at all, we will never be re-queried. */
2328 strcat (own_buf, ";qXfer:features:read+");
2329
2330 if (transport_is_reliable)
2331 strcat (own_buf, ";QStartNoAckMode+");
2332
2333 if (the_target->qxfer_osdata != NULL)
2334 strcat (own_buf, ";qXfer:osdata:read+");
2335
2336 if (target_supports_multi_process ())
2337 strcat (own_buf, ";multiprocess+");
2338
2339 if (target_supports_fork_events ())
2340 strcat (own_buf, ";fork-events+");
2341
2342 if (target_supports_vfork_events ())
2343 strcat (own_buf, ";vfork-events+");
2344
2345 if (target_supports_exec_events ())
2346 strcat (own_buf, ";exec-events+");
2347
2348 if (target_supports_non_stop ())
2349 strcat (own_buf, ";QNonStop+");
2350
2351 if (target_supports_disable_randomization ())
2352 strcat (own_buf, ";QDisableRandomization+");
2353
2354 strcat (own_buf, ";qXfer:threads:read+");
2355
2356 if (target_supports_tracepoints ())
2357 {
2358 strcat (own_buf, ";ConditionalTracepoints+");
2359 strcat (own_buf, ";TraceStateVariables+");
2360 strcat (own_buf, ";TracepointSource+");
2361 strcat (own_buf, ";DisconnectedTracing+");
2362 if (gdb_supports_qRelocInsn && target_supports_fast_tracepoints ())
2363 strcat (own_buf, ";FastTracepoints+");
2364 strcat (own_buf, ";StaticTracepoints+");
2365 strcat (own_buf, ";InstallInTrace+");
2366 strcat (own_buf, ";qXfer:statictrace:read+");
2367 strcat (own_buf, ";qXfer:traceframe-info:read+");
2368 strcat (own_buf, ";EnableDisableTracepoints+");
2369 strcat (own_buf, ";QTBuffer:size+");
2370 strcat (own_buf, ";tracenz+");
2371 }
2372
2373 if (target_supports_hardware_single_step ()
2374 || target_supports_software_single_step () )
2375 {
2376 strcat (own_buf, ";ConditionalBreakpoints+");
2377 }
2378 strcat (own_buf, ";BreakpointCommands+");
2379
2380 if (target_supports_agent ())
2381 strcat (own_buf, ";QAgent+");
2382
2383 supported_btrace_packets (own_buf);
2384
2385 if (target_supports_stopped_by_sw_breakpoint ())
2386 strcat (own_buf, ";swbreak+");
2387
2388 if (target_supports_stopped_by_hw_breakpoint ())
2389 strcat (own_buf, ";hwbreak+");
2390
2391 if (the_target->pid_to_exec_file != NULL)
2392 strcat (own_buf, ";qXfer:exec-file:read+");
2393
2394 strcat (own_buf, ";vContSupported+");
2395
2396 strcat (own_buf, ";QThreadEvents+");
2397
2398 strcat (own_buf, ";no-resumed+");
2399
2400 /* Reinitialize components as needed for the new connection. */
2401 hostio_handle_new_gdb_connection ();
2402 target_handle_new_gdb_connection ();
2403
2404 return;
2405 }
2406
2407 /* Thread-local storage support. */
2408 if (the_target->get_tls_address != NULL
2409 && startswith (own_buf, "qGetTLSAddr:"))
2410 {
2411 char *p = own_buf + 12;
2412 CORE_ADDR parts[2], address = 0;
2413 int i, err;
2414 ptid_t ptid = null_ptid;
2415
2416 require_running (own_buf);
2417
2418 for (i = 0; i < 3; i++)
2419 {
2420 char *p2;
2421 int len;
2422
2423 if (p == NULL)
2424 break;
2425
2426 p2 = strchr (p, ',');
2427 if (p2)
2428 {
2429 len = p2 - p;
2430 p2++;
2431 }
2432 else
2433 {
2434 len = strlen (p);
2435 p2 = NULL;
2436 }
2437
2438 if (i == 0)
2439 ptid = read_ptid (p, NULL);
2440 else
2441 decode_address (&parts[i - 1], p, len);
2442 p = p2;
2443 }
2444
2445 if (p != NULL || i < 3)
2446 err = 1;
2447 else
2448 {
2449 struct thread_info *thread = find_thread_ptid (ptid);
2450
2451 if (thread == NULL)
2452 err = 2;
2453 else
2454 err = the_target->get_tls_address (thread, parts[0], parts[1],
2455 &address);
2456 }
2457
2458 if (err == 0)
2459 {
2460 strcpy (own_buf, paddress(address));
2461 return;
2462 }
2463 else if (err > 0)
2464 {
2465 write_enn (own_buf);
2466 return;
2467 }
2468
2469 /* Otherwise, pretend we do not understand this packet. */
2470 }
2471
2472 /* Windows OS Thread Information Block address support. */
2473 if (the_target->get_tib_address != NULL
2474 && startswith (own_buf, "qGetTIBAddr:"))
2475 {
2476 char *annex;
2477 int n;
2478 CORE_ADDR tlb;
2479 ptid_t ptid = read_ptid (own_buf + 12, &annex);
2480
2481 n = (*the_target->get_tib_address) (ptid, &tlb);
2482 if (n == 1)
2483 {
2484 strcpy (own_buf, paddress(tlb));
2485 return;
2486 }
2487 else if (n == 0)
2488 {
2489 write_enn (own_buf);
2490 return;
2491 }
2492 return;
2493 }
2494
2495 /* Handle "monitor" commands. */
2496 if (startswith (own_buf, "qRcmd,"))
2497 {
2498 char *mon = (char *) malloc (PBUFSIZ);
2499 int len = strlen (own_buf + 6);
2500
2501 if (mon == NULL)
2502 {
2503 write_enn (own_buf);
2504 return;
2505 }
2506
2507 if ((len % 2) != 0
2508 || hex2bin (own_buf + 6, (gdb_byte *) mon, len / 2) != len / 2)
2509 {
2510 write_enn (own_buf);
2511 free (mon);
2512 return;
2513 }
2514 mon[len / 2] = '\0';
2515
2516 write_ok (own_buf);
2517
2518 if (the_target->handle_monitor_command == NULL
2519 || (*the_target->handle_monitor_command) (mon) == 0)
2520 /* Default processing. */
2521 handle_monitor_command (mon, own_buf);
2522
2523 free (mon);
2524 return;
2525 }
2526
2527 if (startswith (own_buf, "qSearch:memory:"))
2528 {
2529 require_running (own_buf);
2530 handle_search_memory (own_buf, packet_len);
2531 return;
2532 }
2533
2534 if (strcmp (own_buf, "qAttached") == 0
2535 || startswith (own_buf, "qAttached:"))
2536 {
2537 struct process_info *process;
2538
2539 if (own_buf[sizeof ("qAttached") - 1])
2540 {
2541 int pid = strtoul (own_buf + sizeof ("qAttached:") - 1, NULL, 16);
2542 process = (struct process_info *)
2543 find_inferior_id (&all_processes, pid_to_ptid (pid));
2544 }
2545 else
2546 {
2547 require_running (own_buf);
2548 process = current_process ();
2549 }
2550
2551 if (process == NULL)
2552 {
2553 write_enn (own_buf);
2554 return;
2555 }
2556
2557 strcpy (own_buf, process->attached ? "1" : "0");
2558 return;
2559 }
2560
2561 if (startswith (own_buf, "qCRC:"))
2562 {
2563 /* CRC check (compare-section). */
2564 char *comma;
2565 ULONGEST base;
2566 int len;
2567 unsigned long long crc;
2568
2569 require_running (own_buf);
2570 comma = unpack_varlen_hex (own_buf + 5, &base);
2571 if (*comma++ != ',')
2572 {
2573 write_enn (own_buf);
2574 return;
2575 }
2576 len = strtoul (comma, NULL, 16);
2577 crc = crc32 (base, len, 0xffffffff);
2578 /* Check for memory failure. */
2579 if (crc == (unsigned long long) -1)
2580 {
2581 write_enn (own_buf);
2582 return;
2583 }
2584 sprintf (own_buf, "C%lx", (unsigned long) crc);
2585 return;
2586 }
2587
2588 if (handle_qxfer (own_buf, packet_len, new_packet_len_p))
2589 return;
2590
2591 if (target_supports_tracepoints () && handle_tracepoint_query (own_buf))
2592 return;
2593
2594 /* Otherwise we didn't know what packet it was. Say we didn't
2595 understand it. */
2596 own_buf[0] = 0;
2597 }
2598
2599 static void gdb_wants_all_threads_stopped (void);
2600 static void resume (struct thread_resume *actions, size_t n);
2601
2602 /* The callback that is passed to visit_actioned_threads. */
2603 typedef int (visit_actioned_threads_callback_ftype)
2604 (const struct thread_resume *, struct thread_info *);
2605
2606 /* Struct to pass data to visit_actioned_threads. */
2607
2608 struct visit_actioned_threads_data
2609 {
2610 const struct thread_resume *actions;
2611 size_t num_actions;
2612 visit_actioned_threads_callback_ftype *callback;
2613 };
2614
2615 /* Call CALLBACK for any thread to which ACTIONS applies to. Returns
2616 true if CALLBACK returns true. Returns false if no matching thread
2617 is found or CALLBACK results false.
2618 Note: This function is itself a callback for find_inferior. */
2619
2620 static int
2621 visit_actioned_threads (struct inferior_list_entry *entry, void *datap)
2622 {
2623 struct visit_actioned_threads_data *data
2624 = (struct visit_actioned_threads_data *) datap;
2625 const struct thread_resume *actions = data->actions;
2626 size_t num_actions = data->num_actions;
2627 visit_actioned_threads_callback_ftype *callback = data->callback;
2628 size_t i;
2629
2630 for (i = 0; i < num_actions; i++)
2631 {
2632 const struct thread_resume *action = &actions[i];
2633
2634 if (ptid_equal (action->thread, minus_one_ptid)
2635 || ptid_equal (action->thread, entry->id)
2636 || ((ptid_get_pid (action->thread)
2637 == ptid_get_pid (entry->id))
2638 && ptid_get_lwp (action->thread) == -1))
2639 {
2640 struct thread_info *thread = (struct thread_info *) entry;
2641
2642 if ((*callback) (action, thread))
2643 return 1;
2644 }
2645 }
2646
2647 return 0;
2648 }
2649
2650 /* Callback for visit_actioned_threads. If the thread has a pending
2651 status to report, report it now. */
2652
2653 static int
2654 handle_pending_status (const struct thread_resume *resumption,
2655 struct thread_info *thread)
2656 {
2657 if (thread->status_pending_p)
2658 {
2659 thread->status_pending_p = 0;
2660
2661 last_status = thread->last_status;
2662 last_ptid = thread->entry.id;
2663 prepare_resume_reply (own_buf, last_ptid, &last_status);
2664 return 1;
2665 }
2666 return 0;
2667 }
2668
2669 /* Parse vCont packets. */
2670 static void
2671 handle_v_cont (char *own_buf)
2672 {
2673 char *p, *q;
2674 int n = 0, i = 0;
2675 struct thread_resume *resume_info;
2676 struct thread_resume default_action { null_ptid };
2677
2678 /* Count the number of semicolons in the packet. There should be one
2679 for every action. */
2680 p = &own_buf[5];
2681 while (p)
2682 {
2683 n++;
2684 p++;
2685 p = strchr (p, ';');
2686 }
2687
2688 resume_info = (struct thread_resume *) malloc (n * sizeof (resume_info[0]));
2689 if (resume_info == NULL)
2690 goto err;
2691
2692 p = &own_buf[5];
2693 while (*p)
2694 {
2695 p++;
2696
2697 memset (&resume_info[i], 0, sizeof resume_info[i]);
2698
2699 if (p[0] == 's' || p[0] == 'S')
2700 resume_info[i].kind = resume_step;
2701 else if (p[0] == 'r')
2702 resume_info[i].kind = resume_step;
2703 else if (p[0] == 'c' || p[0] == 'C')
2704 resume_info[i].kind = resume_continue;
2705 else if (p[0] == 't')
2706 resume_info[i].kind = resume_stop;
2707 else
2708 goto err;
2709
2710 if (p[0] == 'S' || p[0] == 'C')
2711 {
2712 int sig;
2713 sig = strtol (p + 1, &q, 16);
2714 if (p == q)
2715 goto err;
2716 p = q;
2717
2718 if (!gdb_signal_to_host_p ((enum gdb_signal) sig))
2719 goto err;
2720 resume_info[i].sig = gdb_signal_to_host ((enum gdb_signal) sig);
2721 }
2722 else if (p[0] == 'r')
2723 {
2724 ULONGEST addr;
2725
2726 p = unpack_varlen_hex (p + 1, &addr);
2727 resume_info[i].step_range_start = addr;
2728
2729 if (*p != ',')
2730 goto err;
2731
2732 p = unpack_varlen_hex (p + 1, &addr);
2733 resume_info[i].step_range_end = addr;
2734 }
2735 else
2736 {
2737 p = p + 1;
2738 }
2739
2740 if (p[0] == 0)
2741 {
2742 resume_info[i].thread = minus_one_ptid;
2743 default_action = resume_info[i];
2744
2745 /* Note: we don't increment i here, we'll overwrite this entry
2746 the next time through. */
2747 }
2748 else if (p[0] == ':')
2749 {
2750 ptid_t ptid = read_ptid (p + 1, &q);
2751
2752 if (p == q)
2753 goto err;
2754 p = q;
2755 if (p[0] != ';' && p[0] != 0)
2756 goto err;
2757
2758 resume_info[i].thread = ptid;
2759
2760 i++;
2761 }
2762 }
2763
2764 if (i < n)
2765 resume_info[i] = default_action;
2766
2767 resume (resume_info, n);
2768 free (resume_info);
2769 return;
2770
2771 err:
2772 write_enn (own_buf);
2773 free (resume_info);
2774 return;
2775 }
2776
2777 /* Resume target with ACTIONS, an array of NUM_ACTIONS elements. */
2778
2779 static void
2780 resume (struct thread_resume *actions, size_t num_actions)
2781 {
2782 if (!non_stop)
2783 {
2784 /* Check if among the threads that GDB wants actioned, there's
2785 one with a pending status to report. If so, skip actually
2786 resuming/stopping and report the pending event
2787 immediately. */
2788 struct visit_actioned_threads_data data;
2789
2790 data.actions = actions;
2791 data.num_actions = num_actions;
2792 data.callback = handle_pending_status;
2793 if (find_inferior (&all_threads, visit_actioned_threads, &data) != NULL)
2794 return;
2795
2796 enable_async_io ();
2797 }
2798
2799 (*the_target->resume) (actions, num_actions);
2800
2801 if (non_stop)
2802 write_ok (own_buf);
2803 else
2804 {
2805 last_ptid = mywait (minus_one_ptid, &last_status, 0, 1);
2806
2807 if (last_status.kind == TARGET_WAITKIND_NO_RESUMED
2808 && !report_no_resumed)
2809 {
2810 /* The client does not support this stop reply. At least
2811 return error. */
2812 sprintf (own_buf, "E.No unwaited-for children left.");
2813 disable_async_io ();
2814 return;
2815 }
2816
2817 if (last_status.kind != TARGET_WAITKIND_EXITED
2818 && last_status.kind != TARGET_WAITKIND_SIGNALLED
2819 && last_status.kind != TARGET_WAITKIND_NO_RESUMED)
2820 current_thread->last_status = last_status;
2821
2822 /* From the client's perspective, all-stop mode always stops all
2823 threads implicitly (and the target backend has already done
2824 so by now). Tag all threads as "want-stopped", so we don't
2825 resume them implicitly without the client telling us to. */
2826 gdb_wants_all_threads_stopped ();
2827 prepare_resume_reply (own_buf, last_ptid, &last_status);
2828 disable_async_io ();
2829
2830 if (last_status.kind == TARGET_WAITKIND_EXITED
2831 || last_status.kind == TARGET_WAITKIND_SIGNALLED)
2832 target_mourn_inferior (last_ptid);
2833 }
2834 }
2835
2836 /* Attach to a new program. Return 1 if successful, 0 if failure. */
2837 static int
2838 handle_v_attach (char *own_buf)
2839 {
2840 int pid;
2841
2842 pid = strtol (own_buf + 8, NULL, 16);
2843 if (pid != 0 && attach_inferior (pid) == 0)
2844 {
2845 /* Don't report shared library events after attaching, even if
2846 some libraries are preloaded. GDB will always poll the
2847 library list. Avoids the "stopped by shared library event"
2848 notice on the GDB side. */
2849 dlls_changed = 0;
2850
2851 if (non_stop)
2852 {
2853 /* In non-stop, we don't send a resume reply. Stop events
2854 will follow up using the normal notification
2855 mechanism. */
2856 write_ok (own_buf);
2857 }
2858 else
2859 prepare_resume_reply (own_buf, last_ptid, &last_status);
2860
2861 return 1;
2862 }
2863 else
2864 {
2865 write_enn (own_buf);
2866 return 0;
2867 }
2868 }
2869
2870 /* Run a new program. Return 1 if successful, 0 if failure. */
2871 static int
2872 handle_v_run (char *own_buf)
2873 {
2874 char *p, *next_p;
2875 std::vector<char *> new_argv;
2876 char *new_program_name = NULL;
2877 int i, new_argc;
2878
2879 new_argc = 0;
2880 for (p = own_buf + strlen ("vRun;"); p && *p; p = strchr (p, ';'))
2881 {
2882 p++;
2883 new_argc++;
2884 }
2885
2886 for (i = 0, p = own_buf + strlen ("vRun;"); *p; p = next_p, ++i)
2887 {
2888 next_p = strchr (p, ';');
2889 if (next_p == NULL)
2890 next_p = p + strlen (p);
2891
2892 if (i == 0 && p == next_p)
2893 {
2894 /* No program specified. */
2895 new_program_name = NULL;
2896 }
2897 else if (p == next_p)
2898 {
2899 /* Empty argument. */
2900 new_argv.push_back (xstrdup ("''"));
2901 }
2902 else
2903 {
2904 size_t len = (next_p - p) / 2;
2905 /* ARG is the unquoted argument received via the RSP. */
2906 char *arg = (char *) xmalloc (len + 1);
2907 /* FULL_ARGS will contain the quoted version of ARG. */
2908 char *full_arg = (char *) xmalloc ((len + 1) * 2);
2909 /* These are pointers used to navigate the strings above. */
2910 char *tmp_arg = arg;
2911 char *tmp_full_arg = full_arg;
2912 int need_quote = 0;
2913
2914 hex2bin (p, (gdb_byte *) arg, len);
2915 arg[len] = '\0';
2916
2917 while (*tmp_arg != '\0')
2918 {
2919 switch (*tmp_arg)
2920 {
2921 case '\n':
2922 /* Quote \n. */
2923 *tmp_full_arg = '\'';
2924 ++tmp_full_arg;
2925 need_quote = 1;
2926 break;
2927
2928 case '\'':
2929 /* Quote single quote. */
2930 *tmp_full_arg = '\\';
2931 ++tmp_full_arg;
2932 break;
2933
2934 default:
2935 break;
2936 }
2937
2938 *tmp_full_arg = *tmp_arg;
2939 ++tmp_full_arg;
2940 ++tmp_arg;
2941 }
2942
2943 if (need_quote)
2944 *tmp_full_arg++ = '\'';
2945
2946 /* Finish FULL_ARG and push it into the vector containing
2947 the argv. */
2948 *tmp_full_arg = '\0';
2949 if (i == 0)
2950 new_program_name = full_arg;
2951 else
2952 new_argv.push_back (full_arg);
2953 xfree (arg);
2954 }
2955 if (*next_p)
2956 next_p++;
2957 }
2958 new_argv.push_back (NULL);
2959
2960 if (new_program_name == NULL)
2961 {
2962 /* GDB didn't specify a program to run. Use the program from the
2963 last run with the new argument list. */
2964 if (program_name == NULL)
2965 {
2966 write_enn (own_buf);
2967 free_vector_argv (new_argv);
2968 return 0;
2969 }
2970 }
2971 else
2972 {
2973 xfree (program_name);
2974 program_name = new_program_name;
2975 }
2976
2977 /* Free the old argv and install the new one. */
2978 free_vector_argv (program_args);
2979 program_args = new_argv;
2980
2981 create_inferior (program_name, program_args);
2982
2983 if (last_status.kind == TARGET_WAITKIND_STOPPED)
2984 {
2985 prepare_resume_reply (own_buf, last_ptid, &last_status);
2986
2987 /* In non-stop, sending a resume reply doesn't set the general
2988 thread, but GDB assumes a vRun sets it (this is so GDB can
2989 query which is the main thread of the new inferior. */
2990 if (non_stop)
2991 general_thread = last_ptid;
2992
2993 return 1;
2994 }
2995 else
2996 {
2997 write_enn (own_buf);
2998 return 0;
2999 }
3000 }
3001
3002 /* Kill process. Return 1 if successful, 0 if failure. */
3003 static int
3004 handle_v_kill (char *own_buf)
3005 {
3006 int pid;
3007 char *p = &own_buf[6];
3008 if (multi_process)
3009 pid = strtol (p, NULL, 16);
3010 else
3011 pid = signal_pid;
3012 if (pid != 0 && kill_inferior (pid) == 0)
3013 {
3014 last_status.kind = TARGET_WAITKIND_SIGNALLED;
3015 last_status.value.sig = GDB_SIGNAL_KILL;
3016 last_ptid = pid_to_ptid (pid);
3017 discard_queued_stop_replies (last_ptid);
3018 write_ok (own_buf);
3019 return 1;
3020 }
3021 else
3022 {
3023 write_enn (own_buf);
3024 return 0;
3025 }
3026 }
3027
3028 /* Handle all of the extended 'v' packets. */
3029 void
3030 handle_v_requests (char *own_buf, int packet_len, int *new_packet_len)
3031 {
3032 if (!disable_packet_vCont)
3033 {
3034 if (strcmp (own_buf, "vCtrlC") == 0)
3035 {
3036 (*the_target->request_interrupt) ();
3037 write_ok (own_buf);
3038 return;
3039 }
3040
3041 if (startswith (own_buf, "vCont;"))
3042 {
3043 handle_v_cont (own_buf);
3044 return;
3045 }
3046
3047 if (startswith (own_buf, "vCont?"))
3048 {
3049 strcpy (own_buf, "vCont;c;C;t");
3050
3051 if (target_supports_hardware_single_step ()
3052 || target_supports_software_single_step ()
3053 || !vCont_supported)
3054 {
3055 /* If target supports single step either by hardware or by
3056 software, add actions s and S to the list of supported
3057 actions. On the other hand, if GDB doesn't request the
3058 supported vCont actions in qSupported packet, add s and
3059 S to the list too. */
3060 own_buf = own_buf + strlen (own_buf);
3061 strcpy (own_buf, ";s;S");
3062 }
3063
3064 if (target_supports_range_stepping ())
3065 {
3066 own_buf = own_buf + strlen (own_buf);
3067 strcpy (own_buf, ";r");
3068 }
3069 return;
3070 }
3071 }
3072
3073 if (startswith (own_buf, "vFile:")
3074 && handle_vFile (own_buf, packet_len, new_packet_len))
3075 return;
3076
3077 if (startswith (own_buf, "vAttach;"))
3078 {
3079 if ((!extended_protocol || !multi_process) && target_running ())
3080 {
3081 fprintf (stderr, "Already debugging a process\n");
3082 write_enn (own_buf);
3083 return;
3084 }
3085 handle_v_attach (own_buf);
3086 return;
3087 }
3088
3089 if (startswith (own_buf, "vRun;"))
3090 {
3091 if ((!extended_protocol || !multi_process) && target_running ())
3092 {
3093 fprintf (stderr, "Already debugging a process\n");
3094 write_enn (own_buf);
3095 return;
3096 }
3097 handle_v_run (own_buf);
3098 return;
3099 }
3100
3101 if (startswith (own_buf, "vKill;"))
3102 {
3103 if (!target_running ())
3104 {
3105 fprintf (stderr, "No process to kill\n");
3106 write_enn (own_buf);
3107 return;
3108 }
3109 handle_v_kill (own_buf);
3110 return;
3111 }
3112
3113 if (handle_notif_ack (own_buf, packet_len))
3114 return;
3115
3116 /* Otherwise we didn't know what packet it was. Say we didn't
3117 understand it. */
3118 own_buf[0] = 0;
3119 return;
3120 }
3121
3122 /* Resume thread and wait for another event. In non-stop mode,
3123 don't really wait here, but return immediatelly to the event
3124 loop. */
3125 static void
3126 myresume (char *own_buf, int step, int sig)
3127 {
3128 struct thread_resume resume_info[2];
3129 int n = 0;
3130 int valid_cont_thread;
3131
3132 valid_cont_thread = (!ptid_equal (cont_thread, null_ptid)
3133 && !ptid_equal (cont_thread, minus_one_ptid));
3134
3135 if (step || sig || valid_cont_thread)
3136 {
3137 resume_info[0].thread = current_ptid;
3138 if (step)
3139 resume_info[0].kind = resume_step;
3140 else
3141 resume_info[0].kind = resume_continue;
3142 resume_info[0].sig = sig;
3143 n++;
3144 }
3145
3146 if (!valid_cont_thread)
3147 {
3148 resume_info[n].thread = minus_one_ptid;
3149 resume_info[n].kind = resume_continue;
3150 resume_info[n].sig = 0;
3151 n++;
3152 }
3153
3154 resume (resume_info, n);
3155 }
3156
3157 /* Callback for for_each_inferior. Make a new stop reply for each
3158 stopped thread. */
3159
3160 static int
3161 queue_stop_reply_callback (struct inferior_list_entry *entry, void *arg)
3162 {
3163 struct thread_info *thread = (struct thread_info *) entry;
3164
3165 /* For now, assume targets that don't have this callback also don't
3166 manage the thread's last_status field. */
3167 if (the_target->thread_stopped == NULL)
3168 {
3169 struct vstop_notif *new_notif = XNEW (struct vstop_notif);
3170
3171 new_notif->ptid = entry->id;
3172 new_notif->status = thread->last_status;
3173 /* Pass the last stop reply back to GDB, but don't notify
3174 yet. */
3175 notif_event_enque (&notif_stop,
3176 (struct notif_event *) new_notif);
3177 }
3178 else
3179 {
3180 if (thread_stopped (thread))
3181 {
3182 if (debug_threads)
3183 {
3184 char *status_string
3185 = target_waitstatus_to_string (&thread->last_status);
3186
3187 debug_printf ("Reporting thread %s as already stopped with %s\n",
3188 target_pid_to_str (entry->id),
3189 status_string);
3190
3191 xfree (status_string);
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 int
3454 first_thread_of (struct inferior_list_entry *entry, void *args)
3455 {
3456 int pid = * (int *) args;
3457
3458 if (ptid_get_pid (entry->id) == pid)
3459 return 1;
3460
3461 return 0;
3462 }
3463
3464 static void
3465 kill_inferior_callback (struct inferior_list_entry *entry)
3466 {
3467 struct process_info *process = (struct process_info *) entry;
3468 int pid = ptid_get_pid (process->entry.id);
3469
3470 kill_inferior (pid);
3471 discard_queued_stop_replies (pid_to_ptid (pid));
3472 }
3473
3474 /* Callback for for_each_inferior to detach or kill the inferior,
3475 depending on whether we attached to it or not.
3476 We inform the user whether we're detaching or killing the process
3477 as this is only called when gdbserver is about to exit. */
3478
3479 static void
3480 detach_or_kill_inferior_callback (struct inferior_list_entry *entry)
3481 {
3482 struct process_info *process = (struct process_info *) entry;
3483 int pid = ptid_get_pid (process->entry.id);
3484
3485 if (process->attached)
3486 detach_inferior (pid);
3487 else
3488 kill_inferior (pid);
3489
3490 discard_queued_stop_replies (pid_to_ptid (pid));
3491 }
3492
3493 /* for_each_inferior callback for detach_or_kill_for_exit to print
3494 the pids of started inferiors. */
3495
3496 static void
3497 print_started_pid (struct inferior_list_entry *entry)
3498 {
3499 struct process_info *process = (struct process_info *) entry;
3500
3501 if (! process->attached)
3502 {
3503 int pid = ptid_get_pid (process->entry.id);
3504 fprintf (stderr, " %d", pid);
3505 }
3506 }
3507
3508 /* for_each_inferior callback for detach_or_kill_for_exit to print
3509 the pids of attached inferiors. */
3510
3511 static void
3512 print_attached_pid (struct inferior_list_entry *entry)
3513 {
3514 struct process_info *process = (struct process_info *) entry;
3515
3516 if (process->attached)
3517 {
3518 int pid = ptid_get_pid (process->entry.id);
3519 fprintf (stderr, " %d", pid);
3520 }
3521 }
3522
3523 /* Call this when exiting gdbserver with possible inferiors that need
3524 to be killed or detached from. */
3525
3526 static void
3527 detach_or_kill_for_exit (void)
3528 {
3529 /* First print a list of the inferiors we will be killing/detaching.
3530 This is to assist the user, for example, in case the inferior unexpectedly
3531 dies after we exit: did we screw up or did the inferior exit on its own?
3532 Having this info will save some head-scratching. */
3533
3534 if (have_started_inferiors_p ())
3535 {
3536 fprintf (stderr, "Killing process(es):");
3537 for_each_inferior (&all_processes, print_started_pid);
3538 fprintf (stderr, "\n");
3539 }
3540 if (have_attached_inferiors_p ())
3541 {
3542 fprintf (stderr, "Detaching process(es):");
3543 for_each_inferior (&all_processes, print_attached_pid);
3544 fprintf (stderr, "\n");
3545 }
3546
3547 /* Now we can kill or detach the inferiors. */
3548
3549 for_each_inferior (&all_processes, detach_or_kill_inferior_callback);
3550 }
3551
3552 /* Value that will be passed to exit(3) when gdbserver exits. */
3553 static int exit_code;
3554
3555 /* Cleanup version of detach_or_kill_for_exit. */
3556
3557 static void
3558 detach_or_kill_for_exit_cleanup (void *ignore)
3559 {
3560
3561 TRY
3562 {
3563 detach_or_kill_for_exit ();
3564 }
3565
3566 CATCH (exception, RETURN_MASK_ALL)
3567 {
3568 fflush (stdout);
3569 fprintf (stderr, "Detach or kill failed: %s\n", exception.message);
3570 exit_code = 1;
3571 }
3572 END_CATCH
3573 }
3574
3575 /* Main function. This is called by the real "main" function,
3576 wrapped in a TRY_CATCH that handles any uncaught exceptions. */
3577
3578 static void ATTRIBUTE_NORETURN
3579 captured_main (int argc, char *argv[])
3580 {
3581 int bad_attach;
3582 int pid;
3583 char *arg_end;
3584 const char *port = NULL;
3585 char **next_arg = &argv[1];
3586 volatile int multi_mode = 0;
3587 volatile int attach = 0;
3588 int was_running;
3589 bool selftest = false;
3590
3591 while (*next_arg != NULL && **next_arg == '-')
3592 {
3593 if (strcmp (*next_arg, "--version") == 0)
3594 {
3595 gdbserver_version ();
3596 exit (0);
3597 }
3598 else if (strcmp (*next_arg, "--help") == 0)
3599 {
3600 gdbserver_usage (stdout);
3601 exit (0);
3602 }
3603 else if (strcmp (*next_arg, "--attach") == 0)
3604 attach = 1;
3605 else if (strcmp (*next_arg, "--multi") == 0)
3606 multi_mode = 1;
3607 else if (strcmp (*next_arg, "--wrapper") == 0)
3608 {
3609 char **tmp;
3610
3611 next_arg++;
3612
3613 tmp = next_arg;
3614 while (*next_arg != NULL && strcmp (*next_arg, "--") != 0)
3615 {
3616 wrapper_argv += *next_arg;
3617 wrapper_argv += ' ';
3618 next_arg++;
3619 }
3620
3621 if (!wrapper_argv.empty ())
3622 {
3623 /* Erase the last whitespace. */
3624 wrapper_argv.erase (wrapper_argv.end () - 1);
3625 }
3626
3627 if (next_arg == tmp || *next_arg == NULL)
3628 {
3629 gdbserver_usage (stderr);
3630 exit (1);
3631 }
3632
3633 /* Consume the "--". */
3634 *next_arg = NULL;
3635 }
3636 else if (strcmp (*next_arg, "--debug") == 0)
3637 debug_threads = 1;
3638 else if (startswith (*next_arg, "--debug-format="))
3639 {
3640 char *error_msg
3641 = parse_debug_format_options ((*next_arg)
3642 + sizeof ("--debug-format=") - 1, 0);
3643
3644 if (error_msg != NULL)
3645 {
3646 fprintf (stderr, "%s", error_msg);
3647 exit (1);
3648 }
3649 }
3650 else if (strcmp (*next_arg, "--remote-debug") == 0)
3651 remote_debug = 1;
3652 else if (strcmp (*next_arg, "--disable-packet") == 0)
3653 {
3654 gdbserver_show_disableable (stdout);
3655 exit (0);
3656 }
3657 else if (startswith (*next_arg, "--disable-packet="))
3658 {
3659 char *packets, *tok;
3660
3661 packets = *next_arg += sizeof ("--disable-packet=") - 1;
3662 for (tok = strtok (packets, ",");
3663 tok != NULL;
3664 tok = strtok (NULL, ","))
3665 {
3666 if (strcmp ("vCont", tok) == 0)
3667 disable_packet_vCont = 1;
3668 else if (strcmp ("Tthread", tok) == 0)
3669 disable_packet_Tthread = 1;
3670 else if (strcmp ("qC", tok) == 0)
3671 disable_packet_qC = 1;
3672 else if (strcmp ("qfThreadInfo", tok) == 0)
3673 disable_packet_qfThreadInfo = 1;
3674 else if (strcmp ("threads", tok) == 0)
3675 {
3676 disable_packet_vCont = 1;
3677 disable_packet_Tthread = 1;
3678 disable_packet_qC = 1;
3679 disable_packet_qfThreadInfo = 1;
3680 }
3681 else
3682 {
3683 fprintf (stderr, "Don't know how to disable \"%s\".\n\n",
3684 tok);
3685 gdbserver_show_disableable (stderr);
3686 exit (1);
3687 }
3688 }
3689 }
3690 else if (strcmp (*next_arg, "-") == 0)
3691 {
3692 /* "-" specifies a stdio connection and is a form of port
3693 specification. */
3694 port = STDIO_CONNECTION_NAME;
3695 next_arg++;
3696 break;
3697 }
3698 else if (strcmp (*next_arg, "--disable-randomization") == 0)
3699 disable_randomization = 1;
3700 else if (strcmp (*next_arg, "--no-disable-randomization") == 0)
3701 disable_randomization = 0;
3702 else if (strcmp (*next_arg, "--startup-with-shell") == 0)
3703 startup_with_shell = true;
3704 else if (strcmp (*next_arg, "--no-startup-with-shell") == 0)
3705 startup_with_shell = false;
3706 else if (strcmp (*next_arg, "--once") == 0)
3707 run_once = 1;
3708 else if (strcmp (*next_arg, "--selftest") == 0)
3709 selftest = true;
3710 else
3711 {
3712 fprintf (stderr, "Unknown argument: %s\n", *next_arg);
3713 exit (1);
3714 }
3715
3716 next_arg++;
3717 continue;
3718 }
3719
3720 if (port == NULL)
3721 {
3722 port = *next_arg;
3723 next_arg++;
3724 }
3725 if ((port == NULL || (!attach && !multi_mode && *next_arg == NULL))
3726 && !selftest)
3727 {
3728 gdbserver_usage (stderr);
3729 exit (1);
3730 }
3731
3732 /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
3733 opened by remote_prepare. */
3734 notice_open_fds ();
3735
3736 save_original_signals_state ();
3737
3738 /* We need to know whether the remote connection is stdio before
3739 starting the inferior. Inferiors created in this scenario have
3740 stdin,stdout redirected. So do this here before we call
3741 start_inferior. */
3742 if (port != NULL)
3743 remote_prepare (port);
3744
3745 bad_attach = 0;
3746 pid = 0;
3747
3748 /* --attach used to come after PORT, so allow it there for
3749 compatibility. */
3750 if (*next_arg != NULL && strcmp (*next_arg, "--attach") == 0)
3751 {
3752 attach = 1;
3753 next_arg++;
3754 }
3755
3756 if (attach
3757 && (*next_arg == NULL
3758 || (*next_arg)[0] == '\0'
3759 || (pid = strtoul (*next_arg, &arg_end, 0)) == 0
3760 || *arg_end != '\0'
3761 || next_arg[1] != NULL))
3762 bad_attach = 1;
3763
3764 if (bad_attach)
3765 {
3766 gdbserver_usage (stderr);
3767 exit (1);
3768 }
3769
3770 /* Gather information about the environment. */
3771 our_environ = gdb_environ::from_host_environ ();
3772
3773 initialize_async_io ();
3774 initialize_low ();
3775 have_job_control ();
3776 initialize_event_loop ();
3777 if (target_supports_tracepoints ())
3778 initialize_tracepoint ();
3779 initialize_notif ();
3780
3781 own_buf = (char *) xmalloc (PBUFSIZ + 1);
3782 mem_buf = (unsigned char *) xmalloc (PBUFSIZ);
3783
3784 if (selftest)
3785 {
3786 selftests::run_tests ();
3787 throw_quit ("Quit");
3788 }
3789
3790 if (pid == 0 && *next_arg != NULL)
3791 {
3792 int i, n;
3793
3794 n = argc - (next_arg - argv);
3795 program_name = xstrdup (next_arg[0]);
3796 for (i = 1; i < n; i++)
3797 program_args.push_back (xstrdup (next_arg[i]));
3798 program_args.push_back (NULL);
3799
3800 /* Wait till we are at first instruction in program. */
3801 create_inferior (program_name, program_args);
3802
3803 /* We are now (hopefully) stopped at the first instruction of
3804 the target process. This assumes that the target process was
3805 successfully created. */
3806 }
3807 else if (pid != 0)
3808 {
3809 if (attach_inferior (pid) == -1)
3810 error ("Attaching not supported on this target");
3811
3812 /* Otherwise succeeded. */
3813 }
3814 else
3815 {
3816 last_status.kind = TARGET_WAITKIND_EXITED;
3817 last_status.value.integer = 0;
3818 last_ptid = minus_one_ptid;
3819 }
3820 make_cleanup (detach_or_kill_for_exit_cleanup, NULL);
3821
3822 /* Don't report shared library events on the initial connection,
3823 even if some libraries are preloaded. Avoids the "stopped by
3824 shared library event" notice on gdb side. */
3825 dlls_changed = 0;
3826
3827 if (last_status.kind == TARGET_WAITKIND_EXITED
3828 || last_status.kind == TARGET_WAITKIND_SIGNALLED)
3829 was_running = 0;
3830 else
3831 was_running = 1;
3832
3833 if (!was_running && !multi_mode)
3834 error ("No program to debug");
3835
3836 while (1)
3837 {
3838
3839 noack_mode = 0;
3840 multi_process = 0;
3841 report_fork_events = 0;
3842 report_vfork_events = 0;
3843 report_exec_events = 0;
3844 /* Be sure we're out of tfind mode. */
3845 current_traceframe = -1;
3846 cont_thread = null_ptid;
3847 swbreak_feature = 0;
3848 hwbreak_feature = 0;
3849 vCont_supported = 0;
3850
3851 remote_open (port);
3852
3853 TRY
3854 {
3855 /* Wait for events. This will return when all event sources
3856 are removed from the event loop. */
3857 start_event_loop ();
3858
3859 /* If an exit was requested (using the "monitor exit"
3860 command), terminate now. */
3861 if (exit_requested)
3862 throw_quit ("Quit");
3863
3864 /* The only other way to get here is for getpkt to fail:
3865
3866 - If --once was specified, we're done.
3867
3868 - If not in extended-remote mode, and we're no longer
3869 debugging anything, simply exit: GDB has disconnected
3870 after processing the last process exit.
3871
3872 - Otherwise, close the connection and reopen it at the
3873 top of the loop. */
3874 if (run_once || (!extended_protocol && !target_running ()))
3875 throw_quit ("Quit");
3876
3877 fprintf (stderr,
3878 "Remote side has terminated connection. "
3879 "GDBserver will reopen the connection.\n");
3880
3881 /* Get rid of any pending statuses. An eventual reconnection
3882 (by the same GDB instance or another) will refresh all its
3883 state from scratch. */
3884 discard_queued_stop_replies (minus_one_ptid);
3885 for_each_inferior (&all_threads,
3886 clear_pending_status_callback);
3887
3888 if (tracing)
3889 {
3890 if (disconnected_tracing)
3891 {
3892 /* Try to enable non-stop/async mode, so we we can
3893 both wait for an async socket accept, and handle
3894 async target events simultaneously. There's also
3895 no point either in having the target always stop
3896 all threads, when we're going to pass signals
3897 down without informing GDB. */
3898 if (!non_stop)
3899 {
3900 if (start_non_stop (1))
3901 non_stop = 1;
3902
3903 /* Detaching implicitly resumes all threads;
3904 simply disconnecting does not. */
3905 }
3906 }
3907 else
3908 {
3909 fprintf (stderr,
3910 "Disconnected tracing disabled; "
3911 "stopping trace run.\n");
3912 stop_tracing ();
3913 }
3914 }
3915 }
3916 CATCH (exception, RETURN_MASK_ERROR)
3917 {
3918 fflush (stdout);
3919 fprintf (stderr, "gdbserver: %s\n", exception.message);
3920
3921 if (response_needed)
3922 {
3923 write_enn (own_buf);
3924 putpkt (own_buf);
3925 }
3926
3927 if (run_once)
3928 throw_quit ("Quit");
3929 }
3930 END_CATCH
3931 }
3932 }
3933
3934 /* Main function. */
3935
3936 int
3937 main (int argc, char *argv[])
3938 {
3939
3940 TRY
3941 {
3942 captured_main (argc, argv);
3943 }
3944 CATCH (exception, RETURN_MASK_ALL)
3945 {
3946 if (exception.reason == RETURN_ERROR)
3947 {
3948 fflush (stdout);
3949 fprintf (stderr, "%s\n", exception.message);
3950 fprintf (stderr, "Exiting\n");
3951 exit_code = 1;
3952 }
3953
3954 exit (exit_code);
3955 }
3956 END_CATCH
3957
3958 gdb_assert_not_reached ("captured_main should never return");
3959 }
3960
3961 /* Process options coming from Z packets for a breakpoint. PACKET is
3962 the packet buffer. *PACKET is updated to point to the first char
3963 after the last processed option. */
3964
3965 static void
3966 process_point_options (struct gdb_breakpoint *bp, char **packet)
3967 {
3968 char *dataptr = *packet;
3969 int persist;
3970
3971 /* Check if data has the correct format. */
3972 if (*dataptr != ';')
3973 return;
3974
3975 dataptr++;
3976
3977 while (*dataptr)
3978 {
3979 if (*dataptr == ';')
3980 ++dataptr;
3981
3982 if (*dataptr == 'X')
3983 {
3984 /* Conditional expression. */
3985 if (debug_threads)
3986 debug_printf ("Found breakpoint condition.\n");
3987 if (!add_breakpoint_condition (bp, &dataptr))
3988 dataptr = strchrnul (dataptr, ';');
3989 }
3990 else if (startswith (dataptr, "cmds:"))
3991 {
3992 dataptr += strlen ("cmds:");
3993 if (debug_threads)
3994 debug_printf ("Found breakpoint commands %s.\n", dataptr);
3995 persist = (*dataptr == '1');
3996 dataptr += 2;
3997 if (add_breakpoint_commands (bp, &dataptr, persist))
3998 dataptr = strchrnul (dataptr, ';');
3999 }
4000 else
4001 {
4002 fprintf (stderr, "Unknown token %c, ignoring.\n",
4003 *dataptr);
4004 /* Skip tokens until we find one that we recognize. */
4005 dataptr = strchrnul (dataptr, ';');
4006 }
4007 }
4008 *packet = dataptr;
4009 }
4010
4011 /* Event loop callback that handles a serial event. The first byte in
4012 the serial buffer gets us here. We expect characters to arrive at
4013 a brisk pace, so we read the rest of the packet with a blocking
4014 getpkt call. */
4015
4016 static int
4017 process_serial_event (void)
4018 {
4019 char ch;
4020 int i = 0;
4021 int signal;
4022 unsigned int len;
4023 int res;
4024 CORE_ADDR mem_addr;
4025 int pid;
4026 unsigned char sig;
4027 int packet_len;
4028 int new_packet_len = -1;
4029
4030 disable_async_io ();
4031
4032 response_needed = 0;
4033 packet_len = getpkt (own_buf);
4034 if (packet_len <= 0)
4035 {
4036 remote_close ();
4037 /* Force an event loop break. */
4038 return -1;
4039 }
4040 response_needed = 1;
4041
4042 i = 0;
4043 ch = own_buf[i++];
4044 switch (ch)
4045 {
4046 case 'q':
4047 handle_query (own_buf, packet_len, &new_packet_len);
4048 break;
4049 case 'Q':
4050 handle_general_set (own_buf);
4051 break;
4052 case 'D':
4053 require_running (own_buf);
4054
4055 if (multi_process)
4056 {
4057 i++; /* skip ';' */
4058 pid = strtol (&own_buf[i], NULL, 16);
4059 }
4060 else
4061 pid = ptid_get_pid (current_ptid);
4062
4063 if ((tracing && disconnected_tracing) || any_persistent_commands ())
4064 {
4065 struct process_info *process = find_process_pid (pid);
4066
4067 if (process == NULL)
4068 {
4069 write_enn (own_buf);
4070 break;
4071 }
4072
4073 if (tracing && disconnected_tracing)
4074 fprintf (stderr,
4075 "Disconnected tracing in effect, "
4076 "leaving gdbserver attached to the process\n");
4077
4078 if (any_persistent_commands ())
4079 fprintf (stderr,
4080 "Persistent commands are present, "
4081 "leaving gdbserver attached to the process\n");
4082
4083 /* Make sure we're in non-stop/async mode, so we we can both
4084 wait for an async socket accept, and handle async target
4085 events simultaneously. There's also no point either in
4086 having the target stop all threads, when we're going to
4087 pass signals down without informing GDB. */
4088 if (!non_stop)
4089 {
4090 if (debug_threads)
4091 debug_printf ("Forcing non-stop mode\n");
4092
4093 non_stop = 1;
4094 start_non_stop (1);
4095 }
4096
4097 process->gdb_detached = 1;
4098
4099 /* Detaching implicitly resumes all threads. */
4100 target_continue_no_signal (minus_one_ptid);
4101
4102 write_ok (own_buf);
4103 break; /* from switch/case */
4104 }
4105
4106 fprintf (stderr, "Detaching from process %d\n", pid);
4107 stop_tracing ();
4108 if (detach_inferior (pid) != 0)
4109 write_enn (own_buf);
4110 else
4111 {
4112 discard_queued_stop_replies (pid_to_ptid (pid));
4113 write_ok (own_buf);
4114
4115 if (extended_protocol || target_running ())
4116 {
4117 /* There is still at least one inferior remaining or
4118 we are in extended mode, so don't terminate gdbserver,
4119 and instead treat this like a normal program exit. */
4120 last_status.kind = TARGET_WAITKIND_EXITED;
4121 last_status.value.integer = 0;
4122 last_ptid = pid_to_ptid (pid);
4123
4124 current_thread = NULL;
4125 }
4126 else
4127 {
4128 putpkt (own_buf);
4129 remote_close ();
4130
4131 /* If we are attached, then we can exit. Otherwise, we
4132 need to hang around doing nothing, until the child is
4133 gone. */
4134 join_inferior (pid);
4135 exit (0);
4136 }
4137 }
4138 break;
4139 case '!':
4140 extended_protocol = 1;
4141 write_ok (own_buf);
4142 break;
4143 case '?':
4144 handle_status (own_buf);
4145 break;
4146 case 'H':
4147 if (own_buf[1] == 'c' || own_buf[1] == 'g' || own_buf[1] == 's')
4148 {
4149 ptid_t gdb_id, thread_id;
4150 int pid;
4151
4152 require_running (own_buf);
4153
4154 gdb_id = read_ptid (&own_buf[2], NULL);
4155
4156 pid = ptid_get_pid (gdb_id);
4157
4158 if (ptid_equal (gdb_id, null_ptid)
4159 || ptid_equal (gdb_id, minus_one_ptid))
4160 thread_id = null_ptid;
4161 else if (pid != 0
4162 && ptid_equal (pid_to_ptid (pid),
4163 gdb_id))
4164 {
4165 struct thread_info *thread =
4166 (struct thread_info *) find_inferior (&all_threads,
4167 first_thread_of,
4168 &pid);
4169 if (!thread)
4170 {
4171 write_enn (own_buf);
4172 break;
4173 }
4174
4175 thread_id = thread->entry.id;
4176 }
4177 else
4178 {
4179 thread_id = gdb_id_to_thread_id (gdb_id);
4180 if (ptid_equal (thread_id, null_ptid))
4181 {
4182 write_enn (own_buf);
4183 break;
4184 }
4185 }
4186
4187 if (own_buf[1] == 'g')
4188 {
4189 if (ptid_equal (thread_id, null_ptid))
4190 {
4191 /* GDB is telling us to choose any thread. Check if
4192 the currently selected thread is still valid. If
4193 it is not, select the first available. */
4194 struct thread_info *thread =
4195 (struct thread_info *) find_inferior_id (&all_threads,
4196 general_thread);
4197 if (thread == NULL)
4198 thread = get_first_thread ();
4199 thread_id = thread->entry.id;
4200 }
4201
4202 general_thread = thread_id;
4203 set_desired_thread (1);
4204 gdb_assert (current_thread != NULL);
4205 }
4206 else if (own_buf[1] == 'c')
4207 cont_thread = thread_id;
4208
4209 write_ok (own_buf);
4210 }
4211 else
4212 {
4213 /* Silently ignore it so that gdb can extend the protocol
4214 without compatibility headaches. */
4215 own_buf[0] = '\0';
4216 }
4217 break;
4218 case 'g':
4219 require_running (own_buf);
4220 if (current_traceframe >= 0)
4221 {
4222 struct regcache *regcache
4223 = new_register_cache (current_target_desc ());
4224
4225 if (fetch_traceframe_registers (current_traceframe,
4226 regcache, -1) == 0)
4227 registers_to_string (regcache, own_buf);
4228 else
4229 write_enn (own_buf);
4230 free_register_cache (regcache);
4231 }
4232 else
4233 {
4234 struct regcache *regcache;
4235
4236 if (!set_desired_thread (1))
4237 write_enn (own_buf);
4238 else
4239 {
4240 regcache = get_thread_regcache (current_thread, 1);
4241 registers_to_string (regcache, own_buf);
4242 }
4243 }
4244 break;
4245 case 'G':
4246 require_running (own_buf);
4247 if (current_traceframe >= 0)
4248 write_enn (own_buf);
4249 else
4250 {
4251 struct regcache *regcache;
4252
4253 if (!set_desired_thread (1))
4254 write_enn (own_buf);
4255 else
4256 {
4257 regcache = get_thread_regcache (current_thread, 1);
4258 registers_from_string (regcache, &own_buf[1]);
4259 write_ok (own_buf);
4260 }
4261 }
4262 break;
4263 case 'm':
4264 require_running (own_buf);
4265 decode_m_packet (&own_buf[1], &mem_addr, &len);
4266 res = gdb_read_memory (mem_addr, mem_buf, len);
4267 if (res < 0)
4268 write_enn (own_buf);
4269 else
4270 bin2hex (mem_buf, own_buf, res);
4271 break;
4272 case 'M':
4273 require_running (own_buf);
4274 decode_M_packet (&own_buf[1], &mem_addr, &len, &mem_buf);
4275 if (gdb_write_memory (mem_addr, mem_buf, len) == 0)
4276 write_ok (own_buf);
4277 else
4278 write_enn (own_buf);
4279 break;
4280 case 'X':
4281 require_running (own_buf);
4282 if (decode_X_packet (&own_buf[1], packet_len - 1,
4283 &mem_addr, &len, &mem_buf) < 0
4284 || gdb_write_memory (mem_addr, mem_buf, len) != 0)
4285 write_enn (own_buf);
4286 else
4287 write_ok (own_buf);
4288 break;
4289 case 'C':
4290 require_running (own_buf);
4291 hex2bin (own_buf + 1, &sig, 1);
4292 if (gdb_signal_to_host_p ((enum gdb_signal) sig))
4293 signal = gdb_signal_to_host ((enum gdb_signal) sig);
4294 else
4295 signal = 0;
4296 myresume (own_buf, 0, signal);
4297 break;
4298 case 'S':
4299 require_running (own_buf);
4300 hex2bin (own_buf + 1, &sig, 1);
4301 if (gdb_signal_to_host_p ((enum gdb_signal) sig))
4302 signal = gdb_signal_to_host ((enum gdb_signal) sig);
4303 else
4304 signal = 0;
4305 myresume (own_buf, 1, signal);
4306 break;
4307 case 'c':
4308 require_running (own_buf);
4309 signal = 0;
4310 myresume (own_buf, 0, signal);
4311 break;
4312 case 's':
4313 require_running (own_buf);
4314 signal = 0;
4315 myresume (own_buf, 1, signal);
4316 break;
4317 case 'Z': /* insert_ ... */
4318 /* Fallthrough. */
4319 case 'z': /* remove_ ... */
4320 {
4321 char *dataptr;
4322 ULONGEST addr;
4323 int kind;
4324 char type = own_buf[1];
4325 int res;
4326 const int insert = ch == 'Z';
4327 char *p = &own_buf[3];
4328
4329 p = unpack_varlen_hex (p, &addr);
4330 kind = strtol (p + 1, &dataptr, 16);
4331
4332 if (insert)
4333 {
4334 struct gdb_breakpoint *bp;
4335
4336 bp = set_gdb_breakpoint (type, addr, kind, &res);
4337 if (bp != NULL)
4338 {
4339 res = 0;
4340
4341 /* GDB may have sent us a list of *point parameters to
4342 be evaluated on the target's side. Read such list
4343 here. If we already have a list of parameters, GDB
4344 is telling us to drop that list and use this one
4345 instead. */
4346 clear_breakpoint_conditions_and_commands (bp);
4347 process_point_options (bp, &dataptr);
4348 }
4349 }
4350 else
4351 res = delete_gdb_breakpoint (type, addr, kind);
4352
4353 if (res == 0)
4354 write_ok (own_buf);
4355 else if (res == 1)
4356 /* Unsupported. */
4357 own_buf[0] = '\0';
4358 else
4359 write_enn (own_buf);
4360 break;
4361 }
4362 case 'k':
4363 response_needed = 0;
4364 if (!target_running ())
4365 /* The packet we received doesn't make sense - but we can't
4366 reply to it, either. */
4367 return 0;
4368
4369 fprintf (stderr, "Killing all inferiors\n");
4370 for_each_inferior (&all_processes, kill_inferior_callback);
4371
4372 /* When using the extended protocol, we wait with no program
4373 running. The traditional protocol will exit instead. */
4374 if (extended_protocol)
4375 {
4376 last_status.kind = TARGET_WAITKIND_EXITED;
4377 last_status.value.sig = GDB_SIGNAL_KILL;
4378 return 0;
4379 }
4380 else
4381 exit (0);
4382
4383 case 'T':
4384 {
4385 ptid_t gdb_id, thread_id;
4386
4387 require_running (own_buf);
4388
4389 gdb_id = read_ptid (&own_buf[1], NULL);
4390 thread_id = gdb_id_to_thread_id (gdb_id);
4391 if (ptid_equal (thread_id, null_ptid))
4392 {
4393 write_enn (own_buf);
4394 break;
4395 }
4396
4397 if (mythread_alive (thread_id))
4398 write_ok (own_buf);
4399 else
4400 write_enn (own_buf);
4401 }
4402 break;
4403 case 'R':
4404 response_needed = 0;
4405
4406 /* Restarting the inferior is only supported in the extended
4407 protocol. */
4408 if (extended_protocol)
4409 {
4410 if (target_running ())
4411 for_each_inferior (&all_processes,
4412 kill_inferior_callback);
4413 fprintf (stderr, "GDBserver restarting\n");
4414
4415 /* Wait till we are at 1st instruction in prog. */
4416 if (program_name != NULL)
4417 {
4418 create_inferior (program_name, program_args);
4419
4420 if (last_status.kind == TARGET_WAITKIND_STOPPED)
4421 {
4422 /* Stopped at the first instruction of the target
4423 process. */
4424 general_thread = last_ptid;
4425 }
4426 else
4427 {
4428 /* Something went wrong. */
4429 general_thread = null_ptid;
4430 }
4431 }
4432 else
4433 {
4434 last_status.kind = TARGET_WAITKIND_EXITED;
4435 last_status.value.sig = GDB_SIGNAL_KILL;
4436 }
4437 return 0;
4438 }
4439 else
4440 {
4441 /* It is a request we don't understand. Respond with an
4442 empty packet so that gdb knows that we don't support this
4443 request. */
4444 own_buf[0] = '\0';
4445 break;
4446 }
4447 case 'v':
4448 /* Extended (long) request. */
4449 handle_v_requests (own_buf, packet_len, &new_packet_len);
4450 break;
4451
4452 default:
4453 /* It is a request we don't understand. Respond with an empty
4454 packet so that gdb knows that we don't support this
4455 request. */
4456 own_buf[0] = '\0';
4457 break;
4458 }
4459
4460 if (new_packet_len != -1)
4461 putpkt_binary (own_buf, new_packet_len);
4462 else
4463 putpkt (own_buf);
4464
4465 response_needed = 0;
4466
4467 if (exit_requested)
4468 return -1;
4469
4470 return 0;
4471 }
4472
4473 /* Event-loop callback for serial events. */
4474
4475 int
4476 handle_serial_event (int err, gdb_client_data client_data)
4477 {
4478 if (debug_threads)
4479 debug_printf ("handling possible serial event\n");
4480
4481 /* Really handle it. */
4482 if (process_serial_event () < 0)
4483 return -1;
4484
4485 /* Be sure to not change the selected thread behind GDB's back.
4486 Important in the non-stop mode asynchronous protocol. */
4487 set_desired_thread (1);
4488
4489 return 0;
4490 }
4491
4492 /* Push a stop notification on the notification queue. */
4493
4494 static void
4495 push_stop_notification (ptid_t ptid, struct target_waitstatus *status)
4496 {
4497 struct vstop_notif *vstop_notif = XNEW (struct vstop_notif);
4498
4499 vstop_notif->status = *status;
4500 vstop_notif->ptid = ptid;
4501 /* Push Stop notification. */
4502 notif_push (&notif_stop, (struct notif_event *) vstop_notif);
4503 }
4504
4505 /* Event-loop callback for target events. */
4506
4507 int
4508 handle_target_event (int err, gdb_client_data client_data)
4509 {
4510 if (debug_threads)
4511 debug_printf ("handling possible target event\n");
4512
4513 last_ptid = mywait (minus_one_ptid, &last_status,
4514 TARGET_WNOHANG, 1);
4515
4516 if (last_status.kind == TARGET_WAITKIND_NO_RESUMED)
4517 {
4518 if (gdb_connected () && report_no_resumed)
4519 push_stop_notification (null_ptid, &last_status);
4520 }
4521 else if (last_status.kind != TARGET_WAITKIND_IGNORE)
4522 {
4523 int pid = ptid_get_pid (last_ptid);
4524 struct process_info *process = find_process_pid (pid);
4525 int forward_event = !gdb_connected () || process->gdb_detached;
4526
4527 if (last_status.kind == TARGET_WAITKIND_EXITED
4528 || last_status.kind == TARGET_WAITKIND_SIGNALLED)
4529 {
4530 mark_breakpoints_out (process);
4531 target_mourn_inferior (last_ptid);
4532 }
4533 else if (last_status.kind == TARGET_WAITKIND_THREAD_EXITED)
4534 ;
4535 else
4536 {
4537 /* We're reporting this thread as stopped. Update its
4538 "want-stopped" state to what the client wants, until it
4539 gets a new resume action. */
4540 current_thread->last_resume_kind = resume_stop;
4541 current_thread->last_status = last_status;
4542 }
4543
4544 if (forward_event)
4545 {
4546 if (!target_running ())
4547 {
4548 /* The last process exited. We're done. */
4549 exit (0);
4550 }
4551
4552 if (last_status.kind == TARGET_WAITKIND_EXITED
4553 || last_status.kind == TARGET_WAITKIND_SIGNALLED
4554 || last_status.kind == TARGET_WAITKIND_THREAD_EXITED)
4555 ;
4556 else
4557 {
4558 /* A thread stopped with a signal, but gdb isn't
4559 connected to handle it. Pass it down to the
4560 inferior, as if it wasn't being traced. */
4561 enum gdb_signal signal;
4562
4563 if (debug_threads)
4564 debug_printf ("GDB not connected; forwarding event %d for"
4565 " [%s]\n",
4566 (int) last_status.kind,
4567 target_pid_to_str (last_ptid));
4568
4569 if (last_status.kind == TARGET_WAITKIND_STOPPED)
4570 signal = last_status.value.sig;
4571 else
4572 signal = GDB_SIGNAL_0;
4573 target_continue (last_ptid, signal);
4574 }
4575 }
4576 else
4577 push_stop_notification (last_ptid, &last_status);
4578 }
4579
4580 /* Be sure to not change the selected thread behind GDB's back.
4581 Important in the non-stop mode asynchronous protocol. */
4582 set_desired_thread (1);
4583
4584 return 0;
4585 }
4586
4587 #if GDB_SELF_TEST
4588 namespace selftests
4589 {
4590
4591 void
4592 reset ()
4593 {}
4594
4595 } // namespace selftests
4596 #endif /* GDB_SELF_TEST */
This page took 0.124521 seconds and 4 git commands to generate.