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