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