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