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