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