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