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