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