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