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