• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Main code for remote server for GDB.
2    Copyright (C) 1989, 1993, 1994, 1995, 1997, 1998, 1999, 2000, 2002, 2003,
3    2004, 2005, 2006, 2011
4    Free Software Foundation, Inc.
5 
6    This file is part of GDB.
7    It has been modified to integrate it in valgrind
8 
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13 
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18 
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 51 Franklin Street, Fifth Floor,
22    Boston, MA 02110-1301, USA.  */
23 
24 #include "server.h"
25 #include "regdef.h"
26 #include "pub_core_options.h"
27 #include "pub_core_translate.h"
28 #include "pub_core_mallocfree.h"
29 #include "pub_core_initimg.h"
30 #include "pub_core_execontext.h"
31 #include "pub_core_syswrap.h"      // VG_(show_open_fds)
32 #include "pub_core_scheduler.h"
33 #include "pub_core_transtab.h"
34 #include "pub_core_debuginfo.h"
35 #include "pub_core_addrinfo.h"
36 #include "pub_core_aspacemgr.h"
37 
38 unsigned long cont_thread;
39 unsigned long general_thread;
40 unsigned long step_thread;
41 unsigned long thread_from_wait;
42 unsigned long old_thread_from_wait;
43 
44 int pass_signals[TARGET_SIGNAL_LAST]; /* indexed by gdb signal nr */
45 
46 /* for a gdbserver integrated in valgrind, resuming the process consists
47    in returning the control to valgrind.
48    The guess process resumes its execution.
49    Then at the next error or break or ..., valgrind calls gdbserver again.
50    A resume reply packet must then be built to inform GDB that the
51    resume request is finished.
52    resume_reply_packet_needed records the fact that the next call to gdbserver
53    must send a resume packet to gdb. */
54 static Bool resume_reply_packet_needed = False;
55 
56 VG_MINIMAL_JMP_BUF(toplevel);
57 
58 /* Decode a qXfer read request.  Return 0 if everything looks OK,
59    or -1 otherwise.  */
60 
61 static
decode_xfer_read(char * buf,const char ** annex,CORE_ADDR * ofs,unsigned int * len)62 int decode_xfer_read (char *buf, const char **annex, CORE_ADDR *ofs, unsigned int *len)
63 {
64    /* Extract and NUL-terminate the annex.  */
65    *annex = buf;
66    while (*buf && *buf != ':')
67       buf++;
68    if (*buf == '\0')
69       return -1;
70    *buf++ = 0;
71 
72    /* After the read/write marker and annex, qXfer looks like a
73       traditional 'm' packet.  */
74    decode_m_packet (buf, ofs, len);
75 
76    return 0;
77 }
78 
79 /* Write the response to a successful qXfer read.  Returns the
80    length of the (binary) data stored in BUF, corresponding
81    to as much of DATA/LEN as we could fit.  IS_MORE controls
82    the first character of the response.  */
83 static
write_qxfer_response(char * buf,unsigned char * data,int len,int is_more)84 int write_qxfer_response (char *buf, unsigned char *data, int len, int is_more)
85 {
86    int out_len;
87 
88    if (is_more)
89       buf[0] = 'm';
90    else
91       buf[0] = 'l';
92 
93    return remote_escape_output (data, len, (unsigned char *) buf + 1, &out_len,
94                                 PBUFSIZ - POVERHSIZ - 1) + 1;
95 }
96 
97 static Bool initial_valgrind_sink_saved = False;
98 /* True <=> valgrind log sink saved in initial_valgrind_sink */
99 static OutputSink initial_valgrind_sink;
100 
101 static Bool command_output_to_log = False;
102 /* True <=> command output goes to log instead of gdb */
103 
reset_valgrind_sink(const char * info)104 void reset_valgrind_sink(const char *info)
105 {
106    if (VG_(log_output_sink).fd != initial_valgrind_sink.fd
107        && initial_valgrind_sink_saved) {
108       VG_(log_output_sink).fd = initial_valgrind_sink.fd;
109       VG_(umsg) ("Reset valgrind output to log (%s)\n",
110                  (info = NULL ? "" : info));
111    }
112 }
113 
print_to_initial_valgrind_sink(const char * msg)114 void print_to_initial_valgrind_sink (const char *msg)
115 {
116    vg_assert (initial_valgrind_sink_saved);
117    VG_(write) (initial_valgrind_sink.fd, msg, strlen(msg));
118 }
119 
120 
121 static
kill_request(const char * msg)122 void kill_request (const char *msg)
123 {
124    VG_(umsg) ("%s", msg);
125    VG_(exit) (0);
126 }
127 
128 // s is a NULL terminated string made of O or more words (separated by spaces).
129 // Returns a pointer to the Nth word in s.
130 // If Nth word does not exist, return a pointer to the last (0) byte of s.
131 static
wordn(const char * s,int n)132 const char *wordn (const char *s, int n)
133 {
134    int word_seen = 0;
135    Bool searching_word = True;
136 
137    while (*s) {
138       if (*s == ' ')
139          searching_word = True;
140       else {
141          if (searching_word) {
142             searching_word = False;
143             word_seen++;
144             if (word_seen == n)
145                return s;
146          }
147       }
148       s++;
149    }
150    return s;
151 }
152 
VG_(print_all_stats)153 void VG_(print_all_stats) (Bool memory_stats, Bool tool_stats)
154 {
155    if (memory_stats) {
156       VG_(message)(Vg_DebugMsg, "\n");
157       VG_(message)(Vg_DebugMsg,
158          "------ Valgrind's internal memory use stats follow ------\n" );
159       VG_(sanity_check_malloc_all)();
160        VG_(message)
161           (Vg_DebugMsg,
162            "------ %'13llu bytes have already been mmap-ed ANONYMOUS.\n",
163            VG_(am_get_anonsize_total)());
164       VG_(print_all_arena_stats)();
165       if (VG_(clo_profile_heap))
166          VG_(print_arena_cc_analysis) ();
167       VG_(message)(Vg_DebugMsg, "\n");
168    }
169 
170    VG_(print_translation_stats)();
171    VG_(print_tt_tc_stats)();
172    VG_(print_scheduler_stats)();
173    VG_(print_ExeContext_stats)( False /* with_stacktraces */ );
174    VG_(print_errormgr_stats)();
175    if (tool_stats && VG_(needs).print_stats) {
176       VG_TDICT_CALL(tool_print_stats);
177    }
178 }
179 
180 /* handle_gdb_valgrind_command handles the provided mon string command.
181    If command is recognised, return 1 else return 0.
182    Note that in case of ambiguous command, 1 is returned.
183 
184    *sink_wanted_at_return is modified if one of the commands
185    'v.set *_output' is handled.
186 */
187 static
handle_gdb_valgrind_command(char * mon,OutputSink * sink_wanted_at_return)188 int handle_gdb_valgrind_command (char *mon, OutputSink *sink_wanted_at_return)
189 {
190    UWord ret = 0;
191    char s[strlen(mon)+1]; /* copy for strtok_r */
192    char *wcmd;
193    HChar *ssaveptr;
194    const char *endptr;
195    int   kwdid;
196    int int_value;
197 
198    vg_assert (initial_valgrind_sink_saved);
199 
200    strcpy (s, mon);
201    wcmd = strtok_r (s, " ", &ssaveptr);
202    /* NB: if possible, avoid introducing a new command below which
203       starts with the same 3 first letters as an already existing
204       command. This ensures a shorter abbreviation for the user. */
205    switch (VG_(keyword_id) ("help v.set v.info v.wait v.kill v.translate"
206                             " v.do",
207                             wcmd, kwd_report_duplicated_matches)) {
208    case -2:
209       ret = 1;
210       break;
211    case -1:
212       break;
213    case  0: /* help */
214       ret = 1;
215       wcmd = strtok_r (NULL, " ", &ssaveptr);
216       if (wcmd == NULL) {
217          int_value = 0;
218       } else {
219          switch (VG_(keyword_id) ("debug", wcmd, kwd_report_all)) {
220          case -2: int_value = 0; break;
221          case -1: int_value = 0; break;
222          case  0: int_value = 1; break;
223          default: vg_assert (0);
224          }
225       }
226 
227       VG_(gdb_printf) (
228 "general valgrind monitor commands:\n"
229 "  help [debug]            : monitor command help. With debug: + debugging commands\n"
230 "  v.wait [<ms>]           : sleep <ms> (default 0) then continue\n"
231 "  v.info all_errors       : show all errors found so far\n"
232 "  v.info last_error       : show last error found\n"
233 "  v.info location <addr>  : show information about location <addr>\n"
234 "  v.info n_errs_found [msg] : show the nr of errors found so far and the given msg\n"
235 "  v.info open_fds         : show open file descriptors (only if --track-fds=yes)\n"
236 "  v.kill                  : kill the Valgrind process\n"
237 "  v.set gdb_output        : set valgrind output to gdb\n"
238 "  v.set log_output        : set valgrind output to log\n"
239 "  v.set mixed_output      : set valgrind output to log, interactive output to gdb\n"
240 "  v.set merge-recursive-frames <num> : merge recursive calls in max <num> frames\n"
241 "  v.set vgdb-error <errornr> : debug me at error >= <errornr> \n");
242       if (int_value) { VG_(gdb_printf) (
243 "debugging valgrind internals monitor commands:\n"
244 "  v.do   expensive_sanity_check_general : do an expensive sanity check now\n"
245 "  v.info gdbserver_status : show gdbserver status\n"
246 "  v.info memory [aspacemgr] : show valgrind heap memory stats\n"
247 "     (with aspacemgr arg, also shows valgrind segments on log ouput)\n"
248 "  v.info exectxt          : show stacktraces and stats of all execontexts\n"
249 "  v.info scheduler        : show valgrind thread state and stacktrace\n"
250 "  v.info stats            : show various valgrind and tool stats\n"
251 "  v.set debuglog <level>  : set valgrind debug log level to <level>\n"
252 "  v.set hostvisibility [yes*|no] : (en/dis)ables access by gdb/gdbserver to\n"
253 "    Valgrind internal host status/memory\n"
254 "  v.translate <addr> [<traceflags>]  : debug translation of <addr> with <traceflags>\n"
255 "    (default traceflags 0b00100000 : show after instrumentation)\n"
256 "   An additional flag  0b100000000 allows to show gdbserver instrumentation\n");
257       }
258       break;
259    case  1: /* v.set */
260       ret = 1;
261       wcmd = strtok_r (NULL, " ", &ssaveptr);
262       switch (kwdid = VG_(keyword_id)
263               ("vgdb-error debuglog merge-recursive-frames"
264                " gdb_output log_output mixed_output hostvisibility",
265                wcmd, kwd_report_all)) {
266       case -2:
267       case -1:
268          break;
269       case 0: /* vgdb-error */
270       case 1: /* debuglog */
271       case 2: /* merge-recursive-frames */
272          wcmd = strtok_r (NULL, " ", &ssaveptr);
273          if (wcmd == NULL) {
274             int_value = 0;
275             endptr = "empty"; /* to report an error below */
276          } else {
277             HChar *the_end;
278             int_value = strtol (wcmd, &the_end, 10);
279             endptr = the_end;
280          }
281          if (*endptr != '\0') {
282             VG_(gdb_printf) ("missing or malformed integer value\n");
283          } else if (kwdid == 0) {
284             VG_(printf) ("vgdb-error value changed from %d to %d\n",
285                              VG_(dyn_vgdb_error), int_value);
286             VG_(dyn_vgdb_error) = int_value;
287          } else if (kwdid == 1) {
288             VG_(printf) ("debuglog value changed from %d to %d\n",
289                              VG_(debugLog_getLevel)(), int_value);
290             VG_(debugLog_startup) (int_value, "gdbsrv");
291          } else if (kwdid == 2) {
292             VG_(printf)
293                ("merge-recursive-frames value changed from %d to %d\n",
294                 VG_(clo_merge_recursive_frames), int_value);
295             VG_(clo_merge_recursive_frames) = int_value;
296          } else {
297             vg_assert (0);
298          }
299          break;
300       case 3: /* gdb_output */
301          (*sink_wanted_at_return).fd = -2;
302          command_output_to_log = False;
303          VG_(gdb_printf) ("valgrind output will go to gdb\n");
304          break;
305       case 4: /* log_output */
306          (*sink_wanted_at_return).fd = initial_valgrind_sink.fd;
307          command_output_to_log = True;
308          VG_(gdb_printf) ("valgrind output will go to log\n");
309          break;
310       case 5: /* mixed output */
311          (*sink_wanted_at_return).fd = initial_valgrind_sink.fd;
312          command_output_to_log = False;
313          VG_(gdb_printf)
314             ("valgrind output will go to log, "
315              "interactive output will go to gdb\n");
316          break;
317       case 6: /* hostvisibility */
318          wcmd = strtok_r (NULL, " ", &ssaveptr);
319          if (wcmd != NULL) {
320             switch (VG_(keyword_id) ("yes no", wcmd, kwd_report_all)) {
321             case -2:
322             case -1: break;
323             case  0:
324                hostvisibility = True;
325                break;
326             case 1:
327                hostvisibility = False;
328                break;
329             default: vg_assert (0);
330             }
331          } else {
332             hostvisibility = True;
333          }
334          if (hostvisibility) {
335             const DebugInfo *tooldi
336                = VG_(find_DebugInfo) ((Addr)handle_gdb_valgrind_command);
337             /* Normally, we should always find the tooldi. In case we
338                do not, suggest a 'likely somewhat working' address: */
339             const Addr tool_text_start
340                = tooldi ?
341                VG_(DebugInfo_get_text_avma) (tooldi) : 0x38000000;
342             const NSegment *toolseg
343                = tooldi ?
344                  VG_(am_find_nsegment) (VG_(DebugInfo_get_text_avma) (tooldi))
345                  : NULL;
346             VG_(gdb_printf)
347                ("Enabled access to Valgrind memory/status by GDB\n"
348                 "If not yet done, tell GDB which valgrind file(s) to use, "
349                 "typically:\n"
350                 "add-symbol-file %s %p\n",
351                 toolseg ? VG_(am_get_filename)(toolseg)
352                 : "<toolfile> <address> e.g.",
353                 (void*)tool_text_start);
354          } else
355             VG_(gdb_printf)
356                ("Disabled access to Valgrind memory/status by GDB\n");
357          break;
358       default:
359          vg_assert (0);
360       }
361       break;
362    case  2: /* v.info */ {
363       ret = 1;
364       wcmd = strtok_r (NULL, " ", &ssaveptr);
365       switch (kwdid = VG_(keyword_id)
366               ("all_errors n_errs_found last_error gdbserver_status memory"
367                " scheduler stats open_fds exectxt location",
368                wcmd, kwd_report_all)) {
369       case -2:
370       case -1:
371          break;
372       case 0: // all_errors
373          // A verbosity of minimum 2 is needed to show the errors.
374          VG_(show_all_errors)(/* verbosity */ 2, /* xml */ False);
375          break;
376       case  1: // n_errs_found
377          VG_(printf) ("n_errs_found %d n_errs_shown %d (vgdb-error %d) %s\n",
378                       VG_(get_n_errs_found) (),
379                       VG_(get_n_errs_shown) (),
380                       VG_(dyn_vgdb_error),
381                       wordn (mon, 3));
382          break;
383       case 2: // last_error
384          VG_(show_last_error)();
385          break;
386       case  3: // gdbserver_status
387          VG_(gdbserver_status_output)();
388          break;
389       case  4: /* memory */
390          VG_(printf) ("%'13llu bytes have already been mmap-ed ANONYMOUS.\n",
391                       VG_(am_get_anonsize_total)());
392          VG_(print_all_arena_stats) ();
393          if (VG_(clo_profile_heap))
394             VG_(print_arena_cc_analysis) ();
395          wcmd = strtok_r (NULL, " ", &ssaveptr);
396          if (wcmd != NULL) {
397             switch (VG_(keyword_id) ("aspacemgr", wcmd, kwd_report_all)) {
398             case -2:
399             case -1: break;
400             case  0:
401                VG_(am_show_nsegments) (0, "gdbserver v.info memory aspacemgr");
402                break;
403             default: vg_assert (0);
404             }
405          }
406 
407          ret = 1;
408          break;
409       case  5: /* scheduler */
410          VG_(show_sched_status) (True,  // host_stacktrace
411                                  True,  // stack_usage
412                                  True); // exited_threads
413          ret = 1;
414          break;
415       case  6: /* stats */
416          VG_(print_all_stats)(False, /* Memory stats */
417                               True   /* Tool stats */);
418          ret = 1;
419          break;
420       case  7: /* open_fds */
421          if (VG_(clo_track_fds))
422             VG_(show_open_fds) ("");
423          else
424             VG_(gdb_printf)
425                ("Valgrind must be started with --track-fds=yes"
426                 " to show open fds\n");
427          ret = 1;
428          break;
429       case  8: /* exectxt */
430          VG_(print_ExeContext_stats) (True /* with_stacktraces */);
431          ret = 1;
432          break;
433       case  9: { /* location */
434          /* Note: we prefer 'v.info location' and not 'v.info address' as
435             v.info address is inconsistent with the GDB (native)
436             command 'info address' which gives the address for a symbol.
437             GDB equivalent command of 'v.info location' is 'info symbol'. */
438          Addr address;
439          SizeT dummy_sz = 0x1234;
440          if (VG_(strtok_get_address_and_size) (&address,
441                                                &dummy_sz, &ssaveptr)) {
442             // If tool provides location information, use that.
443             if (VG_(needs).info_location) {
444                VG_TDICT_CALL(tool_info_location, address);
445             }
446             // If tool does not provide location info, use the common one.
447             // Also use the common to compare with tool when debug log is set.
448             if (!VG_(needs).info_location || VG_(debugLog_getLevel)() > 0 ) {
449                AddrInfo ai;
450                ai.tag = Addr_Undescribed;
451                VG_(describe_addr) (address, &ai);
452                VG_(pp_addrinfo) (address, &ai);
453                VG_(clear_addrinfo) (&ai);
454             }
455          }
456          ret = 1;
457          break;
458       }
459       default:
460          vg_assert(0);
461       }
462       break;
463    }
464    case  3: /* v.wait */
465       wcmd = strtok_r (NULL, " ", &ssaveptr);
466       if (wcmd != NULL) {
467          int_value = strtol (wcmd, NULL, 10);
468          VG_(printf) ("gdbserver: continuing in %d ms ...\n", int_value);
469          VG_(poll)(NULL, 0, int_value);
470       }
471       VG_(printf) ("gdbserver: continuing after wait ...\n");
472       ret = 1;
473       break;
474    case  4: /* v.kill */
475       kill_request ("monitor command request to kill this process\n");
476       break;
477    case  5: { /* v.translate */
478       Addr address;
479       SizeT verbosity = 0x20;
480 
481       ret = 1;
482 
483       if (VG_(strtok_get_address_and_size) (&address, &verbosity, &ssaveptr)) {
484          /* we need to force the output to log for the translation trace,
485             as low level VEX tracing cannot be redirected to gdb. */
486          int saved_command_output_to_log = command_output_to_log;
487          int saved_fd = VG_(log_output_sink).fd;
488          Bool single_stepping_on_entry = valgrind_single_stepping();
489          int vex_verbosity = verbosity & 0xff;
490          VG_(log_output_sink).fd = initial_valgrind_sink.fd;
491          if ((verbosity & 0x100) && !single_stepping_on_entry) {
492             valgrind_set_single_stepping(True);
493             // to force gdbserver instrumentation.
494          }
495 #        if defined(VGA_arm)
496          // on arm, we need to (potentially) convert this address
497          // to the thumb form.
498          address = thumb_pc (address);
499 #        endif
500 
501          VG_(translate) ( 0 /* dummy ThreadId; irrelevant due to debugging*/,
502                           address,
503                           /*debugging*/True,
504                           (Int) vex_verbosity,
505                           /*bbs_done*/0,
506                           /*allow redir?*/True);
507          if ((verbosity & 0x100) && !single_stepping_on_entry) {
508             valgrind_set_single_stepping(False);
509             // reset single stepping.
510          }
511          command_output_to_log = saved_command_output_to_log;
512          VG_(log_output_sink).fd = saved_fd;
513       }
514       break;
515    }
516 
517    case  6: /* v.do */
518       ret = 1;
519       wcmd = strtok_r (NULL, " ", &ssaveptr);
520       switch (VG_(keyword_id) ("expensive_sanity_check_general",
521                                wcmd, kwd_report_all)) {
522          case -2:
523          case -1: break;
524          case  0: { /* expensive_sanity_check_general */
525             // Temporarily bump up sanity level to check e.g. the malloc arenas.
526             const Int save_clo_sanity_level = VG_(clo_sanity_level);
527             if (VG_(clo_sanity_level) < 4) VG_(clo_sanity_level) = 4;
528             VG_(sanity_check_general) (/* force_expensive */ True);
529             VG_(clo_sanity_level) = save_clo_sanity_level;
530             break;
531          }
532          default: vg_assert (0);
533       }
534       break;
535 
536    default:
537       vg_assert (0);
538    }
539    return ret;
540 }
541 
542 /* handle_gdb_monitor_command handles the provided mon string command,
543    which can be either a "standard" valgrind monitor command
544    or a tool specific monitor command.
545    If command recognised, return 1 else return 0.
546    Note that in case of ambiguous command, 1 is returned.
547 */
548 static
handle_gdb_monitor_command(char * mon)549 int handle_gdb_monitor_command (char *mon)
550 {
551    UWord ret = 0;
552    UWord tool_ret = 0;
553    // initially, we assume that when returning, the desired sink is the
554    // one we have when entering. It can however be changed by the standard
555    // valgrind command handling.
556    OutputSink sink_wanted_at_return = VG_(log_output_sink);
557    // When using gdbserver, we temporarily disable xml output.
558    Bool save_clo_xml = VG_(clo_xml);
559    VG_(clo_xml) = False;
560 
561    if (!initial_valgrind_sink_saved) {
562       /* first time we enter here, we save the valgrind default log sink */
563       initial_valgrind_sink = sink_wanted_at_return;
564       initial_valgrind_sink_saved = True;
565    }
566 
567    if (!command_output_to_log)
568       VG_(log_output_sink).fd = -2; /* redirect to monitor_output */
569 
570    ret = handle_gdb_valgrind_command (mon, &sink_wanted_at_return);
571 
572    /* Even if command was recognised by valgrind core, we call the
573       tool command handler : this is needed to handle help command
574       and/or to let the tool do some additional processing of a
575       valgrind standard command. Note however that if valgrind
576       recognised the command, we will always return success. */
577    if (VG_(needs).client_requests) {
578       /* If the tool reports an error when handling a monitor command,
579          we need to avoid calling gdbserver during this command
580          handling. So, we temporarily set VG_(dyn_vgdb_error) to
581          a huge value to ensure m_errormgr.c does not call gdbserver. */
582       Int save_dyn_vgdb_error = VG_(dyn_vgdb_error);
583       UWord arg[2];
584       VG_(dyn_vgdb_error) = 999999999;
585       arg[0] = (UWord) VG_USERREQ__GDB_MONITOR_COMMAND;
586       arg[1] = (UWord) mon;
587       VG_TDICT_CALL(tool_handle_client_request, VG_(running_tid), arg,
588                     &tool_ret);
589       VG_(dyn_vgdb_error) = save_dyn_vgdb_error;
590    }
591 
592    VG_(message_flush) ();
593 
594    /* restore or set the desired output */
595    VG_(log_output_sink).fd = sink_wanted_at_return.fd;
596    VG_(clo_xml) = save_clo_xml;
597 
598    if (ret | tool_ret)
599       return 1;
600    else
601       return 0;
602 }
603 
604 
605 /* Handle all of the extended 'Q' packets.  */
606 static
handle_set(char * arg_own_buf,int * new_packet_len_p)607 void handle_set (char *arg_own_buf, int *new_packet_len_p)
608 {
609    if (strcmp ("QStartNoAckMode", arg_own_buf) == 0) {
610       noack_mode = True;
611       write_ok (arg_own_buf);
612       return;
613    }
614 
615    if (strncmp ("QPassSignals:", arg_own_buf, 13) == 0) {
616       int i;
617       char *from, *to;
618       char *end = arg_own_buf + strlen(arg_own_buf);
619       CORE_ADDR sig;
620       for (i = 0; i < TARGET_SIGNAL_LAST; i++)
621          pass_signals[i] = 0;
622 
623       from = arg_own_buf + 13;
624       while (from < end) {
625          to = strchr(from, ';');
626          if (to == NULL) to = end;
627          decode_address (&sig, from, to - from);
628          pass_signals[(int)sig] = 1;
629          dlog(3, "pass_signal gdb_nr %d %s\n",
630               (int)sig, target_signal_to_name(sig));
631          from = to;
632          if (*from == ';') from++;
633       }
634       write_ok (arg_own_buf);
635       return;
636    }
637    /* Otherwise we didn't know what packet it was.  Say we didn't
638       understand it.  */
639    arg_own_buf[0] = 0;
640 }
641 
VG_(client_monitor_command)642 Bool VG_(client_monitor_command) (HChar *cmd)
643 {
644    const Bool connected = remote_connected();
645    const int saved_command_output_to_log = command_output_to_log;
646    Bool handled;
647 
648    if (!connected)
649       command_output_to_log = True;
650    handled = handle_gdb_monitor_command (cmd);
651    if (!connected) {
652       // reset the log output unless cmd changed it.
653       if (command_output_to_log)
654          command_output_to_log = saved_command_output_to_log;
655    }
656    if (handled)
657       return False; // recognised
658    else
659       return True; // not recognised
660 }
661 
662 /* Handle all of the extended 'q' packets.  */
663 static
handle_query(char * arg_own_buf,int * new_packet_len_p)664 void handle_query (char *arg_own_buf, int *new_packet_len_p)
665 {
666    static struct inferior_list_entry *thread_ptr;
667 
668    /* thread local storage query */
669    if (strncmp ("qGetTLSAddr:", arg_own_buf, 12) == 0) {
670       char *from, *to;
671       char *end = arg_own_buf + strlen(arg_own_buf);
672       unsigned long gdb_id;
673       CORE_ADDR lm;
674       CORE_ADDR offset;
675       struct thread_info *ti;
676 
677       from = arg_own_buf + 12;
678       to = strchr(from, ',');
679       *to = 0;
680       gdb_id = strtoul (from, NULL, 16);
681       from = to + 1;
682       to = strchr(from, ',');
683       decode_address (&offset, from, to - from);
684       from = to + 1;
685       to = end;
686       decode_address (&lm, from, to - from);
687       dlog(2, "qGetTLSAddr thread %lu offset %p lm %p\n",
688            gdb_id, (void*)offset, (void*)lm);
689 
690       ti = gdb_id_to_thread (gdb_id);
691       if (ti != NULL) {
692          ThreadState *tst;
693          Addr tls_addr;
694 
695          tst = (ThreadState *) inferior_target_data (ti);
696          if (valgrind_get_tls_addr(tst, offset, lm, &tls_addr)) {
697             VG_(sprintf) (arg_own_buf, "%lx", tls_addr);
698             return;
699          }
700          // else we will report we do not support qGetTLSAddr
701       } else {
702          write_enn (arg_own_buf);
703          return;
704       }
705    }
706 
707    /* qRcmd, monitor command handling.  */
708    if (strncmp ("qRcmd,", arg_own_buf, 6) == 0) {
709       char *p = arg_own_buf + 6;
710       int cmdlen = strlen(p)/2;
711       char cmd[cmdlen+1];
712 
713       if (unhexify (cmd, p, cmdlen) != cmdlen) {
714          write_enn (arg_own_buf);
715          return;
716       }
717       cmd[cmdlen] = '\0';
718 
719       if (handle_gdb_monitor_command (cmd)) {
720          write_ok (arg_own_buf);
721          return;
722       } else {
723          /* cmd not recognised */
724          VG_(gdb_printf)
725             ("command '%s' not recognised\n"
726              "In gdb,     try 'monitor help'\n"
727              "In a shell, try 'vgdb help'\n",
728              cmd);
729          write_ok (arg_own_buf);
730          return;
731       }
732    }
733 
734    /* provide some valgrind specific info in return to qThreadExtraInfo. */
735    if (strncmp ("qThreadExtraInfo,", arg_own_buf, 17) == 0) {
736       unsigned long gdb_id;
737       struct thread_info *ti;
738       ThreadState *tst;
739 
740       gdb_id = strtoul (&arg_own_buf[17], NULL, 16);
741       ti = gdb_id_to_thread (gdb_id);
742       if (ti != NULL) {
743          tst = (ThreadState *) inferior_target_data (ti);
744          /* Additional info is the tid, the thread status and the thread's
745             name, if any. */
746          SizeT len = strlen(VG_(name_of_ThreadStatus)(tst->status)) + 20;
747          if (tst->thread_name) len += strlen(tst->thread_name);
748          /* As the string will be hexified and copied into own_buf we need
749             to limit the length to avoid buffer overflow. */
750          if (len * 2 > (PBUFSIZ + POVERHSIZ))
751             len = (PBUFSIZ + POVERHSIZ) / 2;
752          char status[len];
753          if (tst->thread_name) {
754             VG_(snprintf) (status, sizeof(status), "tid %d %s %s",
755                            tst->tid,
756                            VG_(name_of_ThreadStatus)(tst->status),
757                            tst->thread_name);
758          } else {
759             VG_(snprintf) (status, sizeof(status), "tid %d %s",
760                            tst->tid,
761                            VG_(name_of_ThreadStatus)(tst->status));
762          }
763          hexify (arg_own_buf, status, strlen(status));
764          return;
765       } else {
766          write_enn (arg_own_buf);
767          return;
768       }
769    }
770 
771    if (strcmp ("qAttached", arg_own_buf) == 0) {
772       /* tell gdb to always detach, never kill the process */
773       arg_own_buf[0] = '1';
774       arg_own_buf[1] = 0;
775       return;
776    }
777 
778    if (strcmp ("qSymbol::", arg_own_buf) == 0) {
779       /* We have no symbol to read. */
780       write_ok (arg_own_buf);
781       return;
782    }
783 
784    if (strcmp ("qfThreadInfo", arg_own_buf) == 0) {
785       thread_ptr = all_threads.head;
786       VG_(sprintf) (arg_own_buf, "m%x",
787                     thread_to_gdb_id ((struct thread_info *)thread_ptr));
788       thread_ptr = thread_ptr->next;
789       return;
790    }
791 
792    if (strcmp ("qsThreadInfo", arg_own_buf) == 0) {
793       if (thread_ptr != NULL) {
794          VG_(sprintf) (arg_own_buf, "m%x",
795                        thread_to_gdb_id ((struct thread_info *)thread_ptr));
796          thread_ptr = thread_ptr->next;
797          return;
798       } else {
799          VG_(sprintf) (arg_own_buf, "l");
800          return;
801       }
802    }
803 
804    if (valgrind_target_xml(VG_(clo_vgdb_shadow_registers)) != NULL
805         && strncmp ("qXfer:features:read:", arg_own_buf, 20) == 0) {
806       CORE_ADDR ofs;
807       unsigned int len, doc_len;
808       const char *annex = NULL;
809       // First, the annex is extracted from the packet received.
810       // Then, it is replaced by the corresponding file name.
811       int fd;
812 
813       /* Grab the annex, offset, and length.  */
814       if (decode_xfer_read (arg_own_buf + 20, &annex, &ofs, &len) < 0) {
815          strcpy (arg_own_buf, "E00");
816          return;
817       }
818 
819       if (strcmp (annex, "target.xml") == 0) {
820          annex = valgrind_target_xml(VG_(clo_vgdb_shadow_registers));
821          if (annex != NULL && VG_(clo_vgdb_shadow_registers)) {
822             /* Ensure the shadow registers are initialized. */
823             initialize_shadow_low(True);
824          }
825          if (annex == NULL) {
826             strcpy (arg_own_buf, "E00");
827             return;
828          }
829       }
830 
831       {
832          char doc[VG_(strlen)(VG_(libdir)) + 1 + VG_(strlen)(annex) + 1];
833          struct vg_stat stat_doc;
834          char toread[len];
835          int len_read;
836 
837          VG_(sprintf)(doc, "%s/%s", VG_(libdir), annex);
838          fd = VG_(fd_open) (doc, VKI_O_RDONLY, 0);
839          if (fd == -1) {
840             strcpy (arg_own_buf, "E00");
841             return;
842          }
843          if (VG_(fstat) (fd, &stat_doc) != 0) {
844             VG_(close) (fd);
845             strcpy (arg_own_buf, "E00");
846             return;
847          }
848          doc_len = stat_doc.size;
849 
850          if (len > PBUFSIZ - POVERHSIZ)
851             len = PBUFSIZ - POVERHSIZ;
852 
853          if (ofs > doc_len) {
854             write_enn (arg_own_buf);
855             VG_(close) (fd);
856             return;
857          }
858          VG_(lseek) (fd, ofs, VKI_SEEK_SET);
859          len_read = VG_(read) (fd, toread, len);
860          *new_packet_len_p = write_qxfer_response (arg_own_buf,
861                                                    (unsigned char *)toread,
862                                                    len_read,
863                                                    ofs + len_read < doc_len);
864          VG_(close) (fd);
865          return;
866       }
867    }
868 
869    if (strncmp ("qXfer:auxv:read:", arg_own_buf, 16) == 0) {
870       unsigned char *data;
871       int n;
872       CORE_ADDR ofs;
873       unsigned int len;
874       const char *annex;
875 
876       /* Reject any annex; grab the offset and length.  */
877       if (decode_xfer_read (arg_own_buf + 16, &annex, &ofs, &len) < 0
878           || annex[0] != '\0') {
879          strcpy (arg_own_buf, "E00");
880          return;
881       }
882 
883       if (len > PBUFSIZ - POVERHSIZ)
884          len = PBUFSIZ - POVERHSIZ;
885       data = malloc (len);
886 
887       {
888          UWord *client_auxv = VG_(client_auxv);
889          unsigned int client_auxv_len = 0;
890          while (*client_auxv != 0) {
891             dlog(4, "auxv %lld %llx\n",
892                  (ULong)*client_auxv,
893                  (ULong)*(client_auxv+1));
894             client_auxv++;
895             client_auxv++;
896             client_auxv_len += 2 * sizeof(UWord);
897          }
898          client_auxv_len += 2 * sizeof(UWord);
899          dlog(4, "auxv len %d\n", client_auxv_len);
900 
901          if (ofs >= client_auxv_len)
902             n = -1;
903          else {
904             n = client_auxv_len - ofs;
905             VG_(memcpy) (data, (unsigned char *) VG_(client_auxv), n);
906          }
907       }
908 
909       if (n < 0)
910          write_enn (arg_own_buf);
911       else if (n > len)
912          *new_packet_len_p = write_qxfer_response (arg_own_buf, data, len, 1);
913       else
914          *new_packet_len_p = write_qxfer_response (arg_own_buf, data, n, 0);
915 
916       free (data);
917 
918       return;
919    }
920 
921    if (strncmp ("qXfer:exec-file:read:", arg_own_buf, 21) == 0) {
922       unsigned char *data;
923       int n;
924       CORE_ADDR ofs;
925       unsigned int len;
926       const char *annex;
927       unsigned long pid;
928       const HChar *name;
929 
930       /* grab the annex, offset and length.  */
931       if (decode_xfer_read (arg_own_buf + 21, &annex, &ofs, &len) < 0) {
932          strcpy (arg_own_buf, "E00");
933          return;
934       }
935 
936       /* Reject any annex with invalid/unexpected pid */
937       if (strlen(annex) > 0)
938          pid = strtoul (annex, NULL, 16);
939       else
940          pid = 0;
941       if ((int)pid != VG_(getpid)() && pid != 0) {
942          VG_(sprintf) (arg_own_buf,
943                        "E.Valgrind gdbserver pid is %d."
944                        " Cannot give info for pid %d",
945                        VG_(getpid)(), (int) pid);
946          return;
947       }
948 
949       if (len > PBUFSIZ - 2)
950          len = PBUFSIZ - 2;
951       data = malloc (len);
952 
953       if (!VG_(resolve_filename)(VG_(cl_exec_fd), &name)) {
954          VG_(sprintf) (arg_own_buf,
955                        "E.Valgrind gdbserver could not"
956                        " resolve pid %d exec filename.",
957                        VG_(getpid)());
958          return;
959       }
960 
961       if (ofs >= strlen(name))
962          n = -1;
963       else {
964          n = strlen(name) - ofs;
965          VG_(memcpy) (data, name, n);
966       }
967 
968       if (n < 0)
969          write_enn (arg_own_buf);
970       else if (n > len)
971          *new_packet_len_p = write_qxfer_response (arg_own_buf, data, len, 1);
972       else
973          *new_packet_len_p = write_qxfer_response (arg_own_buf, data, n, 0);
974 
975       free (data);
976 
977       return;
978    }
979 
980    if (strncmp ("qXfer:siginfo:read:", arg_own_buf, 19) == 0) {
981       vki_siginfo_t info;
982       int n;
983       CORE_ADDR ofs;
984       unsigned int len;
985       const char *annex;
986 
987       /* Reject any annex; grab the offset and length.  */
988       if (decode_xfer_read (arg_own_buf + 19, &annex, &ofs, &len) < 0
989           || annex[0] != '\0') {
990          strcpy (arg_own_buf, "E00");
991          return;
992       }
993 
994       if (len > PBUFSIZ - POVERHSIZ)
995          len = PBUFSIZ - POVERHSIZ;
996 
997       gdbserver_pending_signal_to_report(&info);
998 
999       if (ofs >= sizeof(info))
1000          n = -1;
1001       else
1002          n = sizeof(info) - ofs;
1003 
1004       if (n < 0)
1005          write_enn (arg_own_buf);
1006       else if (n > len)
1007          *new_packet_len_p = write_qxfer_response (arg_own_buf,
1008                                                    (unsigned char *)&info,
1009                                                    len, 1);
1010       else
1011          *new_packet_len_p = write_qxfer_response (arg_own_buf,
1012                                                    (unsigned char *)&info,
1013                                                    n, 0);
1014 
1015       return;
1016    }
1017 
1018    /* Protocol features query.  */
1019    if (strncmp ("qSupported", arg_own_buf, 10) == 0
1020        && (arg_own_buf[10] == ':' || arg_own_buf[10] == '\0')) {
1021       VG_(sprintf) (arg_own_buf, "PacketSize=%x", PBUFSIZ - 1);
1022       /* Note: max packet size including frame and checksum, but without
1023          trailing null byte, which is not sent/received. */
1024 
1025       strcat (arg_own_buf, ";QStartNoAckMode+");
1026       strcat (arg_own_buf, ";QPassSignals+");
1027       if (VG_(client_auxv))
1028          strcat (arg_own_buf, ";qXfer:auxv:read+");
1029 
1030       if (valgrind_target_xml(VG_(clo_vgdb_shadow_registers)) != NULL) {
1031          strcat (arg_own_buf, ";qXfer:features:read+");
1032          /* if a new gdb connects to us, we have to reset the register
1033             set to the normal register sets to allow this new gdb to
1034             decide to use or not the shadow registers.
1035 
1036             Note that the reset is only done for gdb that are sending
1037             qSupported packets. If a user first connected with a recent
1038             gdb using shadow registers and then with a very old gdb
1039             that does not use qSupported packet, then the old gdb will
1040             not properly connect. */
1041          initialize_shadow_low(False);
1042       }
1043       strcat (arg_own_buf, ";qXfer:exec-file:read+");
1044       strcat (arg_own_buf, ";qXfer:siginfo:read+");
1045       return;
1046    }
1047 
1048    /* Otherwise we didn't know what packet it was.  Say we didn't
1049       understand it.  */
1050    arg_own_buf[0] = 0;
1051 }
1052 
1053 /* Handle all of the extended 'v' packets.  */
1054 static
handle_v_requests(char * arg_own_buf,char * status,int * zignal)1055 void handle_v_requests (char *arg_own_buf, char *status, int *zignal)
1056 {
1057    /* vcont packet code from gdb 6.6 removed */
1058 
1059    /* Otherwise we didn't know what packet it was.  Say we didn't
1060       understand it.  */
1061    arg_own_buf[0] = 0;
1062    return;
1063 }
1064 
1065 static
myresume(int step,int sig)1066 void myresume (int step, int sig)
1067 {
1068    struct thread_resume resume_info[2];
1069    int n = 0;
1070 
1071    if (step || sig) {
1072       resume_info[0].step = step;
1073       resume_info[0].sig = sig;
1074       n++;
1075    }
1076    resume_info[n].step = 0;
1077    resume_info[n].sig = 0;
1078 
1079    resume_reply_packet_needed = True;
1080    valgrind_resume (resume_info);
1081 }
1082 
1083 /* server_main global variables */
1084 static char *own_buf;
1085 static unsigned char *mem_buf;
1086 
gdbserver_init(void)1087 void gdbserver_init (void)
1088 {
1089    dlog(1, "gdbserver_init gdbserver embedded in valgrind: %s\n", version);
1090    noack_mode = False;
1091    valgrind_initialize_target ();
1092    // After a fork, gdbserver_init can be called again.
1093    // We do not have to re-malloc the buffers in such a case.
1094    if (own_buf == NULL)
1095       own_buf = malloc (PBUFSIZ+POVERHSIZ);
1096    if (mem_buf == NULL)
1097       mem_buf = malloc (PBUFSIZ+POVERHSIZ);
1098    // Note: normally, we should only malloc PBUFSIZ. However,
1099    // GDB has a bug, and in some cases, sends e.g. 'm' packets
1100    // asking for slightly more than the PacketSize given at
1101    // connection initialisation. So, we bypass the GDB bug
1102    // by allocating slightly more.
1103 }
1104 
gdbserver_terminate(void)1105 void gdbserver_terminate (void)
1106 {
1107    /* last call to gdbserver is cleanup call */
1108    if (VG_MINIMAL_SETJMP(toplevel)) {
1109       dlog(0, "error caused VG_MINIMAL_LONGJMP to gdbserver_terminate\n");
1110       return;
1111    }
1112    remote_close();
1113 }
1114 
server_main(void)1115 void server_main (void)
1116 {
1117    static char status;
1118    static int zignal;
1119 
1120    char ch;
1121    int i = 0;
1122    unsigned int len;
1123    CORE_ADDR mem_addr;
1124 
1125    zignal = valgrind_wait (&status);
1126    if (VG_MINIMAL_SETJMP(toplevel)) {
1127       dlog(0, "error caused VG_MINIMAL_LONGJMP to server_main\n");
1128    }
1129    while (1) {
1130       unsigned char sig;
1131       int packet_len;
1132       int new_packet_len = -1;
1133 
1134       if (resume_reply_packet_needed) {
1135          /* Send the resume reply to reply to last GDB resume
1136             request. */
1137          resume_reply_packet_needed = False;
1138          prepare_resume_reply (own_buf, status, zignal);
1139          putpkt (own_buf);
1140       }
1141 
1142       /* If our status is terminal (exit or fatal signal) get out
1143          as quickly as we can. We won't be able to handle any request
1144          anymore.  */
1145       if (status == 'W' || status == 'X') {
1146          return;
1147       }
1148 
1149       packet_len = getpkt (own_buf);
1150       if (packet_len <= 0)
1151          break;
1152 
1153       i = 0;
1154       ch = own_buf[i++];
1155       switch (ch) {
1156       case 'Q':
1157          handle_set (own_buf, &new_packet_len);
1158          break;
1159       case 'q':
1160          handle_query (own_buf, &new_packet_len);
1161          break;
1162       case 'd':
1163          /* set/unset debugging is done through valgrind debug level. */
1164          own_buf[0] = '\0';
1165          break;
1166       case 'D':
1167          reset_valgrind_sink("gdb detaching from process");
1168 
1169          /* When detaching or kill the process, gdb expects to get
1170             an packet OK back.  Any other output will make gdb
1171             believes detach did not work. */
1172          write_ok (own_buf);
1173          putpkt (own_buf);
1174          remote_finish (reset_after_error);
1175          remote_open (VG_(clo_vgdb_prefix));
1176          myresume (0, 0);
1177          resume_reply_packet_needed = False;
1178          return;
1179       case '!':
1180          /* We can not use the extended protocol with valgrind,
1181             because we can not restart the running
1182             program.  So return unrecognized.  */
1183          own_buf[0] = '\0';
1184          break;
1185       case '?':
1186          prepare_resume_reply (own_buf, status, zignal);
1187          break;
1188       case 'H':
1189          if (own_buf[1] == 'c' || own_buf[1] == 'g' || own_buf[1] == 's') {
1190             unsigned long gdb_id, thread_id;
1191 
1192             gdb_id = strtoul (&own_buf[2], NULL, 16);
1193             thread_id = gdb_id_to_thread_id (gdb_id);
1194             if (thread_id == 0) {
1195                write_enn (own_buf);
1196                break;
1197             }
1198 
1199             if (own_buf[1] == 'g') {
1200                general_thread = thread_id;
1201                set_desired_inferior (1);
1202             } else if (own_buf[1] == 'c') {
1203                cont_thread = thread_id;
1204             } else if (own_buf[1] == 's') {
1205                step_thread = thread_id;
1206             }
1207 
1208             write_ok (own_buf);
1209          } else {
1210             /* Silently ignore it so that gdb can extend the protocol
1211                without compatibility headaches.  */
1212             own_buf[0] = '\0';
1213          }
1214          break;
1215       case 'g':
1216          set_desired_inferior (1);
1217          registers_to_string (own_buf);
1218          break;
1219       case 'G':
1220          set_desired_inferior (1);
1221          registers_from_string (&own_buf[1]);
1222          write_ok (own_buf);
1223          break;
1224       case 'P': {
1225          int regno;
1226          char *regbytes;
1227          Bool mod;
1228          ThreadState *tst;
1229          regno = strtol(&own_buf[1], NULL, 16);
1230          regbytes = strchr(&own_buf[0], '=') + 1;
1231          set_desired_inferior (1);
1232          tst = (ThreadState *) inferior_target_data (current_inferior);
1233          /* Only accept changing registers in "runnable state3.
1234             In fact, it would be ok to change most of the registers
1235             except a few "sensitive" registers such as the PC, SP, BP.
1236             We assume we do not need to very specific here, and that we
1237             can just refuse all of these. */
1238          if (tst->status == VgTs_Runnable || tst->status == VgTs_Yielding) {
1239             supply_register_from_string (regno, regbytes, &mod);
1240             write_ok (own_buf);
1241          } else {
1242             /* at least from gdb 6.6 onwards, an E. error
1243                reply is shown to the user. So, we do an error
1244                msg which both is accepted by gdb as an error msg
1245                and is readable by the user. */
1246             VG_(sprintf)
1247                (own_buf,
1248 "E.\n"
1249 "ERROR changing register %s regno %d\n"
1250 "gdb commands changing registers (pc, sp, ...) (e.g. 'jump',\n"
1251 "set pc, calling from gdb a function in the debugged process, ...)\n"
1252 "can only be accepted if the thread is VgTs_Runnable or VgTs_Yielding state\n"
1253 "Thread status is %s\n",
1254                 find_register_by_number (regno)->name, regno,
1255                 VG_(name_of_ThreadStatus)(tst->status));
1256             if (VG_(clo_verbosity) > 1)
1257                VG_(umsg) ("%s\n", own_buf);
1258          }
1259          break;
1260       }
1261       case 'm':
1262          decode_m_packet (&own_buf[1], &mem_addr, &len);
1263          if (valgrind_read_memory (mem_addr, mem_buf, len) == 0)
1264             convert_int_to_ascii (mem_buf, own_buf, len);
1265          else
1266             write_enn (own_buf);
1267          break;
1268       case 'M':
1269          decode_M_packet (&own_buf[1], &mem_addr, &len, mem_buf);
1270          if (valgrind_write_memory (mem_addr, mem_buf, len) == 0)
1271             write_ok (own_buf);
1272          else
1273             write_enn (own_buf);
1274          break;
1275       case 'X':
1276          if (decode_X_packet (&own_buf[1], packet_len - 1,
1277                               &mem_addr, &len, mem_buf) < 0
1278              || valgrind_write_memory (mem_addr, mem_buf, len) != 0)
1279             write_enn (own_buf);
1280          else
1281             write_ok (own_buf);
1282          break;
1283       case 'C':
1284          convert_ascii_to_int (own_buf + 1, &sig, 1);
1285          if (target_signal_to_host_p (sig))
1286             zignal = target_signal_to_host (sig);
1287          else
1288             zignal = 0;
1289          set_desired_inferior (0);
1290          myresume (0, zignal);
1291          return; // return control to valgrind
1292       case 'S':
1293          convert_ascii_to_int (own_buf + 1, &sig, 1);
1294          if (target_signal_to_host_p (sig))
1295             zignal = target_signal_to_host (sig);
1296          else
1297             zignal = 0;
1298          set_desired_inferior (0);
1299          myresume (1, zignal);
1300          return; // return control to valgrind
1301       case 'c':
1302          set_desired_inferior (0);
1303          myresume (0, 0);
1304          return; // return control to valgrind
1305       case 's':
1306          set_desired_inferior (0);
1307          myresume (1, 0);
1308          return; // return control to valgrind
1309       case 'Z': {
1310          char *lenptr;
1311          char *dataptr;
1312          CORE_ADDR addr = strtoul (&own_buf[3], &lenptr, 16);
1313          int zlen = strtol (lenptr + 1, &dataptr, 16);
1314          char type = own_buf[1];
1315 
1316          if (type < '0' || type > '4') {
1317             /* Watchpoint command type unrecognized. */
1318             own_buf[0] = '\0';
1319          } else {
1320             int res;
1321 
1322             res = valgrind_insert_watchpoint (type, addr, zlen);
1323             if (res == 0)
1324                write_ok (own_buf);
1325             else if (res == 1)
1326                /* Unsupported.  */
1327                own_buf[0] = '\0';
1328             else
1329                write_enn (own_buf);
1330          }
1331          break;
1332       }
1333       case 'z': {
1334          char *lenptr;
1335          char *dataptr;
1336          CORE_ADDR addr = strtoul (&own_buf[3], &lenptr, 16);
1337          int zlen = strtol (lenptr + 1, &dataptr, 16);
1338          char type = own_buf[1];
1339 
1340          if (type < '0' || type > '4') {
1341             /* Watchpoint command type unrecognized. */
1342             own_buf[0] = '\0';
1343          } else {
1344             int res;
1345 
1346             res = valgrind_remove_watchpoint (type, addr, zlen);
1347             if (res == 0)
1348                write_ok (own_buf);
1349             else if (res == 1)
1350                /* Unsupported.  */
1351                own_buf[0] = '\0';
1352             else
1353                write_enn (own_buf);
1354          }
1355          break;
1356       }
1357       case 'k':
1358          kill_request("Gdb request to kill this process\n");
1359          break;
1360       case 'T': {
1361          unsigned long gdb_id, thread_id;
1362 
1363          gdb_id = strtoul (&own_buf[1], NULL, 16);
1364          thread_id = gdb_id_to_thread_id (gdb_id);
1365          if (thread_id == 0) {
1366             write_enn (own_buf);
1367             break;
1368          }
1369 
1370          if (valgrind_thread_alive (thread_id))
1371             write_ok (own_buf);
1372          else
1373             write_enn (own_buf);
1374          break;
1375       }
1376       case 'R':
1377          /* Restarting the inferior is only supported in the
1378             extended protocol.
1379             => It is a request we don't understand.  Respond with an
1380             empty packet so that gdb knows that we don't support this
1381             request.  */
1382          own_buf[0] = '\0';
1383          break;
1384       case 'v':
1385          /* Extended (long) request.  */
1386          handle_v_requests (own_buf, &status, &zignal);
1387          break;
1388       default:
1389          /* It is a request we don't understand.  Respond with an
1390             empty packet so that gdb knows that we don't support this
1391             request.  */
1392          own_buf[0] = '\0';
1393          break;
1394       }
1395 
1396       if (new_packet_len != -1)
1397          putpkt_binary (own_buf, new_packet_len);
1398       else
1399          putpkt (own_buf);
1400 
1401       if (status == 'W')
1402          VG_(umsg) ("\nChild exited with status %d\n", zignal);
1403       if (status == 'X')
1404          VG_(umsg) ("\nChild terminated with signal = 0x%x (%s)\n",
1405                     target_signal_to_host (zignal),
1406                     target_signal_to_name (zignal));
1407       if (status == 'W' || status == 'X') {
1408          VG_(umsg) ("Process exiting\n");
1409          VG_(exit) (0);
1410       }
1411    }
1412 
1413    /* We come here when getpkt fails => close the connection,
1414       and re-open. Then return control to valgrind.
1415       We return the control to valgrind as we assume that
1416       the connection was closed due to vgdb having finished
1417       to execute a command. */
1418    if (VG_(clo_verbosity) > 1)
1419       VG_(umsg) ("Remote side has terminated connection.  "
1420                  "GDBserver will reopen the connection.\n");
1421    remote_finish (reset_after_error);
1422    remote_open (VG_(clo_vgdb_prefix));
1423    myresume (0, 0);
1424    resume_reply_packet_needed = False;
1425    return;
1426 }
1427