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