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