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