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