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