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