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