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