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