Mark pieces of values as unavailable if the corresponding memory
[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;
458 pp = unpack_varlen_hex (p, &ul);
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
0b16c5cf
PA
1356/* Find out if the stub attached to PID (and hence GDB should offer to
1357 detach instead of killing it when bailing out). */
1358
1359static int
1360remote_query_attached (int pid)
1361{
1362 struct remote_state *rs = get_remote_state ();
1363
1364 if (remote_protocol_packets[PACKET_qAttached].support == PACKET_DISABLE)
1365 return 0;
1366
1367 if (remote_multi_process_p (rs))
1368 sprintf (rs->buf, "qAttached:%x", pid);
1369 else
1370 sprintf (rs->buf, "qAttached");
1371
1372 putpkt (rs->buf);
1373 getpkt (&rs->buf, &rs->buf_size, 0);
1374
1375 switch (packet_ok (rs->buf,
1554e9be 1376 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1377 {
1378 case PACKET_OK:
1379 if (strcmp (rs->buf, "1") == 0)
1380 return 1;
1381 break;
1382 case PACKET_ERROR:
1383 warning (_("Remote failure reply: %s"), rs->buf);
1384 break;
1385 case PACKET_UNKNOWN:
1386 break;
1387 }
1388
1389 return 0;
1390}
1391
1941c569
PA
1392/* Add PID to GDB's inferior table. Since we can be connected to a
1393 remote system before before knowing about any inferior, mark the
0b16c5cf
PA
1394 target with execution when we find the first inferior. If ATTACHED
1395 is 1, then we had just attached to this inferior. If it is 0, then
1396 we just created this inferior. If it is -1, then try querying the
1397 remote stub to find out if it had attached to the inferior or
1398 not. */
1941c569
PA
1399
1400static struct inferior *
0b16c5cf 1401remote_add_inferior (int pid, int attached)
1941c569 1402{
1941c569
PA
1403 struct inferior *inf;
1404
0b16c5cf
PA
1405 /* Check whether this process we're learning about is to be
1406 considered attached, or if is to be considered to have been
1407 spawned by the stub. */
1408 if (attached == -1)
1409 attached = remote_query_attached (pid);
1410
6c95b8df
PA
1411 if (gdbarch_has_global_solist (target_gdbarch))
1412 {
1413 /* If the target shares code across all inferiors, then every
1414 attach adds a new inferior. */
1415 inf = add_inferior (pid);
1416
1417 /* ... and every inferior is bound to the same program space.
1418 However, each inferior may still have its own address
1419 space. */
1420 inf->aspace = maybe_new_address_space ();
1421 inf->pspace = current_program_space;
1422 }
1423 else
1424 {
1425 /* In the traditional debugging scenario, there's a 1-1 match
1426 between program/address spaces. We simply bind the inferior
1427 to the program space's address space. */
1428 inf = current_inferior ();
1429 inferior_appeared (inf, pid);
1430 }
1941c569 1431
0b16c5cf
PA
1432 inf->attach_flag = attached;
1433
1941c569
PA
1434 return inf;
1435}
1436
1437/* Add thread PTID to GDB's thread list. Tag it as executing/running
1438 according to RUNNING. */
1439
c906108c 1440static void
1941c569 1441remote_add_thread (ptid_t ptid, int running)
c906108c 1442{
1941c569
PA
1443 add_thread (ptid);
1444
1445 set_executing (ptid, running);
1446 set_running (ptid, running);
1447}
1448
1449/* Come here when we learn about a thread id from the remote target.
1450 It may be the first time we hear about such thread, so take the
1451 opportunity to add it to GDB's thread list. In case this is the
1452 first time we're noticing its corresponding inferior, add it to
1453 GDB's inferior list as well. */
1454
1455static void
1456remote_notice_new_inferior (ptid_t currthread, int running)
1457{
c906108c
SS
1458 /* If this is a new thread, add it to GDB's thread list.
1459 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1460
1461 if (in_thread_list (currthread) && is_exited (currthread))
1462 {
1463 /* We're seeing an event on a thread id we knew had exited.
1464 This has to be a new thread reusing the old id. Add it. */
1941c569 1465 remote_add_thread (currthread, running);
82f73884
PA
1466 return;
1467 }
1468
79d7f229 1469 if (!in_thread_list (currthread))
c0a2216e 1470 {
1941c569 1471 struct inferior *inf = NULL;
bad34192 1472 int pid = ptid_get_pid (currthread);
1941c569 1473
bad34192
PA
1474 if (ptid_is_pid (inferior_ptid)
1475 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1476 {
1477 /* inferior_ptid has no thread member yet. This can happen
1478 with the vAttach -> remote_wait,"TAAthread:" path if the
1479 stub doesn't support qC. This is the first stop reported
1480 after an attach, so this is the main thread. Update the
1481 ptid in the thread list. */
bad34192
PA
1482 if (in_thread_list (pid_to_ptid (pid)))
1483 thread_change_ptid (inferior_ptid, currthread);
1484 else
1485 {
1486 remote_add_thread (currthread, running);
1487 inferior_ptid = currthread;
1488 }
dc146f7c 1489 return;
c0a2216e 1490 }
82f73884
PA
1491
1492 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1493 {
1494 /* inferior_ptid is not set yet. This can happen with the
1495 vRun -> remote_wait,"TAAthread:" path if the stub
1496 doesn't support qC. This is the first stop reported
1497 after an attach, so this is the main thread. Update the
1498 ptid in the thread list. */
dc146f7c 1499 thread_change_ptid (inferior_ptid, currthread);
82f73884 1500 return;
c0a2216e 1501 }
82f73884 1502
29c87f7f
PA
1503 /* When connecting to a target remote, or to a target
1504 extended-remote which already was debugging an inferior, we
1505 may not know about it yet. Add it before adding its child
1506 thread, so notifications are emitted in a sensible order. */
1507 if (!in_inferior_list (ptid_get_pid (currthread)))
0b16c5cf 1508 inf = remote_add_inferior (ptid_get_pid (currthread), -1);
29c87f7f 1509
82f73884 1510 /* This is really a new thread. Add it. */
1941c569
PA
1511 remote_add_thread (currthread, running);
1512
1513 /* If we found a new inferior, let the common code do whatever
1514 it needs to with it (e.g., read shared libraries, insert
1515 breakpoints). */
1516 if (inf != NULL)
1517 notice_new_inferior (currthread, running, 0);
c0a2216e 1518 }
c906108c
SS
1519}
1520
dc146f7c
VP
1521/* Return the private thread data, creating it if necessary. */
1522
1523struct private_thread_info *
1524demand_private_info (ptid_t ptid)
1525{
1526 struct thread_info *info = find_thread_ptid (ptid);
1527
1528 gdb_assert (info);
1529
1530 if (!info->private)
1531 {
1532 info->private = xmalloc (sizeof (*(info->private)));
1533 info->private_dtor = free_private_thread_info;
1534 info->private->core = -1;
1535 info->private->extra = 0;
1536 }
1537
1538 return info->private;
1539}
1540
74531fed
PA
1541/* Call this function as a result of
1542 1) A halt indication (T packet) containing a thread id
1543 2) A direct query of currthread
0df8b418 1544 3) Successful execution of set thread */
74531fed
PA
1545
1546static void
1547record_currthread (ptid_t currthread)
1548{
1549 general_thread = currthread;
74531fed
PA
1550}
1551
89be2091
DJ
1552static char *last_pass_packet;
1553
1554/* If 'QPassSignals' is supported, tell the remote stub what signals
1555 it can simply pass through to the inferior without reporting. */
1556
1557static void
1558remote_pass_signals (void)
1559{
1560 if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1561 {
1562 char *pass_packet, *p;
1563 int numsigs = (int) TARGET_SIGNAL_LAST;
1564 int count = 0, i;
1565
1566 gdb_assert (numsigs < 256);
1567 for (i = 0; i < numsigs; i++)
1568 {
1569 if (signal_stop_state (i) == 0
1570 && signal_print_state (i) == 0
1571 && signal_pass_state (i) == 1)
1572 count++;
1573 }
1574 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1575 strcpy (pass_packet, "QPassSignals:");
1576 p = pass_packet + strlen (pass_packet);
1577 for (i = 0; i < numsigs; i++)
1578 {
1579 if (signal_stop_state (i) == 0
1580 && signal_print_state (i) == 0
1581 && signal_pass_state (i) == 1)
1582 {
1583 if (i >= 16)
1584 *p++ = tohex (i >> 4);
1585 *p++ = tohex (i & 15);
1586 if (count)
1587 *p++ = ';';
1588 else
1589 break;
1590 count--;
1591 }
1592 }
1593 *p = 0;
1594 if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
1595 {
1596 struct remote_state *rs = get_remote_state ();
1597 char *buf = rs->buf;
1598
1599 putpkt (pass_packet);
1600 getpkt (&rs->buf, &rs->buf_size, 0);
1601 packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1602 if (last_pass_packet)
1603 xfree (last_pass_packet);
1604 last_pass_packet = pass_packet;
1605 }
1606 else
1607 xfree (pass_packet);
1608 }
1609}
1610
f0223081
PA
1611static void
1612remote_notice_signals (ptid_t ptid)
1613{
1614 /* Update the remote on signals to silently pass, if they've
1615 changed. */
1616 remote_pass_signals ();
1617}
1618
79d7f229
PA
1619/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1620 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1621 thread. If GEN is set, set the general thread, if not, then set
1622 the step/continue thread. */
c906108c 1623static void
79d7f229 1624set_thread (struct ptid ptid, int gen)
c906108c 1625{
d01949b6 1626 struct remote_state *rs = get_remote_state ();
79d7f229 1627 ptid_t state = gen ? general_thread : continue_thread;
6d820c5c 1628 char *buf = rs->buf;
79d7f229 1629 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 1630
79d7f229 1631 if (ptid_equal (state, ptid))
c906108c
SS
1632 return;
1633
79d7f229
PA
1634 *buf++ = 'H';
1635 *buf++ = gen ? 'g' : 'c';
1636 if (ptid_equal (ptid, magic_null_ptid))
1637 xsnprintf (buf, endbuf - buf, "0");
1638 else if (ptid_equal (ptid, any_thread_ptid))
1639 xsnprintf (buf, endbuf - buf, "0");
1640 else if (ptid_equal (ptid, minus_one_ptid))
1641 xsnprintf (buf, endbuf - buf, "-1");
1642 else
82f73884 1643 write_ptid (buf, endbuf, ptid);
79d7f229 1644 putpkt (rs->buf);
6d820c5c 1645 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 1646 if (gen)
79d7f229 1647 general_thread = ptid;
c906108c 1648 else
79d7f229 1649 continue_thread = ptid;
c906108c 1650}
79d7f229
PA
1651
1652static void
1653set_general_thread (struct ptid ptid)
1654{
1655 set_thread (ptid, 1);
1656}
1657
1658static void
1659set_continue_thread (struct ptid ptid)
1660{
1661 set_thread (ptid, 0);
1662}
1663
3c9c4b83
PA
1664/* Change the remote current process. Which thread within the process
1665 ends up selected isn't important, as long as it is the same process
1666 as what INFERIOR_PTID points to.
1667
1668 This comes from that fact that there is no explicit notion of
1669 "selected process" in the protocol. The selected process for
1670 general operations is the process the selected general thread
1671 belongs to. */
1672
1673static void
1674set_general_process (void)
1675{
1676 struct remote_state *rs = get_remote_state ();
1677
1678 /* If the remote can't handle multiple processes, don't bother. */
1679 if (!remote_multi_process_p (rs))
1680 return;
1681
1682 /* We only need to change the remote current thread if it's pointing
1683 at some other process. */
1684 if (ptid_get_pid (general_thread) != ptid_get_pid (inferior_ptid))
1685 set_general_thread (inferior_ptid);
1686}
1687
c906108c 1688\f
79d7f229
PA
1689/* Return nonzero if the thread PTID is still alive on the remote
1690 system. */
c906108c
SS
1691
1692static int
28439f5e 1693remote_thread_alive (struct target_ops *ops, ptid_t ptid)
c906108c 1694{
6d820c5c 1695 struct remote_state *rs = get_remote_state ();
82f73884 1696 char *p, *endp;
c906108c 1697
c0a2216e
PA
1698 if (ptid_equal (ptid, magic_null_ptid))
1699 /* The main thread is always alive. */
1700 return 1;
1701
1702 if (ptid_get_pid (ptid) != 0 && ptid_get_tid (ptid) == 0)
1703 /* The main thread is always alive. This can happen after a
1704 vAttach, if the remote side doesn't support
1705 multi-threading. */
1706 return 1;
1707
82f73884
PA
1708 p = rs->buf;
1709 endp = rs->buf + get_remote_packet_size ();
1710
1711 *p++ = 'T';
1712 write_ptid (p, endp, ptid);
1713
2e9f7625 1714 putpkt (rs->buf);
6d820c5c 1715 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 1716 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
1717}
1718
1719/* About these extended threadlist and threadinfo packets. They are
1720 variable length packets but, the fields within them are often fixed
1721 length. They are redundent enough to send over UDP as is the
1722 remote protocol in general. There is a matching unit test module
1723 in libstub. */
1724
cce74817
JM
1725#define OPAQUETHREADBYTES 8
1726
1727/* a 64 bit opaque identifier */
1728typedef unsigned char threadref[OPAQUETHREADBYTES];
1729
23860348 1730/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 1731 libstub protocol encoding, and remote.c. It is not particularly
23860348 1732 changable. */
cce74817
JM
1733
1734/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 1735 Plan to fix this. */
cce74817 1736
23860348 1737typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 1738
9d1f7ab2 1739/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 1740 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
1741
1742struct gdb_ext_thread_info
c5aa993b 1743 {
23860348 1744 threadref threadid; /* External form of thread reference. */
2bc416ba 1745 int active; /* Has state interesting to GDB?
23860348 1746 regs, stack. */
2bc416ba 1747 char display[256]; /* Brief state display, name,
cedea757 1748 blocked/suspended. */
23860348 1749 char shortname[32]; /* To be used to name threads. */
2bc416ba 1750 char more_display[256]; /* Long info, statistics, queue depth,
23860348 1751 whatever. */
c5aa993b 1752 };
cce74817
JM
1753
1754/* The volume of remote transfers can be limited by submitting
1755 a mask containing bits specifying the desired information.
1756 Use a union of these values as the 'selection' parameter to
0df8b418 1757 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
1758
1759#define TAG_THREADID 1
1760#define TAG_EXISTS 2
1761#define TAG_DISPLAY 4
1762#define TAG_THREADNAME 8
c5aa993b 1763#define TAG_MOREDISPLAY 16
cce74817 1764
23860348 1765#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 1766
b2dd6311 1767char *unpack_varlen_hex (char *buff, ULONGEST *result);
cce74817 1768
a14ed312 1769static char *unpack_nibble (char *buf, int *val);
cce74817 1770
a14ed312 1771static char *pack_nibble (char *buf, int nibble);
cce74817 1772
23860348 1773static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
cce74817 1774
a14ed312 1775static char *unpack_byte (char *buf, int *value);
cce74817 1776
a14ed312 1777static char *pack_int (char *buf, int value);
cce74817 1778
a14ed312 1779static char *unpack_int (char *buf, int *value);
cce74817 1780
a14ed312 1781static char *unpack_string (char *src, char *dest, int length);
cce74817 1782
23860348 1783static char *pack_threadid (char *pkt, threadref *id);
cce74817 1784
23860348 1785static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 1786
23860348 1787void int_to_threadref (threadref *id, int value);
cce74817 1788
23860348 1789static int threadref_to_int (threadref *ref);
cce74817 1790
23860348 1791static void copy_threadref (threadref *dest, threadref *src);
cce74817 1792
23860348 1793static int threadmatch (threadref *dest, threadref *src);
cce74817 1794
2bc416ba 1795static char *pack_threadinfo_request (char *pkt, int mode,
23860348 1796 threadref *id);
cce74817 1797
a14ed312 1798static int remote_unpack_thread_info_response (char *pkt,
23860348 1799 threadref *expectedref,
a14ed312
KB
1800 struct gdb_ext_thread_info
1801 *info);
cce74817
JM
1802
1803
2bc416ba 1804static int remote_get_threadinfo (threadref *threadid,
23860348 1805 int fieldset, /*TAG mask */
a14ed312 1806 struct gdb_ext_thread_info *info);
cce74817 1807
a14ed312
KB
1808static char *pack_threadlist_request (char *pkt, int startflag,
1809 int threadcount,
23860348 1810 threadref *nextthread);
cce74817 1811
a14ed312
KB
1812static int parse_threadlist_response (char *pkt,
1813 int result_limit,
23860348 1814 threadref *original_echo,
2bc416ba 1815 threadref *resultlist,
23860348 1816 int *doneflag);
cce74817 1817
a14ed312 1818static int remote_get_threadlist (int startflag,
23860348 1819 threadref *nextthread,
a14ed312
KB
1820 int result_limit,
1821 int *done,
2bc416ba 1822 int *result_count,
23860348 1823 threadref *threadlist);
cce74817 1824
23860348 1825typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 1826
a14ed312
KB
1827static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1828 void *context, int looplimit);
cce74817 1829
23860348 1830static int remote_newthread_step (threadref *ref, void *context);
cce74817 1831
82f73884
PA
1832
1833/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
1834 buffer we're allowed to write to. Returns
1835 BUF+CHARACTERS_WRITTEN. */
1836
1837static char *
1838write_ptid (char *buf, const char *endbuf, ptid_t ptid)
1839{
1840 int pid, tid;
1841 struct remote_state *rs = get_remote_state ();
1842
1843 if (remote_multi_process_p (rs))
1844 {
1845 pid = ptid_get_pid (ptid);
1846 if (pid < 0)
1847 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
1848 else
1849 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
1850 }
1851 tid = ptid_get_tid (ptid);
1852 if (tid < 0)
1853 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
1854 else
1855 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
1856
1857 return buf;
1858}
1859
1860/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
1861 passed the last parsed char. Returns null_ptid on error. */
1862
1863static ptid_t
1864read_ptid (char *buf, char **obuf)
1865{
1866 char *p = buf;
1867 char *pp;
1868 ULONGEST pid = 0, tid = 0;
82f73884
PA
1869
1870 if (*p == 'p')
1871 {
1872 /* Multi-process ptid. */
1873 pp = unpack_varlen_hex (p + 1, &pid);
1874 if (*pp != '.')
1875 error (_("invalid remote ptid: %s\n"), p);
1876
1877 p = pp;
1878 pp = unpack_varlen_hex (p + 1, &tid);
1879 if (obuf)
1880 *obuf = pp;
1881 return ptid_build (pid, 0, tid);
1882 }
1883
1884 /* No multi-process. Just a tid. */
1885 pp = unpack_varlen_hex (p, &tid);
1886
1887 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
1888 what's in inferior_ptid, unless it's null at this point. If so,
1889 then since there's no way to know the pid of the reported
1890 threads, use the magic number. */
1891 if (ptid_equal (inferior_ptid, null_ptid))
1892 pid = ptid_get_pid (magic_null_ptid);
1893 else
1894 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
1895
1896 if (obuf)
1897 *obuf = pp;
1898 return ptid_build (pid, 0, tid);
1899}
1900
23860348 1901/* Encode 64 bits in 16 chars of hex. */
c906108c
SS
1902
1903static const char hexchars[] = "0123456789abcdef";
1904
1905static int
fba45db2 1906ishex (int ch, int *val)
c906108c
SS
1907{
1908 if ((ch >= 'a') && (ch <= 'f'))
1909 {
1910 *val = ch - 'a' + 10;
1911 return 1;
1912 }
1913 if ((ch >= 'A') && (ch <= 'F'))
1914 {
1915 *val = ch - 'A' + 10;
1916 return 1;
1917 }
1918 if ((ch >= '0') && (ch <= '9'))
1919 {
1920 *val = ch - '0';
1921 return 1;
1922 }
1923 return 0;
1924}
1925
1926static int
fba45db2 1927stubhex (int ch)
c906108c
SS
1928{
1929 if (ch >= 'a' && ch <= 'f')
1930 return ch - 'a' + 10;
1931 if (ch >= '0' && ch <= '9')
1932 return ch - '0';
1933 if (ch >= 'A' && ch <= 'F')
1934 return ch - 'A' + 10;
1935 return -1;
1936}
1937
1938static int
fba45db2 1939stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
1940{
1941 int nibble;
1942 int retval = 0;
1943
1944 while (fieldlength)
1945 {
1946 nibble = stubhex (*buff++);
1947 retval |= nibble;
1948 fieldlength--;
1949 if (fieldlength)
1950 retval = retval << 4;
1951 }
1952 return retval;
1953}
1954
1955char *
fba45db2 1956unpack_varlen_hex (char *buff, /* packet to parse */
b2dd6311 1957 ULONGEST *result)
c906108c
SS
1958{
1959 int nibble;
d49c44d5 1960 ULONGEST retval = 0;
c906108c
SS
1961
1962 while (ishex (*buff, &nibble))
1963 {
1964 buff++;
1965 retval = retval << 4;
1966 retval |= nibble & 0x0f;
1967 }
1968 *result = retval;
1969 return buff;
1970}
1971
1972static char *
fba45db2 1973unpack_nibble (char *buf, int *val)
c906108c 1974{
b7589f7d 1975 *val = fromhex (*buf++);
c906108c
SS
1976 return buf;
1977}
1978
1979static char *
fba45db2 1980pack_nibble (char *buf, int nibble)
c906108c
SS
1981{
1982 *buf++ = hexchars[(nibble & 0x0f)];
1983 return buf;
1984}
1985
1986static char *
fba45db2 1987pack_hex_byte (char *pkt, int byte)
c906108c
SS
1988{
1989 *pkt++ = hexchars[(byte >> 4) & 0xf];
1990 *pkt++ = hexchars[(byte & 0xf)];
1991 return pkt;
1992}
1993
1994static char *
fba45db2 1995unpack_byte (char *buf, int *value)
c906108c
SS
1996{
1997 *value = stub_unpack_int (buf, 2);
1998 return buf + 2;
1999}
2000
2001static char *
fba45db2 2002pack_int (char *buf, int value)
c906108c
SS
2003{
2004 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2005 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2006 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2007 buf = pack_hex_byte (buf, (value & 0xff));
2008 return buf;
2009}
2010
2011static char *
fba45db2 2012unpack_int (char *buf, int *value)
c906108c
SS
2013{
2014 *value = stub_unpack_int (buf, 8);
2015 return buf + 8;
2016}
2017
23860348 2018#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2019static char *pack_string (char *pkt, char *string);
c906108c
SS
2020
2021static char *
fba45db2 2022pack_string (char *pkt, char *string)
c906108c
SS
2023{
2024 char ch;
2025 int len;
2026
2027 len = strlen (string);
2028 if (len > 200)
23860348 2029 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2030 pkt = pack_hex_byte (pkt, len);
2031 while (len-- > 0)
2032 {
2033 ch = *string++;
2034 if ((ch == '\0') || (ch == '#'))
23860348 2035 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2036 *pkt++ = ch;
2037 }
2038 return pkt;
2039}
2040#endif /* 0 (unused) */
2041
2042static char *
fba45db2 2043unpack_string (char *src, char *dest, int length)
c906108c
SS
2044{
2045 while (length--)
2046 *dest++ = *src++;
2047 *dest = '\0';
2048 return src;
2049}
2050
2051static char *
fba45db2 2052pack_threadid (char *pkt, threadref *id)
c906108c
SS
2053{
2054 char *limit;
2055 unsigned char *altid;
2056
2057 altid = (unsigned char *) id;
2058 limit = pkt + BUF_THREAD_ID_SIZE;
2059 while (pkt < limit)
2060 pkt = pack_hex_byte (pkt, *altid++);
2061 return pkt;
2062}
2063
2064
2065static char *
fba45db2 2066unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2067{
2068 char *altref;
2069 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2070 int x, y;
2071
2072 altref = (char *) id;
2073
2074 while (inbuf < limit)
2075 {
2076 x = stubhex (*inbuf++);
2077 y = stubhex (*inbuf++);
2078 *altref++ = (x << 4) | y;
2079 }
2080 return inbuf;
2081}
2082
2083/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2084 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2085 to use 64bit thread references internally. This is an adapter
2086 function. */
2087
2088void
fba45db2 2089int_to_threadref (threadref *id, int value)
c906108c
SS
2090{
2091 unsigned char *scan;
2092
2093 scan = (unsigned char *) id;
2094 {
2095 int i = 4;
2096 while (i--)
2097 *scan++ = 0;
2098 }
2099 *scan++ = (value >> 24) & 0xff;
2100 *scan++ = (value >> 16) & 0xff;
2101 *scan++ = (value >> 8) & 0xff;
2102 *scan++ = (value & 0xff);
2103}
2104
2105static int
fba45db2 2106threadref_to_int (threadref *ref)
c906108c
SS
2107{
2108 int i, value = 0;
2109 unsigned char *scan;
2110
cfd77fa1 2111 scan = *ref;
c906108c
SS
2112 scan += 4;
2113 i = 4;
2114 while (i-- > 0)
2115 value = (value << 8) | ((*scan++) & 0xff);
2116 return value;
2117}
2118
2119static void
fba45db2 2120copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2121{
2122 int i;
2123 unsigned char *csrc, *cdest;
2124
2125 csrc = (unsigned char *) src;
2126 cdest = (unsigned char *) dest;
2127 i = 8;
2128 while (i--)
2129 *cdest++ = *csrc++;
2130}
2131
2132static int
fba45db2 2133threadmatch (threadref *dest, threadref *src)
c906108c 2134{
23860348 2135 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2136#if 0
2137 unsigned char *srcp, *destp;
2138 int i, result;
2139 srcp = (char *) src;
2140 destp = (char *) dest;
2141
2142 result = 1;
2143 while (i-- > 0)
2144 result &= (*srcp++ == *destp++) ? 1 : 0;
2145 return result;
2146#endif
2147 return 1;
2148}
2149
2150/*
c5aa993b
JM
2151 threadid:1, # always request threadid
2152 context_exists:2,
2153 display:4,
2154 unique_name:8,
2155 more_display:16
2156 */
c906108c
SS
2157
2158/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2159
2160static char *
fba45db2 2161pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2162{
23860348
MS
2163 *pkt++ = 'q'; /* Info Query */
2164 *pkt++ = 'P'; /* process or thread info */
2165 pkt = pack_int (pkt, mode); /* mode */
c906108c 2166 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2167 *pkt = '\0'; /* terminate */
c906108c
SS
2168 return pkt;
2169}
2170
23860348 2171/* These values tag the fields in a thread info response packet. */
c906108c 2172/* Tagging the fields allows us to request specific fields and to
23860348 2173 add more fields as time goes by. */
c906108c 2174
23860348 2175#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2176#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2177 fetch registers and its stack? */
c5aa993b 2178#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2179#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2180#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2181 the process. */
c906108c
SS
2182
2183static int
fba45db2
KB
2184remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2185 struct gdb_ext_thread_info *info)
c906108c 2186{
d01949b6 2187 struct remote_state *rs = get_remote_state ();
c906108c 2188 int mask, length;
cfd77fa1 2189 int tag;
c906108c 2190 threadref ref;
6d820c5c 2191 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2192 int retval = 1;
2193
23860348 2194 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2195 info->active = 0;
2196 info->display[0] = '\0';
2197 info->shortname[0] = '\0';
2198 info->more_display[0] = '\0';
2199
23860348
MS
2200 /* Assume the characters indicating the packet type have been
2201 stripped. */
c906108c
SS
2202 pkt = unpack_int (pkt, &mask); /* arg mask */
2203 pkt = unpack_threadid (pkt, &ref);
2204
2205 if (mask == 0)
8a3fe4f8 2206 warning (_("Incomplete response to threadinfo request."));
c906108c 2207 if (!threadmatch (&ref, expectedref))
23860348 2208 { /* This is an answer to a different request. */
8a3fe4f8 2209 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2210 return 0;
2211 }
2212 copy_threadref (&info->threadid, &ref);
2213
23860348 2214 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2215
23860348
MS
2216 /* Packets are terminated with nulls. */
2217 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2218 {
2219 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2220 pkt = unpack_byte (pkt, &length); /* length */
2221 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2222 {
8a3fe4f8 2223 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2224 retval = 0;
2225 break;
2226 }
2227 if (tag == TAG_THREADID)
2228 {
2229 if (length != 16)
2230 {
8a3fe4f8 2231 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2232 retval = 0;
2233 break;
2234 }
2235 pkt = unpack_threadid (pkt, &ref);
2236 mask = mask & ~TAG_THREADID;
2237 continue;
2238 }
2239 if (tag == TAG_EXISTS)
2240 {
2241 info->active = stub_unpack_int (pkt, length);
2242 pkt += length;
2243 mask = mask & ~(TAG_EXISTS);
2244 if (length > 8)
2245 {
8a3fe4f8 2246 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2247 retval = 0;
2248 break;
2249 }
2250 continue;
2251 }
2252 if (tag == TAG_THREADNAME)
2253 {
2254 pkt = unpack_string (pkt, &info->shortname[0], length);
2255 mask = mask & ~TAG_THREADNAME;
2256 continue;
2257 }
2258 if (tag == TAG_DISPLAY)
2259 {
2260 pkt = unpack_string (pkt, &info->display[0], length);
2261 mask = mask & ~TAG_DISPLAY;
2262 continue;
2263 }
2264 if (tag == TAG_MOREDISPLAY)
2265 {
2266 pkt = unpack_string (pkt, &info->more_display[0], length);
2267 mask = mask & ~TAG_MOREDISPLAY;
2268 continue;
2269 }
8a3fe4f8 2270 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2271 break; /* Not a tag we know about. */
c906108c
SS
2272 }
2273 return retval;
2274}
2275
2276static int
fba45db2
KB
2277remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2278 struct gdb_ext_thread_info *info)
c906108c 2279{
d01949b6 2280 struct remote_state *rs = get_remote_state ();
c906108c 2281 int result;
c906108c 2282
2e9f7625
DJ
2283 pack_threadinfo_request (rs->buf, fieldset, threadid);
2284 putpkt (rs->buf);
6d820c5c 2285 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2286
2287 if (rs->buf[0] == '\0')
2288 return 0;
2289
2e9f7625 2290 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2291 threadid, info);
c906108c
SS
2292 return result;
2293}
2294
c906108c
SS
2295/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2296
2297static char *
fba45db2
KB
2298pack_threadlist_request (char *pkt, int startflag, int threadcount,
2299 threadref *nextthread)
c906108c
SS
2300{
2301 *pkt++ = 'q'; /* info query packet */
2302 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2303 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2304 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2305 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2306 *pkt = '\0';
2307 return pkt;
2308}
2309
2310/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2311
2312static int
fba45db2
KB
2313parse_threadlist_response (char *pkt, int result_limit,
2314 threadref *original_echo, threadref *resultlist,
2315 int *doneflag)
c906108c 2316{
d01949b6 2317 struct remote_state *rs = get_remote_state ();
c906108c
SS
2318 char *limit;
2319 int count, resultcount, done;
2320
2321 resultcount = 0;
2322 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2323 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2324 /* done parse past here */
c906108c
SS
2325 pkt = unpack_byte (pkt, &count); /* count field */
2326 pkt = unpack_nibble (pkt, &done);
2327 /* The first threadid is the argument threadid. */
2328 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2329 while ((count-- > 0) && (pkt < limit))
2330 {
2331 pkt = unpack_threadid (pkt, resultlist++);
2332 if (resultcount++ >= result_limit)
2333 break;
2334 }
2335 if (doneflag)
2336 *doneflag = done;
2337 return resultcount;
2338}
2339
2340static int
fba45db2
KB
2341remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2342 int *done, int *result_count, threadref *threadlist)
c906108c 2343{
d01949b6 2344 struct remote_state *rs = get_remote_state ();
c906108c 2345 static threadref echo_nextthread;
c906108c
SS
2346 int result = 1;
2347
23860348 2348 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2349 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2350 >= get_remote_packet_size ())
ea9c271d 2351 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2352
6d820c5c
DJ
2353 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2354 putpkt (rs->buf);
2355 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2356
d8f2712d 2357 if (*rs->buf == '\0')
21bce120 2358 return 0;
d8f2712d
VP
2359 else
2360 *result_count =
2361 parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
2362 threadlist, done);
c906108c
SS
2363
2364 if (!threadmatch (&echo_nextthread, nextthread))
2365 {
23860348
MS
2366 /* FIXME: This is a good reason to drop the packet. */
2367 /* Possably, there is a duplicate response. */
c906108c
SS
2368 /* Possabilities :
2369 retransmit immediatly - race conditions
2370 retransmit after timeout - yes
2371 exit
2372 wait for packet, then exit
2373 */
8a3fe4f8 2374 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2375 return 0; /* I choose simply exiting. */
c906108c
SS
2376 }
2377 if (*result_count <= 0)
2378 {
2379 if (*done != 1)
2380 {
8a3fe4f8 2381 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2382 result = 0;
2383 }
2384 return result; /* break; */
2385 }
2386 if (*result_count > result_limit)
2387 {
2388 *result_count = 0;
8a3fe4f8 2389 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2390 return 0;
2391 }
2392 return result;
2393}
2394
23860348
MS
2395/* This is the interface between remote and threads, remotes upper
2396 interface. */
c906108c
SS
2397
2398/* remote_find_new_threads retrieves the thread list and for each
2399 thread in the list, looks up the thread in GDB's internal list,
79d7f229 2400 adding the thread if it does not already exist. This involves
c906108c
SS
2401 getting partial thread lists from the remote target so, polling the
2402 quit_flag is required. */
2403
2404
23860348 2405/* About this many threadisds fit in a packet. */
c906108c
SS
2406
2407#define MAXTHREADLISTRESULTS 32
2408
2409static int
fba45db2
KB
2410remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2411 int looplimit)
c906108c
SS
2412{
2413 int done, i, result_count;
2414 int startflag = 1;
2415 int result = 1;
2416 int loopcount = 0;
2417 static threadref nextthread;
2418 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
2419
2420 done = 0;
2421 while (!done)
2422 {
2423 if (loopcount++ > looplimit)
2424 {
2425 result = 0;
8a3fe4f8 2426 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2427 break;
2428 }
2429 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
2430 &done, &result_count, resultthreadlist))
2431 {
2432 result = 0;
2433 break;
2434 }
23860348 2435 /* Clear for later iterations. */
c906108c
SS
2436 startflag = 0;
2437 /* Setup to resume next batch of thread references, set nextthread. */
2438 if (result_count >= 1)
2439 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
2440 i = 0;
2441 while (result_count--)
2442 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
2443 break;
2444 }
2445 return result;
2446}
2447
2448static int
fba45db2 2449remote_newthread_step (threadref *ref, void *context)
c906108c 2450{
79d7f229
PA
2451 int pid = ptid_get_pid (inferior_ptid);
2452 ptid_t ptid = ptid_build (pid, 0, threadref_to_int (ref));
39f77062
KB
2453
2454 if (!in_thread_list (ptid))
2455 add_thread (ptid);
c906108c
SS
2456 return 1; /* continue iterator */
2457}
2458
2459#define CRAZY_MAX_THREADS 1000
2460
39f77062
KB
2461static ptid_t
2462remote_current_thread (ptid_t oldpid)
c906108c 2463{
d01949b6 2464 struct remote_state *rs = get_remote_state ();
c906108c
SS
2465
2466 putpkt ("qC");
6d820c5c 2467 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2468 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
82f73884 2469 return read_ptid (&rs->buf[2], NULL);
c906108c
SS
2470 else
2471 return oldpid;
2472}
2473
802188a7
RM
2474/* Find new threads for info threads command.
2475 * Original version, using John Metzler's thread protocol.
9d1f7ab2 2476 */
cce74817
JM
2477
2478static void
fba45db2 2479remote_find_new_threads (void)
c906108c 2480{
c5aa993b
JM
2481 remote_threadlist_iterator (remote_newthread_step, 0,
2482 CRAZY_MAX_THREADS);
c906108c
SS
2483}
2484
dc146f7c
VP
2485#if defined(HAVE_LIBEXPAT)
2486
2487typedef struct thread_item
2488{
2489 ptid_t ptid;
2490 char *extra;
2491 int core;
2492} thread_item_t;
2493DEF_VEC_O(thread_item_t);
2494
2495struct threads_parsing_context
2496{
2497 VEC (thread_item_t) *items;
2498};
2499
2500static void
2501start_thread (struct gdb_xml_parser *parser,
2502 const struct gdb_xml_element *element,
2503 void *user_data, VEC(gdb_xml_value_s) *attributes)
2504{
2505 struct threads_parsing_context *data = user_data;
2506
2507 struct thread_item item;
2508 char *id;
3d2c1d41 2509 struct gdb_xml_value *attr;
dc146f7c 2510
3d2c1d41 2511 id = xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
2512 item.ptid = read_ptid (id, NULL);
2513
3d2c1d41
PA
2514 attr = xml_find_attribute (attributes, "core");
2515 if (attr != NULL)
2516 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
2517 else
2518 item.core = -1;
2519
2520 item.extra = 0;
2521
2522 VEC_safe_push (thread_item_t, data->items, &item);
2523}
2524
2525static void
2526end_thread (struct gdb_xml_parser *parser,
2527 const struct gdb_xml_element *element,
2528 void *user_data, const char *body_text)
2529{
2530 struct threads_parsing_context *data = user_data;
2531
2532 if (body_text && *body_text)
2ae2a0b7 2533 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
2534}
2535
2536const struct gdb_xml_attribute thread_attributes[] = {
2537 { "id", GDB_XML_AF_NONE, NULL, NULL },
2538 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2539 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2540};
2541
2542const struct gdb_xml_element thread_children[] = {
2543 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2544};
2545
2546const struct gdb_xml_element threads_children[] = {
2547 { "thread", thread_attributes, thread_children,
2548 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2549 start_thread, end_thread },
2550 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2551};
2552
2553const struct gdb_xml_element threads_elements[] = {
2554 { "threads", NULL, threads_children,
2555 GDB_XML_EF_NONE, NULL, NULL },
2556 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2557};
2558
02357a4a
PA
2559/* Discard the contents of the constructed thread info context. */
2560
2561static void
2562clear_threads_parsing_context (void *p)
2563{
2564 struct threads_parsing_context *context = p;
2565 int i;
2566 struct thread_item *item;
2567
2568 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2569 xfree (item->extra);
2570
2571 VEC_free (thread_item_t, context->items);
2572}
2573
dc146f7c
VP
2574#endif
2575
9d1f7ab2
MS
2576/*
2577 * Find all threads for info threads command.
2578 * Uses new thread protocol contributed by Cisco.
2579 * Falls back and attempts to use the older method (above)
2580 * if the target doesn't respond to the new method.
2581 */
2582
0f71a2f6 2583static void
28439f5e 2584remote_threads_info (struct target_ops *ops)
0f71a2f6 2585{
d01949b6 2586 struct remote_state *rs = get_remote_state ();
085dd6e6 2587 char *bufp;
79d7f229 2588 ptid_t new_thread;
0f71a2f6
JM
2589
2590 if (remote_desc == 0) /* paranoia */
8a3fe4f8 2591 error (_("Command can only be used when connected to the remote target."));
0f71a2f6 2592
dc146f7c
VP
2593#if defined(HAVE_LIBEXPAT)
2594 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2595 {
2596 char *xml = target_read_stralloc (&current_target,
2597 TARGET_OBJECT_THREADS, NULL);
2598
2599 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 2600
dc146f7c
VP
2601 if (xml && *xml)
2602 {
dc146f7c 2603 struct threads_parsing_context context;
dc146f7c 2604
efc0eabd
PA
2605 context.items = NULL;
2606 make_cleanup (clear_threads_parsing_context, &context);
dc146f7c 2607
efc0eabd
PA
2608 if (gdb_xml_parse_quick (_("threads"), "threads.dtd",
2609 threads_elements, xml, &context) == 0)
dc146f7c
VP
2610 {
2611 int i;
2612 struct thread_item *item;
2613
3e43a32a
MS
2614 for (i = 0;
2615 VEC_iterate (thread_item_t, context.items, i, item);
2616 ++i)
dc146f7c
VP
2617 {
2618 if (!ptid_equal (item->ptid, null_ptid))
2619 {
2620 struct private_thread_info *info;
2621 /* In non-stop mode, we assume new found threads
2622 are running until proven otherwise with a
2623 stop reply. In all-stop, we can only get
2624 here if all threads are stopped. */
2625 int running = non_stop ? 1 : 0;
2626
2627 remote_notice_new_inferior (item->ptid, running);
2628
2629 info = demand_private_info (item->ptid);
2630 info->core = item->core;
2631 info->extra = item->extra;
02357a4a 2632 item->extra = NULL;
dc146f7c 2633 }
dc146f7c
VP
2634 }
2635 }
dc146f7c
VP
2636 }
2637
2638 do_cleanups (back_to);
2639 return;
2640 }
2641#endif
2642
9d1f7ab2
MS
2643 if (use_threadinfo_query)
2644 {
2645 putpkt ("qfThreadInfo");
6d820c5c 2646 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2647 bufp = rs->buf;
9d1f7ab2 2648 if (bufp[0] != '\0') /* q packet recognized */
802188a7 2649 {
9d1f7ab2
MS
2650 while (*bufp++ == 'm') /* reply contains one or more TID */
2651 {
2652 do
2653 {
82f73884 2654 new_thread = read_ptid (bufp, &bufp);
1941c569 2655 if (!ptid_equal (new_thread, null_ptid))
82f73884 2656 {
74531fed 2657 /* In non-stop mode, we assume new found threads
1941c569 2658 are running until proven otherwise with a
74531fed
PA
2659 stop reply. In all-stop, we can only get
2660 here if all threads are stopped. */
1941c569
PA
2661 int running = non_stop ? 1 : 0;
2662
2663 remote_notice_new_inferior (new_thread, running);
82f73884 2664 }
9d1f7ab2
MS
2665 }
2666 while (*bufp++ == ','); /* comma-separated list */
2667 putpkt ("qsThreadInfo");
6d820c5c 2668 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2669 bufp = rs->buf;
9d1f7ab2
MS
2670 }
2671 return; /* done */
2672 }
2673 }
2674
74531fed
PA
2675 /* Only qfThreadInfo is supported in non-stop mode. */
2676 if (non_stop)
2677 return;
2678
23860348 2679 /* Else fall back to old method based on jmetzler protocol. */
9d1f7ab2
MS
2680 use_threadinfo_query = 0;
2681 remote_find_new_threads ();
2682 return;
2683}
2684
802188a7 2685/*
9d1f7ab2
MS
2686 * Collect a descriptive string about the given thread.
2687 * The target may say anything it wants to about the thread
2688 * (typically info about its blocked / runnable state, name, etc.).
2689 * This string will appear in the info threads display.
802188a7 2690 *
9d1f7ab2
MS
2691 * Optional: targets are not required to implement this function.
2692 */
2693
2694static char *
2695remote_threads_extra_info (struct thread_info *tp)
2696{
d01949b6 2697 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
2698 int result;
2699 int set;
2700 threadref id;
2701 struct gdb_ext_thread_info threadinfo;
23860348 2702 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
2703 int n = 0; /* position in display_buf */
2704
2705 if (remote_desc == 0) /* paranoia */
8e65ff28 2706 internal_error (__FILE__, __LINE__,
e2e0b3e5 2707 _("remote_threads_extra_info"));
9d1f7ab2 2708
60e569b9
PA
2709 if (ptid_equal (tp->ptid, magic_null_ptid)
2710 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_tid (tp->ptid) == 0))
2711 /* This is the main thread which was added by GDB. The remote
2712 server doesn't know about it. */
2713 return NULL;
2714
dc146f7c
VP
2715 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2716 {
2717 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 2718
dc146f7c
VP
2719 if (info && info->private)
2720 return info->private->extra;
2721 else
2722 return NULL;
2723 }
2724
9d1f7ab2
MS
2725 if (use_threadextra_query)
2726 {
82f73884
PA
2727 char *b = rs->buf;
2728 char *endb = rs->buf + get_remote_packet_size ();
2729
2730 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2731 b += strlen (b);
2732 write_ptid (b, endb, tp->ptid);
2733
2e9f7625 2734 putpkt (rs->buf);
6d820c5c 2735 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2736 if (rs->buf[0] != 0)
9d1f7ab2 2737 {
2e9f7625
DJ
2738 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2739 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 2740 display_buf [result] = '\0';
9d1f7ab2
MS
2741 return display_buf;
2742 }
0f71a2f6 2743 }
9d1f7ab2
MS
2744
2745 /* If the above query fails, fall back to the old method. */
2746 use_threadextra_query = 0;
2747 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2748 | TAG_MOREDISPLAY | TAG_DISPLAY;
79d7f229 2749 int_to_threadref (&id, ptid_get_tid (tp->ptid));
9d1f7ab2
MS
2750 if (remote_get_threadinfo (&id, set, &threadinfo))
2751 if (threadinfo.active)
0f71a2f6 2752 {
9d1f7ab2 2753 if (*threadinfo.shortname)
2bc416ba 2754 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 2755 " Name: %s,", threadinfo.shortname);
9d1f7ab2 2756 if (*threadinfo.display)
2bc416ba 2757 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 2758 " State: %s,", threadinfo.display);
9d1f7ab2 2759 if (*threadinfo.more_display)
2bc416ba 2760 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 2761 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
2762
2763 if (n > 0)
c5aa993b 2764 {
23860348 2765 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
2766 if (',' == display_buf[n-1])
2767 display_buf[n-1] = ' ';
2768 return display_buf;
c5aa993b 2769 }
0f71a2f6 2770 }
9d1f7ab2 2771 return NULL;
0f71a2f6 2772}
c906108c 2773\f
c5aa993b 2774
0fb4aa4b
PA
2775static int
2776remote_static_tracepoint_marker_at (CORE_ADDR addr,
2777 struct static_tracepoint_marker *marker)
2778{
2779 struct remote_state *rs = get_remote_state ();
2780 char *p = rs->buf;
2781
2782 sprintf (p, "qTSTMat:");
2783 p += strlen (p);
2784 p += hexnumstr (p, addr);
2785 putpkt (rs->buf);
2786 getpkt (&rs->buf, &rs->buf_size, 0);
2787 p = rs->buf;
2788
2789 if (*p == 'E')
2790 error (_("Remote failure reply: %s"), p);
2791
2792 if (*p++ == 'm')
2793 {
2794 parse_static_tracepoint_marker_definition (p, &p, marker);
2795 return 1;
2796 }
2797
2798 return 0;
2799}
2800
2801static void
2802free_current_marker (void *arg)
2803{
2804 struct static_tracepoint_marker **marker_p = arg;
2805
2806 if (*marker_p != NULL)
2807 {
2808 release_static_tracepoint_marker (*marker_p);
2809 xfree (*marker_p);
2810 }
2811 else
2812 *marker_p = NULL;
2813}
2814
2815static VEC(static_tracepoint_marker_p) *
2816remote_static_tracepoint_markers_by_strid (const char *strid)
2817{
2818 struct remote_state *rs = get_remote_state ();
2819 VEC(static_tracepoint_marker_p) *markers = NULL;
2820 struct static_tracepoint_marker *marker = NULL;
2821 struct cleanup *old_chain;
2822 char *p;
2823
2824 /* Ask for a first packet of static tracepoint marker
2825 definition. */
2826 putpkt ("qTfSTM");
2827 getpkt (&rs->buf, &rs->buf_size, 0);
2828 p = rs->buf;
2829 if (*p == 'E')
2830 error (_("Remote failure reply: %s"), p);
2831
2832 old_chain = make_cleanup (free_current_marker, &marker);
2833
2834 while (*p++ == 'm')
2835 {
2836 if (marker == NULL)
2837 marker = XCNEW (struct static_tracepoint_marker);
2838
2839 do
2840 {
2841 parse_static_tracepoint_marker_definition (p, &p, marker);
2842
2843 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
2844 {
2845 VEC_safe_push (static_tracepoint_marker_p,
2846 markers, marker);
2847 marker = NULL;
2848 }
2849 else
2850 {
2851 release_static_tracepoint_marker (marker);
2852 memset (marker, 0, sizeof (*marker));
2853 }
2854 }
2855 while (*p++ == ','); /* comma-separated list */
2856 /* Ask for another packet of static tracepoint definition. */
2857 putpkt ("qTsSTM");
2858 getpkt (&rs->buf, &rs->buf_size, 0);
2859 p = rs->buf;
2860 }
2861
2862 do_cleanups (old_chain);
2863 return markers;
2864}
2865
2866\f
10760264
JB
2867/* Implement the to_get_ada_task_ptid function for the remote targets. */
2868
2869static ptid_t
2870remote_get_ada_task_ptid (long lwp, long thread)
2871{
2872 return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
2873}
2874\f
2875
24b06219 2876/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
2877
2878static void
fba45db2 2879extended_remote_restart (void)
c906108c 2880{
d01949b6 2881 struct remote_state *rs = get_remote_state ();
c906108c
SS
2882
2883 /* Send the restart command; for reasons I don't understand the
2884 remote side really expects a number after the "R". */
ea9c271d 2885 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 2886 putpkt (rs->buf);
c906108c 2887
ad9a8f3f 2888 remote_fileio_reset ();
c906108c
SS
2889}
2890\f
2891/* Clean up connection to a remote debugger. */
2892
c906108c 2893static void
fba45db2 2894remote_close (int quitting)
c906108c 2895{
d3fd5342
PA
2896 if (remote_desc == NULL)
2897 return; /* already closed */
2898
2899 /* Make sure we leave stdin registered in the event loop, and we
2900 don't leave the async SIGINT signal handler installed. */
2901 remote_terminal_ours ();
ce5ce7ed 2902
d3fd5342
PA
2903 serial_close (remote_desc);
2904 remote_desc = NULL;
ce5ce7ed
PA
2905
2906 /* We don't have a connection to the remote stub anymore. Get rid
2907 of all the inferiors and their threads we were controlling. */
2908 discard_all_inferiors ();
0f2caa1b 2909 inferior_ptid = null_ptid;
ce5ce7ed 2910
74531fed
PA
2911 /* We're no longer interested in any of these events. */
2912 discard_pending_stop_replies (-1);
2913
2914 if (remote_async_inferior_event_token)
2915 delete_async_event_handler (&remote_async_inferior_event_token);
2916 if (remote_async_get_pending_events_token)
2917 delete_async_event_handler (&remote_async_get_pending_events_token);
c906108c
SS
2918}
2919
23860348 2920/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
2921
2922static void
fba45db2 2923get_offsets (void)
c906108c 2924{
d01949b6 2925 struct remote_state *rs = get_remote_state ();
2e9f7625 2926 char *buf;
085dd6e6 2927 char *ptr;
31d99776
DJ
2928 int lose, num_segments = 0, do_sections, do_segments;
2929 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 2930 struct section_offsets *offs;
31d99776
DJ
2931 struct symfile_segment_data *data;
2932
2933 if (symfile_objfile == NULL)
2934 return;
c906108c
SS
2935
2936 putpkt ("qOffsets");
6d820c5c 2937 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2938 buf = rs->buf;
c906108c
SS
2939
2940 if (buf[0] == '\000')
2941 return; /* Return silently. Stub doesn't support
23860348 2942 this command. */
c906108c
SS
2943 if (buf[0] == 'E')
2944 {
8a3fe4f8 2945 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
2946 return;
2947 }
2948
2949 /* Pick up each field in turn. This used to be done with scanf, but
2950 scanf will make trouble if CORE_ADDR size doesn't match
2951 conversion directives correctly. The following code will work
2952 with any size of CORE_ADDR. */
2953 text_addr = data_addr = bss_addr = 0;
2954 ptr = buf;
2955 lose = 0;
2956
2957 if (strncmp (ptr, "Text=", 5) == 0)
2958 {
2959 ptr += 5;
2960 /* Don't use strtol, could lose on big values. */
2961 while (*ptr && *ptr != ';')
2962 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 2963
31d99776
DJ
2964 if (strncmp (ptr, ";Data=", 6) == 0)
2965 {
2966 ptr += 6;
2967 while (*ptr && *ptr != ';')
2968 data_addr = (data_addr << 4) + fromhex (*ptr++);
2969 }
2970 else
2971 lose = 1;
2972
2973 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
2974 {
2975 ptr += 5;
2976 while (*ptr && *ptr != ';')
2977 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 2978
31d99776
DJ
2979 if (bss_addr != data_addr)
2980 warning (_("Target reported unsupported offsets: %s"), buf);
2981 }
2982 else
2983 lose = 1;
2984 }
2985 else if (strncmp (ptr, "TextSeg=", 8) == 0)
c906108c 2986 {
31d99776
DJ
2987 ptr += 8;
2988 /* Don't use strtol, could lose on big values. */
c906108c 2989 while (*ptr && *ptr != ';')
31d99776
DJ
2990 text_addr = (text_addr << 4) + fromhex (*ptr++);
2991 num_segments = 1;
2992
2993 if (strncmp (ptr, ";DataSeg=", 9) == 0)
2994 {
2995 ptr += 9;
2996 while (*ptr && *ptr != ';')
2997 data_addr = (data_addr << 4) + fromhex (*ptr++);
2998 num_segments++;
2999 }
c906108c
SS
3000 }
3001 else
3002 lose = 1;
3003
3004 if (lose)
8a3fe4f8 3005 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3006 else if (*ptr != '\0')
3007 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3008
802188a7 3009 offs = ((struct section_offsets *)
a39a16c4 3010 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3011 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3012 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3013
31d99776
DJ
3014 data = get_symfile_segment_data (symfile_objfile->obfd);
3015 do_segments = (data != NULL);
3016 do_sections = num_segments == 0;
c906108c 3017
28c32713 3018 if (num_segments > 0)
31d99776 3019 {
31d99776
DJ
3020 segments[0] = text_addr;
3021 segments[1] = data_addr;
3022 }
28c32713
JB
3023 /* If we have two segments, we can still try to relocate everything
3024 by assuming that the .text and .data offsets apply to the whole
3025 text and data segments. Convert the offsets given in the packet
3026 to base addresses for symfile_map_offsets_to_segments. */
3027 else if (data && data->num_segments == 2)
3028 {
3029 segments[0] = data->segment_bases[0] + text_addr;
3030 segments[1] = data->segment_bases[1] + data_addr;
3031 num_segments = 2;
3032 }
8d385431
DJ
3033 /* If the object file has only one segment, assume that it is text
3034 rather than data; main programs with no writable data are rare,
3035 but programs with no code are useless. Of course the code might
3036 have ended up in the data segment... to detect that we would need
3037 the permissions here. */
3038 else if (data && data->num_segments == 1)
3039 {
3040 segments[0] = data->segment_bases[0] + text_addr;
3041 num_segments = 1;
3042 }
28c32713
JB
3043 /* There's no way to relocate by segment. */
3044 else
3045 do_segments = 0;
31d99776
DJ
3046
3047 if (do_segments)
3048 {
3049 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3050 offs, num_segments, segments);
3051
3052 if (ret == 0 && !do_sections)
3e43a32a
MS
3053 error (_("Can not handle qOffsets TextSeg "
3054 "response with this symbol file"));
31d99776
DJ
3055
3056 if (ret > 0)
3057 do_sections = 0;
3058 }
c906108c 3059
9ef895d6
DJ
3060 if (data)
3061 free_symfile_segment_data (data);
31d99776
DJ
3062
3063 if (do_sections)
3064 {
3065 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3066
3e43a32a
MS
3067 /* This is a temporary kludge to force data and bss to use the
3068 same offsets because that's what nlmconv does now. The real
3069 solution requires changes to the stub and remote.c that I
3070 don't have time to do right now. */
31d99776
DJ
3071
3072 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3073 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3074 }
c906108c
SS
3075
3076 objfile_relocate (symfile_objfile, offs);
3077}
3078
74531fed
PA
3079/* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3080 threads we know are stopped already. This is used during the
3081 initial remote connection in non-stop mode --- threads that are
3082 reported as already being stopped are left stopped. */
3083
3084static int
3085set_stop_requested_callback (struct thread_info *thread, void *data)
3086{
3087 /* If we have a stop reply for this thread, it must be stopped. */
3088 if (peek_stop_reply (thread->ptid))
3089 set_stop_requested (thread->ptid, 1);
3090
3091 return 0;
3092}
3093
8621d6a9 3094/* Stub for catch_exception. */
0f71a2f6 3095
2d717e4f
DJ
3096struct start_remote_args
3097{
3098 int from_tty;
3099
3100 /* The current target. */
3101 struct target_ops *target;
3102
3103 /* Non-zero if this is an extended-remote target. */
3104 int extended_p;
3105};
3106
9a7071a8
JB
3107/* Send interrupt_sequence to remote target. */
3108static void
3109send_interrupt_sequence ()
3110{
3111 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3112 serial_write (remote_desc, "\x03", 1);
3113 else if (interrupt_sequence_mode == interrupt_sequence_break)
3114 serial_send_break (remote_desc);
3115 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3116 {
3117 serial_send_break (remote_desc);
3118 serial_write (remote_desc, "g", 1);
3119 }
3120 else
3121 internal_error (__FILE__, __LINE__,
3122 _("Invalid value for interrupt_sequence_mode: %s."),
3123 interrupt_sequence_mode);
3124}
3125
9cbc821d 3126static void
2d717e4f 3127remote_start_remote (struct ui_out *uiout, void *opaque)
c906108c 3128{
2d717e4f 3129 struct start_remote_args *args = opaque;
c8d104ad
PA
3130 struct remote_state *rs = get_remote_state ();
3131 struct packet_config *noack_config;
2d717e4f 3132 char *wait_status = NULL;
8621d6a9 3133
23860348 3134 immediate_quit++; /* Allow user to interrupt it. */
c906108c 3135
c8d104ad
PA
3136 /* Ack any packet which the remote side has already sent. */
3137 serial_write (remote_desc, "+", 1);
3138
9a7071a8
JB
3139 if (interrupt_on_connect)
3140 send_interrupt_sequence ();
3141
c8d104ad
PA
3142 /* The first packet we send to the target is the optional "supported
3143 packets" request. If the target can answer this, it will tell us
3144 which later probes to skip. */
3145 remote_query_supported ();
3146
d914c394
SS
3147 /* If the stub wants to get a QAllow, compose one and send it. */
3148 if (remote_protocol_packets[PACKET_QAllow].support != PACKET_DISABLE)
3149 remote_set_permissions ();
3150
c8d104ad
PA
3151 /* Next, we possibly activate noack mode.
3152
3153 If the QStartNoAckMode packet configuration is set to AUTO,
3154 enable noack mode if the stub reported a wish for it with
3155 qSupported.
3156
3157 If set to TRUE, then enable noack mode even if the stub didn't
3158 report it in qSupported. If the stub doesn't reply OK, the
3159 session ends with an error.
3160
3161 If FALSE, then don't activate noack mode, regardless of what the
3162 stub claimed should be the default with qSupported. */
3163
3164 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3165
3166 if (noack_config->detect == AUTO_BOOLEAN_TRUE
3167 || (noack_config->detect == AUTO_BOOLEAN_AUTO
3168 && noack_config->support == PACKET_ENABLE))
3169 {
3170 putpkt ("QStartNoAckMode");
3171 getpkt (&rs->buf, &rs->buf_size, 0);
3172 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3173 rs->noack_mode = 1;
3174 }
3175
5fe04517
PA
3176 if (args->extended_p)
3177 {
3178 /* Tell the remote that we are using the extended protocol. */
3179 putpkt ("!");
3180 getpkt (&rs->buf, &rs->buf_size, 0);
3181 }
3182
d962ef82
DJ
3183 /* Next, if the target can specify a description, read it. We do
3184 this before anything involving memory or registers. */
3185 target_find_description ();
3186
6c95b8df
PA
3187 /* Next, now that we know something about the target, update the
3188 address spaces in the program spaces. */
3189 update_address_spaces ();
3190
50c71eaf
PA
3191 /* On OSs where the list of libraries is global to all
3192 processes, we fetch them early. */
3193 if (gdbarch_has_global_solist (target_gdbarch))
3194 solib_add (NULL, args->from_tty, args->target, auto_solib_add);
3195
74531fed
PA
3196 if (non_stop)
3197 {
3198 if (!rs->non_stop_aware)
3e43a32a
MS
3199 error (_("Non-stop mode requested, but remote "
3200 "does not support non-stop"));
74531fed
PA
3201
3202 putpkt ("QNonStop:1");
3203 getpkt (&rs->buf, &rs->buf_size, 0);
3204
3205 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3206 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
3207
3208 /* Find about threads and processes the stub is already
3209 controlling. We default to adding them in the running state.
3210 The '?' query below will then tell us about which threads are
3211 stopped. */
28439f5e 3212 remote_threads_info (args->target);
74531fed
PA
3213 }
3214 else if (rs->non_stop_aware)
3215 {
3216 /* Don't assume that the stub can operate in all-stop mode.
3217 Request it explicitely. */
3218 putpkt ("QNonStop:0");
3219 getpkt (&rs->buf, &rs->buf_size, 0);
3220
3221 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3222 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
3223 }
3224
2d717e4f
DJ
3225 /* Check whether the target is running now. */
3226 putpkt ("?");
3227 getpkt (&rs->buf, &rs->buf_size, 0);
3228
74531fed 3229 if (!non_stop)
2d717e4f 3230 {
74531fed 3231 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 3232 {
c35b1492 3233 if (!args->extended_p)
74531fed 3234 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
3235
3236 /* We're connected, but not running. Drop out before we
3237 call start_remote. */
3238 return;
2d717e4f
DJ
3239 }
3240 else
74531fed 3241 {
74531fed
PA
3242 /* Save the reply for later. */
3243 wait_status = alloca (strlen (rs->buf) + 1);
3244 strcpy (wait_status, rs->buf);
3245 }
3246
3247 /* Let the stub know that we want it to return the thread. */
3248 set_continue_thread (minus_one_ptid);
3249
3250 /* Without this, some commands which require an active target
3251 (such as kill) won't work. This variable serves (at least)
3252 double duty as both the pid of the target process (if it has
3253 such), and as a flag indicating that a target is active.
3254 These functions should be split out into seperate variables,
3255 especially since GDB will someday have a notion of debugging
3256 several processes. */
3257 inferior_ptid = magic_null_ptid;
3258
3259 /* Now, if we have thread information, update inferior_ptid. */
3260 inferior_ptid = remote_current_thread (inferior_ptid);
3261
0b16c5cf 3262 remote_add_inferior (ptid_get_pid (inferior_ptid), -1);
74531fed
PA
3263
3264 /* Always add the main thread. */
3265 add_thread_silent (inferior_ptid);
3266
3267 get_offsets (); /* Get text, data & bss offsets. */
3268
d962ef82
DJ
3269 /* If we could not find a description using qXfer, and we know
3270 how to do it some other way, try again. This is not
3271 supported for non-stop; it could be, but it is tricky if
3272 there are no stopped threads when we connect. */
3273 if (remote_read_description_p (args->target)
3274 && gdbarch_target_desc (target_gdbarch) == NULL)
3275 {
3276 target_clear_description ();
3277 target_find_description ();
3278 }
3279
74531fed
PA
3280 /* Use the previously fetched status. */
3281 gdb_assert (wait_status != NULL);
3282 strcpy (rs->buf, wait_status);
3283 rs->cached_wait_status = 1;
3284
3285 immediate_quit--;
3286 start_remote (args->from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
3287 }
3288 else
3289 {
68c97600
PA
3290 /* Clear WFI global state. Do this before finding about new
3291 threads and inferiors, and setting the current inferior.
3292 Otherwise we would clear the proceed status of the current
3293 inferior when we want its stop_soon state to be preserved
3294 (see notice_new_inferior). */
3295 init_wait_for_inferior ();
3296
74531fed
PA
3297 /* In non-stop, we will either get an "OK", meaning that there
3298 are no stopped threads at this time; or, a regular stop
3299 reply. In the latter case, there may be more than one thread
3300 stopped --- we pull them all out using the vStopped
3301 mechanism. */
3302 if (strcmp (rs->buf, "OK") != 0)
3303 {
3304 struct stop_reply *stop_reply;
3305 struct cleanup *old_chain;
2d717e4f 3306
74531fed
PA
3307 stop_reply = stop_reply_xmalloc ();
3308 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
2d717e4f 3309
74531fed
PA
3310 remote_parse_stop_reply (rs->buf, stop_reply);
3311 discard_cleanups (old_chain);
c0a2216e 3312
74531fed
PA
3313 /* get_pending_stop_replies acks this one, and gets the rest
3314 out. */
3315 pending_stop_reply = stop_reply;
3316 remote_get_pending_stop_replies ();
c906108c 3317
74531fed
PA
3318 /* Make sure that threads that were stopped remain
3319 stopped. */
3320 iterate_over_threads (set_stop_requested_callback, NULL);
3321 }
2d717e4f 3322
74531fed
PA
3323 if (target_can_async_p ())
3324 target_async (inferior_event_handler, 0);
c906108c 3325
74531fed
PA
3326 if (thread_count () == 0)
3327 {
c35b1492 3328 if (!args->extended_p)
74531fed 3329 error (_("The target is not running (try extended-remote?)"));
82f73884 3330
c35b1492
PA
3331 /* We're connected, but not running. Drop out before we
3332 call start_remote. */
3333 return;
3334 }
74531fed
PA
3335
3336 /* Let the stub know that we want it to return the thread. */
c0a2216e 3337
74531fed
PA
3338 /* Force the stub to choose a thread. */
3339 set_general_thread (null_ptid);
c906108c 3340
74531fed
PA
3341 /* Query it. */
3342 inferior_ptid = remote_current_thread (minus_one_ptid);
3343 if (ptid_equal (inferior_ptid, minus_one_ptid))
3344 error (_("remote didn't report the current thread in non-stop mode"));
c906108c 3345
74531fed
PA
3346 get_offsets (); /* Get text, data & bss offsets. */
3347
3348 /* In non-stop mode, any cached wait status will be stored in
3349 the stop reply queue. */
3350 gdb_assert (wait_status == NULL);
f0223081
PA
3351
3352 /* Update the remote on signals to silently pass, or more
3353 importantly, which to not ignore, in case a previous session
3354 had set some different set of signals to be ignored. */
3355 remote_pass_signals ();
74531fed 3356 }
c8d104ad 3357
c8d104ad
PA
3358 /* If we connected to a live target, do some additional setup. */
3359 if (target_has_execution)
3360 {
3361 if (exec_bfd) /* No use without an exec file. */
3362 remote_check_symbols (symfile_objfile);
3363 }
50c71eaf 3364
d5551862
SS
3365 /* Possibly the target has been engaged in a trace run started
3366 previously; find out where things are at. */
ad91cd99 3367 if (remote_get_trace_status (current_trace_status ()) != -1)
d5551862 3368 {
00bf0b85
SS
3369 struct uploaded_tp *uploaded_tps = NULL;
3370 struct uploaded_tsv *uploaded_tsvs = NULL;
3371
00bf0b85
SS
3372 if (current_trace_status ()->running)
3373 printf_filtered (_("Trace is already running on the target.\n"));
3374
3375 /* Get trace state variables first, they may be checked when
3376 parsing uploaded commands. */
3377
3378 remote_upload_trace_state_variables (&uploaded_tsvs);
3379
3380 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3381
3382 remote_upload_tracepoints (&uploaded_tps);
3383
3384 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
3385 }
3386
2567c7d9
PA
3387 /* If breakpoints are global, insert them now. */
3388 if (gdbarch_has_global_breakpoints (target_gdbarch)
50c71eaf
PA
3389 && breakpoints_always_inserted_mode ())
3390 insert_breakpoints ();
c906108c
SS
3391}
3392
3393/* Open a connection to a remote debugger.
3394 NAME is the filename used for communication. */
3395
3396static void
fba45db2 3397remote_open (char *name, int from_tty)
c906108c 3398{
75c99385 3399 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
3400}
3401
c906108c
SS
3402/* Open a connection to a remote debugger using the extended
3403 remote gdb protocol. NAME is the filename used for communication. */
3404
3405static void
fba45db2 3406extended_remote_open (char *name, int from_tty)
c906108c 3407{
75c99385 3408 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
3409}
3410
c906108c
SS
3411/* Generic code for opening a connection to a remote target. */
3412
d471ea57
AC
3413static void
3414init_all_packet_configs (void)
3415{
3416 int i;
a744cf53 3417
444abaca
DJ
3418 for (i = 0; i < PACKET_MAX; i++)
3419 update_packet_config (&remote_protocol_packets[i]);
d471ea57
AC
3420}
3421
23860348 3422/* Symbol look-up. */
dc8acb97
MS
3423
3424static void
3425remote_check_symbols (struct objfile *objfile)
3426{
d01949b6 3427 struct remote_state *rs = get_remote_state ();
dc8acb97
MS
3428 char *msg, *reply, *tmp;
3429 struct minimal_symbol *sym;
3430 int end;
3431
444abaca 3432 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
dc8acb97
MS
3433 return;
3434
3c9c4b83
PA
3435 /* Make sure the remote is pointing at the right process. */
3436 set_general_process ();
3437
6d820c5c
DJ
3438 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3439 because we need both at the same time. */
ea9c271d 3440 msg = alloca (get_remote_packet_size ());
6d820c5c 3441
23860348 3442 /* Invite target to request symbol lookups. */
dc8acb97
MS
3443
3444 putpkt ("qSymbol::");
6d820c5c
DJ
3445 getpkt (&rs->buf, &rs->buf_size, 0);
3446 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2e9f7625 3447 reply = rs->buf;
dc8acb97
MS
3448
3449 while (strncmp (reply, "qSymbol:", 8) == 0)
3450 {
3451 tmp = &reply[8];
cfd77fa1 3452 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
3453 msg[end] = '\0';
3454 sym = lookup_minimal_symbol (msg, NULL, NULL);
3455 if (sym == NULL)
ea9c271d 3456 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 3457 else
2bbe3cc1 3458 {
5af949e3 3459 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
2bbe3cc1
DJ
3460 CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
3461
3462 /* If this is a function address, return the start of code
3463 instead of any data function descriptor. */
1cf3db46 3464 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch,
2bbe3cc1
DJ
3465 sym_addr,
3466 &current_target);
3467
3468 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 3469 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
3470 }
3471
dc8acb97 3472 putpkt (msg);
6d820c5c 3473 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3474 reply = rs->buf;
dc8acb97
MS
3475 }
3476}
3477
9db8d71f
DJ
3478static struct serial *
3479remote_serial_open (char *name)
3480{
3481 static int udp_warning = 0;
3482
3483 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3484 of in ser-tcp.c, because it is the remote protocol assuming that the
3485 serial connection is reliable and not the serial connection promising
3486 to be. */
3487 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
3488 {
3e43a32a
MS
3489 warning (_("The remote protocol may be unreliable over UDP.\n"
3490 "Some events may be lost, rendering further debugging "
3491 "impossible."));
9db8d71f
DJ
3492 udp_warning = 1;
3493 }
3494
3495 return serial_open (name);
3496}
3497
d914c394
SS
3498/* Inform the target of our permission settings. The permission flags
3499 work without this, but if the target knows the settings, it can do
3500 a couple things. First, it can add its own check, to catch cases
3501 that somehow manage to get by the permissions checks in target
3502 methods. Second, if the target is wired to disallow particular
3503 settings (for instance, a system in the field that is not set up to
3504 be able to stop at a breakpoint), it can object to any unavailable
3505 permissions. */
3506
3507void
3508remote_set_permissions (void)
3509{
3510 struct remote_state *rs = get_remote_state ();
3511
3512 sprintf (rs->buf, "QAllow:"
3513 "WriteReg:%x;WriteMem:%x;"
3514 "InsertBreak:%x;InsertTrace:%x;"
3515 "InsertFastTrace:%x;Stop:%x",
3516 may_write_registers, may_write_memory,
3517 may_insert_breakpoints, may_insert_tracepoints,
3518 may_insert_fast_tracepoints, may_stop);
3519 putpkt (rs->buf);
3520 getpkt (&rs->buf, &rs->buf_size, 0);
3521
3522 /* If the target didn't like the packet, warn the user. Do not try
3523 to undo the user's settings, that would just be maddening. */
3524 if (strcmp (rs->buf, "OK") != 0)
3525 warning ("Remote refused setting permissions with: %s", rs->buf);
3526}
3527
be2a5f71
DJ
3528/* This type describes each known response to the qSupported
3529 packet. */
3530struct protocol_feature
3531{
3532 /* The name of this protocol feature. */
3533 const char *name;
3534
3535 /* The default for this protocol feature. */
3536 enum packet_support default_support;
3537
3538 /* The function to call when this feature is reported, or after
3539 qSupported processing if the feature is not supported.
3540 The first argument points to this structure. The second
3541 argument indicates whether the packet requested support be
3542 enabled, disabled, or probed (or the default, if this function
3543 is being called at the end of processing and this feature was
3544 not reported). The third argument may be NULL; if not NULL, it
3545 is a NUL-terminated string taken from the packet following
3546 this feature's name and an equals sign. */
3547 void (*func) (const struct protocol_feature *, enum packet_support,
3548 const char *);
3549
3550 /* The corresponding packet for this feature. Only used if
3551 FUNC is remote_supported_packet. */
3552 int packet;
3553};
3554
be2a5f71
DJ
3555static void
3556remote_supported_packet (const struct protocol_feature *feature,
3557 enum packet_support support,
3558 const char *argument)
3559{
3560 if (argument)
3561 {
3562 warning (_("Remote qSupported response supplied an unexpected value for"
3563 " \"%s\"."), feature->name);
3564 return;
3565 }
3566
3567 if (remote_protocol_packets[feature->packet].support
3568 == PACKET_SUPPORT_UNKNOWN)
3569 remote_protocol_packets[feature->packet].support = support;
3570}
be2a5f71
DJ
3571
3572static void
3573remote_packet_size (const struct protocol_feature *feature,
3574 enum packet_support support, const char *value)
3575{
3576 struct remote_state *rs = get_remote_state ();
3577
3578 int packet_size;
3579 char *value_end;
3580
3581 if (support != PACKET_ENABLE)
3582 return;
3583
3584 if (value == NULL || *value == '\0')
3585 {
3586 warning (_("Remote target reported \"%s\" without a size."),
3587 feature->name);
3588 return;
3589 }
3590
3591 errno = 0;
3592 packet_size = strtol (value, &value_end, 16);
3593 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3594 {
3595 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3596 feature->name, value);
3597 return;
3598 }
3599
3600 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3601 {
3602 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3603 packet_size, MAX_REMOTE_PACKET_SIZE);
3604 packet_size = MAX_REMOTE_PACKET_SIZE;
3605 }
3606
3607 /* Record the new maximum packet size. */
3608 rs->explicit_packet_size = packet_size;
3609}
3610
82f73884
PA
3611static void
3612remote_multi_process_feature (const struct protocol_feature *feature,
3613 enum packet_support support, const char *value)
3614{
3615 struct remote_state *rs = get_remote_state ();
a744cf53 3616
82f73884
PA
3617 rs->multi_process_aware = (support == PACKET_ENABLE);
3618}
3619
74531fed
PA
3620static void
3621remote_non_stop_feature (const struct protocol_feature *feature,
3622 enum packet_support support, const char *value)
3623{
3624 struct remote_state *rs = get_remote_state ();
a744cf53 3625
74531fed
PA
3626 rs->non_stop_aware = (support == PACKET_ENABLE);
3627}
3628
782b2b07
SS
3629static void
3630remote_cond_tracepoint_feature (const struct protocol_feature *feature,
3631 enum packet_support support,
3632 const char *value)
3633{
3634 struct remote_state *rs = get_remote_state ();
a744cf53 3635
782b2b07
SS
3636 rs->cond_tracepoints = (support == PACKET_ENABLE);
3637}
3638
7a697b8d
SS
3639static void
3640remote_fast_tracepoint_feature (const struct protocol_feature *feature,
3641 enum packet_support support,
3642 const char *value)
3643{
3644 struct remote_state *rs = get_remote_state ();
a744cf53 3645
7a697b8d
SS
3646 rs->fast_tracepoints = (support == PACKET_ENABLE);
3647}
3648
0fb4aa4b
PA
3649static void
3650remote_static_tracepoint_feature (const struct protocol_feature *feature,
3651 enum packet_support support,
3652 const char *value)
3653{
3654 struct remote_state *rs = get_remote_state ();
3655
3656 rs->static_tracepoints = (support == PACKET_ENABLE);
3657}
3658
d5551862
SS
3659static void
3660remote_disconnected_tracing_feature (const struct protocol_feature *feature,
3661 enum packet_support support,
3662 const char *value)
3663{
3664 struct remote_state *rs = get_remote_state ();
a744cf53 3665
d5551862
SS
3666 rs->disconnected_tracing = (support == PACKET_ENABLE);
3667}
3668
be2a5f71 3669static struct protocol_feature remote_protocol_features[] = {
0876f84a 3670 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 3671 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 3672 PACKET_qXfer_auxv },
23181151
DJ
3673 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3674 PACKET_qXfer_features },
cfa9d6d9
DJ
3675 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3676 PACKET_qXfer_libraries },
fd79ecee 3677 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 3678 PACKET_qXfer_memory_map },
4de6483e
UW
3679 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3680 PACKET_qXfer_spu_read },
3681 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3682 PACKET_qXfer_spu_write },
07e059b5
VP
3683 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3684 PACKET_qXfer_osdata },
dc146f7c
VP
3685 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
3686 PACKET_qXfer_threads },
b3b9301e
PA
3687 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
3688 PACKET_qXfer_traceframe_info },
89be2091
DJ
3689 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3690 PACKET_QPassSignals },
a6f3e723
SL
3691 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
3692 PACKET_QStartNoAckMode },
82f73884 3693 { "multiprocess", PACKET_DISABLE, remote_multi_process_feature, -1 },
74531fed 3694 { "QNonStop", PACKET_DISABLE, remote_non_stop_feature, -1 },
4aa995e1
PA
3695 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
3696 PACKET_qXfer_siginfo_read },
3697 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
3698 PACKET_qXfer_siginfo_write },
782b2b07
SS
3699 { "ConditionalTracepoints", PACKET_DISABLE, remote_cond_tracepoint_feature,
3700 PACKET_ConditionalTracepoints },
7a697b8d
SS
3701 { "FastTracepoints", PACKET_DISABLE, remote_fast_tracepoint_feature,
3702 PACKET_FastTracepoints },
0fb4aa4b
PA
3703 { "StaticTracepoints", PACKET_DISABLE, remote_static_tracepoint_feature,
3704 PACKET_StaticTracepoints },
d5551862
SS
3705 { "DisconnectedTracing", PACKET_DISABLE, remote_disconnected_tracing_feature,
3706 -1 },
40ab02ce
MS
3707 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
3708 PACKET_bc },
3709 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
3710 PACKET_bs },
409873ef
SS
3711 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
3712 PACKET_TracepointSource },
d914c394
SS
3713 { "QAllow", PACKET_DISABLE, remote_supported_packet,
3714 PACKET_QAllow },
be2a5f71
DJ
3715};
3716
c8d5aac9
L
3717static char *remote_support_xml;
3718
3719/* Register string appended to "xmlRegisters=" in qSupported query. */
3720
3721void
6e39997a 3722register_remote_support_xml (const char *xml)
c8d5aac9
L
3723{
3724#if defined(HAVE_LIBEXPAT)
3725 if (remote_support_xml == NULL)
c4f7c687 3726 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
3727 else
3728 {
3729 char *copy = xstrdup (remote_support_xml + 13);
3730 char *p = strtok (copy, ",");
3731
3732 do
3733 {
3734 if (strcmp (p, xml) == 0)
3735 {
3736 /* already there */
3737 xfree (copy);
3738 return;
3739 }
3740 }
3741 while ((p = strtok (NULL, ",")) != NULL);
3742 xfree (copy);
3743
94b0dee1
PA
3744 remote_support_xml = reconcat (remote_support_xml,
3745 remote_support_xml, ",", xml,
3746 (char *) NULL);
c8d5aac9
L
3747 }
3748#endif
3749}
3750
3751static char *
3752remote_query_supported_append (char *msg, const char *append)
3753{
3754 if (msg)
94b0dee1 3755 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
3756 else
3757 return xstrdup (append);
3758}
3759
be2a5f71
DJ
3760static void
3761remote_query_supported (void)
3762{
3763 struct remote_state *rs = get_remote_state ();
3764 char *next;
3765 int i;
3766 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
3767
3768 /* The packet support flags are handled differently for this packet
3769 than for most others. We treat an error, a disabled packet, and
3770 an empty response identically: any features which must be reported
3771 to be used will be automatically disabled. An empty buffer
3772 accomplishes this, since that is also the representation for a list
3773 containing no features. */
3774
3775 rs->buf[0] = 0;
3776 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
3777 {
c8d5aac9 3778 char *q = NULL;
94b0dee1 3779 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9
L
3780
3781 if (rs->extended)
3782 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9
L
3783
3784 if (remote_support_xml)
3785 q = remote_query_supported_append (q, remote_support_xml);
3786
dde08ee1
PA
3787 q = remote_query_supported_append (q, "qRelocInsn+");
3788
3789 q = reconcat (q, "qSupported:", q, (char *) NULL);
3790 putpkt (q);
82f73884 3791
94b0dee1
PA
3792 do_cleanups (old_chain);
3793
be2a5f71
DJ
3794 getpkt (&rs->buf, &rs->buf_size, 0);
3795
3796 /* If an error occured, warn, but do not return - just reset the
3797 buffer to empty and go on to disable features. */
3798 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
3799 == PACKET_ERROR)
3800 {
3801 warning (_("Remote failure reply: %s"), rs->buf);
3802 rs->buf[0] = 0;
3803 }
3804 }
3805
3806 memset (seen, 0, sizeof (seen));
3807
3808 next = rs->buf;
3809 while (*next)
3810 {
3811 enum packet_support is_supported;
3812 char *p, *end, *name_end, *value;
3813
3814 /* First separate out this item from the rest of the packet. If
3815 there's another item after this, we overwrite the separator
3816 (terminated strings are much easier to work with). */
3817 p = next;
3818 end = strchr (p, ';');
3819 if (end == NULL)
3820 {
3821 end = p + strlen (p);
3822 next = end;
3823 }
3824 else
3825 {
89be2091
DJ
3826 *end = '\0';
3827 next = end + 1;
3828
be2a5f71
DJ
3829 if (end == p)
3830 {
3831 warning (_("empty item in \"qSupported\" response"));
3832 continue;
3833 }
be2a5f71
DJ
3834 }
3835
3836 name_end = strchr (p, '=');
3837 if (name_end)
3838 {
3839 /* This is a name=value entry. */
3840 is_supported = PACKET_ENABLE;
3841 value = name_end + 1;
3842 *name_end = '\0';
3843 }
3844 else
3845 {
3846 value = NULL;
3847 switch (end[-1])
3848 {
3849 case '+':
3850 is_supported = PACKET_ENABLE;
3851 break;
3852
3853 case '-':
3854 is_supported = PACKET_DISABLE;
3855 break;
3856
3857 case '?':
3858 is_supported = PACKET_SUPPORT_UNKNOWN;
3859 break;
3860
3861 default:
3e43a32a
MS
3862 warning (_("unrecognized item \"%s\" "
3863 "in \"qSupported\" response"), p);
be2a5f71
DJ
3864 continue;
3865 }
3866 end[-1] = '\0';
3867 }
3868
3869 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
3870 if (strcmp (remote_protocol_features[i].name, p) == 0)
3871 {
3872 const struct protocol_feature *feature;
3873
3874 seen[i] = 1;
3875 feature = &remote_protocol_features[i];
3876 feature->func (feature, is_supported, value);
3877 break;
3878 }
3879 }
3880
3881 /* If we increased the packet size, make sure to increase the global
3882 buffer size also. We delay this until after parsing the entire
3883 qSupported packet, because this is the same buffer we were
3884 parsing. */
3885 if (rs->buf_size < rs->explicit_packet_size)
3886 {
3887 rs->buf_size = rs->explicit_packet_size;
3888 rs->buf = xrealloc (rs->buf, rs->buf_size);
3889 }
3890
3891 /* Handle the defaults for unmentioned features. */
3892 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
3893 if (!seen[i])
3894 {
3895 const struct protocol_feature *feature;
3896
3897 feature = &remote_protocol_features[i];
3898 feature->func (feature, feature->default_support, NULL);
3899 }
3900}
3901
3902
c906108c 3903static void
3e43a32a
MS
3904remote_open_1 (char *name, int from_tty,
3905 struct target_ops *target, int extended_p)
c906108c 3906{
d01949b6 3907 struct remote_state *rs = get_remote_state ();
a6f3e723 3908
c906108c 3909 if (name == 0)
8a3fe4f8 3910 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 3911 "serial device is attached to the remote system\n"
8a3fe4f8 3912 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 3913
23860348 3914 /* See FIXME above. */
c6ebd6cf 3915 if (!target_async_permitted)
92d1e331 3916 wait_forever_enabled_p = 1;
6426a772 3917
2d717e4f
DJ
3918 /* If we're connected to a running target, target_preopen will kill it.
3919 But if we're connected to a target system with no running process,
3920 then we will still be connected when it returns. Ask this question
3921 first, before target_preopen has a chance to kill anything. */
c35b1492 3922 if (remote_desc != NULL && !have_inferiors ())
2d717e4f
DJ
3923 {
3924 if (!from_tty
3925 || query (_("Already connected to a remote target. Disconnect? ")))
3926 pop_target ();
3927 else
3928 error (_("Still connected."));
3929 }
3930
c906108c
SS
3931 target_preopen (from_tty);
3932
3933 unpush_target (target);
3934
2d717e4f
DJ
3935 /* This time without a query. If we were connected to an
3936 extended-remote target and target_preopen killed the running
3937 process, we may still be connected. If we are starting "target
3938 remote" now, the extended-remote target will not have been
3939 removed by unpush_target. */
c35b1492 3940 if (remote_desc != NULL && !have_inferiors ())
2d717e4f
DJ
3941 pop_target ();
3942
89be2091
DJ
3943 /* Make sure we send the passed signals list the next time we resume. */
3944 xfree (last_pass_packet);
3945 last_pass_packet = NULL;
3946
ad9a8f3f 3947 remote_fileio_reset ();
1dd41f16
NS
3948 reopen_exec_file ();
3949 reread_symbols ();
3950
9db8d71f 3951 remote_desc = remote_serial_open (name);
c906108c
SS
3952 if (!remote_desc)
3953 perror_with_name (name);
3954
3955 if (baud_rate != -1)
3956 {
2cd58942 3957 if (serial_setbaudrate (remote_desc, baud_rate))
c906108c 3958 {
9b74d5d3
KB
3959 /* The requested speed could not be set. Error out to
3960 top level after closing remote_desc. Take care to
3961 set remote_desc to NULL to avoid closing remote_desc
3962 more than once. */
2cd58942 3963 serial_close (remote_desc);
9b74d5d3 3964 remote_desc = NULL;
c906108c
SS
3965 perror_with_name (name);
3966 }
3967 }
3968
2cd58942 3969 serial_raw (remote_desc);
c906108c
SS
3970
3971 /* If there is something sitting in the buffer we might take it as a
3972 response to a command, which would be bad. */
2cd58942 3973 serial_flush_input (remote_desc);
c906108c
SS
3974
3975 if (from_tty)
3976 {
3977 puts_filtered ("Remote debugging using ");
3978 puts_filtered (name);
3979 puts_filtered ("\n");
3980 }
23860348 3981 push_target (target); /* Switch to using remote target now. */
c906108c 3982
74531fed
PA
3983 /* Register extra event sources in the event loop. */
3984 remote_async_inferior_event_token
3985 = create_async_event_handler (remote_async_inferior_event_handler,
3986 NULL);
3987 remote_async_get_pending_events_token
3988 = create_async_event_handler (remote_async_get_pending_events_handler,
3989 NULL);
3990
be2a5f71
DJ
3991 /* Reset the target state; these things will be queried either by
3992 remote_query_supported or as they are needed. */
d471ea57 3993 init_all_packet_configs ();
74531fed 3994 rs->cached_wait_status = 0;
be2a5f71 3995 rs->explicit_packet_size = 0;
a6f3e723 3996 rs->noack_mode = 0;
82f73884
PA
3997 rs->multi_process_aware = 0;
3998 rs->extended = extended_p;
74531fed 3999 rs->non_stop_aware = 0;
e24a49d8 4000 rs->waiting_for_stop_reply = 0;
3a29589a 4001 rs->ctrlc_pending_p = 0;
802188a7 4002
79d7f229
PA
4003 general_thread = not_sent_ptid;
4004 continue_thread = not_sent_ptid;
c906108c 4005
9d1f7ab2
MS
4006 /* Probe for ability to use "ThreadInfo" query, as required. */
4007 use_threadinfo_query = 1;
4008 use_threadextra_query = 1;
4009
c6ebd6cf 4010 if (target_async_permitted)
92d1e331 4011 {
23860348 4012 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4013 remote_async_terminal_ours_p = 1;
4014
4015 /* FIXME: cagney/1999-09-23: During the initial connection it is
4016 assumed that the target is already ready and able to respond to
0df8b418 4017 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4018 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4019 around this. Eventually a mechanism that allows
92d1e331 4020 wait_for_inferior() to expect/get timeouts will be
23860348 4021 implemented. */
92d1e331
DJ
4022 wait_forever_enabled_p = 0;
4023 }
4024
23860348 4025 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4026 no_shared_libraries (NULL, 0);
f78f6cf1 4027
74531fed
PA
4028 /* Start afresh. */
4029 init_thread_list ();
4030
36918e70 4031 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4032 target (we'd otherwise be in an inconsistent state) and then
4033 propogate the error on up the exception chain. This ensures that
4034 the caller doesn't stumble along blindly assuming that the
4035 function succeeded. The CLI doesn't have this problem but other
4036 UI's, such as MI do.
36918e70
AC
4037
4038 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4039 this function should return an error indication letting the
ce2826aa 4040 caller restore the previous state. Unfortunately the command
36918e70
AC
4041 ``target remote'' is directly wired to this function making that
4042 impossible. On a positive note, the CLI side of this problem has
4043 been fixed - the function set_cmd_context() makes it possible for
4044 all the ``target ....'' commands to share a common callback
4045 function. See cli-dump.c. */
109c3e39 4046 {
2d717e4f
DJ
4047 struct gdb_exception ex;
4048 struct start_remote_args args;
4049
4050 args.from_tty = from_tty;
4051 args.target = target;
4052 args.extended_p = extended_p;
4053
4054 ex = catch_exception (uiout, remote_start_remote, &args, RETURN_MASK_ALL);
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. */
0d8f58ca 4460 p = 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. */
4475 p = append_resumption (p, endp, ptid, /*step=*/ 0, TARGET_SIGNAL_0);
c906108c
SS
4476 }
4477 else
506fb367
DJ
4478 {
4479 /* Scheduler locking; resume only PTID. */
0d8f58ca 4480 p = 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)
4536 warning (" - Can't pass signal %d to target in reverse: ignored.\n",
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
4707 p = write_ptid (p, endp, nptid);
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
74ca34ce 5773static void
28439f5e
PA
5774remote_fetch_registers (struct target_ops *ops,
5775 struct regcache *regcache, int regnum)
74ca34ce 5776{
74ca34ce
DJ
5777 struct remote_arch_state *rsa = get_remote_arch_state ();
5778 int i;
5779
79d7f229 5780 set_general_thread (inferior_ptid);
74ca34ce
DJ
5781
5782 if (regnum >= 0)
5783 {
5784 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 5785
74ca34ce
DJ
5786 gdb_assert (reg != NULL);
5787
5788 /* If this register might be in the 'g' packet, try that first -
5789 we are likely to read more than one register. If this is the
5790 first 'g' packet, we might be overly optimistic about its
5791 contents, so fall back to 'p'. */
5792 if (reg->in_g_packet)
5793 {
56be3814 5794 fetch_registers_using_g (regcache);
74ca34ce
DJ
5795 if (reg->in_g_packet)
5796 return;
5797 }
5798
56be3814 5799 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
5800 return;
5801
5802 /* This register is not available. */
56be3814 5803 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
5804
5805 return;
5806 }
5807
56be3814 5808 fetch_registers_using_g (regcache);
74ca34ce 5809
4a22f64d 5810 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 5811 if (!rsa->regs[i].in_g_packet)
56be3814 5812 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
5813 {
5814 /* This register is not available. */
56be3814 5815 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
5816 }
5817}
5818
c906108c
SS
5819/* Prepare to store registers. Since we may send them all (using a
5820 'G' request), we have to read out the ones we don't want to change
5821 first. */
5822
c5aa993b 5823static void
316f2060 5824remote_prepare_to_store (struct regcache *regcache)
c906108c 5825{
ea9c271d 5826 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 5827 int i;
cfd77fa1 5828 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 5829
c906108c 5830 /* Make sure the entire registers array is valid. */
444abaca 5831 switch (remote_protocol_packets[PACKET_P].support)
5a2468f5
JM
5832 {
5833 case PACKET_DISABLE:
5834 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 5835 /* Make sure all the necessary registers are cached. */
4a22f64d 5836 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 5837 if (rsa->regs[i].in_g_packet)
316f2060 5838 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
5839 break;
5840 case PACKET_ENABLE:
5841 break;
5842 }
5843}
5844
ad10f812 5845/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 5846 packet was not recognized. */
5a2468f5
JM
5847
5848static int
1f4437a4
MS
5849store_register_using_P (const struct regcache *regcache,
5850 struct packet_reg *reg)
5a2468f5 5851{
4a22f64d 5852 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 5853 struct remote_state *rs = get_remote_state ();
5a2468f5 5854 /* Try storing a single register. */
6d820c5c 5855 char *buf = rs->buf;
cfd77fa1 5856 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 5857 char *p;
5a2468f5 5858
74ca34ce
DJ
5859 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
5860 return 0;
5861
5862 if (reg->pnum == -1)
5863 return 0;
5864
ea9c271d 5865 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 5866 p = buf + strlen (buf);
56be3814 5867 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 5868 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
5869 putpkt (rs->buf);
5870 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 5871
74ca34ce
DJ
5872 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
5873 {
5874 case PACKET_OK:
5875 return 1;
5876 case PACKET_ERROR:
27a9c0bf
MS
5877 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
5878 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
5879 case PACKET_UNKNOWN:
5880 return 0;
5881 default:
5882 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
5883 }
c906108c
SS
5884}
5885
23860348
MS
5886/* Store register REGNUM, or all registers if REGNUM == -1, from the
5887 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
5888
5889static void
56be3814 5890store_registers_using_G (const struct regcache *regcache)
c906108c 5891{
d01949b6 5892 struct remote_state *rs = get_remote_state ();
ea9c271d 5893 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 5894 gdb_byte *regs;
c906108c
SS
5895 char *p;
5896
193cb69f
AC
5897 /* Extract all the registers in the regcache copying them into a
5898 local buffer. */
5899 {
b323314b 5900 int i;
a744cf53 5901
ea9c271d
DJ
5902 regs = alloca (rsa->sizeof_g_packet);
5903 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 5904 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 5905 {
ea9c271d 5906 struct packet_reg *r = &rsa->regs[i];
a744cf53 5907
b323314b 5908 if (r->in_g_packet)
56be3814 5909 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
5910 }
5911 }
c906108c
SS
5912
5913 /* Command describes registers byte by byte,
5914 each byte encoded as two hex characters. */
6d820c5c 5915 p = rs->buf;
193cb69f 5916 *p++ = 'G';
74ca34ce
DJ
5917 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
5918 updated. */
5919 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
5920 putpkt (rs->buf);
5921 getpkt (&rs->buf, &rs->buf_size, 0);
5922 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
5923 error (_("Could not write registers; remote failure reply '%s'"),
5924 rs->buf);
c906108c 5925}
74ca34ce
DJ
5926
5927/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
5928 of the register cache buffer. FIXME: ignores errors. */
5929
5930static void
28439f5e
PA
5931remote_store_registers (struct target_ops *ops,
5932 struct regcache *regcache, int regnum)
74ca34ce 5933{
74ca34ce
DJ
5934 struct remote_arch_state *rsa = get_remote_arch_state ();
5935 int i;
5936
79d7f229 5937 set_general_thread (inferior_ptid);
74ca34ce
DJ
5938
5939 if (regnum >= 0)
5940 {
5941 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 5942
74ca34ce
DJ
5943 gdb_assert (reg != NULL);
5944
5945 /* Always prefer to store registers using the 'P' packet if
5946 possible; we often change only a small number of registers.
5947 Sometimes we change a larger number; we'd need help from a
5948 higher layer to know to use 'G'. */
56be3814 5949 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
5950 return;
5951
5952 /* For now, don't complain if we have no way to write the
5953 register. GDB loses track of unavailable registers too
5954 easily. Some day, this may be an error. We don't have
0df8b418 5955 any way to read the register, either... */
74ca34ce
DJ
5956 if (!reg->in_g_packet)
5957 return;
5958
56be3814 5959 store_registers_using_G (regcache);
74ca34ce
DJ
5960 return;
5961 }
5962
56be3814 5963 store_registers_using_G (regcache);
74ca34ce 5964
4a22f64d 5965 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 5966 if (!rsa->regs[i].in_g_packet)
56be3814 5967 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
5968 /* See above for why we do not issue an error here. */
5969 continue;
5970}
c906108c
SS
5971\f
5972
5973/* Return the number of hex digits in num. */
5974
5975static int
fba45db2 5976hexnumlen (ULONGEST num)
c906108c
SS
5977{
5978 int i;
5979
5980 for (i = 0; num != 0; i++)
5981 num >>= 4;
5982
5983 return max (i, 1);
5984}
5985
2df3850c 5986/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
5987
5988static int
fba45db2 5989hexnumstr (char *buf, ULONGEST num)
c906108c 5990{
c906108c 5991 int len = hexnumlen (num);
a744cf53 5992
2df3850c
JM
5993 return hexnumnstr (buf, num, len);
5994}
5995
c906108c 5996
2df3850c 5997/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 5998
2df3850c 5999static int
fba45db2 6000hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
6001{
6002 int i;
6003
6004 buf[width] = '\0';
6005
6006 for (i = width - 1; i >= 0; i--)
c906108c 6007 {
c5aa993b 6008 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
6009 num >>= 4;
6010 }
6011
2df3850c 6012 return width;
c906108c
SS
6013}
6014
23860348 6015/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
6016
6017static CORE_ADDR
fba45db2 6018remote_address_masked (CORE_ADDR addr)
c906108c 6019{
911c95a5 6020 int address_size = remote_address_size;
a744cf53 6021
911c95a5
UW
6022 /* If "remoteaddresssize" was not set, default to target address size. */
6023 if (!address_size)
1cf3db46 6024 address_size = gdbarch_addr_bit (target_gdbarch);
911c95a5
UW
6025
6026 if (address_size > 0
6027 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
6028 {
6029 /* Only create a mask when that mask can safely be constructed
23860348 6030 in a ULONGEST variable. */
c906108c 6031 ULONGEST mask = 1;
a744cf53 6032
911c95a5 6033 mask = (mask << address_size) - 1;
c906108c
SS
6034 addr &= mask;
6035 }
6036 return addr;
6037}
6038
a31ea83d
DJ
6039/* Convert BUFFER, binary data at least LEN bytes long, into escaped
6040 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
6041 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
6042 (which may be more than *OUT_LEN due to escape characters). The
6043 total number of bytes in the output buffer will be at most
6044 OUT_MAXLEN. */
6045
6046static int
6047remote_escape_output (const gdb_byte *buffer, int len,
6048 gdb_byte *out_buf, int *out_len,
6049 int out_maxlen)
6050{
6051 int input_index, output_index;
6052
6053 output_index = 0;
6054 for (input_index = 0; input_index < len; input_index++)
6055 {
6056 gdb_byte b = buffer[input_index];
6057
6058 if (b == '$' || b == '#' || b == '}')
6059 {
6060 /* These must be escaped. */
6061 if (output_index + 2 > out_maxlen)
6062 break;
6063 out_buf[output_index++] = '}';
6064 out_buf[output_index++] = b ^ 0x20;
6065 }
6066 else
6067 {
6068 if (output_index + 1 > out_maxlen)
6069 break;
6070 out_buf[output_index++] = b;
6071 }
6072 }
6073
6074 *out_len = input_index;
6075 return output_index;
6076}
6077
0876f84a
DJ
6078/* Convert BUFFER, escaped data LEN bytes long, into binary data
6079 in OUT_BUF. Return the number of bytes written to OUT_BUF.
6080 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
6081
6082 This function reverses remote_escape_output. It allows more
6083 escaped characters than that function does, in particular because
6084 '*' must be escaped to avoid the run-length encoding processing
6085 in reading packets. */
6086
6087static int
6088remote_unescape_input (const gdb_byte *buffer, int len,
6089 gdb_byte *out_buf, int out_maxlen)
6090{
6091 int input_index, output_index;
6092 int escaped;
6093
6094 output_index = 0;
6095 escaped = 0;
6096 for (input_index = 0; input_index < len; input_index++)
6097 {
6098 gdb_byte b = buffer[input_index];
6099
6100 if (output_index + 1 > out_maxlen)
6101 {
6102 warning (_("Received too much data from remote target;"
6103 " ignoring overflow."));
6104 return output_index;
6105 }
6106
6107 if (escaped)
6108 {
6109 out_buf[output_index++] = b ^ 0x20;
6110 escaped = 0;
6111 }
6112 else if (b == '}')
6113 escaped = 1;
6114 else
6115 out_buf[output_index++] = b;
6116 }
6117
6118 if (escaped)
6119 error (_("Unmatched escape character in target response."));
6120
6121 return output_index;
6122}
6123
c906108c
SS
6124/* Determine whether the remote target supports binary downloading.
6125 This is accomplished by sending a no-op memory write of zero length
6126 to the target at the specified address. It does not suffice to send
23860348
MS
6127 the whole packet, since many stubs strip the eighth bit and
6128 subsequently compute a wrong checksum, which causes real havoc with
6129 remote_write_bytes.
7a292a7a 6130
96baa820 6131 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 6132 clean. In cases like this, the user should clear "remote
23860348 6133 X-packet". */
96baa820 6134
c906108c 6135static void
fba45db2 6136check_binary_download (CORE_ADDR addr)
c906108c 6137{
d01949b6 6138 struct remote_state *rs = get_remote_state ();
24b06219 6139
444abaca 6140 switch (remote_protocol_packets[PACKET_X].support)
c906108c 6141 {
96baa820
JM
6142 case PACKET_DISABLE:
6143 break;
6144 case PACKET_ENABLE:
6145 break;
6146 case PACKET_SUPPORT_UNKNOWN:
6147 {
96baa820 6148 char *p;
802188a7 6149
2e9f7625 6150 p = rs->buf;
96baa820
JM
6151 *p++ = 'X';
6152 p += hexnumstr (p, (ULONGEST) addr);
6153 *p++ = ',';
6154 p += hexnumstr (p, (ULONGEST) 0);
6155 *p++ = ':';
6156 *p = '\0';
802188a7 6157
2e9f7625 6158 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 6159 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 6160
2e9f7625 6161 if (rs->buf[0] == '\0')
96baa820
JM
6162 {
6163 if (remote_debug)
6164 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
6165 "binary downloading NOT "
6166 "supported by target\n");
444abaca 6167 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
6168 }
6169 else
6170 {
6171 if (remote_debug)
6172 fprintf_unfiltered (gdb_stdlog,
6173 "binary downloading suppported by target\n");
444abaca 6174 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
6175 }
6176 break;
6177 }
c906108c
SS
6178 }
6179}
6180
6181/* Write memory data directly to the remote machine.
6182 This does not inform the data cache; the data cache uses this.
a76d924d 6183 HEADER is the starting part of the packet.
c906108c
SS
6184 MEMADDR is the address in the remote memory space.
6185 MYADDR is the address of the buffer in our space.
6186 LEN is the number of bytes.
a76d924d
DJ
6187 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6188 should send data as binary ('X'), or hex-encoded ('M').
6189
6190 The function creates packet of the form
6191 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6192
6193 where encoding of <DATA> is termined by PACKET_FORMAT.
6194
6195 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6196 are omitted.
6197
6198 Returns the number of bytes transferred, or 0 (setting errno) for
23860348 6199 error. Only transfer a single packet. */
c906108c 6200
a76d924d
DJ
6201static int
6202remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
6203 const gdb_byte *myaddr, int len,
6204 char packet_format, int use_length)
c906108c 6205{
6d820c5c 6206 struct remote_state *rs = get_remote_state ();
cfd77fa1 6207 char *p;
a76d924d
DJ
6208 char *plen = NULL;
6209 int plenlen = 0;
917317f4
JM
6210 int todo;
6211 int nr_bytes;
a257b5bb 6212 int payload_size;
6765f3e5 6213 int payload_length;
a76d924d
DJ
6214 int header_length;
6215
6216 if (packet_format != 'X' && packet_format != 'M')
6217 internal_error (__FILE__, __LINE__,
9b20d036 6218 _("remote_write_bytes_aux: bad packet format"));
c906108c 6219
b2182ed2
DJ
6220 if (len <= 0)
6221 return 0;
6222
3de11b2e 6223 payload_size = get_memory_write_packet_size ();
2bc416ba 6224
6d820c5c
DJ
6225 /* The packet buffer will be large enough for the payload;
6226 get_memory_packet_size ensures this. */
a76d924d 6227 rs->buf[0] = '\0';
c906108c 6228
a257b5bb 6229 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
6230 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6231
a76d924d
DJ
6232 payload_size -= strlen ("$,:#NN");
6233 if (!use_length)
0df8b418 6234 /* The comma won't be used. */
a76d924d
DJ
6235 payload_size += 1;
6236 header_length = strlen (header);
6237 payload_size -= header_length;
3de11b2e 6238 payload_size -= hexnumlen (memaddr);
c906108c 6239
a76d924d 6240 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 6241
a76d924d
DJ
6242 strcat (rs->buf, header);
6243 p = rs->buf + strlen (header);
6244
6245 /* Compute a best guess of the number of bytes actually transfered. */
6246 if (packet_format == 'X')
c906108c 6247 {
23860348 6248 /* Best guess at number of bytes that will fit. */
a257b5bb 6249 todo = min (len, payload_size);
a76d924d
DJ
6250 if (use_length)
6251 payload_size -= hexnumlen (todo);
3de11b2e 6252 todo = min (todo, payload_size);
a76d924d
DJ
6253 }
6254 else
6255 {
23860348 6256 /* Num bytes that will fit. */
a257b5bb 6257 todo = min (len, payload_size / 2);
a76d924d
DJ
6258 if (use_length)
6259 payload_size -= hexnumlen (todo);
3de11b2e 6260 todo = min (todo, payload_size / 2);
917317f4 6261 }
a76d924d 6262
3de11b2e
NS
6263 if (todo <= 0)
6264 internal_error (__FILE__, __LINE__,
6265 _("minumum packet size too small to write data"));
802188a7 6266
6765f3e5
DJ
6267 /* If we already need another packet, then try to align the end
6268 of this packet to a useful boundary. */
6269 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6270 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6271
a257b5bb 6272 /* Append "<memaddr>". */
917317f4
JM
6273 memaddr = remote_address_masked (memaddr);
6274 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 6275
a76d924d
DJ
6276 if (use_length)
6277 {
6278 /* Append ",". */
6279 *p++ = ',';
802188a7 6280
a76d924d
DJ
6281 /* Append <len>. Retain the location/size of <len>. It may need to
6282 be adjusted once the packet body has been created. */
6283 plen = p;
6284 plenlen = hexnumstr (p, (ULONGEST) todo);
6285 p += plenlen;
6286 }
a257b5bb
AC
6287
6288 /* Append ":". */
917317f4
JM
6289 *p++ = ':';
6290 *p = '\0';
802188a7 6291
a257b5bb 6292 /* Append the packet body. */
a76d924d 6293 if (packet_format == 'X')
917317f4 6294 {
917317f4
JM
6295 /* Binary mode. Send target system values byte by byte, in
6296 increasing byte addresses. Only escape certain critical
6297 characters. */
6765f3e5
DJ
6298 payload_length = remote_escape_output (myaddr, todo, p, &nr_bytes,
6299 payload_size);
6300
6301 /* If not all TODO bytes fit, then we'll need another packet. Make
9b7194bc
DJ
6302 a second try to keep the end of the packet aligned. Don't do
6303 this if the packet is tiny. */
6304 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6765f3e5
DJ
6305 {
6306 int new_nr_bytes;
6307
6308 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6309 - memaddr);
6310 if (new_nr_bytes != nr_bytes)
6311 payload_length = remote_escape_output (myaddr, new_nr_bytes,
6312 p, &nr_bytes,
6313 payload_size);
6314 }
6315
6316 p += payload_length;
a76d924d 6317 if (use_length && nr_bytes < todo)
c906108c 6318 {
802188a7 6319 /* Escape chars have filled up the buffer prematurely,
917317f4
JM
6320 and we have actually sent fewer bytes than planned.
6321 Fix-up the length field of the packet. Use the same
6322 number of characters as before. */
917317f4
JM
6323 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6324 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 6325 }
a76d924d
DJ
6326 }
6327 else
6328 {
917317f4
JM
6329 /* Normal mode: Send target system values byte by byte, in
6330 increasing byte addresses. Each byte is encoded as a two hex
6331 value. */
2644f393 6332 nr_bytes = bin2hex (myaddr, p, todo);
aa6c0017 6333 p += 2 * nr_bytes;
c906108c 6334 }
802188a7 6335
2e9f7625 6336 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 6337 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 6338
2e9f7625 6339 if (rs->buf[0] == 'E')
917317f4
JM
6340 {
6341 /* There is no correspondance between what the remote protocol
6342 uses for errors and errno codes. We would like a cleaner way
6343 of representing errors (big enough to include errno codes,
6344 bfd_error codes, and others). But for now just return EIO. */
6345 errno = EIO;
6346 return 0;
6347 }
802188a7 6348
23860348
MS
6349 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6350 fewer bytes than we'd planned. */
917317f4 6351 return nr_bytes;
c906108c
SS
6352}
6353
a76d924d
DJ
6354/* Write memory data directly to the remote machine.
6355 This does not inform the data cache; the data cache uses this.
6356 MEMADDR is the address in the remote memory space.
6357 MYADDR is the address of the buffer in our space.
6358 LEN is the number of bytes.
6359
6360 Returns number of bytes transferred, or 0 (setting errno) for
6361 error. Only transfer a single packet. */
6362
f7605bc2 6363static int
a76d924d
DJ
6364remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
6365{
6366 char *packet_format = 0;
6367
6368 /* Check whether the target supports binary download. */
6369 check_binary_download (memaddr);
6370
6371 switch (remote_protocol_packets[PACKET_X].support)
6372 {
6373 case PACKET_ENABLE:
6374 packet_format = "X";
6375 break;
6376 case PACKET_DISABLE:
6377 packet_format = "M";
6378 break;
6379 case PACKET_SUPPORT_UNKNOWN:
6380 internal_error (__FILE__, __LINE__,
6381 _("remote_write_bytes: bad internal state"));
6382 default:
6383 internal_error (__FILE__, __LINE__, _("bad switch"));
6384 }
6385
6386 return remote_write_bytes_aux (packet_format,
6387 memaddr, myaddr, len, packet_format[0], 1);
6388}
6389
c906108c
SS
6390/* Read memory data directly from the remote machine.
6391 This does not use the data cache; the data cache uses this.
6392 MEMADDR is the address in the remote memory space.
6393 MYADDR is the address of the buffer in our space.
6394 LEN is the number of bytes.
6395
6396 Returns number of bytes transferred, or 0 for error. */
6397
f7605bc2 6398static int
cfd77fa1 6399remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
c906108c 6400{
6d820c5c 6401 struct remote_state *rs = get_remote_state ();
23860348 6402 int max_buf_size; /* Max size of packet output buffer. */
f7605bc2
PA
6403 char *p;
6404 int todo;
6405 int i;
c906108c 6406
b2182ed2
DJ
6407 if (len <= 0)
6408 return 0;
6409
11cf8741 6410 max_buf_size = get_memory_read_packet_size ();
6d820c5c
DJ
6411 /* The packet buffer will be large enough for the payload;
6412 get_memory_packet_size ensures this. */
c906108c 6413
f7605bc2
PA
6414 /* Number if bytes that will fit. */
6415 todo = min (len, max_buf_size / 2);
c906108c 6416
f7605bc2
PA
6417 /* Construct "m"<memaddr>","<len>". */
6418 memaddr = remote_address_masked (memaddr);
6419 p = rs->buf;
6420 *p++ = 'm';
6421 p += hexnumstr (p, (ULONGEST) memaddr);
6422 *p++ = ',';
6423 p += hexnumstr (p, (ULONGEST) todo);
6424 *p = '\0';
6425 putpkt (rs->buf);
6426 getpkt (&rs->buf, &rs->buf_size, 0);
6427 if (rs->buf[0] == 'E'
6428 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6429 && rs->buf[3] == '\0')
6430 {
6431 /* There is no correspondance between what the remote protocol
6432 uses for errors and errno codes. We would like a cleaner way
6433 of representing errors (big enough to include errno codes,
6434 bfd_error codes, and others). But for now just return
6435 EIO. */
6436 errno = EIO;
6437 return 0;
c906108c 6438 }
f7605bc2
PA
6439 /* Reply describes memory byte by byte, each byte encoded as two hex
6440 characters. */
6441 p = rs->buf;
6442 i = hex2bin (p, myaddr, todo);
6443 /* Return what we have. Let higher layers handle partial reads. */
6444 return i;
c906108c 6445}
74531fed
PA
6446\f
6447
6448/* Remote notification handler. */
6449
6450static void
6451handle_notification (char *buf, size_t length)
6452{
6453 if (strncmp (buf, "Stop:", 5) == 0)
6454 {
6455 if (pending_stop_reply)
0723dbf5
PA
6456 {
6457 /* We've already parsed the in-flight stop-reply, but the
6458 stub for some reason thought we didn't, possibly due to
6459 timeout on its side. Just ignore it. */
6460 if (remote_debug)
6461 fprintf_unfiltered (gdb_stdlog, "ignoring resent notification\n");
6462 }
74531fed
PA
6463 else
6464 {
6465 struct cleanup *old_chain;
6466 struct stop_reply *reply = stop_reply_xmalloc ();
a744cf53 6467
74531fed
PA
6468 old_chain = make_cleanup (do_stop_reply_xfree, reply);
6469
6470 remote_parse_stop_reply (buf + 5, reply);
6471
6472 discard_cleanups (old_chain);
6473
6474 /* Be careful to only set it after parsing, since an error
6475 may be thrown then. */
6476 pending_stop_reply = reply;
6477
6478 /* Notify the event loop there's a stop reply to acknowledge
6479 and that there may be more events to fetch. */
6480 mark_async_event_handler (remote_async_get_pending_events_token);
0723dbf5
PA
6481
6482 if (remote_debug)
6483 fprintf_unfiltered (gdb_stdlog, "stop notification captured\n");
74531fed
PA
6484 }
6485 }
6486 else
6487 /* We ignore notifications we don't recognize, for compatibility
6488 with newer stubs. */
6489 ;
6490}
6491
c906108c
SS
6492\f
6493/* Read or write LEN bytes from inferior memory at MEMADDR,
23860348
MS
6494 transferring to or from debugger address BUFFER. Write to inferior
6495 if SHOULD_WRITE is nonzero. Returns length of data written or
6496 read; 0 for error. TARGET is unused. */
392a587b 6497
c906108c 6498static int
961cb7b5 6499remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
0a65a603 6500 int should_write, struct mem_attrib *attrib,
29e57380 6501 struct target_ops *target)
c906108c 6502{
4930751a
C
6503 int res;
6504
82f73884
PA
6505 set_general_thread (inferior_ptid);
6506
4930751a 6507 if (should_write)
b2182ed2 6508 res = remote_write_bytes (mem_addr, buffer, mem_len);
4930751a 6509 else
b2182ed2 6510 res = remote_read_bytes (mem_addr, buffer, mem_len);
4930751a
C
6511
6512 return res;
c906108c
SS
6513}
6514
a76d924d
DJ
6515/* Sends a packet with content determined by the printf format string
6516 FORMAT and the remaining arguments, then gets the reply. Returns
6517 whether the packet was a success, a failure, or unknown. */
6518
2c0b251b 6519static enum packet_result
a76d924d
DJ
6520remote_send_printf (const char *format, ...)
6521{
6522 struct remote_state *rs = get_remote_state ();
6523 int max_size = get_remote_packet_size ();
a76d924d 6524 va_list ap;
a744cf53 6525
a76d924d
DJ
6526 va_start (ap, format);
6527
6528 rs->buf[0] = '\0';
6529 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 6530 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
6531
6532 if (putpkt (rs->buf) < 0)
6533 error (_("Communication problem with target."));
6534
6535 rs->buf[0] = '\0';
6536 getpkt (&rs->buf, &rs->buf_size, 0);
6537
6538 return packet_check_result (rs->buf);
6539}
6540
6541static void
6542restore_remote_timeout (void *p)
6543{
6544 int value = *(int *)p;
a744cf53 6545
a76d924d
DJ
6546 remote_timeout = value;
6547}
6548
6549/* Flash writing can take quite some time. We'll set
6550 effectively infinite timeout for flash operations.
6551 In future, we'll need to decide on a better approach. */
6552static const int remote_flash_timeout = 1000;
6553
6554static void
6555remote_flash_erase (struct target_ops *ops,
6556 ULONGEST address, LONGEST length)
6557{
5af949e3 6558 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
a76d924d
DJ
6559 int saved_remote_timeout = remote_timeout;
6560 enum packet_result ret;
a76d924d
DJ
6561 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6562 &saved_remote_timeout);
a744cf53 6563
a76d924d
DJ
6564 remote_timeout = remote_flash_timeout;
6565
6566 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 6567 phex (address, addr_size),
a76d924d
DJ
6568 phex (length, 4));
6569 switch (ret)
6570 {
6571 case PACKET_UNKNOWN:
6572 error (_("Remote target does not support flash erase"));
6573 case PACKET_ERROR:
6574 error (_("Error erasing flash with vFlashErase packet"));
6575 default:
6576 break;
6577 }
6578
6579 do_cleanups (back_to);
6580}
6581
6582static LONGEST
6583remote_flash_write (struct target_ops *ops,
6584 ULONGEST address, LONGEST length,
6585 const gdb_byte *data)
6586{
6587 int saved_remote_timeout = remote_timeout;
6588 int ret;
6589 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6590 &saved_remote_timeout);
6591
6592 remote_timeout = remote_flash_timeout;
6593 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
6594 do_cleanups (back_to);
6595
6596 return ret;
6597}
6598
6599static void
6600remote_flash_done (struct target_ops *ops)
6601{
6602 int saved_remote_timeout = remote_timeout;
6603 int ret;
6604 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6605 &saved_remote_timeout);
6606
6607 remote_timeout = remote_flash_timeout;
6608 ret = remote_send_printf ("vFlashDone");
6609 do_cleanups (back_to);
6610
6611 switch (ret)
6612 {
6613 case PACKET_UNKNOWN:
6614 error (_("Remote target does not support vFlashDone"));
6615 case PACKET_ERROR:
6616 error (_("Error finishing flash operation"));
6617 default:
6618 break;
6619 }
6620}
6621
c906108c 6622static void
fba45db2 6623remote_files_info (struct target_ops *ignore)
c906108c
SS
6624{
6625 puts_filtered ("Debugging a target over a serial line.\n");
6626}
6627\f
6628/* Stuff for dealing with the packets which are part of this protocol.
6629 See comment at top of file for details. */
6630
0876f84a 6631/* Read a single character from the remote end. */
c906108c
SS
6632
6633static int
fba45db2 6634readchar (int timeout)
c906108c
SS
6635{
6636 int ch;
6637
2cd58942 6638 ch = serial_readchar (remote_desc, timeout);
c906108c 6639
2acceee2 6640 if (ch >= 0)
0876f84a 6641 return ch;
2acceee2
JM
6642
6643 switch ((enum serial_rc) ch)
c906108c
SS
6644 {
6645 case SERIAL_EOF:
ce5ce7ed 6646 pop_target ();
8a3fe4f8 6647 error (_("Remote connection closed"));
2acceee2 6648 /* no return */
c906108c 6649 case SERIAL_ERROR:
4ac8c4da 6650 pop_target ();
3e43a32a
MS
6651 perror_with_name (_("Remote communication error. "
6652 "Target disconnected."));
2acceee2 6653 /* no return */
c906108c 6654 case SERIAL_TIMEOUT:
2acceee2 6655 break;
c906108c 6656 }
2acceee2 6657 return ch;
c906108c
SS
6658}
6659
6d820c5c
DJ
6660/* Send the command in *BUF to the remote machine, and read the reply
6661 into *BUF. Report an error if we get an error reply. Resize
6662 *BUF using xrealloc if necessary to hold the result, and update
6663 *SIZEOF_BUF. */
c906108c
SS
6664
6665static void
6d820c5c
DJ
6666remote_send (char **buf,
6667 long *sizeof_buf)
c906108c 6668{
6d820c5c 6669 putpkt (*buf);
c2d11a7d 6670 getpkt (buf, sizeof_buf, 0);
c906108c 6671
6d820c5c
DJ
6672 if ((*buf)[0] == 'E')
6673 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
6674}
6675
6e5abd65
PA
6676/* Return a pointer to an xmalloc'ed string representing an escaped
6677 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
6678 etc. The caller is responsible for releasing the returned
6679 memory. */
6680
6681static char *
6682escape_buffer (const char *buf, int n)
6683{
6684 struct cleanup *old_chain;
6685 struct ui_file *stb;
6686 char *str;
6e5abd65
PA
6687
6688 stb = mem_fileopen ();
6689 old_chain = make_cleanup_ui_file_delete (stb);
6690
6691 fputstrn_unfiltered (buf, n, 0, stb);
759ef836 6692 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
6693 do_cleanups (old_chain);
6694 return str;
6695}
6696
c906108c
SS
6697/* Display a null-terminated packet on stdout, for debugging, using C
6698 string notation. */
6699
6700static void
fba45db2 6701print_packet (char *buf)
c906108c
SS
6702{
6703 puts_filtered ("\"");
43e526b9 6704 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
6705 puts_filtered ("\"");
6706}
6707
6708int
fba45db2 6709putpkt (char *buf)
c906108c
SS
6710{
6711 return putpkt_binary (buf, strlen (buf));
6712}
6713
6714/* Send a packet to the remote machine, with error checking. The data
23860348 6715 of the packet is in BUF. The string in BUF can be at most
ea9c271d 6716 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
6717 and for a possible /0 if we are debugging (remote_debug) and want
6718 to print the sent packet as a string. */
c906108c
SS
6719
6720static int
fba45db2 6721putpkt_binary (char *buf, int cnt)
c906108c 6722{
2d717e4f 6723 struct remote_state *rs = get_remote_state ();
c906108c
SS
6724 int i;
6725 unsigned char csum = 0;
11cf8741 6726 char *buf2 = alloca (cnt + 6);
085dd6e6 6727
c906108c
SS
6728 int ch;
6729 int tcount = 0;
6730 char *p;
6731
e24a49d8
PA
6732 /* Catch cases like trying to read memory or listing threads while
6733 we're waiting for a stop reply. The remote server wouldn't be
6734 ready to handle this request, so we'd hang and timeout. We don't
6735 have to worry about this in synchronous mode, because in that
6736 case it's not possible to issue a command while the target is
74531fed
PA
6737 running. This is not a problem in non-stop mode, because in that
6738 case, the stub is always ready to process serial input. */
6739 if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
e24a49d8
PA
6740 error (_("Cannot execute this command while the target is running."));
6741
2d717e4f
DJ
6742 /* We're sending out a new packet. Make sure we don't look at a
6743 stale cached response. */
6744 rs->cached_wait_status = 0;
6745
c906108c
SS
6746 /* Copy the packet into buffer BUF2, encapsulating it
6747 and giving it a checksum. */
6748
c906108c
SS
6749 p = buf2;
6750 *p++ = '$';
6751
6752 for (i = 0; i < cnt; i++)
6753 {
6754 csum += buf[i];
6755 *p++ = buf[i];
6756 }
6757 *p++ = '#';
6758 *p++ = tohex ((csum >> 4) & 0xf);
6759 *p++ = tohex (csum & 0xf);
6760
6761 /* Send it over and over until we get a positive ack. */
6762
6763 while (1)
6764 {
6765 int started_error_output = 0;
6766
6767 if (remote_debug)
6768 {
6e5abd65
PA
6769 struct cleanup *old_chain;
6770 char *str;
6771
c906108c 6772 *p = '\0';
6e5abd65
PA
6773 str = escape_buffer (buf2, p - buf2);
6774 old_chain = make_cleanup (xfree, str);
6775 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 6776 gdb_flush (gdb_stdlog);
6e5abd65 6777 do_cleanups (old_chain);
c906108c 6778 }
2cd58942 6779 if (serial_write (remote_desc, buf2, p - buf2))
e2e0b3e5 6780 perror_with_name (_("putpkt: write failed"));
c906108c 6781
a6f3e723
SL
6782 /* If this is a no acks version of the remote protocol, send the
6783 packet and move on. */
6784 if (rs->noack_mode)
6785 break;
6786
74531fed
PA
6787 /* Read until either a timeout occurs (-2) or '+' is read.
6788 Handle any notification that arrives in the mean time. */
c906108c
SS
6789 while (1)
6790 {
6791 ch = readchar (remote_timeout);
6792
c5aa993b 6793 if (remote_debug)
c906108c
SS
6794 {
6795 switch (ch)
6796 {
6797 case '+':
1216fa2c 6798 case '-':
c906108c
SS
6799 case SERIAL_TIMEOUT:
6800 case '$':
74531fed 6801 case '%':
c906108c
SS
6802 if (started_error_output)
6803 {
6804 putchar_unfiltered ('\n');
6805 started_error_output = 0;
6806 }
6807 }
6808 }
6809
6810 switch (ch)
6811 {
6812 case '+':
6813 if (remote_debug)
0f71a2f6 6814 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 6815 return 1;
1216fa2c
AC
6816 case '-':
6817 if (remote_debug)
6818 fprintf_unfiltered (gdb_stdlog, "Nak\n");
c906108c 6819 case SERIAL_TIMEOUT:
c5aa993b 6820 tcount++;
c906108c
SS
6821 if (tcount > 3)
6822 return 0;
23860348 6823 break; /* Retransmit buffer. */
c906108c
SS
6824 case '$':
6825 {
40e3f985 6826 if (remote_debug)
2bc416ba 6827 fprintf_unfiltered (gdb_stdlog,
23860348 6828 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
6829 /* It's probably an old response sent because an ACK
6830 was lost. Gobble up the packet and ack it so it
6831 doesn't get retransmitted when we resend this
6832 packet. */
6d820c5c 6833 skip_frame ();
d6f7abdf 6834 serial_write (remote_desc, "+", 1);
23860348 6835 continue; /* Now, go look for +. */
c906108c 6836 }
74531fed
PA
6837
6838 case '%':
6839 {
6840 int val;
6841
6842 /* If we got a notification, handle it, and go back to looking
6843 for an ack. */
6844 /* We've found the start of a notification. Now
6845 collect the data. */
6846 val = read_frame (&rs->buf, &rs->buf_size);
6847 if (val >= 0)
6848 {
6849 if (remote_debug)
6850 {
6e5abd65
PA
6851 struct cleanup *old_chain;
6852 char *str;
6853
6854 str = escape_buffer (rs->buf, val);
6855 old_chain = make_cleanup (xfree, str);
6856 fprintf_unfiltered (gdb_stdlog,
6857 " Notification received: %s\n",
6858 str);
6859 do_cleanups (old_chain);
74531fed
PA
6860 }
6861 handle_notification (rs->buf, val);
6862 /* We're in sync now, rewait for the ack. */
6863 tcount = 0;
6864 }
6865 else
6866 {
6867 if (remote_debug)
6868 {
6869 if (!started_error_output)
6870 {
6871 started_error_output = 1;
6872 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
6873 }
6874 fputc_unfiltered (ch & 0177, gdb_stdlog);
6875 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
6876 }
6877 }
6878 continue;
6879 }
6880 /* fall-through */
c906108c
SS
6881 default:
6882 if (remote_debug)
6883 {
6884 if (!started_error_output)
6885 {
6886 started_error_output = 1;
0f71a2f6 6887 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 6888 }
0f71a2f6 6889 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
6890 }
6891 continue;
6892 }
23860348 6893 break; /* Here to retransmit. */
c906108c
SS
6894 }
6895
6896#if 0
6897 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
6898 able to get out next time we call QUIT, without anything as
6899 violent as interrupt_query. If we want to provide a way out of
6900 here without getting to the next QUIT, it should be based on
6901 hitting ^C twice as in remote_wait. */
c906108c
SS
6902 if (quit_flag)
6903 {
6904 quit_flag = 0;
6905 interrupt_query ();
6906 }
6907#endif
6908 }
a6f3e723 6909 return 0;
c906108c
SS
6910}
6911
6d820c5c
DJ
6912/* Come here after finding the start of a frame when we expected an
6913 ack. Do our best to discard the rest of this packet. */
6914
6915static void
6916skip_frame (void)
6917{
6918 int c;
6919
6920 while (1)
6921 {
6922 c = readchar (remote_timeout);
6923 switch (c)
6924 {
6925 case SERIAL_TIMEOUT:
6926 /* Nothing we can do. */
6927 return;
6928 case '#':
6929 /* Discard the two bytes of checksum and stop. */
6930 c = readchar (remote_timeout);
6931 if (c >= 0)
6932 c = readchar (remote_timeout);
6933
6934 return;
6935 case '*': /* Run length encoding. */
6936 /* Discard the repeat count. */
6937 c = readchar (remote_timeout);
6938 if (c < 0)
6939 return;
6940 break;
6941 default:
6942 /* A regular character. */
6943 break;
6944 }
6945 }
6946}
6947
c906108c 6948/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
6949 into *BUF, verifying the checksum, length, and handling run-length
6950 compression. NUL terminate the buffer. If there is not enough room,
6951 expand *BUF using xrealloc.
c906108c 6952
c2d11a7d
JM
6953 Returns -1 on error, number of characters in buffer (ignoring the
6954 trailing NULL) on success. (could be extended to return one of the
23860348 6955 SERIAL status indications). */
c2d11a7d
JM
6956
6957static long
6d820c5c
DJ
6958read_frame (char **buf_p,
6959 long *sizeof_buf)
c906108c
SS
6960{
6961 unsigned char csum;
c2d11a7d 6962 long bc;
c906108c 6963 int c;
6d820c5c 6964 char *buf = *buf_p;
a6f3e723 6965 struct remote_state *rs = get_remote_state ();
c906108c
SS
6966
6967 csum = 0;
c2d11a7d 6968 bc = 0;
c906108c
SS
6969
6970 while (1)
6971 {
6972 c = readchar (remote_timeout);
c906108c
SS
6973 switch (c)
6974 {
6975 case SERIAL_TIMEOUT:
6976 if (remote_debug)
0f71a2f6 6977 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 6978 return -1;
c906108c
SS
6979 case '$':
6980 if (remote_debug)
0f71a2f6
JM
6981 fputs_filtered ("Saw new packet start in middle of old one\n",
6982 gdb_stdlog);
23860348 6983 return -1; /* Start a new packet, count retries. */
c906108c
SS
6984 case '#':
6985 {
6986 unsigned char pktcsum;
e1b09194
AC
6987 int check_0 = 0;
6988 int check_1 = 0;
c906108c 6989
c2d11a7d 6990 buf[bc] = '\0';
c906108c 6991
e1b09194
AC
6992 check_0 = readchar (remote_timeout);
6993 if (check_0 >= 0)
6994 check_1 = readchar (remote_timeout);
802188a7 6995
e1b09194
AC
6996 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
6997 {
6998 if (remote_debug)
2bc416ba 6999 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 7000 gdb_stdlog);
e1b09194
AC
7001 return -1;
7002 }
7003 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
7004 {
7005 if (remote_debug)
2bc416ba 7006 fputs_filtered ("Communication error in checksum\n",
23860348 7007 gdb_stdlog);
40e3f985
FN
7008 return -1;
7009 }
c906108c 7010
a6f3e723
SL
7011 /* Don't recompute the checksum; with no ack packets we
7012 don't have any way to indicate a packet retransmission
7013 is necessary. */
7014 if (rs->noack_mode)
7015 return bc;
7016
e1b09194 7017 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 7018 if (csum == pktcsum)
c2d11a7d 7019 return bc;
c906108c 7020
c5aa993b 7021 if (remote_debug)
c906108c 7022 {
6e5abd65
PA
7023 struct cleanup *old_chain;
7024 char *str;
7025
7026 str = escape_buffer (buf, bc);
7027 old_chain = make_cleanup (xfree, str);
7028 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7029 "Bad checksum, sentsum=0x%x, "
7030 "csum=0x%x, buf=%s\n",
6e5abd65
PA
7031 pktcsum, csum, str);
7032 do_cleanups (old_chain);
c906108c 7033 }
c2d11a7d 7034 /* Number of characters in buffer ignoring trailing
23860348 7035 NULL. */
c2d11a7d 7036 return -1;
c906108c 7037 }
23860348 7038 case '*': /* Run length encoding. */
c2c6d25f
JM
7039 {
7040 int repeat;
c906108c 7041
a744cf53 7042 csum += c;
b4501125
AC
7043 c = readchar (remote_timeout);
7044 csum += c;
23860348 7045 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 7046
23860348 7047 /* The character before ``*'' is repeated. */
c2d11a7d 7048
6d820c5c 7049 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 7050 {
6d820c5c
DJ
7051 if (bc + repeat - 1 >= *sizeof_buf - 1)
7052 {
7053 /* Make some more room in the buffer. */
7054 *sizeof_buf += repeat;
7055 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7056 buf = *buf_p;
7057 }
7058
c2d11a7d
JM
7059 memset (&buf[bc], buf[bc - 1], repeat);
7060 bc += repeat;
c2c6d25f
JM
7061 continue;
7062 }
7063
c2d11a7d 7064 buf[bc] = '\0';
6d820c5c 7065 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 7066 return -1;
c2c6d25f 7067 }
c906108c 7068 default:
6d820c5c 7069 if (bc >= *sizeof_buf - 1)
c906108c 7070 {
6d820c5c
DJ
7071 /* Make some more room in the buffer. */
7072 *sizeof_buf *= 2;
7073 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7074 buf = *buf_p;
c906108c
SS
7075 }
7076
6d820c5c
DJ
7077 buf[bc++] = c;
7078 csum += c;
7079 continue;
c906108c
SS
7080 }
7081 }
7082}
7083
7084/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
7085 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7086 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7087 rather than timing out; this is used (in synchronous mode) to wait
7088 for a target that is is executing user code to stop. */
d9fcf2fb
JM
7089/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7090 don't have to change all the calls to getpkt to deal with the
7091 return value, because at the moment I don't know what the right
23860348 7092 thing to do it for those. */
c906108c 7093void
6d820c5c
DJ
7094getpkt (char **buf,
7095 long *sizeof_buf,
c2d11a7d 7096 int forever)
d9fcf2fb
JM
7097{
7098 int timed_out;
7099
7100 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7101}
7102
7103
7104/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
7105 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7106 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7107 rather than timing out; this is used (in synchronous mode) to wait
7108 for a target that is is executing user code to stop. If FOREVER ==
7109 0, this function is allowed to time out gracefully and return an
74531fed
PA
7110 indication of this to the caller. Otherwise return the number of
7111 bytes read. If EXPECTING_NOTIF, consider receiving a notification
7112 enough reason to return to the caller. */
7113
3172dc30 7114static int
74531fed
PA
7115getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
7116 int expecting_notif)
c906108c 7117{
2d717e4f 7118 struct remote_state *rs = get_remote_state ();
c906108c
SS
7119 int c;
7120 int tries;
7121 int timeout;
df4b58fe 7122 int val = -1;
c906108c 7123
2d717e4f
DJ
7124 /* We're reading a new response. Make sure we don't look at a
7125 previously cached response. */
7126 rs->cached_wait_status = 0;
7127
6d820c5c 7128 strcpy (*buf, "timeout");
c906108c
SS
7129
7130 if (forever)
74531fed
PA
7131 timeout = watchdog > 0 ? watchdog : -1;
7132 else if (expecting_notif)
7133 timeout = 0; /* There should already be a char in the buffer. If
7134 not, bail out. */
c906108c
SS
7135 else
7136 timeout = remote_timeout;
7137
7138#define MAX_TRIES 3
7139
74531fed
PA
7140 /* Process any number of notifications, and then return when
7141 we get a packet. */
7142 for (;;)
c906108c 7143 {
74531fed
PA
7144 /* If we get a timeout or bad checksm, retry up to MAX_TRIES
7145 times. */
7146 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 7147 {
74531fed
PA
7148 /* This can loop forever if the remote side sends us
7149 characters continuously, but if it pauses, we'll get
7150 SERIAL_TIMEOUT from readchar because of timeout. Then
7151 we'll count that as a retry.
7152
7153 Note that even when forever is set, we will only wait
7154 forever prior to the start of a packet. After that, we
7155 expect characters to arrive at a brisk pace. They should
7156 show up within remote_timeout intervals. */
7157 do
7158 c = readchar (timeout);
7159 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
7160
7161 if (c == SERIAL_TIMEOUT)
7162 {
74531fed
PA
7163 if (expecting_notif)
7164 return -1; /* Don't complain, it's normal to not get
7165 anything in this case. */
7166
23860348 7167 if (forever) /* Watchdog went off? Kill the target. */
c906108c 7168 {
2acceee2 7169 QUIT;
ce5ce7ed 7170 pop_target ();
489eaeba 7171 error (_("Watchdog timeout has expired. Target detached."));
c906108c 7172 }
c906108c 7173 if (remote_debug)
0f71a2f6 7174 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 7175 }
74531fed
PA
7176 else
7177 {
7178 /* We've found the start of a packet or notification.
7179 Now collect the data. */
7180 val = read_frame (buf, sizeof_buf);
7181 if (val >= 0)
7182 break;
7183 }
7184
7185 serial_write (remote_desc, "-", 1);
c906108c 7186 }
c906108c 7187
74531fed
PA
7188 if (tries > MAX_TRIES)
7189 {
7190 /* We have tried hard enough, and just can't receive the
7191 packet/notification. Give up. */
7192 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 7193
74531fed
PA
7194 /* Skip the ack char if we're in no-ack mode. */
7195 if (!rs->noack_mode)
7196 serial_write (remote_desc, "+", 1);
7197 return -1;
7198 }
c906108c 7199
74531fed
PA
7200 /* If we got an ordinary packet, return that to our caller. */
7201 if (c == '$')
c906108c
SS
7202 {
7203 if (remote_debug)
43e526b9 7204 {
6e5abd65
PA
7205 struct cleanup *old_chain;
7206 char *str;
7207
7208 str = escape_buffer (*buf, val);
7209 old_chain = make_cleanup (xfree, str);
7210 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7211 do_cleanups (old_chain);
43e526b9 7212 }
a6f3e723
SL
7213
7214 /* Skip the ack char if we're in no-ack mode. */
7215 if (!rs->noack_mode)
7216 serial_write (remote_desc, "+", 1);
0876f84a 7217 return val;
c906108c
SS
7218 }
7219
74531fed
PA
7220 /* If we got a notification, handle it, and go back to looking
7221 for a packet. */
7222 else
7223 {
7224 gdb_assert (c == '%');
7225
7226 if (remote_debug)
7227 {
6e5abd65
PA
7228 struct cleanup *old_chain;
7229 char *str;
7230
7231 str = escape_buffer (*buf, val);
7232 old_chain = make_cleanup (xfree, str);
7233 fprintf_unfiltered (gdb_stdlog,
7234 " Notification received: %s\n",
7235 str);
7236 do_cleanups (old_chain);
74531fed 7237 }
c906108c 7238
74531fed 7239 handle_notification (*buf, val);
c906108c 7240
74531fed 7241 /* Notifications require no acknowledgement. */
a6f3e723 7242
74531fed
PA
7243 if (expecting_notif)
7244 return -1;
7245 }
7246 }
7247}
7248
7249static int
7250getpkt_sane (char **buf, long *sizeof_buf, int forever)
7251{
7252 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0);
7253}
7254
7255static int
7256getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever)
7257{
7258 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1);
c906108c 7259}
74531fed 7260
c906108c
SS
7261\f
7262static void
7d85a9c0 7263remote_kill (struct target_ops *ops)
43ff13b4 7264{
23860348
MS
7265 /* Use catch_errors so the user can quit from gdb even when we
7266 aren't on speaking terms with the remote system. */
c5aa993b 7267 catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
43ff13b4
JM
7268
7269 /* Don't wait for it to die. I'm not really sure it matters whether
7270 we do or not. For the existing stubs, kill is a noop. */
7271 target_mourn_inferior ();
7272}
7273
82f73884
PA
7274static int
7275remote_vkill (int pid, struct remote_state *rs)
7276{
7277 if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7278 return -1;
7279
7280 /* Tell the remote target to detach. */
7281 sprintf (rs->buf, "vKill;%x", pid);
7282 putpkt (rs->buf);
7283 getpkt (&rs->buf, &rs->buf_size, 0);
7284
7285 if (packet_ok (rs->buf,
7286 &remote_protocol_packets[PACKET_vKill]) == PACKET_OK)
7287 return 0;
7288 else if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7289 return -1;
7290 else
7291 return 1;
7292}
7293
7294static void
7d85a9c0 7295extended_remote_kill (struct target_ops *ops)
82f73884
PA
7296{
7297 int res;
7298 int pid = ptid_get_pid (inferior_ptid);
7299 struct remote_state *rs = get_remote_state ();
7300
7301 res = remote_vkill (pid, rs);
7302 if (res == -1 && !remote_multi_process_p (rs))
7303 {
7304 /* Don't try 'k' on a multi-process aware stub -- it has no way
7305 to specify the pid. */
7306
7307 putpkt ("k");
7308#if 0
7309 getpkt (&rs->buf, &rs->buf_size, 0);
7310 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7311 res = 1;
7312#else
7313 /* Don't wait for it to die. I'm not really sure it matters whether
7314 we do or not. For the existing stubs, kill is a noop. */
7315 res = 0;
7316#endif
7317 }
7318
7319 if (res != 0)
7320 error (_("Can't kill process"));
7321
82f73884
PA
7322 target_mourn_inferior ();
7323}
7324
c906108c 7325static void
136d6dae 7326remote_mourn (struct target_ops *ops)
c906108c 7327{
136d6dae 7328 remote_mourn_1 (ops);
c906108c
SS
7329}
7330
c906108c
SS
7331/* Worker function for remote_mourn. */
7332static void
fba45db2 7333remote_mourn_1 (struct target_ops *target)
c906108c
SS
7334{
7335 unpush_target (target);
ce5ce7ed 7336
8a2492ee
PA
7337 /* remote_close takes care of doing most of the clean up. */
7338 generic_mourn_inferior ();
c906108c
SS
7339}
7340
2d717e4f
DJ
7341static void
7342extended_remote_mourn_1 (struct target_ops *target)
7343{
7344 struct remote_state *rs = get_remote_state ();
c906108c 7345
e24a49d8
PA
7346 /* In case we got here due to an error, but we're going to stay
7347 connected. */
7348 rs->waiting_for_stop_reply = 0;
7349
74531fed
PA
7350 /* We're no longer interested in these events. */
7351 discard_pending_stop_replies (ptid_get_pid (inferior_ptid));
7352
dc1981d7
PA
7353 /* If the current general thread belonged to the process we just
7354 detached from or has exited, the remote side current general
7355 thread becomes undefined. Considering a case like this:
7356
7357 - We just got here due to a detach.
7358 - The process that we're detaching from happens to immediately
7359 report a global breakpoint being hit in non-stop mode, in the
7360 same thread we had selected before.
7361 - GDB attaches to this process again.
7362 - This event happens to be the next event we handle.
7363
7364 GDB would consider that the current general thread didn't need to
7365 be set on the stub side (with Hg), since for all it knew,
7366 GENERAL_THREAD hadn't changed.
7367
7368 Notice that although in all-stop mode, the remote server always
7369 sets the current thread to the thread reporting the stop event,
7370 that doesn't happen in non-stop mode; in non-stop, the stub *must
7371 not* change the current thread when reporting a breakpoint hit,
7372 due to the decoupling of event reporting and event handling.
7373
7374 To keep things simple, we always invalidate our notion of the
7375 current thread. */
7376 record_currthread (minus_one_ptid);
7377
2d717e4f
DJ
7378 /* Unlike "target remote", we do not want to unpush the target; then
7379 the next time the user says "run", we won't be connected. */
7380
48aa3c27
PA
7381 /* Call common code to mark the inferior as not running. */
7382 generic_mourn_inferior ();
7383
d729566a 7384 if (!have_inferiors ())
2d717e4f 7385 {
82f73884
PA
7386 if (!remote_multi_process_p (rs))
7387 {
7388 /* Check whether the target is running now - some remote stubs
7389 automatically restart after kill. */
7390 putpkt ("?");
7391 getpkt (&rs->buf, &rs->buf_size, 0);
7392
7393 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7394 {
3e43a32a
MS
7395 /* Assume that the target has been restarted. Set
7396 inferior_ptid so that bits of core GDB realizes
7397 there's something here, e.g., so that the user can
7398 say "kill" again. */
82f73884
PA
7399 inferior_ptid = magic_null_ptid;
7400 }
82f73884 7401 }
2d717e4f
DJ
7402 }
7403}
c906108c
SS
7404
7405static void
136d6dae 7406extended_remote_mourn (struct target_ops *ops)
c906108c 7407{
136d6dae 7408 extended_remote_mourn_1 (ops);
2d717e4f 7409}
c906108c 7410
2d717e4f
DJ
7411static int
7412extended_remote_run (char *args)
7413{
7414 struct remote_state *rs = get_remote_state ();
2d717e4f 7415 int len;
c906108c 7416
2d717e4f
DJ
7417 /* If the user has disabled vRun support, or we have detected that
7418 support is not available, do not try it. */
7419 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7420 return -1;
424163ea 7421
2d717e4f
DJ
7422 strcpy (rs->buf, "vRun;");
7423 len = strlen (rs->buf);
c906108c 7424
2d717e4f
DJ
7425 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
7426 error (_("Remote file name too long for run packet"));
7427 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
7428
d1a41061 7429 gdb_assert (args != NULL);
2d717e4f
DJ
7430 if (*args)
7431 {
7432 struct cleanup *back_to;
7433 int i;
7434 char **argv;
7435
d1a41061 7436 argv = gdb_buildargv (args);
2d717e4f
DJ
7437 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
7438 for (i = 0; argv[i] != NULL; i++)
7439 {
7440 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
7441 error (_("Argument list too long for run packet"));
7442 rs->buf[len++] = ';';
7443 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
7444 }
7445 do_cleanups (back_to);
7446 }
7447
7448 rs->buf[len++] = '\0';
7449
7450 putpkt (rs->buf);
7451 getpkt (&rs->buf, &rs->buf_size, 0);
7452
7453 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
7454 {
7455 /* We have a wait response; we don't need it, though. All is well. */
7456 return 0;
7457 }
7458 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7459 /* It wasn't disabled before, but it is now. */
7460 return -1;
7461 else
7462 {
7463 if (remote_exec_file[0] == '\0')
7464 error (_("Running the default executable on the remote target failed; "
7465 "try \"set remote exec-file\"?"));
7466 else
7467 error (_("Running \"%s\" on the remote target failed"),
7468 remote_exec_file);
7469 }
c906108c
SS
7470}
7471
2d717e4f
DJ
7472/* In the extended protocol we want to be able to do things like
7473 "run" and have them basically work as expected. So we need
7474 a special create_inferior function. We support changing the
7475 executable file and the command line arguments, but not the
7476 environment. */
7477
43ff13b4 7478static void
2d717e4f 7479extended_remote_create_inferior_1 (char *exec_file, char *args,
75c99385 7480 char **env, int from_tty)
43ff13b4 7481{
43ff13b4 7482 /* If running asynchronously, register the target file descriptor
23860348 7483 with the event loop. */
75c99385 7484 if (target_can_async_p ())
2acceee2 7485 target_async (inferior_event_handler, 0);
43ff13b4
JM
7486
7487 /* Now restart the remote server. */
2d717e4f
DJ
7488 if (extended_remote_run (args) == -1)
7489 {
7490 /* vRun was not supported. Fail if we need it to do what the
7491 user requested. */
7492 if (remote_exec_file[0])
7493 error (_("Remote target does not support \"set remote exec-file\""));
7494 if (args[0])
7495 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 7496
2d717e4f
DJ
7497 /* Fall back to "R". */
7498 extended_remote_restart ();
7499 }
424163ea 7500
6c95b8df
PA
7501 if (!have_inferiors ())
7502 {
7503 /* Clean up from the last time we ran, before we mark the target
7504 running again. This will mark breakpoints uninserted, and
7505 get_offsets may insert breakpoints. */
7506 init_thread_list ();
7507 init_wait_for_inferior ();
7508 }
45280a52 7509
2d717e4f 7510 /* Now mark the inferior as running before we do anything else. */
79d7f229 7511 inferior_ptid = magic_null_ptid;
c0a2216e 7512
74531fed
PA
7513 /* Now, if we have thread information, update inferior_ptid. */
7514 inferior_ptid = remote_current_thread (inferior_ptid);
7515
0b16c5cf 7516 remote_add_inferior (ptid_get_pid (inferior_ptid), 0);
c0a2216e
PA
7517 add_thread_silent (inferior_ptid);
7518
2d717e4f
DJ
7519 /* Get updated offsets, if the stub uses qOffsets. */
7520 get_offsets ();
2d717e4f
DJ
7521}
7522
7523static void
136d6dae
VP
7524extended_remote_create_inferior (struct target_ops *ops,
7525 char *exec_file, char *args,
2d717e4f
DJ
7526 char **env, int from_tty)
7527{
75c99385 7528 extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
43ff13b4 7529}
c906108c 7530\f
c5aa993b 7531
8181d85f
DJ
7532/* Insert a breakpoint. On targets that have software breakpoint
7533 support, we ask the remote target to do the work; on targets
7534 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
7535
7536static int
a6d9a66e
UW
7537remote_insert_breakpoint (struct gdbarch *gdbarch,
7538 struct bp_target_info *bp_tgt)
c906108c 7539{
d471ea57
AC
7540 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
7541 If it succeeds, then set the support to PACKET_ENABLE. If it
7542 fails, and the user has explicitly requested the Z support then
23860348 7543 report an error, otherwise, mark it disabled and go on. */
802188a7 7544
444abaca 7545 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
96baa820 7546 {
7c0f6dcc 7547 CORE_ADDR addr = bp_tgt->placed_address;
4fff2411
JZ
7548 struct remote_state *rs;
7549 char *p;
7c0f6dcc 7550 int bpsize;
4fff2411 7551
a1dcb23a 7552 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
7553
7554 rs = get_remote_state ();
7555 p = rs->buf;
802188a7 7556
96baa820
JM
7557 *(p++) = 'Z';
7558 *(p++) = '0';
7559 *(p++) = ',';
7c0f6dcc 7560 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 7561 p += hexnumstr (p, addr);
7c0f6dcc 7562 sprintf (p, ",%d", bpsize);
802188a7 7563
6d820c5c
DJ
7564 putpkt (rs->buf);
7565 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 7566
6d820c5c 7567 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 7568 {
d471ea57
AC
7569 case PACKET_ERROR:
7570 return -1;
7571 case PACKET_OK:
7c0f6dcc
JL
7572 bp_tgt->placed_address = addr;
7573 bp_tgt->placed_size = bpsize;
d471ea57
AC
7574 return 0;
7575 case PACKET_UNKNOWN:
7576 break;
96baa820
JM
7577 }
7578 }
c906108c 7579
a6d9a66e 7580 return memory_insert_breakpoint (gdbarch, bp_tgt);
c906108c
SS
7581}
7582
7583static int
a6d9a66e
UW
7584remote_remove_breakpoint (struct gdbarch *gdbarch,
7585 struct bp_target_info *bp_tgt)
c906108c 7586{
8181d85f 7587 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 7588 struct remote_state *rs = get_remote_state ();
96baa820 7589
444abaca 7590 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
96baa820 7591 {
6d820c5c 7592 char *p = rs->buf;
802188a7 7593
96baa820
JM
7594 *(p++) = 'z';
7595 *(p++) = '0';
7596 *(p++) = ',';
7597
8181d85f
DJ
7598 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
7599 p += hexnumstr (p, addr);
7600 sprintf (p, ",%d", bp_tgt->placed_size);
802188a7 7601
6d820c5c
DJ
7602 putpkt (rs->buf);
7603 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 7604
6d820c5c 7605 return (rs->buf[0] == 'E');
96baa820
JM
7606 }
7607
a6d9a66e 7608 return memory_remove_breakpoint (gdbarch, bp_tgt);
c906108c
SS
7609}
7610
d471ea57
AC
7611static int
7612watchpoint_to_Z_packet (int type)
7613{
7614 switch (type)
7615 {
7616 case hw_write:
bb858e6a 7617 return Z_PACKET_WRITE_WP;
d471ea57
AC
7618 break;
7619 case hw_read:
bb858e6a 7620 return Z_PACKET_READ_WP;
d471ea57
AC
7621 break;
7622 case hw_access:
bb858e6a 7623 return Z_PACKET_ACCESS_WP;
d471ea57
AC
7624 break;
7625 default:
8e65ff28 7626 internal_error (__FILE__, __LINE__,
e2e0b3e5 7627 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
7628 }
7629}
7630
3c3bea1c 7631static int
0cf6dd15
TJB
7632remote_insert_watchpoint (CORE_ADDR addr, int len, int type,
7633 struct expression *cond)
96baa820 7634{
d01949b6 7635 struct remote_state *rs = get_remote_state ();
e514a9d6 7636 char *p;
d471ea57 7637 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 7638
444abaca 7639 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
85d721b8 7640 return 1;
802188a7 7641
6d820c5c
DJ
7642 sprintf (rs->buf, "Z%x,", packet);
7643 p = strchr (rs->buf, '\0');
96baa820
JM
7644 addr = remote_address_masked (addr);
7645 p += hexnumstr (p, (ULONGEST) addr);
d4f3574e 7646 sprintf (p, ",%x", len);
802188a7 7647
6d820c5c
DJ
7648 putpkt (rs->buf);
7649 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 7650
6d820c5c 7651 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
7652 {
7653 case PACKET_ERROR:
d471ea57 7654 return -1;
85d721b8
PA
7655 case PACKET_UNKNOWN:
7656 return 1;
d471ea57
AC
7657 case PACKET_OK:
7658 return 0;
7659 }
8e65ff28 7660 internal_error (__FILE__, __LINE__,
e2e0b3e5 7661 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
7662}
7663
d471ea57 7664
3c3bea1c 7665static int
0cf6dd15
TJB
7666remote_remove_watchpoint (CORE_ADDR addr, int len, int type,
7667 struct expression *cond)
96baa820 7668{
d01949b6 7669 struct remote_state *rs = get_remote_state ();
e514a9d6 7670 char *p;
d471ea57
AC
7671 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
7672
444abaca 7673 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
5cffb350 7674 return -1;
802188a7 7675
6d820c5c
DJ
7676 sprintf (rs->buf, "z%x,", packet);
7677 p = strchr (rs->buf, '\0');
96baa820
JM
7678 addr = remote_address_masked (addr);
7679 p += hexnumstr (p, (ULONGEST) addr);
d4f3574e 7680 sprintf (p, ",%x", len);
6d820c5c
DJ
7681 putpkt (rs->buf);
7682 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 7683
6d820c5c 7684 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
7685 {
7686 case PACKET_ERROR:
7687 case PACKET_UNKNOWN:
7688 return -1;
7689 case PACKET_OK:
7690 return 0;
7691 }
8e65ff28 7692 internal_error (__FILE__, __LINE__,
e2e0b3e5 7693 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
7694}
7695
3c3bea1c 7696
501eef12
AC
7697int remote_hw_watchpoint_limit = -1;
7698int remote_hw_breakpoint_limit = -1;
d471ea57 7699
b9362cc7 7700static int
3c3bea1c 7701remote_check_watch_resources (int type, int cnt, int ot)
96baa820 7702{
3c3bea1c
GS
7703 if (type == bp_hardware_breakpoint)
7704 {
7705 if (remote_hw_breakpoint_limit == 0)
7706 return 0;
501eef12
AC
7707 else if (remote_hw_breakpoint_limit < 0)
7708 return 1;
3c3bea1c
GS
7709 else if (cnt <= remote_hw_breakpoint_limit)
7710 return 1;
7711 }
7712 else
7713 {
7714 if (remote_hw_watchpoint_limit == 0)
7715 return 0;
501eef12
AC
7716 else if (remote_hw_watchpoint_limit < 0)
7717 return 1;
3c3bea1c
GS
7718 else if (ot)
7719 return -1;
7720 else if (cnt <= remote_hw_watchpoint_limit)
7721 return 1;
7722 }
7723 return -1;
7724}
7725
b9362cc7 7726static int
3c3bea1c
GS
7727remote_stopped_by_watchpoint (void)
7728{
82f73884 7729 return remote_stopped_by_watchpoint_p;
3c3bea1c
GS
7730}
7731
4aa7a7f5
JJ
7732static int
7733remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 7734{
4aa7a7f5 7735 int rc = 0;
a744cf53 7736
d983da9c 7737 if (remote_stopped_by_watchpoint ())
4aa7a7f5
JJ
7738 {
7739 *addr_p = remote_watch_data_address;
7740 rc = 1;
7741 }
7742
7743 return rc;
3c3bea1c
GS
7744}
7745
7746
7747static int
a6d9a66e
UW
7748remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
7749 struct bp_target_info *bp_tgt)
3c3bea1c 7750{
8181d85f 7751 CORE_ADDR addr;
4fff2411
JZ
7752 struct remote_state *rs;
7753 char *p;
802188a7 7754
c8189ed1 7755 /* The length field should be set to the size of a breakpoint
8181d85f 7756 instruction, even though we aren't inserting one ourselves. */
c8189ed1 7757
a1dcb23a 7758 gdbarch_remote_breakpoint_from_pc
a6d9a66e 7759 (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
3c3bea1c 7760
444abaca 7761 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5cffb350 7762 return -1;
2bc416ba 7763
4fff2411
JZ
7764 rs = get_remote_state ();
7765 p = rs->buf;
7766
96baa820
JM
7767 *(p++) = 'Z';
7768 *(p++) = '1';
7769 *(p++) = ',';
802188a7 7770
8181d85f 7771 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 7772 p += hexnumstr (p, (ULONGEST) addr);
8181d85f 7773 sprintf (p, ",%x", bp_tgt->placed_size);
96baa820 7774
6d820c5c
DJ
7775 putpkt (rs->buf);
7776 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 7777
6d820c5c 7778 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
7779 {
7780 case PACKET_ERROR:
7781 case PACKET_UNKNOWN:
7782 return -1;
7783 case PACKET_OK:
7784 return 0;
7785 }
8e65ff28 7786 internal_error (__FILE__, __LINE__,
e2e0b3e5 7787 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
7788}
7789
d471ea57 7790
802188a7 7791static int
a6d9a66e
UW
7792remote_remove_hw_breakpoint (struct gdbarch *gdbarch,
7793 struct bp_target_info *bp_tgt)
96baa820 7794{
8181d85f 7795 CORE_ADDR addr;
d01949b6 7796 struct remote_state *rs = get_remote_state ();
6d820c5c 7797 char *p = rs->buf;
c8189ed1 7798
444abaca 7799 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5cffb350 7800 return -1;
802188a7 7801
96baa820
JM
7802 *(p++) = 'z';
7803 *(p++) = '1';
7804 *(p++) = ',';
802188a7 7805
8181d85f 7806 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 7807 p += hexnumstr (p, (ULONGEST) addr);
8181d85f 7808 sprintf (p, ",%x", bp_tgt->placed_size);
96baa820 7809
6d820c5c
DJ
7810 putpkt (rs->buf);
7811 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 7812
6d820c5c 7813 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
7814 {
7815 case PACKET_ERROR:
7816 case PACKET_UNKNOWN:
7817 return -1;
7818 case PACKET_OK:
7819 return 0;
7820 }
8e65ff28 7821 internal_error (__FILE__, __LINE__,
e2e0b3e5 7822 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 7823}
96baa820 7824
23860348 7825/* Table used by the crc32 function to calcuate the checksum. */
c906108c 7826
c5aa993b
JM
7827static unsigned long crc32_table[256] =
7828{0, 0};
c906108c
SS
7829
7830static unsigned long
4a5e7a5b 7831crc32 (const unsigned char *buf, int len, unsigned int crc)
c906108c 7832{
c5aa993b 7833 if (!crc32_table[1])
c906108c 7834 {
23860348 7835 /* Initialize the CRC table and the decoding table. */
c906108c
SS
7836 int i, j;
7837 unsigned int c;
7838
7839 for (i = 0; i < 256; i++)
c5aa993b
JM
7840 {
7841 for (c = i << 24, j = 8; j > 0; --j)
7842 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
7843 crc32_table[i] = c;
7844 }
c906108c
SS
7845 }
7846
7847 while (len--)
7848 {
7849 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
7850 buf++;
7851 }
7852 return crc;
7853}
7854
4a5e7a5b
PA
7855/* Verify memory using the "qCRC:" request. */
7856
7857static int
7858remote_verify_memory (struct target_ops *ops,
7859 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
7860{
7861 struct remote_state *rs = get_remote_state ();
7862 unsigned long host_crc, target_crc;
7863 char *tmp;
7864
7865 /* FIXME: assumes lma can fit into long. */
7866 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
7867 (long) lma, (long) size);
7868 putpkt (rs->buf);
7869
7870 /* Be clever; compute the host_crc before waiting for target
7871 reply. */
7872 host_crc = crc32 (data, size, 0xffffffff);
7873
7874 getpkt (&rs->buf, &rs->buf_size, 0);
7875 if (rs->buf[0] == 'E')
7876 return -1;
7877
7878 if (rs->buf[0] != 'C')
7879 error (_("remote target does not support this operation"));
7880
7881 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
7882 target_crc = target_crc * 16 + fromhex (*tmp);
7883
7884 return (host_crc == target_crc);
7885}
7886
c906108c
SS
7887/* compare-sections command
7888
7889 With no arguments, compares each loadable section in the exec bfd
7890 with the same memory range on the target, and reports mismatches.
4a5e7a5b 7891 Useful for verifying the image on the target against the exec file. */
e514a9d6 7892
c906108c 7893static void
fba45db2 7894compare_sections_command (char *args, int from_tty)
c906108c
SS
7895{
7896 asection *s;
c906108c 7897 struct cleanup *old_chain;
085dd6e6 7898 char *sectdata;
ce359b09 7899 const char *sectname;
c906108c
SS
7900 bfd_size_type size;
7901 bfd_vma lma;
7902 int matched = 0;
7903 int mismatched = 0;
4a5e7a5b 7904 int res;
c906108c
SS
7905
7906 if (!exec_bfd)
8a3fe4f8 7907 error (_("command cannot be used without an exec file"));
c906108c 7908
c5aa993b 7909 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
7910 {
7911 if (!(s->flags & SEC_LOAD))
0df8b418 7912 continue; /* Skip non-loadable section. */
c906108c 7913
2c500098 7914 size = bfd_get_section_size (s);
c906108c 7915 if (size == 0)
0df8b418 7916 continue; /* Skip zero-length section. */
c906108c 7917
ce359b09 7918 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 7919 if (args && strcmp (args, sectname) != 0)
0df8b418 7920 continue; /* Not the section selected by user. */
c906108c 7921
0df8b418 7922 matched = 1; /* Do this section. */
c906108c 7923 lma = s->lma;
c906108c 7924
c906108c 7925 sectdata = xmalloc (size);
b8c9b27d 7926 old_chain = make_cleanup (xfree, sectdata);
c906108c 7927 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 7928
4a5e7a5b
PA
7929 res = target_verify_memory (sectdata, lma, size);
7930
7931 if (res == -1)
5af949e3
UW
7932 error (_("target memory fault, section %s, range %s -- %s"), sectname,
7933 paddress (target_gdbarch, lma),
7934 paddress (target_gdbarch, lma + size));
c906108c 7935
5af949e3
UW
7936 printf_filtered ("Section %s, range %s -- %s: ", sectname,
7937 paddress (target_gdbarch, lma),
7938 paddress (target_gdbarch, lma + size));
4a5e7a5b 7939 if (res)
c906108c
SS
7940 printf_filtered ("matched.\n");
7941 else
c5aa993b
JM
7942 {
7943 printf_filtered ("MIS-MATCHED!\n");
7944 mismatched++;
7945 }
c906108c
SS
7946
7947 do_cleanups (old_chain);
7948 }
7949 if (mismatched > 0)
8a3fe4f8
AC
7950 warning (_("One or more sections of the remote executable does not match\n\
7951the loaded file\n"));
c906108c 7952 if (args && !matched)
a3f17187 7953 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
7954}
7955
0e7f50da
UW
7956/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
7957 into remote target. The number of bytes written to the remote
7958 target is returned, or -1 for error. */
7959
7960static LONGEST
7961remote_write_qxfer (struct target_ops *ops, const char *object_name,
7962 const char *annex, const gdb_byte *writebuf,
7963 ULONGEST offset, LONGEST len,
7964 struct packet_config *packet)
7965{
7966 int i, buf_len;
7967 ULONGEST n;
0e7f50da
UW
7968 struct remote_state *rs = get_remote_state ();
7969 int max_size = get_memory_write_packet_size ();
7970
7971 if (packet->support == PACKET_DISABLE)
7972 return -1;
7973
7974 /* Insert header. */
7975 i = snprintf (rs->buf, max_size,
7976 "qXfer:%s:write:%s:%s:",
7977 object_name, annex ? annex : "",
7978 phex_nz (offset, sizeof offset));
7979 max_size -= (i + 1);
7980
7981 /* Escape as much data as fits into rs->buf. */
7982 buf_len = remote_escape_output
7983 (writebuf, len, (rs->buf + i), &max_size, max_size);
7984
7985 if (putpkt_binary (rs->buf, i + buf_len) < 0
7986 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
7987 || packet_ok (rs->buf, packet) != PACKET_OK)
7988 return -1;
7989
7990 unpack_varlen_hex (rs->buf, &n);
7991 return n;
7992}
7993
0876f84a
DJ
7994/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
7995 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
7996 number of bytes read is returned, or 0 for EOF, or -1 for error.
7997 The number of bytes read may be less than LEN without indicating an
7998 EOF. PACKET is checked and updated to indicate whether the remote
7999 target supports this object. */
8000
8001static LONGEST
8002remote_read_qxfer (struct target_ops *ops, const char *object_name,
8003 const char *annex,
8004 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
8005 struct packet_config *packet)
8006{
8007 static char *finished_object;
8008 static char *finished_annex;
8009 static ULONGEST finished_offset;
8010
8011 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
8012 LONGEST i, n, packet_len;
8013
8014 if (packet->support == PACKET_DISABLE)
8015 return -1;
8016
8017 /* Check whether we've cached an end-of-object packet that matches
8018 this request. */
8019 if (finished_object)
8020 {
8021 if (strcmp (object_name, finished_object) == 0
8022 && strcmp (annex ? annex : "", finished_annex) == 0
8023 && offset == finished_offset)
8024 return 0;
8025
8026 /* Otherwise, we're now reading something different. Discard
8027 the cache. */
8028 xfree (finished_object);
8029 xfree (finished_annex);
8030 finished_object = NULL;
8031 finished_annex = NULL;
8032 }
8033
8034 /* Request only enough to fit in a single packet. The actual data
8035 may not, since we don't know how much of it will need to be escaped;
8036 the target is free to respond with slightly less data. We subtract
8037 five to account for the response type and the protocol frame. */
8038 n = min (get_remote_packet_size () - 5, len);
8039 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8040 object_name, annex ? annex : "",
8041 phex_nz (offset, sizeof offset),
8042 phex_nz (n, sizeof n));
8043 i = putpkt (rs->buf);
8044 if (i < 0)
8045 return -1;
8046
8047 rs->buf[0] = '\0';
8048 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8049 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
8050 return -1;
8051
8052 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8053 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8054
8055 /* 'm' means there is (or at least might be) more data after this
8056 batch. That does not make sense unless there's at least one byte
8057 of data in this reply. */
8058 if (rs->buf[0] == 'm' && packet_len == 1)
8059 error (_("Remote qXfer reply contained no data."));
8060
8061 /* Got some data. */
8062 i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
8063
8064 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
8065 or possibly empty. If we have the final block of a non-empty
8066 object, record this fact to bypass a subsequent partial read. */
8067 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a
DJ
8068 {
8069 finished_object = xstrdup (object_name);
8070 finished_annex = xstrdup (annex ? annex : "");
8071 finished_offset = offset + i;
8072 }
8073
8074 return i;
8075}
8076
1e3ff5ad 8077static LONGEST
4b8a223f 8078remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5
MK
8079 const char *annex, gdb_byte *readbuf,
8080 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
c906108c 8081{
82f73884 8082 struct remote_state *rs;
c906108c 8083 int i;
6d820c5c 8084 char *p2;
1e3ff5ad 8085 char query_type;
c906108c 8086
82f73884
PA
8087 set_general_thread (inferior_ptid);
8088
8089 rs = get_remote_state ();
8090
b2182ed2 8091 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
8092 if (object == TARGET_OBJECT_MEMORY)
8093 {
8094 int xfered;
a744cf53 8095
21e3b9b9
DJ
8096 errno = 0;
8097
2d717e4f
DJ
8098 /* If the remote target is connected but not running, we should
8099 pass this request down to a lower stratum (e.g. the executable
8100 file). */
8101 if (!target_has_execution)
8102 return 0;
8103
21e3b9b9 8104 if (writebuf != NULL)
b2182ed2 8105 xfered = remote_write_bytes (offset, writebuf, len);
21e3b9b9 8106 else
b2182ed2 8107 xfered = remote_read_bytes (offset, readbuf, len);
21e3b9b9
DJ
8108
8109 if (xfered > 0)
8110 return xfered;
8111 else if (xfered == 0 && errno == 0)
8112 return 0;
8113 else
8114 return -1;
8115 }
8116
0df8b418 8117 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
8118 if (object == TARGET_OBJECT_SPU)
8119 {
8120 if (readbuf)
8121 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
8122 &remote_protocol_packets
8123 [PACKET_qXfer_spu_read]);
8124 else
8125 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
8126 &remote_protocol_packets
8127 [PACKET_qXfer_spu_write]);
8128 }
8129
4aa995e1
PA
8130 /* Handle extra signal info using qxfer packets. */
8131 if (object == TARGET_OBJECT_SIGNAL_INFO)
8132 {
8133 if (readbuf)
8134 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
8135 &remote_protocol_packets
8136 [PACKET_qXfer_siginfo_read]);
8137 else
3e43a32a
MS
8138 return remote_write_qxfer (ops, "siginfo", annex,
8139 writebuf, offset, len,
4aa995e1
PA
8140 &remote_protocol_packets
8141 [PACKET_qXfer_siginfo_write]);
8142 }
8143
0fb4aa4b
PA
8144 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8145 {
8146 if (readbuf)
3e43a32a
MS
8147 return remote_read_qxfer (ops, "statictrace", annex,
8148 readbuf, offset, len,
0fb4aa4b
PA
8149 &remote_protocol_packets
8150 [PACKET_qXfer_statictrace_read]);
8151 else
8152 return -1;
8153 }
8154
a76d924d
DJ
8155 /* Only handle flash writes. */
8156 if (writebuf != NULL)
8157 {
8158 LONGEST xfered;
8159
8160 switch (object)
8161 {
8162 case TARGET_OBJECT_FLASH:
8163 xfered = remote_flash_write (ops, offset, len, writebuf);
8164
8165 if (xfered > 0)
8166 return xfered;
8167 else if (xfered == 0 && errno == 0)
8168 return 0;
8169 else
8170 return -1;
8171
8172 default:
8173 return -1;
8174 }
8175 }
4b8a223f 8176
1e3ff5ad
AC
8177 /* Map pre-existing objects onto letters. DO NOT do this for new
8178 objects!!! Instead specify new query packets. */
8179 switch (object)
c906108c 8180 {
1e3ff5ad
AC
8181 case TARGET_OBJECT_AVR:
8182 query_type = 'R';
8183 break;
802188a7
RM
8184
8185 case TARGET_OBJECT_AUXV:
0876f84a
DJ
8186 gdb_assert (annex == NULL);
8187 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
8188 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 8189
23181151
DJ
8190 case TARGET_OBJECT_AVAILABLE_FEATURES:
8191 return remote_read_qxfer
8192 (ops, "features", annex, readbuf, offset, len,
8193 &remote_protocol_packets[PACKET_qXfer_features]);
8194
cfa9d6d9
DJ
8195 case TARGET_OBJECT_LIBRARIES:
8196 return remote_read_qxfer
8197 (ops, "libraries", annex, readbuf, offset, len,
8198 &remote_protocol_packets[PACKET_qXfer_libraries]);
8199
fd79ecee
DJ
8200 case TARGET_OBJECT_MEMORY_MAP:
8201 gdb_assert (annex == NULL);
8202 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
8203 &remote_protocol_packets[PACKET_qXfer_memory_map]);
8204
07e059b5
VP
8205 case TARGET_OBJECT_OSDATA:
8206 /* Should only get here if we're connected. */
8207 gdb_assert (remote_desc);
8208 return remote_read_qxfer
8209 (ops, "osdata", annex, readbuf, offset, len,
8210 &remote_protocol_packets[PACKET_qXfer_osdata]);
8211
dc146f7c
VP
8212 case TARGET_OBJECT_THREADS:
8213 gdb_assert (annex == NULL);
8214 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
8215 &remote_protocol_packets[PACKET_qXfer_threads]);
8216
b3b9301e
PA
8217 case TARGET_OBJECT_TRACEFRAME_INFO:
8218 gdb_assert (annex == NULL);
8219 return remote_read_qxfer
8220 (ops, "traceframe-info", annex, readbuf, offset, len,
8221 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
1e3ff5ad 8222 default:
c906108c
SS
8223 return -1;
8224 }
8225
4b8a223f 8226 /* Note: a zero OFFSET and LEN can be used to query the minimum
1e3ff5ad 8227 buffer size. */
4b8a223f 8228 if (offset == 0 && len == 0)
ea9c271d 8229 return (get_remote_packet_size ());
0df8b418 8230 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 8231 large enough let the caller deal with it. */
ea9c271d 8232 if (len < get_remote_packet_size ())
1e3ff5ad 8233 return -1;
ea9c271d 8234 len = get_remote_packet_size ();
1e3ff5ad 8235
23860348 8236 /* Except for querying the minimum buffer size, target must be open. */
c5aa993b 8237 if (!remote_desc)
8a3fe4f8 8238 error (_("remote query is only available after target open"));
c906108c 8239
1e3ff5ad 8240 gdb_assert (annex != NULL);
4b8a223f 8241 gdb_assert (readbuf != NULL);
c906108c 8242
6d820c5c 8243 p2 = rs->buf;
c906108c
SS
8244 *p2++ = 'q';
8245 *p2++ = query_type;
8246
23860348
MS
8247 /* We used one buffer char for the remote protocol q command and
8248 another for the query type. As the remote protocol encapsulation
8249 uses 4 chars plus one extra in case we are debugging
8250 (remote_debug), we have PBUFZIZ - 7 left to pack the query
8251 string. */
c906108c 8252 i = 0;
ea9c271d 8253 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 8254 {
1e3ff5ad
AC
8255 /* Bad caller may have sent forbidden characters. */
8256 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
8257 *p2++ = annex[i];
c906108c
SS
8258 i++;
8259 }
1e3ff5ad
AC
8260 *p2 = '\0';
8261 gdb_assert (annex[i] == '\0');
c906108c 8262
6d820c5c 8263 i = putpkt (rs->buf);
c5aa993b
JM
8264 if (i < 0)
8265 return i;
c906108c 8266
6d820c5c
DJ
8267 getpkt (&rs->buf, &rs->buf_size, 0);
8268 strcpy ((char *) readbuf, rs->buf);
c906108c 8269
cfd77fa1 8270 return strlen ((char *) readbuf);
c906108c
SS
8271}
8272
08388c79
DE
8273static int
8274remote_search_memory (struct target_ops* ops,
8275 CORE_ADDR start_addr, ULONGEST search_space_len,
8276 const gdb_byte *pattern, ULONGEST pattern_len,
8277 CORE_ADDR *found_addrp)
8278{
5af949e3 8279 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
08388c79
DE
8280 struct remote_state *rs = get_remote_state ();
8281 int max_size = get_memory_write_packet_size ();
8282 struct packet_config *packet =
8283 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
8284 /* Number of packet bytes used to encode the pattern;
8285 this could be more than PATTERN_LEN due to escape characters. */
08388c79 8286 int escaped_pattern_len;
0df8b418 8287 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
8288 int used_pattern_len;
8289 int i;
8290 int found;
8291 ULONGEST found_addr;
8292
8293 /* Don't go to the target if we don't have to.
8294 This is done before checking packet->support to avoid the possibility that
8295 a success for this edge case means the facility works in general. */
8296 if (pattern_len > search_space_len)
8297 return 0;
8298 if (pattern_len == 0)
8299 {
8300 *found_addrp = start_addr;
8301 return 1;
8302 }
8303
8304 /* If we already know the packet isn't supported, fall back to the simple
8305 way of searching memory. */
8306
8307 if (packet->support == PACKET_DISABLE)
8308 {
8309 /* Target doesn't provided special support, fall back and use the
8310 standard support (copy memory and do the search here). */
8311 return simple_search_memory (ops, start_addr, search_space_len,
8312 pattern, pattern_len, found_addrp);
8313 }
8314
8315 /* Insert header. */
8316 i = snprintf (rs->buf, max_size,
8317 "qSearch:memory:%s;%s;",
5af949e3 8318 phex_nz (start_addr, addr_size),
08388c79
DE
8319 phex_nz (search_space_len, sizeof (search_space_len)));
8320 max_size -= (i + 1);
8321
8322 /* Escape as much data as fits into rs->buf. */
8323 escaped_pattern_len =
8324 remote_escape_output (pattern, pattern_len, (rs->buf + i),
8325 &used_pattern_len, max_size);
8326
8327 /* Bail if the pattern is too large. */
8328 if (used_pattern_len != pattern_len)
9b20d036 8329 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
8330
8331 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
8332 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8333 || packet_ok (rs->buf, packet) != PACKET_OK)
8334 {
8335 /* The request may not have worked because the command is not
8336 supported. If so, fall back to the simple way. */
8337 if (packet->support == PACKET_DISABLE)
8338 {
8339 return simple_search_memory (ops, start_addr, search_space_len,
8340 pattern, pattern_len, found_addrp);
8341 }
8342 return -1;
8343 }
8344
8345 if (rs->buf[0] == '0')
8346 found = 0;
8347 else if (rs->buf[0] == '1')
8348 {
8349 found = 1;
8350 if (rs->buf[1] != ',')
10e0fa18 8351 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
8352 unpack_varlen_hex (rs->buf + 2, &found_addr);
8353 *found_addrp = found_addr;
8354 }
8355 else
10e0fa18 8356 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
8357
8358 return found;
8359}
8360
96baa820
JM
8361static void
8362remote_rcmd (char *command,
d9fcf2fb 8363 struct ui_file *outbuf)
96baa820 8364{
d01949b6 8365 struct remote_state *rs = get_remote_state ();
2e9f7625 8366 char *p = rs->buf;
96baa820
JM
8367
8368 if (!remote_desc)
8a3fe4f8 8369 error (_("remote rcmd is only available after target open"));
96baa820 8370
23860348 8371 /* Send a NULL command across as an empty command. */
7be570e7
JM
8372 if (command == NULL)
8373 command = "";
8374
23860348 8375 /* The query prefix. */
2e9f7625
DJ
8376 strcpy (rs->buf, "qRcmd,");
8377 p = strchr (rs->buf, '\0');
96baa820 8378
3e43a32a
MS
8379 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
8380 > get_remote_packet_size ())
8a3fe4f8 8381 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 8382
23860348 8383 /* Encode the actual command. */
cfd77fa1 8384 bin2hex ((gdb_byte *) command, p, 0);
96baa820 8385
6d820c5c 8386 if (putpkt (rs->buf) < 0)
8a3fe4f8 8387 error (_("Communication problem with target."));
96baa820
JM
8388
8389 /* get/display the response */
8390 while (1)
8391 {
2e9f7625
DJ
8392 char *buf;
8393
00bf0b85 8394 /* XXX - see also remote_get_noisy_reply(). */
2e9f7625 8395 rs->buf[0] = '\0';
6d820c5c 8396 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 8397 buf = rs->buf;
96baa820 8398 if (buf[0] == '\0')
8a3fe4f8 8399 error (_("Target does not support this command."));
96baa820
JM
8400 if (buf[0] == 'O' && buf[1] != 'K')
8401 {
23860348 8402 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
8403 continue;
8404 }
8405 if (strcmp (buf, "OK") == 0)
8406 break;
7be570e7
JM
8407 if (strlen (buf) == 3 && buf[0] == 'E'
8408 && isdigit (buf[1]) && isdigit (buf[2]))
8409 {
8a3fe4f8 8410 error (_("Protocol error with Rcmd"));
7be570e7 8411 }
96baa820
JM
8412 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
8413 {
8414 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 8415
96baa820
JM
8416 fputc_unfiltered (c, outbuf);
8417 }
8418 break;
8419 }
8420}
8421
fd79ecee
DJ
8422static VEC(mem_region_s) *
8423remote_memory_map (struct target_ops *ops)
8424{
8425 VEC(mem_region_s) *result = NULL;
8426 char *text = target_read_stralloc (&current_target,
8427 TARGET_OBJECT_MEMORY_MAP, NULL);
8428
8429 if (text)
8430 {
8431 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 8432
fd79ecee
DJ
8433 result = parse_memory_map (text);
8434 do_cleanups (back_to);
8435 }
8436
8437 return result;
8438}
8439
c906108c 8440static void
fba45db2 8441packet_command (char *args, int from_tty)
c906108c 8442{
d01949b6 8443 struct remote_state *rs = get_remote_state ();
c906108c 8444
c5aa993b 8445 if (!remote_desc)
8a3fe4f8 8446 error (_("command can only be used with remote target"));
c906108c 8447
c5aa993b 8448 if (!args)
8a3fe4f8 8449 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
8450
8451 puts_filtered ("sending: ");
8452 print_packet (args);
8453 puts_filtered ("\n");
8454 putpkt (args);
8455
6d820c5c 8456 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 8457 puts_filtered ("received: ");
6d820c5c 8458 print_packet (rs->buf);
c906108c
SS
8459 puts_filtered ("\n");
8460}
8461
8462#if 0
23860348 8463/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 8464
a14ed312 8465static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 8466
a14ed312 8467static void threadset_test_cmd (char *cmd, int tty);
c906108c 8468
a14ed312 8469static void threadalive_test (char *cmd, int tty);
c906108c 8470
a14ed312 8471static void threadlist_test_cmd (char *cmd, int tty);
c906108c 8472
23860348 8473int get_and_display_threadinfo (threadref *ref);
c906108c 8474
a14ed312 8475static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 8476
23860348 8477static int thread_display_step (threadref *ref, void *context);
c906108c 8478
a14ed312 8479static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 8480
a14ed312 8481static void init_remote_threadtests (void);
c906108c 8482
23860348 8483#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
8484
8485static void
fba45db2 8486threadset_test_cmd (char *cmd, int tty)
c906108c
SS
8487{
8488 int sample_thread = SAMPLE_THREAD;
8489
a3f17187 8490 printf_filtered (_("Remote threadset test\n"));
79d7f229 8491 set_general_thread (sample_thread);
c906108c
SS
8492}
8493
8494
8495static void
fba45db2 8496threadalive_test (char *cmd, int tty)
c906108c
SS
8497{
8498 int sample_thread = SAMPLE_THREAD;
79d7f229
PA
8499 int pid = ptid_get_pid (inferior_ptid);
8500 ptid_t ptid = ptid_build (pid, 0, sample_thread);
c906108c 8501
79d7f229 8502 if (remote_thread_alive (ptid))
c906108c
SS
8503 printf_filtered ("PASS: Thread alive test\n");
8504 else
8505 printf_filtered ("FAIL: Thread alive test\n");
8506}
8507
23860348 8508void output_threadid (char *title, threadref *ref);
c906108c
SS
8509
8510void
fba45db2 8511output_threadid (char *title, threadref *ref)
c906108c
SS
8512{
8513 char hexid[20];
8514
23860348 8515 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
8516 hexid[16] = 0;
8517 printf_filtered ("%s %s\n", title, (&hexid[0]));
8518}
8519
8520static void
fba45db2 8521threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
8522{
8523 int startflag = 1;
8524 threadref nextthread;
8525 int done, result_count;
8526 threadref threadlist[3];
8527
8528 printf_filtered ("Remote Threadlist test\n");
8529 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
8530 &result_count, &threadlist[0]))
8531 printf_filtered ("FAIL: threadlist test\n");
8532 else
8533 {
8534 threadref *scan = threadlist;
8535 threadref *limit = scan + result_count;
8536
8537 while (scan < limit)
8538 output_threadid (" thread ", scan++);
8539 }
8540}
8541
8542void
fba45db2 8543display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
8544{
8545 output_threadid ("Threadid: ", &info->threadid);
8546 printf_filtered ("Name: %s\n ", info->shortname);
8547 printf_filtered ("State: %s\n", info->display);
8548 printf_filtered ("other: %s\n\n", info->more_display);
8549}
8550
8551int
fba45db2 8552get_and_display_threadinfo (threadref *ref)
c906108c
SS
8553{
8554 int result;
8555 int set;
8556 struct gdb_ext_thread_info threadinfo;
8557
8558 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
8559 | TAG_MOREDISPLAY | TAG_DISPLAY;
8560 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
8561 display_thread_info (&threadinfo);
8562 return result;
8563}
8564
8565static void
fba45db2 8566threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
8567{
8568 int athread = SAMPLE_THREAD;
8569 threadref thread;
8570 int set;
8571
8572 int_to_threadref (&thread, athread);
8573 printf_filtered ("Remote Threadinfo test\n");
8574 if (!get_and_display_threadinfo (&thread))
8575 printf_filtered ("FAIL cannot get thread info\n");
8576}
8577
8578static int
fba45db2 8579thread_display_step (threadref *ref, void *context)
c906108c
SS
8580{
8581 /* output_threadid(" threadstep ",ref); *//* simple test */
8582 return get_and_display_threadinfo (ref);
8583}
8584
8585static void
fba45db2 8586threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
8587{
8588 printf_filtered ("Remote Threadlist update test\n");
8589 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
8590}
8591
8592static void
8593init_remote_threadtests (void)
8594{
3e43a32a
MS
8595 add_com ("tlist", class_obscure, threadlist_test_cmd,
8596 _("Fetch and print the remote list of "
8597 "thread identifiers, one pkt only"));
c906108c 8598 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 8599 _("Fetch and display info about one thread"));
c906108c 8600 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 8601 _("Test setting to a different thread"));
c906108c 8602 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 8603 _("Iterate through updating all remote thread info"));
c906108c 8604 add_com ("talive", class_obscure, threadalive_test,
1bedd215 8605 _(" Remote thread alive test "));
c906108c
SS
8606}
8607
8608#endif /* 0 */
8609
f3fb8c85
MS
8610/* Convert a thread ID to a string. Returns the string in a static
8611 buffer. */
8612
8613static char *
117de6a9 8614remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 8615{
79d7f229 8616 static char buf[64];
82f73884 8617 struct remote_state *rs = get_remote_state ();
f3fb8c85 8618
ecd0ada5
PA
8619 if (ptid_is_pid (ptid))
8620 {
8621 /* Printing an inferior target id. */
8622
8623 /* When multi-process extensions are off, there's no way in the
8624 remote protocol to know the remote process id, if there's any
8625 at all. There's one exception --- when we're connected with
8626 target extended-remote, and we manually attached to a process
8627 with "attach PID". We don't record anywhere a flag that
8628 allows us to distinguish that case from the case of
8629 connecting with extended-remote and the stub already being
8630 attached to a process, and reporting yes to qAttached, hence
8631 no smart special casing here. */
8632 if (!remote_multi_process_p (rs))
8633 {
8634 xsnprintf (buf, sizeof buf, "Remote target");
8635 return buf;
8636 }
8637
8638 return normal_pid_to_str (ptid);
82f73884 8639 }
ecd0ada5 8640 else
79d7f229 8641 {
ecd0ada5
PA
8642 if (ptid_equal (magic_null_ptid, ptid))
8643 xsnprintf (buf, sizeof buf, "Thread <main>");
8644 else if (remote_multi_process_p (rs))
8645 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
8646 ptid_get_pid (ptid), ptid_get_tid (ptid));
8647 else
8648 xsnprintf (buf, sizeof buf, "Thread %ld",
8649 ptid_get_tid (ptid));
79d7f229
PA
8650 return buf;
8651 }
f3fb8c85
MS
8652}
8653
38691318
KB
8654/* Get the address of the thread local variable in OBJFILE which is
8655 stored at OFFSET within the thread local storage for thread PTID. */
8656
8657static CORE_ADDR
117de6a9
PA
8658remote_get_thread_local_address (struct target_ops *ops,
8659 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 8660{
444abaca 8661 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
38691318
KB
8662 {
8663 struct remote_state *rs = get_remote_state ();
6d820c5c 8664 char *p = rs->buf;
82f73884 8665 char *endp = rs->buf + get_remote_packet_size ();
571dd617 8666 enum packet_result result;
38691318
KB
8667
8668 strcpy (p, "qGetTLSAddr:");
8669 p += strlen (p);
82f73884 8670 p = write_ptid (p, endp, ptid);
38691318
KB
8671 *p++ = ',';
8672 p += hexnumstr (p, offset);
8673 *p++ = ',';
8674 p += hexnumstr (p, lm);
8675 *p++ = '\0';
8676
6d820c5c
DJ
8677 putpkt (rs->buf);
8678 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
8679 result = packet_ok (rs->buf,
8680 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 8681 if (result == PACKET_OK)
38691318
KB
8682 {
8683 ULONGEST result;
8684
6d820c5c 8685 unpack_varlen_hex (rs->buf, &result);
38691318
KB
8686 return result;
8687 }
571dd617 8688 else if (result == PACKET_UNKNOWN)
109c3e39
AC
8689 throw_error (TLS_GENERIC_ERROR,
8690 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 8691 else
109c3e39
AC
8692 throw_error (TLS_GENERIC_ERROR,
8693 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
8694 }
8695 else
109c3e39
AC
8696 throw_error (TLS_GENERIC_ERROR,
8697 _("TLS not supported or disabled on this target"));
38691318
KB
8698 /* Not reached. */
8699 return 0;
8700}
8701
711e434b
PM
8702/* Provide thread local base, i.e. Thread Information Block address.
8703 Returns 1 if ptid is found and thread_local_base is non zero. */
8704
8705int
8706remote_get_tib_address (ptid_t ptid, CORE_ADDR *addr)
8707{
8708 if (remote_protocol_packets[PACKET_qGetTIBAddr].support != PACKET_DISABLE)
8709 {
8710 struct remote_state *rs = get_remote_state ();
8711 char *p = rs->buf;
8712 char *endp = rs->buf + get_remote_packet_size ();
8713 enum packet_result result;
8714
8715 strcpy (p, "qGetTIBAddr:");
8716 p += strlen (p);
8717 p = write_ptid (p, endp, ptid);
8718 *p++ = '\0';
8719
8720 putpkt (rs->buf);
8721 getpkt (&rs->buf, &rs->buf_size, 0);
8722 result = packet_ok (rs->buf,
8723 &remote_protocol_packets[PACKET_qGetTIBAddr]);
8724 if (result == PACKET_OK)
8725 {
8726 ULONGEST result;
8727
8728 unpack_varlen_hex (rs->buf, &result);
8729 if (addr)
8730 *addr = (CORE_ADDR) result;
8731 return 1;
8732 }
8733 else if (result == PACKET_UNKNOWN)
8734 error (_("Remote target doesn't support qGetTIBAddr packet"));
8735 else
8736 error (_("Remote target failed to process qGetTIBAddr request"));
8737 }
8738 else
8739 error (_("qGetTIBAddr not supported or disabled on this target"));
8740 /* Not reached. */
8741 return 0;
8742}
8743
29709017
DJ
8744/* Support for inferring a target description based on the current
8745 architecture and the size of a 'g' packet. While the 'g' packet
8746 can have any size (since optional registers can be left off the
8747 end), some sizes are easily recognizable given knowledge of the
8748 approximate architecture. */
8749
8750struct remote_g_packet_guess
8751{
8752 int bytes;
8753 const struct target_desc *tdesc;
8754};
8755typedef struct remote_g_packet_guess remote_g_packet_guess_s;
8756DEF_VEC_O(remote_g_packet_guess_s);
8757
8758struct remote_g_packet_data
8759{
8760 VEC(remote_g_packet_guess_s) *guesses;
8761};
8762
8763static struct gdbarch_data *remote_g_packet_data_handle;
8764
8765static void *
8766remote_g_packet_data_init (struct obstack *obstack)
8767{
8768 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
8769}
8770
8771void
8772register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
8773 const struct target_desc *tdesc)
8774{
8775 struct remote_g_packet_data *data
8776 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
8777 struct remote_g_packet_guess new_guess, *guess;
8778 int ix;
8779
8780 gdb_assert (tdesc != NULL);
8781
8782 for (ix = 0;
8783 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
8784 ix++)
8785 if (guess->bytes == bytes)
8786 internal_error (__FILE__, __LINE__,
9b20d036 8787 _("Duplicate g packet description added for size %d"),
29709017
DJ
8788 bytes);
8789
8790 new_guess.bytes = bytes;
8791 new_guess.tdesc = tdesc;
8792 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
8793}
8794
d962ef82
DJ
8795/* Return 1 if remote_read_description would do anything on this target
8796 and architecture, 0 otherwise. */
8797
8798static int
8799remote_read_description_p (struct target_ops *target)
8800{
8801 struct remote_g_packet_data *data
8802 = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
8803
8804 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
8805 return 1;
8806
8807 return 0;
8808}
8809
29709017
DJ
8810static const struct target_desc *
8811remote_read_description (struct target_ops *target)
8812{
8813 struct remote_g_packet_data *data
1cf3db46 8814 = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
29709017 8815
d962ef82
DJ
8816 /* Do not try this during initial connection, when we do not know
8817 whether there is a running but stopped thread. */
8818 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
8819 return NULL;
8820
29709017
DJ
8821 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
8822 {
8823 struct remote_g_packet_guess *guess;
8824 int ix;
8825 int bytes = send_g_packet ();
8826
8827 for (ix = 0;
8828 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
8829 ix++)
8830 if (guess->bytes == bytes)
8831 return guess->tdesc;
8832
8833 /* We discard the g packet. A minor optimization would be to
8834 hold on to it, and fill the register cache once we have selected
8835 an architecture, but it's too tricky to do safely. */
8836 }
8837
8838 return NULL;
8839}
8840
a6b151f1
DJ
8841/* Remote file transfer support. This is host-initiated I/O, not
8842 target-initiated; for target-initiated, see remote-fileio.c. */
8843
8844/* If *LEFT is at least the length of STRING, copy STRING to
8845 *BUFFER, update *BUFFER to point to the new end of the buffer, and
8846 decrease *LEFT. Otherwise raise an error. */
8847
8848static void
8849remote_buffer_add_string (char **buffer, int *left, char *string)
8850{
8851 int len = strlen (string);
8852
8853 if (len > *left)
8854 error (_("Packet too long for target."));
8855
8856 memcpy (*buffer, string, len);
8857 *buffer += len;
8858 *left -= len;
8859
8860 /* NUL-terminate the buffer as a convenience, if there is
8861 room. */
8862 if (*left)
8863 **buffer = '\0';
8864}
8865
8866/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
8867 *BUFFER, update *BUFFER to point to the new end of the buffer, and
8868 decrease *LEFT. Otherwise raise an error. */
8869
8870static void
8871remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
8872 int len)
8873{
8874 if (2 * len > *left)
8875 error (_("Packet too long for target."));
8876
8877 bin2hex (bytes, *buffer, len);
8878 *buffer += 2 * len;
8879 *left -= 2 * len;
8880
8881 /* NUL-terminate the buffer as a convenience, if there is
8882 room. */
8883 if (*left)
8884 **buffer = '\0';
8885}
8886
8887/* If *LEFT is large enough, convert VALUE to hex and add it to
8888 *BUFFER, update *BUFFER to point to the new end of the buffer, and
8889 decrease *LEFT. Otherwise raise an error. */
8890
8891static void
8892remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
8893{
8894 int len = hexnumlen (value);
8895
8896 if (len > *left)
8897 error (_("Packet too long for target."));
8898
8899 hexnumstr (*buffer, value);
8900 *buffer += len;
8901 *left -= len;
8902
8903 /* NUL-terminate the buffer as a convenience, if there is
8904 room. */
8905 if (*left)
8906 **buffer = '\0';
8907}
8908
8909/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
8910 value, *REMOTE_ERRNO to the remote error number or zero if none
8911 was included, and *ATTACHMENT to point to the start of the annex
8912 if any. The length of the packet isn't needed here; there may
8913 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
8914
8915 Return 0 if the packet could be parsed, -1 if it could not. If
8916 -1 is returned, the other variables may not be initialized. */
8917
8918static int
8919remote_hostio_parse_result (char *buffer, int *retcode,
8920 int *remote_errno, char **attachment)
8921{
8922 char *p, *p2;
8923
8924 *remote_errno = 0;
8925 *attachment = NULL;
8926
8927 if (buffer[0] != 'F')
8928 return -1;
8929
8930 errno = 0;
8931 *retcode = strtol (&buffer[1], &p, 16);
8932 if (errno != 0 || p == &buffer[1])
8933 return -1;
8934
8935 /* Check for ",errno". */
8936 if (*p == ',')
8937 {
8938 errno = 0;
8939 *remote_errno = strtol (p + 1, &p2, 16);
8940 if (errno != 0 || p + 1 == p2)
8941 return -1;
8942 p = p2;
8943 }
8944
8945 /* Check for ";attachment". If there is no attachment, the
8946 packet should end here. */
8947 if (*p == ';')
8948 {
8949 *attachment = p + 1;
8950 return 0;
8951 }
8952 else if (*p == '\0')
8953 return 0;
8954 else
8955 return -1;
8956}
8957
8958/* Send a prepared I/O packet to the target and read its response.
8959 The prepared packet is in the global RS->BUF before this function
8960 is called, and the answer is there when we return.
8961
8962 COMMAND_BYTES is the length of the request to send, which may include
8963 binary data. WHICH_PACKET is the packet configuration to check
8964 before attempting a packet. If an error occurs, *REMOTE_ERRNO
8965 is set to the error number and -1 is returned. Otherwise the value
8966 returned by the function is returned.
8967
8968 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
8969 attachment is expected; an error will be reported if there's a
8970 mismatch. If one is found, *ATTACHMENT will be set to point into
8971 the packet buffer and *ATTACHMENT_LEN will be set to the
8972 attachment's length. */
8973
8974static int
8975remote_hostio_send_command (int command_bytes, int which_packet,
8976 int *remote_errno, char **attachment,
8977 int *attachment_len)
8978{
8979 struct remote_state *rs = get_remote_state ();
8980 int ret, bytes_read;
8981 char *attachment_tmp;
8982
f1838a98
UW
8983 if (!remote_desc
8984 || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
a6b151f1
DJ
8985 {
8986 *remote_errno = FILEIO_ENOSYS;
8987 return -1;
8988 }
8989
8990 putpkt_binary (rs->buf, command_bytes);
8991 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8992
8993 /* If it timed out, something is wrong. Don't try to parse the
8994 buffer. */
8995 if (bytes_read < 0)
8996 {
8997 *remote_errno = FILEIO_EINVAL;
8998 return -1;
8999 }
9000
9001 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9002 {
9003 case PACKET_ERROR:
9004 *remote_errno = FILEIO_EINVAL;
9005 return -1;
9006 case PACKET_UNKNOWN:
9007 *remote_errno = FILEIO_ENOSYS;
9008 return -1;
9009 case PACKET_OK:
9010 break;
9011 }
9012
9013 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9014 &attachment_tmp))
9015 {
9016 *remote_errno = FILEIO_EINVAL;
9017 return -1;
9018 }
9019
9020 /* Make sure we saw an attachment if and only if we expected one. */
9021 if ((attachment_tmp == NULL && attachment != NULL)
9022 || (attachment_tmp != NULL && attachment == NULL))
9023 {
9024 *remote_errno = FILEIO_EINVAL;
9025 return -1;
9026 }
9027
9028 /* If an attachment was found, it must point into the packet buffer;
9029 work out how many bytes there were. */
9030 if (attachment_tmp != NULL)
9031 {
9032 *attachment = attachment_tmp;
9033 *attachment_len = bytes_read - (*attachment - rs->buf);
9034 }
9035
9036 return ret;
9037}
9038
9039/* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9040 remote file descriptor, or -1 if an error occurs (and set
9041 *REMOTE_ERRNO). */
9042
9043static int
9044remote_hostio_open (const char *filename, int flags, int mode,
9045 int *remote_errno)
9046{
9047 struct remote_state *rs = get_remote_state ();
9048 char *p = rs->buf;
9049 int left = get_remote_packet_size () - 1;
9050
9051 remote_buffer_add_string (&p, &left, "vFile:open:");
9052
9053 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9054 strlen (filename));
9055 remote_buffer_add_string (&p, &left, ",");
9056
9057 remote_buffer_add_int (&p, &left, flags);
9058 remote_buffer_add_string (&p, &left, ",");
9059
9060 remote_buffer_add_int (&p, &left, mode);
9061
9062 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9063 remote_errno, NULL, NULL);
9064}
9065
9066/* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9067 Return the number of bytes written, or -1 if an error occurs (and
9068 set *REMOTE_ERRNO). */
9069
9070static int
9071remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
9072 ULONGEST offset, int *remote_errno)
9073{
9074 struct remote_state *rs = get_remote_state ();
9075 char *p = rs->buf;
9076 int left = get_remote_packet_size ();
9077 int out_len;
9078
9079 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9080
9081 remote_buffer_add_int (&p, &left, fd);
9082 remote_buffer_add_string (&p, &left, ",");
9083
9084 remote_buffer_add_int (&p, &left, offset);
9085 remote_buffer_add_string (&p, &left, ",");
9086
9087 p += remote_escape_output (write_buf, len, p, &out_len,
9088 get_remote_packet_size () - (p - rs->buf));
9089
9090 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9091 remote_errno, NULL, NULL);
9092}
9093
9094/* Read up to LEN bytes FD on the remote target into READ_BUF
9095 Return the number of bytes read, or -1 if an error occurs (and
9096 set *REMOTE_ERRNO). */
9097
9098static int
9099remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
9100 ULONGEST offset, int *remote_errno)
9101{
9102 struct remote_state *rs = get_remote_state ();
9103 char *p = rs->buf;
9104 char *attachment;
9105 int left = get_remote_packet_size ();
9106 int ret, attachment_len;
9107 int read_len;
9108
9109 remote_buffer_add_string (&p, &left, "vFile:pread:");
9110
9111 remote_buffer_add_int (&p, &left, fd);
9112 remote_buffer_add_string (&p, &left, ",");
9113
9114 remote_buffer_add_int (&p, &left, len);
9115 remote_buffer_add_string (&p, &left, ",");
9116
9117 remote_buffer_add_int (&p, &left, offset);
9118
9119 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9120 remote_errno, &attachment,
9121 &attachment_len);
9122
9123 if (ret < 0)
9124 return ret;
9125
9126 read_len = remote_unescape_input (attachment, attachment_len,
9127 read_buf, len);
9128 if (read_len != ret)
9129 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9130
9131 return ret;
9132}
9133
9134/* Close FD on the remote target. Return 0, or -1 if an error occurs
9135 (and set *REMOTE_ERRNO). */
9136
9137static int
9138remote_hostio_close (int fd, int *remote_errno)
9139{
9140 struct remote_state *rs = get_remote_state ();
9141 char *p = rs->buf;
9142 int left = get_remote_packet_size () - 1;
9143
9144 remote_buffer_add_string (&p, &left, "vFile:close:");
9145
9146 remote_buffer_add_int (&p, &left, fd);
9147
9148 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
9149 remote_errno, NULL, NULL);
9150}
9151
9152/* Unlink FILENAME on the remote target. Return 0, or -1 if an error
9153 occurs (and set *REMOTE_ERRNO). */
9154
9155static int
9156remote_hostio_unlink (const char *filename, int *remote_errno)
9157{
9158 struct remote_state *rs = get_remote_state ();
9159 char *p = rs->buf;
9160 int left = get_remote_packet_size () - 1;
9161
9162 remote_buffer_add_string (&p, &left, "vFile:unlink:");
9163
9164 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9165 strlen (filename));
9166
9167 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
9168 remote_errno, NULL, NULL);
9169}
9170
9171static int
9172remote_fileio_errno_to_host (int errnum)
9173{
9174 switch (errnum)
9175 {
9176 case FILEIO_EPERM:
9177 return EPERM;
9178 case FILEIO_ENOENT:
9179 return ENOENT;
9180 case FILEIO_EINTR:
9181 return EINTR;
9182 case FILEIO_EIO:
9183 return EIO;
9184 case FILEIO_EBADF:
9185 return EBADF;
9186 case FILEIO_EACCES:
9187 return EACCES;
9188 case FILEIO_EFAULT:
9189 return EFAULT;
9190 case FILEIO_EBUSY:
9191 return EBUSY;
9192 case FILEIO_EEXIST:
9193 return EEXIST;
9194 case FILEIO_ENODEV:
9195 return ENODEV;
9196 case FILEIO_ENOTDIR:
9197 return ENOTDIR;
9198 case FILEIO_EISDIR:
9199 return EISDIR;
9200 case FILEIO_EINVAL:
9201 return EINVAL;
9202 case FILEIO_ENFILE:
9203 return ENFILE;
9204 case FILEIO_EMFILE:
9205 return EMFILE;
9206 case FILEIO_EFBIG:
9207 return EFBIG;
9208 case FILEIO_ENOSPC:
9209 return ENOSPC;
9210 case FILEIO_ESPIPE:
9211 return ESPIPE;
9212 case FILEIO_EROFS:
9213 return EROFS;
9214 case FILEIO_ENOSYS:
9215 return ENOSYS;
9216 case FILEIO_ENAMETOOLONG:
9217 return ENAMETOOLONG;
9218 }
9219 return -1;
9220}
9221
9222static char *
9223remote_hostio_error (int errnum)
9224{
9225 int host_error = remote_fileio_errno_to_host (errnum);
9226
9227 if (host_error == -1)
9228 error (_("Unknown remote I/O error %d"), errnum);
9229 else
9230 error (_("Remote I/O error: %s"), safe_strerror (host_error));
9231}
9232
a6b151f1
DJ
9233static void
9234remote_hostio_close_cleanup (void *opaque)
9235{
9236 int fd = *(int *) opaque;
9237 int remote_errno;
9238
9239 remote_hostio_close (fd, &remote_errno);
9240}
9241
f1838a98
UW
9242
9243static void *
9244remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
9245{
9246 const char *filename = bfd_get_filename (abfd);
9247 int fd, remote_errno;
9248 int *stream;
9249
9250 gdb_assert (remote_filename_p (filename));
9251
9252 fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
9253 if (fd == -1)
9254 {
9255 errno = remote_fileio_errno_to_host (remote_errno);
9256 bfd_set_error (bfd_error_system_call);
9257 return NULL;
9258 }
9259
9260 stream = xmalloc (sizeof (int));
9261 *stream = fd;
9262 return stream;
9263}
9264
9265static int
9266remote_bfd_iovec_close (struct bfd *abfd, void *stream)
9267{
9268 int fd = *(int *)stream;
9269 int remote_errno;
9270
9271 xfree (stream);
9272
9273 /* Ignore errors on close; these may happen if the remote
9274 connection was already torn down. */
9275 remote_hostio_close (fd, &remote_errno);
9276
9277 return 1;
9278}
9279
9280static file_ptr
9281remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
9282 file_ptr nbytes, file_ptr offset)
9283{
9284 int fd = *(int *)stream;
9285 int remote_errno;
9286 file_ptr pos, bytes;
9287
9288 pos = 0;
9289 while (nbytes > pos)
9290 {
9291 bytes = remote_hostio_pread (fd, (char *)buf + pos, nbytes - pos,
9292 offset + pos, &remote_errno);
9293 if (bytes == 0)
9294 /* Success, but no bytes, means end-of-file. */
9295 break;
9296 if (bytes == -1)
9297 {
9298 errno = remote_fileio_errno_to_host (remote_errno);
9299 bfd_set_error (bfd_error_system_call);
9300 return -1;
9301 }
9302
9303 pos += bytes;
9304 }
9305
9306 return pos;
9307}
9308
9309static int
9310remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
9311{
9312 /* FIXME: We should probably implement remote_hostio_stat. */
9313 sb->st_size = INT_MAX;
9314 return 0;
9315}
9316
9317int
9318remote_filename_p (const char *filename)
9319{
9320 return strncmp (filename, "remote:", 7) == 0;
9321}
9322
9323bfd *
9324remote_bfd_open (const char *remote_file, const char *target)
9325{
9326 return bfd_openr_iovec (remote_file, target,
9327 remote_bfd_iovec_open, NULL,
9328 remote_bfd_iovec_pread,
9329 remote_bfd_iovec_close,
9330 remote_bfd_iovec_stat);
9331}
9332
a6b151f1
DJ
9333void
9334remote_file_put (const char *local_file, const char *remote_file, int from_tty)
9335{
9336 struct cleanup *back_to, *close_cleanup;
9337 int retcode, fd, remote_errno, bytes, io_size;
9338 FILE *file;
9339 gdb_byte *buffer;
9340 int bytes_in_buffer;
9341 int saw_eof;
9342 ULONGEST offset;
9343
9344 if (!remote_desc)
9345 error (_("command can only be used with remote target"));
9346
9347 file = fopen (local_file, "rb");
9348 if (file == NULL)
9349 perror_with_name (local_file);
7c8a8b04 9350 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
9351
9352 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
9353 | FILEIO_O_TRUNC),
9354 0700, &remote_errno);
9355 if (fd == -1)
9356 remote_hostio_error (remote_errno);
9357
9358 /* Send up to this many bytes at once. They won't all fit in the
9359 remote packet limit, so we'll transfer slightly fewer. */
9360 io_size = get_remote_packet_size ();
9361 buffer = xmalloc (io_size);
9362 make_cleanup (xfree, buffer);
9363
9364 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
9365
9366 bytes_in_buffer = 0;
9367 saw_eof = 0;
9368 offset = 0;
9369 while (bytes_in_buffer || !saw_eof)
9370 {
9371 if (!saw_eof)
9372 {
3e43a32a
MS
9373 bytes = fread (buffer + bytes_in_buffer, 1,
9374 io_size - bytes_in_buffer,
a6b151f1
DJ
9375 file);
9376 if (bytes == 0)
9377 {
9378 if (ferror (file))
9379 error (_("Error reading %s."), local_file);
9380 else
9381 {
9382 /* EOF. Unless there is something still in the
9383 buffer from the last iteration, we are done. */
9384 saw_eof = 1;
9385 if (bytes_in_buffer == 0)
9386 break;
9387 }
9388 }
9389 }
9390 else
9391 bytes = 0;
9392
9393 bytes += bytes_in_buffer;
9394 bytes_in_buffer = 0;
9395
3e43a32a
MS
9396 retcode = remote_hostio_pwrite (fd, buffer, bytes,
9397 offset, &remote_errno);
a6b151f1
DJ
9398
9399 if (retcode < 0)
9400 remote_hostio_error (remote_errno);
9401 else if (retcode == 0)
9402 error (_("Remote write of %d bytes returned 0!"), bytes);
9403 else if (retcode < bytes)
9404 {
9405 /* Short write. Save the rest of the read data for the next
9406 write. */
9407 bytes_in_buffer = bytes - retcode;
9408 memmove (buffer, buffer + retcode, bytes_in_buffer);
9409 }
9410
9411 offset += retcode;
9412 }
9413
9414 discard_cleanups (close_cleanup);
9415 if (remote_hostio_close (fd, &remote_errno))
9416 remote_hostio_error (remote_errno);
9417
9418 if (from_tty)
9419 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
9420 do_cleanups (back_to);
9421}
9422
9423void
9424remote_file_get (const char *remote_file, const char *local_file, int from_tty)
9425{
9426 struct cleanup *back_to, *close_cleanup;
cea39f65 9427 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
9428 FILE *file;
9429 gdb_byte *buffer;
9430 ULONGEST offset;
9431
9432 if (!remote_desc)
9433 error (_("command can only be used with remote target"));
9434
9435 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
9436 if (fd == -1)
9437 remote_hostio_error (remote_errno);
9438
9439 file = fopen (local_file, "wb");
9440 if (file == NULL)
9441 perror_with_name (local_file);
7c8a8b04 9442 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
9443
9444 /* Send up to this many bytes at once. They won't all fit in the
9445 remote packet limit, so we'll transfer slightly fewer. */
9446 io_size = get_remote_packet_size ();
9447 buffer = xmalloc (io_size);
9448 make_cleanup (xfree, buffer);
9449
9450 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
9451
9452 offset = 0;
9453 while (1)
9454 {
9455 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
9456 if (bytes == 0)
9457 /* Success, but no bytes, means end-of-file. */
9458 break;
9459 if (bytes == -1)
9460 remote_hostio_error (remote_errno);
9461
9462 offset += bytes;
9463
9464 bytes = fwrite (buffer, 1, bytes, file);
9465 if (bytes == 0)
9466 perror_with_name (local_file);
9467 }
9468
9469 discard_cleanups (close_cleanup);
9470 if (remote_hostio_close (fd, &remote_errno))
9471 remote_hostio_error (remote_errno);
9472
9473 if (from_tty)
9474 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
9475 do_cleanups (back_to);
9476}
9477
9478void
9479remote_file_delete (const char *remote_file, int from_tty)
9480{
9481 int retcode, remote_errno;
9482
9483 if (!remote_desc)
9484 error (_("command can only be used with remote target"));
9485
9486 retcode = remote_hostio_unlink (remote_file, &remote_errno);
9487 if (retcode == -1)
9488 remote_hostio_error (remote_errno);
9489
9490 if (from_tty)
9491 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
9492}
9493
9494static void
9495remote_put_command (char *args, int from_tty)
9496{
9497 struct cleanup *back_to;
9498 char **argv;
9499
d1a41061
PP
9500 if (args == NULL)
9501 error_no_arg (_("file to put"));
9502
9503 argv = gdb_buildargv (args);
a6b151f1
DJ
9504 back_to = make_cleanup_freeargv (argv);
9505 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
9506 error (_("Invalid parameters to remote put"));
9507
9508 remote_file_put (argv[0], argv[1], from_tty);
9509
9510 do_cleanups (back_to);
9511}
9512
9513static void
9514remote_get_command (char *args, int from_tty)
9515{
9516 struct cleanup *back_to;
9517 char **argv;
9518
d1a41061
PP
9519 if (args == NULL)
9520 error_no_arg (_("file to get"));
9521
9522 argv = gdb_buildargv (args);
a6b151f1
DJ
9523 back_to = make_cleanup_freeargv (argv);
9524 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
9525 error (_("Invalid parameters to remote get"));
9526
9527 remote_file_get (argv[0], argv[1], from_tty);
9528
9529 do_cleanups (back_to);
9530}
9531
9532static void
9533remote_delete_command (char *args, int from_tty)
9534{
9535 struct cleanup *back_to;
9536 char **argv;
9537
d1a41061
PP
9538 if (args == NULL)
9539 error_no_arg (_("file to delete"));
9540
9541 argv = gdb_buildargv (args);
a6b151f1
DJ
9542 back_to = make_cleanup_freeargv (argv);
9543 if (argv[0] == NULL || argv[1] != NULL)
9544 error (_("Invalid parameters to remote delete"));
9545
9546 remote_file_delete (argv[0], from_tty);
9547
9548 do_cleanups (back_to);
9549}
9550
9551static void
9552remote_command (char *args, int from_tty)
9553{
9554 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
9555}
9556
b2175913
MS
9557static int
9558remote_can_execute_reverse (void)
9559{
40ab02ce
MS
9560 if (remote_protocol_packets[PACKET_bs].support == PACKET_ENABLE
9561 || remote_protocol_packets[PACKET_bc].support == PACKET_ENABLE)
9562 return 1;
9563 else
9564 return 0;
b2175913
MS
9565}
9566
74531fed
PA
9567static int
9568remote_supports_non_stop (void)
9569{
9570 return 1;
9571}
9572
8a305172
PA
9573static int
9574remote_supports_multi_process (void)
9575{
9576 struct remote_state *rs = get_remote_state ();
a744cf53 9577
8a305172
PA
9578 return remote_multi_process_p (rs);
9579}
9580
782b2b07
SS
9581int
9582remote_supports_cond_tracepoints (void)
9583{
9584 struct remote_state *rs = get_remote_state ();
a744cf53 9585
782b2b07
SS
9586 return rs->cond_tracepoints;
9587}
9588
7a697b8d
SS
9589int
9590remote_supports_fast_tracepoints (void)
9591{
9592 struct remote_state *rs = get_remote_state ();
a744cf53 9593
7a697b8d
SS
9594 return rs->fast_tracepoints;
9595}
9596
0fb4aa4b
PA
9597static int
9598remote_supports_static_tracepoints (void)
9599{
9600 struct remote_state *rs = get_remote_state ();
9601
9602 return rs->static_tracepoints;
9603}
9604
35b1e5cc 9605static void
ad91cd99 9606remote_trace_init (void)
35b1e5cc
SS
9607{
9608 putpkt ("QTinit");
9609 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 9610 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
9611 error (_("Target does not support this command."));
9612}
9613
9614static void free_actions_list (char **actions_list);
9615static void free_actions_list_cleanup_wrapper (void *);
9616static void
9617free_actions_list_cleanup_wrapper (void *al)
9618{
9619 free_actions_list (al);
9620}
9621
9622static void
9623free_actions_list (char **actions_list)
9624{
9625 int ndx;
9626
9627 if (actions_list == 0)
9628 return;
9629
9630 for (ndx = 0; actions_list[ndx]; ndx++)
9631 xfree (actions_list[ndx]);
9632
9633 xfree (actions_list);
9634}
9635
409873ef
SS
9636/* Recursive routine to walk through command list including loops, and
9637 download packets for each command. */
9638
9639static void
9640remote_download_command_source (int num, ULONGEST addr,
9641 struct command_line *cmds)
9642{
9643 struct remote_state *rs = get_remote_state ();
9644 struct command_line *cmd;
9645
9646 for (cmd = cmds; cmd; cmd = cmd->next)
9647 {
0df8b418 9648 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
9649 strcpy (rs->buf, "QTDPsrc:");
9650 encode_source_string (num, addr, "cmd", cmd->line,
9651 rs->buf + strlen (rs->buf),
9652 rs->buf_size - strlen (rs->buf));
9653 putpkt (rs->buf);
9654 remote_get_noisy_reply (&target_buf, &target_buf_size);
9655 if (strcmp (target_buf, "OK"))
9656 warning (_("Target does not support source download."));
9657
9658 if (cmd->control_type == while_control
9659 || cmd->control_type == while_stepping_control)
9660 {
9661 remote_download_command_source (num, addr, *cmd->body_list);
9662
0df8b418 9663 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
9664 strcpy (rs->buf, "QTDPsrc:");
9665 encode_source_string (num, addr, "cmd", "end",
9666 rs->buf + strlen (rs->buf),
9667 rs->buf_size - strlen (rs->buf));
9668 putpkt (rs->buf);
9669 remote_get_noisy_reply (&target_buf, &target_buf_size);
9670 if (strcmp (target_buf, "OK"))
9671 warning (_("Target does not support source download."));
9672 }
9673 }
9674}
9675
35b1e5cc
SS
9676static void
9677remote_download_tracepoint (struct breakpoint *t)
9678{
9355b391 9679 struct bp_location *loc;
35b1e5cc 9680 CORE_ADDR tpaddr;
409873ef 9681 char addrbuf[40];
35b1e5cc
SS
9682 char buf[2048];
9683 char **tdp_actions;
9684 char **stepping_actions;
9685 int ndx;
9686 struct cleanup *old_chain = NULL;
9687 struct agent_expr *aexpr;
9688 struct cleanup *aexpr_chain = NULL;
9689 char *pkt;
9690
9355b391
SS
9691 /* Iterate over all the tracepoint locations. It's up to the target to
9692 notice multiple tracepoint packets with the same number but different
9693 addresses, and treat them as multiple locations. */
9694 for (loc = t->loc; loc; loc = loc->next)
9695 {
9696 encode_actions (t, loc, &tdp_actions, &stepping_actions);
9697 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
9698 tdp_actions);
3e43a32a
MS
9699 (void) make_cleanup (free_actions_list_cleanup_wrapper,
9700 stepping_actions);
9355b391
SS
9701
9702 tpaddr = loc->address;
409873ef 9703 sprintf_vma (addrbuf, tpaddr);
9355b391 9704 sprintf (buf, "QTDP:%x:%s:%c:%lx:%x", t->number,
409873ef 9705 addrbuf, /* address */
9355b391
SS
9706 (t->enable_state == bp_enabled ? 'E' : 'D'),
9707 t->step_count, t->pass_count);
9708 /* Fast tracepoints are mostly handled by the target, but we can
9709 tell the target how big of an instruction block should be moved
9710 around. */
9711 if (t->type == bp_fast_tracepoint)
35b1e5cc 9712 {
9355b391
SS
9713 /* Only test for support at download time; we may not know
9714 target capabilities at definition time. */
9715 if (remote_supports_fast_tracepoints ())
9716 {
9717 int isize;
35b1e5cc 9718
9355b391
SS
9719 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch,
9720 tpaddr, &isize, NULL))
9721 sprintf (buf + strlen (buf), ":F%x", isize);
9722 else
9723 /* If it passed validation at definition but fails now,
9724 something is very wrong. */
9725 internal_error (__FILE__, __LINE__,
9b20d036
MS
9726 _("Fast tracepoint not "
9727 "valid during download"));
9355b391 9728 }
35b1e5cc 9729 else
9355b391
SS
9730 /* Fast tracepoints are functionally identical to regular
9731 tracepoints, so don't take lack of support as a reason to
9732 give up on the trace run. */
3e43a32a
MS
9733 warning (_("Target does not support fast tracepoints, "
9734 "downloading %d as regular tracepoint"), t->number);
35b1e5cc 9735 }
0fb4aa4b
PA
9736 else if (t->type == bp_static_tracepoint)
9737 {
9738 /* Only test for support at download time; we may not know
9739 target capabilities at definition time. */
9740 if (remote_supports_static_tracepoints ())
9741 {
9742 struct static_tracepoint_marker marker;
9743
9744 if (target_static_tracepoint_marker_at (tpaddr, &marker))
9745 strcat (buf, ":S");
9746 else
74232302 9747 error (_("Static tracepoint not valid during download"));
0fb4aa4b
PA
9748 }
9749 else
9750 /* Fast tracepoints are functionally identical to regular
9751 tracepoints, so don't take lack of support as a reason
9752 to give up on the trace run. */
9753 error (_("Target does not support static tracepoints"));
9754 }
9355b391
SS
9755 /* If the tracepoint has a conditional, make it into an agent
9756 expression and append to the definition. */
9757 if (loc->cond)
35b1e5cc 9758 {
9355b391
SS
9759 /* Only test support at download time, we may not know target
9760 capabilities at definition time. */
9761 if (remote_supports_cond_tracepoints ())
9762 {
9763 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
9764 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
9765 sprintf (buf + strlen (buf), ":X%x,", aexpr->len);
9766 pkt = buf + strlen (buf);
9767 for (ndx = 0; ndx < aexpr->len; ++ndx)
9768 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
9769 *pkt = '\0';
9770 do_cleanups (aexpr_chain);
9771 }
9772 else
3e43a32a
MS
9773 warning (_("Target does not support conditional tracepoints, "
9774 "ignoring tp %d cond"), t->number);
35b1e5cc 9775 }
35b1e5cc 9776
a7bdde9e 9777 if (t->commands || *default_collect)
9355b391
SS
9778 strcat (buf, "-");
9779 putpkt (buf);
9780 remote_get_noisy_reply (&target_buf, &target_buf_size);
9781 if (strcmp (target_buf, "OK"))
9782 error (_("Target does not support tracepoints."));
35b1e5cc 9783
9355b391
SS
9784 /* do_single_steps (t); */
9785 if (tdp_actions)
35b1e5cc 9786 {
9355b391
SS
9787 for (ndx = 0; tdp_actions[ndx]; ndx++)
9788 {
0df8b418 9789 QUIT; /* Allow user to bail out with ^C. */
9355b391 9790 sprintf (buf, "QTDP:-%x:%s:%s%c",
409873ef 9791 t->number, addrbuf, /* address */
9355b391
SS
9792 tdp_actions[ndx],
9793 ((tdp_actions[ndx + 1] || stepping_actions)
9794 ? '-' : 0));
9795 putpkt (buf);
9796 remote_get_noisy_reply (&target_buf,
9797 &target_buf_size);
9798 if (strcmp (target_buf, "OK"))
9799 error (_("Error on target while setting tracepoints."));
9800 }
35b1e5cc 9801 }
9355b391 9802 if (stepping_actions)
35b1e5cc 9803 {
9355b391
SS
9804 for (ndx = 0; stepping_actions[ndx]; ndx++)
9805 {
0df8b418 9806 QUIT; /* Allow user to bail out with ^C. */
9355b391 9807 sprintf (buf, "QTDP:-%x:%s:%s%s%s",
409873ef 9808 t->number, addrbuf, /* address */
9355b391
SS
9809 ((ndx == 0) ? "S" : ""),
9810 stepping_actions[ndx],
9811 (stepping_actions[ndx + 1] ? "-" : ""));
9812 putpkt (buf);
9813 remote_get_noisy_reply (&target_buf,
9814 &target_buf_size);
9815 if (strcmp (target_buf, "OK"))
9816 error (_("Error on target while setting tracepoints."));
9817 }
35b1e5cc 9818 }
409873ef 9819
3e43a32a
MS
9820 if (remote_protocol_packets[PACKET_TracepointSource].support
9821 == PACKET_ENABLE)
409873ef
SS
9822 {
9823 if (t->addr_string)
9824 {
9825 strcpy (buf, "QTDPsrc:");
9826 encode_source_string (t->number, loc->address,
9827 "at", t->addr_string, buf + strlen (buf),
9828 2048 - strlen (buf));
9829
9830 putpkt (buf);
9831 remote_get_noisy_reply (&target_buf, &target_buf_size);
9832 if (strcmp (target_buf, "OK"))
9833 warning (_("Target does not support source download."));
9834 }
9835 if (t->cond_string)
9836 {
9837 strcpy (buf, "QTDPsrc:");
9838 encode_source_string (t->number, loc->address,
9839 "cond", t->cond_string, buf + strlen (buf),
9840 2048 - strlen (buf));
9841 putpkt (buf);
9842 remote_get_noisy_reply (&target_buf, &target_buf_size);
9843 if (strcmp (target_buf, "OK"))
9844 warning (_("Target does not support source download."));
9845 }
9846 remote_download_command_source (t->number, loc->address,
5cea2a26 9847 breakpoint_commands (t));
409873ef
SS
9848 }
9849
9355b391 9850 do_cleanups (old_chain);
35b1e5cc 9851 }
35b1e5cc
SS
9852}
9853
9854static void
9855remote_download_trace_state_variable (struct trace_state_variable *tsv)
9856{
9857 struct remote_state *rs = get_remote_state ();
00bf0b85 9858 char *p;
35b1e5cc 9859
00bf0b85
SS
9860 sprintf (rs->buf, "QTDV:%x:%s:%x:",
9861 tsv->number, phex ((ULONGEST) tsv->initial_value, 8), tsv->builtin);
9862 p = rs->buf + strlen (rs->buf);
9863 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
9864 error (_("Trace state variable name too long for tsv definition packet"));
9865 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, 0);
9866 *p++ = '\0';
35b1e5cc
SS
9867 putpkt (rs->buf);
9868 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
9869 if (*target_buf == '\0')
9870 error (_("Target does not support this command."));
9871 if (strcmp (target_buf, "OK") != 0)
9872 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
9873}
9874
9875static void
ad91cd99 9876remote_trace_set_readonly_regions (void)
35b1e5cc
SS
9877{
9878 asection *s;
9879 bfd_size_type size;
608bcef2 9880 bfd_vma vma;
35b1e5cc
SS
9881 int anysecs = 0;
9882
9883 if (!exec_bfd)
9884 return; /* No information to give. */
9885
9886 strcpy (target_buf, "QTro");
9887 for (s = exec_bfd->sections; s; s = s->next)
9888 {
9889 char tmp1[40], tmp2[40];
9890
9891 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 9892 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
9893 (s->flags & SEC_READONLY) == 0)
9894 continue;
9895
9896 anysecs = 1;
608bcef2 9897 vma = bfd_get_section_vma (,s);
35b1e5cc 9898 size = bfd_get_section_size (s);
608bcef2
HZ
9899 sprintf_vma (tmp1, vma);
9900 sprintf_vma (tmp2, vma + size);
35b1e5cc
SS
9901 sprintf (target_buf + strlen (target_buf),
9902 ":%s,%s", tmp1, tmp2);
9903 }
9904 if (anysecs)
9905 {
9906 putpkt (target_buf);
9907 getpkt (&target_buf, &target_buf_size, 0);
9908 }
9909}
9910
9911static void
ad91cd99 9912remote_trace_start (void)
35b1e5cc
SS
9913{
9914 putpkt ("QTStart");
9915 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
9916 if (*target_buf == '\0')
9917 error (_("Target does not support this command."));
9918 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
9919 error (_("Bogus reply from target: %s"), target_buf);
9920}
9921
9922static int
00bf0b85 9923remote_get_trace_status (struct trace_status *ts)
35b1e5cc 9924{
aa369b55 9925 char *p;
0df8b418 9926 /* FIXME we need to get register block size some other way. */
00bf0b85 9927 extern int trace_regblock_size;
a744cf53 9928
00bf0b85
SS
9929 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
9930
35b1e5cc 9931 putpkt ("qTStatus");
ad91cd99 9932 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
00bf0b85
SS
9933
9934 /* If the remote target doesn't do tracing, flag it. */
9935 if (*p == '\0')
9936 return -1;
35b1e5cc 9937
00bf0b85
SS
9938 /* We're working with a live target. */
9939 ts->from_file = 0;
9940
9941 /* Set some defaults. */
9942 ts->running_known = 0;
9943 ts->stop_reason = trace_stop_reason_unknown;
9944 ts->traceframe_count = -1;
9945 ts->buffer_free = 0;
9946
9947 if (*p++ != 'T')
35b1e5cc
SS
9948 error (_("Bogus trace status reply from target: %s"), target_buf);
9949
00bf0b85
SS
9950 parse_trace_status (p, ts);
9951
9952 return ts->running;
35b1e5cc
SS
9953}
9954
9955static void
ad91cd99 9956remote_trace_stop (void)
35b1e5cc
SS
9957{
9958 putpkt ("QTStop");
9959 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
9960 if (*target_buf == '\0')
9961 error (_("Target does not support this command."));
9962 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
9963 error (_("Bogus reply from target: %s"), target_buf);
9964}
9965
9966static int
9967remote_trace_find (enum trace_find_type type, int num,
9968 ULONGEST addr1, ULONGEST addr2,
9969 int *tpp)
9970{
9971 struct remote_state *rs = get_remote_state ();
9972 char *p, *reply;
9973 int target_frameno = -1, target_tracept = -1;
9974
9975 p = rs->buf;
9976 strcpy (p, "QTFrame:");
9977 p = strchr (p, '\0');
9978 switch (type)
9979 {
9980 case tfind_number:
9981 sprintf (p, "%x", num);
9982 break;
9983 case tfind_pc:
00bf0b85 9984 sprintf (p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
9985 break;
9986 case tfind_tp:
9987 sprintf (p, "tdp:%x", num);
9988 break;
9989 case tfind_range:
00bf0b85 9990 sprintf (p, "range:%s:%s", phex_nz (addr1, 0), phex_nz (addr2, 0));
35b1e5cc
SS
9991 break;
9992 case tfind_outside:
00bf0b85 9993 sprintf (p, "outside:%s:%s", phex_nz (addr1, 0), phex_nz (addr2, 0));
35b1e5cc
SS
9994 break;
9995 default:
9b20d036 9996 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
9997 }
9998
9999 putpkt (rs->buf);
10000 reply = remote_get_noisy_reply (&(rs->buf), &sizeof_pkt);
ad91cd99
PA
10001 if (*reply == '\0')
10002 error (_("Target does not support this command."));
35b1e5cc
SS
10003
10004 while (reply && *reply)
10005 switch (*reply)
10006 {
10007 case 'F':
f197e0f1
VP
10008 p = ++reply;
10009 target_frameno = (int) strtol (p, &reply, 16);
10010 if (reply == p)
10011 error (_("Unable to parse trace frame number"));
10012 if (target_frameno == -1)
10013 return -1;
35b1e5cc
SS
10014 break;
10015 case 'T':
f197e0f1
VP
10016 p = ++reply;
10017 target_tracept = (int) strtol (p, &reply, 16);
10018 if (reply == p)
10019 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
10020 break;
10021 case 'O': /* "OK"? */
10022 if (reply[1] == 'K' && reply[2] == '\0')
10023 reply += 2;
10024 else
10025 error (_("Bogus reply from target: %s"), reply);
10026 break;
10027 default:
10028 error (_("Bogus reply from target: %s"), reply);
10029 }
10030 if (tpp)
10031 *tpp = target_tracept;
10032 return target_frameno;
10033}
10034
10035static int
10036remote_get_trace_state_variable_value (int tsvnum, LONGEST *val)
10037{
10038 struct remote_state *rs = get_remote_state ();
10039 char *reply;
10040 ULONGEST uval;
10041
10042 sprintf (rs->buf, "qTV:%x", tsvnum);
10043 putpkt (rs->buf);
10044 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10045 if (reply && *reply)
10046 {
10047 if (*reply == 'V')
10048 {
10049 unpack_varlen_hex (reply + 1, &uval);
10050 *val = (LONGEST) uval;
10051 return 1;
10052 }
10053 }
10054 return 0;
10055}
10056
00bf0b85 10057static int
011aacb0 10058remote_save_trace_data (const char *filename)
00bf0b85
SS
10059{
10060 struct remote_state *rs = get_remote_state ();
10061 char *p, *reply;
10062
10063 p = rs->buf;
10064 strcpy (p, "QTSave:");
10065 p += strlen (p);
10066 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
10067 error (_("Remote file name too long for trace save packet"));
10068 p += 2 * bin2hex ((gdb_byte *) filename, p, 0);
10069 *p++ = '\0';
10070 putpkt (rs->buf);
ad91cd99
PA
10071 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10072 if (*reply != '\0')
10073 error (_("Target does not support this command."));
10074 if (strcmp (reply, "OK") != 0)
10075 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
10076 return 0;
10077}
10078
10079/* This is basically a memory transfer, but needs to be its own packet
10080 because we don't know how the target actually organizes its trace
10081 memory, plus we want to be able to ask for as much as possible, but
10082 not be unhappy if we don't get as much as we ask for. */
10083
10084static LONGEST
10085remote_get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
10086{
10087 struct remote_state *rs = get_remote_state ();
10088 char *reply;
10089 char *p;
10090 int rslt;
10091
10092 p = rs->buf;
10093 strcpy (p, "qTBuffer:");
10094 p += strlen (p);
10095 p += hexnumstr (p, offset);
10096 *p++ = ',';
10097 p += hexnumstr (p, len);
10098 *p++ = '\0';
10099
10100 putpkt (rs->buf);
10101 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10102 if (reply && *reply)
10103 {
10104 /* 'l' by itself means we're at the end of the buffer and
10105 there is nothing more to get. */
10106 if (*reply == 'l')
10107 return 0;
10108
10109 /* Convert the reply into binary. Limit the number of bytes to
10110 convert according to our passed-in buffer size, rather than
10111 what was returned in the packet; if the target is
10112 unexpectedly generous and gives us a bigger reply than we
10113 asked for, we don't want to crash. */
10114 rslt = hex2bin (target_buf, buf, len);
10115 return rslt;
10116 }
10117
10118 /* Something went wrong, flag as an error. */
10119 return -1;
10120}
10121
35b1e5cc
SS
10122static void
10123remote_set_disconnected_tracing (int val)
10124{
10125 struct remote_state *rs = get_remote_state ();
10126
33da3f1c
SS
10127 if (rs->disconnected_tracing)
10128 {
ad91cd99
PA
10129 char *reply;
10130
33da3f1c
SS
10131 sprintf (rs->buf, "QTDisconnected:%x", val);
10132 putpkt (rs->buf);
ad91cd99
PA
10133 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10134 if (*reply == '\0')
33da3f1c 10135 error (_("Target does not support this command."));
ad91cd99
PA
10136 if (strcmp (reply, "OK") != 0)
10137 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
10138 }
10139 else if (val)
10140 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
10141}
10142
dc146f7c
VP
10143static int
10144remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
10145{
10146 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 10147
dc146f7c
VP
10148 if (info && info->private)
10149 return info->private->core;
10150 return -1;
10151}
10152
4daf5ac0
SS
10153static void
10154remote_set_circular_trace_buffer (int val)
10155{
10156 struct remote_state *rs = get_remote_state ();
ad91cd99 10157 char *reply;
4daf5ac0
SS
10158
10159 sprintf (rs->buf, "QTBuffer:circular:%x", val);
10160 putpkt (rs->buf);
ad91cd99
PA
10161 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10162 if (*reply == '\0')
4daf5ac0 10163 error (_("Target does not support this command."));
ad91cd99
PA
10164 if (strcmp (reply, "OK") != 0)
10165 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
10166}
10167
b3b9301e
PA
10168static struct traceframe_info *
10169remote_traceframe_info (void)
10170{
10171 char *text;
10172
10173 text = target_read_stralloc (&current_target,
10174 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
10175 if (text != NULL)
10176 {
10177 struct traceframe_info *info;
10178 struct cleanup *back_to = make_cleanup (xfree, text);
10179
10180 info = parse_traceframe_info (text);
10181 do_cleanups (back_to);
10182 return info;
10183 }
10184
10185 return NULL;
10186}
10187
c906108c 10188static void
fba45db2 10189init_remote_ops (void)
c906108c 10190{
c5aa993b 10191 remote_ops.to_shortname = "remote";
c906108c 10192 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 10193 remote_ops.to_doc =
c906108c 10194 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
10195Specify the serial device it is connected to\n\
10196(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
10197 remote_ops.to_open = remote_open;
10198 remote_ops.to_close = remote_close;
c906108c 10199 remote_ops.to_detach = remote_detach;
6ad8ae5c 10200 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 10201 remote_ops.to_resume = remote_resume;
c906108c
SS
10202 remote_ops.to_wait = remote_wait;
10203 remote_ops.to_fetch_registers = remote_fetch_registers;
10204 remote_ops.to_store_registers = remote_store_registers;
10205 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c8e73a31 10206 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
c5aa993b 10207 remote_ops.to_files_info = remote_files_info;
c906108c
SS
10208 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
10209 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
3c3bea1c
GS
10210 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
10211 remote_ops.to_stopped_data_address = remote_stopped_data_address;
10212 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
10213 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
10214 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
10215 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
10216 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b
JM
10217 remote_ops.to_kill = remote_kill;
10218 remote_ops.to_load = generic_load;
c906108c 10219 remote_ops.to_mourn_inferior = remote_mourn;
f0223081 10220 remote_ops.to_notice_signals = remote_notice_signals;
c906108c 10221 remote_ops.to_thread_alive = remote_thread_alive;
0f71a2f6 10222 remote_ops.to_find_new_threads = remote_threads_info;
0caabb7e 10223 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 10224 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 10225 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 10226 remote_ops.to_stop = remote_stop;
4b8a223f 10227 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 10228 remote_ops.to_rcmd = remote_rcmd;
49d03eab 10229 remote_ops.to_log_command = serial_log_command;
38691318 10230 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 10231 remote_ops.to_stratum = process_stratum;
c35b1492
PA
10232 remote_ops.to_has_all_memory = default_child_has_all_memory;
10233 remote_ops.to_has_memory = default_child_has_memory;
10234 remote_ops.to_has_stack = default_child_has_stack;
10235 remote_ops.to_has_registers = default_child_has_registers;
10236 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 10237 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 10238 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 10239 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 10240 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
10241 remote_ops.to_flash_erase = remote_flash_erase;
10242 remote_ops.to_flash_done = remote_flash_done;
29709017 10243 remote_ops.to_read_description = remote_read_description;
08388c79 10244 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
10245 remote_ops.to_can_async_p = remote_can_async_p;
10246 remote_ops.to_is_async_p = remote_is_async_p;
10247 remote_ops.to_async = remote_async;
10248 remote_ops.to_async_mask = remote_async_mask;
10249 remote_ops.to_terminal_inferior = remote_terminal_inferior;
10250 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 10251 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 10252 remote_ops.to_supports_multi_process = remote_supports_multi_process;
35b1e5cc
SS
10253 remote_ops.to_trace_init = remote_trace_init;
10254 remote_ops.to_download_tracepoint = remote_download_tracepoint;
3e43a32a
MS
10255 remote_ops.to_download_trace_state_variable
10256 = remote_download_trace_state_variable;
35b1e5cc
SS
10257 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
10258 remote_ops.to_trace_start = remote_trace_start;
10259 remote_ops.to_get_trace_status = remote_get_trace_status;
10260 remote_ops.to_trace_stop = remote_trace_stop;
10261 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
10262 remote_ops.to_get_trace_state_variable_value
10263 = remote_get_trace_state_variable_value;
00bf0b85
SS
10264 remote_ops.to_save_trace_data = remote_save_trace_data;
10265 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
10266 remote_ops.to_upload_trace_state_variables
10267 = remote_upload_trace_state_variables;
00bf0b85 10268 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
35b1e5cc 10269 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 10270 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
dc146f7c 10271 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 10272 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 10273 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 10274 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
10275 remote_ops.to_static_tracepoint_marker_at
10276 = remote_static_tracepoint_marker_at;
10277 remote_ops.to_static_tracepoint_markers_by_strid
10278 = remote_static_tracepoint_markers_by_strid;
b3b9301e 10279 remote_ops.to_traceframe_info = remote_traceframe_info;
c906108c
SS
10280}
10281
10282/* Set up the extended remote vector by making a copy of the standard
10283 remote vector and adding to it. */
10284
10285static void
fba45db2 10286init_extended_remote_ops (void)
c906108c
SS
10287{
10288 extended_remote_ops = remote_ops;
10289
0f71a2f6 10290 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 10291 extended_remote_ops.to_longname =
c906108c 10292 "Extended remote serial target in gdb-specific protocol";
c5aa993b 10293 extended_remote_ops.to_doc =
c906108c 10294 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
10295Specify the serial device it is connected to (e.g. /dev/ttya).";
10296 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
10297 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
10298 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
10299 extended_remote_ops.to_detach = extended_remote_detach;
10300 extended_remote_ops.to_attach = extended_remote_attach;
82f73884 10301 extended_remote_ops.to_kill = extended_remote_kill;
0f71a2f6
JM
10302}
10303
6426a772
JM
10304static int
10305remote_can_async_p (void)
10306{
c6ebd6cf 10307 if (!target_async_permitted)
75c99385
PA
10308 /* We only enable async when the user specifically asks for it. */
10309 return 0;
10310
23860348 10311 /* We're async whenever the serial device is. */
b84876c2 10312 return remote_async_mask_value && serial_can_async_p (remote_desc);
6426a772
JM
10313}
10314
10315static int
10316remote_is_async_p (void)
10317{
c6ebd6cf 10318 if (!target_async_permitted)
75c99385
PA
10319 /* We only enable async when the user specifically asks for it. */
10320 return 0;
10321
23860348 10322 /* We're async whenever the serial device is. */
b84876c2 10323 return remote_async_mask_value && serial_is_async_p (remote_desc);
6426a772
JM
10324}
10325
2acceee2
JM
10326/* Pass the SERIAL event on and up to the client. One day this code
10327 will be able to delay notifying the client of an event until the
23860348 10328 point where an entire packet has been received. */
2acceee2 10329
2bc416ba 10330static void (*async_client_callback) (enum inferior_event_type event_type,
23860348 10331 void *context);
2acceee2
JM
10332static void *async_client_context;
10333static serial_event_ftype remote_async_serial_handler;
10334
6426a772 10335static void
819cc324 10336remote_async_serial_handler (struct serial *scb, void *context)
6426a772 10337{
2acceee2
JM
10338 /* Don't propogate error information up to the client. Instead let
10339 the client find out about the error by querying the target. */
10340 async_client_callback (INF_REG_EVENT, async_client_context);
10341}
10342
74531fed
PA
10343static void
10344remote_async_inferior_event_handler (gdb_client_data data)
10345{
10346 inferior_event_handler (INF_REG_EVENT, NULL);
10347}
10348
10349static void
10350remote_async_get_pending_events_handler (gdb_client_data data)
10351{
10352 remote_get_pending_stop_replies ();
10353}
10354
2acceee2 10355static void
2bc416ba 10356remote_async (void (*callback) (enum inferior_event_type event_type,
23860348 10357 void *context), void *context)
2acceee2 10358{
b84876c2 10359 if (remote_async_mask_value == 0)
8e65ff28 10360 internal_error (__FILE__, __LINE__,
e2e0b3e5 10361 _("Calling remote_async when async is masked"));
ed9a39eb 10362
2acceee2
JM
10363 if (callback != NULL)
10364 {
2cd58942 10365 serial_async (remote_desc, remote_async_serial_handler, NULL);
2acceee2
JM
10366 async_client_callback = callback;
10367 async_client_context = context;
10368 }
10369 else
2cd58942 10370 serial_async (remote_desc, NULL, NULL);
6426a772
JM
10371}
10372
b84876c2
PA
10373static int
10374remote_async_mask (int new_mask)
10375{
10376 int curr_mask = remote_async_mask_value;
a744cf53 10377
b84876c2
PA
10378 remote_async_mask_value = new_mask;
10379 return curr_mask;
10380}
10381
5a2468f5 10382static void
c2d11a7d 10383set_remote_cmd (char *args, int from_tty)
5a2468f5 10384{
427c3a89 10385 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
5a2468f5
JM
10386}
10387
d471ea57
AC
10388static void
10389show_remote_cmd (char *args, int from_tty)
10390{
37a105a1 10391 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 10392 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
10393 struct cleanup *showlist_chain;
10394 struct cmd_list_element *list = remote_show_cmdlist;
10395
10396 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
10397 for (; list != NULL; list = list->next)
10398 if (strcmp (list->name, "Z-packet") == 0)
10399 continue;
427c3a89
DJ
10400 else if (list->type == not_set_cmd)
10401 /* Alias commands are exactly like the original, except they
10402 don't have the normal type. */
10403 continue;
10404 else
37a105a1
DJ
10405 {
10406 struct cleanup *option_chain
10407 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 10408
37a105a1
DJ
10409 ui_out_field_string (uiout, "name", list->name);
10410 ui_out_text (uiout, ": ");
427c3a89
DJ
10411 if (list->type == show_cmd)
10412 do_setshow_command ((char *) NULL, from_tty, list);
10413 else
10414 cmd_func (list, NULL, from_tty);
37a105a1
DJ
10415 /* Close the tuple. */
10416 do_cleanups (option_chain);
10417 }
427c3a89
DJ
10418
10419 /* Close the tuple. */
10420 do_cleanups (showlist_chain);
d471ea57 10421}
5a2468f5 10422
0f71a2f6 10423
23860348 10424/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
10425static void
10426remote_new_objfile (struct objfile *objfile)
10427{
23860348 10428 if (remote_desc != 0) /* Have a remote connection. */
06d3b283 10429 remote_check_symbols (objfile);
dc8acb97
MS
10430}
10431
00bf0b85
SS
10432/* Pull all the tracepoints defined on the target and create local
10433 data structures representing them. We don't want to create real
10434 tracepoints yet, we don't want to mess up the user's existing
10435 collection. */
10436
10437static int
10438remote_upload_tracepoints (struct uploaded_tp **utpp)
d5551862 10439{
00bf0b85
SS
10440 struct remote_state *rs = get_remote_state ();
10441 char *p;
d5551862 10442
00bf0b85
SS
10443 /* Ask for a first packet of tracepoint definition. */
10444 putpkt ("qTfP");
10445 getpkt (&rs->buf, &rs->buf_size, 0);
10446 p = rs->buf;
10447 while (*p && *p != 'l')
d5551862 10448 {
00bf0b85
SS
10449 parse_tracepoint_definition (p, utpp);
10450 /* Ask for another packet of tracepoint definition. */
10451 putpkt ("qTsP");
10452 getpkt (&rs->buf, &rs->buf_size, 0);
10453 p = rs->buf;
d5551862 10454 }
00bf0b85 10455 return 0;
d5551862
SS
10456}
10457
00bf0b85
SS
10458static int
10459remote_upload_trace_state_variables (struct uploaded_tsv **utsvp)
d5551862 10460{
00bf0b85 10461 struct remote_state *rs = get_remote_state ();
d5551862 10462 char *p;
d5551862 10463
00bf0b85
SS
10464 /* Ask for a first packet of variable definition. */
10465 putpkt ("qTfV");
d5551862
SS
10466 getpkt (&rs->buf, &rs->buf_size, 0);
10467 p = rs->buf;
00bf0b85 10468 while (*p && *p != 'l')
d5551862 10469 {
00bf0b85
SS
10470 parse_tsv_definition (p, utsvp);
10471 /* Ask for another packet of variable definition. */
10472 putpkt ("qTsV");
d5551862
SS
10473 getpkt (&rs->buf, &rs->buf_size, 0);
10474 p = rs->buf;
10475 }
00bf0b85 10476 return 0;
d5551862
SS
10477}
10478
c906108c 10479void
fba45db2 10480_initialize_remote (void)
c906108c 10481{
ea9c271d 10482 struct remote_state *rs;
9a7071a8
JB
10483 struct cmd_list_element *cmd;
10484 char *cmd_name;
ea9c271d 10485
0f71a2f6 10486 /* architecture specific data */
2bc416ba 10487 remote_gdbarch_data_handle =
23860348 10488 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
10489 remote_g_packet_data_handle =
10490 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 10491
ea9c271d
DJ
10492 /* Initialize the per-target state. At the moment there is only one
10493 of these, not one per target. Only one target is active at a
10494 time. The default buffer size is unimportant; it will be expanded
10495 whenever a larger buffer is needed. */
0b83947e 10496 rs = get_remote_state_raw ();
ea9c271d
DJ
10497 rs->buf_size = 400;
10498 rs->buf = xmalloc (rs->buf_size);
10499
c906108c
SS
10500 init_remote_ops ();
10501 add_target (&remote_ops);
10502
10503 init_extended_remote_ops ();
10504 add_target (&extended_remote_ops);
cce74817 10505
dc8acb97 10506 /* Hook into new objfile notification. */
06d3b283 10507 observer_attach_new_objfile (remote_new_objfile);
dc8acb97 10508
b803fb0f
DJ
10509 /* Set up signal handlers. */
10510 sigint_remote_token =
10511 create_async_signal_handler (async_remote_interrupt, NULL);
10512 sigint_remote_twice_token =
10513 create_async_signal_handler (inferior_event_handler_wrapper, NULL);
10514
c906108c
SS
10515#if 0
10516 init_remote_threadtests ();
10517#endif
10518
23860348 10519 /* set/show remote ... */
d471ea57 10520
1bedd215 10521 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
10522Remote protocol specific variables\n\
10523Configure various remote-protocol specific variables such as\n\
1bedd215 10524the packets being used"),
cff3e48b 10525 &remote_set_cmdlist, "set remote ",
23860348 10526 0 /* allow-unknown */, &setlist);
1bedd215 10527 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
10528Remote protocol specific variables\n\
10529Configure various remote-protocol specific variables such as\n\
1bedd215 10530the packets being used"),
cff3e48b 10531 &remote_show_cmdlist, "show remote ",
23860348 10532 0 /* allow-unknown */, &showlist);
5a2468f5 10533
1a966eab
AC
10534 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
10535Compare section data on target to the exec file.\n\
10536Argument is a single section name (default: all loaded sections)."),
c906108c
SS
10537 &cmdlist);
10538
1a966eab
AC
10539 add_cmd ("packet", class_maintenance, packet_command, _("\
10540Send an arbitrary packet to a remote target.\n\
c906108c
SS
10541 maintenance packet TEXT\n\
10542If GDB is talking to an inferior via the GDB serial protocol, then\n\
10543this command sends the string TEXT to the inferior, and displays the\n\
10544response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 10545terminating `#' character and checksum."),
c906108c
SS
10546 &maintenancelist);
10547
7915a72c
AC
10548 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
10549Set whether to send break if interrupted."), _("\
10550Show whether to send break if interrupted."), _("\
10551If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 10552 set_remotebreak, show_remotebreak,
e707bbc2 10553 &setlist, &showlist);
9a7071a8
JB
10554 cmd_name = "remotebreak";
10555 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
10556 deprecate_cmd (cmd, "set remote interrupt-sequence");
10557 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
10558 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
10559 deprecate_cmd (cmd, "show remote interrupt-sequence");
10560
10561 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
10562 interrupt_sequence_modes, &interrupt_sequence_mode,
10563 _("\
9a7071a8
JB
10564Set interrupt sequence to remote target."), _("\
10565Show interrupt sequence to remote target."), _("\
10566Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
10567 NULL, show_interrupt_sequence,
10568 &remote_set_cmdlist,
10569 &remote_show_cmdlist);
10570
10571 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
10572 &interrupt_on_connect, _("\
10573Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
10574Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
10575If set, interrupt sequence is sent to remote target."),
10576 NULL, NULL,
10577 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 10578
23860348 10579 /* Install commands for configuring memory read/write packets. */
11cf8741 10580
1a966eab
AC
10581 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
10582Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 10583 &setlist);
1a966eab
AC
10584 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
10585Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
10586 &showlist);
10587 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
10588 set_memory_write_packet_size, _("\
10589Set the maximum number of bytes per memory-write packet.\n\
10590Specify the number of bytes in a packet or 0 (zero) for the\n\
10591default packet size. The actual limit is further reduced\n\
10592dependent on the target. Specify ``fixed'' to disable the\n\
10593further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
10594 &remote_set_cmdlist);
10595 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
10596 set_memory_read_packet_size, _("\
10597Set the maximum number of bytes per memory-read packet.\n\
10598Specify the number of bytes in a packet or 0 (zero) for the\n\
10599default packet size. The actual limit is further reduced\n\
10600dependent on the target. Specify ``fixed'' to disable the\n\
10601further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
10602 &remote_set_cmdlist);
10603 add_cmd ("memory-write-packet-size", no_class,
10604 show_memory_write_packet_size,
1a966eab 10605 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
10606 &remote_show_cmdlist);
10607 add_cmd ("memory-read-packet-size", no_class,
10608 show_memory_read_packet_size,
1a966eab 10609 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 10610 &remote_show_cmdlist);
c906108c 10611
b3f42336 10612 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
10613 &remote_hw_watchpoint_limit, _("\
10614Set the maximum number of target hardware watchpoints."), _("\
10615Show the maximum number of target hardware watchpoints."), _("\
10616Specify a negative limit for unlimited."),
3e43a32a
MS
10617 NULL, NULL, /* FIXME: i18n: The maximum
10618 number of target hardware
10619 watchpoints is %s. */
b3f42336
AC
10620 &remote_set_cmdlist, &remote_show_cmdlist);
10621 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
10622 &remote_hw_breakpoint_limit, _("\
10623Set the maximum number of target hardware breakpoints."), _("\
10624Show the maximum number of target hardware breakpoints."), _("\
10625Specify a negative limit for unlimited."),
3e43a32a
MS
10626 NULL, NULL, /* FIXME: i18n: The maximum
10627 number of target hardware
10628 breakpoints is %s. */
b3f42336 10629 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 10630
4d28ad1e
AC
10631 add_setshow_integer_cmd ("remoteaddresssize", class_obscure,
10632 &remote_address_size, _("\
10633Set the maximum size of the address (in bits) in a memory packet."), _("\
10634Show the maximum size of the address (in bits) in a memory packet."), NULL,
10635 NULL,
10636 NULL, /* FIXME: i18n: */
10637 &setlist, &showlist);
c906108c 10638
444abaca 10639 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 10640 "X", "binary-download", 1);
0f71a2f6 10641
444abaca 10642 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 10643 "vCont", "verbose-resume", 0);
506fb367 10644
89be2091
DJ
10645 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
10646 "QPassSignals", "pass-signals", 0);
10647
444abaca 10648 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 10649 "qSymbol", "symbol-lookup", 0);
dc8acb97 10650
444abaca 10651 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 10652 "P", "set-register", 1);
d471ea57 10653
444abaca 10654 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 10655 "p", "fetch-register", 1);
b96ec7ac 10656
444abaca 10657 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 10658 "Z0", "software-breakpoint", 0);
d471ea57 10659
444abaca 10660 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 10661 "Z1", "hardware-breakpoint", 0);
d471ea57 10662
444abaca 10663 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 10664 "Z2", "write-watchpoint", 0);
d471ea57 10665
444abaca 10666 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 10667 "Z3", "read-watchpoint", 0);
d471ea57 10668
444abaca 10669 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 10670 "Z4", "access-watchpoint", 0);
d471ea57 10671
0876f84a
DJ
10672 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
10673 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 10674
23181151
DJ
10675 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
10676 "qXfer:features:read", "target-features", 0);
10677
cfa9d6d9
DJ
10678 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
10679 "qXfer:libraries:read", "library-info", 0);
10680
fd79ecee
DJ
10681 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
10682 "qXfer:memory-map:read", "memory-map", 0);
10683
0e7f50da
UW
10684 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
10685 "qXfer:spu:read", "read-spu-object", 0);
10686
10687 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
10688 "qXfer:spu:write", "write-spu-object", 0);
10689
07e059b5
VP
10690 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
10691 "qXfer:osdata:read", "osdata", 0);
10692
dc146f7c
VP
10693 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
10694 "qXfer:threads:read", "threads", 0);
10695
4aa995e1
PA
10696 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
10697 "qXfer:siginfo:read", "read-siginfo-object", 0);
10698
10699 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
10700 "qXfer:siginfo:write", "write-siginfo-object", 0);
10701
b3b9301e
PA
10702 add_packet_config_cmd
10703 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
10704 "qXfer:trace-frame-info:read", "traceframe-info", 0);
10705
444abaca 10706 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 10707 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
10708 0);
10709
711e434b
PM
10710 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
10711 "qGetTIBAddr", "get-thread-information-block-address",
10712 0);
10713
40ab02ce
MS
10714 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
10715 "bc", "reverse-continue", 0);
10716
10717 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
10718 "bs", "reverse-step", 0);
10719
be2a5f71
DJ
10720 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
10721 "qSupported", "supported-packets", 0);
10722
08388c79
DE
10723 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
10724 "qSearch:memory", "search-memory", 0);
10725
a6b151f1
DJ
10726 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
10727 "vFile:open", "hostio-open", 0);
10728
10729 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
10730 "vFile:pread", "hostio-pread", 0);
10731
10732 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
10733 "vFile:pwrite", "hostio-pwrite", 0);
10734
10735 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
10736 "vFile:close", "hostio-close", 0);
10737
10738 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
10739 "vFile:unlink", "hostio-unlink", 0);
10740
2d717e4f
DJ
10741 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
10742 "vAttach", "attach", 0);
10743
10744 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
10745 "vRun", "run", 0);
10746
a6f3e723
SL
10747 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
10748 "QStartNoAckMode", "noack", 0);
10749
82f73884
PA
10750 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
10751 "vKill", "kill", 0);
10752
0b16c5cf
PA
10753 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
10754 "qAttached", "query-attached", 0);
10755
782b2b07 10756 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
10757 "ConditionalTracepoints",
10758 "conditional-tracepoints", 0);
7a697b8d
SS
10759 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
10760 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 10761
409873ef
SS
10762 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
10763 "TracepointSource", "TracepointSource", 0);
10764
d914c394
SS
10765 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
10766 "QAllow", "allow", 0);
10767
0fb4aa4b
PA
10768 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
10769 "StaticTracepoints", "static-tracepoints", 0);
10770
10771 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
10772 "qXfer:statictrace:read", "read-sdata-object", 0);
10773
37a105a1
DJ
10774 /* Keep the old ``set remote Z-packet ...'' working. Each individual
10775 Z sub-packet has its own set and show commands, but users may
10776 have sets to this variable in their .gdbinit files (or in their
10777 documentation). */
e9e68a56 10778 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
10779 &remote_Z_packet_detect, _("\
10780Set use of remote protocol `Z' packets"), _("\
10781Show use of remote protocol `Z' packets "), _("\
3b64bf98 10782When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 10783packets."),
e9e68a56 10784 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
10785 show_remote_protocol_Z_packet_cmd,
10786 /* FIXME: i18n: Use of remote protocol
10787 `Z' packets is %s. */
e9e68a56 10788 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 10789
a6b151f1
DJ
10790 add_prefix_cmd ("remote", class_files, remote_command, _("\
10791Manipulate files on the remote system\n\
10792Transfer files to and from the remote target system."),
10793 &remote_cmdlist, "remote ",
10794 0 /* allow-unknown */, &cmdlist);
10795
10796 add_cmd ("put", class_files, remote_put_command,
10797 _("Copy a local file to the remote system."),
10798 &remote_cmdlist);
10799
10800 add_cmd ("get", class_files, remote_get_command,
10801 _("Copy a remote file to the local system."),
10802 &remote_cmdlist);
10803
10804 add_cmd ("delete", class_files, remote_delete_command,
10805 _("Delete a remote file."),
10806 &remote_cmdlist);
10807
2d717e4f
DJ
10808 remote_exec_file = xstrdup ("");
10809 add_setshow_string_noescape_cmd ("exec-file", class_files,
10810 &remote_exec_file, _("\
10811Set the remote pathname for \"run\""), _("\
10812Show the remote pathname for \"run\""), NULL, NULL, NULL,
10813 &remote_set_cmdlist, &remote_show_cmdlist);
10814
449092f6
CV
10815 /* Eventually initialize fileio. See fileio.c */
10816 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229
PA
10817
10818 /* Take advantage of the fact that the LWP field is not used, to tag
10819 special ptids with it set to != 0. */
82f73884
PA
10820 magic_null_ptid = ptid_build (42000, 1, -1);
10821 not_sent_ptid = ptid_build (42000, 1, -2);
10822 any_thread_ptid = ptid_build (42000, 1, 0);
35b1e5cc
SS
10823
10824 target_buf_size = 2048;
10825 target_buf = xmalloc (target_buf_size);
c906108c 10826}
10760264 10827
This page took 2.174353 seconds and 4 git commands to generate.