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