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