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