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