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