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