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