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