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