constify to_open
[deliverable/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
ecd75fc8 3 Copyright (C) 1988-2014 Free Software Foundation, Inc.
c906108c 4
c5aa993b
JM
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
c5aa993b
JM
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5aa993b 19
23860348 20/* See the GDB User Guide for details of the GDB remote protocol. */
c5aa993b 21
c906108c 22#include "defs.h"
0e9f083f 23#include <string.h>
c906108c
SS
24#include <ctype.h>
25#include <fcntl.h>
c906108c 26#include "inferior.h"
45741a9c 27#include "infrun.h"
c906108c
SS
28#include "bfd.h"
29#include "symfile.h"
60250e8b 30#include "exceptions.h"
c906108c 31#include "target.h"
c5aa993b 32/*#include "terminal.h" */
c906108c
SS
33#include "gdbcmd.h"
34#include "objfiles.h"
35#include "gdb-stabs.h"
36#include "gdbthread.h"
c2c6d25f 37#include "remote.h"
722247f1 38#include "remote-notif.h"
4e052eda 39#include "regcache.h"
fd0407d6 40#include "value.h"
1ff9c3d6 41#include "gdb_assert.h"
6867ae3e 42#include "observer.h"
a77053c2 43#include "solib.h"
37a105a1
DJ
44#include "cli/cli-decode.h"
45#include "cli/cli-setshow.h"
424163ea 46#include "target-descriptions.h"
a4453b7e 47#include "gdb_bfd.h"
614c279d 48#include "filestuff.h"
9c3d6531 49#include "rsp-low.h"
c906108c 50
9846de1b 51#include <sys/time.h>
c906108c 52
43ff13b4 53#include "event-loop.h"
c2c6d25f 54#include "event-top.h"
2acceee2 55#include "inf-loop.h"
43ff13b4 56
c906108c
SS
57#include <signal.h>
58#include "serial.h"
59
6240bebf
MS
60#include "gdbcore.h" /* for exec_bfd */
61
449092f6 62#include "remote-fileio.h"
a6b151f1 63#include "gdb/fileio.h"
53ce3c39 64#include <sys/stat.h>
dc146f7c 65#include "xml-support.h"
449092f6 66
fd79ecee
DJ
67#include "memory-map.h"
68
35b1e5cc
SS
69#include "tracepoint.h"
70#include "ax.h"
71#include "ax-gdb.h"
d1feda86 72#include "agent.h"
9accd112 73#include "btrace.h"
35b1e5cc 74
0df8b418 75/* Temp hacks for tracepoint encoding migration. */
35b1e5cc
SS
76static char *target_buf;
77static long target_buf_size;
35b1e5cc 78
6765f3e5
DJ
79/* The size to align memory write packets, when practical. The protocol
80 does not guarantee any alignment, and gdb will generate short
81 writes and unaligned writes, but even as a best-effort attempt this
82 can improve bulk transfers. For instance, if a write is misaligned
83 relative to the target's data bus, the stub may need to make an extra
84 round trip fetching data from the target. This doesn't make a
85 huge difference, but it's easy to do, so we try to be helpful.
86
87 The alignment chosen is arbitrary; usually data bus width is
88 important here, not the possibly larger cache line size. */
89enum { REMOTE_ALIGN_WRITES = 16 };
90
23860348 91/* Prototypes for local functions. */
934b9bac 92static void async_cleanup_sigint_signal_handler (void *dummy);
6d820c5c 93static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
74531fed 94static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
fee9eda9 95 int forever, int *is_notif);
6426a772 96
934b9bac
JK
97static void async_handle_remote_sigint (int);
98static void async_handle_remote_sigint_twice (int);
43ff13b4 99
a14ed312 100static void remote_files_info (struct target_ops *ignore);
c906108c 101
f32dbf8c
MM
102static void remote_prepare_to_store (struct target_ops *self,
103 struct regcache *regcache);
c906108c 104
014f9477
TT
105static void remote_open_1 (const char *, int, struct target_ops *,
106 int extended_p);
c906108c 107
de90e03d 108static void remote_close (struct target_ops *self);
c906108c 109
136d6dae 110static void remote_mourn (struct target_ops *ops);
c906108c 111
a14ed312 112static void extended_remote_restart (void);
c906108c 113
136d6dae 114static void extended_remote_mourn (struct target_ops *);
c906108c 115
a14ed312 116static void remote_mourn_1 (struct target_ops *);
c906108c 117
6d820c5c 118static void remote_send (char **buf, long *sizeof_buf_p);
c906108c 119
a14ed312 120static int readchar (int timeout);
c906108c 121
c33e31fd
PA
122static void remote_serial_write (const char *str, int len);
123
7d85a9c0 124static void remote_kill (struct target_ops *ops);
c906108c 125
6a109b6b 126static int remote_can_async_p (struct target_ops *);
75c99385 127
6a109b6b 128static int remote_is_async_p (struct target_ops *);
75c99385 129
6a109b6b
TT
130static void remote_async (struct target_ops *ops,
131 void (*callback) (enum inferior_event_type event_type,
132 void *context),
133 void *context);
75c99385 134
934b9bac 135static void sync_remote_interrupt_twice (int signo);
7a292a7a 136
a14ed312 137static void interrupt_query (void);
c906108c 138
79d7f229
PA
139static void set_general_thread (struct ptid ptid);
140static void set_continue_thread (struct ptid ptid);
c906108c 141
a14ed312 142static void get_offsets (void);
c906108c 143
6d820c5c
DJ
144static void skip_frame (void);
145
146static long read_frame (char **buf_p, long *sizeof_buf);
c906108c 147
a14ed312 148static int hexnumlen (ULONGEST num);
c906108c 149
a14ed312 150static void init_remote_ops (void);
c906108c 151
a14ed312 152static void init_extended_remote_ops (void);
c906108c 153
1eab8a48 154static void remote_stop (struct target_ops *self, ptid_t);
c906108c 155
a14ed312 156static int stubhex (int ch);
c906108c 157
a14ed312 158static int hexnumstr (char *, ULONGEST);
c906108c 159
a14ed312 160static int hexnumnstr (char *, ULONGEST, int);
2df3850c 161
a14ed312 162static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 163
baa336ce 164static void print_packet (const char *);
c906108c 165
a14ed312 166static void compare_sections_command (char *, int);
c906108c 167
a14ed312 168static void packet_command (char *, int);
c906108c 169
a14ed312 170static int stub_unpack_int (char *buff, int fieldlength);
c906108c 171
39f77062 172static ptid_t remote_current_thread (ptid_t oldptid);
c906108c 173
a14ed312 174static void remote_find_new_threads (void);
c906108c 175
baa336ce 176static int putpkt_binary (const char *buf, int cnt);
c906108c 177
a14ed312 178static void check_binary_download (CORE_ADDR addr);
c906108c 179
5a2468f5 180struct packet_config;
5a2468f5 181
a14ed312 182static void show_packet_config_cmd (struct packet_config *config);
5a2468f5 183
bb572ddd
DJ
184static void show_remote_protocol_packet_cmd (struct ui_file *file,
185 int from_tty,
186 struct cmd_list_element *c,
187 const char *value);
188
82f73884
PA
189static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
190static ptid_t read_ptid (char *buf, char **obuf);
191
c378d69d 192static void remote_set_permissions (struct target_ops *self);
d914c394 193
d5551862 194struct remote_state;
8bd200f1
TT
195static int remote_get_trace_status (struct target_ops *self,
196 struct trace_status *ts);
d5551862 197
ab6617cc
TT
198static int remote_upload_tracepoints (struct target_ops *self,
199 struct uploaded_tp **utpp);
00bf0b85 200
181e3713
TT
201static int remote_upload_trace_state_variables (struct target_ops *self,
202 struct uploaded_tsv **utsvp);
00bf0b85 203
c8d104ad
PA
204static void remote_query_supported (void);
205
36d25514 206static void remote_check_symbols (void);
c8d104ad 207
a14ed312 208void _initialize_remote (void);
c906108c 209
74531fed 210struct stop_reply;
74531fed 211static void stop_reply_xfree (struct stop_reply *);
722247f1 212static void remote_parse_stop_reply (char *, struct stop_reply *);
74531fed 213static void push_stop_reply (struct stop_reply *);
bcc75809 214static void discard_pending_stop_replies_in_queue (struct remote_state *);
74531fed
PA
215static int peek_stop_reply (ptid_t ptid);
216
217static void remote_async_inferior_event_handler (gdb_client_data);
74531fed 218
e3594fd1 219static void remote_terminal_ours (struct target_ops *self);
d3fd5342 220
d962ef82
DJ
221static int remote_read_description_p (struct target_ops *target);
222
176a6961 223static void remote_console_output (char *msg);
dde08ee1 224
efcc2da7 225static int remote_supports_cond_breakpoints (struct target_ops *self);
b775012e 226
78eff0ec 227static int remote_can_run_breakpoint_commands (struct target_ops *self);
d3ce09f5 228
a6b151f1
DJ
229/* For "remote". */
230
231static struct cmd_list_element *remote_cmdlist;
232
bb572ddd
DJ
233/* For "set remote" and "show remote". */
234
235static struct cmd_list_element *remote_set_cmdlist;
236static struct cmd_list_element *remote_show_cmdlist;
237
d458bd84
PA
238/* Stub vCont actions support.
239
240 Each field is a boolean flag indicating whether the stub reports
241 support for the corresponding action. */
242
243struct vCont_action_support
244{
245 /* vCont;t */
246 int t;
c1e36e3e
PA
247
248 /* vCont;r */
249 int r;
d458bd84
PA
250};
251
c1e36e3e
PA
252/* Controls whether GDB is willing to use range stepping. */
253
254static int use_range_stepping = 1;
255
0d031856
TT
256#define OPAQUETHREADBYTES 8
257
258/* a 64 bit opaque identifier */
259typedef unsigned char threadref[OPAQUETHREADBYTES];
260
261/* About this many threadisds fit in a packet. */
262
263#define MAXTHREADLISTRESULTS 32
264
ea9c271d
DJ
265/* Description of the remote protocol state for the currently
266 connected target. This is per-target state, and independent of the
267 selected architecture. */
268
269struct remote_state
270{
271 /* A buffer to use for incoming packets, and its current size. The
272 buffer is grown dynamically for larger incoming packets.
273 Outgoing packets may also be constructed in this buffer.
274 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
275 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
276 packets. */
277 char *buf;
278 long buf_size;
be2a5f71 279
1e51243a
PA
280 /* True if we're going through initial connection setup (finding out
281 about the remote side's threads, relocating symbols, etc.). */
282 int starting_up;
283
be2a5f71
DJ
284 /* If we negotiated packet size explicitly (and thus can bypass
285 heuristics for the largest packet size that will not overflow
286 a buffer in the stub), this will be set to that packet size.
287 Otherwise zero, meaning to use the guessed size. */
288 long explicit_packet_size;
2d717e4f
DJ
289
290 /* remote_wait is normally called when the target is running and
291 waits for a stop reply packet. But sometimes we need to call it
292 when the target is already stopped. We can send a "?" packet
293 and have remote_wait read the response. Or, if we already have
294 the response, we can stash it in BUF and tell remote_wait to
295 skip calling getpkt. This flag is set when BUF contains a
296 stop reply packet and the target is not waiting. */
297 int cached_wait_status;
a6f3e723
SL
298
299 /* True, if in no ack mode. That is, neither GDB nor the stub will
300 expect acks from each other. The connection is assumed to be
301 reliable. */
302 int noack_mode;
82f73884
PA
303
304 /* True if we're connected in extended remote mode. */
305 int extended;
306
e24a49d8
PA
307 /* True if we resumed the target and we're waiting for the target to
308 stop. In the mean time, we can't start another command/query.
309 The remote server wouldn't be ready to process it, so we'd
310 timeout waiting for a reply that would never come and eventually
311 we'd close the connection. This can happen in asynchronous mode
312 because we allow GDB commands while the target is running. */
313 int waiting_for_stop_reply;
74531fed 314
d458bd84
PA
315 /* The status of the stub support for the various vCont actions. */
316 struct vCont_action_support supports_vCont;
782b2b07 317
3a29589a
DJ
318 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
319 responded to that. */
320 int ctrlc_pending_p;
5d93a237
TT
321
322 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
323 remote_open knows that we don't have a file open when the program
324 starts. */
325 struct serial *remote_desc;
47f8a51d
TT
326
327 /* These are the threads which we last sent to the remote system. The
328 TID member will be -1 for all or -2 for not sent yet. */
329 ptid_t general_thread;
330 ptid_t continue_thread;
262e1174
TT
331
332 /* This is the traceframe which we last selected on the remote system.
333 It will be -1 if no traceframe is selected. */
334 int remote_traceframe_number;
747dc59d
TT
335
336 char *last_pass_packet;
5e4a05c4
TT
337
338 /* The last QProgramSignals packet sent to the target. We bypass
339 sending a new program signals list down to the target if the new
340 packet is exactly the same as the last we sent. IOW, we only let
341 the target know about program signals list changes. */
342 char *last_program_signals_packet;
b73be471
TT
343
344 enum gdb_signal last_sent_signal;
280ceea3
TT
345
346 int last_sent_step;
8e88304f
TT
347
348 char *finished_object;
349 char *finished_annex;
350 ULONGEST finished_offset;
b80fafe3
TT
351
352 /* Should we try the 'ThreadInfo' query packet?
353
354 This variable (NOT available to the user: auto-detect only!)
355 determines whether GDB will use the new, simpler "ThreadInfo"
356 query or the older, more complex syntax for thread queries.
357 This is an auto-detect variable (set to true at each connect,
358 and set to false when the target fails to recognize it). */
359 int use_threadinfo_query;
360 int use_threadextra_query;
88b496c3
TT
361
362 void (*async_client_callback) (enum inferior_event_type event_type,
363 void *context);
364 void *async_client_context;
ee154bee
TT
365
366 /* This is set to the data address of the access causing the target
367 to stop for a watchpoint. */
368 CORE_ADDR remote_watch_data_address;
369
370 /* This is non-zero if target stopped for a watchpoint. */
371 int remote_stopped_by_watchpoint_p;
0d031856
TT
372
373 threadref echo_nextthread;
374 threadref nextthread;
375 threadref resultthreadlist[MAXTHREADLISTRESULTS];
5965e028
YQ
376
377 /* The state of remote notification. */
378 struct remote_notif_state *notif_state;
ea9c271d
DJ
379};
380
dc146f7c
VP
381/* Private data that we'll store in (struct thread_info)->private. */
382struct private_thread_info
383{
384 char *extra;
385 int core;
386};
387
388static void
389free_private_thread_info (struct private_thread_info *info)
390{
391 xfree (info->extra);
392 xfree (info);
393}
394
ea9c271d
DJ
395/* This data could be associated with a target, but we do not always
396 have access to the current target when we need it, so for now it is
397 static. This will be fine for as long as only one target is in use
398 at a time. */
cf792862 399static struct remote_state *remote_state;
ea9c271d
DJ
400
401static struct remote_state *
0b83947e 402get_remote_state_raw (void)
ea9c271d 403{
cf792862
TT
404 return remote_state;
405}
406
407/* Allocate a new struct remote_state with xmalloc, initialize it, and
408 return it. */
409
410static struct remote_state *
411new_remote_state (void)
412{
413 struct remote_state *result = XCNEW (struct remote_state);
414
415 /* The default buffer size is unimportant; it will be expanded
416 whenever a larger buffer is needed. */
417 result->buf_size = 400;
418 result->buf = xmalloc (result->buf_size);
262e1174 419 result->remote_traceframe_number = -1;
b73be471 420 result->last_sent_signal = GDB_SIGNAL_0;
cf792862
TT
421
422 return result;
ea9c271d
DJ
423}
424
425/* Description of the remote protocol for a given architecture. */
d01949b6 426
ad10f812
AC
427struct packet_reg
428{
429 long offset; /* Offset into G packet. */
430 long regnum; /* GDB's internal register number. */
431 LONGEST pnum; /* Remote protocol register number. */
b323314b 432 int in_g_packet; /* Always part of G packet. */
f5656ead 433 /* long size in bytes; == register_size (target_gdbarch (), regnum);
23860348 434 at present. */
f5656ead 435 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
c9f4d572 436 at present. */
ad10f812
AC
437};
438
ea9c271d 439struct remote_arch_state
d01949b6 440{
ad10f812
AC
441 /* Description of the remote protocol registers. */
442 long sizeof_g_packet;
b323314b
AC
443
444 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 445 (making an array gdbarch_num_regs in size). */
b323314b 446 struct packet_reg *regs;
ad10f812 447
d01949b6
AC
448 /* This is the size (in chars) of the first response to the ``g''
449 packet. It is used as a heuristic when determining the maximum
450 size of memory-read and memory-write packets. A target will
451 typically only reserve a buffer large enough to hold the ``g''
452 packet. The size does not include packet overhead (headers and
23860348 453 trailers). */
d01949b6
AC
454 long actual_register_packet_size;
455
456 /* This is the maximum size (in chars) of a non read/write packet.
23860348 457 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
458 long remote_packet_size;
459};
460
35b1e5cc
SS
461/* Utility: generate error from an incoming stub packet. */
462static void
463trace_error (char *buf)
464{
465 if (*buf++ != 'E')
466 return; /* not an error msg */
467 switch (*buf)
468 {
469 case '1': /* malformed packet error */
470 if (*++buf == '0') /* general case: */
471 error (_("remote.c: error in outgoing packet."));
472 else
473 error (_("remote.c: error in outgoing packet at field #%ld."),
474 strtol (buf, NULL, 16));
35b1e5cc
SS
475 default:
476 error (_("Target returns error code '%s'."), buf);
477 }
478}
479
480/* Utility: wait for reply from stub, while accepting "O" packets. */
481static char *
482remote_get_noisy_reply (char **buf_p,
483 long *sizeof_buf)
484{
485 do /* Loop on reply from remote stub. */
486 {
487 char *buf;
a744cf53 488
0df8b418 489 QUIT; /* Allow user to bail out with ^C. */
35b1e5cc
SS
490 getpkt (buf_p, sizeof_buf, 0);
491 buf = *buf_p;
ad91cd99 492 if (buf[0] == 'E')
35b1e5cc 493 trace_error (buf);
dde08ee1
PA
494 else if (strncmp (buf, "qRelocInsn:", strlen ("qRelocInsn:")) == 0)
495 {
496 ULONGEST ul;
497 CORE_ADDR from, to, org_to;
498 char *p, *pp;
499 int adjusted_size = 0;
500 volatile struct gdb_exception ex;
501
502 p = buf + strlen ("qRelocInsn:");
503 pp = unpack_varlen_hex (p, &ul);
504 if (*pp != ';')
cb91c06a 505 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
506 from = ul;
507
508 p = pp + 1;
a9cbf802 509 unpack_varlen_hex (p, &ul);
dde08ee1
PA
510 to = ul;
511
512 org_to = to;
513
514 TRY_CATCH (ex, RETURN_MASK_ALL)
515 {
f5656ead 516 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
dde08ee1
PA
517 }
518 if (ex.reason >= 0)
519 {
520 adjusted_size = to - org_to;
521
bba74b36 522 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
523 putpkt (buf);
524 }
525 else if (ex.reason < 0 && ex.error == MEMORY_ERROR)
526 {
527 /* Propagate memory errors silently back to the target.
528 The stub may have limited the range of addresses we
529 can write to, for example. */
530 putpkt ("E01");
531 }
532 else
533 {
534 /* Something unexpectedly bad happened. Be verbose so
535 we can tell what, and propagate the error back to the
536 stub, so it doesn't get stuck waiting for a
537 response. */
538 exception_fprintf (gdb_stderr, ex,
539 _("warning: relocating instruction: "));
540 putpkt ("E01");
541 }
542 }
ad91cd99 543 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
544 remote_console_output (buf + 1); /* 'O' message from stub */
545 else
0df8b418 546 return buf; /* Here's the actual reply. */
35b1e5cc
SS
547 }
548 while (1);
549}
3c3bea1c 550
d01949b6
AC
551/* Handle for retreving the remote protocol data from gdbarch. */
552static struct gdbarch_data *remote_gdbarch_data_handle;
553
ea9c271d
DJ
554static struct remote_arch_state *
555get_remote_arch_state (void)
d01949b6 556{
f5656ead 557 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
d01949b6
AC
558}
559
0b83947e
DJ
560/* Fetch the global remote target state. */
561
562static struct remote_state *
563get_remote_state (void)
564{
565 /* Make sure that the remote architecture state has been
566 initialized, because doing so might reallocate rs->buf. Any
567 function which calls getpkt also needs to be mindful of changes
568 to rs->buf, but this call limits the number of places which run
569 into trouble. */
570 get_remote_arch_state ();
571
572 return get_remote_state_raw ();
573}
574
74ca34ce
DJ
575static int
576compare_pnums (const void *lhs_, const void *rhs_)
577{
578 const struct packet_reg * const *lhs = lhs_;
579 const struct packet_reg * const *rhs = rhs_;
580
581 if ((*lhs)->pnum < (*rhs)->pnum)
582 return -1;
583 else if ((*lhs)->pnum == (*rhs)->pnum)
584 return 0;
585 else
586 return 1;
587}
588
c21236dc
PA
589static int
590map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 591{
74ca34ce 592 int regnum, num_remote_regs, offset;
74ca34ce 593 struct packet_reg **remote_regs;
ea9c271d 594
4a22f64d 595 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 596 {
c21236dc 597 struct packet_reg *r = &regs[regnum];
baef701f 598
4a22f64d 599 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
600 /* Do not try to fetch zero-sized (placeholder) registers. */
601 r->pnum = -1;
602 else
603 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
604
b323314b 605 r->regnum = regnum;
74ca34ce
DJ
606 }
607
608 /* Define the g/G packet format as the contents of each register
609 with a remote protocol number, in order of ascending protocol
610 number. */
611
4a22f64d 612 remote_regs = alloca (gdbarch_num_regs (gdbarch)
c21236dc 613 * sizeof (struct packet_reg *));
f57d151a 614 for (num_remote_regs = 0, regnum = 0;
4a22f64d 615 regnum < gdbarch_num_regs (gdbarch);
f57d151a 616 regnum++)
c21236dc
PA
617 if (regs[regnum].pnum != -1)
618 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 619
74ca34ce
DJ
620 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
621 compare_pnums);
622
623 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
624 {
625 remote_regs[regnum]->in_g_packet = 1;
626 remote_regs[regnum]->offset = offset;
4a22f64d 627 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
628 }
629
c21236dc
PA
630 return offset;
631}
632
633/* Given the architecture described by GDBARCH, return the remote
634 protocol register's number and the register's offset in the g/G
635 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
636 If the target does not have a mapping for REGNUM, return false,
637 otherwise, return true. */
638
639int
640remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
641 int *pnum, int *poffset)
642{
643 int sizeof_g_packet;
644 struct packet_reg *regs;
645 struct cleanup *old_chain;
646
647 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
648
649 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
650 old_chain = make_cleanup (xfree, regs);
651
652 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
653
654 *pnum = regs[regnum].pnum;
655 *poffset = regs[regnum].offset;
656
657 do_cleanups (old_chain);
658
659 return *pnum != -1;
660}
661
662static void *
663init_remote_state (struct gdbarch *gdbarch)
664{
665 struct remote_state *rs = get_remote_state_raw ();
666 struct remote_arch_state *rsa;
667
668 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
669
670 /* Use the architecture to build a regnum<->pnum table, which will be
671 1:1 unless a feature set specifies otherwise. */
672 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
673 gdbarch_num_regs (gdbarch),
674 struct packet_reg);
675
74ca34ce
DJ
676 /* Record the maximum possible size of the g packet - it may turn out
677 to be smaller. */
c21236dc 678 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 679
0df8b418 680 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
681 remote stubs have a hardwired buffer size of 400 bytes
682 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
683 as the maximum packet-size to ensure that the packet and an extra
684 NUL character can always fit in the buffer. This stops GDB
685 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
686 already a full buffer (As of 1999-12-04 that was most stubs). */
687 rsa->remote_packet_size = 400 - 1;
d01949b6 688
ea9c271d
DJ
689 /* This one is filled in when a ``g'' packet is received. */
690 rsa->actual_register_packet_size = 0;
691
692 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
693 default, adjust the size accordingly. Remember that each byte is
694 encoded as two characters. 32 is the overhead for the packet
695 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 696 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 697 little. */
ea9c271d
DJ
698 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
699 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 700
ea9c271d
DJ
701 /* Make sure that the packet buffer is plenty big enough for
702 this architecture. */
703 if (rs->buf_size < rsa->remote_packet_size)
704 {
705 rs->buf_size = 2 * rsa->remote_packet_size;
7fca722e 706 rs->buf = xrealloc (rs->buf, rs->buf_size);
ea9c271d 707 }
6d820c5c 708
ea9c271d
DJ
709 return rsa;
710}
711
712/* Return the current allowed size of a remote packet. This is
713 inferred from the current architecture, and should be used to
714 limit the length of outgoing packets. */
715static long
716get_remote_packet_size (void)
717{
be2a5f71 718 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
719 struct remote_arch_state *rsa = get_remote_arch_state ();
720
be2a5f71
DJ
721 if (rs->explicit_packet_size)
722 return rs->explicit_packet_size;
723
ea9c271d 724 return rsa->remote_packet_size;
d01949b6
AC
725}
726
ad10f812 727static struct packet_reg *
ea9c271d 728packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 729{
f5656ead 730 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
b323314b
AC
731 return NULL;
732 else
ad10f812 733 {
ea9c271d 734 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 735
b323314b
AC
736 gdb_assert (r->regnum == regnum);
737 return r;
ad10f812 738 }
ad10f812
AC
739}
740
741static struct packet_reg *
ea9c271d 742packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 743{
b323314b 744 int i;
a744cf53 745
f5656ead 746 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
ad10f812 747 {
ea9c271d 748 struct packet_reg *r = &rsa->regs[i];
a744cf53 749
b323314b
AC
750 if (r->pnum == pnum)
751 return r;
ad10f812
AC
752 }
753 return NULL;
d01949b6
AC
754}
755
c906108c
SS
756static struct target_ops remote_ops;
757
758static struct target_ops extended_remote_ops;
759
6426a772
JM
760/* FIXME: cagney/1999-09-23: Even though getpkt was called with
761 ``forever'' still use the normal timeout mechanism. This is
762 currently used by the ASYNC code to guarentee that target reads
763 during the initial connect always time-out. Once getpkt has been
764 modified to return a timeout indication and, in turn
765 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 766 this can go away. */
6426a772
JM
767static int wait_forever_enabled_p = 1;
768
9a7071a8
JB
769/* Allow the user to specify what sequence to send to the remote
770 when he requests a program interruption: Although ^C is usually
771 what remote systems expect (this is the default, here), it is
772 sometimes preferable to send a break. On other systems such
773 as the Linux kernel, a break followed by g, which is Magic SysRq g
774 is required in order to interrupt the execution. */
775const char interrupt_sequence_control_c[] = "Ctrl-C";
776const char interrupt_sequence_break[] = "BREAK";
777const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 778static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
779 {
780 interrupt_sequence_control_c,
781 interrupt_sequence_break,
782 interrupt_sequence_break_g,
783 NULL
784 };
785static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
786
787static void
788show_interrupt_sequence (struct ui_file *file, int from_tty,
789 struct cmd_list_element *c,
790 const char *value)
791{
792 if (interrupt_sequence_mode == interrupt_sequence_control_c)
793 fprintf_filtered (file,
794 _("Send the ASCII ETX character (Ctrl-c) "
795 "to the remote target to interrupt the "
796 "execution of the program.\n"));
797 else if (interrupt_sequence_mode == interrupt_sequence_break)
798 fprintf_filtered (file,
799 _("send a break signal to the remote target "
800 "to interrupt the execution of the program.\n"));
801 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
802 fprintf_filtered (file,
803 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
804 "the remote target to interrupt the execution "
805 "of Linux kernel.\n"));
806 else
807 internal_error (__FILE__, __LINE__,
808 _("Invalid value for interrupt_sequence_mode: %s."),
809 interrupt_sequence_mode);
810}
6426a772 811
9a7071a8
JB
812/* This boolean variable specifies whether interrupt_sequence is sent
813 to the remote target when gdb connects to it.
814 This is mostly needed when you debug the Linux kernel: The Linux kernel
815 expects BREAK g which is Magic SysRq g for connecting gdb. */
816static int interrupt_on_connect = 0;
c906108c 817
9a7071a8
JB
818/* This variable is used to implement the "set/show remotebreak" commands.
819 Since these commands are now deprecated in favor of "set/show remote
820 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
821static int remote_break;
822
9a7071a8
JB
823static void
824set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
825{
826 if (remote_break)
827 interrupt_sequence_mode = interrupt_sequence_break;
828 else
829 interrupt_sequence_mode = interrupt_sequence_control_c;
830}
831
832static void
833show_remotebreak (struct ui_file *file, int from_tty,
834 struct cmd_list_element *c,
835 const char *value)
836{
837}
838
c906108c
SS
839/* This variable sets the number of bits in an address that are to be
840 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 841 leading zeros, the entire address would be sent. This variable
c906108c
SS
842 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
843 initial implementation of remote.c restricted the address sent in
844 memory packets to ``host::sizeof long'' bytes - (typically 32
845 bits). Consequently, for 64 bit targets, the upper 32 bits of an
846 address was never sent. Since fixing this bug may cause a break in
847 some remote targets this variable is principly provided to
23860348 848 facilitate backward compatibility. */
c906108c 849
883b9c6c 850static unsigned int remote_address_size;
c906108c 851
75c99385
PA
852/* Temporary to track who currently owns the terminal. See
853 remote_terminal_* for more details. */
6426a772
JM
854
855static int remote_async_terminal_ours_p;
856
2d717e4f
DJ
857/* The executable file to use for "run" on the remote side. */
858
859static char *remote_exec_file = "";
860
11cf8741 861\f
11cf8741 862/* User configurable variables for the number of characters in a
ea9c271d
DJ
863 memory read/write packet. MIN (rsa->remote_packet_size,
864 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 865 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
866 (speed up transfers). The variables ``preferred_*'' (the user
867 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 868 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
869
870struct memory_packet_config
871{
872 char *name;
873 long size;
874 int fixed_p;
875};
876
877/* Compute the current size of a read/write packet. Since this makes
878 use of ``actual_register_packet_size'' the computation is dynamic. */
879
880static long
881get_memory_packet_size (struct memory_packet_config *config)
882{
d01949b6 883 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
884 struct remote_arch_state *rsa = get_remote_arch_state ();
885
11cf8741
JM
886 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
887 law?) that some hosts don't cope very well with large alloca()
888 calls. Eventually the alloca() code will be replaced by calls to
889 xmalloc() and make_cleanups() allowing this restriction to either
23860348 890 be lifted or removed. */
11cf8741
JM
891#ifndef MAX_REMOTE_PACKET_SIZE
892#define MAX_REMOTE_PACKET_SIZE 16384
893#endif
3de11b2e 894 /* NOTE: 20 ensures we can write at least one byte. */
11cf8741 895#ifndef MIN_REMOTE_PACKET_SIZE
3de11b2e 896#define MIN_REMOTE_PACKET_SIZE 20
11cf8741
JM
897#endif
898 long what_they_get;
899 if (config->fixed_p)
900 {
901 if (config->size <= 0)
902 what_they_get = MAX_REMOTE_PACKET_SIZE;
903 else
904 what_they_get = config->size;
905 }
906 else
907 {
ea9c271d 908 what_they_get = get_remote_packet_size ();
23860348 909 /* Limit the packet to the size specified by the user. */
11cf8741
JM
910 if (config->size > 0
911 && what_they_get > config->size)
912 what_they_get = config->size;
be2a5f71
DJ
913
914 /* Limit it to the size of the targets ``g'' response unless we have
915 permission from the stub to use a larger packet size. */
916 if (rs->explicit_packet_size == 0
917 && rsa->actual_register_packet_size > 0
918 && what_they_get > rsa->actual_register_packet_size)
919 what_they_get = rsa->actual_register_packet_size;
11cf8741
JM
920 }
921 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
922 what_they_get = MAX_REMOTE_PACKET_SIZE;
923 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
924 what_they_get = MIN_REMOTE_PACKET_SIZE;
6d820c5c
DJ
925
926 /* Make sure there is room in the global buffer for this packet
927 (including its trailing NUL byte). */
928 if (rs->buf_size < what_they_get + 1)
929 {
930 rs->buf_size = 2 * what_they_get;
931 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
932 }
933
11cf8741
JM
934 return what_they_get;
935}
936
0df8b418 937/* Update the size of a read/write packet. If they user wants
23860348 938 something really big then do a sanity check. */
11cf8741
JM
939
940static void
941set_memory_packet_size (char *args, struct memory_packet_config *config)
942{
943 int fixed_p = config->fixed_p;
944 long size = config->size;
a744cf53 945
11cf8741 946 if (args == NULL)
8a3fe4f8 947 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
948 else if (strcmp (args, "hard") == 0
949 || strcmp (args, "fixed") == 0)
950 fixed_p = 1;
951 else if (strcmp (args, "soft") == 0
952 || strcmp (args, "limit") == 0)
953 fixed_p = 0;
954 else
955 {
956 char *end;
a744cf53 957
11cf8741
JM
958 size = strtoul (args, &end, 0);
959 if (args == end)
8a3fe4f8 960 error (_("Invalid %s (bad syntax)."), config->name);
11cf8741
JM
961#if 0
962 /* Instead of explicitly capping the size of a packet to
963 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
964 instead allowed to set the size to something arbitrarily
23860348 965 large. */
11cf8741 966 if (size > MAX_REMOTE_PACKET_SIZE)
8a3fe4f8 967 error (_("Invalid %s (too large)."), config->name);
11cf8741
JM
968#endif
969 }
23860348 970 /* Extra checks? */
11cf8741
JM
971 if (fixed_p && !config->fixed_p)
972 {
e2e0b3e5
AC
973 if (! query (_("The target may not be able to correctly handle a %s\n"
974 "of %ld bytes. Change the packet size? "),
11cf8741 975 config->name, size))
8a3fe4f8 976 error (_("Packet size not changed."));
11cf8741 977 }
23860348 978 /* Update the config. */
11cf8741
JM
979 config->fixed_p = fixed_p;
980 config->size = size;
981}
982
983static void
984show_memory_packet_size (struct memory_packet_config *config)
985{
a3f17187 986 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 987 if (config->fixed_p)
a3f17187 988 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
989 get_memory_packet_size (config));
990 else
a3f17187 991 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
992 get_memory_packet_size (config));
993}
994
995static struct memory_packet_config memory_write_packet_config =
996{
997 "memory-write-packet-size",
998};
999
1000static void
1001set_memory_write_packet_size (char *args, int from_tty)
1002{
1003 set_memory_packet_size (args, &memory_write_packet_config);
1004}
1005
1006static void
1007show_memory_write_packet_size (char *args, int from_tty)
1008{
1009 show_memory_packet_size (&memory_write_packet_config);
1010}
1011
1012static long
1013get_memory_write_packet_size (void)
1014{
1015 return get_memory_packet_size (&memory_write_packet_config);
1016}
1017
1018static struct memory_packet_config memory_read_packet_config =
1019{
1020 "memory-read-packet-size",
1021};
1022
1023static void
1024set_memory_read_packet_size (char *args, int from_tty)
1025{
1026 set_memory_packet_size (args, &memory_read_packet_config);
1027}
1028
1029static void
1030show_memory_read_packet_size (char *args, int from_tty)
1031{
1032 show_memory_packet_size (&memory_read_packet_config);
1033}
1034
1035static long
1036get_memory_read_packet_size (void)
1037{
1038 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1039
11cf8741
JM
1040 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1041 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1042 increased beyond this. */
1043 if (size > get_remote_packet_size ())
1044 size = get_remote_packet_size ();
11cf8741
JM
1045 return size;
1046}
1047
11cf8741 1048\f
5a2468f5 1049/* Generic configuration support for packets the stub optionally
0df8b418 1050 supports. Allows the user to specify the use of the packet as well
23860348 1051 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1052
1053enum packet_support
1054 {
1055 PACKET_SUPPORT_UNKNOWN = 0,
1056 PACKET_ENABLE,
1057 PACKET_DISABLE
1058 };
1059
5a2468f5
JM
1060struct packet_config
1061 {
bb572ddd
DJ
1062 const char *name;
1063 const char *title;
4082afcc
PA
1064
1065 /* If auto, GDB auto-detects support for this packet or feature,
1066 either through qSupported, or by trying the packet and looking
1067 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1068 packet. If false, the packet is disabled. Configs that don't
1069 have an associated command always have this set to auto. */
7f19b9a2 1070 enum auto_boolean detect;
4082afcc
PA
1071
1072 /* Does the target support this packet? */
5a2468f5
JM
1073 enum packet_support support;
1074 };
1075
d471ea57 1076/* Analyze a packet's return value and update the packet config
23860348 1077 accordingly. */
d471ea57
AC
1078
1079enum packet_result
1080{
1081 PACKET_ERROR,
1082 PACKET_OK,
1083 PACKET_UNKNOWN
1084};
1085
4082afcc
PA
1086static enum packet_support packet_config_support (struct packet_config *config);
1087static enum packet_support packet_support (int packet);
5a2468f5
JM
1088
1089static void
fba45db2 1090show_packet_config_cmd (struct packet_config *config)
5a2468f5
JM
1091{
1092 char *support = "internal-error";
a744cf53 1093
4082afcc 1094 switch (packet_config_support (config))
5a2468f5
JM
1095 {
1096 case PACKET_ENABLE:
1097 support = "enabled";
1098 break;
1099 case PACKET_DISABLE:
1100 support = "disabled";
1101 break;
1102 case PACKET_SUPPORT_UNKNOWN:
1103 support = "unknown";
1104 break;
1105 }
1106 switch (config->detect)
1107 {
7f19b9a2 1108 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1109 printf_filtered (_("Support for the `%s' packet "
1110 "is auto-detected, currently %s.\n"),
37a105a1 1111 config->name, support);
5a2468f5 1112 break;
7f19b9a2
AC
1113 case AUTO_BOOLEAN_TRUE:
1114 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1115 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1116 config->name, support);
8e248173 1117 break;
5a2468f5
JM
1118 }
1119}
1120
1121static void
bb572ddd
DJ
1122add_packet_config_cmd (struct packet_config *config, const char *name,
1123 const char *title, int legacy)
d471ea57 1124{
5a2468f5
JM
1125 char *set_doc;
1126 char *show_doc;
d471ea57 1127 char *cmd_name;
3ed07be4 1128
5a2468f5
JM
1129 config->name = name;
1130 config->title = title;
b435e160
AC
1131 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1132 name, title);
3e43a32a
MS
1133 show_doc = xstrprintf ("Show current use of remote "
1134 "protocol `%s' (%s) packet",
b435e160 1135 name, title);
d471ea57 1136 /* set/show TITLE-packet {auto,on,off} */
b435e160 1137 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1138 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1139 &config->detect, set_doc,
1140 show_doc, NULL, /* help_doc */
4082afcc 1141 NULL,
bb572ddd
DJ
1142 show_remote_protocol_packet_cmd,
1143 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1144 /* The command code copies the documentation strings. */
1145 xfree (set_doc);
1146 xfree (show_doc);
23860348 1147 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1148 if (legacy)
1149 {
1150 char *legacy_name;
a744cf53 1151
b435e160 1152 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1153 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1154 &remote_set_cmdlist);
d471ea57 1155 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1156 &remote_show_cmdlist);
d471ea57 1157 }
5a2468f5
JM
1158}
1159
d471ea57 1160static enum packet_result
a76d924d 1161packet_check_result (const char *buf)
5a2468f5 1162{
d471ea57 1163 if (buf[0] != '\0')
5a2468f5 1164 {
d471ea57 1165 /* The stub recognized the packet request. Check that the
23860348 1166 operation succeeded. */
a76d924d
DJ
1167 if (buf[0] == 'E'
1168 && isxdigit (buf[1]) && isxdigit (buf[2])
1169 && buf[3] == '\0')
1170 /* "Enn" - definitly an error. */
1171 return PACKET_ERROR;
1172
1173 /* Always treat "E." as an error. This will be used for
1174 more verbose error messages, such as E.memtypes. */
1175 if (buf[0] == 'E' && buf[1] == '.')
1176 return PACKET_ERROR;
1177
1178 /* The packet may or may not be OK. Just assume it is. */
1179 return PACKET_OK;
1180 }
1181 else
1182 /* The stub does not support the packet. */
1183 return PACKET_UNKNOWN;
1184}
1185
1186static enum packet_result
1187packet_ok (const char *buf, struct packet_config *config)
1188{
1189 enum packet_result result;
1190
4082afcc
PA
1191 if (config->detect != AUTO_BOOLEAN_TRUE
1192 && config->support == PACKET_DISABLE)
1193 internal_error (__FILE__, __LINE__,
1194 _("packet_ok: attempt to use a disabled packet"));
1195
a76d924d
DJ
1196 result = packet_check_result (buf);
1197 switch (result)
1198 {
1199 case PACKET_OK:
1200 case PACKET_ERROR:
1201 /* The stub recognized the packet request. */
4082afcc 1202 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1203 {
d471ea57
AC
1204 if (remote_debug)
1205 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1206 "Packet %s (%s) is supported\n",
1207 config->name, config->title);
d471ea57 1208 config->support = PACKET_ENABLE;
d471ea57 1209 }
a76d924d
DJ
1210 break;
1211 case PACKET_UNKNOWN:
23860348 1212 /* The stub does not support the packet. */
4082afcc
PA
1213 if (config->detect == AUTO_BOOLEAN_AUTO
1214 && config->support == PACKET_ENABLE)
d471ea57 1215 {
4082afcc
PA
1216 /* If the stub previously indicated that the packet was
1217 supported then there is a protocol error. */
1218 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1219 config->name, config->title);
1220 }
1221 else if (config->detect == AUTO_BOOLEAN_TRUE)
1222 {
1223 /* The user set it wrong. */
1224 error (_("Enabled packet %s (%s) not recognized by stub"),
1225 config->name, config->title);
d471ea57 1226 }
4082afcc
PA
1227
1228 if (remote_debug)
1229 fprintf_unfiltered (gdb_stdlog,
1230 "Packet %s (%s) is NOT supported\n",
1231 config->name, config->title);
1232 config->support = PACKET_DISABLE;
a76d924d 1233 break;
5a2468f5 1234 }
a76d924d
DJ
1235
1236 return result;
5a2468f5
JM
1237}
1238
444abaca
DJ
1239enum {
1240 PACKET_vCont = 0,
1241 PACKET_X,
1242 PACKET_qSymbol,
1243 PACKET_P,
1244 PACKET_p,
1245 PACKET_Z0,
1246 PACKET_Z1,
1247 PACKET_Z2,
1248 PACKET_Z3,
1249 PACKET_Z4,
a6b151f1
DJ
1250 PACKET_vFile_open,
1251 PACKET_vFile_pread,
1252 PACKET_vFile_pwrite,
1253 PACKET_vFile_close,
1254 PACKET_vFile_unlink,
b9e7b9c3 1255 PACKET_vFile_readlink,
0876f84a 1256 PACKET_qXfer_auxv,
23181151 1257 PACKET_qXfer_features,
cfa9d6d9 1258 PACKET_qXfer_libraries,
2268b414 1259 PACKET_qXfer_libraries_svr4,
fd79ecee 1260 PACKET_qXfer_memory_map,
0e7f50da
UW
1261 PACKET_qXfer_spu_read,
1262 PACKET_qXfer_spu_write,
07e059b5 1263 PACKET_qXfer_osdata,
dc146f7c 1264 PACKET_qXfer_threads,
0fb4aa4b 1265 PACKET_qXfer_statictrace_read,
b3b9301e 1266 PACKET_qXfer_traceframe_info,
169081d0 1267 PACKET_qXfer_uib,
711e434b 1268 PACKET_qGetTIBAddr,
444abaca 1269 PACKET_qGetTLSAddr,
be2a5f71 1270 PACKET_qSupported,
bd3eecc3 1271 PACKET_qTStatus,
89be2091 1272 PACKET_QPassSignals,
9b224c5e 1273 PACKET_QProgramSignals,
936d2992 1274 PACKET_qCRC,
08388c79 1275 PACKET_qSearch_memory,
2d717e4f
DJ
1276 PACKET_vAttach,
1277 PACKET_vRun,
a6f3e723 1278 PACKET_QStartNoAckMode,
82f73884 1279 PACKET_vKill,
4aa995e1
PA
1280 PACKET_qXfer_siginfo_read,
1281 PACKET_qXfer_siginfo_write,
0b16c5cf 1282 PACKET_qAttached,
4082afcc
PA
1283
1284 /* Support for conditional tracepoints. */
782b2b07 1285 PACKET_ConditionalTracepoints,
4082afcc
PA
1286
1287 /* Support for target-side breakpoint conditions. */
3788aec7 1288 PACKET_ConditionalBreakpoints,
4082afcc
PA
1289
1290 /* Support for target-side breakpoint commands. */
d3ce09f5 1291 PACKET_BreakpointCommands,
4082afcc
PA
1292
1293 /* Support for fast tracepoints. */
7a697b8d 1294 PACKET_FastTracepoints,
4082afcc
PA
1295
1296 /* Support for static tracepoints. */
0fb4aa4b 1297 PACKET_StaticTracepoints,
4082afcc
PA
1298
1299 /* Support for installing tracepoints while a trace experiment is
1300 running. */
1e4d1764 1301 PACKET_InstallInTrace,
4082afcc 1302
40ab02ce
MS
1303 PACKET_bc,
1304 PACKET_bs,
409873ef 1305 PACKET_TracepointSource,
d914c394 1306 PACKET_QAllow,
78d85199 1307 PACKET_qXfer_fdpic,
03583c20 1308 PACKET_QDisableRandomization,
d1feda86 1309 PACKET_QAgent,
f6f899bf 1310 PACKET_QTBuffer_size,
9accd112
MM
1311 PACKET_Qbtrace_off,
1312 PACKET_Qbtrace_bts,
1313 PACKET_qXfer_btrace,
4082afcc
PA
1314
1315 /* Support for the QNonStop packet. */
1316 PACKET_QNonStop,
1317
1318 /* Support for multi-process extensions. */
1319 PACKET_multiprocess_feature,
1320
1321 /* Support for enabling and disabling tracepoints while a trace
1322 experiment is running. */
1323 PACKET_EnableDisableTracepoints_feature,
1324
1325 /* Support for collecting strings using the tracenz bytecode. */
1326 PACKET_tracenz_feature,
1327
1328 /* Support for continuing to run a trace experiment while GDB is
1329 disconnected. */
1330 PACKET_DisconnectedTracing_feature,
1331
1332 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1333 PACKET_augmented_libraries_svr4_read_feature,
1334
444abaca
DJ
1335 PACKET_MAX
1336};
506fb367 1337
444abaca 1338static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1339
4082afcc
PA
1340/* Returns whether a given packet or feature is supported. This takes
1341 into account the state of the corresponding "set remote foo-packet"
1342 command, which may be used to bypass auto-detection. */
dc8acb97 1343
4082afcc
PA
1344static enum packet_support
1345packet_config_support (struct packet_config *config)
1346{
1347 switch (config->detect)
444abaca 1348 {
4082afcc
PA
1349 case AUTO_BOOLEAN_TRUE:
1350 return PACKET_ENABLE;
1351 case AUTO_BOOLEAN_FALSE:
1352 return PACKET_DISABLE;
1353 case AUTO_BOOLEAN_AUTO:
1354 return config->support;
1355 default:
1356 gdb_assert_not_reached (_("bad switch"));
444abaca 1357 }
4082afcc
PA
1358}
1359
1360/* Same as packet_config_support, but takes the packet's enum value as
1361 argument. */
1362
1363static enum packet_support
1364packet_support (int packet)
1365{
1366 struct packet_config *config = &remote_protocol_packets[packet];
1367
1368 return packet_config_support (config);
dc8acb97
MS
1369}
1370
5a2468f5 1371static void
444abaca
DJ
1372show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1373 struct cmd_list_element *c,
1374 const char *value)
5a2468f5 1375{
444abaca 1376 struct packet_config *packet;
5a2468f5 1377
444abaca
DJ
1378 for (packet = remote_protocol_packets;
1379 packet < &remote_protocol_packets[PACKET_MAX];
1380 packet++)
1381 {
1382 if (&packet->detect == c->var)
1383 {
1384 show_packet_config_cmd (packet);
1385 return;
1386 }
1387 }
9b20d036 1388 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1389 c->name);
5a2468f5
JM
1390}
1391
d471ea57
AC
1392/* Should we try one of the 'Z' requests? */
1393
1394enum Z_packet_type
1395{
1396 Z_PACKET_SOFTWARE_BP,
1397 Z_PACKET_HARDWARE_BP,
1398 Z_PACKET_WRITE_WP,
1399 Z_PACKET_READ_WP,
1400 Z_PACKET_ACCESS_WP,
1401 NR_Z_PACKET_TYPES
1402};
96baa820 1403
d471ea57 1404/* For compatibility with older distributions. Provide a ``set remote
23860348 1405 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1406
7f19b9a2 1407static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1408
1409static void
fba45db2
KB
1410set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1411 struct cmd_list_element *c)
96baa820 1412{
d471ea57 1413 int i;
a744cf53 1414
d471ea57 1415 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1416 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1417}
1418
1419static void
08546159
AC
1420show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1421 struct cmd_list_element *c,
1422 const char *value)
96baa820 1423{
d471ea57 1424 int i;
a744cf53 1425
d471ea57
AC
1426 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1427 {
444abaca 1428 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1429 }
96baa820
JM
1430}
1431
4082afcc
PA
1432/* Returns true if the multi-process extensions are in effect. */
1433
1434static int
1435remote_multi_process_p (struct remote_state *rs)
1436{
1437 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1438}
1439
23860348 1440/* Tokens for use by the asynchronous signal handlers for SIGINT. */
934b9bac
JK
1441static struct async_signal_handler *async_sigint_remote_twice_token;
1442static struct async_signal_handler *async_sigint_remote_token;
43ff13b4 1443
74531fed
PA
1444\f
1445/* Asynchronous signal handle registered as event loop source for
1446 when we have pending events ready to be passed to the core. */
1447
1448static struct async_event_handler *remote_async_inferior_event_token;
1449
c906108c
SS
1450\f
1451
79d7f229
PA
1452static ptid_t magic_null_ptid;
1453static ptid_t not_sent_ptid;
1454static ptid_t any_thread_ptid;
1455
0b16c5cf
PA
1456/* Find out if the stub attached to PID (and hence GDB should offer to
1457 detach instead of killing it when bailing out). */
1458
1459static int
1460remote_query_attached (int pid)
1461{
1462 struct remote_state *rs = get_remote_state ();
bba74b36 1463 size_t size = get_remote_packet_size ();
0b16c5cf 1464
4082afcc 1465 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1466 return 0;
1467
1468 if (remote_multi_process_p (rs))
bba74b36 1469 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1470 else
bba74b36 1471 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1472
1473 putpkt (rs->buf);
1474 getpkt (&rs->buf, &rs->buf_size, 0);
1475
1476 switch (packet_ok (rs->buf,
1554e9be 1477 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1478 {
1479 case PACKET_OK:
1480 if (strcmp (rs->buf, "1") == 0)
1481 return 1;
1482 break;
1483 case PACKET_ERROR:
1484 warning (_("Remote failure reply: %s"), rs->buf);
1485 break;
1486 case PACKET_UNKNOWN:
1487 break;
1488 }
1489
1490 return 0;
1491}
1492
49c62f2e
PA
1493/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1494 has been invented by GDB, instead of reported by the target. Since
1495 we can be connected to a remote system before before knowing about
1496 any inferior, mark the target with execution when we find the first
1497 inferior. If ATTACHED is 1, then we had just attached to this
1498 inferior. If it is 0, then we just created this inferior. If it
1499 is -1, then try querying the remote stub to find out if it had
1500 attached to the inferior or not. */
1941c569
PA
1501
1502static struct inferior *
49c62f2e 1503remote_add_inferior (int fake_pid_p, int pid, int attached)
1941c569 1504{
1941c569
PA
1505 struct inferior *inf;
1506
0b16c5cf
PA
1507 /* Check whether this process we're learning about is to be
1508 considered attached, or if is to be considered to have been
1509 spawned by the stub. */
1510 if (attached == -1)
1511 attached = remote_query_attached (pid);
1512
f5656ead 1513 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1514 {
1515 /* If the target shares code across all inferiors, then every
1516 attach adds a new inferior. */
1517 inf = add_inferior (pid);
1518
1519 /* ... and every inferior is bound to the same program space.
1520 However, each inferior may still have its own address
1521 space. */
1522 inf->aspace = maybe_new_address_space ();
1523 inf->pspace = current_program_space;
1524 }
1525 else
1526 {
1527 /* In the traditional debugging scenario, there's a 1-1 match
1528 between program/address spaces. We simply bind the inferior
1529 to the program space's address space. */
1530 inf = current_inferior ();
1531 inferior_appeared (inf, pid);
1532 }
1941c569 1533
0b16c5cf 1534 inf->attach_flag = attached;
49c62f2e 1535 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1536
1941c569
PA
1537 return inf;
1538}
1539
1540/* Add thread PTID to GDB's thread list. Tag it as executing/running
1541 according to RUNNING. */
1542
c906108c 1543static void
1941c569 1544remote_add_thread (ptid_t ptid, int running)
c906108c 1545{
b7ea362b
PA
1546 struct remote_state *rs = get_remote_state ();
1547
1548 /* GDB historically didn't pull threads in the initial connection
1549 setup. If the remote target doesn't even have a concept of
1550 threads (e.g., a bare-metal target), even if internally we
1551 consider that a single-threaded target, mentioning a new thread
1552 might be confusing to the user. Be silent then, preserving the
1553 age old behavior. */
1554 if (rs->starting_up)
1555 add_thread_silent (ptid);
1556 else
1557 add_thread (ptid);
1941c569
PA
1558
1559 set_executing (ptid, running);
1560 set_running (ptid, running);
1561}
1562
1563/* Come here when we learn about a thread id from the remote target.
1564 It may be the first time we hear about such thread, so take the
1565 opportunity to add it to GDB's thread list. In case this is the
1566 first time we're noticing its corresponding inferior, add it to
1567 GDB's inferior list as well. */
1568
1569static void
1570remote_notice_new_inferior (ptid_t currthread, int running)
1571{
c906108c
SS
1572 /* If this is a new thread, add it to GDB's thread list.
1573 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1574
1575 if (in_thread_list (currthread) && is_exited (currthread))
1576 {
1577 /* We're seeing an event on a thread id we knew had exited.
1578 This has to be a new thread reusing the old id. Add it. */
1941c569 1579 remote_add_thread (currthread, running);
82f73884
PA
1580 return;
1581 }
1582
79d7f229 1583 if (!in_thread_list (currthread))
c0a2216e 1584 {
1941c569 1585 struct inferior *inf = NULL;
bad34192 1586 int pid = ptid_get_pid (currthread);
1941c569 1587
bad34192
PA
1588 if (ptid_is_pid (inferior_ptid)
1589 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1590 {
1591 /* inferior_ptid has no thread member yet. This can happen
1592 with the vAttach -> remote_wait,"TAAthread:" path if the
1593 stub doesn't support qC. This is the first stop reported
1594 after an attach, so this is the main thread. Update the
1595 ptid in the thread list. */
bad34192
PA
1596 if (in_thread_list (pid_to_ptid (pid)))
1597 thread_change_ptid (inferior_ptid, currthread);
1598 else
1599 {
1600 remote_add_thread (currthread, running);
1601 inferior_ptid = currthread;
1602 }
dc146f7c 1603 return;
c0a2216e 1604 }
82f73884
PA
1605
1606 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1607 {
1608 /* inferior_ptid is not set yet. This can happen with the
1609 vRun -> remote_wait,"TAAthread:" path if the stub
1610 doesn't support qC. This is the first stop reported
1611 after an attach, so this is the main thread. Update the
1612 ptid in the thread list. */
dc146f7c 1613 thread_change_ptid (inferior_ptid, currthread);
82f73884 1614 return;
c0a2216e 1615 }
82f73884 1616
29c87f7f
PA
1617 /* When connecting to a target remote, or to a target
1618 extended-remote which already was debugging an inferior, we
1619 may not know about it yet. Add it before adding its child
1620 thread, so notifications are emitted in a sensible order. */
1621 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1622 {
1623 struct remote_state *rs = get_remote_state ();
1624 int fake_pid_p = !remote_multi_process_p (rs);
1625
1626 inf = remote_add_inferior (fake_pid_p,
1627 ptid_get_pid (currthread), -1);
1628 }
29c87f7f 1629
82f73884 1630 /* This is really a new thread. Add it. */
1941c569
PA
1631 remote_add_thread (currthread, running);
1632
1633 /* If we found a new inferior, let the common code do whatever
1634 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1635 breakpoints), unless we're just setting up an all-stop
1636 connection. */
1941c569 1637 if (inf != NULL)
b7ea362b
PA
1638 {
1639 struct remote_state *rs = get_remote_state ();
1640
1641 if (non_stop || !rs->starting_up)
1642 notice_new_inferior (currthread, running, 0);
1643 }
c0a2216e 1644 }
c906108c
SS
1645}
1646
dc146f7c
VP
1647/* Return the private thread data, creating it if necessary. */
1648
70221824 1649static struct private_thread_info *
dc146f7c
VP
1650demand_private_info (ptid_t ptid)
1651{
1652 struct thread_info *info = find_thread_ptid (ptid);
1653
1654 gdb_assert (info);
1655
1656 if (!info->private)
1657 {
1658 info->private = xmalloc (sizeof (*(info->private)));
1659 info->private_dtor = free_private_thread_info;
1660 info->private->core = -1;
1661 info->private->extra = 0;
1662 }
1663
1664 return info->private;
1665}
1666
74531fed
PA
1667/* Call this function as a result of
1668 1) A halt indication (T packet) containing a thread id
1669 2) A direct query of currthread
0df8b418 1670 3) Successful execution of set thread */
74531fed
PA
1671
1672static void
47f8a51d 1673record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1674{
47f8a51d 1675 rs->general_thread = currthread;
74531fed
PA
1676}
1677
89be2091
DJ
1678/* If 'QPassSignals' is supported, tell the remote stub what signals
1679 it can simply pass through to the inferior without reporting. */
1680
1681static void
94bedb42
TT
1682remote_pass_signals (struct target_ops *self,
1683 int numsigs, unsigned char *pass_signals)
89be2091 1684{
4082afcc 1685 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
1686 {
1687 char *pass_packet, *p;
89be2091 1688 int count = 0, i;
747dc59d 1689 struct remote_state *rs = get_remote_state ();
89be2091
DJ
1690
1691 gdb_assert (numsigs < 256);
1692 for (i = 0; i < numsigs; i++)
1693 {
2455069d 1694 if (pass_signals[i])
89be2091
DJ
1695 count++;
1696 }
1697 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1698 strcpy (pass_packet, "QPassSignals:");
1699 p = pass_packet + strlen (pass_packet);
1700 for (i = 0; i < numsigs; i++)
1701 {
2455069d 1702 if (pass_signals[i])
89be2091
DJ
1703 {
1704 if (i >= 16)
1705 *p++ = tohex (i >> 4);
1706 *p++ = tohex (i & 15);
1707 if (count)
1708 *p++ = ';';
1709 else
1710 break;
1711 count--;
1712 }
1713 }
1714 *p = 0;
747dc59d 1715 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 1716 {
89be2091
DJ
1717 putpkt (pass_packet);
1718 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1719 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
1720 if (rs->last_pass_packet)
1721 xfree (rs->last_pass_packet);
1722 rs->last_pass_packet = pass_packet;
89be2091
DJ
1723 }
1724 else
1725 xfree (pass_packet);
1726 }
1727}
1728
9b224c5e
PA
1729/* If 'QProgramSignals' is supported, tell the remote stub what
1730 signals it should pass through to the inferior when detaching. */
1731
1732static void
daf5e9b6
TT
1733remote_program_signals (struct target_ops *self,
1734 int numsigs, unsigned char *signals)
9b224c5e 1735{
4082afcc 1736 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
1737 {
1738 char *packet, *p;
1739 int count = 0, i;
5e4a05c4 1740 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
1741
1742 gdb_assert (numsigs < 256);
1743 for (i = 0; i < numsigs; i++)
1744 {
1745 if (signals[i])
1746 count++;
1747 }
1748 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1749 strcpy (packet, "QProgramSignals:");
1750 p = packet + strlen (packet);
1751 for (i = 0; i < numsigs; i++)
1752 {
1753 if (signal_pass_state (i))
1754 {
1755 if (i >= 16)
1756 *p++ = tohex (i >> 4);
1757 *p++ = tohex (i & 15);
1758 if (count)
1759 *p++ = ';';
1760 else
1761 break;
1762 count--;
1763 }
1764 }
1765 *p = 0;
5e4a05c4
TT
1766 if (!rs->last_program_signals_packet
1767 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 1768 {
9b224c5e
PA
1769 putpkt (packet);
1770 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1771 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
1772 xfree (rs->last_program_signals_packet);
1773 rs->last_program_signals_packet = packet;
9b224c5e
PA
1774 }
1775 else
1776 xfree (packet);
1777 }
1778}
1779
79d7f229
PA
1780/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1781 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1782 thread. If GEN is set, set the general thread, if not, then set
1783 the step/continue thread. */
c906108c 1784static void
79d7f229 1785set_thread (struct ptid ptid, int gen)
c906108c 1786{
d01949b6 1787 struct remote_state *rs = get_remote_state ();
47f8a51d 1788 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 1789 char *buf = rs->buf;
79d7f229 1790 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 1791
79d7f229 1792 if (ptid_equal (state, ptid))
c906108c
SS
1793 return;
1794
79d7f229
PA
1795 *buf++ = 'H';
1796 *buf++ = gen ? 'g' : 'c';
1797 if (ptid_equal (ptid, magic_null_ptid))
1798 xsnprintf (buf, endbuf - buf, "0");
1799 else if (ptid_equal (ptid, any_thread_ptid))
1800 xsnprintf (buf, endbuf - buf, "0");
1801 else if (ptid_equal (ptid, minus_one_ptid))
1802 xsnprintf (buf, endbuf - buf, "-1");
1803 else
82f73884 1804 write_ptid (buf, endbuf, ptid);
79d7f229 1805 putpkt (rs->buf);
6d820c5c 1806 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 1807 if (gen)
47f8a51d 1808 rs->general_thread = ptid;
c906108c 1809 else
47f8a51d 1810 rs->continue_thread = ptid;
c906108c 1811}
79d7f229
PA
1812
1813static void
1814set_general_thread (struct ptid ptid)
1815{
1816 set_thread (ptid, 1);
1817}
1818
1819static void
1820set_continue_thread (struct ptid ptid)
1821{
1822 set_thread (ptid, 0);
1823}
1824
3c9c4b83
PA
1825/* Change the remote current process. Which thread within the process
1826 ends up selected isn't important, as long as it is the same process
1827 as what INFERIOR_PTID points to.
1828
1829 This comes from that fact that there is no explicit notion of
1830 "selected process" in the protocol. The selected process for
1831 general operations is the process the selected general thread
1832 belongs to. */
1833
1834static void
1835set_general_process (void)
1836{
1837 struct remote_state *rs = get_remote_state ();
1838
1839 /* If the remote can't handle multiple processes, don't bother. */
901f9912 1840 if (!rs->extended || !remote_multi_process_p (rs))
3c9c4b83
PA
1841 return;
1842
1843 /* We only need to change the remote current thread if it's pointing
1844 at some other process. */
47f8a51d 1845 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
1846 set_general_thread (inferior_ptid);
1847}
1848
c906108c 1849\f
79d7f229
PA
1850/* Return nonzero if the thread PTID is still alive on the remote
1851 system. */
c906108c
SS
1852
1853static int
28439f5e 1854remote_thread_alive (struct target_ops *ops, ptid_t ptid)
c906108c 1855{
6d820c5c 1856 struct remote_state *rs = get_remote_state ();
82f73884 1857 char *p, *endp;
c906108c 1858
c0a2216e
PA
1859 if (ptid_equal (ptid, magic_null_ptid))
1860 /* The main thread is always alive. */
1861 return 1;
1862
ba348170 1863 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
1864 /* The main thread is always alive. This can happen after a
1865 vAttach, if the remote side doesn't support
1866 multi-threading. */
1867 return 1;
1868
82f73884
PA
1869 p = rs->buf;
1870 endp = rs->buf + get_remote_packet_size ();
1871
1872 *p++ = 'T';
1873 write_ptid (p, endp, ptid);
1874
2e9f7625 1875 putpkt (rs->buf);
6d820c5c 1876 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 1877 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
1878}
1879
1880/* About these extended threadlist and threadinfo packets. They are
1881 variable length packets but, the fields within them are often fixed
1882 length. They are redundent enough to send over UDP as is the
1883 remote protocol in general. There is a matching unit test module
1884 in libstub. */
1885
23860348 1886/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 1887 libstub protocol encoding, and remote.c. It is not particularly
23860348 1888 changable. */
cce74817
JM
1889
1890/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 1891 Plan to fix this. */
cce74817 1892
23860348 1893typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 1894
9d1f7ab2 1895/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 1896 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
1897
1898struct gdb_ext_thread_info
c5aa993b 1899 {
23860348 1900 threadref threadid; /* External form of thread reference. */
2bc416ba 1901 int active; /* Has state interesting to GDB?
23860348 1902 regs, stack. */
2bc416ba 1903 char display[256]; /* Brief state display, name,
cedea757 1904 blocked/suspended. */
23860348 1905 char shortname[32]; /* To be used to name threads. */
2bc416ba 1906 char more_display[256]; /* Long info, statistics, queue depth,
23860348 1907 whatever. */
c5aa993b 1908 };
cce74817
JM
1909
1910/* The volume of remote transfers can be limited by submitting
1911 a mask containing bits specifying the desired information.
1912 Use a union of these values as the 'selection' parameter to
0df8b418 1913 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
1914
1915#define TAG_THREADID 1
1916#define TAG_EXISTS 2
1917#define TAG_DISPLAY 4
1918#define TAG_THREADNAME 8
c5aa993b 1919#define TAG_MOREDISPLAY 16
cce74817 1920
23860348 1921#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 1922
a14ed312 1923static char *unpack_nibble (char *buf, int *val);
cce74817 1924
a14ed312 1925static char *unpack_byte (char *buf, int *value);
cce74817 1926
a14ed312 1927static char *pack_int (char *buf, int value);
cce74817 1928
a14ed312 1929static char *unpack_int (char *buf, int *value);
cce74817 1930
a14ed312 1931static char *unpack_string (char *src, char *dest, int length);
cce74817 1932
23860348 1933static char *pack_threadid (char *pkt, threadref *id);
cce74817 1934
23860348 1935static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 1936
23860348 1937void int_to_threadref (threadref *id, int value);
cce74817 1938
23860348 1939static int threadref_to_int (threadref *ref);
cce74817 1940
23860348 1941static void copy_threadref (threadref *dest, threadref *src);
cce74817 1942
23860348 1943static int threadmatch (threadref *dest, threadref *src);
cce74817 1944
2bc416ba 1945static char *pack_threadinfo_request (char *pkt, int mode,
23860348 1946 threadref *id);
cce74817 1947
a14ed312 1948static int remote_unpack_thread_info_response (char *pkt,
23860348 1949 threadref *expectedref,
a14ed312
KB
1950 struct gdb_ext_thread_info
1951 *info);
cce74817
JM
1952
1953
2bc416ba 1954static int remote_get_threadinfo (threadref *threadid,
23860348 1955 int fieldset, /*TAG mask */
a14ed312 1956 struct gdb_ext_thread_info *info);
cce74817 1957
a14ed312
KB
1958static char *pack_threadlist_request (char *pkt, int startflag,
1959 int threadcount,
23860348 1960 threadref *nextthread);
cce74817 1961
a14ed312
KB
1962static int parse_threadlist_response (char *pkt,
1963 int result_limit,
23860348 1964 threadref *original_echo,
2bc416ba 1965 threadref *resultlist,
23860348 1966 int *doneflag);
cce74817 1967
a14ed312 1968static int remote_get_threadlist (int startflag,
23860348 1969 threadref *nextthread,
a14ed312
KB
1970 int result_limit,
1971 int *done,
2bc416ba 1972 int *result_count,
23860348 1973 threadref *threadlist);
cce74817 1974
23860348 1975typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 1976
a14ed312
KB
1977static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1978 void *context, int looplimit);
cce74817 1979
23860348 1980static int remote_newthread_step (threadref *ref, void *context);
cce74817 1981
82f73884
PA
1982
1983/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
1984 buffer we're allowed to write to. Returns
1985 BUF+CHARACTERS_WRITTEN. */
1986
1987static char *
1988write_ptid (char *buf, const char *endbuf, ptid_t ptid)
1989{
1990 int pid, tid;
1991 struct remote_state *rs = get_remote_state ();
1992
1993 if (remote_multi_process_p (rs))
1994 {
1995 pid = ptid_get_pid (ptid);
1996 if (pid < 0)
1997 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
1998 else
1999 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2000 }
ba348170 2001 tid = ptid_get_lwp (ptid);
82f73884
PA
2002 if (tid < 0)
2003 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2004 else
2005 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2006
2007 return buf;
2008}
2009
2010/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2011 passed the last parsed char. Returns null_ptid on error. */
2012
2013static ptid_t
2014read_ptid (char *buf, char **obuf)
2015{
2016 char *p = buf;
2017 char *pp;
2018 ULONGEST pid = 0, tid = 0;
82f73884
PA
2019
2020 if (*p == 'p')
2021 {
2022 /* Multi-process ptid. */
2023 pp = unpack_varlen_hex (p + 1, &pid);
2024 if (*pp != '.')
b37520b6 2025 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2026
2027 p = pp;
2028 pp = unpack_varlen_hex (p + 1, &tid);
2029 if (obuf)
2030 *obuf = pp;
ba348170 2031 return ptid_build (pid, tid, 0);
82f73884
PA
2032 }
2033
2034 /* No multi-process. Just a tid. */
2035 pp = unpack_varlen_hex (p, &tid);
2036
2037 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2038 what's in inferior_ptid, unless it's null at this point. If so,
2039 then since there's no way to know the pid of the reported
2040 threads, use the magic number. */
2041 if (ptid_equal (inferior_ptid, null_ptid))
2042 pid = ptid_get_pid (magic_null_ptid);
2043 else
2044 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2045
2046 if (obuf)
2047 *obuf = pp;
ba348170 2048 return ptid_build (pid, tid, 0);
82f73884
PA
2049}
2050
c906108c 2051static int
fba45db2 2052stubhex (int ch)
c906108c
SS
2053{
2054 if (ch >= 'a' && ch <= 'f')
2055 return ch - 'a' + 10;
2056 if (ch >= '0' && ch <= '9')
2057 return ch - '0';
2058 if (ch >= 'A' && ch <= 'F')
2059 return ch - 'A' + 10;
2060 return -1;
2061}
2062
2063static int
fba45db2 2064stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2065{
2066 int nibble;
2067 int retval = 0;
2068
2069 while (fieldlength)
2070 {
2071 nibble = stubhex (*buff++);
2072 retval |= nibble;
2073 fieldlength--;
2074 if (fieldlength)
2075 retval = retval << 4;
2076 }
2077 return retval;
2078}
2079
c906108c 2080static char *
fba45db2 2081unpack_nibble (char *buf, int *val)
c906108c 2082{
b7589f7d 2083 *val = fromhex (*buf++);
c906108c
SS
2084 return buf;
2085}
2086
c906108c 2087static char *
fba45db2 2088unpack_byte (char *buf, int *value)
c906108c
SS
2089{
2090 *value = stub_unpack_int (buf, 2);
2091 return buf + 2;
2092}
2093
2094static char *
fba45db2 2095pack_int (char *buf, int value)
c906108c
SS
2096{
2097 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2098 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2099 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2100 buf = pack_hex_byte (buf, (value & 0xff));
2101 return buf;
2102}
2103
2104static char *
fba45db2 2105unpack_int (char *buf, int *value)
c906108c
SS
2106{
2107 *value = stub_unpack_int (buf, 8);
2108 return buf + 8;
2109}
2110
23860348 2111#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2112static char *pack_string (char *pkt, char *string);
c906108c
SS
2113
2114static char *
fba45db2 2115pack_string (char *pkt, char *string)
c906108c
SS
2116{
2117 char ch;
2118 int len;
2119
2120 len = strlen (string);
2121 if (len > 200)
23860348 2122 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2123 pkt = pack_hex_byte (pkt, len);
2124 while (len-- > 0)
2125 {
2126 ch = *string++;
2127 if ((ch == '\0') || (ch == '#'))
23860348 2128 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2129 *pkt++ = ch;
2130 }
2131 return pkt;
2132}
2133#endif /* 0 (unused) */
2134
2135static char *
fba45db2 2136unpack_string (char *src, char *dest, int length)
c906108c
SS
2137{
2138 while (length--)
2139 *dest++ = *src++;
2140 *dest = '\0';
2141 return src;
2142}
2143
2144static char *
fba45db2 2145pack_threadid (char *pkt, threadref *id)
c906108c
SS
2146{
2147 char *limit;
2148 unsigned char *altid;
2149
2150 altid = (unsigned char *) id;
2151 limit = pkt + BUF_THREAD_ID_SIZE;
2152 while (pkt < limit)
2153 pkt = pack_hex_byte (pkt, *altid++);
2154 return pkt;
2155}
2156
2157
2158static char *
fba45db2 2159unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2160{
2161 char *altref;
2162 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2163 int x, y;
2164
2165 altref = (char *) id;
2166
2167 while (inbuf < limit)
2168 {
2169 x = stubhex (*inbuf++);
2170 y = stubhex (*inbuf++);
2171 *altref++ = (x << 4) | y;
2172 }
2173 return inbuf;
2174}
2175
2176/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2177 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2178 to use 64bit thread references internally. This is an adapter
2179 function. */
2180
2181void
fba45db2 2182int_to_threadref (threadref *id, int value)
c906108c
SS
2183{
2184 unsigned char *scan;
2185
2186 scan = (unsigned char *) id;
2187 {
2188 int i = 4;
2189 while (i--)
2190 *scan++ = 0;
2191 }
2192 *scan++ = (value >> 24) & 0xff;
2193 *scan++ = (value >> 16) & 0xff;
2194 *scan++ = (value >> 8) & 0xff;
2195 *scan++ = (value & 0xff);
2196}
2197
2198static int
fba45db2 2199threadref_to_int (threadref *ref)
c906108c
SS
2200{
2201 int i, value = 0;
2202 unsigned char *scan;
2203
cfd77fa1 2204 scan = *ref;
c906108c
SS
2205 scan += 4;
2206 i = 4;
2207 while (i-- > 0)
2208 value = (value << 8) | ((*scan++) & 0xff);
2209 return value;
2210}
2211
2212static void
fba45db2 2213copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2214{
2215 int i;
2216 unsigned char *csrc, *cdest;
2217
2218 csrc = (unsigned char *) src;
2219 cdest = (unsigned char *) dest;
2220 i = 8;
2221 while (i--)
2222 *cdest++ = *csrc++;
2223}
2224
2225static int
fba45db2 2226threadmatch (threadref *dest, threadref *src)
c906108c 2227{
23860348 2228 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2229#if 0
2230 unsigned char *srcp, *destp;
2231 int i, result;
2232 srcp = (char *) src;
2233 destp = (char *) dest;
2234
2235 result = 1;
2236 while (i-- > 0)
2237 result &= (*srcp++ == *destp++) ? 1 : 0;
2238 return result;
2239#endif
2240 return 1;
2241}
2242
2243/*
c5aa993b
JM
2244 threadid:1, # always request threadid
2245 context_exists:2,
2246 display:4,
2247 unique_name:8,
2248 more_display:16
2249 */
c906108c
SS
2250
2251/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2252
2253static char *
fba45db2 2254pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2255{
23860348
MS
2256 *pkt++ = 'q'; /* Info Query */
2257 *pkt++ = 'P'; /* process or thread info */
2258 pkt = pack_int (pkt, mode); /* mode */
c906108c 2259 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2260 *pkt = '\0'; /* terminate */
c906108c
SS
2261 return pkt;
2262}
2263
23860348 2264/* These values tag the fields in a thread info response packet. */
c906108c 2265/* Tagging the fields allows us to request specific fields and to
23860348 2266 add more fields as time goes by. */
c906108c 2267
23860348 2268#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2269#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2270 fetch registers and its stack? */
c5aa993b 2271#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2272#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2273#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2274 the process. */
c906108c
SS
2275
2276static int
fba45db2
KB
2277remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2278 struct gdb_ext_thread_info *info)
c906108c 2279{
d01949b6 2280 struct remote_state *rs = get_remote_state ();
c906108c 2281 int mask, length;
cfd77fa1 2282 int tag;
c906108c 2283 threadref ref;
6d820c5c 2284 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2285 int retval = 1;
2286
23860348 2287 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2288 info->active = 0;
2289 info->display[0] = '\0';
2290 info->shortname[0] = '\0';
2291 info->more_display[0] = '\0';
2292
23860348
MS
2293 /* Assume the characters indicating the packet type have been
2294 stripped. */
c906108c
SS
2295 pkt = unpack_int (pkt, &mask); /* arg mask */
2296 pkt = unpack_threadid (pkt, &ref);
2297
2298 if (mask == 0)
8a3fe4f8 2299 warning (_("Incomplete response to threadinfo request."));
c906108c 2300 if (!threadmatch (&ref, expectedref))
23860348 2301 { /* This is an answer to a different request. */
8a3fe4f8 2302 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2303 return 0;
2304 }
2305 copy_threadref (&info->threadid, &ref);
2306
23860348 2307 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2308
23860348
MS
2309 /* Packets are terminated with nulls. */
2310 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2311 {
2312 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2313 pkt = unpack_byte (pkt, &length); /* length */
2314 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2315 {
8a3fe4f8 2316 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2317 retval = 0;
2318 break;
2319 }
2320 if (tag == TAG_THREADID)
2321 {
2322 if (length != 16)
2323 {
8a3fe4f8 2324 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2325 retval = 0;
2326 break;
2327 }
2328 pkt = unpack_threadid (pkt, &ref);
2329 mask = mask & ~TAG_THREADID;
2330 continue;
2331 }
2332 if (tag == TAG_EXISTS)
2333 {
2334 info->active = stub_unpack_int (pkt, length);
2335 pkt += length;
2336 mask = mask & ~(TAG_EXISTS);
2337 if (length > 8)
2338 {
8a3fe4f8 2339 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2340 retval = 0;
2341 break;
2342 }
2343 continue;
2344 }
2345 if (tag == TAG_THREADNAME)
2346 {
2347 pkt = unpack_string (pkt, &info->shortname[0], length);
2348 mask = mask & ~TAG_THREADNAME;
2349 continue;
2350 }
2351 if (tag == TAG_DISPLAY)
2352 {
2353 pkt = unpack_string (pkt, &info->display[0], length);
2354 mask = mask & ~TAG_DISPLAY;
2355 continue;
2356 }
2357 if (tag == TAG_MOREDISPLAY)
2358 {
2359 pkt = unpack_string (pkt, &info->more_display[0], length);
2360 mask = mask & ~TAG_MOREDISPLAY;
2361 continue;
2362 }
8a3fe4f8 2363 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2364 break; /* Not a tag we know about. */
c906108c
SS
2365 }
2366 return retval;
2367}
2368
2369static int
fba45db2
KB
2370remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2371 struct gdb_ext_thread_info *info)
c906108c 2372{
d01949b6 2373 struct remote_state *rs = get_remote_state ();
c906108c 2374 int result;
c906108c 2375
2e9f7625
DJ
2376 pack_threadinfo_request (rs->buf, fieldset, threadid);
2377 putpkt (rs->buf);
6d820c5c 2378 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2379
2380 if (rs->buf[0] == '\0')
2381 return 0;
2382
2e9f7625 2383 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2384 threadid, info);
c906108c
SS
2385 return result;
2386}
2387
c906108c
SS
2388/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2389
2390static char *
fba45db2
KB
2391pack_threadlist_request (char *pkt, int startflag, int threadcount,
2392 threadref *nextthread)
c906108c
SS
2393{
2394 *pkt++ = 'q'; /* info query packet */
2395 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2396 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2397 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2398 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2399 *pkt = '\0';
2400 return pkt;
2401}
2402
2403/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2404
2405static int
fba45db2
KB
2406parse_threadlist_response (char *pkt, int result_limit,
2407 threadref *original_echo, threadref *resultlist,
2408 int *doneflag)
c906108c 2409{
d01949b6 2410 struct remote_state *rs = get_remote_state ();
c906108c
SS
2411 char *limit;
2412 int count, resultcount, done;
2413
2414 resultcount = 0;
2415 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2416 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2417 /* done parse past here */
c906108c
SS
2418 pkt = unpack_byte (pkt, &count); /* count field */
2419 pkt = unpack_nibble (pkt, &done);
2420 /* The first threadid is the argument threadid. */
2421 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2422 while ((count-- > 0) && (pkt < limit))
2423 {
2424 pkt = unpack_threadid (pkt, resultlist++);
2425 if (resultcount++ >= result_limit)
2426 break;
2427 }
2428 if (doneflag)
2429 *doneflag = done;
2430 return resultcount;
2431}
2432
2433static int
fba45db2
KB
2434remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2435 int *done, int *result_count, threadref *threadlist)
c906108c 2436{
d01949b6 2437 struct remote_state *rs = get_remote_state ();
c906108c
SS
2438 int result = 1;
2439
23860348 2440 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2441 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2442 >= get_remote_packet_size ())
ea9c271d 2443 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2444
6d820c5c
DJ
2445 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2446 putpkt (rs->buf);
2447 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2448
d8f2712d 2449 if (*rs->buf == '\0')
21bce120 2450 return 0;
d8f2712d
VP
2451 else
2452 *result_count =
0d031856
TT
2453 parse_threadlist_response (rs->buf + 2, result_limit,
2454 &rs->echo_nextthread, threadlist, done);
c906108c 2455
0d031856 2456 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2457 {
23860348
MS
2458 /* FIXME: This is a good reason to drop the packet. */
2459 /* Possably, there is a duplicate response. */
c906108c
SS
2460 /* Possabilities :
2461 retransmit immediatly - race conditions
2462 retransmit after timeout - yes
2463 exit
2464 wait for packet, then exit
2465 */
8a3fe4f8 2466 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2467 return 0; /* I choose simply exiting. */
c906108c
SS
2468 }
2469 if (*result_count <= 0)
2470 {
2471 if (*done != 1)
2472 {
8a3fe4f8 2473 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2474 result = 0;
2475 }
2476 return result; /* break; */
2477 }
2478 if (*result_count > result_limit)
2479 {
2480 *result_count = 0;
8a3fe4f8 2481 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2482 return 0;
2483 }
2484 return result;
2485}
2486
23860348
MS
2487/* This is the interface between remote and threads, remotes upper
2488 interface. */
c906108c
SS
2489
2490/* remote_find_new_threads retrieves the thread list and for each
2491 thread in the list, looks up the thread in GDB's internal list,
79d7f229 2492 adding the thread if it does not already exist. This involves
c906108c
SS
2493 getting partial thread lists from the remote target so, polling the
2494 quit_flag is required. */
2495
2496
c906108c 2497static int
fba45db2
KB
2498remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2499 int looplimit)
c906108c 2500{
0d031856 2501 struct remote_state *rs = get_remote_state ();
c906108c
SS
2502 int done, i, result_count;
2503 int startflag = 1;
2504 int result = 1;
2505 int loopcount = 0;
c906108c
SS
2506
2507 done = 0;
2508 while (!done)
2509 {
2510 if (loopcount++ > looplimit)
2511 {
2512 result = 0;
8a3fe4f8 2513 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2514 break;
2515 }
0d031856
TT
2516 if (!remote_get_threadlist (startflag, &rs->nextthread,
2517 MAXTHREADLISTRESULTS,
2518 &done, &result_count, rs->resultthreadlist))
c906108c
SS
2519 {
2520 result = 0;
2521 break;
2522 }
23860348 2523 /* Clear for later iterations. */
c906108c
SS
2524 startflag = 0;
2525 /* Setup to resume next batch of thread references, set nextthread. */
2526 if (result_count >= 1)
0d031856
TT
2527 copy_threadref (&rs->nextthread,
2528 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2529 i = 0;
2530 while (result_count--)
0d031856 2531 if (!(result = (*stepfunction) (&rs->resultthreadlist[i++], context)))
c906108c
SS
2532 break;
2533 }
2534 return result;
2535}
2536
2537static int
fba45db2 2538remote_newthread_step (threadref *ref, void *context)
c906108c 2539{
79d7f229 2540 int pid = ptid_get_pid (inferior_ptid);
ba348170 2541 ptid_t ptid = ptid_build (pid, threadref_to_int (ref), 0);
39f77062
KB
2542
2543 if (!in_thread_list (ptid))
2544 add_thread (ptid);
c906108c
SS
2545 return 1; /* continue iterator */
2546}
2547
2548#define CRAZY_MAX_THREADS 1000
2549
39f77062
KB
2550static ptid_t
2551remote_current_thread (ptid_t oldpid)
c906108c 2552{
d01949b6 2553 struct remote_state *rs = get_remote_state ();
c906108c
SS
2554
2555 putpkt ("qC");
6d820c5c 2556 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2557 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
82f73884 2558 return read_ptid (&rs->buf[2], NULL);
c906108c
SS
2559 else
2560 return oldpid;
2561}
2562
802188a7
RM
2563/* Find new threads for info threads command.
2564 * Original version, using John Metzler's thread protocol.
9d1f7ab2 2565 */
cce74817
JM
2566
2567static void
fba45db2 2568remote_find_new_threads (void)
c906108c 2569{
c5aa993b
JM
2570 remote_threadlist_iterator (remote_newthread_step, 0,
2571 CRAZY_MAX_THREADS);
c906108c
SS
2572}
2573
dc146f7c
VP
2574#if defined(HAVE_LIBEXPAT)
2575
2576typedef struct thread_item
2577{
2578 ptid_t ptid;
2579 char *extra;
2580 int core;
2581} thread_item_t;
2582DEF_VEC_O(thread_item_t);
2583
2584struct threads_parsing_context
2585{
2586 VEC (thread_item_t) *items;
2587};
2588
2589static void
2590start_thread (struct gdb_xml_parser *parser,
2591 const struct gdb_xml_element *element,
2592 void *user_data, VEC(gdb_xml_value_s) *attributes)
2593{
2594 struct threads_parsing_context *data = user_data;
2595
2596 struct thread_item item;
2597 char *id;
3d2c1d41 2598 struct gdb_xml_value *attr;
dc146f7c 2599
3d2c1d41 2600 id = xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
2601 item.ptid = read_ptid (id, NULL);
2602
3d2c1d41
PA
2603 attr = xml_find_attribute (attributes, "core");
2604 if (attr != NULL)
2605 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
2606 else
2607 item.core = -1;
2608
2609 item.extra = 0;
2610
2611 VEC_safe_push (thread_item_t, data->items, &item);
2612}
2613
2614static void
2615end_thread (struct gdb_xml_parser *parser,
2616 const struct gdb_xml_element *element,
2617 void *user_data, const char *body_text)
2618{
2619 struct threads_parsing_context *data = user_data;
2620
2621 if (body_text && *body_text)
2ae2a0b7 2622 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
2623}
2624
2625const struct gdb_xml_attribute thread_attributes[] = {
2626 { "id", GDB_XML_AF_NONE, NULL, NULL },
2627 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2628 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2629};
2630
2631const struct gdb_xml_element thread_children[] = {
2632 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2633};
2634
2635const struct gdb_xml_element threads_children[] = {
2636 { "thread", thread_attributes, thread_children,
2637 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2638 start_thread, end_thread },
2639 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2640};
2641
2642const struct gdb_xml_element threads_elements[] = {
2643 { "threads", NULL, threads_children,
2644 GDB_XML_EF_NONE, NULL, NULL },
2645 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2646};
2647
02357a4a
PA
2648/* Discard the contents of the constructed thread info context. */
2649
2650static void
2651clear_threads_parsing_context (void *p)
2652{
2653 struct threads_parsing_context *context = p;
2654 int i;
2655 struct thread_item *item;
2656
2657 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2658 xfree (item->extra);
2659
2660 VEC_free (thread_item_t, context->items);
2661}
2662
dc146f7c
VP
2663#endif
2664
9d1f7ab2
MS
2665/*
2666 * Find all threads for info threads command.
2667 * Uses new thread protocol contributed by Cisco.
2668 * Falls back and attempts to use the older method (above)
2669 * if the target doesn't respond to the new method.
2670 */
2671
0f71a2f6 2672static void
28439f5e 2673remote_threads_info (struct target_ops *ops)
0f71a2f6 2674{
d01949b6 2675 struct remote_state *rs = get_remote_state ();
085dd6e6 2676 char *bufp;
79d7f229 2677 ptid_t new_thread;
0f71a2f6 2678
5d93a237 2679 if (rs->remote_desc == 0) /* paranoia */
8a3fe4f8 2680 error (_("Command can only be used when connected to the remote target."));
0f71a2f6 2681
dc146f7c 2682#if defined(HAVE_LIBEXPAT)
4082afcc 2683 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
2684 {
2685 char *xml = target_read_stralloc (&current_target,
2686 TARGET_OBJECT_THREADS, NULL);
2687
2688 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 2689
dc146f7c
VP
2690 if (xml && *xml)
2691 {
dc146f7c 2692 struct threads_parsing_context context;
dc146f7c 2693
efc0eabd
PA
2694 context.items = NULL;
2695 make_cleanup (clear_threads_parsing_context, &context);
dc146f7c 2696
efc0eabd
PA
2697 if (gdb_xml_parse_quick (_("threads"), "threads.dtd",
2698 threads_elements, xml, &context) == 0)
dc146f7c
VP
2699 {
2700 int i;
2701 struct thread_item *item;
2702
3e43a32a
MS
2703 for (i = 0;
2704 VEC_iterate (thread_item_t, context.items, i, item);
2705 ++i)
dc146f7c
VP
2706 {
2707 if (!ptid_equal (item->ptid, null_ptid))
2708 {
2709 struct private_thread_info *info;
2710 /* In non-stop mode, we assume new found threads
2711 are running until proven otherwise with a
2712 stop reply. In all-stop, we can only get
2713 here if all threads are stopped. */
2714 int running = non_stop ? 1 : 0;
2715
2716 remote_notice_new_inferior (item->ptid, running);
2717
2718 info = demand_private_info (item->ptid);
2719 info->core = item->core;
2720 info->extra = item->extra;
02357a4a 2721 item->extra = NULL;
dc146f7c 2722 }
dc146f7c
VP
2723 }
2724 }
dc146f7c
VP
2725 }
2726
2727 do_cleanups (back_to);
2728 return;
2729 }
2730#endif
2731
b80fafe3 2732 if (rs->use_threadinfo_query)
9d1f7ab2
MS
2733 {
2734 putpkt ("qfThreadInfo");
6d820c5c 2735 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2736 bufp = rs->buf;
9d1f7ab2 2737 if (bufp[0] != '\0') /* q packet recognized */
802188a7 2738 {
44d594fd
PA
2739 struct cleanup *old_chain;
2740 char *saved_reply;
2741
2742 /* remote_notice_new_inferior (in the loop below) may make
2743 new RSP calls, which clobber rs->buf. Work with a
2744 copy. */
2745 bufp = saved_reply = xstrdup (rs->buf);
2746 old_chain = make_cleanup (free_current_contents, &saved_reply);
2747
9d1f7ab2
MS
2748 while (*bufp++ == 'm') /* reply contains one or more TID */
2749 {
2750 do
2751 {
82f73884 2752 new_thread = read_ptid (bufp, &bufp);
1941c569 2753 if (!ptid_equal (new_thread, null_ptid))
82f73884 2754 {
74531fed 2755 /* In non-stop mode, we assume new found threads
1941c569 2756 are running until proven otherwise with a
74531fed
PA
2757 stop reply. In all-stop, we can only get
2758 here if all threads are stopped. */
1941c569
PA
2759 int running = non_stop ? 1 : 0;
2760
2761 remote_notice_new_inferior (new_thread, running);
82f73884 2762 }
9d1f7ab2
MS
2763 }
2764 while (*bufp++ == ','); /* comma-separated list */
44d594fd 2765 free_current_contents (&saved_reply);
9d1f7ab2 2766 putpkt ("qsThreadInfo");
6d820c5c 2767 getpkt (&rs->buf, &rs->buf_size, 0);
44d594fd 2768 bufp = saved_reply = xstrdup (rs->buf);
9d1f7ab2 2769 }
44d594fd 2770 do_cleanups (old_chain);
9d1f7ab2
MS
2771 return; /* done */
2772 }
2773 }
2774
74531fed
PA
2775 /* Only qfThreadInfo is supported in non-stop mode. */
2776 if (non_stop)
2777 return;
2778
23860348 2779 /* Else fall back to old method based on jmetzler protocol. */
b80fafe3 2780 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
2781 remote_find_new_threads ();
2782 return;
2783}
2784
802188a7 2785/*
9d1f7ab2
MS
2786 * Collect a descriptive string about the given thread.
2787 * The target may say anything it wants to about the thread
2788 * (typically info about its blocked / runnable state, name, etc.).
2789 * This string will appear in the info threads display.
802188a7 2790 *
9d1f7ab2
MS
2791 * Optional: targets are not required to implement this function.
2792 */
2793
2794static char *
c15906d8 2795remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 2796{
d01949b6 2797 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
2798 int result;
2799 int set;
2800 threadref id;
2801 struct gdb_ext_thread_info threadinfo;
23860348 2802 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
2803 int n = 0; /* position in display_buf */
2804
5d93a237 2805 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 2806 internal_error (__FILE__, __LINE__,
e2e0b3e5 2807 _("remote_threads_extra_info"));
9d1f7ab2 2808
60e569b9 2809 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 2810 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
2811 /* This is the main thread which was added by GDB. The remote
2812 server doesn't know about it. */
2813 return NULL;
2814
4082afcc 2815 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
2816 {
2817 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 2818
dc146f7c
VP
2819 if (info && info->private)
2820 return info->private->extra;
2821 else
2822 return NULL;
2823 }
2824
b80fafe3 2825 if (rs->use_threadextra_query)
9d1f7ab2 2826 {
82f73884
PA
2827 char *b = rs->buf;
2828 char *endb = rs->buf + get_remote_packet_size ();
2829
2830 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2831 b += strlen (b);
2832 write_ptid (b, endb, tp->ptid);
2833
2e9f7625 2834 putpkt (rs->buf);
6d820c5c 2835 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2836 if (rs->buf[0] != 0)
9d1f7ab2 2837 {
2e9f7625
DJ
2838 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2839 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 2840 display_buf [result] = '\0';
9d1f7ab2
MS
2841 return display_buf;
2842 }
0f71a2f6 2843 }
9d1f7ab2
MS
2844
2845 /* If the above query fails, fall back to the old method. */
b80fafe3 2846 rs->use_threadextra_query = 0;
9d1f7ab2
MS
2847 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2848 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 2849 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
2850 if (remote_get_threadinfo (&id, set, &threadinfo))
2851 if (threadinfo.active)
0f71a2f6 2852 {
9d1f7ab2 2853 if (*threadinfo.shortname)
2bc416ba 2854 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 2855 " Name: %s,", threadinfo.shortname);
9d1f7ab2 2856 if (*threadinfo.display)
2bc416ba 2857 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 2858 " State: %s,", threadinfo.display);
9d1f7ab2 2859 if (*threadinfo.more_display)
2bc416ba 2860 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 2861 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
2862
2863 if (n > 0)
c5aa993b 2864 {
23860348 2865 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
2866 if (',' == display_buf[n-1])
2867 display_buf[n-1] = ' ';
2868 return display_buf;
c5aa993b 2869 }
0f71a2f6 2870 }
9d1f7ab2 2871 return NULL;
0f71a2f6 2872}
c906108c 2873\f
c5aa993b 2874
0fb4aa4b 2875static int
61fc905d 2876remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
2877 struct static_tracepoint_marker *marker)
2878{
2879 struct remote_state *rs = get_remote_state ();
2880 char *p = rs->buf;
2881
bba74b36 2882 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
2883 p += strlen (p);
2884 p += hexnumstr (p, addr);
2885 putpkt (rs->buf);
2886 getpkt (&rs->buf, &rs->buf_size, 0);
2887 p = rs->buf;
2888
2889 if (*p == 'E')
2890 error (_("Remote failure reply: %s"), p);
2891
2892 if (*p++ == 'm')
2893 {
2894 parse_static_tracepoint_marker_definition (p, &p, marker);
2895 return 1;
2896 }
2897
2898 return 0;
2899}
2900
0fb4aa4b 2901static VEC(static_tracepoint_marker_p) *
c686c57f
TT
2902remote_static_tracepoint_markers_by_strid (struct target_ops *self,
2903 const char *strid)
0fb4aa4b
PA
2904{
2905 struct remote_state *rs = get_remote_state ();
2906 VEC(static_tracepoint_marker_p) *markers = NULL;
2907 struct static_tracepoint_marker *marker = NULL;
2908 struct cleanup *old_chain;
2909 char *p;
2910
2911 /* Ask for a first packet of static tracepoint marker
2912 definition. */
2913 putpkt ("qTfSTM");
2914 getpkt (&rs->buf, &rs->buf_size, 0);
2915 p = rs->buf;
2916 if (*p == 'E')
2917 error (_("Remote failure reply: %s"), p);
2918
2919 old_chain = make_cleanup (free_current_marker, &marker);
2920
2921 while (*p++ == 'm')
2922 {
2923 if (marker == NULL)
2924 marker = XCNEW (struct static_tracepoint_marker);
2925
2926 do
2927 {
2928 parse_static_tracepoint_marker_definition (p, &p, marker);
2929
2930 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
2931 {
2932 VEC_safe_push (static_tracepoint_marker_p,
2933 markers, marker);
2934 marker = NULL;
2935 }
2936 else
2937 {
2938 release_static_tracepoint_marker (marker);
2939 memset (marker, 0, sizeof (*marker));
2940 }
2941 }
2942 while (*p++ == ','); /* comma-separated list */
2943 /* Ask for another packet of static tracepoint definition. */
2944 putpkt ("qTsSTM");
2945 getpkt (&rs->buf, &rs->buf_size, 0);
2946 p = rs->buf;
2947 }
2948
2949 do_cleanups (old_chain);
2950 return markers;
2951}
2952
2953\f
10760264
JB
2954/* Implement the to_get_ada_task_ptid function for the remote targets. */
2955
2956static ptid_t
1e6b91a4 2957remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 2958{
ba348170 2959 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
2960}
2961\f
2962
24b06219 2963/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
2964
2965static void
fba45db2 2966extended_remote_restart (void)
c906108c 2967{
d01949b6 2968 struct remote_state *rs = get_remote_state ();
c906108c
SS
2969
2970 /* Send the restart command; for reasons I don't understand the
2971 remote side really expects a number after the "R". */
ea9c271d 2972 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 2973 putpkt (rs->buf);
c906108c 2974
ad9a8f3f 2975 remote_fileio_reset ();
c906108c
SS
2976}
2977\f
2978/* Clean up connection to a remote debugger. */
2979
c906108c 2980static void
de90e03d 2981remote_close (struct target_ops *self)
c906108c 2982{
5d93a237
TT
2983 struct remote_state *rs = get_remote_state ();
2984
2985 if (rs->remote_desc == NULL)
d3fd5342
PA
2986 return; /* already closed */
2987
2988 /* Make sure we leave stdin registered in the event loop, and we
2989 don't leave the async SIGINT signal handler installed. */
e3594fd1 2990 remote_terminal_ours (self);
ce5ce7ed 2991
5d93a237
TT
2992 serial_close (rs->remote_desc);
2993 rs->remote_desc = NULL;
ce5ce7ed
PA
2994
2995 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
2996 of all the inferiors and their threads we were controlling.
2997 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
2998 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 2999 inferior_ptid = null_ptid;
f67fd822 3000 discard_all_inferiors ();
ce5ce7ed 3001
f48ff2a7
YQ
3002 /* We are closing the remote target, so we should discard
3003 everything of this target. */
bcc75809 3004 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3005
3006 if (remote_async_inferior_event_token)
3007 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3008
5965e028 3009 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3010
3011 trace_reset_local_state ();
c906108c
SS
3012}
3013
23860348 3014/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3015
3016static void
fba45db2 3017get_offsets (void)
c906108c 3018{
d01949b6 3019 struct remote_state *rs = get_remote_state ();
2e9f7625 3020 char *buf;
085dd6e6 3021 char *ptr;
31d99776
DJ
3022 int lose, num_segments = 0, do_sections, do_segments;
3023 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3024 struct section_offsets *offs;
31d99776
DJ
3025 struct symfile_segment_data *data;
3026
3027 if (symfile_objfile == NULL)
3028 return;
c906108c
SS
3029
3030 putpkt ("qOffsets");
6d820c5c 3031 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3032 buf = rs->buf;
c906108c
SS
3033
3034 if (buf[0] == '\000')
3035 return; /* Return silently. Stub doesn't support
23860348 3036 this command. */
c906108c
SS
3037 if (buf[0] == 'E')
3038 {
8a3fe4f8 3039 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3040 return;
3041 }
3042
3043 /* Pick up each field in turn. This used to be done with scanf, but
3044 scanf will make trouble if CORE_ADDR size doesn't match
3045 conversion directives correctly. The following code will work
3046 with any size of CORE_ADDR. */
3047 text_addr = data_addr = bss_addr = 0;
3048 ptr = buf;
3049 lose = 0;
3050
3051 if (strncmp (ptr, "Text=", 5) == 0)
3052 {
3053 ptr += 5;
3054 /* Don't use strtol, could lose on big values. */
3055 while (*ptr && *ptr != ';')
3056 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3057
31d99776
DJ
3058 if (strncmp (ptr, ";Data=", 6) == 0)
3059 {
3060 ptr += 6;
3061 while (*ptr && *ptr != ';')
3062 data_addr = (data_addr << 4) + fromhex (*ptr++);
3063 }
3064 else
3065 lose = 1;
3066
3067 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
3068 {
3069 ptr += 5;
3070 while (*ptr && *ptr != ';')
3071 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3072
31d99776
DJ
3073 if (bss_addr != data_addr)
3074 warning (_("Target reported unsupported offsets: %s"), buf);
3075 }
3076 else
3077 lose = 1;
3078 }
3079 else if (strncmp (ptr, "TextSeg=", 8) == 0)
c906108c 3080 {
31d99776
DJ
3081 ptr += 8;
3082 /* Don't use strtol, could lose on big values. */
c906108c 3083 while (*ptr && *ptr != ';')
31d99776
DJ
3084 text_addr = (text_addr << 4) + fromhex (*ptr++);
3085 num_segments = 1;
3086
3087 if (strncmp (ptr, ";DataSeg=", 9) == 0)
3088 {
3089 ptr += 9;
3090 while (*ptr && *ptr != ';')
3091 data_addr = (data_addr << 4) + fromhex (*ptr++);
3092 num_segments++;
3093 }
c906108c
SS
3094 }
3095 else
3096 lose = 1;
3097
3098 if (lose)
8a3fe4f8 3099 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3100 else if (*ptr != '\0')
3101 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3102
802188a7 3103 offs = ((struct section_offsets *)
a39a16c4 3104 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3105 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3106 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3107
31d99776
DJ
3108 data = get_symfile_segment_data (symfile_objfile->obfd);
3109 do_segments = (data != NULL);
3110 do_sections = num_segments == 0;
c906108c 3111
28c32713 3112 if (num_segments > 0)
31d99776 3113 {
31d99776
DJ
3114 segments[0] = text_addr;
3115 segments[1] = data_addr;
3116 }
28c32713
JB
3117 /* If we have two segments, we can still try to relocate everything
3118 by assuming that the .text and .data offsets apply to the whole
3119 text and data segments. Convert the offsets given in the packet
3120 to base addresses for symfile_map_offsets_to_segments. */
3121 else if (data && data->num_segments == 2)
3122 {
3123 segments[0] = data->segment_bases[0] + text_addr;
3124 segments[1] = data->segment_bases[1] + data_addr;
3125 num_segments = 2;
3126 }
8d385431
DJ
3127 /* If the object file has only one segment, assume that it is text
3128 rather than data; main programs with no writable data are rare,
3129 but programs with no code are useless. Of course the code might
3130 have ended up in the data segment... to detect that we would need
3131 the permissions here. */
3132 else if (data && data->num_segments == 1)
3133 {
3134 segments[0] = data->segment_bases[0] + text_addr;
3135 num_segments = 1;
3136 }
28c32713
JB
3137 /* There's no way to relocate by segment. */
3138 else
3139 do_segments = 0;
31d99776
DJ
3140
3141 if (do_segments)
3142 {
3143 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3144 offs, num_segments, segments);
3145
3146 if (ret == 0 && !do_sections)
3e43a32a
MS
3147 error (_("Can not handle qOffsets TextSeg "
3148 "response with this symbol file"));
31d99776
DJ
3149
3150 if (ret > 0)
3151 do_sections = 0;
3152 }
c906108c 3153
9ef895d6
DJ
3154 if (data)
3155 free_symfile_segment_data (data);
31d99776
DJ
3156
3157 if (do_sections)
3158 {
3159 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3160
3e43a32a
MS
3161 /* This is a temporary kludge to force data and bss to use the
3162 same offsets because that's what nlmconv does now. The real
3163 solution requires changes to the stub and remote.c that I
3164 don't have time to do right now. */
31d99776
DJ
3165
3166 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3167 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3168 }
c906108c
SS
3169
3170 objfile_relocate (symfile_objfile, offs);
3171}
3172
74531fed
PA
3173/* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3174 threads we know are stopped already. This is used during the
3175 initial remote connection in non-stop mode --- threads that are
3176 reported as already being stopped are left stopped. */
3177
3178static int
3179set_stop_requested_callback (struct thread_info *thread, void *data)
3180{
3181 /* If we have a stop reply for this thread, it must be stopped. */
3182 if (peek_stop_reply (thread->ptid))
3183 set_stop_requested (thread->ptid, 1);
3184
3185 return 0;
3186}
3187
9a7071a8
JB
3188/* Send interrupt_sequence to remote target. */
3189static void
eeae04df 3190send_interrupt_sequence (void)
9a7071a8 3191{
5d93a237
TT
3192 struct remote_state *rs = get_remote_state ();
3193
9a7071a8 3194 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3195 remote_serial_write ("\x03", 1);
9a7071a8 3196 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3197 serial_send_break (rs->remote_desc);
9a7071a8
JB
3198 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3199 {
5d93a237 3200 serial_send_break (rs->remote_desc);
c33e31fd 3201 remote_serial_write ("g", 1);
9a7071a8
JB
3202 }
3203 else
3204 internal_error (__FILE__, __LINE__,
3205 _("Invalid value for interrupt_sequence_mode: %s."),
3206 interrupt_sequence_mode);
3207}
3208
3405876a
PA
3209
3210/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3211 and extract the PTID. Returns NULL_PTID if not found. */
3212
3213static ptid_t
3214stop_reply_extract_thread (char *stop_reply)
3215{
3216 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3217 {
3218 char *p;
3219
3220 /* Txx r:val ; r:val (...) */
3221 p = &stop_reply[3];
3222
3223 /* Look for "register" named "thread". */
3224 while (*p != '\0')
3225 {
3226 char *p1;
3227
3228 p1 = strchr (p, ':');
3229 if (p1 == NULL)
3230 return null_ptid;
3231
3232 if (strncmp (p, "thread", p1 - p) == 0)
3233 return read_ptid (++p1, &p);
3234
3235 p1 = strchr (p, ';');
3236 if (p1 == NULL)
3237 return null_ptid;
3238 p1++;
3239
3240 p = p1;
3241 }
3242 }
3243
3244 return null_ptid;
3245}
3246
b7ea362b
PA
3247/* Determine the remote side's current thread. If we have a stop
3248 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3249 "thread" register we can extract the current thread from. If not,
3250 ask the remote which is the current thread with qC. The former
3251 method avoids a roundtrip. */
3252
3253static ptid_t
3254get_current_thread (char *wait_status)
3255{
3256 ptid_t ptid;
3257
3258 /* Note we don't use remote_parse_stop_reply as that makes use of
3259 the target architecture, which we haven't yet fully determined at
3260 this point. */
3261 if (wait_status != NULL)
3262 ptid = stop_reply_extract_thread (wait_status);
3263 if (ptid_equal (ptid, null_ptid))
3264 ptid = remote_current_thread (inferior_ptid);
3265
3266 return ptid;
3267}
3268
49c62f2e
PA
3269/* Query the remote target for which is the current thread/process,
3270 add it to our tables, and update INFERIOR_PTID. The caller is
3271 responsible for setting the state such that the remote end is ready
3405876a
PA
3272 to return the current thread.
3273
3274 This function is called after handling the '?' or 'vRun' packets,
3275 whose response is a stop reply from which we can also try
3276 extracting the thread. If the target doesn't support the explicit
3277 qC query, we infer the current thread from that stop reply, passed
3278 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3279
3280static void
3405876a 3281add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3282{
3283 struct remote_state *rs = get_remote_state ();
3284 int fake_pid_p = 0;
3405876a 3285 ptid_t ptid = null_ptid;
49c62f2e
PA
3286
3287 inferior_ptid = null_ptid;
3288
b7ea362b
PA
3289 /* Now, if we have thread information, update inferior_ptid. */
3290 ptid = get_current_thread (wait_status);
3405876a 3291
49c62f2e
PA
3292 if (!ptid_equal (ptid, null_ptid))
3293 {
3294 if (!remote_multi_process_p (rs))
3295 fake_pid_p = 1;
3296
3297 inferior_ptid = ptid;
3298 }
3299 else
3300 {
3301 /* Without this, some commands which require an active target
3302 (such as kill) won't work. This variable serves (at least)
3303 double duty as both the pid of the target process (if it has
3304 such), and as a flag indicating that a target is active. */
3305 inferior_ptid = magic_null_ptid;
3306 fake_pid_p = 1;
3307 }
3308
3309 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1);
3310
3311 /* Add the main thread. */
3312 add_thread_silent (inferior_ptid);
3313}
3314
9cbc821d 3315static void
04bd08de 3316remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 3317{
c8d104ad
PA
3318 struct remote_state *rs = get_remote_state ();
3319 struct packet_config *noack_config;
2d717e4f 3320 char *wait_status = NULL;
8621d6a9 3321
23860348 3322 immediate_quit++; /* Allow user to interrupt it. */
522002f9 3323 QUIT;
c906108c 3324
9a7071a8
JB
3325 if (interrupt_on_connect)
3326 send_interrupt_sequence ();
3327
57e12211 3328 /* Ack any packet which the remote side has already sent. */
5d93a237 3329 serial_write (rs->remote_desc, "+", 1);
57e12211 3330
1e51243a
PA
3331 /* Signal other parts that we're going through the initial setup,
3332 and so things may not be stable yet. */
3333 rs->starting_up = 1;
3334
c8d104ad
PA
3335 /* The first packet we send to the target is the optional "supported
3336 packets" request. If the target can answer this, it will tell us
3337 which later probes to skip. */
3338 remote_query_supported ();
3339
d914c394 3340 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 3341 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 3342 remote_set_permissions (target);
d914c394 3343
c8d104ad
PA
3344 /* Next, we possibly activate noack mode.
3345
3346 If the QStartNoAckMode packet configuration is set to AUTO,
3347 enable noack mode if the stub reported a wish for it with
3348 qSupported.
3349
3350 If set to TRUE, then enable noack mode even if the stub didn't
3351 report it in qSupported. If the stub doesn't reply OK, the
3352 session ends with an error.
3353
3354 If FALSE, then don't activate noack mode, regardless of what the
3355 stub claimed should be the default with qSupported. */
3356
3357 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 3358 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
3359 {
3360 putpkt ("QStartNoAckMode");
3361 getpkt (&rs->buf, &rs->buf_size, 0);
3362 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3363 rs->noack_mode = 1;
3364 }
3365
04bd08de 3366 if (extended_p)
5fe04517
PA
3367 {
3368 /* Tell the remote that we are using the extended protocol. */
3369 putpkt ("!");
3370 getpkt (&rs->buf, &rs->buf_size, 0);
3371 }
3372
9b224c5e
PA
3373 /* Let the target know which signals it is allowed to pass down to
3374 the program. */
3375 update_signals_program_target ();
3376
d962ef82
DJ
3377 /* Next, if the target can specify a description, read it. We do
3378 this before anything involving memory or registers. */
3379 target_find_description ();
3380
6c95b8df
PA
3381 /* Next, now that we know something about the target, update the
3382 address spaces in the program spaces. */
3383 update_address_spaces ();
3384
50c71eaf
PA
3385 /* On OSs where the list of libraries is global to all
3386 processes, we fetch them early. */
f5656ead 3387 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 3388 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 3389
74531fed
PA
3390 if (non_stop)
3391 {
4082afcc 3392 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
3393 error (_("Non-stop mode requested, but remote "
3394 "does not support non-stop"));
74531fed
PA
3395
3396 putpkt ("QNonStop:1");
3397 getpkt (&rs->buf, &rs->buf_size, 0);
3398
3399 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3400 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
3401
3402 /* Find about threads and processes the stub is already
3403 controlling. We default to adding them in the running state.
3404 The '?' query below will then tell us about which threads are
3405 stopped. */
04bd08de 3406 remote_threads_info (target);
74531fed 3407 }
4082afcc 3408 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
3409 {
3410 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 3411 Request it explicitly. */
74531fed
PA
3412 putpkt ("QNonStop:0");
3413 getpkt (&rs->buf, &rs->buf_size, 0);
3414
3415 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3416 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
3417 }
3418
a0743c90
YQ
3419 /* Upload TSVs regardless of whether the target is running or not. The
3420 remote stub, such as GDBserver, may have some predefined or builtin
3421 TSVs, even if the target is not running. */
8bd200f1 3422 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
3423 {
3424 struct uploaded_tsv *uploaded_tsvs = NULL;
3425
181e3713 3426 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
3427 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3428 }
3429
2d717e4f
DJ
3430 /* Check whether the target is running now. */
3431 putpkt ("?");
3432 getpkt (&rs->buf, &rs->buf_size, 0);
3433
74531fed 3434 if (!non_stop)
2d717e4f 3435 {
e714e1bf
UW
3436 ptid_t ptid;
3437 int fake_pid_p = 0;
3438 struct inferior *inf;
3439
74531fed 3440 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 3441 {
04bd08de 3442 if (!extended_p)
74531fed 3443 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
3444
3445 /* We're connected, but not running. Drop out before we
3446 call start_remote. */
e278ad5b 3447 rs->starting_up = 0;
c35b1492 3448 return;
2d717e4f
DJ
3449 }
3450 else
74531fed 3451 {
74531fed
PA
3452 /* Save the reply for later. */
3453 wait_status = alloca (strlen (rs->buf) + 1);
3454 strcpy (wait_status, rs->buf);
3455 }
3456
b7ea362b
PA
3457 /* Fetch thread list. */
3458 target_find_new_threads ();
3459
74531fed
PA
3460 /* Let the stub know that we want it to return the thread. */
3461 set_continue_thread (minus_one_ptid);
3462
b7ea362b
PA
3463 if (thread_count () == 0)
3464 {
3465 /* Target has no concept of threads at all. GDB treats
3466 non-threaded target as single-threaded; add a main
3467 thread. */
3468 add_current_inferior_and_thread (wait_status);
3469 }
3470 else
3471 {
3472 /* We have thread information; select the thread the target
3473 says should be current. If we're reconnecting to a
3474 multi-threaded program, this will ideally be the thread
3475 that last reported an event before GDB disconnected. */
3476 inferior_ptid = get_current_thread (wait_status);
3477 if (ptid_equal (inferior_ptid, null_ptid))
3478 {
3479 /* Odd... The target was able to list threads, but not
3480 tell us which thread was current (no "thread"
3481 register in T stop reply?). Just pick the first
3482 thread in the thread list then. */
3483 inferior_ptid = thread_list->ptid;
3484 }
3485 }
74531fed 3486
6e586cc5
YQ
3487 /* init_wait_for_inferior should be called before get_offsets in order
3488 to manage `inserted' flag in bp loc in a correct state.
3489 breakpoint_init_inferior, called from init_wait_for_inferior, set
3490 `inserted' flag to 0, while before breakpoint_re_set, called from
3491 start_remote, set `inserted' flag to 1. In the initialization of
3492 inferior, breakpoint_init_inferior should be called first, and then
3493 breakpoint_re_set can be called. If this order is broken, state of
3494 `inserted' flag is wrong, and cause some problems on breakpoint
3495 manipulation. */
3496 init_wait_for_inferior ();
3497
74531fed
PA
3498 get_offsets (); /* Get text, data & bss offsets. */
3499
d962ef82
DJ
3500 /* If we could not find a description using qXfer, and we know
3501 how to do it some other way, try again. This is not
3502 supported for non-stop; it could be, but it is tricky if
3503 there are no stopped threads when we connect. */
04bd08de 3504 if (remote_read_description_p (target)
f5656ead 3505 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
3506 {
3507 target_clear_description ();
3508 target_find_description ();
3509 }
3510
74531fed
PA
3511 /* Use the previously fetched status. */
3512 gdb_assert (wait_status != NULL);
3513 strcpy (rs->buf, wait_status);
3514 rs->cached_wait_status = 1;
3515
3516 immediate_quit--;
04bd08de 3517 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
3518 }
3519 else
3520 {
68c97600
PA
3521 /* Clear WFI global state. Do this before finding about new
3522 threads and inferiors, and setting the current inferior.
3523 Otherwise we would clear the proceed status of the current
3524 inferior when we want its stop_soon state to be preserved
3525 (see notice_new_inferior). */
3526 init_wait_for_inferior ();
3527
74531fed
PA
3528 /* In non-stop, we will either get an "OK", meaning that there
3529 are no stopped threads at this time; or, a regular stop
3530 reply. In the latter case, there may be more than one thread
3531 stopped --- we pull them all out using the vStopped
3532 mechanism. */
3533 if (strcmp (rs->buf, "OK") != 0)
3534 {
722247f1 3535 struct notif_client *notif = &notif_client_stop;
2d717e4f 3536
722247f1
YQ
3537 /* remote_notif_get_pending_replies acks this one, and gets
3538 the rest out. */
f48ff2a7 3539 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
3540 = remote_notif_parse (notif, rs->buf);
3541 remote_notif_get_pending_events (notif);
c906108c 3542
74531fed
PA
3543 /* Make sure that threads that were stopped remain
3544 stopped. */
3545 iterate_over_threads (set_stop_requested_callback, NULL);
3546 }
2d717e4f 3547
74531fed
PA
3548 if (target_can_async_p ())
3549 target_async (inferior_event_handler, 0);
c906108c 3550
74531fed
PA
3551 if (thread_count () == 0)
3552 {
04bd08de 3553 if (!extended_p)
74531fed 3554 error (_("The target is not running (try extended-remote?)"));
82f73884 3555
c35b1492
PA
3556 /* We're connected, but not running. Drop out before we
3557 call start_remote. */
e278ad5b 3558 rs->starting_up = 0;
c35b1492
PA
3559 return;
3560 }
74531fed
PA
3561
3562 /* Let the stub know that we want it to return the thread. */
c0a2216e 3563
74531fed
PA
3564 /* Force the stub to choose a thread. */
3565 set_general_thread (null_ptid);
c906108c 3566
74531fed
PA
3567 /* Query it. */
3568 inferior_ptid = remote_current_thread (minus_one_ptid);
3569 if (ptid_equal (inferior_ptid, minus_one_ptid))
3570 error (_("remote didn't report the current thread in non-stop mode"));
c906108c 3571
74531fed
PA
3572 get_offsets (); /* Get text, data & bss offsets. */
3573
3574 /* In non-stop mode, any cached wait status will be stored in
3575 the stop reply queue. */
3576 gdb_assert (wait_status == NULL);
f0223081 3577
2455069d 3578 /* Report all signals during attach/startup. */
94bedb42 3579 remote_pass_signals (target, 0, NULL);
74531fed 3580 }
c8d104ad 3581
c8d104ad
PA
3582 /* If we connected to a live target, do some additional setup. */
3583 if (target_has_execution)
3584 {
f4ccffad 3585 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 3586 remote_check_symbols ();
c8d104ad 3587 }
50c71eaf 3588
d5551862
SS
3589 /* Possibly the target has been engaged in a trace run started
3590 previously; find out where things are at. */
8bd200f1 3591 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 3592 {
00bf0b85 3593 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 3594
00bf0b85
SS
3595 if (current_trace_status ()->running)
3596 printf_filtered (_("Trace is already running on the target.\n"));
3597
ab6617cc 3598 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
3599
3600 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
3601 }
3602
1e51243a
PA
3603 /* The thread and inferior lists are now synchronized with the
3604 target, our symbols have been relocated, and we're merged the
3605 target's tracepoints with ours. We're done with basic start
3606 up. */
3607 rs->starting_up = 0;
3608
2567c7d9 3609 /* If breakpoints are global, insert them now. */
f5656ead 3610 if (gdbarch_has_global_breakpoints (target_gdbarch ())
50c71eaf
PA
3611 && breakpoints_always_inserted_mode ())
3612 insert_breakpoints ();
c906108c
SS
3613}
3614
3615/* Open a connection to a remote debugger.
3616 NAME is the filename used for communication. */
3617
3618static void
014f9477 3619remote_open (const char *name, int from_tty)
c906108c 3620{
75c99385 3621 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
3622}
3623
c906108c
SS
3624/* Open a connection to a remote debugger using the extended
3625 remote gdb protocol. NAME is the filename used for communication. */
3626
3627static void
014f9477 3628extended_remote_open (const char *name, int from_tty)
c906108c 3629{
75c99385 3630 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
3631}
3632
ca4f7f8b
PA
3633/* Reset all packets back to "unknown support". Called when opening a
3634 new connection to a remote target. */
c906108c 3635
d471ea57 3636static void
ca4f7f8b 3637reset_all_packet_configs_support (void)
d471ea57
AC
3638{
3639 int i;
a744cf53 3640
444abaca 3641 for (i = 0; i < PACKET_MAX; i++)
4082afcc 3642 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
3643}
3644
ca4f7f8b
PA
3645/* Initialize all packet configs. */
3646
3647static void
3648init_all_packet_configs (void)
3649{
3650 int i;
3651
3652 for (i = 0; i < PACKET_MAX; i++)
3653 {
3654 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
3655 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3656 }
3657}
3658
23860348 3659/* Symbol look-up. */
dc8acb97
MS
3660
3661static void
36d25514 3662remote_check_symbols (void)
dc8acb97 3663{
d01949b6 3664 struct remote_state *rs = get_remote_state ();
dc8acb97 3665 char *msg, *reply, *tmp;
3b7344d5 3666 struct bound_minimal_symbol sym;
dc8acb97
MS
3667 int end;
3668
63154eca
PA
3669 /* The remote side has no concept of inferiors that aren't running
3670 yet, it only knows about running processes. If we're connected
3671 but our current inferior is not running, we should not invite the
3672 remote target to request symbol lookups related to its
3673 (unrelated) current process. */
3674 if (!target_has_execution)
3675 return;
3676
4082afcc 3677 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
3678 return;
3679
63154eca
PA
3680 /* Make sure the remote is pointing at the right process. Note
3681 there's no way to select "no process". */
3c9c4b83
PA
3682 set_general_process ();
3683
6d820c5c
DJ
3684 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3685 because we need both at the same time. */
ea9c271d 3686 msg = alloca (get_remote_packet_size ());
6d820c5c 3687
23860348 3688 /* Invite target to request symbol lookups. */
dc8acb97
MS
3689
3690 putpkt ("qSymbol::");
6d820c5c
DJ
3691 getpkt (&rs->buf, &rs->buf_size, 0);
3692 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2e9f7625 3693 reply = rs->buf;
dc8acb97
MS
3694
3695 while (strncmp (reply, "qSymbol:", 8) == 0)
3696 {
77e371c0
TT
3697 struct bound_minimal_symbol sym;
3698
dc8acb97 3699 tmp = &reply[8];
cfd77fa1 3700 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
3701 msg[end] = '\0';
3702 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 3703 if (sym.minsym == NULL)
ea9c271d 3704 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 3705 else
2bbe3cc1 3706 {
f5656ead 3707 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 3708 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
3709
3710 /* If this is a function address, return the start of code
3711 instead of any data function descriptor. */
f5656ead 3712 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
3713 sym_addr,
3714 &current_target);
3715
3716 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 3717 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
3718 }
3719
dc8acb97 3720 putpkt (msg);
6d820c5c 3721 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3722 reply = rs->buf;
dc8acb97
MS
3723 }
3724}
3725
9db8d71f 3726static struct serial *
baa336ce 3727remote_serial_open (const char *name)
9db8d71f
DJ
3728{
3729 static int udp_warning = 0;
3730
3731 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3732 of in ser-tcp.c, because it is the remote protocol assuming that the
3733 serial connection is reliable and not the serial connection promising
3734 to be. */
3735 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
3736 {
3e43a32a
MS
3737 warning (_("The remote protocol may be unreliable over UDP.\n"
3738 "Some events may be lost, rendering further debugging "
3739 "impossible."));
9db8d71f
DJ
3740 udp_warning = 1;
3741 }
3742
3743 return serial_open (name);
3744}
3745
d914c394
SS
3746/* Inform the target of our permission settings. The permission flags
3747 work without this, but if the target knows the settings, it can do
3748 a couple things. First, it can add its own check, to catch cases
3749 that somehow manage to get by the permissions checks in target
3750 methods. Second, if the target is wired to disallow particular
3751 settings (for instance, a system in the field that is not set up to
3752 be able to stop at a breakpoint), it can object to any unavailable
3753 permissions. */
3754
3755void
c378d69d 3756remote_set_permissions (struct target_ops *self)
d914c394
SS
3757{
3758 struct remote_state *rs = get_remote_state ();
3759
bba74b36
YQ
3760 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3761 "WriteReg:%x;WriteMem:%x;"
3762 "InsertBreak:%x;InsertTrace:%x;"
3763 "InsertFastTrace:%x;Stop:%x",
3764 may_write_registers, may_write_memory,
3765 may_insert_breakpoints, may_insert_tracepoints,
3766 may_insert_fast_tracepoints, may_stop);
d914c394
SS
3767 putpkt (rs->buf);
3768 getpkt (&rs->buf, &rs->buf_size, 0);
3769
3770 /* If the target didn't like the packet, warn the user. Do not try
3771 to undo the user's settings, that would just be maddening. */
3772 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 3773 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
3774}
3775
be2a5f71
DJ
3776/* This type describes each known response to the qSupported
3777 packet. */
3778struct protocol_feature
3779{
3780 /* The name of this protocol feature. */
3781 const char *name;
3782
3783 /* The default for this protocol feature. */
3784 enum packet_support default_support;
3785
3786 /* The function to call when this feature is reported, or after
3787 qSupported processing if the feature is not supported.
3788 The first argument points to this structure. The second
3789 argument indicates whether the packet requested support be
3790 enabled, disabled, or probed (or the default, if this function
3791 is being called at the end of processing and this feature was
3792 not reported). The third argument may be NULL; if not NULL, it
3793 is a NUL-terminated string taken from the packet following
3794 this feature's name and an equals sign. */
3795 void (*func) (const struct protocol_feature *, enum packet_support,
3796 const char *);
3797
3798 /* The corresponding packet for this feature. Only used if
3799 FUNC is remote_supported_packet. */
3800 int packet;
3801};
3802
be2a5f71
DJ
3803static void
3804remote_supported_packet (const struct protocol_feature *feature,
3805 enum packet_support support,
3806 const char *argument)
3807{
3808 if (argument)
3809 {
3810 warning (_("Remote qSupported response supplied an unexpected value for"
3811 " \"%s\"."), feature->name);
3812 return;
3813 }
3814
4082afcc 3815 remote_protocol_packets[feature->packet].support = support;
be2a5f71 3816}
be2a5f71
DJ
3817
3818static void
3819remote_packet_size (const struct protocol_feature *feature,
3820 enum packet_support support, const char *value)
3821{
3822 struct remote_state *rs = get_remote_state ();
3823
3824 int packet_size;
3825 char *value_end;
3826
3827 if (support != PACKET_ENABLE)
3828 return;
3829
3830 if (value == NULL || *value == '\0')
3831 {
3832 warning (_("Remote target reported \"%s\" without a size."),
3833 feature->name);
3834 return;
3835 }
3836
3837 errno = 0;
3838 packet_size = strtol (value, &value_end, 16);
3839 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3840 {
3841 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3842 feature->name, value);
3843 return;
3844 }
3845
3846 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3847 {
3848 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3849 packet_size, MAX_REMOTE_PACKET_SIZE);
3850 packet_size = MAX_REMOTE_PACKET_SIZE;
3851 }
3852
3853 /* Record the new maximum packet size. */
3854 rs->explicit_packet_size = packet_size;
3855}
3856
dc473cfb 3857static const struct protocol_feature remote_protocol_features[] = {
0876f84a 3858 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 3859 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 3860 PACKET_qXfer_auxv },
23181151
DJ
3861 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3862 PACKET_qXfer_features },
cfa9d6d9
DJ
3863 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3864 PACKET_qXfer_libraries },
2268b414
JK
3865 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
3866 PACKET_qXfer_libraries_svr4 },
ced63ec0 3867 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 3868 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 3869 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 3870 PACKET_qXfer_memory_map },
4de6483e
UW
3871 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3872 PACKET_qXfer_spu_read },
3873 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3874 PACKET_qXfer_spu_write },
07e059b5
VP
3875 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3876 PACKET_qXfer_osdata },
dc146f7c
VP
3877 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
3878 PACKET_qXfer_threads },
b3b9301e
PA
3879 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
3880 PACKET_qXfer_traceframe_info },
89be2091
DJ
3881 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3882 PACKET_QPassSignals },
9b224c5e
PA
3883 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
3884 PACKET_QProgramSignals },
a6f3e723
SL
3885 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
3886 PACKET_QStartNoAckMode },
4082afcc
PA
3887 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
3888 PACKET_multiprocess_feature },
3889 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
3890 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
3891 PACKET_qXfer_siginfo_read },
3892 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
3893 PACKET_qXfer_siginfo_write },
4082afcc 3894 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 3895 PACKET_ConditionalTracepoints },
4082afcc 3896 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 3897 PACKET_ConditionalBreakpoints },
4082afcc 3898 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 3899 PACKET_BreakpointCommands },
4082afcc 3900 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 3901 PACKET_FastTracepoints },
4082afcc 3902 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 3903 PACKET_StaticTracepoints },
4082afcc 3904 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 3905 PACKET_InstallInTrace},
4082afcc
PA
3906 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
3907 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
3908 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
3909 PACKET_bc },
3910 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
3911 PACKET_bs },
409873ef
SS
3912 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
3913 PACKET_TracepointSource },
d914c394
SS
3914 { "QAllow", PACKET_DISABLE, remote_supported_packet,
3915 PACKET_QAllow },
4082afcc
PA
3916 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
3917 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
3918 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
3919 PACKET_qXfer_fdpic },
169081d0
TG
3920 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
3921 PACKET_qXfer_uib },
03583c20
UW
3922 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
3923 PACKET_QDisableRandomization },
d1feda86 3924 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
3925 { "QTBuffer:size", PACKET_DISABLE,
3926 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 3927 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
3928 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
3929 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
3930 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
3931 PACKET_qXfer_btrace }
be2a5f71
DJ
3932};
3933
c8d5aac9
L
3934static char *remote_support_xml;
3935
3936/* Register string appended to "xmlRegisters=" in qSupported query. */
3937
3938void
6e39997a 3939register_remote_support_xml (const char *xml)
c8d5aac9
L
3940{
3941#if defined(HAVE_LIBEXPAT)
3942 if (remote_support_xml == NULL)
c4f7c687 3943 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
3944 else
3945 {
3946 char *copy = xstrdup (remote_support_xml + 13);
3947 char *p = strtok (copy, ",");
3948
3949 do
3950 {
3951 if (strcmp (p, xml) == 0)
3952 {
3953 /* already there */
3954 xfree (copy);
3955 return;
3956 }
3957 }
3958 while ((p = strtok (NULL, ",")) != NULL);
3959 xfree (copy);
3960
94b0dee1
PA
3961 remote_support_xml = reconcat (remote_support_xml,
3962 remote_support_xml, ",", xml,
3963 (char *) NULL);
c8d5aac9
L
3964 }
3965#endif
3966}
3967
3968static char *
3969remote_query_supported_append (char *msg, const char *append)
3970{
3971 if (msg)
94b0dee1 3972 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
3973 else
3974 return xstrdup (append);
3975}
3976
be2a5f71
DJ
3977static void
3978remote_query_supported (void)
3979{
3980 struct remote_state *rs = get_remote_state ();
3981 char *next;
3982 int i;
3983 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
3984
3985 /* The packet support flags are handled differently for this packet
3986 than for most others. We treat an error, a disabled packet, and
3987 an empty response identically: any features which must be reported
3988 to be used will be automatically disabled. An empty buffer
3989 accomplishes this, since that is also the representation for a list
3990 containing no features. */
3991
3992 rs->buf[0] = 0;
4082afcc 3993 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 3994 {
c8d5aac9 3995 char *q = NULL;
94b0dee1 3996 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 3997
901f9912 3998 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9
L
3999
4000 if (remote_support_xml)
4001 q = remote_query_supported_append (q, remote_support_xml);
4002
dde08ee1
PA
4003 q = remote_query_supported_append (q, "qRelocInsn+");
4004
4005 q = reconcat (q, "qSupported:", q, (char *) NULL);
4006 putpkt (q);
82f73884 4007
94b0dee1
PA
4008 do_cleanups (old_chain);
4009
be2a5f71
DJ
4010 getpkt (&rs->buf, &rs->buf_size, 0);
4011
4012 /* If an error occured, warn, but do not return - just reset the
4013 buffer to empty and go on to disable features. */
4014 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4015 == PACKET_ERROR)
4016 {
4017 warning (_("Remote failure reply: %s"), rs->buf);
4018 rs->buf[0] = 0;
4019 }
4020 }
4021
4022 memset (seen, 0, sizeof (seen));
4023
4024 next = rs->buf;
4025 while (*next)
4026 {
4027 enum packet_support is_supported;
4028 char *p, *end, *name_end, *value;
4029
4030 /* First separate out this item from the rest of the packet. If
4031 there's another item after this, we overwrite the separator
4032 (terminated strings are much easier to work with). */
4033 p = next;
4034 end = strchr (p, ';');
4035 if (end == NULL)
4036 {
4037 end = p + strlen (p);
4038 next = end;
4039 }
4040 else
4041 {
89be2091
DJ
4042 *end = '\0';
4043 next = end + 1;
4044
be2a5f71
DJ
4045 if (end == p)
4046 {
4047 warning (_("empty item in \"qSupported\" response"));
4048 continue;
4049 }
be2a5f71
DJ
4050 }
4051
4052 name_end = strchr (p, '=');
4053 if (name_end)
4054 {
4055 /* This is a name=value entry. */
4056 is_supported = PACKET_ENABLE;
4057 value = name_end + 1;
4058 *name_end = '\0';
4059 }
4060 else
4061 {
4062 value = NULL;
4063 switch (end[-1])
4064 {
4065 case '+':
4066 is_supported = PACKET_ENABLE;
4067 break;
4068
4069 case '-':
4070 is_supported = PACKET_DISABLE;
4071 break;
4072
4073 case '?':
4074 is_supported = PACKET_SUPPORT_UNKNOWN;
4075 break;
4076
4077 default:
3e43a32a
MS
4078 warning (_("unrecognized item \"%s\" "
4079 "in \"qSupported\" response"), p);
be2a5f71
DJ
4080 continue;
4081 }
4082 end[-1] = '\0';
4083 }
4084
4085 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4086 if (strcmp (remote_protocol_features[i].name, p) == 0)
4087 {
4088 const struct protocol_feature *feature;
4089
4090 seen[i] = 1;
4091 feature = &remote_protocol_features[i];
4092 feature->func (feature, is_supported, value);
4093 break;
4094 }
4095 }
4096
4097 /* If we increased the packet size, make sure to increase the global
4098 buffer size also. We delay this until after parsing the entire
4099 qSupported packet, because this is the same buffer we were
4100 parsing. */
4101 if (rs->buf_size < rs->explicit_packet_size)
4102 {
4103 rs->buf_size = rs->explicit_packet_size;
4104 rs->buf = xrealloc (rs->buf, rs->buf_size);
4105 }
4106
4107 /* Handle the defaults for unmentioned features. */
4108 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4109 if (!seen[i])
4110 {
4111 const struct protocol_feature *feature;
4112
4113 feature = &remote_protocol_features[i];
4114 feature->func (feature, feature->default_support, NULL);
4115 }
4116}
4117
78a095c3
JK
4118/* Remove any of the remote.c targets from target stack. Upper targets depend
4119 on it so remove them first. */
4120
4121static void
4122remote_unpush_target (void)
4123{
4124 pop_all_targets_above (process_stratum - 1);
4125}
be2a5f71 4126
c906108c 4127static void
014f9477 4128remote_open_1 (const char *name, int from_tty,
3e43a32a 4129 struct target_ops *target, int extended_p)
c906108c 4130{
d01949b6 4131 struct remote_state *rs = get_remote_state ();
a6f3e723 4132
c906108c 4133 if (name == 0)
8a3fe4f8 4134 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4135 "serial device is attached to the remote system\n"
8a3fe4f8 4136 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4137
23860348 4138 /* See FIXME above. */
c6ebd6cf 4139 if (!target_async_permitted)
92d1e331 4140 wait_forever_enabled_p = 1;
6426a772 4141
2d717e4f 4142 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4143 Ask this question first, before target_preopen has a chance to kill
4144 anything. */
5d93a237 4145 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4146 {
78a095c3
JK
4147 if (from_tty
4148 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4149 error (_("Still connected."));
4150 }
4151
78a095c3 4152 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4153 target_preopen (from_tty);
4154
89be2091 4155 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4156 xfree (rs->last_pass_packet);
4157 rs->last_pass_packet = NULL;
89be2091 4158
9b224c5e
PA
4159 /* Make sure we send the program signals list the next time we
4160 resume. */
5e4a05c4
TT
4161 xfree (rs->last_program_signals_packet);
4162 rs->last_program_signals_packet = NULL;
9b224c5e 4163
ad9a8f3f 4164 remote_fileio_reset ();
1dd41f16
NS
4165 reopen_exec_file ();
4166 reread_symbols ();
4167
5d93a237
TT
4168 rs->remote_desc = remote_serial_open (name);
4169 if (!rs->remote_desc)
c906108c
SS
4170 perror_with_name (name);
4171
4172 if (baud_rate != -1)
4173 {
5d93a237 4174 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4175 {
9b74d5d3
KB
4176 /* The requested speed could not be set. Error out to
4177 top level after closing remote_desc. Take care to
4178 set remote_desc to NULL to avoid closing remote_desc
4179 more than once. */
5d93a237
TT
4180 serial_close (rs->remote_desc);
4181 rs->remote_desc = NULL;
c906108c
SS
4182 perror_with_name (name);
4183 }
4184 }
4185
5d93a237 4186 serial_raw (rs->remote_desc);
c906108c
SS
4187
4188 /* If there is something sitting in the buffer we might take it as a
4189 response to a command, which would be bad. */
5d93a237 4190 serial_flush_input (rs->remote_desc);
c906108c
SS
4191
4192 if (from_tty)
4193 {
4194 puts_filtered ("Remote debugging using ");
4195 puts_filtered (name);
4196 puts_filtered ("\n");
4197 }
23860348 4198 push_target (target); /* Switch to using remote target now. */
c906108c 4199
74531fed
PA
4200 /* Register extra event sources in the event loop. */
4201 remote_async_inferior_event_token
4202 = create_async_event_handler (remote_async_inferior_event_handler,
4203 NULL);
5965e028 4204 rs->notif_state = remote_notif_state_allocate ();
74531fed 4205
be2a5f71
DJ
4206 /* Reset the target state; these things will be queried either by
4207 remote_query_supported or as they are needed. */
ca4f7f8b 4208 reset_all_packet_configs_support ();
74531fed 4209 rs->cached_wait_status = 0;
be2a5f71 4210 rs->explicit_packet_size = 0;
a6f3e723 4211 rs->noack_mode = 0;
82f73884 4212 rs->extended = extended_p;
e24a49d8 4213 rs->waiting_for_stop_reply = 0;
3a29589a 4214 rs->ctrlc_pending_p = 0;
802188a7 4215
47f8a51d
TT
4216 rs->general_thread = not_sent_ptid;
4217 rs->continue_thread = not_sent_ptid;
262e1174 4218 rs->remote_traceframe_number = -1;
c906108c 4219
9d1f7ab2 4220 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
4221 rs->use_threadinfo_query = 1;
4222 rs->use_threadextra_query = 1;
9d1f7ab2 4223
c6ebd6cf 4224 if (target_async_permitted)
92d1e331 4225 {
23860348 4226 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4227 remote_async_terminal_ours_p = 1;
4228
4229 /* FIXME: cagney/1999-09-23: During the initial connection it is
4230 assumed that the target is already ready and able to respond to
0df8b418 4231 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4232 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4233 around this. Eventually a mechanism that allows
92d1e331 4234 wait_for_inferior() to expect/get timeouts will be
23860348 4235 implemented. */
92d1e331
DJ
4236 wait_forever_enabled_p = 0;
4237 }
4238
23860348 4239 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4240 no_shared_libraries (NULL, 0);
f78f6cf1 4241
74531fed
PA
4242 /* Start afresh. */
4243 init_thread_list ();
4244
36918e70 4245 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4246 target (we'd otherwise be in an inconsistent state) and then
4247 propogate the error on up the exception chain. This ensures that
4248 the caller doesn't stumble along blindly assuming that the
4249 function succeeded. The CLI doesn't have this problem but other
4250 UI's, such as MI do.
36918e70
AC
4251
4252 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4253 this function should return an error indication letting the
ce2826aa 4254 caller restore the previous state. Unfortunately the command
36918e70
AC
4255 ``target remote'' is directly wired to this function making that
4256 impossible. On a positive note, the CLI side of this problem has
4257 been fixed - the function set_cmd_context() makes it possible for
4258 all the ``target ....'' commands to share a common callback
4259 function. See cli-dump.c. */
109c3e39 4260 {
04bd08de 4261 volatile struct gdb_exception ex;
2d717e4f 4262
04bd08de
TT
4263 TRY_CATCH (ex, RETURN_MASK_ALL)
4264 {
4265 remote_start_remote (from_tty, target, extended_p);
4266 }
109c3e39
AC
4267 if (ex.reason < 0)
4268 {
c8d104ad
PA
4269 /* Pop the partially set up target - unless something else did
4270 already before throwing the exception. */
5d93a237 4271 if (rs->remote_desc != NULL)
78a095c3 4272 remote_unpush_target ();
c6ebd6cf 4273 if (target_async_permitted)
109c3e39
AC
4274 wait_forever_enabled_p = 1;
4275 throw_exception (ex);
4276 }
4277 }
c906108c 4278
c6ebd6cf 4279 if (target_async_permitted)
92d1e331 4280 wait_forever_enabled_p = 1;
43ff13b4
JM
4281}
4282
c906108c
SS
4283/* This takes a program previously attached to and detaches it. After
4284 this is done, GDB can be used to debug some other program. We
4285 better not have left any breakpoints in the target program or it'll
4286 die when it hits one. */
4287
4288static void
52554a0e 4289remote_detach_1 (const char *args, int from_tty, int extended)
c906108c 4290{
82f73884 4291 int pid = ptid_get_pid (inferior_ptid);
d01949b6 4292 struct remote_state *rs = get_remote_state ();
c906108c
SS
4293
4294 if (args)
8a3fe4f8 4295 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 4296
2d717e4f
DJ
4297 if (!target_has_execution)
4298 error (_("No process to detach from."));
4299
7cee1e54
PA
4300 if (from_tty)
4301 {
4302 char *exec_file = get_exec_file (0);
4303 if (exec_file == NULL)
4304 exec_file = "";
4305 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4306 target_pid_to_str (pid_to_ptid (pid)));
4307 gdb_flush (gdb_stdout);
4308 }
4309
c906108c 4310 /* Tell the remote target to detach. */
82f73884 4311 if (remote_multi_process_p (rs))
bba74b36 4312 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
82f73884
PA
4313 else
4314 strcpy (rs->buf, "D");
4315
4ddda9b5
PA
4316 putpkt (rs->buf);
4317 getpkt (&rs->buf, &rs->buf_size, 0);
4318
82f73884
PA
4319 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4320 ;
4321 else if (rs->buf[0] == '\0')
4322 error (_("Remote doesn't know how to detach"));
4323 else
4ddda9b5 4324 error (_("Can't detach process."));
c906108c 4325
7cee1e54
PA
4326 if (from_tty && !extended)
4327 puts_filtered (_("Ending remote debugging.\n"));
82f73884 4328
82f73884 4329 target_mourn_inferior ();
2d717e4f
DJ
4330}
4331
4332static void
52554a0e 4333remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f
DJ
4334{
4335 remote_detach_1 (args, from_tty, 0);
4336}
4337
4338static void
52554a0e 4339extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f
DJ
4340{
4341 remote_detach_1 (args, from_tty, 1);
c906108c
SS
4342}
4343
6ad8ae5c
DJ
4344/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4345
43ff13b4 4346static void
fee354ee 4347remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 4348{
43ff13b4 4349 if (args)
2d717e4f 4350 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 4351
2d717e4f
DJ
4352 /* Make sure we unpush even the extended remote targets; mourn
4353 won't do it. So call remote_mourn_1 directly instead of
4354 target_mourn_inferior. */
4355 remote_mourn_1 (target);
4356
43ff13b4
JM
4357 if (from_tty)
4358 puts_filtered ("Ending remote debugging.\n");
4359}
4360
2d717e4f
DJ
4361/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4362 be chatty about it. */
4363
4364static void
c0939df1
TT
4365extended_remote_attach_1 (struct target_ops *target, const char *args,
4366 int from_tty)
2d717e4f
DJ
4367{
4368 struct remote_state *rs = get_remote_state ();
be86555c 4369 int pid;
96ef3384 4370 char *wait_status = NULL;
2d717e4f 4371
74164c56 4372 pid = parse_pid_to_attach (args);
2d717e4f 4373
74164c56
JK
4374 /* Remote PID can be freely equal to getpid, do not check it here the same
4375 way as in other targets. */
2d717e4f 4376
4082afcc 4377 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
4378 error (_("This target does not support attaching to a process"));
4379
7cee1e54
PA
4380 if (from_tty)
4381 {
4382 char *exec_file = get_exec_file (0);
4383
4384 if (exec_file)
4385 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4386 target_pid_to_str (pid_to_ptid (pid)));
4387 else
4388 printf_unfiltered (_("Attaching to %s\n"),
4389 target_pid_to_str (pid_to_ptid (pid)));
4390
4391 gdb_flush (gdb_stdout);
4392 }
4393
bba74b36 4394 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
4395 putpkt (rs->buf);
4396 getpkt (&rs->buf, &rs->buf_size, 0);
4397
4082afcc
PA
4398 switch (packet_ok (rs->buf,
4399 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 4400 {
4082afcc 4401 case PACKET_OK:
74531fed
PA
4402 if (!non_stop)
4403 {
4404 /* Save the reply for later. */
4405 wait_status = alloca (strlen (rs->buf) + 1);
4406 strcpy (wait_status, rs->buf);
4407 }
4408 else if (strcmp (rs->buf, "OK") != 0)
4409 error (_("Attaching to %s failed with: %s"),
4410 target_pid_to_str (pid_to_ptid (pid)),
4411 rs->buf);
4082afcc
PA
4412 break;
4413 case PACKET_UNKNOWN:
4414 error (_("This target does not support attaching to a process"));
4415 default:
4416 error (_("Attaching to %s failed"),
4417 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 4418 }
2d717e4f 4419
49c62f2e 4420 set_current_inferior (remote_add_inferior (0, pid, 1));
bad34192 4421
2d717e4f 4422 inferior_ptid = pid_to_ptid (pid);
79d7f229 4423
bad34192
PA
4424 if (non_stop)
4425 {
4426 struct thread_info *thread;
79d7f229 4427
bad34192
PA
4428 /* Get list of threads. */
4429 remote_threads_info (target);
82f73884 4430
bad34192
PA
4431 thread = first_thread_of_process (pid);
4432 if (thread)
4433 inferior_ptid = thread->ptid;
4434 else
4435 inferior_ptid = pid_to_ptid (pid);
4436
4437 /* Invalidate our notion of the remote current thread. */
47f8a51d 4438 record_currthread (rs, minus_one_ptid);
bad34192 4439 }
74531fed 4440 else
bad34192
PA
4441 {
4442 /* Now, if we have thread information, update inferior_ptid. */
4443 inferior_ptid = remote_current_thread (inferior_ptid);
4444
4445 /* Add the main thread to the thread list. */
4446 add_thread_silent (inferior_ptid);
4447 }
c0a2216e 4448
96ef3384
UW
4449 /* Next, if the target can specify a description, read it. We do
4450 this before anything involving memory or registers. */
4451 target_find_description ();
4452
74531fed
PA
4453 if (!non_stop)
4454 {
4455 /* Use the previously fetched status. */
4456 gdb_assert (wait_status != NULL);
4457
4458 if (target_can_async_p ())
4459 {
722247f1
YQ
4460 struct notif_event *reply
4461 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 4462
722247f1 4463 push_stop_reply ((struct stop_reply *) reply);
74531fed
PA
4464
4465 target_async (inferior_event_handler, 0);
4466 }
4467 else
4468 {
4469 gdb_assert (wait_status != NULL);
4470 strcpy (rs->buf, wait_status);
4471 rs->cached_wait_status = 1;
4472 }
4473 }
4474 else
4475 gdb_assert (wait_status == NULL);
2d717e4f
DJ
4476}
4477
4478static void
c0939df1 4479extended_remote_attach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4480{
136d6dae 4481 extended_remote_attach_1 (ops, args, from_tty);
2d717e4f
DJ
4482}
4483
b9c1d481
AS
4484/* Implementation of the to_post_attach method. */
4485
4486static void
4487extended_remote_post_attach (struct target_ops *ops, int pid)
4488{
4489 /* In certain cases GDB might not have had the chance to start
4490 symbol lookup up until now. This could happen if the debugged
4491 binary is not using shared libraries, the vsyscall page is not
4492 present (on Linux) and the binary itself hadn't changed since the
4493 debugging process was started. */
4494 if (symfile_objfile != NULL)
4495 remote_check_symbols();
4496}
4497
c906108c 4498\f
506fb367
DJ
4499/* Check for the availability of vCont. This function should also check
4500 the response. */
c906108c
SS
4501
4502static void
6d820c5c 4503remote_vcont_probe (struct remote_state *rs)
c906108c 4504{
2e9f7625 4505 char *buf;
6d820c5c 4506
2e9f7625
DJ
4507 strcpy (rs->buf, "vCont?");
4508 putpkt (rs->buf);
6d820c5c 4509 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4510 buf = rs->buf;
c906108c 4511
506fb367
DJ
4512 /* Make sure that the features we assume are supported. */
4513 if (strncmp (buf, "vCont", 5) == 0)
4514 {
4515 char *p = &buf[5];
4516 int support_s, support_S, support_c, support_C;
4517
4518 support_s = 0;
4519 support_S = 0;
4520 support_c = 0;
4521 support_C = 0;
d458bd84 4522 rs->supports_vCont.t = 0;
c1e36e3e 4523 rs->supports_vCont.r = 0;
506fb367
DJ
4524 while (p && *p == ';')
4525 {
4526 p++;
4527 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4528 support_s = 1;
4529 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4530 support_S = 1;
4531 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4532 support_c = 1;
4533 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4534 support_C = 1;
74531fed 4535 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 4536 rs->supports_vCont.t = 1;
c1e36e3e
PA
4537 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4538 rs->supports_vCont.r = 1;
506fb367
DJ
4539
4540 p = strchr (p, ';');
4541 }
c906108c 4542
506fb367
DJ
4543 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4544 BUF will make packet_ok disable the packet. */
4545 if (!support_s || !support_S || !support_c || !support_C)
4546 buf[0] = 0;
4547 }
c906108c 4548
444abaca 4549 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 4550}
c906108c 4551
0d8f58ca
PA
4552/* Helper function for building "vCont" resumptions. Write a
4553 resumption to P. ENDP points to one-passed-the-end of the buffer
4554 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4555 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4556 resumed thread should be single-stepped and/or signalled. If PTID
4557 equals minus_one_ptid, then all threads are resumed; if PTID
4558 represents a process, then all threads of the process are resumed;
4559 the thread to be stepped and/or signalled is given in the global
4560 INFERIOR_PTID. */
4561
4562static char *
4563append_resumption (char *p, char *endp,
2ea28649 4564 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
4565{
4566 struct remote_state *rs = get_remote_state ();
4567
a493e3e2 4568 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 4569 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
4570 else if (step
4571 /* GDB is willing to range step. */
4572 && use_range_stepping
4573 /* Target supports range stepping. */
4574 && rs->supports_vCont.r
4575 /* We don't currently support range stepping multiple
4576 threads with a wildcard (though the protocol allows it,
4577 so stubs shouldn't make an active effort to forbid
4578 it). */
4579 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4580 {
4581 struct thread_info *tp;
4582
4583 if (ptid_equal (ptid, minus_one_ptid))
4584 {
4585 /* If we don't know about the target thread's tid, then
4586 we're resuming magic_null_ptid (see caller). */
4587 tp = find_thread_ptid (magic_null_ptid);
4588 }
4589 else
4590 tp = find_thread_ptid (ptid);
4591 gdb_assert (tp != NULL);
4592
4593 if (tp->control.may_range_step)
4594 {
4595 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4596
4597 p += xsnprintf (p, endp - p, ";r%s,%s",
4598 phex_nz (tp->control.step_range_start,
4599 addr_size),
4600 phex_nz (tp->control.step_range_end,
4601 addr_size));
4602 }
4603 else
4604 p += xsnprintf (p, endp - p, ";s");
4605 }
0d8f58ca
PA
4606 else if (step)
4607 p += xsnprintf (p, endp - p, ";s");
a493e3e2 4608 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
4609 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4610 else
4611 p += xsnprintf (p, endp - p, ";c");
4612
4613 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4614 {
4615 ptid_t nptid;
4616
4617 /* All (-1) threads of process. */
ba348170 4618 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
4619
4620 p += xsnprintf (p, endp - p, ":");
4621 p = write_ptid (p, endp, nptid);
4622 }
4623 else if (!ptid_equal (ptid, minus_one_ptid))
4624 {
4625 p += xsnprintf (p, endp - p, ":");
4626 p = write_ptid (p, endp, ptid);
4627 }
4628
4629 return p;
4630}
4631
e5ef252a
PA
4632/* Append a vCont continue-with-signal action for threads that have a
4633 non-zero stop signal. */
4634
4635static char *
4636append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4637{
4638 struct thread_info *thread;
4639
034f788c 4640 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
4641 if (ptid_match (thread->ptid, ptid)
4642 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 4643 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
4644 {
4645 p = append_resumption (p, endp, thread->ptid,
4646 0, thread->suspend.stop_signal);
4647 thread->suspend.stop_signal = GDB_SIGNAL_0;
4648 }
4649
4650 return p;
4651}
4652
506fb367
DJ
4653/* Resume the remote inferior by using a "vCont" packet. The thread
4654 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
4655 resumed thread should be single-stepped and/or signalled. If PTID
4656 equals minus_one_ptid, then all threads are resumed; the thread to
4657 be stepped and/or signalled is given in the global INFERIOR_PTID.
4658 This function returns non-zero iff it resumes the inferior.
44eaed12 4659
506fb367
DJ
4660 This function issues a strict subset of all possible vCont commands at the
4661 moment. */
44eaed12 4662
506fb367 4663static int
2ea28649 4664remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
4665{
4666 struct remote_state *rs = get_remote_state ();
82f73884
PA
4667 char *p;
4668 char *endp;
44eaed12 4669
4082afcc 4670 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 4671 remote_vcont_probe (rs);
44eaed12 4672
4082afcc 4673 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 4674 return 0;
44eaed12 4675
82f73884
PA
4676 p = rs->buf;
4677 endp = rs->buf + get_remote_packet_size ();
4678
506fb367
DJ
4679 /* If we could generate a wider range of packets, we'd have to worry
4680 about overflowing BUF. Should there be a generic
4681 "multi-part-packet" packet? */
4682
0d8f58ca
PA
4683 p += xsnprintf (p, endp - p, "vCont");
4684
79d7f229 4685 if (ptid_equal (ptid, magic_null_ptid))
c906108c 4686 {
79d7f229
PA
4687 /* MAGIC_NULL_PTID means that we don't have any active threads,
4688 so we don't have any TID numbers the inferior will
4689 understand. Make sure to only send forms that do not specify
4690 a TID. */
a9cbf802 4691 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 4692 }
0d8f58ca 4693 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 4694 {
0d8f58ca
PA
4695 /* Resume all threads (of all processes, or of a single
4696 process), with preference for INFERIOR_PTID. This assumes
4697 inferior_ptid belongs to the set of all threads we are about
4698 to resume. */
a493e3e2 4699 if (step || siggnal != GDB_SIGNAL_0)
82f73884 4700 {
0d8f58ca
PA
4701 /* Step inferior_ptid, with or without signal. */
4702 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 4703 }
0d8f58ca 4704
e5ef252a
PA
4705 /* Also pass down any pending signaled resumption for other
4706 threads not the current. */
4707 p = append_pending_thread_resumptions (p, endp, ptid);
4708
0d8f58ca 4709 /* And continue others without a signal. */
a493e3e2 4710 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
4711 }
4712 else
506fb367
DJ
4713 {
4714 /* Scheduler locking; resume only PTID. */
a9cbf802 4715 append_resumption (p, endp, ptid, step, siggnal);
506fb367 4716 }
c906108c 4717
82f73884
PA
4718 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4719 putpkt (rs->buf);
506fb367 4720
74531fed
PA
4721 if (non_stop)
4722 {
4723 /* In non-stop, the stub replies to vCont with "OK". The stop
4724 reply will be reported asynchronously by means of a `%Stop'
4725 notification. */
4726 getpkt (&rs->buf, &rs->buf_size, 0);
4727 if (strcmp (rs->buf, "OK") != 0)
4728 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4729 }
4730
506fb367 4731 return 1;
c906108c 4732}
43ff13b4 4733
506fb367
DJ
4734/* Tell the remote machine to resume. */
4735
43ff13b4 4736static void
28439f5e 4737remote_resume (struct target_ops *ops,
2ea28649 4738 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 4739{
d01949b6 4740 struct remote_state *rs = get_remote_state ();
2e9f7625 4741 char *buf;
43ff13b4 4742
722247f1
YQ
4743 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
4744 (explained in remote-notif.c:handle_notification) so
4745 remote_notif_process is not called. We need find a place where
4746 it is safe to start a 'vNotif' sequence. It is good to do it
4747 before resuming inferior, because inferior was stopped and no RSP
4748 traffic at that moment. */
4749 if (!non_stop)
5965e028 4750 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 4751
b73be471 4752 rs->last_sent_signal = siggnal;
280ceea3 4753 rs->last_sent_step = step;
43ff13b4 4754
506fb367 4755 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
4756 /* No reverse support (yet) for vCont. */
4757 if (execution_direction != EXEC_REVERSE)
4758 if (remote_vcont_resume (ptid, step, siggnal))
4759 goto done;
506fb367 4760
79d7f229
PA
4761 /* All other supported resume packets do use Hc, so set the continue
4762 thread. */
4763 if (ptid_equal (ptid, minus_one_ptid))
4764 set_continue_thread (any_thread_ptid);
506fb367 4765 else
79d7f229 4766 set_continue_thread (ptid);
506fb367 4767
2e9f7625 4768 buf = rs->buf;
b2175913
MS
4769 if (execution_direction == EXEC_REVERSE)
4770 {
4771 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 4772 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 4773 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 4774 siggnal);
40ab02ce 4775
4082afcc 4776 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
40ab02ce 4777 error (_("Remote reverse-step not supported."));
4082afcc 4778 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
08c93ed9 4779 error (_("Remote reverse-continue not supported."));
40ab02ce 4780
b2175913
MS
4781 strcpy (buf, step ? "bs" : "bc");
4782 }
a493e3e2 4783 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
4784 {
4785 buf[0] = step ? 'S' : 'C';
c5aa993b 4786 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 4787 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
4788 buf[3] = '\0';
4789 }
4790 else
c5aa993b 4791 strcpy (buf, step ? "s" : "c");
506fb367 4792
44eaed12 4793 putpkt (buf);
43ff13b4 4794
75c99385 4795 done:
2acceee2 4796 /* We are about to start executing the inferior, let's register it
0df8b418
MS
4797 with the event loop. NOTE: this is the one place where all the
4798 execution commands end up. We could alternatively do this in each
23860348 4799 of the execution commands in infcmd.c. */
2acceee2
JM
4800 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4801 into infcmd.c in order to allow inferior function calls to work
23860348 4802 NOT asynchronously. */
362646f5 4803 if (target_can_async_p ())
2acceee2 4804 target_async (inferior_event_handler, 0);
e24a49d8
PA
4805
4806 /* We've just told the target to resume. The remote server will
4807 wait for the inferior to stop, and then send a stop reply. In
4808 the mean time, we can't start another command/query ourselves
74531fed
PA
4809 because the stub wouldn't be ready to process it. This applies
4810 only to the base all-stop protocol, however. In non-stop (which
4811 only supports vCont), the stub replies with an "OK", and is
4812 immediate able to process further serial input. */
4813 if (!non_stop)
4814 rs->waiting_for_stop_reply = 1;
43ff13b4 4815}
c906108c 4816\f
43ff13b4
JM
4817
4818/* Set up the signal handler for SIGINT, while the target is
23860348 4819 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 4820static void
934b9bac 4821async_initialize_sigint_signal_handler (void)
43ff13b4 4822{
934b9bac 4823 signal (SIGINT, async_handle_remote_sigint);
43ff13b4
JM
4824}
4825
23860348 4826/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 4827static void
934b9bac 4828async_handle_remote_sigint (int sig)
43ff13b4 4829{
934b9bac 4830 signal (sig, async_handle_remote_sigint_twice);
b2ee242b
PA
4831 /* Note we need to go through gdb_call_async_signal_handler in order
4832 to wake up the event loop on Windows. */
4833 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
43ff13b4
JM
4834}
4835
4836/* Signal handler for SIGINT, installed after SIGINT has already been
4837 sent once. It will take effect the second time that the user sends
23860348 4838 a ^C. */
43ff13b4 4839static void
934b9bac 4840async_handle_remote_sigint_twice (int sig)
43ff13b4 4841{
934b9bac 4842 signal (sig, async_handle_remote_sigint);
b2ee242b
PA
4843 /* See note in async_handle_remote_sigint. */
4844 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
43ff13b4
JM
4845}
4846
6426a772 4847/* Perform the real interruption of the target execution, in response
23860348 4848 to a ^C. */
c5aa993b 4849static void
fba45db2 4850async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
4851{
4852 if (remote_debug)
248fd3bf 4853 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
43ff13b4 4854
94cc34af 4855 target_stop (inferior_ptid);
43ff13b4
JM
4856}
4857
0df8b418 4858/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 4859 up on the target alltogether. */
47e1ce27 4860static void
fba45db2 4861async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 4862{
2df3850c 4863 if (remote_debug)
248fd3bf 4864 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
b803fb0f
DJ
4865
4866 interrupt_query ();
43ff13b4
JM
4867}
4868
4869/* Reinstall the usual SIGINT handlers, after the target has
23860348 4870 stopped. */
6426a772 4871static void
934b9bac 4872async_cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
4873{
4874 signal (SIGINT, handle_sigint);
43ff13b4
JM
4875}
4876
c906108c
SS
4877/* Send ^C to target to halt it. Target will respond, and send us a
4878 packet. */
507f3c78 4879static void (*ofunc) (int);
c906108c 4880
0df8b418
MS
4881/* The command line interface's stop routine. This function is installed
4882 as a signal handler for SIGINT. The first time a user requests a
4883 stop, we call remote_stop to send a break or ^C. If there is no
7a292a7a 4884 response from the target (it didn't stop when the user requested it),
23860348 4885 we ask the user if he'd like to detach from the target. */
c906108c 4886static void
934b9bac 4887sync_remote_interrupt (int signo)
c906108c 4888{
23860348 4889 /* If this doesn't work, try more severe steps. */
934b9bac 4890 signal (signo, sync_remote_interrupt_twice);
7a292a7a 4891
934b9bac 4892 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
7a292a7a
SS
4893}
4894
4895/* The user typed ^C twice. */
4896
4897static void
934b9bac 4898sync_remote_interrupt_twice (int signo)
7a292a7a
SS
4899{
4900 signal (signo, ofunc);
934b9bac
JK
4901 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
4902 signal (signo, sync_remote_interrupt);
c906108c 4903}
7a292a7a 4904
74531fed
PA
4905/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
4906 thread, all threads of a remote process, or all threads of all
4907 processes. */
4908
4909static void
4910remote_stop_ns (ptid_t ptid)
4911{
4912 struct remote_state *rs = get_remote_state ();
4913 char *p = rs->buf;
4914 char *endp = rs->buf + get_remote_packet_size ();
74531fed 4915
4082afcc 4916 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
4917 remote_vcont_probe (rs);
4918
d458bd84 4919 if (!rs->supports_vCont.t)
74531fed
PA
4920 error (_("Remote server does not support stopping threads"));
4921
f91d3df5
PA
4922 if (ptid_equal (ptid, minus_one_ptid)
4923 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
4924 p += xsnprintf (p, endp - p, "vCont;t");
4925 else
4926 {
4927 ptid_t nptid;
4928
74531fed
PA
4929 p += xsnprintf (p, endp - p, "vCont;t:");
4930
4931 if (ptid_is_pid (ptid))
4932 /* All (-1) threads of process. */
ba348170 4933 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
4934 else
4935 {
4936 /* Small optimization: if we already have a stop reply for
4937 this thread, no use in telling the stub we want this
4938 stopped. */
4939 if (peek_stop_reply (ptid))
4940 return;
4941
4942 nptid = ptid;
4943 }
4944
a9cbf802 4945 write_ptid (p, endp, nptid);
74531fed
PA
4946 }
4947
4948 /* In non-stop, we get an immediate OK reply. The stop reply will
4949 come in asynchronously by notification. */
4950 putpkt (rs->buf);
4951 getpkt (&rs->buf, &rs->buf_size, 0);
4952 if (strcmp (rs->buf, "OK") != 0)
4953 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
4954}
4955
4956/* All-stop version of target_stop. Sends a break or a ^C to stop the
4957 remote target. It is undefined which thread of which process
4958 reports the stop. */
4959
4960static void
4961remote_stop_as (ptid_t ptid)
4962{
4963 struct remote_state *rs = get_remote_state ();
4964
3a29589a
DJ
4965 rs->ctrlc_pending_p = 1;
4966
74531fed
PA
4967 /* If the inferior is stopped already, but the core didn't know
4968 about it yet, just ignore the request. The cached wait status
4969 will be collected in remote_wait. */
4970 if (rs->cached_wait_status)
4971 return;
4972
9a7071a8
JB
4973 /* Send interrupt_sequence to remote target. */
4974 send_interrupt_sequence ();
74531fed
PA
4975}
4976
0df8b418 4977/* This is the generic stop called via the target vector. When a target
7a292a7a 4978 interrupt is requested, either by the command line or the GUI, we
23860348 4979 will eventually end up here. */
74531fed 4980
c906108c 4981static void
1eab8a48 4982remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 4983{
7a292a7a 4984 if (remote_debug)
0f71a2f6 4985 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 4986
74531fed
PA
4987 if (non_stop)
4988 remote_stop_ns (ptid);
c906108c 4989 else
74531fed 4990 remote_stop_as (ptid);
c906108c
SS
4991}
4992
4993/* Ask the user what to do when an interrupt is received. */
4994
4995static void
fba45db2 4996interrupt_query (void)
c906108c
SS
4997{
4998 target_terminal_ours ();
4999
74531fed 5000 if (target_can_async_p ())
c906108c 5001 {
74531fed 5002 signal (SIGINT, handle_sigint);
039e3c22 5003 quit ();
c906108c 5004 }
74531fed
PA
5005 else
5006 {
9e2f0ad4
HZ
5007 if (query (_("Interrupted while waiting for the program.\n\
5008Give up (and stop debugging it)? ")))
74531fed 5009 {
78a095c3 5010 remote_unpush_target ();
039e3c22 5011 quit ();
74531fed
PA
5012 }
5013 }
c906108c
SS
5014
5015 target_terminal_inferior ();
5016}
5017
6426a772
JM
5018/* Enable/disable target terminal ownership. Most targets can use
5019 terminal groups to control terminal ownership. Remote targets are
5020 different in that explicit transfer of ownership to/from GDB/target
23860348 5021 is required. */
6426a772
JM
5022
5023static void
d2f640d4 5024remote_terminal_inferior (struct target_ops *self)
6426a772 5025{
c6ebd6cf 5026 if (!target_async_permitted)
75c99385
PA
5027 /* Nothing to do. */
5028 return;
5029
d9d2d8b6
PA
5030 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5031 idempotent. The event-loop GDB talking to an asynchronous target
5032 with a synchronous command calls this function from both
5033 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5034 transfer the terminal to the target when it shouldn't this guard
5035 can go away. */
6426a772
JM
5036 if (!remote_async_terminal_ours_p)
5037 return;
5038 delete_file_handler (input_fd);
5039 remote_async_terminal_ours_p = 0;
934b9bac 5040 async_initialize_sigint_signal_handler ();
6426a772
JM
5041 /* NOTE: At this point we could also register our selves as the
5042 recipient of all input. Any characters typed could then be
23860348 5043 passed on down to the target. */
6426a772
JM
5044}
5045
5046static void
e3594fd1 5047remote_terminal_ours (struct target_ops *self)
6426a772 5048{
c6ebd6cf 5049 if (!target_async_permitted)
75c99385
PA
5050 /* Nothing to do. */
5051 return;
5052
5053 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5054 if (remote_async_terminal_ours_p)
5055 return;
934b9bac 5056 async_cleanup_sigint_signal_handler (NULL);
6426a772
JM
5057 add_file_handler (input_fd, stdin_event_handler, 0);
5058 remote_async_terminal_ours_p = 1;
5059}
5060
176a6961 5061static void
917317f4 5062remote_console_output (char *msg)
c906108c
SS
5063{
5064 char *p;
5065
c5aa993b 5066 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5067 {
5068 char tb[2];
5069 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5070
c906108c
SS
5071 tb[0] = c;
5072 tb[1] = 0;
43ff13b4 5073 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5074 }
00db5b94
PA
5075 gdb_flush (gdb_stdtarg);
5076}
74531fed
PA
5077
5078typedef struct cached_reg
5079{
5080 int num;
5081 gdb_byte data[MAX_REGISTER_SIZE];
5082} cached_reg_t;
5083
5084DEF_VEC_O(cached_reg_t);
5085
722247f1 5086typedef struct stop_reply
74531fed 5087{
722247f1 5088 struct notif_event base;
74531fed 5089
722247f1 5090 /* The identifier of the thread about this event */
74531fed
PA
5091 ptid_t ptid;
5092
340e3c99 5093 /* The remote state this event is associated with. When the remote
bcc75809
YQ
5094 connection, represented by a remote_state object, is closed,
5095 all the associated stop_reply events should be released. */
5096 struct remote_state *rs;
5097
74531fed
PA
5098 struct target_waitstatus ws;
5099
15148d6a
PA
5100 /* Expedited registers. This makes remote debugging a bit more
5101 efficient for those targets that provide critical registers as
5102 part of their normal status mechanism (as another roundtrip to
5103 fetch them is avoided). */
74531fed
PA
5104 VEC(cached_reg_t) *regcache;
5105
5106 int stopped_by_watchpoint_p;
5107 CORE_ADDR watch_data_address;
5108
dc146f7c 5109 int core;
722247f1 5110} *stop_reply_p;
a744cf53 5111
722247f1
YQ
5112DECLARE_QUEUE_P (stop_reply_p);
5113DEFINE_QUEUE_P (stop_reply_p);
5114/* The list of already fetched and acknowledged stop events. This
5115 queue is used for notification Stop, and other notifications
5116 don't need queue for their events, because the notification events
5117 of Stop can't be consumed immediately, so that events should be
5118 queued first, and be consumed by remote_wait_{ns,as} one per
5119 time. Other notifications can consume their events immediately,
5120 so queue is not needed for them. */
5121static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
5122
5123static void
5124stop_reply_xfree (struct stop_reply *r)
5125{
f48ff2a7 5126 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
5127}
5128
722247f1
YQ
5129static void
5130remote_notif_stop_parse (struct notif_client *self, char *buf,
5131 struct notif_event *event)
5132{
5133 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5134}
5135
5136static void
5137remote_notif_stop_ack (struct notif_client *self, char *buf,
5138 struct notif_event *event)
5139{
5140 struct stop_reply *stop_reply = (struct stop_reply *) event;
5141
5142 /* acknowledge */
5143 putpkt ((char *) self->ack_command);
5144
5145 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5146 /* We got an unknown stop reply. */
5147 error (_("Unknown stop reply"));
5148
5149 push_stop_reply (stop_reply);
5150}
5151
5152static int
5153remote_notif_stop_can_get_pending_events (struct notif_client *self)
5154{
5155 /* We can't get pending events in remote_notif_process for
5156 notification stop, and we have to do this in remote_wait_ns
5157 instead. If we fetch all queued events from stub, remote stub
5158 may exit and we have no chance to process them back in
5159 remote_wait_ns. */
5160 mark_async_event_handler (remote_async_inferior_event_token);
5161 return 0;
5162}
5163
5164static void
5165stop_reply_dtr (struct notif_event *event)
5166{
5167 struct stop_reply *r = (struct stop_reply *) event;
5168
5169 VEC_free (cached_reg_t, r->regcache);
5170}
5171
5172static struct notif_event *
5173remote_notif_stop_alloc_reply (void)
5174{
5175 struct notif_event *r
70ba0933 5176 = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
5177
5178 r->dtr = stop_reply_dtr;
5179
5180 return r;
5181}
5182
5183/* A client of notification Stop. */
5184
5185struct notif_client notif_client_stop =
5186{
5187 "Stop",
5188 "vStopped",
5189 remote_notif_stop_parse,
5190 remote_notif_stop_ack,
5191 remote_notif_stop_can_get_pending_events,
5192 remote_notif_stop_alloc_reply,
f48ff2a7 5193 REMOTE_NOTIF_STOP,
722247f1
YQ
5194};
5195
5196/* A parameter to pass data in and out. */
5197
5198struct queue_iter_param
5199{
5200 void *input;
5201 struct stop_reply *output;
5202};
5203
f48ff2a7
YQ
5204/* Remove stop replies in the queue if its pid is equal to the given
5205 inferior's pid. */
722247f1
YQ
5206
5207static int
f48ff2a7
YQ
5208remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5209 QUEUE_ITER (stop_reply_p) *iter,
5210 stop_reply_p event,
5211 void *data)
722247f1
YQ
5212{
5213 struct queue_iter_param *param = data;
5214 struct inferior *inf = param->input;
5215
f48ff2a7 5216 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
5217 {
5218 stop_reply_xfree (event);
5219 QUEUE_remove_elem (stop_reply_p, q, iter);
5220 }
5221
5222 return 1;
5223}
5224
f48ff2a7 5225/* Discard all pending stop replies of inferior INF. */
c906108c 5226
74531fed 5227static void
5f4cf0bb 5228discard_pending_stop_replies (struct inferior *inf)
c906108c 5229{
722247f1
YQ
5230 int i;
5231 struct queue_iter_param param;
f48ff2a7
YQ
5232 struct stop_reply *reply;
5233 struct remote_state *rs = get_remote_state ();
5234 struct remote_notif_state *rns = rs->notif_state;
5235
5236 /* This function can be notified when an inferior exists. When the
5237 target is not remote, the notification state is NULL. */
5238 if (rs->remote_desc == NULL)
5239 return;
5240
5241 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 5242
74531fed 5243 /* Discard the in-flight notification. */
f48ff2a7 5244 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 5245 {
722247f1 5246 stop_reply_xfree (reply);
f48ff2a7 5247 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 5248 }
c906108c 5249
722247f1
YQ
5250 param.input = inf;
5251 param.output = NULL;
74531fed
PA
5252 /* Discard the stop replies we have already pulled with
5253 vStopped. */
722247f1 5254 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
5255 remove_stop_reply_for_inferior, &param);
5256}
5257
bcc75809
YQ
5258/* If its remote state is equal to the given remote state,
5259 remove EVENT from the stop reply queue. */
5260
5261static int
5262remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5263 QUEUE_ITER (stop_reply_p) *iter,
5264 stop_reply_p event,
5265 void *data)
5266{
5267 struct queue_iter_param *param = data;
5268 struct remote_state *rs = param->input;
5269
5270 if (event->rs == rs)
5271 {
5272 stop_reply_xfree (event);
5273 QUEUE_remove_elem (stop_reply_p, q, iter);
5274 }
5275
5276 return 1;
5277}
5278
5279/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
5280
5281static void
bcc75809 5282discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
5283{
5284 struct queue_iter_param param;
5285
bcc75809 5286 param.input = rs;
f48ff2a7
YQ
5287 param.output = NULL;
5288 /* Discard the stop replies we have already pulled with
5289 vStopped. */
5290 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 5291 remove_stop_reply_of_remote_state, &param);
722247f1 5292}
74531fed 5293
722247f1
YQ
5294/* A parameter to pass data in and out. */
5295
5296static int
5297remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5298 QUEUE_ITER (stop_reply_p) *iter,
5299 stop_reply_p event,
5300 void *data)
5301{
5302 struct queue_iter_param *param = data;
5303 ptid_t *ptid = param->input;
5304
5305 if (ptid_match (event->ptid, *ptid))
5306 {
5307 param->output = event;
5308 QUEUE_remove_elem (stop_reply_p, q, iter);
5309 return 0;
c8e38a49 5310 }
722247f1
YQ
5311
5312 return 1;
74531fed 5313}
43ff13b4 5314
722247f1
YQ
5315/* Remove the first reply in 'stop_reply_queue' which matches
5316 PTID. */
2e9f7625 5317
722247f1
YQ
5318static struct stop_reply *
5319remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 5320{
722247f1
YQ
5321 struct queue_iter_param param;
5322
5323 param.input = &ptid;
5324 param.output = NULL;
5325
5326 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5327 remote_notif_remove_once_on_match, &param);
5328 if (notif_debug)
5329 fprintf_unfiltered (gdb_stdlog,
5330 "notif: discard queued event: 'Stop' in %s\n",
5331 target_pid_to_str (ptid));
a744cf53 5332
722247f1 5333 return param.output;
74531fed 5334}
75c99385 5335
74531fed
PA
5336/* Look for a queued stop reply belonging to PTID. If one is found,
5337 remove it from the queue, and return it. Returns NULL if none is
5338 found. If there are still queued events left to process, tell the
5339 event loop to get back to target_wait soon. */
e24a49d8 5340
74531fed
PA
5341static struct stop_reply *
5342queued_stop_reply (ptid_t ptid)
5343{
722247f1 5344 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 5345
722247f1 5346 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
5347 /* There's still at least an event left. */
5348 mark_async_event_handler (remote_async_inferior_event_token);
5349
722247f1 5350 return r;
74531fed
PA
5351}
5352
5353/* Push a fully parsed stop reply in the stop reply queue. Since we
5354 know that we now have at least one queued event left to pass to the
5355 core side, tell the event loop to get back to target_wait soon. */
5356
5357static void
5358push_stop_reply (struct stop_reply *new_event)
5359{
722247f1 5360 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 5361
722247f1
YQ
5362 if (notif_debug)
5363 fprintf_unfiltered (gdb_stdlog,
5364 "notif: push 'Stop' %s to queue %d\n",
5365 target_pid_to_str (new_event->ptid),
5366 QUEUE_length (stop_reply_p,
5367 stop_reply_queue));
74531fed
PA
5368
5369 mark_async_event_handler (remote_async_inferior_event_token);
5370}
5371
722247f1
YQ
5372static int
5373stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5374 QUEUE_ITER (stop_reply_p) *iter,
5375 struct stop_reply *event,
5376 void *data)
5377{
5378 ptid_t *ptid = data;
5379
5380 return !(ptid_equal (*ptid, event->ptid)
5381 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5382}
5383
74531fed
PA
5384/* Returns true if we have a stop reply for PTID. */
5385
5386static int
5387peek_stop_reply (ptid_t ptid)
5388{
722247f1
YQ
5389 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5390 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
5391}
5392
5393/* Parse the stop reply in BUF. Either the function succeeds, and the
5394 result is stored in EVENT, or throws an error. */
5395
5396static void
5397remote_parse_stop_reply (char *buf, struct stop_reply *event)
5398{
5399 struct remote_arch_state *rsa = get_remote_arch_state ();
5400 ULONGEST addr;
5401 char *p;
5402
5403 event->ptid = null_ptid;
bcc75809 5404 event->rs = get_remote_state ();
74531fed
PA
5405 event->ws.kind = TARGET_WAITKIND_IGNORE;
5406 event->ws.value.integer = 0;
74531fed
PA
5407 event->stopped_by_watchpoint_p = 0;
5408 event->regcache = NULL;
dc146f7c 5409 event->core = -1;
74531fed
PA
5410
5411 switch (buf[0])
5412 {
5413 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
5414 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5415 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5416 ss = signal number
5417 n... = register number
5418 r... = register contents
5419 */
5420
5421 p = &buf[3]; /* after Txx */
5422 while (*p)
5423 {
5424 char *p1;
5425 char *p_temp;
5426 int fieldsize;
5427 LONGEST pnum = 0;
43ff13b4 5428
cea39f65
MS
5429 /* If the packet contains a register number, save it in
5430 pnum and set p1 to point to the character following it.
5431 Otherwise p1 points to p. */
3c3bea1c 5432
cea39f65
MS
5433 /* If this packet is an awatch packet, don't parse the 'a'
5434 as a register number. */
c8e38a49 5435
dc146f7c
VP
5436 if (strncmp (p, "awatch", strlen("awatch")) != 0
5437 && strncmp (p, "core", strlen ("core") != 0))
cea39f65
MS
5438 {
5439 /* Read the ``P'' register number. */
5440 pnum = strtol (p, &p_temp, 16);
5441 p1 = p_temp;
5442 }
5443 else
5444 p1 = p;
802188a7 5445
cea39f65
MS
5446 if (p1 == p) /* No register number present here. */
5447 {
5448 p1 = strchr (p, ':');
5449 if (p1 == NULL)
5450 error (_("Malformed packet(a) (missing colon): %s\n\
c8e38a49 5451Packet: '%s'\n"),
cea39f65
MS
5452 p, buf);
5453 if (strncmp (p, "thread", p1 - p) == 0)
5454 event->ptid = read_ptid (++p1, &p);
5455 else if ((strncmp (p, "watch", p1 - p) == 0)
5456 || (strncmp (p, "rwatch", p1 - p) == 0)
5457 || (strncmp (p, "awatch", p1 - p) == 0))
5458 {
5459 event->stopped_by_watchpoint_p = 1;
5460 p = unpack_varlen_hex (++p1, &addr);
5461 event->watch_data_address = (CORE_ADDR) addr;
5462 }
5463 else if (strncmp (p, "library", p1 - p) == 0)
5464 {
5465 p1++;
5466 p_temp = p1;
5467 while (*p_temp && *p_temp != ';')
5468 p_temp++;
c8e38a49 5469
5b5596ff 5470 event->ws.kind = TARGET_WAITKIND_LOADED;
cea39f65
MS
5471 p = p_temp;
5472 }
5473 else if (strncmp (p, "replaylog", p1 - p) == 0)
5474 {
5b5596ff
PA
5475 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5476 /* p1 will indicate "begin" or "end", but it makes
5477 no difference for now, so ignore it. */
cea39f65
MS
5478 p_temp = strchr (p1 + 1, ';');
5479 if (p_temp)
c8e38a49 5480 p = p_temp;
cea39f65 5481 }
dc146f7c
VP
5482 else if (strncmp (p, "core", p1 - p) == 0)
5483 {
5484 ULONGEST c;
a744cf53 5485
dc146f7c
VP
5486 p = unpack_varlen_hex (++p1, &c);
5487 event->core = c;
5488 }
cea39f65
MS
5489 else
5490 {
5491 /* Silently skip unknown optional info. */
5492 p_temp = strchr (p1 + 1, ';');
5493 if (p_temp)
5494 p = p_temp;
5495 }
5496 }
5497 else
5498 {
5499 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5500 cached_reg_t cached_reg;
74531fed 5501
cea39f65 5502 p = p1;
75c99385 5503
cea39f65
MS
5504 if (*p != ':')
5505 error (_("Malformed packet(b) (missing colon): %s\n\
8a3fe4f8 5506Packet: '%s'\n"),
cea39f65
MS
5507 p, buf);
5508 ++p;
43ff13b4 5509
cea39f65
MS
5510 if (reg == NULL)
5511 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 5512Packet: '%s'\n"),
7c47795c 5513 hex_string (pnum), p, buf);
c8e38a49 5514
cea39f65 5515 cached_reg.num = reg->regnum;
4100683b 5516
cea39f65 5517 fieldsize = hex2bin (p, cached_reg.data,
f5656ead 5518 register_size (target_gdbarch (),
cea39f65
MS
5519 reg->regnum));
5520 p += 2 * fieldsize;
f5656ead 5521 if (fieldsize < register_size (target_gdbarch (),
cea39f65
MS
5522 reg->regnum))
5523 warning (_("Remote reply is too short: %s"), buf);
74531fed 5524
cea39f65
MS
5525 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5526 }
c8e38a49 5527
cea39f65
MS
5528 if (*p != ';')
5529 error (_("Remote register badly formatted: %s\nhere: %s"),
5530 buf, p);
5531 ++p;
5532 }
5b5596ff
PA
5533
5534 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
5535 break;
5536
c8e38a49
PA
5537 /* fall through */
5538 case 'S': /* Old style status, just signal only. */
3a09da41
PA
5539 {
5540 int sig;
5541
5542 event->ws.kind = TARGET_WAITKIND_STOPPED;
5543 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
5544 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
5545 event->ws.value.sig = (enum gdb_signal) sig;
5546 else
5547 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5548 }
c8e38a49
PA
5549 break;
5550 case 'W': /* Target exited. */
5551 case 'X':
5552 {
5553 char *p;
5554 int pid;
5555 ULONGEST value;
82f73884 5556
c8e38a49
PA
5557 /* GDB used to accept only 2 hex chars here. Stubs should
5558 only send more if they detect GDB supports multi-process
5559 support. */
5560 p = unpack_varlen_hex (&buf[1], &value);
82f73884 5561
c8e38a49
PA
5562 if (buf[0] == 'W')
5563 {
5564 /* The remote process exited. */
74531fed
PA
5565 event->ws.kind = TARGET_WAITKIND_EXITED;
5566 event->ws.value.integer = value;
c8e38a49
PA
5567 }
5568 else
5569 {
5570 /* The remote process exited with a signal. */
74531fed 5571 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
5572 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
5573 event->ws.value.sig = (enum gdb_signal) value;
5574 else
5575 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 5576 }
82f73884 5577
c8e38a49
PA
5578 /* If no process is specified, assume inferior_ptid. */
5579 pid = ptid_get_pid (inferior_ptid);
5580 if (*p == '\0')
5581 ;
5582 else if (*p == ';')
5583 {
5584 p++;
5585
5586 if (p == '\0')
82f73884 5587 ;
c8e38a49
PA
5588 else if (strncmp (p,
5589 "process:", sizeof ("process:") - 1) == 0)
82f73884 5590 {
c8e38a49 5591 ULONGEST upid;
a744cf53 5592
c8e38a49
PA
5593 p += sizeof ("process:") - 1;
5594 unpack_varlen_hex (p, &upid);
5595 pid = upid;
82f73884
PA
5596 }
5597 else
5598 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 5599 }
c8e38a49
PA
5600 else
5601 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
5602 event->ptid = pid_to_ptid (pid);
5603 }
5604 break;
5605 }
5606
5607 if (non_stop && ptid_equal (event->ptid, null_ptid))
5608 error (_("No process or thread specified in stop reply: %s"), buf);
5609}
5610
722247f1
YQ
5611/* When the stub wants to tell GDB about a new notification reply, it
5612 sends a notification (%Stop, for example). Those can come it at
5613 any time, hence, we have to make sure that any pending
5614 putpkt/getpkt sequence we're making is finished, before querying
5615 the stub for more events with the corresponding ack command
5616 (vStopped, for example). E.g., if we started a vStopped sequence
5617 immediately upon receiving the notification, something like this
5618 could happen:
74531fed
PA
5619
5620 1.1) --> Hg 1
5621 1.2) <-- OK
5622 1.3) --> g
5623 1.4) <-- %Stop
5624 1.5) --> vStopped
5625 1.6) <-- (registers reply to step #1.3)
5626
5627 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5628 query.
5629
796cb314 5630 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
5631 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5632 doing whatever we were doing:
5633
5634 2.1) --> Hg 1
5635 2.2) <-- OK
5636 2.3) --> g
5637 2.4) <-- %Stop
5638 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5639 2.5) <-- (registers reply to step #2.3)
5640
5641 Eventualy after step #2.5, we return to the event loop, which
5642 notices there's an event on the
5643 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5644 associated callback --- the function below. At this point, we're
5645 always safe to start a vStopped sequence. :
5646
5647 2.6) --> vStopped
5648 2.7) <-- T05 thread:2
5649 2.8) --> vStopped
5650 2.9) --> OK
5651*/
5652
722247f1
YQ
5653void
5654remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
5655{
5656 struct remote_state *rs = get_remote_state ();
74531fed 5657
f48ff2a7 5658 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 5659 {
722247f1
YQ
5660 if (notif_debug)
5661 fprintf_unfiltered (gdb_stdlog,
5662 "notif: process: '%s' ack pending event\n",
5663 nc->name);
74531fed 5664
722247f1 5665 /* acknowledge */
f48ff2a7
YQ
5666 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
5667 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
5668
5669 while (1)
5670 {
5671 getpkt (&rs->buf, &rs->buf_size, 0);
5672 if (strcmp (rs->buf, "OK") == 0)
5673 break;
5674 else
722247f1 5675 remote_notif_ack (nc, rs->buf);
74531fed
PA
5676 }
5677 }
722247f1
YQ
5678 else
5679 {
5680 if (notif_debug)
5681 fprintf_unfiltered (gdb_stdlog,
5682 "notif: process: '%s' no pending reply\n",
5683 nc->name);
5684 }
74531fed
PA
5685}
5686
74531fed
PA
5687/* Called when it is decided that STOP_REPLY holds the info of the
5688 event that is to be returned to the core. This function always
5689 destroys STOP_REPLY. */
5690
5691static ptid_t
5692process_stop_reply (struct stop_reply *stop_reply,
5693 struct target_waitstatus *status)
5694{
5695 ptid_t ptid;
5696
5697 *status = stop_reply->ws;
5698 ptid = stop_reply->ptid;
5699
5700 /* If no thread/process was reported by the stub, assume the current
5701 inferior. */
5702 if (ptid_equal (ptid, null_ptid))
5703 ptid = inferior_ptid;
5704
5f3563ea
PA
5705 if (status->kind != TARGET_WAITKIND_EXITED
5706 && status->kind != TARGET_WAITKIND_SIGNALLED)
74531fed 5707 {
ee154bee
TT
5708 struct remote_state *rs = get_remote_state ();
5709
5f3563ea
PA
5710 /* Expedited registers. */
5711 if (stop_reply->regcache)
5712 {
217f1f79 5713 struct regcache *regcache
f5656ead 5714 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
5715 cached_reg_t *reg;
5716 int ix;
5717
5718 for (ix = 0;
5719 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5720 ix++)
217f1f79 5721 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
5722 VEC_free (cached_reg_t, stop_reply->regcache);
5723 }
74531fed 5724
ee154bee
TT
5725 rs->remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
5726 rs->remote_watch_data_address = stop_reply->watch_data_address;
1941c569
PA
5727
5728 remote_notice_new_inferior (ptid, 0);
dc146f7c 5729 demand_private_info (ptid)->core = stop_reply->core;
74531fed
PA
5730 }
5731
74531fed
PA
5732 stop_reply_xfree (stop_reply);
5733 return ptid;
5734}
5735
5736/* The non-stop mode version of target_wait. */
5737
5738static ptid_t
47608cb1 5739remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
5740{
5741 struct remote_state *rs = get_remote_state ();
74531fed
PA
5742 struct stop_reply *stop_reply;
5743 int ret;
fee9eda9 5744 int is_notif = 0;
74531fed
PA
5745
5746 /* If in non-stop mode, get out of getpkt even if a
5747 notification is received. */
5748
5749 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 5750 0 /* forever */, &is_notif);
74531fed
PA
5751 while (1)
5752 {
fee9eda9 5753 if (ret != -1 && !is_notif)
74531fed
PA
5754 switch (rs->buf[0])
5755 {
5756 case 'E': /* Error of some sort. */
5757 /* We're out of sync with the target now. Did it continue
5758 or not? We can't tell which thread it was in non-stop,
5759 so just ignore this. */
5760 warning (_("Remote failure reply: %s"), rs->buf);
5761 break;
5762 case 'O': /* Console output. */
5763 remote_console_output (rs->buf + 1);
5764 break;
5765 default:
5766 warning (_("Invalid remote reply: %s"), rs->buf);
5767 break;
5768 }
5769
5770 /* Acknowledge a pending stop reply that may have arrived in the
5771 mean time. */
f48ff2a7 5772 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 5773 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
5774
5775 /* If indeed we noticed a stop reply, we're done. */
5776 stop_reply = queued_stop_reply (ptid);
5777 if (stop_reply != NULL)
5778 return process_stop_reply (stop_reply, status);
5779
47608cb1 5780 /* Still no event. If we're just polling for an event, then
74531fed 5781 return to the event loop. */
47608cb1 5782 if (options & TARGET_WNOHANG)
74531fed
PA
5783 {
5784 status->kind = TARGET_WAITKIND_IGNORE;
5785 return minus_one_ptid;
5786 }
5787
47608cb1 5788 /* Otherwise do a blocking wait. */
74531fed 5789 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 5790 1 /* forever */, &is_notif);
74531fed
PA
5791 }
5792}
5793
5794/* Wait until the remote machine stops, then return, storing status in
5795 STATUS just as `wait' would. */
5796
5797static ptid_t
47608cb1 5798remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
5799{
5800 struct remote_state *rs = get_remote_state ();
74531fed 5801 ptid_t event_ptid = null_ptid;
cea39f65 5802 char *buf;
74531fed
PA
5803 struct stop_reply *stop_reply;
5804
47608cb1
PA
5805 again:
5806
74531fed
PA
5807 status->kind = TARGET_WAITKIND_IGNORE;
5808 status->value.integer = 0;
5809
5810 stop_reply = queued_stop_reply (ptid);
5811 if (stop_reply != NULL)
5812 return process_stop_reply (stop_reply, status);
5813
5814 if (rs->cached_wait_status)
5815 /* Use the cached wait status, but only once. */
5816 rs->cached_wait_status = 0;
5817 else
5818 {
5819 int ret;
722247f1 5820 int is_notif;
74531fed
PA
5821
5822 if (!target_is_async_p ())
5823 {
934b9bac 5824 ofunc = signal (SIGINT, sync_remote_interrupt);
74531fed
PA
5825 /* If the user hit C-c before this packet, or between packets,
5826 pretend that it was hit right here. */
522002f9 5827 if (check_quit_flag ())
74531fed 5828 {
522002f9 5829 clear_quit_flag ();
934b9bac 5830 sync_remote_interrupt (SIGINT);
74531fed
PA
5831 }
5832 }
5833
5834 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5835 _never_ wait for ever -> test on target_is_async_p().
5836 However, before we do that we need to ensure that the caller
5837 knows how to take the target into/out of async mode. */
722247f1
YQ
5838 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5839 wait_forever_enabled_p, &is_notif);
5840
5e1b953b
SDJ
5841 if (!target_is_async_p ())
5842 signal (SIGINT, ofunc);
5843
722247f1
YQ
5844 /* GDB gets a notification. Return to core as this event is
5845 not interesting. */
5846 if (ret != -1 && is_notif)
5847 return minus_one_ptid;
74531fed
PA
5848 }
5849
5850 buf = rs->buf;
5851
ee154bee 5852 rs->remote_stopped_by_watchpoint_p = 0;
74531fed
PA
5853
5854 /* We got something. */
5855 rs->waiting_for_stop_reply = 0;
5856
3a29589a
DJ
5857 /* Assume that the target has acknowledged Ctrl-C unless we receive
5858 an 'F' or 'O' packet. */
5859 if (buf[0] != 'F' && buf[0] != 'O')
5860 rs->ctrlc_pending_p = 0;
5861
74531fed
PA
5862 switch (buf[0])
5863 {
5864 case 'E': /* Error of some sort. */
5865 /* We're out of sync with the target now. Did it continue or
5866 not? Not is more likely, so report a stop. */
5867 warning (_("Remote failure reply: %s"), buf);
5868 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 5869 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
5870 break;
5871 case 'F': /* File-I/O request. */
3a29589a
DJ
5872 remote_fileio_request (buf, rs->ctrlc_pending_p);
5873 rs->ctrlc_pending_p = 0;
74531fed
PA
5874 break;
5875 case 'T': case 'S': case 'X': case 'W':
5876 {
722247f1
YQ
5877 struct stop_reply *stop_reply
5878 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
5879 rs->buf);
74531fed 5880
74531fed 5881 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
5882 break;
5883 }
5884 case 'O': /* Console output. */
5885 remote_console_output (buf + 1);
e24a49d8 5886
c8e38a49
PA
5887 /* The target didn't really stop; keep waiting. */
5888 rs->waiting_for_stop_reply = 1;
e24a49d8 5889
c8e38a49
PA
5890 break;
5891 case '\0':
b73be471 5892 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
5893 {
5894 /* Zero length reply means that we tried 'S' or 'C' and the
5895 remote system doesn't support it. */
5896 target_terminal_ours_for_output ();
5897 printf_filtered
5898 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
5899 gdb_signal_to_name (rs->last_sent_signal));
5900 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
5901 target_terminal_inferior ();
5902
280ceea3 5903 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49
PA
5904 putpkt ((char *) buf);
5905
5906 /* We just told the target to resume, so a stop reply is in
5907 order. */
e24a49d8 5908 rs->waiting_for_stop_reply = 1;
c8e38a49 5909 break;
43ff13b4 5910 }
c8e38a49
PA
5911 /* else fallthrough */
5912 default:
5913 warning (_("Invalid remote reply: %s"), buf);
5914 /* Keep waiting. */
5915 rs->waiting_for_stop_reply = 1;
5916 break;
43ff13b4 5917 }
c8e38a49 5918
c8e38a49 5919 if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
5920 {
5921 /* Nothing interesting happened. If we're doing a non-blocking
5922 poll, we're done. Otherwise, go back to waiting. */
5923 if (options & TARGET_WNOHANG)
5924 return minus_one_ptid;
5925 else
5926 goto again;
5927 }
74531fed
PA
5928 else if (status->kind != TARGET_WAITKIND_EXITED
5929 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
5930 {
5931 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 5932 record_currthread (rs, event_ptid);
82f73884
PA
5933 else
5934 event_ptid = inferior_ptid;
43ff13b4 5935 }
74531fed
PA
5936 else
5937 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 5938 record_currthread (rs, minus_one_ptid);
79d7f229 5939
82f73884 5940 return event_ptid;
43ff13b4
JM
5941}
5942
74531fed
PA
5943/* Wait until the remote machine stops, then return, storing status in
5944 STATUS just as `wait' would. */
5945
c8e38a49 5946static ptid_t
117de6a9 5947remote_wait (struct target_ops *ops,
47608cb1 5948 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
5949{
5950 ptid_t event_ptid;
5951
74531fed 5952 if (non_stop)
47608cb1 5953 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 5954 else
47608cb1 5955 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 5956
74531fed 5957 if (target_can_async_p ())
c8e38a49 5958 {
74531fed
PA
5959 /* If there are are events left in the queue tell the event loop
5960 to return here. */
722247f1 5961 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 5962 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 5963 }
c8e38a49
PA
5964
5965 return event_ptid;
5966}
5967
74ca34ce 5968/* Fetch a single register using a 'p' packet. */
c906108c 5969
b96ec7ac 5970static int
56be3814 5971fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
5972{
5973 struct remote_state *rs = get_remote_state ();
2e9f7625 5974 char *buf, *p;
b96ec7ac
AC
5975 char regp[MAX_REGISTER_SIZE];
5976 int i;
5977
4082afcc 5978 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
5979 return 0;
5980
5981 if (reg->pnum == -1)
5982 return 0;
5983
2e9f7625 5984 p = rs->buf;
fcad0fa4 5985 *p++ = 'p';
74ca34ce 5986 p += hexnumstr (p, reg->pnum);
fcad0fa4 5987 *p++ = '\0';
1f4437a4
MS
5988 putpkt (rs->buf);
5989 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 5990
2e9f7625
DJ
5991 buf = rs->buf;
5992
74ca34ce
DJ
5993 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
5994 {
5995 case PACKET_OK:
5996 break;
5997 case PACKET_UNKNOWN:
5998 return 0;
5999 case PACKET_ERROR:
27a9c0bf
MS
6000 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6001 gdbarch_register_name (get_regcache_arch (regcache),
6002 reg->regnum),
6003 buf);
74ca34ce 6004 }
3f9a994c
JB
6005
6006 /* If this register is unfetchable, tell the regcache. */
6007 if (buf[0] == 'x')
8480adf2 6008 {
56be3814 6009 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 6010 return 1;
b96ec7ac 6011 }
b96ec7ac 6012
3f9a994c
JB
6013 /* Otherwise, parse and supply the value. */
6014 p = buf;
6015 i = 0;
6016 while (p[0] != 0)
6017 {
6018 if (p[1] == 0)
74ca34ce 6019 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
6020
6021 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6022 p += 2;
6023 }
56be3814 6024 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 6025 return 1;
b96ec7ac
AC
6026}
6027
74ca34ce
DJ
6028/* Fetch the registers included in the target's 'g' packet. */
6029
29709017
DJ
6030static int
6031send_g_packet (void)
c906108c 6032{
d01949b6 6033 struct remote_state *rs = get_remote_state ();
cea39f65 6034 int buf_len;
c906108c 6035
bba74b36 6036 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 6037 remote_send (&rs->buf, &rs->buf_size);
c906108c 6038
29709017
DJ
6039 /* We can get out of synch in various cases. If the first character
6040 in the buffer is not a hex character, assume that has happened
6041 and try to fetch another packet to read. */
6042 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6043 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6044 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6045 && rs->buf[0] != 'x') /* New: unavailable register value. */
6046 {
6047 if (remote_debug)
6048 fprintf_unfiltered (gdb_stdlog,
6049 "Bad register packet; fetching a new packet\n");
6050 getpkt (&rs->buf, &rs->buf_size, 0);
6051 }
6052
74ca34ce
DJ
6053 buf_len = strlen (rs->buf);
6054
6055 /* Sanity check the received packet. */
6056 if (buf_len % 2 != 0)
6057 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
6058
6059 return buf_len / 2;
6060}
6061
6062static void
56be3814 6063process_g_packet (struct regcache *regcache)
29709017 6064{
4a22f64d 6065 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
6066 struct remote_state *rs = get_remote_state ();
6067 struct remote_arch_state *rsa = get_remote_arch_state ();
6068 int i, buf_len;
6069 char *p;
6070 char *regs;
6071
6072 buf_len = strlen (rs->buf);
6073
6074 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
6075 if (buf_len > 2 * rsa->sizeof_g_packet)
6076 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6077
6078 /* Save the size of the packet sent to us by the target. It is used
6079 as a heuristic when determining the max size of packets that the
6080 target can safely receive. */
6081 if (rsa->actual_register_packet_size == 0)
6082 rsa->actual_register_packet_size = buf_len;
6083
6084 /* If this is smaller than we guessed the 'g' packet would be,
6085 update our records. A 'g' reply that doesn't include a register's
6086 value implies either that the register is not available, or that
6087 the 'p' packet must be used. */
6088 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 6089 {
74ca34ce
DJ
6090 rsa->sizeof_g_packet = buf_len / 2;
6091
4a22f64d 6092 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 6093 {
74ca34ce
DJ
6094 if (rsa->regs[i].pnum == -1)
6095 continue;
6096
6097 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6098 rsa->regs[i].in_g_packet = 0;
b96ec7ac 6099 else
74ca34ce 6100 rsa->regs[i].in_g_packet = 1;
b96ec7ac 6101 }
74ca34ce 6102 }
b323314b 6103
74ca34ce 6104 regs = alloca (rsa->sizeof_g_packet);
c906108c
SS
6105
6106 /* Unimplemented registers read as all bits zero. */
ea9c271d 6107 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 6108
c906108c
SS
6109 /* Reply describes registers byte by byte, each byte encoded as two
6110 hex characters. Suck them all up, then supply them to the
6111 register cacheing/storage mechanism. */
6112
74ca34ce 6113 p = rs->buf;
ea9c271d 6114 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 6115 {
74ca34ce
DJ
6116 if (p[0] == 0 || p[1] == 0)
6117 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6118 internal_error (__FILE__, __LINE__,
9b20d036 6119 _("unexpected end of 'g' packet reply"));
74ca34ce 6120
c906108c 6121 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 6122 regs[i] = 0; /* 'x' */
c906108c
SS
6123 else
6124 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6125 p += 2;
6126 }
6127
a744cf53
MS
6128 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6129 {
6130 struct packet_reg *r = &rsa->regs[i];
6131
6132 if (r->in_g_packet)
6133 {
6134 if (r->offset * 2 >= strlen (rs->buf))
6135 /* This shouldn't happen - we adjusted in_g_packet above. */
6136 internal_error (__FILE__, __LINE__,
9b20d036 6137 _("unexpected end of 'g' packet reply"));
a744cf53
MS
6138 else if (rs->buf[r->offset * 2] == 'x')
6139 {
6140 gdb_assert (r->offset * 2 < strlen (rs->buf));
6141 /* The register isn't available, mark it as such (at
6142 the same time setting the value to zero). */
6143 regcache_raw_supply (regcache, r->regnum, NULL);
6144 }
6145 else
6146 regcache_raw_supply (regcache, r->regnum,
6147 regs + r->offset);
6148 }
6149 }
c906108c
SS
6150}
6151
29709017 6152static void
56be3814 6153fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
6154{
6155 send_g_packet ();
56be3814 6156 process_g_packet (regcache);
29709017
DJ
6157}
6158
e6e4e701
PA
6159/* Make the remote selected traceframe match GDB's selected
6160 traceframe. */
6161
6162static void
6163set_remote_traceframe (void)
6164{
6165 int newnum;
262e1174 6166 struct remote_state *rs = get_remote_state ();
e6e4e701 6167
262e1174 6168 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
6169 return;
6170
6171 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 6172 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
6173
6174 newnum = target_trace_find (tfind_number,
6175 get_traceframe_number (), 0, 0, NULL);
6176
6177 /* Should not happen. If it does, all bets are off. */
6178 if (newnum != get_traceframe_number ())
6179 warning (_("could not set remote traceframe"));
6180}
6181
74ca34ce 6182static void
28439f5e
PA
6183remote_fetch_registers (struct target_ops *ops,
6184 struct regcache *regcache, int regnum)
74ca34ce 6185{
74ca34ce
DJ
6186 struct remote_arch_state *rsa = get_remote_arch_state ();
6187 int i;
6188
e6e4e701 6189 set_remote_traceframe ();
79d7f229 6190 set_general_thread (inferior_ptid);
74ca34ce
DJ
6191
6192 if (regnum >= 0)
6193 {
6194 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6195
74ca34ce
DJ
6196 gdb_assert (reg != NULL);
6197
6198 /* If this register might be in the 'g' packet, try that first -
6199 we are likely to read more than one register. If this is the
6200 first 'g' packet, we might be overly optimistic about its
6201 contents, so fall back to 'p'. */
6202 if (reg->in_g_packet)
6203 {
56be3814 6204 fetch_registers_using_g (regcache);
74ca34ce
DJ
6205 if (reg->in_g_packet)
6206 return;
6207 }
6208
56be3814 6209 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
6210 return;
6211
6212 /* This register is not available. */
56be3814 6213 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
6214
6215 return;
6216 }
6217
56be3814 6218 fetch_registers_using_g (regcache);
74ca34ce 6219
4a22f64d 6220 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6221 if (!rsa->regs[i].in_g_packet)
56be3814 6222 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
6223 {
6224 /* This register is not available. */
56be3814 6225 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
6226 }
6227}
6228
c906108c
SS
6229/* Prepare to store registers. Since we may send them all (using a
6230 'G' request), we have to read out the ones we don't want to change
6231 first. */
6232
c5aa993b 6233static void
f32dbf8c 6234remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 6235{
ea9c271d 6236 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 6237 int i;
cfd77fa1 6238 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 6239
c906108c 6240 /* Make sure the entire registers array is valid. */
4082afcc 6241 switch (packet_support (PACKET_P))
5a2468f5
JM
6242 {
6243 case PACKET_DISABLE:
6244 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 6245 /* Make sure all the necessary registers are cached. */
4a22f64d 6246 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 6247 if (rsa->regs[i].in_g_packet)
316f2060 6248 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
6249 break;
6250 case PACKET_ENABLE:
6251 break;
6252 }
6253}
6254
ad10f812 6255/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 6256 packet was not recognized. */
5a2468f5
JM
6257
6258static int
1f4437a4
MS
6259store_register_using_P (const struct regcache *regcache,
6260 struct packet_reg *reg)
5a2468f5 6261{
4a22f64d 6262 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 6263 struct remote_state *rs = get_remote_state ();
5a2468f5 6264 /* Try storing a single register. */
6d820c5c 6265 char *buf = rs->buf;
cfd77fa1 6266 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 6267 char *p;
5a2468f5 6268
4082afcc 6269 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
6270 return 0;
6271
6272 if (reg->pnum == -1)
6273 return 0;
6274
ea9c271d 6275 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 6276 p = buf + strlen (buf);
56be3814 6277 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 6278 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
6279 putpkt (rs->buf);
6280 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 6281
74ca34ce
DJ
6282 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6283 {
6284 case PACKET_OK:
6285 return 1;
6286 case PACKET_ERROR:
27a9c0bf
MS
6287 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6288 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
6289 case PACKET_UNKNOWN:
6290 return 0;
6291 default:
6292 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6293 }
c906108c
SS
6294}
6295
23860348
MS
6296/* Store register REGNUM, or all registers if REGNUM == -1, from the
6297 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
6298
6299static void
56be3814 6300store_registers_using_G (const struct regcache *regcache)
c906108c 6301{
d01949b6 6302 struct remote_state *rs = get_remote_state ();
ea9c271d 6303 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 6304 gdb_byte *regs;
c906108c
SS
6305 char *p;
6306
193cb69f
AC
6307 /* Extract all the registers in the regcache copying them into a
6308 local buffer. */
6309 {
b323314b 6310 int i;
a744cf53 6311
ea9c271d
DJ
6312 regs = alloca (rsa->sizeof_g_packet);
6313 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 6314 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 6315 {
ea9c271d 6316 struct packet_reg *r = &rsa->regs[i];
a744cf53 6317
b323314b 6318 if (r->in_g_packet)
56be3814 6319 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
6320 }
6321 }
c906108c
SS
6322
6323 /* Command describes registers byte by byte,
6324 each byte encoded as two hex characters. */
6d820c5c 6325 p = rs->buf;
193cb69f 6326 *p++ = 'G';
74ca34ce
DJ
6327 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6328 updated. */
6329 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
6330 putpkt (rs->buf);
6331 getpkt (&rs->buf, &rs->buf_size, 0);
6332 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
6333 error (_("Could not write registers; remote failure reply '%s'"),
6334 rs->buf);
c906108c 6335}
74ca34ce
DJ
6336
6337/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6338 of the register cache buffer. FIXME: ignores errors. */
6339
6340static void
28439f5e
PA
6341remote_store_registers (struct target_ops *ops,
6342 struct regcache *regcache, int regnum)
74ca34ce 6343{
74ca34ce
DJ
6344 struct remote_arch_state *rsa = get_remote_arch_state ();
6345 int i;
6346
e6e4e701 6347 set_remote_traceframe ();
79d7f229 6348 set_general_thread (inferior_ptid);
74ca34ce
DJ
6349
6350 if (regnum >= 0)
6351 {
6352 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6353
74ca34ce
DJ
6354 gdb_assert (reg != NULL);
6355
6356 /* Always prefer to store registers using the 'P' packet if
6357 possible; we often change only a small number of registers.
6358 Sometimes we change a larger number; we'd need help from a
6359 higher layer to know to use 'G'. */
56be3814 6360 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
6361 return;
6362
6363 /* For now, don't complain if we have no way to write the
6364 register. GDB loses track of unavailable registers too
6365 easily. Some day, this may be an error. We don't have
0df8b418 6366 any way to read the register, either... */
74ca34ce
DJ
6367 if (!reg->in_g_packet)
6368 return;
6369
56be3814 6370 store_registers_using_G (regcache);
74ca34ce
DJ
6371 return;
6372 }
6373
56be3814 6374 store_registers_using_G (regcache);
74ca34ce 6375
4a22f64d 6376 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6377 if (!rsa->regs[i].in_g_packet)
56be3814 6378 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
6379 /* See above for why we do not issue an error here. */
6380 continue;
6381}
c906108c
SS
6382\f
6383
6384/* Return the number of hex digits in num. */
6385
6386static int
fba45db2 6387hexnumlen (ULONGEST num)
c906108c
SS
6388{
6389 int i;
6390
6391 for (i = 0; num != 0; i++)
6392 num >>= 4;
6393
6394 return max (i, 1);
6395}
6396
2df3850c 6397/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
6398
6399static int
fba45db2 6400hexnumstr (char *buf, ULONGEST num)
c906108c 6401{
c906108c 6402 int len = hexnumlen (num);
a744cf53 6403
2df3850c
JM
6404 return hexnumnstr (buf, num, len);
6405}
6406
c906108c 6407
2df3850c 6408/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 6409
2df3850c 6410static int
fba45db2 6411hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
6412{
6413 int i;
6414
6415 buf[width] = '\0';
6416
6417 for (i = width - 1; i >= 0; i--)
c906108c 6418 {
c5aa993b 6419 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
6420 num >>= 4;
6421 }
6422
2df3850c 6423 return width;
c906108c
SS
6424}
6425
23860348 6426/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
6427
6428static CORE_ADDR
fba45db2 6429remote_address_masked (CORE_ADDR addr)
c906108c 6430{
883b9c6c 6431 unsigned int address_size = remote_address_size;
a744cf53 6432
911c95a5
UW
6433 /* If "remoteaddresssize" was not set, default to target address size. */
6434 if (!address_size)
f5656ead 6435 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
6436
6437 if (address_size > 0
6438 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
6439 {
6440 /* Only create a mask when that mask can safely be constructed
23860348 6441 in a ULONGEST variable. */
c906108c 6442 ULONGEST mask = 1;
a744cf53 6443
911c95a5 6444 mask = (mask << address_size) - 1;
c906108c
SS
6445 addr &= mask;
6446 }
6447 return addr;
6448}
6449
6450/* Determine whether the remote target supports binary downloading.
6451 This is accomplished by sending a no-op memory write of zero length
6452 to the target at the specified address. It does not suffice to send
23860348
MS
6453 the whole packet, since many stubs strip the eighth bit and
6454 subsequently compute a wrong checksum, which causes real havoc with
6455 remote_write_bytes.
7a292a7a 6456
96baa820 6457 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 6458 clean. In cases like this, the user should clear "remote
23860348 6459 X-packet". */
96baa820 6460
c906108c 6461static void
fba45db2 6462check_binary_download (CORE_ADDR addr)
c906108c 6463{
d01949b6 6464 struct remote_state *rs = get_remote_state ();
24b06219 6465
4082afcc 6466 switch (packet_support (PACKET_X))
c906108c 6467 {
96baa820
JM
6468 case PACKET_DISABLE:
6469 break;
6470 case PACKET_ENABLE:
6471 break;
6472 case PACKET_SUPPORT_UNKNOWN:
6473 {
96baa820 6474 char *p;
802188a7 6475
2e9f7625 6476 p = rs->buf;
96baa820
JM
6477 *p++ = 'X';
6478 p += hexnumstr (p, (ULONGEST) addr);
6479 *p++ = ',';
6480 p += hexnumstr (p, (ULONGEST) 0);
6481 *p++ = ':';
6482 *p = '\0';
802188a7 6483
2e9f7625 6484 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 6485 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 6486
2e9f7625 6487 if (rs->buf[0] == '\0')
96baa820
JM
6488 {
6489 if (remote_debug)
6490 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
6491 "binary downloading NOT "
6492 "supported by target\n");
444abaca 6493 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
6494 }
6495 else
6496 {
6497 if (remote_debug)
6498 fprintf_unfiltered (gdb_stdlog,
64b9b334 6499 "binary downloading supported by target\n");
444abaca 6500 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
6501 }
6502 break;
6503 }
c906108c
SS
6504 }
6505}
6506
6507/* Write memory data directly to the remote machine.
6508 This does not inform the data cache; the data cache uses this.
a76d924d 6509 HEADER is the starting part of the packet.
c906108c
SS
6510 MEMADDR is the address in the remote memory space.
6511 MYADDR is the address of the buffer in our space.
6512 LEN is the number of bytes.
a76d924d
DJ
6513 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6514 should send data as binary ('X'), or hex-encoded ('M').
6515
6516 The function creates packet of the form
6517 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6518
6519 where encoding of <DATA> is termined by PACKET_FORMAT.
6520
6521 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6522 are omitted.
6523
9b409511
YQ
6524 Return the transferred status, error or OK (an
6525 'enum target_xfer_status' value). Save the number of bytes
6526 transferred in *XFERED_LEN. Only transfer a single packet. */
c906108c 6527
9b409511 6528static enum target_xfer_status
a76d924d 6529remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
5d6df423 6530 const gdb_byte *myaddr, ULONGEST len,
9b409511
YQ
6531 ULONGEST *xfered_len, char packet_format,
6532 int use_length)
c906108c 6533{
6d820c5c 6534 struct remote_state *rs = get_remote_state ();
cfd77fa1 6535 char *p;
a76d924d
DJ
6536 char *plen = NULL;
6537 int plenlen = 0;
917317f4
JM
6538 int todo;
6539 int nr_bytes;
a257b5bb 6540 int payload_size;
6765f3e5 6541 int payload_length;
a76d924d
DJ
6542 int header_length;
6543
6544 if (packet_format != 'X' && packet_format != 'M')
6545 internal_error (__FILE__, __LINE__,
9b20d036 6546 _("remote_write_bytes_aux: bad packet format"));
c906108c 6547
5d6df423 6548 if (len == 0)
9b409511 6549 return TARGET_XFER_EOF;
b2182ed2 6550
3de11b2e 6551 payload_size = get_memory_write_packet_size ();
2bc416ba 6552
6d820c5c
DJ
6553 /* The packet buffer will be large enough for the payload;
6554 get_memory_packet_size ensures this. */
a76d924d 6555 rs->buf[0] = '\0';
c906108c 6556
a257b5bb 6557 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
6558 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6559
a76d924d
DJ
6560 payload_size -= strlen ("$,:#NN");
6561 if (!use_length)
0df8b418 6562 /* The comma won't be used. */
a76d924d
DJ
6563 payload_size += 1;
6564 header_length = strlen (header);
6565 payload_size -= header_length;
3de11b2e 6566 payload_size -= hexnumlen (memaddr);
c906108c 6567
a76d924d 6568 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 6569
a76d924d
DJ
6570 strcat (rs->buf, header);
6571 p = rs->buf + strlen (header);
6572
6573 /* Compute a best guess of the number of bytes actually transfered. */
6574 if (packet_format == 'X')
c906108c 6575 {
23860348 6576 /* Best guess at number of bytes that will fit. */
a257b5bb 6577 todo = min (len, payload_size);
a76d924d
DJ
6578 if (use_length)
6579 payload_size -= hexnumlen (todo);
3de11b2e 6580 todo = min (todo, payload_size);
a76d924d
DJ
6581 }
6582 else
6583 {
23860348 6584 /* Num bytes that will fit. */
a257b5bb 6585 todo = min (len, payload_size / 2);
a76d924d
DJ
6586 if (use_length)
6587 payload_size -= hexnumlen (todo);
3de11b2e 6588 todo = min (todo, payload_size / 2);
917317f4 6589 }
a76d924d 6590
3de11b2e
NS
6591 if (todo <= 0)
6592 internal_error (__FILE__, __LINE__,
405f8e94 6593 _("minimum packet size too small to write data"));
802188a7 6594
6765f3e5
DJ
6595 /* If we already need another packet, then try to align the end
6596 of this packet to a useful boundary. */
6597 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6598 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6599
a257b5bb 6600 /* Append "<memaddr>". */
917317f4
JM
6601 memaddr = remote_address_masked (memaddr);
6602 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 6603
a76d924d
DJ
6604 if (use_length)
6605 {
6606 /* Append ",". */
6607 *p++ = ',';
802188a7 6608
a76d924d
DJ
6609 /* Append <len>. Retain the location/size of <len>. It may need to
6610 be adjusted once the packet body has been created. */
6611 plen = p;
6612 plenlen = hexnumstr (p, (ULONGEST) todo);
6613 p += plenlen;
6614 }
a257b5bb
AC
6615
6616 /* Append ":". */
917317f4
JM
6617 *p++ = ':';
6618 *p = '\0';
802188a7 6619
a257b5bb 6620 /* Append the packet body. */
a76d924d 6621 if (packet_format == 'X')
917317f4 6622 {
917317f4
JM
6623 /* Binary mode. Send target system values byte by byte, in
6624 increasing byte addresses. Only escape certain critical
6625 characters. */
bc20a4af
PA
6626 payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
6627 &nr_bytes, payload_size);
6765f3e5
DJ
6628
6629 /* If not all TODO bytes fit, then we'll need another packet. Make
9b7194bc
DJ
6630 a second try to keep the end of the packet aligned. Don't do
6631 this if the packet is tiny. */
6632 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6765f3e5
DJ
6633 {
6634 int new_nr_bytes;
6635
6636 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6637 - memaddr);
6638 if (new_nr_bytes != nr_bytes)
6639 payload_length = remote_escape_output (myaddr, new_nr_bytes,
bc20a4af 6640 (gdb_byte *) p, &nr_bytes,
6765f3e5
DJ
6641 payload_size);
6642 }
6643
6644 p += payload_length;
a76d924d 6645 if (use_length && nr_bytes < todo)
c906108c 6646 {
802188a7 6647 /* Escape chars have filled up the buffer prematurely,
917317f4
JM
6648 and we have actually sent fewer bytes than planned.
6649 Fix-up the length field of the packet. Use the same
6650 number of characters as before. */
917317f4
JM
6651 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6652 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 6653 }
a76d924d
DJ
6654 }
6655 else
6656 {
917317f4
JM
6657 /* Normal mode: Send target system values byte by byte, in
6658 increasing byte addresses. Each byte is encoded as a two hex
6659 value. */
2644f393 6660 nr_bytes = bin2hex (myaddr, p, todo);
aa6c0017 6661 p += 2 * nr_bytes;
c906108c 6662 }
802188a7 6663
2e9f7625 6664 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 6665 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 6666
2e9f7625 6667 if (rs->buf[0] == 'E')
00d84524 6668 return TARGET_XFER_E_IO;
802188a7 6669
23860348
MS
6670 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6671 fewer bytes than we'd planned. */
9b409511
YQ
6672 *xfered_len = (ULONGEST) nr_bytes;
6673 return TARGET_XFER_OK;
c906108c
SS
6674}
6675
a76d924d
DJ
6676/* Write memory data directly to the remote machine.
6677 This does not inform the data cache; the data cache uses this.
6678 MEMADDR is the address in the remote memory space.
6679 MYADDR is the address of the buffer in our space.
6680 LEN is the number of bytes.
6681
9b409511
YQ
6682 Return the transferred status, error or OK (an
6683 'enum target_xfer_status' value). Save the number of bytes
6684 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 6685
9b409511
YQ
6686static enum target_xfer_status
6687remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
6688 ULONGEST *xfered_len)
a76d924d
DJ
6689{
6690 char *packet_format = 0;
6691
6692 /* Check whether the target supports binary download. */
6693 check_binary_download (memaddr);
6694
4082afcc 6695 switch (packet_support (PACKET_X))
a76d924d
DJ
6696 {
6697 case PACKET_ENABLE:
6698 packet_format = "X";
6699 break;
6700 case PACKET_DISABLE:
6701 packet_format = "M";
6702 break;
6703 case PACKET_SUPPORT_UNKNOWN:
6704 internal_error (__FILE__, __LINE__,
6705 _("remote_write_bytes: bad internal state"));
6706 default:
6707 internal_error (__FILE__, __LINE__, _("bad switch"));
6708 }
6709
6710 return remote_write_bytes_aux (packet_format,
9b409511
YQ
6711 memaddr, myaddr, len, xfered_len,
6712 packet_format[0], 1);
a76d924d
DJ
6713}
6714
9217e74e
YQ
6715/* Read memory data directly from the remote machine.
6716 This does not use the data cache; the data cache uses this.
6717 MEMADDR is the address in the remote memory space.
6718 MYADDR is the address of the buffer in our space.
6719 LEN is the number of bytes.
6720
6721 Return the transferred status, error or OK (an
6722 'enum target_xfer_status' value). Save the number of bytes
6723 transferred in *XFERED_LEN. */
6724
6725static enum target_xfer_status
6726remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len,
6727 ULONGEST *xfered_len)
6728{
6729 struct remote_state *rs = get_remote_state ();
6730 int max_buf_size; /* Max size of packet output buffer. */
6731 char *p;
6732 int todo;
6733 int i;
6734
6735 max_buf_size = get_memory_read_packet_size ();
6736 /* The packet buffer will be large enough for the payload;
6737 get_memory_packet_size ensures this. */
6738
6739 /* Number if bytes that will fit. */
6740 todo = min (len, max_buf_size / 2);
6741
6742 /* Construct "m"<memaddr>","<len>". */
6743 memaddr = remote_address_masked (memaddr);
6744 p = rs->buf;
6745 *p++ = 'm';
6746 p += hexnumstr (p, (ULONGEST) memaddr);
6747 *p++ = ',';
6748 p += hexnumstr (p, (ULONGEST) todo);
6749 *p = '\0';
6750 putpkt (rs->buf);
6751 getpkt (&rs->buf, &rs->buf_size, 0);
6752 if (rs->buf[0] == 'E'
6753 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6754 && rs->buf[3] == '\0')
6755 return TARGET_XFER_E_IO;
6756 /* Reply describes memory byte by byte, each byte encoded as two hex
6757 characters. */
6758 p = rs->buf;
6759 i = hex2bin (p, myaddr, todo);
6760 /* Return what we have. Let higher layers handle partial reads. */
6761 *xfered_len = (ULONGEST) i;
6762 return TARGET_XFER_OK;
6763}
6764
b55fbac4
YQ
6765/* Using the set of read-only target sections of remote, read live
6766 read-only memory.
8acf9577
YQ
6767
6768 For interface/parameters/return description see target.h,
6769 to_xfer_partial. */
6770
6771static enum target_xfer_status
b55fbac4
YQ
6772remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
6773 ULONGEST memaddr, ULONGEST len,
6774 ULONGEST *xfered_len)
8acf9577
YQ
6775{
6776 struct target_section *secp;
6777 struct target_section_table *table;
6778
6779 secp = target_section_by_addr (ops, memaddr);
6780 if (secp != NULL
6781 && (bfd_get_section_flags (secp->the_bfd_section->owner,
6782 secp->the_bfd_section)
6783 & SEC_READONLY))
6784 {
6785 struct target_section *p;
6786 ULONGEST memend = memaddr + len;
6787
6788 table = target_get_section_table (ops);
6789
6790 for (p = table->sections; p < table->sections_end; p++)
6791 {
6792 if (memaddr >= p->addr)
6793 {
6794 if (memend <= p->endaddr)
6795 {
6796 /* Entire transfer is within this section. */
b55fbac4
YQ
6797 return remote_read_bytes_1 (memaddr, readbuf, len,
6798 xfered_len);
8acf9577
YQ
6799 }
6800 else if (memaddr >= p->endaddr)
6801 {
6802 /* This section ends before the transfer starts. */
6803 continue;
6804 }
6805 else
6806 {
6807 /* This section overlaps the transfer. Just do half. */
6808 len = p->endaddr - memaddr;
b55fbac4
YQ
6809 return remote_read_bytes_1 (memaddr, readbuf, len,
6810 xfered_len);
8acf9577
YQ
6811 }
6812 }
6813 }
6814 }
6815
6816 return TARGET_XFER_EOF;
6817}
6818
9217e74e
YQ
6819/* Similar to remote_read_bytes_1, but it reads from the remote stub
6820 first if the requested memory is unavailable in traceframe.
6821 Otherwise, fall back to remote_read_bytes_1. */
c906108c 6822
9b409511 6823static enum target_xfer_status
8acf9577
YQ
6824remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
6825 gdb_byte *myaddr, ULONGEST len, ULONGEST *xfered_len)
c906108c 6826{
6b6aa828 6827 if (len == 0)
b2182ed2
DJ
6828 return 0;
6829
8acf9577
YQ
6830 if (get_traceframe_number () != -1)
6831 {
6832 VEC(mem_range_s) *available;
6833
6834 /* If we fail to get the set of available memory, then the
6835 target does not support querying traceframe info, and so we
6836 attempt reading from the traceframe anyway (assuming the
6837 target implements the old QTro packet then). */
6838 if (traceframe_available_memory (&available, memaddr, len))
6839 {
6840 struct cleanup *old_chain;
6841
6842 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
6843
6844 if (VEC_empty (mem_range_s, available)
6845 || VEC_index (mem_range_s, available, 0)->start != memaddr)
6846 {
6847 enum target_xfer_status res;
6848
6849 /* Don't read into the traceframe's available
6850 memory. */
6851 if (!VEC_empty (mem_range_s, available))
6852 {
6853 LONGEST oldlen = len;
6854
6855 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
6856 gdb_assert (len <= oldlen);
6857 }
6858
6859 do_cleanups (old_chain);
6860
6861 /* This goes through the topmost target again. */
b55fbac4 6862 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8acf9577
YQ
6863 len, xfered_len);
6864 if (res == TARGET_XFER_OK)
6865 return TARGET_XFER_OK;
6866 else
6867 {
6868 /* No use trying further, we know some memory starting
6869 at MEMADDR isn't available. */
6870 *xfered_len = len;
6871 return TARGET_XFER_UNAVAILABLE;
6872 }
6873 }
6874
6875 /* Don't try to read more than how much is available, in
6876 case the target implements the deprecated QTro packet to
6877 cater for older GDBs (the target's knowledge of read-only
6878 sections may be outdated by now). */
6879 len = VEC_index (mem_range_s, available, 0)->length;
6880
6881 do_cleanups (old_chain);
6882 }
6883 }
6884
9217e74e 6885 return remote_read_bytes_1 (memaddr, myaddr, len, xfered_len);
c906108c 6886}
74531fed 6887
c906108c 6888\f
c906108c 6889
a76d924d
DJ
6890/* Sends a packet with content determined by the printf format string
6891 FORMAT and the remaining arguments, then gets the reply. Returns
6892 whether the packet was a success, a failure, or unknown. */
6893
2c0b251b 6894static enum packet_result
a76d924d
DJ
6895remote_send_printf (const char *format, ...)
6896{
6897 struct remote_state *rs = get_remote_state ();
6898 int max_size = get_remote_packet_size ();
a76d924d 6899 va_list ap;
a744cf53 6900
a76d924d
DJ
6901 va_start (ap, format);
6902
6903 rs->buf[0] = '\0';
6904 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 6905 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
6906
6907 if (putpkt (rs->buf) < 0)
6908 error (_("Communication problem with target."));
6909
6910 rs->buf[0] = '\0';
6911 getpkt (&rs->buf, &rs->buf_size, 0);
6912
6913 return packet_check_result (rs->buf);
6914}
6915
6916static void
6917restore_remote_timeout (void *p)
6918{
6919 int value = *(int *)p;
a744cf53 6920
a76d924d
DJ
6921 remote_timeout = value;
6922}
6923
6924/* Flash writing can take quite some time. We'll set
6925 effectively infinite timeout for flash operations.
6926 In future, we'll need to decide on a better approach. */
6927static const int remote_flash_timeout = 1000;
6928
6929static void
6930remote_flash_erase (struct target_ops *ops,
6931 ULONGEST address, LONGEST length)
6932{
f5656ead 6933 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
6934 int saved_remote_timeout = remote_timeout;
6935 enum packet_result ret;
a76d924d
DJ
6936 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6937 &saved_remote_timeout);
a744cf53 6938
a76d924d
DJ
6939 remote_timeout = remote_flash_timeout;
6940
6941 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 6942 phex (address, addr_size),
a76d924d
DJ
6943 phex (length, 4));
6944 switch (ret)
6945 {
6946 case PACKET_UNKNOWN:
6947 error (_("Remote target does not support flash erase"));
6948 case PACKET_ERROR:
6949 error (_("Error erasing flash with vFlashErase packet"));
6950 default:
6951 break;
6952 }
6953
6954 do_cleanups (back_to);
6955}
6956
9b409511
YQ
6957static enum target_xfer_status
6958remote_flash_write (struct target_ops *ops, ULONGEST address,
6959 ULONGEST length, ULONGEST *xfered_len,
6960 const gdb_byte *data)
a76d924d
DJ
6961{
6962 int saved_remote_timeout = remote_timeout;
9b409511 6963 enum target_xfer_status ret;
a76d924d 6964 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 6965 &saved_remote_timeout);
a76d924d
DJ
6966
6967 remote_timeout = remote_flash_timeout;
9b409511
YQ
6968 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length,
6969 xfered_len,'X', 0);
a76d924d
DJ
6970 do_cleanups (back_to);
6971
6972 return ret;
6973}
6974
6975static void
6976remote_flash_done (struct target_ops *ops)
6977{
6978 int saved_remote_timeout = remote_timeout;
6979 int ret;
6980 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6981 &saved_remote_timeout);
6982
6983 remote_timeout = remote_flash_timeout;
6984 ret = remote_send_printf ("vFlashDone");
6985 do_cleanups (back_to);
6986
6987 switch (ret)
6988 {
6989 case PACKET_UNKNOWN:
6990 error (_("Remote target does not support vFlashDone"));
6991 case PACKET_ERROR:
6992 error (_("Error finishing flash operation"));
6993 default:
6994 break;
6995 }
6996}
6997
c906108c 6998static void
fba45db2 6999remote_files_info (struct target_ops *ignore)
c906108c
SS
7000{
7001 puts_filtered ("Debugging a target over a serial line.\n");
7002}
7003\f
7004/* Stuff for dealing with the packets which are part of this protocol.
7005 See comment at top of file for details. */
7006
1927e618
PA
7007/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7008 error to higher layers. Called when a serial error is detected.
7009 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
7010 the system error message for errno at function entry and final dot
7011 for output compatibility with throw_perror_with_name. */
1927e618
PA
7012
7013static void
7014unpush_and_perror (const char *string)
7015{
d6cb50a2 7016 int saved_errno = errno;
1927e618
PA
7017
7018 remote_unpush_target ();
d6cb50a2
JK
7019 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7020 safe_strerror (saved_errno));
1927e618
PA
7021}
7022
0876f84a 7023/* Read a single character from the remote end. */
c906108c
SS
7024
7025static int
fba45db2 7026readchar (int timeout)
c906108c
SS
7027{
7028 int ch;
5d93a237 7029 struct remote_state *rs = get_remote_state ();
c906108c 7030
5d93a237 7031 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 7032
2acceee2 7033 if (ch >= 0)
0876f84a 7034 return ch;
2acceee2
JM
7035
7036 switch ((enum serial_rc) ch)
c906108c
SS
7037 {
7038 case SERIAL_EOF:
78a095c3 7039 remote_unpush_target ();
598d3636 7040 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 7041 /* no return */
c906108c 7042 case SERIAL_ERROR:
1927e618
PA
7043 unpush_and_perror (_("Remote communication error. "
7044 "Target disconnected."));
2acceee2 7045 /* no return */
c906108c 7046 case SERIAL_TIMEOUT:
2acceee2 7047 break;
c906108c 7048 }
2acceee2 7049 return ch;
c906108c
SS
7050}
7051
c33e31fd
PA
7052/* Wrapper for serial_write that closes the target and throws if
7053 writing fails. */
7054
7055static void
7056remote_serial_write (const char *str, int len)
7057{
5d93a237
TT
7058 struct remote_state *rs = get_remote_state ();
7059
7060 if (serial_write (rs->remote_desc, str, len))
c33e31fd 7061 {
1927e618
PA
7062 unpush_and_perror (_("Remote communication error. "
7063 "Target disconnected."));
c33e31fd
PA
7064 }
7065}
7066
6d820c5c
DJ
7067/* Send the command in *BUF to the remote machine, and read the reply
7068 into *BUF. Report an error if we get an error reply. Resize
7069 *BUF using xrealloc if necessary to hold the result, and update
7070 *SIZEOF_BUF. */
c906108c
SS
7071
7072static void
6d820c5c
DJ
7073remote_send (char **buf,
7074 long *sizeof_buf)
c906108c 7075{
6d820c5c 7076 putpkt (*buf);
c2d11a7d 7077 getpkt (buf, sizeof_buf, 0);
c906108c 7078
6d820c5c
DJ
7079 if ((*buf)[0] == 'E')
7080 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
7081}
7082
6e5abd65
PA
7083/* Return a pointer to an xmalloc'ed string representing an escaped
7084 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7085 etc. The caller is responsible for releasing the returned
7086 memory. */
7087
7088static char *
7089escape_buffer (const char *buf, int n)
7090{
7091 struct cleanup *old_chain;
7092 struct ui_file *stb;
7093 char *str;
6e5abd65
PA
7094
7095 stb = mem_fileopen ();
7096 old_chain = make_cleanup_ui_file_delete (stb);
7097
6ef284bd 7098 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 7099 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
7100 do_cleanups (old_chain);
7101 return str;
7102}
7103
c906108c
SS
7104/* Display a null-terminated packet on stdout, for debugging, using C
7105 string notation. */
7106
7107static void
baa336ce 7108print_packet (const char *buf)
c906108c
SS
7109{
7110 puts_filtered ("\"");
43e526b9 7111 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
7112 puts_filtered ("\"");
7113}
7114
7115int
baa336ce 7116putpkt (const char *buf)
c906108c
SS
7117{
7118 return putpkt_binary (buf, strlen (buf));
7119}
7120
7121/* Send a packet to the remote machine, with error checking. The data
23860348 7122 of the packet is in BUF. The string in BUF can be at most
ea9c271d 7123 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
7124 and for a possible /0 if we are debugging (remote_debug) and want
7125 to print the sent packet as a string. */
c906108c
SS
7126
7127static int
baa336ce 7128putpkt_binary (const char *buf, int cnt)
c906108c 7129{
2d717e4f 7130 struct remote_state *rs = get_remote_state ();
c906108c
SS
7131 int i;
7132 unsigned char csum = 0;
11cf8741 7133 char *buf2 = alloca (cnt + 6);
085dd6e6 7134
c906108c
SS
7135 int ch;
7136 int tcount = 0;
7137 char *p;
dd61ec5c 7138 char *message;
c906108c 7139
e24a49d8
PA
7140 /* Catch cases like trying to read memory or listing threads while
7141 we're waiting for a stop reply. The remote server wouldn't be
7142 ready to handle this request, so we'd hang and timeout. We don't
7143 have to worry about this in synchronous mode, because in that
7144 case it's not possible to issue a command while the target is
74531fed
PA
7145 running. This is not a problem in non-stop mode, because in that
7146 case, the stub is always ready to process serial input. */
7147 if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
9597b22a
DE
7148 {
7149 error (_("Cannot execute this command while the target is running.\n"
7150 "Use the \"interrupt\" command to stop the target\n"
7151 "and then try again."));
7152 }
e24a49d8 7153
2d717e4f
DJ
7154 /* We're sending out a new packet. Make sure we don't look at a
7155 stale cached response. */
7156 rs->cached_wait_status = 0;
7157
c906108c
SS
7158 /* Copy the packet into buffer BUF2, encapsulating it
7159 and giving it a checksum. */
7160
c906108c
SS
7161 p = buf2;
7162 *p++ = '$';
7163
7164 for (i = 0; i < cnt; i++)
7165 {
7166 csum += buf[i];
7167 *p++ = buf[i];
7168 }
7169 *p++ = '#';
7170 *p++ = tohex ((csum >> 4) & 0xf);
7171 *p++ = tohex (csum & 0xf);
7172
7173 /* Send it over and over until we get a positive ack. */
7174
7175 while (1)
7176 {
7177 int started_error_output = 0;
7178
7179 if (remote_debug)
7180 {
6e5abd65
PA
7181 struct cleanup *old_chain;
7182 char *str;
7183
c906108c 7184 *p = '\0';
6e5abd65
PA
7185 str = escape_buffer (buf2, p - buf2);
7186 old_chain = make_cleanup (xfree, str);
7187 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 7188 gdb_flush (gdb_stdlog);
6e5abd65 7189 do_cleanups (old_chain);
c906108c 7190 }
c33e31fd 7191 remote_serial_write (buf2, p - buf2);
c906108c 7192
a6f3e723
SL
7193 /* If this is a no acks version of the remote protocol, send the
7194 packet and move on. */
7195 if (rs->noack_mode)
7196 break;
7197
74531fed
PA
7198 /* Read until either a timeout occurs (-2) or '+' is read.
7199 Handle any notification that arrives in the mean time. */
c906108c
SS
7200 while (1)
7201 {
7202 ch = readchar (remote_timeout);
7203
c5aa993b 7204 if (remote_debug)
c906108c
SS
7205 {
7206 switch (ch)
7207 {
7208 case '+':
1216fa2c 7209 case '-':
c906108c
SS
7210 case SERIAL_TIMEOUT:
7211 case '$':
74531fed 7212 case '%':
c906108c
SS
7213 if (started_error_output)
7214 {
7215 putchar_unfiltered ('\n');
7216 started_error_output = 0;
7217 }
7218 }
7219 }
7220
7221 switch (ch)
7222 {
7223 case '+':
7224 if (remote_debug)
0f71a2f6 7225 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 7226 return 1;
1216fa2c
AC
7227 case '-':
7228 if (remote_debug)
7229 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 7230 /* FALLTHROUGH */
c906108c 7231 case SERIAL_TIMEOUT:
c5aa993b 7232 tcount++;
c906108c
SS
7233 if (tcount > 3)
7234 return 0;
23860348 7235 break; /* Retransmit buffer. */
c906108c
SS
7236 case '$':
7237 {
40e3f985 7238 if (remote_debug)
2bc416ba 7239 fprintf_unfiltered (gdb_stdlog,
23860348 7240 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
7241 /* It's probably an old response sent because an ACK
7242 was lost. Gobble up the packet and ack it so it
7243 doesn't get retransmitted when we resend this
7244 packet. */
6d820c5c 7245 skip_frame ();
c33e31fd 7246 remote_serial_write ("+", 1);
23860348 7247 continue; /* Now, go look for +. */
c906108c 7248 }
74531fed
PA
7249
7250 case '%':
7251 {
7252 int val;
7253
7254 /* If we got a notification, handle it, and go back to looking
7255 for an ack. */
7256 /* We've found the start of a notification. Now
7257 collect the data. */
7258 val = read_frame (&rs->buf, &rs->buf_size);
7259 if (val >= 0)
7260 {
7261 if (remote_debug)
7262 {
6e5abd65
PA
7263 struct cleanup *old_chain;
7264 char *str;
7265
7266 str = escape_buffer (rs->buf, val);
7267 old_chain = make_cleanup (xfree, str);
7268 fprintf_unfiltered (gdb_stdlog,
7269 " Notification received: %s\n",
7270 str);
7271 do_cleanups (old_chain);
74531fed 7272 }
5965e028 7273 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
7274 /* We're in sync now, rewait for the ack. */
7275 tcount = 0;
7276 }
7277 else
7278 {
7279 if (remote_debug)
7280 {
7281 if (!started_error_output)
7282 {
7283 started_error_output = 1;
7284 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7285 }
7286 fputc_unfiltered (ch & 0177, gdb_stdlog);
7287 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7288 }
7289 }
7290 continue;
7291 }
7292 /* fall-through */
c906108c
SS
7293 default:
7294 if (remote_debug)
7295 {
7296 if (!started_error_output)
7297 {
7298 started_error_output = 1;
0f71a2f6 7299 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 7300 }
0f71a2f6 7301 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
7302 }
7303 continue;
7304 }
23860348 7305 break; /* Here to retransmit. */
c906108c
SS
7306 }
7307
7308#if 0
7309 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
7310 able to get out next time we call QUIT, without anything as
7311 violent as interrupt_query. If we want to provide a way out of
7312 here without getting to the next QUIT, it should be based on
7313 hitting ^C twice as in remote_wait. */
c906108c
SS
7314 if (quit_flag)
7315 {
7316 quit_flag = 0;
7317 interrupt_query ();
7318 }
7319#endif
7320 }
a6f3e723 7321 return 0;
c906108c
SS
7322}
7323
6d820c5c
DJ
7324/* Come here after finding the start of a frame when we expected an
7325 ack. Do our best to discard the rest of this packet. */
7326
7327static void
7328skip_frame (void)
7329{
7330 int c;
7331
7332 while (1)
7333 {
7334 c = readchar (remote_timeout);
7335 switch (c)
7336 {
7337 case SERIAL_TIMEOUT:
7338 /* Nothing we can do. */
7339 return;
7340 case '#':
7341 /* Discard the two bytes of checksum and stop. */
7342 c = readchar (remote_timeout);
7343 if (c >= 0)
7344 c = readchar (remote_timeout);
7345
7346 return;
7347 case '*': /* Run length encoding. */
7348 /* Discard the repeat count. */
7349 c = readchar (remote_timeout);
7350 if (c < 0)
7351 return;
7352 break;
7353 default:
7354 /* A regular character. */
7355 break;
7356 }
7357 }
7358}
7359
c906108c 7360/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
7361 into *BUF, verifying the checksum, length, and handling run-length
7362 compression. NUL terminate the buffer. If there is not enough room,
7363 expand *BUF using xrealloc.
c906108c 7364
c2d11a7d
JM
7365 Returns -1 on error, number of characters in buffer (ignoring the
7366 trailing NULL) on success. (could be extended to return one of the
23860348 7367 SERIAL status indications). */
c2d11a7d
JM
7368
7369static long
6d820c5c
DJ
7370read_frame (char **buf_p,
7371 long *sizeof_buf)
c906108c
SS
7372{
7373 unsigned char csum;
c2d11a7d 7374 long bc;
c906108c 7375 int c;
6d820c5c 7376 char *buf = *buf_p;
a6f3e723 7377 struct remote_state *rs = get_remote_state ();
c906108c
SS
7378
7379 csum = 0;
c2d11a7d 7380 bc = 0;
c906108c
SS
7381
7382 while (1)
7383 {
7384 c = readchar (remote_timeout);
c906108c
SS
7385 switch (c)
7386 {
7387 case SERIAL_TIMEOUT:
7388 if (remote_debug)
0f71a2f6 7389 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 7390 return -1;
c906108c
SS
7391 case '$':
7392 if (remote_debug)
0f71a2f6
JM
7393 fputs_filtered ("Saw new packet start in middle of old one\n",
7394 gdb_stdlog);
23860348 7395 return -1; /* Start a new packet, count retries. */
c906108c
SS
7396 case '#':
7397 {
7398 unsigned char pktcsum;
e1b09194
AC
7399 int check_0 = 0;
7400 int check_1 = 0;
c906108c 7401
c2d11a7d 7402 buf[bc] = '\0';
c906108c 7403
e1b09194
AC
7404 check_0 = readchar (remote_timeout);
7405 if (check_0 >= 0)
7406 check_1 = readchar (remote_timeout);
802188a7 7407
e1b09194
AC
7408 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7409 {
7410 if (remote_debug)
2bc416ba 7411 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 7412 gdb_stdlog);
e1b09194
AC
7413 return -1;
7414 }
7415 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
7416 {
7417 if (remote_debug)
2bc416ba 7418 fputs_filtered ("Communication error in checksum\n",
23860348 7419 gdb_stdlog);
40e3f985
FN
7420 return -1;
7421 }
c906108c 7422
a6f3e723
SL
7423 /* Don't recompute the checksum; with no ack packets we
7424 don't have any way to indicate a packet retransmission
7425 is necessary. */
7426 if (rs->noack_mode)
7427 return bc;
7428
e1b09194 7429 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 7430 if (csum == pktcsum)
c2d11a7d 7431 return bc;
c906108c 7432
c5aa993b 7433 if (remote_debug)
c906108c 7434 {
6e5abd65
PA
7435 struct cleanup *old_chain;
7436 char *str;
7437
7438 str = escape_buffer (buf, bc);
7439 old_chain = make_cleanup (xfree, str);
7440 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7441 "Bad checksum, sentsum=0x%x, "
7442 "csum=0x%x, buf=%s\n",
6e5abd65
PA
7443 pktcsum, csum, str);
7444 do_cleanups (old_chain);
c906108c 7445 }
c2d11a7d 7446 /* Number of characters in buffer ignoring trailing
23860348 7447 NULL. */
c2d11a7d 7448 return -1;
c906108c 7449 }
23860348 7450 case '*': /* Run length encoding. */
c2c6d25f
JM
7451 {
7452 int repeat;
c906108c 7453
a744cf53 7454 csum += c;
b4501125
AC
7455 c = readchar (remote_timeout);
7456 csum += c;
23860348 7457 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 7458
23860348 7459 /* The character before ``*'' is repeated. */
c2d11a7d 7460
6d820c5c 7461 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 7462 {
6d820c5c
DJ
7463 if (bc + repeat - 1 >= *sizeof_buf - 1)
7464 {
7465 /* Make some more room in the buffer. */
7466 *sizeof_buf += repeat;
7467 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7468 buf = *buf_p;
7469 }
7470
c2d11a7d
JM
7471 memset (&buf[bc], buf[bc - 1], repeat);
7472 bc += repeat;
c2c6d25f
JM
7473 continue;
7474 }
7475
c2d11a7d 7476 buf[bc] = '\0';
6d820c5c 7477 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 7478 return -1;
c2c6d25f 7479 }
c906108c 7480 default:
6d820c5c 7481 if (bc >= *sizeof_buf - 1)
c906108c 7482 {
6d820c5c
DJ
7483 /* Make some more room in the buffer. */
7484 *sizeof_buf *= 2;
7485 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7486 buf = *buf_p;
c906108c
SS
7487 }
7488
6d820c5c
DJ
7489 buf[bc++] = c;
7490 csum += c;
7491 continue;
c906108c
SS
7492 }
7493 }
7494}
7495
7496/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
7497 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7498 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7499 rather than timing out; this is used (in synchronous mode) to wait
7500 for a target that is is executing user code to stop. */
d9fcf2fb
JM
7501/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7502 don't have to change all the calls to getpkt to deal with the
7503 return value, because at the moment I don't know what the right
23860348 7504 thing to do it for those. */
c906108c 7505void
6d820c5c
DJ
7506getpkt (char **buf,
7507 long *sizeof_buf,
c2d11a7d 7508 int forever)
d9fcf2fb
JM
7509{
7510 int timed_out;
7511
7512 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7513}
7514
7515
7516/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
7517 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7518 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7519 rather than timing out; this is used (in synchronous mode) to wait
7520 for a target that is is executing user code to stop. If FOREVER ==
7521 0, this function is allowed to time out gracefully and return an
74531fed
PA
7522 indication of this to the caller. Otherwise return the number of
7523 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
7524 enough reason to return to the caller. *IS_NOTIF is an output
7525 boolean that indicates whether *BUF holds a notification or not
7526 (a regular packet). */
74531fed 7527
3172dc30 7528static int
74531fed 7529getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 7530 int expecting_notif, int *is_notif)
c906108c 7531{
2d717e4f 7532 struct remote_state *rs = get_remote_state ();
c906108c
SS
7533 int c;
7534 int tries;
7535 int timeout;
df4b58fe 7536 int val = -1;
c906108c 7537
2d717e4f
DJ
7538 /* We're reading a new response. Make sure we don't look at a
7539 previously cached response. */
7540 rs->cached_wait_status = 0;
7541
6d820c5c 7542 strcpy (*buf, "timeout");
c906108c
SS
7543
7544 if (forever)
74531fed
PA
7545 timeout = watchdog > 0 ? watchdog : -1;
7546 else if (expecting_notif)
7547 timeout = 0; /* There should already be a char in the buffer. If
7548 not, bail out. */
c906108c
SS
7549 else
7550 timeout = remote_timeout;
7551
7552#define MAX_TRIES 3
7553
74531fed
PA
7554 /* Process any number of notifications, and then return when
7555 we get a packet. */
7556 for (;;)
c906108c 7557 {
d9c43928 7558 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
7559 times. */
7560 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 7561 {
74531fed
PA
7562 /* This can loop forever if the remote side sends us
7563 characters continuously, but if it pauses, we'll get
7564 SERIAL_TIMEOUT from readchar because of timeout. Then
7565 we'll count that as a retry.
7566
7567 Note that even when forever is set, we will only wait
7568 forever prior to the start of a packet. After that, we
7569 expect characters to arrive at a brisk pace. They should
7570 show up within remote_timeout intervals. */
7571 do
7572 c = readchar (timeout);
7573 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
7574
7575 if (c == SERIAL_TIMEOUT)
7576 {
74531fed
PA
7577 if (expecting_notif)
7578 return -1; /* Don't complain, it's normal to not get
7579 anything in this case. */
7580
23860348 7581 if (forever) /* Watchdog went off? Kill the target. */
c906108c 7582 {
2acceee2 7583 QUIT;
78a095c3 7584 remote_unpush_target ();
598d3636
JK
7585 throw_error (TARGET_CLOSE_ERROR,
7586 _("Watchdog timeout has expired. "
7587 "Target detached."));
c906108c 7588 }
c906108c 7589 if (remote_debug)
0f71a2f6 7590 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 7591 }
74531fed
PA
7592 else
7593 {
7594 /* We've found the start of a packet or notification.
7595 Now collect the data. */
7596 val = read_frame (buf, sizeof_buf);
7597 if (val >= 0)
7598 break;
7599 }
7600
c33e31fd 7601 remote_serial_write ("-", 1);
c906108c 7602 }
c906108c 7603
74531fed
PA
7604 if (tries > MAX_TRIES)
7605 {
7606 /* We have tried hard enough, and just can't receive the
7607 packet/notification. Give up. */
7608 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 7609
74531fed
PA
7610 /* Skip the ack char if we're in no-ack mode. */
7611 if (!rs->noack_mode)
c33e31fd 7612 remote_serial_write ("+", 1);
74531fed
PA
7613 return -1;
7614 }
c906108c 7615
74531fed
PA
7616 /* If we got an ordinary packet, return that to our caller. */
7617 if (c == '$')
c906108c
SS
7618 {
7619 if (remote_debug)
43e526b9 7620 {
6e5abd65
PA
7621 struct cleanup *old_chain;
7622 char *str;
7623
7624 str = escape_buffer (*buf, val);
7625 old_chain = make_cleanup (xfree, str);
7626 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7627 do_cleanups (old_chain);
43e526b9 7628 }
a6f3e723
SL
7629
7630 /* Skip the ack char if we're in no-ack mode. */
7631 if (!rs->noack_mode)
c33e31fd 7632 remote_serial_write ("+", 1);
fee9eda9
YQ
7633 if (is_notif != NULL)
7634 *is_notif = 0;
0876f84a 7635 return val;
c906108c
SS
7636 }
7637
74531fed
PA
7638 /* If we got a notification, handle it, and go back to looking
7639 for a packet. */
7640 else
7641 {
7642 gdb_assert (c == '%');
7643
7644 if (remote_debug)
7645 {
6e5abd65
PA
7646 struct cleanup *old_chain;
7647 char *str;
7648
7649 str = escape_buffer (*buf, val);
7650 old_chain = make_cleanup (xfree, str);
7651 fprintf_unfiltered (gdb_stdlog,
7652 " Notification received: %s\n",
7653 str);
7654 do_cleanups (old_chain);
74531fed 7655 }
fee9eda9
YQ
7656 if (is_notif != NULL)
7657 *is_notif = 1;
c906108c 7658
5965e028 7659 handle_notification (rs->notif_state, *buf);
c906108c 7660
74531fed 7661 /* Notifications require no acknowledgement. */
a6f3e723 7662
74531fed 7663 if (expecting_notif)
fee9eda9 7664 return val;
74531fed
PA
7665 }
7666 }
7667}
7668
7669static int
7670getpkt_sane (char **buf, long *sizeof_buf, int forever)
7671{
fee9eda9 7672 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
7673}
7674
7675static int
fee9eda9
YQ
7676getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
7677 int *is_notif)
74531fed 7678{
fee9eda9
YQ
7679 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
7680 is_notif);
c906108c 7681}
74531fed 7682
c906108c
SS
7683\f
7684static void
7d85a9c0 7685remote_kill (struct target_ops *ops)
43ff13b4 7686{
c90a6fb7 7687 volatile struct gdb_exception ex;
0fdf84ca
PA
7688
7689 /* Catch errors so the user can quit from gdb even when we
23860348 7690 aren't on speaking terms with the remote system. */
0fdf84ca
PA
7691 TRY_CATCH (ex, RETURN_MASK_ERROR)
7692 {
7693 putpkt ("k");
7694 }
7695 if (ex.reason < 0)
7696 {
7697 if (ex.error == TARGET_CLOSE_ERROR)
7698 {
7699 /* If we got an (EOF) error that caused the target
7700 to go away, then we're done, that's what we wanted.
7701 "k" is susceptible to cause a premature EOF, given
7702 that the remote server isn't actually required to
7703 reply to "k", and it can happen that it doesn't
7704 even get to reply ACK to the "k". */
7705 return;
7706 }
7707
7708 /* Otherwise, something went wrong. We didn't actually kill
7709 the target. Just propagate the exception, and let the
7710 user or higher layers decide what to do. */
7711 throw_exception (ex);
7712 }
43ff13b4 7713
0fdf84ca
PA
7714 /* We've killed the remote end, we get to mourn it. Since this is
7715 target remote, single-process, mourning the inferior also
7716 unpushes remote_ops. */
43ff13b4
JM
7717 target_mourn_inferior ();
7718}
7719
82f73884
PA
7720static int
7721remote_vkill (int pid, struct remote_state *rs)
7722{
4082afcc 7723 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
7724 return -1;
7725
7726 /* Tell the remote target to detach. */
bba74b36 7727 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
7728 putpkt (rs->buf);
7729 getpkt (&rs->buf, &rs->buf_size, 0);
7730
4082afcc
PA
7731 switch (packet_ok (rs->buf,
7732 &remote_protocol_packets[PACKET_vKill]))
7733 {
7734 case PACKET_OK:
7735 return 0;
7736 case PACKET_ERROR:
7737 return 1;
7738 case PACKET_UNKNOWN:
7739 return -1;
7740 default:
7741 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7742 }
82f73884
PA
7743}
7744
7745static void
7d85a9c0 7746extended_remote_kill (struct target_ops *ops)
82f73884
PA
7747{
7748 int res;
7749 int pid = ptid_get_pid (inferior_ptid);
7750 struct remote_state *rs = get_remote_state ();
7751
7752 res = remote_vkill (pid, rs);
901f9912 7753 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
82f73884
PA
7754 {
7755 /* Don't try 'k' on a multi-process aware stub -- it has no way
7756 to specify the pid. */
7757
7758 putpkt ("k");
7759#if 0
7760 getpkt (&rs->buf, &rs->buf_size, 0);
7761 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7762 res = 1;
7763#else
7764 /* Don't wait for it to die. I'm not really sure it matters whether
7765 we do or not. For the existing stubs, kill is a noop. */
7766 res = 0;
7767#endif
7768 }
7769
7770 if (res != 0)
7771 error (_("Can't kill process"));
7772
82f73884
PA
7773 target_mourn_inferior ();
7774}
7775
c906108c 7776static void
136d6dae 7777remote_mourn (struct target_ops *ops)
c906108c 7778{
136d6dae 7779 remote_mourn_1 (ops);
c906108c
SS
7780}
7781
c906108c
SS
7782/* Worker function for remote_mourn. */
7783static void
fba45db2 7784remote_mourn_1 (struct target_ops *target)
c906108c
SS
7785{
7786 unpush_target (target);
ce5ce7ed 7787
8a2492ee
PA
7788 /* remote_close takes care of doing most of the clean up. */
7789 generic_mourn_inferior ();
c906108c
SS
7790}
7791
2d717e4f
DJ
7792static void
7793extended_remote_mourn_1 (struct target_ops *target)
7794{
7795 struct remote_state *rs = get_remote_state ();
c906108c 7796
e24a49d8
PA
7797 /* In case we got here due to an error, but we're going to stay
7798 connected. */
7799 rs->waiting_for_stop_reply = 0;
7800
dc1981d7
PA
7801 /* If the current general thread belonged to the process we just
7802 detached from or has exited, the remote side current general
7803 thread becomes undefined. Considering a case like this:
7804
7805 - We just got here due to a detach.
7806 - The process that we're detaching from happens to immediately
7807 report a global breakpoint being hit in non-stop mode, in the
7808 same thread we had selected before.
7809 - GDB attaches to this process again.
7810 - This event happens to be the next event we handle.
7811
7812 GDB would consider that the current general thread didn't need to
7813 be set on the stub side (with Hg), since for all it knew,
7814 GENERAL_THREAD hadn't changed.
7815
7816 Notice that although in all-stop mode, the remote server always
7817 sets the current thread to the thread reporting the stop event,
7818 that doesn't happen in non-stop mode; in non-stop, the stub *must
7819 not* change the current thread when reporting a breakpoint hit,
7820 due to the decoupling of event reporting and event handling.
7821
7822 To keep things simple, we always invalidate our notion of the
7823 current thread. */
47f8a51d 7824 record_currthread (rs, minus_one_ptid);
dc1981d7 7825
2d717e4f
DJ
7826 /* Unlike "target remote", we do not want to unpush the target; then
7827 the next time the user says "run", we won't be connected. */
7828
48aa3c27
PA
7829 /* Call common code to mark the inferior as not running. */
7830 generic_mourn_inferior ();
7831
d729566a 7832 if (!have_inferiors ())
2d717e4f 7833 {
82f73884
PA
7834 if (!remote_multi_process_p (rs))
7835 {
7836 /* Check whether the target is running now - some remote stubs
7837 automatically restart after kill. */
7838 putpkt ("?");
7839 getpkt (&rs->buf, &rs->buf_size, 0);
7840
7841 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7842 {
3e43a32a
MS
7843 /* Assume that the target has been restarted. Set
7844 inferior_ptid so that bits of core GDB realizes
7845 there's something here, e.g., so that the user can
7846 say "kill" again. */
82f73884
PA
7847 inferior_ptid = magic_null_ptid;
7848 }
82f73884 7849 }
2d717e4f
DJ
7850 }
7851}
c906108c
SS
7852
7853static void
136d6dae 7854extended_remote_mourn (struct target_ops *ops)
c906108c 7855{
136d6dae 7856 extended_remote_mourn_1 (ops);
2d717e4f 7857}
c906108c 7858
03583c20 7859static int
2bfc0540 7860extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 7861{
4082afcc 7862 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
7863}
7864
7865static void
7866extended_remote_disable_randomization (int val)
7867{
7868 struct remote_state *rs = get_remote_state ();
7869 char *reply;
7870
bba74b36
YQ
7871 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
7872 val);
03583c20
UW
7873 putpkt (rs->buf);
7874 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
7875 if (*reply == '\0')
7876 error (_("Target does not support QDisableRandomization."));
7877 if (strcmp (reply, "OK") != 0)
7878 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
7879}
7880
2d717e4f
DJ
7881static int
7882extended_remote_run (char *args)
7883{
7884 struct remote_state *rs = get_remote_state ();
2d717e4f 7885 int len;
c906108c 7886
2d717e4f
DJ
7887 /* If the user has disabled vRun support, or we have detected that
7888 support is not available, do not try it. */
4082afcc 7889 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 7890 return -1;
424163ea 7891
2d717e4f
DJ
7892 strcpy (rs->buf, "vRun;");
7893 len = strlen (rs->buf);
c906108c 7894
2d717e4f
DJ
7895 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
7896 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
7897 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
7898 strlen (remote_exec_file));
2d717e4f 7899
d1a41061 7900 gdb_assert (args != NULL);
2d717e4f
DJ
7901 if (*args)
7902 {
7903 struct cleanup *back_to;
7904 int i;
7905 char **argv;
7906
d1a41061 7907 argv = gdb_buildargv (args);
6e366df1 7908 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
7909 for (i = 0; argv[i] != NULL; i++)
7910 {
7911 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
7912 error (_("Argument list too long for run packet"));
7913 rs->buf[len++] = ';';
9f1b45b0
TT
7914 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
7915 strlen (argv[i]));
2d717e4f
DJ
7916 }
7917 do_cleanups (back_to);
7918 }
7919
7920 rs->buf[len++] = '\0';
7921
7922 putpkt (rs->buf);
7923 getpkt (&rs->buf, &rs->buf_size, 0);
7924
4082afcc 7925 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 7926 {
4082afcc 7927 case PACKET_OK:
3405876a 7928 /* We have a wait response. All is well. */
2d717e4f 7929 return 0;
4082afcc
PA
7930 case PACKET_UNKNOWN:
7931 return -1;
7932 case PACKET_ERROR:
2d717e4f
DJ
7933 if (remote_exec_file[0] == '\0')
7934 error (_("Running the default executable on the remote target failed; "
7935 "try \"set remote exec-file\"?"));
7936 else
7937 error (_("Running \"%s\" on the remote target failed"),
7938 remote_exec_file);
4082afcc
PA
7939 default:
7940 gdb_assert_not_reached (_("bad switch"));
2d717e4f 7941 }
c906108c
SS
7942}
7943
2d717e4f
DJ
7944/* In the extended protocol we want to be able to do things like
7945 "run" and have them basically work as expected. So we need
7946 a special create_inferior function. We support changing the
7947 executable file and the command line arguments, but not the
7948 environment. */
7949
43ff13b4 7950static void
77a19445
TT
7951extended_remote_create_inferior (struct target_ops *ops,
7952 char *exec_file, char *args,
7953 char **env, int from_tty)
43ff13b4 7954{
3405876a
PA
7955 int run_worked;
7956 char *stop_reply;
7957 struct remote_state *rs = get_remote_state ();
7958
43ff13b4 7959 /* If running asynchronously, register the target file descriptor
23860348 7960 with the event loop. */
75c99385 7961 if (target_can_async_p ())
2acceee2 7962 target_async (inferior_event_handler, 0);
43ff13b4 7963
03583c20 7964 /* Disable address space randomization if requested (and supported). */
2bfc0540 7965 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
7966 extended_remote_disable_randomization (disable_randomization);
7967
43ff13b4 7968 /* Now restart the remote server. */
3405876a
PA
7969 run_worked = extended_remote_run (args) != -1;
7970 if (!run_worked)
2d717e4f
DJ
7971 {
7972 /* vRun was not supported. Fail if we need it to do what the
7973 user requested. */
7974 if (remote_exec_file[0])
7975 error (_("Remote target does not support \"set remote exec-file\""));
7976 if (args[0])
7977 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 7978
2d717e4f
DJ
7979 /* Fall back to "R". */
7980 extended_remote_restart ();
7981 }
424163ea 7982
6c95b8df
PA
7983 if (!have_inferiors ())
7984 {
7985 /* Clean up from the last time we ran, before we mark the target
7986 running again. This will mark breakpoints uninserted, and
7987 get_offsets may insert breakpoints. */
7988 init_thread_list ();
7989 init_wait_for_inferior ();
7990 }
45280a52 7991
3405876a
PA
7992 /* vRun's success return is a stop reply. */
7993 stop_reply = run_worked ? rs->buf : NULL;
7994 add_current_inferior_and_thread (stop_reply);
c0a2216e 7995
2d717e4f
DJ
7996 /* Get updated offsets, if the stub uses qOffsets. */
7997 get_offsets ();
2d717e4f 7998}
c906108c 7999\f
c5aa993b 8000
b775012e
LM
8001/* Given a location's target info BP_TGT and the packet buffer BUF, output
8002 the list of conditions (in agent expression bytecode format), if any, the
8003 target needs to evaluate. The output is placed into the packet buffer
bba74b36 8004 started from BUF and ended at BUF_END. */
b775012e
LM
8005
8006static int
8007remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
8008 struct bp_target_info *bp_tgt, char *buf,
8009 char *buf_end)
b775012e
LM
8010{
8011 struct agent_expr *aexpr = NULL;
8012 int i, ix;
8013 char *pkt;
8014 char *buf_start = buf;
8015
8016 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8017 return 0;
8018
8019 buf += strlen (buf);
bba74b36 8020 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
8021 buf++;
8022
8023 /* Send conditions to the target and free the vector. */
8024 for (ix = 0;
8025 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8026 ix++)
8027 {
bba74b36 8028 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
8029 buf += strlen (buf);
8030 for (i = 0; i < aexpr->len; ++i)
8031 buf = pack_hex_byte (buf, aexpr->buf[i]);
8032 *buf = '\0';
8033 }
b775012e
LM
8034 return 0;
8035}
8036
d3ce09f5
SS
8037static void
8038remote_add_target_side_commands (struct gdbarch *gdbarch,
8039 struct bp_target_info *bp_tgt, char *buf)
8040{
8041 struct agent_expr *aexpr = NULL;
8042 int i, ix;
8043
8044 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8045 return;
8046
8047 buf += strlen (buf);
8048
8049 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8050 buf += strlen (buf);
8051
8052 /* Concatenate all the agent expressions that are commands into the
8053 cmds parameter. */
8054 for (ix = 0;
8055 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8056 ix++)
8057 {
8058 sprintf (buf, "X%x,", aexpr->len);
8059 buf += strlen (buf);
8060 for (i = 0; i < aexpr->len; ++i)
8061 buf = pack_hex_byte (buf, aexpr->buf[i]);
8062 *buf = '\0';
8063 }
d3ce09f5
SS
8064}
8065
8181d85f
DJ
8066/* Insert a breakpoint. On targets that have software breakpoint
8067 support, we ask the remote target to do the work; on targets
8068 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
8069
8070static int
3db08215
MM
8071remote_insert_breakpoint (struct target_ops *ops,
8072 struct gdbarch *gdbarch,
a6d9a66e 8073 struct bp_target_info *bp_tgt)
c906108c 8074{
d471ea57
AC
8075 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8076 If it succeeds, then set the support to PACKET_ENABLE. If it
8077 fails, and the user has explicitly requested the Z support then
23860348 8078 report an error, otherwise, mark it disabled and go on. */
802188a7 8079
4082afcc 8080 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 8081 {
7c0f6dcc 8082 CORE_ADDR addr = bp_tgt->placed_address;
4fff2411 8083 struct remote_state *rs;
bba74b36 8084 char *p, *endbuf;
7c0f6dcc 8085 int bpsize;
b775012e 8086 struct condition_list *cond = NULL;
4fff2411 8087
28439a30
PA
8088 /* Make sure the remote is pointing at the right process, if
8089 necessary. */
8090 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8091 set_general_process ();
8092
a1dcb23a 8093 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
8094
8095 rs = get_remote_state ();
8096 p = rs->buf;
bba74b36 8097 endbuf = rs->buf + get_remote_packet_size ();
802188a7 8098
96baa820
JM
8099 *(p++) = 'Z';
8100 *(p++) = '0';
8101 *(p++) = ',';
7c0f6dcc 8102 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 8103 p += hexnumstr (p, addr);
bba74b36 8104 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 8105
efcc2da7 8106 if (remote_supports_cond_breakpoints (ops))
bba74b36 8107 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8108
78eff0ec 8109 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
8110 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8111
6d820c5c
DJ
8112 putpkt (rs->buf);
8113 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8114
6d820c5c 8115 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 8116 {
d471ea57
AC
8117 case PACKET_ERROR:
8118 return -1;
8119 case PACKET_OK:
7c0f6dcc
JL
8120 bp_tgt->placed_address = addr;
8121 bp_tgt->placed_size = bpsize;
d471ea57
AC
8122 return 0;
8123 case PACKET_UNKNOWN:
8124 break;
96baa820
JM
8125 }
8126 }
c906108c 8127
0000e5cc
PA
8128 /* If this breakpoint has target-side commands but this stub doesn't
8129 support Z0 packets, throw error. */
8130 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8131 throw_error (NOT_SUPPORTED_ERROR, _("\
8132Target doesn't support breakpoints that have target side commands."));
8133
3db08215 8134 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8135}
8136
8137static int
3db08215
MM
8138remote_remove_breakpoint (struct target_ops *ops,
8139 struct gdbarch *gdbarch,
a6d9a66e 8140 struct bp_target_info *bp_tgt)
c906108c 8141{
8181d85f 8142 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 8143 struct remote_state *rs = get_remote_state ();
96baa820 8144
4082afcc 8145 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 8146 {
6d820c5c 8147 char *p = rs->buf;
bba74b36 8148 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 8149
28439a30
PA
8150 /* Make sure the remote is pointing at the right process, if
8151 necessary. */
8152 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8153 set_general_process ();
8154
96baa820
JM
8155 *(p++) = 'z';
8156 *(p++) = '0';
8157 *(p++) = ',';
8158
8181d85f
DJ
8159 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8160 p += hexnumstr (p, addr);
bba74b36 8161 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 8162
6d820c5c
DJ
8163 putpkt (rs->buf);
8164 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8165
6d820c5c 8166 return (rs->buf[0] == 'E');
96baa820
JM
8167 }
8168
3db08215 8169 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8170}
8171
d471ea57
AC
8172static int
8173watchpoint_to_Z_packet (int type)
8174{
8175 switch (type)
8176 {
8177 case hw_write:
bb858e6a 8178 return Z_PACKET_WRITE_WP;
d471ea57
AC
8179 break;
8180 case hw_read:
bb858e6a 8181 return Z_PACKET_READ_WP;
d471ea57
AC
8182 break;
8183 case hw_access:
bb858e6a 8184 return Z_PACKET_ACCESS_WP;
d471ea57
AC
8185 break;
8186 default:
8e65ff28 8187 internal_error (__FILE__, __LINE__,
e2e0b3e5 8188 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
8189 }
8190}
8191
3c3bea1c 8192static int
7bb99c53
TT
8193remote_insert_watchpoint (struct target_ops *self,
8194 CORE_ADDR addr, int len, int type,
0cf6dd15 8195 struct expression *cond)
96baa820 8196{
d01949b6 8197 struct remote_state *rs = get_remote_state ();
bba74b36 8198 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8199 char *p;
d471ea57 8200 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 8201
4082afcc 8202 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 8203 return 1;
802188a7 8204
28439a30
PA
8205 /* Make sure the remote is pointing at the right process, if
8206 necessary. */
8207 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8208 set_general_process ();
8209
bba74b36 8210 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 8211 p = strchr (rs->buf, '\0');
96baa820
JM
8212 addr = remote_address_masked (addr);
8213 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8214 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 8215
6d820c5c
DJ
8216 putpkt (rs->buf);
8217 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8218
6d820c5c 8219 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8220 {
8221 case PACKET_ERROR:
d471ea57 8222 return -1;
85d721b8
PA
8223 case PACKET_UNKNOWN:
8224 return 1;
d471ea57
AC
8225 case PACKET_OK:
8226 return 0;
8227 }
8e65ff28 8228 internal_error (__FILE__, __LINE__,
e2e0b3e5 8229 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
8230}
8231
283002cf
MR
8232static int
8233remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8234 CORE_ADDR start, int length)
8235{
8236 CORE_ADDR diff = remote_address_masked (addr - start);
8237
8238 return diff < length;
8239}
8240
d471ea57 8241
3c3bea1c 8242static int
11b5219a
TT
8243remote_remove_watchpoint (struct target_ops *self,
8244 CORE_ADDR addr, int len, int type,
0cf6dd15 8245 struct expression *cond)
96baa820 8246{
d01949b6 8247 struct remote_state *rs = get_remote_state ();
bba74b36 8248 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8249 char *p;
d471ea57
AC
8250 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8251
4082afcc 8252 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 8253 return -1;
802188a7 8254
28439a30
PA
8255 /* Make sure the remote is pointing at the right process, if
8256 necessary. */
8257 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8258 set_general_process ();
8259
bba74b36 8260 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 8261 p = strchr (rs->buf, '\0');
96baa820
JM
8262 addr = remote_address_masked (addr);
8263 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8264 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
8265 putpkt (rs->buf);
8266 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8267
6d820c5c 8268 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8269 {
8270 case PACKET_ERROR:
8271 case PACKET_UNKNOWN:
8272 return -1;
8273 case PACKET_OK:
8274 return 0;
8275 }
8e65ff28 8276 internal_error (__FILE__, __LINE__,
e2e0b3e5 8277 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
8278}
8279
3c3bea1c 8280
501eef12 8281int remote_hw_watchpoint_limit = -1;
480a3f21 8282int remote_hw_watchpoint_length_limit = -1;
501eef12 8283int remote_hw_breakpoint_limit = -1;
d471ea57 8284
480a3f21 8285static int
31568a15
TT
8286remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8287 CORE_ADDR addr, int len)
480a3f21
PW
8288{
8289 if (remote_hw_watchpoint_length_limit == 0)
8290 return 0;
8291 else if (remote_hw_watchpoint_length_limit < 0)
8292 return 1;
8293 else if (len <= remote_hw_watchpoint_length_limit)
8294 return 1;
8295 else
8296 return 0;
8297}
8298
b9362cc7 8299static int
5461485a
TT
8300remote_check_watch_resources (struct target_ops *self,
8301 int type, int cnt, int ot)
96baa820 8302{
3c3bea1c
GS
8303 if (type == bp_hardware_breakpoint)
8304 {
8305 if (remote_hw_breakpoint_limit == 0)
8306 return 0;
501eef12
AC
8307 else if (remote_hw_breakpoint_limit < 0)
8308 return 1;
3c3bea1c
GS
8309 else if (cnt <= remote_hw_breakpoint_limit)
8310 return 1;
8311 }
8312 else
8313 {
8314 if (remote_hw_watchpoint_limit == 0)
8315 return 0;
501eef12
AC
8316 else if (remote_hw_watchpoint_limit < 0)
8317 return 1;
3c3bea1c
GS
8318 else if (ot)
8319 return -1;
8320 else if (cnt <= remote_hw_watchpoint_limit)
8321 return 1;
8322 }
8323 return -1;
8324}
8325
b9362cc7 8326static int
6a109b6b 8327remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 8328{
ee154bee
TT
8329 struct remote_state *rs = get_remote_state ();
8330
8331 return rs->remote_stopped_by_watchpoint_p;
3c3bea1c
GS
8332}
8333
4aa7a7f5
JJ
8334static int
8335remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 8336{
ee154bee 8337 struct remote_state *rs = get_remote_state ();
4aa7a7f5 8338 int rc = 0;
a744cf53 8339
6a109b6b 8340 if (remote_stopped_by_watchpoint (target))
4aa7a7f5 8341 {
ee154bee 8342 *addr_p = rs->remote_watch_data_address;
4aa7a7f5
JJ
8343 rc = 1;
8344 }
8345
8346 return rc;
3c3bea1c
GS
8347}
8348
8349
8350static int
23a26771 8351remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 8352 struct bp_target_info *bp_tgt)
3c3bea1c 8353{
8181d85f 8354 CORE_ADDR addr;
4fff2411 8355 struct remote_state *rs;
bba74b36 8356 char *p, *endbuf;
dd61ec5c 8357 char *message;
802188a7 8358
c8189ed1 8359 /* The length field should be set to the size of a breakpoint
8181d85f 8360 instruction, even though we aren't inserting one ourselves. */
c8189ed1 8361
a1dcb23a 8362 gdbarch_remote_breakpoint_from_pc
a6d9a66e 8363 (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
3c3bea1c 8364
4082afcc 8365 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 8366 return -1;
2bc416ba 8367
28439a30
PA
8368 /* Make sure the remote is pointing at the right process, if
8369 necessary. */
8370 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8371 set_general_process ();
8372
4fff2411
JZ
8373 rs = get_remote_state ();
8374 p = rs->buf;
bba74b36 8375 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 8376
96baa820
JM
8377 *(p++) = 'Z';
8378 *(p++) = '1';
8379 *(p++) = ',';
802188a7 8380
8181d85f 8381 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 8382 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8383 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 8384
efcc2da7 8385 if (remote_supports_cond_breakpoints (self))
bba74b36 8386 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8387
78eff0ec 8388 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
8389 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8390
6d820c5c
DJ
8391 putpkt (rs->buf);
8392 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8393
6d820c5c 8394 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
8395 {
8396 case PACKET_ERROR:
dd61ec5c
MW
8397 if (rs->buf[1] == '.')
8398 {
8399 message = strchr (rs->buf + 2, '.');
8400 if (message)
0316657e 8401 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
8402 }
8403 return -1;
d471ea57
AC
8404 case PACKET_UNKNOWN:
8405 return -1;
8406 case PACKET_OK:
8407 return 0;
8408 }
8e65ff28 8409 internal_error (__FILE__, __LINE__,
e2e0b3e5 8410 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
8411}
8412
d471ea57 8413
802188a7 8414static int
a64dc96c 8415remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 8416 struct bp_target_info *bp_tgt)
96baa820 8417{
8181d85f 8418 CORE_ADDR addr;
d01949b6 8419 struct remote_state *rs = get_remote_state ();
6d820c5c 8420 char *p = rs->buf;
bba74b36 8421 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 8422
4082afcc 8423 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 8424 return -1;
802188a7 8425
28439a30
PA
8426 /* Make sure the remote is pointing at the right process, if
8427 necessary. */
8428 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8429 set_general_process ();
8430
96baa820
JM
8431 *(p++) = 'z';
8432 *(p++) = '1';
8433 *(p++) = ',';
802188a7 8434
8181d85f 8435 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 8436 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8437 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 8438
6d820c5c
DJ
8439 putpkt (rs->buf);
8440 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 8441
6d820c5c 8442 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
8443 {
8444 case PACKET_ERROR:
8445 case PACKET_UNKNOWN:
8446 return -1;
8447 case PACKET_OK:
8448 return 0;
8449 }
8e65ff28 8450 internal_error (__FILE__, __LINE__,
e2e0b3e5 8451 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 8452}
96baa820 8453
4a5e7a5b
PA
8454/* Verify memory using the "qCRC:" request. */
8455
8456static int
8457remote_verify_memory (struct target_ops *ops,
8458 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8459{
8460 struct remote_state *rs = get_remote_state ();
8461 unsigned long host_crc, target_crc;
8462 char *tmp;
8463
936d2992
PA
8464 /* It doesn't make sense to use qCRC if the remote target is
8465 connected but not running. */
8466 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
8467 {
8468 enum packet_result result;
28439a30 8469
936d2992
PA
8470 /* Make sure the remote is pointing at the right process. */
8471 set_general_process ();
4a5e7a5b 8472
936d2992
PA
8473 /* FIXME: assumes lma can fit into long. */
8474 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8475 (long) lma, (long) size);
8476 putpkt (rs->buf);
4a5e7a5b 8477
936d2992
PA
8478 /* Be clever; compute the host_crc before waiting for target
8479 reply. */
8480 host_crc = xcrc32 (data, size, 0xffffffff);
8481
8482 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 8483
936d2992
PA
8484 result = packet_ok (rs->buf,
8485 &remote_protocol_packets[PACKET_qCRC]);
8486 if (result == PACKET_ERROR)
8487 return -1;
8488 else if (result == PACKET_OK)
8489 {
8490 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8491 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 8492
936d2992
PA
8493 return (host_crc == target_crc);
8494 }
8495 }
4a5e7a5b 8496
936d2992 8497 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
8498}
8499
c906108c
SS
8500/* compare-sections command
8501
8502 With no arguments, compares each loadable section in the exec bfd
8503 with the same memory range on the target, and reports mismatches.
4a5e7a5b 8504 Useful for verifying the image on the target against the exec file. */
e514a9d6 8505
c906108c 8506static void
fba45db2 8507compare_sections_command (char *args, int from_tty)
c906108c
SS
8508{
8509 asection *s;
c906108c 8510 struct cleanup *old_chain;
948f8e3d 8511 gdb_byte *sectdata;
ce359b09 8512 const char *sectname;
c906108c
SS
8513 bfd_size_type size;
8514 bfd_vma lma;
8515 int matched = 0;
8516 int mismatched = 0;
4a5e7a5b 8517 int res;
95cf3b38 8518 int read_only = 0;
c906108c
SS
8519
8520 if (!exec_bfd)
8a3fe4f8 8521 error (_("command cannot be used without an exec file"));
c906108c 8522
28439a30
PA
8523 /* Make sure the remote is pointing at the right process. */
8524 set_general_process ();
8525
95cf3b38
DT
8526 if (args != NULL && strcmp (args, "-r") == 0)
8527 {
8528 read_only = 1;
8529 args = NULL;
8530 }
8531
c5aa993b 8532 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
8533 {
8534 if (!(s->flags & SEC_LOAD))
0df8b418 8535 continue; /* Skip non-loadable section. */
c906108c 8536
95cf3b38
DT
8537 if (read_only && (s->flags & SEC_READONLY) == 0)
8538 continue; /* Skip writeable sections */
8539
2c500098 8540 size = bfd_get_section_size (s);
c906108c 8541 if (size == 0)
0df8b418 8542 continue; /* Skip zero-length section. */
c906108c 8543
ce359b09 8544 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 8545 if (args && strcmp (args, sectname) != 0)
0df8b418 8546 continue; /* Not the section selected by user. */
c906108c 8547
0df8b418 8548 matched = 1; /* Do this section. */
c906108c 8549 lma = s->lma;
c906108c 8550
c906108c 8551 sectdata = xmalloc (size);
b8c9b27d 8552 old_chain = make_cleanup (xfree, sectdata);
c906108c 8553 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 8554
4a5e7a5b
PA
8555 res = target_verify_memory (sectdata, lma, size);
8556
8557 if (res == -1)
5af949e3 8558 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
8559 paddress (target_gdbarch (), lma),
8560 paddress (target_gdbarch (), lma + size));
c906108c 8561
5af949e3 8562 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
8563 paddress (target_gdbarch (), lma),
8564 paddress (target_gdbarch (), lma + size));
4a5e7a5b 8565 if (res)
c906108c
SS
8566 printf_filtered ("matched.\n");
8567 else
c5aa993b
JM
8568 {
8569 printf_filtered ("MIS-MATCHED!\n");
8570 mismatched++;
8571 }
c906108c
SS
8572
8573 do_cleanups (old_chain);
8574 }
8575 if (mismatched > 0)
936d2992 8576 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 8577the loaded file\n"));
c906108c 8578 if (args && !matched)
a3f17187 8579 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
8580}
8581
0e7f50da
UW
8582/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8583 into remote target. The number of bytes written to the remote
8584 target is returned, or -1 for error. */
8585
9b409511 8586static enum target_xfer_status
0e7f50da
UW
8587remote_write_qxfer (struct target_ops *ops, const char *object_name,
8588 const char *annex, const gdb_byte *writebuf,
9b409511 8589 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
8590 struct packet_config *packet)
8591{
8592 int i, buf_len;
8593 ULONGEST n;
0e7f50da
UW
8594 struct remote_state *rs = get_remote_state ();
8595 int max_size = get_memory_write_packet_size ();
8596
8597 if (packet->support == PACKET_DISABLE)
2ed4b548 8598 return TARGET_XFER_E_IO;
0e7f50da
UW
8599
8600 /* Insert header. */
8601 i = snprintf (rs->buf, max_size,
8602 "qXfer:%s:write:%s:%s:",
8603 object_name, annex ? annex : "",
8604 phex_nz (offset, sizeof offset));
8605 max_size -= (i + 1);
8606
8607 /* Escape as much data as fits into rs->buf. */
8608 buf_len = remote_escape_output
bc20a4af 8609 (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
8610
8611 if (putpkt_binary (rs->buf, i + buf_len) < 0
8612 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8613 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 8614 return TARGET_XFER_E_IO;
0e7f50da
UW
8615
8616 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
8617
8618 *xfered_len = n;
8619 return TARGET_XFER_OK;
0e7f50da
UW
8620}
8621
0876f84a
DJ
8622/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8623 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8624 number of bytes read is returned, or 0 for EOF, or -1 for error.
8625 The number of bytes read may be less than LEN without indicating an
8626 EOF. PACKET is checked and updated to indicate whether the remote
8627 target supports this object. */
8628
9b409511 8629static enum target_xfer_status
0876f84a
DJ
8630remote_read_qxfer (struct target_ops *ops, const char *object_name,
8631 const char *annex,
8632 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 8633 ULONGEST *xfered_len,
0876f84a
DJ
8634 struct packet_config *packet)
8635{
0876f84a 8636 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
8637 LONGEST i, n, packet_len;
8638
8639 if (packet->support == PACKET_DISABLE)
2ed4b548 8640 return TARGET_XFER_E_IO;
0876f84a
DJ
8641
8642 /* Check whether we've cached an end-of-object packet that matches
8643 this request. */
8e88304f 8644 if (rs->finished_object)
0876f84a 8645 {
8e88304f
TT
8646 if (strcmp (object_name, rs->finished_object) == 0
8647 && strcmp (annex ? annex : "", rs->finished_annex) == 0
8648 && offset == rs->finished_offset)
9b409511
YQ
8649 return TARGET_XFER_EOF;
8650
0876f84a
DJ
8651
8652 /* Otherwise, we're now reading something different. Discard
8653 the cache. */
8e88304f
TT
8654 xfree (rs->finished_object);
8655 xfree (rs->finished_annex);
8656 rs->finished_object = NULL;
8657 rs->finished_annex = NULL;
0876f84a
DJ
8658 }
8659
8660 /* Request only enough to fit in a single packet. The actual data
8661 may not, since we don't know how much of it will need to be escaped;
8662 the target is free to respond with slightly less data. We subtract
8663 five to account for the response type and the protocol frame. */
8664 n = min (get_remote_packet_size () - 5, len);
8665 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8666 object_name, annex ? annex : "",
8667 phex_nz (offset, sizeof offset),
8668 phex_nz (n, sizeof n));
8669 i = putpkt (rs->buf);
8670 if (i < 0)
2ed4b548 8671 return TARGET_XFER_E_IO;
0876f84a
DJ
8672
8673 rs->buf[0] = '\0';
8674 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8675 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 8676 return TARGET_XFER_E_IO;
0876f84a
DJ
8677
8678 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8679 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8680
8681 /* 'm' means there is (or at least might be) more data after this
8682 batch. That does not make sense unless there's at least one byte
8683 of data in this reply. */
8684 if (rs->buf[0] == 'm' && packet_len == 1)
8685 error (_("Remote qXfer reply contained no data."));
8686
8687 /* Got some data. */
bc20a4af
PA
8688 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
8689 packet_len - 1, readbuf, n);
0876f84a
DJ
8690
8691 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
8692 or possibly empty. If we have the final block of a non-empty
8693 object, record this fact to bypass a subsequent partial read. */
8694 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 8695 {
8e88304f
TT
8696 rs->finished_object = xstrdup (object_name);
8697 rs->finished_annex = xstrdup (annex ? annex : "");
8698 rs->finished_offset = offset + i;
0876f84a
DJ
8699 }
8700
9b409511
YQ
8701 if (i == 0)
8702 return TARGET_XFER_EOF;
8703 else
8704 {
8705 *xfered_len = i;
8706 return TARGET_XFER_OK;
8707 }
0876f84a
DJ
8708}
8709
9b409511 8710static enum target_xfer_status
4b8a223f 8711remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 8712 const char *annex, gdb_byte *readbuf,
9b409511
YQ
8713 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
8714 ULONGEST *xfered_len)
c906108c 8715{
82f73884 8716 struct remote_state *rs;
c906108c 8717 int i;
6d820c5c 8718 char *p2;
1e3ff5ad 8719 char query_type;
c906108c 8720
e6e4e701 8721 set_remote_traceframe ();
82f73884
PA
8722 set_general_thread (inferior_ptid);
8723
8724 rs = get_remote_state ();
8725
b2182ed2 8726 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
8727 if (object == TARGET_OBJECT_MEMORY)
8728 {
2d717e4f
DJ
8729 /* If the remote target is connected but not running, we should
8730 pass this request down to a lower stratum (e.g. the executable
8731 file). */
8732 if (!target_has_execution)
9b409511 8733 return TARGET_XFER_EOF;
2d717e4f 8734
21e3b9b9 8735 if (writebuf != NULL)
9b409511 8736 return remote_write_bytes (offset, writebuf, len, xfered_len);
21e3b9b9 8737 else
8acf9577 8738 return remote_read_bytes (ops, offset, readbuf, len, xfered_len);
21e3b9b9
DJ
8739 }
8740
0df8b418 8741 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
8742 if (object == TARGET_OBJECT_SPU)
8743 {
8744 if (readbuf)
8745 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
8746 xfered_len, &remote_protocol_packets
8747 [PACKET_qXfer_spu_read]);
0e7f50da
UW
8748 else
8749 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
8750 xfered_len, &remote_protocol_packets
8751 [PACKET_qXfer_spu_write]);
0e7f50da
UW
8752 }
8753
4aa995e1
PA
8754 /* Handle extra signal info using qxfer packets. */
8755 if (object == TARGET_OBJECT_SIGNAL_INFO)
8756 {
8757 if (readbuf)
8758 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 8759 xfered_len, &remote_protocol_packets
4aa995e1
PA
8760 [PACKET_qXfer_siginfo_read]);
8761 else
3e43a32a 8762 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 8763 writebuf, offset, len, xfered_len,
4aa995e1
PA
8764 &remote_protocol_packets
8765 [PACKET_qXfer_siginfo_write]);
8766 }
8767
0fb4aa4b
PA
8768 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8769 {
8770 if (readbuf)
3e43a32a 8771 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 8772 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
8773 &remote_protocol_packets
8774 [PACKET_qXfer_statictrace_read]);
8775 else
2ed4b548 8776 return TARGET_XFER_E_IO;
0fb4aa4b
PA
8777 }
8778
a76d924d
DJ
8779 /* Only handle flash writes. */
8780 if (writebuf != NULL)
8781 {
8782 LONGEST xfered;
8783
8784 switch (object)
8785 {
8786 case TARGET_OBJECT_FLASH:
9b409511
YQ
8787 return remote_flash_write (ops, offset, len, xfered_len,
8788 writebuf);
a76d924d
DJ
8789
8790 default:
2ed4b548 8791 return TARGET_XFER_E_IO;
a76d924d
DJ
8792 }
8793 }
4b8a223f 8794
1e3ff5ad
AC
8795 /* Map pre-existing objects onto letters. DO NOT do this for new
8796 objects!!! Instead specify new query packets. */
8797 switch (object)
c906108c 8798 {
1e3ff5ad
AC
8799 case TARGET_OBJECT_AVR:
8800 query_type = 'R';
8801 break;
802188a7
RM
8802
8803 case TARGET_OBJECT_AUXV:
0876f84a
DJ
8804 gdb_assert (annex == NULL);
8805 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 8806 xfered_len,
0876f84a 8807 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 8808
23181151
DJ
8809 case TARGET_OBJECT_AVAILABLE_FEATURES:
8810 return remote_read_qxfer
9b409511 8811 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
8812 &remote_protocol_packets[PACKET_qXfer_features]);
8813
cfa9d6d9
DJ
8814 case TARGET_OBJECT_LIBRARIES:
8815 return remote_read_qxfer
9b409511 8816 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
8817 &remote_protocol_packets[PACKET_qXfer_libraries]);
8818
2268b414
JK
8819 case TARGET_OBJECT_LIBRARIES_SVR4:
8820 return remote_read_qxfer
9b409511 8821 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
8822 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
8823
fd79ecee
DJ
8824 case TARGET_OBJECT_MEMORY_MAP:
8825 gdb_assert (annex == NULL);
8826 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 8827 xfered_len,
fd79ecee
DJ
8828 &remote_protocol_packets[PACKET_qXfer_memory_map]);
8829
07e059b5
VP
8830 case TARGET_OBJECT_OSDATA:
8831 /* Should only get here if we're connected. */
5d93a237 8832 gdb_assert (rs->remote_desc);
07e059b5 8833 return remote_read_qxfer
9b409511 8834 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
8835 &remote_protocol_packets[PACKET_qXfer_osdata]);
8836
dc146f7c
VP
8837 case TARGET_OBJECT_THREADS:
8838 gdb_assert (annex == NULL);
8839 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 8840 xfered_len,
dc146f7c
VP
8841 &remote_protocol_packets[PACKET_qXfer_threads]);
8842
b3b9301e
PA
8843 case TARGET_OBJECT_TRACEFRAME_INFO:
8844 gdb_assert (annex == NULL);
8845 return remote_read_qxfer
9b409511 8846 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 8847 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
8848
8849 case TARGET_OBJECT_FDPIC:
8850 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 8851 xfered_len,
78d85199 8852 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
8853
8854 case TARGET_OBJECT_OPENVMS_UIB:
8855 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 8856 xfered_len,
169081d0
TG
8857 &remote_protocol_packets[PACKET_qXfer_uib]);
8858
9accd112
MM
8859 case TARGET_OBJECT_BTRACE:
8860 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 8861 xfered_len,
9accd112
MM
8862 &remote_protocol_packets[PACKET_qXfer_btrace]);
8863
1e3ff5ad 8864 default:
2ed4b548 8865 return TARGET_XFER_E_IO;
c906108c
SS
8866 }
8867
4b8a223f 8868 /* Note: a zero OFFSET and LEN can be used to query the minimum
1e3ff5ad 8869 buffer size. */
4b8a223f 8870 if (offset == 0 && len == 0)
ea9c271d 8871 return (get_remote_packet_size ());
0df8b418 8872 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 8873 large enough let the caller deal with it. */
ea9c271d 8874 if (len < get_remote_packet_size ())
2ed4b548 8875 return TARGET_XFER_E_IO;
ea9c271d 8876 len = get_remote_packet_size ();
1e3ff5ad 8877
23860348 8878 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 8879 if (!rs->remote_desc)
8a3fe4f8 8880 error (_("remote query is only available after target open"));
c906108c 8881
1e3ff5ad 8882 gdb_assert (annex != NULL);
4b8a223f 8883 gdb_assert (readbuf != NULL);
c906108c 8884
6d820c5c 8885 p2 = rs->buf;
c906108c
SS
8886 *p2++ = 'q';
8887 *p2++ = query_type;
8888
23860348
MS
8889 /* We used one buffer char for the remote protocol q command and
8890 another for the query type. As the remote protocol encapsulation
8891 uses 4 chars plus one extra in case we are debugging
8892 (remote_debug), we have PBUFZIZ - 7 left to pack the query
8893 string. */
c906108c 8894 i = 0;
ea9c271d 8895 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 8896 {
1e3ff5ad
AC
8897 /* Bad caller may have sent forbidden characters. */
8898 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
8899 *p2++ = annex[i];
c906108c
SS
8900 i++;
8901 }
1e3ff5ad
AC
8902 *p2 = '\0';
8903 gdb_assert (annex[i] == '\0');
c906108c 8904
6d820c5c 8905 i = putpkt (rs->buf);
c5aa993b 8906 if (i < 0)
2ed4b548 8907 return TARGET_XFER_E_IO;
c906108c 8908
6d820c5c
DJ
8909 getpkt (&rs->buf, &rs->buf_size, 0);
8910 strcpy ((char *) readbuf, rs->buf);
c906108c 8911
9b409511
YQ
8912 *xfered_len = strlen ((char *) readbuf);
8913 return TARGET_XFER_OK;
c906108c
SS
8914}
8915
08388c79
DE
8916static int
8917remote_search_memory (struct target_ops* ops,
8918 CORE_ADDR start_addr, ULONGEST search_space_len,
8919 const gdb_byte *pattern, ULONGEST pattern_len,
8920 CORE_ADDR *found_addrp)
8921{
f5656ead 8922 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
8923 struct remote_state *rs = get_remote_state ();
8924 int max_size = get_memory_write_packet_size ();
8925 struct packet_config *packet =
8926 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
8927 /* Number of packet bytes used to encode the pattern;
8928 this could be more than PATTERN_LEN due to escape characters. */
08388c79 8929 int escaped_pattern_len;
0df8b418 8930 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
8931 int used_pattern_len;
8932 int i;
8933 int found;
8934 ULONGEST found_addr;
8935
8936 /* Don't go to the target if we don't have to.
8937 This is done before checking packet->support to avoid the possibility that
8938 a success for this edge case means the facility works in general. */
8939 if (pattern_len > search_space_len)
8940 return 0;
8941 if (pattern_len == 0)
8942 {
8943 *found_addrp = start_addr;
8944 return 1;
8945 }
8946
8947 /* If we already know the packet isn't supported, fall back to the simple
8948 way of searching memory. */
8949
4082afcc 8950 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
8951 {
8952 /* Target doesn't provided special support, fall back and use the
8953 standard support (copy memory and do the search here). */
8954 return simple_search_memory (ops, start_addr, search_space_len,
8955 pattern, pattern_len, found_addrp);
8956 }
8957
28439a30
PA
8958 /* Make sure the remote is pointing at the right process. */
8959 set_general_process ();
8960
08388c79
DE
8961 /* Insert header. */
8962 i = snprintf (rs->buf, max_size,
8963 "qSearch:memory:%s;%s;",
5af949e3 8964 phex_nz (start_addr, addr_size),
08388c79
DE
8965 phex_nz (search_space_len, sizeof (search_space_len)));
8966 max_size -= (i + 1);
8967
8968 /* Escape as much data as fits into rs->buf. */
8969 escaped_pattern_len =
bc20a4af 8970 remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
08388c79
DE
8971 &used_pattern_len, max_size);
8972
8973 /* Bail if the pattern is too large. */
8974 if (used_pattern_len != pattern_len)
9b20d036 8975 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
8976
8977 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
8978 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8979 || packet_ok (rs->buf, packet) != PACKET_OK)
8980 {
8981 /* The request may not have worked because the command is not
8982 supported. If so, fall back to the simple way. */
8983 if (packet->support == PACKET_DISABLE)
8984 {
8985 return simple_search_memory (ops, start_addr, search_space_len,
8986 pattern, pattern_len, found_addrp);
8987 }
8988 return -1;
8989 }
8990
8991 if (rs->buf[0] == '0')
8992 found = 0;
8993 else if (rs->buf[0] == '1')
8994 {
8995 found = 1;
8996 if (rs->buf[1] != ',')
10e0fa18 8997 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
8998 unpack_varlen_hex (rs->buf + 2, &found_addr);
8999 *found_addrp = found_addr;
9000 }
9001 else
10e0fa18 9002 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9003
9004 return found;
9005}
9006
96baa820 9007static void
a30bf1f1 9008remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 9009 struct ui_file *outbuf)
96baa820 9010{
d01949b6 9011 struct remote_state *rs = get_remote_state ();
2e9f7625 9012 char *p = rs->buf;
96baa820 9013
5d93a237 9014 if (!rs->remote_desc)
8a3fe4f8 9015 error (_("remote rcmd is only available after target open"));
96baa820 9016
23860348 9017 /* Send a NULL command across as an empty command. */
7be570e7
JM
9018 if (command == NULL)
9019 command = "";
9020
23860348 9021 /* The query prefix. */
2e9f7625
DJ
9022 strcpy (rs->buf, "qRcmd,");
9023 p = strchr (rs->buf, '\0');
96baa820 9024
3e43a32a
MS
9025 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9026 > get_remote_packet_size ())
8a3fe4f8 9027 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 9028
23860348 9029 /* Encode the actual command. */
a30bf1f1 9030 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 9031
6d820c5c 9032 if (putpkt (rs->buf) < 0)
8a3fe4f8 9033 error (_("Communication problem with target."));
96baa820
JM
9034
9035 /* get/display the response */
9036 while (1)
9037 {
2e9f7625
DJ
9038 char *buf;
9039
00bf0b85 9040 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 9041 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 9042 rs->buf[0] = '\0';
5b37825d
PW
9043 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9044 {
9045 /* Timeout. Continue to (try to) read responses.
9046 This is better than stopping with an error, assuming the stub
9047 is still executing the (long) monitor command.
9048 If needed, the user can interrupt gdb using C-c, obtaining
9049 an effect similar to stop on timeout. */
9050 continue;
9051 }
2e9f7625 9052 buf = rs->buf;
96baa820 9053 if (buf[0] == '\0')
8a3fe4f8 9054 error (_("Target does not support this command."));
96baa820
JM
9055 if (buf[0] == 'O' && buf[1] != 'K')
9056 {
23860348 9057 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
9058 continue;
9059 }
9060 if (strcmp (buf, "OK") == 0)
9061 break;
7be570e7
JM
9062 if (strlen (buf) == 3 && buf[0] == 'E'
9063 && isdigit (buf[1]) && isdigit (buf[2]))
9064 {
8a3fe4f8 9065 error (_("Protocol error with Rcmd"));
7be570e7 9066 }
96baa820
JM
9067 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9068 {
9069 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 9070
96baa820
JM
9071 fputc_unfiltered (c, outbuf);
9072 }
9073 break;
9074 }
9075}
9076
fd79ecee
DJ
9077static VEC(mem_region_s) *
9078remote_memory_map (struct target_ops *ops)
9079{
9080 VEC(mem_region_s) *result = NULL;
9081 char *text = target_read_stralloc (&current_target,
9082 TARGET_OBJECT_MEMORY_MAP, NULL);
9083
9084 if (text)
9085 {
9086 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 9087
fd79ecee
DJ
9088 result = parse_memory_map (text);
9089 do_cleanups (back_to);
9090 }
9091
9092 return result;
9093}
9094
c906108c 9095static void
fba45db2 9096packet_command (char *args, int from_tty)
c906108c 9097{
d01949b6 9098 struct remote_state *rs = get_remote_state ();
c906108c 9099
5d93a237 9100 if (!rs->remote_desc)
8a3fe4f8 9101 error (_("command can only be used with remote target"));
c906108c 9102
c5aa993b 9103 if (!args)
8a3fe4f8 9104 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
9105
9106 puts_filtered ("sending: ");
9107 print_packet (args);
9108 puts_filtered ("\n");
9109 putpkt (args);
9110
6d820c5c 9111 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 9112 puts_filtered ("received: ");
6d820c5c 9113 print_packet (rs->buf);
c906108c
SS
9114 puts_filtered ("\n");
9115}
9116
9117#if 0
23860348 9118/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 9119
a14ed312 9120static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 9121
a14ed312 9122static void threadset_test_cmd (char *cmd, int tty);
c906108c 9123
a14ed312 9124static void threadalive_test (char *cmd, int tty);
c906108c 9125
a14ed312 9126static void threadlist_test_cmd (char *cmd, int tty);
c906108c 9127
23860348 9128int get_and_display_threadinfo (threadref *ref);
c906108c 9129
a14ed312 9130static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 9131
23860348 9132static int thread_display_step (threadref *ref, void *context);
c906108c 9133
a14ed312 9134static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 9135
a14ed312 9136static void init_remote_threadtests (void);
c906108c 9137
23860348 9138#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
9139
9140static void
fba45db2 9141threadset_test_cmd (char *cmd, int tty)
c906108c
SS
9142{
9143 int sample_thread = SAMPLE_THREAD;
9144
a3f17187 9145 printf_filtered (_("Remote threadset test\n"));
79d7f229 9146 set_general_thread (sample_thread);
c906108c
SS
9147}
9148
9149
9150static void
fba45db2 9151threadalive_test (char *cmd, int tty)
c906108c
SS
9152{
9153 int sample_thread = SAMPLE_THREAD;
79d7f229 9154 int pid = ptid_get_pid (inferior_ptid);
ba348170 9155 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 9156
79d7f229 9157 if (remote_thread_alive (ptid))
c906108c
SS
9158 printf_filtered ("PASS: Thread alive test\n");
9159 else
9160 printf_filtered ("FAIL: Thread alive test\n");
9161}
9162
23860348 9163void output_threadid (char *title, threadref *ref);
c906108c
SS
9164
9165void
fba45db2 9166output_threadid (char *title, threadref *ref)
c906108c
SS
9167{
9168 char hexid[20];
9169
23860348 9170 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
9171 hexid[16] = 0;
9172 printf_filtered ("%s %s\n", title, (&hexid[0]));
9173}
9174
9175static void
fba45db2 9176threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
9177{
9178 int startflag = 1;
9179 threadref nextthread;
9180 int done, result_count;
9181 threadref threadlist[3];
9182
9183 printf_filtered ("Remote Threadlist test\n");
9184 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9185 &result_count, &threadlist[0]))
9186 printf_filtered ("FAIL: threadlist test\n");
9187 else
9188 {
9189 threadref *scan = threadlist;
9190 threadref *limit = scan + result_count;
9191
9192 while (scan < limit)
9193 output_threadid (" thread ", scan++);
9194 }
9195}
9196
9197void
fba45db2 9198display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
9199{
9200 output_threadid ("Threadid: ", &info->threadid);
9201 printf_filtered ("Name: %s\n ", info->shortname);
9202 printf_filtered ("State: %s\n", info->display);
9203 printf_filtered ("other: %s\n\n", info->more_display);
9204}
9205
9206int
fba45db2 9207get_and_display_threadinfo (threadref *ref)
c906108c
SS
9208{
9209 int result;
9210 int set;
9211 struct gdb_ext_thread_info threadinfo;
9212
9213 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9214 | TAG_MOREDISPLAY | TAG_DISPLAY;
9215 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9216 display_thread_info (&threadinfo);
9217 return result;
9218}
9219
9220static void
fba45db2 9221threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
9222{
9223 int athread = SAMPLE_THREAD;
9224 threadref thread;
9225 int set;
9226
9227 int_to_threadref (&thread, athread);
9228 printf_filtered ("Remote Threadinfo test\n");
9229 if (!get_and_display_threadinfo (&thread))
9230 printf_filtered ("FAIL cannot get thread info\n");
9231}
9232
9233static int
fba45db2 9234thread_display_step (threadref *ref, void *context)
c906108c
SS
9235{
9236 /* output_threadid(" threadstep ",ref); *//* simple test */
9237 return get_and_display_threadinfo (ref);
9238}
9239
9240static void
fba45db2 9241threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
9242{
9243 printf_filtered ("Remote Threadlist update test\n");
9244 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9245}
9246
9247static void
9248init_remote_threadtests (void)
9249{
3e43a32a
MS
9250 add_com ("tlist", class_obscure, threadlist_test_cmd,
9251 _("Fetch and print the remote list of "
9252 "thread identifiers, one pkt only"));
c906108c 9253 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 9254 _("Fetch and display info about one thread"));
c906108c 9255 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 9256 _("Test setting to a different thread"));
c906108c 9257 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 9258 _("Iterate through updating all remote thread info"));
c906108c 9259 add_com ("talive", class_obscure, threadalive_test,
1bedd215 9260 _(" Remote thread alive test "));
c906108c
SS
9261}
9262
9263#endif /* 0 */
9264
f3fb8c85
MS
9265/* Convert a thread ID to a string. Returns the string in a static
9266 buffer. */
9267
9268static char *
117de6a9 9269remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 9270{
79d7f229 9271 static char buf[64];
82f73884 9272 struct remote_state *rs = get_remote_state ();
f3fb8c85 9273
7cee1e54
PA
9274 if (ptid_equal (ptid, null_ptid))
9275 return normal_pid_to_str (ptid);
9276 else if (ptid_is_pid (ptid))
ecd0ada5
PA
9277 {
9278 /* Printing an inferior target id. */
9279
9280 /* When multi-process extensions are off, there's no way in the
9281 remote protocol to know the remote process id, if there's any
9282 at all. There's one exception --- when we're connected with
9283 target extended-remote, and we manually attached to a process
9284 with "attach PID". We don't record anywhere a flag that
9285 allows us to distinguish that case from the case of
9286 connecting with extended-remote and the stub already being
9287 attached to a process, and reporting yes to qAttached, hence
9288 no smart special casing here. */
9289 if (!remote_multi_process_p (rs))
9290 {
9291 xsnprintf (buf, sizeof buf, "Remote target");
9292 return buf;
9293 }
9294
9295 return normal_pid_to_str (ptid);
82f73884 9296 }
ecd0ada5 9297 else
79d7f229 9298 {
ecd0ada5
PA
9299 if (ptid_equal (magic_null_ptid, ptid))
9300 xsnprintf (buf, sizeof buf, "Thread <main>");
901f9912 9301 else if (rs->extended && remote_multi_process_p (rs))
ecd0ada5 9302 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
ba348170 9303 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
9304 else
9305 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 9306 ptid_get_lwp (ptid));
79d7f229
PA
9307 return buf;
9308 }
f3fb8c85
MS
9309}
9310
38691318
KB
9311/* Get the address of the thread local variable in OBJFILE which is
9312 stored at OFFSET within the thread local storage for thread PTID. */
9313
9314static CORE_ADDR
117de6a9
PA
9315remote_get_thread_local_address (struct target_ops *ops,
9316 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 9317{
4082afcc 9318 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
9319 {
9320 struct remote_state *rs = get_remote_state ();
6d820c5c 9321 char *p = rs->buf;
82f73884 9322 char *endp = rs->buf + get_remote_packet_size ();
571dd617 9323 enum packet_result result;
38691318
KB
9324
9325 strcpy (p, "qGetTLSAddr:");
9326 p += strlen (p);
82f73884 9327 p = write_ptid (p, endp, ptid);
38691318
KB
9328 *p++ = ',';
9329 p += hexnumstr (p, offset);
9330 *p++ = ',';
9331 p += hexnumstr (p, lm);
9332 *p++ = '\0';
9333
6d820c5c
DJ
9334 putpkt (rs->buf);
9335 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
9336 result = packet_ok (rs->buf,
9337 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 9338 if (result == PACKET_OK)
38691318
KB
9339 {
9340 ULONGEST result;
9341
6d820c5c 9342 unpack_varlen_hex (rs->buf, &result);
38691318
KB
9343 return result;
9344 }
571dd617 9345 else if (result == PACKET_UNKNOWN)
109c3e39
AC
9346 throw_error (TLS_GENERIC_ERROR,
9347 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 9348 else
109c3e39
AC
9349 throw_error (TLS_GENERIC_ERROR,
9350 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
9351 }
9352 else
109c3e39
AC
9353 throw_error (TLS_GENERIC_ERROR,
9354 _("TLS not supported or disabled on this target"));
38691318
KB
9355 /* Not reached. */
9356 return 0;
9357}
9358
711e434b
PM
9359/* Provide thread local base, i.e. Thread Information Block address.
9360 Returns 1 if ptid is found and thread_local_base is non zero. */
9361
70221824 9362static int
bd7ae0f5 9363remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 9364{
4082afcc 9365 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
9366 {
9367 struct remote_state *rs = get_remote_state ();
9368 char *p = rs->buf;
9369 char *endp = rs->buf + get_remote_packet_size ();
9370 enum packet_result result;
9371
9372 strcpy (p, "qGetTIBAddr:");
9373 p += strlen (p);
9374 p = write_ptid (p, endp, ptid);
9375 *p++ = '\0';
9376
9377 putpkt (rs->buf);
9378 getpkt (&rs->buf, &rs->buf_size, 0);
9379 result = packet_ok (rs->buf,
9380 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9381 if (result == PACKET_OK)
9382 {
9383 ULONGEST result;
9384
9385 unpack_varlen_hex (rs->buf, &result);
9386 if (addr)
9387 *addr = (CORE_ADDR) result;
9388 return 1;
9389 }
9390 else if (result == PACKET_UNKNOWN)
9391 error (_("Remote target doesn't support qGetTIBAddr packet"));
9392 else
9393 error (_("Remote target failed to process qGetTIBAddr request"));
9394 }
9395 else
9396 error (_("qGetTIBAddr not supported or disabled on this target"));
9397 /* Not reached. */
9398 return 0;
9399}
9400
29709017
DJ
9401/* Support for inferring a target description based on the current
9402 architecture and the size of a 'g' packet. While the 'g' packet
9403 can have any size (since optional registers can be left off the
9404 end), some sizes are easily recognizable given knowledge of the
9405 approximate architecture. */
9406
9407struct remote_g_packet_guess
9408{
9409 int bytes;
9410 const struct target_desc *tdesc;
9411};
9412typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9413DEF_VEC_O(remote_g_packet_guess_s);
9414
9415struct remote_g_packet_data
9416{
9417 VEC(remote_g_packet_guess_s) *guesses;
9418};
9419
9420static struct gdbarch_data *remote_g_packet_data_handle;
9421
9422static void *
9423remote_g_packet_data_init (struct obstack *obstack)
9424{
9425 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9426}
9427
9428void
9429register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9430 const struct target_desc *tdesc)
9431{
9432 struct remote_g_packet_data *data
9433 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9434 struct remote_g_packet_guess new_guess, *guess;
9435 int ix;
9436
9437 gdb_assert (tdesc != NULL);
9438
9439 for (ix = 0;
9440 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9441 ix++)
9442 if (guess->bytes == bytes)
9443 internal_error (__FILE__, __LINE__,
9b20d036 9444 _("Duplicate g packet description added for size %d"),
29709017
DJ
9445 bytes);
9446
9447 new_guess.bytes = bytes;
9448 new_guess.tdesc = tdesc;
9449 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9450}
9451
d962ef82
DJ
9452/* Return 1 if remote_read_description would do anything on this target
9453 and architecture, 0 otherwise. */
9454
9455static int
9456remote_read_description_p (struct target_ops *target)
9457{
9458 struct remote_g_packet_data *data
f5656ead 9459 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
d962ef82
DJ
9460
9461 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9462 return 1;
9463
9464 return 0;
9465}
9466
29709017
DJ
9467static const struct target_desc *
9468remote_read_description (struct target_ops *target)
9469{
9470 struct remote_g_packet_data *data
f5656ead 9471 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
29709017 9472
d962ef82
DJ
9473 /* Do not try this during initial connection, when we do not know
9474 whether there is a running but stopped thread. */
9475 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 9476 return target->beneath->to_read_description (target->beneath);
d962ef82 9477
29709017
DJ
9478 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9479 {
9480 struct remote_g_packet_guess *guess;
9481 int ix;
9482 int bytes = send_g_packet ();
9483
9484 for (ix = 0;
9485 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9486 ix++)
9487 if (guess->bytes == bytes)
9488 return guess->tdesc;
9489
9490 /* We discard the g packet. A minor optimization would be to
9491 hold on to it, and fill the register cache once we have selected
9492 an architecture, but it's too tricky to do safely. */
9493 }
9494
2117c711 9495 return target->beneath->to_read_description (target->beneath);
29709017
DJ
9496}
9497
a6b151f1
DJ
9498/* Remote file transfer support. This is host-initiated I/O, not
9499 target-initiated; for target-initiated, see remote-fileio.c. */
9500
9501/* If *LEFT is at least the length of STRING, copy STRING to
9502 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9503 decrease *LEFT. Otherwise raise an error. */
9504
9505static void
9506remote_buffer_add_string (char **buffer, int *left, char *string)
9507{
9508 int len = strlen (string);
9509
9510 if (len > *left)
9511 error (_("Packet too long for target."));
9512
9513 memcpy (*buffer, string, len);
9514 *buffer += len;
9515 *left -= len;
9516
9517 /* NUL-terminate the buffer as a convenience, if there is
9518 room. */
9519 if (*left)
9520 **buffer = '\0';
9521}
9522
9523/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9524 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9525 decrease *LEFT. Otherwise raise an error. */
9526
9527static void
9528remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9529 int len)
9530{
9531 if (2 * len > *left)
9532 error (_("Packet too long for target."));
9533
9534 bin2hex (bytes, *buffer, len);
9535 *buffer += 2 * len;
9536 *left -= 2 * len;
9537
9538 /* NUL-terminate the buffer as a convenience, if there is
9539 room. */
9540 if (*left)
9541 **buffer = '\0';
9542}
9543
9544/* If *LEFT is large enough, convert VALUE to hex and add it to
9545 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9546 decrease *LEFT. Otherwise raise an error. */
9547
9548static void
9549remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9550{
9551 int len = hexnumlen (value);
9552
9553 if (len > *left)
9554 error (_("Packet too long for target."));
9555
9556 hexnumstr (*buffer, value);
9557 *buffer += len;
9558 *left -= len;
9559
9560 /* NUL-terminate the buffer as a convenience, if there is
9561 room. */
9562 if (*left)
9563 **buffer = '\0';
9564}
9565
9566/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9567 value, *REMOTE_ERRNO to the remote error number or zero if none
9568 was included, and *ATTACHMENT to point to the start of the annex
9569 if any. The length of the packet isn't needed here; there may
9570 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9571
9572 Return 0 if the packet could be parsed, -1 if it could not. If
9573 -1 is returned, the other variables may not be initialized. */
9574
9575static int
9576remote_hostio_parse_result (char *buffer, int *retcode,
9577 int *remote_errno, char **attachment)
9578{
9579 char *p, *p2;
9580
9581 *remote_errno = 0;
9582 *attachment = NULL;
9583
9584 if (buffer[0] != 'F')
9585 return -1;
9586
9587 errno = 0;
9588 *retcode = strtol (&buffer[1], &p, 16);
9589 if (errno != 0 || p == &buffer[1])
9590 return -1;
9591
9592 /* Check for ",errno". */
9593 if (*p == ',')
9594 {
9595 errno = 0;
9596 *remote_errno = strtol (p + 1, &p2, 16);
9597 if (errno != 0 || p + 1 == p2)
9598 return -1;
9599 p = p2;
9600 }
9601
9602 /* Check for ";attachment". If there is no attachment, the
9603 packet should end here. */
9604 if (*p == ';')
9605 {
9606 *attachment = p + 1;
9607 return 0;
9608 }
9609 else if (*p == '\0')
9610 return 0;
9611 else
9612 return -1;
9613}
9614
9615/* Send a prepared I/O packet to the target and read its response.
9616 The prepared packet is in the global RS->BUF before this function
9617 is called, and the answer is there when we return.
9618
9619 COMMAND_BYTES is the length of the request to send, which may include
9620 binary data. WHICH_PACKET is the packet configuration to check
9621 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9622 is set to the error number and -1 is returned. Otherwise the value
9623 returned by the function is returned.
9624
9625 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9626 attachment is expected; an error will be reported if there's a
9627 mismatch. If one is found, *ATTACHMENT will be set to point into
9628 the packet buffer and *ATTACHMENT_LEN will be set to the
9629 attachment's length. */
9630
9631static int
9632remote_hostio_send_command (int command_bytes, int which_packet,
9633 int *remote_errno, char **attachment,
9634 int *attachment_len)
9635{
9636 struct remote_state *rs = get_remote_state ();
9637 int ret, bytes_read;
9638 char *attachment_tmp;
9639
5d93a237 9640 if (!rs->remote_desc
4082afcc 9641 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
9642 {
9643 *remote_errno = FILEIO_ENOSYS;
9644 return -1;
9645 }
9646
9647 putpkt_binary (rs->buf, command_bytes);
9648 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9649
9650 /* If it timed out, something is wrong. Don't try to parse the
9651 buffer. */
9652 if (bytes_read < 0)
9653 {
9654 *remote_errno = FILEIO_EINVAL;
9655 return -1;
9656 }
9657
9658 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9659 {
9660 case PACKET_ERROR:
9661 *remote_errno = FILEIO_EINVAL;
9662 return -1;
9663 case PACKET_UNKNOWN:
9664 *remote_errno = FILEIO_ENOSYS;
9665 return -1;
9666 case PACKET_OK:
9667 break;
9668 }
9669
9670 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9671 &attachment_tmp))
9672 {
9673 *remote_errno = FILEIO_EINVAL;
9674 return -1;
9675 }
9676
9677 /* Make sure we saw an attachment if and only if we expected one. */
9678 if ((attachment_tmp == NULL && attachment != NULL)
9679 || (attachment_tmp != NULL && attachment == NULL))
9680 {
9681 *remote_errno = FILEIO_EINVAL;
9682 return -1;
9683 }
9684
9685 /* If an attachment was found, it must point into the packet buffer;
9686 work out how many bytes there were. */
9687 if (attachment_tmp != NULL)
9688 {
9689 *attachment = attachment_tmp;
9690 *attachment_len = bytes_read - (*attachment - rs->buf);
9691 }
9692
9693 return ret;
9694}
9695
9696/* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9697 remote file descriptor, or -1 if an error occurs (and set
9698 *REMOTE_ERRNO). */
9699
9700static int
cd897586
TT
9701remote_hostio_open (struct target_ops *self,
9702 const char *filename, int flags, int mode,
a6b151f1
DJ
9703 int *remote_errno)
9704{
9705 struct remote_state *rs = get_remote_state ();
9706 char *p = rs->buf;
9707 int left = get_remote_packet_size () - 1;
9708
9709 remote_buffer_add_string (&p, &left, "vFile:open:");
9710
9711 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9712 strlen (filename));
9713 remote_buffer_add_string (&p, &left, ",");
9714
9715 remote_buffer_add_int (&p, &left, flags);
9716 remote_buffer_add_string (&p, &left, ",");
9717
9718 remote_buffer_add_int (&p, &left, mode);
9719
9720 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9721 remote_errno, NULL, NULL);
9722}
9723
9724/* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9725 Return the number of bytes written, or -1 if an error occurs (and
9726 set *REMOTE_ERRNO). */
9727
9728static int
0d866f62
TT
9729remote_hostio_pwrite (struct target_ops *self,
9730 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
9731 ULONGEST offset, int *remote_errno)
9732{
9733 struct remote_state *rs = get_remote_state ();
9734 char *p = rs->buf;
9735 int left = get_remote_packet_size ();
9736 int out_len;
9737
9738 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9739
9740 remote_buffer_add_int (&p, &left, fd);
9741 remote_buffer_add_string (&p, &left, ",");
9742
9743 remote_buffer_add_int (&p, &left, offset);
9744 remote_buffer_add_string (&p, &left, ",");
9745
bc20a4af 9746 p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
a6b151f1
DJ
9747 get_remote_packet_size () - (p - rs->buf));
9748
9749 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9750 remote_errno, NULL, NULL);
9751}
9752
9753/* Read up to LEN bytes FD on the remote target into READ_BUF
9754 Return the number of bytes read, or -1 if an error occurs (and
9755 set *REMOTE_ERRNO). */
9756
9757static int
a3be983c
TT
9758remote_hostio_pread (struct target_ops *self,
9759 int fd, gdb_byte *read_buf, int len,
a6b151f1
DJ
9760 ULONGEST offset, int *remote_errno)
9761{
9762 struct remote_state *rs = get_remote_state ();
9763 char *p = rs->buf;
9764 char *attachment;
9765 int left = get_remote_packet_size ();
9766 int ret, attachment_len;
9767 int read_len;
9768
9769 remote_buffer_add_string (&p, &left, "vFile:pread:");
9770
9771 remote_buffer_add_int (&p, &left, fd);
9772 remote_buffer_add_string (&p, &left, ",");
9773
9774 remote_buffer_add_int (&p, &left, len);
9775 remote_buffer_add_string (&p, &left, ",");
9776
9777 remote_buffer_add_int (&p, &left, offset);
9778
9779 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9780 remote_errno, &attachment,
9781 &attachment_len);
9782
9783 if (ret < 0)
9784 return ret;
9785
bc20a4af 9786 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
9787 read_buf, len);
9788 if (read_len != ret)
9789 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9790
9791 return ret;
9792}
9793
9794/* Close FD on the remote target. Return 0, or -1 if an error occurs
9795 (and set *REMOTE_ERRNO). */
9796
9797static int
df39ea25 9798remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
9799{
9800 struct remote_state *rs = get_remote_state ();
9801 char *p = rs->buf;
9802 int left = get_remote_packet_size () - 1;
9803
9804 remote_buffer_add_string (&p, &left, "vFile:close:");
9805
9806 remote_buffer_add_int (&p, &left, fd);
9807
9808 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
9809 remote_errno, NULL, NULL);
9810}
9811
9812/* Unlink FILENAME on the remote target. Return 0, or -1 if an error
9813 occurs (and set *REMOTE_ERRNO). */
9814
9815static int
dbbca37d
TT
9816remote_hostio_unlink (struct target_ops *self,
9817 const char *filename, int *remote_errno)
a6b151f1
DJ
9818{
9819 struct remote_state *rs = get_remote_state ();
9820 char *p = rs->buf;
9821 int left = get_remote_packet_size () - 1;
9822
9823 remote_buffer_add_string (&p, &left, "vFile:unlink:");
9824
9825 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9826 strlen (filename));
9827
9828 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
9829 remote_errno, NULL, NULL);
9830}
9831
b9e7b9c3
UW
9832/* Read value of symbolic link FILENAME on the remote target. Return
9833 a null-terminated string allocated via xmalloc, or NULL if an error
9834 occurs (and set *REMOTE_ERRNO). */
9835
9836static char *
fab5aa7c
TT
9837remote_hostio_readlink (struct target_ops *self,
9838 const char *filename, int *remote_errno)
b9e7b9c3
UW
9839{
9840 struct remote_state *rs = get_remote_state ();
9841 char *p = rs->buf;
9842 char *attachment;
9843 int left = get_remote_packet_size ();
9844 int len, attachment_len;
9845 int read_len;
9846 char *ret;
9847
9848 remote_buffer_add_string (&p, &left, "vFile:readlink:");
9849
9850 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9851 strlen (filename));
9852
9853 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
9854 remote_errno, &attachment,
9855 &attachment_len);
9856
9857 if (len < 0)
9858 return NULL;
9859
9860 ret = xmalloc (len + 1);
9861
bc20a4af
PA
9862 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9863 (gdb_byte *) ret, len);
b9e7b9c3
UW
9864 if (read_len != len)
9865 error (_("Readlink returned %d, but %d bytes."), len, read_len);
9866
9867 ret[len] = '\0';
9868 return ret;
9869}
9870
a6b151f1
DJ
9871static int
9872remote_fileio_errno_to_host (int errnum)
9873{
9874 switch (errnum)
9875 {
9876 case FILEIO_EPERM:
9877 return EPERM;
9878 case FILEIO_ENOENT:
9879 return ENOENT;
9880 case FILEIO_EINTR:
9881 return EINTR;
9882 case FILEIO_EIO:
9883 return EIO;
9884 case FILEIO_EBADF:
9885 return EBADF;
9886 case FILEIO_EACCES:
9887 return EACCES;
9888 case FILEIO_EFAULT:
9889 return EFAULT;
9890 case FILEIO_EBUSY:
9891 return EBUSY;
9892 case FILEIO_EEXIST:
9893 return EEXIST;
9894 case FILEIO_ENODEV:
9895 return ENODEV;
9896 case FILEIO_ENOTDIR:
9897 return ENOTDIR;
9898 case FILEIO_EISDIR:
9899 return EISDIR;
9900 case FILEIO_EINVAL:
9901 return EINVAL;
9902 case FILEIO_ENFILE:
9903 return ENFILE;
9904 case FILEIO_EMFILE:
9905 return EMFILE;
9906 case FILEIO_EFBIG:
9907 return EFBIG;
9908 case FILEIO_ENOSPC:
9909 return ENOSPC;
9910 case FILEIO_ESPIPE:
9911 return ESPIPE;
9912 case FILEIO_EROFS:
9913 return EROFS;
9914 case FILEIO_ENOSYS:
9915 return ENOSYS;
9916 case FILEIO_ENAMETOOLONG:
9917 return ENAMETOOLONG;
9918 }
9919 return -1;
9920}
9921
9922static char *
9923remote_hostio_error (int errnum)
9924{
9925 int host_error = remote_fileio_errno_to_host (errnum);
9926
9927 if (host_error == -1)
9928 error (_("Unknown remote I/O error %d"), errnum);
9929 else
9930 error (_("Remote I/O error: %s"), safe_strerror (host_error));
9931}
9932
a6b151f1
DJ
9933static void
9934remote_hostio_close_cleanup (void *opaque)
9935{
9936 int fd = *(int *) opaque;
9937 int remote_errno;
9938
df39ea25 9939 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
9940}
9941
f1838a98
UW
9942
9943static void *
9944remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
9945{
9946 const char *filename = bfd_get_filename (abfd);
9947 int fd, remote_errno;
9948 int *stream;
9949
9950 gdb_assert (remote_filename_p (filename));
9951
cd897586
TT
9952 fd = remote_hostio_open (find_target_at (process_stratum),
9953 filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
f1838a98
UW
9954 if (fd == -1)
9955 {
9956 errno = remote_fileio_errno_to_host (remote_errno);
9957 bfd_set_error (bfd_error_system_call);
9958 return NULL;
9959 }
9960
9961 stream = xmalloc (sizeof (int));
9962 *stream = fd;
9963 return stream;
9964}
9965
9966static int
9967remote_bfd_iovec_close (struct bfd *abfd, void *stream)
9968{
9969 int fd = *(int *)stream;
9970 int remote_errno;
9971
9972 xfree (stream);
9973
9974 /* Ignore errors on close; these may happen if the remote
9975 connection was already torn down. */
df39ea25 9976 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
f1838a98 9977
39ed5604
JK
9978 /* Zero means success. */
9979 return 0;
f1838a98
UW
9980}
9981
9982static file_ptr
9983remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
9984 file_ptr nbytes, file_ptr offset)
9985{
9986 int fd = *(int *)stream;
9987 int remote_errno;
9988 file_ptr pos, bytes;
9989
9990 pos = 0;
9991 while (nbytes > pos)
9992 {
a3be983c
TT
9993 bytes = remote_hostio_pread (find_target_at (process_stratum),
9994 fd, (gdb_byte *) buf + pos, nbytes - pos,
f1838a98
UW
9995 offset + pos, &remote_errno);
9996 if (bytes == 0)
9997 /* Success, but no bytes, means end-of-file. */
9998 break;
9999 if (bytes == -1)
10000 {
10001 errno = remote_fileio_errno_to_host (remote_errno);
10002 bfd_set_error (bfd_error_system_call);
10003 return -1;
10004 }
10005
10006 pos += bytes;
10007 }
10008
10009 return pos;
10010}
10011
10012static int
10013remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
10014{
10015 /* FIXME: We should probably implement remote_hostio_stat. */
10016 sb->st_size = INT_MAX;
10017 return 0;
10018}
10019
10020int
10021remote_filename_p (const char *filename)
10022{
3736004f
PA
10023 return strncmp (filename,
10024 REMOTE_SYSROOT_PREFIX,
10025 sizeof (REMOTE_SYSROOT_PREFIX) - 1) == 0;
f1838a98
UW
10026}
10027
10028bfd *
10029remote_bfd_open (const char *remote_file, const char *target)
10030{
64c31149
TT
10031 bfd *abfd = gdb_bfd_openr_iovec (remote_file, target,
10032 remote_bfd_iovec_open, NULL,
10033 remote_bfd_iovec_pread,
10034 remote_bfd_iovec_close,
10035 remote_bfd_iovec_stat);
10036
a4453b7e 10037 return abfd;
f1838a98
UW
10038}
10039
a6b151f1
DJ
10040void
10041remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10042{
10043 struct cleanup *back_to, *close_cleanup;
10044 int retcode, fd, remote_errno, bytes, io_size;
10045 FILE *file;
10046 gdb_byte *buffer;
10047 int bytes_in_buffer;
10048 int saw_eof;
10049 ULONGEST offset;
5d93a237 10050 struct remote_state *rs = get_remote_state ();
a6b151f1 10051
5d93a237 10052 if (!rs->remote_desc)
a6b151f1
DJ
10053 error (_("command can only be used with remote target"));
10054
614c279d 10055 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
10056 if (file == NULL)
10057 perror_with_name (local_file);
7c8a8b04 10058 back_to = make_cleanup_fclose (file);
a6b151f1 10059
cd897586
TT
10060 fd = remote_hostio_open (find_target_at (process_stratum),
10061 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1
DJ
10062 | FILEIO_O_TRUNC),
10063 0700, &remote_errno);
10064 if (fd == -1)
10065 remote_hostio_error (remote_errno);
10066
10067 /* Send up to this many bytes at once. They won't all fit in the
10068 remote packet limit, so we'll transfer slightly fewer. */
10069 io_size = get_remote_packet_size ();
10070 buffer = xmalloc (io_size);
10071 make_cleanup (xfree, buffer);
10072
10073 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10074
10075 bytes_in_buffer = 0;
10076 saw_eof = 0;
10077 offset = 0;
10078 while (bytes_in_buffer || !saw_eof)
10079 {
10080 if (!saw_eof)
10081 {
3e43a32a
MS
10082 bytes = fread (buffer + bytes_in_buffer, 1,
10083 io_size - bytes_in_buffer,
a6b151f1
DJ
10084 file);
10085 if (bytes == 0)
10086 {
10087 if (ferror (file))
10088 error (_("Error reading %s."), local_file);
10089 else
10090 {
10091 /* EOF. Unless there is something still in the
10092 buffer from the last iteration, we are done. */
10093 saw_eof = 1;
10094 if (bytes_in_buffer == 0)
10095 break;
10096 }
10097 }
10098 }
10099 else
10100 bytes = 0;
10101
10102 bytes += bytes_in_buffer;
10103 bytes_in_buffer = 0;
10104
0d866f62
TT
10105 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
10106 fd, buffer, bytes,
3e43a32a 10107 offset, &remote_errno);
a6b151f1
DJ
10108
10109 if (retcode < 0)
10110 remote_hostio_error (remote_errno);
10111 else if (retcode == 0)
10112 error (_("Remote write of %d bytes returned 0!"), bytes);
10113 else if (retcode < bytes)
10114 {
10115 /* Short write. Save the rest of the read data for the next
10116 write. */
10117 bytes_in_buffer = bytes - retcode;
10118 memmove (buffer, buffer + retcode, bytes_in_buffer);
10119 }
10120
10121 offset += retcode;
10122 }
10123
10124 discard_cleanups (close_cleanup);
df39ea25 10125 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
10126 remote_hostio_error (remote_errno);
10127
10128 if (from_tty)
10129 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10130 do_cleanups (back_to);
10131}
10132
10133void
10134remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10135{
10136 struct cleanup *back_to, *close_cleanup;
cea39f65 10137 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
10138 FILE *file;
10139 gdb_byte *buffer;
10140 ULONGEST offset;
5d93a237 10141 struct remote_state *rs = get_remote_state ();
a6b151f1 10142
5d93a237 10143 if (!rs->remote_desc)
a6b151f1
DJ
10144 error (_("command can only be used with remote target"));
10145
cd897586
TT
10146 fd = remote_hostio_open (find_target_at (process_stratum),
10147 remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
a6b151f1
DJ
10148 if (fd == -1)
10149 remote_hostio_error (remote_errno);
10150
614c279d 10151 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
10152 if (file == NULL)
10153 perror_with_name (local_file);
7c8a8b04 10154 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
10155
10156 /* Send up to this many bytes at once. They won't all fit in the
10157 remote packet limit, so we'll transfer slightly fewer. */
10158 io_size = get_remote_packet_size ();
10159 buffer = xmalloc (io_size);
10160 make_cleanup (xfree, buffer);
10161
10162 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10163
10164 offset = 0;
10165 while (1)
10166 {
a3be983c
TT
10167 bytes = remote_hostio_pread (find_target_at (process_stratum),
10168 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
10169 if (bytes == 0)
10170 /* Success, but no bytes, means end-of-file. */
10171 break;
10172 if (bytes == -1)
10173 remote_hostio_error (remote_errno);
10174
10175 offset += bytes;
10176
10177 bytes = fwrite (buffer, 1, bytes, file);
10178 if (bytes == 0)
10179 perror_with_name (local_file);
10180 }
10181
10182 discard_cleanups (close_cleanup);
df39ea25 10183 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
10184 remote_hostio_error (remote_errno);
10185
10186 if (from_tty)
10187 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10188 do_cleanups (back_to);
10189}
10190
10191void
10192remote_file_delete (const char *remote_file, int from_tty)
10193{
10194 int retcode, remote_errno;
5d93a237 10195 struct remote_state *rs = get_remote_state ();
a6b151f1 10196
5d93a237 10197 if (!rs->remote_desc)
a6b151f1
DJ
10198 error (_("command can only be used with remote target"));
10199
dbbca37d
TT
10200 retcode = remote_hostio_unlink (find_target_at (process_stratum),
10201 remote_file, &remote_errno);
a6b151f1
DJ
10202 if (retcode == -1)
10203 remote_hostio_error (remote_errno);
10204
10205 if (from_tty)
10206 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10207}
10208
10209static void
10210remote_put_command (char *args, int from_tty)
10211{
10212 struct cleanup *back_to;
10213 char **argv;
10214
d1a41061
PP
10215 if (args == NULL)
10216 error_no_arg (_("file to put"));
10217
10218 argv = gdb_buildargv (args);
a6b151f1
DJ
10219 back_to = make_cleanup_freeargv (argv);
10220 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10221 error (_("Invalid parameters to remote put"));
10222
10223 remote_file_put (argv[0], argv[1], from_tty);
10224
10225 do_cleanups (back_to);
10226}
10227
10228static void
10229remote_get_command (char *args, int from_tty)
10230{
10231 struct cleanup *back_to;
10232 char **argv;
10233
d1a41061
PP
10234 if (args == NULL)
10235 error_no_arg (_("file to get"));
10236
10237 argv = gdb_buildargv (args);
a6b151f1
DJ
10238 back_to = make_cleanup_freeargv (argv);
10239 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10240 error (_("Invalid parameters to remote get"));
10241
10242 remote_file_get (argv[0], argv[1], from_tty);
10243
10244 do_cleanups (back_to);
10245}
10246
10247static void
10248remote_delete_command (char *args, int from_tty)
10249{
10250 struct cleanup *back_to;
10251 char **argv;
10252
d1a41061
PP
10253 if (args == NULL)
10254 error_no_arg (_("file to delete"));
10255
10256 argv = gdb_buildargv (args);
a6b151f1
DJ
10257 back_to = make_cleanup_freeargv (argv);
10258 if (argv[0] == NULL || argv[1] != NULL)
10259 error (_("Invalid parameters to remote delete"));
10260
10261 remote_file_delete (argv[0], from_tty);
10262
10263 do_cleanups (back_to);
10264}
10265
10266static void
10267remote_command (char *args, int from_tty)
10268{
635c7e8a 10269 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
10270}
10271
b2175913 10272static int
19db3e69 10273remote_can_execute_reverse (struct target_ops *self)
b2175913 10274{
4082afcc
PA
10275 if (packet_support (PACKET_bs) == PACKET_ENABLE
10276 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
10277 return 1;
10278 else
10279 return 0;
b2175913
MS
10280}
10281
74531fed 10282static int
2a9a2795 10283remote_supports_non_stop (struct target_ops *self)
74531fed
PA
10284{
10285 return 1;
10286}
10287
03583c20 10288static int
2bfc0540 10289remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
10290{
10291 /* Only supported in extended mode. */
10292 return 0;
10293}
10294
8a305172 10295static int
86ce2668 10296remote_supports_multi_process (struct target_ops *self)
8a305172
PA
10297{
10298 struct remote_state *rs = get_remote_state ();
a744cf53 10299
901f9912
UW
10300 /* Only extended-remote handles being attached to multiple
10301 processes, even though plain remote can use the multi-process
10302 thread id extensions, so that GDB knows the target process's
10303 PID. */
10304 return rs->extended && remote_multi_process_p (rs);
8a305172
PA
10305}
10306
70221824 10307static int
782b2b07
SS
10308remote_supports_cond_tracepoints (void)
10309{
4082afcc 10310 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
10311}
10312
3788aec7 10313static int
efcc2da7 10314remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 10315{
4082afcc 10316 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
10317}
10318
70221824 10319static int
7a697b8d
SS
10320remote_supports_fast_tracepoints (void)
10321{
4082afcc 10322 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
10323}
10324
0fb4aa4b
PA
10325static int
10326remote_supports_static_tracepoints (void)
10327{
4082afcc 10328 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
10329}
10330
1e4d1764
YQ
10331static int
10332remote_supports_install_in_trace (void)
10333{
4082afcc 10334 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
10335}
10336
d248b706 10337static int
7d178d6a 10338remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 10339{
4082afcc
PA
10340 return (packet_support (PACKET_EnableDisableTracepoints_feature)
10341 == PACKET_ENABLE);
d248b706
KY
10342}
10343
3065dfb6 10344static int
6de37a3a 10345remote_supports_string_tracing (struct target_ops *self)
3065dfb6 10346{
4082afcc 10347 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
10348}
10349
d3ce09f5 10350static int
78eff0ec 10351remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 10352{
4082afcc 10353 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
10354}
10355
35b1e5cc 10356static void
ecae04e1 10357remote_trace_init (struct target_ops *self)
35b1e5cc
SS
10358{
10359 putpkt ("QTinit");
10360 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 10361 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
10362 error (_("Target does not support this command."));
10363}
10364
10365static void free_actions_list (char **actions_list);
10366static void free_actions_list_cleanup_wrapper (void *);
10367static void
10368free_actions_list_cleanup_wrapper (void *al)
10369{
10370 free_actions_list (al);
10371}
10372
10373static void
10374free_actions_list (char **actions_list)
10375{
10376 int ndx;
10377
10378 if (actions_list == 0)
10379 return;
10380
10381 for (ndx = 0; actions_list[ndx]; ndx++)
10382 xfree (actions_list[ndx]);
10383
10384 xfree (actions_list);
10385}
10386
409873ef
SS
10387/* Recursive routine to walk through command list including loops, and
10388 download packets for each command. */
10389
10390static void
10391remote_download_command_source (int num, ULONGEST addr,
10392 struct command_line *cmds)
10393{
10394 struct remote_state *rs = get_remote_state ();
10395 struct command_line *cmd;
10396
10397 for (cmd = cmds; cmd; cmd = cmd->next)
10398 {
0df8b418 10399 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
10400 strcpy (rs->buf, "QTDPsrc:");
10401 encode_source_string (num, addr, "cmd", cmd->line,
10402 rs->buf + strlen (rs->buf),
10403 rs->buf_size - strlen (rs->buf));
10404 putpkt (rs->buf);
10405 remote_get_noisy_reply (&target_buf, &target_buf_size);
10406 if (strcmp (target_buf, "OK"))
10407 warning (_("Target does not support source download."));
10408
10409 if (cmd->control_type == while_control
10410 || cmd->control_type == while_stepping_control)
10411 {
10412 remote_download_command_source (num, addr, *cmd->body_list);
10413
0df8b418 10414 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
10415 strcpy (rs->buf, "QTDPsrc:");
10416 encode_source_string (num, addr, "cmd", "end",
10417 rs->buf + strlen (rs->buf),
10418 rs->buf_size - strlen (rs->buf));
10419 putpkt (rs->buf);
10420 remote_get_noisy_reply (&target_buf, &target_buf_size);
10421 if (strcmp (target_buf, "OK"))
10422 warning (_("Target does not support source download."));
10423 }
10424 }
10425}
10426
35b1e5cc 10427static void
548f7808 10428remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 10429{
bba74b36 10430#define BUF_SIZE 2048
e8ba3115 10431
35b1e5cc 10432 CORE_ADDR tpaddr;
409873ef 10433 char addrbuf[40];
bba74b36 10434 char buf[BUF_SIZE];
35b1e5cc
SS
10435 char **tdp_actions;
10436 char **stepping_actions;
10437 int ndx;
10438 struct cleanup *old_chain = NULL;
10439 struct agent_expr *aexpr;
10440 struct cleanup *aexpr_chain = NULL;
10441 char *pkt;
e8ba3115 10442 struct breakpoint *b = loc->owner;
d9b3f62e 10443 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 10444
dc673c81 10445 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
10446 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10447 tdp_actions);
10448 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10449 stepping_actions);
10450
10451 tpaddr = loc->address;
10452 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
10453 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10454 addrbuf, /* address */
10455 (b->enable_state == bp_enabled ? 'E' : 'D'),
10456 t->step_count, t->pass_count);
e8ba3115
YQ
10457 /* Fast tracepoints are mostly handled by the target, but we can
10458 tell the target how big of an instruction block should be moved
10459 around. */
10460 if (b->type == bp_fast_tracepoint)
10461 {
10462 /* Only test for support at download time; we may not know
10463 target capabilities at definition time. */
10464 if (remote_supports_fast_tracepoints ())
35b1e5cc 10465 {
e8ba3115 10466 int isize;
35b1e5cc 10467
f5656ead 10468 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
e8ba3115 10469 tpaddr, &isize, NULL))
bba74b36
YQ
10470 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10471 isize);
35b1e5cc 10472 else
e8ba3115
YQ
10473 /* If it passed validation at definition but fails now,
10474 something is very wrong. */
10475 internal_error (__FILE__, __LINE__,
10476 _("Fast tracepoint not "
10477 "valid during download"));
35b1e5cc 10478 }
e8ba3115
YQ
10479 else
10480 /* Fast tracepoints are functionally identical to regular
10481 tracepoints, so don't take lack of support as a reason to
10482 give up on the trace run. */
10483 warning (_("Target does not support fast tracepoints, "
10484 "downloading %d as regular tracepoint"), b->number);
10485 }
10486 else if (b->type == bp_static_tracepoint)
10487 {
10488 /* Only test for support at download time; we may not know
10489 target capabilities at definition time. */
10490 if (remote_supports_static_tracepoints ())
0fb4aa4b 10491 {
e8ba3115 10492 struct static_tracepoint_marker marker;
0fb4aa4b 10493
e8ba3115
YQ
10494 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10495 strcat (buf, ":S");
0fb4aa4b 10496 else
e8ba3115 10497 error (_("Static tracepoint not valid during download"));
0fb4aa4b 10498 }
e8ba3115
YQ
10499 else
10500 /* Fast tracepoints are functionally identical to regular
10501 tracepoints, so don't take lack of support as a reason
10502 to give up on the trace run. */
10503 error (_("Target does not support static tracepoints"));
10504 }
10505 /* If the tracepoint has a conditional, make it into an agent
10506 expression and append to the definition. */
10507 if (loc->cond)
10508 {
10509 /* Only test support at download time, we may not know target
10510 capabilities at definition time. */
10511 if (remote_supports_cond_tracepoints ())
35b1e5cc 10512 {
e8ba3115
YQ
10513 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10514 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
10515 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10516 aexpr->len);
e8ba3115
YQ
10517 pkt = buf + strlen (buf);
10518 for (ndx = 0; ndx < aexpr->len; ++ndx)
10519 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10520 *pkt = '\0';
10521 do_cleanups (aexpr_chain);
35b1e5cc 10522 }
e8ba3115
YQ
10523 else
10524 warning (_("Target does not support conditional tracepoints, "
10525 "ignoring tp %d cond"), b->number);
10526 }
35b1e5cc 10527
d9b3f62e 10528 if (b->commands || *default_collect)
e8ba3115
YQ
10529 strcat (buf, "-");
10530 putpkt (buf);
10531 remote_get_noisy_reply (&target_buf, &target_buf_size);
10532 if (strcmp (target_buf, "OK"))
10533 error (_("Target does not support tracepoints."));
35b1e5cc 10534
e8ba3115
YQ
10535 /* do_single_steps (t); */
10536 if (tdp_actions)
10537 {
10538 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 10539 {
e8ba3115 10540 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
10541 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10542 b->number, addrbuf, /* address */
10543 tdp_actions[ndx],
10544 ((tdp_actions[ndx + 1] || stepping_actions)
10545 ? '-' : 0));
e8ba3115
YQ
10546 putpkt (buf);
10547 remote_get_noisy_reply (&target_buf,
10548 &target_buf_size);
10549 if (strcmp (target_buf, "OK"))
10550 error (_("Error on target while setting tracepoints."));
35b1e5cc 10551 }
e8ba3115
YQ
10552 }
10553 if (stepping_actions)
10554 {
10555 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 10556 {
e8ba3115 10557 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
10558 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10559 b->number, addrbuf, /* address */
10560 ((ndx == 0) ? "S" : ""),
10561 stepping_actions[ndx],
10562 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
10563 putpkt (buf);
10564 remote_get_noisy_reply (&target_buf,
10565 &target_buf_size);
10566 if (strcmp (target_buf, "OK"))
10567 error (_("Error on target while setting tracepoints."));
35b1e5cc 10568 }
e8ba3115 10569 }
409873ef 10570
4082afcc 10571 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115
YQ
10572 {
10573 if (b->addr_string)
409873ef 10574 {
e8ba3115
YQ
10575 strcpy (buf, "QTDPsrc:");
10576 encode_source_string (b->number, loc->address,
10577 "at", b->addr_string, buf + strlen (buf),
10578 2048 - strlen (buf));
409873ef 10579
e8ba3115
YQ
10580 putpkt (buf);
10581 remote_get_noisy_reply (&target_buf, &target_buf_size);
10582 if (strcmp (target_buf, "OK"))
10583 warning (_("Target does not support source download."));
409873ef 10584 }
e8ba3115
YQ
10585 if (b->cond_string)
10586 {
10587 strcpy (buf, "QTDPsrc:");
10588 encode_source_string (b->number, loc->address,
10589 "cond", b->cond_string, buf + strlen (buf),
10590 2048 - strlen (buf));
10591 putpkt (buf);
10592 remote_get_noisy_reply (&target_buf, &target_buf_size);
10593 if (strcmp (target_buf, "OK"))
10594 warning (_("Target does not support source download."));
10595 }
10596 remote_download_command_source (b->number, loc->address,
10597 breakpoint_commands (b));
35b1e5cc 10598 }
e8ba3115
YQ
10599
10600 do_cleanups (old_chain);
35b1e5cc
SS
10601}
10602
1e4d1764 10603static int
a52a8357 10604remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 10605{
1e51243a
PA
10606 struct remote_state *rs = get_remote_state ();
10607 struct trace_status *ts;
10608 int status;
10609
10610 /* Don't try to install tracepoints until we've relocated our
10611 symbols, and fetched and merged the target's tracepoint list with
10612 ours. */
10613 if (rs->starting_up)
10614 return 0;
10615
10616 ts = current_trace_status ();
8bd200f1 10617 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
10618
10619 if (status == -1 || !ts->running_known || !ts->running)
10620 return 0;
10621
10622 /* If we are in a tracing experiment, but remote stub doesn't support
10623 installing tracepoint in trace, we have to return. */
10624 if (!remote_supports_install_in_trace ())
10625 return 0;
10626
10627 return 1;
10628}
10629
10630
35b1e5cc 10631static void
559d2b81
TT
10632remote_download_trace_state_variable (struct target_ops *self,
10633 struct trace_state_variable *tsv)
35b1e5cc
SS
10634{
10635 struct remote_state *rs = get_remote_state ();
00bf0b85 10636 char *p;
35b1e5cc 10637
bba74b36
YQ
10638 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10639 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10640 tsv->builtin);
00bf0b85
SS
10641 p = rs->buf + strlen (rs->buf);
10642 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10643 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 10644 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 10645 *p++ = '\0';
35b1e5cc
SS
10646 putpkt (rs->buf);
10647 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
10648 if (*target_buf == '\0')
10649 error (_("Target does not support this command."));
10650 if (strcmp (target_buf, "OK") != 0)
10651 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
10652}
10653
d248b706 10654static void
46670d57
TT
10655remote_enable_tracepoint (struct target_ops *self,
10656 struct bp_location *location)
d248b706
KY
10657{
10658 struct remote_state *rs = get_remote_state ();
10659 char addr_buf[40];
10660
10661 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
10662 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10663 location->owner->number, addr_buf);
d248b706
KY
10664 putpkt (rs->buf);
10665 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10666 if (*rs->buf == '\0')
10667 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10668 if (strcmp (rs->buf, "OK") != 0)
10669 error (_("Error on target while enabling tracepoint."));
10670}
10671
10672static void
780b049c
TT
10673remote_disable_tracepoint (struct target_ops *self,
10674 struct bp_location *location)
d248b706
KY
10675{
10676 struct remote_state *rs = get_remote_state ();
10677 char addr_buf[40];
10678
10679 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
10680 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10681 location->owner->number, addr_buf);
d248b706
KY
10682 putpkt (rs->buf);
10683 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10684 if (*rs->buf == '\0')
10685 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10686 if (strcmp (rs->buf, "OK") != 0)
10687 error (_("Error on target while disabling tracepoint."));
10688}
10689
35b1e5cc 10690static void
583f9a86 10691remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
10692{
10693 asection *s;
81b9b86e 10694 bfd *abfd = NULL;
35b1e5cc 10695 bfd_size_type size;
608bcef2 10696 bfd_vma vma;
35b1e5cc 10697 int anysecs = 0;
c2fa21f1 10698 int offset = 0;
35b1e5cc
SS
10699
10700 if (!exec_bfd)
10701 return; /* No information to give. */
10702
10703 strcpy (target_buf, "QTro");
9779ab84 10704 offset = strlen (target_buf);
35b1e5cc
SS
10705 for (s = exec_bfd->sections; s; s = s->next)
10706 {
10707 char tmp1[40], tmp2[40];
c2fa21f1 10708 int sec_length;
35b1e5cc
SS
10709
10710 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 10711 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
10712 (s->flags & SEC_READONLY) == 0)
10713 continue;
10714
10715 anysecs = 1;
81b9b86e 10716 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 10717 size = bfd_get_section_size (s);
608bcef2
HZ
10718 sprintf_vma (tmp1, vma);
10719 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
10720 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10721 if (offset + sec_length + 1 > target_buf_size)
10722 {
4082afcc 10723 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 10724 warning (_("\
c2fa21f1
HZ
10725Too many sections for read-only sections definition packet."));
10726 break;
10727 }
bba74b36
YQ
10728 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10729 tmp1, tmp2);
c2fa21f1 10730 offset += sec_length;
35b1e5cc
SS
10731 }
10732 if (anysecs)
10733 {
10734 putpkt (target_buf);
10735 getpkt (&target_buf, &target_buf_size, 0);
10736 }
10737}
10738
10739static void
e2d1aae3 10740remote_trace_start (struct target_ops *self)
35b1e5cc
SS
10741{
10742 putpkt ("QTStart");
10743 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
10744 if (*target_buf == '\0')
10745 error (_("Target does not support this command."));
10746 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
10747 error (_("Bogus reply from target: %s"), target_buf);
10748}
10749
10750static int
8bd200f1 10751remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 10752{
953b98d1 10753 /* Initialize it just to avoid a GCC false warning. */
f652de6f 10754 char *p = NULL;
0df8b418 10755 /* FIXME we need to get register block size some other way. */
00bf0b85 10756 extern int trace_regblock_size;
67f41397 10757 volatile struct gdb_exception ex;
bd3eecc3
PA
10758 enum packet_result result;
10759
4082afcc 10760 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 10761 return -1;
a744cf53 10762
00bf0b85
SS
10763 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10764
049dc89b
JK
10765 putpkt ("qTStatus");
10766
67f41397
JK
10767 TRY_CATCH (ex, RETURN_MASK_ERROR)
10768 {
10769 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10770 }
10771 if (ex.reason < 0)
10772 {
598d3636
JK
10773 if (ex.error != TARGET_CLOSE_ERROR)
10774 {
10775 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10776 return -1;
10777 }
10778 throw_exception (ex);
67f41397 10779 }
00bf0b85 10780
bd3eecc3
PA
10781 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
10782
00bf0b85 10783 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 10784 if (result == PACKET_UNKNOWN)
00bf0b85 10785 return -1;
35b1e5cc 10786
00bf0b85 10787 /* We're working with a live target. */
f5911ea1 10788 ts->filename = NULL;
00bf0b85 10789
00bf0b85 10790 if (*p++ != 'T')
35b1e5cc
SS
10791 error (_("Bogus trace status reply from target: %s"), target_buf);
10792
84cebc4a
YQ
10793 /* Function 'parse_trace_status' sets default value of each field of
10794 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
10795 parse_trace_status (p, ts);
10796
10797 return ts->running;
35b1e5cc
SS
10798}
10799
70221824 10800static void
db90e85c 10801remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
10802 struct uploaded_tp *utp)
10803{
10804 struct remote_state *rs = get_remote_state ();
f196051f
SS
10805 char *reply;
10806 struct bp_location *loc;
10807 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 10808 size_t size = get_remote_packet_size ();
f196051f
SS
10809
10810 if (tp)
10811 {
10812 tp->base.hit_count = 0;
10813 tp->traceframe_usage = 0;
10814 for (loc = tp->base.loc; loc; loc = loc->next)
10815 {
10816 /* If the tracepoint was never downloaded, don't go asking for
10817 any status. */
10818 if (tp->number_on_target == 0)
10819 continue;
bba74b36
YQ
10820 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
10821 phex_nz (loc->address, 0));
f196051f
SS
10822 putpkt (rs->buf);
10823 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10824 if (reply && *reply)
10825 {
10826 if (*reply == 'V')
10827 parse_tracepoint_status (reply + 1, bp, utp);
10828 }
10829 }
10830 }
10831 else if (utp)
10832 {
10833 utp->hit_count = 0;
10834 utp->traceframe_usage = 0;
bba74b36
YQ
10835 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
10836 phex_nz (utp->addr, 0));
f196051f
SS
10837 putpkt (rs->buf);
10838 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10839 if (reply && *reply)
10840 {
10841 if (*reply == 'V')
10842 parse_tracepoint_status (reply + 1, bp, utp);
10843 }
10844 }
10845}
10846
35b1e5cc 10847static void
74499f1b 10848remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
10849{
10850 putpkt ("QTStop");
10851 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
10852 if (*target_buf == '\0')
10853 error (_("Target does not support this command."));
10854 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
10855 error (_("Bogus reply from target: %s"), target_buf);
10856}
10857
10858static int
bd4c6793
TT
10859remote_trace_find (struct target_ops *self,
10860 enum trace_find_type type, int num,
cc5925ad 10861 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
10862 int *tpp)
10863{
10864 struct remote_state *rs = get_remote_state ();
bba74b36 10865 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
10866 char *p, *reply;
10867 int target_frameno = -1, target_tracept = -1;
10868
e6e4e701
PA
10869 /* Lookups other than by absolute frame number depend on the current
10870 trace selected, so make sure it is correct on the remote end
10871 first. */
10872 if (type != tfind_number)
10873 set_remote_traceframe ();
10874
35b1e5cc
SS
10875 p = rs->buf;
10876 strcpy (p, "QTFrame:");
10877 p = strchr (p, '\0');
10878 switch (type)
10879 {
10880 case tfind_number:
bba74b36 10881 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
10882 break;
10883 case tfind_pc:
bba74b36 10884 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
10885 break;
10886 case tfind_tp:
bba74b36 10887 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
10888 break;
10889 case tfind_range:
bba74b36
YQ
10890 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
10891 phex_nz (addr2, 0));
35b1e5cc
SS
10892 break;
10893 case tfind_outside:
bba74b36
YQ
10894 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
10895 phex_nz (addr2, 0));
35b1e5cc
SS
10896 break;
10897 default:
9b20d036 10898 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
10899 }
10900
10901 putpkt (rs->buf);
2f65bcb7 10902 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
10903 if (*reply == '\0')
10904 error (_("Target does not support this command."));
35b1e5cc
SS
10905
10906 while (reply && *reply)
10907 switch (*reply)
10908 {
10909 case 'F':
f197e0f1
VP
10910 p = ++reply;
10911 target_frameno = (int) strtol (p, &reply, 16);
10912 if (reply == p)
10913 error (_("Unable to parse trace frame number"));
e6e4e701
PA
10914 /* Don't update our remote traceframe number cache on failure
10915 to select a remote traceframe. */
f197e0f1
VP
10916 if (target_frameno == -1)
10917 return -1;
35b1e5cc
SS
10918 break;
10919 case 'T':
f197e0f1
VP
10920 p = ++reply;
10921 target_tracept = (int) strtol (p, &reply, 16);
10922 if (reply == p)
10923 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
10924 break;
10925 case 'O': /* "OK"? */
10926 if (reply[1] == 'K' && reply[2] == '\0')
10927 reply += 2;
10928 else
10929 error (_("Bogus reply from target: %s"), reply);
10930 break;
10931 default:
10932 error (_("Bogus reply from target: %s"), reply);
10933 }
10934 if (tpp)
10935 *tpp = target_tracept;
e6e4e701 10936
262e1174 10937 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
10938 return target_frameno;
10939}
10940
10941static int
4011015b
TT
10942remote_get_trace_state_variable_value (struct target_ops *self,
10943 int tsvnum, LONGEST *val)
35b1e5cc
SS
10944{
10945 struct remote_state *rs = get_remote_state ();
10946 char *reply;
10947 ULONGEST uval;
10948
e6e4e701
PA
10949 set_remote_traceframe ();
10950
bba74b36 10951 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
10952 putpkt (rs->buf);
10953 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10954 if (reply && *reply)
10955 {
10956 if (*reply == 'V')
10957 {
10958 unpack_varlen_hex (reply + 1, &uval);
10959 *val = (LONGEST) uval;
10960 return 1;
10961 }
10962 }
10963 return 0;
10964}
10965
00bf0b85 10966static int
dc3decaf 10967remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
10968{
10969 struct remote_state *rs = get_remote_state ();
10970 char *p, *reply;
10971
10972 p = rs->buf;
10973 strcpy (p, "QTSave:");
10974 p += strlen (p);
10975 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
10976 error (_("Remote file name too long for trace save packet"));
9f1b45b0 10977 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
10978 *p++ = '\0';
10979 putpkt (rs->buf);
ad91cd99 10980 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 10981 if (*reply == '\0')
ad91cd99
PA
10982 error (_("Target does not support this command."));
10983 if (strcmp (reply, "OK") != 0)
10984 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
10985 return 0;
10986}
10987
10988/* This is basically a memory transfer, but needs to be its own packet
10989 because we don't know how the target actually organizes its trace
10990 memory, plus we want to be able to ask for as much as possible, but
10991 not be unhappy if we don't get as much as we ask for. */
10992
10993static LONGEST
88ee6f45
TT
10994remote_get_raw_trace_data (struct target_ops *self,
10995 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
10996{
10997 struct remote_state *rs = get_remote_state ();
10998 char *reply;
10999 char *p;
11000 int rslt;
11001
11002 p = rs->buf;
11003 strcpy (p, "qTBuffer:");
11004 p += strlen (p);
11005 p += hexnumstr (p, offset);
11006 *p++ = ',';
11007 p += hexnumstr (p, len);
11008 *p++ = '\0';
11009
11010 putpkt (rs->buf);
11011 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11012 if (reply && *reply)
11013 {
11014 /* 'l' by itself means we're at the end of the buffer and
11015 there is nothing more to get. */
11016 if (*reply == 'l')
11017 return 0;
11018
11019 /* Convert the reply into binary. Limit the number of bytes to
11020 convert according to our passed-in buffer size, rather than
11021 what was returned in the packet; if the target is
11022 unexpectedly generous and gives us a bigger reply than we
11023 asked for, we don't want to crash. */
11024 rslt = hex2bin (target_buf, buf, len);
11025 return rslt;
11026 }
11027
11028 /* Something went wrong, flag as an error. */
11029 return -1;
11030}
11031
35b1e5cc 11032static void
37b25738 11033remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
11034{
11035 struct remote_state *rs = get_remote_state ();
11036
4082afcc 11037 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 11038 {
ad91cd99
PA
11039 char *reply;
11040
bba74b36 11041 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 11042 putpkt (rs->buf);
ad91cd99
PA
11043 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11044 if (*reply == '\0')
33da3f1c 11045 error (_("Target does not support this command."));
ad91cd99
PA
11046 if (strcmp (reply, "OK") != 0)
11047 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
11048 }
11049 else if (val)
11050 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
11051}
11052
dc146f7c
VP
11053static int
11054remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11055{
11056 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 11057
dc146f7c
VP
11058 if (info && info->private)
11059 return info->private->core;
11060 return -1;
11061}
11062
4daf5ac0 11063static void
736d5b1f 11064remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
11065{
11066 struct remote_state *rs = get_remote_state ();
ad91cd99 11067 char *reply;
4daf5ac0 11068
bba74b36 11069 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 11070 putpkt (rs->buf);
ad91cd99
PA
11071 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11072 if (*reply == '\0')
4daf5ac0 11073 error (_("Target does not support this command."));
ad91cd99
PA
11074 if (strcmp (reply, "OK") != 0)
11075 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
11076}
11077
b3b9301e 11078static struct traceframe_info *
a893e81f 11079remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
11080{
11081 char *text;
11082
11083 text = target_read_stralloc (&current_target,
11084 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11085 if (text != NULL)
11086 {
11087 struct traceframe_info *info;
11088 struct cleanup *back_to = make_cleanup (xfree, text);
11089
11090 info = parse_traceframe_info (text);
11091 do_cleanups (back_to);
11092 return info;
11093 }
11094
11095 return NULL;
11096}
11097
405f8e94
SS
11098/* Handle the qTMinFTPILen packet. Returns the minimum length of
11099 instruction on which a fast tracepoint may be placed. Returns -1
11100 if the packet is not supported, and 0 if the minimum instruction
11101 length is unknown. */
11102
11103static int
0e67620a 11104remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
11105{
11106 struct remote_state *rs = get_remote_state ();
11107 char *reply;
11108
e886a173
PA
11109 /* If we're not debugging a process yet, the IPA can't be
11110 loaded. */
11111 if (!target_has_execution)
11112 return 0;
11113
11114 /* Make sure the remote is pointing at the right process. */
11115 set_general_process ();
11116
bba74b36 11117 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
11118 putpkt (rs->buf);
11119 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11120 if (*reply == '\0')
11121 return -1;
11122 else
11123 {
11124 ULONGEST min_insn_len;
11125
11126 unpack_varlen_hex (reply, &min_insn_len);
11127
11128 return (int) min_insn_len;
11129 }
11130}
11131
f6f899bf 11132static void
4da384be 11133remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 11134{
4082afcc 11135 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
11136 {
11137 struct remote_state *rs = get_remote_state ();
11138 char *buf = rs->buf;
11139 char *endbuf = rs->buf + get_remote_packet_size ();
11140 enum packet_result result;
11141
11142 gdb_assert (val >= 0 || val == -1);
11143 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11144 /* Send -1 as literal "-1" to avoid host size dependency. */
11145 if (val < 0)
11146 {
11147 *buf++ = '-';
11148 buf += hexnumstr (buf, (ULONGEST) -val);
11149 }
11150 else
11151 buf += hexnumstr (buf, (ULONGEST) val);
11152
11153 putpkt (rs->buf);
11154 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11155 result = packet_ok (rs->buf,
11156 &remote_protocol_packets[PACKET_QTBuffer_size]);
11157
11158 if (result != PACKET_OK)
11159 warning (_("Bogus reply from target: %s"), rs->buf);
11160 }
11161}
11162
f196051f 11163static int
d9e68a2c
TT
11164remote_set_trace_notes (struct target_ops *self,
11165 const char *user, const char *notes,
ca623f82 11166 const char *stop_notes)
f196051f
SS
11167{
11168 struct remote_state *rs = get_remote_state ();
11169 char *reply;
11170 char *buf = rs->buf;
11171 char *endbuf = rs->buf + get_remote_packet_size ();
11172 int nbytes;
11173
11174 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11175 if (user)
11176 {
11177 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 11178 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
11179 buf += 2 * nbytes;
11180 *buf++ = ';';
11181 }
11182 if (notes)
11183 {
11184 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 11185 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
11186 buf += 2 * nbytes;
11187 *buf++ = ';';
11188 }
11189 if (stop_notes)
11190 {
11191 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 11192 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
11193 buf += 2 * nbytes;
11194 *buf++ = ';';
11195 }
11196 /* Ensure the buffer is terminated. */
11197 *buf = '\0';
11198
11199 putpkt (rs->buf);
11200 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11201 if (*reply == '\0')
11202 return 0;
11203
11204 if (strcmp (reply, "OK") != 0)
11205 error (_("Bogus reply from target: %s"), reply);
11206
11207 return 1;
11208}
11209
d1feda86 11210static int
2c152180 11211remote_use_agent (struct target_ops *self, int use)
d1feda86 11212{
4082afcc 11213 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
11214 {
11215 struct remote_state *rs = get_remote_state ();
11216
11217 /* If the stub supports QAgent. */
bba74b36 11218 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
11219 putpkt (rs->buf);
11220 getpkt (&rs->buf, &rs->buf_size, 0);
11221
11222 if (strcmp (rs->buf, "OK") == 0)
11223 {
11224 use_agent = use;
11225 return 1;
11226 }
11227 }
11228
11229 return 0;
11230}
11231
11232static int
fe38f897 11233remote_can_use_agent (struct target_ops *self)
d1feda86 11234{
4082afcc 11235 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
11236}
11237
9accd112
MM
11238struct btrace_target_info
11239{
11240 /* The ptid of the traced thread. */
11241 ptid_t ptid;
11242};
11243
11244/* Check whether the target supports branch tracing. */
11245
11246static int
46917d26 11247remote_supports_btrace (struct target_ops *self)
9accd112 11248{
4082afcc 11249 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 11250 return 0;
4082afcc 11251 if (packet_support (PACKET_Qbtrace_bts) != PACKET_ENABLE)
9accd112 11252 return 0;
4082afcc 11253 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
11254 return 0;
11255
11256 return 1;
11257}
11258
11259/* Enable branch tracing. */
11260
11261static struct btrace_target_info *
e3c49f88 11262remote_enable_btrace (struct target_ops *self, ptid_t ptid)
9accd112
MM
11263{
11264 struct btrace_target_info *tinfo = NULL;
11265 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11266 struct remote_state *rs = get_remote_state ();
11267 char *buf = rs->buf;
11268 char *endbuf = rs->buf + get_remote_packet_size ();
11269
4082afcc 11270 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
11271 error (_("Target does not support branch tracing."));
11272
11273 set_general_thread (ptid);
11274
11275 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11276 putpkt (rs->buf);
11277 getpkt (&rs->buf, &rs->buf_size, 0);
11278
11279 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11280 {
11281 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11282 error (_("Could not enable branch tracing for %s: %s"),
11283 target_pid_to_str (ptid), rs->buf + 2);
11284 else
11285 error (_("Could not enable branch tracing for %s."),
11286 target_pid_to_str (ptid));
11287 }
11288
11289 tinfo = xzalloc (sizeof (*tinfo));
11290 tinfo->ptid = ptid;
11291
11292 return tinfo;
11293}
11294
11295/* Disable branch tracing. */
11296
11297static void
25e95349
TT
11298remote_disable_btrace (struct target_ops *self,
11299 struct btrace_target_info *tinfo)
9accd112
MM
11300{
11301 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11302 struct remote_state *rs = get_remote_state ();
11303 char *buf = rs->buf;
11304 char *endbuf = rs->buf + get_remote_packet_size ();
11305
4082afcc 11306 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
11307 error (_("Target does not support branch tracing."));
11308
11309 set_general_thread (tinfo->ptid);
11310
11311 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11312 putpkt (rs->buf);
11313 getpkt (&rs->buf, &rs->buf_size, 0);
11314
11315 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11316 {
11317 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11318 error (_("Could not disable branch tracing for %s: %s"),
11319 target_pid_to_str (tinfo->ptid), rs->buf + 2);
11320 else
11321 error (_("Could not disable branch tracing for %s."),
11322 target_pid_to_str (tinfo->ptid));
11323 }
11324
11325 xfree (tinfo);
11326}
11327
11328/* Teardown branch tracing. */
11329
11330static void
1777056d
TT
11331remote_teardown_btrace (struct target_ops *self,
11332 struct btrace_target_info *tinfo)
9accd112
MM
11333{
11334 /* We must not talk to the target during teardown. */
11335 xfree (tinfo);
11336}
11337
11338/* Read the branch trace. */
11339
969c39fb 11340static enum btrace_error
39c49f83
TT
11341remote_read_btrace (struct target_ops *self,
11342 VEC (btrace_block_s) **btrace,
969c39fb 11343 struct btrace_target_info *tinfo,
9accd112
MM
11344 enum btrace_read_type type)
11345{
11346 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11347 struct remote_state *rs = get_remote_state ();
969c39fb 11348 struct cleanup *cleanup;
9accd112
MM
11349 const char *annex;
11350 char *xml;
11351
4082afcc 11352 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
11353 error (_("Target does not support branch tracing."));
11354
11355#if !defined(HAVE_LIBEXPAT)
11356 error (_("Cannot process branch tracing result. XML parsing not supported."));
11357#endif
11358
11359 switch (type)
11360 {
864089d2 11361 case BTRACE_READ_ALL:
9accd112
MM
11362 annex = "all";
11363 break;
864089d2 11364 case BTRACE_READ_NEW:
9accd112
MM
11365 annex = "new";
11366 break;
969c39fb
MM
11367 case BTRACE_READ_DELTA:
11368 annex = "delta";
11369 break;
9accd112
MM
11370 default:
11371 internal_error (__FILE__, __LINE__,
11372 _("Bad branch tracing read type: %u."),
11373 (unsigned int) type);
11374 }
11375
11376 xml = target_read_stralloc (&current_target,
11377 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
11378 if (xml == NULL)
11379 return BTRACE_ERR_UNKNOWN;
9accd112 11380
969c39fb
MM
11381 cleanup = make_cleanup (xfree, xml);
11382 *btrace = parse_xml_btrace (xml);
11383 do_cleanups (cleanup);
9accd112 11384
969c39fb 11385 return BTRACE_ERR_NONE;
9accd112
MM
11386}
11387
ced63ec0 11388static int
5436ff03 11389remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 11390{
4082afcc
PA
11391 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
11392 == PACKET_ENABLE);
ced63ec0
GB
11393}
11394
9dd130a0
TT
11395/* Implementation of to_load. */
11396
11397static void
9cbe5fff 11398remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
11399{
11400 generic_load (name, from_tty);
11401}
11402
c906108c 11403static void
fba45db2 11404init_remote_ops (void)
c906108c 11405{
c5aa993b 11406 remote_ops.to_shortname = "remote";
c906108c 11407 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 11408 remote_ops.to_doc =
c906108c 11409 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
11410Specify the serial device it is connected to\n\
11411(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
11412 remote_ops.to_open = remote_open;
11413 remote_ops.to_close = remote_close;
c906108c 11414 remote_ops.to_detach = remote_detach;
6ad8ae5c 11415 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 11416 remote_ops.to_resume = remote_resume;
c906108c
SS
11417 remote_ops.to_wait = remote_wait;
11418 remote_ops.to_fetch_registers = remote_fetch_registers;
11419 remote_ops.to_store_registers = remote_store_registers;
11420 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 11421 remote_ops.to_files_info = remote_files_info;
c906108c
SS
11422 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11423 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
3c3bea1c
GS
11424 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11425 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
11426 remote_ops.to_watchpoint_addr_within_range =
11427 remote_watchpoint_addr_within_range;
3c3bea1c
GS
11428 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11429 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11430 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
11431 remote_ops.to_region_ok_for_hw_watchpoint
11432 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
11433 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11434 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 11435 remote_ops.to_kill = remote_kill;
9dd130a0 11436 remote_ops.to_load = remote_load;
c906108c 11437 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 11438 remote_ops.to_pass_signals = remote_pass_signals;
9b224c5e 11439 remote_ops.to_program_signals = remote_program_signals;
c906108c 11440 remote_ops.to_thread_alive = remote_thread_alive;
0f71a2f6 11441 remote_ops.to_find_new_threads = remote_threads_info;
0caabb7e 11442 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 11443 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 11444 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 11445 remote_ops.to_stop = remote_stop;
4b8a223f 11446 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 11447 remote_ops.to_rcmd = remote_rcmd;
49d03eab 11448 remote_ops.to_log_command = serial_log_command;
38691318 11449 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 11450 remote_ops.to_stratum = process_stratum;
c35b1492
PA
11451 remote_ops.to_has_all_memory = default_child_has_all_memory;
11452 remote_ops.to_has_memory = default_child_has_memory;
11453 remote_ops.to_has_stack = default_child_has_stack;
11454 remote_ops.to_has_registers = default_child_has_registers;
11455 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 11456 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 11457 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 11458 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 11459 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
11460 remote_ops.to_flash_erase = remote_flash_erase;
11461 remote_ops.to_flash_done = remote_flash_done;
29709017 11462 remote_ops.to_read_description = remote_read_description;
08388c79 11463 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
11464 remote_ops.to_can_async_p = remote_can_async_p;
11465 remote_ops.to_is_async_p = remote_is_async_p;
11466 remote_ops.to_async = remote_async;
75c99385
PA
11467 remote_ops.to_terminal_inferior = remote_terminal_inferior;
11468 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 11469 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 11470 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
11471 remote_ops.to_supports_disable_randomization
11472 = remote_supports_disable_randomization;
7313baad
UW
11473 remote_ops.to_fileio_open = remote_hostio_open;
11474 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11475 remote_ops.to_fileio_pread = remote_hostio_pread;
11476 remote_ops.to_fileio_close = remote_hostio_close;
11477 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 11478 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 11479 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 11480 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 11481 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 11482 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
11483 remote_ops.to_trace_init = remote_trace_init;
11484 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 11485 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
11486 remote_ops.to_download_trace_state_variable
11487 = remote_download_trace_state_variable;
d248b706
KY
11488 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11489 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
11490 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11491 remote_ops.to_trace_start = remote_trace_start;
11492 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 11493 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
11494 remote_ops.to_trace_stop = remote_trace_stop;
11495 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
11496 remote_ops.to_get_trace_state_variable_value
11497 = remote_get_trace_state_variable_value;
00bf0b85
SS
11498 remote_ops.to_save_trace_data = remote_save_trace_data;
11499 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
11500 remote_ops.to_upload_trace_state_variables
11501 = remote_upload_trace_state_variables;
00bf0b85 11502 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 11503 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 11504 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 11505 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 11506 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 11507 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 11508 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 11509 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 11510 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 11511 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
11512 remote_ops.to_static_tracepoint_marker_at
11513 = remote_static_tracepoint_marker_at;
11514 remote_ops.to_static_tracepoint_markers_by_strid
11515 = remote_static_tracepoint_markers_by_strid;
b3b9301e 11516 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
11517 remote_ops.to_use_agent = remote_use_agent;
11518 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
11519 remote_ops.to_supports_btrace = remote_supports_btrace;
11520 remote_ops.to_enable_btrace = remote_enable_btrace;
11521 remote_ops.to_disable_btrace = remote_disable_btrace;
11522 remote_ops.to_teardown_btrace = remote_teardown_btrace;
11523 remote_ops.to_read_btrace = remote_read_btrace;
ced63ec0
GB
11524 remote_ops.to_augmented_libraries_svr4_read =
11525 remote_augmented_libraries_svr4_read;
c906108c
SS
11526}
11527
11528/* Set up the extended remote vector by making a copy of the standard
11529 remote vector and adding to it. */
11530
11531static void
fba45db2 11532init_extended_remote_ops (void)
c906108c
SS
11533{
11534 extended_remote_ops = remote_ops;
11535
0f71a2f6 11536 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 11537 extended_remote_ops.to_longname =
c906108c 11538 "Extended remote serial target in gdb-specific protocol";
c5aa993b 11539 extended_remote_ops.to_doc =
c906108c 11540 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
11541Specify the serial device it is connected to (e.g. /dev/ttya).";
11542 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
11543 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11544 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
11545 extended_remote_ops.to_detach = extended_remote_detach;
11546 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 11547 extended_remote_ops.to_post_attach = extended_remote_post_attach;
82f73884 11548 extended_remote_ops.to_kill = extended_remote_kill;
03583c20
UW
11549 extended_remote_ops.to_supports_disable_randomization
11550 = extended_remote_supports_disable_randomization;
0f71a2f6
JM
11551}
11552
6426a772 11553static int
6a109b6b 11554remote_can_async_p (struct target_ops *ops)
6426a772 11555{
5d93a237
TT
11556 struct remote_state *rs = get_remote_state ();
11557
c6ebd6cf 11558 if (!target_async_permitted)
75c99385
PA
11559 /* We only enable async when the user specifically asks for it. */
11560 return 0;
11561
23860348 11562 /* We're async whenever the serial device is. */
5d93a237 11563 return serial_can_async_p (rs->remote_desc);
6426a772
JM
11564}
11565
11566static int
6a109b6b 11567remote_is_async_p (struct target_ops *ops)
6426a772 11568{
5d93a237
TT
11569 struct remote_state *rs = get_remote_state ();
11570
c6ebd6cf 11571 if (!target_async_permitted)
75c99385
PA
11572 /* We only enable async when the user specifically asks for it. */
11573 return 0;
11574
23860348 11575 /* We're async whenever the serial device is. */
5d93a237 11576 return serial_is_async_p (rs->remote_desc);
6426a772
JM
11577}
11578
2acceee2
JM
11579/* Pass the SERIAL event on and up to the client. One day this code
11580 will be able to delay notifying the client of an event until the
23860348 11581 point where an entire packet has been received. */
2acceee2 11582
2acceee2
JM
11583static serial_event_ftype remote_async_serial_handler;
11584
6426a772 11585static void
819cc324 11586remote_async_serial_handler (struct serial *scb, void *context)
6426a772 11587{
88b496c3
TT
11588 struct remote_state *rs = context;
11589
2acceee2
JM
11590 /* Don't propogate error information up to the client. Instead let
11591 the client find out about the error by querying the target. */
88b496c3 11592 rs->async_client_callback (INF_REG_EVENT, rs->async_client_context);
2acceee2
JM
11593}
11594
74531fed
PA
11595static void
11596remote_async_inferior_event_handler (gdb_client_data data)
11597{
11598 inferior_event_handler (INF_REG_EVENT, NULL);
11599}
11600
2acceee2 11601static void
6a109b6b
TT
11602remote_async (struct target_ops *ops,
11603 void (*callback) (enum inferior_event_type event_type,
11604 void *context),
11605 void *context)
2acceee2 11606{
5d93a237
TT
11607 struct remote_state *rs = get_remote_state ();
11608
2acceee2
JM
11609 if (callback != NULL)
11610 {
88b496c3
TT
11611 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
11612 rs->async_client_callback = callback;
11613 rs->async_client_context = context;
2acceee2
JM
11614 }
11615 else
5d93a237 11616 serial_async (rs->remote_desc, NULL, NULL);
6426a772
JM
11617}
11618
5a2468f5 11619static void
c2d11a7d 11620set_remote_cmd (char *args, int from_tty)
5a2468f5 11621{
635c7e8a 11622 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
11623}
11624
d471ea57
AC
11625static void
11626show_remote_cmd (char *args, int from_tty)
11627{
37a105a1 11628 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 11629 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
11630 struct cleanup *showlist_chain;
11631 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 11632 struct ui_out *uiout = current_uiout;
37a105a1
DJ
11633
11634 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
11635 for (; list != NULL; list = list->next)
11636 if (strcmp (list->name, "Z-packet") == 0)
11637 continue;
427c3a89
DJ
11638 else if (list->type == not_set_cmd)
11639 /* Alias commands are exactly like the original, except they
11640 don't have the normal type. */
11641 continue;
11642 else
37a105a1
DJ
11643 {
11644 struct cleanup *option_chain
11645 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 11646
37a105a1
DJ
11647 ui_out_field_string (uiout, "name", list->name);
11648 ui_out_text (uiout, ": ");
427c3a89 11649 if (list->type == show_cmd)
5b9afe8a 11650 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
11651 else
11652 cmd_func (list, NULL, from_tty);
37a105a1
DJ
11653 /* Close the tuple. */
11654 do_cleanups (option_chain);
11655 }
427c3a89
DJ
11656
11657 /* Close the tuple. */
11658 do_cleanups (showlist_chain);
d471ea57 11659}
5a2468f5 11660
0f71a2f6 11661
23860348 11662/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
11663static void
11664remote_new_objfile (struct objfile *objfile)
11665{
5d93a237
TT
11666 struct remote_state *rs = get_remote_state ();
11667
11668 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 11669 remote_check_symbols ();
dc8acb97
MS
11670}
11671
00bf0b85
SS
11672/* Pull all the tracepoints defined on the target and create local
11673 data structures representing them. We don't want to create real
11674 tracepoints yet, we don't want to mess up the user's existing
11675 collection. */
11676
11677static int
ab6617cc 11678remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 11679{
00bf0b85
SS
11680 struct remote_state *rs = get_remote_state ();
11681 char *p;
d5551862 11682
00bf0b85
SS
11683 /* Ask for a first packet of tracepoint definition. */
11684 putpkt ("qTfP");
11685 getpkt (&rs->buf, &rs->buf_size, 0);
11686 p = rs->buf;
11687 while (*p && *p != 'l')
d5551862 11688 {
00bf0b85
SS
11689 parse_tracepoint_definition (p, utpp);
11690 /* Ask for another packet of tracepoint definition. */
11691 putpkt ("qTsP");
11692 getpkt (&rs->buf, &rs->buf_size, 0);
11693 p = rs->buf;
d5551862 11694 }
00bf0b85 11695 return 0;
d5551862
SS
11696}
11697
00bf0b85 11698static int
181e3713
TT
11699remote_upload_trace_state_variables (struct target_ops *self,
11700 struct uploaded_tsv **utsvp)
d5551862 11701{
00bf0b85 11702 struct remote_state *rs = get_remote_state ();
d5551862 11703 char *p;
d5551862 11704
00bf0b85
SS
11705 /* Ask for a first packet of variable definition. */
11706 putpkt ("qTfV");
d5551862
SS
11707 getpkt (&rs->buf, &rs->buf_size, 0);
11708 p = rs->buf;
00bf0b85 11709 while (*p && *p != 'l')
d5551862 11710 {
00bf0b85
SS
11711 parse_tsv_definition (p, utsvp);
11712 /* Ask for another packet of variable definition. */
11713 putpkt ("qTsV");
d5551862
SS
11714 getpkt (&rs->buf, &rs->buf_size, 0);
11715 p = rs->buf;
11716 }
00bf0b85 11717 return 0;
d5551862
SS
11718}
11719
c1e36e3e
PA
11720/* The "set/show range-stepping" show hook. */
11721
11722static void
11723show_range_stepping (struct ui_file *file, int from_tty,
11724 struct cmd_list_element *c,
11725 const char *value)
11726{
11727 fprintf_filtered (file,
11728 _("Debugger's willingness to use range stepping "
11729 "is %s.\n"), value);
11730}
11731
11732/* The "set/show range-stepping" set hook. */
11733
11734static void
11735set_range_stepping (char *ignore_args, int from_tty,
11736 struct cmd_list_element *c)
11737{
5d93a237
TT
11738 struct remote_state *rs = get_remote_state ();
11739
c1e36e3e
PA
11740 /* Whene enabling, check whether range stepping is actually
11741 supported by the target, and warn if not. */
11742 if (use_range_stepping)
11743 {
5d93a237 11744 if (rs->remote_desc != NULL)
c1e36e3e 11745 {
4082afcc 11746 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
11747 remote_vcont_probe (rs);
11748
4082afcc 11749 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
11750 && rs->supports_vCont.r)
11751 return;
11752 }
11753
11754 warning (_("Range stepping is not supported by the current target"));
11755 }
11756}
11757
c906108c 11758void
fba45db2 11759_initialize_remote (void)
c906108c 11760{
ea9c271d 11761 struct remote_state *rs;
9a7071a8 11762 struct cmd_list_element *cmd;
6f937416 11763 const char *cmd_name;
ea9c271d 11764
0f71a2f6 11765 /* architecture specific data */
2bc416ba 11766 remote_gdbarch_data_handle =
23860348 11767 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
11768 remote_g_packet_data_handle =
11769 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 11770
ea9c271d
DJ
11771 /* Initialize the per-target state. At the moment there is only one
11772 of these, not one per target. Only one target is active at a
cf792862
TT
11773 time. */
11774 remote_state = new_remote_state ();
ea9c271d 11775
c906108c
SS
11776 init_remote_ops ();
11777 add_target (&remote_ops);
11778
11779 init_extended_remote_ops ();
11780 add_target (&extended_remote_ops);
cce74817 11781
dc8acb97 11782 /* Hook into new objfile notification. */
06d3b283 11783 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
11784 /* We're no longer interested in notification events of an inferior
11785 when it exits. */
11786 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 11787
b803fb0f 11788 /* Set up signal handlers. */
934b9bac 11789 async_sigint_remote_token =
b803fb0f 11790 create_async_signal_handler (async_remote_interrupt, NULL);
934b9bac 11791 async_sigint_remote_twice_token =
6d549500 11792 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 11793
c906108c
SS
11794#if 0
11795 init_remote_threadtests ();
11796#endif
11797
722247f1 11798 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 11799 /* set/show remote ... */
d471ea57 11800
1bedd215 11801 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
11802Remote protocol specific variables\n\
11803Configure various remote-protocol specific variables such as\n\
1bedd215 11804the packets being used"),
cff3e48b 11805 &remote_set_cmdlist, "set remote ",
23860348 11806 0 /* allow-unknown */, &setlist);
1bedd215 11807 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
11808Remote protocol specific variables\n\
11809Configure various remote-protocol specific variables such as\n\
1bedd215 11810the packets being used"),
cff3e48b 11811 &remote_show_cmdlist, "show remote ",
23860348 11812 0 /* allow-unknown */, &showlist);
5a2468f5 11813
1a966eab
AC
11814 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
11815Compare section data on target to the exec file.\n\
95cf3b38
DT
11816Argument is a single section name (default: all loaded sections).\n\
11817To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
11818 &cmdlist);
11819
1a966eab
AC
11820 add_cmd ("packet", class_maintenance, packet_command, _("\
11821Send an arbitrary packet to a remote target.\n\
c906108c
SS
11822 maintenance packet TEXT\n\
11823If GDB is talking to an inferior via the GDB serial protocol, then\n\
11824this command sends the string TEXT to the inferior, and displays the\n\
11825response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 11826terminating `#' character and checksum."),
c906108c
SS
11827 &maintenancelist);
11828
7915a72c
AC
11829 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
11830Set whether to send break if interrupted."), _("\
11831Show whether to send break if interrupted."), _("\
11832If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 11833 set_remotebreak, show_remotebreak,
e707bbc2 11834 &setlist, &showlist);
9a7071a8
JB
11835 cmd_name = "remotebreak";
11836 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
11837 deprecate_cmd (cmd, "set remote interrupt-sequence");
11838 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
11839 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
11840 deprecate_cmd (cmd, "show remote interrupt-sequence");
11841
11842 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
11843 interrupt_sequence_modes, &interrupt_sequence_mode,
11844 _("\
9a7071a8
JB
11845Set interrupt sequence to remote target."), _("\
11846Show interrupt sequence to remote target."), _("\
11847Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
11848 NULL, show_interrupt_sequence,
11849 &remote_set_cmdlist,
11850 &remote_show_cmdlist);
11851
11852 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
11853 &interrupt_on_connect, _("\
11854Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11855Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11856If set, interrupt sequence is sent to remote target."),
11857 NULL, NULL,
11858 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 11859
23860348 11860 /* Install commands for configuring memory read/write packets. */
11cf8741 11861
1a966eab
AC
11862 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
11863Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 11864 &setlist);
1a966eab
AC
11865 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
11866Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
11867 &showlist);
11868 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
11869 set_memory_write_packet_size, _("\
11870Set the maximum number of bytes per memory-write packet.\n\
11871Specify the number of bytes in a packet or 0 (zero) for the\n\
11872default packet size. The actual limit is further reduced\n\
11873dependent on the target. Specify ``fixed'' to disable the\n\
11874further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
11875 &remote_set_cmdlist);
11876 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
11877 set_memory_read_packet_size, _("\
11878Set the maximum number of bytes per memory-read packet.\n\
11879Specify the number of bytes in a packet or 0 (zero) for the\n\
11880default packet size. The actual limit is further reduced\n\
11881dependent on the target. Specify ``fixed'' to disable the\n\
11882further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
11883 &remote_set_cmdlist);
11884 add_cmd ("memory-write-packet-size", no_class,
11885 show_memory_write_packet_size,
1a966eab 11886 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
11887 &remote_show_cmdlist);
11888 add_cmd ("memory-read-packet-size", no_class,
11889 show_memory_read_packet_size,
1a966eab 11890 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 11891 &remote_show_cmdlist);
c906108c 11892
b3f42336 11893 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
11894 &remote_hw_watchpoint_limit, _("\
11895Set the maximum number of target hardware watchpoints."), _("\
11896Show the maximum number of target hardware watchpoints."), _("\
11897Specify a negative limit for unlimited."),
3e43a32a
MS
11898 NULL, NULL, /* FIXME: i18n: The maximum
11899 number of target hardware
11900 watchpoints is %s. */
b3f42336 11901 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
11902 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
11903 &remote_hw_watchpoint_length_limit, _("\
11904Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
11905Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
11906Specify a negative limit for unlimited."),
11907 NULL, NULL, /* FIXME: i18n: The maximum
11908 length (in bytes) of a target
11909 hardware watchpoint is %s. */
11910 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 11911 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
11912 &remote_hw_breakpoint_limit, _("\
11913Set the maximum number of target hardware breakpoints."), _("\
11914Show the maximum number of target hardware breakpoints."), _("\
11915Specify a negative limit for unlimited."),
3e43a32a
MS
11916 NULL, NULL, /* FIXME: i18n: The maximum
11917 number of target hardware
11918 breakpoints is %s. */
b3f42336 11919 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 11920
1b493192
PA
11921 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
11922 &remote_address_size, _("\
4d28ad1e
AC
11923Set the maximum size of the address (in bits) in a memory packet."), _("\
11924Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
11925 NULL,
11926 NULL, /* FIXME: i18n: */
11927 &setlist, &showlist);
c906108c 11928
ca4f7f8b
PA
11929 init_all_packet_configs ();
11930
444abaca 11931 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 11932 "X", "binary-download", 1);
0f71a2f6 11933
444abaca 11934 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 11935 "vCont", "verbose-resume", 0);
506fb367 11936
89be2091
DJ
11937 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
11938 "QPassSignals", "pass-signals", 0);
11939
9b224c5e
PA
11940 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
11941 "QProgramSignals", "program-signals", 0);
11942
444abaca 11943 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 11944 "qSymbol", "symbol-lookup", 0);
dc8acb97 11945
444abaca 11946 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 11947 "P", "set-register", 1);
d471ea57 11948
444abaca 11949 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 11950 "p", "fetch-register", 1);
b96ec7ac 11951
444abaca 11952 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 11953 "Z0", "software-breakpoint", 0);
d471ea57 11954
444abaca 11955 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 11956 "Z1", "hardware-breakpoint", 0);
d471ea57 11957
444abaca 11958 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 11959 "Z2", "write-watchpoint", 0);
d471ea57 11960
444abaca 11961 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 11962 "Z3", "read-watchpoint", 0);
d471ea57 11963
444abaca 11964 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 11965 "Z4", "access-watchpoint", 0);
d471ea57 11966
0876f84a
DJ
11967 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
11968 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 11969
23181151
DJ
11970 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
11971 "qXfer:features:read", "target-features", 0);
11972
cfa9d6d9
DJ
11973 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
11974 "qXfer:libraries:read", "library-info", 0);
11975
2268b414
JK
11976 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
11977 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
11978
fd79ecee
DJ
11979 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
11980 "qXfer:memory-map:read", "memory-map", 0);
11981
0e7f50da
UW
11982 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
11983 "qXfer:spu:read", "read-spu-object", 0);
11984
11985 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
11986 "qXfer:spu:write", "write-spu-object", 0);
11987
07e059b5
VP
11988 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
11989 "qXfer:osdata:read", "osdata", 0);
11990
dc146f7c
VP
11991 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
11992 "qXfer:threads:read", "threads", 0);
11993
4aa995e1
PA
11994 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
11995 "qXfer:siginfo:read", "read-siginfo-object", 0);
11996
11997 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
11998 "qXfer:siginfo:write", "write-siginfo-object", 0);
11999
b3b9301e
PA
12000 add_packet_config_cmd
12001 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 12002 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 12003
169081d0
TG
12004 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12005 "qXfer:uib:read", "unwind-info-block", 0);
12006
444abaca 12007 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 12008 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
12009 0);
12010
711e434b
PM
12011 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12012 "qGetTIBAddr", "get-thread-information-block-address",
12013 0);
12014
40ab02ce
MS
12015 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12016 "bc", "reverse-continue", 0);
12017
12018 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12019 "bs", "reverse-step", 0);
12020
be2a5f71
DJ
12021 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12022 "qSupported", "supported-packets", 0);
12023
08388c79
DE
12024 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12025 "qSearch:memory", "search-memory", 0);
12026
bd3eecc3
PA
12027 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12028 "qTStatus", "trace-status", 0);
12029
a6b151f1
DJ
12030 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12031 "vFile:open", "hostio-open", 0);
12032
12033 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12034 "vFile:pread", "hostio-pread", 0);
12035
12036 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12037 "vFile:pwrite", "hostio-pwrite", 0);
12038
12039 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12040 "vFile:close", "hostio-close", 0);
12041
12042 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12043 "vFile:unlink", "hostio-unlink", 0);
12044
b9e7b9c3
UW
12045 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12046 "vFile:readlink", "hostio-readlink", 0);
12047
2d717e4f
DJ
12048 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12049 "vAttach", "attach", 0);
12050
12051 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12052 "vRun", "run", 0);
12053
a6f3e723
SL
12054 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12055 "QStartNoAckMode", "noack", 0);
12056
82f73884
PA
12057 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12058 "vKill", "kill", 0);
12059
0b16c5cf
PA
12060 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12061 "qAttached", "query-attached", 0);
12062
782b2b07 12063 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
12064 "ConditionalTracepoints",
12065 "conditional-tracepoints", 0);
3788aec7
LM
12066
12067 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12068 "ConditionalBreakpoints",
12069 "conditional-breakpoints", 0);
12070
d3ce09f5
SS
12071 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12072 "BreakpointCommands",
12073 "breakpoint-commands", 0);
12074
7a697b8d
SS
12075 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12076 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 12077
409873ef
SS
12078 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12079 "TracepointSource", "TracepointSource", 0);
12080
d914c394
SS
12081 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12082 "QAllow", "allow", 0);
12083
0fb4aa4b
PA
12084 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12085 "StaticTracepoints", "static-tracepoints", 0);
12086
1e4d1764
YQ
12087 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12088 "InstallInTrace", "install-in-trace", 0);
12089
0fb4aa4b
PA
12090 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12091 "qXfer:statictrace:read", "read-sdata-object", 0);
12092
78d85199
YQ
12093 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12094 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12095
03583c20
UW
12096 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12097 "QDisableRandomization", "disable-randomization", 0);
12098
d1feda86
YQ
12099 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12100 "QAgent", "agent", 0);
12101
f6f899bf
HAQ
12102 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12103 "QTBuffer:size", "trace-buffer-size", 0);
12104
9accd112
MM
12105 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12106 "Qbtrace:off", "disable-btrace", 0);
12107
12108 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12109 "Qbtrace:bts", "enable-btrace", 0);
12110
12111 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12112 "qXfer:btrace", "read-btrace", 0);
12113
ca4f7f8b
PA
12114 /* Assert that we've registered commands for all packet configs. */
12115 {
12116 int i;
12117
12118 for (i = 0; i < PACKET_MAX; i++)
12119 {
12120 /* Ideally all configs would have a command associated. Some
12121 still don't though. */
12122 int excepted;
12123
12124 switch (i)
12125 {
12126 case PACKET_QNonStop:
12127 case PACKET_multiprocess_feature:
12128 case PACKET_EnableDisableTracepoints_feature:
12129 case PACKET_tracenz_feature:
12130 case PACKET_DisconnectedTracing_feature:
12131 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
12132 case PACKET_qCRC:
12133 /* Additions to this list need to be well justified:
12134 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
12135 excepted = 1;
12136 break;
12137 default:
12138 excepted = 0;
12139 break;
12140 }
12141
12142 /* This catches both forgetting to add a config command, and
12143 forgetting to remove a packet from the exception list. */
12144 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
12145 }
12146 }
12147
37a105a1
DJ
12148 /* Keep the old ``set remote Z-packet ...'' working. Each individual
12149 Z sub-packet has its own set and show commands, but users may
12150 have sets to this variable in their .gdbinit files (or in their
12151 documentation). */
e9e68a56 12152 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
12153 &remote_Z_packet_detect, _("\
12154Set use of remote protocol `Z' packets"), _("\
12155Show use of remote protocol `Z' packets "), _("\
3b64bf98 12156When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 12157packets."),
e9e68a56 12158 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
12159 show_remote_protocol_Z_packet_cmd,
12160 /* FIXME: i18n: Use of remote protocol
12161 `Z' packets is %s. */
e9e68a56 12162 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 12163
a6b151f1
DJ
12164 add_prefix_cmd ("remote", class_files, remote_command, _("\
12165Manipulate files on the remote system\n\
12166Transfer files to and from the remote target system."),
12167 &remote_cmdlist, "remote ",
12168 0 /* allow-unknown */, &cmdlist);
12169
12170 add_cmd ("put", class_files, remote_put_command,
12171 _("Copy a local file to the remote system."),
12172 &remote_cmdlist);
12173
12174 add_cmd ("get", class_files, remote_get_command,
12175 _("Copy a remote file to the local system."),
12176 &remote_cmdlist);
12177
12178 add_cmd ("delete", class_files, remote_delete_command,
12179 _("Delete a remote file."),
12180 &remote_cmdlist);
12181
2d717e4f
DJ
12182 remote_exec_file = xstrdup ("");
12183 add_setshow_string_noescape_cmd ("exec-file", class_files,
12184 &remote_exec_file, _("\
12185Set the remote pathname for \"run\""), _("\
12186Show the remote pathname for \"run\""), NULL, NULL, NULL,
12187 &remote_set_cmdlist, &remote_show_cmdlist);
12188
c1e36e3e
PA
12189 add_setshow_boolean_cmd ("range-stepping", class_run,
12190 &use_range_stepping, _("\
12191Enable or disable range stepping."), _("\
12192Show whether target-assisted range stepping is enabled."), _("\
12193If on, and the target supports it, when stepping a source line, GDB\n\
12194tells the target to step the corresponding range of addresses itself instead\n\
12195of issuing multiple single-steps. This speeds up source level\n\
12196stepping. If off, GDB always issues single-steps, even if range\n\
12197stepping is supported by the target. The default is on."),
12198 set_range_stepping,
12199 show_range_stepping,
12200 &setlist,
12201 &showlist);
12202
449092f6
CV
12203 /* Eventually initialize fileio. See fileio.c */
12204 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 12205
ba348170 12206 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 12207 special ptids with it set to != 0. */
ba348170
PA
12208 magic_null_ptid = ptid_build (42000, -1, 1);
12209 not_sent_ptid = ptid_build (42000, -2, 1);
12210 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
12211
12212 target_buf_size = 2048;
12213 target_buf = xmalloc (target_buf_size);
c906108c 12214}
10760264 12215
This page took 2.825223 seconds and 4 git commands to generate.