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