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