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