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