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