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