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