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