Darwin: Make stack growth tracking consistent with other architectures
[valgrind.git] / coregrind / m_gdbserver / server.c
blobd53033012bad80e93c286a03fdd3d21d6f1257e4
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.
6 This file is part of GDB.
7 It has been modified to integrate it in valgrind
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.
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.
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. */
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"
34 unsigned long cont_thread;
35 unsigned long general_thread;
36 unsigned long step_thread;
37 unsigned long thread_from_wait;
38 unsigned long old_thread_from_wait;
40 int pass_signals[TARGET_SIGNAL_LAST]; /* indexed by gdb signal nr */
42 /* for a gdbserver integrated in valgrind, resuming the process consists
43 in returning the control to valgrind.
44 The guess process resumes its execution.
45 Then at the next error or break or ..., valgrind calls gdbserver again.
46 A resume reply packet must then be built to inform GDB that the
47 resume request is finished.
48 resume_reply_packet_needed records the fact that the next call to gdbserver
49 must send a resume packet to gdb. */
50 static Bool resume_reply_packet_needed = False;
52 VG_MINIMAL_JMP_BUF(toplevel);
54 /* Decode a qXfer read request. Return 0 if everything looks OK,
55 or -1 otherwise. */
57 static
58 int decode_xfer_read (char *buf, const char **annex, CORE_ADDR *ofs, unsigned int *len)
60 /* Extract and NUL-terminate the annex. */
61 *annex = buf;
62 while (*buf && *buf != ':')
63 buf++;
64 if (*buf == '\0')
65 return -1;
66 *buf++ = 0;
68 /* After the read/write marker and annex, qXfer looks like a
69 traditional 'm' packet. */
70 decode_m_packet (buf, ofs, len);
72 return 0;
75 /* Write the response to a successful qXfer read. Returns the
76 length of the (binary) data stored in BUF, corresponding
77 to as much of DATA/LEN as we could fit. IS_MORE controls
78 the first character of the response. */
79 static
80 int write_qxfer_response (char *buf, unsigned char *data, int len, int is_more)
82 int out_len;
84 if (is_more)
85 buf[0] = 'm';
86 else
87 buf[0] = 'l';
89 return remote_escape_output (data, len, (unsigned char *) buf + 1, &out_len,
90 PBUFSIZ - POVERHSIZ - 1) + 1;
93 static Bool initial_valgrind_sink_saved = False;
94 /* True <=> valgrind log sink saved in initial_valgrind_sink */
95 static OutputSink initial_valgrind_sink;
97 static Bool command_output_to_log = False;
98 /* True <=> command output goes to log instead of gdb */
100 void reset_valgrind_sink(const char *info)
102 if (VG_(log_output_sink).fd != initial_valgrind_sink.fd
103 && initial_valgrind_sink_saved) {
104 VG_(log_output_sink).fd = initial_valgrind_sink.fd;
105 VG_(umsg) ("Reset valgrind output to log (%s)\n",
106 (info = NULL ? "" : info));
110 void print_to_initial_valgrind_sink (const char *msg)
112 vg_assert (initial_valgrind_sink_saved);
113 VG_(write) (initial_valgrind_sink.fd, msg, strlen(msg));
117 static
118 void kill_request (const char *msg)
120 VG_(umsg) ("%s", msg);
121 remote_close();
122 VG_(exit) (0);
125 /* handle_gdb_valgrind_command handles the provided mon string command.
126 If command is recognised, return 1 else return 0.
127 Note that in case of ambiguous command, 1 is returned.
129 *sink_wanted_at_return is modified if one of the commands
130 'v.set *_output' is handled.
132 static
133 int handle_gdb_valgrind_command (char* mon, OutputSink* sink_wanted_at_return)
135 UWord ret = 0;
136 char s[strlen(mon)+1]; /* copy for strtok_r */
137 char* wcmd;
138 HChar* ssaveptr;
139 const char* endptr;
140 int kwdid;
141 int int_value;
143 vg_assert (initial_valgrind_sink_saved);
145 strcpy (s, mon);
146 wcmd = strtok_r (s, " ", &ssaveptr);
147 /* NB: if possible, avoid introducing a new command below which
148 starts with the same 3 first letters as an already existing
149 command. This ensures a shorter abbreviation for the user. */
150 switch (VG_(keyword_id) ("help v.set v.info v.wait v.kill v.translate"
151 " v.do",
152 wcmd, kwd_report_duplicated_matches)) {
153 case -2:
154 ret = 1;
155 break;
156 case -1:
157 break;
158 case 0: /* help */
159 ret = 1;
160 wcmd = strtok_r (NULL, " ", &ssaveptr);
161 if (wcmd == NULL) {
162 int_value = 0;
163 } else {
164 switch (VG_(keyword_id) ("debug", wcmd, kwd_report_all)) {
165 case -2: int_value = 0; break;
166 case -1: int_value = 0; break;
167 case 0: int_value = 1; break;
168 default: tl_assert (0);
172 VG_(gdb_printf) (
173 "general valgrind monitor commands:\n"
174 " help [debug] : monitor command help. With debug: + debugging commands\n"
175 " v.wait [<ms>] : sleep <ms> (default 0) then continue\n"
176 " v.info all_errors : show all errors found so far\n"
177 " v.info last_error : show last error found\n"
178 " v.info n_errs_found : show the nr of errors found so far\n"
179 " v.info open_fds : show open file descriptors (only if --track-fds=yes)\n"
180 " v.kill : kill the Valgrind process\n"
181 " v.set gdb_output : set valgrind output to gdb\n"
182 " v.set log_output : set valgrind output to log\n"
183 " v.set mixed_output : set valgrind output to log, interactive output to gdb\n"
184 " v.set merge-recursive-frames <num> : merge recursive calls in max <num> frames\n"
185 " v.set vgdb-error <errornr> : debug me at error >= <errornr> \n");
186 if (int_value) { VG_(gdb_printf) (
187 "debugging valgrind internals monitor commands:\n"
188 " v.do expensive_sanity_check_general : do an expensive sanity check now\n"
189 " v.info gdbserver_status : show gdbserver status\n"
190 " v.info memory [aspacemgr] : show valgrind heap memory stats\n"
191 " (with aspacemgr arg, also shows valgrind segments on log ouput)\n"
192 " v.info exectxt : show stacktraces and stats of all execontexts\n"
193 " v.info scheduler : show valgrind thread state and stacktrace\n"
194 " v.set debuglog <level> : set valgrind debug log level to <level>\n"
195 " v.translate <addr> [<traceflags>] : debug translation of <addr> with <traceflags>\n"
196 " (default traceflags 0b00100000 : show after instrumentation)\n"
197 " An additional flag 0b100000000 allows to show gdbserver instrumentation\n");
199 break;
200 case 1: /* v.set */
201 ret = 1;
202 wcmd = strtok_r (NULL, " ", &ssaveptr);
203 switch (kwdid = VG_(keyword_id)
204 ("vgdb-error debuglog merge-recursive-frames"
205 " gdb_output log_output mixed_output",
206 wcmd, kwd_report_all)) {
207 case -2:
208 case -1:
209 break;
210 case 0: /* vgdb-error */
211 case 1: /* debuglog */
212 case 2: /* merge-recursive-frames */
213 wcmd = strtok_r (NULL, " ", &ssaveptr);
214 if (wcmd == NULL) {
215 int_value = 0;
216 endptr = "empty"; /* to report an error below */
217 } else {
218 HChar *the_end;
219 int_value = strtol (wcmd, &the_end, 10);
220 endptr = the_end;
222 if (*endptr != '\0') {
223 VG_(gdb_printf) ("missing or malformed integer value\n");
224 } else if (kwdid == 0) {
225 VG_(gdb_printf) ("vgdb-error value changed from %d to %d\n",
226 VG_(dyn_vgdb_error), int_value);
227 VG_(dyn_vgdb_error) = int_value;
228 } else if (kwdid == 1) {
229 VG_(gdb_printf) ("debuglog value changed from %d to %d\n",
230 VG_(debugLog_getLevel)(), int_value);
231 VG_(debugLog_startup) (int_value, "gdbsrv");
232 } else if (kwdid == 2) {
233 VG_(gdb_printf)
234 ("merge-recursive-frames value changed from %d to %d\n",
235 VG_(clo_merge_recursive_frames), int_value);
236 VG_(clo_merge_recursive_frames) = int_value;
237 } else {
238 vg_assert (0);
240 break;
241 case 3: /* gdb_output */
242 (*sink_wanted_at_return).fd = -2;
243 command_output_to_log = False;
244 VG_(gdb_printf) ("valgrind output will go to gdb\n");
245 break;
246 case 4: /* log_output */
247 (*sink_wanted_at_return).fd = initial_valgrind_sink.fd;
248 command_output_to_log = True;
249 VG_(gdb_printf) ("valgrind output will go to log\n");
250 break;
251 case 5: /* mixed output */
252 (*sink_wanted_at_return).fd = initial_valgrind_sink.fd;
253 command_output_to_log = False;
254 VG_(gdb_printf)
255 ("valgrind output will go to log, interactive output will go to gdb\n");
256 break;
257 default:
258 vg_assert (0);
260 break;
261 case 2: /* v.info */ {
262 ret = 1;
263 wcmd = strtok_r (NULL, " ", &ssaveptr);
264 switch (kwdid = VG_(keyword_id)
265 ("all_errors n_errs_found last_error gdbserver_status memory"
266 " scheduler open_fds exectxt",
267 wcmd, kwd_report_all)) {
268 case -2:
269 case -1:
270 break;
271 case 0: // all_errors
272 // A verbosity of minimum 2 is needed to show the errors.
273 VG_(show_all_errors)(/* verbosity */ 2, /* xml */ False);
274 break;
275 case 1: // n_errs_found
276 VG_(gdb_printf) ("n_errs_found %d n_errs_shown %d (vgdb-error %d)\n",
277 VG_(get_n_errs_found) (),
278 VG_(get_n_errs_shown) (),
279 VG_(dyn_vgdb_error));
280 break;
281 case 2: // last_error
282 VG_(show_last_error)();
283 break;
284 case 3: // gdbserver_status
285 VG_(gdbserver_status_output)();
286 break;
287 case 4: /* memory */
288 VG_(print_all_arena_stats) ();
289 if (VG_(clo_profile_heap))
290 VG_(print_arena_cc_analysis) ();
291 wcmd = strtok_r (NULL, " ", &ssaveptr);
292 if (wcmd != NULL) {
293 switch (VG_(keyword_id) ("aspacemgr", wcmd, kwd_report_all)) {
294 case -2:
295 case -1: break;
296 case 0:
297 VG_(am_show_nsegments) (0, "gdbserver v.info memory aspacemgr");
298 break;
299 default: tl_assert (0);
303 ret = 1;
304 break;
305 case 5: /* scheduler */
306 VG_(show_sched_status) ();
307 ret = 1;
308 break;
309 case 6: /* open_fds */
310 if (VG_(clo_track_fds))
311 VG_(show_open_fds) ("");
312 else
313 VG_(gdb_printf)
314 ("Valgrind must be started with --track-fds=yes"
315 " to show open fds\n");
316 ret = 1;
317 break;
318 case 7: /* exectxt */
319 VG_(print_ExeContext_stats) (True /* with_stacktraces */);
320 ret = 1;
321 break;
322 default:
323 vg_assert(0);
325 break;
327 case 3: /* v.wait */
328 wcmd = strtok_r (NULL, " ", &ssaveptr);
329 if (wcmd != NULL) {
330 int_value = strtol (wcmd, NULL, 10);
331 VG_(gdb_printf) ("gdbserver: continuing in %d ms ...\n", int_value);
332 VG_(poll)(NULL, 0, int_value);
334 VG_(gdb_printf) ("gdbserver: continuing after wait ...\n");
335 ret = 1;
336 break;
337 case 4: /* v.kill */
338 kill_request ("monitor command request to kill this process\n");
339 break;
340 case 5: { /* v.translate */
341 Addr address;
342 SizeT verbosity = 0x20;
344 ret = 1;
346 VG_(strtok_get_address_and_size) (&address, &verbosity, &ssaveptr);
347 if (address != (Addr) 0 || verbosity != 0) {
348 /* we need to force the output to log for the translation trace,
349 as low level VEX tracing cannot be redirected to gdb. */
350 int saved_command_output_to_log = command_output_to_log;
351 int saved_fd = VG_(log_output_sink).fd;
352 Bool single_stepping_on_entry = valgrind_single_stepping();
353 int vex_verbosity = verbosity & 0xff;
354 VG_(log_output_sink).fd = initial_valgrind_sink.fd;
355 if ((verbosity & 0x100) && !single_stepping_on_entry) {
356 valgrind_set_single_stepping(True);
357 // to force gdbserver instrumentation.
359 # if defined(VGA_arm)
360 // on arm, we need to (potentially) convert this address
361 // to the thumb form.
362 address = thumb_pc (address);
363 # endif
365 VG_(translate) ( 0 /* dummy ThreadId; irrelevant due to debugging*/,
366 address,
367 /*debugging*/True,
368 (Int) vex_verbosity,
369 /*bbs_done*/0,
370 /*allow redir?*/True);
371 if ((verbosity & 0x100) && !single_stepping_on_entry) {
372 valgrind_set_single_stepping(False);
373 // reset single stepping.
375 command_output_to_log = saved_command_output_to_log;
376 VG_(log_output_sink).fd = saved_fd;
378 break;
381 case 6: /* v.do */
382 ret = 1;
383 wcmd = strtok_r (NULL, " ", &ssaveptr);
384 switch (VG_(keyword_id) ("expensive_sanity_check_general",
385 wcmd, kwd_report_all)) {
386 case -2:
387 case -1: break;
388 case 0: { /* expensive_sanity_check_general */
389 // Temporarily bump up sanity level to check e.g. the malloc arenas.
390 const Int save_clo_sanity_level = VG_(clo_sanity_level);
391 if (VG_(clo_sanity_level) < 4) VG_(clo_sanity_level) = 4;
392 VG_(sanity_check_general) (/* force_expensive */ True);
393 VG_(clo_sanity_level) = save_clo_sanity_level;
394 break;
396 default: tl_assert (0);
398 break;
400 default:
401 vg_assert (0);
403 return ret;
406 /* handle_gdb_monitor_command handles the provided mon string command,
407 which can be either a "standard" valgrind monitor command
408 or a tool specific monitor command.
409 If command recognised, return 1 else return 0.
410 Note that in case of ambiguous command, 1 is returned.
412 static
413 int handle_gdb_monitor_command (char* mon)
415 UWord ret = 0;
416 UWord tool_ret = 0;
417 // initially, we assume that when returning, the desired sink is the
418 // one we have when entering. It can however be changed by the standard
419 // valgrind command handling.
420 OutputSink sink_wanted_at_return = VG_(log_output_sink);
422 if (!initial_valgrind_sink_saved) {
423 /* first time we enter here, we save the valgrind default log sink */
424 initial_valgrind_sink = sink_wanted_at_return;
425 initial_valgrind_sink_saved = True;
428 if (!command_output_to_log)
429 VG_(log_output_sink).fd = -2; /* redirect to monitor_output */
431 ret = handle_gdb_valgrind_command (mon, &sink_wanted_at_return);
433 /* Even if command was recognised by valgrind core, we call the
434 tool command handler : this is needed to handle help command
435 and/or to let the tool do some additional processing of a
436 valgrind standard command. Note however that if valgrind
437 recognised the command, we will always return success. */
438 if (VG_(needs).client_requests) {
439 /* If the tool reports an error when handling a monitor command,
440 we need to avoid calling gdbserver during this command
441 handling. So, we temporarily set VG_(dyn_vgdb_error) to
442 a huge value to ensure m_errormgr.c does not call gdbserver. */
443 Int save_dyn_vgdb_error = VG_(dyn_vgdb_error);
444 UWord arg[2];
445 VG_(dyn_vgdb_error) = 999999999;
446 arg[0] = (UWord) VG_USERREQ__GDB_MONITOR_COMMAND;
447 arg[1] = (UWord) mon;
448 VG_TDICT_CALL(tool_handle_client_request, VG_(running_tid), arg,
449 &tool_ret);
450 VG_(dyn_vgdb_error) = save_dyn_vgdb_error;
453 /* restore or set the desired output */
454 VG_(log_output_sink).fd = sink_wanted_at_return.fd;
455 if (ret | tool_ret)
456 return 1;
457 else
458 return 0;
462 /* Handle all of the extended 'Q' packets. */
463 static
464 void handle_set (char *arg_own_buf, int *new_packet_len_p)
466 if (strcmp ("QStartNoAckMode", arg_own_buf) == 0) {
467 noack_mode = True;
468 write_ok (arg_own_buf);
469 return;
472 if (strncmp ("QPassSignals:", arg_own_buf, 13) == 0) {
473 int i;
474 char *from, *to;
475 char *end = arg_own_buf + strlen(arg_own_buf);
476 CORE_ADDR sig;
477 for (i = 0; i < TARGET_SIGNAL_LAST; i++)
478 pass_signals[i] = 0;
480 from = arg_own_buf + 13;
481 while (from < end) {
482 to = strchr(from, ';');
483 if (to == NULL) to = end;
484 decode_address (&sig, from, to - from);
485 pass_signals[(int)sig] = 1;
486 dlog(1, "pass_signal gdb_nr %d %s\n",
487 (int)sig, target_signal_to_name(sig));
488 from = to;
489 if (*from == ';') from++;
491 write_ok (arg_own_buf);
492 return;
494 /* Otherwise we didn't know what packet it was. Say we didn't
495 understand it. */
496 arg_own_buf[0] = 0;
499 Bool VG_(client_monitor_command) (HChar* cmd)
501 const Bool connected = remote_connected();
502 const int saved_command_output_to_log = command_output_to_log;
503 Bool handled;
505 if (!connected)
506 command_output_to_log = True;
507 handled = handle_gdb_monitor_command (cmd);
508 if (!connected) {
509 // reset the log output unless cmd changed it.
510 if (command_output_to_log)
511 command_output_to_log = saved_command_output_to_log;
513 if (handled)
514 return False; // recognised
515 else
516 return True; // not recognised
519 /* Handle all of the extended 'q' packets. */
520 static
521 void handle_query (char *arg_own_buf, int *new_packet_len_p)
523 static struct inferior_list_entry *thread_ptr;
525 /* qRcmd, monitor command handling. */
526 if (strncmp ("qRcmd,", arg_own_buf, 6) == 0) {
527 char *p = arg_own_buf + 6;
528 int cmdlen = strlen(p)/2;
529 char cmd[cmdlen+1];
531 if (unhexify (cmd, p, cmdlen) != cmdlen) {
532 write_enn (arg_own_buf);
533 return;
535 cmd[cmdlen] = '\0';
537 if (handle_gdb_monitor_command (cmd)) {
538 /* In case the command is from a standalone vgdb,
539 connection will be closed soon => flush the output. */
540 VG_(message_flush) ();
541 write_ok (arg_own_buf);
542 return;
543 } else {
544 /* cmd not recognised */
545 VG_(gdb_printf)
546 ("command '%s' not recognised\n"
547 "In gdb, try 'monitor help'\n"
548 "In a shell, try 'vgdb help'\n",
549 cmd);
550 write_ok (arg_own_buf);
551 return;
555 /* provide some valgrind specific info in return to qThreadExtraInfo. */
556 if (strncmp ("qThreadExtraInfo,", arg_own_buf, 17) == 0) {
557 unsigned long gdb_id;
558 struct thread_info *ti;
559 ThreadState *tst;
560 char status[100];
562 gdb_id = strtoul (&arg_own_buf[17], NULL, 16);
563 ti = gdb_id_to_thread (gdb_id);
564 if (ti != NULL) {
565 tst = (ThreadState *) inferior_target_data (ti);
566 /* Additional info is the tid and the thread status. */
567 VG_(snprintf) (status, sizeof(status), "tid %d %s",
568 tst->tid,
569 VG_(name_of_ThreadStatus)(tst->status));
570 hexify (arg_own_buf, status, strlen(status));
571 return;
572 } else {
573 write_enn (arg_own_buf);
574 return;
578 if (strcmp ("qAttached", arg_own_buf) == 0) {
579 /* tell gdb to always detach, never kill the process */
580 arg_own_buf[0] = '1';
581 arg_own_buf[1] = 0;
582 return;
585 if (strcmp ("qSymbol::", arg_own_buf) == 0) {
586 /* We have no symbol to read. */
587 write_ok (arg_own_buf);
588 return;
591 if (strcmp ("qfThreadInfo", arg_own_buf) == 0) {
592 thread_ptr = all_threads.head;
593 VG_(sprintf) (arg_own_buf, "m%x",
594 thread_to_gdb_id ((struct thread_info *)thread_ptr));
595 thread_ptr = thread_ptr->next;
596 return;
599 if (strcmp ("qsThreadInfo", arg_own_buf) == 0) {
600 if (thread_ptr != NULL) {
601 VG_(sprintf) (arg_own_buf, "m%x",
602 thread_to_gdb_id ((struct thread_info *)thread_ptr));
603 thread_ptr = thread_ptr->next;
604 return;
605 } else {
606 VG_(sprintf) (arg_own_buf, "l");
607 return;
611 if (valgrind_target_xml(VG_(clo_vgdb_shadow_registers)) != NULL
612 && strncmp ("qXfer:features:read:", arg_own_buf, 20) == 0) {
613 CORE_ADDR ofs;
614 unsigned int len, doc_len;
615 const char *annex = NULL;
616 // First, the annex is extracted from the packet received.
617 // Then, it is replaced by the corresponding file name.
618 int fd;
620 /* Grab the annex, offset, and length. */
621 if (decode_xfer_read (arg_own_buf + 20, &annex, &ofs, &len) < 0) {
622 strcpy (arg_own_buf, "E00");
623 return;
626 if (strcmp (annex, "target.xml") == 0) {
627 annex = valgrind_target_xml(VG_(clo_vgdb_shadow_registers));
628 if (annex != NULL && VG_(clo_vgdb_shadow_registers)) {
629 /* Ensure the shadow registers are initialized. */
630 initialize_shadow_low(True);
632 if (annex == NULL) {
633 strcpy (arg_own_buf, "E00");
634 return;
639 char doc[VG_(strlen)(VG_(libdir)) + 1 + VG_(strlen)(annex) + 1];
640 struct vg_stat stat_doc;
641 char toread[len];
642 int len_read;
644 VG_(sprintf)(doc, "%s/%s", VG_(libdir), annex);
645 fd = VG_(fd_open) (doc, VKI_O_RDONLY, 0);
646 if (fd == -1) {
647 strcpy (arg_own_buf, "E00");
648 return;
650 if (VG_(fstat) (fd, &stat_doc) != 0) {
651 VG_(close) (fd);
652 strcpy (arg_own_buf, "E00");
653 return;
655 doc_len = stat_doc.size;
657 if (len > PBUFSIZ - POVERHSIZ)
658 len = PBUFSIZ - POVERHSIZ;
660 if (ofs > doc_len) {
661 write_enn (arg_own_buf);
662 VG_(close) (fd);
663 return;
665 VG_(lseek) (fd, ofs, VKI_SEEK_SET);
666 len_read = VG_(read) (fd, toread, len);
667 *new_packet_len_p = write_qxfer_response (arg_own_buf, (unsigned char *)toread,
668 len_read, ofs + len_read < doc_len);
669 VG_(close) (fd);
670 return;
674 if (strncmp ("qXfer:auxv:read:", arg_own_buf, 16) == 0) {
675 unsigned char *data;
676 int n;
677 CORE_ADDR ofs;
678 unsigned int len;
679 const char *annex;
681 /* Reject any annex; grab the offset and length. */
682 if (decode_xfer_read (arg_own_buf + 16, &annex, &ofs, &len) < 0
683 || annex[0] != '\0') {
684 strcpy (arg_own_buf, "E00");
685 return;
688 if (len > PBUFSIZ - 2)
689 len = PBUFSIZ - 2;
690 data = malloc (len);
693 UWord *client_auxv = VG_(client_auxv);
694 unsigned int client_auxv_len = 0;
695 while (*client_auxv != 0) {
696 dlog(4, "auxv %lld %llx\n",
697 (ULong)*client_auxv,
698 (ULong)*(client_auxv+1));
699 client_auxv++;
700 client_auxv++;
701 client_auxv_len += 2 * sizeof(UWord);
703 client_auxv_len += 2 * sizeof(UWord);
704 dlog(4, "auxv len %d\n", client_auxv_len);
706 if (ofs >= client_auxv_len)
707 n = -1;
708 else {
709 n = client_auxv_len - ofs;
710 VG_(memcpy) (data, (unsigned char *) VG_(client_auxv), n);
714 if (n < 0)
715 write_enn (arg_own_buf);
716 else if (n > len)
717 *new_packet_len_p = write_qxfer_response (arg_own_buf, data, len, 1);
718 else
719 *new_packet_len_p = write_qxfer_response (arg_own_buf, data, n, 0);
721 free (data);
723 return;
727 /* Protocol features query. */
728 if (strncmp ("qSupported", arg_own_buf, 10) == 0
729 && (arg_own_buf[10] == ':' || arg_own_buf[10] == '\0')) {
730 VG_(sprintf) (arg_own_buf, "PacketSize=%x", PBUFSIZ - 1);
731 /* Note: max packet size including frame and checksum, but without
732 trailing null byte, which is not sent/received. */
734 strcat (arg_own_buf, ";QStartNoAckMode+");
735 strcat (arg_own_buf, ";QPassSignals+");
736 if (VG_(client_auxv))
737 strcat (arg_own_buf, ";qXfer:auxv:read+");
739 if (valgrind_target_xml(VG_(clo_vgdb_shadow_registers)) != NULL) {
740 strcat (arg_own_buf, ";qXfer:features:read+");
741 /* if a new gdb connects to us, we have to reset the register
742 set to the normal register sets to allow this new gdb to
743 decide to use or not the shadow registers.
745 Note that the reset is only done for gdb that are sending
746 qSupported packets. If a user first connected with a recent
747 gdb using shadow registers and then with a very old gdb
748 that does not use qSupported packet, then the old gdb will
749 not properly connect. */
750 initialize_shadow_low(False);
752 return;
755 /* Otherwise we didn't know what packet it was. Say we didn't
756 understand it. */
757 arg_own_buf[0] = 0;
760 /* Handle all of the extended 'v' packets. */
761 static
762 void handle_v_requests (char *arg_own_buf, char *status, int *zignal)
764 /* vcont packet code from gdb 6.6 removed */
766 /* Otherwise we didn't know what packet it was. Say we didn't
767 understand it. */
768 arg_own_buf[0] = 0;
769 return;
772 static
773 void myresume (int step, int sig)
775 struct thread_resume resume_info[2];
776 int n = 0;
778 if (step || sig) {
779 resume_info[0].step = step;
780 resume_info[0].sig = sig;
781 n++;
783 resume_info[n].step = 0;
784 resume_info[n].sig = 0;
786 resume_reply_packet_needed = True;
787 valgrind_resume (resume_info);
790 /* server_main global variables */
791 static char *own_buf;
792 static unsigned char *mem_buf;
794 void gdbserver_init (void)
796 dlog(1, "gdbserver_init gdbserver embedded in valgrind: %s\n", version);
797 noack_mode = False;
798 valgrind_initialize_target ();
799 // After a fork, gdbserver_init can be called again.
800 // We do not have to re-malloc the buffers in such a case.
801 if (own_buf == NULL)
802 own_buf = malloc (PBUFSIZ);
803 if (mem_buf == NULL)
804 mem_buf = malloc (PBUFSIZ);
807 void gdbserver_terminate (void)
809 /* last call to gdbserver is cleanup call */
810 if (VG_MINIMAL_SETJMP(toplevel)) {
811 dlog(0, "error caused VG_MINIMAL_LONGJMP to gdbserver_terminate\n");
812 return;
814 remote_close();
817 void server_main (void)
819 static char status;
820 static int zignal;
822 char ch;
823 int i = 0;
824 unsigned int len;
825 CORE_ADDR mem_addr;
827 zignal = valgrind_wait (&status);
828 if (VG_MINIMAL_SETJMP(toplevel)) {
829 dlog(0, "error caused VG_MINIMAL_LONGJMP to server_main\n");
831 while (1) {
832 unsigned char sig;
833 int packet_len;
834 int new_packet_len = -1;
836 if (resume_reply_packet_needed) {
837 /* Send the resume reply to reply to last GDB resume
838 request. */
839 resume_reply_packet_needed = False;
840 prepare_resume_reply (own_buf, status, zignal);
841 putpkt (own_buf);
844 /* If we our status is terminal (exit or fatal signal) get out
845 as quickly as we can. We won't be able to handle any request
846 anymore. */
847 if (status == 'W' || status == 'X') {
848 return;
851 packet_len = getpkt (own_buf);
852 if (packet_len <= 0)
853 break;
855 i = 0;
856 ch = own_buf[i++];
857 switch (ch) {
858 case 'Q':
859 handle_set (own_buf, &new_packet_len);
860 break;
861 case 'q':
862 handle_query (own_buf, &new_packet_len);
863 break;
864 case 'd':
865 /* set/unset debugging is done through valgrind debug level. */
866 own_buf[0] = '\0';
867 break;
868 case 'D':
869 reset_valgrind_sink("gdb detaching from process");
871 /* When detaching or kill the process, gdb expects to get
872 an packet OK back. Any other output will make gdb
873 believes detach did not work. */
874 write_ok (own_buf);
875 putpkt (own_buf);
876 remote_finish (reset_after_error);
877 remote_open (VG_(clo_vgdb_prefix));
878 myresume (0, 0);
879 resume_reply_packet_needed = False;
880 return;
881 case '!':
882 /* We can not use the extended protocol with valgrind,
883 because we can not restart the running
884 program. So return unrecognized. */
885 own_buf[0] = '\0';
886 break;
887 case '?':
888 prepare_resume_reply (own_buf, status, zignal);
889 break;
890 case 'H':
891 if (own_buf[1] == 'c' || own_buf[1] == 'g' || own_buf[1] == 's') {
892 unsigned long gdb_id, thread_id;
894 gdb_id = strtoul (&own_buf[2], NULL, 16);
895 thread_id = gdb_id_to_thread_id (gdb_id);
896 if (thread_id == 0) {
897 write_enn (own_buf);
898 break;
901 if (own_buf[1] == 'g') {
902 general_thread = thread_id;
903 set_desired_inferior (1);
904 } else if (own_buf[1] == 'c') {
905 cont_thread = thread_id;
906 } else if (own_buf[1] == 's') {
907 step_thread = thread_id;
910 write_ok (own_buf);
911 } else {
912 /* Silently ignore it so that gdb can extend the protocol
913 without compatibility headaches. */
914 own_buf[0] = '\0';
916 break;
917 case 'g':
918 set_desired_inferior (1);
919 registers_to_string (own_buf);
920 break;
921 case 'G':
922 set_desired_inferior (1);
923 registers_from_string (&own_buf[1]);
924 write_ok (own_buf);
925 break;
926 case 'P': {
927 int regno;
928 char *regbytes;
929 Bool mod;
930 ThreadState *tst;
931 regno = strtol(&own_buf[1], NULL, 16);
932 regbytes = strchr(&own_buf[0], '=') + 1;
933 set_desired_inferior (1);
934 tst = (ThreadState *) inferior_target_data (current_inferior);
935 /* Only accept changing registers in "runnable state3.
936 In fact, it would be ok to change most of the registers
937 except a few "sensitive" registers such as the PC, SP, BP.
938 We assume we do not need to very specific here, and that we
939 can just refuse all of these. */
940 if (tst->status == VgTs_Runnable || tst->status == VgTs_Yielding) {
941 supply_register_from_string (regno, regbytes, &mod);
942 write_ok (own_buf);
943 } else {
944 /* at least from gdb 6.6 onwards, an E. error
945 reply is shown to the user. So, we do an error
946 msg which both is accepted by gdb as an error msg
947 and is readable by the user. */
948 VG_(sprintf)
949 (own_buf,
950 "E.\n"
951 "ERROR changing register %s regno %d\n"
952 "gdb commands changing registers (pc, sp, ...) (e.g. 'jump',\n"
953 "set pc, calling from gdb a function in the debugged process, ...)\n"
954 "can only be accepted if the thread is VgTs_Runnable or VgTs_Yielding state\n"
955 "Thread status is %s\n",
956 find_register_by_number (regno)->name, regno,
957 VG_(name_of_ThreadStatus)(tst->status));
958 if (VG_(clo_verbosity) > 1)
959 VG_(umsg) ("%s\n", own_buf);
961 break;
963 case 'm':
964 decode_m_packet (&own_buf[1], &mem_addr, &len);
965 if (valgrind_read_memory (mem_addr, mem_buf, len) == 0)
966 convert_int_to_ascii (mem_buf, own_buf, len);
967 else
968 write_enn (own_buf);
969 break;
970 case 'M':
971 decode_M_packet (&own_buf[1], &mem_addr, &len, mem_buf);
972 if (valgrind_write_memory (mem_addr, mem_buf, len) == 0)
973 write_ok (own_buf);
974 else
975 write_enn (own_buf);
976 break;
977 case 'X':
978 if (decode_X_packet (&own_buf[1], packet_len - 1,
979 &mem_addr, &len, mem_buf) < 0
980 || valgrind_write_memory (mem_addr, mem_buf, len) != 0)
981 write_enn (own_buf);
982 else
983 write_ok (own_buf);
984 break;
985 case 'C':
986 convert_ascii_to_int (own_buf + 1, &sig, 1);
987 if (target_signal_to_host_p (sig))
988 zignal = target_signal_to_host (sig);
989 else
990 zignal = 0;
991 set_desired_inferior (0);
992 myresume (0, zignal);
993 return; // return control to valgrind
994 case 'S':
995 convert_ascii_to_int (own_buf + 1, &sig, 1);
996 if (target_signal_to_host_p (sig))
997 zignal = target_signal_to_host (sig);
998 else
999 zignal = 0;
1000 set_desired_inferior (0);
1001 myresume (1, zignal);
1002 return; // return control to valgrind
1003 case 'c':
1004 set_desired_inferior (0);
1005 myresume (0, 0);
1006 return; // return control to valgrind
1007 case 's':
1008 set_desired_inferior (0);
1009 myresume (1, 0);
1010 return; // return control to valgrind
1011 case 'Z': {
1012 char *lenptr;
1013 char *dataptr;
1014 CORE_ADDR addr = strtoul (&own_buf[3], &lenptr, 16);
1015 int zlen = strtol (lenptr + 1, &dataptr, 16);
1016 char type = own_buf[1];
1018 if (type < '0' || type > '4') {
1019 /* Watchpoint command type unrecognized. */
1020 own_buf[0] = '\0';
1021 } else {
1022 int res;
1024 res = valgrind_insert_watchpoint (type, addr, zlen);
1025 if (res == 0)
1026 write_ok (own_buf);
1027 else if (res == 1)
1028 /* Unsupported. */
1029 own_buf[0] = '\0';
1030 else
1031 write_enn (own_buf);
1033 break;
1035 case 'z': {
1036 char *lenptr;
1037 char *dataptr;
1038 CORE_ADDR addr = strtoul (&own_buf[3], &lenptr, 16);
1039 int zlen = strtol (lenptr + 1, &dataptr, 16);
1040 char type = own_buf[1];
1042 if (type < '0' || type > '4') {
1043 /* Watchpoint command type unrecognized. */
1044 own_buf[0] = '\0';
1045 } else {
1046 int res;
1048 res = valgrind_remove_watchpoint (type, addr, zlen);
1049 if (res == 0)
1050 write_ok (own_buf);
1051 else if (res == 1)
1052 /* Unsupported. */
1053 own_buf[0] = '\0';
1054 else
1055 write_enn (own_buf);
1057 break;
1059 case 'k':
1060 kill_request("Gdb request to kill this process\n");
1061 break;
1062 case 'T': {
1063 unsigned long gdb_id, thread_id;
1065 gdb_id = strtoul (&own_buf[1], NULL, 16);
1066 thread_id = gdb_id_to_thread_id (gdb_id);
1067 if (thread_id == 0) {
1068 write_enn (own_buf);
1069 break;
1072 if (valgrind_thread_alive (thread_id))
1073 write_ok (own_buf);
1074 else
1075 write_enn (own_buf);
1076 break;
1078 case 'R':
1079 /* Restarting the inferior is only supported in the
1080 extended protocol.
1081 => It is a request we don't understand. Respond with an
1082 empty packet so that gdb knows that we don't support this
1083 request. */
1084 own_buf[0] = '\0';
1085 break;
1086 case 'v':
1087 /* Extended (long) request. */
1088 handle_v_requests (own_buf, &status, &zignal);
1089 break;
1090 default:
1091 /* It is a request we don't understand. Respond with an
1092 empty packet so that gdb knows that we don't support this
1093 request. */
1094 own_buf[0] = '\0';
1095 break;
1098 if (new_packet_len != -1)
1099 putpkt_binary (own_buf, new_packet_len);
1100 else
1101 putpkt (own_buf);
1103 if (status == 'W')
1104 VG_(umsg) ("\nChild exited with status %d\n", zignal);
1105 if (status == 'X')
1106 VG_(umsg) ("\nChild terminated with signal = 0x%x (%s)\n",
1107 target_signal_to_host (zignal),
1108 target_signal_to_name (zignal));
1109 if (status == 'W' || status == 'X') {
1110 VG_(umsg) ("Process exiting\n");
1111 VG_(exit) (0);
1115 /* We come here when getpkt fails => close the connection,
1116 and re-open. Then return control to valgrind.
1117 We return the control to valgrind as we assume that
1118 the connection was closed due to vgdb having finished
1119 to execute a command. */
1120 if (VG_(clo_verbosity) > 1)
1121 VG_(umsg) ("Remote side has terminated connection. "
1122 "GDBserver will reopen the connection.\n");
1123 remote_finish (reset_after_error);
1124 remote_open (VG_(clo_vgdb_prefix));
1125 myresume (0, 0);
1126 resume_reply_packet_needed = False;
1127 return;