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