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