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