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