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