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