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