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