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