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