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