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