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