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