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