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