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