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