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