Implement remote_bfd_iovec_stat
[deliverable/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
32d0add0 3 Copyright (C) 1988-2015 Free Software Foundation, Inc.
c906108c 4
c5aa993b
JM
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
c5aa993b
JM
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5aa993b 19
23860348 20/* See the GDB User Guide for details of the GDB remote protocol. */
c5aa993b 21
c906108c 22#include "defs.h"
c906108c
SS
23#include <ctype.h>
24#include <fcntl.h>
c906108c 25#include "inferior.h"
45741a9c 26#include "infrun.h"
c906108c
SS
27#include "bfd.h"
28#include "symfile.h"
29#include "target.h"
c5aa993b 30/*#include "terminal.h" */
c906108c
SS
31#include "gdbcmd.h"
32#include "objfiles.h"
33#include "gdb-stabs.h"
34#include "gdbthread.h"
c2c6d25f 35#include "remote.h"
722247f1 36#include "remote-notif.h"
4e052eda 37#include "regcache.h"
fd0407d6 38#include "value.h"
6867ae3e 39#include "observer.h"
a77053c2 40#include "solib.h"
37a105a1
DJ
41#include "cli/cli-decode.h"
42#include "cli/cli-setshow.h"
424163ea 43#include "target-descriptions.h"
a4453b7e 44#include "gdb_bfd.h"
614c279d 45#include "filestuff.h"
9c3d6531 46#include "rsp-low.h"
c906108c 47
9846de1b 48#include <sys/time.h>
c906108c 49
43ff13b4 50#include "event-loop.h"
c2c6d25f 51#include "event-top.h"
2acceee2 52#include "inf-loop.h"
43ff13b4 53
c906108c
SS
54#include <signal.h>
55#include "serial.h"
56
6240bebf
MS
57#include "gdbcore.h" /* for exec_bfd */
58
449092f6 59#include "remote-fileio.h"
a6b151f1 60#include "gdb/fileio.h"
53ce3c39 61#include <sys/stat.h>
dc146f7c 62#include "xml-support.h"
449092f6 63
fd79ecee
DJ
64#include "memory-map.h"
65
35b1e5cc
SS
66#include "tracepoint.h"
67#include "ax.h"
68#include "ax-gdb.h"
d1feda86 69#include "agent.h"
9accd112 70#include "btrace.h"
35b1e5cc 71
0df8b418 72/* Temp hacks for tracepoint encoding migration. */
35b1e5cc
SS
73static char *target_buf;
74static long target_buf_size;
35b1e5cc 75
6765f3e5
DJ
76/* The size to align memory write packets, when practical. The protocol
77 does not guarantee any alignment, and gdb will generate short
78 writes and unaligned writes, but even as a best-effort attempt this
79 can improve bulk transfers. For instance, if a write is misaligned
80 relative to the target's data bus, the stub may need to make an extra
81 round trip fetching data from the target. This doesn't make a
82 huge difference, but it's easy to do, so we try to be helpful.
83
84 The alignment chosen is arbitrary; usually data bus width is
85 important here, not the possibly larger cache line size. */
86enum { REMOTE_ALIGN_WRITES = 16 };
87
23860348 88/* Prototypes for local functions. */
934b9bac 89static void async_cleanup_sigint_signal_handler (void *dummy);
6d820c5c 90static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
74531fed 91static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
fee9eda9 92 int forever, int *is_notif);
6426a772 93
934b9bac
JK
94static void async_handle_remote_sigint (int);
95static void async_handle_remote_sigint_twice (int);
43ff13b4 96
a14ed312 97static void remote_files_info (struct target_ops *ignore);
c906108c 98
f32dbf8c
MM
99static void remote_prepare_to_store (struct target_ops *self,
100 struct regcache *regcache);
c906108c 101
014f9477
TT
102static void remote_open_1 (const char *, int, struct target_ops *,
103 int extended_p);
c906108c 104
de90e03d 105static void remote_close (struct target_ops *self);
c906108c 106
136d6dae 107static void remote_mourn (struct target_ops *ops);
c906108c 108
a14ed312 109static void extended_remote_restart (void);
c906108c 110
136d6dae 111static void extended_remote_mourn (struct target_ops *);
c906108c 112
a14ed312 113static void remote_mourn_1 (struct target_ops *);
c906108c 114
6d820c5c 115static void remote_send (char **buf, long *sizeof_buf_p);
c906108c 116
a14ed312 117static int readchar (int timeout);
c906108c 118
c33e31fd
PA
119static void remote_serial_write (const char *str, int len);
120
7d85a9c0 121static void remote_kill (struct target_ops *ops);
c906108c 122
6a109b6b 123static int remote_can_async_p (struct target_ops *);
75c99385 124
6a109b6b 125static int remote_is_async_p (struct target_ops *);
75c99385 126
6a109b6b
TT
127static void remote_async (struct target_ops *ops,
128 void (*callback) (enum inferior_event_type event_type,
129 void *context),
130 void *context);
75c99385 131
934b9bac 132static void sync_remote_interrupt_twice (int signo);
7a292a7a 133
a14ed312 134static void interrupt_query (void);
c906108c 135
79d7f229
PA
136static void set_general_thread (struct ptid ptid);
137static void set_continue_thread (struct ptid ptid);
c906108c 138
a14ed312 139static void get_offsets (void);
c906108c 140
6d820c5c
DJ
141static void skip_frame (void);
142
143static long read_frame (char **buf_p, long *sizeof_buf);
c906108c 144
a14ed312 145static int hexnumlen (ULONGEST num);
c906108c 146
a14ed312 147static void init_remote_ops (void);
c906108c 148
a14ed312 149static void init_extended_remote_ops (void);
c906108c 150
1eab8a48 151static void remote_stop (struct target_ops *self, ptid_t);
c906108c 152
a14ed312 153static int stubhex (int ch);
c906108c 154
a14ed312 155static int hexnumstr (char *, ULONGEST);
c906108c 156
a14ed312 157static int hexnumnstr (char *, ULONGEST, int);
2df3850c 158
a14ed312 159static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 160
baa336ce 161static void print_packet (const char *);
c906108c 162
a14ed312 163static void compare_sections_command (char *, int);
c906108c 164
a14ed312 165static void packet_command (char *, int);
c906108c 166
a14ed312 167static int stub_unpack_int (char *buff, int fieldlength);
c906108c 168
39f77062 169static ptid_t remote_current_thread (ptid_t oldptid);
c906108c 170
baa336ce 171static int putpkt_binary (const char *buf, int cnt);
c906108c 172
a14ed312 173static void check_binary_download (CORE_ADDR addr);
c906108c 174
5a2468f5 175struct packet_config;
5a2468f5 176
a14ed312 177static void show_packet_config_cmd (struct packet_config *config);
5a2468f5 178
bb572ddd
DJ
179static void show_remote_protocol_packet_cmd (struct ui_file *file,
180 int from_tty,
181 struct cmd_list_element *c,
182 const char *value);
183
82f73884
PA
184static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
185static ptid_t read_ptid (char *buf, char **obuf);
186
c378d69d 187static void remote_set_permissions (struct target_ops *self);
d914c394 188
d5551862 189struct remote_state;
8bd200f1
TT
190static int remote_get_trace_status (struct target_ops *self,
191 struct trace_status *ts);
d5551862 192
ab6617cc
TT
193static int remote_upload_tracepoints (struct target_ops *self,
194 struct uploaded_tp **utpp);
00bf0b85 195
181e3713
TT
196static int remote_upload_trace_state_variables (struct target_ops *self,
197 struct uploaded_tsv **utsvp);
00bf0b85 198
c8d104ad
PA
199static void remote_query_supported (void);
200
36d25514 201static void remote_check_symbols (void);
c8d104ad 202
a14ed312 203void _initialize_remote (void);
c906108c 204
74531fed 205struct stop_reply;
74531fed 206static void stop_reply_xfree (struct stop_reply *);
722247f1 207static void remote_parse_stop_reply (char *, struct stop_reply *);
74531fed 208static void push_stop_reply (struct stop_reply *);
bcc75809 209static void discard_pending_stop_replies_in_queue (struct remote_state *);
74531fed
PA
210static int peek_stop_reply (ptid_t ptid);
211
212static void remote_async_inferior_event_handler (gdb_client_data);
74531fed 213
e3594fd1 214static void remote_terminal_ours (struct target_ops *self);
d3fd5342 215
d962ef82
DJ
216static int remote_read_description_p (struct target_ops *target);
217
176a6961 218static void remote_console_output (char *msg);
dde08ee1 219
efcc2da7 220static int remote_supports_cond_breakpoints (struct target_ops *self);
b775012e 221
78eff0ec 222static int remote_can_run_breakpoint_commands (struct target_ops *self);
d3ce09f5 223
f4abbc16
MM
224static void remote_btrace_reset (void);
225
a6b151f1
DJ
226/* For "remote". */
227
228static struct cmd_list_element *remote_cmdlist;
229
bb572ddd
DJ
230/* For "set remote" and "show remote". */
231
232static struct cmd_list_element *remote_set_cmdlist;
233static struct cmd_list_element *remote_show_cmdlist;
234
d458bd84
PA
235/* Stub vCont actions support.
236
237 Each field is a boolean flag indicating whether the stub reports
238 support for the corresponding action. */
239
240struct vCont_action_support
241{
242 /* vCont;t */
243 int t;
c1e36e3e
PA
244
245 /* vCont;r */
246 int r;
d458bd84
PA
247};
248
c1e36e3e
PA
249/* Controls whether GDB is willing to use range stepping. */
250
251static int use_range_stepping = 1;
252
0d031856
TT
253#define OPAQUETHREADBYTES 8
254
255/* a 64 bit opaque identifier */
256typedef unsigned char threadref[OPAQUETHREADBYTES];
257
258/* About this many threadisds fit in a packet. */
259
260#define MAXTHREADLISTRESULTS 32
261
ea9c271d
DJ
262/* Description of the remote protocol state for the currently
263 connected target. This is per-target state, and independent of the
264 selected architecture. */
265
266struct remote_state
267{
268 /* A buffer to use for incoming packets, and its current size. The
269 buffer is grown dynamically for larger incoming packets.
270 Outgoing packets may also be constructed in this buffer.
271 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
272 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
273 packets. */
274 char *buf;
275 long buf_size;
be2a5f71 276
1e51243a
PA
277 /* True if we're going through initial connection setup (finding out
278 about the remote side's threads, relocating symbols, etc.). */
279 int starting_up;
280
be2a5f71
DJ
281 /* If we negotiated packet size explicitly (and thus can bypass
282 heuristics for the largest packet size that will not overflow
283 a buffer in the stub), this will be set to that packet size.
284 Otherwise zero, meaning to use the guessed size. */
285 long explicit_packet_size;
2d717e4f
DJ
286
287 /* remote_wait is normally called when the target is running and
288 waits for a stop reply packet. But sometimes we need to call it
289 when the target is already stopped. We can send a "?" packet
290 and have remote_wait read the response. Or, if we already have
291 the response, we can stash it in BUF and tell remote_wait to
292 skip calling getpkt. This flag is set when BUF contains a
293 stop reply packet and the target is not waiting. */
294 int cached_wait_status;
a6f3e723
SL
295
296 /* True, if in no ack mode. That is, neither GDB nor the stub will
297 expect acks from each other. The connection is assumed to be
298 reliable. */
299 int noack_mode;
82f73884
PA
300
301 /* True if we're connected in extended remote mode. */
302 int extended;
303
e24a49d8
PA
304 /* True if we resumed the target and we're waiting for the target to
305 stop. In the mean time, we can't start another command/query.
306 The remote server wouldn't be ready to process it, so we'd
307 timeout waiting for a reply that would never come and eventually
308 we'd close the connection. This can happen in asynchronous mode
309 because we allow GDB commands while the target is running. */
310 int waiting_for_stop_reply;
74531fed 311
d458bd84
PA
312 /* The status of the stub support for the various vCont actions. */
313 struct vCont_action_support supports_vCont;
782b2b07 314
3a29589a
DJ
315 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
316 responded to that. */
317 int ctrlc_pending_p;
5d93a237
TT
318
319 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
320 remote_open knows that we don't have a file open when the program
321 starts. */
322 struct serial *remote_desc;
47f8a51d
TT
323
324 /* These are the threads which we last sent to the remote system. The
325 TID member will be -1 for all or -2 for not sent yet. */
326 ptid_t general_thread;
327 ptid_t continue_thread;
262e1174
TT
328
329 /* This is the traceframe which we last selected on the remote system.
330 It will be -1 if no traceframe is selected. */
331 int remote_traceframe_number;
747dc59d
TT
332
333 char *last_pass_packet;
5e4a05c4
TT
334
335 /* The last QProgramSignals packet sent to the target. We bypass
336 sending a new program signals list down to the target if the new
337 packet is exactly the same as the last we sent. IOW, we only let
338 the target know about program signals list changes. */
339 char *last_program_signals_packet;
b73be471
TT
340
341 enum gdb_signal last_sent_signal;
280ceea3
TT
342
343 int last_sent_step;
8e88304f
TT
344
345 char *finished_object;
346 char *finished_annex;
347 ULONGEST finished_offset;
b80fafe3
TT
348
349 /* Should we try the 'ThreadInfo' query packet?
350
351 This variable (NOT available to the user: auto-detect only!)
352 determines whether GDB will use the new, simpler "ThreadInfo"
353 query or the older, more complex syntax for thread queries.
354 This is an auto-detect variable (set to true at each connect,
355 and set to false when the target fails to recognize it). */
356 int use_threadinfo_query;
357 int use_threadextra_query;
88b496c3
TT
358
359 void (*async_client_callback) (enum inferior_event_type event_type,
360 void *context);
361 void *async_client_context;
ee154bee
TT
362
363 /* This is set to the data address of the access causing the target
364 to stop for a watchpoint. */
365 CORE_ADDR remote_watch_data_address;
366
f7e6eed5
PA
367 /* Whether the target stopped for a breakpoint/watchpoint. */
368 enum target_stop_reason stop_reason;
0d031856
TT
369
370 threadref echo_nextthread;
371 threadref nextthread;
372 threadref resultthreadlist[MAXTHREADLISTRESULTS];
5965e028
YQ
373
374 /* The state of remote notification. */
375 struct remote_notif_state *notif_state;
f4abbc16
MM
376
377 /* The branch trace configuration. */
378 struct btrace_config btrace_config;
ea9c271d
DJ
379};
380
dc146f7c
VP
381/* Private data that we'll store in (struct thread_info)->private. */
382struct private_thread_info
383{
384 char *extra;
385 int core;
386};
387
388static void
389free_private_thread_info (struct private_thread_info *info)
390{
391 xfree (info->extra);
392 xfree (info);
393}
394
ea9c271d
DJ
395/* This data could be associated with a target, but we do not always
396 have access to the current target when we need it, so for now it is
397 static. This will be fine for as long as only one target is in use
398 at a time. */
cf792862 399static struct remote_state *remote_state;
ea9c271d
DJ
400
401static struct remote_state *
0b83947e 402get_remote_state_raw (void)
ea9c271d 403{
cf792862
TT
404 return remote_state;
405}
406
407/* Allocate a new struct remote_state with xmalloc, initialize it, and
408 return it. */
409
410static struct remote_state *
411new_remote_state (void)
412{
413 struct remote_state *result = XCNEW (struct remote_state);
414
415 /* The default buffer size is unimportant; it will be expanded
416 whenever a larger buffer is needed. */
417 result->buf_size = 400;
418 result->buf = xmalloc (result->buf_size);
262e1174 419 result->remote_traceframe_number = -1;
b73be471 420 result->last_sent_signal = GDB_SIGNAL_0;
cf792862
TT
421
422 return result;
ea9c271d
DJ
423}
424
425/* Description of the remote protocol for a given architecture. */
d01949b6 426
ad10f812
AC
427struct packet_reg
428{
429 long offset; /* Offset into G packet. */
430 long regnum; /* GDB's internal register number. */
431 LONGEST pnum; /* Remote protocol register number. */
b323314b 432 int in_g_packet; /* Always part of G packet. */
f5656ead 433 /* long size in bytes; == register_size (target_gdbarch (), regnum);
23860348 434 at present. */
f5656ead 435 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
c9f4d572 436 at present. */
ad10f812
AC
437};
438
ea9c271d 439struct remote_arch_state
d01949b6 440{
ad10f812
AC
441 /* Description of the remote protocol registers. */
442 long sizeof_g_packet;
b323314b
AC
443
444 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 445 (making an array gdbarch_num_regs in size). */
b323314b 446 struct packet_reg *regs;
ad10f812 447
d01949b6
AC
448 /* This is the size (in chars) of the first response to the ``g''
449 packet. It is used as a heuristic when determining the maximum
450 size of memory-read and memory-write packets. A target will
451 typically only reserve a buffer large enough to hold the ``g''
452 packet. The size does not include packet overhead (headers and
23860348 453 trailers). */
d01949b6
AC
454 long actual_register_packet_size;
455
456 /* This is the maximum size (in chars) of a non read/write packet.
23860348 457 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
458 long remote_packet_size;
459};
460
35b1e5cc
SS
461/* Utility: generate error from an incoming stub packet. */
462static void
463trace_error (char *buf)
464{
465 if (*buf++ != 'E')
466 return; /* not an error msg */
467 switch (*buf)
468 {
469 case '1': /* malformed packet error */
470 if (*++buf == '0') /* general case: */
471 error (_("remote.c: error in outgoing packet."));
472 else
473 error (_("remote.c: error in outgoing packet at field #%ld."),
474 strtol (buf, NULL, 16));
35b1e5cc
SS
475 default:
476 error (_("Target returns error code '%s'."), buf);
477 }
478}
479
480/* Utility: wait for reply from stub, while accepting "O" packets. */
481static char *
482remote_get_noisy_reply (char **buf_p,
483 long *sizeof_buf)
484{
485 do /* Loop on reply from remote stub. */
486 {
487 char *buf;
a744cf53 488
0df8b418 489 QUIT; /* Allow user to bail out with ^C. */
35b1e5cc
SS
490 getpkt (buf_p, sizeof_buf, 0);
491 buf = *buf_p;
ad91cd99 492 if (buf[0] == 'E')
35b1e5cc 493 trace_error (buf);
61012eef 494 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
495 {
496 ULONGEST ul;
497 CORE_ADDR from, to, org_to;
498 char *p, *pp;
499 int adjusted_size = 0;
7556d4a4 500 int relocated = 0;
dde08ee1
PA
501
502 p = buf + strlen ("qRelocInsn:");
503 pp = unpack_varlen_hex (p, &ul);
504 if (*pp != ';')
cb91c06a 505 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
506 from = ul;
507
508 p = pp + 1;
a9cbf802 509 unpack_varlen_hex (p, &ul);
dde08ee1
PA
510 to = ul;
511
512 org_to = to;
513
492d29ea 514 TRY
dde08ee1 515 {
f5656ead 516 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 517 relocated = 1;
dde08ee1 518 }
492d29ea 519 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
520 {
521 if (ex.error == MEMORY_ERROR)
522 {
523 /* Propagate memory errors silently back to the
524 target. The stub may have limited the range of
525 addresses we can write to, for example. */
526 }
527 else
528 {
529 /* Something unexpectedly bad happened. Be verbose
530 so we can tell what, and propagate the error back
531 to the stub, so it doesn't get stuck waiting for
532 a response. */
533 exception_fprintf (gdb_stderr, ex,
534 _("warning: relocating instruction: "));
535 }
536 putpkt ("E01");
537 }
492d29ea 538 END_CATCH
7556d4a4
PA
539
540 if (relocated)
dde08ee1
PA
541 {
542 adjusted_size = to - org_to;
543
bba74b36 544 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
545 putpkt (buf);
546 }
dde08ee1 547 }
ad91cd99 548 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
549 remote_console_output (buf + 1); /* 'O' message from stub */
550 else
0df8b418 551 return buf; /* Here's the actual reply. */
35b1e5cc
SS
552 }
553 while (1);
554}
3c3bea1c 555
d01949b6
AC
556/* Handle for retreving the remote protocol data from gdbarch. */
557static struct gdbarch_data *remote_gdbarch_data_handle;
558
ea9c271d
DJ
559static struct remote_arch_state *
560get_remote_arch_state (void)
d01949b6 561{
f5656ead 562 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
d01949b6
AC
563}
564
0b83947e
DJ
565/* Fetch the global remote target state. */
566
567static struct remote_state *
568get_remote_state (void)
569{
570 /* Make sure that the remote architecture state has been
571 initialized, because doing so might reallocate rs->buf. Any
572 function which calls getpkt also needs to be mindful of changes
573 to rs->buf, but this call limits the number of places which run
574 into trouble. */
575 get_remote_arch_state ();
576
577 return get_remote_state_raw ();
578}
579
74ca34ce
DJ
580static int
581compare_pnums (const void *lhs_, const void *rhs_)
582{
583 const struct packet_reg * const *lhs = lhs_;
584 const struct packet_reg * const *rhs = rhs_;
585
586 if ((*lhs)->pnum < (*rhs)->pnum)
587 return -1;
588 else if ((*lhs)->pnum == (*rhs)->pnum)
589 return 0;
590 else
591 return 1;
592}
593
c21236dc
PA
594static int
595map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 596{
74ca34ce 597 int regnum, num_remote_regs, offset;
74ca34ce 598 struct packet_reg **remote_regs;
ea9c271d 599
4a22f64d 600 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 601 {
c21236dc 602 struct packet_reg *r = &regs[regnum];
baef701f 603
4a22f64d 604 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
605 /* Do not try to fetch zero-sized (placeholder) registers. */
606 r->pnum = -1;
607 else
608 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
609
b323314b 610 r->regnum = regnum;
74ca34ce
DJ
611 }
612
613 /* Define the g/G packet format as the contents of each register
614 with a remote protocol number, in order of ascending protocol
615 number. */
616
4a22f64d 617 remote_regs = alloca (gdbarch_num_regs (gdbarch)
c21236dc 618 * sizeof (struct packet_reg *));
f57d151a 619 for (num_remote_regs = 0, regnum = 0;
4a22f64d 620 regnum < gdbarch_num_regs (gdbarch);
f57d151a 621 regnum++)
c21236dc
PA
622 if (regs[regnum].pnum != -1)
623 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 624
74ca34ce
DJ
625 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
626 compare_pnums);
627
628 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
629 {
630 remote_regs[regnum]->in_g_packet = 1;
631 remote_regs[regnum]->offset = offset;
4a22f64d 632 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
633 }
634
c21236dc
PA
635 return offset;
636}
637
638/* Given the architecture described by GDBARCH, return the remote
639 protocol register's number and the register's offset in the g/G
640 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
641 If the target does not have a mapping for REGNUM, return false,
642 otherwise, return true. */
643
644int
645remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
646 int *pnum, int *poffset)
647{
648 int sizeof_g_packet;
649 struct packet_reg *regs;
650 struct cleanup *old_chain;
651
652 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
653
654 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
655 old_chain = make_cleanup (xfree, regs);
656
657 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
658
659 *pnum = regs[regnum].pnum;
660 *poffset = regs[regnum].offset;
661
662 do_cleanups (old_chain);
663
664 return *pnum != -1;
665}
666
667static void *
668init_remote_state (struct gdbarch *gdbarch)
669{
670 struct remote_state *rs = get_remote_state_raw ();
671 struct remote_arch_state *rsa;
672
673 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
674
675 /* Use the architecture to build a regnum<->pnum table, which will be
676 1:1 unless a feature set specifies otherwise. */
677 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
678 gdbarch_num_regs (gdbarch),
679 struct packet_reg);
680
74ca34ce
DJ
681 /* Record the maximum possible size of the g packet - it may turn out
682 to be smaller. */
c21236dc 683 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 684
0df8b418 685 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
686 remote stubs have a hardwired buffer size of 400 bytes
687 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
688 as the maximum packet-size to ensure that the packet and an extra
689 NUL character can always fit in the buffer. This stops GDB
690 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
691 already a full buffer (As of 1999-12-04 that was most stubs). */
692 rsa->remote_packet_size = 400 - 1;
d01949b6 693
ea9c271d
DJ
694 /* This one is filled in when a ``g'' packet is received. */
695 rsa->actual_register_packet_size = 0;
696
697 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
698 default, adjust the size accordingly. Remember that each byte is
699 encoded as two characters. 32 is the overhead for the packet
700 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 701 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 702 little. */
ea9c271d
DJ
703 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
704 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 705
ea9c271d
DJ
706 /* Make sure that the packet buffer is plenty big enough for
707 this architecture. */
708 if (rs->buf_size < rsa->remote_packet_size)
709 {
710 rs->buf_size = 2 * rsa->remote_packet_size;
7fca722e 711 rs->buf = xrealloc (rs->buf, rs->buf_size);
ea9c271d 712 }
6d820c5c 713
ea9c271d
DJ
714 return rsa;
715}
716
717/* Return the current allowed size of a remote packet. This is
718 inferred from the current architecture, and should be used to
719 limit the length of outgoing packets. */
720static long
721get_remote_packet_size (void)
722{
be2a5f71 723 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
724 struct remote_arch_state *rsa = get_remote_arch_state ();
725
be2a5f71
DJ
726 if (rs->explicit_packet_size)
727 return rs->explicit_packet_size;
728
ea9c271d 729 return rsa->remote_packet_size;
d01949b6
AC
730}
731
ad10f812 732static struct packet_reg *
ea9c271d 733packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 734{
f5656ead 735 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
b323314b
AC
736 return NULL;
737 else
ad10f812 738 {
ea9c271d 739 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 740
b323314b
AC
741 gdb_assert (r->regnum == regnum);
742 return r;
ad10f812 743 }
ad10f812
AC
744}
745
746static struct packet_reg *
ea9c271d 747packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 748{
b323314b 749 int i;
a744cf53 750
f5656ead 751 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
ad10f812 752 {
ea9c271d 753 struct packet_reg *r = &rsa->regs[i];
a744cf53 754
b323314b
AC
755 if (r->pnum == pnum)
756 return r;
ad10f812
AC
757 }
758 return NULL;
d01949b6
AC
759}
760
c906108c
SS
761static struct target_ops remote_ops;
762
763static struct target_ops extended_remote_ops;
764
6426a772
JM
765/* FIXME: cagney/1999-09-23: Even though getpkt was called with
766 ``forever'' still use the normal timeout mechanism. This is
767 currently used by the ASYNC code to guarentee that target reads
768 during the initial connect always time-out. Once getpkt has been
769 modified to return a timeout indication and, in turn
770 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 771 this can go away. */
6426a772
JM
772static int wait_forever_enabled_p = 1;
773
9a7071a8
JB
774/* Allow the user to specify what sequence to send to the remote
775 when he requests a program interruption: Although ^C is usually
776 what remote systems expect (this is the default, here), it is
777 sometimes preferable to send a break. On other systems such
778 as the Linux kernel, a break followed by g, which is Magic SysRq g
779 is required in order to interrupt the execution. */
780const char interrupt_sequence_control_c[] = "Ctrl-C";
781const char interrupt_sequence_break[] = "BREAK";
782const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 783static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
784 {
785 interrupt_sequence_control_c,
786 interrupt_sequence_break,
787 interrupt_sequence_break_g,
788 NULL
789 };
790static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
791
792static void
793show_interrupt_sequence (struct ui_file *file, int from_tty,
794 struct cmd_list_element *c,
795 const char *value)
796{
797 if (interrupt_sequence_mode == interrupt_sequence_control_c)
798 fprintf_filtered (file,
799 _("Send the ASCII ETX character (Ctrl-c) "
800 "to the remote target to interrupt the "
801 "execution of the program.\n"));
802 else if (interrupt_sequence_mode == interrupt_sequence_break)
803 fprintf_filtered (file,
804 _("send a break signal to the remote target "
805 "to interrupt the execution of the program.\n"));
806 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
807 fprintf_filtered (file,
808 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
809 "the remote target to interrupt the execution "
810 "of Linux kernel.\n"));
811 else
812 internal_error (__FILE__, __LINE__,
813 _("Invalid value for interrupt_sequence_mode: %s."),
814 interrupt_sequence_mode);
815}
6426a772 816
9a7071a8
JB
817/* This boolean variable specifies whether interrupt_sequence is sent
818 to the remote target when gdb connects to it.
819 This is mostly needed when you debug the Linux kernel: The Linux kernel
820 expects BREAK g which is Magic SysRq g for connecting gdb. */
821static int interrupt_on_connect = 0;
c906108c 822
9a7071a8
JB
823/* This variable is used to implement the "set/show remotebreak" commands.
824 Since these commands are now deprecated in favor of "set/show remote
825 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
826static int remote_break;
827
9a7071a8
JB
828static void
829set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
830{
831 if (remote_break)
832 interrupt_sequence_mode = interrupt_sequence_break;
833 else
834 interrupt_sequence_mode = interrupt_sequence_control_c;
835}
836
837static void
838show_remotebreak (struct ui_file *file, int from_tty,
839 struct cmd_list_element *c,
840 const char *value)
841{
842}
843
c906108c
SS
844/* This variable sets the number of bits in an address that are to be
845 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 846 leading zeros, the entire address would be sent. This variable
c906108c
SS
847 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
848 initial implementation of remote.c restricted the address sent in
849 memory packets to ``host::sizeof long'' bytes - (typically 32
850 bits). Consequently, for 64 bit targets, the upper 32 bits of an
851 address was never sent. Since fixing this bug may cause a break in
852 some remote targets this variable is principly provided to
23860348 853 facilitate backward compatibility. */
c906108c 854
883b9c6c 855static unsigned int remote_address_size;
c906108c 856
75c99385
PA
857/* Temporary to track who currently owns the terminal. See
858 remote_terminal_* for more details. */
6426a772
JM
859
860static int remote_async_terminal_ours_p;
861
2d717e4f
DJ
862/* The executable file to use for "run" on the remote side. */
863
864static char *remote_exec_file = "";
865
11cf8741 866\f
11cf8741 867/* User configurable variables for the number of characters in a
ea9c271d
DJ
868 memory read/write packet. MIN (rsa->remote_packet_size,
869 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 870 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
871 (speed up transfers). The variables ``preferred_*'' (the user
872 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 873 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
874
875struct memory_packet_config
876{
877 char *name;
878 long size;
879 int fixed_p;
880};
881
882/* Compute the current size of a read/write packet. Since this makes
883 use of ``actual_register_packet_size'' the computation is dynamic. */
884
885static long
886get_memory_packet_size (struct memory_packet_config *config)
887{
d01949b6 888 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
889 struct remote_arch_state *rsa = get_remote_arch_state ();
890
11cf8741
JM
891 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
892 law?) that some hosts don't cope very well with large alloca()
893 calls. Eventually the alloca() code will be replaced by calls to
894 xmalloc() and make_cleanups() allowing this restriction to either
23860348 895 be lifted or removed. */
11cf8741
JM
896#ifndef MAX_REMOTE_PACKET_SIZE
897#define MAX_REMOTE_PACKET_SIZE 16384
898#endif
3de11b2e 899 /* NOTE: 20 ensures we can write at least one byte. */
11cf8741 900#ifndef MIN_REMOTE_PACKET_SIZE
3de11b2e 901#define MIN_REMOTE_PACKET_SIZE 20
11cf8741
JM
902#endif
903 long what_they_get;
904 if (config->fixed_p)
905 {
906 if (config->size <= 0)
907 what_they_get = MAX_REMOTE_PACKET_SIZE;
908 else
909 what_they_get = config->size;
910 }
911 else
912 {
ea9c271d 913 what_they_get = get_remote_packet_size ();
23860348 914 /* Limit the packet to the size specified by the user. */
11cf8741
JM
915 if (config->size > 0
916 && what_they_get > config->size)
917 what_they_get = config->size;
be2a5f71
DJ
918
919 /* Limit it to the size of the targets ``g'' response unless we have
920 permission from the stub to use a larger packet size. */
921 if (rs->explicit_packet_size == 0
922 && rsa->actual_register_packet_size > 0
923 && what_they_get > rsa->actual_register_packet_size)
924 what_they_get = rsa->actual_register_packet_size;
11cf8741
JM
925 }
926 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
927 what_they_get = MAX_REMOTE_PACKET_SIZE;
928 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
929 what_they_get = MIN_REMOTE_PACKET_SIZE;
6d820c5c
DJ
930
931 /* Make sure there is room in the global buffer for this packet
932 (including its trailing NUL byte). */
933 if (rs->buf_size < what_they_get + 1)
934 {
935 rs->buf_size = 2 * what_they_get;
936 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
937 }
938
11cf8741
JM
939 return what_they_get;
940}
941
0df8b418 942/* Update the size of a read/write packet. If they user wants
23860348 943 something really big then do a sanity check. */
11cf8741
JM
944
945static void
946set_memory_packet_size (char *args, struct memory_packet_config *config)
947{
948 int fixed_p = config->fixed_p;
949 long size = config->size;
a744cf53 950
11cf8741 951 if (args == NULL)
8a3fe4f8 952 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
953 else if (strcmp (args, "hard") == 0
954 || strcmp (args, "fixed") == 0)
955 fixed_p = 1;
956 else if (strcmp (args, "soft") == 0
957 || strcmp (args, "limit") == 0)
958 fixed_p = 0;
959 else
960 {
961 char *end;
a744cf53 962
11cf8741
JM
963 size = strtoul (args, &end, 0);
964 if (args == end)
8a3fe4f8 965 error (_("Invalid %s (bad syntax)."), config->name);
11cf8741
JM
966#if 0
967 /* Instead of explicitly capping the size of a packet to
968 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
969 instead allowed to set the size to something arbitrarily
23860348 970 large. */
11cf8741 971 if (size > MAX_REMOTE_PACKET_SIZE)
8a3fe4f8 972 error (_("Invalid %s (too large)."), config->name);
11cf8741
JM
973#endif
974 }
23860348 975 /* Extra checks? */
11cf8741
JM
976 if (fixed_p && !config->fixed_p)
977 {
e2e0b3e5
AC
978 if (! query (_("The target may not be able to correctly handle a %s\n"
979 "of %ld bytes. Change the packet size? "),
11cf8741 980 config->name, size))
8a3fe4f8 981 error (_("Packet size not changed."));
11cf8741 982 }
23860348 983 /* Update the config. */
11cf8741
JM
984 config->fixed_p = fixed_p;
985 config->size = size;
986}
987
988static void
989show_memory_packet_size (struct memory_packet_config *config)
990{
a3f17187 991 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 992 if (config->fixed_p)
a3f17187 993 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
994 get_memory_packet_size (config));
995 else
a3f17187 996 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
997 get_memory_packet_size (config));
998}
999
1000static struct memory_packet_config memory_write_packet_config =
1001{
1002 "memory-write-packet-size",
1003};
1004
1005static void
1006set_memory_write_packet_size (char *args, int from_tty)
1007{
1008 set_memory_packet_size (args, &memory_write_packet_config);
1009}
1010
1011static void
1012show_memory_write_packet_size (char *args, int from_tty)
1013{
1014 show_memory_packet_size (&memory_write_packet_config);
1015}
1016
1017static long
1018get_memory_write_packet_size (void)
1019{
1020 return get_memory_packet_size (&memory_write_packet_config);
1021}
1022
1023static struct memory_packet_config memory_read_packet_config =
1024{
1025 "memory-read-packet-size",
1026};
1027
1028static void
1029set_memory_read_packet_size (char *args, int from_tty)
1030{
1031 set_memory_packet_size (args, &memory_read_packet_config);
1032}
1033
1034static void
1035show_memory_read_packet_size (char *args, int from_tty)
1036{
1037 show_memory_packet_size (&memory_read_packet_config);
1038}
1039
1040static long
1041get_memory_read_packet_size (void)
1042{
1043 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1044
11cf8741
JM
1045 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1046 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1047 increased beyond this. */
1048 if (size > get_remote_packet_size ())
1049 size = get_remote_packet_size ();
11cf8741
JM
1050 return size;
1051}
1052
11cf8741 1053\f
5a2468f5 1054/* Generic configuration support for packets the stub optionally
0df8b418 1055 supports. Allows the user to specify the use of the packet as well
23860348 1056 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1057
1058enum packet_support
1059 {
1060 PACKET_SUPPORT_UNKNOWN = 0,
1061 PACKET_ENABLE,
1062 PACKET_DISABLE
1063 };
1064
5a2468f5
JM
1065struct packet_config
1066 {
bb572ddd
DJ
1067 const char *name;
1068 const char *title;
4082afcc
PA
1069
1070 /* If auto, GDB auto-detects support for this packet or feature,
1071 either through qSupported, or by trying the packet and looking
1072 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1073 packet. If false, the packet is disabled. Configs that don't
1074 have an associated command always have this set to auto. */
7f19b9a2 1075 enum auto_boolean detect;
4082afcc
PA
1076
1077 /* Does the target support this packet? */
5a2468f5
JM
1078 enum packet_support support;
1079 };
1080
d471ea57 1081/* Analyze a packet's return value and update the packet config
23860348 1082 accordingly. */
d471ea57
AC
1083
1084enum packet_result
1085{
1086 PACKET_ERROR,
1087 PACKET_OK,
1088 PACKET_UNKNOWN
1089};
1090
4082afcc
PA
1091static enum packet_support packet_config_support (struct packet_config *config);
1092static enum packet_support packet_support (int packet);
5a2468f5
JM
1093
1094static void
fba45db2 1095show_packet_config_cmd (struct packet_config *config)
5a2468f5
JM
1096{
1097 char *support = "internal-error";
a744cf53 1098
4082afcc 1099 switch (packet_config_support (config))
5a2468f5
JM
1100 {
1101 case PACKET_ENABLE:
1102 support = "enabled";
1103 break;
1104 case PACKET_DISABLE:
1105 support = "disabled";
1106 break;
1107 case PACKET_SUPPORT_UNKNOWN:
1108 support = "unknown";
1109 break;
1110 }
1111 switch (config->detect)
1112 {
7f19b9a2 1113 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1114 printf_filtered (_("Support for the `%s' packet "
1115 "is auto-detected, currently %s.\n"),
37a105a1 1116 config->name, support);
5a2468f5 1117 break;
7f19b9a2
AC
1118 case AUTO_BOOLEAN_TRUE:
1119 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1120 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1121 config->name, support);
8e248173 1122 break;
5a2468f5
JM
1123 }
1124}
1125
1126static void
bb572ddd
DJ
1127add_packet_config_cmd (struct packet_config *config, const char *name,
1128 const char *title, int legacy)
d471ea57 1129{
5a2468f5
JM
1130 char *set_doc;
1131 char *show_doc;
d471ea57 1132 char *cmd_name;
3ed07be4 1133
5a2468f5
JM
1134 config->name = name;
1135 config->title = title;
b435e160
AC
1136 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1137 name, title);
3e43a32a
MS
1138 show_doc = xstrprintf ("Show current use of remote "
1139 "protocol `%s' (%s) packet",
b435e160 1140 name, title);
d471ea57 1141 /* set/show TITLE-packet {auto,on,off} */
b435e160 1142 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1143 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1144 &config->detect, set_doc,
1145 show_doc, NULL, /* help_doc */
4082afcc 1146 NULL,
bb572ddd
DJ
1147 show_remote_protocol_packet_cmd,
1148 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1149 /* The command code copies the documentation strings. */
1150 xfree (set_doc);
1151 xfree (show_doc);
23860348 1152 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1153 if (legacy)
1154 {
1155 char *legacy_name;
a744cf53 1156
b435e160 1157 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1158 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1159 &remote_set_cmdlist);
d471ea57 1160 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1161 &remote_show_cmdlist);
d471ea57 1162 }
5a2468f5
JM
1163}
1164
d471ea57 1165static enum packet_result
a76d924d 1166packet_check_result (const char *buf)
5a2468f5 1167{
d471ea57 1168 if (buf[0] != '\0')
5a2468f5 1169 {
d471ea57 1170 /* The stub recognized the packet request. Check that the
23860348 1171 operation succeeded. */
a76d924d
DJ
1172 if (buf[0] == 'E'
1173 && isxdigit (buf[1]) && isxdigit (buf[2])
1174 && buf[3] == '\0')
1175 /* "Enn" - definitly an error. */
1176 return PACKET_ERROR;
1177
1178 /* Always treat "E." as an error. This will be used for
1179 more verbose error messages, such as E.memtypes. */
1180 if (buf[0] == 'E' && buf[1] == '.')
1181 return PACKET_ERROR;
1182
1183 /* The packet may or may not be OK. Just assume it is. */
1184 return PACKET_OK;
1185 }
1186 else
1187 /* The stub does not support the packet. */
1188 return PACKET_UNKNOWN;
1189}
1190
1191static enum packet_result
1192packet_ok (const char *buf, struct packet_config *config)
1193{
1194 enum packet_result result;
1195
4082afcc
PA
1196 if (config->detect != AUTO_BOOLEAN_TRUE
1197 && config->support == PACKET_DISABLE)
1198 internal_error (__FILE__, __LINE__,
1199 _("packet_ok: attempt to use a disabled packet"));
1200
a76d924d
DJ
1201 result = packet_check_result (buf);
1202 switch (result)
1203 {
1204 case PACKET_OK:
1205 case PACKET_ERROR:
1206 /* The stub recognized the packet request. */
4082afcc 1207 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1208 {
d471ea57
AC
1209 if (remote_debug)
1210 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1211 "Packet %s (%s) is supported\n",
1212 config->name, config->title);
d471ea57 1213 config->support = PACKET_ENABLE;
d471ea57 1214 }
a76d924d
DJ
1215 break;
1216 case PACKET_UNKNOWN:
23860348 1217 /* The stub does not support the packet. */
4082afcc
PA
1218 if (config->detect == AUTO_BOOLEAN_AUTO
1219 && config->support == PACKET_ENABLE)
d471ea57 1220 {
4082afcc
PA
1221 /* If the stub previously indicated that the packet was
1222 supported then there is a protocol error. */
1223 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1224 config->name, config->title);
1225 }
1226 else if (config->detect == AUTO_BOOLEAN_TRUE)
1227 {
1228 /* The user set it wrong. */
1229 error (_("Enabled packet %s (%s) not recognized by stub"),
1230 config->name, config->title);
d471ea57 1231 }
4082afcc
PA
1232
1233 if (remote_debug)
1234 fprintf_unfiltered (gdb_stdlog,
1235 "Packet %s (%s) is NOT supported\n",
1236 config->name, config->title);
1237 config->support = PACKET_DISABLE;
a76d924d 1238 break;
5a2468f5 1239 }
a76d924d
DJ
1240
1241 return result;
5a2468f5
JM
1242}
1243
444abaca
DJ
1244enum {
1245 PACKET_vCont = 0,
1246 PACKET_X,
1247 PACKET_qSymbol,
1248 PACKET_P,
1249 PACKET_p,
1250 PACKET_Z0,
1251 PACKET_Z1,
1252 PACKET_Z2,
1253 PACKET_Z3,
1254 PACKET_Z4,
a6b151f1
DJ
1255 PACKET_vFile_open,
1256 PACKET_vFile_pread,
1257 PACKET_vFile_pwrite,
1258 PACKET_vFile_close,
1259 PACKET_vFile_unlink,
b9e7b9c3 1260 PACKET_vFile_readlink,
0a93529c 1261 PACKET_vFile_fstat,
0876f84a 1262 PACKET_qXfer_auxv,
23181151 1263 PACKET_qXfer_features,
cfa9d6d9 1264 PACKET_qXfer_libraries,
2268b414 1265 PACKET_qXfer_libraries_svr4,
fd79ecee 1266 PACKET_qXfer_memory_map,
0e7f50da
UW
1267 PACKET_qXfer_spu_read,
1268 PACKET_qXfer_spu_write,
07e059b5 1269 PACKET_qXfer_osdata,
dc146f7c 1270 PACKET_qXfer_threads,
0fb4aa4b 1271 PACKET_qXfer_statictrace_read,
b3b9301e 1272 PACKET_qXfer_traceframe_info,
169081d0 1273 PACKET_qXfer_uib,
711e434b 1274 PACKET_qGetTIBAddr,
444abaca 1275 PACKET_qGetTLSAddr,
be2a5f71 1276 PACKET_qSupported,
bd3eecc3 1277 PACKET_qTStatus,
89be2091 1278 PACKET_QPassSignals,
9b224c5e 1279 PACKET_QProgramSignals,
936d2992 1280 PACKET_qCRC,
08388c79 1281 PACKET_qSearch_memory,
2d717e4f
DJ
1282 PACKET_vAttach,
1283 PACKET_vRun,
a6f3e723 1284 PACKET_QStartNoAckMode,
82f73884 1285 PACKET_vKill,
4aa995e1
PA
1286 PACKET_qXfer_siginfo_read,
1287 PACKET_qXfer_siginfo_write,
0b16c5cf 1288 PACKET_qAttached,
4082afcc
PA
1289
1290 /* Support for conditional tracepoints. */
782b2b07 1291 PACKET_ConditionalTracepoints,
4082afcc
PA
1292
1293 /* Support for target-side breakpoint conditions. */
3788aec7 1294 PACKET_ConditionalBreakpoints,
4082afcc
PA
1295
1296 /* Support for target-side breakpoint commands. */
d3ce09f5 1297 PACKET_BreakpointCommands,
4082afcc
PA
1298
1299 /* Support for fast tracepoints. */
7a697b8d 1300 PACKET_FastTracepoints,
4082afcc
PA
1301
1302 /* Support for static tracepoints. */
0fb4aa4b 1303 PACKET_StaticTracepoints,
4082afcc
PA
1304
1305 /* Support for installing tracepoints while a trace experiment is
1306 running. */
1e4d1764 1307 PACKET_InstallInTrace,
4082afcc 1308
40ab02ce
MS
1309 PACKET_bc,
1310 PACKET_bs,
409873ef 1311 PACKET_TracepointSource,
d914c394 1312 PACKET_QAllow,
78d85199 1313 PACKET_qXfer_fdpic,
03583c20 1314 PACKET_QDisableRandomization,
d1feda86 1315 PACKET_QAgent,
f6f899bf 1316 PACKET_QTBuffer_size,
9accd112
MM
1317 PACKET_Qbtrace_off,
1318 PACKET_Qbtrace_bts,
1319 PACKET_qXfer_btrace,
4082afcc
PA
1320
1321 /* Support for the QNonStop packet. */
1322 PACKET_QNonStop,
1323
1324 /* Support for multi-process extensions. */
1325 PACKET_multiprocess_feature,
1326
1327 /* Support for enabling and disabling tracepoints while a trace
1328 experiment is running. */
1329 PACKET_EnableDisableTracepoints_feature,
1330
1331 /* Support for collecting strings using the tracenz bytecode. */
1332 PACKET_tracenz_feature,
1333
1334 /* Support for continuing to run a trace experiment while GDB is
1335 disconnected. */
1336 PACKET_DisconnectedTracing_feature,
1337
1338 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1339 PACKET_augmented_libraries_svr4_read_feature,
1340
f4abbc16
MM
1341 /* Support for the qXfer:btrace-conf:read packet. */
1342 PACKET_qXfer_btrace_conf,
1343
d33501a5
MM
1344 /* Support for the Qbtrace-conf:bts:size packet. */
1345 PACKET_Qbtrace_conf_bts_size,
1346
f7e6eed5
PA
1347 /* Support for swbreak+ feature. */
1348 PACKET_swbreak_feature,
1349
1350 /* Support for hwbreak+ feature. */
1351 PACKET_hwbreak_feature,
1352
444abaca
DJ
1353 PACKET_MAX
1354};
506fb367 1355
444abaca 1356static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1357
f7e6eed5
PA
1358/* Returns the packet's corresponding "set remote foo-packet" command
1359 state. See struct packet_config for more details. */
1360
1361static enum auto_boolean
1362packet_set_cmd_state (int packet)
1363{
1364 return remote_protocol_packets[packet].detect;
1365}
1366
4082afcc
PA
1367/* Returns whether a given packet or feature is supported. This takes
1368 into account the state of the corresponding "set remote foo-packet"
1369 command, which may be used to bypass auto-detection. */
dc8acb97 1370
4082afcc
PA
1371static enum packet_support
1372packet_config_support (struct packet_config *config)
1373{
1374 switch (config->detect)
444abaca 1375 {
4082afcc
PA
1376 case AUTO_BOOLEAN_TRUE:
1377 return PACKET_ENABLE;
1378 case AUTO_BOOLEAN_FALSE:
1379 return PACKET_DISABLE;
1380 case AUTO_BOOLEAN_AUTO:
1381 return config->support;
1382 default:
1383 gdb_assert_not_reached (_("bad switch"));
444abaca 1384 }
4082afcc
PA
1385}
1386
1387/* Same as packet_config_support, but takes the packet's enum value as
1388 argument. */
1389
1390static enum packet_support
1391packet_support (int packet)
1392{
1393 struct packet_config *config = &remote_protocol_packets[packet];
1394
1395 return packet_config_support (config);
dc8acb97
MS
1396}
1397
5a2468f5 1398static void
444abaca
DJ
1399show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1400 struct cmd_list_element *c,
1401 const char *value)
5a2468f5 1402{
444abaca 1403 struct packet_config *packet;
5a2468f5 1404
444abaca
DJ
1405 for (packet = remote_protocol_packets;
1406 packet < &remote_protocol_packets[PACKET_MAX];
1407 packet++)
1408 {
1409 if (&packet->detect == c->var)
1410 {
1411 show_packet_config_cmd (packet);
1412 return;
1413 }
1414 }
9b20d036 1415 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1416 c->name);
5a2468f5
JM
1417}
1418
d471ea57
AC
1419/* Should we try one of the 'Z' requests? */
1420
1421enum Z_packet_type
1422{
1423 Z_PACKET_SOFTWARE_BP,
1424 Z_PACKET_HARDWARE_BP,
1425 Z_PACKET_WRITE_WP,
1426 Z_PACKET_READ_WP,
1427 Z_PACKET_ACCESS_WP,
1428 NR_Z_PACKET_TYPES
1429};
96baa820 1430
d471ea57 1431/* For compatibility with older distributions. Provide a ``set remote
23860348 1432 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1433
7f19b9a2 1434static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1435
1436static void
fba45db2
KB
1437set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1438 struct cmd_list_element *c)
96baa820 1439{
d471ea57 1440 int i;
a744cf53 1441
d471ea57 1442 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1443 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1444}
1445
1446static void
08546159
AC
1447show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1448 struct cmd_list_element *c,
1449 const char *value)
96baa820 1450{
d471ea57 1451 int i;
a744cf53 1452
d471ea57
AC
1453 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1454 {
444abaca 1455 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1456 }
96baa820
JM
1457}
1458
4082afcc
PA
1459/* Returns true if the multi-process extensions are in effect. */
1460
1461static int
1462remote_multi_process_p (struct remote_state *rs)
1463{
1464 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1465}
1466
23860348 1467/* Tokens for use by the asynchronous signal handlers for SIGINT. */
934b9bac
JK
1468static struct async_signal_handler *async_sigint_remote_twice_token;
1469static struct async_signal_handler *async_sigint_remote_token;
43ff13b4 1470
74531fed
PA
1471\f
1472/* Asynchronous signal handle registered as event loop source for
1473 when we have pending events ready to be passed to the core. */
1474
1475static struct async_event_handler *remote_async_inferior_event_token;
1476
c906108c
SS
1477\f
1478
79d7f229
PA
1479static ptid_t magic_null_ptid;
1480static ptid_t not_sent_ptid;
1481static ptid_t any_thread_ptid;
1482
0b16c5cf
PA
1483/* Find out if the stub attached to PID (and hence GDB should offer to
1484 detach instead of killing it when bailing out). */
1485
1486static int
1487remote_query_attached (int pid)
1488{
1489 struct remote_state *rs = get_remote_state ();
bba74b36 1490 size_t size = get_remote_packet_size ();
0b16c5cf 1491
4082afcc 1492 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1493 return 0;
1494
1495 if (remote_multi_process_p (rs))
bba74b36 1496 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1497 else
bba74b36 1498 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1499
1500 putpkt (rs->buf);
1501 getpkt (&rs->buf, &rs->buf_size, 0);
1502
1503 switch (packet_ok (rs->buf,
1554e9be 1504 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1505 {
1506 case PACKET_OK:
1507 if (strcmp (rs->buf, "1") == 0)
1508 return 1;
1509 break;
1510 case PACKET_ERROR:
1511 warning (_("Remote failure reply: %s"), rs->buf);
1512 break;
1513 case PACKET_UNKNOWN:
1514 break;
1515 }
1516
1517 return 0;
1518}
1519
49c62f2e
PA
1520/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1521 has been invented by GDB, instead of reported by the target. Since
1522 we can be connected to a remote system before before knowing about
1523 any inferior, mark the target with execution when we find the first
1524 inferior. If ATTACHED is 1, then we had just attached to this
1525 inferior. If it is 0, then we just created this inferior. If it
1526 is -1, then try querying the remote stub to find out if it had
1527 attached to the inferior or not. */
1941c569
PA
1528
1529static struct inferior *
49c62f2e 1530remote_add_inferior (int fake_pid_p, int pid, int attached)
1941c569 1531{
1941c569
PA
1532 struct inferior *inf;
1533
0b16c5cf
PA
1534 /* Check whether this process we're learning about is to be
1535 considered attached, or if is to be considered to have been
1536 spawned by the stub. */
1537 if (attached == -1)
1538 attached = remote_query_attached (pid);
1539
f5656ead 1540 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1541 {
1542 /* If the target shares code across all inferiors, then every
1543 attach adds a new inferior. */
1544 inf = add_inferior (pid);
1545
1546 /* ... and every inferior is bound to the same program space.
1547 However, each inferior may still have its own address
1548 space. */
1549 inf->aspace = maybe_new_address_space ();
1550 inf->pspace = current_program_space;
1551 }
1552 else
1553 {
1554 /* In the traditional debugging scenario, there's a 1-1 match
1555 between program/address spaces. We simply bind the inferior
1556 to the program space's address space. */
1557 inf = current_inferior ();
1558 inferior_appeared (inf, pid);
1559 }
1941c569 1560
0b16c5cf 1561 inf->attach_flag = attached;
49c62f2e 1562 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1563
1941c569
PA
1564 return inf;
1565}
1566
1567/* Add thread PTID to GDB's thread list. Tag it as executing/running
1568 according to RUNNING. */
1569
c906108c 1570static void
1941c569 1571remote_add_thread (ptid_t ptid, int running)
c906108c 1572{
b7ea362b
PA
1573 struct remote_state *rs = get_remote_state ();
1574
1575 /* GDB historically didn't pull threads in the initial connection
1576 setup. If the remote target doesn't even have a concept of
1577 threads (e.g., a bare-metal target), even if internally we
1578 consider that a single-threaded target, mentioning a new thread
1579 might be confusing to the user. Be silent then, preserving the
1580 age old behavior. */
1581 if (rs->starting_up)
1582 add_thread_silent (ptid);
1583 else
1584 add_thread (ptid);
1941c569
PA
1585
1586 set_executing (ptid, running);
1587 set_running (ptid, running);
1588}
1589
1590/* Come here when we learn about a thread id from the remote target.
1591 It may be the first time we hear about such thread, so take the
1592 opportunity to add it to GDB's thread list. In case this is the
1593 first time we're noticing its corresponding inferior, add it to
1594 GDB's inferior list as well. */
1595
1596static void
1597remote_notice_new_inferior (ptid_t currthread, int running)
1598{
c906108c
SS
1599 /* If this is a new thread, add it to GDB's thread list.
1600 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1601
1602 if (in_thread_list (currthread) && is_exited (currthread))
1603 {
1604 /* We're seeing an event on a thread id we knew had exited.
1605 This has to be a new thread reusing the old id. Add it. */
1941c569 1606 remote_add_thread (currthread, running);
82f73884
PA
1607 return;
1608 }
1609
79d7f229 1610 if (!in_thread_list (currthread))
c0a2216e 1611 {
1941c569 1612 struct inferior *inf = NULL;
bad34192 1613 int pid = ptid_get_pid (currthread);
1941c569 1614
bad34192
PA
1615 if (ptid_is_pid (inferior_ptid)
1616 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1617 {
1618 /* inferior_ptid has no thread member yet. This can happen
1619 with the vAttach -> remote_wait,"TAAthread:" path if the
1620 stub doesn't support qC. This is the first stop reported
1621 after an attach, so this is the main thread. Update the
1622 ptid in the thread list. */
bad34192
PA
1623 if (in_thread_list (pid_to_ptid (pid)))
1624 thread_change_ptid (inferior_ptid, currthread);
1625 else
1626 {
1627 remote_add_thread (currthread, running);
1628 inferior_ptid = currthread;
1629 }
dc146f7c 1630 return;
c0a2216e 1631 }
82f73884
PA
1632
1633 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1634 {
1635 /* inferior_ptid is not set yet. This can happen with the
1636 vRun -> remote_wait,"TAAthread:" path if the stub
1637 doesn't support qC. This is the first stop reported
1638 after an attach, so this is the main thread. Update the
1639 ptid in the thread list. */
dc146f7c 1640 thread_change_ptid (inferior_ptid, currthread);
82f73884 1641 return;
c0a2216e 1642 }
82f73884 1643
29c87f7f
PA
1644 /* When connecting to a target remote, or to a target
1645 extended-remote which already was debugging an inferior, we
1646 may not know about it yet. Add it before adding its child
1647 thread, so notifications are emitted in a sensible order. */
1648 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1649 {
1650 struct remote_state *rs = get_remote_state ();
1651 int fake_pid_p = !remote_multi_process_p (rs);
1652
1653 inf = remote_add_inferior (fake_pid_p,
1654 ptid_get_pid (currthread), -1);
1655 }
29c87f7f 1656
82f73884 1657 /* This is really a new thread. Add it. */
1941c569
PA
1658 remote_add_thread (currthread, running);
1659
1660 /* If we found a new inferior, let the common code do whatever
1661 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1662 breakpoints), unless we're just setting up an all-stop
1663 connection. */
1941c569 1664 if (inf != NULL)
b7ea362b
PA
1665 {
1666 struct remote_state *rs = get_remote_state ();
1667
1668 if (non_stop || !rs->starting_up)
1669 notice_new_inferior (currthread, running, 0);
1670 }
c0a2216e 1671 }
c906108c
SS
1672}
1673
dc146f7c
VP
1674/* Return the private thread data, creating it if necessary. */
1675
70221824 1676static struct private_thread_info *
dc146f7c
VP
1677demand_private_info (ptid_t ptid)
1678{
1679 struct thread_info *info = find_thread_ptid (ptid);
1680
1681 gdb_assert (info);
1682
fe978cb0 1683 if (!info->priv)
dc146f7c 1684 {
fe978cb0 1685 info->priv = xmalloc (sizeof (*(info->priv)));
dc146f7c 1686 info->private_dtor = free_private_thread_info;
fe978cb0
PA
1687 info->priv->core = -1;
1688 info->priv->extra = 0;
dc146f7c
VP
1689 }
1690
fe978cb0 1691 return info->priv;
dc146f7c
VP
1692}
1693
74531fed
PA
1694/* Call this function as a result of
1695 1) A halt indication (T packet) containing a thread id
1696 2) A direct query of currthread
0df8b418 1697 3) Successful execution of set thread */
74531fed
PA
1698
1699static void
47f8a51d 1700record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1701{
47f8a51d 1702 rs->general_thread = currthread;
74531fed
PA
1703}
1704
89be2091
DJ
1705/* If 'QPassSignals' is supported, tell the remote stub what signals
1706 it can simply pass through to the inferior without reporting. */
1707
1708static void
94bedb42
TT
1709remote_pass_signals (struct target_ops *self,
1710 int numsigs, unsigned char *pass_signals)
89be2091 1711{
4082afcc 1712 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
1713 {
1714 char *pass_packet, *p;
89be2091 1715 int count = 0, i;
747dc59d 1716 struct remote_state *rs = get_remote_state ();
89be2091
DJ
1717
1718 gdb_assert (numsigs < 256);
1719 for (i = 0; i < numsigs; i++)
1720 {
2455069d 1721 if (pass_signals[i])
89be2091
DJ
1722 count++;
1723 }
1724 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1725 strcpy (pass_packet, "QPassSignals:");
1726 p = pass_packet + strlen (pass_packet);
1727 for (i = 0; i < numsigs; i++)
1728 {
2455069d 1729 if (pass_signals[i])
89be2091
DJ
1730 {
1731 if (i >= 16)
1732 *p++ = tohex (i >> 4);
1733 *p++ = tohex (i & 15);
1734 if (count)
1735 *p++ = ';';
1736 else
1737 break;
1738 count--;
1739 }
1740 }
1741 *p = 0;
747dc59d 1742 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 1743 {
89be2091
DJ
1744 putpkt (pass_packet);
1745 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1746 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
1747 if (rs->last_pass_packet)
1748 xfree (rs->last_pass_packet);
1749 rs->last_pass_packet = pass_packet;
89be2091
DJ
1750 }
1751 else
1752 xfree (pass_packet);
1753 }
1754}
1755
9b224c5e
PA
1756/* If 'QProgramSignals' is supported, tell the remote stub what
1757 signals it should pass through to the inferior when detaching. */
1758
1759static void
daf5e9b6
TT
1760remote_program_signals (struct target_ops *self,
1761 int numsigs, unsigned char *signals)
9b224c5e 1762{
4082afcc 1763 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
1764 {
1765 char *packet, *p;
1766 int count = 0, i;
5e4a05c4 1767 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
1768
1769 gdb_assert (numsigs < 256);
1770 for (i = 0; i < numsigs; i++)
1771 {
1772 if (signals[i])
1773 count++;
1774 }
1775 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1776 strcpy (packet, "QProgramSignals:");
1777 p = packet + strlen (packet);
1778 for (i = 0; i < numsigs; i++)
1779 {
1780 if (signal_pass_state (i))
1781 {
1782 if (i >= 16)
1783 *p++ = tohex (i >> 4);
1784 *p++ = tohex (i & 15);
1785 if (count)
1786 *p++ = ';';
1787 else
1788 break;
1789 count--;
1790 }
1791 }
1792 *p = 0;
5e4a05c4
TT
1793 if (!rs->last_program_signals_packet
1794 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 1795 {
9b224c5e
PA
1796 putpkt (packet);
1797 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1798 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
1799 xfree (rs->last_program_signals_packet);
1800 rs->last_program_signals_packet = packet;
9b224c5e
PA
1801 }
1802 else
1803 xfree (packet);
1804 }
1805}
1806
79d7f229
PA
1807/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1808 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1809 thread. If GEN is set, set the general thread, if not, then set
1810 the step/continue thread. */
c906108c 1811static void
79d7f229 1812set_thread (struct ptid ptid, int gen)
c906108c 1813{
d01949b6 1814 struct remote_state *rs = get_remote_state ();
47f8a51d 1815 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 1816 char *buf = rs->buf;
79d7f229 1817 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 1818
79d7f229 1819 if (ptid_equal (state, ptid))
c906108c
SS
1820 return;
1821
79d7f229
PA
1822 *buf++ = 'H';
1823 *buf++ = gen ? 'g' : 'c';
1824 if (ptid_equal (ptid, magic_null_ptid))
1825 xsnprintf (buf, endbuf - buf, "0");
1826 else if (ptid_equal (ptid, any_thread_ptid))
1827 xsnprintf (buf, endbuf - buf, "0");
1828 else if (ptid_equal (ptid, minus_one_ptid))
1829 xsnprintf (buf, endbuf - buf, "-1");
1830 else
82f73884 1831 write_ptid (buf, endbuf, ptid);
79d7f229 1832 putpkt (rs->buf);
6d820c5c 1833 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 1834 if (gen)
47f8a51d 1835 rs->general_thread = ptid;
c906108c 1836 else
47f8a51d 1837 rs->continue_thread = ptid;
c906108c 1838}
79d7f229
PA
1839
1840static void
1841set_general_thread (struct ptid ptid)
1842{
1843 set_thread (ptid, 1);
1844}
1845
1846static void
1847set_continue_thread (struct ptid ptid)
1848{
1849 set_thread (ptid, 0);
1850}
1851
3c9c4b83
PA
1852/* Change the remote current process. Which thread within the process
1853 ends up selected isn't important, as long as it is the same process
1854 as what INFERIOR_PTID points to.
1855
1856 This comes from that fact that there is no explicit notion of
1857 "selected process" in the protocol. The selected process for
1858 general operations is the process the selected general thread
1859 belongs to. */
1860
1861static void
1862set_general_process (void)
1863{
1864 struct remote_state *rs = get_remote_state ();
1865
1866 /* If the remote can't handle multiple processes, don't bother. */
901f9912 1867 if (!rs->extended || !remote_multi_process_p (rs))
3c9c4b83
PA
1868 return;
1869
1870 /* We only need to change the remote current thread if it's pointing
1871 at some other process. */
47f8a51d 1872 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
1873 set_general_thread (inferior_ptid);
1874}
1875
c906108c 1876\f
7d1a114c
PA
1877/* Return nonzero if this is the main thread that we made up ourselves
1878 to model non-threaded targets as single-threaded. */
c906108c
SS
1879
1880static int
7d1a114c 1881remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 1882{
6d820c5c 1883 struct remote_state *rs = get_remote_state ();
82f73884 1884 char *p, *endp;
c906108c 1885
c0a2216e
PA
1886 if (ptid_equal (ptid, magic_null_ptid))
1887 /* The main thread is always alive. */
1888 return 1;
1889
ba348170 1890 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
1891 /* The main thread is always alive. This can happen after a
1892 vAttach, if the remote side doesn't support
1893 multi-threading. */
1894 return 1;
1895
7d1a114c
PA
1896 return 0;
1897}
1898
1899/* Return nonzero if the thread PTID is still alive on the remote
1900 system. */
1901
1902static int
1903remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1904{
1905 struct remote_state *rs = get_remote_state ();
1906 char *p, *endp;
1907
1908 /* Check if this is a thread that we made up ourselves to model
1909 non-threaded targets as single-threaded. */
1910 if (remote_thread_always_alive (ops, ptid))
1911 return 1;
1912
82f73884
PA
1913 p = rs->buf;
1914 endp = rs->buf + get_remote_packet_size ();
1915
1916 *p++ = 'T';
1917 write_ptid (p, endp, ptid);
1918
2e9f7625 1919 putpkt (rs->buf);
6d820c5c 1920 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 1921 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
1922}
1923
1924/* About these extended threadlist and threadinfo packets. They are
1925 variable length packets but, the fields within them are often fixed
1926 length. They are redundent enough to send over UDP as is the
1927 remote protocol in general. There is a matching unit test module
1928 in libstub. */
1929
23860348 1930/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 1931 libstub protocol encoding, and remote.c. It is not particularly
23860348 1932 changable. */
cce74817
JM
1933
1934/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 1935 Plan to fix this. */
cce74817 1936
23860348 1937typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 1938
9d1f7ab2 1939/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 1940 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
1941
1942struct gdb_ext_thread_info
c5aa993b 1943 {
23860348 1944 threadref threadid; /* External form of thread reference. */
2bc416ba 1945 int active; /* Has state interesting to GDB?
23860348 1946 regs, stack. */
2bc416ba 1947 char display[256]; /* Brief state display, name,
cedea757 1948 blocked/suspended. */
23860348 1949 char shortname[32]; /* To be used to name threads. */
2bc416ba 1950 char more_display[256]; /* Long info, statistics, queue depth,
23860348 1951 whatever. */
c5aa993b 1952 };
cce74817
JM
1953
1954/* The volume of remote transfers can be limited by submitting
1955 a mask containing bits specifying the desired information.
1956 Use a union of these values as the 'selection' parameter to
0df8b418 1957 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
1958
1959#define TAG_THREADID 1
1960#define TAG_EXISTS 2
1961#define TAG_DISPLAY 4
1962#define TAG_THREADNAME 8
c5aa993b 1963#define TAG_MOREDISPLAY 16
cce74817 1964
23860348 1965#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 1966
a14ed312 1967static char *unpack_nibble (char *buf, int *val);
cce74817 1968
a14ed312 1969static char *unpack_byte (char *buf, int *value);
cce74817 1970
a14ed312 1971static char *pack_int (char *buf, int value);
cce74817 1972
a14ed312 1973static char *unpack_int (char *buf, int *value);
cce74817 1974
a14ed312 1975static char *unpack_string (char *src, char *dest, int length);
cce74817 1976
23860348 1977static char *pack_threadid (char *pkt, threadref *id);
cce74817 1978
23860348 1979static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 1980
23860348 1981void int_to_threadref (threadref *id, int value);
cce74817 1982
23860348 1983static int threadref_to_int (threadref *ref);
cce74817 1984
23860348 1985static void copy_threadref (threadref *dest, threadref *src);
cce74817 1986
23860348 1987static int threadmatch (threadref *dest, threadref *src);
cce74817 1988
2bc416ba 1989static char *pack_threadinfo_request (char *pkt, int mode,
23860348 1990 threadref *id);
cce74817 1991
a14ed312 1992static int remote_unpack_thread_info_response (char *pkt,
23860348 1993 threadref *expectedref,
a14ed312
KB
1994 struct gdb_ext_thread_info
1995 *info);
cce74817
JM
1996
1997
2bc416ba 1998static int remote_get_threadinfo (threadref *threadid,
23860348 1999 int fieldset, /*TAG mask */
a14ed312 2000 struct gdb_ext_thread_info *info);
cce74817 2001
a14ed312
KB
2002static char *pack_threadlist_request (char *pkt, int startflag,
2003 int threadcount,
23860348 2004 threadref *nextthread);
cce74817 2005
a14ed312
KB
2006static int parse_threadlist_response (char *pkt,
2007 int result_limit,
23860348 2008 threadref *original_echo,
2bc416ba 2009 threadref *resultlist,
23860348 2010 int *doneflag);
cce74817 2011
a14ed312 2012static int remote_get_threadlist (int startflag,
23860348 2013 threadref *nextthread,
a14ed312
KB
2014 int result_limit,
2015 int *done,
2bc416ba 2016 int *result_count,
23860348 2017 threadref *threadlist);
cce74817 2018
23860348 2019typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2020
a14ed312
KB
2021static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2022 void *context, int looplimit);
cce74817 2023
23860348 2024static int remote_newthread_step (threadref *ref, void *context);
cce74817 2025
82f73884
PA
2026
2027/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2028 buffer we're allowed to write to. Returns
2029 BUF+CHARACTERS_WRITTEN. */
2030
2031static char *
2032write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2033{
2034 int pid, tid;
2035 struct remote_state *rs = get_remote_state ();
2036
2037 if (remote_multi_process_p (rs))
2038 {
2039 pid = ptid_get_pid (ptid);
2040 if (pid < 0)
2041 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2042 else
2043 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2044 }
ba348170 2045 tid = ptid_get_lwp (ptid);
82f73884
PA
2046 if (tid < 0)
2047 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2048 else
2049 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2050
2051 return buf;
2052}
2053
2054/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2055 passed the last parsed char. Returns null_ptid on error. */
2056
2057static ptid_t
2058read_ptid (char *buf, char **obuf)
2059{
2060 char *p = buf;
2061 char *pp;
2062 ULONGEST pid = 0, tid = 0;
82f73884
PA
2063
2064 if (*p == 'p')
2065 {
2066 /* Multi-process ptid. */
2067 pp = unpack_varlen_hex (p + 1, &pid);
2068 if (*pp != '.')
b37520b6 2069 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2070
2071 p = pp;
2072 pp = unpack_varlen_hex (p + 1, &tid);
2073 if (obuf)
2074 *obuf = pp;
ba348170 2075 return ptid_build (pid, tid, 0);
82f73884
PA
2076 }
2077
2078 /* No multi-process. Just a tid. */
2079 pp = unpack_varlen_hex (p, &tid);
2080
2081 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2082 what's in inferior_ptid, unless it's null at this point. If so,
2083 then since there's no way to know the pid of the reported
2084 threads, use the magic number. */
2085 if (ptid_equal (inferior_ptid, null_ptid))
2086 pid = ptid_get_pid (magic_null_ptid);
2087 else
2088 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2089
2090 if (obuf)
2091 *obuf = pp;
ba348170 2092 return ptid_build (pid, tid, 0);
82f73884
PA
2093}
2094
c906108c 2095static int
fba45db2 2096stubhex (int ch)
c906108c
SS
2097{
2098 if (ch >= 'a' && ch <= 'f')
2099 return ch - 'a' + 10;
2100 if (ch >= '0' && ch <= '9')
2101 return ch - '0';
2102 if (ch >= 'A' && ch <= 'F')
2103 return ch - 'A' + 10;
2104 return -1;
2105}
2106
2107static int
fba45db2 2108stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2109{
2110 int nibble;
2111 int retval = 0;
2112
2113 while (fieldlength)
2114 {
2115 nibble = stubhex (*buff++);
2116 retval |= nibble;
2117 fieldlength--;
2118 if (fieldlength)
2119 retval = retval << 4;
2120 }
2121 return retval;
2122}
2123
c906108c 2124static char *
fba45db2 2125unpack_nibble (char *buf, int *val)
c906108c 2126{
b7589f7d 2127 *val = fromhex (*buf++);
c906108c
SS
2128 return buf;
2129}
2130
c906108c 2131static char *
fba45db2 2132unpack_byte (char *buf, int *value)
c906108c
SS
2133{
2134 *value = stub_unpack_int (buf, 2);
2135 return buf + 2;
2136}
2137
2138static char *
fba45db2 2139pack_int (char *buf, int value)
c906108c
SS
2140{
2141 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2142 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2143 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2144 buf = pack_hex_byte (buf, (value & 0xff));
2145 return buf;
2146}
2147
2148static char *
fba45db2 2149unpack_int (char *buf, int *value)
c906108c
SS
2150{
2151 *value = stub_unpack_int (buf, 8);
2152 return buf + 8;
2153}
2154
23860348 2155#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2156static char *pack_string (char *pkt, char *string);
c906108c
SS
2157
2158static char *
fba45db2 2159pack_string (char *pkt, char *string)
c906108c
SS
2160{
2161 char ch;
2162 int len;
2163
2164 len = strlen (string);
2165 if (len > 200)
23860348 2166 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2167 pkt = pack_hex_byte (pkt, len);
2168 while (len-- > 0)
2169 {
2170 ch = *string++;
2171 if ((ch == '\0') || (ch == '#'))
23860348 2172 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2173 *pkt++ = ch;
2174 }
2175 return pkt;
2176}
2177#endif /* 0 (unused) */
2178
2179static char *
fba45db2 2180unpack_string (char *src, char *dest, int length)
c906108c
SS
2181{
2182 while (length--)
2183 *dest++ = *src++;
2184 *dest = '\0';
2185 return src;
2186}
2187
2188static char *
fba45db2 2189pack_threadid (char *pkt, threadref *id)
c906108c
SS
2190{
2191 char *limit;
2192 unsigned char *altid;
2193
2194 altid = (unsigned char *) id;
2195 limit = pkt + BUF_THREAD_ID_SIZE;
2196 while (pkt < limit)
2197 pkt = pack_hex_byte (pkt, *altid++);
2198 return pkt;
2199}
2200
2201
2202static char *
fba45db2 2203unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2204{
2205 char *altref;
2206 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2207 int x, y;
2208
2209 altref = (char *) id;
2210
2211 while (inbuf < limit)
2212 {
2213 x = stubhex (*inbuf++);
2214 y = stubhex (*inbuf++);
2215 *altref++ = (x << 4) | y;
2216 }
2217 return inbuf;
2218}
2219
2220/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2221 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2222 to use 64bit thread references internally. This is an adapter
2223 function. */
2224
2225void
fba45db2 2226int_to_threadref (threadref *id, int value)
c906108c
SS
2227{
2228 unsigned char *scan;
2229
2230 scan = (unsigned char *) id;
2231 {
2232 int i = 4;
2233 while (i--)
2234 *scan++ = 0;
2235 }
2236 *scan++ = (value >> 24) & 0xff;
2237 *scan++ = (value >> 16) & 0xff;
2238 *scan++ = (value >> 8) & 0xff;
2239 *scan++ = (value & 0xff);
2240}
2241
2242static int
fba45db2 2243threadref_to_int (threadref *ref)
c906108c
SS
2244{
2245 int i, value = 0;
2246 unsigned char *scan;
2247
cfd77fa1 2248 scan = *ref;
c906108c
SS
2249 scan += 4;
2250 i = 4;
2251 while (i-- > 0)
2252 value = (value << 8) | ((*scan++) & 0xff);
2253 return value;
2254}
2255
2256static void
fba45db2 2257copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2258{
2259 int i;
2260 unsigned char *csrc, *cdest;
2261
2262 csrc = (unsigned char *) src;
2263 cdest = (unsigned char *) dest;
2264 i = 8;
2265 while (i--)
2266 *cdest++ = *csrc++;
2267}
2268
2269static int
fba45db2 2270threadmatch (threadref *dest, threadref *src)
c906108c 2271{
23860348 2272 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2273#if 0
2274 unsigned char *srcp, *destp;
2275 int i, result;
2276 srcp = (char *) src;
2277 destp = (char *) dest;
2278
2279 result = 1;
2280 while (i-- > 0)
2281 result &= (*srcp++ == *destp++) ? 1 : 0;
2282 return result;
2283#endif
2284 return 1;
2285}
2286
2287/*
c5aa993b
JM
2288 threadid:1, # always request threadid
2289 context_exists:2,
2290 display:4,
2291 unique_name:8,
2292 more_display:16
2293 */
c906108c
SS
2294
2295/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2296
2297static char *
fba45db2 2298pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2299{
23860348
MS
2300 *pkt++ = 'q'; /* Info Query */
2301 *pkt++ = 'P'; /* process or thread info */
2302 pkt = pack_int (pkt, mode); /* mode */
c906108c 2303 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2304 *pkt = '\0'; /* terminate */
c906108c
SS
2305 return pkt;
2306}
2307
23860348 2308/* These values tag the fields in a thread info response packet. */
c906108c 2309/* Tagging the fields allows us to request specific fields and to
23860348 2310 add more fields as time goes by. */
c906108c 2311
23860348 2312#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2313#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2314 fetch registers and its stack? */
c5aa993b 2315#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2316#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2317#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2318 the process. */
c906108c
SS
2319
2320static int
fba45db2
KB
2321remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2322 struct gdb_ext_thread_info *info)
c906108c 2323{
d01949b6 2324 struct remote_state *rs = get_remote_state ();
c906108c 2325 int mask, length;
cfd77fa1 2326 int tag;
c906108c 2327 threadref ref;
6d820c5c 2328 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2329 int retval = 1;
2330
23860348 2331 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2332 info->active = 0;
2333 info->display[0] = '\0';
2334 info->shortname[0] = '\0';
2335 info->more_display[0] = '\0';
2336
23860348
MS
2337 /* Assume the characters indicating the packet type have been
2338 stripped. */
c906108c
SS
2339 pkt = unpack_int (pkt, &mask); /* arg mask */
2340 pkt = unpack_threadid (pkt, &ref);
2341
2342 if (mask == 0)
8a3fe4f8 2343 warning (_("Incomplete response to threadinfo request."));
c906108c 2344 if (!threadmatch (&ref, expectedref))
23860348 2345 { /* This is an answer to a different request. */
8a3fe4f8 2346 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2347 return 0;
2348 }
2349 copy_threadref (&info->threadid, &ref);
2350
23860348 2351 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2352
23860348
MS
2353 /* Packets are terminated with nulls. */
2354 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2355 {
2356 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2357 pkt = unpack_byte (pkt, &length); /* length */
2358 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2359 {
8a3fe4f8 2360 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2361 retval = 0;
2362 break;
2363 }
2364 if (tag == TAG_THREADID)
2365 {
2366 if (length != 16)
2367 {
8a3fe4f8 2368 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2369 retval = 0;
2370 break;
2371 }
2372 pkt = unpack_threadid (pkt, &ref);
2373 mask = mask & ~TAG_THREADID;
2374 continue;
2375 }
2376 if (tag == TAG_EXISTS)
2377 {
2378 info->active = stub_unpack_int (pkt, length);
2379 pkt += length;
2380 mask = mask & ~(TAG_EXISTS);
2381 if (length > 8)
2382 {
8a3fe4f8 2383 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2384 retval = 0;
2385 break;
2386 }
2387 continue;
2388 }
2389 if (tag == TAG_THREADNAME)
2390 {
2391 pkt = unpack_string (pkt, &info->shortname[0], length);
2392 mask = mask & ~TAG_THREADNAME;
2393 continue;
2394 }
2395 if (tag == TAG_DISPLAY)
2396 {
2397 pkt = unpack_string (pkt, &info->display[0], length);
2398 mask = mask & ~TAG_DISPLAY;
2399 continue;
2400 }
2401 if (tag == TAG_MOREDISPLAY)
2402 {
2403 pkt = unpack_string (pkt, &info->more_display[0], length);
2404 mask = mask & ~TAG_MOREDISPLAY;
2405 continue;
2406 }
8a3fe4f8 2407 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2408 break; /* Not a tag we know about. */
c906108c
SS
2409 }
2410 return retval;
2411}
2412
2413static int
fba45db2
KB
2414remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2415 struct gdb_ext_thread_info *info)
c906108c 2416{
d01949b6 2417 struct remote_state *rs = get_remote_state ();
c906108c 2418 int result;
c906108c 2419
2e9f7625
DJ
2420 pack_threadinfo_request (rs->buf, fieldset, threadid);
2421 putpkt (rs->buf);
6d820c5c 2422 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2423
2424 if (rs->buf[0] == '\0')
2425 return 0;
2426
2e9f7625 2427 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2428 threadid, info);
c906108c
SS
2429 return result;
2430}
2431
c906108c
SS
2432/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2433
2434static char *
fba45db2
KB
2435pack_threadlist_request (char *pkt, int startflag, int threadcount,
2436 threadref *nextthread)
c906108c
SS
2437{
2438 *pkt++ = 'q'; /* info query packet */
2439 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2440 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2441 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2442 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2443 *pkt = '\0';
2444 return pkt;
2445}
2446
2447/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2448
2449static int
fba45db2
KB
2450parse_threadlist_response (char *pkt, int result_limit,
2451 threadref *original_echo, threadref *resultlist,
2452 int *doneflag)
c906108c 2453{
d01949b6 2454 struct remote_state *rs = get_remote_state ();
c906108c
SS
2455 char *limit;
2456 int count, resultcount, done;
2457
2458 resultcount = 0;
2459 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2460 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2461 /* done parse past here */
c906108c
SS
2462 pkt = unpack_byte (pkt, &count); /* count field */
2463 pkt = unpack_nibble (pkt, &done);
2464 /* The first threadid is the argument threadid. */
2465 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2466 while ((count-- > 0) && (pkt < limit))
2467 {
2468 pkt = unpack_threadid (pkt, resultlist++);
2469 if (resultcount++ >= result_limit)
2470 break;
2471 }
2472 if (doneflag)
2473 *doneflag = done;
2474 return resultcount;
2475}
2476
6dc54d91
PA
2477/* Fetch the next batch of threads from the remote. Returns -1 if the
2478 qL packet is not supported, 0 on error and 1 on success. */
2479
c906108c 2480static int
fba45db2
KB
2481remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2482 int *done, int *result_count, threadref *threadlist)
c906108c 2483{
d01949b6 2484 struct remote_state *rs = get_remote_state ();
c906108c
SS
2485 int result = 1;
2486
23860348 2487 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2488 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2489 >= get_remote_packet_size ())
ea9c271d 2490 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2491
6d820c5c
DJ
2492 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2493 putpkt (rs->buf);
2494 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2495 if (*rs->buf == '\0')
6dc54d91
PA
2496 {
2497 /* Packet not supported. */
2498 return -1;
2499 }
2500
2501 *result_count =
2502 parse_threadlist_response (rs->buf + 2, result_limit,
2503 &rs->echo_nextthread, threadlist, done);
c906108c 2504
0d031856 2505 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2506 {
23860348
MS
2507 /* FIXME: This is a good reason to drop the packet. */
2508 /* Possably, there is a duplicate response. */
c906108c
SS
2509 /* Possabilities :
2510 retransmit immediatly - race conditions
2511 retransmit after timeout - yes
2512 exit
2513 wait for packet, then exit
2514 */
8a3fe4f8 2515 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2516 return 0; /* I choose simply exiting. */
c906108c
SS
2517 }
2518 if (*result_count <= 0)
2519 {
2520 if (*done != 1)
2521 {
8a3fe4f8 2522 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2523 result = 0;
2524 }
2525 return result; /* break; */
2526 }
2527 if (*result_count > result_limit)
2528 {
2529 *result_count = 0;
8a3fe4f8 2530 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2531 return 0;
2532 }
2533 return result;
2534}
2535
6dc54d91
PA
2536/* Fetch the list of remote threads, with the qL packet, and call
2537 STEPFUNCTION for each thread found. Stops iterating and returns 1
2538 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2539 STEPFUNCTION returns false. If the packet is not supported,
2540 returns -1. */
c906108c 2541
c906108c 2542static int
fba45db2
KB
2543remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2544 int looplimit)
c906108c 2545{
0d031856 2546 struct remote_state *rs = get_remote_state ();
c906108c
SS
2547 int done, i, result_count;
2548 int startflag = 1;
2549 int result = 1;
2550 int loopcount = 0;
c906108c
SS
2551
2552 done = 0;
2553 while (!done)
2554 {
2555 if (loopcount++ > looplimit)
2556 {
2557 result = 0;
8a3fe4f8 2558 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2559 break;
2560 }
6dc54d91
PA
2561 result = remote_get_threadlist (startflag, &rs->nextthread,
2562 MAXTHREADLISTRESULTS,
2563 &done, &result_count,
2564 rs->resultthreadlist);
2565 if (result <= 0)
2566 break;
23860348 2567 /* Clear for later iterations. */
c906108c
SS
2568 startflag = 0;
2569 /* Setup to resume next batch of thread references, set nextthread. */
2570 if (result_count >= 1)
0d031856
TT
2571 copy_threadref (&rs->nextthread,
2572 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2573 i = 0;
2574 while (result_count--)
6dc54d91
PA
2575 {
2576 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2577 {
2578 result = 0;
2579 break;
2580 }
2581 }
c906108c
SS
2582 }
2583 return result;
2584}
2585
6dc54d91
PA
2586/* A thread found on the remote target. */
2587
2588typedef struct thread_item
2589{
2590 /* The thread's PTID. */
2591 ptid_t ptid;
2592
2593 /* The thread's extra info. May be NULL. */
2594 char *extra;
2595
2596 /* The core the thread was running on. -1 if not known. */
2597 int core;
2598} thread_item_t;
2599DEF_VEC_O(thread_item_t);
2600
2601/* Context passed around to the various methods listing remote
2602 threads. As new threads are found, they're added to the ITEMS
2603 vector. */
2604
2605struct threads_listing_context
2606{
2607 /* The threads found on the remote target. */
2608 VEC (thread_item_t) *items;
2609};
2610
80134cf5
PA
2611/* Discard the contents of the constructed thread listing context. */
2612
2613static void
2614clear_threads_listing_context (void *p)
2615{
2616 struct threads_listing_context *context = p;
2617 int i;
2618 struct thread_item *item;
2619
2620 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2621 xfree (item->extra);
2622
2623 VEC_free (thread_item_t, context->items);
2624}
2625
c906108c 2626static int
6dc54d91 2627remote_newthread_step (threadref *ref, void *data)
c906108c 2628{
6dc54d91
PA
2629 struct threads_listing_context *context = data;
2630 struct thread_item item;
79d7f229 2631 int pid = ptid_get_pid (inferior_ptid);
39f77062 2632
6dc54d91
PA
2633 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2634 item.core = -1;
2635 item.extra = NULL;
2636
2637 VEC_safe_push (thread_item_t, context->items, &item);
2638
c906108c
SS
2639 return 1; /* continue iterator */
2640}
2641
2642#define CRAZY_MAX_THREADS 1000
2643
39f77062
KB
2644static ptid_t
2645remote_current_thread (ptid_t oldpid)
c906108c 2646{
d01949b6 2647 struct remote_state *rs = get_remote_state ();
c906108c
SS
2648
2649 putpkt ("qC");
6d820c5c 2650 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2651 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
82f73884 2652 return read_ptid (&rs->buf[2], NULL);
c906108c
SS
2653 else
2654 return oldpid;
2655}
2656
6dc54d91 2657/* List remote threads using the deprecated qL packet. */
cce74817 2658
6dc54d91
PA
2659static int
2660remote_get_threads_with_ql (struct target_ops *ops,
2661 struct threads_listing_context *context)
c906108c 2662{
6dc54d91
PA
2663 if (remote_threadlist_iterator (remote_newthread_step, context,
2664 CRAZY_MAX_THREADS) >= 0)
2665 return 1;
2666
2667 return 0;
c906108c
SS
2668}
2669
dc146f7c
VP
2670#if defined(HAVE_LIBEXPAT)
2671
dc146f7c
VP
2672static void
2673start_thread (struct gdb_xml_parser *parser,
2674 const struct gdb_xml_element *element,
2675 void *user_data, VEC(gdb_xml_value_s) *attributes)
2676{
6dc54d91 2677 struct threads_listing_context *data = user_data;
dc146f7c
VP
2678
2679 struct thread_item item;
2680 char *id;
3d2c1d41 2681 struct gdb_xml_value *attr;
dc146f7c 2682
3d2c1d41 2683 id = xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
2684 item.ptid = read_ptid (id, NULL);
2685
3d2c1d41
PA
2686 attr = xml_find_attribute (attributes, "core");
2687 if (attr != NULL)
2688 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
2689 else
2690 item.core = -1;
2691
2692 item.extra = 0;
2693
2694 VEC_safe_push (thread_item_t, data->items, &item);
2695}
2696
2697static void
2698end_thread (struct gdb_xml_parser *parser,
2699 const struct gdb_xml_element *element,
2700 void *user_data, const char *body_text)
2701{
6dc54d91 2702 struct threads_listing_context *data = user_data;
dc146f7c
VP
2703
2704 if (body_text && *body_text)
2ae2a0b7 2705 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
2706}
2707
2708const struct gdb_xml_attribute thread_attributes[] = {
2709 { "id", GDB_XML_AF_NONE, NULL, NULL },
2710 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2711 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2712};
2713
2714const struct gdb_xml_element thread_children[] = {
2715 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2716};
2717
2718const struct gdb_xml_element threads_children[] = {
2719 { "thread", thread_attributes, thread_children,
2720 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2721 start_thread, end_thread },
2722 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2723};
2724
2725const struct gdb_xml_element threads_elements[] = {
2726 { "threads", NULL, threads_children,
2727 GDB_XML_EF_NONE, NULL, NULL },
2728 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2729};
2730
2731#endif
2732
6dc54d91 2733/* List remote threads using qXfer:threads:read. */
9d1f7ab2 2734
6dc54d91
PA
2735static int
2736remote_get_threads_with_qxfer (struct target_ops *ops,
2737 struct threads_listing_context *context)
0f71a2f6 2738{
dc146f7c 2739#if defined(HAVE_LIBEXPAT)
4082afcc 2740 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 2741 {
6dc54d91 2742 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 2743 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 2744
6dc54d91 2745 if (xml != NULL && *xml != '\0')
dc146f7c 2746 {
6dc54d91
PA
2747 gdb_xml_parse_quick (_("threads"), "threads.dtd",
2748 threads_elements, xml, context);
dc146f7c
VP
2749 }
2750
2751 do_cleanups (back_to);
6dc54d91 2752 return 1;
dc146f7c
VP
2753 }
2754#endif
2755
6dc54d91
PA
2756 return 0;
2757}
2758
2759/* List remote threads using qfThreadInfo/qsThreadInfo. */
2760
2761static int
2762remote_get_threads_with_qthreadinfo (struct target_ops *ops,
2763 struct threads_listing_context *context)
2764{
2765 struct remote_state *rs = get_remote_state ();
2766
b80fafe3 2767 if (rs->use_threadinfo_query)
9d1f7ab2 2768 {
6dc54d91
PA
2769 char *bufp;
2770
9d1f7ab2 2771 putpkt ("qfThreadInfo");
6d820c5c 2772 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2773 bufp = rs->buf;
9d1f7ab2 2774 if (bufp[0] != '\0') /* q packet recognized */
802188a7 2775 {
9d1f7ab2
MS
2776 while (*bufp++ == 'm') /* reply contains one or more TID */
2777 {
2778 do
2779 {
6dc54d91
PA
2780 struct thread_item item;
2781
2782 item.ptid = read_ptid (bufp, &bufp);
2783 item.core = -1;
2784 item.extra = NULL;
2785
2786 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
2787 }
2788 while (*bufp++ == ','); /* comma-separated list */
2789 putpkt ("qsThreadInfo");
6d820c5c 2790 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 2791 bufp = rs->buf;
9d1f7ab2 2792 }
6dc54d91
PA
2793 return 1;
2794 }
2795 else
2796 {
2797 /* Packet not recognized. */
2798 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
2799 }
2800 }
2801
6dc54d91
PA
2802 return 0;
2803}
2804
e8032dde 2805/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
2806 targets. */
2807
2808static void
e8032dde 2809remote_update_thread_list (struct target_ops *ops)
6dc54d91
PA
2810{
2811 struct remote_state *rs = get_remote_state ();
2812 struct threads_listing_context context;
2813 struct cleanup *old_chain;
ab970af1 2814 int got_list = 0;
e8032dde 2815
6dc54d91
PA
2816 context.items = NULL;
2817 old_chain = make_cleanup (clear_threads_listing_context, &context);
2818
2819 /* We have a few different mechanisms to fetch the thread list. Try
2820 them all, starting with the most preferred one first, falling
2821 back to older methods. */
2822 if (remote_get_threads_with_qxfer (ops, &context)
2823 || remote_get_threads_with_qthreadinfo (ops, &context)
2824 || remote_get_threads_with_ql (ops, &context))
2825 {
2826 int i;
2827 struct thread_item *item;
ab970af1
PA
2828 struct thread_info *tp, *tmp;
2829
2830 got_list = 1;
2831
7d1a114c
PA
2832 if (VEC_empty (thread_item_t, context.items)
2833 && remote_thread_always_alive (ops, inferior_ptid))
2834 {
2835 /* Some targets don't really support threads, but still
2836 reply an (empty) thread list in response to the thread
2837 listing packets, instead of replying "packet not
2838 supported". Exit early so we don't delete the main
2839 thread. */
2840 do_cleanups (old_chain);
2841 return;
2842 }
2843
ab970af1
PA
2844 /* CONTEXT now holds the current thread list on the remote
2845 target end. Delete GDB-side threads no longer found on the
2846 target. */
2847 ALL_NON_EXITED_THREADS_SAFE (tp, tmp)
2848 {
2849 for (i = 0;
2850 VEC_iterate (thread_item_t, context.items, i, item);
2851 ++i)
2852 {
2853 if (ptid_equal (item->ptid, tp->ptid))
2854 break;
2855 }
2856
2857 if (i == VEC_length (thread_item_t, context.items))
2858 {
2859 /* Not found. */
2860 delete_thread (tp->ptid);
2861 }
2862 }
74531fed 2863
ab970af1 2864 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
2865 for (i = 0;
2866 VEC_iterate (thread_item_t, context.items, i, item);
2867 ++i)
2868 {
2869 if (!ptid_equal (item->ptid, null_ptid))
2870 {
2871 struct private_thread_info *info;
2872 /* In non-stop mode, we assume new found threads are
2873 running until proven otherwise with a stop reply. In
2874 all-stop, we can only get here if all threads are
2875 stopped. */
2876 int running = non_stop ? 1 : 0;
2877
2878 remote_notice_new_inferior (item->ptid, running);
2879
2880 info = demand_private_info (item->ptid);
2881 info->core = item->core;
2882 info->extra = item->extra;
2883 item->extra = NULL;
2884 }
2885 }
2886 }
2887
ab970af1
PA
2888 if (!got_list)
2889 {
2890 /* If no thread listing method is supported, then query whether
2891 each known thread is alive, one by one, with the T packet.
2892 If the target doesn't support threads at all, then this is a
2893 no-op. See remote_thread_alive. */
2894 prune_threads ();
2895 }
2896
6dc54d91 2897 do_cleanups (old_chain);
9d1f7ab2
MS
2898}
2899
802188a7 2900/*
9d1f7ab2
MS
2901 * Collect a descriptive string about the given thread.
2902 * The target may say anything it wants to about the thread
2903 * (typically info about its blocked / runnable state, name, etc.).
2904 * This string will appear in the info threads display.
802188a7 2905 *
9d1f7ab2
MS
2906 * Optional: targets are not required to implement this function.
2907 */
2908
2909static char *
c15906d8 2910remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 2911{
d01949b6 2912 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
2913 int result;
2914 int set;
2915 threadref id;
2916 struct gdb_ext_thread_info threadinfo;
23860348 2917 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
2918 int n = 0; /* position in display_buf */
2919
5d93a237 2920 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 2921 internal_error (__FILE__, __LINE__,
e2e0b3e5 2922 _("remote_threads_extra_info"));
9d1f7ab2 2923
60e569b9 2924 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 2925 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
2926 /* This is the main thread which was added by GDB. The remote
2927 server doesn't know about it. */
2928 return NULL;
2929
4082afcc 2930 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
2931 {
2932 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 2933
fe978cb0
PA
2934 if (info && info->priv)
2935 return info->priv->extra;
dc146f7c
VP
2936 else
2937 return NULL;
2938 }
2939
b80fafe3 2940 if (rs->use_threadextra_query)
9d1f7ab2 2941 {
82f73884
PA
2942 char *b = rs->buf;
2943 char *endb = rs->buf + get_remote_packet_size ();
2944
2945 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2946 b += strlen (b);
2947 write_ptid (b, endb, tp->ptid);
2948
2e9f7625 2949 putpkt (rs->buf);
6d820c5c 2950 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2951 if (rs->buf[0] != 0)
9d1f7ab2 2952 {
2e9f7625
DJ
2953 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2954 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 2955 display_buf [result] = '\0';
9d1f7ab2
MS
2956 return display_buf;
2957 }
0f71a2f6 2958 }
9d1f7ab2
MS
2959
2960 /* If the above query fails, fall back to the old method. */
b80fafe3 2961 rs->use_threadextra_query = 0;
9d1f7ab2
MS
2962 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2963 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 2964 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
2965 if (remote_get_threadinfo (&id, set, &threadinfo))
2966 if (threadinfo.active)
0f71a2f6 2967 {
9d1f7ab2 2968 if (*threadinfo.shortname)
2bc416ba 2969 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 2970 " Name: %s,", threadinfo.shortname);
9d1f7ab2 2971 if (*threadinfo.display)
2bc416ba 2972 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 2973 " State: %s,", threadinfo.display);
9d1f7ab2 2974 if (*threadinfo.more_display)
2bc416ba 2975 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 2976 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
2977
2978 if (n > 0)
c5aa993b 2979 {
23860348 2980 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
2981 if (',' == display_buf[n-1])
2982 display_buf[n-1] = ' ';
2983 return display_buf;
c5aa993b 2984 }
0f71a2f6 2985 }
9d1f7ab2 2986 return NULL;
0f71a2f6 2987}
c906108c 2988\f
c5aa993b 2989
0fb4aa4b 2990static int
61fc905d 2991remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
2992 struct static_tracepoint_marker *marker)
2993{
2994 struct remote_state *rs = get_remote_state ();
2995 char *p = rs->buf;
2996
bba74b36 2997 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
2998 p += strlen (p);
2999 p += hexnumstr (p, addr);
3000 putpkt (rs->buf);
3001 getpkt (&rs->buf, &rs->buf_size, 0);
3002 p = rs->buf;
3003
3004 if (*p == 'E')
3005 error (_("Remote failure reply: %s"), p);
3006
3007 if (*p++ == 'm')
3008 {
3009 parse_static_tracepoint_marker_definition (p, &p, marker);
3010 return 1;
3011 }
3012
3013 return 0;
3014}
3015
0fb4aa4b 3016static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3017remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3018 const char *strid)
0fb4aa4b
PA
3019{
3020 struct remote_state *rs = get_remote_state ();
3021 VEC(static_tracepoint_marker_p) *markers = NULL;
3022 struct static_tracepoint_marker *marker = NULL;
3023 struct cleanup *old_chain;
3024 char *p;
3025
3026 /* Ask for a first packet of static tracepoint marker
3027 definition. */
3028 putpkt ("qTfSTM");
3029 getpkt (&rs->buf, &rs->buf_size, 0);
3030 p = rs->buf;
3031 if (*p == 'E')
3032 error (_("Remote failure reply: %s"), p);
3033
3034 old_chain = make_cleanup (free_current_marker, &marker);
3035
3036 while (*p++ == 'm')
3037 {
3038 if (marker == NULL)
3039 marker = XCNEW (struct static_tracepoint_marker);
3040
3041 do
3042 {
3043 parse_static_tracepoint_marker_definition (p, &p, marker);
3044
3045 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3046 {
3047 VEC_safe_push (static_tracepoint_marker_p,
3048 markers, marker);
3049 marker = NULL;
3050 }
3051 else
3052 {
3053 release_static_tracepoint_marker (marker);
3054 memset (marker, 0, sizeof (*marker));
3055 }
3056 }
3057 while (*p++ == ','); /* comma-separated list */
3058 /* Ask for another packet of static tracepoint definition. */
3059 putpkt ("qTsSTM");
3060 getpkt (&rs->buf, &rs->buf_size, 0);
3061 p = rs->buf;
3062 }
3063
3064 do_cleanups (old_chain);
3065 return markers;
3066}
3067
3068\f
10760264
JB
3069/* Implement the to_get_ada_task_ptid function for the remote targets. */
3070
3071static ptid_t
1e6b91a4 3072remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3073{
ba348170 3074 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3075}
3076\f
3077
24b06219 3078/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3079
3080static void
fba45db2 3081extended_remote_restart (void)
c906108c 3082{
d01949b6 3083 struct remote_state *rs = get_remote_state ();
c906108c
SS
3084
3085 /* Send the restart command; for reasons I don't understand the
3086 remote side really expects a number after the "R". */
ea9c271d 3087 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3088 putpkt (rs->buf);
c906108c 3089
ad9a8f3f 3090 remote_fileio_reset ();
c906108c
SS
3091}
3092\f
3093/* Clean up connection to a remote debugger. */
3094
c906108c 3095static void
de90e03d 3096remote_close (struct target_ops *self)
c906108c 3097{
5d93a237
TT
3098 struct remote_state *rs = get_remote_state ();
3099
3100 if (rs->remote_desc == NULL)
d3fd5342
PA
3101 return; /* already closed */
3102
3103 /* Make sure we leave stdin registered in the event loop, and we
3104 don't leave the async SIGINT signal handler installed. */
e3594fd1 3105 remote_terminal_ours (self);
ce5ce7ed 3106
5d93a237
TT
3107 serial_close (rs->remote_desc);
3108 rs->remote_desc = NULL;
ce5ce7ed
PA
3109
3110 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3111 of all the inferiors and their threads we were controlling.
3112 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3113 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3114 inferior_ptid = null_ptid;
f67fd822 3115 discard_all_inferiors ();
ce5ce7ed 3116
f48ff2a7
YQ
3117 /* We are closing the remote target, so we should discard
3118 everything of this target. */
bcc75809 3119 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3120
3121 if (remote_async_inferior_event_token)
3122 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3123
5965e028 3124 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3125
3126 trace_reset_local_state ();
c906108c
SS
3127}
3128
23860348 3129/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3130
3131static void
fba45db2 3132get_offsets (void)
c906108c 3133{
d01949b6 3134 struct remote_state *rs = get_remote_state ();
2e9f7625 3135 char *buf;
085dd6e6 3136 char *ptr;
31d99776
DJ
3137 int lose, num_segments = 0, do_sections, do_segments;
3138 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3139 struct section_offsets *offs;
31d99776
DJ
3140 struct symfile_segment_data *data;
3141
3142 if (symfile_objfile == NULL)
3143 return;
c906108c
SS
3144
3145 putpkt ("qOffsets");
6d820c5c 3146 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3147 buf = rs->buf;
c906108c
SS
3148
3149 if (buf[0] == '\000')
3150 return; /* Return silently. Stub doesn't support
23860348 3151 this command. */
c906108c
SS
3152 if (buf[0] == 'E')
3153 {
8a3fe4f8 3154 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3155 return;
3156 }
3157
3158 /* Pick up each field in turn. This used to be done with scanf, but
3159 scanf will make trouble if CORE_ADDR size doesn't match
3160 conversion directives correctly. The following code will work
3161 with any size of CORE_ADDR. */
3162 text_addr = data_addr = bss_addr = 0;
3163 ptr = buf;
3164 lose = 0;
3165
61012eef 3166 if (startswith (ptr, "Text="))
c906108c
SS
3167 {
3168 ptr += 5;
3169 /* Don't use strtol, could lose on big values. */
3170 while (*ptr && *ptr != ';')
3171 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3172
61012eef 3173 if (startswith (ptr, ";Data="))
31d99776
DJ
3174 {
3175 ptr += 6;
3176 while (*ptr && *ptr != ';')
3177 data_addr = (data_addr << 4) + fromhex (*ptr++);
3178 }
3179 else
3180 lose = 1;
3181
61012eef 3182 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3183 {
3184 ptr += 5;
3185 while (*ptr && *ptr != ';')
3186 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3187
31d99776
DJ
3188 if (bss_addr != data_addr)
3189 warning (_("Target reported unsupported offsets: %s"), buf);
3190 }
3191 else
3192 lose = 1;
3193 }
61012eef 3194 else if (startswith (ptr, "TextSeg="))
c906108c 3195 {
31d99776
DJ
3196 ptr += 8;
3197 /* Don't use strtol, could lose on big values. */
c906108c 3198 while (*ptr && *ptr != ';')
31d99776
DJ
3199 text_addr = (text_addr << 4) + fromhex (*ptr++);
3200 num_segments = 1;
3201
61012eef 3202 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3203 {
3204 ptr += 9;
3205 while (*ptr && *ptr != ';')
3206 data_addr = (data_addr << 4) + fromhex (*ptr++);
3207 num_segments++;
3208 }
c906108c
SS
3209 }
3210 else
3211 lose = 1;
3212
3213 if (lose)
8a3fe4f8 3214 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3215 else if (*ptr != '\0')
3216 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3217
802188a7 3218 offs = ((struct section_offsets *)
a39a16c4 3219 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3220 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3221 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3222
31d99776
DJ
3223 data = get_symfile_segment_data (symfile_objfile->obfd);
3224 do_segments = (data != NULL);
3225 do_sections = num_segments == 0;
c906108c 3226
28c32713 3227 if (num_segments > 0)
31d99776 3228 {
31d99776
DJ
3229 segments[0] = text_addr;
3230 segments[1] = data_addr;
3231 }
28c32713
JB
3232 /* If we have two segments, we can still try to relocate everything
3233 by assuming that the .text and .data offsets apply to the whole
3234 text and data segments. Convert the offsets given in the packet
3235 to base addresses for symfile_map_offsets_to_segments. */
3236 else if (data && data->num_segments == 2)
3237 {
3238 segments[0] = data->segment_bases[0] + text_addr;
3239 segments[1] = data->segment_bases[1] + data_addr;
3240 num_segments = 2;
3241 }
8d385431
DJ
3242 /* If the object file has only one segment, assume that it is text
3243 rather than data; main programs with no writable data are rare,
3244 but programs with no code are useless. Of course the code might
3245 have ended up in the data segment... to detect that we would need
3246 the permissions here. */
3247 else if (data && data->num_segments == 1)
3248 {
3249 segments[0] = data->segment_bases[0] + text_addr;
3250 num_segments = 1;
3251 }
28c32713
JB
3252 /* There's no way to relocate by segment. */
3253 else
3254 do_segments = 0;
31d99776
DJ
3255
3256 if (do_segments)
3257 {
3258 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3259 offs, num_segments, segments);
3260
3261 if (ret == 0 && !do_sections)
3e43a32a
MS
3262 error (_("Can not handle qOffsets TextSeg "
3263 "response with this symbol file"));
31d99776
DJ
3264
3265 if (ret > 0)
3266 do_sections = 0;
3267 }
c906108c 3268
9ef895d6
DJ
3269 if (data)
3270 free_symfile_segment_data (data);
31d99776
DJ
3271
3272 if (do_sections)
3273 {
3274 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3275
3e43a32a
MS
3276 /* This is a temporary kludge to force data and bss to use the
3277 same offsets because that's what nlmconv does now. The real
3278 solution requires changes to the stub and remote.c that I
3279 don't have time to do right now. */
31d99776
DJ
3280
3281 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3282 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3283 }
c906108c
SS
3284
3285 objfile_relocate (symfile_objfile, offs);
3286}
3287
74531fed
PA
3288/* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3289 threads we know are stopped already. This is used during the
3290 initial remote connection in non-stop mode --- threads that are
3291 reported as already being stopped are left stopped. */
3292
3293static int
3294set_stop_requested_callback (struct thread_info *thread, void *data)
3295{
3296 /* If we have a stop reply for this thread, it must be stopped. */
3297 if (peek_stop_reply (thread->ptid))
3298 set_stop_requested (thread->ptid, 1);
3299
3300 return 0;
3301}
3302
9a7071a8
JB
3303/* Send interrupt_sequence to remote target. */
3304static void
eeae04df 3305send_interrupt_sequence (void)
9a7071a8 3306{
5d93a237
TT
3307 struct remote_state *rs = get_remote_state ();
3308
9a7071a8 3309 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3310 remote_serial_write ("\x03", 1);
9a7071a8 3311 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3312 serial_send_break (rs->remote_desc);
9a7071a8
JB
3313 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3314 {
5d93a237 3315 serial_send_break (rs->remote_desc);
c33e31fd 3316 remote_serial_write ("g", 1);
9a7071a8
JB
3317 }
3318 else
3319 internal_error (__FILE__, __LINE__,
3320 _("Invalid value for interrupt_sequence_mode: %s."),
3321 interrupt_sequence_mode);
3322}
3323
3405876a
PA
3324
3325/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3326 and extract the PTID. Returns NULL_PTID if not found. */
3327
3328static ptid_t
3329stop_reply_extract_thread (char *stop_reply)
3330{
3331 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3332 {
3333 char *p;
3334
3335 /* Txx r:val ; r:val (...) */
3336 p = &stop_reply[3];
3337
3338 /* Look for "register" named "thread". */
3339 while (*p != '\0')
3340 {
3341 char *p1;
3342
3343 p1 = strchr (p, ':');
3344 if (p1 == NULL)
3345 return null_ptid;
3346
3347 if (strncmp (p, "thread", p1 - p) == 0)
3348 return read_ptid (++p1, &p);
3349
3350 p1 = strchr (p, ';');
3351 if (p1 == NULL)
3352 return null_ptid;
3353 p1++;
3354
3355 p = p1;
3356 }
3357 }
3358
3359 return null_ptid;
3360}
3361
b7ea362b
PA
3362/* Determine the remote side's current thread. If we have a stop
3363 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3364 "thread" register we can extract the current thread from. If not,
3365 ask the remote which is the current thread with qC. The former
3366 method avoids a roundtrip. */
3367
3368static ptid_t
3369get_current_thread (char *wait_status)
3370{
3371 ptid_t ptid;
3372
3373 /* Note we don't use remote_parse_stop_reply as that makes use of
3374 the target architecture, which we haven't yet fully determined at
3375 this point. */
3376 if (wait_status != NULL)
3377 ptid = stop_reply_extract_thread (wait_status);
3378 if (ptid_equal (ptid, null_ptid))
3379 ptid = remote_current_thread (inferior_ptid);
3380
3381 return ptid;
3382}
3383
49c62f2e
PA
3384/* Query the remote target for which is the current thread/process,
3385 add it to our tables, and update INFERIOR_PTID. The caller is
3386 responsible for setting the state such that the remote end is ready
3405876a
PA
3387 to return the current thread.
3388
3389 This function is called after handling the '?' or 'vRun' packets,
3390 whose response is a stop reply from which we can also try
3391 extracting the thread. If the target doesn't support the explicit
3392 qC query, we infer the current thread from that stop reply, passed
3393 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3394
3395static void
3405876a 3396add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3397{
3398 struct remote_state *rs = get_remote_state ();
3399 int fake_pid_p = 0;
3405876a 3400 ptid_t ptid = null_ptid;
49c62f2e
PA
3401
3402 inferior_ptid = null_ptid;
3403
b7ea362b
PA
3404 /* Now, if we have thread information, update inferior_ptid. */
3405 ptid = get_current_thread (wait_status);
3405876a 3406
49c62f2e
PA
3407 if (!ptid_equal (ptid, null_ptid))
3408 {
3409 if (!remote_multi_process_p (rs))
3410 fake_pid_p = 1;
3411
3412 inferior_ptid = ptid;
3413 }
3414 else
3415 {
3416 /* Without this, some commands which require an active target
3417 (such as kill) won't work. This variable serves (at least)
3418 double duty as both the pid of the target process (if it has
3419 such), and as a flag indicating that a target is active. */
3420 inferior_ptid = magic_null_ptid;
3421 fake_pid_p = 1;
3422 }
3423
3424 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1);
3425
3426 /* Add the main thread. */
3427 add_thread_silent (inferior_ptid);
3428}
3429
9cbc821d 3430static void
04bd08de 3431remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 3432{
c8d104ad
PA
3433 struct remote_state *rs = get_remote_state ();
3434 struct packet_config *noack_config;
2d717e4f 3435 char *wait_status = NULL;
8621d6a9 3436
23860348 3437 immediate_quit++; /* Allow user to interrupt it. */
522002f9 3438 QUIT;
c906108c 3439
9a7071a8
JB
3440 if (interrupt_on_connect)
3441 send_interrupt_sequence ();
3442
57e12211 3443 /* Ack any packet which the remote side has already sent. */
5d93a237 3444 serial_write (rs->remote_desc, "+", 1);
57e12211 3445
1e51243a
PA
3446 /* Signal other parts that we're going through the initial setup,
3447 and so things may not be stable yet. */
3448 rs->starting_up = 1;
3449
c8d104ad
PA
3450 /* The first packet we send to the target is the optional "supported
3451 packets" request. If the target can answer this, it will tell us
3452 which later probes to skip. */
3453 remote_query_supported ();
3454
d914c394 3455 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 3456 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 3457 remote_set_permissions (target);
d914c394 3458
c8d104ad
PA
3459 /* Next, we possibly activate noack mode.
3460
3461 If the QStartNoAckMode packet configuration is set to AUTO,
3462 enable noack mode if the stub reported a wish for it with
3463 qSupported.
3464
3465 If set to TRUE, then enable noack mode even if the stub didn't
3466 report it in qSupported. If the stub doesn't reply OK, the
3467 session ends with an error.
3468
3469 If FALSE, then don't activate noack mode, regardless of what the
3470 stub claimed should be the default with qSupported. */
3471
3472 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 3473 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
3474 {
3475 putpkt ("QStartNoAckMode");
3476 getpkt (&rs->buf, &rs->buf_size, 0);
3477 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3478 rs->noack_mode = 1;
3479 }
3480
04bd08de 3481 if (extended_p)
5fe04517
PA
3482 {
3483 /* Tell the remote that we are using the extended protocol. */
3484 putpkt ("!");
3485 getpkt (&rs->buf, &rs->buf_size, 0);
3486 }
3487
9b224c5e
PA
3488 /* Let the target know which signals it is allowed to pass down to
3489 the program. */
3490 update_signals_program_target ();
3491
d962ef82
DJ
3492 /* Next, if the target can specify a description, read it. We do
3493 this before anything involving memory or registers. */
3494 target_find_description ();
3495
6c95b8df
PA
3496 /* Next, now that we know something about the target, update the
3497 address spaces in the program spaces. */
3498 update_address_spaces ();
3499
50c71eaf
PA
3500 /* On OSs where the list of libraries is global to all
3501 processes, we fetch them early. */
f5656ead 3502 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 3503 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 3504
74531fed
PA
3505 if (non_stop)
3506 {
4082afcc 3507 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
3508 error (_("Non-stop mode requested, but remote "
3509 "does not support non-stop"));
74531fed
PA
3510
3511 putpkt ("QNonStop:1");
3512 getpkt (&rs->buf, &rs->buf_size, 0);
3513
3514 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3515 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
3516
3517 /* Find about threads and processes the stub is already
3518 controlling. We default to adding them in the running state.
3519 The '?' query below will then tell us about which threads are
3520 stopped. */
e8032dde 3521 remote_update_thread_list (target);
74531fed 3522 }
4082afcc 3523 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
3524 {
3525 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 3526 Request it explicitly. */
74531fed
PA
3527 putpkt ("QNonStop:0");
3528 getpkt (&rs->buf, &rs->buf_size, 0);
3529
3530 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3531 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
3532 }
3533
a0743c90
YQ
3534 /* Upload TSVs regardless of whether the target is running or not. The
3535 remote stub, such as GDBserver, may have some predefined or builtin
3536 TSVs, even if the target is not running. */
8bd200f1 3537 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
3538 {
3539 struct uploaded_tsv *uploaded_tsvs = NULL;
3540
181e3713 3541 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
3542 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3543 }
3544
2d717e4f
DJ
3545 /* Check whether the target is running now. */
3546 putpkt ("?");
3547 getpkt (&rs->buf, &rs->buf_size, 0);
3548
74531fed 3549 if (!non_stop)
2d717e4f 3550 {
e714e1bf
UW
3551 ptid_t ptid;
3552 int fake_pid_p = 0;
3553 struct inferior *inf;
3554
74531fed 3555 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 3556 {
04bd08de 3557 if (!extended_p)
74531fed 3558 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
3559
3560 /* We're connected, but not running. Drop out before we
3561 call start_remote. */
e278ad5b 3562 rs->starting_up = 0;
c35b1492 3563 return;
2d717e4f
DJ
3564 }
3565 else
74531fed 3566 {
74531fed
PA
3567 /* Save the reply for later. */
3568 wait_status = alloca (strlen (rs->buf) + 1);
3569 strcpy (wait_status, rs->buf);
3570 }
3571
b7ea362b 3572 /* Fetch thread list. */
e8032dde 3573 target_update_thread_list ();
b7ea362b 3574
74531fed
PA
3575 /* Let the stub know that we want it to return the thread. */
3576 set_continue_thread (minus_one_ptid);
3577
b7ea362b
PA
3578 if (thread_count () == 0)
3579 {
3580 /* Target has no concept of threads at all. GDB treats
3581 non-threaded target as single-threaded; add a main
3582 thread. */
3583 add_current_inferior_and_thread (wait_status);
3584 }
3585 else
3586 {
3587 /* We have thread information; select the thread the target
3588 says should be current. If we're reconnecting to a
3589 multi-threaded program, this will ideally be the thread
3590 that last reported an event before GDB disconnected. */
3591 inferior_ptid = get_current_thread (wait_status);
3592 if (ptid_equal (inferior_ptid, null_ptid))
3593 {
3594 /* Odd... The target was able to list threads, but not
3595 tell us which thread was current (no "thread"
3596 register in T stop reply?). Just pick the first
3597 thread in the thread list then. */
3598 inferior_ptid = thread_list->ptid;
3599 }
3600 }
74531fed 3601
6e586cc5
YQ
3602 /* init_wait_for_inferior should be called before get_offsets in order
3603 to manage `inserted' flag in bp loc in a correct state.
3604 breakpoint_init_inferior, called from init_wait_for_inferior, set
3605 `inserted' flag to 0, while before breakpoint_re_set, called from
3606 start_remote, set `inserted' flag to 1. In the initialization of
3607 inferior, breakpoint_init_inferior should be called first, and then
3608 breakpoint_re_set can be called. If this order is broken, state of
3609 `inserted' flag is wrong, and cause some problems on breakpoint
3610 manipulation. */
3611 init_wait_for_inferior ();
3612
74531fed
PA
3613 get_offsets (); /* Get text, data & bss offsets. */
3614
d962ef82
DJ
3615 /* If we could not find a description using qXfer, and we know
3616 how to do it some other way, try again. This is not
3617 supported for non-stop; it could be, but it is tricky if
3618 there are no stopped threads when we connect. */
04bd08de 3619 if (remote_read_description_p (target)
f5656ead 3620 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
3621 {
3622 target_clear_description ();
3623 target_find_description ();
3624 }
3625
74531fed
PA
3626 /* Use the previously fetched status. */
3627 gdb_assert (wait_status != NULL);
3628 strcpy (rs->buf, wait_status);
3629 rs->cached_wait_status = 1;
3630
3631 immediate_quit--;
04bd08de 3632 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
3633 }
3634 else
3635 {
68c97600
PA
3636 /* Clear WFI global state. Do this before finding about new
3637 threads and inferiors, and setting the current inferior.
3638 Otherwise we would clear the proceed status of the current
3639 inferior when we want its stop_soon state to be preserved
3640 (see notice_new_inferior). */
3641 init_wait_for_inferior ();
3642
74531fed
PA
3643 /* In non-stop, we will either get an "OK", meaning that there
3644 are no stopped threads at this time; or, a regular stop
3645 reply. In the latter case, there may be more than one thread
3646 stopped --- we pull them all out using the vStopped
3647 mechanism. */
3648 if (strcmp (rs->buf, "OK") != 0)
3649 {
722247f1 3650 struct notif_client *notif = &notif_client_stop;
2d717e4f 3651
722247f1
YQ
3652 /* remote_notif_get_pending_replies acks this one, and gets
3653 the rest out. */
f48ff2a7 3654 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
3655 = remote_notif_parse (notif, rs->buf);
3656 remote_notif_get_pending_events (notif);
c906108c 3657
74531fed
PA
3658 /* Make sure that threads that were stopped remain
3659 stopped. */
3660 iterate_over_threads (set_stop_requested_callback, NULL);
3661 }
2d717e4f 3662
74531fed
PA
3663 if (target_can_async_p ())
3664 target_async (inferior_event_handler, 0);
c906108c 3665
74531fed
PA
3666 if (thread_count () == 0)
3667 {
04bd08de 3668 if (!extended_p)
74531fed 3669 error (_("The target is not running (try extended-remote?)"));
82f73884 3670
c35b1492
PA
3671 /* We're connected, but not running. Drop out before we
3672 call start_remote. */
e278ad5b 3673 rs->starting_up = 0;
c35b1492
PA
3674 return;
3675 }
74531fed
PA
3676
3677 /* Let the stub know that we want it to return the thread. */
c0a2216e 3678
74531fed
PA
3679 /* Force the stub to choose a thread. */
3680 set_general_thread (null_ptid);
c906108c 3681
74531fed
PA
3682 /* Query it. */
3683 inferior_ptid = remote_current_thread (minus_one_ptid);
3684 if (ptid_equal (inferior_ptid, minus_one_ptid))
3685 error (_("remote didn't report the current thread in non-stop mode"));
c906108c 3686
74531fed
PA
3687 get_offsets (); /* Get text, data & bss offsets. */
3688
3689 /* In non-stop mode, any cached wait status will be stored in
3690 the stop reply queue. */
3691 gdb_assert (wait_status == NULL);
f0223081 3692
2455069d 3693 /* Report all signals during attach/startup. */
94bedb42 3694 remote_pass_signals (target, 0, NULL);
74531fed 3695 }
c8d104ad 3696
c8d104ad
PA
3697 /* If we connected to a live target, do some additional setup. */
3698 if (target_has_execution)
3699 {
f4ccffad 3700 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 3701 remote_check_symbols ();
c8d104ad 3702 }
50c71eaf 3703
d5551862
SS
3704 /* Possibly the target has been engaged in a trace run started
3705 previously; find out where things are at. */
8bd200f1 3706 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 3707 {
00bf0b85 3708 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 3709
00bf0b85
SS
3710 if (current_trace_status ()->running)
3711 printf_filtered (_("Trace is already running on the target.\n"));
3712
ab6617cc 3713 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
3714
3715 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
3716 }
3717
1e51243a
PA
3718 /* The thread and inferior lists are now synchronized with the
3719 target, our symbols have been relocated, and we're merged the
3720 target's tracepoints with ours. We're done with basic start
3721 up. */
3722 rs->starting_up = 0;
3723
a25a5a45
PA
3724 /* Maybe breakpoints are global and need to be inserted now. */
3725 if (breakpoints_should_be_inserted_now ())
50c71eaf 3726 insert_breakpoints ();
c906108c
SS
3727}
3728
3729/* Open a connection to a remote debugger.
3730 NAME is the filename used for communication. */
3731
3732static void
014f9477 3733remote_open (const char *name, int from_tty)
c906108c 3734{
75c99385 3735 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
3736}
3737
c906108c
SS
3738/* Open a connection to a remote debugger using the extended
3739 remote gdb protocol. NAME is the filename used for communication. */
3740
3741static void
014f9477 3742extended_remote_open (const char *name, int from_tty)
c906108c 3743{
75c99385 3744 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
3745}
3746
ca4f7f8b
PA
3747/* Reset all packets back to "unknown support". Called when opening a
3748 new connection to a remote target. */
c906108c 3749
d471ea57 3750static void
ca4f7f8b 3751reset_all_packet_configs_support (void)
d471ea57
AC
3752{
3753 int i;
a744cf53 3754
444abaca 3755 for (i = 0; i < PACKET_MAX; i++)
4082afcc 3756 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
3757}
3758
ca4f7f8b
PA
3759/* Initialize all packet configs. */
3760
3761static void
3762init_all_packet_configs (void)
3763{
3764 int i;
3765
3766 for (i = 0; i < PACKET_MAX; i++)
3767 {
3768 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
3769 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3770 }
3771}
3772
23860348 3773/* Symbol look-up. */
dc8acb97
MS
3774
3775static void
36d25514 3776remote_check_symbols (void)
dc8acb97 3777{
d01949b6 3778 struct remote_state *rs = get_remote_state ();
dc8acb97 3779 char *msg, *reply, *tmp;
3b7344d5 3780 struct bound_minimal_symbol sym;
dc8acb97
MS
3781 int end;
3782
63154eca
PA
3783 /* The remote side has no concept of inferiors that aren't running
3784 yet, it only knows about running processes. If we're connected
3785 but our current inferior is not running, we should not invite the
3786 remote target to request symbol lookups related to its
3787 (unrelated) current process. */
3788 if (!target_has_execution)
3789 return;
3790
4082afcc 3791 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
3792 return;
3793
63154eca
PA
3794 /* Make sure the remote is pointing at the right process. Note
3795 there's no way to select "no process". */
3c9c4b83
PA
3796 set_general_process ();
3797
6d820c5c
DJ
3798 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3799 because we need both at the same time. */
ea9c271d 3800 msg = alloca (get_remote_packet_size ());
6d820c5c 3801
23860348 3802 /* Invite target to request symbol lookups. */
dc8acb97
MS
3803
3804 putpkt ("qSymbol::");
6d820c5c
DJ
3805 getpkt (&rs->buf, &rs->buf_size, 0);
3806 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2e9f7625 3807 reply = rs->buf;
dc8acb97 3808
61012eef 3809 while (startswith (reply, "qSymbol:"))
dc8acb97 3810 {
77e371c0
TT
3811 struct bound_minimal_symbol sym;
3812
dc8acb97 3813 tmp = &reply[8];
cfd77fa1 3814 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
3815 msg[end] = '\0';
3816 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 3817 if (sym.minsym == NULL)
ea9c271d 3818 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 3819 else
2bbe3cc1 3820 {
f5656ead 3821 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 3822 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
3823
3824 /* If this is a function address, return the start of code
3825 instead of any data function descriptor. */
f5656ead 3826 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
3827 sym_addr,
3828 &current_target);
3829
3830 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 3831 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
3832 }
3833
dc8acb97 3834 putpkt (msg);
6d820c5c 3835 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3836 reply = rs->buf;
dc8acb97
MS
3837 }
3838}
3839
9db8d71f 3840static struct serial *
baa336ce 3841remote_serial_open (const char *name)
9db8d71f
DJ
3842{
3843 static int udp_warning = 0;
3844
3845 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3846 of in ser-tcp.c, because it is the remote protocol assuming that the
3847 serial connection is reliable and not the serial connection promising
3848 to be. */
61012eef 3849 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 3850 {
3e43a32a
MS
3851 warning (_("The remote protocol may be unreliable over UDP.\n"
3852 "Some events may be lost, rendering further debugging "
3853 "impossible."));
9db8d71f
DJ
3854 udp_warning = 1;
3855 }
3856
3857 return serial_open (name);
3858}
3859
d914c394
SS
3860/* Inform the target of our permission settings. The permission flags
3861 work without this, but if the target knows the settings, it can do
3862 a couple things. First, it can add its own check, to catch cases
3863 that somehow manage to get by the permissions checks in target
3864 methods. Second, if the target is wired to disallow particular
3865 settings (for instance, a system in the field that is not set up to
3866 be able to stop at a breakpoint), it can object to any unavailable
3867 permissions. */
3868
3869void
c378d69d 3870remote_set_permissions (struct target_ops *self)
d914c394
SS
3871{
3872 struct remote_state *rs = get_remote_state ();
3873
bba74b36
YQ
3874 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3875 "WriteReg:%x;WriteMem:%x;"
3876 "InsertBreak:%x;InsertTrace:%x;"
3877 "InsertFastTrace:%x;Stop:%x",
3878 may_write_registers, may_write_memory,
3879 may_insert_breakpoints, may_insert_tracepoints,
3880 may_insert_fast_tracepoints, may_stop);
d914c394
SS
3881 putpkt (rs->buf);
3882 getpkt (&rs->buf, &rs->buf_size, 0);
3883
3884 /* If the target didn't like the packet, warn the user. Do not try
3885 to undo the user's settings, that would just be maddening. */
3886 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 3887 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
3888}
3889
be2a5f71
DJ
3890/* This type describes each known response to the qSupported
3891 packet. */
3892struct protocol_feature
3893{
3894 /* The name of this protocol feature. */
3895 const char *name;
3896
3897 /* The default for this protocol feature. */
3898 enum packet_support default_support;
3899
3900 /* The function to call when this feature is reported, or after
3901 qSupported processing if the feature is not supported.
3902 The first argument points to this structure. The second
3903 argument indicates whether the packet requested support be
3904 enabled, disabled, or probed (or the default, if this function
3905 is being called at the end of processing and this feature was
3906 not reported). The third argument may be NULL; if not NULL, it
3907 is a NUL-terminated string taken from the packet following
3908 this feature's name and an equals sign. */
3909 void (*func) (const struct protocol_feature *, enum packet_support,
3910 const char *);
3911
3912 /* The corresponding packet for this feature. Only used if
3913 FUNC is remote_supported_packet. */
3914 int packet;
3915};
3916
be2a5f71
DJ
3917static void
3918remote_supported_packet (const struct protocol_feature *feature,
3919 enum packet_support support,
3920 const char *argument)
3921{
3922 if (argument)
3923 {
3924 warning (_("Remote qSupported response supplied an unexpected value for"
3925 " \"%s\"."), feature->name);
3926 return;
3927 }
3928
4082afcc 3929 remote_protocol_packets[feature->packet].support = support;
be2a5f71 3930}
be2a5f71
DJ
3931
3932static void
3933remote_packet_size (const struct protocol_feature *feature,
3934 enum packet_support support, const char *value)
3935{
3936 struct remote_state *rs = get_remote_state ();
3937
3938 int packet_size;
3939 char *value_end;
3940
3941 if (support != PACKET_ENABLE)
3942 return;
3943
3944 if (value == NULL || *value == '\0')
3945 {
3946 warning (_("Remote target reported \"%s\" without a size."),
3947 feature->name);
3948 return;
3949 }
3950
3951 errno = 0;
3952 packet_size = strtol (value, &value_end, 16);
3953 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3954 {
3955 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3956 feature->name, value);
3957 return;
3958 }
3959
3960 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3961 {
3962 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3963 packet_size, MAX_REMOTE_PACKET_SIZE);
3964 packet_size = MAX_REMOTE_PACKET_SIZE;
3965 }
3966
3967 /* Record the new maximum packet size. */
3968 rs->explicit_packet_size = packet_size;
3969}
3970
dc473cfb 3971static const struct protocol_feature remote_protocol_features[] = {
0876f84a 3972 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 3973 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 3974 PACKET_qXfer_auxv },
23181151
DJ
3975 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3976 PACKET_qXfer_features },
cfa9d6d9
DJ
3977 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3978 PACKET_qXfer_libraries },
2268b414
JK
3979 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
3980 PACKET_qXfer_libraries_svr4 },
ced63ec0 3981 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 3982 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 3983 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 3984 PACKET_qXfer_memory_map },
4de6483e
UW
3985 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3986 PACKET_qXfer_spu_read },
3987 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3988 PACKET_qXfer_spu_write },
07e059b5
VP
3989 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3990 PACKET_qXfer_osdata },
dc146f7c
VP
3991 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
3992 PACKET_qXfer_threads },
b3b9301e
PA
3993 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
3994 PACKET_qXfer_traceframe_info },
89be2091
DJ
3995 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3996 PACKET_QPassSignals },
9b224c5e
PA
3997 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
3998 PACKET_QProgramSignals },
a6f3e723
SL
3999 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4000 PACKET_QStartNoAckMode },
4082afcc
PA
4001 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4002 PACKET_multiprocess_feature },
4003 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4004 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4005 PACKET_qXfer_siginfo_read },
4006 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4007 PACKET_qXfer_siginfo_write },
4082afcc 4008 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4009 PACKET_ConditionalTracepoints },
4082afcc 4010 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4011 PACKET_ConditionalBreakpoints },
4082afcc 4012 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4013 PACKET_BreakpointCommands },
4082afcc 4014 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4015 PACKET_FastTracepoints },
4082afcc 4016 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4017 PACKET_StaticTracepoints },
4082afcc 4018 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4019 PACKET_InstallInTrace},
4082afcc
PA
4020 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4021 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4022 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4023 PACKET_bc },
4024 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4025 PACKET_bs },
409873ef
SS
4026 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4027 PACKET_TracepointSource },
d914c394
SS
4028 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4029 PACKET_QAllow },
4082afcc
PA
4030 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4031 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4032 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4033 PACKET_qXfer_fdpic },
169081d0
TG
4034 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4035 PACKET_qXfer_uib },
03583c20
UW
4036 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4037 PACKET_QDisableRandomization },
d1feda86 4038 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4039 { "QTBuffer:size", PACKET_DISABLE,
4040 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4041 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4042 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4043 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4044 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4045 PACKET_qXfer_btrace },
4046 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4047 PACKET_qXfer_btrace_conf },
4048 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4049 PACKET_Qbtrace_conf_bts_size },
4050 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c
GB
4051 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4052 { "vFile:fstat", PACKET_DISABLE, remote_supported_packet,
4053 PACKET_vFile_fstat },
be2a5f71
DJ
4054};
4055
c8d5aac9
L
4056static char *remote_support_xml;
4057
4058/* Register string appended to "xmlRegisters=" in qSupported query. */
4059
4060void
6e39997a 4061register_remote_support_xml (const char *xml)
c8d5aac9
L
4062{
4063#if defined(HAVE_LIBEXPAT)
4064 if (remote_support_xml == NULL)
c4f7c687 4065 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4066 else
4067 {
4068 char *copy = xstrdup (remote_support_xml + 13);
4069 char *p = strtok (copy, ",");
4070
4071 do
4072 {
4073 if (strcmp (p, xml) == 0)
4074 {
4075 /* already there */
4076 xfree (copy);
4077 return;
4078 }
4079 }
4080 while ((p = strtok (NULL, ",")) != NULL);
4081 xfree (copy);
4082
94b0dee1
PA
4083 remote_support_xml = reconcat (remote_support_xml,
4084 remote_support_xml, ",", xml,
4085 (char *) NULL);
c8d5aac9
L
4086 }
4087#endif
4088}
4089
4090static char *
4091remote_query_supported_append (char *msg, const char *append)
4092{
4093 if (msg)
94b0dee1 4094 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4095 else
4096 return xstrdup (append);
4097}
4098
be2a5f71
DJ
4099static void
4100remote_query_supported (void)
4101{
4102 struct remote_state *rs = get_remote_state ();
4103 char *next;
4104 int i;
4105 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4106
4107 /* The packet support flags are handled differently for this packet
4108 than for most others. We treat an error, a disabled packet, and
4109 an empty response identically: any features which must be reported
4110 to be used will be automatically disabled. An empty buffer
4111 accomplishes this, since that is also the representation for a list
4112 containing no features. */
4113
4114 rs->buf[0] = 0;
4082afcc 4115 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4116 {
c8d5aac9 4117 char *q = NULL;
94b0dee1 4118 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4119
901f9912 4120 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4121
f7e6eed5
PA
4122 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4123 q = remote_query_supported_append (q, "swbreak+");
4124 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4125 q = remote_query_supported_append (q, "hwbreak+");
4126
c8d5aac9
L
4127 if (remote_support_xml)
4128 q = remote_query_supported_append (q, remote_support_xml);
4129
dde08ee1
PA
4130 q = remote_query_supported_append (q, "qRelocInsn+");
4131
4132 q = reconcat (q, "qSupported:", q, (char *) NULL);
4133 putpkt (q);
82f73884 4134
94b0dee1
PA
4135 do_cleanups (old_chain);
4136
be2a5f71
DJ
4137 getpkt (&rs->buf, &rs->buf_size, 0);
4138
4139 /* If an error occured, warn, but do not return - just reset the
4140 buffer to empty and go on to disable features. */
4141 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4142 == PACKET_ERROR)
4143 {
4144 warning (_("Remote failure reply: %s"), rs->buf);
4145 rs->buf[0] = 0;
4146 }
4147 }
4148
4149 memset (seen, 0, sizeof (seen));
4150
4151 next = rs->buf;
4152 while (*next)
4153 {
4154 enum packet_support is_supported;
4155 char *p, *end, *name_end, *value;
4156
4157 /* First separate out this item from the rest of the packet. If
4158 there's another item after this, we overwrite the separator
4159 (terminated strings are much easier to work with). */
4160 p = next;
4161 end = strchr (p, ';');
4162 if (end == NULL)
4163 {
4164 end = p + strlen (p);
4165 next = end;
4166 }
4167 else
4168 {
89be2091
DJ
4169 *end = '\0';
4170 next = end + 1;
4171
be2a5f71
DJ
4172 if (end == p)
4173 {
4174 warning (_("empty item in \"qSupported\" response"));
4175 continue;
4176 }
be2a5f71
DJ
4177 }
4178
4179 name_end = strchr (p, '=');
4180 if (name_end)
4181 {
4182 /* This is a name=value entry. */
4183 is_supported = PACKET_ENABLE;
4184 value = name_end + 1;
4185 *name_end = '\0';
4186 }
4187 else
4188 {
4189 value = NULL;
4190 switch (end[-1])
4191 {
4192 case '+':
4193 is_supported = PACKET_ENABLE;
4194 break;
4195
4196 case '-':
4197 is_supported = PACKET_DISABLE;
4198 break;
4199
4200 case '?':
4201 is_supported = PACKET_SUPPORT_UNKNOWN;
4202 break;
4203
4204 default:
3e43a32a
MS
4205 warning (_("unrecognized item \"%s\" "
4206 "in \"qSupported\" response"), p);
be2a5f71
DJ
4207 continue;
4208 }
4209 end[-1] = '\0';
4210 }
4211
4212 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4213 if (strcmp (remote_protocol_features[i].name, p) == 0)
4214 {
4215 const struct protocol_feature *feature;
4216
4217 seen[i] = 1;
4218 feature = &remote_protocol_features[i];
4219 feature->func (feature, is_supported, value);
4220 break;
4221 }
4222 }
4223
4224 /* If we increased the packet size, make sure to increase the global
4225 buffer size also. We delay this until after parsing the entire
4226 qSupported packet, because this is the same buffer we were
4227 parsing. */
4228 if (rs->buf_size < rs->explicit_packet_size)
4229 {
4230 rs->buf_size = rs->explicit_packet_size;
4231 rs->buf = xrealloc (rs->buf, rs->buf_size);
4232 }
4233
4234 /* Handle the defaults for unmentioned features. */
4235 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4236 if (!seen[i])
4237 {
4238 const struct protocol_feature *feature;
4239
4240 feature = &remote_protocol_features[i];
4241 feature->func (feature, feature->default_support, NULL);
4242 }
4243}
4244
78a095c3
JK
4245/* Remove any of the remote.c targets from target stack. Upper targets depend
4246 on it so remove them first. */
4247
4248static void
4249remote_unpush_target (void)
4250{
4251 pop_all_targets_above (process_stratum - 1);
4252}
be2a5f71 4253
c906108c 4254static void
014f9477 4255remote_open_1 (const char *name, int from_tty,
3e43a32a 4256 struct target_ops *target, int extended_p)
c906108c 4257{
d01949b6 4258 struct remote_state *rs = get_remote_state ();
a6f3e723 4259
c906108c 4260 if (name == 0)
8a3fe4f8 4261 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4262 "serial device is attached to the remote system\n"
8a3fe4f8 4263 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4264
23860348 4265 /* See FIXME above. */
c6ebd6cf 4266 if (!target_async_permitted)
92d1e331 4267 wait_forever_enabled_p = 1;
6426a772 4268
2d717e4f 4269 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4270 Ask this question first, before target_preopen has a chance to kill
4271 anything. */
5d93a237 4272 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4273 {
78a095c3
JK
4274 if (from_tty
4275 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4276 error (_("Still connected."));
4277 }
4278
78a095c3 4279 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4280 target_preopen (from_tty);
4281
89be2091 4282 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4283 xfree (rs->last_pass_packet);
4284 rs->last_pass_packet = NULL;
89be2091 4285
9b224c5e
PA
4286 /* Make sure we send the program signals list the next time we
4287 resume. */
5e4a05c4
TT
4288 xfree (rs->last_program_signals_packet);
4289 rs->last_program_signals_packet = NULL;
9b224c5e 4290
ad9a8f3f 4291 remote_fileio_reset ();
1dd41f16
NS
4292 reopen_exec_file ();
4293 reread_symbols ();
4294
5d93a237
TT
4295 rs->remote_desc = remote_serial_open (name);
4296 if (!rs->remote_desc)
c906108c
SS
4297 perror_with_name (name);
4298
4299 if (baud_rate != -1)
4300 {
5d93a237 4301 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4302 {
9b74d5d3
KB
4303 /* The requested speed could not be set. Error out to
4304 top level after closing remote_desc. Take care to
4305 set remote_desc to NULL to avoid closing remote_desc
4306 more than once. */
5d93a237
TT
4307 serial_close (rs->remote_desc);
4308 rs->remote_desc = NULL;
c906108c
SS
4309 perror_with_name (name);
4310 }
4311 }
4312
5d93a237 4313 serial_raw (rs->remote_desc);
c906108c
SS
4314
4315 /* If there is something sitting in the buffer we might take it as a
4316 response to a command, which would be bad. */
5d93a237 4317 serial_flush_input (rs->remote_desc);
c906108c
SS
4318
4319 if (from_tty)
4320 {
4321 puts_filtered ("Remote debugging using ");
4322 puts_filtered (name);
4323 puts_filtered ("\n");
4324 }
23860348 4325 push_target (target); /* Switch to using remote target now. */
c906108c 4326
74531fed
PA
4327 /* Register extra event sources in the event loop. */
4328 remote_async_inferior_event_token
4329 = create_async_event_handler (remote_async_inferior_event_handler,
4330 NULL);
5965e028 4331 rs->notif_state = remote_notif_state_allocate ();
74531fed 4332
be2a5f71
DJ
4333 /* Reset the target state; these things will be queried either by
4334 remote_query_supported or as they are needed. */
ca4f7f8b 4335 reset_all_packet_configs_support ();
74531fed 4336 rs->cached_wait_status = 0;
be2a5f71 4337 rs->explicit_packet_size = 0;
a6f3e723 4338 rs->noack_mode = 0;
82f73884 4339 rs->extended = extended_p;
e24a49d8 4340 rs->waiting_for_stop_reply = 0;
3a29589a 4341 rs->ctrlc_pending_p = 0;
802188a7 4342
47f8a51d
TT
4343 rs->general_thread = not_sent_ptid;
4344 rs->continue_thread = not_sent_ptid;
262e1174 4345 rs->remote_traceframe_number = -1;
c906108c 4346
9d1f7ab2 4347 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
4348 rs->use_threadinfo_query = 1;
4349 rs->use_threadextra_query = 1;
9d1f7ab2 4350
c6ebd6cf 4351 if (target_async_permitted)
92d1e331 4352 {
23860348 4353 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4354 remote_async_terminal_ours_p = 1;
4355
4356 /* FIXME: cagney/1999-09-23: During the initial connection it is
4357 assumed that the target is already ready and able to respond to
0df8b418 4358 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4359 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4360 around this. Eventually a mechanism that allows
92d1e331 4361 wait_for_inferior() to expect/get timeouts will be
23860348 4362 implemented. */
92d1e331
DJ
4363 wait_forever_enabled_p = 0;
4364 }
4365
23860348 4366 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4367 no_shared_libraries (NULL, 0);
f78f6cf1 4368
74531fed
PA
4369 /* Start afresh. */
4370 init_thread_list ();
4371
36918e70 4372 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4373 target (we'd otherwise be in an inconsistent state) and then
4374 propogate the error on up the exception chain. This ensures that
4375 the caller doesn't stumble along blindly assuming that the
4376 function succeeded. The CLI doesn't have this problem but other
4377 UI's, such as MI do.
36918e70
AC
4378
4379 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4380 this function should return an error indication letting the
ce2826aa 4381 caller restore the previous state. Unfortunately the command
36918e70
AC
4382 ``target remote'' is directly wired to this function making that
4383 impossible. On a positive note, the CLI side of this problem has
4384 been fixed - the function set_cmd_context() makes it possible for
4385 all the ``target ....'' commands to share a common callback
4386 function. See cli-dump.c. */
109c3e39 4387 {
2d717e4f 4388
492d29ea 4389 TRY
04bd08de
TT
4390 {
4391 remote_start_remote (from_tty, target, extended_p);
4392 }
492d29ea 4393 CATCH (ex, RETURN_MASK_ALL)
109c3e39 4394 {
c8d104ad
PA
4395 /* Pop the partially set up target - unless something else did
4396 already before throwing the exception. */
5d93a237 4397 if (rs->remote_desc != NULL)
78a095c3 4398 remote_unpush_target ();
c6ebd6cf 4399 if (target_async_permitted)
109c3e39
AC
4400 wait_forever_enabled_p = 1;
4401 throw_exception (ex);
4402 }
492d29ea 4403 END_CATCH
109c3e39 4404 }
c906108c 4405
f4abbc16
MM
4406 remote_btrace_reset ();
4407
c6ebd6cf 4408 if (target_async_permitted)
92d1e331 4409 wait_forever_enabled_p = 1;
43ff13b4
JM
4410}
4411
c906108c
SS
4412/* This takes a program previously attached to and detaches it. After
4413 this is done, GDB can be used to debug some other program. We
4414 better not have left any breakpoints in the target program or it'll
4415 die when it hits one. */
4416
4417static void
52554a0e 4418remote_detach_1 (const char *args, int from_tty, int extended)
c906108c 4419{
82f73884 4420 int pid = ptid_get_pid (inferior_ptid);
d01949b6 4421 struct remote_state *rs = get_remote_state ();
c906108c
SS
4422
4423 if (args)
8a3fe4f8 4424 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 4425
2d717e4f
DJ
4426 if (!target_has_execution)
4427 error (_("No process to detach from."));
4428
7cee1e54
PA
4429 if (from_tty)
4430 {
4431 char *exec_file = get_exec_file (0);
4432 if (exec_file == NULL)
4433 exec_file = "";
4434 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4435 target_pid_to_str (pid_to_ptid (pid)));
4436 gdb_flush (gdb_stdout);
4437 }
4438
c906108c 4439 /* Tell the remote target to detach. */
82f73884 4440 if (remote_multi_process_p (rs))
bba74b36 4441 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
82f73884
PA
4442 else
4443 strcpy (rs->buf, "D");
4444
4ddda9b5
PA
4445 putpkt (rs->buf);
4446 getpkt (&rs->buf, &rs->buf_size, 0);
4447
82f73884
PA
4448 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4449 ;
4450 else if (rs->buf[0] == '\0')
4451 error (_("Remote doesn't know how to detach"));
4452 else
4ddda9b5 4453 error (_("Can't detach process."));
c906108c 4454
7cee1e54
PA
4455 if (from_tty && !extended)
4456 puts_filtered (_("Ending remote debugging.\n"));
82f73884 4457
82f73884 4458 target_mourn_inferior ();
2d717e4f
DJ
4459}
4460
4461static void
52554a0e 4462remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f
DJ
4463{
4464 remote_detach_1 (args, from_tty, 0);
4465}
4466
4467static void
52554a0e 4468extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f
DJ
4469{
4470 remote_detach_1 (args, from_tty, 1);
c906108c
SS
4471}
4472
6ad8ae5c
DJ
4473/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4474
43ff13b4 4475static void
fee354ee 4476remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 4477{
43ff13b4 4478 if (args)
2d717e4f 4479 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 4480
2d717e4f
DJ
4481 /* Make sure we unpush even the extended remote targets; mourn
4482 won't do it. So call remote_mourn_1 directly instead of
4483 target_mourn_inferior. */
4484 remote_mourn_1 (target);
4485
43ff13b4
JM
4486 if (from_tty)
4487 puts_filtered ("Ending remote debugging.\n");
4488}
4489
2d717e4f
DJ
4490/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4491 be chatty about it. */
4492
4493static void
c0939df1
TT
4494extended_remote_attach_1 (struct target_ops *target, const char *args,
4495 int from_tty)
2d717e4f
DJ
4496{
4497 struct remote_state *rs = get_remote_state ();
be86555c 4498 int pid;
96ef3384 4499 char *wait_status = NULL;
2d717e4f 4500
74164c56 4501 pid = parse_pid_to_attach (args);
2d717e4f 4502
74164c56
JK
4503 /* Remote PID can be freely equal to getpid, do not check it here the same
4504 way as in other targets. */
2d717e4f 4505
4082afcc 4506 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
4507 error (_("This target does not support attaching to a process"));
4508
7cee1e54
PA
4509 if (from_tty)
4510 {
4511 char *exec_file = get_exec_file (0);
4512
4513 if (exec_file)
4514 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4515 target_pid_to_str (pid_to_ptid (pid)));
4516 else
4517 printf_unfiltered (_("Attaching to %s\n"),
4518 target_pid_to_str (pid_to_ptid (pid)));
4519
4520 gdb_flush (gdb_stdout);
4521 }
4522
bba74b36 4523 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
4524 putpkt (rs->buf);
4525 getpkt (&rs->buf, &rs->buf_size, 0);
4526
4082afcc
PA
4527 switch (packet_ok (rs->buf,
4528 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 4529 {
4082afcc 4530 case PACKET_OK:
74531fed
PA
4531 if (!non_stop)
4532 {
4533 /* Save the reply for later. */
4534 wait_status = alloca (strlen (rs->buf) + 1);
4535 strcpy (wait_status, rs->buf);
4536 }
4537 else if (strcmp (rs->buf, "OK") != 0)
4538 error (_("Attaching to %s failed with: %s"),
4539 target_pid_to_str (pid_to_ptid (pid)),
4540 rs->buf);
4082afcc
PA
4541 break;
4542 case PACKET_UNKNOWN:
4543 error (_("This target does not support attaching to a process"));
4544 default:
4545 error (_("Attaching to %s failed"),
4546 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 4547 }
2d717e4f 4548
49c62f2e 4549 set_current_inferior (remote_add_inferior (0, pid, 1));
bad34192 4550
2d717e4f 4551 inferior_ptid = pid_to_ptid (pid);
79d7f229 4552
bad34192
PA
4553 if (non_stop)
4554 {
4555 struct thread_info *thread;
79d7f229 4556
bad34192 4557 /* Get list of threads. */
e8032dde 4558 remote_update_thread_list (target);
82f73884 4559
bad34192
PA
4560 thread = first_thread_of_process (pid);
4561 if (thread)
4562 inferior_ptid = thread->ptid;
4563 else
4564 inferior_ptid = pid_to_ptid (pid);
4565
4566 /* Invalidate our notion of the remote current thread. */
47f8a51d 4567 record_currthread (rs, minus_one_ptid);
bad34192 4568 }
74531fed 4569 else
bad34192
PA
4570 {
4571 /* Now, if we have thread information, update inferior_ptid. */
4572 inferior_ptid = remote_current_thread (inferior_ptid);
4573
4574 /* Add the main thread to the thread list. */
4575 add_thread_silent (inferior_ptid);
4576 }
c0a2216e 4577
96ef3384
UW
4578 /* Next, if the target can specify a description, read it. We do
4579 this before anything involving memory or registers. */
4580 target_find_description ();
4581
74531fed
PA
4582 if (!non_stop)
4583 {
4584 /* Use the previously fetched status. */
4585 gdb_assert (wait_status != NULL);
4586
4587 if (target_can_async_p ())
4588 {
722247f1
YQ
4589 struct notif_event *reply
4590 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 4591
722247f1 4592 push_stop_reply ((struct stop_reply *) reply);
74531fed
PA
4593
4594 target_async (inferior_event_handler, 0);
4595 }
4596 else
4597 {
4598 gdb_assert (wait_status != NULL);
4599 strcpy (rs->buf, wait_status);
4600 rs->cached_wait_status = 1;
4601 }
4602 }
4603 else
4604 gdb_assert (wait_status == NULL);
2d717e4f
DJ
4605}
4606
4607static void
c0939df1 4608extended_remote_attach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4609{
136d6dae 4610 extended_remote_attach_1 (ops, args, from_tty);
2d717e4f
DJ
4611}
4612
b9c1d481
AS
4613/* Implementation of the to_post_attach method. */
4614
4615static void
4616extended_remote_post_attach (struct target_ops *ops, int pid)
4617{
4618 /* In certain cases GDB might not have had the chance to start
4619 symbol lookup up until now. This could happen if the debugged
4620 binary is not using shared libraries, the vsyscall page is not
4621 present (on Linux) and the binary itself hadn't changed since the
4622 debugging process was started. */
4623 if (symfile_objfile != NULL)
4624 remote_check_symbols();
4625}
4626
c906108c 4627\f
506fb367
DJ
4628/* Check for the availability of vCont. This function should also check
4629 the response. */
c906108c
SS
4630
4631static void
6d820c5c 4632remote_vcont_probe (struct remote_state *rs)
c906108c 4633{
2e9f7625 4634 char *buf;
6d820c5c 4635
2e9f7625
DJ
4636 strcpy (rs->buf, "vCont?");
4637 putpkt (rs->buf);
6d820c5c 4638 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4639 buf = rs->buf;
c906108c 4640
506fb367 4641 /* Make sure that the features we assume are supported. */
61012eef 4642 if (startswith (buf, "vCont"))
506fb367
DJ
4643 {
4644 char *p = &buf[5];
4645 int support_s, support_S, support_c, support_C;
4646
4647 support_s = 0;
4648 support_S = 0;
4649 support_c = 0;
4650 support_C = 0;
d458bd84 4651 rs->supports_vCont.t = 0;
c1e36e3e 4652 rs->supports_vCont.r = 0;
506fb367
DJ
4653 while (p && *p == ';')
4654 {
4655 p++;
4656 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4657 support_s = 1;
4658 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4659 support_S = 1;
4660 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4661 support_c = 1;
4662 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4663 support_C = 1;
74531fed 4664 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 4665 rs->supports_vCont.t = 1;
c1e36e3e
PA
4666 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4667 rs->supports_vCont.r = 1;
506fb367
DJ
4668
4669 p = strchr (p, ';');
4670 }
c906108c 4671
506fb367
DJ
4672 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4673 BUF will make packet_ok disable the packet. */
4674 if (!support_s || !support_S || !support_c || !support_C)
4675 buf[0] = 0;
4676 }
c906108c 4677
444abaca 4678 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 4679}
c906108c 4680
0d8f58ca
PA
4681/* Helper function for building "vCont" resumptions. Write a
4682 resumption to P. ENDP points to one-passed-the-end of the buffer
4683 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4684 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4685 resumed thread should be single-stepped and/or signalled. If PTID
4686 equals minus_one_ptid, then all threads are resumed; if PTID
4687 represents a process, then all threads of the process are resumed;
4688 the thread to be stepped and/or signalled is given in the global
4689 INFERIOR_PTID. */
4690
4691static char *
4692append_resumption (char *p, char *endp,
2ea28649 4693 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
4694{
4695 struct remote_state *rs = get_remote_state ();
4696
a493e3e2 4697 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 4698 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
4699 else if (step
4700 /* GDB is willing to range step. */
4701 && use_range_stepping
4702 /* Target supports range stepping. */
4703 && rs->supports_vCont.r
4704 /* We don't currently support range stepping multiple
4705 threads with a wildcard (though the protocol allows it,
4706 so stubs shouldn't make an active effort to forbid
4707 it). */
4708 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4709 {
4710 struct thread_info *tp;
4711
4712 if (ptid_equal (ptid, minus_one_ptid))
4713 {
4714 /* If we don't know about the target thread's tid, then
4715 we're resuming magic_null_ptid (see caller). */
4716 tp = find_thread_ptid (magic_null_ptid);
4717 }
4718 else
4719 tp = find_thread_ptid (ptid);
4720 gdb_assert (tp != NULL);
4721
4722 if (tp->control.may_range_step)
4723 {
4724 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4725
4726 p += xsnprintf (p, endp - p, ";r%s,%s",
4727 phex_nz (tp->control.step_range_start,
4728 addr_size),
4729 phex_nz (tp->control.step_range_end,
4730 addr_size));
4731 }
4732 else
4733 p += xsnprintf (p, endp - p, ";s");
4734 }
0d8f58ca
PA
4735 else if (step)
4736 p += xsnprintf (p, endp - p, ";s");
a493e3e2 4737 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
4738 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4739 else
4740 p += xsnprintf (p, endp - p, ";c");
4741
4742 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4743 {
4744 ptid_t nptid;
4745
4746 /* All (-1) threads of process. */
ba348170 4747 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
4748
4749 p += xsnprintf (p, endp - p, ":");
4750 p = write_ptid (p, endp, nptid);
4751 }
4752 else if (!ptid_equal (ptid, minus_one_ptid))
4753 {
4754 p += xsnprintf (p, endp - p, ":");
4755 p = write_ptid (p, endp, ptid);
4756 }
4757
4758 return p;
4759}
4760
e5ef252a
PA
4761/* Append a vCont continue-with-signal action for threads that have a
4762 non-zero stop signal. */
4763
4764static char *
4765append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4766{
4767 struct thread_info *thread;
4768
034f788c 4769 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
4770 if (ptid_match (thread->ptid, ptid)
4771 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 4772 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
4773 {
4774 p = append_resumption (p, endp, thread->ptid,
4775 0, thread->suspend.stop_signal);
4776 thread->suspend.stop_signal = GDB_SIGNAL_0;
4777 }
4778
4779 return p;
4780}
4781
506fb367
DJ
4782/* Resume the remote inferior by using a "vCont" packet. The thread
4783 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
4784 resumed thread should be single-stepped and/or signalled. If PTID
4785 equals minus_one_ptid, then all threads are resumed; the thread to
4786 be stepped and/or signalled is given in the global INFERIOR_PTID.
4787 This function returns non-zero iff it resumes the inferior.
44eaed12 4788
506fb367
DJ
4789 This function issues a strict subset of all possible vCont commands at the
4790 moment. */
44eaed12 4791
506fb367 4792static int
2ea28649 4793remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
4794{
4795 struct remote_state *rs = get_remote_state ();
82f73884
PA
4796 char *p;
4797 char *endp;
44eaed12 4798
4082afcc 4799 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 4800 remote_vcont_probe (rs);
44eaed12 4801
4082afcc 4802 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 4803 return 0;
44eaed12 4804
82f73884
PA
4805 p = rs->buf;
4806 endp = rs->buf + get_remote_packet_size ();
4807
506fb367
DJ
4808 /* If we could generate a wider range of packets, we'd have to worry
4809 about overflowing BUF. Should there be a generic
4810 "multi-part-packet" packet? */
4811
0d8f58ca
PA
4812 p += xsnprintf (p, endp - p, "vCont");
4813
79d7f229 4814 if (ptid_equal (ptid, magic_null_ptid))
c906108c 4815 {
79d7f229
PA
4816 /* MAGIC_NULL_PTID means that we don't have any active threads,
4817 so we don't have any TID numbers the inferior will
4818 understand. Make sure to only send forms that do not specify
4819 a TID. */
a9cbf802 4820 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 4821 }
0d8f58ca 4822 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 4823 {
0d8f58ca
PA
4824 /* Resume all threads (of all processes, or of a single
4825 process), with preference for INFERIOR_PTID. This assumes
4826 inferior_ptid belongs to the set of all threads we are about
4827 to resume. */
a493e3e2 4828 if (step || siggnal != GDB_SIGNAL_0)
82f73884 4829 {
0d8f58ca
PA
4830 /* Step inferior_ptid, with or without signal. */
4831 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 4832 }
0d8f58ca 4833
e5ef252a
PA
4834 /* Also pass down any pending signaled resumption for other
4835 threads not the current. */
4836 p = append_pending_thread_resumptions (p, endp, ptid);
4837
0d8f58ca 4838 /* And continue others without a signal. */
a493e3e2 4839 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
4840 }
4841 else
506fb367
DJ
4842 {
4843 /* Scheduler locking; resume only PTID. */
a9cbf802 4844 append_resumption (p, endp, ptid, step, siggnal);
506fb367 4845 }
c906108c 4846
82f73884
PA
4847 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4848 putpkt (rs->buf);
506fb367 4849
74531fed
PA
4850 if (non_stop)
4851 {
4852 /* In non-stop, the stub replies to vCont with "OK". The stop
4853 reply will be reported asynchronously by means of a `%Stop'
4854 notification. */
4855 getpkt (&rs->buf, &rs->buf_size, 0);
4856 if (strcmp (rs->buf, "OK") != 0)
4857 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4858 }
4859
506fb367 4860 return 1;
c906108c 4861}
43ff13b4 4862
506fb367
DJ
4863/* Tell the remote machine to resume. */
4864
43ff13b4 4865static void
28439f5e 4866remote_resume (struct target_ops *ops,
2ea28649 4867 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 4868{
d01949b6 4869 struct remote_state *rs = get_remote_state ();
2e9f7625 4870 char *buf;
43ff13b4 4871
722247f1
YQ
4872 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
4873 (explained in remote-notif.c:handle_notification) so
4874 remote_notif_process is not called. We need find a place where
4875 it is safe to start a 'vNotif' sequence. It is good to do it
4876 before resuming inferior, because inferior was stopped and no RSP
4877 traffic at that moment. */
4878 if (!non_stop)
5965e028 4879 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 4880
b73be471 4881 rs->last_sent_signal = siggnal;
280ceea3 4882 rs->last_sent_step = step;
43ff13b4 4883
506fb367 4884 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
4885 /* No reverse support (yet) for vCont. */
4886 if (execution_direction != EXEC_REVERSE)
4887 if (remote_vcont_resume (ptid, step, siggnal))
4888 goto done;
506fb367 4889
79d7f229
PA
4890 /* All other supported resume packets do use Hc, so set the continue
4891 thread. */
4892 if (ptid_equal (ptid, minus_one_ptid))
4893 set_continue_thread (any_thread_ptid);
506fb367 4894 else
79d7f229 4895 set_continue_thread (ptid);
506fb367 4896
2e9f7625 4897 buf = rs->buf;
b2175913
MS
4898 if (execution_direction == EXEC_REVERSE)
4899 {
4900 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 4901 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 4902 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 4903 siggnal);
40ab02ce 4904
4082afcc 4905 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
40ab02ce 4906 error (_("Remote reverse-step not supported."));
4082afcc 4907 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
08c93ed9 4908 error (_("Remote reverse-continue not supported."));
40ab02ce 4909
b2175913
MS
4910 strcpy (buf, step ? "bs" : "bc");
4911 }
a493e3e2 4912 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
4913 {
4914 buf[0] = step ? 'S' : 'C';
c5aa993b 4915 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 4916 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
4917 buf[3] = '\0';
4918 }
4919 else
c5aa993b 4920 strcpy (buf, step ? "s" : "c");
506fb367 4921
44eaed12 4922 putpkt (buf);
43ff13b4 4923
75c99385 4924 done:
2acceee2 4925 /* We are about to start executing the inferior, let's register it
0df8b418
MS
4926 with the event loop. NOTE: this is the one place where all the
4927 execution commands end up. We could alternatively do this in each
23860348 4928 of the execution commands in infcmd.c. */
2acceee2
JM
4929 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4930 into infcmd.c in order to allow inferior function calls to work
23860348 4931 NOT asynchronously. */
362646f5 4932 if (target_can_async_p ())
2acceee2 4933 target_async (inferior_event_handler, 0);
e24a49d8
PA
4934
4935 /* We've just told the target to resume. The remote server will
4936 wait for the inferior to stop, and then send a stop reply. In
4937 the mean time, we can't start another command/query ourselves
74531fed
PA
4938 because the stub wouldn't be ready to process it. This applies
4939 only to the base all-stop protocol, however. In non-stop (which
4940 only supports vCont), the stub replies with an "OK", and is
4941 immediate able to process further serial input. */
4942 if (!non_stop)
4943 rs->waiting_for_stop_reply = 1;
43ff13b4 4944}
c906108c 4945\f
43ff13b4
JM
4946
4947/* Set up the signal handler for SIGINT, while the target is
23860348 4948 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 4949static void
934b9bac 4950async_initialize_sigint_signal_handler (void)
43ff13b4 4951{
934b9bac 4952 signal (SIGINT, async_handle_remote_sigint);
43ff13b4
JM
4953}
4954
23860348 4955/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 4956static void
934b9bac 4957async_handle_remote_sigint (int sig)
43ff13b4 4958{
934b9bac 4959 signal (sig, async_handle_remote_sigint_twice);
b2ee242b
PA
4960 /* Note we need to go through gdb_call_async_signal_handler in order
4961 to wake up the event loop on Windows. */
4962 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
43ff13b4
JM
4963}
4964
4965/* Signal handler for SIGINT, installed after SIGINT has already been
4966 sent once. It will take effect the second time that the user sends
23860348 4967 a ^C. */
43ff13b4 4968static void
934b9bac 4969async_handle_remote_sigint_twice (int sig)
43ff13b4 4970{
934b9bac 4971 signal (sig, async_handle_remote_sigint);
b2ee242b
PA
4972 /* See note in async_handle_remote_sigint. */
4973 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
43ff13b4
JM
4974}
4975
6426a772 4976/* Perform the real interruption of the target execution, in response
23860348 4977 to a ^C. */
c5aa993b 4978static void
fba45db2 4979async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
4980{
4981 if (remote_debug)
248fd3bf 4982 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
43ff13b4 4983
94cc34af 4984 target_stop (inferior_ptid);
43ff13b4
JM
4985}
4986
0df8b418 4987/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 4988 up on the target alltogether. */
47e1ce27 4989static void
fba45db2 4990async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 4991{
2df3850c 4992 if (remote_debug)
248fd3bf 4993 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
b803fb0f
DJ
4994
4995 interrupt_query ();
43ff13b4
JM
4996}
4997
4998/* Reinstall the usual SIGINT handlers, after the target has
23860348 4999 stopped. */
6426a772 5000static void
934b9bac 5001async_cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
5002{
5003 signal (SIGINT, handle_sigint);
43ff13b4
JM
5004}
5005
c906108c
SS
5006/* Send ^C to target to halt it. Target will respond, and send us a
5007 packet. */
507f3c78 5008static void (*ofunc) (int);
c906108c 5009
0df8b418
MS
5010/* The command line interface's stop routine. This function is installed
5011 as a signal handler for SIGINT. The first time a user requests a
5012 stop, we call remote_stop to send a break or ^C. If there is no
7a292a7a 5013 response from the target (it didn't stop when the user requested it),
23860348 5014 we ask the user if he'd like to detach from the target. */
c906108c 5015static void
934b9bac 5016sync_remote_interrupt (int signo)
c906108c 5017{
23860348 5018 /* If this doesn't work, try more severe steps. */
934b9bac 5019 signal (signo, sync_remote_interrupt_twice);
7a292a7a 5020
934b9bac 5021 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
7a292a7a
SS
5022}
5023
5024/* The user typed ^C twice. */
5025
5026static void
934b9bac 5027sync_remote_interrupt_twice (int signo)
7a292a7a
SS
5028{
5029 signal (signo, ofunc);
934b9bac
JK
5030 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5031 signal (signo, sync_remote_interrupt);
c906108c 5032}
7a292a7a 5033
74531fed
PA
5034/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5035 thread, all threads of a remote process, or all threads of all
5036 processes. */
5037
5038static void
5039remote_stop_ns (ptid_t ptid)
5040{
5041 struct remote_state *rs = get_remote_state ();
5042 char *p = rs->buf;
5043 char *endp = rs->buf + get_remote_packet_size ();
74531fed 5044
4082afcc 5045 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
5046 remote_vcont_probe (rs);
5047
d458bd84 5048 if (!rs->supports_vCont.t)
74531fed
PA
5049 error (_("Remote server does not support stopping threads"));
5050
f91d3df5
PA
5051 if (ptid_equal (ptid, minus_one_ptid)
5052 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5053 p += xsnprintf (p, endp - p, "vCont;t");
5054 else
5055 {
5056 ptid_t nptid;
5057
74531fed
PA
5058 p += xsnprintf (p, endp - p, "vCont;t:");
5059
5060 if (ptid_is_pid (ptid))
5061 /* All (-1) threads of process. */
ba348170 5062 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
5063 else
5064 {
5065 /* Small optimization: if we already have a stop reply for
5066 this thread, no use in telling the stub we want this
5067 stopped. */
5068 if (peek_stop_reply (ptid))
5069 return;
5070
5071 nptid = ptid;
5072 }
5073
a9cbf802 5074 write_ptid (p, endp, nptid);
74531fed
PA
5075 }
5076
5077 /* In non-stop, we get an immediate OK reply. The stop reply will
5078 come in asynchronously by notification. */
5079 putpkt (rs->buf);
5080 getpkt (&rs->buf, &rs->buf_size, 0);
5081 if (strcmp (rs->buf, "OK") != 0)
5082 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5083}
5084
5085/* All-stop version of target_stop. Sends a break or a ^C to stop the
5086 remote target. It is undefined which thread of which process
5087 reports the stop. */
5088
5089static void
5090remote_stop_as (ptid_t ptid)
5091{
5092 struct remote_state *rs = get_remote_state ();
5093
3a29589a
DJ
5094 rs->ctrlc_pending_p = 1;
5095
74531fed
PA
5096 /* If the inferior is stopped already, but the core didn't know
5097 about it yet, just ignore the request. The cached wait status
5098 will be collected in remote_wait. */
5099 if (rs->cached_wait_status)
5100 return;
5101
9a7071a8
JB
5102 /* Send interrupt_sequence to remote target. */
5103 send_interrupt_sequence ();
74531fed
PA
5104}
5105
0df8b418 5106/* This is the generic stop called via the target vector. When a target
7a292a7a 5107 interrupt is requested, either by the command line or the GUI, we
23860348 5108 will eventually end up here. */
74531fed 5109
c906108c 5110static void
1eab8a48 5111remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5112{
7a292a7a 5113 if (remote_debug)
0f71a2f6 5114 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5115
74531fed
PA
5116 if (non_stop)
5117 remote_stop_ns (ptid);
c906108c 5118 else
74531fed 5119 remote_stop_as (ptid);
c906108c
SS
5120}
5121
5122/* Ask the user what to do when an interrupt is received. */
5123
5124static void
fba45db2 5125interrupt_query (void)
c906108c
SS
5126{
5127 target_terminal_ours ();
5128
d9d41e78 5129 if (target_is_async_p ())
c906108c 5130 {
74531fed 5131 signal (SIGINT, handle_sigint);
039e3c22 5132 quit ();
c906108c 5133 }
74531fed
PA
5134 else
5135 {
9e2f0ad4
HZ
5136 if (query (_("Interrupted while waiting for the program.\n\
5137Give up (and stop debugging it)? ")))
74531fed 5138 {
78a095c3 5139 remote_unpush_target ();
039e3c22 5140 quit ();
74531fed
PA
5141 }
5142 }
c906108c
SS
5143
5144 target_terminal_inferior ();
5145}
5146
6426a772
JM
5147/* Enable/disable target terminal ownership. Most targets can use
5148 terminal groups to control terminal ownership. Remote targets are
5149 different in that explicit transfer of ownership to/from GDB/target
23860348 5150 is required. */
6426a772
JM
5151
5152static void
d2f640d4 5153remote_terminal_inferior (struct target_ops *self)
6426a772 5154{
c6ebd6cf 5155 if (!target_async_permitted)
75c99385
PA
5156 /* Nothing to do. */
5157 return;
5158
d9d2d8b6
PA
5159 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5160 idempotent. The event-loop GDB talking to an asynchronous target
5161 with a synchronous command calls this function from both
5162 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5163 transfer the terminal to the target when it shouldn't this guard
5164 can go away. */
6426a772
JM
5165 if (!remote_async_terminal_ours_p)
5166 return;
5167 delete_file_handler (input_fd);
5168 remote_async_terminal_ours_p = 0;
934b9bac 5169 async_initialize_sigint_signal_handler ();
6426a772
JM
5170 /* NOTE: At this point we could also register our selves as the
5171 recipient of all input. Any characters typed could then be
23860348 5172 passed on down to the target. */
6426a772
JM
5173}
5174
5175static void
e3594fd1 5176remote_terminal_ours (struct target_ops *self)
6426a772 5177{
c6ebd6cf 5178 if (!target_async_permitted)
75c99385
PA
5179 /* Nothing to do. */
5180 return;
5181
5182 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5183 if (remote_async_terminal_ours_p)
5184 return;
934b9bac 5185 async_cleanup_sigint_signal_handler (NULL);
6426a772
JM
5186 add_file_handler (input_fd, stdin_event_handler, 0);
5187 remote_async_terminal_ours_p = 1;
5188}
5189
176a6961 5190static void
917317f4 5191remote_console_output (char *msg)
c906108c
SS
5192{
5193 char *p;
5194
c5aa993b 5195 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5196 {
5197 char tb[2];
5198 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5199
c906108c
SS
5200 tb[0] = c;
5201 tb[1] = 0;
43ff13b4 5202 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5203 }
00db5b94
PA
5204 gdb_flush (gdb_stdtarg);
5205}
74531fed
PA
5206
5207typedef struct cached_reg
5208{
5209 int num;
5210 gdb_byte data[MAX_REGISTER_SIZE];
5211} cached_reg_t;
5212
5213DEF_VEC_O(cached_reg_t);
5214
722247f1 5215typedef struct stop_reply
74531fed 5216{
722247f1 5217 struct notif_event base;
74531fed 5218
722247f1 5219 /* The identifier of the thread about this event */
74531fed
PA
5220 ptid_t ptid;
5221
340e3c99 5222 /* The remote state this event is associated with. When the remote
bcc75809
YQ
5223 connection, represented by a remote_state object, is closed,
5224 all the associated stop_reply events should be released. */
5225 struct remote_state *rs;
5226
74531fed
PA
5227 struct target_waitstatus ws;
5228
15148d6a
PA
5229 /* Expedited registers. This makes remote debugging a bit more
5230 efficient for those targets that provide critical registers as
5231 part of their normal status mechanism (as another roundtrip to
5232 fetch them is avoided). */
74531fed
PA
5233 VEC(cached_reg_t) *regcache;
5234
f7e6eed5
PA
5235 enum target_stop_reason stop_reason;
5236
74531fed
PA
5237 CORE_ADDR watch_data_address;
5238
dc146f7c 5239 int core;
722247f1 5240} *stop_reply_p;
a744cf53 5241
722247f1
YQ
5242DECLARE_QUEUE_P (stop_reply_p);
5243DEFINE_QUEUE_P (stop_reply_p);
5244/* The list of already fetched and acknowledged stop events. This
5245 queue is used for notification Stop, and other notifications
5246 don't need queue for their events, because the notification events
5247 of Stop can't be consumed immediately, so that events should be
5248 queued first, and be consumed by remote_wait_{ns,as} one per
5249 time. Other notifications can consume their events immediately,
5250 so queue is not needed for them. */
5251static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
5252
5253static void
5254stop_reply_xfree (struct stop_reply *r)
5255{
f48ff2a7 5256 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
5257}
5258
722247f1
YQ
5259static void
5260remote_notif_stop_parse (struct notif_client *self, char *buf,
5261 struct notif_event *event)
5262{
5263 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5264}
5265
5266static void
5267remote_notif_stop_ack (struct notif_client *self, char *buf,
5268 struct notif_event *event)
5269{
5270 struct stop_reply *stop_reply = (struct stop_reply *) event;
5271
5272 /* acknowledge */
5273 putpkt ((char *) self->ack_command);
5274
5275 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5276 /* We got an unknown stop reply. */
5277 error (_("Unknown stop reply"));
5278
5279 push_stop_reply (stop_reply);
5280}
5281
5282static int
5283remote_notif_stop_can_get_pending_events (struct notif_client *self)
5284{
5285 /* We can't get pending events in remote_notif_process for
5286 notification stop, and we have to do this in remote_wait_ns
5287 instead. If we fetch all queued events from stub, remote stub
5288 may exit and we have no chance to process them back in
5289 remote_wait_ns. */
5290 mark_async_event_handler (remote_async_inferior_event_token);
5291 return 0;
5292}
5293
5294static void
5295stop_reply_dtr (struct notif_event *event)
5296{
5297 struct stop_reply *r = (struct stop_reply *) event;
5298
5299 VEC_free (cached_reg_t, r->regcache);
5300}
5301
5302static struct notif_event *
5303remote_notif_stop_alloc_reply (void)
5304{
5305 struct notif_event *r
70ba0933 5306 = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
5307
5308 r->dtr = stop_reply_dtr;
5309
5310 return r;
5311}
5312
5313/* A client of notification Stop. */
5314
5315struct notif_client notif_client_stop =
5316{
5317 "Stop",
5318 "vStopped",
5319 remote_notif_stop_parse,
5320 remote_notif_stop_ack,
5321 remote_notif_stop_can_get_pending_events,
5322 remote_notif_stop_alloc_reply,
f48ff2a7 5323 REMOTE_NOTIF_STOP,
722247f1
YQ
5324};
5325
5326/* A parameter to pass data in and out. */
5327
5328struct queue_iter_param
5329{
5330 void *input;
5331 struct stop_reply *output;
5332};
5333
f48ff2a7
YQ
5334/* Remove stop replies in the queue if its pid is equal to the given
5335 inferior's pid. */
722247f1
YQ
5336
5337static int
f48ff2a7
YQ
5338remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5339 QUEUE_ITER (stop_reply_p) *iter,
5340 stop_reply_p event,
5341 void *data)
722247f1
YQ
5342{
5343 struct queue_iter_param *param = data;
5344 struct inferior *inf = param->input;
5345
f48ff2a7 5346 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
5347 {
5348 stop_reply_xfree (event);
5349 QUEUE_remove_elem (stop_reply_p, q, iter);
5350 }
5351
5352 return 1;
5353}
5354
f48ff2a7 5355/* Discard all pending stop replies of inferior INF. */
c906108c 5356
74531fed 5357static void
5f4cf0bb 5358discard_pending_stop_replies (struct inferior *inf)
c906108c 5359{
722247f1
YQ
5360 int i;
5361 struct queue_iter_param param;
f48ff2a7
YQ
5362 struct stop_reply *reply;
5363 struct remote_state *rs = get_remote_state ();
5364 struct remote_notif_state *rns = rs->notif_state;
5365
5366 /* This function can be notified when an inferior exists. When the
5367 target is not remote, the notification state is NULL. */
5368 if (rs->remote_desc == NULL)
5369 return;
5370
5371 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 5372
74531fed 5373 /* Discard the in-flight notification. */
f48ff2a7 5374 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 5375 {
722247f1 5376 stop_reply_xfree (reply);
f48ff2a7 5377 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 5378 }
c906108c 5379
722247f1
YQ
5380 param.input = inf;
5381 param.output = NULL;
74531fed
PA
5382 /* Discard the stop replies we have already pulled with
5383 vStopped. */
722247f1 5384 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
5385 remove_stop_reply_for_inferior, &param);
5386}
5387
bcc75809
YQ
5388/* If its remote state is equal to the given remote state,
5389 remove EVENT from the stop reply queue. */
5390
5391static int
5392remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5393 QUEUE_ITER (stop_reply_p) *iter,
5394 stop_reply_p event,
5395 void *data)
5396{
5397 struct queue_iter_param *param = data;
5398 struct remote_state *rs = param->input;
5399
5400 if (event->rs == rs)
5401 {
5402 stop_reply_xfree (event);
5403 QUEUE_remove_elem (stop_reply_p, q, iter);
5404 }
5405
5406 return 1;
5407}
5408
5409/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
5410
5411static void
bcc75809 5412discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
5413{
5414 struct queue_iter_param param;
5415
bcc75809 5416 param.input = rs;
f48ff2a7
YQ
5417 param.output = NULL;
5418 /* Discard the stop replies we have already pulled with
5419 vStopped. */
5420 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 5421 remove_stop_reply_of_remote_state, &param);
722247f1 5422}
74531fed 5423
722247f1
YQ
5424/* A parameter to pass data in and out. */
5425
5426static int
5427remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5428 QUEUE_ITER (stop_reply_p) *iter,
5429 stop_reply_p event,
5430 void *data)
5431{
5432 struct queue_iter_param *param = data;
5433 ptid_t *ptid = param->input;
5434
5435 if (ptid_match (event->ptid, *ptid))
5436 {
5437 param->output = event;
5438 QUEUE_remove_elem (stop_reply_p, q, iter);
5439 return 0;
c8e38a49 5440 }
722247f1
YQ
5441
5442 return 1;
74531fed 5443}
43ff13b4 5444
722247f1
YQ
5445/* Remove the first reply in 'stop_reply_queue' which matches
5446 PTID. */
2e9f7625 5447
722247f1
YQ
5448static struct stop_reply *
5449remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 5450{
722247f1
YQ
5451 struct queue_iter_param param;
5452
5453 param.input = &ptid;
5454 param.output = NULL;
5455
5456 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5457 remote_notif_remove_once_on_match, &param);
5458 if (notif_debug)
5459 fprintf_unfiltered (gdb_stdlog,
5460 "notif: discard queued event: 'Stop' in %s\n",
5461 target_pid_to_str (ptid));
a744cf53 5462
722247f1 5463 return param.output;
74531fed 5464}
75c99385 5465
74531fed
PA
5466/* Look for a queued stop reply belonging to PTID. If one is found,
5467 remove it from the queue, and return it. Returns NULL if none is
5468 found. If there are still queued events left to process, tell the
5469 event loop to get back to target_wait soon. */
e24a49d8 5470
74531fed
PA
5471static struct stop_reply *
5472queued_stop_reply (ptid_t ptid)
5473{
722247f1 5474 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 5475
722247f1 5476 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
5477 /* There's still at least an event left. */
5478 mark_async_event_handler (remote_async_inferior_event_token);
5479
722247f1 5480 return r;
74531fed
PA
5481}
5482
5483/* Push a fully parsed stop reply in the stop reply queue. Since we
5484 know that we now have at least one queued event left to pass to the
5485 core side, tell the event loop to get back to target_wait soon. */
5486
5487static void
5488push_stop_reply (struct stop_reply *new_event)
5489{
722247f1 5490 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 5491
722247f1
YQ
5492 if (notif_debug)
5493 fprintf_unfiltered (gdb_stdlog,
5494 "notif: push 'Stop' %s to queue %d\n",
5495 target_pid_to_str (new_event->ptid),
5496 QUEUE_length (stop_reply_p,
5497 stop_reply_queue));
74531fed
PA
5498
5499 mark_async_event_handler (remote_async_inferior_event_token);
5500}
5501
722247f1
YQ
5502static int
5503stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5504 QUEUE_ITER (stop_reply_p) *iter,
5505 struct stop_reply *event,
5506 void *data)
5507{
5508 ptid_t *ptid = data;
5509
5510 return !(ptid_equal (*ptid, event->ptid)
5511 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5512}
5513
74531fed
PA
5514/* Returns true if we have a stop reply for PTID. */
5515
5516static int
5517peek_stop_reply (ptid_t ptid)
5518{
722247f1
YQ
5519 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5520 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
5521}
5522
1f10ba14
PA
5523/* Skip PACKET until the next semi-colon (or end of string). */
5524
5525static char *
5526skip_to_semicolon (char *p)
5527{
5528 while (*p != '\0' && *p != ';')
5529 p++;
5530 return p;
5531}
5532
74531fed
PA
5533/* Parse the stop reply in BUF. Either the function succeeds, and the
5534 result is stored in EVENT, or throws an error. */
5535
5536static void
5537remote_parse_stop_reply (char *buf, struct stop_reply *event)
5538{
5539 struct remote_arch_state *rsa = get_remote_arch_state ();
5540 ULONGEST addr;
5541 char *p;
5542
5543 event->ptid = null_ptid;
bcc75809 5544 event->rs = get_remote_state ();
74531fed
PA
5545 event->ws.kind = TARGET_WAITKIND_IGNORE;
5546 event->ws.value.integer = 0;
f7e6eed5 5547 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 5548 event->regcache = NULL;
dc146f7c 5549 event->core = -1;
74531fed
PA
5550
5551 switch (buf[0])
5552 {
5553 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
5554 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5555 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5556 ss = signal number
5557 n... = register number
5558 r... = register contents
5559 */
5560
5561 p = &buf[3]; /* after Txx */
5562 while (*p)
5563 {
5564 char *p1;
cea39f65 5565 int fieldsize;
43ff13b4 5566
1f10ba14
PA
5567 p1 = strchr (p, ':');
5568 if (p1 == NULL)
5569 error (_("Malformed packet(a) (missing colon): %s\n\
5570Packet: '%s'\n"),
5571 p, buf);
5572 if (p == p1)
5573 error (_("Malformed packet(a) (missing register number): %s\n\
5574Packet: '%s'\n"),
5575 p, buf);
3c3bea1c 5576
1f10ba14
PA
5577 /* Some "registers" are actually extended stop information.
5578 Note if you're adding a new entry here: GDB 7.9 and
5579 earlier assume that all register "numbers" that start
5580 with an hex digit are real register numbers. Make sure
5581 the server only sends such a packet if it knows the
5582 client understands it. */
c8e38a49 5583
1f10ba14
PA
5584 if (strncmp (p, "thread", p1 - p) == 0)
5585 event->ptid = read_ptid (++p1, &p);
5586 else if ((strncmp (p, "watch", p1 - p) == 0)
5587 || (strncmp (p, "rwatch", p1 - p) == 0)
5588 || (strncmp (p, "awatch", p1 - p) == 0))
cea39f65 5589 {
f7e6eed5 5590 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
5591 p = unpack_varlen_hex (++p1, &addr);
5592 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 5593 }
f7e6eed5
PA
5594 else if (strncmp (p, "swbreak", p1 - p) == 0)
5595 {
5596 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
5597
5598 /* Make sure the stub doesn't forget to indicate support
5599 with qSupported. */
5600 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
5601 error (_("Unexpected swbreak stop reason"));
5602
5603 /* The value part is documented as "must be empty",
5604 though we ignore it, in case we ever decide to make
5605 use of it in a backward compatible way. */
5606 p = skip_to_semicolon (p1 + 1);
5607 }
5608 else if (strncmp (p, "hwbreak", p1 - p) == 0)
5609 {
5610 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
5611
5612 /* Make sure the stub doesn't forget to indicate support
5613 with qSupported. */
5614 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
5615 error (_("Unexpected hwbreak stop reason"));
5616
5617 /* See above. */
5618 p = skip_to_semicolon (p1 + 1);
5619 }
1f10ba14 5620 else if (strncmp (p, "library", p1 - p) == 0)
cea39f65 5621 {
1f10ba14
PA
5622 event->ws.kind = TARGET_WAITKIND_LOADED;
5623 p = skip_to_semicolon (p1 + 1);
5624 }
5625 else if (strncmp (p, "replaylog", p1 - p) == 0)
5626 {
5627 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5628 /* p1 will indicate "begin" or "end", but it makes
5629 no difference for now, so ignore it. */
5630 p = skip_to_semicolon (p1 + 1);
5631 }
5632 else if (strncmp (p, "core", p1 - p) == 0)
5633 {
5634 ULONGEST c;
a744cf53 5635
1f10ba14
PA
5636 p = unpack_varlen_hex (++p1, &c);
5637 event->core = c;
cea39f65
MS
5638 }
5639 else
5640 {
1f10ba14
PA
5641 ULONGEST pnum;
5642 char *p_temp;
5643
5644 /* Maybe a real ``P'' register number. */
5645 p_temp = unpack_varlen_hex (p, &pnum);
5646 /* If the first invalid character is the colon, we got a
5647 register number. Otherwise, it's an unknown stop
5648 reason. */
5649 if (p_temp == p1)
5650 {
5651 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5652 cached_reg_t cached_reg;
43ff13b4 5653
1f10ba14
PA
5654 if (reg == NULL)
5655 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 5656Packet: '%s'\n"),
1f10ba14 5657 hex_string (pnum), p, buf);
c8e38a49 5658
1f10ba14 5659 cached_reg.num = reg->regnum;
4100683b 5660
1f10ba14
PA
5661 p = p1 + 1;
5662 fieldsize = hex2bin (p, cached_reg.data,
5663 register_size (target_gdbarch (),
5664 reg->regnum));
5665 p += 2 * fieldsize;
5666 if (fieldsize < register_size (target_gdbarch (),
5667 reg->regnum))
5668 warning (_("Remote reply is too short: %s"), buf);
74531fed 5669
1f10ba14
PA
5670 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5671 }
5672 else
5673 {
5674 /* Not a number. Silently skip unknown optional
5675 info. */
5676 p = skip_to_semicolon (p1 + 1);
5677 }
cea39f65 5678 }
c8e38a49 5679
cea39f65
MS
5680 if (*p != ';')
5681 error (_("Remote register badly formatted: %s\nhere: %s"),
5682 buf, p);
5683 ++p;
5684 }
5b5596ff
PA
5685
5686 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
5687 break;
5688
c8e38a49
PA
5689 /* fall through */
5690 case 'S': /* Old style status, just signal only. */
3a09da41
PA
5691 {
5692 int sig;
5693
5694 event->ws.kind = TARGET_WAITKIND_STOPPED;
5695 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
5696 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
5697 event->ws.value.sig = (enum gdb_signal) sig;
5698 else
5699 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5700 }
c8e38a49
PA
5701 break;
5702 case 'W': /* Target exited. */
5703 case 'X':
5704 {
5705 char *p;
5706 int pid;
5707 ULONGEST value;
82f73884 5708
c8e38a49
PA
5709 /* GDB used to accept only 2 hex chars here. Stubs should
5710 only send more if they detect GDB supports multi-process
5711 support. */
5712 p = unpack_varlen_hex (&buf[1], &value);
82f73884 5713
c8e38a49
PA
5714 if (buf[0] == 'W')
5715 {
5716 /* The remote process exited. */
74531fed
PA
5717 event->ws.kind = TARGET_WAITKIND_EXITED;
5718 event->ws.value.integer = value;
c8e38a49
PA
5719 }
5720 else
5721 {
5722 /* The remote process exited with a signal. */
74531fed 5723 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
5724 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
5725 event->ws.value.sig = (enum gdb_signal) value;
5726 else
5727 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 5728 }
82f73884 5729
c8e38a49
PA
5730 /* If no process is specified, assume inferior_ptid. */
5731 pid = ptid_get_pid (inferior_ptid);
5732 if (*p == '\0')
5733 ;
5734 else if (*p == ';')
5735 {
5736 p++;
5737
0b24eb2d 5738 if (*p == '\0')
82f73884 5739 ;
61012eef 5740 else if (startswith (p, "process:"))
82f73884 5741 {
c8e38a49 5742 ULONGEST upid;
a744cf53 5743
c8e38a49
PA
5744 p += sizeof ("process:") - 1;
5745 unpack_varlen_hex (p, &upid);
5746 pid = upid;
82f73884
PA
5747 }
5748 else
5749 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 5750 }
c8e38a49
PA
5751 else
5752 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
5753 event->ptid = pid_to_ptid (pid);
5754 }
5755 break;
5756 }
5757
5758 if (non_stop && ptid_equal (event->ptid, null_ptid))
5759 error (_("No process or thread specified in stop reply: %s"), buf);
5760}
5761
722247f1
YQ
5762/* When the stub wants to tell GDB about a new notification reply, it
5763 sends a notification (%Stop, for example). Those can come it at
5764 any time, hence, we have to make sure that any pending
5765 putpkt/getpkt sequence we're making is finished, before querying
5766 the stub for more events with the corresponding ack command
5767 (vStopped, for example). E.g., if we started a vStopped sequence
5768 immediately upon receiving the notification, something like this
5769 could happen:
74531fed
PA
5770
5771 1.1) --> Hg 1
5772 1.2) <-- OK
5773 1.3) --> g
5774 1.4) <-- %Stop
5775 1.5) --> vStopped
5776 1.6) <-- (registers reply to step #1.3)
5777
5778 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5779 query.
5780
796cb314 5781 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
5782 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5783 doing whatever we were doing:
5784
5785 2.1) --> Hg 1
5786 2.2) <-- OK
5787 2.3) --> g
5788 2.4) <-- %Stop
5789 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5790 2.5) <-- (registers reply to step #2.3)
5791
5792 Eventualy after step #2.5, we return to the event loop, which
5793 notices there's an event on the
5794 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5795 associated callback --- the function below. At this point, we're
5796 always safe to start a vStopped sequence. :
5797
5798 2.6) --> vStopped
5799 2.7) <-- T05 thread:2
5800 2.8) --> vStopped
5801 2.9) --> OK
5802*/
5803
722247f1
YQ
5804void
5805remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
5806{
5807 struct remote_state *rs = get_remote_state ();
74531fed 5808
f48ff2a7 5809 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 5810 {
722247f1
YQ
5811 if (notif_debug)
5812 fprintf_unfiltered (gdb_stdlog,
5813 "notif: process: '%s' ack pending event\n",
5814 nc->name);
74531fed 5815
722247f1 5816 /* acknowledge */
f48ff2a7
YQ
5817 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
5818 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
5819
5820 while (1)
5821 {
5822 getpkt (&rs->buf, &rs->buf_size, 0);
5823 if (strcmp (rs->buf, "OK") == 0)
5824 break;
5825 else
722247f1 5826 remote_notif_ack (nc, rs->buf);
74531fed
PA
5827 }
5828 }
722247f1
YQ
5829 else
5830 {
5831 if (notif_debug)
5832 fprintf_unfiltered (gdb_stdlog,
5833 "notif: process: '%s' no pending reply\n",
5834 nc->name);
5835 }
74531fed
PA
5836}
5837
74531fed
PA
5838/* Called when it is decided that STOP_REPLY holds the info of the
5839 event that is to be returned to the core. This function always
5840 destroys STOP_REPLY. */
5841
5842static ptid_t
5843process_stop_reply (struct stop_reply *stop_reply,
5844 struct target_waitstatus *status)
5845{
5846 ptid_t ptid;
5847
5848 *status = stop_reply->ws;
5849 ptid = stop_reply->ptid;
5850
5851 /* If no thread/process was reported by the stub, assume the current
5852 inferior. */
5853 if (ptid_equal (ptid, null_ptid))
5854 ptid = inferior_ptid;
5855
5f3563ea
PA
5856 if (status->kind != TARGET_WAITKIND_EXITED
5857 && status->kind != TARGET_WAITKIND_SIGNALLED)
74531fed 5858 {
ee154bee
TT
5859 struct remote_state *rs = get_remote_state ();
5860
5f3563ea
PA
5861 /* Expedited registers. */
5862 if (stop_reply->regcache)
5863 {
217f1f79 5864 struct regcache *regcache
f5656ead 5865 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
5866 cached_reg_t *reg;
5867 int ix;
5868
5869 for (ix = 0;
5870 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5871 ix++)
217f1f79 5872 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
5873 VEC_free (cached_reg_t, stop_reply->regcache);
5874 }
74531fed 5875
f7e6eed5 5876 rs->stop_reason = stop_reply->stop_reason;
ee154bee 5877 rs->remote_watch_data_address = stop_reply->watch_data_address;
1941c569
PA
5878
5879 remote_notice_new_inferior (ptid, 0);
dc146f7c 5880 demand_private_info (ptid)->core = stop_reply->core;
74531fed
PA
5881 }
5882
74531fed
PA
5883 stop_reply_xfree (stop_reply);
5884 return ptid;
5885}
5886
5887/* The non-stop mode version of target_wait. */
5888
5889static ptid_t
47608cb1 5890remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
5891{
5892 struct remote_state *rs = get_remote_state ();
74531fed
PA
5893 struct stop_reply *stop_reply;
5894 int ret;
fee9eda9 5895 int is_notif = 0;
74531fed
PA
5896
5897 /* If in non-stop mode, get out of getpkt even if a
5898 notification is received. */
5899
5900 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 5901 0 /* forever */, &is_notif);
74531fed
PA
5902 while (1)
5903 {
fee9eda9 5904 if (ret != -1 && !is_notif)
74531fed
PA
5905 switch (rs->buf[0])
5906 {
5907 case 'E': /* Error of some sort. */
5908 /* We're out of sync with the target now. Did it continue
5909 or not? We can't tell which thread it was in non-stop,
5910 so just ignore this. */
5911 warning (_("Remote failure reply: %s"), rs->buf);
5912 break;
5913 case 'O': /* Console output. */
5914 remote_console_output (rs->buf + 1);
5915 break;
5916 default:
5917 warning (_("Invalid remote reply: %s"), rs->buf);
5918 break;
5919 }
5920
5921 /* Acknowledge a pending stop reply that may have arrived in the
5922 mean time. */
f48ff2a7 5923 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 5924 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
5925
5926 /* If indeed we noticed a stop reply, we're done. */
5927 stop_reply = queued_stop_reply (ptid);
5928 if (stop_reply != NULL)
5929 return process_stop_reply (stop_reply, status);
5930
47608cb1 5931 /* Still no event. If we're just polling for an event, then
74531fed 5932 return to the event loop. */
47608cb1 5933 if (options & TARGET_WNOHANG)
74531fed
PA
5934 {
5935 status->kind = TARGET_WAITKIND_IGNORE;
5936 return minus_one_ptid;
5937 }
5938
47608cb1 5939 /* Otherwise do a blocking wait. */
74531fed 5940 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 5941 1 /* forever */, &is_notif);
74531fed
PA
5942 }
5943}
5944
5945/* Wait until the remote machine stops, then return, storing status in
5946 STATUS just as `wait' would. */
5947
5948static ptid_t
47608cb1 5949remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
5950{
5951 struct remote_state *rs = get_remote_state ();
74531fed 5952 ptid_t event_ptid = null_ptid;
cea39f65 5953 char *buf;
74531fed
PA
5954 struct stop_reply *stop_reply;
5955
47608cb1
PA
5956 again:
5957
74531fed
PA
5958 status->kind = TARGET_WAITKIND_IGNORE;
5959 status->value.integer = 0;
5960
5961 stop_reply = queued_stop_reply (ptid);
5962 if (stop_reply != NULL)
5963 return process_stop_reply (stop_reply, status);
5964
5965 if (rs->cached_wait_status)
5966 /* Use the cached wait status, but only once. */
5967 rs->cached_wait_status = 0;
5968 else
5969 {
5970 int ret;
722247f1 5971 int is_notif;
74531fed
PA
5972
5973 if (!target_is_async_p ())
5974 {
934b9bac 5975 ofunc = signal (SIGINT, sync_remote_interrupt);
74531fed
PA
5976 /* If the user hit C-c before this packet, or between packets,
5977 pretend that it was hit right here. */
522002f9 5978 if (check_quit_flag ())
74531fed 5979 {
522002f9 5980 clear_quit_flag ();
934b9bac 5981 sync_remote_interrupt (SIGINT);
74531fed
PA
5982 }
5983 }
5984
5985 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5986 _never_ wait for ever -> test on target_is_async_p().
5987 However, before we do that we need to ensure that the caller
5988 knows how to take the target into/out of async mode. */
722247f1
YQ
5989 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5990 wait_forever_enabled_p, &is_notif);
5991
5e1b953b
SDJ
5992 if (!target_is_async_p ())
5993 signal (SIGINT, ofunc);
5994
722247f1
YQ
5995 /* GDB gets a notification. Return to core as this event is
5996 not interesting. */
5997 if (ret != -1 && is_notif)
5998 return minus_one_ptid;
74531fed
PA
5999 }
6000
6001 buf = rs->buf;
6002
f7e6eed5 6003 rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed
PA
6004
6005 /* We got something. */
6006 rs->waiting_for_stop_reply = 0;
6007
3a29589a
DJ
6008 /* Assume that the target has acknowledged Ctrl-C unless we receive
6009 an 'F' or 'O' packet. */
6010 if (buf[0] != 'F' && buf[0] != 'O')
6011 rs->ctrlc_pending_p = 0;
6012
74531fed
PA
6013 switch (buf[0])
6014 {
6015 case 'E': /* Error of some sort. */
6016 /* We're out of sync with the target now. Did it continue or
6017 not? Not is more likely, so report a stop. */
6018 warning (_("Remote failure reply: %s"), buf);
6019 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 6020 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
6021 break;
6022 case 'F': /* File-I/O request. */
3a29589a
DJ
6023 remote_fileio_request (buf, rs->ctrlc_pending_p);
6024 rs->ctrlc_pending_p = 0;
74531fed
PA
6025 break;
6026 case 'T': case 'S': case 'X': case 'W':
6027 {
722247f1
YQ
6028 struct stop_reply *stop_reply
6029 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6030 rs->buf);
74531fed 6031
74531fed 6032 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
6033 break;
6034 }
6035 case 'O': /* Console output. */
6036 remote_console_output (buf + 1);
e24a49d8 6037
c8e38a49
PA
6038 /* The target didn't really stop; keep waiting. */
6039 rs->waiting_for_stop_reply = 1;
e24a49d8 6040
c8e38a49
PA
6041 break;
6042 case '\0':
b73be471 6043 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
6044 {
6045 /* Zero length reply means that we tried 'S' or 'C' and the
6046 remote system doesn't support it. */
6047 target_terminal_ours_for_output ();
6048 printf_filtered
6049 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
6050 gdb_signal_to_name (rs->last_sent_signal));
6051 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
6052 target_terminal_inferior ();
6053
280ceea3 6054 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49
PA
6055 putpkt ((char *) buf);
6056
6057 /* We just told the target to resume, so a stop reply is in
6058 order. */
e24a49d8 6059 rs->waiting_for_stop_reply = 1;
c8e38a49 6060 break;
43ff13b4 6061 }
c8e38a49
PA
6062 /* else fallthrough */
6063 default:
6064 warning (_("Invalid remote reply: %s"), buf);
6065 /* Keep waiting. */
6066 rs->waiting_for_stop_reply = 1;
6067 break;
43ff13b4 6068 }
c8e38a49 6069
c8e38a49 6070 if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
6071 {
6072 /* Nothing interesting happened. If we're doing a non-blocking
6073 poll, we're done. Otherwise, go back to waiting. */
6074 if (options & TARGET_WNOHANG)
6075 return minus_one_ptid;
6076 else
6077 goto again;
6078 }
74531fed
PA
6079 else if (status->kind != TARGET_WAITKIND_EXITED
6080 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
6081 {
6082 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 6083 record_currthread (rs, event_ptid);
82f73884
PA
6084 else
6085 event_ptid = inferior_ptid;
43ff13b4 6086 }
74531fed
PA
6087 else
6088 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 6089 record_currthread (rs, minus_one_ptid);
79d7f229 6090
82f73884 6091 return event_ptid;
43ff13b4
JM
6092}
6093
74531fed
PA
6094/* Wait until the remote machine stops, then return, storing status in
6095 STATUS just as `wait' would. */
6096
c8e38a49 6097static ptid_t
117de6a9 6098remote_wait (struct target_ops *ops,
47608cb1 6099 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
6100{
6101 ptid_t event_ptid;
6102
74531fed 6103 if (non_stop)
47608cb1 6104 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 6105 else
47608cb1 6106 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 6107
d9d41e78 6108 if (target_is_async_p ())
c8e38a49 6109 {
74531fed
PA
6110 /* If there are are events left in the queue tell the event loop
6111 to return here. */
722247f1 6112 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 6113 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 6114 }
c8e38a49
PA
6115
6116 return event_ptid;
6117}
6118
74ca34ce 6119/* Fetch a single register using a 'p' packet. */
c906108c 6120
b96ec7ac 6121static int
56be3814 6122fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
6123{
6124 struct remote_state *rs = get_remote_state ();
2e9f7625 6125 char *buf, *p;
b96ec7ac
AC
6126 char regp[MAX_REGISTER_SIZE];
6127 int i;
6128
4082afcc 6129 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
6130 return 0;
6131
6132 if (reg->pnum == -1)
6133 return 0;
6134
2e9f7625 6135 p = rs->buf;
fcad0fa4 6136 *p++ = 'p';
74ca34ce 6137 p += hexnumstr (p, reg->pnum);
fcad0fa4 6138 *p++ = '\0';
1f4437a4
MS
6139 putpkt (rs->buf);
6140 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 6141
2e9f7625
DJ
6142 buf = rs->buf;
6143
74ca34ce
DJ
6144 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6145 {
6146 case PACKET_OK:
6147 break;
6148 case PACKET_UNKNOWN:
6149 return 0;
6150 case PACKET_ERROR:
27a9c0bf
MS
6151 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6152 gdbarch_register_name (get_regcache_arch (regcache),
6153 reg->regnum),
6154 buf);
74ca34ce 6155 }
3f9a994c
JB
6156
6157 /* If this register is unfetchable, tell the regcache. */
6158 if (buf[0] == 'x')
8480adf2 6159 {
56be3814 6160 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 6161 return 1;
b96ec7ac 6162 }
b96ec7ac 6163
3f9a994c
JB
6164 /* Otherwise, parse and supply the value. */
6165 p = buf;
6166 i = 0;
6167 while (p[0] != 0)
6168 {
6169 if (p[1] == 0)
74ca34ce 6170 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
6171
6172 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6173 p += 2;
6174 }
56be3814 6175 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 6176 return 1;
b96ec7ac
AC
6177}
6178
74ca34ce
DJ
6179/* Fetch the registers included in the target's 'g' packet. */
6180
29709017
DJ
6181static int
6182send_g_packet (void)
c906108c 6183{
d01949b6 6184 struct remote_state *rs = get_remote_state ();
cea39f65 6185 int buf_len;
c906108c 6186
bba74b36 6187 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 6188 remote_send (&rs->buf, &rs->buf_size);
c906108c 6189
29709017
DJ
6190 /* We can get out of synch in various cases. If the first character
6191 in the buffer is not a hex character, assume that has happened
6192 and try to fetch another packet to read. */
6193 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6194 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6195 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6196 && rs->buf[0] != 'x') /* New: unavailable register value. */
6197 {
6198 if (remote_debug)
6199 fprintf_unfiltered (gdb_stdlog,
6200 "Bad register packet; fetching a new packet\n");
6201 getpkt (&rs->buf, &rs->buf_size, 0);
6202 }
6203
74ca34ce
DJ
6204 buf_len = strlen (rs->buf);
6205
6206 /* Sanity check the received packet. */
6207 if (buf_len % 2 != 0)
6208 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
6209
6210 return buf_len / 2;
6211}
6212
6213static void
56be3814 6214process_g_packet (struct regcache *regcache)
29709017 6215{
4a22f64d 6216 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
6217 struct remote_state *rs = get_remote_state ();
6218 struct remote_arch_state *rsa = get_remote_arch_state ();
6219 int i, buf_len;
6220 char *p;
6221 char *regs;
6222
6223 buf_len = strlen (rs->buf);
6224
6225 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
6226 if (buf_len > 2 * rsa->sizeof_g_packet)
6227 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6228
6229 /* Save the size of the packet sent to us by the target. It is used
6230 as a heuristic when determining the max size of packets that the
6231 target can safely receive. */
6232 if (rsa->actual_register_packet_size == 0)
6233 rsa->actual_register_packet_size = buf_len;
6234
6235 /* If this is smaller than we guessed the 'g' packet would be,
6236 update our records. A 'g' reply that doesn't include a register's
6237 value implies either that the register is not available, or that
6238 the 'p' packet must be used. */
6239 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 6240 {
74ca34ce
DJ
6241 rsa->sizeof_g_packet = buf_len / 2;
6242
4a22f64d 6243 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 6244 {
74ca34ce
DJ
6245 if (rsa->regs[i].pnum == -1)
6246 continue;
6247
6248 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6249 rsa->regs[i].in_g_packet = 0;
b96ec7ac 6250 else
74ca34ce 6251 rsa->regs[i].in_g_packet = 1;
b96ec7ac 6252 }
74ca34ce 6253 }
b323314b 6254
74ca34ce 6255 regs = alloca (rsa->sizeof_g_packet);
c906108c
SS
6256
6257 /* Unimplemented registers read as all bits zero. */
ea9c271d 6258 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 6259
c906108c
SS
6260 /* Reply describes registers byte by byte, each byte encoded as two
6261 hex characters. Suck them all up, then supply them to the
6262 register cacheing/storage mechanism. */
6263
74ca34ce 6264 p = rs->buf;
ea9c271d 6265 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 6266 {
74ca34ce
DJ
6267 if (p[0] == 0 || p[1] == 0)
6268 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6269 internal_error (__FILE__, __LINE__,
9b20d036 6270 _("unexpected end of 'g' packet reply"));
74ca34ce 6271
c906108c 6272 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 6273 regs[i] = 0; /* 'x' */
c906108c
SS
6274 else
6275 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6276 p += 2;
6277 }
6278
a744cf53
MS
6279 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6280 {
6281 struct packet_reg *r = &rsa->regs[i];
6282
6283 if (r->in_g_packet)
6284 {
6285 if (r->offset * 2 >= strlen (rs->buf))
6286 /* This shouldn't happen - we adjusted in_g_packet above. */
6287 internal_error (__FILE__, __LINE__,
9b20d036 6288 _("unexpected end of 'g' packet reply"));
a744cf53
MS
6289 else if (rs->buf[r->offset * 2] == 'x')
6290 {
6291 gdb_assert (r->offset * 2 < strlen (rs->buf));
6292 /* The register isn't available, mark it as such (at
6293 the same time setting the value to zero). */
6294 regcache_raw_supply (regcache, r->regnum, NULL);
6295 }
6296 else
6297 regcache_raw_supply (regcache, r->regnum,
6298 regs + r->offset);
6299 }
6300 }
c906108c
SS
6301}
6302
29709017 6303static void
56be3814 6304fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
6305{
6306 send_g_packet ();
56be3814 6307 process_g_packet (regcache);
29709017
DJ
6308}
6309
e6e4e701
PA
6310/* Make the remote selected traceframe match GDB's selected
6311 traceframe. */
6312
6313static void
6314set_remote_traceframe (void)
6315{
6316 int newnum;
262e1174 6317 struct remote_state *rs = get_remote_state ();
e6e4e701 6318
262e1174 6319 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
6320 return;
6321
6322 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 6323 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
6324
6325 newnum = target_trace_find (tfind_number,
6326 get_traceframe_number (), 0, 0, NULL);
6327
6328 /* Should not happen. If it does, all bets are off. */
6329 if (newnum != get_traceframe_number ())
6330 warning (_("could not set remote traceframe"));
6331}
6332
74ca34ce 6333static void
28439f5e
PA
6334remote_fetch_registers (struct target_ops *ops,
6335 struct regcache *regcache, int regnum)
74ca34ce 6336{
74ca34ce
DJ
6337 struct remote_arch_state *rsa = get_remote_arch_state ();
6338 int i;
6339
e6e4e701 6340 set_remote_traceframe ();
79d7f229 6341 set_general_thread (inferior_ptid);
74ca34ce
DJ
6342
6343 if (regnum >= 0)
6344 {
6345 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6346
74ca34ce
DJ
6347 gdb_assert (reg != NULL);
6348
6349 /* If this register might be in the 'g' packet, try that first -
6350 we are likely to read more than one register. If this is the
6351 first 'g' packet, we might be overly optimistic about its
6352 contents, so fall back to 'p'. */
6353 if (reg->in_g_packet)
6354 {
56be3814 6355 fetch_registers_using_g (regcache);
74ca34ce
DJ
6356 if (reg->in_g_packet)
6357 return;
6358 }
6359
56be3814 6360 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
6361 return;
6362
6363 /* This register is not available. */
56be3814 6364 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
6365
6366 return;
6367 }
6368
56be3814 6369 fetch_registers_using_g (regcache);
74ca34ce 6370
4a22f64d 6371 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6372 if (!rsa->regs[i].in_g_packet)
56be3814 6373 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
6374 {
6375 /* This register is not available. */
56be3814 6376 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
6377 }
6378}
6379
c906108c
SS
6380/* Prepare to store registers. Since we may send them all (using a
6381 'G' request), we have to read out the ones we don't want to change
6382 first. */
6383
c5aa993b 6384static void
f32dbf8c 6385remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 6386{
ea9c271d 6387 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 6388 int i;
cfd77fa1 6389 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 6390
c906108c 6391 /* Make sure the entire registers array is valid. */
4082afcc 6392 switch (packet_support (PACKET_P))
5a2468f5
JM
6393 {
6394 case PACKET_DISABLE:
6395 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 6396 /* Make sure all the necessary registers are cached. */
4a22f64d 6397 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 6398 if (rsa->regs[i].in_g_packet)
316f2060 6399 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
6400 break;
6401 case PACKET_ENABLE:
6402 break;
6403 }
6404}
6405
ad10f812 6406/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 6407 packet was not recognized. */
5a2468f5
JM
6408
6409static int
1f4437a4
MS
6410store_register_using_P (const struct regcache *regcache,
6411 struct packet_reg *reg)
5a2468f5 6412{
4a22f64d 6413 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 6414 struct remote_state *rs = get_remote_state ();
5a2468f5 6415 /* Try storing a single register. */
6d820c5c 6416 char *buf = rs->buf;
cfd77fa1 6417 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 6418 char *p;
5a2468f5 6419
4082afcc 6420 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
6421 return 0;
6422
6423 if (reg->pnum == -1)
6424 return 0;
6425
ea9c271d 6426 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 6427 p = buf + strlen (buf);
56be3814 6428 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 6429 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
6430 putpkt (rs->buf);
6431 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 6432
74ca34ce
DJ
6433 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6434 {
6435 case PACKET_OK:
6436 return 1;
6437 case PACKET_ERROR:
27a9c0bf
MS
6438 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6439 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
6440 case PACKET_UNKNOWN:
6441 return 0;
6442 default:
6443 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6444 }
c906108c
SS
6445}
6446
23860348
MS
6447/* Store register REGNUM, or all registers if REGNUM == -1, from the
6448 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
6449
6450static void
56be3814 6451store_registers_using_G (const struct regcache *regcache)
c906108c 6452{
d01949b6 6453 struct remote_state *rs = get_remote_state ();
ea9c271d 6454 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 6455 gdb_byte *regs;
c906108c
SS
6456 char *p;
6457
193cb69f
AC
6458 /* Extract all the registers in the regcache copying them into a
6459 local buffer. */
6460 {
b323314b 6461 int i;
a744cf53 6462
ea9c271d
DJ
6463 regs = alloca (rsa->sizeof_g_packet);
6464 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 6465 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 6466 {
ea9c271d 6467 struct packet_reg *r = &rsa->regs[i];
a744cf53 6468
b323314b 6469 if (r->in_g_packet)
56be3814 6470 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
6471 }
6472 }
c906108c
SS
6473
6474 /* Command describes registers byte by byte,
6475 each byte encoded as two hex characters. */
6d820c5c 6476 p = rs->buf;
193cb69f 6477 *p++ = 'G';
74ca34ce
DJ
6478 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6479 updated. */
6480 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
6481 putpkt (rs->buf);
6482 getpkt (&rs->buf, &rs->buf_size, 0);
6483 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
6484 error (_("Could not write registers; remote failure reply '%s'"),
6485 rs->buf);
c906108c 6486}
74ca34ce
DJ
6487
6488/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6489 of the register cache buffer. FIXME: ignores errors. */
6490
6491static void
28439f5e
PA
6492remote_store_registers (struct target_ops *ops,
6493 struct regcache *regcache, int regnum)
74ca34ce 6494{
74ca34ce
DJ
6495 struct remote_arch_state *rsa = get_remote_arch_state ();
6496 int i;
6497
e6e4e701 6498 set_remote_traceframe ();
79d7f229 6499 set_general_thread (inferior_ptid);
74ca34ce
DJ
6500
6501 if (regnum >= 0)
6502 {
6503 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6504
74ca34ce
DJ
6505 gdb_assert (reg != NULL);
6506
6507 /* Always prefer to store registers using the 'P' packet if
6508 possible; we often change only a small number of registers.
6509 Sometimes we change a larger number; we'd need help from a
6510 higher layer to know to use 'G'. */
56be3814 6511 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
6512 return;
6513
6514 /* For now, don't complain if we have no way to write the
6515 register. GDB loses track of unavailable registers too
6516 easily. Some day, this may be an error. We don't have
0df8b418 6517 any way to read the register, either... */
74ca34ce
DJ
6518 if (!reg->in_g_packet)
6519 return;
6520
56be3814 6521 store_registers_using_G (regcache);
74ca34ce
DJ
6522 return;
6523 }
6524
56be3814 6525 store_registers_using_G (regcache);
74ca34ce 6526
4a22f64d 6527 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6528 if (!rsa->regs[i].in_g_packet)
56be3814 6529 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
6530 /* See above for why we do not issue an error here. */
6531 continue;
6532}
c906108c
SS
6533\f
6534
6535/* Return the number of hex digits in num. */
6536
6537static int
fba45db2 6538hexnumlen (ULONGEST num)
c906108c
SS
6539{
6540 int i;
6541
6542 for (i = 0; num != 0; i++)
6543 num >>= 4;
6544
6545 return max (i, 1);
6546}
6547
2df3850c 6548/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
6549
6550static int
fba45db2 6551hexnumstr (char *buf, ULONGEST num)
c906108c 6552{
c906108c 6553 int len = hexnumlen (num);
a744cf53 6554
2df3850c
JM
6555 return hexnumnstr (buf, num, len);
6556}
6557
c906108c 6558
2df3850c 6559/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 6560
2df3850c 6561static int
fba45db2 6562hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
6563{
6564 int i;
6565
6566 buf[width] = '\0';
6567
6568 for (i = width - 1; i >= 0; i--)
c906108c 6569 {
c5aa993b 6570 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
6571 num >>= 4;
6572 }
6573
2df3850c 6574 return width;
c906108c
SS
6575}
6576
23860348 6577/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
6578
6579static CORE_ADDR
fba45db2 6580remote_address_masked (CORE_ADDR addr)
c906108c 6581{
883b9c6c 6582 unsigned int address_size = remote_address_size;
a744cf53 6583
911c95a5
UW
6584 /* If "remoteaddresssize" was not set, default to target address size. */
6585 if (!address_size)
f5656ead 6586 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
6587
6588 if (address_size > 0
6589 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
6590 {
6591 /* Only create a mask when that mask can safely be constructed
23860348 6592 in a ULONGEST variable. */
c906108c 6593 ULONGEST mask = 1;
a744cf53 6594
911c95a5 6595 mask = (mask << address_size) - 1;
c906108c
SS
6596 addr &= mask;
6597 }
6598 return addr;
6599}
6600
6601/* Determine whether the remote target supports binary downloading.
6602 This is accomplished by sending a no-op memory write of zero length
6603 to the target at the specified address. It does not suffice to send
23860348
MS
6604 the whole packet, since many stubs strip the eighth bit and
6605 subsequently compute a wrong checksum, which causes real havoc with
6606 remote_write_bytes.
7a292a7a 6607
96baa820 6608 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 6609 clean. In cases like this, the user should clear "remote
23860348 6610 X-packet". */
96baa820 6611
c906108c 6612static void
fba45db2 6613check_binary_download (CORE_ADDR addr)
c906108c 6614{
d01949b6 6615 struct remote_state *rs = get_remote_state ();
24b06219 6616
4082afcc 6617 switch (packet_support (PACKET_X))
c906108c 6618 {
96baa820
JM
6619 case PACKET_DISABLE:
6620 break;
6621 case PACKET_ENABLE:
6622 break;
6623 case PACKET_SUPPORT_UNKNOWN:
6624 {
96baa820 6625 char *p;
802188a7 6626
2e9f7625 6627 p = rs->buf;
96baa820
JM
6628 *p++ = 'X';
6629 p += hexnumstr (p, (ULONGEST) addr);
6630 *p++ = ',';
6631 p += hexnumstr (p, (ULONGEST) 0);
6632 *p++ = ':';
6633 *p = '\0';
802188a7 6634
2e9f7625 6635 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 6636 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 6637
2e9f7625 6638 if (rs->buf[0] == '\0')
96baa820
JM
6639 {
6640 if (remote_debug)
6641 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
6642 "binary downloading NOT "
6643 "supported by target\n");
444abaca 6644 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
6645 }
6646 else
6647 {
6648 if (remote_debug)
6649 fprintf_unfiltered (gdb_stdlog,
64b9b334 6650 "binary downloading supported by target\n");
444abaca 6651 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
6652 }
6653 break;
6654 }
c906108c
SS
6655 }
6656}
6657
6658/* Write memory data directly to the remote machine.
6659 This does not inform the data cache; the data cache uses this.
a76d924d 6660 HEADER is the starting part of the packet.
c906108c
SS
6661 MEMADDR is the address in the remote memory space.
6662 MYADDR is the address of the buffer in our space.
6663 LEN is the number of bytes.
a76d924d
DJ
6664 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6665 should send data as binary ('X'), or hex-encoded ('M').
6666
6667 The function creates packet of the form
6668 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6669
6670 where encoding of <DATA> is termined by PACKET_FORMAT.
6671
6672 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6673 are omitted.
6674
9b409511
YQ
6675 Return the transferred status, error or OK (an
6676 'enum target_xfer_status' value). Save the number of bytes
6677 transferred in *XFERED_LEN. Only transfer a single packet. */
c906108c 6678
9b409511 6679static enum target_xfer_status
a76d924d 6680remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
5d6df423 6681 const gdb_byte *myaddr, ULONGEST len,
9b409511
YQ
6682 ULONGEST *xfered_len, char packet_format,
6683 int use_length)
c906108c 6684{
6d820c5c 6685 struct remote_state *rs = get_remote_state ();
cfd77fa1 6686 char *p;
a76d924d
DJ
6687 char *plen = NULL;
6688 int plenlen = 0;
917317f4
JM
6689 int todo;
6690 int nr_bytes;
a257b5bb 6691 int payload_size;
6765f3e5 6692 int payload_length;
a76d924d
DJ
6693 int header_length;
6694
6695 if (packet_format != 'X' && packet_format != 'M')
6696 internal_error (__FILE__, __LINE__,
9b20d036 6697 _("remote_write_bytes_aux: bad packet format"));
c906108c 6698
5d6df423 6699 if (len == 0)
9b409511 6700 return TARGET_XFER_EOF;
b2182ed2 6701
3de11b2e 6702 payload_size = get_memory_write_packet_size ();
2bc416ba 6703
6d820c5c
DJ
6704 /* The packet buffer will be large enough for the payload;
6705 get_memory_packet_size ensures this. */
a76d924d 6706 rs->buf[0] = '\0';
c906108c 6707
a257b5bb 6708 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
6709 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6710
a76d924d
DJ
6711 payload_size -= strlen ("$,:#NN");
6712 if (!use_length)
0df8b418 6713 /* The comma won't be used. */
a76d924d
DJ
6714 payload_size += 1;
6715 header_length = strlen (header);
6716 payload_size -= header_length;
3de11b2e 6717 payload_size -= hexnumlen (memaddr);
c906108c 6718
a76d924d 6719 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 6720
a76d924d
DJ
6721 strcat (rs->buf, header);
6722 p = rs->buf + strlen (header);
6723
6724 /* Compute a best guess of the number of bytes actually transfered. */
6725 if (packet_format == 'X')
c906108c 6726 {
23860348 6727 /* Best guess at number of bytes that will fit. */
a257b5bb 6728 todo = min (len, payload_size);
a76d924d
DJ
6729 if (use_length)
6730 payload_size -= hexnumlen (todo);
3de11b2e 6731 todo = min (todo, payload_size);
a76d924d
DJ
6732 }
6733 else
6734 {
23860348 6735 /* Num bytes that will fit. */
a257b5bb 6736 todo = min (len, payload_size / 2);
a76d924d
DJ
6737 if (use_length)
6738 payload_size -= hexnumlen (todo);
3de11b2e 6739 todo = min (todo, payload_size / 2);
917317f4 6740 }
a76d924d 6741
3de11b2e
NS
6742 if (todo <= 0)
6743 internal_error (__FILE__, __LINE__,
405f8e94 6744 _("minimum packet size too small to write data"));
802188a7 6745
6765f3e5
DJ
6746 /* If we already need another packet, then try to align the end
6747 of this packet to a useful boundary. */
6748 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6749 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6750
a257b5bb 6751 /* Append "<memaddr>". */
917317f4
JM
6752 memaddr = remote_address_masked (memaddr);
6753 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 6754
a76d924d
DJ
6755 if (use_length)
6756 {
6757 /* Append ",". */
6758 *p++ = ',';
802188a7 6759
a76d924d
DJ
6760 /* Append <len>. Retain the location/size of <len>. It may need to
6761 be adjusted once the packet body has been created. */
6762 plen = p;
6763 plenlen = hexnumstr (p, (ULONGEST) todo);
6764 p += plenlen;
6765 }
a257b5bb
AC
6766
6767 /* Append ":". */
917317f4
JM
6768 *p++ = ':';
6769 *p = '\0';
802188a7 6770
a257b5bb 6771 /* Append the packet body. */
a76d924d 6772 if (packet_format == 'X')
917317f4 6773 {
917317f4
JM
6774 /* Binary mode. Send target system values byte by byte, in
6775 increasing byte addresses. Only escape certain critical
6776 characters. */
bc20a4af
PA
6777 payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
6778 &nr_bytes, payload_size);
6765f3e5
DJ
6779
6780 /* If not all TODO bytes fit, then we'll need another packet. Make
9b7194bc
DJ
6781 a second try to keep the end of the packet aligned. Don't do
6782 this if the packet is tiny. */
6783 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6765f3e5
DJ
6784 {
6785 int new_nr_bytes;
6786
6787 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6788 - memaddr);
6789 if (new_nr_bytes != nr_bytes)
6790 payload_length = remote_escape_output (myaddr, new_nr_bytes,
bc20a4af 6791 (gdb_byte *) p, &nr_bytes,
6765f3e5
DJ
6792 payload_size);
6793 }
6794
6795 p += payload_length;
a76d924d 6796 if (use_length && nr_bytes < todo)
c906108c 6797 {
802188a7 6798 /* Escape chars have filled up the buffer prematurely,
917317f4
JM
6799 and we have actually sent fewer bytes than planned.
6800 Fix-up the length field of the packet. Use the same
6801 number of characters as before. */
917317f4
JM
6802 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6803 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 6804 }
a76d924d
DJ
6805 }
6806 else
6807 {
917317f4
JM
6808 /* Normal mode: Send target system values byte by byte, in
6809 increasing byte addresses. Each byte is encoded as a two hex
6810 value. */
2644f393 6811 nr_bytes = bin2hex (myaddr, p, todo);
aa6c0017 6812 p += 2 * nr_bytes;
c906108c 6813 }
802188a7 6814
2e9f7625 6815 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 6816 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 6817
2e9f7625 6818 if (rs->buf[0] == 'E')
00d84524 6819 return TARGET_XFER_E_IO;
802188a7 6820
23860348
MS
6821 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6822 fewer bytes than we'd planned. */
9b409511
YQ
6823 *xfered_len = (ULONGEST) nr_bytes;
6824 return TARGET_XFER_OK;
c906108c
SS
6825}
6826
a76d924d
DJ
6827/* Write memory data directly to the remote machine.
6828 This does not inform the data cache; the data cache uses this.
6829 MEMADDR is the address in the remote memory space.
6830 MYADDR is the address of the buffer in our space.
6831 LEN is the number of bytes.
6832
9b409511
YQ
6833 Return the transferred status, error or OK (an
6834 'enum target_xfer_status' value). Save the number of bytes
6835 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 6836
9b409511
YQ
6837static enum target_xfer_status
6838remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
6839 ULONGEST *xfered_len)
a76d924d
DJ
6840{
6841 char *packet_format = 0;
6842
6843 /* Check whether the target supports binary download. */
6844 check_binary_download (memaddr);
6845
4082afcc 6846 switch (packet_support (PACKET_X))
a76d924d
DJ
6847 {
6848 case PACKET_ENABLE:
6849 packet_format = "X";
6850 break;
6851 case PACKET_DISABLE:
6852 packet_format = "M";
6853 break;
6854 case PACKET_SUPPORT_UNKNOWN:
6855 internal_error (__FILE__, __LINE__,
6856 _("remote_write_bytes: bad internal state"));
6857 default:
6858 internal_error (__FILE__, __LINE__, _("bad switch"));
6859 }
6860
6861 return remote_write_bytes_aux (packet_format,
9b409511
YQ
6862 memaddr, myaddr, len, xfered_len,
6863 packet_format[0], 1);
a76d924d
DJ
6864}
6865
9217e74e
YQ
6866/* Read memory data directly from the remote machine.
6867 This does not use the data cache; the data cache uses this.
6868 MEMADDR is the address in the remote memory space.
6869 MYADDR is the address of the buffer in our space.
6870 LEN is the number of bytes.
6871
6872 Return the transferred status, error or OK (an
6873 'enum target_xfer_status' value). Save the number of bytes
6874 transferred in *XFERED_LEN. */
6875
6876static enum target_xfer_status
6877remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len,
6878 ULONGEST *xfered_len)
6879{
6880 struct remote_state *rs = get_remote_state ();
6881 int max_buf_size; /* Max size of packet output buffer. */
6882 char *p;
6883 int todo;
6884 int i;
6885
6886 max_buf_size = get_memory_read_packet_size ();
6887 /* The packet buffer will be large enough for the payload;
6888 get_memory_packet_size ensures this. */
6889
6890 /* Number if bytes that will fit. */
6891 todo = min (len, max_buf_size / 2);
6892
6893 /* Construct "m"<memaddr>","<len>". */
6894 memaddr = remote_address_masked (memaddr);
6895 p = rs->buf;
6896 *p++ = 'm';
6897 p += hexnumstr (p, (ULONGEST) memaddr);
6898 *p++ = ',';
6899 p += hexnumstr (p, (ULONGEST) todo);
6900 *p = '\0';
6901 putpkt (rs->buf);
6902 getpkt (&rs->buf, &rs->buf_size, 0);
6903 if (rs->buf[0] == 'E'
6904 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6905 && rs->buf[3] == '\0')
6906 return TARGET_XFER_E_IO;
6907 /* Reply describes memory byte by byte, each byte encoded as two hex
6908 characters. */
6909 p = rs->buf;
6910 i = hex2bin (p, myaddr, todo);
6911 /* Return what we have. Let higher layers handle partial reads. */
6912 *xfered_len = (ULONGEST) i;
6913 return TARGET_XFER_OK;
6914}
6915
b55fbac4
YQ
6916/* Using the set of read-only target sections of remote, read live
6917 read-only memory.
8acf9577
YQ
6918
6919 For interface/parameters/return description see target.h,
6920 to_xfer_partial. */
6921
6922static enum target_xfer_status
b55fbac4
YQ
6923remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
6924 ULONGEST memaddr, ULONGEST len,
6925 ULONGEST *xfered_len)
8acf9577
YQ
6926{
6927 struct target_section *secp;
6928 struct target_section_table *table;
6929
6930 secp = target_section_by_addr (ops, memaddr);
6931 if (secp != NULL
6932 && (bfd_get_section_flags (secp->the_bfd_section->owner,
6933 secp->the_bfd_section)
6934 & SEC_READONLY))
6935 {
6936 struct target_section *p;
6937 ULONGEST memend = memaddr + len;
6938
6939 table = target_get_section_table (ops);
6940
6941 for (p = table->sections; p < table->sections_end; p++)
6942 {
6943 if (memaddr >= p->addr)
6944 {
6945 if (memend <= p->endaddr)
6946 {
6947 /* Entire transfer is within this section. */
b55fbac4
YQ
6948 return remote_read_bytes_1 (memaddr, readbuf, len,
6949 xfered_len);
8acf9577
YQ
6950 }
6951 else if (memaddr >= p->endaddr)
6952 {
6953 /* This section ends before the transfer starts. */
6954 continue;
6955 }
6956 else
6957 {
6958 /* This section overlaps the transfer. Just do half. */
6959 len = p->endaddr - memaddr;
b55fbac4
YQ
6960 return remote_read_bytes_1 (memaddr, readbuf, len,
6961 xfered_len);
8acf9577
YQ
6962 }
6963 }
6964 }
6965 }
6966
6967 return TARGET_XFER_EOF;
6968}
6969
9217e74e
YQ
6970/* Similar to remote_read_bytes_1, but it reads from the remote stub
6971 first if the requested memory is unavailable in traceframe.
6972 Otherwise, fall back to remote_read_bytes_1. */
c906108c 6973
9b409511 6974static enum target_xfer_status
8acf9577
YQ
6975remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
6976 gdb_byte *myaddr, ULONGEST len, ULONGEST *xfered_len)
c906108c 6977{
6b6aa828 6978 if (len == 0)
96c4f946 6979 return TARGET_XFER_EOF;
b2182ed2 6980
8acf9577
YQ
6981 if (get_traceframe_number () != -1)
6982 {
6983 VEC(mem_range_s) *available;
6984
6985 /* If we fail to get the set of available memory, then the
6986 target does not support querying traceframe info, and so we
6987 attempt reading from the traceframe anyway (assuming the
6988 target implements the old QTro packet then). */
6989 if (traceframe_available_memory (&available, memaddr, len))
6990 {
6991 struct cleanup *old_chain;
6992
6993 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
6994
6995 if (VEC_empty (mem_range_s, available)
6996 || VEC_index (mem_range_s, available, 0)->start != memaddr)
6997 {
6998 enum target_xfer_status res;
6999
7000 /* Don't read into the traceframe's available
7001 memory. */
7002 if (!VEC_empty (mem_range_s, available))
7003 {
7004 LONGEST oldlen = len;
7005
7006 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7007 gdb_assert (len <= oldlen);
7008 }
7009
7010 do_cleanups (old_chain);
7011
7012 /* This goes through the topmost target again. */
b55fbac4 7013 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8acf9577
YQ
7014 len, xfered_len);
7015 if (res == TARGET_XFER_OK)
7016 return TARGET_XFER_OK;
7017 else
7018 {
7019 /* No use trying further, we know some memory starting
7020 at MEMADDR isn't available. */
7021 *xfered_len = len;
7022 return TARGET_XFER_UNAVAILABLE;
7023 }
7024 }
7025
7026 /* Don't try to read more than how much is available, in
7027 case the target implements the deprecated QTro packet to
7028 cater for older GDBs (the target's knowledge of read-only
7029 sections may be outdated by now). */
7030 len = VEC_index (mem_range_s, available, 0)->length;
7031
7032 do_cleanups (old_chain);
7033 }
7034 }
7035
9217e74e 7036 return remote_read_bytes_1 (memaddr, myaddr, len, xfered_len);
c906108c 7037}
74531fed 7038
c906108c 7039\f
c906108c 7040
a76d924d
DJ
7041/* Sends a packet with content determined by the printf format string
7042 FORMAT and the remaining arguments, then gets the reply. Returns
7043 whether the packet was a success, a failure, or unknown. */
7044
77b64a49
PA
7045static enum packet_result remote_send_printf (const char *format, ...)
7046 ATTRIBUTE_PRINTF (1, 2);
7047
2c0b251b 7048static enum packet_result
a76d924d
DJ
7049remote_send_printf (const char *format, ...)
7050{
7051 struct remote_state *rs = get_remote_state ();
7052 int max_size = get_remote_packet_size ();
a76d924d 7053 va_list ap;
a744cf53 7054
a76d924d
DJ
7055 va_start (ap, format);
7056
7057 rs->buf[0] = '\0';
7058 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 7059 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
7060
7061 if (putpkt (rs->buf) < 0)
7062 error (_("Communication problem with target."));
7063
7064 rs->buf[0] = '\0';
7065 getpkt (&rs->buf, &rs->buf_size, 0);
7066
7067 return packet_check_result (rs->buf);
7068}
7069
7070static void
7071restore_remote_timeout (void *p)
7072{
7073 int value = *(int *)p;
a744cf53 7074
a76d924d
DJ
7075 remote_timeout = value;
7076}
7077
7078/* Flash writing can take quite some time. We'll set
7079 effectively infinite timeout for flash operations.
7080 In future, we'll need to decide on a better approach. */
7081static const int remote_flash_timeout = 1000;
7082
7083static void
7084remote_flash_erase (struct target_ops *ops,
7085 ULONGEST address, LONGEST length)
7086{
f5656ead 7087 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
7088 int saved_remote_timeout = remote_timeout;
7089 enum packet_result ret;
a76d924d
DJ
7090 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7091 &saved_remote_timeout);
a744cf53 7092
a76d924d
DJ
7093 remote_timeout = remote_flash_timeout;
7094
7095 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 7096 phex (address, addr_size),
a76d924d
DJ
7097 phex (length, 4));
7098 switch (ret)
7099 {
7100 case PACKET_UNKNOWN:
7101 error (_("Remote target does not support flash erase"));
7102 case PACKET_ERROR:
7103 error (_("Error erasing flash with vFlashErase packet"));
7104 default:
7105 break;
7106 }
7107
7108 do_cleanups (back_to);
7109}
7110
9b409511
YQ
7111static enum target_xfer_status
7112remote_flash_write (struct target_ops *ops, ULONGEST address,
7113 ULONGEST length, ULONGEST *xfered_len,
7114 const gdb_byte *data)
a76d924d
DJ
7115{
7116 int saved_remote_timeout = remote_timeout;
9b409511 7117 enum target_xfer_status ret;
a76d924d 7118 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 7119 &saved_remote_timeout);
a76d924d
DJ
7120
7121 remote_timeout = remote_flash_timeout;
9b409511
YQ
7122 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length,
7123 xfered_len,'X', 0);
a76d924d
DJ
7124 do_cleanups (back_to);
7125
7126 return ret;
7127}
7128
7129static void
7130remote_flash_done (struct target_ops *ops)
7131{
7132 int saved_remote_timeout = remote_timeout;
7133 int ret;
7134 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7135 &saved_remote_timeout);
7136
7137 remote_timeout = remote_flash_timeout;
7138 ret = remote_send_printf ("vFlashDone");
7139 do_cleanups (back_to);
7140
7141 switch (ret)
7142 {
7143 case PACKET_UNKNOWN:
7144 error (_("Remote target does not support vFlashDone"));
7145 case PACKET_ERROR:
7146 error (_("Error finishing flash operation"));
7147 default:
7148 break;
7149 }
7150}
7151
c906108c 7152static void
fba45db2 7153remote_files_info (struct target_ops *ignore)
c906108c
SS
7154{
7155 puts_filtered ("Debugging a target over a serial line.\n");
7156}
7157\f
7158/* Stuff for dealing with the packets which are part of this protocol.
7159 See comment at top of file for details. */
7160
1927e618
PA
7161/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7162 error to higher layers. Called when a serial error is detected.
7163 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
7164 the system error message for errno at function entry and final dot
7165 for output compatibility with throw_perror_with_name. */
1927e618
PA
7166
7167static void
7168unpush_and_perror (const char *string)
7169{
d6cb50a2 7170 int saved_errno = errno;
1927e618
PA
7171
7172 remote_unpush_target ();
d6cb50a2
JK
7173 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7174 safe_strerror (saved_errno));
1927e618
PA
7175}
7176
0876f84a 7177/* Read a single character from the remote end. */
c906108c
SS
7178
7179static int
fba45db2 7180readchar (int timeout)
c906108c
SS
7181{
7182 int ch;
5d93a237 7183 struct remote_state *rs = get_remote_state ();
c906108c 7184
5d93a237 7185 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 7186
2acceee2 7187 if (ch >= 0)
0876f84a 7188 return ch;
2acceee2
JM
7189
7190 switch ((enum serial_rc) ch)
c906108c
SS
7191 {
7192 case SERIAL_EOF:
78a095c3 7193 remote_unpush_target ();
598d3636 7194 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 7195 /* no return */
c906108c 7196 case SERIAL_ERROR:
1927e618
PA
7197 unpush_and_perror (_("Remote communication error. "
7198 "Target disconnected."));
2acceee2 7199 /* no return */
c906108c 7200 case SERIAL_TIMEOUT:
2acceee2 7201 break;
c906108c 7202 }
2acceee2 7203 return ch;
c906108c
SS
7204}
7205
c33e31fd
PA
7206/* Wrapper for serial_write that closes the target and throws if
7207 writing fails. */
7208
7209static void
7210remote_serial_write (const char *str, int len)
7211{
5d93a237
TT
7212 struct remote_state *rs = get_remote_state ();
7213
7214 if (serial_write (rs->remote_desc, str, len))
c33e31fd 7215 {
1927e618
PA
7216 unpush_and_perror (_("Remote communication error. "
7217 "Target disconnected."));
c33e31fd
PA
7218 }
7219}
7220
6d820c5c
DJ
7221/* Send the command in *BUF to the remote machine, and read the reply
7222 into *BUF. Report an error if we get an error reply. Resize
7223 *BUF using xrealloc if necessary to hold the result, and update
7224 *SIZEOF_BUF. */
c906108c
SS
7225
7226static void
6d820c5c
DJ
7227remote_send (char **buf,
7228 long *sizeof_buf)
c906108c 7229{
6d820c5c 7230 putpkt (*buf);
c2d11a7d 7231 getpkt (buf, sizeof_buf, 0);
c906108c 7232
6d820c5c
DJ
7233 if ((*buf)[0] == 'E')
7234 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
7235}
7236
6e5abd65
PA
7237/* Return a pointer to an xmalloc'ed string representing an escaped
7238 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7239 etc. The caller is responsible for releasing the returned
7240 memory. */
7241
7242static char *
7243escape_buffer (const char *buf, int n)
7244{
7245 struct cleanup *old_chain;
7246 struct ui_file *stb;
7247 char *str;
6e5abd65
PA
7248
7249 stb = mem_fileopen ();
7250 old_chain = make_cleanup_ui_file_delete (stb);
7251
6ef284bd 7252 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 7253 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
7254 do_cleanups (old_chain);
7255 return str;
7256}
7257
c906108c
SS
7258/* Display a null-terminated packet on stdout, for debugging, using C
7259 string notation. */
7260
7261static void
baa336ce 7262print_packet (const char *buf)
c906108c
SS
7263{
7264 puts_filtered ("\"");
43e526b9 7265 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
7266 puts_filtered ("\"");
7267}
7268
7269int
baa336ce 7270putpkt (const char *buf)
c906108c
SS
7271{
7272 return putpkt_binary (buf, strlen (buf));
7273}
7274
7275/* Send a packet to the remote machine, with error checking. The data
23860348 7276 of the packet is in BUF. The string in BUF can be at most
ea9c271d 7277 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
7278 and for a possible /0 if we are debugging (remote_debug) and want
7279 to print the sent packet as a string. */
c906108c
SS
7280
7281static int
baa336ce 7282putpkt_binary (const char *buf, int cnt)
c906108c 7283{
2d717e4f 7284 struct remote_state *rs = get_remote_state ();
c906108c
SS
7285 int i;
7286 unsigned char csum = 0;
11cf8741 7287 char *buf2 = alloca (cnt + 6);
085dd6e6 7288
c906108c
SS
7289 int ch;
7290 int tcount = 0;
7291 char *p;
dd61ec5c 7292 char *message;
c906108c 7293
e24a49d8
PA
7294 /* Catch cases like trying to read memory or listing threads while
7295 we're waiting for a stop reply. The remote server wouldn't be
7296 ready to handle this request, so we'd hang and timeout. We don't
7297 have to worry about this in synchronous mode, because in that
7298 case it's not possible to issue a command while the target is
74531fed
PA
7299 running. This is not a problem in non-stop mode, because in that
7300 case, the stub is always ready to process serial input. */
d9d41e78 7301 if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
9597b22a
DE
7302 {
7303 error (_("Cannot execute this command while the target is running.\n"
7304 "Use the \"interrupt\" command to stop the target\n"
7305 "and then try again."));
7306 }
e24a49d8 7307
2d717e4f
DJ
7308 /* We're sending out a new packet. Make sure we don't look at a
7309 stale cached response. */
7310 rs->cached_wait_status = 0;
7311
c906108c
SS
7312 /* Copy the packet into buffer BUF2, encapsulating it
7313 and giving it a checksum. */
7314
c906108c
SS
7315 p = buf2;
7316 *p++ = '$';
7317
7318 for (i = 0; i < cnt; i++)
7319 {
7320 csum += buf[i];
7321 *p++ = buf[i];
7322 }
7323 *p++ = '#';
7324 *p++ = tohex ((csum >> 4) & 0xf);
7325 *p++ = tohex (csum & 0xf);
7326
7327 /* Send it over and over until we get a positive ack. */
7328
7329 while (1)
7330 {
7331 int started_error_output = 0;
7332
7333 if (remote_debug)
7334 {
6e5abd65
PA
7335 struct cleanup *old_chain;
7336 char *str;
7337
c906108c 7338 *p = '\0';
6e5abd65
PA
7339 str = escape_buffer (buf2, p - buf2);
7340 old_chain = make_cleanup (xfree, str);
7341 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 7342 gdb_flush (gdb_stdlog);
6e5abd65 7343 do_cleanups (old_chain);
c906108c 7344 }
c33e31fd 7345 remote_serial_write (buf2, p - buf2);
c906108c 7346
a6f3e723
SL
7347 /* If this is a no acks version of the remote protocol, send the
7348 packet and move on. */
7349 if (rs->noack_mode)
7350 break;
7351
74531fed
PA
7352 /* Read until either a timeout occurs (-2) or '+' is read.
7353 Handle any notification that arrives in the mean time. */
c906108c
SS
7354 while (1)
7355 {
7356 ch = readchar (remote_timeout);
7357
c5aa993b 7358 if (remote_debug)
c906108c
SS
7359 {
7360 switch (ch)
7361 {
7362 case '+':
1216fa2c 7363 case '-':
c906108c
SS
7364 case SERIAL_TIMEOUT:
7365 case '$':
74531fed 7366 case '%':
c906108c
SS
7367 if (started_error_output)
7368 {
7369 putchar_unfiltered ('\n');
7370 started_error_output = 0;
7371 }
7372 }
7373 }
7374
7375 switch (ch)
7376 {
7377 case '+':
7378 if (remote_debug)
0f71a2f6 7379 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 7380 return 1;
1216fa2c
AC
7381 case '-':
7382 if (remote_debug)
7383 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 7384 /* FALLTHROUGH */
c906108c 7385 case SERIAL_TIMEOUT:
c5aa993b 7386 tcount++;
c906108c
SS
7387 if (tcount > 3)
7388 return 0;
23860348 7389 break; /* Retransmit buffer. */
c906108c
SS
7390 case '$':
7391 {
40e3f985 7392 if (remote_debug)
2bc416ba 7393 fprintf_unfiltered (gdb_stdlog,
23860348 7394 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
7395 /* It's probably an old response sent because an ACK
7396 was lost. Gobble up the packet and ack it so it
7397 doesn't get retransmitted when we resend this
7398 packet. */
6d820c5c 7399 skip_frame ();
c33e31fd 7400 remote_serial_write ("+", 1);
23860348 7401 continue; /* Now, go look for +. */
c906108c 7402 }
74531fed
PA
7403
7404 case '%':
7405 {
7406 int val;
7407
7408 /* If we got a notification, handle it, and go back to looking
7409 for an ack. */
7410 /* We've found the start of a notification. Now
7411 collect the data. */
7412 val = read_frame (&rs->buf, &rs->buf_size);
7413 if (val >= 0)
7414 {
7415 if (remote_debug)
7416 {
6e5abd65
PA
7417 struct cleanup *old_chain;
7418 char *str;
7419
7420 str = escape_buffer (rs->buf, val);
7421 old_chain = make_cleanup (xfree, str);
7422 fprintf_unfiltered (gdb_stdlog,
7423 " Notification received: %s\n",
7424 str);
7425 do_cleanups (old_chain);
74531fed 7426 }
5965e028 7427 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
7428 /* We're in sync now, rewait for the ack. */
7429 tcount = 0;
7430 }
7431 else
7432 {
7433 if (remote_debug)
7434 {
7435 if (!started_error_output)
7436 {
7437 started_error_output = 1;
7438 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7439 }
7440 fputc_unfiltered (ch & 0177, gdb_stdlog);
7441 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7442 }
7443 }
7444 continue;
7445 }
7446 /* fall-through */
c906108c
SS
7447 default:
7448 if (remote_debug)
7449 {
7450 if (!started_error_output)
7451 {
7452 started_error_output = 1;
0f71a2f6 7453 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 7454 }
0f71a2f6 7455 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
7456 }
7457 continue;
7458 }
23860348 7459 break; /* Here to retransmit. */
c906108c
SS
7460 }
7461
7462#if 0
7463 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
7464 able to get out next time we call QUIT, without anything as
7465 violent as interrupt_query. If we want to provide a way out of
7466 here without getting to the next QUIT, it should be based on
7467 hitting ^C twice as in remote_wait. */
c906108c
SS
7468 if (quit_flag)
7469 {
7470 quit_flag = 0;
7471 interrupt_query ();
7472 }
7473#endif
7474 }
a6f3e723 7475 return 0;
c906108c
SS
7476}
7477
6d820c5c
DJ
7478/* Come here after finding the start of a frame when we expected an
7479 ack. Do our best to discard the rest of this packet. */
7480
7481static void
7482skip_frame (void)
7483{
7484 int c;
7485
7486 while (1)
7487 {
7488 c = readchar (remote_timeout);
7489 switch (c)
7490 {
7491 case SERIAL_TIMEOUT:
7492 /* Nothing we can do. */
7493 return;
7494 case '#':
7495 /* Discard the two bytes of checksum and stop. */
7496 c = readchar (remote_timeout);
7497 if (c >= 0)
7498 c = readchar (remote_timeout);
7499
7500 return;
7501 case '*': /* Run length encoding. */
7502 /* Discard the repeat count. */
7503 c = readchar (remote_timeout);
7504 if (c < 0)
7505 return;
7506 break;
7507 default:
7508 /* A regular character. */
7509 break;
7510 }
7511 }
7512}
7513
c906108c 7514/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
7515 into *BUF, verifying the checksum, length, and handling run-length
7516 compression. NUL terminate the buffer. If there is not enough room,
7517 expand *BUF using xrealloc.
c906108c 7518
c2d11a7d
JM
7519 Returns -1 on error, number of characters in buffer (ignoring the
7520 trailing NULL) on success. (could be extended to return one of the
23860348 7521 SERIAL status indications). */
c2d11a7d
JM
7522
7523static long
6d820c5c
DJ
7524read_frame (char **buf_p,
7525 long *sizeof_buf)
c906108c
SS
7526{
7527 unsigned char csum;
c2d11a7d 7528 long bc;
c906108c 7529 int c;
6d820c5c 7530 char *buf = *buf_p;
a6f3e723 7531 struct remote_state *rs = get_remote_state ();
c906108c
SS
7532
7533 csum = 0;
c2d11a7d 7534 bc = 0;
c906108c
SS
7535
7536 while (1)
7537 {
7538 c = readchar (remote_timeout);
c906108c
SS
7539 switch (c)
7540 {
7541 case SERIAL_TIMEOUT:
7542 if (remote_debug)
0f71a2f6 7543 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 7544 return -1;
c906108c
SS
7545 case '$':
7546 if (remote_debug)
0f71a2f6
JM
7547 fputs_filtered ("Saw new packet start in middle of old one\n",
7548 gdb_stdlog);
23860348 7549 return -1; /* Start a new packet, count retries. */
c906108c
SS
7550 case '#':
7551 {
7552 unsigned char pktcsum;
e1b09194
AC
7553 int check_0 = 0;
7554 int check_1 = 0;
c906108c 7555
c2d11a7d 7556 buf[bc] = '\0';
c906108c 7557
e1b09194
AC
7558 check_0 = readchar (remote_timeout);
7559 if (check_0 >= 0)
7560 check_1 = readchar (remote_timeout);
802188a7 7561
e1b09194
AC
7562 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7563 {
7564 if (remote_debug)
2bc416ba 7565 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 7566 gdb_stdlog);
e1b09194
AC
7567 return -1;
7568 }
7569 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
7570 {
7571 if (remote_debug)
2bc416ba 7572 fputs_filtered ("Communication error in checksum\n",
23860348 7573 gdb_stdlog);
40e3f985
FN
7574 return -1;
7575 }
c906108c 7576
a6f3e723
SL
7577 /* Don't recompute the checksum; with no ack packets we
7578 don't have any way to indicate a packet retransmission
7579 is necessary. */
7580 if (rs->noack_mode)
7581 return bc;
7582
e1b09194 7583 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 7584 if (csum == pktcsum)
c2d11a7d 7585 return bc;
c906108c 7586
c5aa993b 7587 if (remote_debug)
c906108c 7588 {
6e5abd65
PA
7589 struct cleanup *old_chain;
7590 char *str;
7591
7592 str = escape_buffer (buf, bc);
7593 old_chain = make_cleanup (xfree, str);
7594 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7595 "Bad checksum, sentsum=0x%x, "
7596 "csum=0x%x, buf=%s\n",
6e5abd65
PA
7597 pktcsum, csum, str);
7598 do_cleanups (old_chain);
c906108c 7599 }
c2d11a7d 7600 /* Number of characters in buffer ignoring trailing
23860348 7601 NULL. */
c2d11a7d 7602 return -1;
c906108c 7603 }
23860348 7604 case '*': /* Run length encoding. */
c2c6d25f
JM
7605 {
7606 int repeat;
c906108c 7607
a744cf53 7608 csum += c;
b4501125
AC
7609 c = readchar (remote_timeout);
7610 csum += c;
23860348 7611 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 7612
23860348 7613 /* The character before ``*'' is repeated. */
c2d11a7d 7614
6d820c5c 7615 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 7616 {
6d820c5c
DJ
7617 if (bc + repeat - 1 >= *sizeof_buf - 1)
7618 {
7619 /* Make some more room in the buffer. */
7620 *sizeof_buf += repeat;
7621 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7622 buf = *buf_p;
7623 }
7624
c2d11a7d
JM
7625 memset (&buf[bc], buf[bc - 1], repeat);
7626 bc += repeat;
c2c6d25f
JM
7627 continue;
7628 }
7629
c2d11a7d 7630 buf[bc] = '\0';
6d820c5c 7631 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 7632 return -1;
c2c6d25f 7633 }
c906108c 7634 default:
6d820c5c 7635 if (bc >= *sizeof_buf - 1)
c906108c 7636 {
6d820c5c
DJ
7637 /* Make some more room in the buffer. */
7638 *sizeof_buf *= 2;
7639 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7640 buf = *buf_p;
c906108c
SS
7641 }
7642
6d820c5c
DJ
7643 buf[bc++] = c;
7644 csum += c;
7645 continue;
c906108c
SS
7646 }
7647 }
7648}
7649
7650/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
7651 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7652 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7653 rather than timing out; this is used (in synchronous mode) to wait
7654 for a target that is is executing user code to stop. */
d9fcf2fb
JM
7655/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7656 don't have to change all the calls to getpkt to deal with the
7657 return value, because at the moment I don't know what the right
23860348 7658 thing to do it for those. */
c906108c 7659void
6d820c5c
DJ
7660getpkt (char **buf,
7661 long *sizeof_buf,
c2d11a7d 7662 int forever)
d9fcf2fb
JM
7663{
7664 int timed_out;
7665
7666 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7667}
7668
7669
7670/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
7671 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7672 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7673 rather than timing out; this is used (in synchronous mode) to wait
7674 for a target that is is executing user code to stop. If FOREVER ==
7675 0, this function is allowed to time out gracefully and return an
74531fed
PA
7676 indication of this to the caller. Otherwise return the number of
7677 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
7678 enough reason to return to the caller. *IS_NOTIF is an output
7679 boolean that indicates whether *BUF holds a notification or not
7680 (a regular packet). */
74531fed 7681
3172dc30 7682static int
74531fed 7683getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 7684 int expecting_notif, int *is_notif)
c906108c 7685{
2d717e4f 7686 struct remote_state *rs = get_remote_state ();
c906108c
SS
7687 int c;
7688 int tries;
7689 int timeout;
df4b58fe 7690 int val = -1;
c906108c 7691
2d717e4f
DJ
7692 /* We're reading a new response. Make sure we don't look at a
7693 previously cached response. */
7694 rs->cached_wait_status = 0;
7695
6d820c5c 7696 strcpy (*buf, "timeout");
c906108c
SS
7697
7698 if (forever)
74531fed
PA
7699 timeout = watchdog > 0 ? watchdog : -1;
7700 else if (expecting_notif)
7701 timeout = 0; /* There should already be a char in the buffer. If
7702 not, bail out. */
c906108c
SS
7703 else
7704 timeout = remote_timeout;
7705
7706#define MAX_TRIES 3
7707
74531fed
PA
7708 /* Process any number of notifications, and then return when
7709 we get a packet. */
7710 for (;;)
c906108c 7711 {
d9c43928 7712 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
7713 times. */
7714 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 7715 {
74531fed
PA
7716 /* This can loop forever if the remote side sends us
7717 characters continuously, but if it pauses, we'll get
7718 SERIAL_TIMEOUT from readchar because of timeout. Then
7719 we'll count that as a retry.
7720
7721 Note that even when forever is set, we will only wait
7722 forever prior to the start of a packet. After that, we
7723 expect characters to arrive at a brisk pace. They should
7724 show up within remote_timeout intervals. */
7725 do
7726 c = readchar (timeout);
7727 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
7728
7729 if (c == SERIAL_TIMEOUT)
7730 {
74531fed
PA
7731 if (expecting_notif)
7732 return -1; /* Don't complain, it's normal to not get
7733 anything in this case. */
7734
23860348 7735 if (forever) /* Watchdog went off? Kill the target. */
c906108c 7736 {
2acceee2 7737 QUIT;
78a095c3 7738 remote_unpush_target ();
598d3636
JK
7739 throw_error (TARGET_CLOSE_ERROR,
7740 _("Watchdog timeout has expired. "
7741 "Target detached."));
c906108c 7742 }
c906108c 7743 if (remote_debug)
0f71a2f6 7744 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 7745 }
74531fed
PA
7746 else
7747 {
7748 /* We've found the start of a packet or notification.
7749 Now collect the data. */
7750 val = read_frame (buf, sizeof_buf);
7751 if (val >= 0)
7752 break;
7753 }
7754
c33e31fd 7755 remote_serial_write ("-", 1);
c906108c 7756 }
c906108c 7757
74531fed
PA
7758 if (tries > MAX_TRIES)
7759 {
7760 /* We have tried hard enough, and just can't receive the
7761 packet/notification. Give up. */
7762 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 7763
74531fed
PA
7764 /* Skip the ack char if we're in no-ack mode. */
7765 if (!rs->noack_mode)
c33e31fd 7766 remote_serial_write ("+", 1);
74531fed
PA
7767 return -1;
7768 }
c906108c 7769
74531fed
PA
7770 /* If we got an ordinary packet, return that to our caller. */
7771 if (c == '$')
c906108c
SS
7772 {
7773 if (remote_debug)
43e526b9 7774 {
6e5abd65
PA
7775 struct cleanup *old_chain;
7776 char *str;
7777
7778 str = escape_buffer (*buf, val);
7779 old_chain = make_cleanup (xfree, str);
7780 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7781 do_cleanups (old_chain);
43e526b9 7782 }
a6f3e723
SL
7783
7784 /* Skip the ack char if we're in no-ack mode. */
7785 if (!rs->noack_mode)
c33e31fd 7786 remote_serial_write ("+", 1);
fee9eda9
YQ
7787 if (is_notif != NULL)
7788 *is_notif = 0;
0876f84a 7789 return val;
c906108c
SS
7790 }
7791
74531fed
PA
7792 /* If we got a notification, handle it, and go back to looking
7793 for a packet. */
7794 else
7795 {
7796 gdb_assert (c == '%');
7797
7798 if (remote_debug)
7799 {
6e5abd65
PA
7800 struct cleanup *old_chain;
7801 char *str;
7802
7803 str = escape_buffer (*buf, val);
7804 old_chain = make_cleanup (xfree, str);
7805 fprintf_unfiltered (gdb_stdlog,
7806 " Notification received: %s\n",
7807 str);
7808 do_cleanups (old_chain);
74531fed 7809 }
fee9eda9
YQ
7810 if (is_notif != NULL)
7811 *is_notif = 1;
c906108c 7812
5965e028 7813 handle_notification (rs->notif_state, *buf);
c906108c 7814
74531fed 7815 /* Notifications require no acknowledgement. */
a6f3e723 7816
74531fed 7817 if (expecting_notif)
fee9eda9 7818 return val;
74531fed
PA
7819 }
7820 }
7821}
7822
7823static int
7824getpkt_sane (char **buf, long *sizeof_buf, int forever)
7825{
fee9eda9 7826 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
7827}
7828
7829static int
fee9eda9
YQ
7830getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
7831 int *is_notif)
74531fed 7832{
fee9eda9
YQ
7833 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
7834 is_notif);
c906108c 7835}
74531fed 7836
c906108c
SS
7837\f
7838static void
7d85a9c0 7839remote_kill (struct target_ops *ops)
43ff13b4 7840{
0fdf84ca
PA
7841
7842 /* Catch errors so the user can quit from gdb even when we
23860348 7843 aren't on speaking terms with the remote system. */
492d29ea 7844 TRY
0fdf84ca
PA
7845 {
7846 putpkt ("k");
7847 }
492d29ea 7848 CATCH (ex, RETURN_MASK_ERROR)
0fdf84ca
PA
7849 {
7850 if (ex.error == TARGET_CLOSE_ERROR)
7851 {
7852 /* If we got an (EOF) error that caused the target
7853 to go away, then we're done, that's what we wanted.
7854 "k" is susceptible to cause a premature EOF, given
7855 that the remote server isn't actually required to
7856 reply to "k", and it can happen that it doesn't
7857 even get to reply ACK to the "k". */
7858 return;
7859 }
7860
7861 /* Otherwise, something went wrong. We didn't actually kill
7862 the target. Just propagate the exception, and let the
7863 user or higher layers decide what to do. */
7864 throw_exception (ex);
7865 }
492d29ea 7866 END_CATCH
43ff13b4 7867
0fdf84ca
PA
7868 /* We've killed the remote end, we get to mourn it. Since this is
7869 target remote, single-process, mourning the inferior also
7870 unpushes remote_ops. */
43ff13b4
JM
7871 target_mourn_inferior ();
7872}
7873
82f73884
PA
7874static int
7875remote_vkill (int pid, struct remote_state *rs)
7876{
4082afcc 7877 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
7878 return -1;
7879
7880 /* Tell the remote target to detach. */
bba74b36 7881 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
7882 putpkt (rs->buf);
7883 getpkt (&rs->buf, &rs->buf_size, 0);
7884
4082afcc
PA
7885 switch (packet_ok (rs->buf,
7886 &remote_protocol_packets[PACKET_vKill]))
7887 {
7888 case PACKET_OK:
7889 return 0;
7890 case PACKET_ERROR:
7891 return 1;
7892 case PACKET_UNKNOWN:
7893 return -1;
7894 default:
7895 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7896 }
82f73884
PA
7897}
7898
7899static void
7d85a9c0 7900extended_remote_kill (struct target_ops *ops)
82f73884
PA
7901{
7902 int res;
7903 int pid = ptid_get_pid (inferior_ptid);
7904 struct remote_state *rs = get_remote_state ();
7905
7906 res = remote_vkill (pid, rs);
901f9912 7907 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
82f73884
PA
7908 {
7909 /* Don't try 'k' on a multi-process aware stub -- it has no way
7910 to specify the pid. */
7911
7912 putpkt ("k");
7913#if 0
7914 getpkt (&rs->buf, &rs->buf_size, 0);
7915 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7916 res = 1;
7917#else
7918 /* Don't wait for it to die. I'm not really sure it matters whether
7919 we do or not. For the existing stubs, kill is a noop. */
7920 res = 0;
7921#endif
7922 }
7923
7924 if (res != 0)
7925 error (_("Can't kill process"));
7926
82f73884
PA
7927 target_mourn_inferior ();
7928}
7929
c906108c 7930static void
136d6dae 7931remote_mourn (struct target_ops *ops)
c906108c 7932{
136d6dae 7933 remote_mourn_1 (ops);
c906108c
SS
7934}
7935
c906108c
SS
7936/* Worker function for remote_mourn. */
7937static void
fba45db2 7938remote_mourn_1 (struct target_ops *target)
c906108c
SS
7939{
7940 unpush_target (target);
ce5ce7ed 7941
8a2492ee
PA
7942 /* remote_close takes care of doing most of the clean up. */
7943 generic_mourn_inferior ();
c906108c
SS
7944}
7945
2d717e4f
DJ
7946static void
7947extended_remote_mourn_1 (struct target_ops *target)
7948{
7949 struct remote_state *rs = get_remote_state ();
c906108c 7950
e24a49d8
PA
7951 /* In case we got here due to an error, but we're going to stay
7952 connected. */
7953 rs->waiting_for_stop_reply = 0;
7954
dc1981d7
PA
7955 /* If the current general thread belonged to the process we just
7956 detached from or has exited, the remote side current general
7957 thread becomes undefined. Considering a case like this:
7958
7959 - We just got here due to a detach.
7960 - The process that we're detaching from happens to immediately
7961 report a global breakpoint being hit in non-stop mode, in the
7962 same thread we had selected before.
7963 - GDB attaches to this process again.
7964 - This event happens to be the next event we handle.
7965
7966 GDB would consider that the current general thread didn't need to
7967 be set on the stub side (with Hg), since for all it knew,
7968 GENERAL_THREAD hadn't changed.
7969
7970 Notice that although in all-stop mode, the remote server always
7971 sets the current thread to the thread reporting the stop event,
7972 that doesn't happen in non-stop mode; in non-stop, the stub *must
7973 not* change the current thread when reporting a breakpoint hit,
7974 due to the decoupling of event reporting and event handling.
7975
7976 To keep things simple, we always invalidate our notion of the
7977 current thread. */
47f8a51d 7978 record_currthread (rs, minus_one_ptid);
dc1981d7 7979
2d717e4f
DJ
7980 /* Unlike "target remote", we do not want to unpush the target; then
7981 the next time the user says "run", we won't be connected. */
7982
48aa3c27
PA
7983 /* Call common code to mark the inferior as not running. */
7984 generic_mourn_inferior ();
7985
d729566a 7986 if (!have_inferiors ())
2d717e4f 7987 {
82f73884
PA
7988 if (!remote_multi_process_p (rs))
7989 {
7990 /* Check whether the target is running now - some remote stubs
7991 automatically restart after kill. */
7992 putpkt ("?");
7993 getpkt (&rs->buf, &rs->buf_size, 0);
7994
7995 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7996 {
3e43a32a
MS
7997 /* Assume that the target has been restarted. Set
7998 inferior_ptid so that bits of core GDB realizes
7999 there's something here, e.g., so that the user can
8000 say "kill" again. */
82f73884
PA
8001 inferior_ptid = magic_null_ptid;
8002 }
82f73884 8003 }
2d717e4f
DJ
8004 }
8005}
c906108c
SS
8006
8007static void
136d6dae 8008extended_remote_mourn (struct target_ops *ops)
c906108c 8009{
136d6dae 8010 extended_remote_mourn_1 (ops);
2d717e4f 8011}
c906108c 8012
03583c20 8013static int
2bfc0540 8014extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 8015{
4082afcc 8016 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
8017}
8018
8019static void
8020extended_remote_disable_randomization (int val)
8021{
8022 struct remote_state *rs = get_remote_state ();
8023 char *reply;
8024
bba74b36
YQ
8025 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8026 val);
03583c20
UW
8027 putpkt (rs->buf);
8028 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8029 if (*reply == '\0')
8030 error (_("Target does not support QDisableRandomization."));
8031 if (strcmp (reply, "OK") != 0)
8032 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8033}
8034
2d717e4f
DJ
8035static int
8036extended_remote_run (char *args)
8037{
8038 struct remote_state *rs = get_remote_state ();
2d717e4f 8039 int len;
c906108c 8040
2d717e4f
DJ
8041 /* If the user has disabled vRun support, or we have detected that
8042 support is not available, do not try it. */
4082afcc 8043 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 8044 return -1;
424163ea 8045
2d717e4f
DJ
8046 strcpy (rs->buf, "vRun;");
8047 len = strlen (rs->buf);
c906108c 8048
2d717e4f
DJ
8049 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8050 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
8051 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8052 strlen (remote_exec_file));
2d717e4f 8053
d1a41061 8054 gdb_assert (args != NULL);
2d717e4f
DJ
8055 if (*args)
8056 {
8057 struct cleanup *back_to;
8058 int i;
8059 char **argv;
8060
d1a41061 8061 argv = gdb_buildargv (args);
6e366df1 8062 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
8063 for (i = 0; argv[i] != NULL; i++)
8064 {
8065 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8066 error (_("Argument list too long for run packet"));
8067 rs->buf[len++] = ';';
9f1b45b0
TT
8068 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8069 strlen (argv[i]));
2d717e4f
DJ
8070 }
8071 do_cleanups (back_to);
8072 }
8073
8074 rs->buf[len++] = '\0';
8075
8076 putpkt (rs->buf);
8077 getpkt (&rs->buf, &rs->buf_size, 0);
8078
4082afcc 8079 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 8080 {
4082afcc 8081 case PACKET_OK:
3405876a 8082 /* We have a wait response. All is well. */
2d717e4f 8083 return 0;
4082afcc
PA
8084 case PACKET_UNKNOWN:
8085 return -1;
8086 case PACKET_ERROR:
2d717e4f
DJ
8087 if (remote_exec_file[0] == '\0')
8088 error (_("Running the default executable on the remote target failed; "
8089 "try \"set remote exec-file\"?"));
8090 else
8091 error (_("Running \"%s\" on the remote target failed"),
8092 remote_exec_file);
4082afcc
PA
8093 default:
8094 gdb_assert_not_reached (_("bad switch"));
2d717e4f 8095 }
c906108c
SS
8096}
8097
2d717e4f
DJ
8098/* In the extended protocol we want to be able to do things like
8099 "run" and have them basically work as expected. So we need
8100 a special create_inferior function. We support changing the
8101 executable file and the command line arguments, but not the
8102 environment. */
8103
43ff13b4 8104static void
77a19445
TT
8105extended_remote_create_inferior (struct target_ops *ops,
8106 char *exec_file, char *args,
8107 char **env, int from_tty)
43ff13b4 8108{
3405876a
PA
8109 int run_worked;
8110 char *stop_reply;
8111 struct remote_state *rs = get_remote_state ();
8112
43ff13b4 8113 /* If running asynchronously, register the target file descriptor
23860348 8114 with the event loop. */
75c99385 8115 if (target_can_async_p ())
2acceee2 8116 target_async (inferior_event_handler, 0);
43ff13b4 8117
03583c20 8118 /* Disable address space randomization if requested (and supported). */
2bfc0540 8119 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
8120 extended_remote_disable_randomization (disable_randomization);
8121
43ff13b4 8122 /* Now restart the remote server. */
3405876a
PA
8123 run_worked = extended_remote_run (args) != -1;
8124 if (!run_worked)
2d717e4f
DJ
8125 {
8126 /* vRun was not supported. Fail if we need it to do what the
8127 user requested. */
8128 if (remote_exec_file[0])
8129 error (_("Remote target does not support \"set remote exec-file\""));
8130 if (args[0])
8131 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 8132
2d717e4f
DJ
8133 /* Fall back to "R". */
8134 extended_remote_restart ();
8135 }
424163ea 8136
6c95b8df
PA
8137 if (!have_inferiors ())
8138 {
8139 /* Clean up from the last time we ran, before we mark the target
8140 running again. This will mark breakpoints uninserted, and
8141 get_offsets may insert breakpoints. */
8142 init_thread_list ();
8143 init_wait_for_inferior ();
8144 }
45280a52 8145
3405876a
PA
8146 /* vRun's success return is a stop reply. */
8147 stop_reply = run_worked ? rs->buf : NULL;
8148 add_current_inferior_and_thread (stop_reply);
c0a2216e 8149
2d717e4f
DJ
8150 /* Get updated offsets, if the stub uses qOffsets. */
8151 get_offsets ();
2d717e4f 8152}
c906108c 8153\f
c5aa993b 8154
b775012e
LM
8155/* Given a location's target info BP_TGT and the packet buffer BUF, output
8156 the list of conditions (in agent expression bytecode format), if any, the
8157 target needs to evaluate. The output is placed into the packet buffer
bba74b36 8158 started from BUF and ended at BUF_END. */
b775012e
LM
8159
8160static int
8161remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
8162 struct bp_target_info *bp_tgt, char *buf,
8163 char *buf_end)
b775012e
LM
8164{
8165 struct agent_expr *aexpr = NULL;
8166 int i, ix;
8167 char *pkt;
8168 char *buf_start = buf;
8169
8170 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8171 return 0;
8172
8173 buf += strlen (buf);
bba74b36 8174 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
8175 buf++;
8176
8177 /* Send conditions to the target and free the vector. */
8178 for (ix = 0;
8179 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8180 ix++)
8181 {
bba74b36 8182 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
8183 buf += strlen (buf);
8184 for (i = 0; i < aexpr->len; ++i)
8185 buf = pack_hex_byte (buf, aexpr->buf[i]);
8186 *buf = '\0';
8187 }
b775012e
LM
8188 return 0;
8189}
8190
d3ce09f5
SS
8191static void
8192remote_add_target_side_commands (struct gdbarch *gdbarch,
8193 struct bp_target_info *bp_tgt, char *buf)
8194{
8195 struct agent_expr *aexpr = NULL;
8196 int i, ix;
8197
8198 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8199 return;
8200
8201 buf += strlen (buf);
8202
8203 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8204 buf += strlen (buf);
8205
8206 /* Concatenate all the agent expressions that are commands into the
8207 cmds parameter. */
8208 for (ix = 0;
8209 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8210 ix++)
8211 {
8212 sprintf (buf, "X%x,", aexpr->len);
8213 buf += strlen (buf);
8214 for (i = 0; i < aexpr->len; ++i)
8215 buf = pack_hex_byte (buf, aexpr->buf[i]);
8216 *buf = '\0';
8217 }
d3ce09f5
SS
8218}
8219
8181d85f
DJ
8220/* Insert a breakpoint. On targets that have software breakpoint
8221 support, we ask the remote target to do the work; on targets
8222 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
8223
8224static int
3db08215
MM
8225remote_insert_breakpoint (struct target_ops *ops,
8226 struct gdbarch *gdbarch,
a6d9a66e 8227 struct bp_target_info *bp_tgt)
c906108c 8228{
d471ea57
AC
8229 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8230 If it succeeds, then set the support to PACKET_ENABLE. If it
8231 fails, and the user has explicitly requested the Z support then
23860348 8232 report an error, otherwise, mark it disabled and go on. */
802188a7 8233
4082afcc 8234 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 8235 {
0d5ed153 8236 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 8237 struct remote_state *rs;
bba74b36 8238 char *p, *endbuf;
7c0f6dcc 8239 int bpsize;
b775012e 8240 struct condition_list *cond = NULL;
4fff2411 8241
28439a30
PA
8242 /* Make sure the remote is pointing at the right process, if
8243 necessary. */
8244 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8245 set_general_process ();
8246
a1dcb23a 8247 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
8248
8249 rs = get_remote_state ();
8250 p = rs->buf;
bba74b36 8251 endbuf = rs->buf + get_remote_packet_size ();
802188a7 8252
96baa820
JM
8253 *(p++) = 'Z';
8254 *(p++) = '0';
8255 *(p++) = ',';
7c0f6dcc 8256 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 8257 p += hexnumstr (p, addr);
bba74b36 8258 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 8259
efcc2da7 8260 if (remote_supports_cond_breakpoints (ops))
bba74b36 8261 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8262
78eff0ec 8263 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
8264 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8265
6d820c5c
DJ
8266 putpkt (rs->buf);
8267 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8268
6d820c5c 8269 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 8270 {
d471ea57
AC
8271 case PACKET_ERROR:
8272 return -1;
8273 case PACKET_OK:
7c0f6dcc
JL
8274 bp_tgt->placed_address = addr;
8275 bp_tgt->placed_size = bpsize;
d471ea57
AC
8276 return 0;
8277 case PACKET_UNKNOWN:
8278 break;
96baa820
JM
8279 }
8280 }
c906108c 8281
0000e5cc
PA
8282 /* If this breakpoint has target-side commands but this stub doesn't
8283 support Z0 packets, throw error. */
8284 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8285 throw_error (NOT_SUPPORTED_ERROR, _("\
8286Target doesn't support breakpoints that have target side commands."));
8287
3db08215 8288 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8289}
8290
8291static int
3db08215
MM
8292remote_remove_breakpoint (struct target_ops *ops,
8293 struct gdbarch *gdbarch,
a6d9a66e 8294 struct bp_target_info *bp_tgt)
c906108c 8295{
8181d85f 8296 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 8297 struct remote_state *rs = get_remote_state ();
96baa820 8298
4082afcc 8299 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 8300 {
6d820c5c 8301 char *p = rs->buf;
bba74b36 8302 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 8303
28439a30
PA
8304 /* Make sure the remote is pointing at the right process, if
8305 necessary. */
8306 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8307 set_general_process ();
8308
96baa820
JM
8309 *(p++) = 'z';
8310 *(p++) = '0';
8311 *(p++) = ',';
8312
8181d85f
DJ
8313 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8314 p += hexnumstr (p, addr);
bba74b36 8315 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 8316
6d820c5c
DJ
8317 putpkt (rs->buf);
8318 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8319
6d820c5c 8320 return (rs->buf[0] == 'E');
96baa820
JM
8321 }
8322
3db08215 8323 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8324}
8325
d471ea57
AC
8326static int
8327watchpoint_to_Z_packet (int type)
8328{
8329 switch (type)
8330 {
8331 case hw_write:
bb858e6a 8332 return Z_PACKET_WRITE_WP;
d471ea57
AC
8333 break;
8334 case hw_read:
bb858e6a 8335 return Z_PACKET_READ_WP;
d471ea57
AC
8336 break;
8337 case hw_access:
bb858e6a 8338 return Z_PACKET_ACCESS_WP;
d471ea57
AC
8339 break;
8340 default:
8e65ff28 8341 internal_error (__FILE__, __LINE__,
e2e0b3e5 8342 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
8343 }
8344}
8345
3c3bea1c 8346static int
7bb99c53
TT
8347remote_insert_watchpoint (struct target_ops *self,
8348 CORE_ADDR addr, int len, int type,
0cf6dd15 8349 struct expression *cond)
96baa820 8350{
d01949b6 8351 struct remote_state *rs = get_remote_state ();
bba74b36 8352 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8353 char *p;
d471ea57 8354 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 8355
4082afcc 8356 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 8357 return 1;
802188a7 8358
28439a30
PA
8359 /* Make sure the remote is pointing at the right process, if
8360 necessary. */
8361 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8362 set_general_process ();
8363
bba74b36 8364 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 8365 p = strchr (rs->buf, '\0');
96baa820
JM
8366 addr = remote_address_masked (addr);
8367 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8368 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 8369
6d820c5c
DJ
8370 putpkt (rs->buf);
8371 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8372
6d820c5c 8373 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8374 {
8375 case PACKET_ERROR:
d471ea57 8376 return -1;
85d721b8
PA
8377 case PACKET_UNKNOWN:
8378 return 1;
d471ea57
AC
8379 case PACKET_OK:
8380 return 0;
8381 }
8e65ff28 8382 internal_error (__FILE__, __LINE__,
e2e0b3e5 8383 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
8384}
8385
283002cf
MR
8386static int
8387remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8388 CORE_ADDR start, int length)
8389{
8390 CORE_ADDR diff = remote_address_masked (addr - start);
8391
8392 return diff < length;
8393}
8394
d471ea57 8395
3c3bea1c 8396static int
11b5219a
TT
8397remote_remove_watchpoint (struct target_ops *self,
8398 CORE_ADDR addr, int len, int type,
0cf6dd15 8399 struct expression *cond)
96baa820 8400{
d01949b6 8401 struct remote_state *rs = get_remote_state ();
bba74b36 8402 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8403 char *p;
d471ea57
AC
8404 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8405
4082afcc 8406 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 8407 return -1;
802188a7 8408
28439a30
PA
8409 /* Make sure the remote is pointing at the right process, if
8410 necessary. */
8411 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8412 set_general_process ();
8413
bba74b36 8414 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 8415 p = strchr (rs->buf, '\0');
96baa820
JM
8416 addr = remote_address_masked (addr);
8417 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8418 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
8419 putpkt (rs->buf);
8420 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8421
6d820c5c 8422 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
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_watchpoint: reached end of function"));
96baa820
JM
8432}
8433
3c3bea1c 8434
501eef12 8435int remote_hw_watchpoint_limit = -1;
480a3f21 8436int remote_hw_watchpoint_length_limit = -1;
501eef12 8437int remote_hw_breakpoint_limit = -1;
d471ea57 8438
480a3f21 8439static int
31568a15
TT
8440remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8441 CORE_ADDR addr, int len)
480a3f21
PW
8442{
8443 if (remote_hw_watchpoint_length_limit == 0)
8444 return 0;
8445 else if (remote_hw_watchpoint_length_limit < 0)
8446 return 1;
8447 else if (len <= remote_hw_watchpoint_length_limit)
8448 return 1;
8449 else
8450 return 0;
8451}
8452
b9362cc7 8453static int
5461485a
TT
8454remote_check_watch_resources (struct target_ops *self,
8455 int type, int cnt, int ot)
96baa820 8456{
3c3bea1c
GS
8457 if (type == bp_hardware_breakpoint)
8458 {
8459 if (remote_hw_breakpoint_limit == 0)
8460 return 0;
501eef12
AC
8461 else if (remote_hw_breakpoint_limit < 0)
8462 return 1;
3c3bea1c
GS
8463 else if (cnt <= remote_hw_breakpoint_limit)
8464 return 1;
8465 }
8466 else
8467 {
8468 if (remote_hw_watchpoint_limit == 0)
8469 return 0;
501eef12
AC
8470 else if (remote_hw_watchpoint_limit < 0)
8471 return 1;
3c3bea1c
GS
8472 else if (ot)
8473 return -1;
8474 else if (cnt <= remote_hw_watchpoint_limit)
8475 return 1;
8476 }
8477 return -1;
8478}
8479
f7e6eed5
PA
8480/* The to_stopped_by_sw_breakpoint method of target remote. */
8481
8482static int
8483remote_stopped_by_sw_breakpoint (struct target_ops *ops)
8484{
8485 struct remote_state *rs = get_remote_state ();
8486
8487 return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
8488}
8489
8490/* The to_supports_stopped_by_sw_breakpoint method of target
8491 remote. */
8492
8493static int
8494remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
8495{
8496 struct remote_state *rs = get_remote_state ();
8497
8498 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
8499}
8500
8501/* The to_stopped_by_hw_breakpoint method of target remote. */
8502
8503static int
8504remote_stopped_by_hw_breakpoint (struct target_ops *ops)
8505{
8506 struct remote_state *rs = get_remote_state ();
8507
8508 return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
8509}
8510
8511/* The to_supports_stopped_by_hw_breakpoint method of target
8512 remote. */
8513
8514static int
8515remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
8516{
8517 struct remote_state *rs = get_remote_state ();
8518
8519 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
8520}
8521
b9362cc7 8522static int
6a109b6b 8523remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 8524{
ee154bee
TT
8525 struct remote_state *rs = get_remote_state ();
8526
f7e6eed5 8527 return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
3c3bea1c
GS
8528}
8529
4aa7a7f5
JJ
8530static int
8531remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 8532{
ee154bee 8533 struct remote_state *rs = get_remote_state ();
4aa7a7f5 8534 int rc = 0;
a744cf53 8535
6a109b6b 8536 if (remote_stopped_by_watchpoint (target))
4aa7a7f5 8537 {
ee154bee 8538 *addr_p = rs->remote_watch_data_address;
4aa7a7f5
JJ
8539 rc = 1;
8540 }
8541
8542 return rc;
3c3bea1c
GS
8543}
8544
8545
8546static int
23a26771 8547remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 8548 struct bp_target_info *bp_tgt)
3c3bea1c 8549{
0d5ed153 8550 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 8551 struct remote_state *rs;
bba74b36 8552 char *p, *endbuf;
dd61ec5c 8553 char *message;
0d5ed153 8554 int bpsize;
802188a7 8555
c8189ed1 8556 /* The length field should be set to the size of a breakpoint
8181d85f 8557 instruction, even though we aren't inserting one ourselves. */
c8189ed1 8558
0d5ed153 8559 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 8560
4082afcc 8561 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 8562 return -1;
2bc416ba 8563
28439a30
PA
8564 /* Make sure the remote is pointing at the right process, if
8565 necessary. */
8566 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8567 set_general_process ();
8568
4fff2411
JZ
8569 rs = get_remote_state ();
8570 p = rs->buf;
bba74b36 8571 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 8572
96baa820
JM
8573 *(p++) = 'Z';
8574 *(p++) = '1';
8575 *(p++) = ',';
802188a7 8576
0d5ed153 8577 addr = remote_address_masked (addr);
96baa820 8578 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 8579 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 8580
efcc2da7 8581 if (remote_supports_cond_breakpoints (self))
bba74b36 8582 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8583
78eff0ec 8584 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
8585 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8586
6d820c5c
DJ
8587 putpkt (rs->buf);
8588 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8589
6d820c5c 8590 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
8591 {
8592 case PACKET_ERROR:
dd61ec5c
MW
8593 if (rs->buf[1] == '.')
8594 {
8595 message = strchr (rs->buf + 2, '.');
8596 if (message)
0316657e 8597 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
8598 }
8599 return -1;
d471ea57
AC
8600 case PACKET_UNKNOWN:
8601 return -1;
8602 case PACKET_OK:
0d5ed153
MR
8603 bp_tgt->placed_address = addr;
8604 bp_tgt->placed_size = bpsize;
d471ea57
AC
8605 return 0;
8606 }
8e65ff28 8607 internal_error (__FILE__, __LINE__,
e2e0b3e5 8608 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
8609}
8610
d471ea57 8611
802188a7 8612static int
a64dc96c 8613remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 8614 struct bp_target_info *bp_tgt)
96baa820 8615{
8181d85f 8616 CORE_ADDR addr;
d01949b6 8617 struct remote_state *rs = get_remote_state ();
6d820c5c 8618 char *p = rs->buf;
bba74b36 8619 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 8620
4082afcc 8621 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 8622 return -1;
802188a7 8623
28439a30
PA
8624 /* Make sure the remote is pointing at the right process, if
8625 necessary. */
8626 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8627 set_general_process ();
8628
96baa820
JM
8629 *(p++) = 'z';
8630 *(p++) = '1';
8631 *(p++) = ',';
802188a7 8632
8181d85f 8633 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 8634 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8635 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 8636
6d820c5c
DJ
8637 putpkt (rs->buf);
8638 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 8639
6d820c5c 8640 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
8641 {
8642 case PACKET_ERROR:
8643 case PACKET_UNKNOWN:
8644 return -1;
8645 case PACKET_OK:
8646 return 0;
8647 }
8e65ff28 8648 internal_error (__FILE__, __LINE__,
e2e0b3e5 8649 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 8650}
96baa820 8651
4a5e7a5b
PA
8652/* Verify memory using the "qCRC:" request. */
8653
8654static int
8655remote_verify_memory (struct target_ops *ops,
8656 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8657{
8658 struct remote_state *rs = get_remote_state ();
8659 unsigned long host_crc, target_crc;
8660 char *tmp;
8661
936d2992
PA
8662 /* It doesn't make sense to use qCRC if the remote target is
8663 connected but not running. */
8664 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
8665 {
8666 enum packet_result result;
28439a30 8667
936d2992
PA
8668 /* Make sure the remote is pointing at the right process. */
8669 set_general_process ();
4a5e7a5b 8670
936d2992
PA
8671 /* FIXME: assumes lma can fit into long. */
8672 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8673 (long) lma, (long) size);
8674 putpkt (rs->buf);
4a5e7a5b 8675
936d2992
PA
8676 /* Be clever; compute the host_crc before waiting for target
8677 reply. */
8678 host_crc = xcrc32 (data, size, 0xffffffff);
8679
8680 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 8681
936d2992
PA
8682 result = packet_ok (rs->buf,
8683 &remote_protocol_packets[PACKET_qCRC]);
8684 if (result == PACKET_ERROR)
8685 return -1;
8686 else if (result == PACKET_OK)
8687 {
8688 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8689 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 8690
936d2992
PA
8691 return (host_crc == target_crc);
8692 }
8693 }
4a5e7a5b 8694
936d2992 8695 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
8696}
8697
c906108c
SS
8698/* compare-sections command
8699
8700 With no arguments, compares each loadable section in the exec bfd
8701 with the same memory range on the target, and reports mismatches.
4a5e7a5b 8702 Useful for verifying the image on the target against the exec file. */
e514a9d6 8703
c906108c 8704static void
fba45db2 8705compare_sections_command (char *args, int from_tty)
c906108c
SS
8706{
8707 asection *s;
c906108c 8708 struct cleanup *old_chain;
948f8e3d 8709 gdb_byte *sectdata;
ce359b09 8710 const char *sectname;
c906108c
SS
8711 bfd_size_type size;
8712 bfd_vma lma;
8713 int matched = 0;
8714 int mismatched = 0;
4a5e7a5b 8715 int res;
95cf3b38 8716 int read_only = 0;
c906108c
SS
8717
8718 if (!exec_bfd)
8a3fe4f8 8719 error (_("command cannot be used without an exec file"));
c906108c 8720
28439a30
PA
8721 /* Make sure the remote is pointing at the right process. */
8722 set_general_process ();
8723
95cf3b38
DT
8724 if (args != NULL && strcmp (args, "-r") == 0)
8725 {
8726 read_only = 1;
8727 args = NULL;
8728 }
8729
c5aa993b 8730 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
8731 {
8732 if (!(s->flags & SEC_LOAD))
0df8b418 8733 continue; /* Skip non-loadable section. */
c906108c 8734
95cf3b38
DT
8735 if (read_only && (s->flags & SEC_READONLY) == 0)
8736 continue; /* Skip writeable sections */
8737
2c500098 8738 size = bfd_get_section_size (s);
c906108c 8739 if (size == 0)
0df8b418 8740 continue; /* Skip zero-length section. */
c906108c 8741
ce359b09 8742 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 8743 if (args && strcmp (args, sectname) != 0)
0df8b418 8744 continue; /* Not the section selected by user. */
c906108c 8745
0df8b418 8746 matched = 1; /* Do this section. */
c906108c 8747 lma = s->lma;
c906108c 8748
c906108c 8749 sectdata = xmalloc (size);
b8c9b27d 8750 old_chain = make_cleanup (xfree, sectdata);
c906108c 8751 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 8752
4a5e7a5b
PA
8753 res = target_verify_memory (sectdata, lma, size);
8754
8755 if (res == -1)
5af949e3 8756 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
8757 paddress (target_gdbarch (), lma),
8758 paddress (target_gdbarch (), lma + size));
c906108c 8759
5af949e3 8760 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
8761 paddress (target_gdbarch (), lma),
8762 paddress (target_gdbarch (), lma + size));
4a5e7a5b 8763 if (res)
c906108c
SS
8764 printf_filtered ("matched.\n");
8765 else
c5aa993b
JM
8766 {
8767 printf_filtered ("MIS-MATCHED!\n");
8768 mismatched++;
8769 }
c906108c
SS
8770
8771 do_cleanups (old_chain);
8772 }
8773 if (mismatched > 0)
936d2992 8774 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 8775the loaded file\n"));
c906108c 8776 if (args && !matched)
a3f17187 8777 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
8778}
8779
0e7f50da
UW
8780/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8781 into remote target. The number of bytes written to the remote
8782 target is returned, or -1 for error. */
8783
9b409511 8784static enum target_xfer_status
0e7f50da
UW
8785remote_write_qxfer (struct target_ops *ops, const char *object_name,
8786 const char *annex, const gdb_byte *writebuf,
9b409511 8787 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
8788 struct packet_config *packet)
8789{
8790 int i, buf_len;
8791 ULONGEST n;
0e7f50da
UW
8792 struct remote_state *rs = get_remote_state ();
8793 int max_size = get_memory_write_packet_size ();
8794
8795 if (packet->support == PACKET_DISABLE)
2ed4b548 8796 return TARGET_XFER_E_IO;
0e7f50da
UW
8797
8798 /* Insert header. */
8799 i = snprintf (rs->buf, max_size,
8800 "qXfer:%s:write:%s:%s:",
8801 object_name, annex ? annex : "",
8802 phex_nz (offset, sizeof offset));
8803 max_size -= (i + 1);
8804
8805 /* Escape as much data as fits into rs->buf. */
8806 buf_len = remote_escape_output
bc20a4af 8807 (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
8808
8809 if (putpkt_binary (rs->buf, i + buf_len) < 0
8810 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8811 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 8812 return TARGET_XFER_E_IO;
0e7f50da
UW
8813
8814 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
8815
8816 *xfered_len = n;
8817 return TARGET_XFER_OK;
0e7f50da
UW
8818}
8819
0876f84a
DJ
8820/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8821 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8822 number of bytes read is returned, or 0 for EOF, or -1 for error.
8823 The number of bytes read may be less than LEN without indicating an
8824 EOF. PACKET is checked and updated to indicate whether the remote
8825 target supports this object. */
8826
9b409511 8827static enum target_xfer_status
0876f84a
DJ
8828remote_read_qxfer (struct target_ops *ops, const char *object_name,
8829 const char *annex,
8830 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 8831 ULONGEST *xfered_len,
0876f84a
DJ
8832 struct packet_config *packet)
8833{
0876f84a 8834 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
8835 LONGEST i, n, packet_len;
8836
8837 if (packet->support == PACKET_DISABLE)
2ed4b548 8838 return TARGET_XFER_E_IO;
0876f84a
DJ
8839
8840 /* Check whether we've cached an end-of-object packet that matches
8841 this request. */
8e88304f 8842 if (rs->finished_object)
0876f84a 8843 {
8e88304f
TT
8844 if (strcmp (object_name, rs->finished_object) == 0
8845 && strcmp (annex ? annex : "", rs->finished_annex) == 0
8846 && offset == rs->finished_offset)
9b409511
YQ
8847 return TARGET_XFER_EOF;
8848
0876f84a
DJ
8849
8850 /* Otherwise, we're now reading something different. Discard
8851 the cache. */
8e88304f
TT
8852 xfree (rs->finished_object);
8853 xfree (rs->finished_annex);
8854 rs->finished_object = NULL;
8855 rs->finished_annex = NULL;
0876f84a
DJ
8856 }
8857
8858 /* Request only enough to fit in a single packet. The actual data
8859 may not, since we don't know how much of it will need to be escaped;
8860 the target is free to respond with slightly less data. We subtract
8861 five to account for the response type and the protocol frame. */
8862 n = min (get_remote_packet_size () - 5, len);
8863 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8864 object_name, annex ? annex : "",
8865 phex_nz (offset, sizeof offset),
8866 phex_nz (n, sizeof n));
8867 i = putpkt (rs->buf);
8868 if (i < 0)
2ed4b548 8869 return TARGET_XFER_E_IO;
0876f84a
DJ
8870
8871 rs->buf[0] = '\0';
8872 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8873 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 8874 return TARGET_XFER_E_IO;
0876f84a
DJ
8875
8876 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8877 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8878
8879 /* 'm' means there is (or at least might be) more data after this
8880 batch. That does not make sense unless there's at least one byte
8881 of data in this reply. */
8882 if (rs->buf[0] == 'm' && packet_len == 1)
8883 error (_("Remote qXfer reply contained no data."));
8884
8885 /* Got some data. */
bc20a4af
PA
8886 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
8887 packet_len - 1, readbuf, n);
0876f84a
DJ
8888
8889 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
8890 or possibly empty. If we have the final block of a non-empty
8891 object, record this fact to bypass a subsequent partial read. */
8892 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 8893 {
8e88304f
TT
8894 rs->finished_object = xstrdup (object_name);
8895 rs->finished_annex = xstrdup (annex ? annex : "");
8896 rs->finished_offset = offset + i;
0876f84a
DJ
8897 }
8898
9b409511
YQ
8899 if (i == 0)
8900 return TARGET_XFER_EOF;
8901 else
8902 {
8903 *xfered_len = i;
8904 return TARGET_XFER_OK;
8905 }
0876f84a
DJ
8906}
8907
9b409511 8908static enum target_xfer_status
4b8a223f 8909remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 8910 const char *annex, gdb_byte *readbuf,
9b409511
YQ
8911 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
8912 ULONGEST *xfered_len)
c906108c 8913{
82f73884 8914 struct remote_state *rs;
c906108c 8915 int i;
6d820c5c 8916 char *p2;
1e3ff5ad 8917 char query_type;
c906108c 8918
e6e4e701 8919 set_remote_traceframe ();
82f73884
PA
8920 set_general_thread (inferior_ptid);
8921
8922 rs = get_remote_state ();
8923
b2182ed2 8924 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
8925 if (object == TARGET_OBJECT_MEMORY)
8926 {
2d717e4f
DJ
8927 /* If the remote target is connected but not running, we should
8928 pass this request down to a lower stratum (e.g. the executable
8929 file). */
8930 if (!target_has_execution)
9b409511 8931 return TARGET_XFER_EOF;
2d717e4f 8932
21e3b9b9 8933 if (writebuf != NULL)
9b409511 8934 return remote_write_bytes (offset, writebuf, len, xfered_len);
21e3b9b9 8935 else
8acf9577 8936 return remote_read_bytes (ops, offset, readbuf, len, xfered_len);
21e3b9b9
DJ
8937 }
8938
0df8b418 8939 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
8940 if (object == TARGET_OBJECT_SPU)
8941 {
8942 if (readbuf)
8943 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
8944 xfered_len, &remote_protocol_packets
8945 [PACKET_qXfer_spu_read]);
0e7f50da
UW
8946 else
8947 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
8948 xfered_len, &remote_protocol_packets
8949 [PACKET_qXfer_spu_write]);
0e7f50da
UW
8950 }
8951
4aa995e1
PA
8952 /* Handle extra signal info using qxfer packets. */
8953 if (object == TARGET_OBJECT_SIGNAL_INFO)
8954 {
8955 if (readbuf)
8956 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 8957 xfered_len, &remote_protocol_packets
4aa995e1
PA
8958 [PACKET_qXfer_siginfo_read]);
8959 else
3e43a32a 8960 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 8961 writebuf, offset, len, xfered_len,
4aa995e1
PA
8962 &remote_protocol_packets
8963 [PACKET_qXfer_siginfo_write]);
8964 }
8965
0fb4aa4b
PA
8966 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8967 {
8968 if (readbuf)
3e43a32a 8969 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 8970 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
8971 &remote_protocol_packets
8972 [PACKET_qXfer_statictrace_read]);
8973 else
2ed4b548 8974 return TARGET_XFER_E_IO;
0fb4aa4b
PA
8975 }
8976
a76d924d
DJ
8977 /* Only handle flash writes. */
8978 if (writebuf != NULL)
8979 {
8980 LONGEST xfered;
8981
8982 switch (object)
8983 {
8984 case TARGET_OBJECT_FLASH:
9b409511
YQ
8985 return remote_flash_write (ops, offset, len, xfered_len,
8986 writebuf);
a76d924d
DJ
8987
8988 default:
2ed4b548 8989 return TARGET_XFER_E_IO;
a76d924d
DJ
8990 }
8991 }
4b8a223f 8992
1e3ff5ad
AC
8993 /* Map pre-existing objects onto letters. DO NOT do this for new
8994 objects!!! Instead specify new query packets. */
8995 switch (object)
c906108c 8996 {
1e3ff5ad
AC
8997 case TARGET_OBJECT_AVR:
8998 query_type = 'R';
8999 break;
802188a7
RM
9000
9001 case TARGET_OBJECT_AUXV:
0876f84a
DJ
9002 gdb_assert (annex == NULL);
9003 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 9004 xfered_len,
0876f84a 9005 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 9006
23181151
DJ
9007 case TARGET_OBJECT_AVAILABLE_FEATURES:
9008 return remote_read_qxfer
9b409511 9009 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
9010 &remote_protocol_packets[PACKET_qXfer_features]);
9011
cfa9d6d9
DJ
9012 case TARGET_OBJECT_LIBRARIES:
9013 return remote_read_qxfer
9b409511 9014 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
9015 &remote_protocol_packets[PACKET_qXfer_libraries]);
9016
2268b414
JK
9017 case TARGET_OBJECT_LIBRARIES_SVR4:
9018 return remote_read_qxfer
9b409511 9019 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
9020 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9021
fd79ecee
DJ
9022 case TARGET_OBJECT_MEMORY_MAP:
9023 gdb_assert (annex == NULL);
9024 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 9025 xfered_len,
fd79ecee
DJ
9026 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9027
07e059b5
VP
9028 case TARGET_OBJECT_OSDATA:
9029 /* Should only get here if we're connected. */
5d93a237 9030 gdb_assert (rs->remote_desc);
07e059b5 9031 return remote_read_qxfer
9b409511 9032 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
9033 &remote_protocol_packets[PACKET_qXfer_osdata]);
9034
dc146f7c
VP
9035 case TARGET_OBJECT_THREADS:
9036 gdb_assert (annex == NULL);
9037 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 9038 xfered_len,
dc146f7c
VP
9039 &remote_protocol_packets[PACKET_qXfer_threads]);
9040
b3b9301e
PA
9041 case TARGET_OBJECT_TRACEFRAME_INFO:
9042 gdb_assert (annex == NULL);
9043 return remote_read_qxfer
9b409511 9044 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 9045 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
9046
9047 case TARGET_OBJECT_FDPIC:
9048 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 9049 xfered_len,
78d85199 9050 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
9051
9052 case TARGET_OBJECT_OPENVMS_UIB:
9053 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 9054 xfered_len,
169081d0
TG
9055 &remote_protocol_packets[PACKET_qXfer_uib]);
9056
9accd112
MM
9057 case TARGET_OBJECT_BTRACE:
9058 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 9059 xfered_len,
9accd112
MM
9060 &remote_protocol_packets[PACKET_qXfer_btrace]);
9061
f4abbc16
MM
9062 case TARGET_OBJECT_BTRACE_CONF:
9063 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9064 len, xfered_len,
9065 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9066
1e3ff5ad 9067 default:
2ed4b548 9068 return TARGET_XFER_E_IO;
c906108c
SS
9069 }
9070
0df8b418 9071 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 9072 large enough let the caller deal with it. */
ea9c271d 9073 if (len < get_remote_packet_size ())
2ed4b548 9074 return TARGET_XFER_E_IO;
ea9c271d 9075 len = get_remote_packet_size ();
1e3ff5ad 9076
23860348 9077 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 9078 if (!rs->remote_desc)
8a3fe4f8 9079 error (_("remote query is only available after target open"));
c906108c 9080
1e3ff5ad 9081 gdb_assert (annex != NULL);
4b8a223f 9082 gdb_assert (readbuf != NULL);
c906108c 9083
6d820c5c 9084 p2 = rs->buf;
c906108c
SS
9085 *p2++ = 'q';
9086 *p2++ = query_type;
9087
23860348
MS
9088 /* We used one buffer char for the remote protocol q command and
9089 another for the query type. As the remote protocol encapsulation
9090 uses 4 chars plus one extra in case we are debugging
9091 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9092 string. */
c906108c 9093 i = 0;
ea9c271d 9094 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 9095 {
1e3ff5ad
AC
9096 /* Bad caller may have sent forbidden characters. */
9097 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9098 *p2++ = annex[i];
c906108c
SS
9099 i++;
9100 }
1e3ff5ad
AC
9101 *p2 = '\0';
9102 gdb_assert (annex[i] == '\0');
c906108c 9103
6d820c5c 9104 i = putpkt (rs->buf);
c5aa993b 9105 if (i < 0)
2ed4b548 9106 return TARGET_XFER_E_IO;
c906108c 9107
6d820c5c
DJ
9108 getpkt (&rs->buf, &rs->buf_size, 0);
9109 strcpy ((char *) readbuf, rs->buf);
c906108c 9110
9b409511
YQ
9111 *xfered_len = strlen ((char *) readbuf);
9112 return TARGET_XFER_OK;
c906108c
SS
9113}
9114
08388c79
DE
9115static int
9116remote_search_memory (struct target_ops* ops,
9117 CORE_ADDR start_addr, ULONGEST search_space_len,
9118 const gdb_byte *pattern, ULONGEST pattern_len,
9119 CORE_ADDR *found_addrp)
9120{
f5656ead 9121 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
9122 struct remote_state *rs = get_remote_state ();
9123 int max_size = get_memory_write_packet_size ();
9124 struct packet_config *packet =
9125 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
9126 /* Number of packet bytes used to encode the pattern;
9127 this could be more than PATTERN_LEN due to escape characters. */
08388c79 9128 int escaped_pattern_len;
0df8b418 9129 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
9130 int used_pattern_len;
9131 int i;
9132 int found;
9133 ULONGEST found_addr;
9134
9135 /* Don't go to the target if we don't have to.
9136 This is done before checking packet->support to avoid the possibility that
9137 a success for this edge case means the facility works in general. */
9138 if (pattern_len > search_space_len)
9139 return 0;
9140 if (pattern_len == 0)
9141 {
9142 *found_addrp = start_addr;
9143 return 1;
9144 }
9145
9146 /* If we already know the packet isn't supported, fall back to the simple
9147 way of searching memory. */
9148
4082afcc 9149 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
9150 {
9151 /* Target doesn't provided special support, fall back and use the
9152 standard support (copy memory and do the search here). */
9153 return simple_search_memory (ops, start_addr, search_space_len,
9154 pattern, pattern_len, found_addrp);
9155 }
9156
28439a30
PA
9157 /* Make sure the remote is pointing at the right process. */
9158 set_general_process ();
9159
08388c79
DE
9160 /* Insert header. */
9161 i = snprintf (rs->buf, max_size,
9162 "qSearch:memory:%s;%s;",
5af949e3 9163 phex_nz (start_addr, addr_size),
08388c79
DE
9164 phex_nz (search_space_len, sizeof (search_space_len)));
9165 max_size -= (i + 1);
9166
9167 /* Escape as much data as fits into rs->buf. */
9168 escaped_pattern_len =
bc20a4af 9169 remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
08388c79
DE
9170 &used_pattern_len, max_size);
9171
9172 /* Bail if the pattern is too large. */
9173 if (used_pattern_len != pattern_len)
9b20d036 9174 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
9175
9176 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9177 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9178 || packet_ok (rs->buf, packet) != PACKET_OK)
9179 {
9180 /* The request may not have worked because the command is not
9181 supported. If so, fall back to the simple way. */
9182 if (packet->support == PACKET_DISABLE)
9183 {
9184 return simple_search_memory (ops, start_addr, search_space_len,
9185 pattern, pattern_len, found_addrp);
9186 }
9187 return -1;
9188 }
9189
9190 if (rs->buf[0] == '0')
9191 found = 0;
9192 else if (rs->buf[0] == '1')
9193 {
9194 found = 1;
9195 if (rs->buf[1] != ',')
10e0fa18 9196 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9197 unpack_varlen_hex (rs->buf + 2, &found_addr);
9198 *found_addrp = found_addr;
9199 }
9200 else
10e0fa18 9201 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9202
9203 return found;
9204}
9205
96baa820 9206static void
a30bf1f1 9207remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 9208 struct ui_file *outbuf)
96baa820 9209{
d01949b6 9210 struct remote_state *rs = get_remote_state ();
2e9f7625 9211 char *p = rs->buf;
96baa820 9212
5d93a237 9213 if (!rs->remote_desc)
8a3fe4f8 9214 error (_("remote rcmd is only available after target open"));
96baa820 9215
23860348 9216 /* Send a NULL command across as an empty command. */
7be570e7
JM
9217 if (command == NULL)
9218 command = "";
9219
23860348 9220 /* The query prefix. */
2e9f7625
DJ
9221 strcpy (rs->buf, "qRcmd,");
9222 p = strchr (rs->buf, '\0');
96baa820 9223
3e43a32a
MS
9224 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9225 > get_remote_packet_size ())
8a3fe4f8 9226 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 9227
23860348 9228 /* Encode the actual command. */
a30bf1f1 9229 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 9230
6d820c5c 9231 if (putpkt (rs->buf) < 0)
8a3fe4f8 9232 error (_("Communication problem with target."));
96baa820
JM
9233
9234 /* get/display the response */
9235 while (1)
9236 {
2e9f7625
DJ
9237 char *buf;
9238
00bf0b85 9239 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 9240 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 9241 rs->buf[0] = '\0';
5b37825d
PW
9242 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9243 {
9244 /* Timeout. Continue to (try to) read responses.
9245 This is better than stopping with an error, assuming the stub
9246 is still executing the (long) monitor command.
9247 If needed, the user can interrupt gdb using C-c, obtaining
9248 an effect similar to stop on timeout. */
9249 continue;
9250 }
2e9f7625 9251 buf = rs->buf;
96baa820 9252 if (buf[0] == '\0')
8a3fe4f8 9253 error (_("Target does not support this command."));
96baa820
JM
9254 if (buf[0] == 'O' && buf[1] != 'K')
9255 {
23860348 9256 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
9257 continue;
9258 }
9259 if (strcmp (buf, "OK") == 0)
9260 break;
7be570e7
JM
9261 if (strlen (buf) == 3 && buf[0] == 'E'
9262 && isdigit (buf[1]) && isdigit (buf[2]))
9263 {
8a3fe4f8 9264 error (_("Protocol error with Rcmd"));
7be570e7 9265 }
96baa820
JM
9266 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9267 {
9268 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 9269
96baa820
JM
9270 fputc_unfiltered (c, outbuf);
9271 }
9272 break;
9273 }
9274}
9275
fd79ecee
DJ
9276static VEC(mem_region_s) *
9277remote_memory_map (struct target_ops *ops)
9278{
9279 VEC(mem_region_s) *result = NULL;
9280 char *text = target_read_stralloc (&current_target,
9281 TARGET_OBJECT_MEMORY_MAP, NULL);
9282
9283 if (text)
9284 {
9285 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 9286
fd79ecee
DJ
9287 result = parse_memory_map (text);
9288 do_cleanups (back_to);
9289 }
9290
9291 return result;
9292}
9293
c906108c 9294static void
fba45db2 9295packet_command (char *args, int from_tty)
c906108c 9296{
d01949b6 9297 struct remote_state *rs = get_remote_state ();
c906108c 9298
5d93a237 9299 if (!rs->remote_desc)
8a3fe4f8 9300 error (_("command can only be used with remote target"));
c906108c 9301
c5aa993b 9302 if (!args)
8a3fe4f8 9303 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
9304
9305 puts_filtered ("sending: ");
9306 print_packet (args);
9307 puts_filtered ("\n");
9308 putpkt (args);
9309
6d820c5c 9310 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 9311 puts_filtered ("received: ");
6d820c5c 9312 print_packet (rs->buf);
c906108c
SS
9313 puts_filtered ("\n");
9314}
9315
9316#if 0
23860348 9317/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 9318
a14ed312 9319static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 9320
a14ed312 9321static void threadset_test_cmd (char *cmd, int tty);
c906108c 9322
a14ed312 9323static void threadalive_test (char *cmd, int tty);
c906108c 9324
a14ed312 9325static void threadlist_test_cmd (char *cmd, int tty);
c906108c 9326
23860348 9327int get_and_display_threadinfo (threadref *ref);
c906108c 9328
a14ed312 9329static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 9330
23860348 9331static int thread_display_step (threadref *ref, void *context);
c906108c 9332
a14ed312 9333static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 9334
a14ed312 9335static void init_remote_threadtests (void);
c906108c 9336
23860348 9337#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
9338
9339static void
fba45db2 9340threadset_test_cmd (char *cmd, int tty)
c906108c
SS
9341{
9342 int sample_thread = SAMPLE_THREAD;
9343
a3f17187 9344 printf_filtered (_("Remote threadset test\n"));
79d7f229 9345 set_general_thread (sample_thread);
c906108c
SS
9346}
9347
9348
9349static void
fba45db2 9350threadalive_test (char *cmd, int tty)
c906108c
SS
9351{
9352 int sample_thread = SAMPLE_THREAD;
79d7f229 9353 int pid = ptid_get_pid (inferior_ptid);
ba348170 9354 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 9355
79d7f229 9356 if (remote_thread_alive (ptid))
c906108c
SS
9357 printf_filtered ("PASS: Thread alive test\n");
9358 else
9359 printf_filtered ("FAIL: Thread alive test\n");
9360}
9361
23860348 9362void output_threadid (char *title, threadref *ref);
c906108c
SS
9363
9364void
fba45db2 9365output_threadid (char *title, threadref *ref)
c906108c
SS
9366{
9367 char hexid[20];
9368
23860348 9369 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
9370 hexid[16] = 0;
9371 printf_filtered ("%s %s\n", title, (&hexid[0]));
9372}
9373
9374static void
fba45db2 9375threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
9376{
9377 int startflag = 1;
9378 threadref nextthread;
9379 int done, result_count;
9380 threadref threadlist[3];
9381
9382 printf_filtered ("Remote Threadlist test\n");
9383 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9384 &result_count, &threadlist[0]))
9385 printf_filtered ("FAIL: threadlist test\n");
9386 else
9387 {
9388 threadref *scan = threadlist;
9389 threadref *limit = scan + result_count;
9390
9391 while (scan < limit)
9392 output_threadid (" thread ", scan++);
9393 }
9394}
9395
9396void
fba45db2 9397display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
9398{
9399 output_threadid ("Threadid: ", &info->threadid);
9400 printf_filtered ("Name: %s\n ", info->shortname);
9401 printf_filtered ("State: %s\n", info->display);
9402 printf_filtered ("other: %s\n\n", info->more_display);
9403}
9404
9405int
fba45db2 9406get_and_display_threadinfo (threadref *ref)
c906108c
SS
9407{
9408 int result;
9409 int set;
9410 struct gdb_ext_thread_info threadinfo;
9411
9412 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9413 | TAG_MOREDISPLAY | TAG_DISPLAY;
9414 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9415 display_thread_info (&threadinfo);
9416 return result;
9417}
9418
9419static void
fba45db2 9420threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
9421{
9422 int athread = SAMPLE_THREAD;
9423 threadref thread;
9424 int set;
9425
9426 int_to_threadref (&thread, athread);
9427 printf_filtered ("Remote Threadinfo test\n");
9428 if (!get_and_display_threadinfo (&thread))
9429 printf_filtered ("FAIL cannot get thread info\n");
9430}
9431
9432static int
fba45db2 9433thread_display_step (threadref *ref, void *context)
c906108c
SS
9434{
9435 /* output_threadid(" threadstep ",ref); *//* simple test */
9436 return get_and_display_threadinfo (ref);
9437}
9438
9439static void
fba45db2 9440threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
9441{
9442 printf_filtered ("Remote Threadlist update test\n");
9443 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9444}
9445
9446static void
9447init_remote_threadtests (void)
9448{
3e43a32a
MS
9449 add_com ("tlist", class_obscure, threadlist_test_cmd,
9450 _("Fetch and print the remote list of "
9451 "thread identifiers, one pkt only"));
c906108c 9452 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 9453 _("Fetch and display info about one thread"));
c906108c 9454 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 9455 _("Test setting to a different thread"));
c906108c 9456 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 9457 _("Iterate through updating all remote thread info"));
c906108c 9458 add_com ("talive", class_obscure, threadalive_test,
1bedd215 9459 _(" Remote thread alive test "));
c906108c
SS
9460}
9461
9462#endif /* 0 */
9463
f3fb8c85
MS
9464/* Convert a thread ID to a string. Returns the string in a static
9465 buffer. */
9466
9467static char *
117de6a9 9468remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 9469{
79d7f229 9470 static char buf[64];
82f73884 9471 struct remote_state *rs = get_remote_state ();
f3fb8c85 9472
7cee1e54
PA
9473 if (ptid_equal (ptid, null_ptid))
9474 return normal_pid_to_str (ptid);
9475 else if (ptid_is_pid (ptid))
ecd0ada5
PA
9476 {
9477 /* Printing an inferior target id. */
9478
9479 /* When multi-process extensions are off, there's no way in the
9480 remote protocol to know the remote process id, if there's any
9481 at all. There's one exception --- when we're connected with
9482 target extended-remote, and we manually attached to a process
9483 with "attach PID". We don't record anywhere a flag that
9484 allows us to distinguish that case from the case of
9485 connecting with extended-remote and the stub already being
9486 attached to a process, and reporting yes to qAttached, hence
9487 no smart special casing here. */
9488 if (!remote_multi_process_p (rs))
9489 {
9490 xsnprintf (buf, sizeof buf, "Remote target");
9491 return buf;
9492 }
9493
9494 return normal_pid_to_str (ptid);
82f73884 9495 }
ecd0ada5 9496 else
79d7f229 9497 {
ecd0ada5
PA
9498 if (ptid_equal (magic_null_ptid, ptid))
9499 xsnprintf (buf, sizeof buf, "Thread <main>");
901f9912 9500 else if (rs->extended && remote_multi_process_p (rs))
ecd0ada5 9501 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
ba348170 9502 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
9503 else
9504 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 9505 ptid_get_lwp (ptid));
79d7f229
PA
9506 return buf;
9507 }
f3fb8c85
MS
9508}
9509
38691318
KB
9510/* Get the address of the thread local variable in OBJFILE which is
9511 stored at OFFSET within the thread local storage for thread PTID. */
9512
9513static CORE_ADDR
117de6a9
PA
9514remote_get_thread_local_address (struct target_ops *ops,
9515 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 9516{
4082afcc 9517 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
9518 {
9519 struct remote_state *rs = get_remote_state ();
6d820c5c 9520 char *p = rs->buf;
82f73884 9521 char *endp = rs->buf + get_remote_packet_size ();
571dd617 9522 enum packet_result result;
38691318
KB
9523
9524 strcpy (p, "qGetTLSAddr:");
9525 p += strlen (p);
82f73884 9526 p = write_ptid (p, endp, ptid);
38691318
KB
9527 *p++ = ',';
9528 p += hexnumstr (p, offset);
9529 *p++ = ',';
9530 p += hexnumstr (p, lm);
9531 *p++ = '\0';
9532
6d820c5c
DJ
9533 putpkt (rs->buf);
9534 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
9535 result = packet_ok (rs->buf,
9536 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 9537 if (result == PACKET_OK)
38691318
KB
9538 {
9539 ULONGEST result;
9540
6d820c5c 9541 unpack_varlen_hex (rs->buf, &result);
38691318
KB
9542 return result;
9543 }
571dd617 9544 else if (result == PACKET_UNKNOWN)
109c3e39
AC
9545 throw_error (TLS_GENERIC_ERROR,
9546 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 9547 else
109c3e39
AC
9548 throw_error (TLS_GENERIC_ERROR,
9549 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
9550 }
9551 else
109c3e39
AC
9552 throw_error (TLS_GENERIC_ERROR,
9553 _("TLS not supported or disabled on this target"));
38691318
KB
9554 /* Not reached. */
9555 return 0;
9556}
9557
711e434b
PM
9558/* Provide thread local base, i.e. Thread Information Block address.
9559 Returns 1 if ptid is found and thread_local_base is non zero. */
9560
70221824 9561static int
bd7ae0f5 9562remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 9563{
4082afcc 9564 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
9565 {
9566 struct remote_state *rs = get_remote_state ();
9567 char *p = rs->buf;
9568 char *endp = rs->buf + get_remote_packet_size ();
9569 enum packet_result result;
9570
9571 strcpy (p, "qGetTIBAddr:");
9572 p += strlen (p);
9573 p = write_ptid (p, endp, ptid);
9574 *p++ = '\0';
9575
9576 putpkt (rs->buf);
9577 getpkt (&rs->buf, &rs->buf_size, 0);
9578 result = packet_ok (rs->buf,
9579 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9580 if (result == PACKET_OK)
9581 {
9582 ULONGEST result;
9583
9584 unpack_varlen_hex (rs->buf, &result);
9585 if (addr)
9586 *addr = (CORE_ADDR) result;
9587 return 1;
9588 }
9589 else if (result == PACKET_UNKNOWN)
9590 error (_("Remote target doesn't support qGetTIBAddr packet"));
9591 else
9592 error (_("Remote target failed to process qGetTIBAddr request"));
9593 }
9594 else
9595 error (_("qGetTIBAddr not supported or disabled on this target"));
9596 /* Not reached. */
9597 return 0;
9598}
9599
29709017
DJ
9600/* Support for inferring a target description based on the current
9601 architecture and the size of a 'g' packet. While the 'g' packet
9602 can have any size (since optional registers can be left off the
9603 end), some sizes are easily recognizable given knowledge of the
9604 approximate architecture. */
9605
9606struct remote_g_packet_guess
9607{
9608 int bytes;
9609 const struct target_desc *tdesc;
9610};
9611typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9612DEF_VEC_O(remote_g_packet_guess_s);
9613
9614struct remote_g_packet_data
9615{
9616 VEC(remote_g_packet_guess_s) *guesses;
9617};
9618
9619static struct gdbarch_data *remote_g_packet_data_handle;
9620
9621static void *
9622remote_g_packet_data_init (struct obstack *obstack)
9623{
9624 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9625}
9626
9627void
9628register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9629 const struct target_desc *tdesc)
9630{
9631 struct remote_g_packet_data *data
9632 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9633 struct remote_g_packet_guess new_guess, *guess;
9634 int ix;
9635
9636 gdb_assert (tdesc != NULL);
9637
9638 for (ix = 0;
9639 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9640 ix++)
9641 if (guess->bytes == bytes)
9642 internal_error (__FILE__, __LINE__,
9b20d036 9643 _("Duplicate g packet description added for size %d"),
29709017
DJ
9644 bytes);
9645
9646 new_guess.bytes = bytes;
9647 new_guess.tdesc = tdesc;
9648 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9649}
9650
d962ef82
DJ
9651/* Return 1 if remote_read_description would do anything on this target
9652 and architecture, 0 otherwise. */
9653
9654static int
9655remote_read_description_p (struct target_ops *target)
9656{
9657 struct remote_g_packet_data *data
f5656ead 9658 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
d962ef82
DJ
9659
9660 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9661 return 1;
9662
9663 return 0;
9664}
9665
29709017
DJ
9666static const struct target_desc *
9667remote_read_description (struct target_ops *target)
9668{
9669 struct remote_g_packet_data *data
f5656ead 9670 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
29709017 9671
d962ef82
DJ
9672 /* Do not try this during initial connection, when we do not know
9673 whether there is a running but stopped thread. */
9674 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 9675 return target->beneath->to_read_description (target->beneath);
d962ef82 9676
29709017
DJ
9677 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9678 {
9679 struct remote_g_packet_guess *guess;
9680 int ix;
9681 int bytes = send_g_packet ();
9682
9683 for (ix = 0;
9684 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9685 ix++)
9686 if (guess->bytes == bytes)
9687 return guess->tdesc;
9688
9689 /* We discard the g packet. A minor optimization would be to
9690 hold on to it, and fill the register cache once we have selected
9691 an architecture, but it's too tricky to do safely. */
9692 }
9693
2117c711 9694 return target->beneath->to_read_description (target->beneath);
29709017
DJ
9695}
9696
a6b151f1
DJ
9697/* Remote file transfer support. This is host-initiated I/O, not
9698 target-initiated; for target-initiated, see remote-fileio.c. */
9699
9700/* If *LEFT is at least the length of STRING, copy STRING to
9701 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9702 decrease *LEFT. Otherwise raise an error. */
9703
9704static void
9705remote_buffer_add_string (char **buffer, int *left, char *string)
9706{
9707 int len = strlen (string);
9708
9709 if (len > *left)
9710 error (_("Packet too long for target."));
9711
9712 memcpy (*buffer, string, len);
9713 *buffer += len;
9714 *left -= len;
9715
9716 /* NUL-terminate the buffer as a convenience, if there is
9717 room. */
9718 if (*left)
9719 **buffer = '\0';
9720}
9721
9722/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9723 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9724 decrease *LEFT. Otherwise raise an error. */
9725
9726static void
9727remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9728 int len)
9729{
9730 if (2 * len > *left)
9731 error (_("Packet too long for target."));
9732
9733 bin2hex (bytes, *buffer, len);
9734 *buffer += 2 * len;
9735 *left -= 2 * len;
9736
9737 /* NUL-terminate the buffer as a convenience, if there is
9738 room. */
9739 if (*left)
9740 **buffer = '\0';
9741}
9742
9743/* If *LEFT is large enough, convert VALUE to hex and add it to
9744 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9745 decrease *LEFT. Otherwise raise an error. */
9746
9747static void
9748remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9749{
9750 int len = hexnumlen (value);
9751
9752 if (len > *left)
9753 error (_("Packet too long for target."));
9754
9755 hexnumstr (*buffer, value);
9756 *buffer += len;
9757 *left -= len;
9758
9759 /* NUL-terminate the buffer as a convenience, if there is
9760 room. */
9761 if (*left)
9762 **buffer = '\0';
9763}
9764
9765/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9766 value, *REMOTE_ERRNO to the remote error number or zero if none
9767 was included, and *ATTACHMENT to point to the start of the annex
9768 if any. The length of the packet isn't needed here; there may
9769 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9770
9771 Return 0 if the packet could be parsed, -1 if it could not. If
9772 -1 is returned, the other variables may not be initialized. */
9773
9774static int
9775remote_hostio_parse_result (char *buffer, int *retcode,
9776 int *remote_errno, char **attachment)
9777{
9778 char *p, *p2;
9779
9780 *remote_errno = 0;
9781 *attachment = NULL;
9782
9783 if (buffer[0] != 'F')
9784 return -1;
9785
9786 errno = 0;
9787 *retcode = strtol (&buffer[1], &p, 16);
9788 if (errno != 0 || p == &buffer[1])
9789 return -1;
9790
9791 /* Check for ",errno". */
9792 if (*p == ',')
9793 {
9794 errno = 0;
9795 *remote_errno = strtol (p + 1, &p2, 16);
9796 if (errno != 0 || p + 1 == p2)
9797 return -1;
9798 p = p2;
9799 }
9800
9801 /* Check for ";attachment". If there is no attachment, the
9802 packet should end here. */
9803 if (*p == ';')
9804 {
9805 *attachment = p + 1;
9806 return 0;
9807 }
9808 else if (*p == '\0')
9809 return 0;
9810 else
9811 return -1;
9812}
9813
9814/* Send a prepared I/O packet to the target and read its response.
9815 The prepared packet is in the global RS->BUF before this function
9816 is called, and the answer is there when we return.
9817
9818 COMMAND_BYTES is the length of the request to send, which may include
9819 binary data. WHICH_PACKET is the packet configuration to check
9820 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9821 is set to the error number and -1 is returned. Otherwise the value
9822 returned by the function is returned.
9823
9824 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9825 attachment is expected; an error will be reported if there's a
9826 mismatch. If one is found, *ATTACHMENT will be set to point into
9827 the packet buffer and *ATTACHMENT_LEN will be set to the
9828 attachment's length. */
9829
9830static int
9831remote_hostio_send_command (int command_bytes, int which_packet,
9832 int *remote_errno, char **attachment,
9833 int *attachment_len)
9834{
9835 struct remote_state *rs = get_remote_state ();
9836 int ret, bytes_read;
9837 char *attachment_tmp;
9838
5d93a237 9839 if (!rs->remote_desc
4082afcc 9840 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
9841 {
9842 *remote_errno = FILEIO_ENOSYS;
9843 return -1;
9844 }
9845
9846 putpkt_binary (rs->buf, command_bytes);
9847 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9848
9849 /* If it timed out, something is wrong. Don't try to parse the
9850 buffer. */
9851 if (bytes_read < 0)
9852 {
9853 *remote_errno = FILEIO_EINVAL;
9854 return -1;
9855 }
9856
9857 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9858 {
9859 case PACKET_ERROR:
9860 *remote_errno = FILEIO_EINVAL;
9861 return -1;
9862 case PACKET_UNKNOWN:
9863 *remote_errno = FILEIO_ENOSYS;
9864 return -1;
9865 case PACKET_OK:
9866 break;
9867 }
9868
9869 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9870 &attachment_tmp))
9871 {
9872 *remote_errno = FILEIO_EINVAL;
9873 return -1;
9874 }
9875
9876 /* Make sure we saw an attachment if and only if we expected one. */
9877 if ((attachment_tmp == NULL && attachment != NULL)
9878 || (attachment_tmp != NULL && attachment == NULL))
9879 {
9880 *remote_errno = FILEIO_EINVAL;
9881 return -1;
9882 }
9883
9884 /* If an attachment was found, it must point into the packet buffer;
9885 work out how many bytes there were. */
9886 if (attachment_tmp != NULL)
9887 {
9888 *attachment = attachment_tmp;
9889 *attachment_len = bytes_read - (*attachment - rs->buf);
9890 }
9891
9892 return ret;
9893}
9894
9895/* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9896 remote file descriptor, or -1 if an error occurs (and set
9897 *REMOTE_ERRNO). */
9898
9899static int
cd897586
TT
9900remote_hostio_open (struct target_ops *self,
9901 const char *filename, int flags, int mode,
a6b151f1
DJ
9902 int *remote_errno)
9903{
9904 struct remote_state *rs = get_remote_state ();
9905 char *p = rs->buf;
9906 int left = get_remote_packet_size () - 1;
9907
9908 remote_buffer_add_string (&p, &left, "vFile:open:");
9909
9910 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9911 strlen (filename));
9912 remote_buffer_add_string (&p, &left, ",");
9913
9914 remote_buffer_add_int (&p, &left, flags);
9915 remote_buffer_add_string (&p, &left, ",");
9916
9917 remote_buffer_add_int (&p, &left, mode);
9918
9919 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9920 remote_errno, NULL, NULL);
9921}
9922
9923/* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9924 Return the number of bytes written, or -1 if an error occurs (and
9925 set *REMOTE_ERRNO). */
9926
9927static int
0d866f62
TT
9928remote_hostio_pwrite (struct target_ops *self,
9929 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
9930 ULONGEST offset, int *remote_errno)
9931{
9932 struct remote_state *rs = get_remote_state ();
9933 char *p = rs->buf;
9934 int left = get_remote_packet_size ();
9935 int out_len;
9936
9937 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9938
9939 remote_buffer_add_int (&p, &left, fd);
9940 remote_buffer_add_string (&p, &left, ",");
9941
9942 remote_buffer_add_int (&p, &left, offset);
9943 remote_buffer_add_string (&p, &left, ",");
9944
bc20a4af 9945 p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
a6b151f1
DJ
9946 get_remote_packet_size () - (p - rs->buf));
9947
9948 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9949 remote_errno, NULL, NULL);
9950}
9951
9952/* Read up to LEN bytes FD on the remote target into READ_BUF
9953 Return the number of bytes read, or -1 if an error occurs (and
9954 set *REMOTE_ERRNO). */
9955
9956static int
a3be983c
TT
9957remote_hostio_pread (struct target_ops *self,
9958 int fd, gdb_byte *read_buf, int len,
a6b151f1
DJ
9959 ULONGEST offset, int *remote_errno)
9960{
9961 struct remote_state *rs = get_remote_state ();
9962 char *p = rs->buf;
9963 char *attachment;
9964 int left = get_remote_packet_size ();
9965 int ret, attachment_len;
9966 int read_len;
9967
9968 remote_buffer_add_string (&p, &left, "vFile:pread:");
9969
9970 remote_buffer_add_int (&p, &left, fd);
9971 remote_buffer_add_string (&p, &left, ",");
9972
9973 remote_buffer_add_int (&p, &left, len);
9974 remote_buffer_add_string (&p, &left, ",");
9975
9976 remote_buffer_add_int (&p, &left, offset);
9977
9978 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9979 remote_errno, &attachment,
9980 &attachment_len);
9981
9982 if (ret < 0)
9983 return ret;
9984
bc20a4af 9985 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
9986 read_buf, len);
9987 if (read_len != ret)
9988 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9989
9990 return ret;
9991}
9992
9993/* Close FD on the remote target. Return 0, or -1 if an error occurs
9994 (and set *REMOTE_ERRNO). */
9995
9996static int
df39ea25 9997remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
9998{
9999 struct remote_state *rs = get_remote_state ();
10000 char *p = rs->buf;
10001 int left = get_remote_packet_size () - 1;
10002
10003 remote_buffer_add_string (&p, &left, "vFile:close:");
10004
10005 remote_buffer_add_int (&p, &left, fd);
10006
10007 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
10008 remote_errno, NULL, NULL);
10009}
10010
10011/* Unlink FILENAME on the remote target. Return 0, or -1 if an error
10012 occurs (and set *REMOTE_ERRNO). */
10013
10014static int
dbbca37d
TT
10015remote_hostio_unlink (struct target_ops *self,
10016 const char *filename, int *remote_errno)
a6b151f1
DJ
10017{
10018 struct remote_state *rs = get_remote_state ();
10019 char *p = rs->buf;
10020 int left = get_remote_packet_size () - 1;
10021
10022 remote_buffer_add_string (&p, &left, "vFile:unlink:");
10023
10024 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10025 strlen (filename));
10026
10027 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10028 remote_errno, NULL, NULL);
10029}
10030
b9e7b9c3
UW
10031/* Read value of symbolic link FILENAME on the remote target. Return
10032 a null-terminated string allocated via xmalloc, or NULL if an error
10033 occurs (and set *REMOTE_ERRNO). */
10034
10035static char *
fab5aa7c
TT
10036remote_hostio_readlink (struct target_ops *self,
10037 const char *filename, int *remote_errno)
b9e7b9c3
UW
10038{
10039 struct remote_state *rs = get_remote_state ();
10040 char *p = rs->buf;
10041 char *attachment;
10042 int left = get_remote_packet_size ();
10043 int len, attachment_len;
10044 int read_len;
10045 char *ret;
10046
10047 remote_buffer_add_string (&p, &left, "vFile:readlink:");
10048
10049 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10050 strlen (filename));
10051
10052 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10053 remote_errno, &attachment,
10054 &attachment_len);
10055
10056 if (len < 0)
10057 return NULL;
10058
10059 ret = xmalloc (len + 1);
10060
bc20a4af
PA
10061 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10062 (gdb_byte *) ret, len);
b9e7b9c3
UW
10063 if (read_len != len)
10064 error (_("Readlink returned %d, but %d bytes."), len, read_len);
10065
10066 ret[len] = '\0';
10067 return ret;
10068}
10069
0a93529c
GB
10070/* Read information about the open file FD on the remote target
10071 into ST. Return 0 on success, or -1 if an error occurs (and
10072 set *REMOTE_ERRNO). */
10073
10074static int
10075remote_hostio_fstat (struct target_ops *self,
10076 int fd, struct stat *st,
10077 int *remote_errno)
10078{
10079 struct remote_state *rs = get_remote_state ();
10080 char *p = rs->buf;
10081 int left = get_remote_packet_size ();
10082 int attachment_len, ret;
10083 char *attachment;
10084 struct fio_stat fst;
10085 int read_len;
10086
10087 if (packet_support (PACKET_vFile_fstat) != PACKET_ENABLE)
10088 {
10089 /* Strictly we should return -1, ENOSYS here, but when
10090 "set sysroot remote:" was implemented in August 2008
10091 BFD's need for a stat function was sidestepped with
10092 this hack. This was not remedied until March 2015
10093 so we retain the previous behavior to avoid breaking
10094 compatibility.
10095
10096 Note that the memset is a March 2015 addition; older
10097 GDBs set st_size *and nothing else* so the structure
10098 would have garbage in all other fields. This might
10099 break something but retaining the previous behavior
10100 here would be just too wrong. */
10101
10102 memset (st, 0, sizeof (struct stat));
10103 st->st_size = INT_MAX;
10104 return 0;
10105 }
10106
10107 remote_buffer_add_string (&p, &left, "vFile:fstat:");
10108
10109 remote_buffer_add_int (&p, &left, fd);
10110
10111 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
10112 remote_errno, &attachment,
10113 &attachment_len);
10114 if (ret < 0)
10115 return ret;
10116
10117 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10118 (gdb_byte *) &fst, sizeof (fst));
10119
10120 if (read_len != ret)
10121 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
10122
10123 if (read_len != sizeof (fst))
10124 error (_("vFile:fstat returned %d bytes, but expecting %d."),
10125 read_len, (int) sizeof (fst));
10126
10127 remote_fileio_to_host_stat (&fst, st);
10128
10129 return 0;
10130}
10131
a6b151f1
DJ
10132static int
10133remote_fileio_errno_to_host (int errnum)
10134{
10135 switch (errnum)
10136 {
10137 case FILEIO_EPERM:
10138 return EPERM;
10139 case FILEIO_ENOENT:
10140 return ENOENT;
10141 case FILEIO_EINTR:
10142 return EINTR;
10143 case FILEIO_EIO:
10144 return EIO;
10145 case FILEIO_EBADF:
10146 return EBADF;
10147 case FILEIO_EACCES:
10148 return EACCES;
10149 case FILEIO_EFAULT:
10150 return EFAULT;
10151 case FILEIO_EBUSY:
10152 return EBUSY;
10153 case FILEIO_EEXIST:
10154 return EEXIST;
10155 case FILEIO_ENODEV:
10156 return ENODEV;
10157 case FILEIO_ENOTDIR:
10158 return ENOTDIR;
10159 case FILEIO_EISDIR:
10160 return EISDIR;
10161 case FILEIO_EINVAL:
10162 return EINVAL;
10163 case FILEIO_ENFILE:
10164 return ENFILE;
10165 case FILEIO_EMFILE:
10166 return EMFILE;
10167 case FILEIO_EFBIG:
10168 return EFBIG;
10169 case FILEIO_ENOSPC:
10170 return ENOSPC;
10171 case FILEIO_ESPIPE:
10172 return ESPIPE;
10173 case FILEIO_EROFS:
10174 return EROFS;
10175 case FILEIO_ENOSYS:
10176 return ENOSYS;
10177 case FILEIO_ENAMETOOLONG:
10178 return ENAMETOOLONG;
10179 }
10180 return -1;
10181}
10182
10183static char *
10184remote_hostio_error (int errnum)
10185{
10186 int host_error = remote_fileio_errno_to_host (errnum);
10187
10188 if (host_error == -1)
10189 error (_("Unknown remote I/O error %d"), errnum);
10190 else
10191 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10192}
10193
a6b151f1
DJ
10194static void
10195remote_hostio_close_cleanup (void *opaque)
10196{
10197 int fd = *(int *) opaque;
10198 int remote_errno;
10199
df39ea25 10200 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
10201}
10202
f1838a98
UW
10203
10204static void *
10205remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
10206{
10207 const char *filename = bfd_get_filename (abfd);
10208 int fd, remote_errno;
10209 int *stream;
10210
10211 gdb_assert (remote_filename_p (filename));
10212
cd897586
TT
10213 fd = remote_hostio_open (find_target_at (process_stratum),
10214 filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
f1838a98
UW
10215 if (fd == -1)
10216 {
10217 errno = remote_fileio_errno_to_host (remote_errno);
10218 bfd_set_error (bfd_error_system_call);
10219 return NULL;
10220 }
10221
10222 stream = xmalloc (sizeof (int));
10223 *stream = fd;
10224 return stream;
10225}
10226
10227static int
10228remote_bfd_iovec_close (struct bfd *abfd, void *stream)
10229{
10230 int fd = *(int *)stream;
10231 int remote_errno;
10232
10233 xfree (stream);
10234
10235 /* Ignore errors on close; these may happen if the remote
10236 connection was already torn down. */
df39ea25 10237 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
f1838a98 10238
39ed5604
JK
10239 /* Zero means success. */
10240 return 0;
f1838a98
UW
10241}
10242
10243static file_ptr
10244remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
10245 file_ptr nbytes, file_ptr offset)
10246{
10247 int fd = *(int *)stream;
10248 int remote_errno;
10249 file_ptr pos, bytes;
10250
10251 pos = 0;
10252 while (nbytes > pos)
10253 {
a3be983c
TT
10254 bytes = remote_hostio_pread (find_target_at (process_stratum),
10255 fd, (gdb_byte *) buf + pos, nbytes - pos,
f1838a98
UW
10256 offset + pos, &remote_errno);
10257 if (bytes == 0)
10258 /* Success, but no bytes, means end-of-file. */
10259 break;
10260 if (bytes == -1)
10261 {
10262 errno = remote_fileio_errno_to_host (remote_errno);
10263 bfd_set_error (bfd_error_system_call);
10264 return -1;
10265 }
10266
10267 pos += bytes;
10268 }
10269
10270 return pos;
10271}
10272
10273static int
10274remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
10275{
0a93529c
GB
10276 int fd = *(int *) stream;
10277 int remote_errno;
10278 int result;
10279
10280 result = remote_hostio_fstat (find_target_at (process_stratum),
10281 fd, sb, &remote_errno);
10282
10283 if (result == -1)
10284 {
10285 errno = remote_fileio_errno_to_host (remote_errno);
10286 bfd_set_error (bfd_error_system_call);
10287 }
10288
10289 return result;
f1838a98
UW
10290}
10291
10292int
10293remote_filename_p (const char *filename)
10294{
61012eef 10295 return startswith (filename, REMOTE_SYSROOT_PREFIX);
f1838a98
UW
10296}
10297
10298bfd *
10299remote_bfd_open (const char *remote_file, const char *target)
10300{
64c31149
TT
10301 bfd *abfd = gdb_bfd_openr_iovec (remote_file, target,
10302 remote_bfd_iovec_open, NULL,
10303 remote_bfd_iovec_pread,
10304 remote_bfd_iovec_close,
10305 remote_bfd_iovec_stat);
10306
a4453b7e 10307 return abfd;
f1838a98
UW
10308}
10309
a6b151f1
DJ
10310void
10311remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10312{
10313 struct cleanup *back_to, *close_cleanup;
10314 int retcode, fd, remote_errno, bytes, io_size;
10315 FILE *file;
10316 gdb_byte *buffer;
10317 int bytes_in_buffer;
10318 int saw_eof;
10319 ULONGEST offset;
5d93a237 10320 struct remote_state *rs = get_remote_state ();
a6b151f1 10321
5d93a237 10322 if (!rs->remote_desc)
a6b151f1
DJ
10323 error (_("command can only be used with remote target"));
10324
614c279d 10325 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
10326 if (file == NULL)
10327 perror_with_name (local_file);
7c8a8b04 10328 back_to = make_cleanup_fclose (file);
a6b151f1 10329
cd897586
TT
10330 fd = remote_hostio_open (find_target_at (process_stratum),
10331 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1
DJ
10332 | FILEIO_O_TRUNC),
10333 0700, &remote_errno);
10334 if (fd == -1)
10335 remote_hostio_error (remote_errno);
10336
10337 /* Send up to this many bytes at once. They won't all fit in the
10338 remote packet limit, so we'll transfer slightly fewer. */
10339 io_size = get_remote_packet_size ();
10340 buffer = xmalloc (io_size);
10341 make_cleanup (xfree, buffer);
10342
10343 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10344
10345 bytes_in_buffer = 0;
10346 saw_eof = 0;
10347 offset = 0;
10348 while (bytes_in_buffer || !saw_eof)
10349 {
10350 if (!saw_eof)
10351 {
3e43a32a
MS
10352 bytes = fread (buffer + bytes_in_buffer, 1,
10353 io_size - bytes_in_buffer,
a6b151f1
DJ
10354 file);
10355 if (bytes == 0)
10356 {
10357 if (ferror (file))
10358 error (_("Error reading %s."), local_file);
10359 else
10360 {
10361 /* EOF. Unless there is something still in the
10362 buffer from the last iteration, we are done. */
10363 saw_eof = 1;
10364 if (bytes_in_buffer == 0)
10365 break;
10366 }
10367 }
10368 }
10369 else
10370 bytes = 0;
10371
10372 bytes += bytes_in_buffer;
10373 bytes_in_buffer = 0;
10374
0d866f62
TT
10375 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
10376 fd, buffer, bytes,
3e43a32a 10377 offset, &remote_errno);
a6b151f1
DJ
10378
10379 if (retcode < 0)
10380 remote_hostio_error (remote_errno);
10381 else if (retcode == 0)
10382 error (_("Remote write of %d bytes returned 0!"), bytes);
10383 else if (retcode < bytes)
10384 {
10385 /* Short write. Save the rest of the read data for the next
10386 write. */
10387 bytes_in_buffer = bytes - retcode;
10388 memmove (buffer, buffer + retcode, bytes_in_buffer);
10389 }
10390
10391 offset += retcode;
10392 }
10393
10394 discard_cleanups (close_cleanup);
df39ea25 10395 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
10396 remote_hostio_error (remote_errno);
10397
10398 if (from_tty)
10399 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10400 do_cleanups (back_to);
10401}
10402
10403void
10404remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10405{
10406 struct cleanup *back_to, *close_cleanup;
cea39f65 10407 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
10408 FILE *file;
10409 gdb_byte *buffer;
10410 ULONGEST offset;
5d93a237 10411 struct remote_state *rs = get_remote_state ();
a6b151f1 10412
5d93a237 10413 if (!rs->remote_desc)
a6b151f1
DJ
10414 error (_("command can only be used with remote target"));
10415
cd897586
TT
10416 fd = remote_hostio_open (find_target_at (process_stratum),
10417 remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
a6b151f1
DJ
10418 if (fd == -1)
10419 remote_hostio_error (remote_errno);
10420
614c279d 10421 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
10422 if (file == NULL)
10423 perror_with_name (local_file);
7c8a8b04 10424 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
10425
10426 /* Send up to this many bytes at once. They won't all fit in the
10427 remote packet limit, so we'll transfer slightly fewer. */
10428 io_size = get_remote_packet_size ();
10429 buffer = xmalloc (io_size);
10430 make_cleanup (xfree, buffer);
10431
10432 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10433
10434 offset = 0;
10435 while (1)
10436 {
a3be983c
TT
10437 bytes = remote_hostio_pread (find_target_at (process_stratum),
10438 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
10439 if (bytes == 0)
10440 /* Success, but no bytes, means end-of-file. */
10441 break;
10442 if (bytes == -1)
10443 remote_hostio_error (remote_errno);
10444
10445 offset += bytes;
10446
10447 bytes = fwrite (buffer, 1, bytes, file);
10448 if (bytes == 0)
10449 perror_with_name (local_file);
10450 }
10451
10452 discard_cleanups (close_cleanup);
df39ea25 10453 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
10454 remote_hostio_error (remote_errno);
10455
10456 if (from_tty)
10457 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10458 do_cleanups (back_to);
10459}
10460
10461void
10462remote_file_delete (const char *remote_file, int from_tty)
10463{
10464 int retcode, remote_errno;
5d93a237 10465 struct remote_state *rs = get_remote_state ();
a6b151f1 10466
5d93a237 10467 if (!rs->remote_desc)
a6b151f1
DJ
10468 error (_("command can only be used with remote target"));
10469
dbbca37d
TT
10470 retcode = remote_hostio_unlink (find_target_at (process_stratum),
10471 remote_file, &remote_errno);
a6b151f1
DJ
10472 if (retcode == -1)
10473 remote_hostio_error (remote_errno);
10474
10475 if (from_tty)
10476 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10477}
10478
10479static void
10480remote_put_command (char *args, int from_tty)
10481{
10482 struct cleanup *back_to;
10483 char **argv;
10484
d1a41061
PP
10485 if (args == NULL)
10486 error_no_arg (_("file to put"));
10487
10488 argv = gdb_buildargv (args);
a6b151f1
DJ
10489 back_to = make_cleanup_freeargv (argv);
10490 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10491 error (_("Invalid parameters to remote put"));
10492
10493 remote_file_put (argv[0], argv[1], from_tty);
10494
10495 do_cleanups (back_to);
10496}
10497
10498static void
10499remote_get_command (char *args, int from_tty)
10500{
10501 struct cleanup *back_to;
10502 char **argv;
10503
d1a41061
PP
10504 if (args == NULL)
10505 error_no_arg (_("file to get"));
10506
10507 argv = gdb_buildargv (args);
a6b151f1
DJ
10508 back_to = make_cleanup_freeargv (argv);
10509 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10510 error (_("Invalid parameters to remote get"));
10511
10512 remote_file_get (argv[0], argv[1], from_tty);
10513
10514 do_cleanups (back_to);
10515}
10516
10517static void
10518remote_delete_command (char *args, int from_tty)
10519{
10520 struct cleanup *back_to;
10521 char **argv;
10522
d1a41061
PP
10523 if (args == NULL)
10524 error_no_arg (_("file to delete"));
10525
10526 argv = gdb_buildargv (args);
a6b151f1
DJ
10527 back_to = make_cleanup_freeargv (argv);
10528 if (argv[0] == NULL || argv[1] != NULL)
10529 error (_("Invalid parameters to remote delete"));
10530
10531 remote_file_delete (argv[0], from_tty);
10532
10533 do_cleanups (back_to);
10534}
10535
10536static void
10537remote_command (char *args, int from_tty)
10538{
635c7e8a 10539 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
10540}
10541
b2175913 10542static int
19db3e69 10543remote_can_execute_reverse (struct target_ops *self)
b2175913 10544{
4082afcc
PA
10545 if (packet_support (PACKET_bs) == PACKET_ENABLE
10546 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
10547 return 1;
10548 else
10549 return 0;
b2175913
MS
10550}
10551
74531fed 10552static int
2a9a2795 10553remote_supports_non_stop (struct target_ops *self)
74531fed
PA
10554{
10555 return 1;
10556}
10557
03583c20 10558static int
2bfc0540 10559remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
10560{
10561 /* Only supported in extended mode. */
10562 return 0;
10563}
10564
8a305172 10565static int
86ce2668 10566remote_supports_multi_process (struct target_ops *self)
8a305172
PA
10567{
10568 struct remote_state *rs = get_remote_state ();
a744cf53 10569
901f9912
UW
10570 /* Only extended-remote handles being attached to multiple
10571 processes, even though plain remote can use the multi-process
10572 thread id extensions, so that GDB knows the target process's
10573 PID. */
10574 return rs->extended && remote_multi_process_p (rs);
8a305172
PA
10575}
10576
70221824 10577static int
782b2b07
SS
10578remote_supports_cond_tracepoints (void)
10579{
4082afcc 10580 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
10581}
10582
3788aec7 10583static int
efcc2da7 10584remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 10585{
4082afcc 10586 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
10587}
10588
70221824 10589static int
7a697b8d
SS
10590remote_supports_fast_tracepoints (void)
10591{
4082afcc 10592 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
10593}
10594
0fb4aa4b
PA
10595static int
10596remote_supports_static_tracepoints (void)
10597{
4082afcc 10598 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
10599}
10600
1e4d1764
YQ
10601static int
10602remote_supports_install_in_trace (void)
10603{
4082afcc 10604 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
10605}
10606
d248b706 10607static int
7d178d6a 10608remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 10609{
4082afcc
PA
10610 return (packet_support (PACKET_EnableDisableTracepoints_feature)
10611 == PACKET_ENABLE);
d248b706
KY
10612}
10613
3065dfb6 10614static int
6de37a3a 10615remote_supports_string_tracing (struct target_ops *self)
3065dfb6 10616{
4082afcc 10617 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
10618}
10619
d3ce09f5 10620static int
78eff0ec 10621remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 10622{
4082afcc 10623 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
10624}
10625
35b1e5cc 10626static void
ecae04e1 10627remote_trace_init (struct target_ops *self)
35b1e5cc
SS
10628{
10629 putpkt ("QTinit");
10630 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 10631 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
10632 error (_("Target does not support this command."));
10633}
10634
10635static void free_actions_list (char **actions_list);
10636static void free_actions_list_cleanup_wrapper (void *);
10637static void
10638free_actions_list_cleanup_wrapper (void *al)
10639{
10640 free_actions_list (al);
10641}
10642
10643static void
10644free_actions_list (char **actions_list)
10645{
10646 int ndx;
10647
10648 if (actions_list == 0)
10649 return;
10650
10651 for (ndx = 0; actions_list[ndx]; ndx++)
10652 xfree (actions_list[ndx]);
10653
10654 xfree (actions_list);
10655}
10656
409873ef
SS
10657/* Recursive routine to walk through command list including loops, and
10658 download packets for each command. */
10659
10660static void
10661remote_download_command_source (int num, ULONGEST addr,
10662 struct command_line *cmds)
10663{
10664 struct remote_state *rs = get_remote_state ();
10665 struct command_line *cmd;
10666
10667 for (cmd = cmds; cmd; cmd = cmd->next)
10668 {
0df8b418 10669 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
10670 strcpy (rs->buf, "QTDPsrc:");
10671 encode_source_string (num, addr, "cmd", cmd->line,
10672 rs->buf + strlen (rs->buf),
10673 rs->buf_size - strlen (rs->buf));
10674 putpkt (rs->buf);
10675 remote_get_noisy_reply (&target_buf, &target_buf_size);
10676 if (strcmp (target_buf, "OK"))
10677 warning (_("Target does not support source download."));
10678
10679 if (cmd->control_type == while_control
10680 || cmd->control_type == while_stepping_control)
10681 {
10682 remote_download_command_source (num, addr, *cmd->body_list);
10683
0df8b418 10684 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
10685 strcpy (rs->buf, "QTDPsrc:");
10686 encode_source_string (num, addr, "cmd", "end",
10687 rs->buf + strlen (rs->buf),
10688 rs->buf_size - strlen (rs->buf));
10689 putpkt (rs->buf);
10690 remote_get_noisy_reply (&target_buf, &target_buf_size);
10691 if (strcmp (target_buf, "OK"))
10692 warning (_("Target does not support source download."));
10693 }
10694 }
10695}
10696
35b1e5cc 10697static void
548f7808 10698remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 10699{
bba74b36 10700#define BUF_SIZE 2048
e8ba3115 10701
35b1e5cc 10702 CORE_ADDR tpaddr;
409873ef 10703 char addrbuf[40];
bba74b36 10704 char buf[BUF_SIZE];
35b1e5cc
SS
10705 char **tdp_actions;
10706 char **stepping_actions;
10707 int ndx;
10708 struct cleanup *old_chain = NULL;
10709 struct agent_expr *aexpr;
10710 struct cleanup *aexpr_chain = NULL;
10711 char *pkt;
e8ba3115 10712 struct breakpoint *b = loc->owner;
d9b3f62e 10713 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 10714
dc673c81 10715 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
10716 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10717 tdp_actions);
10718 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10719 stepping_actions);
10720
10721 tpaddr = loc->address;
10722 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
10723 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10724 addrbuf, /* address */
10725 (b->enable_state == bp_enabled ? 'E' : 'D'),
10726 t->step_count, t->pass_count);
e8ba3115
YQ
10727 /* Fast tracepoints are mostly handled by the target, but we can
10728 tell the target how big of an instruction block should be moved
10729 around. */
10730 if (b->type == bp_fast_tracepoint)
10731 {
10732 /* Only test for support at download time; we may not know
10733 target capabilities at definition time. */
10734 if (remote_supports_fast_tracepoints ())
35b1e5cc 10735 {
e8ba3115 10736 int isize;
35b1e5cc 10737
f5656ead 10738 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
e8ba3115 10739 tpaddr, &isize, NULL))
bba74b36
YQ
10740 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10741 isize);
35b1e5cc 10742 else
e8ba3115
YQ
10743 /* If it passed validation at definition but fails now,
10744 something is very wrong. */
10745 internal_error (__FILE__, __LINE__,
10746 _("Fast tracepoint not "
10747 "valid during download"));
35b1e5cc 10748 }
e8ba3115
YQ
10749 else
10750 /* Fast tracepoints are functionally identical to regular
10751 tracepoints, so don't take lack of support as a reason to
10752 give up on the trace run. */
10753 warning (_("Target does not support fast tracepoints, "
10754 "downloading %d as regular tracepoint"), b->number);
10755 }
10756 else if (b->type == bp_static_tracepoint)
10757 {
10758 /* Only test for support at download time; we may not know
10759 target capabilities at definition time. */
10760 if (remote_supports_static_tracepoints ())
0fb4aa4b 10761 {
e8ba3115 10762 struct static_tracepoint_marker marker;
0fb4aa4b 10763
e8ba3115
YQ
10764 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10765 strcat (buf, ":S");
0fb4aa4b 10766 else
e8ba3115 10767 error (_("Static tracepoint not valid during download"));
0fb4aa4b 10768 }
e8ba3115
YQ
10769 else
10770 /* Fast tracepoints are functionally identical to regular
10771 tracepoints, so don't take lack of support as a reason
10772 to give up on the trace run. */
10773 error (_("Target does not support static tracepoints"));
10774 }
10775 /* If the tracepoint has a conditional, make it into an agent
10776 expression and append to the definition. */
10777 if (loc->cond)
10778 {
10779 /* Only test support at download time, we may not know target
10780 capabilities at definition time. */
10781 if (remote_supports_cond_tracepoints ())
35b1e5cc 10782 {
e8ba3115
YQ
10783 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10784 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
10785 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10786 aexpr->len);
e8ba3115
YQ
10787 pkt = buf + strlen (buf);
10788 for (ndx = 0; ndx < aexpr->len; ++ndx)
10789 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10790 *pkt = '\0';
10791 do_cleanups (aexpr_chain);
35b1e5cc 10792 }
e8ba3115
YQ
10793 else
10794 warning (_("Target does not support conditional tracepoints, "
10795 "ignoring tp %d cond"), b->number);
10796 }
35b1e5cc 10797
d9b3f62e 10798 if (b->commands || *default_collect)
e8ba3115
YQ
10799 strcat (buf, "-");
10800 putpkt (buf);
10801 remote_get_noisy_reply (&target_buf, &target_buf_size);
10802 if (strcmp (target_buf, "OK"))
10803 error (_("Target does not support tracepoints."));
35b1e5cc 10804
e8ba3115
YQ
10805 /* do_single_steps (t); */
10806 if (tdp_actions)
10807 {
10808 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 10809 {
e8ba3115 10810 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
10811 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10812 b->number, addrbuf, /* address */
10813 tdp_actions[ndx],
10814 ((tdp_actions[ndx + 1] || stepping_actions)
10815 ? '-' : 0));
e8ba3115
YQ
10816 putpkt (buf);
10817 remote_get_noisy_reply (&target_buf,
10818 &target_buf_size);
10819 if (strcmp (target_buf, "OK"))
10820 error (_("Error on target while setting tracepoints."));
35b1e5cc 10821 }
e8ba3115
YQ
10822 }
10823 if (stepping_actions)
10824 {
10825 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 10826 {
e8ba3115 10827 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
10828 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10829 b->number, addrbuf, /* address */
10830 ((ndx == 0) ? "S" : ""),
10831 stepping_actions[ndx],
10832 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
10833 putpkt (buf);
10834 remote_get_noisy_reply (&target_buf,
10835 &target_buf_size);
10836 if (strcmp (target_buf, "OK"))
10837 error (_("Error on target while setting tracepoints."));
35b1e5cc 10838 }
e8ba3115 10839 }
409873ef 10840
4082afcc 10841 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115
YQ
10842 {
10843 if (b->addr_string)
409873ef 10844 {
e8ba3115
YQ
10845 strcpy (buf, "QTDPsrc:");
10846 encode_source_string (b->number, loc->address,
10847 "at", b->addr_string, buf + strlen (buf),
10848 2048 - strlen (buf));
409873ef 10849
e8ba3115
YQ
10850 putpkt (buf);
10851 remote_get_noisy_reply (&target_buf, &target_buf_size);
10852 if (strcmp (target_buf, "OK"))
10853 warning (_("Target does not support source download."));
409873ef 10854 }
e8ba3115
YQ
10855 if (b->cond_string)
10856 {
10857 strcpy (buf, "QTDPsrc:");
10858 encode_source_string (b->number, loc->address,
10859 "cond", b->cond_string, buf + strlen (buf),
10860 2048 - strlen (buf));
10861 putpkt (buf);
10862 remote_get_noisy_reply (&target_buf, &target_buf_size);
10863 if (strcmp (target_buf, "OK"))
10864 warning (_("Target does not support source download."));
10865 }
10866 remote_download_command_source (b->number, loc->address,
10867 breakpoint_commands (b));
35b1e5cc 10868 }
e8ba3115
YQ
10869
10870 do_cleanups (old_chain);
35b1e5cc
SS
10871}
10872
1e4d1764 10873static int
a52a8357 10874remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 10875{
1e51243a
PA
10876 struct remote_state *rs = get_remote_state ();
10877 struct trace_status *ts;
10878 int status;
10879
10880 /* Don't try to install tracepoints until we've relocated our
10881 symbols, and fetched and merged the target's tracepoint list with
10882 ours. */
10883 if (rs->starting_up)
10884 return 0;
10885
10886 ts = current_trace_status ();
8bd200f1 10887 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
10888
10889 if (status == -1 || !ts->running_known || !ts->running)
10890 return 0;
10891
10892 /* If we are in a tracing experiment, but remote stub doesn't support
10893 installing tracepoint in trace, we have to return. */
10894 if (!remote_supports_install_in_trace ())
10895 return 0;
10896
10897 return 1;
10898}
10899
10900
35b1e5cc 10901static void
559d2b81
TT
10902remote_download_trace_state_variable (struct target_ops *self,
10903 struct trace_state_variable *tsv)
35b1e5cc
SS
10904{
10905 struct remote_state *rs = get_remote_state ();
00bf0b85 10906 char *p;
35b1e5cc 10907
bba74b36
YQ
10908 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10909 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10910 tsv->builtin);
00bf0b85
SS
10911 p = rs->buf + strlen (rs->buf);
10912 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10913 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 10914 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 10915 *p++ = '\0';
35b1e5cc
SS
10916 putpkt (rs->buf);
10917 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
10918 if (*target_buf == '\0')
10919 error (_("Target does not support this command."));
10920 if (strcmp (target_buf, "OK") != 0)
10921 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
10922}
10923
d248b706 10924static void
46670d57
TT
10925remote_enable_tracepoint (struct target_ops *self,
10926 struct bp_location *location)
d248b706
KY
10927{
10928 struct remote_state *rs = get_remote_state ();
10929 char addr_buf[40];
10930
10931 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
10932 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10933 location->owner->number, addr_buf);
d248b706
KY
10934 putpkt (rs->buf);
10935 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10936 if (*rs->buf == '\0')
10937 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10938 if (strcmp (rs->buf, "OK") != 0)
10939 error (_("Error on target while enabling tracepoint."));
10940}
10941
10942static void
780b049c
TT
10943remote_disable_tracepoint (struct target_ops *self,
10944 struct bp_location *location)
d248b706
KY
10945{
10946 struct remote_state *rs = get_remote_state ();
10947 char addr_buf[40];
10948
10949 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
10950 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10951 location->owner->number, addr_buf);
d248b706
KY
10952 putpkt (rs->buf);
10953 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10954 if (*rs->buf == '\0')
10955 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10956 if (strcmp (rs->buf, "OK") != 0)
10957 error (_("Error on target while disabling tracepoint."));
10958}
10959
35b1e5cc 10960static void
583f9a86 10961remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
10962{
10963 asection *s;
81b9b86e 10964 bfd *abfd = NULL;
35b1e5cc 10965 bfd_size_type size;
608bcef2 10966 bfd_vma vma;
35b1e5cc 10967 int anysecs = 0;
c2fa21f1 10968 int offset = 0;
35b1e5cc
SS
10969
10970 if (!exec_bfd)
10971 return; /* No information to give. */
10972
10973 strcpy (target_buf, "QTro");
9779ab84 10974 offset = strlen (target_buf);
35b1e5cc
SS
10975 for (s = exec_bfd->sections; s; s = s->next)
10976 {
10977 char tmp1[40], tmp2[40];
c2fa21f1 10978 int sec_length;
35b1e5cc
SS
10979
10980 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 10981 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
10982 (s->flags & SEC_READONLY) == 0)
10983 continue;
10984
10985 anysecs = 1;
81b9b86e 10986 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 10987 size = bfd_get_section_size (s);
608bcef2
HZ
10988 sprintf_vma (tmp1, vma);
10989 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
10990 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10991 if (offset + sec_length + 1 > target_buf_size)
10992 {
4082afcc 10993 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 10994 warning (_("\
c2fa21f1
HZ
10995Too many sections for read-only sections definition packet."));
10996 break;
10997 }
bba74b36
YQ
10998 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10999 tmp1, tmp2);
c2fa21f1 11000 offset += sec_length;
35b1e5cc
SS
11001 }
11002 if (anysecs)
11003 {
11004 putpkt (target_buf);
11005 getpkt (&target_buf, &target_buf_size, 0);
11006 }
11007}
11008
11009static void
e2d1aae3 11010remote_trace_start (struct target_ops *self)
35b1e5cc
SS
11011{
11012 putpkt ("QTStart");
11013 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11014 if (*target_buf == '\0')
11015 error (_("Target does not support this command."));
11016 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11017 error (_("Bogus reply from target: %s"), target_buf);
11018}
11019
11020static int
8bd200f1 11021remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 11022{
953b98d1 11023 /* Initialize it just to avoid a GCC false warning. */
f652de6f 11024 char *p = NULL;
0df8b418 11025 /* FIXME we need to get register block size some other way. */
00bf0b85 11026 extern int trace_regblock_size;
bd3eecc3
PA
11027 enum packet_result result;
11028
4082afcc 11029 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 11030 return -1;
a744cf53 11031
00bf0b85
SS
11032 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
11033
049dc89b
JK
11034 putpkt ("qTStatus");
11035
492d29ea 11036 TRY
67f41397
JK
11037 {
11038 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
11039 }
492d29ea 11040 CATCH (ex, RETURN_MASK_ERROR)
67f41397 11041 {
598d3636
JK
11042 if (ex.error != TARGET_CLOSE_ERROR)
11043 {
11044 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
11045 return -1;
11046 }
11047 throw_exception (ex);
67f41397 11048 }
492d29ea 11049 END_CATCH
00bf0b85 11050
bd3eecc3
PA
11051 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
11052
00bf0b85 11053 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 11054 if (result == PACKET_UNKNOWN)
00bf0b85 11055 return -1;
35b1e5cc 11056
00bf0b85 11057 /* We're working with a live target. */
f5911ea1 11058 ts->filename = NULL;
00bf0b85 11059
00bf0b85 11060 if (*p++ != 'T')
35b1e5cc
SS
11061 error (_("Bogus trace status reply from target: %s"), target_buf);
11062
84cebc4a
YQ
11063 /* Function 'parse_trace_status' sets default value of each field of
11064 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
11065 parse_trace_status (p, ts);
11066
11067 return ts->running;
35b1e5cc
SS
11068}
11069
70221824 11070static void
db90e85c 11071remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
11072 struct uploaded_tp *utp)
11073{
11074 struct remote_state *rs = get_remote_state ();
f196051f
SS
11075 char *reply;
11076 struct bp_location *loc;
11077 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 11078 size_t size = get_remote_packet_size ();
f196051f
SS
11079
11080 if (tp)
11081 {
11082 tp->base.hit_count = 0;
11083 tp->traceframe_usage = 0;
11084 for (loc = tp->base.loc; loc; loc = loc->next)
11085 {
11086 /* If the tracepoint was never downloaded, don't go asking for
11087 any status. */
11088 if (tp->number_on_target == 0)
11089 continue;
bba74b36
YQ
11090 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
11091 phex_nz (loc->address, 0));
f196051f
SS
11092 putpkt (rs->buf);
11093 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11094 if (reply && *reply)
11095 {
11096 if (*reply == 'V')
11097 parse_tracepoint_status (reply + 1, bp, utp);
11098 }
11099 }
11100 }
11101 else if (utp)
11102 {
11103 utp->hit_count = 0;
11104 utp->traceframe_usage = 0;
bba74b36
YQ
11105 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
11106 phex_nz (utp->addr, 0));
f196051f
SS
11107 putpkt (rs->buf);
11108 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11109 if (reply && *reply)
11110 {
11111 if (*reply == 'V')
11112 parse_tracepoint_status (reply + 1, bp, utp);
11113 }
11114 }
11115}
11116
35b1e5cc 11117static void
74499f1b 11118remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
11119{
11120 putpkt ("QTStop");
11121 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11122 if (*target_buf == '\0')
11123 error (_("Target does not support this command."));
11124 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11125 error (_("Bogus reply from target: %s"), target_buf);
11126}
11127
11128static int
bd4c6793
TT
11129remote_trace_find (struct target_ops *self,
11130 enum trace_find_type type, int num,
cc5925ad 11131 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
11132 int *tpp)
11133{
11134 struct remote_state *rs = get_remote_state ();
bba74b36 11135 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
11136 char *p, *reply;
11137 int target_frameno = -1, target_tracept = -1;
11138
e6e4e701
PA
11139 /* Lookups other than by absolute frame number depend on the current
11140 trace selected, so make sure it is correct on the remote end
11141 first. */
11142 if (type != tfind_number)
11143 set_remote_traceframe ();
11144
35b1e5cc
SS
11145 p = rs->buf;
11146 strcpy (p, "QTFrame:");
11147 p = strchr (p, '\0');
11148 switch (type)
11149 {
11150 case tfind_number:
bba74b36 11151 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
11152 break;
11153 case tfind_pc:
bba74b36 11154 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
11155 break;
11156 case tfind_tp:
bba74b36 11157 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
11158 break;
11159 case tfind_range:
bba74b36
YQ
11160 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11161 phex_nz (addr2, 0));
35b1e5cc
SS
11162 break;
11163 case tfind_outside:
bba74b36
YQ
11164 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11165 phex_nz (addr2, 0));
35b1e5cc
SS
11166 break;
11167 default:
9b20d036 11168 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
11169 }
11170
11171 putpkt (rs->buf);
2f65bcb7 11172 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
11173 if (*reply == '\0')
11174 error (_("Target does not support this command."));
35b1e5cc
SS
11175
11176 while (reply && *reply)
11177 switch (*reply)
11178 {
11179 case 'F':
f197e0f1
VP
11180 p = ++reply;
11181 target_frameno = (int) strtol (p, &reply, 16);
11182 if (reply == p)
11183 error (_("Unable to parse trace frame number"));
e6e4e701
PA
11184 /* Don't update our remote traceframe number cache on failure
11185 to select a remote traceframe. */
f197e0f1
VP
11186 if (target_frameno == -1)
11187 return -1;
35b1e5cc
SS
11188 break;
11189 case 'T':
f197e0f1
VP
11190 p = ++reply;
11191 target_tracept = (int) strtol (p, &reply, 16);
11192 if (reply == p)
11193 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
11194 break;
11195 case 'O': /* "OK"? */
11196 if (reply[1] == 'K' && reply[2] == '\0')
11197 reply += 2;
11198 else
11199 error (_("Bogus reply from target: %s"), reply);
11200 break;
11201 default:
11202 error (_("Bogus reply from target: %s"), reply);
11203 }
11204 if (tpp)
11205 *tpp = target_tracept;
e6e4e701 11206
262e1174 11207 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
11208 return target_frameno;
11209}
11210
11211static int
4011015b
TT
11212remote_get_trace_state_variable_value (struct target_ops *self,
11213 int tsvnum, LONGEST *val)
35b1e5cc
SS
11214{
11215 struct remote_state *rs = get_remote_state ();
11216 char *reply;
11217 ULONGEST uval;
11218
e6e4e701
PA
11219 set_remote_traceframe ();
11220
bba74b36 11221 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
11222 putpkt (rs->buf);
11223 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11224 if (reply && *reply)
11225 {
11226 if (*reply == 'V')
11227 {
11228 unpack_varlen_hex (reply + 1, &uval);
11229 *val = (LONGEST) uval;
11230 return 1;
11231 }
11232 }
11233 return 0;
11234}
11235
00bf0b85 11236static int
dc3decaf 11237remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
11238{
11239 struct remote_state *rs = get_remote_state ();
11240 char *p, *reply;
11241
11242 p = rs->buf;
11243 strcpy (p, "QTSave:");
11244 p += strlen (p);
11245 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11246 error (_("Remote file name too long for trace save packet"));
9f1b45b0 11247 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
11248 *p++ = '\0';
11249 putpkt (rs->buf);
ad91cd99 11250 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 11251 if (*reply == '\0')
ad91cd99
PA
11252 error (_("Target does not support this command."));
11253 if (strcmp (reply, "OK") != 0)
11254 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
11255 return 0;
11256}
11257
11258/* This is basically a memory transfer, but needs to be its own packet
11259 because we don't know how the target actually organizes its trace
11260 memory, plus we want to be able to ask for as much as possible, but
11261 not be unhappy if we don't get as much as we ask for. */
11262
11263static LONGEST
88ee6f45
TT
11264remote_get_raw_trace_data (struct target_ops *self,
11265 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
11266{
11267 struct remote_state *rs = get_remote_state ();
11268 char *reply;
11269 char *p;
11270 int rslt;
11271
11272 p = rs->buf;
11273 strcpy (p, "qTBuffer:");
11274 p += strlen (p);
11275 p += hexnumstr (p, offset);
11276 *p++ = ',';
11277 p += hexnumstr (p, len);
11278 *p++ = '\0';
11279
11280 putpkt (rs->buf);
11281 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11282 if (reply && *reply)
11283 {
11284 /* 'l' by itself means we're at the end of the buffer and
11285 there is nothing more to get. */
11286 if (*reply == 'l')
11287 return 0;
11288
11289 /* Convert the reply into binary. Limit the number of bytes to
11290 convert according to our passed-in buffer size, rather than
11291 what was returned in the packet; if the target is
11292 unexpectedly generous and gives us a bigger reply than we
11293 asked for, we don't want to crash. */
11294 rslt = hex2bin (target_buf, buf, len);
11295 return rslt;
11296 }
11297
11298 /* Something went wrong, flag as an error. */
11299 return -1;
11300}
11301
35b1e5cc 11302static void
37b25738 11303remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
11304{
11305 struct remote_state *rs = get_remote_state ();
11306
4082afcc 11307 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 11308 {
ad91cd99
PA
11309 char *reply;
11310
bba74b36 11311 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 11312 putpkt (rs->buf);
ad91cd99
PA
11313 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11314 if (*reply == '\0')
33da3f1c 11315 error (_("Target does not support this command."));
ad91cd99
PA
11316 if (strcmp (reply, "OK") != 0)
11317 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
11318 }
11319 else if (val)
11320 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
11321}
11322
dc146f7c
VP
11323static int
11324remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11325{
11326 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 11327
fe978cb0
PA
11328 if (info && info->priv)
11329 return info->priv->core;
dc146f7c
VP
11330 return -1;
11331}
11332
4daf5ac0 11333static void
736d5b1f 11334remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
11335{
11336 struct remote_state *rs = get_remote_state ();
ad91cd99 11337 char *reply;
4daf5ac0 11338
bba74b36 11339 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 11340 putpkt (rs->buf);
ad91cd99
PA
11341 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11342 if (*reply == '\0')
4daf5ac0 11343 error (_("Target does not support this command."));
ad91cd99
PA
11344 if (strcmp (reply, "OK") != 0)
11345 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
11346}
11347
b3b9301e 11348static struct traceframe_info *
a893e81f 11349remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
11350{
11351 char *text;
11352
11353 text = target_read_stralloc (&current_target,
11354 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11355 if (text != NULL)
11356 {
11357 struct traceframe_info *info;
11358 struct cleanup *back_to = make_cleanup (xfree, text);
11359
11360 info = parse_traceframe_info (text);
11361 do_cleanups (back_to);
11362 return info;
11363 }
11364
11365 return NULL;
11366}
11367
405f8e94
SS
11368/* Handle the qTMinFTPILen packet. Returns the minimum length of
11369 instruction on which a fast tracepoint may be placed. Returns -1
11370 if the packet is not supported, and 0 if the minimum instruction
11371 length is unknown. */
11372
11373static int
0e67620a 11374remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
11375{
11376 struct remote_state *rs = get_remote_state ();
11377 char *reply;
11378
e886a173
PA
11379 /* If we're not debugging a process yet, the IPA can't be
11380 loaded. */
11381 if (!target_has_execution)
11382 return 0;
11383
11384 /* Make sure the remote is pointing at the right process. */
11385 set_general_process ();
11386
bba74b36 11387 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
11388 putpkt (rs->buf);
11389 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11390 if (*reply == '\0')
11391 return -1;
11392 else
11393 {
11394 ULONGEST min_insn_len;
11395
11396 unpack_varlen_hex (reply, &min_insn_len);
11397
11398 return (int) min_insn_len;
11399 }
11400}
11401
f6f899bf 11402static void
4da384be 11403remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 11404{
4082afcc 11405 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
11406 {
11407 struct remote_state *rs = get_remote_state ();
11408 char *buf = rs->buf;
11409 char *endbuf = rs->buf + get_remote_packet_size ();
11410 enum packet_result result;
11411
11412 gdb_assert (val >= 0 || val == -1);
11413 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11414 /* Send -1 as literal "-1" to avoid host size dependency. */
11415 if (val < 0)
11416 {
11417 *buf++ = '-';
11418 buf += hexnumstr (buf, (ULONGEST) -val);
11419 }
11420 else
11421 buf += hexnumstr (buf, (ULONGEST) val);
11422
11423 putpkt (rs->buf);
11424 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11425 result = packet_ok (rs->buf,
11426 &remote_protocol_packets[PACKET_QTBuffer_size]);
11427
11428 if (result != PACKET_OK)
11429 warning (_("Bogus reply from target: %s"), rs->buf);
11430 }
11431}
11432
f196051f 11433static int
d9e68a2c
TT
11434remote_set_trace_notes (struct target_ops *self,
11435 const char *user, const char *notes,
ca623f82 11436 const char *stop_notes)
f196051f
SS
11437{
11438 struct remote_state *rs = get_remote_state ();
11439 char *reply;
11440 char *buf = rs->buf;
11441 char *endbuf = rs->buf + get_remote_packet_size ();
11442 int nbytes;
11443
11444 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11445 if (user)
11446 {
11447 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 11448 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
11449 buf += 2 * nbytes;
11450 *buf++ = ';';
11451 }
11452 if (notes)
11453 {
11454 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 11455 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
11456 buf += 2 * nbytes;
11457 *buf++ = ';';
11458 }
11459 if (stop_notes)
11460 {
11461 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 11462 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
11463 buf += 2 * nbytes;
11464 *buf++ = ';';
11465 }
11466 /* Ensure the buffer is terminated. */
11467 *buf = '\0';
11468
11469 putpkt (rs->buf);
11470 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11471 if (*reply == '\0')
11472 return 0;
11473
11474 if (strcmp (reply, "OK") != 0)
11475 error (_("Bogus reply from target: %s"), reply);
11476
11477 return 1;
11478}
11479
d1feda86 11480static int
2c152180 11481remote_use_agent (struct target_ops *self, int use)
d1feda86 11482{
4082afcc 11483 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
11484 {
11485 struct remote_state *rs = get_remote_state ();
11486
11487 /* If the stub supports QAgent. */
bba74b36 11488 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
11489 putpkt (rs->buf);
11490 getpkt (&rs->buf, &rs->buf_size, 0);
11491
11492 if (strcmp (rs->buf, "OK") == 0)
11493 {
11494 use_agent = use;
11495 return 1;
11496 }
11497 }
11498
11499 return 0;
11500}
11501
11502static int
fe38f897 11503remote_can_use_agent (struct target_ops *self)
d1feda86 11504{
4082afcc 11505 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
11506}
11507
9accd112
MM
11508struct btrace_target_info
11509{
11510 /* The ptid of the traced thread. */
11511 ptid_t ptid;
f4abbc16
MM
11512
11513 /* The obtained branch trace configuration. */
11514 struct btrace_config conf;
9accd112
MM
11515};
11516
f4abbc16
MM
11517/* Reset our idea of our target's btrace configuration. */
11518
11519static void
11520remote_btrace_reset (void)
11521{
11522 struct remote_state *rs = get_remote_state ();
11523
11524 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
11525}
11526
9accd112
MM
11527/* Check whether the target supports branch tracing. */
11528
11529static int
043c3577 11530remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 11531{
4082afcc 11532 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 11533 return 0;
4082afcc 11534 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
11535 return 0;
11536
043c3577
MM
11537 switch (format)
11538 {
11539 case BTRACE_FORMAT_NONE:
11540 return 0;
11541
11542 case BTRACE_FORMAT_BTS:
11543 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
11544 }
11545
11546 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
11547}
11548
f4abbc16
MM
11549/* Synchronize the configuration with the target. */
11550
11551static void
11552btrace_sync_conf (const struct btrace_config *conf)
11553{
d33501a5
MM
11554 struct packet_config *packet;
11555 struct remote_state *rs;
11556 char *buf, *pos, *endbuf;
11557
11558 rs = get_remote_state ();
11559 buf = rs->buf;
11560 endbuf = buf + get_remote_packet_size ();
11561
11562 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
11563 if (packet_config_support (packet) == PACKET_ENABLE
11564 && conf->bts.size != rs->btrace_config.bts.size)
11565 {
11566 pos = buf;
11567 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
11568 conf->bts.size);
11569
11570 putpkt (buf);
11571 getpkt (&buf, &rs->buf_size, 0);
11572
11573 if (packet_ok (buf, packet) == PACKET_ERROR)
11574 {
11575 if (buf[0] == 'E' && buf[1] == '.')
11576 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
11577 else
11578 error (_("Failed to configure the BTS buffer size."));
11579 }
11580
11581 rs->btrace_config.bts.size = conf->bts.size;
11582 }
f4abbc16
MM
11583}
11584
11585/* Read the current thread's btrace configuration from the target and
11586 store it into CONF. */
11587
11588static void
11589btrace_read_config (struct btrace_config *conf)
11590{
11591 char *xml;
11592
11593 xml = target_read_stralloc (&current_target,
11594 TARGET_OBJECT_BTRACE_CONF, "");
11595 if (xml != NULL)
11596 {
11597 struct cleanup *cleanup;
11598
11599 cleanup = make_cleanup (xfree, xml);
11600 parse_xml_btrace_conf (conf, xml);
11601 do_cleanups (cleanup);
11602 }
11603}
11604
9accd112
MM
11605/* Enable branch tracing. */
11606
11607static struct btrace_target_info *
f4abbc16
MM
11608remote_enable_btrace (struct target_ops *self, ptid_t ptid,
11609 const struct btrace_config *conf)
9accd112
MM
11610{
11611 struct btrace_target_info *tinfo = NULL;
11612 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11613 struct remote_state *rs = get_remote_state ();
11614 char *buf = rs->buf;
11615 char *endbuf = rs->buf + get_remote_packet_size ();
11616
4082afcc 11617 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
11618 error (_("Target does not support branch tracing."));
11619
f4abbc16
MM
11620 btrace_sync_conf (conf);
11621
9accd112
MM
11622 set_general_thread (ptid);
11623
11624 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11625 putpkt (rs->buf);
11626 getpkt (&rs->buf, &rs->buf_size, 0);
11627
11628 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11629 {
11630 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11631 error (_("Could not enable branch tracing for %s: %s"),
11632 target_pid_to_str (ptid), rs->buf + 2);
11633 else
11634 error (_("Could not enable branch tracing for %s."),
11635 target_pid_to_str (ptid));
11636 }
11637
11638 tinfo = xzalloc (sizeof (*tinfo));
11639 tinfo->ptid = ptid;
11640
f4abbc16
MM
11641 /* If we fail to read the configuration, we lose some information, but the
11642 tracing itself is not impacted. */
492d29ea
PA
11643 TRY
11644 {
11645 btrace_read_config (&tinfo->conf);
11646 }
11647 CATCH (err, RETURN_MASK_ERROR)
11648 {
11649 if (err.message != NULL)
11650 warning ("%s", err.message);
11651 }
11652 END_CATCH
f4abbc16 11653
9accd112
MM
11654 return tinfo;
11655}
11656
11657/* Disable branch tracing. */
11658
11659static void
25e95349
TT
11660remote_disable_btrace (struct target_ops *self,
11661 struct btrace_target_info *tinfo)
9accd112
MM
11662{
11663 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11664 struct remote_state *rs = get_remote_state ();
11665 char *buf = rs->buf;
11666 char *endbuf = rs->buf + get_remote_packet_size ();
11667
4082afcc 11668 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
11669 error (_("Target does not support branch tracing."));
11670
11671 set_general_thread (tinfo->ptid);
11672
11673 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11674 putpkt (rs->buf);
11675 getpkt (&rs->buf, &rs->buf_size, 0);
11676
11677 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11678 {
11679 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11680 error (_("Could not disable branch tracing for %s: %s"),
11681 target_pid_to_str (tinfo->ptid), rs->buf + 2);
11682 else
11683 error (_("Could not disable branch tracing for %s."),
11684 target_pid_to_str (tinfo->ptid));
11685 }
11686
11687 xfree (tinfo);
11688}
11689
11690/* Teardown branch tracing. */
11691
11692static void
1777056d
TT
11693remote_teardown_btrace (struct target_ops *self,
11694 struct btrace_target_info *tinfo)
9accd112
MM
11695{
11696 /* We must not talk to the target during teardown. */
11697 xfree (tinfo);
11698}
11699
11700/* Read the branch trace. */
11701
969c39fb 11702static enum btrace_error
39c49f83 11703remote_read_btrace (struct target_ops *self,
734b0e4b 11704 struct btrace_data *btrace,
969c39fb 11705 struct btrace_target_info *tinfo,
9accd112
MM
11706 enum btrace_read_type type)
11707{
11708 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11709 struct remote_state *rs = get_remote_state ();
969c39fb 11710 struct cleanup *cleanup;
9accd112
MM
11711 const char *annex;
11712 char *xml;
11713
4082afcc 11714 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
11715 error (_("Target does not support branch tracing."));
11716
11717#if !defined(HAVE_LIBEXPAT)
11718 error (_("Cannot process branch tracing result. XML parsing not supported."));
11719#endif
11720
11721 switch (type)
11722 {
864089d2 11723 case BTRACE_READ_ALL:
9accd112
MM
11724 annex = "all";
11725 break;
864089d2 11726 case BTRACE_READ_NEW:
9accd112
MM
11727 annex = "new";
11728 break;
969c39fb
MM
11729 case BTRACE_READ_DELTA:
11730 annex = "delta";
11731 break;
9accd112
MM
11732 default:
11733 internal_error (__FILE__, __LINE__,
11734 _("Bad branch tracing read type: %u."),
11735 (unsigned int) type);
11736 }
11737
11738 xml = target_read_stralloc (&current_target,
11739 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
11740 if (xml == NULL)
11741 return BTRACE_ERR_UNKNOWN;
9accd112 11742
969c39fb 11743 cleanup = make_cleanup (xfree, xml);
734b0e4b 11744 parse_xml_btrace (btrace, xml);
969c39fb 11745 do_cleanups (cleanup);
9accd112 11746
969c39fb 11747 return BTRACE_ERR_NONE;
9accd112
MM
11748}
11749
f4abbc16
MM
11750static const struct btrace_config *
11751remote_btrace_conf (struct target_ops *self,
11752 const struct btrace_target_info *tinfo)
11753{
11754 return &tinfo->conf;
11755}
11756
ced63ec0 11757static int
5436ff03 11758remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 11759{
4082afcc
PA
11760 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
11761 == PACKET_ENABLE);
ced63ec0
GB
11762}
11763
9dd130a0
TT
11764/* Implementation of to_load. */
11765
11766static void
9cbe5fff 11767remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
11768{
11769 generic_load (name, from_tty);
11770}
11771
c906108c 11772static void
fba45db2 11773init_remote_ops (void)
c906108c 11774{
c5aa993b 11775 remote_ops.to_shortname = "remote";
c906108c 11776 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 11777 remote_ops.to_doc =
c906108c 11778 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
11779Specify the serial device it is connected to\n\
11780(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
11781 remote_ops.to_open = remote_open;
11782 remote_ops.to_close = remote_close;
c906108c 11783 remote_ops.to_detach = remote_detach;
6ad8ae5c 11784 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 11785 remote_ops.to_resume = remote_resume;
c906108c
SS
11786 remote_ops.to_wait = remote_wait;
11787 remote_ops.to_fetch_registers = remote_fetch_registers;
11788 remote_ops.to_store_registers = remote_store_registers;
11789 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 11790 remote_ops.to_files_info = remote_files_info;
c906108c
SS
11791 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11792 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
11793 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
11794 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
11795 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
11796 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
11797 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11798 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
11799 remote_ops.to_watchpoint_addr_within_range =
11800 remote_watchpoint_addr_within_range;
3c3bea1c
GS
11801 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11802 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11803 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
11804 remote_ops.to_region_ok_for_hw_watchpoint
11805 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
11806 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11807 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 11808 remote_ops.to_kill = remote_kill;
9dd130a0 11809 remote_ops.to_load = remote_load;
c906108c 11810 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 11811 remote_ops.to_pass_signals = remote_pass_signals;
9b224c5e 11812 remote_ops.to_program_signals = remote_program_signals;
c906108c 11813 remote_ops.to_thread_alive = remote_thread_alive;
e8032dde 11814 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 11815 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 11816 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 11817 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 11818 remote_ops.to_stop = remote_stop;
4b8a223f 11819 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 11820 remote_ops.to_rcmd = remote_rcmd;
49d03eab 11821 remote_ops.to_log_command = serial_log_command;
38691318 11822 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 11823 remote_ops.to_stratum = process_stratum;
c35b1492
PA
11824 remote_ops.to_has_all_memory = default_child_has_all_memory;
11825 remote_ops.to_has_memory = default_child_has_memory;
11826 remote_ops.to_has_stack = default_child_has_stack;
11827 remote_ops.to_has_registers = default_child_has_registers;
11828 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 11829 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 11830 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 11831 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 11832 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
11833 remote_ops.to_flash_erase = remote_flash_erase;
11834 remote_ops.to_flash_done = remote_flash_done;
29709017 11835 remote_ops.to_read_description = remote_read_description;
08388c79 11836 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
11837 remote_ops.to_can_async_p = remote_can_async_p;
11838 remote_ops.to_is_async_p = remote_is_async_p;
11839 remote_ops.to_async = remote_async;
75c99385
PA
11840 remote_ops.to_terminal_inferior = remote_terminal_inferior;
11841 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 11842 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 11843 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
11844 remote_ops.to_supports_disable_randomization
11845 = remote_supports_disable_randomization;
7313baad
UW
11846 remote_ops.to_fileio_open = remote_hostio_open;
11847 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11848 remote_ops.to_fileio_pread = remote_hostio_pread;
11849 remote_ops.to_fileio_close = remote_hostio_close;
11850 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 11851 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 11852 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 11853 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 11854 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 11855 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
11856 remote_ops.to_trace_init = remote_trace_init;
11857 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 11858 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
11859 remote_ops.to_download_trace_state_variable
11860 = remote_download_trace_state_variable;
d248b706
KY
11861 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11862 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
11863 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11864 remote_ops.to_trace_start = remote_trace_start;
11865 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 11866 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
11867 remote_ops.to_trace_stop = remote_trace_stop;
11868 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
11869 remote_ops.to_get_trace_state_variable_value
11870 = remote_get_trace_state_variable_value;
00bf0b85
SS
11871 remote_ops.to_save_trace_data = remote_save_trace_data;
11872 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
11873 remote_ops.to_upload_trace_state_variables
11874 = remote_upload_trace_state_variables;
00bf0b85 11875 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 11876 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 11877 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 11878 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 11879 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 11880 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 11881 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 11882 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 11883 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 11884 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
11885 remote_ops.to_static_tracepoint_marker_at
11886 = remote_static_tracepoint_marker_at;
11887 remote_ops.to_static_tracepoint_markers_by_strid
11888 = remote_static_tracepoint_markers_by_strid;
b3b9301e 11889 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
11890 remote_ops.to_use_agent = remote_use_agent;
11891 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
11892 remote_ops.to_supports_btrace = remote_supports_btrace;
11893 remote_ops.to_enable_btrace = remote_enable_btrace;
11894 remote_ops.to_disable_btrace = remote_disable_btrace;
11895 remote_ops.to_teardown_btrace = remote_teardown_btrace;
11896 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 11897 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
11898 remote_ops.to_augmented_libraries_svr4_read =
11899 remote_augmented_libraries_svr4_read;
c906108c
SS
11900}
11901
11902/* Set up the extended remote vector by making a copy of the standard
11903 remote vector and adding to it. */
11904
11905static void
fba45db2 11906init_extended_remote_ops (void)
c906108c
SS
11907{
11908 extended_remote_ops = remote_ops;
11909
0f71a2f6 11910 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 11911 extended_remote_ops.to_longname =
c906108c 11912 "Extended remote serial target in gdb-specific protocol";
c5aa993b 11913 extended_remote_ops.to_doc =
c906108c 11914 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
11915Specify the serial device it is connected to (e.g. /dev/ttya).";
11916 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
11917 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11918 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
11919 extended_remote_ops.to_detach = extended_remote_detach;
11920 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 11921 extended_remote_ops.to_post_attach = extended_remote_post_attach;
82f73884 11922 extended_remote_ops.to_kill = extended_remote_kill;
03583c20
UW
11923 extended_remote_ops.to_supports_disable_randomization
11924 = extended_remote_supports_disable_randomization;
0f71a2f6
JM
11925}
11926
6426a772 11927static int
6a109b6b 11928remote_can_async_p (struct target_ops *ops)
6426a772 11929{
5d93a237
TT
11930 struct remote_state *rs = get_remote_state ();
11931
c6ebd6cf 11932 if (!target_async_permitted)
75c99385
PA
11933 /* We only enable async when the user specifically asks for it. */
11934 return 0;
11935
23860348 11936 /* We're async whenever the serial device is. */
5d93a237 11937 return serial_can_async_p (rs->remote_desc);
6426a772
JM
11938}
11939
11940static int
6a109b6b 11941remote_is_async_p (struct target_ops *ops)
6426a772 11942{
5d93a237
TT
11943 struct remote_state *rs = get_remote_state ();
11944
c6ebd6cf 11945 if (!target_async_permitted)
75c99385
PA
11946 /* We only enable async when the user specifically asks for it. */
11947 return 0;
11948
23860348 11949 /* We're async whenever the serial device is. */
5d93a237 11950 return serial_is_async_p (rs->remote_desc);
6426a772
JM
11951}
11952
2acceee2
JM
11953/* Pass the SERIAL event on and up to the client. One day this code
11954 will be able to delay notifying the client of an event until the
23860348 11955 point where an entire packet has been received. */
2acceee2 11956
2acceee2
JM
11957static serial_event_ftype remote_async_serial_handler;
11958
6426a772 11959static void
819cc324 11960remote_async_serial_handler (struct serial *scb, void *context)
6426a772 11961{
88b496c3
TT
11962 struct remote_state *rs = context;
11963
2acceee2
JM
11964 /* Don't propogate error information up to the client. Instead let
11965 the client find out about the error by querying the target. */
88b496c3 11966 rs->async_client_callback (INF_REG_EVENT, rs->async_client_context);
2acceee2
JM
11967}
11968
74531fed
PA
11969static void
11970remote_async_inferior_event_handler (gdb_client_data data)
11971{
11972 inferior_event_handler (INF_REG_EVENT, NULL);
11973}
11974
2acceee2 11975static void
6a109b6b
TT
11976remote_async (struct target_ops *ops,
11977 void (*callback) (enum inferior_event_type event_type,
11978 void *context),
11979 void *context)
2acceee2 11980{
5d93a237
TT
11981 struct remote_state *rs = get_remote_state ();
11982
2acceee2
JM
11983 if (callback != NULL)
11984 {
88b496c3
TT
11985 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
11986 rs->async_client_callback = callback;
11987 rs->async_client_context = context;
b7d2e916
PA
11988
11989 /* If there are pending events in the stop reply queue tell the
11990 event loop to process them. */
11991 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
11992 mark_async_event_handler (remote_async_inferior_event_token);
2acceee2
JM
11993 }
11994 else
b7d2e916
PA
11995 {
11996 serial_async (rs->remote_desc, NULL, NULL);
11997 clear_async_event_handler (remote_async_inferior_event_token);
11998 }
6426a772
JM
11999}
12000
5a2468f5 12001static void
c2d11a7d 12002set_remote_cmd (char *args, int from_tty)
5a2468f5 12003{
635c7e8a 12004 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
12005}
12006
d471ea57
AC
12007static void
12008show_remote_cmd (char *args, int from_tty)
12009{
37a105a1 12010 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 12011 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
12012 struct cleanup *showlist_chain;
12013 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 12014 struct ui_out *uiout = current_uiout;
37a105a1
DJ
12015
12016 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
12017 for (; list != NULL; list = list->next)
12018 if (strcmp (list->name, "Z-packet") == 0)
12019 continue;
427c3a89
DJ
12020 else if (list->type == not_set_cmd)
12021 /* Alias commands are exactly like the original, except they
12022 don't have the normal type. */
12023 continue;
12024 else
37a105a1
DJ
12025 {
12026 struct cleanup *option_chain
12027 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 12028
37a105a1
DJ
12029 ui_out_field_string (uiout, "name", list->name);
12030 ui_out_text (uiout, ": ");
427c3a89 12031 if (list->type == show_cmd)
5b9afe8a 12032 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
12033 else
12034 cmd_func (list, NULL, from_tty);
37a105a1
DJ
12035 /* Close the tuple. */
12036 do_cleanups (option_chain);
12037 }
427c3a89
DJ
12038
12039 /* Close the tuple. */
12040 do_cleanups (showlist_chain);
d471ea57 12041}
5a2468f5 12042
0f71a2f6 12043
23860348 12044/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
12045static void
12046remote_new_objfile (struct objfile *objfile)
12047{
5d93a237
TT
12048 struct remote_state *rs = get_remote_state ();
12049
12050 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 12051 remote_check_symbols ();
dc8acb97
MS
12052}
12053
00bf0b85
SS
12054/* Pull all the tracepoints defined on the target and create local
12055 data structures representing them. We don't want to create real
12056 tracepoints yet, we don't want to mess up the user's existing
12057 collection. */
12058
12059static int
ab6617cc 12060remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 12061{
00bf0b85
SS
12062 struct remote_state *rs = get_remote_state ();
12063 char *p;
d5551862 12064
00bf0b85
SS
12065 /* Ask for a first packet of tracepoint definition. */
12066 putpkt ("qTfP");
12067 getpkt (&rs->buf, &rs->buf_size, 0);
12068 p = rs->buf;
12069 while (*p && *p != 'l')
d5551862 12070 {
00bf0b85
SS
12071 parse_tracepoint_definition (p, utpp);
12072 /* Ask for another packet of tracepoint definition. */
12073 putpkt ("qTsP");
12074 getpkt (&rs->buf, &rs->buf_size, 0);
12075 p = rs->buf;
d5551862 12076 }
00bf0b85 12077 return 0;
d5551862
SS
12078}
12079
00bf0b85 12080static int
181e3713
TT
12081remote_upload_trace_state_variables (struct target_ops *self,
12082 struct uploaded_tsv **utsvp)
d5551862 12083{
00bf0b85 12084 struct remote_state *rs = get_remote_state ();
d5551862 12085 char *p;
d5551862 12086
00bf0b85
SS
12087 /* Ask for a first packet of variable definition. */
12088 putpkt ("qTfV");
d5551862
SS
12089 getpkt (&rs->buf, &rs->buf_size, 0);
12090 p = rs->buf;
00bf0b85 12091 while (*p && *p != 'l')
d5551862 12092 {
00bf0b85
SS
12093 parse_tsv_definition (p, utsvp);
12094 /* Ask for another packet of variable definition. */
12095 putpkt ("qTsV");
d5551862
SS
12096 getpkt (&rs->buf, &rs->buf_size, 0);
12097 p = rs->buf;
12098 }
00bf0b85 12099 return 0;
d5551862
SS
12100}
12101
c1e36e3e
PA
12102/* The "set/show range-stepping" show hook. */
12103
12104static void
12105show_range_stepping (struct ui_file *file, int from_tty,
12106 struct cmd_list_element *c,
12107 const char *value)
12108{
12109 fprintf_filtered (file,
12110 _("Debugger's willingness to use range stepping "
12111 "is %s.\n"), value);
12112}
12113
12114/* The "set/show range-stepping" set hook. */
12115
12116static void
12117set_range_stepping (char *ignore_args, int from_tty,
12118 struct cmd_list_element *c)
12119{
5d93a237
TT
12120 struct remote_state *rs = get_remote_state ();
12121
c1e36e3e
PA
12122 /* Whene enabling, check whether range stepping is actually
12123 supported by the target, and warn if not. */
12124 if (use_range_stepping)
12125 {
5d93a237 12126 if (rs->remote_desc != NULL)
c1e36e3e 12127 {
4082afcc 12128 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
12129 remote_vcont_probe (rs);
12130
4082afcc 12131 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
12132 && rs->supports_vCont.r)
12133 return;
12134 }
12135
12136 warning (_("Range stepping is not supported by the current target"));
12137 }
12138}
12139
c906108c 12140void
fba45db2 12141_initialize_remote (void)
c906108c 12142{
ea9c271d 12143 struct remote_state *rs;
9a7071a8 12144 struct cmd_list_element *cmd;
6f937416 12145 const char *cmd_name;
ea9c271d 12146
0f71a2f6 12147 /* architecture specific data */
2bc416ba 12148 remote_gdbarch_data_handle =
23860348 12149 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
12150 remote_g_packet_data_handle =
12151 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 12152
ea9c271d
DJ
12153 /* Initialize the per-target state. At the moment there is only one
12154 of these, not one per target. Only one target is active at a
cf792862
TT
12155 time. */
12156 remote_state = new_remote_state ();
ea9c271d 12157
c906108c
SS
12158 init_remote_ops ();
12159 add_target (&remote_ops);
12160
12161 init_extended_remote_ops ();
12162 add_target (&extended_remote_ops);
cce74817 12163
dc8acb97 12164 /* Hook into new objfile notification. */
06d3b283 12165 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
12166 /* We're no longer interested in notification events of an inferior
12167 when it exits. */
12168 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 12169
b803fb0f 12170 /* Set up signal handlers. */
934b9bac 12171 async_sigint_remote_token =
b803fb0f 12172 create_async_signal_handler (async_remote_interrupt, NULL);
934b9bac 12173 async_sigint_remote_twice_token =
6d549500 12174 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 12175
c906108c
SS
12176#if 0
12177 init_remote_threadtests ();
12178#endif
12179
722247f1 12180 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 12181 /* set/show remote ... */
d471ea57 12182
1bedd215 12183 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
12184Remote protocol specific variables\n\
12185Configure various remote-protocol specific variables such as\n\
1bedd215 12186the packets being used"),
cff3e48b 12187 &remote_set_cmdlist, "set remote ",
23860348 12188 0 /* allow-unknown */, &setlist);
1bedd215 12189 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
12190Remote protocol specific variables\n\
12191Configure various remote-protocol specific variables such as\n\
1bedd215 12192the packets being used"),
cff3e48b 12193 &remote_show_cmdlist, "show remote ",
23860348 12194 0 /* allow-unknown */, &showlist);
5a2468f5 12195
1a966eab
AC
12196 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
12197Compare section data on target to the exec file.\n\
95cf3b38
DT
12198Argument is a single section name (default: all loaded sections).\n\
12199To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
12200 &cmdlist);
12201
1a966eab
AC
12202 add_cmd ("packet", class_maintenance, packet_command, _("\
12203Send an arbitrary packet to a remote target.\n\
c906108c
SS
12204 maintenance packet TEXT\n\
12205If GDB is talking to an inferior via the GDB serial protocol, then\n\
12206this command sends the string TEXT to the inferior, and displays the\n\
12207response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 12208terminating `#' character and checksum."),
c906108c
SS
12209 &maintenancelist);
12210
7915a72c
AC
12211 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
12212Set whether to send break if interrupted."), _("\
12213Show whether to send break if interrupted."), _("\
12214If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 12215 set_remotebreak, show_remotebreak,
e707bbc2 12216 &setlist, &showlist);
9a7071a8
JB
12217 cmd_name = "remotebreak";
12218 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
12219 deprecate_cmd (cmd, "set remote interrupt-sequence");
12220 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
12221 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
12222 deprecate_cmd (cmd, "show remote interrupt-sequence");
12223
12224 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
12225 interrupt_sequence_modes, &interrupt_sequence_mode,
12226 _("\
9a7071a8
JB
12227Set interrupt sequence to remote target."), _("\
12228Show interrupt sequence to remote target."), _("\
12229Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
12230 NULL, show_interrupt_sequence,
12231 &remote_set_cmdlist,
12232 &remote_show_cmdlist);
12233
12234 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
12235 &interrupt_on_connect, _("\
12236Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12237Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12238If set, interrupt sequence is sent to remote target."),
12239 NULL, NULL,
12240 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 12241
23860348 12242 /* Install commands for configuring memory read/write packets. */
11cf8741 12243
1a966eab
AC
12244 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
12245Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 12246 &setlist);
1a966eab
AC
12247 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
12248Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
12249 &showlist);
12250 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
12251 set_memory_write_packet_size, _("\
12252Set the maximum number of bytes per memory-write packet.\n\
12253Specify the number of bytes in a packet or 0 (zero) for the\n\
12254default packet size. The actual limit is further reduced\n\
12255dependent on the target. Specify ``fixed'' to disable the\n\
12256further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
12257 &remote_set_cmdlist);
12258 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
12259 set_memory_read_packet_size, _("\
12260Set the maximum number of bytes per memory-read packet.\n\
12261Specify the number of bytes in a packet or 0 (zero) for the\n\
12262default packet size. The actual limit is further reduced\n\
12263dependent on the target. Specify ``fixed'' to disable the\n\
12264further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
12265 &remote_set_cmdlist);
12266 add_cmd ("memory-write-packet-size", no_class,
12267 show_memory_write_packet_size,
1a966eab 12268 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
12269 &remote_show_cmdlist);
12270 add_cmd ("memory-read-packet-size", no_class,
12271 show_memory_read_packet_size,
1a966eab 12272 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 12273 &remote_show_cmdlist);
c906108c 12274
b3f42336 12275 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
12276 &remote_hw_watchpoint_limit, _("\
12277Set the maximum number of target hardware watchpoints."), _("\
12278Show the maximum number of target hardware watchpoints."), _("\
12279Specify a negative limit for unlimited."),
3e43a32a
MS
12280 NULL, NULL, /* FIXME: i18n: The maximum
12281 number of target hardware
12282 watchpoints is %s. */
b3f42336 12283 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
12284 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
12285 &remote_hw_watchpoint_length_limit, _("\
12286Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
12287Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
12288Specify a negative limit for unlimited."),
12289 NULL, NULL, /* FIXME: i18n: The maximum
12290 length (in bytes) of a target
12291 hardware watchpoint is %s. */
12292 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 12293 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
12294 &remote_hw_breakpoint_limit, _("\
12295Set the maximum number of target hardware breakpoints."), _("\
12296Show the maximum number of target hardware breakpoints."), _("\
12297Specify a negative limit for unlimited."),
3e43a32a
MS
12298 NULL, NULL, /* FIXME: i18n: The maximum
12299 number of target hardware
12300 breakpoints is %s. */
b3f42336 12301 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 12302
1b493192
PA
12303 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
12304 &remote_address_size, _("\
4d28ad1e
AC
12305Set the maximum size of the address (in bits) in a memory packet."), _("\
12306Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
12307 NULL,
12308 NULL, /* FIXME: i18n: */
12309 &setlist, &showlist);
c906108c 12310
ca4f7f8b
PA
12311 init_all_packet_configs ();
12312
444abaca 12313 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 12314 "X", "binary-download", 1);
0f71a2f6 12315
444abaca 12316 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 12317 "vCont", "verbose-resume", 0);
506fb367 12318
89be2091
DJ
12319 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
12320 "QPassSignals", "pass-signals", 0);
12321
9b224c5e
PA
12322 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
12323 "QProgramSignals", "program-signals", 0);
12324
444abaca 12325 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 12326 "qSymbol", "symbol-lookup", 0);
dc8acb97 12327
444abaca 12328 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 12329 "P", "set-register", 1);
d471ea57 12330
444abaca 12331 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 12332 "p", "fetch-register", 1);
b96ec7ac 12333
444abaca 12334 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 12335 "Z0", "software-breakpoint", 0);
d471ea57 12336
444abaca 12337 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 12338 "Z1", "hardware-breakpoint", 0);
d471ea57 12339
444abaca 12340 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 12341 "Z2", "write-watchpoint", 0);
d471ea57 12342
444abaca 12343 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 12344 "Z3", "read-watchpoint", 0);
d471ea57 12345
444abaca 12346 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 12347 "Z4", "access-watchpoint", 0);
d471ea57 12348
0876f84a
DJ
12349 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
12350 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 12351
23181151
DJ
12352 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
12353 "qXfer:features:read", "target-features", 0);
12354
cfa9d6d9
DJ
12355 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
12356 "qXfer:libraries:read", "library-info", 0);
12357
2268b414
JK
12358 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12359 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12360
fd79ecee
DJ
12361 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12362 "qXfer:memory-map:read", "memory-map", 0);
12363
0e7f50da
UW
12364 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12365 "qXfer:spu:read", "read-spu-object", 0);
12366
12367 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12368 "qXfer:spu:write", "write-spu-object", 0);
12369
07e059b5
VP
12370 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12371 "qXfer:osdata:read", "osdata", 0);
12372
dc146f7c
VP
12373 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12374 "qXfer:threads:read", "threads", 0);
12375
4aa995e1
PA
12376 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12377 "qXfer:siginfo:read", "read-siginfo-object", 0);
12378
12379 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12380 "qXfer:siginfo:write", "write-siginfo-object", 0);
12381
b3b9301e
PA
12382 add_packet_config_cmd
12383 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 12384 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 12385
169081d0
TG
12386 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12387 "qXfer:uib:read", "unwind-info-block", 0);
12388
444abaca 12389 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 12390 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
12391 0);
12392
711e434b
PM
12393 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12394 "qGetTIBAddr", "get-thread-information-block-address",
12395 0);
12396
40ab02ce
MS
12397 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12398 "bc", "reverse-continue", 0);
12399
12400 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12401 "bs", "reverse-step", 0);
12402
be2a5f71
DJ
12403 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12404 "qSupported", "supported-packets", 0);
12405
08388c79
DE
12406 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12407 "qSearch:memory", "search-memory", 0);
12408
bd3eecc3
PA
12409 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12410 "qTStatus", "trace-status", 0);
12411
a6b151f1
DJ
12412 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12413 "vFile:open", "hostio-open", 0);
12414
12415 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12416 "vFile:pread", "hostio-pread", 0);
12417
12418 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12419 "vFile:pwrite", "hostio-pwrite", 0);
12420
12421 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12422 "vFile:close", "hostio-close", 0);
12423
12424 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12425 "vFile:unlink", "hostio-unlink", 0);
12426
b9e7b9c3
UW
12427 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12428 "vFile:readlink", "hostio-readlink", 0);
12429
0a93529c
GB
12430 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
12431 "vFile:fstat", "hostio-fstat", 0);
12432
2d717e4f
DJ
12433 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12434 "vAttach", "attach", 0);
12435
12436 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12437 "vRun", "run", 0);
12438
a6f3e723
SL
12439 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12440 "QStartNoAckMode", "noack", 0);
12441
82f73884
PA
12442 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12443 "vKill", "kill", 0);
12444
0b16c5cf
PA
12445 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12446 "qAttached", "query-attached", 0);
12447
782b2b07 12448 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
12449 "ConditionalTracepoints",
12450 "conditional-tracepoints", 0);
3788aec7
LM
12451
12452 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12453 "ConditionalBreakpoints",
12454 "conditional-breakpoints", 0);
12455
d3ce09f5
SS
12456 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12457 "BreakpointCommands",
12458 "breakpoint-commands", 0);
12459
7a697b8d
SS
12460 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12461 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 12462
409873ef
SS
12463 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12464 "TracepointSource", "TracepointSource", 0);
12465
d914c394
SS
12466 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12467 "QAllow", "allow", 0);
12468
0fb4aa4b
PA
12469 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12470 "StaticTracepoints", "static-tracepoints", 0);
12471
1e4d1764
YQ
12472 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12473 "InstallInTrace", "install-in-trace", 0);
12474
0fb4aa4b
PA
12475 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12476 "qXfer:statictrace:read", "read-sdata-object", 0);
12477
78d85199
YQ
12478 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12479 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12480
03583c20
UW
12481 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12482 "QDisableRandomization", "disable-randomization", 0);
12483
d1feda86
YQ
12484 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12485 "QAgent", "agent", 0);
12486
f6f899bf
HAQ
12487 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12488 "QTBuffer:size", "trace-buffer-size", 0);
12489
9accd112
MM
12490 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12491 "Qbtrace:off", "disable-btrace", 0);
12492
12493 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12494 "Qbtrace:bts", "enable-btrace", 0);
12495
12496 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12497 "qXfer:btrace", "read-btrace", 0);
12498
f4abbc16
MM
12499 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
12500 "qXfer:btrace-conf", "read-btrace-conf", 0);
12501
d33501a5
MM
12502 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
12503 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
12504
f7e6eed5
PA
12505 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
12506 "swbreak-feature", "swbreak-feature", 0);
12507
12508 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
12509 "hwbreak-feature", "hwbreak-feature", 0);
12510
ca4f7f8b
PA
12511 /* Assert that we've registered commands for all packet configs. */
12512 {
12513 int i;
12514
12515 for (i = 0; i < PACKET_MAX; i++)
12516 {
12517 /* Ideally all configs would have a command associated. Some
12518 still don't though. */
12519 int excepted;
12520
12521 switch (i)
12522 {
12523 case PACKET_QNonStop:
12524 case PACKET_multiprocess_feature:
12525 case PACKET_EnableDisableTracepoints_feature:
12526 case PACKET_tracenz_feature:
12527 case PACKET_DisconnectedTracing_feature:
12528 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
12529 case PACKET_qCRC:
12530 /* Additions to this list need to be well justified:
12531 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
12532 excepted = 1;
12533 break;
12534 default:
12535 excepted = 0;
12536 break;
12537 }
12538
12539 /* This catches both forgetting to add a config command, and
12540 forgetting to remove a packet from the exception list. */
12541 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
12542 }
12543 }
12544
37a105a1
DJ
12545 /* Keep the old ``set remote Z-packet ...'' working. Each individual
12546 Z sub-packet has its own set and show commands, but users may
12547 have sets to this variable in their .gdbinit files (or in their
12548 documentation). */
e9e68a56 12549 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
12550 &remote_Z_packet_detect, _("\
12551Set use of remote protocol `Z' packets"), _("\
12552Show use of remote protocol `Z' packets "), _("\
3b64bf98 12553When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 12554packets."),
e9e68a56 12555 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
12556 show_remote_protocol_Z_packet_cmd,
12557 /* FIXME: i18n: Use of remote protocol
12558 `Z' packets is %s. */
e9e68a56 12559 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 12560
a6b151f1
DJ
12561 add_prefix_cmd ("remote", class_files, remote_command, _("\
12562Manipulate files on the remote system\n\
12563Transfer files to and from the remote target system."),
12564 &remote_cmdlist, "remote ",
12565 0 /* allow-unknown */, &cmdlist);
12566
12567 add_cmd ("put", class_files, remote_put_command,
12568 _("Copy a local file to the remote system."),
12569 &remote_cmdlist);
12570
12571 add_cmd ("get", class_files, remote_get_command,
12572 _("Copy a remote file to the local system."),
12573 &remote_cmdlist);
12574
12575 add_cmd ("delete", class_files, remote_delete_command,
12576 _("Delete a remote file."),
12577 &remote_cmdlist);
12578
2d717e4f
DJ
12579 remote_exec_file = xstrdup ("");
12580 add_setshow_string_noescape_cmd ("exec-file", class_files,
12581 &remote_exec_file, _("\
12582Set the remote pathname for \"run\""), _("\
12583Show the remote pathname for \"run\""), NULL, NULL, NULL,
12584 &remote_set_cmdlist, &remote_show_cmdlist);
12585
c1e36e3e
PA
12586 add_setshow_boolean_cmd ("range-stepping", class_run,
12587 &use_range_stepping, _("\
12588Enable or disable range stepping."), _("\
12589Show whether target-assisted range stepping is enabled."), _("\
12590If on, and the target supports it, when stepping a source line, GDB\n\
12591tells the target to step the corresponding range of addresses itself instead\n\
12592of issuing multiple single-steps. This speeds up source level\n\
12593stepping. If off, GDB always issues single-steps, even if range\n\
12594stepping is supported by the target. The default is on."),
12595 set_range_stepping,
12596 show_range_stepping,
12597 &setlist,
12598 &showlist);
12599
449092f6
CV
12600 /* Eventually initialize fileio. See fileio.c */
12601 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 12602
ba348170 12603 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 12604 special ptids with it set to != 0. */
ba348170
PA
12605 magic_null_ptid = ptid_build (42000, -1, 1);
12606 not_sent_ptid = ptid_build (42000, -2, 1);
12607 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
12608
12609 target_buf_size = 2048;
12610 target_buf = xmalloc (target_buf_size);
c906108c 12611}
10760264 12612
This page took 2.982154 seconds and 4 git commands to generate.