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