]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
* gdb.texinfo (Maintenance Commands): Add missing ')' for
[thirdparty/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
a14ed312 111static void remote_close (int quitting);
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
fba45db2 3004remote_close (int quitting)
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
4191
c906108c 4192static void
3e43a32a
MS
4193remote_open_1 (char *name, int from_tty,
4194 struct target_ops *target, int extended_p)
c906108c 4195{
d01949b6 4196 struct remote_state *rs = get_remote_state ();
a6f3e723 4197
c906108c 4198 if (name == 0)
8a3fe4f8 4199 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4200 "serial device is attached to the remote system\n"
8a3fe4f8 4201 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4202
23860348 4203 /* See FIXME above. */
c6ebd6cf 4204 if (!target_async_permitted)
92d1e331 4205 wait_forever_enabled_p = 1;
6426a772 4206
2d717e4f
DJ
4207 /* If we're connected to a running target, target_preopen will kill it.
4208 But if we're connected to a target system with no running process,
4209 then we will still be connected when it returns. Ask this question
4210 first, before target_preopen has a chance to kill anything. */
c35b1492 4211 if (remote_desc != NULL && !have_inferiors ())
2d717e4f
DJ
4212 {
4213 if (!from_tty
4214 || query (_("Already connected to a remote target. Disconnect? ")))
4215 pop_target ();
4216 else
4217 error (_("Still connected."));
4218 }
4219
c906108c
SS
4220 target_preopen (from_tty);
4221
4222 unpush_target (target);
4223
2d717e4f
DJ
4224 /* This time without a query. If we were connected to an
4225 extended-remote target and target_preopen killed the running
4226 process, we may still be connected. If we are starting "target
4227 remote" now, the extended-remote target will not have been
4228 removed by unpush_target. */
c35b1492 4229 if (remote_desc != NULL && !have_inferiors ())
2d717e4f
DJ
4230 pop_target ();
4231
89be2091
DJ
4232 /* Make sure we send the passed signals list the next time we resume. */
4233 xfree (last_pass_packet);
4234 last_pass_packet = NULL;
4235
9b224c5e
PA
4236 /* Make sure we send the program signals list the next time we
4237 resume. */
4238 xfree (last_program_signals_packet);
4239 last_program_signals_packet = NULL;
4240
ad9a8f3f 4241 remote_fileio_reset ();
1dd41f16
NS
4242 reopen_exec_file ();
4243 reread_symbols ();
4244
9db8d71f 4245 remote_desc = remote_serial_open (name);
c906108c
SS
4246 if (!remote_desc)
4247 perror_with_name (name);
4248
4249 if (baud_rate != -1)
4250 {
2cd58942 4251 if (serial_setbaudrate (remote_desc, baud_rate))
c906108c 4252 {
9b74d5d3
KB
4253 /* The requested speed could not be set. Error out to
4254 top level after closing remote_desc. Take care to
4255 set remote_desc to NULL to avoid closing remote_desc
4256 more than once. */
2cd58942 4257 serial_close (remote_desc);
9b74d5d3 4258 remote_desc = NULL;
c906108c
SS
4259 perror_with_name (name);
4260 }
4261 }
4262
2cd58942 4263 serial_raw (remote_desc);
c906108c
SS
4264
4265 /* If there is something sitting in the buffer we might take it as a
4266 response to a command, which would be bad. */
2cd58942 4267 serial_flush_input (remote_desc);
c906108c
SS
4268
4269 if (from_tty)
4270 {
4271 puts_filtered ("Remote debugging using ");
4272 puts_filtered (name);
4273 puts_filtered ("\n");
4274 }
23860348 4275 push_target (target); /* Switch to using remote target now. */
c906108c 4276
74531fed
PA
4277 /* Register extra event sources in the event loop. */
4278 remote_async_inferior_event_token
4279 = create_async_event_handler (remote_async_inferior_event_handler,
4280 NULL);
722247f1 4281 remote_notif_register_async_event_handler ();
74531fed 4282
be2a5f71
DJ
4283 /* Reset the target state; these things will be queried either by
4284 remote_query_supported or as they are needed. */
d471ea57 4285 init_all_packet_configs ();
74531fed 4286 rs->cached_wait_status = 0;
be2a5f71 4287 rs->explicit_packet_size = 0;
a6f3e723 4288 rs->noack_mode = 0;
82f73884
PA
4289 rs->multi_process_aware = 0;
4290 rs->extended = extended_p;
74531fed 4291 rs->non_stop_aware = 0;
e24a49d8 4292 rs->waiting_for_stop_reply = 0;
3a29589a 4293 rs->ctrlc_pending_p = 0;
802188a7 4294
79d7f229
PA
4295 general_thread = not_sent_ptid;
4296 continue_thread = not_sent_ptid;
e6e4e701 4297 remote_traceframe_number = -1;
c906108c 4298
9d1f7ab2
MS
4299 /* Probe for ability to use "ThreadInfo" query, as required. */
4300 use_threadinfo_query = 1;
4301 use_threadextra_query = 1;
4302
c6ebd6cf 4303 if (target_async_permitted)
92d1e331 4304 {
23860348 4305 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4306 remote_async_terminal_ours_p = 1;
4307
4308 /* FIXME: cagney/1999-09-23: During the initial connection it is
4309 assumed that the target is already ready and able to respond to
0df8b418 4310 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4311 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4312 around this. Eventually a mechanism that allows
92d1e331 4313 wait_for_inferior() to expect/get timeouts will be
23860348 4314 implemented. */
92d1e331
DJ
4315 wait_forever_enabled_p = 0;
4316 }
4317
23860348 4318 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4319 no_shared_libraries (NULL, 0);
f78f6cf1 4320
74531fed
PA
4321 /* Start afresh. */
4322 init_thread_list ();
4323
36918e70 4324 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4325 target (we'd otherwise be in an inconsistent state) and then
4326 propogate the error on up the exception chain. This ensures that
4327 the caller doesn't stumble along blindly assuming that the
4328 function succeeded. The CLI doesn't have this problem but other
4329 UI's, such as MI do.
36918e70
AC
4330
4331 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4332 this function should return an error indication letting the
ce2826aa 4333 caller restore the previous state. Unfortunately the command
36918e70
AC
4334 ``target remote'' is directly wired to this function making that
4335 impossible. On a positive note, the CLI side of this problem has
4336 been fixed - the function set_cmd_context() makes it possible for
4337 all the ``target ....'' commands to share a common callback
4338 function. See cli-dump.c. */
109c3e39 4339 {
04bd08de 4340 volatile struct gdb_exception ex;
2d717e4f 4341
04bd08de
TT
4342 TRY_CATCH (ex, RETURN_MASK_ALL)
4343 {
4344 remote_start_remote (from_tty, target, extended_p);
4345 }
109c3e39
AC
4346 if (ex.reason < 0)
4347 {
c8d104ad
PA
4348 /* Pop the partially set up target - unless something else did
4349 already before throwing the exception. */
4350 if (remote_desc != NULL)
4351 pop_target ();
c6ebd6cf 4352 if (target_async_permitted)
109c3e39
AC
4353 wait_forever_enabled_p = 1;
4354 throw_exception (ex);
4355 }
4356 }
c906108c 4357
c6ebd6cf 4358 if (target_async_permitted)
92d1e331 4359 wait_forever_enabled_p = 1;
43ff13b4
JM
4360}
4361
c906108c
SS
4362/* This takes a program previously attached to and detaches it. After
4363 this is done, GDB can be used to debug some other program. We
4364 better not have left any breakpoints in the target program or it'll
4365 die when it hits one. */
4366
4367static void
2d717e4f 4368remote_detach_1 (char *args, int from_tty, int extended)
c906108c 4369{
82f73884 4370 int pid = ptid_get_pid (inferior_ptid);
d01949b6 4371 struct remote_state *rs = get_remote_state ();
c906108c
SS
4372
4373 if (args)
8a3fe4f8 4374 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 4375
2d717e4f
DJ
4376 if (!target_has_execution)
4377 error (_("No process to detach from."));
4378
7cee1e54
PA
4379 if (from_tty)
4380 {
4381 char *exec_file = get_exec_file (0);
4382 if (exec_file == NULL)
4383 exec_file = "";
4384 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4385 target_pid_to_str (pid_to_ptid (pid)));
4386 gdb_flush (gdb_stdout);
4387 }
4388
c906108c 4389 /* Tell the remote target to detach. */
82f73884 4390 if (remote_multi_process_p (rs))
bba74b36 4391 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
82f73884
PA
4392 else
4393 strcpy (rs->buf, "D");
4394
4ddda9b5
PA
4395 putpkt (rs->buf);
4396 getpkt (&rs->buf, &rs->buf_size, 0);
4397
82f73884
PA
4398 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4399 ;
4400 else if (rs->buf[0] == '\0')
4401 error (_("Remote doesn't know how to detach"));
4402 else
4ddda9b5 4403 error (_("Can't detach process."));
c906108c 4404
7cee1e54
PA
4405 if (from_tty && !extended)
4406 puts_filtered (_("Ending remote debugging.\n"));
82f73884 4407
82f73884 4408 target_mourn_inferior ();
2d717e4f
DJ
4409}
4410
4411static void
136d6dae 4412remote_detach (struct target_ops *ops, char *args, int from_tty)
2d717e4f
DJ
4413{
4414 remote_detach_1 (args, from_tty, 0);
4415}
4416
4417static void
136d6dae 4418extended_remote_detach (struct target_ops *ops, char *args, int from_tty)
2d717e4f
DJ
4419{
4420 remote_detach_1 (args, from_tty, 1);
c906108c
SS
4421}
4422
6ad8ae5c
DJ
4423/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4424
43ff13b4 4425static void
597320e7 4426remote_disconnect (struct target_ops *target, char *args, int from_tty)
43ff13b4 4427{
43ff13b4 4428 if (args)
2d717e4f 4429 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 4430
2d717e4f
DJ
4431 /* Make sure we unpush even the extended remote targets; mourn
4432 won't do it. So call remote_mourn_1 directly instead of
4433 target_mourn_inferior. */
4434 remote_mourn_1 (target);
4435
43ff13b4
JM
4436 if (from_tty)
4437 puts_filtered ("Ending remote debugging.\n");
4438}
4439
2d717e4f
DJ
4440/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4441 be chatty about it. */
4442
4443static void
4444extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
4445{
4446 struct remote_state *rs = get_remote_state ();
be86555c 4447 int pid;
96ef3384 4448 char *wait_status = NULL;
2d717e4f 4449
74164c56 4450 pid = parse_pid_to_attach (args);
2d717e4f 4451
74164c56
JK
4452 /* Remote PID can be freely equal to getpid, do not check it here the same
4453 way as in other targets. */
2d717e4f
DJ
4454
4455 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4456 error (_("This target does not support attaching to a process"));
4457
7cee1e54
PA
4458 if (from_tty)
4459 {
4460 char *exec_file = get_exec_file (0);
4461
4462 if (exec_file)
4463 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4464 target_pid_to_str (pid_to_ptid (pid)));
4465 else
4466 printf_unfiltered (_("Attaching to %s\n"),
4467 target_pid_to_str (pid_to_ptid (pid)));
4468
4469 gdb_flush (gdb_stdout);
4470 }
4471
bba74b36 4472 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
4473 putpkt (rs->buf);
4474 getpkt (&rs->buf, &rs->buf_size, 0);
4475
3e43a32a
MS
4476 if (packet_ok (rs->buf,
4477 &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
2d717e4f 4478 {
74531fed
PA
4479 if (!non_stop)
4480 {
4481 /* Save the reply for later. */
4482 wait_status = alloca (strlen (rs->buf) + 1);
4483 strcpy (wait_status, rs->buf);
4484 }
4485 else if (strcmp (rs->buf, "OK") != 0)
4486 error (_("Attaching to %s failed with: %s"),
4487 target_pid_to_str (pid_to_ptid (pid)),
4488 rs->buf);
2d717e4f
DJ
4489 }
4490 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4491 error (_("This target does not support attaching to a process"));
4492 else
4493 error (_("Attaching to %s failed"),
4494 target_pid_to_str (pid_to_ptid (pid)));
4495
49c62f2e 4496 set_current_inferior (remote_add_inferior (0, pid, 1));
bad34192 4497
2d717e4f 4498 inferior_ptid = pid_to_ptid (pid);
79d7f229 4499
bad34192
PA
4500 if (non_stop)
4501 {
4502 struct thread_info *thread;
79d7f229 4503
bad34192
PA
4504 /* Get list of threads. */
4505 remote_threads_info (target);
82f73884 4506
bad34192
PA
4507 thread = first_thread_of_process (pid);
4508 if (thread)
4509 inferior_ptid = thread->ptid;
4510 else
4511 inferior_ptid = pid_to_ptid (pid);
4512
4513 /* Invalidate our notion of the remote current thread. */
4514 record_currthread (minus_one_ptid);
4515 }
74531fed 4516 else
bad34192
PA
4517 {
4518 /* Now, if we have thread information, update inferior_ptid. */
4519 inferior_ptid = remote_current_thread (inferior_ptid);
4520
4521 /* Add the main thread to the thread list. */
4522 add_thread_silent (inferior_ptid);
4523 }
c0a2216e 4524
96ef3384
UW
4525 /* Next, if the target can specify a description, read it. We do
4526 this before anything involving memory or registers. */
4527 target_find_description ();
4528
74531fed
PA
4529 if (!non_stop)
4530 {
4531 /* Use the previously fetched status. */
4532 gdb_assert (wait_status != NULL);
4533
4534 if (target_can_async_p ())
4535 {
722247f1
YQ
4536 struct notif_event *reply
4537 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 4538
722247f1 4539 push_stop_reply ((struct stop_reply *) reply);
74531fed
PA
4540
4541 target_async (inferior_event_handler, 0);
4542 }
4543 else
4544 {
4545 gdb_assert (wait_status != NULL);
4546 strcpy (rs->buf, wait_status);
4547 rs->cached_wait_status = 1;
4548 }
4549 }
4550 else
4551 gdb_assert (wait_status == NULL);
2d717e4f
DJ
4552}
4553
4554static void
136d6dae 4555extended_remote_attach (struct target_ops *ops, char *args, int from_tty)
2d717e4f 4556{
136d6dae 4557 extended_remote_attach_1 (ops, args, from_tty);
2d717e4f
DJ
4558}
4559
c906108c
SS
4560/* Convert hex digit A to a number. */
4561
30559e10 4562static int
fba45db2 4563fromhex (int a)
c906108c
SS
4564{
4565 if (a >= '0' && a <= '9')
4566 return a - '0';
4567 else if (a >= 'a' && a <= 'f')
4568 return a - 'a' + 10;
4569 else if (a >= 'A' && a <= 'F')
4570 return a - 'A' + 10;
c5aa993b 4571 else
8a3fe4f8 4572 error (_("Reply contains invalid hex digit %d"), a);
c906108c
SS
4573}
4574
00bf0b85 4575int
cfd77fa1 4576hex2bin (const char *hex, gdb_byte *bin, int count)
30559e10
MS
4577{
4578 int i;
4579
30559e10
MS
4580 for (i = 0; i < count; i++)
4581 {
4582 if (hex[0] == 0 || hex[1] == 0)
4583 {
4584 /* Hex string is short, or of uneven length.
23860348 4585 Return the count that has been converted so far. */
30559e10
MS
4586 return i;
4587 }
4588 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
4589 hex += 2;
4590 }
4591 return i;
4592}
4593
c906108c
SS
4594/* Convert number NIB to a hex digit. */
4595
4596static int
fba45db2 4597tohex (int nib)
c906108c
SS
4598{
4599 if (nib < 10)
c5aa993b 4600 return '0' + nib;
c906108c 4601 else
c5aa993b 4602 return 'a' + nib - 10;
c906108c 4603}
30559e10 4604
00bf0b85 4605int
cfd77fa1 4606bin2hex (const gdb_byte *bin, char *hex, int count)
30559e10
MS
4607{
4608 int i;
a744cf53 4609
23860348 4610 /* May use a length, or a nul-terminated string as input. */
30559e10 4611 if (count == 0)
cfd77fa1 4612 count = strlen ((char *) bin);
30559e10
MS
4613
4614 for (i = 0; i < count; i++)
4615 {
4616 *hex++ = tohex ((*bin >> 4) & 0xf);
4617 *hex++ = tohex (*bin++ & 0xf);
4618 }
4619 *hex = 0;
4620 return i;
4621}
c906108c 4622\f
506fb367
DJ
4623/* Check for the availability of vCont. This function should also check
4624 the response. */
c906108c
SS
4625
4626static void
6d820c5c 4627remote_vcont_probe (struct remote_state *rs)
c906108c 4628{
2e9f7625 4629 char *buf;
6d820c5c 4630
2e9f7625
DJ
4631 strcpy (rs->buf, "vCont?");
4632 putpkt (rs->buf);
6d820c5c 4633 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4634 buf = rs->buf;
c906108c 4635
506fb367
DJ
4636 /* Make sure that the features we assume are supported. */
4637 if (strncmp (buf, "vCont", 5) == 0)
4638 {
4639 char *p = &buf[5];
4640 int support_s, support_S, support_c, support_C;
4641
4642 support_s = 0;
4643 support_S = 0;
4644 support_c = 0;
4645 support_C = 0;
74531fed 4646 rs->support_vCont_t = 0;
506fb367
DJ
4647 while (p && *p == ';')
4648 {
4649 p++;
4650 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4651 support_s = 1;
4652 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4653 support_S = 1;
4654 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4655 support_c = 1;
4656 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4657 support_C = 1;
74531fed
PA
4658 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4659 rs->support_vCont_t = 1;
506fb367
DJ
4660
4661 p = strchr (p, ';');
4662 }
c906108c 4663
506fb367
DJ
4664 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4665 BUF will make packet_ok disable the packet. */
4666 if (!support_s || !support_S || !support_c || !support_C)
4667 buf[0] = 0;
4668 }
c906108c 4669
444abaca 4670 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 4671}
c906108c 4672
0d8f58ca
PA
4673/* Helper function for building "vCont" resumptions. Write a
4674 resumption to P. ENDP points to one-passed-the-end of the buffer
4675 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4676 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4677 resumed thread should be single-stepped and/or signalled. If PTID
4678 equals minus_one_ptid, then all threads are resumed; if PTID
4679 represents a process, then all threads of the process are resumed;
4680 the thread to be stepped and/or signalled is given in the global
4681 INFERIOR_PTID. */
4682
4683static char *
4684append_resumption (char *p, char *endp,
2ea28649 4685 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
4686{
4687 struct remote_state *rs = get_remote_state ();
4688
a493e3e2 4689 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
4690 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4691 else if (step)
4692 p += xsnprintf (p, endp - p, ";s");
a493e3e2 4693 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
4694 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4695 else
4696 p += xsnprintf (p, endp - p, ";c");
4697
4698 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4699 {
4700 ptid_t nptid;
4701
4702 /* All (-1) threads of process. */
4703 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
4704
4705 p += xsnprintf (p, endp - p, ":");
4706 p = write_ptid (p, endp, nptid);
4707 }
4708 else if (!ptid_equal (ptid, minus_one_ptid))
4709 {
4710 p += xsnprintf (p, endp - p, ":");
4711 p = write_ptid (p, endp, ptid);
4712 }
4713
4714 return p;
4715}
4716
e5ef252a
PA
4717/* Append a vCont continue-with-signal action for threads that have a
4718 non-zero stop signal. */
4719
4720static char *
4721append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4722{
4723 struct thread_info *thread;
4724
4725 ALL_THREADS (thread)
4726 if (ptid_match (thread->ptid, ptid)
4727 && !ptid_equal (inferior_ptid, thread->ptid)
4728 && thread->suspend.stop_signal != GDB_SIGNAL_0
4729 && signal_pass_state (thread->suspend.stop_signal))
4730 {
4731 p = append_resumption (p, endp, thread->ptid,
4732 0, thread->suspend.stop_signal);
4733 thread->suspend.stop_signal = GDB_SIGNAL_0;
4734 }
4735
4736 return p;
4737}
4738
506fb367
DJ
4739/* Resume the remote inferior by using a "vCont" packet. The thread
4740 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
4741 resumed thread should be single-stepped and/or signalled. If PTID
4742 equals minus_one_ptid, then all threads are resumed; the thread to
4743 be stepped and/or signalled is given in the global INFERIOR_PTID.
4744 This function returns non-zero iff it resumes the inferior.
44eaed12 4745
506fb367
DJ
4746 This function issues a strict subset of all possible vCont commands at the
4747 moment. */
44eaed12 4748
506fb367 4749static int
2ea28649 4750remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
4751{
4752 struct remote_state *rs = get_remote_state ();
82f73884
PA
4753 char *p;
4754 char *endp;
44eaed12 4755
444abaca 4756 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
6d820c5c 4757 remote_vcont_probe (rs);
44eaed12 4758
444abaca 4759 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
6d820c5c 4760 return 0;
44eaed12 4761
82f73884
PA
4762 p = rs->buf;
4763 endp = rs->buf + get_remote_packet_size ();
4764
506fb367
DJ
4765 /* If we could generate a wider range of packets, we'd have to worry
4766 about overflowing BUF. Should there be a generic
4767 "multi-part-packet" packet? */
4768
0d8f58ca
PA
4769 p += xsnprintf (p, endp - p, "vCont");
4770
79d7f229 4771 if (ptid_equal (ptid, magic_null_ptid))
c906108c 4772 {
79d7f229
PA
4773 /* MAGIC_NULL_PTID means that we don't have any active threads,
4774 so we don't have any TID numbers the inferior will
4775 understand. Make sure to only send forms that do not specify
4776 a TID. */
a9cbf802 4777 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 4778 }
0d8f58ca 4779 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 4780 {
0d8f58ca
PA
4781 /* Resume all threads (of all processes, or of a single
4782 process), with preference for INFERIOR_PTID. This assumes
4783 inferior_ptid belongs to the set of all threads we are about
4784 to resume. */
a493e3e2 4785 if (step || siggnal != GDB_SIGNAL_0)
82f73884 4786 {
0d8f58ca
PA
4787 /* Step inferior_ptid, with or without signal. */
4788 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 4789 }
0d8f58ca 4790
e5ef252a
PA
4791 /* Also pass down any pending signaled resumption for other
4792 threads not the current. */
4793 p = append_pending_thread_resumptions (p, endp, ptid);
4794
0d8f58ca 4795 /* And continue others without a signal. */
a493e3e2 4796 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
4797 }
4798 else
506fb367
DJ
4799 {
4800 /* Scheduler locking; resume only PTID. */
a9cbf802 4801 append_resumption (p, endp, ptid, step, siggnal);
506fb367 4802 }
c906108c 4803
82f73884
PA
4804 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4805 putpkt (rs->buf);
506fb367 4806
74531fed
PA
4807 if (non_stop)
4808 {
4809 /* In non-stop, the stub replies to vCont with "OK". The stop
4810 reply will be reported asynchronously by means of a `%Stop'
4811 notification. */
4812 getpkt (&rs->buf, &rs->buf_size, 0);
4813 if (strcmp (rs->buf, "OK") != 0)
4814 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4815 }
4816
506fb367 4817 return 1;
c906108c 4818}
43ff13b4 4819
506fb367
DJ
4820/* Tell the remote machine to resume. */
4821
a493e3e2 4822static enum gdb_signal last_sent_signal = GDB_SIGNAL_0;
506fb367
DJ
4823
4824static int last_sent_step;
4825
43ff13b4 4826static void
28439f5e 4827remote_resume (struct target_ops *ops,
2ea28649 4828 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 4829{
d01949b6 4830 struct remote_state *rs = get_remote_state ();
2e9f7625 4831 char *buf;
43ff13b4 4832
722247f1
YQ
4833 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
4834 (explained in remote-notif.c:handle_notification) so
4835 remote_notif_process is not called. We need find a place where
4836 it is safe to start a 'vNotif' sequence. It is good to do it
4837 before resuming inferior, because inferior was stopped and no RSP
4838 traffic at that moment. */
4839 if (!non_stop)
4840 remote_notif_process (&notif_client_stop);
4841
43ff13b4
JM
4842 last_sent_signal = siggnal;
4843 last_sent_step = step;
4844
506fb367 4845 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
4846 /* No reverse support (yet) for vCont. */
4847 if (execution_direction != EXEC_REVERSE)
4848 if (remote_vcont_resume (ptid, step, siggnal))
4849 goto done;
506fb367 4850
79d7f229
PA
4851 /* All other supported resume packets do use Hc, so set the continue
4852 thread. */
4853 if (ptid_equal (ptid, minus_one_ptid))
4854 set_continue_thread (any_thread_ptid);
506fb367 4855 else
79d7f229 4856 set_continue_thread (ptid);
506fb367 4857
2e9f7625 4858 buf = rs->buf;
b2175913
MS
4859 if (execution_direction == EXEC_REVERSE)
4860 {
4861 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 4862 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 4863 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 4864 siggnal);
40ab02ce
MS
4865
4866 if (step
4867 && remote_protocol_packets[PACKET_bs].support == PACKET_DISABLE)
4868 error (_("Remote reverse-step not supported."));
4869 if (!step
4870 && remote_protocol_packets[PACKET_bc].support == PACKET_DISABLE)
08c93ed9 4871 error (_("Remote reverse-continue not supported."));
40ab02ce 4872
b2175913
MS
4873 strcpy (buf, step ? "bs" : "bc");
4874 }
a493e3e2 4875 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
4876 {
4877 buf[0] = step ? 'S' : 'C';
c5aa993b 4878 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 4879 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
4880 buf[3] = '\0';
4881 }
4882 else
c5aa993b 4883 strcpy (buf, step ? "s" : "c");
506fb367 4884
44eaed12 4885 putpkt (buf);
43ff13b4 4886
75c99385 4887 done:
2acceee2 4888 /* We are about to start executing the inferior, let's register it
0df8b418
MS
4889 with the event loop. NOTE: this is the one place where all the
4890 execution commands end up. We could alternatively do this in each
23860348 4891 of the execution commands in infcmd.c. */
2acceee2
JM
4892 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4893 into infcmd.c in order to allow inferior function calls to work
23860348 4894 NOT asynchronously. */
362646f5 4895 if (target_can_async_p ())
2acceee2 4896 target_async (inferior_event_handler, 0);
e24a49d8
PA
4897
4898 /* We've just told the target to resume. The remote server will
4899 wait for the inferior to stop, and then send a stop reply. In
4900 the mean time, we can't start another command/query ourselves
74531fed
PA
4901 because the stub wouldn't be ready to process it. This applies
4902 only to the base all-stop protocol, however. In non-stop (which
4903 only supports vCont), the stub replies with an "OK", and is
4904 immediate able to process further serial input. */
4905 if (!non_stop)
4906 rs->waiting_for_stop_reply = 1;
43ff13b4 4907}
c906108c 4908\f
43ff13b4
JM
4909
4910/* Set up the signal handler for SIGINT, while the target is
23860348 4911 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 4912static void
fba45db2 4913initialize_sigint_signal_handler (void)
43ff13b4 4914{
43ff13b4
JM
4915 signal (SIGINT, handle_remote_sigint);
4916}
4917
23860348 4918/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 4919static void
fba45db2 4920handle_remote_sigint (int sig)
43ff13b4
JM
4921{
4922 signal (sig, handle_remote_sigint_twice);
f6fbab7d 4923 mark_async_signal_handler (sigint_remote_token);
43ff13b4
JM
4924}
4925
4926/* Signal handler for SIGINT, installed after SIGINT has already been
4927 sent once. It will take effect the second time that the user sends
23860348 4928 a ^C. */
43ff13b4 4929static void
fba45db2 4930handle_remote_sigint_twice (int sig)
43ff13b4 4931{
b803fb0f 4932 signal (sig, handle_remote_sigint);
f6fbab7d 4933 mark_async_signal_handler (sigint_remote_twice_token);
43ff13b4
JM
4934}
4935
6426a772 4936/* Perform the real interruption of the target execution, in response
23860348 4937 to a ^C. */
c5aa993b 4938static void
fba45db2 4939async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
4940{
4941 if (remote_debug)
248fd3bf 4942 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
43ff13b4 4943
94cc34af 4944 target_stop (inferior_ptid);
43ff13b4
JM
4945}
4946
0df8b418 4947/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 4948 up on the target alltogether. */
2df3850c 4949void
fba45db2 4950async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 4951{
2df3850c 4952 if (remote_debug)
248fd3bf 4953 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
b803fb0f
DJ
4954
4955 interrupt_query ();
43ff13b4
JM
4956}
4957
4958/* Reinstall the usual SIGINT handlers, after the target has
23860348 4959 stopped. */
6426a772
JM
4960static void
4961cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
4962{
4963 signal (SIGINT, handle_sigint);
43ff13b4
JM
4964}
4965
c906108c
SS
4966/* Send ^C to target to halt it. Target will respond, and send us a
4967 packet. */
507f3c78 4968static void (*ofunc) (int);
c906108c 4969
0df8b418
MS
4970/* The command line interface's stop routine. This function is installed
4971 as a signal handler for SIGINT. The first time a user requests a
4972 stop, we call remote_stop to send a break or ^C. If there is no
7a292a7a 4973 response from the target (it didn't stop when the user requested it),
23860348 4974 we ask the user if he'd like to detach from the target. */
c906108c 4975static void
fba45db2 4976remote_interrupt (int signo)
c906108c 4977{
23860348 4978 /* If this doesn't work, try more severe steps. */
7a292a7a
SS
4979 signal (signo, remote_interrupt_twice);
4980
b803fb0f 4981 gdb_call_async_signal_handler (sigint_remote_token, 1);
7a292a7a
SS
4982}
4983
4984/* The user typed ^C twice. */
4985
4986static void
fba45db2 4987remote_interrupt_twice (int signo)
7a292a7a
SS
4988{
4989 signal (signo, ofunc);
b803fb0f 4990 gdb_call_async_signal_handler (sigint_remote_twice_token, 1);
c906108c
SS
4991 signal (signo, remote_interrupt);
4992}
7a292a7a 4993
74531fed
PA
4994/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
4995 thread, all threads of a remote process, or all threads of all
4996 processes. */
4997
4998static void
4999remote_stop_ns (ptid_t ptid)
5000{
5001 struct remote_state *rs = get_remote_state ();
5002 char *p = rs->buf;
5003 char *endp = rs->buf + get_remote_packet_size ();
74531fed
PA
5004
5005 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
5006 remote_vcont_probe (rs);
5007
5008 if (!rs->support_vCont_t)
5009 error (_("Remote server does not support stopping threads"));
5010
f91d3df5
PA
5011 if (ptid_equal (ptid, minus_one_ptid)
5012 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5013 p += xsnprintf (p, endp - p, "vCont;t");
5014 else
5015 {
5016 ptid_t nptid;
5017
74531fed
PA
5018 p += xsnprintf (p, endp - p, "vCont;t:");
5019
5020 if (ptid_is_pid (ptid))
5021 /* All (-1) threads of process. */
5022 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
5023 else
5024 {
5025 /* Small optimization: if we already have a stop reply for
5026 this thread, no use in telling the stub we want this
5027 stopped. */
5028 if (peek_stop_reply (ptid))
5029 return;
5030
5031 nptid = ptid;
5032 }
5033
a9cbf802 5034 write_ptid (p, endp, nptid);
74531fed
PA
5035 }
5036
5037 /* In non-stop, we get an immediate OK reply. The stop reply will
5038 come in asynchronously by notification. */
5039 putpkt (rs->buf);
5040 getpkt (&rs->buf, &rs->buf_size, 0);
5041 if (strcmp (rs->buf, "OK") != 0)
5042 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5043}
5044
5045/* All-stop version of target_stop. Sends a break or a ^C to stop the
5046 remote target. It is undefined which thread of which process
5047 reports the stop. */
5048
5049static void
5050remote_stop_as (ptid_t ptid)
5051{
5052 struct remote_state *rs = get_remote_state ();
5053
3a29589a
DJ
5054 rs->ctrlc_pending_p = 1;
5055
74531fed
PA
5056 /* If the inferior is stopped already, but the core didn't know
5057 about it yet, just ignore the request. The cached wait status
5058 will be collected in remote_wait. */
5059 if (rs->cached_wait_status)
5060 return;
5061
9a7071a8
JB
5062 /* Send interrupt_sequence to remote target. */
5063 send_interrupt_sequence ();
74531fed
PA
5064}
5065
0df8b418 5066/* This is the generic stop called via the target vector. When a target
7a292a7a 5067 interrupt is requested, either by the command line or the GUI, we
23860348 5068 will eventually end up here. */
74531fed 5069
c906108c 5070static void
94cc34af 5071remote_stop (ptid_t ptid)
c906108c 5072{
7a292a7a 5073 if (remote_debug)
0f71a2f6 5074 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5075
74531fed
PA
5076 if (non_stop)
5077 remote_stop_ns (ptid);
c906108c 5078 else
74531fed 5079 remote_stop_as (ptid);
c906108c
SS
5080}
5081
5082/* Ask the user what to do when an interrupt is received. */
5083
5084static void
fba45db2 5085interrupt_query (void)
c906108c
SS
5086{
5087 target_terminal_ours ();
5088
74531fed 5089 if (target_can_async_p ())
c906108c 5090 {
74531fed 5091 signal (SIGINT, handle_sigint);
315a522e 5092 deprecated_throw_reason (RETURN_QUIT);
c906108c 5093 }
74531fed
PA
5094 else
5095 {
9e2f0ad4
HZ
5096 if (query (_("Interrupted while waiting for the program.\n\
5097Give up (and stop debugging it)? ")))
74531fed
PA
5098 {
5099 pop_target ();
5100 deprecated_throw_reason (RETURN_QUIT);
5101 }
5102 }
c906108c
SS
5103
5104 target_terminal_inferior ();
5105}
5106
6426a772
JM
5107/* Enable/disable target terminal ownership. Most targets can use
5108 terminal groups to control terminal ownership. Remote targets are
5109 different in that explicit transfer of ownership to/from GDB/target
23860348 5110 is required. */
6426a772
JM
5111
5112static void
75c99385 5113remote_terminal_inferior (void)
6426a772 5114{
c6ebd6cf 5115 if (!target_async_permitted)
75c99385
PA
5116 /* Nothing to do. */
5117 return;
5118
d9d2d8b6
PA
5119 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5120 idempotent. The event-loop GDB talking to an asynchronous target
5121 with a synchronous command calls this function from both
5122 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5123 transfer the terminal to the target when it shouldn't this guard
5124 can go away. */
6426a772
JM
5125 if (!remote_async_terminal_ours_p)
5126 return;
5127 delete_file_handler (input_fd);
5128 remote_async_terminal_ours_p = 0;
5129 initialize_sigint_signal_handler ();
5130 /* NOTE: At this point we could also register our selves as the
5131 recipient of all input. Any characters typed could then be
23860348 5132 passed on down to the target. */
6426a772
JM
5133}
5134
5135static void
75c99385 5136remote_terminal_ours (void)
6426a772 5137{
c6ebd6cf 5138 if (!target_async_permitted)
75c99385
PA
5139 /* Nothing to do. */
5140 return;
5141
5142 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5143 if (remote_async_terminal_ours_p)
5144 return;
5145 cleanup_sigint_signal_handler (NULL);
5146 add_file_handler (input_fd, stdin_event_handler, 0);
5147 remote_async_terminal_ours_p = 1;
5148}
5149
176a6961 5150static void
917317f4 5151remote_console_output (char *msg)
c906108c
SS
5152{
5153 char *p;
5154
c5aa993b 5155 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5156 {
5157 char tb[2];
5158 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5159
c906108c
SS
5160 tb[0] = c;
5161 tb[1] = 0;
43ff13b4 5162 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5163 }
00db5b94
PA
5164 gdb_flush (gdb_stdtarg);
5165}
74531fed
PA
5166
5167typedef struct cached_reg
5168{
5169 int num;
5170 gdb_byte data[MAX_REGISTER_SIZE];
5171} cached_reg_t;
5172
5173DEF_VEC_O(cached_reg_t);
5174
722247f1 5175typedef struct stop_reply
74531fed 5176{
722247f1 5177 struct notif_event base;
74531fed 5178
722247f1 5179 /* The identifier of the thread about this event */
74531fed
PA
5180 ptid_t ptid;
5181
5182 struct target_waitstatus ws;
5183
15148d6a
PA
5184 /* Expedited registers. This makes remote debugging a bit more
5185 efficient for those targets that provide critical registers as
5186 part of their normal status mechanism (as another roundtrip to
5187 fetch them is avoided). */
74531fed
PA
5188 VEC(cached_reg_t) *regcache;
5189
5190 int stopped_by_watchpoint_p;
5191 CORE_ADDR watch_data_address;
5192
5193 int solibs_changed;
5194 int replay_event;
dc146f7c
VP
5195
5196 int core;
722247f1 5197} *stop_reply_p;
a744cf53 5198
722247f1
YQ
5199DECLARE_QUEUE_P (stop_reply_p);
5200DEFINE_QUEUE_P (stop_reply_p);
5201/* The list of already fetched and acknowledged stop events. This
5202 queue is used for notification Stop, and other notifications
5203 don't need queue for their events, because the notification events
5204 of Stop can't be consumed immediately, so that events should be
5205 queued first, and be consumed by remote_wait_{ns,as} one per
5206 time. Other notifications can consume their events immediately,
5207 so queue is not needed for them. */
5208static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
5209
5210static void
5211stop_reply_xfree (struct stop_reply *r)
5212{
5213 if (r != NULL)
5214 {
5215 VEC_free (cached_reg_t, r->regcache);
5216 xfree (r);
5217 }
c906108c
SS
5218}
5219
722247f1
YQ
5220static void
5221remote_notif_stop_parse (struct notif_client *self, char *buf,
5222 struct notif_event *event)
5223{
5224 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5225}
5226
5227static void
5228remote_notif_stop_ack (struct notif_client *self, char *buf,
5229 struct notif_event *event)
5230{
5231 struct stop_reply *stop_reply = (struct stop_reply *) event;
5232
5233 /* acknowledge */
5234 putpkt ((char *) self->ack_command);
5235
5236 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5237 /* We got an unknown stop reply. */
5238 error (_("Unknown stop reply"));
5239
5240 push_stop_reply (stop_reply);
5241}
5242
5243static int
5244remote_notif_stop_can_get_pending_events (struct notif_client *self)
5245{
5246 /* We can't get pending events in remote_notif_process for
5247 notification stop, and we have to do this in remote_wait_ns
5248 instead. If we fetch all queued events from stub, remote stub
5249 may exit and we have no chance to process them back in
5250 remote_wait_ns. */
5251 mark_async_event_handler (remote_async_inferior_event_token);
5252 return 0;
5253}
5254
5255static void
5256stop_reply_dtr (struct notif_event *event)
5257{
5258 struct stop_reply *r = (struct stop_reply *) event;
5259
5260 VEC_free (cached_reg_t, r->regcache);
5261}
5262
5263static struct notif_event *
5264remote_notif_stop_alloc_reply (void)
5265{
5266 struct notif_event *r
5267 = (struct notif_event *) XMALLOC (struct stop_reply);
5268
5269 r->dtr = stop_reply_dtr;
5270
5271 return r;
5272}
5273
5274/* A client of notification Stop. */
5275
5276struct notif_client notif_client_stop =
5277{
5278 "Stop",
5279 "vStopped",
5280 remote_notif_stop_parse,
5281 remote_notif_stop_ack,
5282 remote_notif_stop_can_get_pending_events,
5283 remote_notif_stop_alloc_reply,
5284 NULL,
5285};
5286
5287/* A parameter to pass data in and out. */
5288
5289struct queue_iter_param
5290{
5291 void *input;
5292 struct stop_reply *output;
5293};
5294
5295/* Remove all queue elements meet the condition it checks. */
5296
5297static int
5298remote_notif_remove_all (QUEUE (stop_reply_p) *q,
5299 QUEUE_ITER (stop_reply_p) *iter,
5300 stop_reply_p event,
5301 void *data)
5302{
5303 struct queue_iter_param *param = data;
5304 struct inferior *inf = param->input;
5305
5306 if (inf == NULL || ptid_get_pid (event->ptid) == inf->pid)
5307 {
5308 stop_reply_xfree (event);
5309 QUEUE_remove_elem (stop_reply_p, q, iter);
5310 }
5311
5312 return 1;
5313}
5314
5f4cf0bb 5315/* Discard all pending stop replies of inferior INF. If INF is NULL,
74531fed 5316 discard everything. */
c906108c 5317
74531fed 5318static void
5f4cf0bb 5319discard_pending_stop_replies (struct inferior *inf)
c906108c 5320{
722247f1
YQ
5321 int i;
5322 struct queue_iter_param param;
5323 struct stop_reply *reply
5324 = (struct stop_reply *) notif_client_stop.pending_event;
c906108c 5325
74531fed 5326 /* Discard the in-flight notification. */
722247f1 5327 if (reply != NULL
5f4cf0bb 5328 && (inf == NULL
722247f1 5329 || ptid_get_pid (reply->ptid) == inf->pid))
74531fed 5330 {
722247f1
YQ
5331 stop_reply_xfree (reply);
5332 notif_client_stop.pending_event = NULL;
74531fed 5333 }
c906108c 5334
722247f1
YQ
5335 param.input = inf;
5336 param.output = NULL;
74531fed
PA
5337 /* Discard the stop replies we have already pulled with
5338 vStopped. */
722247f1
YQ
5339 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5340 remote_notif_remove_all, &param);
5341}
74531fed 5342
722247f1
YQ
5343/* A parameter to pass data in and out. */
5344
5345static int
5346remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5347 QUEUE_ITER (stop_reply_p) *iter,
5348 stop_reply_p event,
5349 void *data)
5350{
5351 struct queue_iter_param *param = data;
5352 ptid_t *ptid = param->input;
5353
5354 if (ptid_match (event->ptid, *ptid))
5355 {
5356 param->output = event;
5357 QUEUE_remove_elem (stop_reply_p, q, iter);
5358 return 0;
c8e38a49 5359 }
722247f1
YQ
5360
5361 return 1;
74531fed 5362}
43ff13b4 5363
722247f1
YQ
5364/* Remove the first reply in 'stop_reply_queue' which matches
5365 PTID. */
2e9f7625 5366
722247f1
YQ
5367static struct stop_reply *
5368remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 5369{
722247f1
YQ
5370 struct queue_iter_param param;
5371
5372 param.input = &ptid;
5373 param.output = NULL;
5374
5375 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5376 remote_notif_remove_once_on_match, &param);
5377 if (notif_debug)
5378 fprintf_unfiltered (gdb_stdlog,
5379 "notif: discard queued event: 'Stop' in %s\n",
5380 target_pid_to_str (ptid));
a744cf53 5381
722247f1 5382 return param.output;
74531fed 5383}
75c99385 5384
74531fed
PA
5385/* Look for a queued stop reply belonging to PTID. If one is found,
5386 remove it from the queue, and return it. Returns NULL if none is
5387 found. If there are still queued events left to process, tell the
5388 event loop to get back to target_wait soon. */
e24a49d8 5389
74531fed
PA
5390static struct stop_reply *
5391queued_stop_reply (ptid_t ptid)
5392{
722247f1 5393 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 5394
722247f1 5395 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
5396 /* There's still at least an event left. */
5397 mark_async_event_handler (remote_async_inferior_event_token);
5398
722247f1 5399 return r;
74531fed
PA
5400}
5401
5402/* Push a fully parsed stop reply in the stop reply queue. Since we
5403 know that we now have at least one queued event left to pass to the
5404 core side, tell the event loop to get back to target_wait soon. */
5405
5406static void
5407push_stop_reply (struct stop_reply *new_event)
5408{
722247f1 5409 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 5410
722247f1
YQ
5411 if (notif_debug)
5412 fprintf_unfiltered (gdb_stdlog,
5413 "notif: push 'Stop' %s to queue %d\n",
5414 target_pid_to_str (new_event->ptid),
5415 QUEUE_length (stop_reply_p,
5416 stop_reply_queue));
74531fed
PA
5417
5418 mark_async_event_handler (remote_async_inferior_event_token);
5419}
5420
722247f1
YQ
5421static int
5422stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5423 QUEUE_ITER (stop_reply_p) *iter,
5424 struct stop_reply *event,
5425 void *data)
5426{
5427 ptid_t *ptid = data;
5428
5429 return !(ptid_equal (*ptid, event->ptid)
5430 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5431}
5432
74531fed
PA
5433/* Returns true if we have a stop reply for PTID. */
5434
5435static int
5436peek_stop_reply (ptid_t ptid)
5437{
722247f1
YQ
5438 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5439 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
5440}
5441
5442/* Parse the stop reply in BUF. Either the function succeeds, and the
5443 result is stored in EVENT, or throws an error. */
5444
5445static void
5446remote_parse_stop_reply (char *buf, struct stop_reply *event)
5447{
5448 struct remote_arch_state *rsa = get_remote_arch_state ();
5449 ULONGEST addr;
5450 char *p;
5451
5452 event->ptid = null_ptid;
5453 event->ws.kind = TARGET_WAITKIND_IGNORE;
5454 event->ws.value.integer = 0;
5455 event->solibs_changed = 0;
5456 event->replay_event = 0;
5457 event->stopped_by_watchpoint_p = 0;
5458 event->regcache = NULL;
dc146f7c 5459 event->core = -1;
74531fed
PA
5460
5461 switch (buf[0])
5462 {
5463 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
5464 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5465 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5466 ss = signal number
5467 n... = register number
5468 r... = register contents
5469 */
5470
5471 p = &buf[3]; /* after Txx */
5472 while (*p)
5473 {
5474 char *p1;
5475 char *p_temp;
5476 int fieldsize;
5477 LONGEST pnum = 0;
43ff13b4 5478
cea39f65
MS
5479 /* If the packet contains a register number, save it in
5480 pnum and set p1 to point to the character following it.
5481 Otherwise p1 points to p. */
3c3bea1c 5482
cea39f65
MS
5483 /* If this packet is an awatch packet, don't parse the 'a'
5484 as a register number. */
c8e38a49 5485
dc146f7c
VP
5486 if (strncmp (p, "awatch", strlen("awatch")) != 0
5487 && strncmp (p, "core", strlen ("core") != 0))
cea39f65
MS
5488 {
5489 /* Read the ``P'' register number. */
5490 pnum = strtol (p, &p_temp, 16);
5491 p1 = p_temp;
5492 }
5493 else
5494 p1 = p;
802188a7 5495
cea39f65
MS
5496 if (p1 == p) /* No register number present here. */
5497 {
5498 p1 = strchr (p, ':');
5499 if (p1 == NULL)
5500 error (_("Malformed packet(a) (missing colon): %s\n\
c8e38a49 5501Packet: '%s'\n"),
cea39f65
MS
5502 p, buf);
5503 if (strncmp (p, "thread", p1 - p) == 0)
5504 event->ptid = read_ptid (++p1, &p);
5505 else if ((strncmp (p, "watch", p1 - p) == 0)
5506 || (strncmp (p, "rwatch", p1 - p) == 0)
5507 || (strncmp (p, "awatch", p1 - p) == 0))
5508 {
5509 event->stopped_by_watchpoint_p = 1;
5510 p = unpack_varlen_hex (++p1, &addr);
5511 event->watch_data_address = (CORE_ADDR) addr;
5512 }
5513 else if (strncmp (p, "library", p1 - p) == 0)
5514 {
5515 p1++;
5516 p_temp = p1;
5517 while (*p_temp && *p_temp != ';')
5518 p_temp++;
c8e38a49 5519
cea39f65
MS
5520 event->solibs_changed = 1;
5521 p = p_temp;
5522 }
5523 else if (strncmp (p, "replaylog", p1 - p) == 0)
5524 {
5525 /* NO_HISTORY event.
5526 p1 will indicate "begin" or "end", but
5527 it makes no difference for now, so ignore it. */
5528 event->replay_event = 1;
5529 p_temp = strchr (p1 + 1, ';');
5530 if (p_temp)
c8e38a49 5531 p = p_temp;
cea39f65 5532 }
dc146f7c
VP
5533 else if (strncmp (p, "core", p1 - p) == 0)
5534 {
5535 ULONGEST c;
a744cf53 5536
dc146f7c
VP
5537 p = unpack_varlen_hex (++p1, &c);
5538 event->core = c;
5539 }
cea39f65
MS
5540 else
5541 {
5542 /* Silently skip unknown optional info. */
5543 p_temp = strchr (p1 + 1, ';');
5544 if (p_temp)
5545 p = p_temp;
5546 }
5547 }
5548 else
5549 {
5550 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5551 cached_reg_t cached_reg;
74531fed 5552
cea39f65 5553 p = p1;
75c99385 5554
cea39f65
MS
5555 if (*p != ':')
5556 error (_("Malformed packet(b) (missing colon): %s\n\
8a3fe4f8 5557Packet: '%s'\n"),
cea39f65
MS
5558 p, buf);
5559 ++p;
43ff13b4 5560
cea39f65
MS
5561 if (reg == NULL)
5562 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 5563Packet: '%s'\n"),
7c47795c 5564 hex_string (pnum), p, buf);
c8e38a49 5565
cea39f65 5566 cached_reg.num = reg->regnum;
4100683b 5567
cea39f65 5568 fieldsize = hex2bin (p, cached_reg.data,
f5656ead 5569 register_size (target_gdbarch (),
cea39f65
MS
5570 reg->regnum));
5571 p += 2 * fieldsize;
f5656ead 5572 if (fieldsize < register_size (target_gdbarch (),
cea39f65
MS
5573 reg->regnum))
5574 warning (_("Remote reply is too short: %s"), buf);
74531fed 5575
cea39f65
MS
5576 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5577 }
c8e38a49 5578
cea39f65
MS
5579 if (*p != ';')
5580 error (_("Remote register badly formatted: %s\nhere: %s"),
5581 buf, p);
5582 ++p;
5583 }
c8e38a49
PA
5584 /* fall through */
5585 case 'S': /* Old style status, just signal only. */
74531fed
PA
5586 if (event->solibs_changed)
5587 event->ws.kind = TARGET_WAITKIND_LOADED;
5588 else if (event->replay_event)
5589 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
c8e38a49
PA
5590 else
5591 {
74531fed 5592 event->ws.kind = TARGET_WAITKIND_STOPPED;
2ea28649 5593 event->ws.value.sig = (enum gdb_signal)
c8e38a49
PA
5594 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
5595 }
5596 break;
5597 case 'W': /* Target exited. */
5598 case 'X':
5599 {
5600 char *p;
5601 int pid;
5602 ULONGEST value;
82f73884 5603
c8e38a49
PA
5604 /* GDB used to accept only 2 hex chars here. Stubs should
5605 only send more if they detect GDB supports multi-process
5606 support. */
5607 p = unpack_varlen_hex (&buf[1], &value);
82f73884 5608
c8e38a49
PA
5609 if (buf[0] == 'W')
5610 {
5611 /* The remote process exited. */
74531fed
PA
5612 event->ws.kind = TARGET_WAITKIND_EXITED;
5613 event->ws.value.integer = value;
c8e38a49
PA
5614 }
5615 else
5616 {
5617 /* The remote process exited with a signal. */
74531fed 5618 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
2ea28649 5619 event->ws.value.sig = (enum gdb_signal) value;
c8e38a49 5620 }
82f73884 5621
c8e38a49
PA
5622 /* If no process is specified, assume inferior_ptid. */
5623 pid = ptid_get_pid (inferior_ptid);
5624 if (*p == '\0')
5625 ;
5626 else if (*p == ';')
5627 {
5628 p++;
5629
5630 if (p == '\0')
82f73884 5631 ;
c8e38a49
PA
5632 else if (strncmp (p,
5633 "process:", sizeof ("process:") - 1) == 0)
82f73884 5634 {
c8e38a49 5635 ULONGEST upid;
a744cf53 5636
c8e38a49
PA
5637 p += sizeof ("process:") - 1;
5638 unpack_varlen_hex (p, &upid);
5639 pid = upid;
82f73884
PA
5640 }
5641 else
5642 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 5643 }
c8e38a49
PA
5644 else
5645 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
5646 event->ptid = pid_to_ptid (pid);
5647 }
5648 break;
5649 }
5650
5651 if (non_stop && ptid_equal (event->ptid, null_ptid))
5652 error (_("No process or thread specified in stop reply: %s"), buf);
5653}
5654
722247f1
YQ
5655/* When the stub wants to tell GDB about a new notification reply, it
5656 sends a notification (%Stop, for example). Those can come it at
5657 any time, hence, we have to make sure that any pending
5658 putpkt/getpkt sequence we're making is finished, before querying
5659 the stub for more events with the corresponding ack command
5660 (vStopped, for example). E.g., if we started a vStopped sequence
5661 immediately upon receiving the notification, something like this
5662 could happen:
74531fed
PA
5663
5664 1.1) --> Hg 1
5665 1.2) <-- OK
5666 1.3) --> g
5667 1.4) <-- %Stop
5668 1.5) --> vStopped
5669 1.6) <-- (registers reply to step #1.3)
5670
5671 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5672 query.
5673
796cb314 5674 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
5675 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5676 doing whatever we were doing:
5677
5678 2.1) --> Hg 1
5679 2.2) <-- OK
5680 2.3) --> g
5681 2.4) <-- %Stop
5682 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5683 2.5) <-- (registers reply to step #2.3)
5684
5685 Eventualy after step #2.5, we return to the event loop, which
5686 notices there's an event on the
5687 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5688 associated callback --- the function below. At this point, we're
5689 always safe to start a vStopped sequence. :
5690
5691 2.6) --> vStopped
5692 2.7) <-- T05 thread:2
5693 2.8) --> vStopped
5694 2.9) --> OK
5695*/
5696
722247f1
YQ
5697void
5698remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
5699{
5700 struct remote_state *rs = get_remote_state ();
74531fed 5701
722247f1 5702 if (nc->pending_event)
74531fed 5703 {
722247f1
YQ
5704 if (notif_debug)
5705 fprintf_unfiltered (gdb_stdlog,
5706 "notif: process: '%s' ack pending event\n",
5707 nc->name);
74531fed 5708
722247f1
YQ
5709 /* acknowledge */
5710 nc->ack (nc, rs->buf, nc->pending_event);
5711 nc->pending_event = NULL;
74531fed
PA
5712
5713 while (1)
5714 {
5715 getpkt (&rs->buf, &rs->buf_size, 0);
5716 if (strcmp (rs->buf, "OK") == 0)
5717 break;
5718 else
722247f1 5719 remote_notif_ack (nc, rs->buf);
74531fed
PA
5720 }
5721 }
722247f1
YQ
5722 else
5723 {
5724 if (notif_debug)
5725 fprintf_unfiltered (gdb_stdlog,
5726 "notif: process: '%s' no pending reply\n",
5727 nc->name);
5728 }
74531fed
PA
5729}
5730
74531fed
PA
5731/* Called when it is decided that STOP_REPLY holds the info of the
5732 event that is to be returned to the core. This function always
5733 destroys STOP_REPLY. */
5734
5735static ptid_t
5736process_stop_reply (struct stop_reply *stop_reply,
5737 struct target_waitstatus *status)
5738{
5739 ptid_t ptid;
5740
5741 *status = stop_reply->ws;
5742 ptid = stop_reply->ptid;
5743
5744 /* If no thread/process was reported by the stub, assume the current
5745 inferior. */
5746 if (ptid_equal (ptid, null_ptid))
5747 ptid = inferior_ptid;
5748
5f3563ea
PA
5749 if (status->kind != TARGET_WAITKIND_EXITED
5750 && status->kind != TARGET_WAITKIND_SIGNALLED)
74531fed 5751 {
5f3563ea
PA
5752 /* Expedited registers. */
5753 if (stop_reply->regcache)
5754 {
217f1f79 5755 struct regcache *regcache
f5656ead 5756 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
5757 cached_reg_t *reg;
5758 int ix;
5759
5760 for (ix = 0;
5761 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5762 ix++)
217f1f79 5763 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
5764 VEC_free (cached_reg_t, stop_reply->regcache);
5765 }
74531fed 5766
5f3563ea
PA
5767 remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
5768 remote_watch_data_address = stop_reply->watch_data_address;
1941c569
PA
5769
5770 remote_notice_new_inferior (ptid, 0);
dc146f7c 5771 demand_private_info (ptid)->core = stop_reply->core;
74531fed
PA
5772 }
5773
74531fed
PA
5774 stop_reply_xfree (stop_reply);
5775 return ptid;
5776}
5777
5778/* The non-stop mode version of target_wait. */
5779
5780static ptid_t
47608cb1 5781remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
5782{
5783 struct remote_state *rs = get_remote_state ();
74531fed
PA
5784 struct stop_reply *stop_reply;
5785 int ret;
fee9eda9 5786 int is_notif = 0;
74531fed
PA
5787
5788 /* If in non-stop mode, get out of getpkt even if a
5789 notification is received. */
5790
5791 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 5792 0 /* forever */, &is_notif);
74531fed
PA
5793 while (1)
5794 {
fee9eda9 5795 if (ret != -1 && !is_notif)
74531fed
PA
5796 switch (rs->buf[0])
5797 {
5798 case 'E': /* Error of some sort. */
5799 /* We're out of sync with the target now. Did it continue
5800 or not? We can't tell which thread it was in non-stop,
5801 so just ignore this. */
5802 warning (_("Remote failure reply: %s"), rs->buf);
5803 break;
5804 case 'O': /* Console output. */
5805 remote_console_output (rs->buf + 1);
5806 break;
5807 default:
5808 warning (_("Invalid remote reply: %s"), rs->buf);
5809 break;
5810 }
5811
5812 /* Acknowledge a pending stop reply that may have arrived in the
5813 mean time. */
722247f1
YQ
5814 if (notif_client_stop.pending_event != NULL)
5815 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
5816
5817 /* If indeed we noticed a stop reply, we're done. */
5818 stop_reply = queued_stop_reply (ptid);
5819 if (stop_reply != NULL)
5820 return process_stop_reply (stop_reply, status);
5821
47608cb1 5822 /* Still no event. If we're just polling for an event, then
74531fed 5823 return to the event loop. */
47608cb1 5824 if (options & TARGET_WNOHANG)
74531fed
PA
5825 {
5826 status->kind = TARGET_WAITKIND_IGNORE;
5827 return minus_one_ptid;
5828 }
5829
47608cb1 5830 /* Otherwise do a blocking wait. */
74531fed 5831 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 5832 1 /* forever */, &is_notif);
74531fed
PA
5833 }
5834}
5835
5836/* Wait until the remote machine stops, then return, storing status in
5837 STATUS just as `wait' would. */
5838
5839static ptid_t
47608cb1 5840remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
5841{
5842 struct remote_state *rs = get_remote_state ();
74531fed 5843 ptid_t event_ptid = null_ptid;
cea39f65 5844 char *buf;
74531fed
PA
5845 struct stop_reply *stop_reply;
5846
47608cb1
PA
5847 again:
5848
74531fed
PA
5849 status->kind = TARGET_WAITKIND_IGNORE;
5850 status->value.integer = 0;
5851
5852 stop_reply = queued_stop_reply (ptid);
5853 if (stop_reply != NULL)
5854 return process_stop_reply (stop_reply, status);
5855
5856 if (rs->cached_wait_status)
5857 /* Use the cached wait status, but only once. */
5858 rs->cached_wait_status = 0;
5859 else
5860 {
5861 int ret;
722247f1 5862 int is_notif;
74531fed
PA
5863
5864 if (!target_is_async_p ())
5865 {
5866 ofunc = signal (SIGINT, remote_interrupt);
5867 /* If the user hit C-c before this packet, or between packets,
5868 pretend that it was hit right here. */
522002f9 5869 if (check_quit_flag ())
74531fed 5870 {
522002f9 5871 clear_quit_flag ();
74531fed
PA
5872 remote_interrupt (SIGINT);
5873 }
5874 }
5875
5876 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5877 _never_ wait for ever -> test on target_is_async_p().
5878 However, before we do that we need to ensure that the caller
5879 knows how to take the target into/out of async mode. */
722247f1
YQ
5880 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5881 wait_forever_enabled_p, &is_notif);
5882
5883 /* GDB gets a notification. Return to core as this event is
5884 not interesting. */
5885 if (ret != -1 && is_notif)
5886 return minus_one_ptid;
5887
74531fed
PA
5888 if (!target_is_async_p ())
5889 signal (SIGINT, ofunc);
5890 }
5891
5892 buf = rs->buf;
5893
5894 remote_stopped_by_watchpoint_p = 0;
5895
5896 /* We got something. */
5897 rs->waiting_for_stop_reply = 0;
5898
3a29589a
DJ
5899 /* Assume that the target has acknowledged Ctrl-C unless we receive
5900 an 'F' or 'O' packet. */
5901 if (buf[0] != 'F' && buf[0] != 'O')
5902 rs->ctrlc_pending_p = 0;
5903
74531fed
PA
5904 switch (buf[0])
5905 {
5906 case 'E': /* Error of some sort. */
5907 /* We're out of sync with the target now. Did it continue or
5908 not? Not is more likely, so report a stop. */
5909 warning (_("Remote failure reply: %s"), buf);
5910 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 5911 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
5912 break;
5913 case 'F': /* File-I/O request. */
3a29589a
DJ
5914 remote_fileio_request (buf, rs->ctrlc_pending_p);
5915 rs->ctrlc_pending_p = 0;
74531fed
PA
5916 break;
5917 case 'T': case 'S': case 'X': case 'W':
5918 {
722247f1
YQ
5919 struct stop_reply *stop_reply
5920 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
5921 rs->buf);
74531fed 5922
74531fed 5923 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
5924 break;
5925 }
5926 case 'O': /* Console output. */
5927 remote_console_output (buf + 1);
e24a49d8 5928
c8e38a49
PA
5929 /* The target didn't really stop; keep waiting. */
5930 rs->waiting_for_stop_reply = 1;
e24a49d8 5931
c8e38a49
PA
5932 break;
5933 case '\0':
a493e3e2 5934 if (last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
5935 {
5936 /* Zero length reply means that we tried 'S' or 'C' and the
5937 remote system doesn't support it. */
5938 target_terminal_ours_for_output ();
5939 printf_filtered
5940 ("Can't send signals to this remote system. %s not sent.\n",
2ea28649 5941 gdb_signal_to_name (last_sent_signal));
a493e3e2 5942 last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
5943 target_terminal_inferior ();
5944
5945 strcpy ((char *) buf, last_sent_step ? "s" : "c");
5946 putpkt ((char *) buf);
5947
5948 /* We just told the target to resume, so a stop reply is in
5949 order. */
e24a49d8 5950 rs->waiting_for_stop_reply = 1;
c8e38a49 5951 break;
43ff13b4 5952 }
c8e38a49
PA
5953 /* else fallthrough */
5954 default:
5955 warning (_("Invalid remote reply: %s"), buf);
5956 /* Keep waiting. */
5957 rs->waiting_for_stop_reply = 1;
5958 break;
43ff13b4 5959 }
c8e38a49 5960
c8e38a49 5961 if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
5962 {
5963 /* Nothing interesting happened. If we're doing a non-blocking
5964 poll, we're done. Otherwise, go back to waiting. */
5965 if (options & TARGET_WNOHANG)
5966 return minus_one_ptid;
5967 else
5968 goto again;
5969 }
74531fed
PA
5970 else if (status->kind != TARGET_WAITKIND_EXITED
5971 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
5972 {
5973 if (!ptid_equal (event_ptid, null_ptid))
5974 record_currthread (event_ptid);
5975 else
5976 event_ptid = inferior_ptid;
43ff13b4 5977 }
74531fed
PA
5978 else
5979 /* A process exit. Invalidate our notion of current thread. */
5980 record_currthread (minus_one_ptid);
79d7f229 5981
82f73884 5982 return event_ptid;
43ff13b4
JM
5983}
5984
74531fed
PA
5985/* Wait until the remote machine stops, then return, storing status in
5986 STATUS just as `wait' would. */
5987
c8e38a49 5988static ptid_t
117de6a9 5989remote_wait (struct target_ops *ops,
47608cb1 5990 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
5991{
5992 ptid_t event_ptid;
5993
74531fed 5994 if (non_stop)
47608cb1 5995 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 5996 else
47608cb1 5997 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 5998
74531fed 5999 if (target_can_async_p ())
c8e38a49 6000 {
74531fed
PA
6001 /* If there are are events left in the queue tell the event loop
6002 to return here. */
722247f1 6003 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 6004 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 6005 }
c8e38a49
PA
6006
6007 return event_ptid;
6008}
6009
74ca34ce 6010/* Fetch a single register using a 'p' packet. */
c906108c 6011
b96ec7ac 6012static int
56be3814 6013fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
6014{
6015 struct remote_state *rs = get_remote_state ();
2e9f7625 6016 char *buf, *p;
b96ec7ac
AC
6017 char regp[MAX_REGISTER_SIZE];
6018 int i;
6019
74ca34ce
DJ
6020 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
6021 return 0;
6022
6023 if (reg->pnum == -1)
6024 return 0;
6025
2e9f7625 6026 p = rs->buf;
fcad0fa4 6027 *p++ = 'p';
74ca34ce 6028 p += hexnumstr (p, reg->pnum);
fcad0fa4 6029 *p++ = '\0';
1f4437a4
MS
6030 putpkt (rs->buf);
6031 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 6032
2e9f7625
DJ
6033 buf = rs->buf;
6034
74ca34ce
DJ
6035 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6036 {
6037 case PACKET_OK:
6038 break;
6039 case PACKET_UNKNOWN:
6040 return 0;
6041 case PACKET_ERROR:
27a9c0bf
MS
6042 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6043 gdbarch_register_name (get_regcache_arch (regcache),
6044 reg->regnum),
6045 buf);
74ca34ce 6046 }
3f9a994c
JB
6047
6048 /* If this register is unfetchable, tell the regcache. */
6049 if (buf[0] == 'x')
8480adf2 6050 {
56be3814 6051 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 6052 return 1;
b96ec7ac 6053 }
b96ec7ac 6054
3f9a994c
JB
6055 /* Otherwise, parse and supply the value. */
6056 p = buf;
6057 i = 0;
6058 while (p[0] != 0)
6059 {
6060 if (p[1] == 0)
74ca34ce 6061 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
6062
6063 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6064 p += 2;
6065 }
56be3814 6066 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 6067 return 1;
b96ec7ac
AC
6068}
6069
74ca34ce
DJ
6070/* Fetch the registers included in the target's 'g' packet. */
6071
29709017
DJ
6072static int
6073send_g_packet (void)
c906108c 6074{
d01949b6 6075 struct remote_state *rs = get_remote_state ();
cea39f65 6076 int buf_len;
c906108c 6077
bba74b36 6078 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 6079 remote_send (&rs->buf, &rs->buf_size);
c906108c 6080
29709017
DJ
6081 /* We can get out of synch in various cases. If the first character
6082 in the buffer is not a hex character, assume that has happened
6083 and try to fetch another packet to read. */
6084 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6085 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6086 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6087 && rs->buf[0] != 'x') /* New: unavailable register value. */
6088 {
6089 if (remote_debug)
6090 fprintf_unfiltered (gdb_stdlog,
6091 "Bad register packet; fetching a new packet\n");
6092 getpkt (&rs->buf, &rs->buf_size, 0);
6093 }
6094
74ca34ce
DJ
6095 buf_len = strlen (rs->buf);
6096
6097 /* Sanity check the received packet. */
6098 if (buf_len % 2 != 0)
6099 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
6100
6101 return buf_len / 2;
6102}
6103
6104static void
56be3814 6105process_g_packet (struct regcache *regcache)
29709017 6106{
4a22f64d 6107 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
6108 struct remote_state *rs = get_remote_state ();
6109 struct remote_arch_state *rsa = get_remote_arch_state ();
6110 int i, buf_len;
6111 char *p;
6112 char *regs;
6113
6114 buf_len = strlen (rs->buf);
6115
6116 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
6117 if (buf_len > 2 * rsa->sizeof_g_packet)
6118 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6119
6120 /* Save the size of the packet sent to us by the target. It is used
6121 as a heuristic when determining the max size of packets that the
6122 target can safely receive. */
6123 if (rsa->actual_register_packet_size == 0)
6124 rsa->actual_register_packet_size = buf_len;
6125
6126 /* If this is smaller than we guessed the 'g' packet would be,
6127 update our records. A 'g' reply that doesn't include a register's
6128 value implies either that the register is not available, or that
6129 the 'p' packet must be used. */
6130 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 6131 {
74ca34ce
DJ
6132 rsa->sizeof_g_packet = buf_len / 2;
6133
4a22f64d 6134 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 6135 {
74ca34ce
DJ
6136 if (rsa->regs[i].pnum == -1)
6137 continue;
6138
6139 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6140 rsa->regs[i].in_g_packet = 0;
b96ec7ac 6141 else
74ca34ce 6142 rsa->regs[i].in_g_packet = 1;
b96ec7ac 6143 }
74ca34ce 6144 }
b323314b 6145
74ca34ce 6146 regs = alloca (rsa->sizeof_g_packet);
c906108c
SS
6147
6148 /* Unimplemented registers read as all bits zero. */
ea9c271d 6149 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 6150
c906108c
SS
6151 /* Reply describes registers byte by byte, each byte encoded as two
6152 hex characters. Suck them all up, then supply them to the
6153 register cacheing/storage mechanism. */
6154
74ca34ce 6155 p = rs->buf;
ea9c271d 6156 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 6157 {
74ca34ce
DJ
6158 if (p[0] == 0 || p[1] == 0)
6159 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6160 internal_error (__FILE__, __LINE__,
9b20d036 6161 _("unexpected end of 'g' packet reply"));
74ca34ce 6162
c906108c 6163 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 6164 regs[i] = 0; /* 'x' */
c906108c
SS
6165 else
6166 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6167 p += 2;
6168 }
6169
a744cf53
MS
6170 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6171 {
6172 struct packet_reg *r = &rsa->regs[i];
6173
6174 if (r->in_g_packet)
6175 {
6176 if (r->offset * 2 >= strlen (rs->buf))
6177 /* This shouldn't happen - we adjusted in_g_packet above. */
6178 internal_error (__FILE__, __LINE__,
9b20d036 6179 _("unexpected end of 'g' packet reply"));
a744cf53
MS
6180 else if (rs->buf[r->offset * 2] == 'x')
6181 {
6182 gdb_assert (r->offset * 2 < strlen (rs->buf));
6183 /* The register isn't available, mark it as such (at
6184 the same time setting the value to zero). */
6185 regcache_raw_supply (regcache, r->regnum, NULL);
6186 }
6187 else
6188 regcache_raw_supply (regcache, r->regnum,
6189 regs + r->offset);
6190 }
6191 }
c906108c
SS
6192}
6193
29709017 6194static void
56be3814 6195fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
6196{
6197 send_g_packet ();
56be3814 6198 process_g_packet (regcache);
29709017
DJ
6199}
6200
e6e4e701
PA
6201/* Make the remote selected traceframe match GDB's selected
6202 traceframe. */
6203
6204static void
6205set_remote_traceframe (void)
6206{
6207 int newnum;
6208
6209 if (remote_traceframe_number == get_traceframe_number ())
6210 return;
6211
6212 /* Avoid recursion, remote_trace_find calls us again. */
6213 remote_traceframe_number = get_traceframe_number ();
6214
6215 newnum = target_trace_find (tfind_number,
6216 get_traceframe_number (), 0, 0, NULL);
6217
6218 /* Should not happen. If it does, all bets are off. */
6219 if (newnum != get_traceframe_number ())
6220 warning (_("could not set remote traceframe"));
6221}
6222
74ca34ce 6223static void
28439f5e
PA
6224remote_fetch_registers (struct target_ops *ops,
6225 struct regcache *regcache, int regnum)
74ca34ce 6226{
74ca34ce
DJ
6227 struct remote_arch_state *rsa = get_remote_arch_state ();
6228 int i;
6229
e6e4e701 6230 set_remote_traceframe ();
79d7f229 6231 set_general_thread (inferior_ptid);
74ca34ce
DJ
6232
6233 if (regnum >= 0)
6234 {
6235 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6236
74ca34ce
DJ
6237 gdb_assert (reg != NULL);
6238
6239 /* If this register might be in the 'g' packet, try that first -
6240 we are likely to read more than one register. If this is the
6241 first 'g' packet, we might be overly optimistic about its
6242 contents, so fall back to 'p'. */
6243 if (reg->in_g_packet)
6244 {
56be3814 6245 fetch_registers_using_g (regcache);
74ca34ce
DJ
6246 if (reg->in_g_packet)
6247 return;
6248 }
6249
56be3814 6250 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
6251 return;
6252
6253 /* This register is not available. */
56be3814 6254 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
6255
6256 return;
6257 }
6258
56be3814 6259 fetch_registers_using_g (regcache);
74ca34ce 6260
4a22f64d 6261 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6262 if (!rsa->regs[i].in_g_packet)
56be3814 6263 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
6264 {
6265 /* This register is not available. */
56be3814 6266 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
6267 }
6268}
6269
c906108c
SS
6270/* Prepare to store registers. Since we may send them all (using a
6271 'G' request), we have to read out the ones we don't want to change
6272 first. */
6273
c5aa993b 6274static void
316f2060 6275remote_prepare_to_store (struct regcache *regcache)
c906108c 6276{
ea9c271d 6277 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 6278 int i;
cfd77fa1 6279 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 6280
c906108c 6281 /* Make sure the entire registers array is valid. */
444abaca 6282 switch (remote_protocol_packets[PACKET_P].support)
5a2468f5
JM
6283 {
6284 case PACKET_DISABLE:
6285 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 6286 /* Make sure all the necessary registers are cached. */
4a22f64d 6287 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 6288 if (rsa->regs[i].in_g_packet)
316f2060 6289 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
6290 break;
6291 case PACKET_ENABLE:
6292 break;
6293 }
6294}
6295
ad10f812 6296/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 6297 packet was not recognized. */
5a2468f5
JM
6298
6299static int
1f4437a4
MS
6300store_register_using_P (const struct regcache *regcache,
6301 struct packet_reg *reg)
5a2468f5 6302{
4a22f64d 6303 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 6304 struct remote_state *rs = get_remote_state ();
5a2468f5 6305 /* Try storing a single register. */
6d820c5c 6306 char *buf = rs->buf;
cfd77fa1 6307 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 6308 char *p;
5a2468f5 6309
74ca34ce
DJ
6310 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
6311 return 0;
6312
6313 if (reg->pnum == -1)
6314 return 0;
6315
ea9c271d 6316 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 6317 p = buf + strlen (buf);
56be3814 6318 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 6319 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
6320 putpkt (rs->buf);
6321 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 6322
74ca34ce
DJ
6323 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6324 {
6325 case PACKET_OK:
6326 return 1;
6327 case PACKET_ERROR:
27a9c0bf
MS
6328 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6329 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
6330 case PACKET_UNKNOWN:
6331 return 0;
6332 default:
6333 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6334 }
c906108c
SS
6335}
6336
23860348
MS
6337/* Store register REGNUM, or all registers if REGNUM == -1, from the
6338 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
6339
6340static void
56be3814 6341store_registers_using_G (const struct regcache *regcache)
c906108c 6342{
d01949b6 6343 struct remote_state *rs = get_remote_state ();
ea9c271d 6344 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 6345 gdb_byte *regs;
c906108c
SS
6346 char *p;
6347
193cb69f
AC
6348 /* Extract all the registers in the regcache copying them into a
6349 local buffer. */
6350 {
b323314b 6351 int i;
a744cf53 6352
ea9c271d
DJ
6353 regs = alloca (rsa->sizeof_g_packet);
6354 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 6355 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 6356 {
ea9c271d 6357 struct packet_reg *r = &rsa->regs[i];
a744cf53 6358
b323314b 6359 if (r->in_g_packet)
56be3814 6360 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
6361 }
6362 }
c906108c
SS
6363
6364 /* Command describes registers byte by byte,
6365 each byte encoded as two hex characters. */
6d820c5c 6366 p = rs->buf;
193cb69f 6367 *p++ = 'G';
74ca34ce
DJ
6368 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6369 updated. */
6370 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
6371 putpkt (rs->buf);
6372 getpkt (&rs->buf, &rs->buf_size, 0);
6373 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
6374 error (_("Could not write registers; remote failure reply '%s'"),
6375 rs->buf);
c906108c 6376}
74ca34ce
DJ
6377
6378/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6379 of the register cache buffer. FIXME: ignores errors. */
6380
6381static void
28439f5e
PA
6382remote_store_registers (struct target_ops *ops,
6383 struct regcache *regcache, int regnum)
74ca34ce 6384{
74ca34ce
DJ
6385 struct remote_arch_state *rsa = get_remote_arch_state ();
6386 int i;
6387
e6e4e701 6388 set_remote_traceframe ();
79d7f229 6389 set_general_thread (inferior_ptid);
74ca34ce
DJ
6390
6391 if (regnum >= 0)
6392 {
6393 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6394
74ca34ce
DJ
6395 gdb_assert (reg != NULL);
6396
6397 /* Always prefer to store registers using the 'P' packet if
6398 possible; we often change only a small number of registers.
6399 Sometimes we change a larger number; we'd need help from a
6400 higher layer to know to use 'G'. */
56be3814 6401 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
6402 return;
6403
6404 /* For now, don't complain if we have no way to write the
6405 register. GDB loses track of unavailable registers too
6406 easily. Some day, this may be an error. We don't have
0df8b418 6407 any way to read the register, either... */
74ca34ce
DJ
6408 if (!reg->in_g_packet)
6409 return;
6410
56be3814 6411 store_registers_using_G (regcache);
74ca34ce
DJ
6412 return;
6413 }
6414
56be3814 6415 store_registers_using_G (regcache);
74ca34ce 6416
4a22f64d 6417 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6418 if (!rsa->regs[i].in_g_packet)
56be3814 6419 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
6420 /* See above for why we do not issue an error here. */
6421 continue;
6422}
c906108c
SS
6423\f
6424
6425/* Return the number of hex digits in num. */
6426
6427static int
fba45db2 6428hexnumlen (ULONGEST num)
c906108c
SS
6429{
6430 int i;
6431
6432 for (i = 0; num != 0; i++)
6433 num >>= 4;
6434
6435 return max (i, 1);
6436}
6437
2df3850c 6438/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
6439
6440static int
fba45db2 6441hexnumstr (char *buf, ULONGEST num)
c906108c 6442{
c906108c 6443 int len = hexnumlen (num);
a744cf53 6444
2df3850c
JM
6445 return hexnumnstr (buf, num, len);
6446}
6447
c906108c 6448
2df3850c 6449/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 6450
2df3850c 6451static int
fba45db2 6452hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
6453{
6454 int i;
6455
6456 buf[width] = '\0';
6457
6458 for (i = width - 1; i >= 0; i--)
c906108c 6459 {
c5aa993b 6460 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
6461 num >>= 4;
6462 }
6463
2df3850c 6464 return width;
c906108c
SS
6465}
6466
23860348 6467/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
6468
6469static CORE_ADDR
fba45db2 6470remote_address_masked (CORE_ADDR addr)
c906108c 6471{
883b9c6c 6472 unsigned int address_size = remote_address_size;
a744cf53 6473
911c95a5
UW
6474 /* If "remoteaddresssize" was not set, default to target address size. */
6475 if (!address_size)
f5656ead 6476 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
6477
6478 if (address_size > 0
6479 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
6480 {
6481 /* Only create a mask when that mask can safely be constructed
23860348 6482 in a ULONGEST variable. */
c906108c 6483 ULONGEST mask = 1;
a744cf53 6484
911c95a5 6485 mask = (mask << address_size) - 1;
c906108c
SS
6486 addr &= mask;
6487 }
6488 return addr;
6489}
6490
a31ea83d
DJ
6491/* Convert BUFFER, binary data at least LEN bytes long, into escaped
6492 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
6493 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
6494 (which may be more than *OUT_LEN due to escape characters). The
6495 total number of bytes in the output buffer will be at most
6496 OUT_MAXLEN. */
6497
6498static int
6499remote_escape_output (const gdb_byte *buffer, int len,
6500 gdb_byte *out_buf, int *out_len,
6501 int out_maxlen)
6502{
6503 int input_index, output_index;
6504
6505 output_index = 0;
6506 for (input_index = 0; input_index < len; input_index++)
6507 {
6508 gdb_byte b = buffer[input_index];
6509
6510 if (b == '$' || b == '#' || b == '}')
6511 {
6512 /* These must be escaped. */
6513 if (output_index + 2 > out_maxlen)
6514 break;
6515 out_buf[output_index++] = '}';
6516 out_buf[output_index++] = b ^ 0x20;
6517 }
6518 else
6519 {
6520 if (output_index + 1 > out_maxlen)
6521 break;
6522 out_buf[output_index++] = b;
6523 }
6524 }
6525
6526 *out_len = input_index;
6527 return output_index;
6528}
6529
0876f84a
DJ
6530/* Convert BUFFER, escaped data LEN bytes long, into binary data
6531 in OUT_BUF. Return the number of bytes written to OUT_BUF.
6532 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
6533
6534 This function reverses remote_escape_output. It allows more
6535 escaped characters than that function does, in particular because
6536 '*' must be escaped to avoid the run-length encoding processing
6537 in reading packets. */
6538
6539static int
6540remote_unescape_input (const gdb_byte *buffer, int len,
6541 gdb_byte *out_buf, int out_maxlen)
6542{
6543 int input_index, output_index;
6544 int escaped;
6545
6546 output_index = 0;
6547 escaped = 0;
6548 for (input_index = 0; input_index < len; input_index++)
6549 {
6550 gdb_byte b = buffer[input_index];
6551
6552 if (output_index + 1 > out_maxlen)
6553 {
6554 warning (_("Received too much data from remote target;"
6555 " ignoring overflow."));
6556 return output_index;
6557 }
6558
6559 if (escaped)
6560 {
6561 out_buf[output_index++] = b ^ 0x20;
6562 escaped = 0;
6563 }
6564 else if (b == '}')
6565 escaped = 1;
6566 else
6567 out_buf[output_index++] = b;
6568 }
6569
6570 if (escaped)
6571 error (_("Unmatched escape character in target response."));
6572
6573 return output_index;
6574}
6575
c906108c
SS
6576/* Determine whether the remote target supports binary downloading.
6577 This is accomplished by sending a no-op memory write of zero length
6578 to the target at the specified address. It does not suffice to send
23860348
MS
6579 the whole packet, since many stubs strip the eighth bit and
6580 subsequently compute a wrong checksum, which causes real havoc with
6581 remote_write_bytes.
7a292a7a 6582
96baa820 6583 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 6584 clean. In cases like this, the user should clear "remote
23860348 6585 X-packet". */
96baa820 6586
c906108c 6587static void
fba45db2 6588check_binary_download (CORE_ADDR addr)
c906108c 6589{
d01949b6 6590 struct remote_state *rs = get_remote_state ();
24b06219 6591
444abaca 6592 switch (remote_protocol_packets[PACKET_X].support)
c906108c 6593 {
96baa820
JM
6594 case PACKET_DISABLE:
6595 break;
6596 case PACKET_ENABLE:
6597 break;
6598 case PACKET_SUPPORT_UNKNOWN:
6599 {
96baa820 6600 char *p;
802188a7 6601
2e9f7625 6602 p = rs->buf;
96baa820
JM
6603 *p++ = 'X';
6604 p += hexnumstr (p, (ULONGEST) addr);
6605 *p++ = ',';
6606 p += hexnumstr (p, (ULONGEST) 0);
6607 *p++ = ':';
6608 *p = '\0';
802188a7 6609
2e9f7625 6610 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 6611 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 6612
2e9f7625 6613 if (rs->buf[0] == '\0')
96baa820
JM
6614 {
6615 if (remote_debug)
6616 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
6617 "binary downloading NOT "
6618 "supported by target\n");
444abaca 6619 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
6620 }
6621 else
6622 {
6623 if (remote_debug)
6624 fprintf_unfiltered (gdb_stdlog,
64b9b334 6625 "binary downloading supported by target\n");
444abaca 6626 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
6627 }
6628 break;
6629 }
c906108c
SS
6630 }
6631}
6632
6633/* Write memory data directly to the remote machine.
6634 This does not inform the data cache; the data cache uses this.
a76d924d 6635 HEADER is the starting part of the packet.
c906108c
SS
6636 MEMADDR is the address in the remote memory space.
6637 MYADDR is the address of the buffer in our space.
6638 LEN is the number of bytes.
a76d924d
DJ
6639 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6640 should send data as binary ('X'), or hex-encoded ('M').
6641
6642 The function creates packet of the form
6643 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6644
6645 where encoding of <DATA> is termined by PACKET_FORMAT.
6646
6647 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6648 are omitted.
6649
6650 Returns the number of bytes transferred, or 0 (setting errno) for
23860348 6651 error. Only transfer a single packet. */
c906108c 6652
a76d924d
DJ
6653static int
6654remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
45aa4659 6655 const gdb_byte *myaddr, ssize_t len,
a76d924d 6656 char packet_format, int use_length)
c906108c 6657{
6d820c5c 6658 struct remote_state *rs = get_remote_state ();
cfd77fa1 6659 char *p;
a76d924d
DJ
6660 char *plen = NULL;
6661 int plenlen = 0;
917317f4
JM
6662 int todo;
6663 int nr_bytes;
a257b5bb 6664 int payload_size;
6765f3e5 6665 int payload_length;
a76d924d
DJ
6666 int header_length;
6667
6668 if (packet_format != 'X' && packet_format != 'M')
6669 internal_error (__FILE__, __LINE__,
9b20d036 6670 _("remote_write_bytes_aux: bad packet format"));
c906108c 6671
b2182ed2
DJ
6672 if (len <= 0)
6673 return 0;
6674
3de11b2e 6675 payload_size = get_memory_write_packet_size ();
2bc416ba 6676
6d820c5c
DJ
6677 /* The packet buffer will be large enough for the payload;
6678 get_memory_packet_size ensures this. */
a76d924d 6679 rs->buf[0] = '\0';
c906108c 6680
a257b5bb 6681 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
6682 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6683
a76d924d
DJ
6684 payload_size -= strlen ("$,:#NN");
6685 if (!use_length)
0df8b418 6686 /* The comma won't be used. */
a76d924d
DJ
6687 payload_size += 1;
6688 header_length = strlen (header);
6689 payload_size -= header_length;
3de11b2e 6690 payload_size -= hexnumlen (memaddr);
c906108c 6691
a76d924d 6692 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 6693
a76d924d
DJ
6694 strcat (rs->buf, header);
6695 p = rs->buf + strlen (header);
6696
6697 /* Compute a best guess of the number of bytes actually transfered. */
6698 if (packet_format == 'X')
c906108c 6699 {
23860348 6700 /* Best guess at number of bytes that will fit. */
a257b5bb 6701 todo = min (len, payload_size);
a76d924d
DJ
6702 if (use_length)
6703 payload_size -= hexnumlen (todo);
3de11b2e 6704 todo = min (todo, payload_size);
a76d924d
DJ
6705 }
6706 else
6707 {
23860348 6708 /* Num bytes that will fit. */
a257b5bb 6709 todo = min (len, payload_size / 2);
a76d924d
DJ
6710 if (use_length)
6711 payload_size -= hexnumlen (todo);
3de11b2e 6712 todo = min (todo, payload_size / 2);
917317f4 6713 }
a76d924d 6714
3de11b2e
NS
6715 if (todo <= 0)
6716 internal_error (__FILE__, __LINE__,
405f8e94 6717 _("minimum packet size too small to write data"));
802188a7 6718
6765f3e5
DJ
6719 /* If we already need another packet, then try to align the end
6720 of this packet to a useful boundary. */
6721 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6722 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6723
a257b5bb 6724 /* Append "<memaddr>". */
917317f4
JM
6725 memaddr = remote_address_masked (memaddr);
6726 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 6727
a76d924d
DJ
6728 if (use_length)
6729 {
6730 /* Append ",". */
6731 *p++ = ',';
802188a7 6732
a76d924d
DJ
6733 /* Append <len>. Retain the location/size of <len>. It may need to
6734 be adjusted once the packet body has been created. */
6735 plen = p;
6736 plenlen = hexnumstr (p, (ULONGEST) todo);
6737 p += plenlen;
6738 }
a257b5bb
AC
6739
6740 /* Append ":". */
917317f4
JM
6741 *p++ = ':';
6742 *p = '\0';
802188a7 6743
a257b5bb 6744 /* Append the packet body. */
a76d924d 6745 if (packet_format == 'X')
917317f4 6746 {
917317f4
JM
6747 /* Binary mode. Send target system values byte by byte, in
6748 increasing byte addresses. Only escape certain critical
6749 characters. */
6765f3e5
DJ
6750 payload_length = remote_escape_output (myaddr, todo, p, &nr_bytes,
6751 payload_size);
6752
6753 /* If not all TODO bytes fit, then we'll need another packet. Make
9b7194bc
DJ
6754 a second try to keep the end of the packet aligned. Don't do
6755 this if the packet is tiny. */
6756 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6765f3e5
DJ
6757 {
6758 int new_nr_bytes;
6759
6760 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6761 - memaddr);
6762 if (new_nr_bytes != nr_bytes)
6763 payload_length = remote_escape_output (myaddr, new_nr_bytes,
6764 p, &nr_bytes,
6765 payload_size);
6766 }
6767
6768 p += payload_length;
a76d924d 6769 if (use_length && nr_bytes < todo)
c906108c 6770 {
802188a7 6771 /* Escape chars have filled up the buffer prematurely,
917317f4
JM
6772 and we have actually sent fewer bytes than planned.
6773 Fix-up the length field of the packet. Use the same
6774 number of characters as before. */
917317f4
JM
6775 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6776 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 6777 }
a76d924d
DJ
6778 }
6779 else
6780 {
917317f4
JM
6781 /* Normal mode: Send target system values byte by byte, in
6782 increasing byte addresses. Each byte is encoded as a two hex
6783 value. */
2644f393 6784 nr_bytes = bin2hex (myaddr, p, todo);
aa6c0017 6785 p += 2 * nr_bytes;
c906108c 6786 }
802188a7 6787
2e9f7625 6788 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 6789 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 6790
2e9f7625 6791 if (rs->buf[0] == 'E')
917317f4
JM
6792 {
6793 /* There is no correspondance between what the remote protocol
6794 uses for errors and errno codes. We would like a cleaner way
6795 of representing errors (big enough to include errno codes,
6796 bfd_error codes, and others). But for now just return EIO. */
6797 errno = EIO;
6798 return 0;
6799 }
802188a7 6800
23860348
MS
6801 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6802 fewer bytes than we'd planned. */
917317f4 6803 return nr_bytes;
c906108c
SS
6804}
6805
a76d924d
DJ
6806/* Write memory data directly to the remote machine.
6807 This does not inform the data cache; the data cache uses this.
6808 MEMADDR is the address in the remote memory space.
6809 MYADDR is the address of the buffer in our space.
6810 LEN is the number of bytes.
6811
6812 Returns number of bytes transferred, or 0 (setting errno) for
6813 error. Only transfer a single packet. */
6814
f7605bc2 6815static int
45aa4659 6816remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ssize_t len)
a76d924d
DJ
6817{
6818 char *packet_format = 0;
6819
6820 /* Check whether the target supports binary download. */
6821 check_binary_download (memaddr);
6822
6823 switch (remote_protocol_packets[PACKET_X].support)
6824 {
6825 case PACKET_ENABLE:
6826 packet_format = "X";
6827 break;
6828 case PACKET_DISABLE:
6829 packet_format = "M";
6830 break;
6831 case PACKET_SUPPORT_UNKNOWN:
6832 internal_error (__FILE__, __LINE__,
6833 _("remote_write_bytes: bad internal state"));
6834 default:
6835 internal_error (__FILE__, __LINE__, _("bad switch"));
6836 }
6837
6838 return remote_write_bytes_aux (packet_format,
6839 memaddr, myaddr, len, packet_format[0], 1);
6840}
6841
c906108c
SS
6842/* Read memory data directly from the remote machine.
6843 This does not use the data cache; the data cache uses this.
6844 MEMADDR is the address in the remote memory space.
6845 MYADDR is the address of the buffer in our space.
6846 LEN is the number of bytes.
6847
6848 Returns number of bytes transferred, or 0 for error. */
6849
f7605bc2 6850static int
cfd77fa1 6851remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
c906108c 6852{
6d820c5c 6853 struct remote_state *rs = get_remote_state ();
23860348 6854 int max_buf_size; /* Max size of packet output buffer. */
f7605bc2
PA
6855 char *p;
6856 int todo;
6857 int i;
c906108c 6858
b2182ed2
DJ
6859 if (len <= 0)
6860 return 0;
6861
11cf8741 6862 max_buf_size = get_memory_read_packet_size ();
6d820c5c
DJ
6863 /* The packet buffer will be large enough for the payload;
6864 get_memory_packet_size ensures this. */
c906108c 6865
f7605bc2
PA
6866 /* Number if bytes that will fit. */
6867 todo = min (len, max_buf_size / 2);
c906108c 6868
f7605bc2
PA
6869 /* Construct "m"<memaddr>","<len>". */
6870 memaddr = remote_address_masked (memaddr);
6871 p = rs->buf;
6872 *p++ = 'm';
6873 p += hexnumstr (p, (ULONGEST) memaddr);
6874 *p++ = ',';
6875 p += hexnumstr (p, (ULONGEST) todo);
6876 *p = '\0';
6877 putpkt (rs->buf);
6878 getpkt (&rs->buf, &rs->buf_size, 0);
6879 if (rs->buf[0] == 'E'
6880 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6881 && rs->buf[3] == '\0')
6882 {
6883 /* There is no correspondance between what the remote protocol
6884 uses for errors and errno codes. We would like a cleaner way
6885 of representing errors (big enough to include errno codes,
6886 bfd_error codes, and others). But for now just return
6887 EIO. */
6888 errno = EIO;
6889 return 0;
c906108c 6890 }
f7605bc2
PA
6891 /* Reply describes memory byte by byte, each byte encoded as two hex
6892 characters. */
6893 p = rs->buf;
6894 i = hex2bin (p, myaddr, todo);
6895 /* Return what we have. Let higher layers handle partial reads. */
6896 return i;
c906108c 6897}
74531fed 6898
c906108c
SS
6899\f
6900/* Read or write LEN bytes from inferior memory at MEMADDR,
23860348
MS
6901 transferring to or from debugger address BUFFER. Write to inferior
6902 if SHOULD_WRITE is nonzero. Returns length of data written or
6903 read; 0 for error. TARGET is unused. */
392a587b 6904
c906108c 6905static int
961cb7b5 6906remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
0a65a603 6907 int should_write, struct mem_attrib *attrib,
29e57380 6908 struct target_ops *target)
c906108c 6909{
4930751a
C
6910 int res;
6911
e6e4e701 6912 set_remote_traceframe ();
82f73884
PA
6913 set_general_thread (inferior_ptid);
6914
4930751a 6915 if (should_write)
b2182ed2 6916 res = remote_write_bytes (mem_addr, buffer, mem_len);
4930751a 6917 else
b2182ed2 6918 res = remote_read_bytes (mem_addr, buffer, mem_len);
4930751a
C
6919
6920 return res;
c906108c
SS
6921}
6922
a76d924d
DJ
6923/* Sends a packet with content determined by the printf format string
6924 FORMAT and the remaining arguments, then gets the reply. Returns
6925 whether the packet was a success, a failure, or unknown. */
6926
2c0b251b 6927static enum packet_result
a76d924d
DJ
6928remote_send_printf (const char *format, ...)
6929{
6930 struct remote_state *rs = get_remote_state ();
6931 int max_size = get_remote_packet_size ();
a76d924d 6932 va_list ap;
a744cf53 6933
a76d924d
DJ
6934 va_start (ap, format);
6935
6936 rs->buf[0] = '\0';
6937 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 6938 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
6939
6940 if (putpkt (rs->buf) < 0)
6941 error (_("Communication problem with target."));
6942
6943 rs->buf[0] = '\0';
6944 getpkt (&rs->buf, &rs->buf_size, 0);
6945
6946 return packet_check_result (rs->buf);
6947}
6948
6949static void
6950restore_remote_timeout (void *p)
6951{
6952 int value = *(int *)p;
a744cf53 6953
a76d924d
DJ
6954 remote_timeout = value;
6955}
6956
6957/* Flash writing can take quite some time. We'll set
6958 effectively infinite timeout for flash operations.
6959 In future, we'll need to decide on a better approach. */
6960static const int remote_flash_timeout = 1000;
6961
6962static void
6963remote_flash_erase (struct target_ops *ops,
6964 ULONGEST address, LONGEST length)
6965{
f5656ead 6966 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
6967 int saved_remote_timeout = remote_timeout;
6968 enum packet_result ret;
a76d924d
DJ
6969 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6970 &saved_remote_timeout);
a744cf53 6971
a76d924d
DJ
6972 remote_timeout = remote_flash_timeout;
6973
6974 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 6975 phex (address, addr_size),
a76d924d
DJ
6976 phex (length, 4));
6977 switch (ret)
6978 {
6979 case PACKET_UNKNOWN:
6980 error (_("Remote target does not support flash erase"));
6981 case PACKET_ERROR:
6982 error (_("Error erasing flash with vFlashErase packet"));
6983 default:
6984 break;
6985 }
6986
6987 do_cleanups (back_to);
6988}
6989
6990static LONGEST
6991remote_flash_write (struct target_ops *ops,
6992 ULONGEST address, LONGEST length,
6993 const gdb_byte *data)
6994{
6995 int saved_remote_timeout = remote_timeout;
6996 int ret;
6997 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6998 &saved_remote_timeout);
6999
7000 remote_timeout = remote_flash_timeout;
7001 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
7002 do_cleanups (back_to);
7003
7004 return ret;
7005}
7006
7007static void
7008remote_flash_done (struct target_ops *ops)
7009{
7010 int saved_remote_timeout = remote_timeout;
7011 int ret;
7012 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7013 &saved_remote_timeout);
7014
7015 remote_timeout = remote_flash_timeout;
7016 ret = remote_send_printf ("vFlashDone");
7017 do_cleanups (back_to);
7018
7019 switch (ret)
7020 {
7021 case PACKET_UNKNOWN:
7022 error (_("Remote target does not support vFlashDone"));
7023 case PACKET_ERROR:
7024 error (_("Error finishing flash operation"));
7025 default:
7026 break;
7027 }
7028}
7029
c906108c 7030static void
fba45db2 7031remote_files_info (struct target_ops *ignore)
c906108c
SS
7032{
7033 puts_filtered ("Debugging a target over a serial line.\n");
7034}
7035\f
7036/* Stuff for dealing with the packets which are part of this protocol.
7037 See comment at top of file for details. */
7038
0876f84a 7039/* Read a single character from the remote end. */
c906108c
SS
7040
7041static int
fba45db2 7042readchar (int timeout)
c906108c
SS
7043{
7044 int ch;
7045
2cd58942 7046 ch = serial_readchar (remote_desc, timeout);
c906108c 7047
2acceee2 7048 if (ch >= 0)
0876f84a 7049 return ch;
2acceee2
JM
7050
7051 switch ((enum serial_rc) ch)
c906108c
SS
7052 {
7053 case SERIAL_EOF:
ce5ce7ed 7054 pop_target ();
8a3fe4f8 7055 error (_("Remote connection closed"));
2acceee2 7056 /* no return */
c906108c 7057 case SERIAL_ERROR:
4ac8c4da 7058 pop_target ();
3e43a32a
MS
7059 perror_with_name (_("Remote communication error. "
7060 "Target disconnected."));
2acceee2 7061 /* no return */
c906108c 7062 case SERIAL_TIMEOUT:
2acceee2 7063 break;
c906108c 7064 }
2acceee2 7065 return ch;
c906108c
SS
7066}
7067
6d820c5c
DJ
7068/* Send the command in *BUF to the remote machine, and read the reply
7069 into *BUF. Report an error if we get an error reply. Resize
7070 *BUF using xrealloc if necessary to hold the result, and update
7071 *SIZEOF_BUF. */
c906108c
SS
7072
7073static void
6d820c5c
DJ
7074remote_send (char **buf,
7075 long *sizeof_buf)
c906108c 7076{
6d820c5c 7077 putpkt (*buf);
c2d11a7d 7078 getpkt (buf, sizeof_buf, 0);
c906108c 7079
6d820c5c
DJ
7080 if ((*buf)[0] == 'E')
7081 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
7082}
7083
6e5abd65
PA
7084/* Return a pointer to an xmalloc'ed string representing an escaped
7085 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7086 etc. The caller is responsible for releasing the returned
7087 memory. */
7088
7089static char *
7090escape_buffer (const char *buf, int n)
7091{
7092 struct cleanup *old_chain;
7093 struct ui_file *stb;
7094 char *str;
6e5abd65
PA
7095
7096 stb = mem_fileopen ();
7097 old_chain = make_cleanup_ui_file_delete (stb);
7098
7099 fputstrn_unfiltered (buf, n, 0, stb);
759ef836 7100 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
7101 do_cleanups (old_chain);
7102 return str;
7103}
7104
c906108c
SS
7105/* Display a null-terminated packet on stdout, for debugging, using C
7106 string notation. */
7107
7108static void
fba45db2 7109print_packet (char *buf)
c906108c
SS
7110{
7111 puts_filtered ("\"");
43e526b9 7112 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
7113 puts_filtered ("\"");
7114}
7115
7116int
fba45db2 7117putpkt (char *buf)
c906108c
SS
7118{
7119 return putpkt_binary (buf, strlen (buf));
7120}
7121
7122/* Send a packet to the remote machine, with error checking. The data
23860348 7123 of the packet is in BUF. The string in BUF can be at most
ea9c271d 7124 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
7125 and for a possible /0 if we are debugging (remote_debug) and want
7126 to print the sent packet as a string. */
c906108c
SS
7127
7128static int
fba45db2 7129putpkt_binary (char *buf, int cnt)
c906108c 7130{
2d717e4f 7131 struct remote_state *rs = get_remote_state ();
c906108c
SS
7132 int i;
7133 unsigned char csum = 0;
11cf8741 7134 char *buf2 = alloca (cnt + 6);
085dd6e6 7135
c906108c
SS
7136 int ch;
7137 int tcount = 0;
7138 char *p;
dd61ec5c 7139 char *message;
c906108c 7140
e24a49d8
PA
7141 /* Catch cases like trying to read memory or listing threads while
7142 we're waiting for a stop reply. The remote server wouldn't be
7143 ready to handle this request, so we'd hang and timeout. We don't
7144 have to worry about this in synchronous mode, because in that
7145 case it's not possible to issue a command while the target is
74531fed
PA
7146 running. This is not a problem in non-stop mode, because in that
7147 case, the stub is always ready to process serial input. */
7148 if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
e24a49d8
PA
7149 error (_("Cannot execute this command while the target is running."));
7150
2d717e4f
DJ
7151 /* We're sending out a new packet. Make sure we don't look at a
7152 stale cached response. */
7153 rs->cached_wait_status = 0;
7154
c906108c
SS
7155 /* Copy the packet into buffer BUF2, encapsulating it
7156 and giving it a checksum. */
7157
c906108c
SS
7158 p = buf2;
7159 *p++ = '$';
7160
7161 for (i = 0; i < cnt; i++)
7162 {
7163 csum += buf[i];
7164 *p++ = buf[i];
7165 }
7166 *p++ = '#';
7167 *p++ = tohex ((csum >> 4) & 0xf);
7168 *p++ = tohex (csum & 0xf);
7169
7170 /* Send it over and over until we get a positive ack. */
7171
7172 while (1)
7173 {
7174 int started_error_output = 0;
7175
7176 if (remote_debug)
7177 {
6e5abd65
PA
7178 struct cleanup *old_chain;
7179 char *str;
7180
c906108c 7181 *p = '\0';
6e5abd65
PA
7182 str = escape_buffer (buf2, p - buf2);
7183 old_chain = make_cleanup (xfree, str);
7184 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 7185 gdb_flush (gdb_stdlog);
6e5abd65 7186 do_cleanups (old_chain);
c906108c 7187 }
2cd58942 7188 if (serial_write (remote_desc, buf2, p - buf2))
e2e0b3e5 7189 perror_with_name (_("putpkt: write failed"));
c906108c 7190
a6f3e723
SL
7191 /* If this is a no acks version of the remote protocol, send the
7192 packet and move on. */
7193 if (rs->noack_mode)
7194 break;
7195
74531fed
PA
7196 /* Read until either a timeout occurs (-2) or '+' is read.
7197 Handle any notification that arrives in the mean time. */
c906108c
SS
7198 while (1)
7199 {
7200 ch = readchar (remote_timeout);
7201
c5aa993b 7202 if (remote_debug)
c906108c
SS
7203 {
7204 switch (ch)
7205 {
7206 case '+':
1216fa2c 7207 case '-':
c906108c
SS
7208 case SERIAL_TIMEOUT:
7209 case '$':
74531fed 7210 case '%':
c906108c
SS
7211 if (started_error_output)
7212 {
7213 putchar_unfiltered ('\n');
7214 started_error_output = 0;
7215 }
7216 }
7217 }
7218
7219 switch (ch)
7220 {
7221 case '+':
7222 if (remote_debug)
0f71a2f6 7223 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 7224 return 1;
1216fa2c
AC
7225 case '-':
7226 if (remote_debug)
7227 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 7228 /* FALLTHROUGH */
c906108c 7229 case SERIAL_TIMEOUT:
c5aa993b 7230 tcount++;
c906108c
SS
7231 if (tcount > 3)
7232 return 0;
23860348 7233 break; /* Retransmit buffer. */
c906108c
SS
7234 case '$':
7235 {
40e3f985 7236 if (remote_debug)
2bc416ba 7237 fprintf_unfiltered (gdb_stdlog,
23860348 7238 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
7239 /* It's probably an old response sent because an ACK
7240 was lost. Gobble up the packet and ack it so it
7241 doesn't get retransmitted when we resend this
7242 packet. */
6d820c5c 7243 skip_frame ();
d6f7abdf 7244 serial_write (remote_desc, "+", 1);
23860348 7245 continue; /* Now, go look for +. */
c906108c 7246 }
74531fed
PA
7247
7248 case '%':
7249 {
7250 int val;
7251
7252 /* If we got a notification, handle it, and go back to looking
7253 for an ack. */
7254 /* We've found the start of a notification. Now
7255 collect the data. */
7256 val = read_frame (&rs->buf, &rs->buf_size);
7257 if (val >= 0)
7258 {
7259 if (remote_debug)
7260 {
6e5abd65
PA
7261 struct cleanup *old_chain;
7262 char *str;
7263
7264 str = escape_buffer (rs->buf, val);
7265 old_chain = make_cleanup (xfree, str);
7266 fprintf_unfiltered (gdb_stdlog,
7267 " Notification received: %s\n",
7268 str);
7269 do_cleanups (old_chain);
74531fed 7270 }
8128fd8e 7271 handle_notification (rs->buf);
74531fed
PA
7272 /* We're in sync now, rewait for the ack. */
7273 tcount = 0;
7274 }
7275 else
7276 {
7277 if (remote_debug)
7278 {
7279 if (!started_error_output)
7280 {
7281 started_error_output = 1;
7282 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7283 }
7284 fputc_unfiltered (ch & 0177, gdb_stdlog);
7285 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7286 }
7287 }
7288 continue;
7289 }
7290 /* fall-through */
c906108c
SS
7291 default:
7292 if (remote_debug)
7293 {
7294 if (!started_error_output)
7295 {
7296 started_error_output = 1;
0f71a2f6 7297 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 7298 }
0f71a2f6 7299 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
7300 }
7301 continue;
7302 }
23860348 7303 break; /* Here to retransmit. */
c906108c
SS
7304 }
7305
7306#if 0
7307 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
7308 able to get out next time we call QUIT, without anything as
7309 violent as interrupt_query. If we want to provide a way out of
7310 here without getting to the next QUIT, it should be based on
7311 hitting ^C twice as in remote_wait. */
c906108c
SS
7312 if (quit_flag)
7313 {
7314 quit_flag = 0;
7315 interrupt_query ();
7316 }
7317#endif
7318 }
a6f3e723 7319 return 0;
c906108c
SS
7320}
7321
6d820c5c
DJ
7322/* Come here after finding the start of a frame when we expected an
7323 ack. Do our best to discard the rest of this packet. */
7324
7325static void
7326skip_frame (void)
7327{
7328 int c;
7329
7330 while (1)
7331 {
7332 c = readchar (remote_timeout);
7333 switch (c)
7334 {
7335 case SERIAL_TIMEOUT:
7336 /* Nothing we can do. */
7337 return;
7338 case '#':
7339 /* Discard the two bytes of checksum and stop. */
7340 c = readchar (remote_timeout);
7341 if (c >= 0)
7342 c = readchar (remote_timeout);
7343
7344 return;
7345 case '*': /* Run length encoding. */
7346 /* Discard the repeat count. */
7347 c = readchar (remote_timeout);
7348 if (c < 0)
7349 return;
7350 break;
7351 default:
7352 /* A regular character. */
7353 break;
7354 }
7355 }
7356}
7357
c906108c 7358/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
7359 into *BUF, verifying the checksum, length, and handling run-length
7360 compression. NUL terminate the buffer. If there is not enough room,
7361 expand *BUF using xrealloc.
c906108c 7362
c2d11a7d
JM
7363 Returns -1 on error, number of characters in buffer (ignoring the
7364 trailing NULL) on success. (could be extended to return one of the
23860348 7365 SERIAL status indications). */
c2d11a7d
JM
7366
7367static long
6d820c5c
DJ
7368read_frame (char **buf_p,
7369 long *sizeof_buf)
c906108c
SS
7370{
7371 unsigned char csum;
c2d11a7d 7372 long bc;
c906108c 7373 int c;
6d820c5c 7374 char *buf = *buf_p;
a6f3e723 7375 struct remote_state *rs = get_remote_state ();
c906108c
SS
7376
7377 csum = 0;
c2d11a7d 7378 bc = 0;
c906108c
SS
7379
7380 while (1)
7381 {
7382 c = readchar (remote_timeout);
c906108c
SS
7383 switch (c)
7384 {
7385 case SERIAL_TIMEOUT:
7386 if (remote_debug)
0f71a2f6 7387 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 7388 return -1;
c906108c
SS
7389 case '$':
7390 if (remote_debug)
0f71a2f6
JM
7391 fputs_filtered ("Saw new packet start in middle of old one\n",
7392 gdb_stdlog);
23860348 7393 return -1; /* Start a new packet, count retries. */
c906108c
SS
7394 case '#':
7395 {
7396 unsigned char pktcsum;
e1b09194
AC
7397 int check_0 = 0;
7398 int check_1 = 0;
c906108c 7399
c2d11a7d 7400 buf[bc] = '\0';
c906108c 7401
e1b09194
AC
7402 check_0 = readchar (remote_timeout);
7403 if (check_0 >= 0)
7404 check_1 = readchar (remote_timeout);
802188a7 7405
e1b09194
AC
7406 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7407 {
7408 if (remote_debug)
2bc416ba 7409 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 7410 gdb_stdlog);
e1b09194
AC
7411 return -1;
7412 }
7413 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
7414 {
7415 if (remote_debug)
2bc416ba 7416 fputs_filtered ("Communication error in checksum\n",
23860348 7417 gdb_stdlog);
40e3f985
FN
7418 return -1;
7419 }
c906108c 7420
a6f3e723
SL
7421 /* Don't recompute the checksum; with no ack packets we
7422 don't have any way to indicate a packet retransmission
7423 is necessary. */
7424 if (rs->noack_mode)
7425 return bc;
7426
e1b09194 7427 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 7428 if (csum == pktcsum)
c2d11a7d 7429 return bc;
c906108c 7430
c5aa993b 7431 if (remote_debug)
c906108c 7432 {
6e5abd65
PA
7433 struct cleanup *old_chain;
7434 char *str;
7435
7436 str = escape_buffer (buf, bc);
7437 old_chain = make_cleanup (xfree, str);
7438 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7439 "Bad checksum, sentsum=0x%x, "
7440 "csum=0x%x, buf=%s\n",
6e5abd65
PA
7441 pktcsum, csum, str);
7442 do_cleanups (old_chain);
c906108c 7443 }
c2d11a7d 7444 /* Number of characters in buffer ignoring trailing
23860348 7445 NULL. */
c2d11a7d 7446 return -1;
c906108c 7447 }
23860348 7448 case '*': /* Run length encoding. */
c2c6d25f
JM
7449 {
7450 int repeat;
c906108c 7451
a744cf53 7452 csum += c;
b4501125
AC
7453 c = readchar (remote_timeout);
7454 csum += c;
23860348 7455 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 7456
23860348 7457 /* The character before ``*'' is repeated. */
c2d11a7d 7458
6d820c5c 7459 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 7460 {
6d820c5c
DJ
7461 if (bc + repeat - 1 >= *sizeof_buf - 1)
7462 {
7463 /* Make some more room in the buffer. */
7464 *sizeof_buf += repeat;
7465 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7466 buf = *buf_p;
7467 }
7468
c2d11a7d
JM
7469 memset (&buf[bc], buf[bc - 1], repeat);
7470 bc += repeat;
c2c6d25f
JM
7471 continue;
7472 }
7473
c2d11a7d 7474 buf[bc] = '\0';
6d820c5c 7475 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 7476 return -1;
c2c6d25f 7477 }
c906108c 7478 default:
6d820c5c 7479 if (bc >= *sizeof_buf - 1)
c906108c 7480 {
6d820c5c
DJ
7481 /* Make some more room in the buffer. */
7482 *sizeof_buf *= 2;
7483 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7484 buf = *buf_p;
c906108c
SS
7485 }
7486
6d820c5c
DJ
7487 buf[bc++] = c;
7488 csum += c;
7489 continue;
c906108c
SS
7490 }
7491 }
7492}
7493
7494/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
7495 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7496 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7497 rather than timing out; this is used (in synchronous mode) to wait
7498 for a target that is is executing user code to stop. */
d9fcf2fb
JM
7499/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7500 don't have to change all the calls to getpkt to deal with the
7501 return value, because at the moment I don't know what the right
23860348 7502 thing to do it for those. */
c906108c 7503void
6d820c5c
DJ
7504getpkt (char **buf,
7505 long *sizeof_buf,
c2d11a7d 7506 int forever)
d9fcf2fb
JM
7507{
7508 int timed_out;
7509
7510 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7511}
7512
7513
7514/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
7515 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7516 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7517 rather than timing out; this is used (in synchronous mode) to wait
7518 for a target that is is executing user code to stop. If FOREVER ==
7519 0, this function is allowed to time out gracefully and return an
74531fed
PA
7520 indication of this to the caller. Otherwise return the number of
7521 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
7522 enough reason to return to the caller. *IS_NOTIF is an output
7523 boolean that indicates whether *BUF holds a notification or not
7524 (a regular packet). */
74531fed 7525
3172dc30 7526static int
74531fed 7527getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 7528 int expecting_notif, int *is_notif)
c906108c 7529{
2d717e4f 7530 struct remote_state *rs = get_remote_state ();
c906108c
SS
7531 int c;
7532 int tries;
7533 int timeout;
df4b58fe 7534 int val = -1;
c906108c 7535
2d717e4f
DJ
7536 /* We're reading a new response. Make sure we don't look at a
7537 previously cached response. */
7538 rs->cached_wait_status = 0;
7539
6d820c5c 7540 strcpy (*buf, "timeout");
c906108c
SS
7541
7542 if (forever)
74531fed
PA
7543 timeout = watchdog > 0 ? watchdog : -1;
7544 else if (expecting_notif)
7545 timeout = 0; /* There should already be a char in the buffer. If
7546 not, bail out. */
c906108c
SS
7547 else
7548 timeout = remote_timeout;
7549
7550#define MAX_TRIES 3
7551
74531fed
PA
7552 /* Process any number of notifications, and then return when
7553 we get a packet. */
7554 for (;;)
c906108c 7555 {
74531fed
PA
7556 /* If we get a timeout or bad checksm, retry up to MAX_TRIES
7557 times. */
7558 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 7559 {
74531fed
PA
7560 /* This can loop forever if the remote side sends us
7561 characters continuously, but if it pauses, we'll get
7562 SERIAL_TIMEOUT from readchar because of timeout. Then
7563 we'll count that as a retry.
7564
7565 Note that even when forever is set, we will only wait
7566 forever prior to the start of a packet. After that, we
7567 expect characters to arrive at a brisk pace. They should
7568 show up within remote_timeout intervals. */
7569 do
7570 c = readchar (timeout);
7571 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
7572
7573 if (c == SERIAL_TIMEOUT)
7574 {
74531fed
PA
7575 if (expecting_notif)
7576 return -1; /* Don't complain, it's normal to not get
7577 anything in this case. */
7578
23860348 7579 if (forever) /* Watchdog went off? Kill the target. */
c906108c 7580 {
2acceee2 7581 QUIT;
ce5ce7ed 7582 pop_target ();
489eaeba 7583 error (_("Watchdog timeout has expired. Target detached."));
c906108c 7584 }
c906108c 7585 if (remote_debug)
0f71a2f6 7586 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 7587 }
74531fed
PA
7588 else
7589 {
7590 /* We've found the start of a packet or notification.
7591 Now collect the data. */
7592 val = read_frame (buf, sizeof_buf);
7593 if (val >= 0)
7594 break;
7595 }
7596
7597 serial_write (remote_desc, "-", 1);
c906108c 7598 }
c906108c 7599
74531fed
PA
7600 if (tries > MAX_TRIES)
7601 {
7602 /* We have tried hard enough, and just can't receive the
7603 packet/notification. Give up. */
7604 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 7605
74531fed
PA
7606 /* Skip the ack char if we're in no-ack mode. */
7607 if (!rs->noack_mode)
7608 serial_write (remote_desc, "+", 1);
7609 return -1;
7610 }
c906108c 7611
74531fed
PA
7612 /* If we got an ordinary packet, return that to our caller. */
7613 if (c == '$')
c906108c
SS
7614 {
7615 if (remote_debug)
43e526b9 7616 {
6e5abd65
PA
7617 struct cleanup *old_chain;
7618 char *str;
7619
7620 str = escape_buffer (*buf, val);
7621 old_chain = make_cleanup (xfree, str);
7622 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7623 do_cleanups (old_chain);
43e526b9 7624 }
a6f3e723
SL
7625
7626 /* Skip the ack char if we're in no-ack mode. */
7627 if (!rs->noack_mode)
7628 serial_write (remote_desc, "+", 1);
fee9eda9
YQ
7629 if (is_notif != NULL)
7630 *is_notif = 0;
0876f84a 7631 return val;
c906108c
SS
7632 }
7633
74531fed
PA
7634 /* If we got a notification, handle it, and go back to looking
7635 for a packet. */
7636 else
7637 {
7638 gdb_assert (c == '%');
7639
7640 if (remote_debug)
7641 {
6e5abd65
PA
7642 struct cleanup *old_chain;
7643 char *str;
7644
7645 str = escape_buffer (*buf, val);
7646 old_chain = make_cleanup (xfree, str);
7647 fprintf_unfiltered (gdb_stdlog,
7648 " Notification received: %s\n",
7649 str);
7650 do_cleanups (old_chain);
74531fed 7651 }
fee9eda9
YQ
7652 if (is_notif != NULL)
7653 *is_notif = 1;
c906108c 7654
8128fd8e 7655 handle_notification (*buf);
c906108c 7656
74531fed 7657 /* Notifications require no acknowledgement. */
a6f3e723 7658
74531fed 7659 if (expecting_notif)
fee9eda9 7660 return val;
74531fed
PA
7661 }
7662 }
7663}
7664
7665static int
7666getpkt_sane (char **buf, long *sizeof_buf, int forever)
7667{
fee9eda9 7668 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
7669}
7670
7671static int
fee9eda9
YQ
7672getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
7673 int *is_notif)
74531fed 7674{
fee9eda9
YQ
7675 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
7676 is_notif);
c906108c 7677}
74531fed 7678
c906108c 7679\f
732f3f12
TT
7680/* A helper function that just calls putpkt; for type correctness. */
7681
7682static int
7683putpkt_for_catch_errors (void *arg)
7684{
7685 return putpkt (arg);
7686}
7687
c906108c 7688static void
7d85a9c0 7689remote_kill (struct target_ops *ops)
43ff13b4 7690{
23860348
MS
7691 /* Use catch_errors so the user can quit from gdb even when we
7692 aren't on speaking terms with the remote system. */
732f3f12 7693 catch_errors (putpkt_for_catch_errors, "k", "", RETURN_MASK_ERROR);
43ff13b4
JM
7694
7695 /* Don't wait for it to die. I'm not really sure it matters whether
7696 we do or not. For the existing stubs, kill is a noop. */
7697 target_mourn_inferior ();
7698}
7699
82f73884
PA
7700static int
7701remote_vkill (int pid, struct remote_state *rs)
7702{
7703 if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7704 return -1;
7705
7706 /* Tell the remote target to detach. */
bba74b36 7707 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
7708 putpkt (rs->buf);
7709 getpkt (&rs->buf, &rs->buf_size, 0);
7710
7711 if (packet_ok (rs->buf,
7712 &remote_protocol_packets[PACKET_vKill]) == PACKET_OK)
7713 return 0;
7714 else if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7715 return -1;
7716 else
7717 return 1;
7718}
7719
7720static void
7d85a9c0 7721extended_remote_kill (struct target_ops *ops)
82f73884
PA
7722{
7723 int res;
7724 int pid = ptid_get_pid (inferior_ptid);
7725 struct remote_state *rs = get_remote_state ();
7726
7727 res = remote_vkill (pid, rs);
901f9912 7728 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
82f73884
PA
7729 {
7730 /* Don't try 'k' on a multi-process aware stub -- it has no way
7731 to specify the pid. */
7732
7733 putpkt ("k");
7734#if 0
7735 getpkt (&rs->buf, &rs->buf_size, 0);
7736 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7737 res = 1;
7738#else
7739 /* Don't wait for it to die. I'm not really sure it matters whether
7740 we do or not. For the existing stubs, kill is a noop. */
7741 res = 0;
7742#endif
7743 }
7744
7745 if (res != 0)
7746 error (_("Can't kill process"));
7747
82f73884
PA
7748 target_mourn_inferior ();
7749}
7750
c906108c 7751static void
136d6dae 7752remote_mourn (struct target_ops *ops)
c906108c 7753{
136d6dae 7754 remote_mourn_1 (ops);
c906108c
SS
7755}
7756
c906108c
SS
7757/* Worker function for remote_mourn. */
7758static void
fba45db2 7759remote_mourn_1 (struct target_ops *target)
c906108c
SS
7760{
7761 unpush_target (target);
ce5ce7ed 7762
8a2492ee
PA
7763 /* remote_close takes care of doing most of the clean up. */
7764 generic_mourn_inferior ();
c906108c
SS
7765}
7766
2d717e4f
DJ
7767static void
7768extended_remote_mourn_1 (struct target_ops *target)
7769{
7770 struct remote_state *rs = get_remote_state ();
c906108c 7771
e24a49d8
PA
7772 /* In case we got here due to an error, but we're going to stay
7773 connected. */
7774 rs->waiting_for_stop_reply = 0;
7775
dc1981d7
PA
7776 /* If the current general thread belonged to the process we just
7777 detached from or has exited, the remote side current general
7778 thread becomes undefined. Considering a case like this:
7779
7780 - We just got here due to a detach.
7781 - The process that we're detaching from happens to immediately
7782 report a global breakpoint being hit in non-stop mode, in the
7783 same thread we had selected before.
7784 - GDB attaches to this process again.
7785 - This event happens to be the next event we handle.
7786
7787 GDB would consider that the current general thread didn't need to
7788 be set on the stub side (with Hg), since for all it knew,
7789 GENERAL_THREAD hadn't changed.
7790
7791 Notice that although in all-stop mode, the remote server always
7792 sets the current thread to the thread reporting the stop event,
7793 that doesn't happen in non-stop mode; in non-stop, the stub *must
7794 not* change the current thread when reporting a breakpoint hit,
7795 due to the decoupling of event reporting and event handling.
7796
7797 To keep things simple, we always invalidate our notion of the
7798 current thread. */
7799 record_currthread (minus_one_ptid);
7800
2d717e4f
DJ
7801 /* Unlike "target remote", we do not want to unpush the target; then
7802 the next time the user says "run", we won't be connected. */
7803
48aa3c27
PA
7804 /* Call common code to mark the inferior as not running. */
7805 generic_mourn_inferior ();
7806
d729566a 7807 if (!have_inferiors ())
2d717e4f 7808 {
82f73884
PA
7809 if (!remote_multi_process_p (rs))
7810 {
7811 /* Check whether the target is running now - some remote stubs
7812 automatically restart after kill. */
7813 putpkt ("?");
7814 getpkt (&rs->buf, &rs->buf_size, 0);
7815
7816 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7817 {
3e43a32a
MS
7818 /* Assume that the target has been restarted. Set
7819 inferior_ptid so that bits of core GDB realizes
7820 there's something here, e.g., so that the user can
7821 say "kill" again. */
82f73884
PA
7822 inferior_ptid = magic_null_ptid;
7823 }
82f73884 7824 }
2d717e4f
DJ
7825 }
7826}
c906108c
SS
7827
7828static void
136d6dae 7829extended_remote_mourn (struct target_ops *ops)
c906108c 7830{
136d6dae 7831 extended_remote_mourn_1 (ops);
2d717e4f 7832}
c906108c 7833
03583c20
UW
7834static int
7835extended_remote_supports_disable_randomization (void)
7836{
7837 return (remote_protocol_packets[PACKET_QDisableRandomization].support
7838 == PACKET_ENABLE);
7839}
7840
7841static void
7842extended_remote_disable_randomization (int val)
7843{
7844 struct remote_state *rs = get_remote_state ();
7845 char *reply;
7846
bba74b36
YQ
7847 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
7848 val);
03583c20
UW
7849 putpkt (rs->buf);
7850 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
7851 if (*reply == '\0')
7852 error (_("Target does not support QDisableRandomization."));
7853 if (strcmp (reply, "OK") != 0)
7854 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
7855}
7856
2d717e4f
DJ
7857static int
7858extended_remote_run (char *args)
7859{
7860 struct remote_state *rs = get_remote_state ();
2d717e4f 7861 int len;
c906108c 7862
2d717e4f
DJ
7863 /* If the user has disabled vRun support, or we have detected that
7864 support is not available, do not try it. */
7865 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7866 return -1;
424163ea 7867
2d717e4f
DJ
7868 strcpy (rs->buf, "vRun;");
7869 len = strlen (rs->buf);
c906108c 7870
2d717e4f
DJ
7871 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
7872 error (_("Remote file name too long for run packet"));
7873 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
7874
d1a41061 7875 gdb_assert (args != NULL);
2d717e4f
DJ
7876 if (*args)
7877 {
7878 struct cleanup *back_to;
7879 int i;
7880 char **argv;
7881
d1a41061 7882 argv = gdb_buildargv (args);
2d717e4f
DJ
7883 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
7884 for (i = 0; argv[i] != NULL; i++)
7885 {
7886 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
7887 error (_("Argument list too long for run packet"));
7888 rs->buf[len++] = ';';
7889 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
7890 }
7891 do_cleanups (back_to);
7892 }
7893
7894 rs->buf[len++] = '\0';
7895
7896 putpkt (rs->buf);
7897 getpkt (&rs->buf, &rs->buf_size, 0);
7898
7899 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
7900 {
3405876a 7901 /* We have a wait response. All is well. */
2d717e4f
DJ
7902 return 0;
7903 }
7904 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7905 /* It wasn't disabled before, but it is now. */
7906 return -1;
7907 else
7908 {
7909 if (remote_exec_file[0] == '\0')
7910 error (_("Running the default executable on the remote target failed; "
7911 "try \"set remote exec-file\"?"));
7912 else
7913 error (_("Running \"%s\" on the remote target failed"),
7914 remote_exec_file);
7915 }
c906108c
SS
7916}
7917
2d717e4f
DJ
7918/* In the extended protocol we want to be able to do things like
7919 "run" and have them basically work as expected. So we need
7920 a special create_inferior function. We support changing the
7921 executable file and the command line arguments, but not the
7922 environment. */
7923
43ff13b4 7924static void
2d717e4f 7925extended_remote_create_inferior_1 (char *exec_file, char *args,
75c99385 7926 char **env, int from_tty)
43ff13b4 7927{
3405876a
PA
7928 int run_worked;
7929 char *stop_reply;
7930 struct remote_state *rs = get_remote_state ();
7931
43ff13b4 7932 /* If running asynchronously, register the target file descriptor
23860348 7933 with the event loop. */
75c99385 7934 if (target_can_async_p ())
2acceee2 7935 target_async (inferior_event_handler, 0);
43ff13b4 7936
03583c20
UW
7937 /* Disable address space randomization if requested (and supported). */
7938 if (extended_remote_supports_disable_randomization ())
7939 extended_remote_disable_randomization (disable_randomization);
7940
43ff13b4 7941 /* Now restart the remote server. */
3405876a
PA
7942 run_worked = extended_remote_run (args) != -1;
7943 if (!run_worked)
2d717e4f
DJ
7944 {
7945 /* vRun was not supported. Fail if we need it to do what the
7946 user requested. */
7947 if (remote_exec_file[0])
7948 error (_("Remote target does not support \"set remote exec-file\""));
7949 if (args[0])
7950 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 7951
2d717e4f
DJ
7952 /* Fall back to "R". */
7953 extended_remote_restart ();
7954 }
424163ea 7955
6c95b8df
PA
7956 if (!have_inferiors ())
7957 {
7958 /* Clean up from the last time we ran, before we mark the target
7959 running again. This will mark breakpoints uninserted, and
7960 get_offsets may insert breakpoints. */
7961 init_thread_list ();
7962 init_wait_for_inferior ();
7963 }
45280a52 7964
3405876a
PA
7965 /* vRun's success return is a stop reply. */
7966 stop_reply = run_worked ? rs->buf : NULL;
7967 add_current_inferior_and_thread (stop_reply);
c0a2216e 7968
2d717e4f
DJ
7969 /* Get updated offsets, if the stub uses qOffsets. */
7970 get_offsets ();
2d717e4f
DJ
7971}
7972
7973static void
136d6dae
VP
7974extended_remote_create_inferior (struct target_ops *ops,
7975 char *exec_file, char *args,
2d717e4f
DJ
7976 char **env, int from_tty)
7977{
75c99385 7978 extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
43ff13b4 7979}
c906108c 7980\f
c5aa993b 7981
b775012e
LM
7982/* Given a location's target info BP_TGT and the packet buffer BUF, output
7983 the list of conditions (in agent expression bytecode format), if any, the
7984 target needs to evaluate. The output is placed into the packet buffer
bba74b36 7985 started from BUF and ended at BUF_END. */
b775012e
LM
7986
7987static int
7988remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
7989 struct bp_target_info *bp_tgt, char *buf,
7990 char *buf_end)
b775012e
LM
7991{
7992 struct agent_expr *aexpr = NULL;
7993 int i, ix;
7994 char *pkt;
7995 char *buf_start = buf;
7996
7997 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
7998 return 0;
7999
8000 buf += strlen (buf);
bba74b36 8001 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
8002 buf++;
8003
8004 /* Send conditions to the target and free the vector. */
8005 for (ix = 0;
8006 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8007 ix++)
8008 {
bba74b36 8009 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
8010 buf += strlen (buf);
8011 for (i = 0; i < aexpr->len; ++i)
8012 buf = pack_hex_byte (buf, aexpr->buf[i]);
8013 *buf = '\0';
8014 }
8015
8016 VEC_free (agent_expr_p, bp_tgt->conditions);
8017 return 0;
8018}
8019
d3ce09f5
SS
8020static void
8021remote_add_target_side_commands (struct gdbarch *gdbarch,
8022 struct bp_target_info *bp_tgt, char *buf)
8023{
8024 struct agent_expr *aexpr = NULL;
8025 int i, ix;
8026
8027 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8028 return;
8029
8030 buf += strlen (buf);
8031
8032 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8033 buf += strlen (buf);
8034
8035 /* Concatenate all the agent expressions that are commands into the
8036 cmds parameter. */
8037 for (ix = 0;
8038 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8039 ix++)
8040 {
8041 sprintf (buf, "X%x,", aexpr->len);
8042 buf += strlen (buf);
8043 for (i = 0; i < aexpr->len; ++i)
8044 buf = pack_hex_byte (buf, aexpr->buf[i]);
8045 *buf = '\0';
8046 }
8047
8048 VEC_free (agent_expr_p, bp_tgt->tcommands);
8049}
8050
8181d85f
DJ
8051/* Insert a breakpoint. On targets that have software breakpoint
8052 support, we ask the remote target to do the work; on targets
8053 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
8054
8055static int
a6d9a66e
UW
8056remote_insert_breakpoint (struct gdbarch *gdbarch,
8057 struct bp_target_info *bp_tgt)
c906108c 8058{
d471ea57
AC
8059 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8060 If it succeeds, then set the support to PACKET_ENABLE. If it
8061 fails, and the user has explicitly requested the Z support then
23860348 8062 report an error, otherwise, mark it disabled and go on. */
802188a7 8063
444abaca 8064 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
96baa820 8065 {
7c0f6dcc 8066 CORE_ADDR addr = bp_tgt->placed_address;
4fff2411 8067 struct remote_state *rs;
bba74b36 8068 char *p, *endbuf;
7c0f6dcc 8069 int bpsize;
b775012e 8070 struct condition_list *cond = NULL;
4fff2411 8071
a1dcb23a 8072 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
8073
8074 rs = get_remote_state ();
8075 p = rs->buf;
bba74b36 8076 endbuf = rs->buf + get_remote_packet_size ();
802188a7 8077
96baa820
JM
8078 *(p++) = 'Z';
8079 *(p++) = '0';
8080 *(p++) = ',';
7c0f6dcc 8081 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 8082 p += hexnumstr (p, addr);
bba74b36 8083 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 8084
b775012e 8085 if (remote_supports_cond_breakpoints ())
bba74b36 8086 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8087
d3ce09f5
SS
8088 if (remote_can_run_breakpoint_commands ())
8089 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8090
6d820c5c
DJ
8091 putpkt (rs->buf);
8092 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8093
6d820c5c 8094 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 8095 {
d471ea57
AC
8096 case PACKET_ERROR:
8097 return -1;
8098 case PACKET_OK:
7c0f6dcc
JL
8099 bp_tgt->placed_address = addr;
8100 bp_tgt->placed_size = bpsize;
d471ea57
AC
8101 return 0;
8102 case PACKET_UNKNOWN:
8103 break;
96baa820
JM
8104 }
8105 }
c906108c 8106
a6d9a66e 8107 return memory_insert_breakpoint (gdbarch, bp_tgt);
c906108c
SS
8108}
8109
8110static int
a6d9a66e
UW
8111remote_remove_breakpoint (struct gdbarch *gdbarch,
8112 struct bp_target_info *bp_tgt)
c906108c 8113{
8181d85f 8114 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 8115 struct remote_state *rs = get_remote_state ();
96baa820 8116
444abaca 8117 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
96baa820 8118 {
6d820c5c 8119 char *p = rs->buf;
bba74b36 8120 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 8121
96baa820
JM
8122 *(p++) = 'z';
8123 *(p++) = '0';
8124 *(p++) = ',';
8125
8181d85f
DJ
8126 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8127 p += hexnumstr (p, addr);
bba74b36 8128 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 8129
6d820c5c
DJ
8130 putpkt (rs->buf);
8131 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8132
6d820c5c 8133 return (rs->buf[0] == 'E');
96baa820
JM
8134 }
8135
a6d9a66e 8136 return memory_remove_breakpoint (gdbarch, bp_tgt);
c906108c
SS
8137}
8138
d471ea57
AC
8139static int
8140watchpoint_to_Z_packet (int type)
8141{
8142 switch (type)
8143 {
8144 case hw_write:
bb858e6a 8145 return Z_PACKET_WRITE_WP;
d471ea57
AC
8146 break;
8147 case hw_read:
bb858e6a 8148 return Z_PACKET_READ_WP;
d471ea57
AC
8149 break;
8150 case hw_access:
bb858e6a 8151 return Z_PACKET_ACCESS_WP;
d471ea57
AC
8152 break;
8153 default:
8e65ff28 8154 internal_error (__FILE__, __LINE__,
e2e0b3e5 8155 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
8156 }
8157}
8158
3c3bea1c 8159static int
0cf6dd15
TJB
8160remote_insert_watchpoint (CORE_ADDR addr, int len, int type,
8161 struct expression *cond)
96baa820 8162{
d01949b6 8163 struct remote_state *rs = get_remote_state ();
bba74b36 8164 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8165 char *p;
d471ea57 8166 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 8167
444abaca 8168 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
85d721b8 8169 return 1;
802188a7 8170
bba74b36 8171 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 8172 p = strchr (rs->buf, '\0');
96baa820
JM
8173 addr = remote_address_masked (addr);
8174 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8175 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 8176
6d820c5c
DJ
8177 putpkt (rs->buf);
8178 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8179
6d820c5c 8180 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8181 {
8182 case PACKET_ERROR:
d471ea57 8183 return -1;
85d721b8
PA
8184 case PACKET_UNKNOWN:
8185 return 1;
d471ea57
AC
8186 case PACKET_OK:
8187 return 0;
8188 }
8e65ff28 8189 internal_error (__FILE__, __LINE__,
e2e0b3e5 8190 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
8191}
8192
283002cf
MR
8193static int
8194remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8195 CORE_ADDR start, int length)
8196{
8197 CORE_ADDR diff = remote_address_masked (addr - start);
8198
8199 return diff < length;
8200}
8201
d471ea57 8202
3c3bea1c 8203static int
0cf6dd15
TJB
8204remote_remove_watchpoint (CORE_ADDR addr, int len, int type,
8205 struct expression *cond)
96baa820 8206{
d01949b6 8207 struct remote_state *rs = get_remote_state ();
bba74b36 8208 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8209 char *p;
d471ea57
AC
8210 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8211
444abaca 8212 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
5cffb350 8213 return -1;
802188a7 8214
bba74b36 8215 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 8216 p = strchr (rs->buf, '\0');
96baa820
JM
8217 addr = remote_address_masked (addr);
8218 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8219 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
8220 putpkt (rs->buf);
8221 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8222
6d820c5c 8223 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8224 {
8225 case PACKET_ERROR:
8226 case PACKET_UNKNOWN:
8227 return -1;
8228 case PACKET_OK:
8229 return 0;
8230 }
8e65ff28 8231 internal_error (__FILE__, __LINE__,
e2e0b3e5 8232 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
8233}
8234
3c3bea1c 8235
501eef12 8236int remote_hw_watchpoint_limit = -1;
480a3f21 8237int remote_hw_watchpoint_length_limit = -1;
501eef12 8238int remote_hw_breakpoint_limit = -1;
d471ea57 8239
480a3f21
PW
8240static int
8241remote_region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
8242{
8243 if (remote_hw_watchpoint_length_limit == 0)
8244 return 0;
8245 else if (remote_hw_watchpoint_length_limit < 0)
8246 return 1;
8247 else if (len <= remote_hw_watchpoint_length_limit)
8248 return 1;
8249 else
8250 return 0;
8251}
8252
b9362cc7 8253static int
3c3bea1c 8254remote_check_watch_resources (int type, int cnt, int ot)
96baa820 8255{
3c3bea1c
GS
8256 if (type == bp_hardware_breakpoint)
8257 {
8258 if (remote_hw_breakpoint_limit == 0)
8259 return 0;
501eef12
AC
8260 else if (remote_hw_breakpoint_limit < 0)
8261 return 1;
3c3bea1c
GS
8262 else if (cnt <= remote_hw_breakpoint_limit)
8263 return 1;
8264 }
8265 else
8266 {
8267 if (remote_hw_watchpoint_limit == 0)
8268 return 0;
501eef12
AC
8269 else if (remote_hw_watchpoint_limit < 0)
8270 return 1;
3c3bea1c
GS
8271 else if (ot)
8272 return -1;
8273 else if (cnt <= remote_hw_watchpoint_limit)
8274 return 1;
8275 }
8276 return -1;
8277}
8278
b9362cc7 8279static int
3c3bea1c
GS
8280remote_stopped_by_watchpoint (void)
8281{
82f73884 8282 return remote_stopped_by_watchpoint_p;
3c3bea1c
GS
8283}
8284
4aa7a7f5
JJ
8285static int
8286remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 8287{
4aa7a7f5 8288 int rc = 0;
a744cf53 8289
d983da9c 8290 if (remote_stopped_by_watchpoint ())
4aa7a7f5
JJ
8291 {
8292 *addr_p = remote_watch_data_address;
8293 rc = 1;
8294 }
8295
8296 return rc;
3c3bea1c
GS
8297}
8298
8299
8300static int
a6d9a66e
UW
8301remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
8302 struct bp_target_info *bp_tgt)
3c3bea1c 8303{
8181d85f 8304 CORE_ADDR addr;
4fff2411 8305 struct remote_state *rs;
bba74b36 8306 char *p, *endbuf;
dd61ec5c 8307 char *message;
802188a7 8308
c8189ed1 8309 /* The length field should be set to the size of a breakpoint
8181d85f 8310 instruction, even though we aren't inserting one ourselves. */
c8189ed1 8311
a1dcb23a 8312 gdbarch_remote_breakpoint_from_pc
a6d9a66e 8313 (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
3c3bea1c 8314
444abaca 8315 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5cffb350 8316 return -1;
2bc416ba 8317
4fff2411
JZ
8318 rs = get_remote_state ();
8319 p = rs->buf;
bba74b36 8320 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 8321
96baa820
JM
8322 *(p++) = 'Z';
8323 *(p++) = '1';
8324 *(p++) = ',';
802188a7 8325
8181d85f 8326 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 8327 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8328 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 8329
b775012e 8330 if (remote_supports_cond_breakpoints ())
bba74b36 8331 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8332
d3ce09f5
SS
8333 if (remote_can_run_breakpoint_commands ())
8334 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8335
6d820c5c
DJ
8336 putpkt (rs->buf);
8337 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8338
6d820c5c 8339 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
8340 {
8341 case PACKET_ERROR:
dd61ec5c
MW
8342 if (rs->buf[1] == '.')
8343 {
8344 message = strchr (rs->buf + 2, '.');
8345 if (message)
0316657e 8346 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
8347 }
8348 return -1;
d471ea57
AC
8349 case PACKET_UNKNOWN:
8350 return -1;
8351 case PACKET_OK:
8352 return 0;
8353 }
8e65ff28 8354 internal_error (__FILE__, __LINE__,
e2e0b3e5 8355 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
8356}
8357
d471ea57 8358
802188a7 8359static int
a6d9a66e
UW
8360remote_remove_hw_breakpoint (struct gdbarch *gdbarch,
8361 struct bp_target_info *bp_tgt)
96baa820 8362{
8181d85f 8363 CORE_ADDR addr;
d01949b6 8364 struct remote_state *rs = get_remote_state ();
6d820c5c 8365 char *p = rs->buf;
bba74b36 8366 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 8367
444abaca 8368 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5cffb350 8369 return -1;
802188a7 8370
96baa820
JM
8371 *(p++) = 'z';
8372 *(p++) = '1';
8373 *(p++) = ',';
802188a7 8374
8181d85f 8375 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 8376 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8377 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 8378
6d820c5c
DJ
8379 putpkt (rs->buf);
8380 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 8381
6d820c5c 8382 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
8383 {
8384 case PACKET_ERROR:
8385 case PACKET_UNKNOWN:
8386 return -1;
8387 case PACKET_OK:
8388 return 0;
8389 }
8e65ff28 8390 internal_error (__FILE__, __LINE__,
e2e0b3e5 8391 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 8392}
96baa820 8393
23860348 8394/* Table used by the crc32 function to calcuate the checksum. */
c906108c 8395
c5aa993b
JM
8396static unsigned long crc32_table[256] =
8397{0, 0};
c906108c
SS
8398
8399static unsigned long
4a5e7a5b 8400crc32 (const unsigned char *buf, int len, unsigned int crc)
c906108c 8401{
c5aa993b 8402 if (!crc32_table[1])
c906108c 8403 {
23860348 8404 /* Initialize the CRC table and the decoding table. */
c906108c
SS
8405 int i, j;
8406 unsigned int c;
8407
8408 for (i = 0; i < 256; i++)
c5aa993b
JM
8409 {
8410 for (c = i << 24, j = 8; j > 0; --j)
8411 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
8412 crc32_table[i] = c;
8413 }
c906108c
SS
8414 }
8415
8416 while (len--)
8417 {
8418 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
8419 buf++;
8420 }
8421 return crc;
8422}
8423
4a5e7a5b
PA
8424/* Verify memory using the "qCRC:" request. */
8425
8426static int
8427remote_verify_memory (struct target_ops *ops,
8428 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8429{
8430 struct remote_state *rs = get_remote_state ();
8431 unsigned long host_crc, target_crc;
8432 char *tmp;
8433
8434 /* FIXME: assumes lma can fit into long. */
8435 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8436 (long) lma, (long) size);
8437 putpkt (rs->buf);
8438
8439 /* Be clever; compute the host_crc before waiting for target
8440 reply. */
8441 host_crc = crc32 (data, size, 0xffffffff);
8442
8443 getpkt (&rs->buf, &rs->buf_size, 0);
8444 if (rs->buf[0] == 'E')
8445 return -1;
8446
8447 if (rs->buf[0] != 'C')
8448 error (_("remote target does not support this operation"));
8449
8450 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8451 target_crc = target_crc * 16 + fromhex (*tmp);
8452
8453 return (host_crc == target_crc);
8454}
8455
c906108c
SS
8456/* compare-sections command
8457
8458 With no arguments, compares each loadable section in the exec bfd
8459 with the same memory range on the target, and reports mismatches.
4a5e7a5b 8460 Useful for verifying the image on the target against the exec file. */
e514a9d6 8461
c906108c 8462static void
fba45db2 8463compare_sections_command (char *args, int from_tty)
c906108c
SS
8464{
8465 asection *s;
c906108c 8466 struct cleanup *old_chain;
085dd6e6 8467 char *sectdata;
ce359b09 8468 const char *sectname;
c906108c
SS
8469 bfd_size_type size;
8470 bfd_vma lma;
8471 int matched = 0;
8472 int mismatched = 0;
4a5e7a5b 8473 int res;
c906108c
SS
8474
8475 if (!exec_bfd)
8a3fe4f8 8476 error (_("command cannot be used without an exec file"));
c906108c 8477
c5aa993b 8478 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
8479 {
8480 if (!(s->flags & SEC_LOAD))
0df8b418 8481 continue; /* Skip non-loadable section. */
c906108c 8482
2c500098 8483 size = bfd_get_section_size (s);
c906108c 8484 if (size == 0)
0df8b418 8485 continue; /* Skip zero-length section. */
c906108c 8486
ce359b09 8487 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 8488 if (args && strcmp (args, sectname) != 0)
0df8b418 8489 continue; /* Not the section selected by user. */
c906108c 8490
0df8b418 8491 matched = 1; /* Do this section. */
c906108c 8492 lma = s->lma;
c906108c 8493
c906108c 8494 sectdata = xmalloc (size);
b8c9b27d 8495 old_chain = make_cleanup (xfree, sectdata);
c906108c 8496 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 8497
4a5e7a5b
PA
8498 res = target_verify_memory (sectdata, lma, size);
8499
8500 if (res == -1)
5af949e3 8501 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
8502 paddress (target_gdbarch (), lma),
8503 paddress (target_gdbarch (), lma + size));
c906108c 8504
5af949e3 8505 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
8506 paddress (target_gdbarch (), lma),
8507 paddress (target_gdbarch (), lma + size));
4a5e7a5b 8508 if (res)
c906108c
SS
8509 printf_filtered ("matched.\n");
8510 else
c5aa993b
JM
8511 {
8512 printf_filtered ("MIS-MATCHED!\n");
8513 mismatched++;
8514 }
c906108c
SS
8515
8516 do_cleanups (old_chain);
8517 }
8518 if (mismatched > 0)
8a3fe4f8
AC
8519 warning (_("One or more sections of the remote executable does not match\n\
8520the loaded file\n"));
c906108c 8521 if (args && !matched)
a3f17187 8522 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
8523}
8524
0e7f50da
UW
8525/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8526 into remote target. The number of bytes written to the remote
8527 target is returned, or -1 for error. */
8528
8529static LONGEST
8530remote_write_qxfer (struct target_ops *ops, const char *object_name,
8531 const char *annex, const gdb_byte *writebuf,
8532 ULONGEST offset, LONGEST len,
8533 struct packet_config *packet)
8534{
8535 int i, buf_len;
8536 ULONGEST n;
0e7f50da
UW
8537 struct remote_state *rs = get_remote_state ();
8538 int max_size = get_memory_write_packet_size ();
8539
8540 if (packet->support == PACKET_DISABLE)
8541 return -1;
8542
8543 /* Insert header. */
8544 i = snprintf (rs->buf, max_size,
8545 "qXfer:%s:write:%s:%s:",
8546 object_name, annex ? annex : "",
8547 phex_nz (offset, sizeof offset));
8548 max_size -= (i + 1);
8549
8550 /* Escape as much data as fits into rs->buf. */
8551 buf_len = remote_escape_output
8552 (writebuf, len, (rs->buf + i), &max_size, max_size);
8553
8554 if (putpkt_binary (rs->buf, i + buf_len) < 0
8555 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8556 || packet_ok (rs->buf, packet) != PACKET_OK)
8557 return -1;
8558
8559 unpack_varlen_hex (rs->buf, &n);
8560 return n;
8561}
8562
0876f84a
DJ
8563/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8564 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8565 number of bytes read is returned, or 0 for EOF, or -1 for error.
8566 The number of bytes read may be less than LEN without indicating an
8567 EOF. PACKET is checked and updated to indicate whether the remote
8568 target supports this object. */
8569
8570static LONGEST
8571remote_read_qxfer (struct target_ops *ops, const char *object_name,
8572 const char *annex,
8573 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
8574 struct packet_config *packet)
8575{
8576 static char *finished_object;
8577 static char *finished_annex;
8578 static ULONGEST finished_offset;
8579
8580 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
8581 LONGEST i, n, packet_len;
8582
8583 if (packet->support == PACKET_DISABLE)
8584 return -1;
8585
8586 /* Check whether we've cached an end-of-object packet that matches
8587 this request. */
8588 if (finished_object)
8589 {
8590 if (strcmp (object_name, finished_object) == 0
8591 && strcmp (annex ? annex : "", finished_annex) == 0
8592 && offset == finished_offset)
8593 return 0;
8594
8595 /* Otherwise, we're now reading something different. Discard
8596 the cache. */
8597 xfree (finished_object);
8598 xfree (finished_annex);
8599 finished_object = NULL;
8600 finished_annex = NULL;
8601 }
8602
8603 /* Request only enough to fit in a single packet. The actual data
8604 may not, since we don't know how much of it will need to be escaped;
8605 the target is free to respond with slightly less data. We subtract
8606 five to account for the response type and the protocol frame. */
8607 n = min (get_remote_packet_size () - 5, len);
8608 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8609 object_name, annex ? annex : "",
8610 phex_nz (offset, sizeof offset),
8611 phex_nz (n, sizeof n));
8612 i = putpkt (rs->buf);
8613 if (i < 0)
8614 return -1;
8615
8616 rs->buf[0] = '\0';
8617 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8618 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
8619 return -1;
8620
8621 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8622 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8623
8624 /* 'm' means there is (or at least might be) more data after this
8625 batch. That does not make sense unless there's at least one byte
8626 of data in this reply. */
8627 if (rs->buf[0] == 'm' && packet_len == 1)
8628 error (_("Remote qXfer reply contained no data."));
8629
8630 /* Got some data. */
8631 i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
8632
8633 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
8634 or possibly empty. If we have the final block of a non-empty
8635 object, record this fact to bypass a subsequent partial read. */
8636 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a
DJ
8637 {
8638 finished_object = xstrdup (object_name);
8639 finished_annex = xstrdup (annex ? annex : "");
8640 finished_offset = offset + i;
8641 }
8642
8643 return i;
8644}
8645
1e3ff5ad 8646static LONGEST
4b8a223f 8647remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5
MK
8648 const char *annex, gdb_byte *readbuf,
8649 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
c906108c 8650{
82f73884 8651 struct remote_state *rs;
c906108c 8652 int i;
6d820c5c 8653 char *p2;
1e3ff5ad 8654 char query_type;
c906108c 8655
e6e4e701 8656 set_remote_traceframe ();
82f73884
PA
8657 set_general_thread (inferior_ptid);
8658
8659 rs = get_remote_state ();
8660
b2182ed2 8661 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
8662 if (object == TARGET_OBJECT_MEMORY)
8663 {
8664 int xfered;
a744cf53 8665
21e3b9b9
DJ
8666 errno = 0;
8667
2d717e4f
DJ
8668 /* If the remote target is connected but not running, we should
8669 pass this request down to a lower stratum (e.g. the executable
8670 file). */
8671 if (!target_has_execution)
8672 return 0;
8673
21e3b9b9 8674 if (writebuf != NULL)
b2182ed2 8675 xfered = remote_write_bytes (offset, writebuf, len);
21e3b9b9 8676 else
b2182ed2 8677 xfered = remote_read_bytes (offset, readbuf, len);
21e3b9b9
DJ
8678
8679 if (xfered > 0)
8680 return xfered;
8681 else if (xfered == 0 && errno == 0)
8682 return 0;
8683 else
8684 return -1;
8685 }
8686
0df8b418 8687 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
8688 if (object == TARGET_OBJECT_SPU)
8689 {
8690 if (readbuf)
8691 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
8692 &remote_protocol_packets
8693 [PACKET_qXfer_spu_read]);
8694 else
8695 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
8696 &remote_protocol_packets
8697 [PACKET_qXfer_spu_write]);
8698 }
8699
4aa995e1
PA
8700 /* Handle extra signal info using qxfer packets. */
8701 if (object == TARGET_OBJECT_SIGNAL_INFO)
8702 {
8703 if (readbuf)
8704 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
8705 &remote_protocol_packets
8706 [PACKET_qXfer_siginfo_read]);
8707 else
3e43a32a
MS
8708 return remote_write_qxfer (ops, "siginfo", annex,
8709 writebuf, offset, len,
4aa995e1
PA
8710 &remote_protocol_packets
8711 [PACKET_qXfer_siginfo_write]);
8712 }
8713
0fb4aa4b
PA
8714 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8715 {
8716 if (readbuf)
3e43a32a
MS
8717 return remote_read_qxfer (ops, "statictrace", annex,
8718 readbuf, offset, len,
0fb4aa4b
PA
8719 &remote_protocol_packets
8720 [PACKET_qXfer_statictrace_read]);
8721 else
8722 return -1;
8723 }
8724
a76d924d
DJ
8725 /* Only handle flash writes. */
8726 if (writebuf != NULL)
8727 {
8728 LONGEST xfered;
8729
8730 switch (object)
8731 {
8732 case TARGET_OBJECT_FLASH:
8733 xfered = remote_flash_write (ops, offset, len, writebuf);
8734
8735 if (xfered > 0)
8736 return xfered;
8737 else if (xfered == 0 && errno == 0)
8738 return 0;
8739 else
8740 return -1;
8741
8742 default:
8743 return -1;
8744 }
8745 }
4b8a223f 8746
1e3ff5ad
AC
8747 /* Map pre-existing objects onto letters. DO NOT do this for new
8748 objects!!! Instead specify new query packets. */
8749 switch (object)
c906108c 8750 {
1e3ff5ad
AC
8751 case TARGET_OBJECT_AVR:
8752 query_type = 'R';
8753 break;
802188a7
RM
8754
8755 case TARGET_OBJECT_AUXV:
0876f84a
DJ
8756 gdb_assert (annex == NULL);
8757 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
8758 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 8759
23181151
DJ
8760 case TARGET_OBJECT_AVAILABLE_FEATURES:
8761 return remote_read_qxfer
8762 (ops, "features", annex, readbuf, offset, len,
8763 &remote_protocol_packets[PACKET_qXfer_features]);
8764
cfa9d6d9
DJ
8765 case TARGET_OBJECT_LIBRARIES:
8766 return remote_read_qxfer
8767 (ops, "libraries", annex, readbuf, offset, len,
8768 &remote_protocol_packets[PACKET_qXfer_libraries]);
8769
2268b414
JK
8770 case TARGET_OBJECT_LIBRARIES_SVR4:
8771 return remote_read_qxfer
8772 (ops, "libraries-svr4", annex, readbuf, offset, len,
8773 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
8774
fd79ecee
DJ
8775 case TARGET_OBJECT_MEMORY_MAP:
8776 gdb_assert (annex == NULL);
8777 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
8778 &remote_protocol_packets[PACKET_qXfer_memory_map]);
8779
07e059b5
VP
8780 case TARGET_OBJECT_OSDATA:
8781 /* Should only get here if we're connected. */
8782 gdb_assert (remote_desc);
8783 return remote_read_qxfer
8784 (ops, "osdata", annex, readbuf, offset, len,
8785 &remote_protocol_packets[PACKET_qXfer_osdata]);
8786
dc146f7c
VP
8787 case TARGET_OBJECT_THREADS:
8788 gdb_assert (annex == NULL);
8789 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
8790 &remote_protocol_packets[PACKET_qXfer_threads]);
8791
b3b9301e
PA
8792 case TARGET_OBJECT_TRACEFRAME_INFO:
8793 gdb_assert (annex == NULL);
8794 return remote_read_qxfer
8795 (ops, "traceframe-info", annex, readbuf, offset, len,
8796 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
8797
8798 case TARGET_OBJECT_FDPIC:
8799 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
8800 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
8801
8802 case TARGET_OBJECT_OPENVMS_UIB:
8803 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
8804 &remote_protocol_packets[PACKET_qXfer_uib]);
8805
9accd112
MM
8806 case TARGET_OBJECT_BTRACE:
8807 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
8808 &remote_protocol_packets[PACKET_qXfer_btrace]);
8809
1e3ff5ad 8810 default:
c906108c
SS
8811 return -1;
8812 }
8813
4b8a223f 8814 /* Note: a zero OFFSET and LEN can be used to query the minimum
1e3ff5ad 8815 buffer size. */
4b8a223f 8816 if (offset == 0 && len == 0)
ea9c271d 8817 return (get_remote_packet_size ());
0df8b418 8818 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 8819 large enough let the caller deal with it. */
ea9c271d 8820 if (len < get_remote_packet_size ())
1e3ff5ad 8821 return -1;
ea9c271d 8822 len = get_remote_packet_size ();
1e3ff5ad 8823
23860348 8824 /* Except for querying the minimum buffer size, target must be open. */
c5aa993b 8825 if (!remote_desc)
8a3fe4f8 8826 error (_("remote query is only available after target open"));
c906108c 8827
1e3ff5ad 8828 gdb_assert (annex != NULL);
4b8a223f 8829 gdb_assert (readbuf != NULL);
c906108c 8830
6d820c5c 8831 p2 = rs->buf;
c906108c
SS
8832 *p2++ = 'q';
8833 *p2++ = query_type;
8834
23860348
MS
8835 /* We used one buffer char for the remote protocol q command and
8836 another for the query type. As the remote protocol encapsulation
8837 uses 4 chars plus one extra in case we are debugging
8838 (remote_debug), we have PBUFZIZ - 7 left to pack the query
8839 string. */
c906108c 8840 i = 0;
ea9c271d 8841 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 8842 {
1e3ff5ad
AC
8843 /* Bad caller may have sent forbidden characters. */
8844 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
8845 *p2++ = annex[i];
c906108c
SS
8846 i++;
8847 }
1e3ff5ad
AC
8848 *p2 = '\0';
8849 gdb_assert (annex[i] == '\0');
c906108c 8850
6d820c5c 8851 i = putpkt (rs->buf);
c5aa993b
JM
8852 if (i < 0)
8853 return i;
c906108c 8854
6d820c5c
DJ
8855 getpkt (&rs->buf, &rs->buf_size, 0);
8856 strcpy ((char *) readbuf, rs->buf);
c906108c 8857
cfd77fa1 8858 return strlen ((char *) readbuf);
c906108c
SS
8859}
8860
08388c79
DE
8861static int
8862remote_search_memory (struct target_ops* ops,
8863 CORE_ADDR start_addr, ULONGEST search_space_len,
8864 const gdb_byte *pattern, ULONGEST pattern_len,
8865 CORE_ADDR *found_addrp)
8866{
f5656ead 8867 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
8868 struct remote_state *rs = get_remote_state ();
8869 int max_size = get_memory_write_packet_size ();
8870 struct packet_config *packet =
8871 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
8872 /* Number of packet bytes used to encode the pattern;
8873 this could be more than PATTERN_LEN due to escape characters. */
08388c79 8874 int escaped_pattern_len;
0df8b418 8875 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
8876 int used_pattern_len;
8877 int i;
8878 int found;
8879 ULONGEST found_addr;
8880
8881 /* Don't go to the target if we don't have to.
8882 This is done before checking packet->support to avoid the possibility that
8883 a success for this edge case means the facility works in general. */
8884 if (pattern_len > search_space_len)
8885 return 0;
8886 if (pattern_len == 0)
8887 {
8888 *found_addrp = start_addr;
8889 return 1;
8890 }
8891
8892 /* If we already know the packet isn't supported, fall back to the simple
8893 way of searching memory. */
8894
8895 if (packet->support == PACKET_DISABLE)
8896 {
8897 /* Target doesn't provided special support, fall back and use the
8898 standard support (copy memory and do the search here). */
8899 return simple_search_memory (ops, start_addr, search_space_len,
8900 pattern, pattern_len, found_addrp);
8901 }
8902
8903 /* Insert header. */
8904 i = snprintf (rs->buf, max_size,
8905 "qSearch:memory:%s;%s;",
5af949e3 8906 phex_nz (start_addr, addr_size),
08388c79
DE
8907 phex_nz (search_space_len, sizeof (search_space_len)));
8908 max_size -= (i + 1);
8909
8910 /* Escape as much data as fits into rs->buf. */
8911 escaped_pattern_len =
8912 remote_escape_output (pattern, pattern_len, (rs->buf + i),
8913 &used_pattern_len, max_size);
8914
8915 /* Bail if the pattern is too large. */
8916 if (used_pattern_len != pattern_len)
9b20d036 8917 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
8918
8919 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
8920 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8921 || packet_ok (rs->buf, packet) != PACKET_OK)
8922 {
8923 /* The request may not have worked because the command is not
8924 supported. If so, fall back to the simple way. */
8925 if (packet->support == PACKET_DISABLE)
8926 {
8927 return simple_search_memory (ops, start_addr, search_space_len,
8928 pattern, pattern_len, found_addrp);
8929 }
8930 return -1;
8931 }
8932
8933 if (rs->buf[0] == '0')
8934 found = 0;
8935 else if (rs->buf[0] == '1')
8936 {
8937 found = 1;
8938 if (rs->buf[1] != ',')
10e0fa18 8939 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
8940 unpack_varlen_hex (rs->buf + 2, &found_addr);
8941 *found_addrp = found_addr;
8942 }
8943 else
10e0fa18 8944 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
8945
8946 return found;
8947}
8948
96baa820
JM
8949static void
8950remote_rcmd (char *command,
d9fcf2fb 8951 struct ui_file *outbuf)
96baa820 8952{
d01949b6 8953 struct remote_state *rs = get_remote_state ();
2e9f7625 8954 char *p = rs->buf;
96baa820
JM
8955
8956 if (!remote_desc)
8a3fe4f8 8957 error (_("remote rcmd is only available after target open"));
96baa820 8958
23860348 8959 /* Send a NULL command across as an empty command. */
7be570e7
JM
8960 if (command == NULL)
8961 command = "";
8962
23860348 8963 /* The query prefix. */
2e9f7625
DJ
8964 strcpy (rs->buf, "qRcmd,");
8965 p = strchr (rs->buf, '\0');
96baa820 8966
3e43a32a
MS
8967 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
8968 > get_remote_packet_size ())
8a3fe4f8 8969 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 8970
23860348 8971 /* Encode the actual command. */
cfd77fa1 8972 bin2hex ((gdb_byte *) command, p, 0);
96baa820 8973
6d820c5c 8974 if (putpkt (rs->buf) < 0)
8a3fe4f8 8975 error (_("Communication problem with target."));
96baa820
JM
8976
8977 /* get/display the response */
8978 while (1)
8979 {
2e9f7625
DJ
8980 char *buf;
8981
00bf0b85 8982 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 8983 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 8984 rs->buf[0] = '\0';
5b37825d
PW
8985 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
8986 {
8987 /* Timeout. Continue to (try to) read responses.
8988 This is better than stopping with an error, assuming the stub
8989 is still executing the (long) monitor command.
8990 If needed, the user can interrupt gdb using C-c, obtaining
8991 an effect similar to stop on timeout. */
8992 continue;
8993 }
2e9f7625 8994 buf = rs->buf;
96baa820 8995 if (buf[0] == '\0')
8a3fe4f8 8996 error (_("Target does not support this command."));
96baa820
JM
8997 if (buf[0] == 'O' && buf[1] != 'K')
8998 {
23860348 8999 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
9000 continue;
9001 }
9002 if (strcmp (buf, "OK") == 0)
9003 break;
7be570e7
JM
9004 if (strlen (buf) == 3 && buf[0] == 'E'
9005 && isdigit (buf[1]) && isdigit (buf[2]))
9006 {
8a3fe4f8 9007 error (_("Protocol error with Rcmd"));
7be570e7 9008 }
96baa820
JM
9009 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9010 {
9011 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 9012
96baa820
JM
9013 fputc_unfiltered (c, outbuf);
9014 }
9015 break;
9016 }
9017}
9018
fd79ecee
DJ
9019static VEC(mem_region_s) *
9020remote_memory_map (struct target_ops *ops)
9021{
9022 VEC(mem_region_s) *result = NULL;
9023 char *text = target_read_stralloc (&current_target,
9024 TARGET_OBJECT_MEMORY_MAP, NULL);
9025
9026 if (text)
9027 {
9028 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 9029
fd79ecee
DJ
9030 result = parse_memory_map (text);
9031 do_cleanups (back_to);
9032 }
9033
9034 return result;
9035}
9036
c906108c 9037static void
fba45db2 9038packet_command (char *args, int from_tty)
c906108c 9039{
d01949b6 9040 struct remote_state *rs = get_remote_state ();
c906108c 9041
c5aa993b 9042 if (!remote_desc)
8a3fe4f8 9043 error (_("command can only be used with remote target"));
c906108c 9044
c5aa993b 9045 if (!args)
8a3fe4f8 9046 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
9047
9048 puts_filtered ("sending: ");
9049 print_packet (args);
9050 puts_filtered ("\n");
9051 putpkt (args);
9052
6d820c5c 9053 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 9054 puts_filtered ("received: ");
6d820c5c 9055 print_packet (rs->buf);
c906108c
SS
9056 puts_filtered ("\n");
9057}
9058
9059#if 0
23860348 9060/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 9061
a14ed312 9062static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 9063
a14ed312 9064static void threadset_test_cmd (char *cmd, int tty);
c906108c 9065
a14ed312 9066static void threadalive_test (char *cmd, int tty);
c906108c 9067
a14ed312 9068static void threadlist_test_cmd (char *cmd, int tty);
c906108c 9069
23860348 9070int get_and_display_threadinfo (threadref *ref);
c906108c 9071
a14ed312 9072static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 9073
23860348 9074static int thread_display_step (threadref *ref, void *context);
c906108c 9075
a14ed312 9076static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 9077
a14ed312 9078static void init_remote_threadtests (void);
c906108c 9079
23860348 9080#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
9081
9082static void
fba45db2 9083threadset_test_cmd (char *cmd, int tty)
c906108c
SS
9084{
9085 int sample_thread = SAMPLE_THREAD;
9086
a3f17187 9087 printf_filtered (_("Remote threadset test\n"));
79d7f229 9088 set_general_thread (sample_thread);
c906108c
SS
9089}
9090
9091
9092static void
fba45db2 9093threadalive_test (char *cmd, int tty)
c906108c
SS
9094{
9095 int sample_thread = SAMPLE_THREAD;
79d7f229
PA
9096 int pid = ptid_get_pid (inferior_ptid);
9097 ptid_t ptid = ptid_build (pid, 0, sample_thread);
c906108c 9098
79d7f229 9099 if (remote_thread_alive (ptid))
c906108c
SS
9100 printf_filtered ("PASS: Thread alive test\n");
9101 else
9102 printf_filtered ("FAIL: Thread alive test\n");
9103}
9104
23860348 9105void output_threadid (char *title, threadref *ref);
c906108c
SS
9106
9107void
fba45db2 9108output_threadid (char *title, threadref *ref)
c906108c
SS
9109{
9110 char hexid[20];
9111
23860348 9112 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
9113 hexid[16] = 0;
9114 printf_filtered ("%s %s\n", title, (&hexid[0]));
9115}
9116
9117static void
fba45db2 9118threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
9119{
9120 int startflag = 1;
9121 threadref nextthread;
9122 int done, result_count;
9123 threadref threadlist[3];
9124
9125 printf_filtered ("Remote Threadlist test\n");
9126 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9127 &result_count, &threadlist[0]))
9128 printf_filtered ("FAIL: threadlist test\n");
9129 else
9130 {
9131 threadref *scan = threadlist;
9132 threadref *limit = scan + result_count;
9133
9134 while (scan < limit)
9135 output_threadid (" thread ", scan++);
9136 }
9137}
9138
9139void
fba45db2 9140display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
9141{
9142 output_threadid ("Threadid: ", &info->threadid);
9143 printf_filtered ("Name: %s\n ", info->shortname);
9144 printf_filtered ("State: %s\n", info->display);
9145 printf_filtered ("other: %s\n\n", info->more_display);
9146}
9147
9148int
fba45db2 9149get_and_display_threadinfo (threadref *ref)
c906108c
SS
9150{
9151 int result;
9152 int set;
9153 struct gdb_ext_thread_info threadinfo;
9154
9155 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9156 | TAG_MOREDISPLAY | TAG_DISPLAY;
9157 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9158 display_thread_info (&threadinfo);
9159 return result;
9160}
9161
9162static void
fba45db2 9163threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
9164{
9165 int athread = SAMPLE_THREAD;
9166 threadref thread;
9167 int set;
9168
9169 int_to_threadref (&thread, athread);
9170 printf_filtered ("Remote Threadinfo test\n");
9171 if (!get_and_display_threadinfo (&thread))
9172 printf_filtered ("FAIL cannot get thread info\n");
9173}
9174
9175static int
fba45db2 9176thread_display_step (threadref *ref, void *context)
c906108c
SS
9177{
9178 /* output_threadid(" threadstep ",ref); *//* simple test */
9179 return get_and_display_threadinfo (ref);
9180}
9181
9182static void
fba45db2 9183threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
9184{
9185 printf_filtered ("Remote Threadlist update test\n");
9186 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9187}
9188
9189static void
9190init_remote_threadtests (void)
9191{
3e43a32a
MS
9192 add_com ("tlist", class_obscure, threadlist_test_cmd,
9193 _("Fetch and print the remote list of "
9194 "thread identifiers, one pkt only"));
c906108c 9195 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 9196 _("Fetch and display info about one thread"));
c906108c 9197 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 9198 _("Test setting to a different thread"));
c906108c 9199 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 9200 _("Iterate through updating all remote thread info"));
c906108c 9201 add_com ("talive", class_obscure, threadalive_test,
1bedd215 9202 _(" Remote thread alive test "));
c906108c
SS
9203}
9204
9205#endif /* 0 */
9206
f3fb8c85
MS
9207/* Convert a thread ID to a string. Returns the string in a static
9208 buffer. */
9209
9210static char *
117de6a9 9211remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 9212{
79d7f229 9213 static char buf[64];
82f73884 9214 struct remote_state *rs = get_remote_state ();
f3fb8c85 9215
7cee1e54
PA
9216 if (ptid_equal (ptid, null_ptid))
9217 return normal_pid_to_str (ptid);
9218 else if (ptid_is_pid (ptid))
ecd0ada5
PA
9219 {
9220 /* Printing an inferior target id. */
9221
9222 /* When multi-process extensions are off, there's no way in the
9223 remote protocol to know the remote process id, if there's any
9224 at all. There's one exception --- when we're connected with
9225 target extended-remote, and we manually attached to a process
9226 with "attach PID". We don't record anywhere a flag that
9227 allows us to distinguish that case from the case of
9228 connecting with extended-remote and the stub already being
9229 attached to a process, and reporting yes to qAttached, hence
9230 no smart special casing here. */
9231 if (!remote_multi_process_p (rs))
9232 {
9233 xsnprintf (buf, sizeof buf, "Remote target");
9234 return buf;
9235 }
9236
9237 return normal_pid_to_str (ptid);
82f73884 9238 }
ecd0ada5 9239 else
79d7f229 9240 {
ecd0ada5
PA
9241 if (ptid_equal (magic_null_ptid, ptid))
9242 xsnprintf (buf, sizeof buf, "Thread <main>");
901f9912 9243 else if (rs->extended && remote_multi_process_p (rs))
ecd0ada5
PA
9244 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
9245 ptid_get_pid (ptid), ptid_get_tid (ptid));
9246 else
9247 xsnprintf (buf, sizeof buf, "Thread %ld",
9248 ptid_get_tid (ptid));
79d7f229
PA
9249 return buf;
9250 }
f3fb8c85
MS
9251}
9252
38691318
KB
9253/* Get the address of the thread local variable in OBJFILE which is
9254 stored at OFFSET within the thread local storage for thread PTID. */
9255
9256static CORE_ADDR
117de6a9
PA
9257remote_get_thread_local_address (struct target_ops *ops,
9258 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 9259{
444abaca 9260 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
38691318
KB
9261 {
9262 struct remote_state *rs = get_remote_state ();
6d820c5c 9263 char *p = rs->buf;
82f73884 9264 char *endp = rs->buf + get_remote_packet_size ();
571dd617 9265 enum packet_result result;
38691318
KB
9266
9267 strcpy (p, "qGetTLSAddr:");
9268 p += strlen (p);
82f73884 9269 p = write_ptid (p, endp, ptid);
38691318
KB
9270 *p++ = ',';
9271 p += hexnumstr (p, offset);
9272 *p++ = ',';
9273 p += hexnumstr (p, lm);
9274 *p++ = '\0';
9275
6d820c5c
DJ
9276 putpkt (rs->buf);
9277 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
9278 result = packet_ok (rs->buf,
9279 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 9280 if (result == PACKET_OK)
38691318
KB
9281 {
9282 ULONGEST result;
9283
6d820c5c 9284 unpack_varlen_hex (rs->buf, &result);
38691318
KB
9285 return result;
9286 }
571dd617 9287 else if (result == PACKET_UNKNOWN)
109c3e39
AC
9288 throw_error (TLS_GENERIC_ERROR,
9289 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 9290 else
109c3e39
AC
9291 throw_error (TLS_GENERIC_ERROR,
9292 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
9293 }
9294 else
109c3e39
AC
9295 throw_error (TLS_GENERIC_ERROR,
9296 _("TLS not supported or disabled on this target"));
38691318
KB
9297 /* Not reached. */
9298 return 0;
9299}
9300
711e434b
PM
9301/* Provide thread local base, i.e. Thread Information Block address.
9302 Returns 1 if ptid is found and thread_local_base is non zero. */
9303
70221824 9304static int
711e434b
PM
9305remote_get_tib_address (ptid_t ptid, CORE_ADDR *addr)
9306{
9307 if (remote_protocol_packets[PACKET_qGetTIBAddr].support != PACKET_DISABLE)
9308 {
9309 struct remote_state *rs = get_remote_state ();
9310 char *p = rs->buf;
9311 char *endp = rs->buf + get_remote_packet_size ();
9312 enum packet_result result;
9313
9314 strcpy (p, "qGetTIBAddr:");
9315 p += strlen (p);
9316 p = write_ptid (p, endp, ptid);
9317 *p++ = '\0';
9318
9319 putpkt (rs->buf);
9320 getpkt (&rs->buf, &rs->buf_size, 0);
9321 result = packet_ok (rs->buf,
9322 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9323 if (result == PACKET_OK)
9324 {
9325 ULONGEST result;
9326
9327 unpack_varlen_hex (rs->buf, &result);
9328 if (addr)
9329 *addr = (CORE_ADDR) result;
9330 return 1;
9331 }
9332 else if (result == PACKET_UNKNOWN)
9333 error (_("Remote target doesn't support qGetTIBAddr packet"));
9334 else
9335 error (_("Remote target failed to process qGetTIBAddr request"));
9336 }
9337 else
9338 error (_("qGetTIBAddr not supported or disabled on this target"));
9339 /* Not reached. */
9340 return 0;
9341}
9342
29709017
DJ
9343/* Support for inferring a target description based on the current
9344 architecture and the size of a 'g' packet. While the 'g' packet
9345 can have any size (since optional registers can be left off the
9346 end), some sizes are easily recognizable given knowledge of the
9347 approximate architecture. */
9348
9349struct remote_g_packet_guess
9350{
9351 int bytes;
9352 const struct target_desc *tdesc;
9353};
9354typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9355DEF_VEC_O(remote_g_packet_guess_s);
9356
9357struct remote_g_packet_data
9358{
9359 VEC(remote_g_packet_guess_s) *guesses;
9360};
9361
9362static struct gdbarch_data *remote_g_packet_data_handle;
9363
9364static void *
9365remote_g_packet_data_init (struct obstack *obstack)
9366{
9367 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9368}
9369
9370void
9371register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9372 const struct target_desc *tdesc)
9373{
9374 struct remote_g_packet_data *data
9375 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9376 struct remote_g_packet_guess new_guess, *guess;
9377 int ix;
9378
9379 gdb_assert (tdesc != NULL);
9380
9381 for (ix = 0;
9382 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9383 ix++)
9384 if (guess->bytes == bytes)
9385 internal_error (__FILE__, __LINE__,
9b20d036 9386 _("Duplicate g packet description added for size %d"),
29709017
DJ
9387 bytes);
9388
9389 new_guess.bytes = bytes;
9390 new_guess.tdesc = tdesc;
9391 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9392}
9393
d962ef82
DJ
9394/* Return 1 if remote_read_description would do anything on this target
9395 and architecture, 0 otherwise. */
9396
9397static int
9398remote_read_description_p (struct target_ops *target)
9399{
9400 struct remote_g_packet_data *data
f5656ead 9401 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
d962ef82
DJ
9402
9403 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9404 return 1;
9405
9406 return 0;
9407}
9408
29709017
DJ
9409static const struct target_desc *
9410remote_read_description (struct target_ops *target)
9411{
9412 struct remote_g_packet_data *data
f5656ead 9413 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
29709017 9414
d962ef82
DJ
9415 /* Do not try this during initial connection, when we do not know
9416 whether there is a running but stopped thread. */
9417 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
9418 return NULL;
9419
29709017
DJ
9420 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9421 {
9422 struct remote_g_packet_guess *guess;
9423 int ix;
9424 int bytes = send_g_packet ();
9425
9426 for (ix = 0;
9427 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9428 ix++)
9429 if (guess->bytes == bytes)
9430 return guess->tdesc;
9431
9432 /* We discard the g packet. A minor optimization would be to
9433 hold on to it, and fill the register cache once we have selected
9434 an architecture, but it's too tricky to do safely. */
9435 }
9436
9437 return NULL;
9438}
9439
a6b151f1
DJ
9440/* Remote file transfer support. This is host-initiated I/O, not
9441 target-initiated; for target-initiated, see remote-fileio.c. */
9442
9443/* If *LEFT is at least the length of STRING, copy STRING to
9444 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9445 decrease *LEFT. Otherwise raise an error. */
9446
9447static void
9448remote_buffer_add_string (char **buffer, int *left, char *string)
9449{
9450 int len = strlen (string);
9451
9452 if (len > *left)
9453 error (_("Packet too long for target."));
9454
9455 memcpy (*buffer, string, len);
9456 *buffer += len;
9457 *left -= len;
9458
9459 /* NUL-terminate the buffer as a convenience, if there is
9460 room. */
9461 if (*left)
9462 **buffer = '\0';
9463}
9464
9465/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9466 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9467 decrease *LEFT. Otherwise raise an error. */
9468
9469static void
9470remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9471 int len)
9472{
9473 if (2 * len > *left)
9474 error (_("Packet too long for target."));
9475
9476 bin2hex (bytes, *buffer, len);
9477 *buffer += 2 * len;
9478 *left -= 2 * len;
9479
9480 /* NUL-terminate the buffer as a convenience, if there is
9481 room. */
9482 if (*left)
9483 **buffer = '\0';
9484}
9485
9486/* If *LEFT is large enough, convert VALUE to hex and add it to
9487 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9488 decrease *LEFT. Otherwise raise an error. */
9489
9490static void
9491remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9492{
9493 int len = hexnumlen (value);
9494
9495 if (len > *left)
9496 error (_("Packet too long for target."));
9497
9498 hexnumstr (*buffer, value);
9499 *buffer += len;
9500 *left -= len;
9501
9502 /* NUL-terminate the buffer as a convenience, if there is
9503 room. */
9504 if (*left)
9505 **buffer = '\0';
9506}
9507
9508/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9509 value, *REMOTE_ERRNO to the remote error number or zero if none
9510 was included, and *ATTACHMENT to point to the start of the annex
9511 if any. The length of the packet isn't needed here; there may
9512 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9513
9514 Return 0 if the packet could be parsed, -1 if it could not. If
9515 -1 is returned, the other variables may not be initialized. */
9516
9517static int
9518remote_hostio_parse_result (char *buffer, int *retcode,
9519 int *remote_errno, char **attachment)
9520{
9521 char *p, *p2;
9522
9523 *remote_errno = 0;
9524 *attachment = NULL;
9525
9526 if (buffer[0] != 'F')
9527 return -1;
9528
9529 errno = 0;
9530 *retcode = strtol (&buffer[1], &p, 16);
9531 if (errno != 0 || p == &buffer[1])
9532 return -1;
9533
9534 /* Check for ",errno". */
9535 if (*p == ',')
9536 {
9537 errno = 0;
9538 *remote_errno = strtol (p + 1, &p2, 16);
9539 if (errno != 0 || p + 1 == p2)
9540 return -1;
9541 p = p2;
9542 }
9543
9544 /* Check for ";attachment". If there is no attachment, the
9545 packet should end here. */
9546 if (*p == ';')
9547 {
9548 *attachment = p + 1;
9549 return 0;
9550 }
9551 else if (*p == '\0')
9552 return 0;
9553 else
9554 return -1;
9555}
9556
9557/* Send a prepared I/O packet to the target and read its response.
9558 The prepared packet is in the global RS->BUF before this function
9559 is called, and the answer is there when we return.
9560
9561 COMMAND_BYTES is the length of the request to send, which may include
9562 binary data. WHICH_PACKET is the packet configuration to check
9563 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9564 is set to the error number and -1 is returned. Otherwise the value
9565 returned by the function is returned.
9566
9567 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9568 attachment is expected; an error will be reported if there's a
9569 mismatch. If one is found, *ATTACHMENT will be set to point into
9570 the packet buffer and *ATTACHMENT_LEN will be set to the
9571 attachment's length. */
9572
9573static int
9574remote_hostio_send_command (int command_bytes, int which_packet,
9575 int *remote_errno, char **attachment,
9576 int *attachment_len)
9577{
9578 struct remote_state *rs = get_remote_state ();
9579 int ret, bytes_read;
9580 char *attachment_tmp;
9581
f1838a98
UW
9582 if (!remote_desc
9583 || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
a6b151f1
DJ
9584 {
9585 *remote_errno = FILEIO_ENOSYS;
9586 return -1;
9587 }
9588
9589 putpkt_binary (rs->buf, command_bytes);
9590 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9591
9592 /* If it timed out, something is wrong. Don't try to parse the
9593 buffer. */
9594 if (bytes_read < 0)
9595 {
9596 *remote_errno = FILEIO_EINVAL;
9597 return -1;
9598 }
9599
9600 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9601 {
9602 case PACKET_ERROR:
9603 *remote_errno = FILEIO_EINVAL;
9604 return -1;
9605 case PACKET_UNKNOWN:
9606 *remote_errno = FILEIO_ENOSYS;
9607 return -1;
9608 case PACKET_OK:
9609 break;
9610 }
9611
9612 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9613 &attachment_tmp))
9614 {
9615 *remote_errno = FILEIO_EINVAL;
9616 return -1;
9617 }
9618
9619 /* Make sure we saw an attachment if and only if we expected one. */
9620 if ((attachment_tmp == NULL && attachment != NULL)
9621 || (attachment_tmp != NULL && attachment == NULL))
9622 {
9623 *remote_errno = FILEIO_EINVAL;
9624 return -1;
9625 }
9626
9627 /* If an attachment was found, it must point into the packet buffer;
9628 work out how many bytes there were. */
9629 if (attachment_tmp != NULL)
9630 {
9631 *attachment = attachment_tmp;
9632 *attachment_len = bytes_read - (*attachment - rs->buf);
9633 }
9634
9635 return ret;
9636}
9637
9638/* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9639 remote file descriptor, or -1 if an error occurs (and set
9640 *REMOTE_ERRNO). */
9641
9642static int
9643remote_hostio_open (const char *filename, int flags, int mode,
9644 int *remote_errno)
9645{
9646 struct remote_state *rs = get_remote_state ();
9647 char *p = rs->buf;
9648 int left = get_remote_packet_size () - 1;
9649
9650 remote_buffer_add_string (&p, &left, "vFile:open:");
9651
9652 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9653 strlen (filename));
9654 remote_buffer_add_string (&p, &left, ",");
9655
9656 remote_buffer_add_int (&p, &left, flags);
9657 remote_buffer_add_string (&p, &left, ",");
9658
9659 remote_buffer_add_int (&p, &left, mode);
9660
9661 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9662 remote_errno, NULL, NULL);
9663}
9664
9665/* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9666 Return the number of bytes written, or -1 if an error occurs (and
9667 set *REMOTE_ERRNO). */
9668
9669static int
9670remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
9671 ULONGEST offset, int *remote_errno)
9672{
9673 struct remote_state *rs = get_remote_state ();
9674 char *p = rs->buf;
9675 int left = get_remote_packet_size ();
9676 int out_len;
9677
9678 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9679
9680 remote_buffer_add_int (&p, &left, fd);
9681 remote_buffer_add_string (&p, &left, ",");
9682
9683 remote_buffer_add_int (&p, &left, offset);
9684 remote_buffer_add_string (&p, &left, ",");
9685
9686 p += remote_escape_output (write_buf, len, p, &out_len,
9687 get_remote_packet_size () - (p - rs->buf));
9688
9689 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9690 remote_errno, NULL, NULL);
9691}
9692
9693/* Read up to LEN bytes FD on the remote target into READ_BUF
9694 Return the number of bytes read, or -1 if an error occurs (and
9695 set *REMOTE_ERRNO). */
9696
9697static int
9698remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
9699 ULONGEST offset, int *remote_errno)
9700{
9701 struct remote_state *rs = get_remote_state ();
9702 char *p = rs->buf;
9703 char *attachment;
9704 int left = get_remote_packet_size ();
9705 int ret, attachment_len;
9706 int read_len;
9707
9708 remote_buffer_add_string (&p, &left, "vFile:pread:");
9709
9710 remote_buffer_add_int (&p, &left, fd);
9711 remote_buffer_add_string (&p, &left, ",");
9712
9713 remote_buffer_add_int (&p, &left, len);
9714 remote_buffer_add_string (&p, &left, ",");
9715
9716 remote_buffer_add_int (&p, &left, offset);
9717
9718 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9719 remote_errno, &attachment,
9720 &attachment_len);
9721
9722 if (ret < 0)
9723 return ret;
9724
9725 read_len = remote_unescape_input (attachment, attachment_len,
9726 read_buf, len);
9727 if (read_len != ret)
9728 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9729
9730 return ret;
9731}
9732
9733/* Close FD on the remote target. Return 0, or -1 if an error occurs
9734 (and set *REMOTE_ERRNO). */
9735
9736static int
9737remote_hostio_close (int fd, int *remote_errno)
9738{
9739 struct remote_state *rs = get_remote_state ();
9740 char *p = rs->buf;
9741 int left = get_remote_packet_size () - 1;
9742
9743 remote_buffer_add_string (&p, &left, "vFile:close:");
9744
9745 remote_buffer_add_int (&p, &left, fd);
9746
9747 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
9748 remote_errno, NULL, NULL);
9749}
9750
9751/* Unlink FILENAME on the remote target. Return 0, or -1 if an error
9752 occurs (and set *REMOTE_ERRNO). */
9753
9754static int
9755remote_hostio_unlink (const char *filename, int *remote_errno)
9756{
9757 struct remote_state *rs = get_remote_state ();
9758 char *p = rs->buf;
9759 int left = get_remote_packet_size () - 1;
9760
9761 remote_buffer_add_string (&p, &left, "vFile:unlink:");
9762
9763 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9764 strlen (filename));
9765
9766 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
9767 remote_errno, NULL, NULL);
9768}
9769
b9e7b9c3
UW
9770/* Read value of symbolic link FILENAME on the remote target. Return
9771 a null-terminated string allocated via xmalloc, or NULL if an error
9772 occurs (and set *REMOTE_ERRNO). */
9773
9774static char *
9775remote_hostio_readlink (const char *filename, int *remote_errno)
9776{
9777 struct remote_state *rs = get_remote_state ();
9778 char *p = rs->buf;
9779 char *attachment;
9780 int left = get_remote_packet_size ();
9781 int len, attachment_len;
9782 int read_len;
9783 char *ret;
9784
9785 remote_buffer_add_string (&p, &left, "vFile:readlink:");
9786
9787 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9788 strlen (filename));
9789
9790 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
9791 remote_errno, &attachment,
9792 &attachment_len);
9793
9794 if (len < 0)
9795 return NULL;
9796
9797 ret = xmalloc (len + 1);
9798
9799 read_len = remote_unescape_input (attachment, attachment_len,
9800 ret, len);
9801 if (read_len != len)
9802 error (_("Readlink returned %d, but %d bytes."), len, read_len);
9803
9804 ret[len] = '\0';
9805 return ret;
9806}
9807
a6b151f1
DJ
9808static int
9809remote_fileio_errno_to_host (int errnum)
9810{
9811 switch (errnum)
9812 {
9813 case FILEIO_EPERM:
9814 return EPERM;
9815 case FILEIO_ENOENT:
9816 return ENOENT;
9817 case FILEIO_EINTR:
9818 return EINTR;
9819 case FILEIO_EIO:
9820 return EIO;
9821 case FILEIO_EBADF:
9822 return EBADF;
9823 case FILEIO_EACCES:
9824 return EACCES;
9825 case FILEIO_EFAULT:
9826 return EFAULT;
9827 case FILEIO_EBUSY:
9828 return EBUSY;
9829 case FILEIO_EEXIST:
9830 return EEXIST;
9831 case FILEIO_ENODEV:
9832 return ENODEV;
9833 case FILEIO_ENOTDIR:
9834 return ENOTDIR;
9835 case FILEIO_EISDIR:
9836 return EISDIR;
9837 case FILEIO_EINVAL:
9838 return EINVAL;
9839 case FILEIO_ENFILE:
9840 return ENFILE;
9841 case FILEIO_EMFILE:
9842 return EMFILE;
9843 case FILEIO_EFBIG:
9844 return EFBIG;
9845 case FILEIO_ENOSPC:
9846 return ENOSPC;
9847 case FILEIO_ESPIPE:
9848 return ESPIPE;
9849 case FILEIO_EROFS:
9850 return EROFS;
9851 case FILEIO_ENOSYS:
9852 return ENOSYS;
9853 case FILEIO_ENAMETOOLONG:
9854 return ENAMETOOLONG;
9855 }
9856 return -1;
9857}
9858
9859static char *
9860remote_hostio_error (int errnum)
9861{
9862 int host_error = remote_fileio_errno_to_host (errnum);
9863
9864 if (host_error == -1)
9865 error (_("Unknown remote I/O error %d"), errnum);
9866 else
9867 error (_("Remote I/O error: %s"), safe_strerror (host_error));
9868}
9869
a6b151f1
DJ
9870static void
9871remote_hostio_close_cleanup (void *opaque)
9872{
9873 int fd = *(int *) opaque;
9874 int remote_errno;
9875
9876 remote_hostio_close (fd, &remote_errno);
9877}
9878
f1838a98
UW
9879
9880static void *
9881remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
9882{
9883 const char *filename = bfd_get_filename (abfd);
9884 int fd, remote_errno;
9885 int *stream;
9886
9887 gdb_assert (remote_filename_p (filename));
9888
9889 fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
9890 if (fd == -1)
9891 {
9892 errno = remote_fileio_errno_to_host (remote_errno);
9893 bfd_set_error (bfd_error_system_call);
9894 return NULL;
9895 }
9896
9897 stream = xmalloc (sizeof (int));
9898 *stream = fd;
9899 return stream;
9900}
9901
9902static int
9903remote_bfd_iovec_close (struct bfd *abfd, void *stream)
9904{
9905 int fd = *(int *)stream;
9906 int remote_errno;
9907
9908 xfree (stream);
9909
9910 /* Ignore errors on close; these may happen if the remote
9911 connection was already torn down. */
9912 remote_hostio_close (fd, &remote_errno);
9913
9914 return 1;
9915}
9916
9917static file_ptr
9918remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
9919 file_ptr nbytes, file_ptr offset)
9920{
9921 int fd = *(int *)stream;
9922 int remote_errno;
9923 file_ptr pos, bytes;
9924
9925 pos = 0;
9926 while (nbytes > pos)
9927 {
9928 bytes = remote_hostio_pread (fd, (char *)buf + pos, nbytes - pos,
9929 offset + pos, &remote_errno);
9930 if (bytes == 0)
9931 /* Success, but no bytes, means end-of-file. */
9932 break;
9933 if (bytes == -1)
9934 {
9935 errno = remote_fileio_errno_to_host (remote_errno);
9936 bfd_set_error (bfd_error_system_call);
9937 return -1;
9938 }
9939
9940 pos += bytes;
9941 }
9942
9943 return pos;
9944}
9945
9946static int
9947remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
9948{
9949 /* FIXME: We should probably implement remote_hostio_stat. */
9950 sb->st_size = INT_MAX;
9951 return 0;
9952}
9953
9954int
9955remote_filename_p (const char *filename)
9956{
9957 return strncmp (filename, "remote:", 7) == 0;
9958}
9959
9960bfd *
9961remote_bfd_open (const char *remote_file, const char *target)
9962{
64c31149
TT
9963 bfd *abfd = gdb_bfd_openr_iovec (remote_file, target,
9964 remote_bfd_iovec_open, NULL,
9965 remote_bfd_iovec_pread,
9966 remote_bfd_iovec_close,
9967 remote_bfd_iovec_stat);
9968
a4453b7e 9969 return abfd;
f1838a98
UW
9970}
9971
a6b151f1
DJ
9972void
9973remote_file_put (const char *local_file, const char *remote_file, int from_tty)
9974{
9975 struct cleanup *back_to, *close_cleanup;
9976 int retcode, fd, remote_errno, bytes, io_size;
9977 FILE *file;
9978 gdb_byte *buffer;
9979 int bytes_in_buffer;
9980 int saw_eof;
9981 ULONGEST offset;
9982
9983 if (!remote_desc)
9984 error (_("command can only be used with remote target"));
9985
9986 file = fopen (local_file, "rb");
9987 if (file == NULL)
9988 perror_with_name (local_file);
7c8a8b04 9989 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
9990
9991 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
9992 | FILEIO_O_TRUNC),
9993 0700, &remote_errno);
9994 if (fd == -1)
9995 remote_hostio_error (remote_errno);
9996
9997 /* Send up to this many bytes at once. They won't all fit in the
9998 remote packet limit, so we'll transfer slightly fewer. */
9999 io_size = get_remote_packet_size ();
10000 buffer = xmalloc (io_size);
10001 make_cleanup (xfree, buffer);
10002
10003 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10004
10005 bytes_in_buffer = 0;
10006 saw_eof = 0;
10007 offset = 0;
10008 while (bytes_in_buffer || !saw_eof)
10009 {
10010 if (!saw_eof)
10011 {
3e43a32a
MS
10012 bytes = fread (buffer + bytes_in_buffer, 1,
10013 io_size - bytes_in_buffer,
a6b151f1
DJ
10014 file);
10015 if (bytes == 0)
10016 {
10017 if (ferror (file))
10018 error (_("Error reading %s."), local_file);
10019 else
10020 {
10021 /* EOF. Unless there is something still in the
10022 buffer from the last iteration, we are done. */
10023 saw_eof = 1;
10024 if (bytes_in_buffer == 0)
10025 break;
10026 }
10027 }
10028 }
10029 else
10030 bytes = 0;
10031
10032 bytes += bytes_in_buffer;
10033 bytes_in_buffer = 0;
10034
3e43a32a
MS
10035 retcode = remote_hostio_pwrite (fd, buffer, bytes,
10036 offset, &remote_errno);
a6b151f1
DJ
10037
10038 if (retcode < 0)
10039 remote_hostio_error (remote_errno);
10040 else if (retcode == 0)
10041 error (_("Remote write of %d bytes returned 0!"), bytes);
10042 else if (retcode < bytes)
10043 {
10044 /* Short write. Save the rest of the read data for the next
10045 write. */
10046 bytes_in_buffer = bytes - retcode;
10047 memmove (buffer, buffer + retcode, bytes_in_buffer);
10048 }
10049
10050 offset += retcode;
10051 }
10052
10053 discard_cleanups (close_cleanup);
10054 if (remote_hostio_close (fd, &remote_errno))
10055 remote_hostio_error (remote_errno);
10056
10057 if (from_tty)
10058 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10059 do_cleanups (back_to);
10060}
10061
10062void
10063remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10064{
10065 struct cleanup *back_to, *close_cleanup;
cea39f65 10066 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
10067 FILE *file;
10068 gdb_byte *buffer;
10069 ULONGEST offset;
10070
10071 if (!remote_desc)
10072 error (_("command can only be used with remote target"));
10073
10074 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
10075 if (fd == -1)
10076 remote_hostio_error (remote_errno);
10077
10078 file = fopen (local_file, "wb");
10079 if (file == NULL)
10080 perror_with_name (local_file);
7c8a8b04 10081 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
10082
10083 /* Send up to this many bytes at once. They won't all fit in the
10084 remote packet limit, so we'll transfer slightly fewer. */
10085 io_size = get_remote_packet_size ();
10086 buffer = xmalloc (io_size);
10087 make_cleanup (xfree, buffer);
10088
10089 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10090
10091 offset = 0;
10092 while (1)
10093 {
10094 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
10095 if (bytes == 0)
10096 /* Success, but no bytes, means end-of-file. */
10097 break;
10098 if (bytes == -1)
10099 remote_hostio_error (remote_errno);
10100
10101 offset += bytes;
10102
10103 bytes = fwrite (buffer, 1, bytes, file);
10104 if (bytes == 0)
10105 perror_with_name (local_file);
10106 }
10107
10108 discard_cleanups (close_cleanup);
10109 if (remote_hostio_close (fd, &remote_errno))
10110 remote_hostio_error (remote_errno);
10111
10112 if (from_tty)
10113 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10114 do_cleanups (back_to);
10115}
10116
10117void
10118remote_file_delete (const char *remote_file, int from_tty)
10119{
10120 int retcode, remote_errno;
10121
10122 if (!remote_desc)
10123 error (_("command can only be used with remote target"));
10124
10125 retcode = remote_hostio_unlink (remote_file, &remote_errno);
10126 if (retcode == -1)
10127 remote_hostio_error (remote_errno);
10128
10129 if (from_tty)
10130 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10131}
10132
10133static void
10134remote_put_command (char *args, int from_tty)
10135{
10136 struct cleanup *back_to;
10137 char **argv;
10138
d1a41061
PP
10139 if (args == NULL)
10140 error_no_arg (_("file to put"));
10141
10142 argv = gdb_buildargv (args);
a6b151f1
DJ
10143 back_to = make_cleanup_freeargv (argv);
10144 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10145 error (_("Invalid parameters to remote put"));
10146
10147 remote_file_put (argv[0], argv[1], from_tty);
10148
10149 do_cleanups (back_to);
10150}
10151
10152static void
10153remote_get_command (char *args, int from_tty)
10154{
10155 struct cleanup *back_to;
10156 char **argv;
10157
d1a41061
PP
10158 if (args == NULL)
10159 error_no_arg (_("file to get"));
10160
10161 argv = gdb_buildargv (args);
a6b151f1
DJ
10162 back_to = make_cleanup_freeargv (argv);
10163 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10164 error (_("Invalid parameters to remote get"));
10165
10166 remote_file_get (argv[0], argv[1], from_tty);
10167
10168 do_cleanups (back_to);
10169}
10170
10171static void
10172remote_delete_command (char *args, int from_tty)
10173{
10174 struct cleanup *back_to;
10175 char **argv;
10176
d1a41061
PP
10177 if (args == NULL)
10178 error_no_arg (_("file to delete"));
10179
10180 argv = gdb_buildargv (args);
a6b151f1
DJ
10181 back_to = make_cleanup_freeargv (argv);
10182 if (argv[0] == NULL || argv[1] != NULL)
10183 error (_("Invalid parameters to remote delete"));
10184
10185 remote_file_delete (argv[0], from_tty);
10186
10187 do_cleanups (back_to);
10188}
10189
10190static void
10191remote_command (char *args, int from_tty)
10192{
10193 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
10194}
10195
b2175913
MS
10196static int
10197remote_can_execute_reverse (void)
10198{
40ab02ce
MS
10199 if (remote_protocol_packets[PACKET_bs].support == PACKET_ENABLE
10200 || remote_protocol_packets[PACKET_bc].support == PACKET_ENABLE)
10201 return 1;
10202 else
10203 return 0;
b2175913
MS
10204}
10205
74531fed
PA
10206static int
10207remote_supports_non_stop (void)
10208{
10209 return 1;
10210}
10211
03583c20
UW
10212static int
10213remote_supports_disable_randomization (void)
10214{
10215 /* Only supported in extended mode. */
10216 return 0;
10217}
10218
8a305172
PA
10219static int
10220remote_supports_multi_process (void)
10221{
10222 struct remote_state *rs = get_remote_state ();
a744cf53 10223
901f9912
UW
10224 /* Only extended-remote handles being attached to multiple
10225 processes, even though plain remote can use the multi-process
10226 thread id extensions, so that GDB knows the target process's
10227 PID. */
10228 return rs->extended && remote_multi_process_p (rs);
8a305172
PA
10229}
10230
70221824 10231static int
782b2b07
SS
10232remote_supports_cond_tracepoints (void)
10233{
10234 struct remote_state *rs = get_remote_state ();
a744cf53 10235
782b2b07
SS
10236 return rs->cond_tracepoints;
10237}
10238
3788aec7
LM
10239static int
10240remote_supports_cond_breakpoints (void)
10241{
10242 struct remote_state *rs = get_remote_state ();
10243
10244 return rs->cond_breakpoints;
10245}
10246
70221824 10247static int
7a697b8d
SS
10248remote_supports_fast_tracepoints (void)
10249{
10250 struct remote_state *rs = get_remote_state ();
a744cf53 10251
7a697b8d
SS
10252 return rs->fast_tracepoints;
10253}
10254
0fb4aa4b
PA
10255static int
10256remote_supports_static_tracepoints (void)
10257{
10258 struct remote_state *rs = get_remote_state ();
10259
10260 return rs->static_tracepoints;
10261}
10262
1e4d1764
YQ
10263static int
10264remote_supports_install_in_trace (void)
10265{
10266 struct remote_state *rs = get_remote_state ();
10267
10268 return rs->install_in_trace;
10269}
10270
d248b706
KY
10271static int
10272remote_supports_enable_disable_tracepoint (void)
10273{
10274 struct remote_state *rs = get_remote_state ();
10275
10276 return rs->enable_disable_tracepoints;
10277}
10278
3065dfb6
SS
10279static int
10280remote_supports_string_tracing (void)
10281{
10282 struct remote_state *rs = get_remote_state ();
10283
10284 return rs->string_tracing;
10285}
10286
d3ce09f5
SS
10287static int
10288remote_can_run_breakpoint_commands (void)
10289{
10290 struct remote_state *rs = get_remote_state ();
10291
10292 return rs->breakpoint_commands;
10293}
10294
35b1e5cc 10295static void
ad91cd99 10296remote_trace_init (void)
35b1e5cc
SS
10297{
10298 putpkt ("QTinit");
10299 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 10300 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
10301 error (_("Target does not support this command."));
10302}
10303
10304static void free_actions_list (char **actions_list);
10305static void free_actions_list_cleanup_wrapper (void *);
10306static void
10307free_actions_list_cleanup_wrapper (void *al)
10308{
10309 free_actions_list (al);
10310}
10311
10312static void
10313free_actions_list (char **actions_list)
10314{
10315 int ndx;
10316
10317 if (actions_list == 0)
10318 return;
10319
10320 for (ndx = 0; actions_list[ndx]; ndx++)
10321 xfree (actions_list[ndx]);
10322
10323 xfree (actions_list);
10324}
10325
409873ef
SS
10326/* Recursive routine to walk through command list including loops, and
10327 download packets for each command. */
10328
10329static void
10330remote_download_command_source (int num, ULONGEST addr,
10331 struct command_line *cmds)
10332{
10333 struct remote_state *rs = get_remote_state ();
10334 struct command_line *cmd;
10335
10336 for (cmd = cmds; cmd; cmd = cmd->next)
10337 {
0df8b418 10338 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
10339 strcpy (rs->buf, "QTDPsrc:");
10340 encode_source_string (num, addr, "cmd", cmd->line,
10341 rs->buf + strlen (rs->buf),
10342 rs->buf_size - strlen (rs->buf));
10343 putpkt (rs->buf);
10344 remote_get_noisy_reply (&target_buf, &target_buf_size);
10345 if (strcmp (target_buf, "OK"))
10346 warning (_("Target does not support source download."));
10347
10348 if (cmd->control_type == while_control
10349 || cmd->control_type == while_stepping_control)
10350 {
10351 remote_download_command_source (num, addr, *cmd->body_list);
10352
0df8b418 10353 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
10354 strcpy (rs->buf, "QTDPsrc:");
10355 encode_source_string (num, addr, "cmd", "end",
10356 rs->buf + strlen (rs->buf),
10357 rs->buf_size - strlen (rs->buf));
10358 putpkt (rs->buf);
10359 remote_get_noisy_reply (&target_buf, &target_buf_size);
10360 if (strcmp (target_buf, "OK"))
10361 warning (_("Target does not support source download."));
10362 }
10363 }
10364}
10365
35b1e5cc 10366static void
e8ba3115 10367remote_download_tracepoint (struct bp_location *loc)
35b1e5cc 10368{
bba74b36 10369#define BUF_SIZE 2048
e8ba3115 10370
35b1e5cc 10371 CORE_ADDR tpaddr;
409873ef 10372 char addrbuf[40];
bba74b36 10373 char buf[BUF_SIZE];
35b1e5cc
SS
10374 char **tdp_actions;
10375 char **stepping_actions;
10376 int ndx;
10377 struct cleanup *old_chain = NULL;
10378 struct agent_expr *aexpr;
10379 struct cleanup *aexpr_chain = NULL;
10380 char *pkt;
e8ba3115 10381 struct breakpoint *b = loc->owner;
d9b3f62e 10382 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 10383
e8ba3115
YQ
10384 encode_actions (loc->owner, loc, &tdp_actions, &stepping_actions);
10385 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10386 tdp_actions);
10387 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10388 stepping_actions);
10389
10390 tpaddr = loc->address;
10391 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
10392 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10393 addrbuf, /* address */
10394 (b->enable_state == bp_enabled ? 'E' : 'D'),
10395 t->step_count, t->pass_count);
e8ba3115
YQ
10396 /* Fast tracepoints are mostly handled by the target, but we can
10397 tell the target how big of an instruction block should be moved
10398 around. */
10399 if (b->type == bp_fast_tracepoint)
10400 {
10401 /* Only test for support at download time; we may not know
10402 target capabilities at definition time. */
10403 if (remote_supports_fast_tracepoints ())
35b1e5cc 10404 {
e8ba3115 10405 int isize;
35b1e5cc 10406
f5656ead 10407 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
e8ba3115 10408 tpaddr, &isize, NULL))
bba74b36
YQ
10409 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10410 isize);
35b1e5cc 10411 else
e8ba3115
YQ
10412 /* If it passed validation at definition but fails now,
10413 something is very wrong. */
10414 internal_error (__FILE__, __LINE__,
10415 _("Fast tracepoint not "
10416 "valid during download"));
35b1e5cc 10417 }
e8ba3115
YQ
10418 else
10419 /* Fast tracepoints are functionally identical to regular
10420 tracepoints, so don't take lack of support as a reason to
10421 give up on the trace run. */
10422 warning (_("Target does not support fast tracepoints, "
10423 "downloading %d as regular tracepoint"), b->number);
10424 }
10425 else if (b->type == bp_static_tracepoint)
10426 {
10427 /* Only test for support at download time; we may not know
10428 target capabilities at definition time. */
10429 if (remote_supports_static_tracepoints ())
0fb4aa4b 10430 {
e8ba3115 10431 struct static_tracepoint_marker marker;
0fb4aa4b 10432
e8ba3115
YQ
10433 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10434 strcat (buf, ":S");
0fb4aa4b 10435 else
e8ba3115 10436 error (_("Static tracepoint not valid during download"));
0fb4aa4b 10437 }
e8ba3115
YQ
10438 else
10439 /* Fast tracepoints are functionally identical to regular
10440 tracepoints, so don't take lack of support as a reason
10441 to give up on the trace run. */
10442 error (_("Target does not support static tracepoints"));
10443 }
10444 /* If the tracepoint has a conditional, make it into an agent
10445 expression and append to the definition. */
10446 if (loc->cond)
10447 {
10448 /* Only test support at download time, we may not know target
10449 capabilities at definition time. */
10450 if (remote_supports_cond_tracepoints ())
35b1e5cc 10451 {
e8ba3115
YQ
10452 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10453 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
10454 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10455 aexpr->len);
e8ba3115
YQ
10456 pkt = buf + strlen (buf);
10457 for (ndx = 0; ndx < aexpr->len; ++ndx)
10458 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10459 *pkt = '\0';
10460 do_cleanups (aexpr_chain);
35b1e5cc 10461 }
e8ba3115
YQ
10462 else
10463 warning (_("Target does not support conditional tracepoints, "
10464 "ignoring tp %d cond"), b->number);
10465 }
35b1e5cc 10466
d9b3f62e 10467 if (b->commands || *default_collect)
e8ba3115
YQ
10468 strcat (buf, "-");
10469 putpkt (buf);
10470 remote_get_noisy_reply (&target_buf, &target_buf_size);
10471 if (strcmp (target_buf, "OK"))
10472 error (_("Target does not support tracepoints."));
35b1e5cc 10473
e8ba3115
YQ
10474 /* do_single_steps (t); */
10475 if (tdp_actions)
10476 {
10477 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 10478 {
e8ba3115 10479 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
10480 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10481 b->number, addrbuf, /* address */
10482 tdp_actions[ndx],
10483 ((tdp_actions[ndx + 1] || stepping_actions)
10484 ? '-' : 0));
e8ba3115
YQ
10485 putpkt (buf);
10486 remote_get_noisy_reply (&target_buf,
10487 &target_buf_size);
10488 if (strcmp (target_buf, "OK"))
10489 error (_("Error on target while setting tracepoints."));
35b1e5cc 10490 }
e8ba3115
YQ
10491 }
10492 if (stepping_actions)
10493 {
10494 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 10495 {
e8ba3115 10496 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
10497 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10498 b->number, addrbuf, /* address */
10499 ((ndx == 0) ? "S" : ""),
10500 stepping_actions[ndx],
10501 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
10502 putpkt (buf);
10503 remote_get_noisy_reply (&target_buf,
10504 &target_buf_size);
10505 if (strcmp (target_buf, "OK"))
10506 error (_("Error on target while setting tracepoints."));
35b1e5cc 10507 }
e8ba3115 10508 }
409873ef 10509
e8ba3115
YQ
10510 if (remote_protocol_packets[PACKET_TracepointSource].support
10511 == PACKET_ENABLE)
10512 {
10513 if (b->addr_string)
409873ef 10514 {
e8ba3115
YQ
10515 strcpy (buf, "QTDPsrc:");
10516 encode_source_string (b->number, loc->address,
10517 "at", b->addr_string, buf + strlen (buf),
10518 2048 - strlen (buf));
409873ef 10519
e8ba3115
YQ
10520 putpkt (buf);
10521 remote_get_noisy_reply (&target_buf, &target_buf_size);
10522 if (strcmp (target_buf, "OK"))
10523 warning (_("Target does not support source download."));
409873ef 10524 }
e8ba3115
YQ
10525 if (b->cond_string)
10526 {
10527 strcpy (buf, "QTDPsrc:");
10528 encode_source_string (b->number, loc->address,
10529 "cond", b->cond_string, buf + strlen (buf),
10530 2048 - strlen (buf));
10531 putpkt (buf);
10532 remote_get_noisy_reply (&target_buf, &target_buf_size);
10533 if (strcmp (target_buf, "OK"))
10534 warning (_("Target does not support source download."));
10535 }
10536 remote_download_command_source (b->number, loc->address,
10537 breakpoint_commands (b));
35b1e5cc 10538 }
e8ba3115
YQ
10539
10540 do_cleanups (old_chain);
35b1e5cc
SS
10541}
10542
1e4d1764
YQ
10543static int
10544remote_can_download_tracepoint (void)
10545{
1e51243a
PA
10546 struct remote_state *rs = get_remote_state ();
10547 struct trace_status *ts;
10548 int status;
10549
10550 /* Don't try to install tracepoints until we've relocated our
10551 symbols, and fetched and merged the target's tracepoint list with
10552 ours. */
10553 if (rs->starting_up)
10554 return 0;
10555
10556 ts = current_trace_status ();
10557 status = remote_get_trace_status (ts);
1e4d1764
YQ
10558
10559 if (status == -1 || !ts->running_known || !ts->running)
10560 return 0;
10561
10562 /* If we are in a tracing experiment, but remote stub doesn't support
10563 installing tracepoint in trace, we have to return. */
10564 if (!remote_supports_install_in_trace ())
10565 return 0;
10566
10567 return 1;
10568}
10569
10570
35b1e5cc
SS
10571static void
10572remote_download_trace_state_variable (struct trace_state_variable *tsv)
10573{
10574 struct remote_state *rs = get_remote_state ();
00bf0b85 10575 char *p;
35b1e5cc 10576
bba74b36
YQ
10577 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10578 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10579 tsv->builtin);
00bf0b85
SS
10580 p = rs->buf + strlen (rs->buf);
10581 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10582 error (_("Trace state variable name too long for tsv definition packet"));
10583 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, 0);
10584 *p++ = '\0';
35b1e5cc
SS
10585 putpkt (rs->buf);
10586 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
10587 if (*target_buf == '\0')
10588 error (_("Target does not support this command."));
10589 if (strcmp (target_buf, "OK") != 0)
10590 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
10591}
10592
d248b706
KY
10593static void
10594remote_enable_tracepoint (struct bp_location *location)
10595{
10596 struct remote_state *rs = get_remote_state ();
10597 char addr_buf[40];
10598
10599 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
10600 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10601 location->owner->number, addr_buf);
d248b706
KY
10602 putpkt (rs->buf);
10603 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10604 if (*rs->buf == '\0')
10605 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10606 if (strcmp (rs->buf, "OK") != 0)
10607 error (_("Error on target while enabling tracepoint."));
10608}
10609
10610static void
10611remote_disable_tracepoint (struct bp_location *location)
10612{
10613 struct remote_state *rs = get_remote_state ();
10614 char addr_buf[40];
10615
10616 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
10617 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10618 location->owner->number, addr_buf);
d248b706
KY
10619 putpkt (rs->buf);
10620 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10621 if (*rs->buf == '\0')
10622 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10623 if (strcmp (rs->buf, "OK") != 0)
10624 error (_("Error on target while disabling tracepoint."));
10625}
10626
35b1e5cc 10627static void
ad91cd99 10628remote_trace_set_readonly_regions (void)
35b1e5cc
SS
10629{
10630 asection *s;
81b9b86e 10631 bfd *abfd = NULL;
35b1e5cc 10632 bfd_size_type size;
608bcef2 10633 bfd_vma vma;
35b1e5cc 10634 int anysecs = 0;
c2fa21f1 10635 int offset = 0;
35b1e5cc
SS
10636
10637 if (!exec_bfd)
10638 return; /* No information to give. */
10639
10640 strcpy (target_buf, "QTro");
10641 for (s = exec_bfd->sections; s; s = s->next)
10642 {
10643 char tmp1[40], tmp2[40];
c2fa21f1 10644 int sec_length;
35b1e5cc
SS
10645
10646 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 10647 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
10648 (s->flags & SEC_READONLY) == 0)
10649 continue;
10650
10651 anysecs = 1;
81b9b86e 10652 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 10653 size = bfd_get_section_size (s);
608bcef2
HZ
10654 sprintf_vma (tmp1, vma);
10655 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
10656 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10657 if (offset + sec_length + 1 > target_buf_size)
10658 {
864ac8a7
HZ
10659 if (remote_protocol_packets[PACKET_qXfer_traceframe_info].support
10660 != PACKET_ENABLE)
10661 warning (_("\
c2fa21f1
HZ
10662Too many sections for read-only sections definition packet."));
10663 break;
10664 }
bba74b36
YQ
10665 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10666 tmp1, tmp2);
c2fa21f1 10667 offset += sec_length;
35b1e5cc
SS
10668 }
10669 if (anysecs)
10670 {
10671 putpkt (target_buf);
10672 getpkt (&target_buf, &target_buf_size, 0);
10673 }
10674}
10675
10676static void
ad91cd99 10677remote_trace_start (void)
35b1e5cc
SS
10678{
10679 putpkt ("QTStart");
10680 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
10681 if (*target_buf == '\0')
10682 error (_("Target does not support this command."));
10683 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
10684 error (_("Bogus reply from target: %s"), target_buf);
10685}
10686
10687static int
00bf0b85 10688remote_get_trace_status (struct trace_status *ts)
35b1e5cc 10689{
953b98d1 10690 /* Initialize it just to avoid a GCC false warning. */
f652de6f 10691 char *p = NULL;
0df8b418 10692 /* FIXME we need to get register block size some other way. */
00bf0b85 10693 extern int trace_regblock_size;
67f41397 10694 volatile struct gdb_exception ex;
a744cf53 10695
00bf0b85
SS
10696 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10697
35b1e5cc 10698 putpkt ("qTStatus");
67f41397
JK
10699
10700 TRY_CATCH (ex, RETURN_MASK_ERROR)
10701 {
10702 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10703 }
10704 if (ex.reason < 0)
10705 {
10706 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10707 return -1;
10708 }
00bf0b85
SS
10709
10710 /* If the remote target doesn't do tracing, flag it. */
10711 if (*p == '\0')
10712 return -1;
35b1e5cc 10713
00bf0b85 10714 /* We're working with a live target. */
f5911ea1 10715 ts->filename = NULL;
00bf0b85 10716
00bf0b85 10717 if (*p++ != 'T')
35b1e5cc
SS
10718 error (_("Bogus trace status reply from target: %s"), target_buf);
10719
84cebc4a
YQ
10720 /* Function 'parse_trace_status' sets default value of each field of
10721 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
10722 parse_trace_status (p, ts);
10723
10724 return ts->running;
35b1e5cc
SS
10725}
10726
70221824 10727static void
f196051f
SS
10728remote_get_tracepoint_status (struct breakpoint *bp,
10729 struct uploaded_tp *utp)
10730{
10731 struct remote_state *rs = get_remote_state ();
f196051f
SS
10732 char *reply;
10733 struct bp_location *loc;
10734 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 10735 size_t size = get_remote_packet_size ();
f196051f
SS
10736
10737 if (tp)
10738 {
10739 tp->base.hit_count = 0;
10740 tp->traceframe_usage = 0;
10741 for (loc = tp->base.loc; loc; loc = loc->next)
10742 {
10743 /* If the tracepoint was never downloaded, don't go asking for
10744 any status. */
10745 if (tp->number_on_target == 0)
10746 continue;
bba74b36
YQ
10747 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
10748 phex_nz (loc->address, 0));
f196051f
SS
10749 putpkt (rs->buf);
10750 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10751 if (reply && *reply)
10752 {
10753 if (*reply == 'V')
10754 parse_tracepoint_status (reply + 1, bp, utp);
10755 }
10756 }
10757 }
10758 else if (utp)
10759 {
10760 utp->hit_count = 0;
10761 utp->traceframe_usage = 0;
bba74b36
YQ
10762 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
10763 phex_nz (utp->addr, 0));
f196051f
SS
10764 putpkt (rs->buf);
10765 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10766 if (reply && *reply)
10767 {
10768 if (*reply == 'V')
10769 parse_tracepoint_status (reply + 1, bp, utp);
10770 }
10771 }
10772}
10773
35b1e5cc 10774static void
ad91cd99 10775remote_trace_stop (void)
35b1e5cc
SS
10776{
10777 putpkt ("QTStop");
10778 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
10779 if (*target_buf == '\0')
10780 error (_("Target does not support this command."));
10781 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
10782 error (_("Bogus reply from target: %s"), target_buf);
10783}
10784
10785static int
10786remote_trace_find (enum trace_find_type type, int num,
10787 ULONGEST addr1, ULONGEST addr2,
10788 int *tpp)
10789{
10790 struct remote_state *rs = get_remote_state ();
bba74b36 10791 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
10792 char *p, *reply;
10793 int target_frameno = -1, target_tracept = -1;
10794
e6e4e701
PA
10795 /* Lookups other than by absolute frame number depend on the current
10796 trace selected, so make sure it is correct on the remote end
10797 first. */
10798 if (type != tfind_number)
10799 set_remote_traceframe ();
10800
35b1e5cc
SS
10801 p = rs->buf;
10802 strcpy (p, "QTFrame:");
10803 p = strchr (p, '\0');
10804 switch (type)
10805 {
10806 case tfind_number:
bba74b36 10807 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
10808 break;
10809 case tfind_pc:
bba74b36 10810 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
10811 break;
10812 case tfind_tp:
bba74b36 10813 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
10814 break;
10815 case tfind_range:
bba74b36
YQ
10816 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
10817 phex_nz (addr2, 0));
35b1e5cc
SS
10818 break;
10819 case tfind_outside:
bba74b36
YQ
10820 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
10821 phex_nz (addr2, 0));
35b1e5cc
SS
10822 break;
10823 default:
9b20d036 10824 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
10825 }
10826
10827 putpkt (rs->buf);
10828 reply = remote_get_noisy_reply (&(rs->buf), &sizeof_pkt);
ad91cd99
PA
10829 if (*reply == '\0')
10830 error (_("Target does not support this command."));
35b1e5cc
SS
10831
10832 while (reply && *reply)
10833 switch (*reply)
10834 {
10835 case 'F':
f197e0f1
VP
10836 p = ++reply;
10837 target_frameno = (int) strtol (p, &reply, 16);
10838 if (reply == p)
10839 error (_("Unable to parse trace frame number"));
e6e4e701
PA
10840 /* Don't update our remote traceframe number cache on failure
10841 to select a remote traceframe. */
f197e0f1
VP
10842 if (target_frameno == -1)
10843 return -1;
35b1e5cc
SS
10844 break;
10845 case 'T':
f197e0f1
VP
10846 p = ++reply;
10847 target_tracept = (int) strtol (p, &reply, 16);
10848 if (reply == p)
10849 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
10850 break;
10851 case 'O': /* "OK"? */
10852 if (reply[1] == 'K' && reply[2] == '\0')
10853 reply += 2;
10854 else
10855 error (_("Bogus reply from target: %s"), reply);
10856 break;
10857 default:
10858 error (_("Bogus reply from target: %s"), reply);
10859 }
10860 if (tpp)
10861 *tpp = target_tracept;
e6e4e701
PA
10862
10863 remote_traceframe_number = target_frameno;
35b1e5cc
SS
10864 return target_frameno;
10865}
10866
10867static int
10868remote_get_trace_state_variable_value (int tsvnum, LONGEST *val)
10869{
10870 struct remote_state *rs = get_remote_state ();
10871 char *reply;
10872 ULONGEST uval;
10873
e6e4e701
PA
10874 set_remote_traceframe ();
10875
bba74b36 10876 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
10877 putpkt (rs->buf);
10878 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10879 if (reply && *reply)
10880 {
10881 if (*reply == 'V')
10882 {
10883 unpack_varlen_hex (reply + 1, &uval);
10884 *val = (LONGEST) uval;
10885 return 1;
10886 }
10887 }
10888 return 0;
10889}
10890
00bf0b85 10891static int
011aacb0 10892remote_save_trace_data (const char *filename)
00bf0b85
SS
10893{
10894 struct remote_state *rs = get_remote_state ();
10895 char *p, *reply;
10896
10897 p = rs->buf;
10898 strcpy (p, "QTSave:");
10899 p += strlen (p);
10900 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
10901 error (_("Remote file name too long for trace save packet"));
10902 p += 2 * bin2hex ((gdb_byte *) filename, p, 0);
10903 *p++ = '\0';
10904 putpkt (rs->buf);
ad91cd99 10905 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 10906 if (*reply == '\0')
ad91cd99
PA
10907 error (_("Target does not support this command."));
10908 if (strcmp (reply, "OK") != 0)
10909 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
10910 return 0;
10911}
10912
10913/* This is basically a memory transfer, but needs to be its own packet
10914 because we don't know how the target actually organizes its trace
10915 memory, plus we want to be able to ask for as much as possible, but
10916 not be unhappy if we don't get as much as we ask for. */
10917
10918static LONGEST
10919remote_get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
10920{
10921 struct remote_state *rs = get_remote_state ();
10922 char *reply;
10923 char *p;
10924 int rslt;
10925
10926 p = rs->buf;
10927 strcpy (p, "qTBuffer:");
10928 p += strlen (p);
10929 p += hexnumstr (p, offset);
10930 *p++ = ',';
10931 p += hexnumstr (p, len);
10932 *p++ = '\0';
10933
10934 putpkt (rs->buf);
10935 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10936 if (reply && *reply)
10937 {
10938 /* 'l' by itself means we're at the end of the buffer and
10939 there is nothing more to get. */
10940 if (*reply == 'l')
10941 return 0;
10942
10943 /* Convert the reply into binary. Limit the number of bytes to
10944 convert according to our passed-in buffer size, rather than
10945 what was returned in the packet; if the target is
10946 unexpectedly generous and gives us a bigger reply than we
10947 asked for, we don't want to crash. */
10948 rslt = hex2bin (target_buf, buf, len);
10949 return rslt;
10950 }
10951
10952 /* Something went wrong, flag as an error. */
10953 return -1;
10954}
10955
35b1e5cc
SS
10956static void
10957remote_set_disconnected_tracing (int val)
10958{
10959 struct remote_state *rs = get_remote_state ();
10960
33da3f1c
SS
10961 if (rs->disconnected_tracing)
10962 {
ad91cd99
PA
10963 char *reply;
10964
bba74b36 10965 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 10966 putpkt (rs->buf);
ad91cd99
PA
10967 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10968 if (*reply == '\0')
33da3f1c 10969 error (_("Target does not support this command."));
ad91cd99
PA
10970 if (strcmp (reply, "OK") != 0)
10971 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
10972 }
10973 else if (val)
10974 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
10975}
10976
dc146f7c
VP
10977static int
10978remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
10979{
10980 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 10981
dc146f7c
VP
10982 if (info && info->private)
10983 return info->private->core;
10984 return -1;
10985}
10986
4daf5ac0
SS
10987static void
10988remote_set_circular_trace_buffer (int val)
10989{
10990 struct remote_state *rs = get_remote_state ();
ad91cd99 10991 char *reply;
4daf5ac0 10992
bba74b36 10993 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 10994 putpkt (rs->buf);
ad91cd99
PA
10995 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10996 if (*reply == '\0')
4daf5ac0 10997 error (_("Target does not support this command."));
ad91cd99
PA
10998 if (strcmp (reply, "OK") != 0)
10999 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
11000}
11001
b3b9301e
PA
11002static struct traceframe_info *
11003remote_traceframe_info (void)
11004{
11005 char *text;
11006
11007 text = target_read_stralloc (&current_target,
11008 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11009 if (text != NULL)
11010 {
11011 struct traceframe_info *info;
11012 struct cleanup *back_to = make_cleanup (xfree, text);
11013
11014 info = parse_traceframe_info (text);
11015 do_cleanups (back_to);
11016 return info;
11017 }
11018
11019 return NULL;
11020}
11021
405f8e94
SS
11022/* Handle the qTMinFTPILen packet. Returns the minimum length of
11023 instruction on which a fast tracepoint may be placed. Returns -1
11024 if the packet is not supported, and 0 if the minimum instruction
11025 length is unknown. */
11026
11027static int
11028remote_get_min_fast_tracepoint_insn_len (void)
11029{
11030 struct remote_state *rs = get_remote_state ();
11031 char *reply;
11032
e886a173
PA
11033 /* If we're not debugging a process yet, the IPA can't be
11034 loaded. */
11035 if (!target_has_execution)
11036 return 0;
11037
11038 /* Make sure the remote is pointing at the right process. */
11039 set_general_process ();
11040
bba74b36 11041 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
11042 putpkt (rs->buf);
11043 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11044 if (*reply == '\0')
11045 return -1;
11046 else
11047 {
11048 ULONGEST min_insn_len;
11049
11050 unpack_varlen_hex (reply, &min_insn_len);
11051
11052 return (int) min_insn_len;
11053 }
11054}
11055
f6f899bf
HAQ
11056static void
11057remote_set_trace_buffer_size (LONGEST val)
11058{
90585175
HAQ
11059 if (remote_protocol_packets[PACKET_QTBuffer_size].support
11060 != PACKET_DISABLE)
f6f899bf
HAQ
11061 {
11062 struct remote_state *rs = get_remote_state ();
11063 char *buf = rs->buf;
11064 char *endbuf = rs->buf + get_remote_packet_size ();
11065 enum packet_result result;
11066
11067 gdb_assert (val >= 0 || val == -1);
11068 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11069 /* Send -1 as literal "-1" to avoid host size dependency. */
11070 if (val < 0)
11071 {
11072 *buf++ = '-';
11073 buf += hexnumstr (buf, (ULONGEST) -val);
11074 }
11075 else
11076 buf += hexnumstr (buf, (ULONGEST) val);
11077
11078 putpkt (rs->buf);
11079 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11080 result = packet_ok (rs->buf,
11081 &remote_protocol_packets[PACKET_QTBuffer_size]);
11082
11083 if (result != PACKET_OK)
11084 warning (_("Bogus reply from target: %s"), rs->buf);
11085 }
11086}
11087
f196051f
SS
11088static int
11089remote_set_trace_notes (char *user, char *notes, char *stop_notes)
11090{
11091 struct remote_state *rs = get_remote_state ();
11092 char *reply;
11093 char *buf = rs->buf;
11094 char *endbuf = rs->buf + get_remote_packet_size ();
11095 int nbytes;
11096
11097 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11098 if (user)
11099 {
11100 buf += xsnprintf (buf, endbuf - buf, "user:");
11101 nbytes = bin2hex (user, buf, 0);
11102 buf += 2 * nbytes;
11103 *buf++ = ';';
11104 }
11105 if (notes)
11106 {
11107 buf += xsnprintf (buf, endbuf - buf, "notes:");
11108 nbytes = bin2hex (notes, buf, 0);
11109 buf += 2 * nbytes;
11110 *buf++ = ';';
11111 }
11112 if (stop_notes)
11113 {
11114 buf += xsnprintf (buf, endbuf - buf, "tstop:");
11115 nbytes = bin2hex (stop_notes, buf, 0);
11116 buf += 2 * nbytes;
11117 *buf++ = ';';
11118 }
11119 /* Ensure the buffer is terminated. */
11120 *buf = '\0';
11121
11122 putpkt (rs->buf);
11123 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11124 if (*reply == '\0')
11125 return 0;
11126
11127 if (strcmp (reply, "OK") != 0)
11128 error (_("Bogus reply from target: %s"), reply);
11129
11130 return 1;
11131}
11132
d1feda86
YQ
11133static int
11134remote_use_agent (int use)
11135{
11136 if (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE)
11137 {
11138 struct remote_state *rs = get_remote_state ();
11139
11140 /* If the stub supports QAgent. */
bba74b36 11141 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
11142 putpkt (rs->buf);
11143 getpkt (&rs->buf, &rs->buf_size, 0);
11144
11145 if (strcmp (rs->buf, "OK") == 0)
11146 {
11147 use_agent = use;
11148 return 1;
11149 }
11150 }
11151
11152 return 0;
11153}
11154
11155static int
11156remote_can_use_agent (void)
11157{
11158 return (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE);
11159}
11160
9accd112
MM
11161struct btrace_target_info
11162{
11163 /* The ptid of the traced thread. */
11164 ptid_t ptid;
11165};
11166
11167/* Check whether the target supports branch tracing. */
11168
11169static int
11170remote_supports_btrace (void)
11171{
11172 if (remote_protocol_packets[PACKET_Qbtrace_off].support != PACKET_ENABLE)
11173 return 0;
11174 if (remote_protocol_packets[PACKET_Qbtrace_bts].support != PACKET_ENABLE)
11175 return 0;
11176 if (remote_protocol_packets[PACKET_qXfer_btrace].support != PACKET_ENABLE)
11177 return 0;
11178
11179 return 1;
11180}
11181
11182/* Enable branch tracing. */
11183
11184static struct btrace_target_info *
11185remote_enable_btrace (ptid_t ptid)
11186{
11187 struct btrace_target_info *tinfo = NULL;
11188 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11189 struct remote_state *rs = get_remote_state ();
11190 char *buf = rs->buf;
11191 char *endbuf = rs->buf + get_remote_packet_size ();
11192
11193 if (packet->support != PACKET_ENABLE)
11194 error (_("Target does not support branch tracing."));
11195
11196 set_general_thread (ptid);
11197
11198 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11199 putpkt (rs->buf);
11200 getpkt (&rs->buf, &rs->buf_size, 0);
11201
11202 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11203 {
11204 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11205 error (_("Could not enable branch tracing for %s: %s"),
11206 target_pid_to_str (ptid), rs->buf + 2);
11207 else
11208 error (_("Could not enable branch tracing for %s."),
11209 target_pid_to_str (ptid));
11210 }
11211
11212 tinfo = xzalloc (sizeof (*tinfo));
11213 tinfo->ptid = ptid;
11214
11215 return tinfo;
11216}
11217
11218/* Disable branch tracing. */
11219
11220static void
11221remote_disable_btrace (struct btrace_target_info *tinfo)
11222{
11223 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11224 struct remote_state *rs = get_remote_state ();
11225 char *buf = rs->buf;
11226 char *endbuf = rs->buf + get_remote_packet_size ();
11227
11228 if (packet->support != PACKET_ENABLE)
11229 error (_("Target does not support branch tracing."));
11230
11231 set_general_thread (tinfo->ptid);
11232
11233 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11234 putpkt (rs->buf);
11235 getpkt (&rs->buf, &rs->buf_size, 0);
11236
11237 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11238 {
11239 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11240 error (_("Could not disable branch tracing for %s: %s"),
11241 target_pid_to_str (tinfo->ptid), rs->buf + 2);
11242 else
11243 error (_("Could not disable branch tracing for %s."),
11244 target_pid_to_str (tinfo->ptid));
11245 }
11246
11247 xfree (tinfo);
11248}
11249
11250/* Teardown branch tracing. */
11251
11252static void
11253remote_teardown_btrace (struct btrace_target_info *tinfo)
11254{
11255 /* We must not talk to the target during teardown. */
11256 xfree (tinfo);
11257}
11258
11259/* Read the branch trace. */
11260
11261static VEC (btrace_block_s) *
11262remote_read_btrace (struct btrace_target_info *tinfo,
11263 enum btrace_read_type type)
11264{
11265 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11266 struct remote_state *rs = get_remote_state ();
11267 VEC (btrace_block_s) *btrace = NULL;
11268 const char *annex;
11269 char *xml;
11270
11271 if (packet->support != PACKET_ENABLE)
11272 error (_("Target does not support branch tracing."));
11273
11274#if !defined(HAVE_LIBEXPAT)
11275 error (_("Cannot process branch tracing result. XML parsing not supported."));
11276#endif
11277
11278 switch (type)
11279 {
11280 case btrace_read_all:
11281 annex = "all";
11282 break;
11283 case btrace_read_new:
11284 annex = "new";
11285 break;
11286 default:
11287 internal_error (__FILE__, __LINE__,
11288 _("Bad branch tracing read type: %u."),
11289 (unsigned int) type);
11290 }
11291
11292 xml = target_read_stralloc (&current_target,
11293 TARGET_OBJECT_BTRACE, annex);
11294 if (xml != NULL)
11295 {
11296 struct cleanup *cleanup = make_cleanup (xfree, xml);
11297
11298 btrace = parse_xml_btrace (xml);
11299 do_cleanups (cleanup);
11300 }
11301
11302 return btrace;
11303}
11304
c906108c 11305static void
fba45db2 11306init_remote_ops (void)
c906108c 11307{
c5aa993b 11308 remote_ops.to_shortname = "remote";
c906108c 11309 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 11310 remote_ops.to_doc =
c906108c 11311 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
11312Specify the serial device it is connected to\n\
11313(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
11314 remote_ops.to_open = remote_open;
11315 remote_ops.to_close = remote_close;
c906108c 11316 remote_ops.to_detach = remote_detach;
6ad8ae5c 11317 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 11318 remote_ops.to_resume = remote_resume;
c906108c
SS
11319 remote_ops.to_wait = remote_wait;
11320 remote_ops.to_fetch_registers = remote_fetch_registers;
11321 remote_ops.to_store_registers = remote_store_registers;
11322 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c8e73a31 11323 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
c5aa993b 11324 remote_ops.to_files_info = remote_files_info;
c906108c
SS
11325 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11326 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
3c3bea1c
GS
11327 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11328 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
11329 remote_ops.to_watchpoint_addr_within_range =
11330 remote_watchpoint_addr_within_range;
3c3bea1c
GS
11331 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11332 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11333 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
11334 remote_ops.to_region_ok_for_hw_watchpoint
11335 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
11336 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11337 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b
JM
11338 remote_ops.to_kill = remote_kill;
11339 remote_ops.to_load = generic_load;
c906108c 11340 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 11341 remote_ops.to_pass_signals = remote_pass_signals;
9b224c5e 11342 remote_ops.to_program_signals = remote_program_signals;
c906108c 11343 remote_ops.to_thread_alive = remote_thread_alive;
0f71a2f6 11344 remote_ops.to_find_new_threads = remote_threads_info;
0caabb7e 11345 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 11346 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 11347 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 11348 remote_ops.to_stop = remote_stop;
4b8a223f 11349 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 11350 remote_ops.to_rcmd = remote_rcmd;
49d03eab 11351 remote_ops.to_log_command = serial_log_command;
38691318 11352 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 11353 remote_ops.to_stratum = process_stratum;
c35b1492
PA
11354 remote_ops.to_has_all_memory = default_child_has_all_memory;
11355 remote_ops.to_has_memory = default_child_has_memory;
11356 remote_ops.to_has_stack = default_child_has_stack;
11357 remote_ops.to_has_registers = default_child_has_registers;
11358 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 11359 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 11360 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 11361 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 11362 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
11363 remote_ops.to_flash_erase = remote_flash_erase;
11364 remote_ops.to_flash_done = remote_flash_done;
29709017 11365 remote_ops.to_read_description = remote_read_description;
08388c79 11366 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
11367 remote_ops.to_can_async_p = remote_can_async_p;
11368 remote_ops.to_is_async_p = remote_is_async_p;
11369 remote_ops.to_async = remote_async;
75c99385
PA
11370 remote_ops.to_terminal_inferior = remote_terminal_inferior;
11371 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 11372 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 11373 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
11374 remote_ops.to_supports_disable_randomization
11375 = remote_supports_disable_randomization;
7313baad
UW
11376 remote_ops.to_fileio_open = remote_hostio_open;
11377 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11378 remote_ops.to_fileio_pread = remote_hostio_pread;
11379 remote_ops.to_fileio_close = remote_hostio_close;
11380 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 11381 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 11382 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 11383 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 11384 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 11385 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
11386 remote_ops.to_trace_init = remote_trace_init;
11387 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 11388 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
11389 remote_ops.to_download_trace_state_variable
11390 = remote_download_trace_state_variable;
d248b706
KY
11391 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11392 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
11393 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11394 remote_ops.to_trace_start = remote_trace_start;
11395 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 11396 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
11397 remote_ops.to_trace_stop = remote_trace_stop;
11398 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
11399 remote_ops.to_get_trace_state_variable_value
11400 = remote_get_trace_state_variable_value;
00bf0b85
SS
11401 remote_ops.to_save_trace_data = remote_save_trace_data;
11402 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
11403 remote_ops.to_upload_trace_state_variables
11404 = remote_upload_trace_state_variables;
00bf0b85 11405 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 11406 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 11407 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 11408 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 11409 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 11410 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 11411 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 11412 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 11413 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 11414 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
11415 remote_ops.to_static_tracepoint_marker_at
11416 = remote_static_tracepoint_marker_at;
11417 remote_ops.to_static_tracepoint_markers_by_strid
11418 = remote_static_tracepoint_markers_by_strid;
b3b9301e 11419 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
11420 remote_ops.to_use_agent = remote_use_agent;
11421 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
11422 remote_ops.to_supports_btrace = remote_supports_btrace;
11423 remote_ops.to_enable_btrace = remote_enable_btrace;
11424 remote_ops.to_disable_btrace = remote_disable_btrace;
11425 remote_ops.to_teardown_btrace = remote_teardown_btrace;
11426 remote_ops.to_read_btrace = remote_read_btrace;
c906108c
SS
11427}
11428
11429/* Set up the extended remote vector by making a copy of the standard
11430 remote vector and adding to it. */
11431
11432static void
fba45db2 11433init_extended_remote_ops (void)
c906108c
SS
11434{
11435 extended_remote_ops = remote_ops;
11436
0f71a2f6 11437 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 11438 extended_remote_ops.to_longname =
c906108c 11439 "Extended remote serial target in gdb-specific protocol";
c5aa993b 11440 extended_remote_ops.to_doc =
c906108c 11441 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
11442Specify the serial device it is connected to (e.g. /dev/ttya).";
11443 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
11444 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11445 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
11446 extended_remote_ops.to_detach = extended_remote_detach;
11447 extended_remote_ops.to_attach = extended_remote_attach;
82f73884 11448 extended_remote_ops.to_kill = extended_remote_kill;
03583c20
UW
11449 extended_remote_ops.to_supports_disable_randomization
11450 = extended_remote_supports_disable_randomization;
0f71a2f6
JM
11451}
11452
6426a772
JM
11453static int
11454remote_can_async_p (void)
11455{
c6ebd6cf 11456 if (!target_async_permitted)
75c99385
PA
11457 /* We only enable async when the user specifically asks for it. */
11458 return 0;
11459
23860348 11460 /* We're async whenever the serial device is. */
3dd5b83d 11461 return serial_can_async_p (remote_desc);
6426a772
JM
11462}
11463
11464static int
11465remote_is_async_p (void)
11466{
c6ebd6cf 11467 if (!target_async_permitted)
75c99385
PA
11468 /* We only enable async when the user specifically asks for it. */
11469 return 0;
11470
23860348 11471 /* We're async whenever the serial device is. */
3dd5b83d 11472 return serial_is_async_p (remote_desc);
6426a772
JM
11473}
11474
2acceee2
JM
11475/* Pass the SERIAL event on and up to the client. One day this code
11476 will be able to delay notifying the client of an event until the
23860348 11477 point where an entire packet has been received. */
2acceee2 11478
2bc416ba 11479static void (*async_client_callback) (enum inferior_event_type event_type,
23860348 11480 void *context);
2acceee2
JM
11481static void *async_client_context;
11482static serial_event_ftype remote_async_serial_handler;
11483
6426a772 11484static void
819cc324 11485remote_async_serial_handler (struct serial *scb, void *context)
6426a772 11486{
2acceee2
JM
11487 /* Don't propogate error information up to the client. Instead let
11488 the client find out about the error by querying the target. */
11489 async_client_callback (INF_REG_EVENT, async_client_context);
11490}
11491
74531fed
PA
11492static void
11493remote_async_inferior_event_handler (gdb_client_data data)
11494{
11495 inferior_event_handler (INF_REG_EVENT, NULL);
11496}
11497
2acceee2 11498static void
2bc416ba 11499remote_async (void (*callback) (enum inferior_event_type event_type,
23860348 11500 void *context), void *context)
2acceee2
JM
11501{
11502 if (callback != NULL)
11503 {
2cd58942 11504 serial_async (remote_desc, remote_async_serial_handler, NULL);
2acceee2
JM
11505 async_client_callback = callback;
11506 async_client_context = context;
11507 }
11508 else
2cd58942 11509 serial_async (remote_desc, NULL, NULL);
6426a772
JM
11510}
11511
5a2468f5 11512static void
c2d11a7d 11513set_remote_cmd (char *args, int from_tty)
5a2468f5 11514{
427c3a89 11515 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
5a2468f5
JM
11516}
11517
d471ea57
AC
11518static void
11519show_remote_cmd (char *args, int from_tty)
11520{
37a105a1 11521 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 11522 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
11523 struct cleanup *showlist_chain;
11524 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 11525 struct ui_out *uiout = current_uiout;
37a105a1
DJ
11526
11527 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
11528 for (; list != NULL; list = list->next)
11529 if (strcmp (list->name, "Z-packet") == 0)
11530 continue;
427c3a89
DJ
11531 else if (list->type == not_set_cmd)
11532 /* Alias commands are exactly like the original, except they
11533 don't have the normal type. */
11534 continue;
11535 else
37a105a1
DJ
11536 {
11537 struct cleanup *option_chain
11538 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 11539
37a105a1
DJ
11540 ui_out_field_string (uiout, "name", list->name);
11541 ui_out_text (uiout, ": ");
427c3a89 11542 if (list->type == show_cmd)
5b9afe8a 11543 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
11544 else
11545 cmd_func (list, NULL, from_tty);
37a105a1
DJ
11546 /* Close the tuple. */
11547 do_cleanups (option_chain);
11548 }
427c3a89
DJ
11549
11550 /* Close the tuple. */
11551 do_cleanups (showlist_chain);
d471ea57 11552}
5a2468f5 11553
0f71a2f6 11554
23860348 11555/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
11556static void
11557remote_new_objfile (struct objfile *objfile)
11558{
23860348 11559 if (remote_desc != 0) /* Have a remote connection. */
06d3b283 11560 remote_check_symbols (objfile);
dc8acb97
MS
11561}
11562
00bf0b85
SS
11563/* Pull all the tracepoints defined on the target and create local
11564 data structures representing them. We don't want to create real
11565 tracepoints yet, we don't want to mess up the user's existing
11566 collection. */
11567
11568static int
11569remote_upload_tracepoints (struct uploaded_tp **utpp)
d5551862 11570{
00bf0b85
SS
11571 struct remote_state *rs = get_remote_state ();
11572 char *p;
d5551862 11573
00bf0b85
SS
11574 /* Ask for a first packet of tracepoint definition. */
11575 putpkt ("qTfP");
11576 getpkt (&rs->buf, &rs->buf_size, 0);
11577 p = rs->buf;
11578 while (*p && *p != 'l')
d5551862 11579 {
00bf0b85
SS
11580 parse_tracepoint_definition (p, utpp);
11581 /* Ask for another packet of tracepoint definition. */
11582 putpkt ("qTsP");
11583 getpkt (&rs->buf, &rs->buf_size, 0);
11584 p = rs->buf;
d5551862 11585 }
00bf0b85 11586 return 0;
d5551862
SS
11587}
11588
00bf0b85
SS
11589static int
11590remote_upload_trace_state_variables (struct uploaded_tsv **utsvp)
d5551862 11591{
00bf0b85 11592 struct remote_state *rs = get_remote_state ();
d5551862 11593 char *p;
d5551862 11594
00bf0b85
SS
11595 /* Ask for a first packet of variable definition. */
11596 putpkt ("qTfV");
d5551862
SS
11597 getpkt (&rs->buf, &rs->buf_size, 0);
11598 p = rs->buf;
00bf0b85 11599 while (*p && *p != 'l')
d5551862 11600 {
00bf0b85
SS
11601 parse_tsv_definition (p, utsvp);
11602 /* Ask for another packet of variable definition. */
11603 putpkt ("qTsV");
d5551862
SS
11604 getpkt (&rs->buf, &rs->buf_size, 0);
11605 p = rs->buf;
11606 }
00bf0b85 11607 return 0;
d5551862
SS
11608}
11609
c906108c 11610void
fba45db2 11611_initialize_remote (void)
c906108c 11612{
ea9c271d 11613 struct remote_state *rs;
9a7071a8
JB
11614 struct cmd_list_element *cmd;
11615 char *cmd_name;
ea9c271d 11616
0f71a2f6 11617 /* architecture specific data */
2bc416ba 11618 remote_gdbarch_data_handle =
23860348 11619 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
11620 remote_g_packet_data_handle =
11621 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 11622
ea9c271d
DJ
11623 /* Initialize the per-target state. At the moment there is only one
11624 of these, not one per target. Only one target is active at a
11625 time. The default buffer size is unimportant; it will be expanded
11626 whenever a larger buffer is needed. */
0b83947e 11627 rs = get_remote_state_raw ();
ea9c271d
DJ
11628 rs->buf_size = 400;
11629 rs->buf = xmalloc (rs->buf_size);
11630
c906108c
SS
11631 init_remote_ops ();
11632 add_target (&remote_ops);
11633
11634 init_extended_remote_ops ();
11635 add_target (&extended_remote_ops);
cce74817 11636
dc8acb97 11637 /* Hook into new objfile notification. */
06d3b283 11638 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
11639 /* We're no longer interested in notification events of an inferior
11640 when it exits. */
11641 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 11642
b803fb0f
DJ
11643 /* Set up signal handlers. */
11644 sigint_remote_token =
11645 create_async_signal_handler (async_remote_interrupt, NULL);
11646 sigint_remote_twice_token =
6d549500 11647 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 11648
c906108c
SS
11649#if 0
11650 init_remote_threadtests ();
11651#endif
11652
722247f1 11653 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 11654 /* set/show remote ... */
d471ea57 11655
1bedd215 11656 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
11657Remote protocol specific variables\n\
11658Configure various remote-protocol specific variables such as\n\
1bedd215 11659the packets being used"),
cff3e48b 11660 &remote_set_cmdlist, "set remote ",
23860348 11661 0 /* allow-unknown */, &setlist);
1bedd215 11662 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
11663Remote protocol specific variables\n\
11664Configure various remote-protocol specific variables such as\n\
1bedd215 11665the packets being used"),
cff3e48b 11666 &remote_show_cmdlist, "show remote ",
23860348 11667 0 /* allow-unknown */, &showlist);
5a2468f5 11668
1a966eab
AC
11669 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
11670Compare section data on target to the exec file.\n\
11671Argument is a single section name (default: all loaded sections)."),
c906108c
SS
11672 &cmdlist);
11673
1a966eab
AC
11674 add_cmd ("packet", class_maintenance, packet_command, _("\
11675Send an arbitrary packet to a remote target.\n\
c906108c
SS
11676 maintenance packet TEXT\n\
11677If GDB is talking to an inferior via the GDB serial protocol, then\n\
11678this command sends the string TEXT to the inferior, and displays the\n\
11679response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 11680terminating `#' character and checksum."),
c906108c
SS
11681 &maintenancelist);
11682
7915a72c
AC
11683 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
11684Set whether to send break if interrupted."), _("\
11685Show whether to send break if interrupted."), _("\
11686If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 11687 set_remotebreak, show_remotebreak,
e707bbc2 11688 &setlist, &showlist);
9a7071a8
JB
11689 cmd_name = "remotebreak";
11690 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
11691 deprecate_cmd (cmd, "set remote interrupt-sequence");
11692 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
11693 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
11694 deprecate_cmd (cmd, "show remote interrupt-sequence");
11695
11696 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
11697 interrupt_sequence_modes, &interrupt_sequence_mode,
11698 _("\
9a7071a8
JB
11699Set interrupt sequence to remote target."), _("\
11700Show interrupt sequence to remote target."), _("\
11701Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
11702 NULL, show_interrupt_sequence,
11703 &remote_set_cmdlist,
11704 &remote_show_cmdlist);
11705
11706 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
11707 &interrupt_on_connect, _("\
11708Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11709Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11710If set, interrupt sequence is sent to remote target."),
11711 NULL, NULL,
11712 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 11713
23860348 11714 /* Install commands for configuring memory read/write packets. */
11cf8741 11715
1a966eab
AC
11716 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
11717Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 11718 &setlist);
1a966eab
AC
11719 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
11720Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
11721 &showlist);
11722 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
11723 set_memory_write_packet_size, _("\
11724Set the maximum number of bytes per memory-write packet.\n\
11725Specify the number of bytes in a packet or 0 (zero) for the\n\
11726default packet size. The actual limit is further reduced\n\
11727dependent on the target. Specify ``fixed'' to disable the\n\
11728further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
11729 &remote_set_cmdlist);
11730 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
11731 set_memory_read_packet_size, _("\
11732Set the maximum number of bytes per memory-read packet.\n\
11733Specify the number of bytes in a packet or 0 (zero) for the\n\
11734default packet size. The actual limit is further reduced\n\
11735dependent on the target. Specify ``fixed'' to disable the\n\
11736further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
11737 &remote_set_cmdlist);
11738 add_cmd ("memory-write-packet-size", no_class,
11739 show_memory_write_packet_size,
1a966eab 11740 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
11741 &remote_show_cmdlist);
11742 add_cmd ("memory-read-packet-size", no_class,
11743 show_memory_read_packet_size,
1a966eab 11744 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 11745 &remote_show_cmdlist);
c906108c 11746
b3f42336 11747 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
11748 &remote_hw_watchpoint_limit, _("\
11749Set the maximum number of target hardware watchpoints."), _("\
11750Show the maximum number of target hardware watchpoints."), _("\
11751Specify a negative limit for unlimited."),
3e43a32a
MS
11752 NULL, NULL, /* FIXME: i18n: The maximum
11753 number of target hardware
11754 watchpoints is %s. */
b3f42336 11755 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
11756 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
11757 &remote_hw_watchpoint_length_limit, _("\
11758Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
11759Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
11760Specify a negative limit for unlimited."),
11761 NULL, NULL, /* FIXME: i18n: The maximum
11762 length (in bytes) of a target
11763 hardware watchpoint is %s. */
11764 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 11765 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
11766 &remote_hw_breakpoint_limit, _("\
11767Set the maximum number of target hardware breakpoints."), _("\
11768Show the maximum number of target hardware breakpoints."), _("\
11769Specify a negative limit for unlimited."),
3e43a32a
MS
11770 NULL, NULL, /* FIXME: i18n: The maximum
11771 number of target hardware
11772 breakpoints is %s. */
b3f42336 11773 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 11774
883b9c6c
YQ
11775 add_setshow_uinteger_cmd ("remoteaddresssize", class_obscure,
11776 &remote_address_size, _("\
4d28ad1e
AC
11777Set the maximum size of the address (in bits) in a memory packet."), _("\
11778Show the maximum size of the address (in bits) in a memory packet."), NULL,
883b9c6c
YQ
11779 NULL,
11780 NULL, /* FIXME: i18n: */
11781 &setlist, &showlist);
c906108c 11782
444abaca 11783 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 11784 "X", "binary-download", 1);
0f71a2f6 11785
444abaca 11786 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 11787 "vCont", "verbose-resume", 0);
506fb367 11788
89be2091
DJ
11789 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
11790 "QPassSignals", "pass-signals", 0);
11791
9b224c5e
PA
11792 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
11793 "QProgramSignals", "program-signals", 0);
11794
444abaca 11795 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 11796 "qSymbol", "symbol-lookup", 0);
dc8acb97 11797
444abaca 11798 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 11799 "P", "set-register", 1);
d471ea57 11800
444abaca 11801 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 11802 "p", "fetch-register", 1);
b96ec7ac 11803
444abaca 11804 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 11805 "Z0", "software-breakpoint", 0);
d471ea57 11806
444abaca 11807 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 11808 "Z1", "hardware-breakpoint", 0);
d471ea57 11809
444abaca 11810 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 11811 "Z2", "write-watchpoint", 0);
d471ea57 11812
444abaca 11813 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 11814 "Z3", "read-watchpoint", 0);
d471ea57 11815
444abaca 11816 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 11817 "Z4", "access-watchpoint", 0);
d471ea57 11818
0876f84a
DJ
11819 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
11820 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 11821
23181151
DJ
11822 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
11823 "qXfer:features:read", "target-features", 0);
11824
cfa9d6d9
DJ
11825 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
11826 "qXfer:libraries:read", "library-info", 0);
11827
2268b414
JK
11828 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
11829 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
11830
fd79ecee
DJ
11831 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
11832 "qXfer:memory-map:read", "memory-map", 0);
11833
0e7f50da
UW
11834 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
11835 "qXfer:spu:read", "read-spu-object", 0);
11836
11837 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
11838 "qXfer:spu:write", "write-spu-object", 0);
11839
07e059b5
VP
11840 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
11841 "qXfer:osdata:read", "osdata", 0);
11842
dc146f7c
VP
11843 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
11844 "qXfer:threads:read", "threads", 0);
11845
4aa995e1
PA
11846 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
11847 "qXfer:siginfo:read", "read-siginfo-object", 0);
11848
11849 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
11850 "qXfer:siginfo:write", "write-siginfo-object", 0);
11851
b3b9301e
PA
11852 add_packet_config_cmd
11853 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
11854 "qXfer:trace-frame-info:read", "traceframe-info", 0);
11855
169081d0
TG
11856 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
11857 "qXfer:uib:read", "unwind-info-block", 0);
11858
444abaca 11859 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 11860 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
11861 0);
11862
711e434b
PM
11863 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
11864 "qGetTIBAddr", "get-thread-information-block-address",
11865 0);
11866
40ab02ce
MS
11867 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
11868 "bc", "reverse-continue", 0);
11869
11870 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
11871 "bs", "reverse-step", 0);
11872
be2a5f71
DJ
11873 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
11874 "qSupported", "supported-packets", 0);
11875
08388c79
DE
11876 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
11877 "qSearch:memory", "search-memory", 0);
11878
a6b151f1
DJ
11879 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
11880 "vFile:open", "hostio-open", 0);
11881
11882 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
11883 "vFile:pread", "hostio-pread", 0);
11884
11885 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
11886 "vFile:pwrite", "hostio-pwrite", 0);
11887
11888 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
11889 "vFile:close", "hostio-close", 0);
11890
11891 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
11892 "vFile:unlink", "hostio-unlink", 0);
11893
b9e7b9c3
UW
11894 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
11895 "vFile:readlink", "hostio-readlink", 0);
11896
2d717e4f
DJ
11897 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
11898 "vAttach", "attach", 0);
11899
11900 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
11901 "vRun", "run", 0);
11902
a6f3e723
SL
11903 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
11904 "QStartNoAckMode", "noack", 0);
11905
82f73884
PA
11906 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
11907 "vKill", "kill", 0);
11908
0b16c5cf
PA
11909 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
11910 "qAttached", "query-attached", 0);
11911
782b2b07 11912 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
11913 "ConditionalTracepoints",
11914 "conditional-tracepoints", 0);
3788aec7
LM
11915
11916 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
11917 "ConditionalBreakpoints",
11918 "conditional-breakpoints", 0);
11919
d3ce09f5
SS
11920 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
11921 "BreakpointCommands",
11922 "breakpoint-commands", 0);
11923
7a697b8d
SS
11924 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
11925 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 11926
409873ef
SS
11927 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
11928 "TracepointSource", "TracepointSource", 0);
11929
d914c394
SS
11930 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
11931 "QAllow", "allow", 0);
11932
0fb4aa4b
PA
11933 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
11934 "StaticTracepoints", "static-tracepoints", 0);
11935
1e4d1764
YQ
11936 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
11937 "InstallInTrace", "install-in-trace", 0);
11938
0fb4aa4b
PA
11939 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
11940 "qXfer:statictrace:read", "read-sdata-object", 0);
11941
78d85199
YQ
11942 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
11943 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
11944
03583c20
UW
11945 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
11946 "QDisableRandomization", "disable-randomization", 0);
11947
d1feda86
YQ
11948 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
11949 "QAgent", "agent", 0);
11950
f6f899bf
HAQ
11951 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
11952 "QTBuffer:size", "trace-buffer-size", 0);
11953
9accd112
MM
11954 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
11955 "Qbtrace:off", "disable-btrace", 0);
11956
11957 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
11958 "Qbtrace:bts", "enable-btrace", 0);
11959
11960 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
11961 "qXfer:btrace", "read-btrace", 0);
11962
37a105a1
DJ
11963 /* Keep the old ``set remote Z-packet ...'' working. Each individual
11964 Z sub-packet has its own set and show commands, but users may
11965 have sets to this variable in their .gdbinit files (or in their
11966 documentation). */
e9e68a56 11967 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
11968 &remote_Z_packet_detect, _("\
11969Set use of remote protocol `Z' packets"), _("\
11970Show use of remote protocol `Z' packets "), _("\
3b64bf98 11971When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 11972packets."),
e9e68a56 11973 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
11974 show_remote_protocol_Z_packet_cmd,
11975 /* FIXME: i18n: Use of remote protocol
11976 `Z' packets is %s. */
e9e68a56 11977 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 11978
a6b151f1
DJ
11979 add_prefix_cmd ("remote", class_files, remote_command, _("\
11980Manipulate files on the remote system\n\
11981Transfer files to and from the remote target system."),
11982 &remote_cmdlist, "remote ",
11983 0 /* allow-unknown */, &cmdlist);
11984
11985 add_cmd ("put", class_files, remote_put_command,
11986 _("Copy a local file to the remote system."),
11987 &remote_cmdlist);
11988
11989 add_cmd ("get", class_files, remote_get_command,
11990 _("Copy a remote file to the local system."),
11991 &remote_cmdlist);
11992
11993 add_cmd ("delete", class_files, remote_delete_command,
11994 _("Delete a remote file."),
11995 &remote_cmdlist);
11996
2d717e4f
DJ
11997 remote_exec_file = xstrdup ("");
11998 add_setshow_string_noescape_cmd ("exec-file", class_files,
11999 &remote_exec_file, _("\
12000Set the remote pathname for \"run\""), _("\
12001Show the remote pathname for \"run\""), NULL, NULL, NULL,
12002 &remote_set_cmdlist, &remote_show_cmdlist);
12003
449092f6
CV
12004 /* Eventually initialize fileio. See fileio.c */
12005 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229
PA
12006
12007 /* Take advantage of the fact that the LWP field is not used, to tag
12008 special ptids with it set to != 0. */
82f73884
PA
12009 magic_null_ptid = ptid_build (42000, 1, -1);
12010 not_sent_ptid = ptid_build (42000, 1, -2);
12011 any_thread_ptid = ptid_build (42000, 1, 0);
35b1e5cc
SS
12012
12013 target_buf_size = 2048;
12014 target_buf = xmalloc (target_buf_size);
c906108c 12015}
10760264 12016