* breakpoint.c (moribund_locations): New.
[deliverable/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
6aba47ca 3 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
9b254dd1 4 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
29182b13 5 Free Software Foundation, Inc.
c906108c 6
c5aa993b
JM
7 This file is part of GDB.
8
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
a9762ec7 11 the Free Software Foundation; either version 3 of the License, or
c5aa993b
JM
12 (at your option) any later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
a9762ec7 20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5aa993b 21
23860348 22/* See the GDB User Guide for details of the GDB remote protocol. */
c5aa993b 23
c906108c
SS
24#include "defs.h"
25#include "gdb_string.h"
26#include <ctype.h>
27#include <fcntl.h>
c906108c
SS
28#include "inferior.h"
29#include "bfd.h"
30#include "symfile.h"
60250e8b 31#include "exceptions.h"
c906108c 32#include "target.h"
c5aa993b 33/*#include "terminal.h" */
c906108c
SS
34#include "gdbcmd.h"
35#include "objfiles.h"
36#include "gdb-stabs.h"
37#include "gdbthread.h"
c2c6d25f 38#include "remote.h"
4e052eda 39#include "regcache.h"
fd0407d6 40#include "value.h"
1ff9c3d6 41#include "gdb_assert.h"
6867ae3e 42#include "observer.h"
a77053c2 43#include "solib.h"
37a105a1
DJ
44#include "cli/cli-decode.h"
45#include "cli/cli-setshow.h"
424163ea 46#include "target-descriptions.h"
c906108c 47
7a292a7a 48#include <ctype.h>
9846de1b 49#include <sys/time.h>
c906108c 50
43ff13b4 51#include "event-loop.h"
c2c6d25f 52#include "event-top.h"
2acceee2 53#include "inf-loop.h"
43ff13b4 54
c906108c
SS
55#include <signal.h>
56#include "serial.h"
57
6240bebf
MS
58#include "gdbcore.h" /* for exec_bfd */
59
449092f6 60#include "remote-fileio.h"
a6b151f1 61#include "gdb/fileio.h"
449092f6 62
fd79ecee
DJ
63#include "memory-map.h"
64
6765f3e5
DJ
65/* The size to align memory write packets, when practical. The protocol
66 does not guarantee any alignment, and gdb will generate short
67 writes and unaligned writes, but even as a best-effort attempt this
68 can improve bulk transfers. For instance, if a write is misaligned
69 relative to the target's data bus, the stub may need to make an extra
70 round trip fetching data from the target. This doesn't make a
71 huge difference, but it's easy to do, so we try to be helpful.
72
73 The alignment chosen is arbitrary; usually data bus width is
74 important here, not the possibly larger cache line size. */
75enum { REMOTE_ALIGN_WRITES = 16 };
76
23860348 77/* Prototypes for local functions. */
6426a772
JM
78static void cleanup_sigint_signal_handler (void *dummy);
79static void initialize_sigint_signal_handler (void);
6d820c5c 80static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
6426a772 81
a14ed312
KB
82static void handle_remote_sigint (int);
83static void handle_remote_sigint_twice (int);
84static void async_remote_interrupt (gdb_client_data);
85void async_remote_interrupt_twice (gdb_client_data);
43ff13b4 86
a14ed312 87static void remote_files_info (struct target_ops *ignore);
c906108c 88
316f2060 89static void remote_prepare_to_store (struct regcache *regcache);
c906108c 90
56be3814 91static void remote_fetch_registers (struct regcache *regcache, int regno);
c906108c 92
39f77062
KB
93static void remote_resume (ptid_t ptid, int step,
94 enum target_signal siggnal);
a14ed312 95static void remote_open (char *name, int from_tty);
c906108c 96
a14ed312 97static void extended_remote_open (char *name, int from_tty);
c906108c 98
75c99385 99static void remote_open_1 (char *, int, struct target_ops *, int extended_p);
c906108c 100
a14ed312 101static void remote_close (int quitting);
c906108c 102
56be3814 103static void remote_store_registers (struct regcache *regcache, int regno);
c906108c 104
a14ed312 105static void remote_mourn (void);
c906108c 106
a14ed312 107static void extended_remote_restart (void);
c906108c 108
a14ed312 109static void extended_remote_mourn (void);
c906108c 110
a14ed312 111static void remote_mourn_1 (struct target_ops *);
c906108c 112
6d820c5c 113static void remote_send (char **buf, long *sizeof_buf_p);
c906108c 114
a14ed312 115static int readchar (int timeout);
c906108c 116
39f77062 117static ptid_t remote_wait (ptid_t ptid,
75c99385 118 struct target_waitstatus *status);
c906108c 119
a14ed312 120static void remote_kill (void);
c906108c 121
a14ed312 122static int tohex (int nib);
c906108c 123
75c99385
PA
124static int remote_can_async_p (void);
125
126static int remote_is_async_p (void);
127
128static void remote_async (void (*callback) (enum inferior_event_type event_type,
129 void *context), void *context);
130
131static int remote_async_mask (int new_mask);
132
a14ed312 133static void remote_detach (char *args, int from_tty);
c906108c 134
a14ed312 135static void remote_interrupt (int signo);
c906108c 136
a14ed312 137static void remote_interrupt_twice (int signo);
7a292a7a 138
a14ed312 139static void interrupt_query (void);
c906108c 140
79d7f229
PA
141static void set_general_thread (struct ptid ptid);
142static void set_continue_thread (struct ptid ptid);
c906108c 143
39f77062 144static int remote_thread_alive (ptid_t);
c906108c 145
a14ed312 146static void get_offsets (void);
c906108c 147
6d820c5c
DJ
148static void skip_frame (void);
149
150static long read_frame (char **buf_p, long *sizeof_buf);
c906108c 151
a14ed312 152static int hexnumlen (ULONGEST num);
c906108c 153
a14ed312 154static void init_remote_ops (void);
c906108c 155
a14ed312 156static void init_extended_remote_ops (void);
c906108c 157
a14ed312 158static void remote_stop (void);
c906108c 159
a14ed312 160static int ishex (int ch, int *val);
c906108c 161
a14ed312 162static int stubhex (int ch);
c906108c 163
a14ed312 164static int hexnumstr (char *, ULONGEST);
c906108c 165
a14ed312 166static int hexnumnstr (char *, ULONGEST, int);
2df3850c 167
a14ed312 168static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 169
a14ed312 170static void print_packet (char *);
c906108c 171
a14ed312 172static unsigned long crc32 (unsigned char *, int, unsigned int);
c906108c 173
a14ed312 174static void compare_sections_command (char *, int);
c906108c 175
a14ed312 176static void packet_command (char *, int);
c906108c 177
a14ed312 178static int stub_unpack_int (char *buff, int fieldlength);
c906108c 179
39f77062 180static ptid_t remote_current_thread (ptid_t oldptid);
c906108c 181
a14ed312 182static void remote_find_new_threads (void);
c906108c 183
79d7f229 184static void record_currthread (ptid_t currthread);
c906108c 185
30559e10 186static int fromhex (int a);
c906108c 187
cfd77fa1 188static int hex2bin (const char *hex, gdb_byte *bin, int count);
c906108c 189
cfd77fa1 190static int bin2hex (const gdb_byte *bin, char *hex, int count);
234fa6d1 191
a14ed312 192static int putpkt_binary (char *buf, int cnt);
c906108c 193
a14ed312 194static void check_binary_download (CORE_ADDR addr);
c906108c 195
5a2468f5 196struct packet_config;
5a2468f5 197
a14ed312 198static void show_packet_config_cmd (struct packet_config *config);
5a2468f5 199
d471ea57 200static void update_packet_config (struct packet_config *config);
5a2468f5 201
bb572ddd
DJ
202static void set_remote_protocol_packet_cmd (char *args, int from_tty,
203 struct cmd_list_element *c);
204
205static void show_remote_protocol_packet_cmd (struct ui_file *file,
206 int from_tty,
207 struct cmd_list_element *c,
208 const char *value);
209
a14ed312 210void _initialize_remote (void);
c906108c 211
75c99385
PA
212/* Controls if async mode is permitted. */
213static int remote_async_permitted = 0;
214
215static int remote_async_permitted_set = 0;
216
217static void
218set_maintenance_remote_async_permitted (char *args, int from_tty,
219 struct cmd_list_element *c)
220{
221 if (target_has_execution)
222 {
223 remote_async_permitted_set = remote_async_permitted; /* revert */
224 error (_("Cannot change this setting while the inferior is running."));
225 }
226
227 remote_async_permitted = remote_async_permitted_set;
228}
229
230static void
231show_maintenance_remote_async_permitted (struct ui_file *file, int from_tty,
232 struct cmd_list_element *c, const char *value)
233{
234 fprintf_filtered (file, _("\
235Controlling the remote inferior in asynchronous mode is %s.\n"),
236 value);
237}
238
a6b151f1
DJ
239/* For "remote". */
240
241static struct cmd_list_element *remote_cmdlist;
242
bb572ddd
DJ
243/* For "set remote" and "show remote". */
244
245static struct cmd_list_element *remote_set_cmdlist;
246static struct cmd_list_element *remote_show_cmdlist;
247
ea9c271d
DJ
248/* Description of the remote protocol state for the currently
249 connected target. This is per-target state, and independent of the
250 selected architecture. */
251
252struct remote_state
253{
254 /* A buffer to use for incoming packets, and its current size. The
255 buffer is grown dynamically for larger incoming packets.
256 Outgoing packets may also be constructed in this buffer.
257 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
258 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
259 packets. */
260 char *buf;
261 long buf_size;
be2a5f71
DJ
262
263 /* If we negotiated packet size explicitly (and thus can bypass
264 heuristics for the largest packet size that will not overflow
265 a buffer in the stub), this will be set to that packet size.
266 Otherwise zero, meaning to use the guessed size. */
267 long explicit_packet_size;
2d717e4f
DJ
268
269 /* remote_wait is normally called when the target is running and
270 waits for a stop reply packet. But sometimes we need to call it
271 when the target is already stopped. We can send a "?" packet
272 and have remote_wait read the response. Or, if we already have
273 the response, we can stash it in BUF and tell remote_wait to
274 skip calling getpkt. This flag is set when BUF contains a
275 stop reply packet and the target is not waiting. */
276 int cached_wait_status;
ea9c271d
DJ
277};
278
279/* This data could be associated with a target, but we do not always
280 have access to the current target when we need it, so for now it is
281 static. This will be fine for as long as only one target is in use
282 at a time. */
283static struct remote_state remote_state;
284
285static struct remote_state *
0b83947e 286get_remote_state_raw (void)
ea9c271d
DJ
287{
288 return &remote_state;
289}
290
291/* Description of the remote protocol for a given architecture. */
d01949b6 292
ad10f812
AC
293struct packet_reg
294{
295 long offset; /* Offset into G packet. */
296 long regnum; /* GDB's internal register number. */
297 LONGEST pnum; /* Remote protocol register number. */
b323314b 298 int in_g_packet; /* Always part of G packet. */
2bc416ba 299 /* long size in bytes; == register_size (current_gdbarch, regnum);
23860348 300 at present. */
c9f4d572
UW
301 /* char *name; == gdbarch_register_name (current_gdbarch, regnum);
302 at present. */
ad10f812
AC
303};
304
ea9c271d 305struct remote_arch_state
d01949b6 306{
ad10f812
AC
307 /* Description of the remote protocol registers. */
308 long sizeof_g_packet;
b323314b
AC
309
310 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 311 (making an array gdbarch_num_regs in size). */
b323314b 312 struct packet_reg *regs;
ad10f812 313
d01949b6
AC
314 /* This is the size (in chars) of the first response to the ``g''
315 packet. It is used as a heuristic when determining the maximum
316 size of memory-read and memory-write packets. A target will
317 typically only reserve a buffer large enough to hold the ``g''
318 packet. The size does not include packet overhead (headers and
23860348 319 trailers). */
d01949b6
AC
320 long actual_register_packet_size;
321
322 /* This is the maximum size (in chars) of a non read/write packet.
23860348 323 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
324 long remote_packet_size;
325};
326
3c3bea1c 327
d01949b6
AC
328/* Handle for retreving the remote protocol data from gdbarch. */
329static struct gdbarch_data *remote_gdbarch_data_handle;
330
ea9c271d
DJ
331static struct remote_arch_state *
332get_remote_arch_state (void)
d01949b6 333{
451fbdda 334 return gdbarch_data (current_gdbarch, remote_gdbarch_data_handle);
d01949b6
AC
335}
336
0b83947e
DJ
337/* Fetch the global remote target state. */
338
339static struct remote_state *
340get_remote_state (void)
341{
342 /* Make sure that the remote architecture state has been
343 initialized, because doing so might reallocate rs->buf. Any
344 function which calls getpkt also needs to be mindful of changes
345 to rs->buf, but this call limits the number of places which run
346 into trouble. */
347 get_remote_arch_state ();
348
349 return get_remote_state_raw ();
350}
351
74ca34ce
DJ
352static int
353compare_pnums (const void *lhs_, const void *rhs_)
354{
355 const struct packet_reg * const *lhs = lhs_;
356 const struct packet_reg * const *rhs = rhs_;
357
358 if ((*lhs)->pnum < (*rhs)->pnum)
359 return -1;
360 else if ((*lhs)->pnum == (*rhs)->pnum)
361 return 0;
362 else
363 return 1;
364}
365
d01949b6
AC
366static void *
367init_remote_state (struct gdbarch *gdbarch)
368{
74ca34ce 369 int regnum, num_remote_regs, offset;
0b83947e 370 struct remote_state *rs = get_remote_state_raw ();
ea9c271d 371 struct remote_arch_state *rsa;
74ca34ce 372 struct packet_reg **remote_regs;
ea9c271d
DJ
373
374 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
d01949b6 375
123dc839
DJ
376 /* Use the architecture to build a regnum<->pnum table, which will be
377 1:1 unless a feature set specifies otherwise. */
f57d151a 378 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
4a22f64d 379 gdbarch_num_regs (gdbarch),
f57d151a 380 struct packet_reg);
4a22f64d 381 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 382 {
ea9c271d 383 struct packet_reg *r = &rsa->regs[regnum];
baef701f 384
4a22f64d 385 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
386 /* Do not try to fetch zero-sized (placeholder) registers. */
387 r->pnum = -1;
388 else
389 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
390
b323314b 391 r->regnum = regnum;
74ca34ce
DJ
392 }
393
394 /* Define the g/G packet format as the contents of each register
395 with a remote protocol number, in order of ascending protocol
396 number. */
397
4a22f64d
UW
398 remote_regs = alloca (gdbarch_num_regs (gdbarch)
399 * sizeof (struct packet_reg *));
f57d151a 400 for (num_remote_regs = 0, regnum = 0;
4a22f64d 401 regnum < gdbarch_num_regs (gdbarch);
f57d151a 402 regnum++)
74ca34ce
DJ
403 if (rsa->regs[regnum].pnum != -1)
404 remote_regs[num_remote_regs++] = &rsa->regs[regnum];
7d58c67d 405
74ca34ce
DJ
406 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
407 compare_pnums);
408
409 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
410 {
411 remote_regs[regnum]->in_g_packet = 1;
412 remote_regs[regnum]->offset = offset;
4a22f64d 413 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
414 }
415
74ca34ce
DJ
416 /* Record the maximum possible size of the g packet - it may turn out
417 to be smaller. */
418 rsa->sizeof_g_packet = offset;
419
d01949b6
AC
420 /* Default maximum number of characters in a packet body. Many
421 remote stubs have a hardwired buffer size of 400 bytes
422 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
423 as the maximum packet-size to ensure that the packet and an extra
424 NUL character can always fit in the buffer. This stops GDB
425 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
426 already a full buffer (As of 1999-12-04 that was most stubs). */
427 rsa->remote_packet_size = 400 - 1;
d01949b6 428
ea9c271d
DJ
429 /* This one is filled in when a ``g'' packet is received. */
430 rsa->actual_register_packet_size = 0;
431
432 /* Should rsa->sizeof_g_packet needs more space than the
ad10f812
AC
433 default, adjust the size accordingly. Remember that each byte is
434 encoded as two characters. 32 is the overhead for the packet
435 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 436 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 437 little. */
ea9c271d
DJ
438 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
439 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 440
ea9c271d
DJ
441 /* Make sure that the packet buffer is plenty big enough for
442 this architecture. */
443 if (rs->buf_size < rsa->remote_packet_size)
444 {
445 rs->buf_size = 2 * rsa->remote_packet_size;
7fca722e 446 rs->buf = xrealloc (rs->buf, rs->buf_size);
ea9c271d 447 }
6d820c5c 448
ea9c271d
DJ
449 return rsa;
450}
451
452/* Return the current allowed size of a remote packet. This is
453 inferred from the current architecture, and should be used to
454 limit the length of outgoing packets. */
455static long
456get_remote_packet_size (void)
457{
be2a5f71 458 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
459 struct remote_arch_state *rsa = get_remote_arch_state ();
460
be2a5f71
DJ
461 if (rs->explicit_packet_size)
462 return rs->explicit_packet_size;
463
ea9c271d 464 return rsa->remote_packet_size;
d01949b6
AC
465}
466
ad10f812 467static struct packet_reg *
ea9c271d 468packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 469{
f57d151a 470 if (regnum < 0 && regnum >= gdbarch_num_regs (current_gdbarch))
b323314b
AC
471 return NULL;
472 else
ad10f812 473 {
ea9c271d 474 struct packet_reg *r = &rsa->regs[regnum];
b323314b
AC
475 gdb_assert (r->regnum == regnum);
476 return r;
ad10f812 477 }
ad10f812
AC
478}
479
480static struct packet_reg *
ea9c271d 481packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 482{
b323314b 483 int i;
f57d151a 484 for (i = 0; i < gdbarch_num_regs (current_gdbarch); i++)
ad10f812 485 {
ea9c271d 486 struct packet_reg *r = &rsa->regs[i];
b323314b
AC
487 if (r->pnum == pnum)
488 return r;
ad10f812
AC
489 }
490 return NULL;
d01949b6
AC
491}
492
3c3bea1c
GS
493/* FIXME: graces/2002-08-08: These variables should eventually be
494 bound to an instance of the target object (as in gdbarch-tdep()),
495 when such a thing exists. */
496
497/* This is set to the data address of the access causing the target
498 to stop for a watchpoint. */
499static CORE_ADDR remote_watch_data_address;
500
94e08568 501/* This is non-zero if target stopped for a watchpoint. */
3c3bea1c
GS
502static int remote_stopped_by_watchpoint_p;
503
c906108c
SS
504static struct target_ops remote_ops;
505
506static struct target_ops extended_remote_ops;
507
b84876c2
PA
508static int remote_async_mask_value = 1;
509
6426a772
JM
510/* FIXME: cagney/1999-09-23: Even though getpkt was called with
511 ``forever'' still use the normal timeout mechanism. This is
512 currently used by the ASYNC code to guarentee that target reads
513 during the initial connect always time-out. Once getpkt has been
514 modified to return a timeout indication and, in turn
515 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 516 this can go away. */
6426a772
JM
517static int wait_forever_enabled_p = 1;
518
519
c906108c
SS
520/* This variable chooses whether to send a ^C or a break when the user
521 requests program interruption. Although ^C is usually what remote
522 systems expect, and that is the default here, sometimes a break is
523 preferable instead. */
524
525static int remote_break;
526
c906108c
SS
527/* Descriptor for I/O to remote machine. Initialize it to NULL so that
528 remote_open knows that we don't have a file open when the program
529 starts. */
819cc324 530static struct serial *remote_desc = NULL;
c906108c 531
c906108c
SS
532/* This variable sets the number of bits in an address that are to be
533 sent in a memory ("M" or "m") packet. Normally, after stripping
534 leading zeros, the entire address would be sent. This variable
535 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
536 initial implementation of remote.c restricted the address sent in
537 memory packets to ``host::sizeof long'' bytes - (typically 32
538 bits). Consequently, for 64 bit targets, the upper 32 bits of an
539 address was never sent. Since fixing this bug may cause a break in
540 some remote targets this variable is principly provided to
23860348 541 facilitate backward compatibility. */
c906108c
SS
542
543static int remote_address_size;
544
75c99385
PA
545/* Temporary to track who currently owns the terminal. See
546 remote_terminal_* for more details. */
6426a772
JM
547
548static int remote_async_terminal_ours_p;
549
2d717e4f
DJ
550/* The executable file to use for "run" on the remote side. */
551
552static char *remote_exec_file = "";
553
11cf8741 554\f
11cf8741 555/* User configurable variables for the number of characters in a
ea9c271d
DJ
556 memory read/write packet. MIN (rsa->remote_packet_size,
557 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 558 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
559 (speed up transfers). The variables ``preferred_*'' (the user
560 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 561 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
562
563struct memory_packet_config
564{
565 char *name;
566 long size;
567 int fixed_p;
568};
569
570/* Compute the current size of a read/write packet. Since this makes
571 use of ``actual_register_packet_size'' the computation is dynamic. */
572
573static long
574get_memory_packet_size (struct memory_packet_config *config)
575{
d01949b6 576 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
577 struct remote_arch_state *rsa = get_remote_arch_state ();
578
11cf8741
JM
579 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
580 law?) that some hosts don't cope very well with large alloca()
581 calls. Eventually the alloca() code will be replaced by calls to
582 xmalloc() and make_cleanups() allowing this restriction to either
23860348 583 be lifted or removed. */
11cf8741
JM
584#ifndef MAX_REMOTE_PACKET_SIZE
585#define MAX_REMOTE_PACKET_SIZE 16384
586#endif
3de11b2e 587 /* NOTE: 20 ensures we can write at least one byte. */
11cf8741 588#ifndef MIN_REMOTE_PACKET_SIZE
3de11b2e 589#define MIN_REMOTE_PACKET_SIZE 20
11cf8741
JM
590#endif
591 long what_they_get;
592 if (config->fixed_p)
593 {
594 if (config->size <= 0)
595 what_they_get = MAX_REMOTE_PACKET_SIZE;
596 else
597 what_they_get = config->size;
598 }
599 else
600 {
ea9c271d 601 what_they_get = get_remote_packet_size ();
23860348 602 /* Limit the packet to the size specified by the user. */
11cf8741
JM
603 if (config->size > 0
604 && what_they_get > config->size)
605 what_they_get = config->size;
be2a5f71
DJ
606
607 /* Limit it to the size of the targets ``g'' response unless we have
608 permission from the stub to use a larger packet size. */
609 if (rs->explicit_packet_size == 0
610 && rsa->actual_register_packet_size > 0
611 && what_they_get > rsa->actual_register_packet_size)
612 what_they_get = rsa->actual_register_packet_size;
11cf8741
JM
613 }
614 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
615 what_they_get = MAX_REMOTE_PACKET_SIZE;
616 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
617 what_they_get = MIN_REMOTE_PACKET_SIZE;
6d820c5c
DJ
618
619 /* Make sure there is room in the global buffer for this packet
620 (including its trailing NUL byte). */
621 if (rs->buf_size < what_they_get + 1)
622 {
623 rs->buf_size = 2 * what_they_get;
624 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
625 }
626
11cf8741
JM
627 return what_they_get;
628}
629
630/* Update the size of a read/write packet. If they user wants
23860348 631 something really big then do a sanity check. */
11cf8741
JM
632
633static void
634set_memory_packet_size (char *args, struct memory_packet_config *config)
635{
636 int fixed_p = config->fixed_p;
637 long size = config->size;
638 if (args == NULL)
8a3fe4f8 639 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
640 else if (strcmp (args, "hard") == 0
641 || strcmp (args, "fixed") == 0)
642 fixed_p = 1;
643 else if (strcmp (args, "soft") == 0
644 || strcmp (args, "limit") == 0)
645 fixed_p = 0;
646 else
647 {
648 char *end;
649 size = strtoul (args, &end, 0);
650 if (args == end)
8a3fe4f8 651 error (_("Invalid %s (bad syntax)."), config->name);
11cf8741
JM
652#if 0
653 /* Instead of explicitly capping the size of a packet to
654 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
655 instead allowed to set the size to something arbitrarily
23860348 656 large. */
11cf8741 657 if (size > MAX_REMOTE_PACKET_SIZE)
8a3fe4f8 658 error (_("Invalid %s (too large)."), config->name);
11cf8741
JM
659#endif
660 }
23860348 661 /* Extra checks? */
11cf8741
JM
662 if (fixed_p && !config->fixed_p)
663 {
e2e0b3e5
AC
664 if (! query (_("The target may not be able to correctly handle a %s\n"
665 "of %ld bytes. Change the packet size? "),
11cf8741 666 config->name, size))
8a3fe4f8 667 error (_("Packet size not changed."));
11cf8741 668 }
23860348 669 /* Update the config. */
11cf8741
JM
670 config->fixed_p = fixed_p;
671 config->size = size;
672}
673
674static void
675show_memory_packet_size (struct memory_packet_config *config)
676{
a3f17187 677 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 678 if (config->fixed_p)
a3f17187 679 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
680 get_memory_packet_size (config));
681 else
a3f17187 682 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
683 get_memory_packet_size (config));
684}
685
686static struct memory_packet_config memory_write_packet_config =
687{
688 "memory-write-packet-size",
689};
690
691static void
692set_memory_write_packet_size (char *args, int from_tty)
693{
694 set_memory_packet_size (args, &memory_write_packet_config);
695}
696
697static void
698show_memory_write_packet_size (char *args, int from_tty)
699{
700 show_memory_packet_size (&memory_write_packet_config);
701}
702
703static long
704get_memory_write_packet_size (void)
705{
706 return get_memory_packet_size (&memory_write_packet_config);
707}
708
709static struct memory_packet_config memory_read_packet_config =
710{
711 "memory-read-packet-size",
712};
713
714static void
715set_memory_read_packet_size (char *args, int from_tty)
716{
717 set_memory_packet_size (args, &memory_read_packet_config);
718}
719
720static void
721show_memory_read_packet_size (char *args, int from_tty)
722{
723 show_memory_packet_size (&memory_read_packet_config);
724}
725
726static long
727get_memory_read_packet_size (void)
728{
729 long size = get_memory_packet_size (&memory_read_packet_config);
730 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
731 extra buffer size argument before the memory read size can be
ea9c271d
DJ
732 increased beyond this. */
733 if (size > get_remote_packet_size ())
734 size = get_remote_packet_size ();
11cf8741
JM
735 return size;
736}
737
11cf8741 738\f
5a2468f5
JM
739/* Generic configuration support for packets the stub optionally
740 supports. Allows the user to specify the use of the packet as well
23860348 741 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
742
743enum packet_support
744 {
745 PACKET_SUPPORT_UNKNOWN = 0,
746 PACKET_ENABLE,
747 PACKET_DISABLE
748 };
749
5a2468f5
JM
750struct packet_config
751 {
bb572ddd
DJ
752 const char *name;
753 const char *title;
7f19b9a2 754 enum auto_boolean detect;
5a2468f5
JM
755 enum packet_support support;
756 };
757
d471ea57 758/* Analyze a packet's return value and update the packet config
23860348 759 accordingly. */
d471ea57
AC
760
761enum packet_result
762{
763 PACKET_ERROR,
764 PACKET_OK,
765 PACKET_UNKNOWN
766};
767
5a2468f5 768static void
d471ea57 769update_packet_config (struct packet_config *config)
5a2468f5 770{
d471ea57
AC
771 switch (config->detect)
772 {
7f19b9a2 773 case AUTO_BOOLEAN_TRUE:
d471ea57
AC
774 config->support = PACKET_ENABLE;
775 break;
7f19b9a2 776 case AUTO_BOOLEAN_FALSE:
d471ea57
AC
777 config->support = PACKET_DISABLE;
778 break;
7f19b9a2 779 case AUTO_BOOLEAN_AUTO:
d471ea57
AC
780 config->support = PACKET_SUPPORT_UNKNOWN;
781 break;
782 }
5a2468f5
JM
783}
784
785static void
fba45db2 786show_packet_config_cmd (struct packet_config *config)
5a2468f5
JM
787{
788 char *support = "internal-error";
789 switch (config->support)
790 {
791 case PACKET_ENABLE:
792 support = "enabled";
793 break;
794 case PACKET_DISABLE:
795 support = "disabled";
796 break;
797 case PACKET_SUPPORT_UNKNOWN:
798 support = "unknown";
799 break;
800 }
801 switch (config->detect)
802 {
7f19b9a2 803 case AUTO_BOOLEAN_AUTO:
37a105a1
DJ
804 printf_filtered (_("Support for the `%s' packet is auto-detected, currently %s.\n"),
805 config->name, support);
5a2468f5 806 break;
7f19b9a2
AC
807 case AUTO_BOOLEAN_TRUE:
808 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
809 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
810 config->name, support);
8e248173 811 break;
5a2468f5
JM
812 }
813}
814
815static void
bb572ddd
DJ
816add_packet_config_cmd (struct packet_config *config, const char *name,
817 const char *title, int legacy)
d471ea57 818{
5a2468f5
JM
819 char *set_doc;
820 char *show_doc;
d471ea57 821 char *cmd_name;
3ed07be4 822
5a2468f5
JM
823 config->name = name;
824 config->title = title;
7f19b9a2 825 config->detect = AUTO_BOOLEAN_AUTO;
8e248173 826 config->support = PACKET_SUPPORT_UNKNOWN;
b435e160
AC
827 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
828 name, title);
829 show_doc = xstrprintf ("Show current use of remote protocol `%s' (%s) packet",
830 name, title);
d471ea57 831 /* set/show TITLE-packet {auto,on,off} */
b435e160 832 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 833 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
2c5b56ce 834 &config->detect, set_doc, show_doc, NULL, /* help_doc */
bb572ddd
DJ
835 set_remote_protocol_packet_cmd,
836 show_remote_protocol_packet_cmd,
837 &remote_set_cmdlist, &remote_show_cmdlist);
23860348 838 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
839 if (legacy)
840 {
841 char *legacy_name;
b435e160 842 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 843 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 844 &remote_set_cmdlist);
d471ea57 845 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 846 &remote_show_cmdlist);
d471ea57 847 }
5a2468f5
JM
848}
849
d471ea57 850static enum packet_result
a76d924d 851packet_check_result (const char *buf)
5a2468f5 852{
d471ea57 853 if (buf[0] != '\0')
5a2468f5 854 {
d471ea57 855 /* The stub recognized the packet request. Check that the
23860348 856 operation succeeded. */
a76d924d
DJ
857 if (buf[0] == 'E'
858 && isxdigit (buf[1]) && isxdigit (buf[2])
859 && buf[3] == '\0')
860 /* "Enn" - definitly an error. */
861 return PACKET_ERROR;
862
863 /* Always treat "E." as an error. This will be used for
864 more verbose error messages, such as E.memtypes. */
865 if (buf[0] == 'E' && buf[1] == '.')
866 return PACKET_ERROR;
867
868 /* The packet may or may not be OK. Just assume it is. */
869 return PACKET_OK;
870 }
871 else
872 /* The stub does not support the packet. */
873 return PACKET_UNKNOWN;
874}
875
876static enum packet_result
877packet_ok (const char *buf, struct packet_config *config)
878{
879 enum packet_result result;
880
881 result = packet_check_result (buf);
882 switch (result)
883 {
884 case PACKET_OK:
885 case PACKET_ERROR:
886 /* The stub recognized the packet request. */
d471ea57
AC
887 switch (config->support)
888 {
889 case PACKET_SUPPORT_UNKNOWN:
890 if (remote_debug)
891 fprintf_unfiltered (gdb_stdlog,
892 "Packet %s (%s) is supported\n",
893 config->name, config->title);
894 config->support = PACKET_ENABLE;
895 break;
896 case PACKET_DISABLE:
8e65ff28 897 internal_error (__FILE__, __LINE__,
e2e0b3e5 898 _("packet_ok: attempt to use a disabled packet"));
d471ea57
AC
899 break;
900 case PACKET_ENABLE:
901 break;
902 }
a76d924d
DJ
903 break;
904 case PACKET_UNKNOWN:
23860348 905 /* The stub does not support the packet. */
d471ea57
AC
906 switch (config->support)
907 {
908 case PACKET_ENABLE:
7f19b9a2 909 if (config->detect == AUTO_BOOLEAN_AUTO)
d471ea57 910 /* If the stub previously indicated that the packet was
23860348 911 supported then there is a protocol error.. */
8a3fe4f8 912 error (_("Protocol error: %s (%s) conflicting enabled responses."),
d471ea57
AC
913 config->name, config->title);
914 else
23860348 915 /* The user set it wrong. */
8a3fe4f8 916 error (_("Enabled packet %s (%s) not recognized by stub"),
d471ea57
AC
917 config->name, config->title);
918 break;
919 case PACKET_SUPPORT_UNKNOWN:
920 if (remote_debug)
921 fprintf_unfiltered (gdb_stdlog,
922 "Packet %s (%s) is NOT supported\n",
923 config->name, config->title);
924 config->support = PACKET_DISABLE;
925 break;
926 case PACKET_DISABLE:
927 break;
928 }
a76d924d 929 break;
5a2468f5 930 }
a76d924d
DJ
931
932 return result;
5a2468f5
JM
933}
934
444abaca
DJ
935enum {
936 PACKET_vCont = 0,
937 PACKET_X,
938 PACKET_qSymbol,
939 PACKET_P,
940 PACKET_p,
941 PACKET_Z0,
942 PACKET_Z1,
943 PACKET_Z2,
944 PACKET_Z3,
945 PACKET_Z4,
a6b151f1
DJ
946 PACKET_vFile_open,
947 PACKET_vFile_pread,
948 PACKET_vFile_pwrite,
949 PACKET_vFile_close,
950 PACKET_vFile_unlink,
0876f84a 951 PACKET_qXfer_auxv,
23181151 952 PACKET_qXfer_features,
cfa9d6d9 953 PACKET_qXfer_libraries,
fd79ecee 954 PACKET_qXfer_memory_map,
0e7f50da
UW
955 PACKET_qXfer_spu_read,
956 PACKET_qXfer_spu_write,
444abaca 957 PACKET_qGetTLSAddr,
be2a5f71 958 PACKET_qSupported,
89be2091 959 PACKET_QPassSignals,
08388c79 960 PACKET_qSearch_memory,
2d717e4f
DJ
961 PACKET_vAttach,
962 PACKET_vRun,
444abaca
DJ
963 PACKET_MAX
964};
506fb367 965
444abaca 966static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97
MS
967
968static void
444abaca
DJ
969set_remote_protocol_packet_cmd (char *args, int from_tty,
970 struct cmd_list_element *c)
dc8acb97 971{
444abaca 972 struct packet_config *packet;
dc8acb97 973
444abaca
DJ
974 for (packet = remote_protocol_packets;
975 packet < &remote_protocol_packets[PACKET_MAX];
976 packet++)
977 {
978 if (&packet->detect == c->var)
979 {
980 update_packet_config (packet);
981 return;
982 }
983 }
984 internal_error (__FILE__, __LINE__, "Could not find config for %s",
985 c->name);
dc8acb97
MS
986}
987
5a2468f5 988static void
444abaca
DJ
989show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
990 struct cmd_list_element *c,
991 const char *value)
5a2468f5 992{
444abaca 993 struct packet_config *packet;
5a2468f5 994
444abaca
DJ
995 for (packet = remote_protocol_packets;
996 packet < &remote_protocol_packets[PACKET_MAX];
997 packet++)
998 {
999 if (&packet->detect == c->var)
1000 {
1001 show_packet_config_cmd (packet);
1002 return;
1003 }
1004 }
1005 internal_error (__FILE__, __LINE__, "Could not find config for %s",
1006 c->name);
5a2468f5
JM
1007}
1008
d471ea57
AC
1009/* Should we try one of the 'Z' requests? */
1010
1011enum Z_packet_type
1012{
1013 Z_PACKET_SOFTWARE_BP,
1014 Z_PACKET_HARDWARE_BP,
1015 Z_PACKET_WRITE_WP,
1016 Z_PACKET_READ_WP,
1017 Z_PACKET_ACCESS_WP,
1018 NR_Z_PACKET_TYPES
1019};
96baa820 1020
d471ea57 1021/* For compatibility with older distributions. Provide a ``set remote
23860348 1022 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1023
7f19b9a2 1024static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1025
1026static void
fba45db2
KB
1027set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1028 struct cmd_list_element *c)
96baa820 1029{
d471ea57
AC
1030 int i;
1031 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1032 {
444abaca
DJ
1033 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1034 update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1035 }
96baa820
JM
1036}
1037
1038static void
08546159
AC
1039show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1040 struct cmd_list_element *c,
1041 const char *value)
96baa820 1042{
d471ea57
AC
1043 int i;
1044 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1045 {
444abaca 1046 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1047 }
96baa820
JM
1048}
1049
9d1f7ab2
MS
1050/* Should we try the 'ThreadInfo' query packet?
1051
1052 This variable (NOT available to the user: auto-detect only!)
1053 determines whether GDB will use the new, simpler "ThreadInfo"
1054 query or the older, more complex syntax for thread queries.
802188a7 1055 This is an auto-detect variable (set to true at each connect,
9d1f7ab2
MS
1056 and set to false when the target fails to recognize it). */
1057
1058static int use_threadinfo_query;
1059static int use_threadextra_query;
1060
23860348 1061/* Tokens for use by the asynchronous signal handlers for SIGINT. */
d5d6fca5
DJ
1062static struct async_signal_handler *sigint_remote_twice_token;
1063static struct async_signal_handler *sigint_remote_token;
43ff13b4 1064
c906108c
SS
1065\f
1066
79d7f229
PA
1067static ptid_t magic_null_ptid;
1068static ptid_t not_sent_ptid;
1069static ptid_t any_thread_ptid;
1070
1071/* These are the threads which we last sent to the remote system. The
1072 TID member will be -1 for all or -2 for not sent yet. */
1073
1074static ptid_t general_thread;
1075static ptid_t continue_thread;
c5aa993b 1076
c906108c
SS
1077
1078/* Call this function as a result of
1079 1) A halt indication (T packet) containing a thread id
1080 2) A direct query of currthread
1081 3) Successful execution of set thread
1082 */
1083
1084static void
79d7f229 1085record_currthread (ptid_t currthread)
c906108c 1086{
c906108c 1087 general_thread = currthread;
cce74817 1088
c906108c
SS
1089 /* If this is a new thread, add it to GDB's thread list.
1090 If we leave it up to WFI to do this, bad things will happen. */
79d7f229 1091 if (!in_thread_list (currthread))
c0a2216e
PA
1092 {
1093 if (ptid_equal (pid_to_ptid (ptid_get_pid (currthread)), inferior_ptid))
1094 {
1095 /* inferior_ptid has no thread member yet. This can happen
1096 with the vAttach -> remote_wait,"TAAthread:" path if the
1097 stub doesn't support qC. This is the first stop reported
1098 after an attach, so this is the main thread. Update the
1099 ptid in the thread list. */
1100 struct thread_info *th = find_thread_pid (inferior_ptid);
1101 inferior_ptid = th->ptid = currthread;
1102 }
1103 else if (ptid_equal (magic_null_ptid, inferior_ptid))
1104 {
1105 /* inferior_ptid is not set yet. This can happen with the
1106 vRun -> remote_wait,"TAAthread:" path if the stub
1107 doesn't support qC. This is the first stop reported
1108 after an attach, so this is the main thread. Update the
1109 ptid in the thread list. */
1110 struct thread_info *th = find_thread_pid (inferior_ptid);
1111 inferior_ptid = th->ptid = currthread;
1112 }
1113 else
1114 /* This is really a new thread. Add it. */
1115 add_thread (currthread);
1116 }
c906108c
SS
1117}
1118
89be2091
DJ
1119static char *last_pass_packet;
1120
1121/* If 'QPassSignals' is supported, tell the remote stub what signals
1122 it can simply pass through to the inferior without reporting. */
1123
1124static void
1125remote_pass_signals (void)
1126{
1127 if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1128 {
1129 char *pass_packet, *p;
1130 int numsigs = (int) TARGET_SIGNAL_LAST;
1131 int count = 0, i;
1132
1133 gdb_assert (numsigs < 256);
1134 for (i = 0; i < numsigs; i++)
1135 {
1136 if (signal_stop_state (i) == 0
1137 && signal_print_state (i) == 0
1138 && signal_pass_state (i) == 1)
1139 count++;
1140 }
1141 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1142 strcpy (pass_packet, "QPassSignals:");
1143 p = pass_packet + strlen (pass_packet);
1144 for (i = 0; i < numsigs; i++)
1145 {
1146 if (signal_stop_state (i) == 0
1147 && signal_print_state (i) == 0
1148 && signal_pass_state (i) == 1)
1149 {
1150 if (i >= 16)
1151 *p++ = tohex (i >> 4);
1152 *p++ = tohex (i & 15);
1153 if (count)
1154 *p++ = ';';
1155 else
1156 break;
1157 count--;
1158 }
1159 }
1160 *p = 0;
1161 if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
1162 {
1163 struct remote_state *rs = get_remote_state ();
1164 char *buf = rs->buf;
1165
1166 putpkt (pass_packet);
1167 getpkt (&rs->buf, &rs->buf_size, 0);
1168 packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1169 if (last_pass_packet)
1170 xfree (last_pass_packet);
1171 last_pass_packet = pass_packet;
1172 }
1173 else
1174 xfree (pass_packet);
1175 }
1176}
1177
79d7f229
PA
1178/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1179 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1180 thread. If GEN is set, set the general thread, if not, then set
1181 the step/continue thread. */
c906108c 1182static void
79d7f229 1183set_thread (struct ptid ptid, int gen)
c906108c 1184{
d01949b6 1185 struct remote_state *rs = get_remote_state ();
79d7f229 1186 ptid_t state = gen ? general_thread : continue_thread;
6d820c5c 1187 char *buf = rs->buf;
79d7f229 1188 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 1189
79d7f229 1190 if (ptid_equal (state, ptid))
c906108c
SS
1191 return;
1192
79d7f229
PA
1193 *buf++ = 'H';
1194 *buf++ = gen ? 'g' : 'c';
1195 if (ptid_equal (ptid, magic_null_ptid))
1196 xsnprintf (buf, endbuf - buf, "0");
1197 else if (ptid_equal (ptid, any_thread_ptid))
1198 xsnprintf (buf, endbuf - buf, "0");
1199 else if (ptid_equal (ptid, minus_one_ptid))
1200 xsnprintf (buf, endbuf - buf, "-1");
1201 else
c906108c 1202 {
79d7f229
PA
1203 int tid = ptid_get_tid (ptid);
1204 if (tid < 0)
1205 xsnprintf (buf, endbuf - buf, "-%x", -tid);
1206 else
1207 xsnprintf (buf, endbuf - buf, "%x", tid);
c906108c 1208 }
79d7f229 1209 putpkt (rs->buf);
6d820c5c 1210 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 1211 if (gen)
79d7f229 1212 general_thread = ptid;
c906108c 1213 else
79d7f229 1214 continue_thread = ptid;
c906108c 1215}
79d7f229
PA
1216
1217static void
1218set_general_thread (struct ptid ptid)
1219{
1220 set_thread (ptid, 1);
1221}
1222
1223static void
1224set_continue_thread (struct ptid ptid)
1225{
1226 set_thread (ptid, 0);
1227}
1228
c906108c 1229\f
79d7f229
PA
1230/* Return nonzero if the thread PTID is still alive on the remote
1231 system. */
c906108c
SS
1232
1233static int
39f77062 1234remote_thread_alive (ptid_t ptid)
c906108c 1235{
6d820c5c 1236 struct remote_state *rs = get_remote_state ();
79d7f229 1237 int tid = ptid_get_tid (ptid);
c906108c 1238
c0a2216e
PA
1239 if (ptid_equal (ptid, magic_null_ptid))
1240 /* The main thread is always alive. */
1241 return 1;
1242
1243 if (ptid_get_pid (ptid) != 0 && ptid_get_tid (ptid) == 0)
1244 /* The main thread is always alive. This can happen after a
1245 vAttach, if the remote side doesn't support
1246 multi-threading. */
1247 return 1;
1248
cce74817 1249 if (tid < 0)
2e9f7625 1250 xsnprintf (rs->buf, get_remote_packet_size (), "T-%08x", -tid);
c906108c 1251 else
2e9f7625
DJ
1252 xsnprintf (rs->buf, get_remote_packet_size (), "T%08x", tid);
1253 putpkt (rs->buf);
6d820c5c 1254 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 1255 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
1256}
1257
1258/* About these extended threadlist and threadinfo packets. They are
1259 variable length packets but, the fields within them are often fixed
1260 length. They are redundent enough to send over UDP as is the
1261 remote protocol in general. There is a matching unit test module
1262 in libstub. */
1263
cce74817
JM
1264#define OPAQUETHREADBYTES 8
1265
1266/* a 64 bit opaque identifier */
1267typedef unsigned char threadref[OPAQUETHREADBYTES];
1268
23860348
MS
1269/* WARNING: This threadref data structure comes from the remote O.S.,
1270 libstub protocol encoding, and remote.c. it is not particularly
1271 changable. */
cce74817
JM
1272
1273/* Right now, the internal structure is int. We want it to be bigger.
1274 Plan to fix this.
c5aa993b 1275 */
cce74817 1276
23860348 1277typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 1278
9d1f7ab2 1279/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 1280 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
1281
1282struct gdb_ext_thread_info
c5aa993b 1283 {
23860348 1284 threadref threadid; /* External form of thread reference. */
2bc416ba 1285 int active; /* Has state interesting to GDB?
23860348 1286 regs, stack. */
2bc416ba 1287 char display[256]; /* Brief state display, name,
cedea757 1288 blocked/suspended. */
23860348 1289 char shortname[32]; /* To be used to name threads. */
2bc416ba 1290 char more_display[256]; /* Long info, statistics, queue depth,
23860348 1291 whatever. */
c5aa993b 1292 };
cce74817
JM
1293
1294/* The volume of remote transfers can be limited by submitting
1295 a mask containing bits specifying the desired information.
1296 Use a union of these values as the 'selection' parameter to
1297 get_thread_info. FIXME: Make these TAG names more thread specific.
c5aa993b 1298 */
cce74817
JM
1299
1300#define TAG_THREADID 1
1301#define TAG_EXISTS 2
1302#define TAG_DISPLAY 4
1303#define TAG_THREADNAME 8
c5aa993b 1304#define TAG_MOREDISPLAY 16
cce74817 1305
23860348 1306#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 1307
b2dd6311 1308char *unpack_varlen_hex (char *buff, ULONGEST *result);
cce74817 1309
a14ed312 1310static char *unpack_nibble (char *buf, int *val);
cce74817 1311
a14ed312 1312static char *pack_nibble (char *buf, int nibble);
cce74817 1313
23860348 1314static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
cce74817 1315
a14ed312 1316static char *unpack_byte (char *buf, int *value);
cce74817 1317
a14ed312 1318static char *pack_int (char *buf, int value);
cce74817 1319
a14ed312 1320static char *unpack_int (char *buf, int *value);
cce74817 1321
a14ed312 1322static char *unpack_string (char *src, char *dest, int length);
cce74817 1323
23860348 1324static char *pack_threadid (char *pkt, threadref *id);
cce74817 1325
23860348 1326static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 1327
23860348 1328void int_to_threadref (threadref *id, int value);
cce74817 1329
23860348 1330static int threadref_to_int (threadref *ref);
cce74817 1331
23860348 1332static void copy_threadref (threadref *dest, threadref *src);
cce74817 1333
23860348 1334static int threadmatch (threadref *dest, threadref *src);
cce74817 1335
2bc416ba 1336static char *pack_threadinfo_request (char *pkt, int mode,
23860348 1337 threadref *id);
cce74817 1338
a14ed312 1339static int remote_unpack_thread_info_response (char *pkt,
23860348 1340 threadref *expectedref,
a14ed312
KB
1341 struct gdb_ext_thread_info
1342 *info);
cce74817
JM
1343
1344
2bc416ba 1345static int remote_get_threadinfo (threadref *threadid,
23860348 1346 int fieldset, /*TAG mask */
a14ed312 1347 struct gdb_ext_thread_info *info);
cce74817 1348
a14ed312
KB
1349static char *pack_threadlist_request (char *pkt, int startflag,
1350 int threadcount,
23860348 1351 threadref *nextthread);
cce74817 1352
a14ed312
KB
1353static int parse_threadlist_response (char *pkt,
1354 int result_limit,
23860348 1355 threadref *original_echo,
2bc416ba 1356 threadref *resultlist,
23860348 1357 int *doneflag);
cce74817 1358
a14ed312 1359static int remote_get_threadlist (int startflag,
23860348 1360 threadref *nextthread,
a14ed312
KB
1361 int result_limit,
1362 int *done,
2bc416ba 1363 int *result_count,
23860348 1364 threadref *threadlist);
cce74817 1365
23860348 1366typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 1367
a14ed312
KB
1368static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1369 void *context, int looplimit);
cce74817 1370
23860348 1371static int remote_newthread_step (threadref *ref, void *context);
cce74817 1372
23860348 1373/* Encode 64 bits in 16 chars of hex. */
c906108c
SS
1374
1375static const char hexchars[] = "0123456789abcdef";
1376
1377static int
fba45db2 1378ishex (int ch, int *val)
c906108c
SS
1379{
1380 if ((ch >= 'a') && (ch <= 'f'))
1381 {
1382 *val = ch - 'a' + 10;
1383 return 1;
1384 }
1385 if ((ch >= 'A') && (ch <= 'F'))
1386 {
1387 *val = ch - 'A' + 10;
1388 return 1;
1389 }
1390 if ((ch >= '0') && (ch <= '9'))
1391 {
1392 *val = ch - '0';
1393 return 1;
1394 }
1395 return 0;
1396}
1397
1398static int
fba45db2 1399stubhex (int ch)
c906108c
SS
1400{
1401 if (ch >= 'a' && ch <= 'f')
1402 return ch - 'a' + 10;
1403 if (ch >= '0' && ch <= '9')
1404 return ch - '0';
1405 if (ch >= 'A' && ch <= 'F')
1406 return ch - 'A' + 10;
1407 return -1;
1408}
1409
1410static int
fba45db2 1411stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
1412{
1413 int nibble;
1414 int retval = 0;
1415
1416 while (fieldlength)
1417 {
1418 nibble = stubhex (*buff++);
1419 retval |= nibble;
1420 fieldlength--;
1421 if (fieldlength)
1422 retval = retval << 4;
1423 }
1424 return retval;
1425}
1426
1427char *
fba45db2 1428unpack_varlen_hex (char *buff, /* packet to parse */
b2dd6311 1429 ULONGEST *result)
c906108c
SS
1430{
1431 int nibble;
d49c44d5 1432 ULONGEST retval = 0;
c906108c
SS
1433
1434 while (ishex (*buff, &nibble))
1435 {
1436 buff++;
1437 retval = retval << 4;
1438 retval |= nibble & 0x0f;
1439 }
1440 *result = retval;
1441 return buff;
1442}
1443
1444static char *
fba45db2 1445unpack_nibble (char *buf, int *val)
c906108c 1446{
b7589f7d 1447 *val = fromhex (*buf++);
c906108c
SS
1448 return buf;
1449}
1450
1451static char *
fba45db2 1452pack_nibble (char *buf, int nibble)
c906108c
SS
1453{
1454 *buf++ = hexchars[(nibble & 0x0f)];
1455 return buf;
1456}
1457
1458static char *
fba45db2 1459pack_hex_byte (char *pkt, int byte)
c906108c
SS
1460{
1461 *pkt++ = hexchars[(byte >> 4) & 0xf];
1462 *pkt++ = hexchars[(byte & 0xf)];
1463 return pkt;
1464}
1465
1466static char *
fba45db2 1467unpack_byte (char *buf, int *value)
c906108c
SS
1468{
1469 *value = stub_unpack_int (buf, 2);
1470 return buf + 2;
1471}
1472
1473static char *
fba45db2 1474pack_int (char *buf, int value)
c906108c
SS
1475{
1476 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
1477 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
1478 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
1479 buf = pack_hex_byte (buf, (value & 0xff));
1480 return buf;
1481}
1482
1483static char *
fba45db2 1484unpack_int (char *buf, int *value)
c906108c
SS
1485{
1486 *value = stub_unpack_int (buf, 8);
1487 return buf + 8;
1488}
1489
23860348 1490#if 0 /* Currently unused, uncomment when needed. */
a14ed312 1491static char *pack_string (char *pkt, char *string);
c906108c
SS
1492
1493static char *
fba45db2 1494pack_string (char *pkt, char *string)
c906108c
SS
1495{
1496 char ch;
1497 int len;
1498
1499 len = strlen (string);
1500 if (len > 200)
23860348 1501 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
1502 pkt = pack_hex_byte (pkt, len);
1503 while (len-- > 0)
1504 {
1505 ch = *string++;
1506 if ((ch == '\0') || (ch == '#'))
23860348 1507 ch = '*'; /* Protect encapsulation. */
c906108c
SS
1508 *pkt++ = ch;
1509 }
1510 return pkt;
1511}
1512#endif /* 0 (unused) */
1513
1514static char *
fba45db2 1515unpack_string (char *src, char *dest, int length)
c906108c
SS
1516{
1517 while (length--)
1518 *dest++ = *src++;
1519 *dest = '\0';
1520 return src;
1521}
1522
1523static char *
fba45db2 1524pack_threadid (char *pkt, threadref *id)
c906108c
SS
1525{
1526 char *limit;
1527 unsigned char *altid;
1528
1529 altid = (unsigned char *) id;
1530 limit = pkt + BUF_THREAD_ID_SIZE;
1531 while (pkt < limit)
1532 pkt = pack_hex_byte (pkt, *altid++);
1533 return pkt;
1534}
1535
1536
1537static char *
fba45db2 1538unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
1539{
1540 char *altref;
1541 char *limit = inbuf + BUF_THREAD_ID_SIZE;
1542 int x, y;
1543
1544 altref = (char *) id;
1545
1546 while (inbuf < limit)
1547 {
1548 x = stubhex (*inbuf++);
1549 y = stubhex (*inbuf++);
1550 *altref++ = (x << 4) | y;
1551 }
1552 return inbuf;
1553}
1554
1555/* Externally, threadrefs are 64 bits but internally, they are still
1556 ints. This is due to a mismatch of specifications. We would like
1557 to use 64bit thread references internally. This is an adapter
1558 function. */
1559
1560void
fba45db2 1561int_to_threadref (threadref *id, int value)
c906108c
SS
1562{
1563 unsigned char *scan;
1564
1565 scan = (unsigned char *) id;
1566 {
1567 int i = 4;
1568 while (i--)
1569 *scan++ = 0;
1570 }
1571 *scan++ = (value >> 24) & 0xff;
1572 *scan++ = (value >> 16) & 0xff;
1573 *scan++ = (value >> 8) & 0xff;
1574 *scan++ = (value & 0xff);
1575}
1576
1577static int
fba45db2 1578threadref_to_int (threadref *ref)
c906108c
SS
1579{
1580 int i, value = 0;
1581 unsigned char *scan;
1582
cfd77fa1 1583 scan = *ref;
c906108c
SS
1584 scan += 4;
1585 i = 4;
1586 while (i-- > 0)
1587 value = (value << 8) | ((*scan++) & 0xff);
1588 return value;
1589}
1590
1591static void
fba45db2 1592copy_threadref (threadref *dest, threadref *src)
c906108c
SS
1593{
1594 int i;
1595 unsigned char *csrc, *cdest;
1596
1597 csrc = (unsigned char *) src;
1598 cdest = (unsigned char *) dest;
1599 i = 8;
1600 while (i--)
1601 *cdest++ = *csrc++;
1602}
1603
1604static int
fba45db2 1605threadmatch (threadref *dest, threadref *src)
c906108c 1606{
23860348 1607 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
1608#if 0
1609 unsigned char *srcp, *destp;
1610 int i, result;
1611 srcp = (char *) src;
1612 destp = (char *) dest;
1613
1614 result = 1;
1615 while (i-- > 0)
1616 result &= (*srcp++ == *destp++) ? 1 : 0;
1617 return result;
1618#endif
1619 return 1;
1620}
1621
1622/*
c5aa993b
JM
1623 threadid:1, # always request threadid
1624 context_exists:2,
1625 display:4,
1626 unique_name:8,
1627 more_display:16
1628 */
c906108c
SS
1629
1630/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
1631
1632static char *
fba45db2 1633pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 1634{
23860348
MS
1635 *pkt++ = 'q'; /* Info Query */
1636 *pkt++ = 'P'; /* process or thread info */
1637 pkt = pack_int (pkt, mode); /* mode */
c906108c 1638 pkt = pack_threadid (pkt, id); /* threadid */
23860348 1639 *pkt = '\0'; /* terminate */
c906108c
SS
1640 return pkt;
1641}
1642
23860348 1643/* These values tag the fields in a thread info response packet. */
c906108c 1644/* Tagging the fields allows us to request specific fields and to
23860348 1645 add more fields as time goes by. */
c906108c 1646
23860348 1647#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 1648#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 1649 fetch registers and its stack? */
c5aa993b 1650#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 1651#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 1652#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 1653 the process. */
c906108c
SS
1654
1655static int
fba45db2
KB
1656remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
1657 struct gdb_ext_thread_info *info)
c906108c 1658{
d01949b6 1659 struct remote_state *rs = get_remote_state ();
c906108c 1660 int mask, length;
cfd77fa1 1661 int tag;
c906108c 1662 threadref ref;
6d820c5c 1663 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
1664 int retval = 1;
1665
23860348 1666 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
1667 info->active = 0;
1668 info->display[0] = '\0';
1669 info->shortname[0] = '\0';
1670 info->more_display[0] = '\0';
1671
23860348
MS
1672 /* Assume the characters indicating the packet type have been
1673 stripped. */
c906108c
SS
1674 pkt = unpack_int (pkt, &mask); /* arg mask */
1675 pkt = unpack_threadid (pkt, &ref);
1676
1677 if (mask == 0)
8a3fe4f8 1678 warning (_("Incomplete response to threadinfo request."));
c906108c 1679 if (!threadmatch (&ref, expectedref))
23860348 1680 { /* This is an answer to a different request. */
8a3fe4f8 1681 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
1682 return 0;
1683 }
1684 copy_threadref (&info->threadid, &ref);
1685
23860348 1686 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 1687
23860348
MS
1688 /* Packets are terminated with nulls. */
1689 while ((pkt < limit) && mask && *pkt)
c906108c
SS
1690 {
1691 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
1692 pkt = unpack_byte (pkt, &length); /* length */
1693 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 1694 {
8a3fe4f8 1695 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
1696 retval = 0;
1697 break;
1698 }
1699 if (tag == TAG_THREADID)
1700 {
1701 if (length != 16)
1702 {
8a3fe4f8 1703 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
1704 retval = 0;
1705 break;
1706 }
1707 pkt = unpack_threadid (pkt, &ref);
1708 mask = mask & ~TAG_THREADID;
1709 continue;
1710 }
1711 if (tag == TAG_EXISTS)
1712 {
1713 info->active = stub_unpack_int (pkt, length);
1714 pkt += length;
1715 mask = mask & ~(TAG_EXISTS);
1716 if (length > 8)
1717 {
8a3fe4f8 1718 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
1719 retval = 0;
1720 break;
1721 }
1722 continue;
1723 }
1724 if (tag == TAG_THREADNAME)
1725 {
1726 pkt = unpack_string (pkt, &info->shortname[0], length);
1727 mask = mask & ~TAG_THREADNAME;
1728 continue;
1729 }
1730 if (tag == TAG_DISPLAY)
1731 {
1732 pkt = unpack_string (pkt, &info->display[0], length);
1733 mask = mask & ~TAG_DISPLAY;
1734 continue;
1735 }
1736 if (tag == TAG_MOREDISPLAY)
1737 {
1738 pkt = unpack_string (pkt, &info->more_display[0], length);
1739 mask = mask & ~TAG_MOREDISPLAY;
1740 continue;
1741 }
8a3fe4f8 1742 warning (_("ERROR RMT: unknown thread info tag."));
23860348 1743 break; /* Not a tag we know about. */
c906108c
SS
1744 }
1745 return retval;
1746}
1747
1748static int
fba45db2
KB
1749remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
1750 struct gdb_ext_thread_info *info)
c906108c 1751{
d01949b6 1752 struct remote_state *rs = get_remote_state ();
c906108c 1753 int result;
c906108c 1754
2e9f7625
DJ
1755 pack_threadinfo_request (rs->buf, fieldset, threadid);
1756 putpkt (rs->buf);
6d820c5c 1757 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 1758 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 1759 threadid, info);
c906108c
SS
1760 return result;
1761}
1762
c906108c
SS
1763/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
1764
1765static char *
fba45db2
KB
1766pack_threadlist_request (char *pkt, int startflag, int threadcount,
1767 threadref *nextthread)
c906108c
SS
1768{
1769 *pkt++ = 'q'; /* info query packet */
1770 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 1771 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
1772 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
1773 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
1774 *pkt = '\0';
1775 return pkt;
1776}
1777
1778/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
1779
1780static int
fba45db2
KB
1781parse_threadlist_response (char *pkt, int result_limit,
1782 threadref *original_echo, threadref *resultlist,
1783 int *doneflag)
c906108c 1784{
d01949b6 1785 struct remote_state *rs = get_remote_state ();
c906108c
SS
1786 char *limit;
1787 int count, resultcount, done;
1788
1789 resultcount = 0;
1790 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 1791 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 1792 /* done parse past here */
c906108c
SS
1793 pkt = unpack_byte (pkt, &count); /* count field */
1794 pkt = unpack_nibble (pkt, &done);
1795 /* The first threadid is the argument threadid. */
1796 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
1797 while ((count-- > 0) && (pkt < limit))
1798 {
1799 pkt = unpack_threadid (pkt, resultlist++);
1800 if (resultcount++ >= result_limit)
1801 break;
1802 }
1803 if (doneflag)
1804 *doneflag = done;
1805 return resultcount;
1806}
1807
1808static int
fba45db2
KB
1809remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
1810 int *done, int *result_count, threadref *threadlist)
c906108c 1811{
d01949b6 1812 struct remote_state *rs = get_remote_state ();
c906108c 1813 static threadref echo_nextthread;
c906108c
SS
1814 int result = 1;
1815
23860348 1816 /* Trancate result limit to be smaller than the packet size. */
ea9c271d
DJ
1817 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10) >= get_remote_packet_size ())
1818 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 1819
6d820c5c
DJ
1820 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
1821 putpkt (rs->buf);
1822 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 1823
d8f2712d
VP
1824 if (*rs->buf == '\0')
1825 *result_count = 0;
1826 else
1827 *result_count =
1828 parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
1829 threadlist, done);
c906108c
SS
1830
1831 if (!threadmatch (&echo_nextthread, nextthread))
1832 {
23860348
MS
1833 /* FIXME: This is a good reason to drop the packet. */
1834 /* Possably, there is a duplicate response. */
c906108c
SS
1835 /* Possabilities :
1836 retransmit immediatly - race conditions
1837 retransmit after timeout - yes
1838 exit
1839 wait for packet, then exit
1840 */
8a3fe4f8 1841 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 1842 return 0; /* I choose simply exiting. */
c906108c
SS
1843 }
1844 if (*result_count <= 0)
1845 {
1846 if (*done != 1)
1847 {
8a3fe4f8 1848 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
1849 result = 0;
1850 }
1851 return result; /* break; */
1852 }
1853 if (*result_count > result_limit)
1854 {
1855 *result_count = 0;
8a3fe4f8 1856 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
1857 return 0;
1858 }
1859 return result;
1860}
1861
23860348
MS
1862/* This is the interface between remote and threads, remotes upper
1863 interface. */
c906108c
SS
1864
1865/* remote_find_new_threads retrieves the thread list and for each
1866 thread in the list, looks up the thread in GDB's internal list,
79d7f229 1867 adding the thread if it does not already exist. This involves
c906108c
SS
1868 getting partial thread lists from the remote target so, polling the
1869 quit_flag is required. */
1870
1871
23860348 1872/* About this many threadisds fit in a packet. */
c906108c
SS
1873
1874#define MAXTHREADLISTRESULTS 32
1875
1876static int
fba45db2
KB
1877remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
1878 int looplimit)
c906108c
SS
1879{
1880 int done, i, result_count;
1881 int startflag = 1;
1882 int result = 1;
1883 int loopcount = 0;
1884 static threadref nextthread;
1885 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
1886
1887 done = 0;
1888 while (!done)
1889 {
1890 if (loopcount++ > looplimit)
1891 {
1892 result = 0;
8a3fe4f8 1893 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
1894 break;
1895 }
1896 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
1897 &done, &result_count, resultthreadlist))
1898 {
1899 result = 0;
1900 break;
1901 }
23860348 1902 /* Clear for later iterations. */
c906108c
SS
1903 startflag = 0;
1904 /* Setup to resume next batch of thread references, set nextthread. */
1905 if (result_count >= 1)
1906 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
1907 i = 0;
1908 while (result_count--)
1909 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
1910 break;
1911 }
1912 return result;
1913}
1914
1915static int
fba45db2 1916remote_newthread_step (threadref *ref, void *context)
c906108c 1917{
79d7f229
PA
1918 int pid = ptid_get_pid (inferior_ptid);
1919 ptid_t ptid = ptid_build (pid, 0, threadref_to_int (ref));
39f77062
KB
1920
1921 if (!in_thread_list (ptid))
1922 add_thread (ptid);
c906108c
SS
1923 return 1; /* continue iterator */
1924}
1925
1926#define CRAZY_MAX_THREADS 1000
1927
39f77062
KB
1928static ptid_t
1929remote_current_thread (ptid_t oldpid)
c906108c 1930{
d01949b6 1931 struct remote_state *rs = get_remote_state ();
79d7f229
PA
1932 char *p = rs->buf;
1933 int tid;
1934 int pid;
c906108c
SS
1935
1936 putpkt ("qC");
6d820c5c 1937 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 1938 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
79d7f229
PA
1939 {
1940 /* Use strtoul here, so we'll correctly parse values whose
1941 highest bit is set. The protocol carries them as a simple
1942 series of hex digits; in the absence of a sign, strtol will
1943 see such values as positive numbers out of range for signed
1944 'long', and return LONG_MAX to indicate an overflow. */
1945 tid = strtoul (&rs->buf[2], NULL, 16);
1946 pid = ptid_get_pid (oldpid);
1947 return ptid_build (pid, 0, tid);
1948 }
c906108c
SS
1949 else
1950 return oldpid;
1951}
1952
802188a7
RM
1953/* Find new threads for info threads command.
1954 * Original version, using John Metzler's thread protocol.
9d1f7ab2 1955 */
cce74817
JM
1956
1957static void
fba45db2 1958remote_find_new_threads (void)
c906108c 1959{
c5aa993b
JM
1960 remote_threadlist_iterator (remote_newthread_step, 0,
1961 CRAZY_MAX_THREADS);
c906108c
SS
1962}
1963
9d1f7ab2
MS
1964/*
1965 * Find all threads for info threads command.
1966 * Uses new thread protocol contributed by Cisco.
1967 * Falls back and attempts to use the older method (above)
1968 * if the target doesn't respond to the new method.
1969 */
1970
0f71a2f6
JM
1971static void
1972remote_threads_info (void)
1973{
d01949b6 1974 struct remote_state *rs = get_remote_state ();
085dd6e6 1975 char *bufp;
0f71a2f6 1976 int tid;
79d7f229
PA
1977 int pid;
1978 ptid_t new_thread;
0f71a2f6
JM
1979
1980 if (remote_desc == 0) /* paranoia */
8a3fe4f8 1981 error (_("Command can only be used when connected to the remote target."));
0f71a2f6 1982
9d1f7ab2
MS
1983 if (use_threadinfo_query)
1984 {
1985 putpkt ("qfThreadInfo");
6d820c5c 1986 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 1987 bufp = rs->buf;
9d1f7ab2 1988 if (bufp[0] != '\0') /* q packet recognized */
802188a7 1989 {
9d1f7ab2
MS
1990 while (*bufp++ == 'm') /* reply contains one or more TID */
1991 {
1992 do
1993 {
c273b20f
JB
1994 /* Use strtoul here, so we'll correctly parse values
1995 whose highest bit is set. The protocol carries
1996 them as a simple series of hex digits; in the
1997 absence of a sign, strtol will see such values as
1998 positive numbers out of range for signed 'long',
1999 and return LONG_MAX to indicate an overflow. */
2000 tid = strtoul (bufp, &bufp, 16);
79d7f229
PA
2001 pid = ptid_get_pid (inferior_ptid);
2002 new_thread = ptid_build (pid, 0, tid);
2003 if (tid != 0 && !in_thread_list (new_thread))
2004 add_thread (new_thread);
9d1f7ab2
MS
2005 }
2006 while (*bufp++ == ','); /* comma-separated list */
2007 putpkt ("qsThreadInfo");
6d820c5c 2008 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2009 bufp = rs->buf;
9d1f7ab2
MS
2010 }
2011 return; /* done */
2012 }
2013 }
2014
23860348 2015 /* Else fall back to old method based on jmetzler protocol. */
9d1f7ab2
MS
2016 use_threadinfo_query = 0;
2017 remote_find_new_threads ();
2018 return;
2019}
2020
802188a7 2021/*
9d1f7ab2
MS
2022 * Collect a descriptive string about the given thread.
2023 * The target may say anything it wants to about the thread
2024 * (typically info about its blocked / runnable state, name, etc.).
2025 * This string will appear in the info threads display.
802188a7 2026 *
9d1f7ab2
MS
2027 * Optional: targets are not required to implement this function.
2028 */
2029
2030static char *
2031remote_threads_extra_info (struct thread_info *tp)
2032{
d01949b6 2033 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
2034 int result;
2035 int set;
2036 threadref id;
2037 struct gdb_ext_thread_info threadinfo;
23860348 2038 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
2039 int n = 0; /* position in display_buf */
2040
2041 if (remote_desc == 0) /* paranoia */
8e65ff28 2042 internal_error (__FILE__, __LINE__,
e2e0b3e5 2043 _("remote_threads_extra_info"));
9d1f7ab2
MS
2044
2045 if (use_threadextra_query)
2046 {
79d7f229
PA
2047 xsnprintf (rs->buf, get_remote_packet_size (), "qThreadExtraInfo,%lx",
2048 ptid_get_tid (tp->ptid));
2e9f7625 2049 putpkt (rs->buf);
6d820c5c 2050 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2051 if (rs->buf[0] != 0)
9d1f7ab2 2052 {
2e9f7625
DJ
2053 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2054 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 2055 display_buf [result] = '\0';
9d1f7ab2
MS
2056 return display_buf;
2057 }
0f71a2f6 2058 }
9d1f7ab2
MS
2059
2060 /* If the above query fails, fall back to the old method. */
2061 use_threadextra_query = 0;
2062 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2063 | TAG_MOREDISPLAY | TAG_DISPLAY;
79d7f229 2064 int_to_threadref (&id, ptid_get_tid (tp->ptid));
9d1f7ab2
MS
2065 if (remote_get_threadinfo (&id, set, &threadinfo))
2066 if (threadinfo.active)
0f71a2f6 2067 {
9d1f7ab2 2068 if (*threadinfo.shortname)
2bc416ba 2069 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 2070 " Name: %s,", threadinfo.shortname);
9d1f7ab2 2071 if (*threadinfo.display)
2bc416ba 2072 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 2073 " State: %s,", threadinfo.display);
9d1f7ab2 2074 if (*threadinfo.more_display)
2bc416ba 2075 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 2076 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
2077
2078 if (n > 0)
c5aa993b 2079 {
23860348 2080 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
2081 if (',' == display_buf[n-1])
2082 display_buf[n-1] = ' ';
2083 return display_buf;
c5aa993b 2084 }
0f71a2f6 2085 }
9d1f7ab2 2086 return NULL;
0f71a2f6 2087}
c906108c 2088\f
c5aa993b 2089
24b06219 2090/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
2091
2092static void
fba45db2 2093extended_remote_restart (void)
c906108c 2094{
d01949b6 2095 struct remote_state *rs = get_remote_state ();
c906108c
SS
2096
2097 /* Send the restart command; for reasons I don't understand the
2098 remote side really expects a number after the "R". */
ea9c271d 2099 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 2100 putpkt (rs->buf);
c906108c 2101
ad9a8f3f 2102 remote_fileio_reset ();
c906108c
SS
2103}
2104\f
2105/* Clean up connection to a remote debugger. */
2106
c906108c 2107static void
fba45db2 2108remote_close (int quitting)
c906108c
SS
2109{
2110 if (remote_desc)
2cd58942 2111 serial_close (remote_desc);
c906108c
SS
2112 remote_desc = NULL;
2113}
2114
23860348 2115/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
2116
2117static void
fba45db2 2118get_offsets (void)
c906108c 2119{
d01949b6 2120 struct remote_state *rs = get_remote_state ();
2e9f7625 2121 char *buf;
085dd6e6 2122 char *ptr;
31d99776
DJ
2123 int lose, num_segments = 0, do_sections, do_segments;
2124 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 2125 struct section_offsets *offs;
31d99776
DJ
2126 struct symfile_segment_data *data;
2127
2128 if (symfile_objfile == NULL)
2129 return;
c906108c
SS
2130
2131 putpkt ("qOffsets");
6d820c5c 2132 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2133 buf = rs->buf;
c906108c
SS
2134
2135 if (buf[0] == '\000')
2136 return; /* Return silently. Stub doesn't support
23860348 2137 this command. */
c906108c
SS
2138 if (buf[0] == 'E')
2139 {
8a3fe4f8 2140 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
2141 return;
2142 }
2143
2144 /* Pick up each field in turn. This used to be done with scanf, but
2145 scanf will make trouble if CORE_ADDR size doesn't match
2146 conversion directives correctly. The following code will work
2147 with any size of CORE_ADDR. */
2148 text_addr = data_addr = bss_addr = 0;
2149 ptr = buf;
2150 lose = 0;
2151
2152 if (strncmp (ptr, "Text=", 5) == 0)
2153 {
2154 ptr += 5;
2155 /* Don't use strtol, could lose on big values. */
2156 while (*ptr && *ptr != ';')
2157 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 2158
31d99776
DJ
2159 if (strncmp (ptr, ";Data=", 6) == 0)
2160 {
2161 ptr += 6;
2162 while (*ptr && *ptr != ';')
2163 data_addr = (data_addr << 4) + fromhex (*ptr++);
2164 }
2165 else
2166 lose = 1;
2167
2168 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
2169 {
2170 ptr += 5;
2171 while (*ptr && *ptr != ';')
2172 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 2173
31d99776
DJ
2174 if (bss_addr != data_addr)
2175 warning (_("Target reported unsupported offsets: %s"), buf);
2176 }
2177 else
2178 lose = 1;
2179 }
2180 else if (strncmp (ptr, "TextSeg=", 8) == 0)
c906108c 2181 {
31d99776
DJ
2182 ptr += 8;
2183 /* Don't use strtol, could lose on big values. */
c906108c 2184 while (*ptr && *ptr != ';')
31d99776
DJ
2185 text_addr = (text_addr << 4) + fromhex (*ptr++);
2186 num_segments = 1;
2187
2188 if (strncmp (ptr, ";DataSeg=", 9) == 0)
2189 {
2190 ptr += 9;
2191 while (*ptr && *ptr != ';')
2192 data_addr = (data_addr << 4) + fromhex (*ptr++);
2193 num_segments++;
2194 }
c906108c
SS
2195 }
2196 else
2197 lose = 1;
2198
2199 if (lose)
8a3fe4f8 2200 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
2201 else if (*ptr != '\0')
2202 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 2203
802188a7 2204 offs = ((struct section_offsets *)
a39a16c4 2205 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 2206 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 2207 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 2208
31d99776
DJ
2209 data = get_symfile_segment_data (symfile_objfile->obfd);
2210 do_segments = (data != NULL);
2211 do_sections = num_segments == 0;
c906108c 2212
28c32713 2213 if (num_segments > 0)
31d99776 2214 {
31d99776
DJ
2215 segments[0] = text_addr;
2216 segments[1] = data_addr;
2217 }
28c32713
JB
2218 /* If we have two segments, we can still try to relocate everything
2219 by assuming that the .text and .data offsets apply to the whole
2220 text and data segments. Convert the offsets given in the packet
2221 to base addresses for symfile_map_offsets_to_segments. */
2222 else if (data && data->num_segments == 2)
2223 {
2224 segments[0] = data->segment_bases[0] + text_addr;
2225 segments[1] = data->segment_bases[1] + data_addr;
2226 num_segments = 2;
2227 }
8d385431
DJ
2228 /* If the object file has only one segment, assume that it is text
2229 rather than data; main programs with no writable data are rare,
2230 but programs with no code are useless. Of course the code might
2231 have ended up in the data segment... to detect that we would need
2232 the permissions here. */
2233 else if (data && data->num_segments == 1)
2234 {
2235 segments[0] = data->segment_bases[0] + text_addr;
2236 num_segments = 1;
2237 }
28c32713
JB
2238 /* There's no way to relocate by segment. */
2239 else
2240 do_segments = 0;
31d99776
DJ
2241
2242 if (do_segments)
2243 {
2244 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
2245 offs, num_segments, segments);
2246
2247 if (ret == 0 && !do_sections)
2248 error (_("Can not handle qOffsets TextSeg response with this symbol file"));
2249
2250 if (ret > 0)
2251 do_sections = 0;
2252 }
c906108c 2253
9ef895d6
DJ
2254 if (data)
2255 free_symfile_segment_data (data);
31d99776
DJ
2256
2257 if (do_sections)
2258 {
2259 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
2260
2261 /* This is a temporary kludge to force data and bss to use the same offsets
2262 because that's what nlmconv does now. The real solution requires changes
2263 to the stub and remote.c that I don't have time to do right now. */
2264
2265 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
2266 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
2267 }
c906108c
SS
2268
2269 objfile_relocate (symfile_objfile, offs);
2270}
2271
8621d6a9 2272/* Stub for catch_exception. */
0f71a2f6 2273
2d717e4f
DJ
2274struct start_remote_args
2275{
2276 int from_tty;
2277
2278 /* The current target. */
2279 struct target_ops *target;
2280
2281 /* Non-zero if this is an extended-remote target. */
2282 int extended_p;
2283};
2284
9cbc821d 2285static void
2d717e4f 2286remote_start_remote (struct ui_out *uiout, void *opaque)
c906108c 2287{
2d717e4f
DJ
2288 struct remote_state *rs = get_remote_state ();
2289 struct start_remote_args *args = opaque;
2290 char *wait_status = NULL;
8621d6a9 2291
23860348 2292 immediate_quit++; /* Allow user to interrupt it. */
c906108c
SS
2293
2294 /* Ack any packet which the remote side has already sent. */
2cd58942 2295 serial_write (remote_desc, "+", 1);
c906108c 2296
2d717e4f
DJ
2297 /* Check whether the target is running now. */
2298 putpkt ("?");
2299 getpkt (&rs->buf, &rs->buf_size, 0);
2300
2301 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2302 {
2303 if (args->extended_p)
2304 {
2305 /* We're connected, but not running. Drop out before we
2306 call start_remote. */
2307 target_mark_exited (args->target);
2308 return;
2309 }
2310 else
2311 error (_("The target is not running (try extended-remote?)"));
2312 }
2313 else
2314 {
2315 if (args->extended_p)
2316 target_mark_running (args->target);
2317
2318 /* Save the reply for later. */
2319 wait_status = alloca (strlen (rs->buf) + 1);
2320 strcpy (wait_status, rs->buf);
2321 }
2322
c0a2216e
PA
2323 /* Start afresh. */
2324 init_thread_list ();
2325
c906108c 2326 /* Let the stub know that we want it to return the thread. */
79d7f229 2327 set_continue_thread (minus_one_ptid);
c906108c 2328
2d717e4f
DJ
2329 /* Without this, some commands which require an active target
2330 (such as kill) won't work. This variable serves (at least)
2331 double duty as both the pid of the target process (if it has
2332 such), and as a flag indicating that a target is active.
2333 These functions should be split out into seperate variables,
2334 especially since GDB will someday have a notion of debugging
2335 several processes. */
79d7f229 2336 inferior_ptid = magic_null_ptid;
2d717e4f
DJ
2337
2338 /* Now, if we have thread information, update inferior_ptid. */
39f77062 2339 inferior_ptid = remote_current_thread (inferior_ptid);
c906108c 2340
c0a2216e
PA
2341 /* Always add the main thread. */
2342 add_thread_silent (inferior_ptid);
2343
23860348 2344 get_offsets (); /* Get text, data & bss offsets. */
c906108c 2345
2d717e4f
DJ
2346 /* Use the previously fetched status. */
2347 gdb_assert (wait_status != NULL);
2348 strcpy (rs->buf, wait_status);
2349 rs->cached_wait_status = 1;
c906108c 2350
2d717e4f
DJ
2351 immediate_quit--;
2352 start_remote (args->from_tty); /* Initialize gdb process mechanisms. */
c906108c
SS
2353}
2354
2355/* Open a connection to a remote debugger.
2356 NAME is the filename used for communication. */
2357
2358static void
fba45db2 2359remote_open (char *name, int from_tty)
c906108c 2360{
75c99385 2361 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
2362}
2363
c906108c
SS
2364/* Open a connection to a remote debugger using the extended
2365 remote gdb protocol. NAME is the filename used for communication. */
2366
2367static void
fba45db2 2368extended_remote_open (char *name, int from_tty)
c906108c 2369{
75c99385 2370 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
2371}
2372
c906108c
SS
2373/* Generic code for opening a connection to a remote target. */
2374
d471ea57
AC
2375static void
2376init_all_packet_configs (void)
2377{
2378 int i;
444abaca
DJ
2379 for (i = 0; i < PACKET_MAX; i++)
2380 update_packet_config (&remote_protocol_packets[i]);
d471ea57
AC
2381}
2382
23860348 2383/* Symbol look-up. */
dc8acb97
MS
2384
2385static void
2386remote_check_symbols (struct objfile *objfile)
2387{
d01949b6 2388 struct remote_state *rs = get_remote_state ();
dc8acb97
MS
2389 char *msg, *reply, *tmp;
2390 struct minimal_symbol *sym;
2391 int end;
2392
444abaca 2393 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
dc8acb97
MS
2394 return;
2395
6d820c5c
DJ
2396 /* Allocate a message buffer. We can't reuse the input buffer in RS,
2397 because we need both at the same time. */
ea9c271d 2398 msg = alloca (get_remote_packet_size ());
6d820c5c 2399
23860348 2400 /* Invite target to request symbol lookups. */
dc8acb97
MS
2401
2402 putpkt ("qSymbol::");
6d820c5c
DJ
2403 getpkt (&rs->buf, &rs->buf_size, 0);
2404 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2e9f7625 2405 reply = rs->buf;
dc8acb97
MS
2406
2407 while (strncmp (reply, "qSymbol:", 8) == 0)
2408 {
2409 tmp = &reply[8];
cfd77fa1 2410 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
2411 msg[end] = '\0';
2412 sym = lookup_minimal_symbol (msg, NULL, NULL);
2413 if (sym == NULL)
ea9c271d 2414 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 2415 else
2bbe3cc1
DJ
2416 {
2417 CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
2418
2419 /* If this is a function address, return the start of code
2420 instead of any data function descriptor. */
2421 sym_addr = gdbarch_convert_from_func_ptr_addr (current_gdbarch,
2422 sym_addr,
2423 &current_target);
2424
2425 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
2426 paddr_nz (sym_addr), &reply[8]);
2427 }
2428
dc8acb97 2429 putpkt (msg);
6d820c5c 2430 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2431 reply = rs->buf;
dc8acb97
MS
2432 }
2433}
2434
9db8d71f
DJ
2435static struct serial *
2436remote_serial_open (char *name)
2437{
2438 static int udp_warning = 0;
2439
2440 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
2441 of in ser-tcp.c, because it is the remote protocol assuming that the
2442 serial connection is reliable and not the serial connection promising
2443 to be. */
2444 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
2445 {
8a3fe4f8
AC
2446 warning (_("\
2447The remote protocol may be unreliable over UDP.\n\
2448Some events may be lost, rendering further debugging impossible."));
9db8d71f
DJ
2449 udp_warning = 1;
2450 }
2451
2452 return serial_open (name);
2453}
2454
be2a5f71
DJ
2455/* This type describes each known response to the qSupported
2456 packet. */
2457struct protocol_feature
2458{
2459 /* The name of this protocol feature. */
2460 const char *name;
2461
2462 /* The default for this protocol feature. */
2463 enum packet_support default_support;
2464
2465 /* The function to call when this feature is reported, or after
2466 qSupported processing if the feature is not supported.
2467 The first argument points to this structure. The second
2468 argument indicates whether the packet requested support be
2469 enabled, disabled, or probed (or the default, if this function
2470 is being called at the end of processing and this feature was
2471 not reported). The third argument may be NULL; if not NULL, it
2472 is a NUL-terminated string taken from the packet following
2473 this feature's name and an equals sign. */
2474 void (*func) (const struct protocol_feature *, enum packet_support,
2475 const char *);
2476
2477 /* The corresponding packet for this feature. Only used if
2478 FUNC is remote_supported_packet. */
2479 int packet;
2480};
2481
be2a5f71
DJ
2482static void
2483remote_supported_packet (const struct protocol_feature *feature,
2484 enum packet_support support,
2485 const char *argument)
2486{
2487 if (argument)
2488 {
2489 warning (_("Remote qSupported response supplied an unexpected value for"
2490 " \"%s\"."), feature->name);
2491 return;
2492 }
2493
2494 if (remote_protocol_packets[feature->packet].support
2495 == PACKET_SUPPORT_UNKNOWN)
2496 remote_protocol_packets[feature->packet].support = support;
2497}
be2a5f71
DJ
2498
2499static void
2500remote_packet_size (const struct protocol_feature *feature,
2501 enum packet_support support, const char *value)
2502{
2503 struct remote_state *rs = get_remote_state ();
2504
2505 int packet_size;
2506 char *value_end;
2507
2508 if (support != PACKET_ENABLE)
2509 return;
2510
2511 if (value == NULL || *value == '\0')
2512 {
2513 warning (_("Remote target reported \"%s\" without a size."),
2514 feature->name);
2515 return;
2516 }
2517
2518 errno = 0;
2519 packet_size = strtol (value, &value_end, 16);
2520 if (errno != 0 || *value_end != '\0' || packet_size < 0)
2521 {
2522 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
2523 feature->name, value);
2524 return;
2525 }
2526
2527 if (packet_size > MAX_REMOTE_PACKET_SIZE)
2528 {
2529 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
2530 packet_size, MAX_REMOTE_PACKET_SIZE);
2531 packet_size = MAX_REMOTE_PACKET_SIZE;
2532 }
2533
2534 /* Record the new maximum packet size. */
2535 rs->explicit_packet_size = packet_size;
2536}
2537
2538static struct protocol_feature remote_protocol_features[] = {
0876f84a 2539 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 2540 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 2541 PACKET_qXfer_auxv },
23181151
DJ
2542 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
2543 PACKET_qXfer_features },
cfa9d6d9
DJ
2544 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
2545 PACKET_qXfer_libraries },
fd79ecee 2546 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 2547 PACKET_qXfer_memory_map },
4de6483e
UW
2548 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
2549 PACKET_qXfer_spu_read },
2550 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
2551 PACKET_qXfer_spu_write },
89be2091
DJ
2552 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
2553 PACKET_QPassSignals },
be2a5f71
DJ
2554};
2555
2556static void
2557remote_query_supported (void)
2558{
2559 struct remote_state *rs = get_remote_state ();
2560 char *next;
2561 int i;
2562 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
2563
2564 /* The packet support flags are handled differently for this packet
2565 than for most others. We treat an error, a disabled packet, and
2566 an empty response identically: any features which must be reported
2567 to be used will be automatically disabled. An empty buffer
2568 accomplishes this, since that is also the representation for a list
2569 containing no features. */
2570
2571 rs->buf[0] = 0;
2572 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
2573 {
2574 putpkt ("qSupported");
2575 getpkt (&rs->buf, &rs->buf_size, 0);
2576
2577 /* If an error occured, warn, but do not return - just reset the
2578 buffer to empty and go on to disable features. */
2579 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
2580 == PACKET_ERROR)
2581 {
2582 warning (_("Remote failure reply: %s"), rs->buf);
2583 rs->buf[0] = 0;
2584 }
2585 }
2586
2587 memset (seen, 0, sizeof (seen));
2588
2589 next = rs->buf;
2590 while (*next)
2591 {
2592 enum packet_support is_supported;
2593 char *p, *end, *name_end, *value;
2594
2595 /* First separate out this item from the rest of the packet. If
2596 there's another item after this, we overwrite the separator
2597 (terminated strings are much easier to work with). */
2598 p = next;
2599 end = strchr (p, ';');
2600 if (end == NULL)
2601 {
2602 end = p + strlen (p);
2603 next = end;
2604 }
2605 else
2606 {
89be2091
DJ
2607 *end = '\0';
2608 next = end + 1;
2609
be2a5f71
DJ
2610 if (end == p)
2611 {
2612 warning (_("empty item in \"qSupported\" response"));
2613 continue;
2614 }
be2a5f71
DJ
2615 }
2616
2617 name_end = strchr (p, '=');
2618 if (name_end)
2619 {
2620 /* This is a name=value entry. */
2621 is_supported = PACKET_ENABLE;
2622 value = name_end + 1;
2623 *name_end = '\0';
2624 }
2625 else
2626 {
2627 value = NULL;
2628 switch (end[-1])
2629 {
2630 case '+':
2631 is_supported = PACKET_ENABLE;
2632 break;
2633
2634 case '-':
2635 is_supported = PACKET_DISABLE;
2636 break;
2637
2638 case '?':
2639 is_supported = PACKET_SUPPORT_UNKNOWN;
2640 break;
2641
2642 default:
2643 warning (_("unrecognized item \"%s\" in \"qSupported\" response"), p);
2644 continue;
2645 }
2646 end[-1] = '\0';
2647 }
2648
2649 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
2650 if (strcmp (remote_protocol_features[i].name, p) == 0)
2651 {
2652 const struct protocol_feature *feature;
2653
2654 seen[i] = 1;
2655 feature = &remote_protocol_features[i];
2656 feature->func (feature, is_supported, value);
2657 break;
2658 }
2659 }
2660
2661 /* If we increased the packet size, make sure to increase the global
2662 buffer size also. We delay this until after parsing the entire
2663 qSupported packet, because this is the same buffer we were
2664 parsing. */
2665 if (rs->buf_size < rs->explicit_packet_size)
2666 {
2667 rs->buf_size = rs->explicit_packet_size;
2668 rs->buf = xrealloc (rs->buf, rs->buf_size);
2669 }
2670
2671 /* Handle the defaults for unmentioned features. */
2672 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
2673 if (!seen[i])
2674 {
2675 const struct protocol_feature *feature;
2676
2677 feature = &remote_protocol_features[i];
2678 feature->func (feature, feature->default_support, NULL);
2679 }
2680}
2681
2682
c906108c 2683static void
75c99385 2684remote_open_1 (char *name, int from_tty, struct target_ops *target, int extended_p)
c906108c 2685{
d01949b6 2686 struct remote_state *rs = get_remote_state ();
c906108c 2687 if (name == 0)
8a3fe4f8 2688 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 2689 "serial device is attached to the remote system\n"
8a3fe4f8 2690 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 2691
23860348 2692 /* See FIXME above. */
75c99385 2693 if (!remote_async_permitted)
92d1e331 2694 wait_forever_enabled_p = 1;
6426a772 2695
2d717e4f
DJ
2696 /* If we're connected to a running target, target_preopen will kill it.
2697 But if we're connected to a target system with no running process,
2698 then we will still be connected when it returns. Ask this question
2699 first, before target_preopen has a chance to kill anything. */
2700 if (remote_desc != NULL && !target_has_execution)
2701 {
2702 if (!from_tty
2703 || query (_("Already connected to a remote target. Disconnect? ")))
2704 pop_target ();
2705 else
2706 error (_("Still connected."));
2707 }
2708
c906108c
SS
2709 target_preopen (from_tty);
2710
2711 unpush_target (target);
2712
2d717e4f
DJ
2713 /* This time without a query. If we were connected to an
2714 extended-remote target and target_preopen killed the running
2715 process, we may still be connected. If we are starting "target
2716 remote" now, the extended-remote target will not have been
2717 removed by unpush_target. */
2718 if (remote_desc != NULL && !target_has_execution)
2719 pop_target ();
2720
89be2091
DJ
2721 /* Make sure we send the passed signals list the next time we resume. */
2722 xfree (last_pass_packet);
2723 last_pass_packet = NULL;
2724
ad9a8f3f 2725 remote_fileio_reset ();
1dd41f16
NS
2726 reopen_exec_file ();
2727 reread_symbols ();
2728
9db8d71f 2729 remote_desc = remote_serial_open (name);
c906108c
SS
2730 if (!remote_desc)
2731 perror_with_name (name);
2732
2733 if (baud_rate != -1)
2734 {
2cd58942 2735 if (serial_setbaudrate (remote_desc, baud_rate))
c906108c 2736 {
9b74d5d3
KB
2737 /* The requested speed could not be set. Error out to
2738 top level after closing remote_desc. Take care to
2739 set remote_desc to NULL to avoid closing remote_desc
2740 more than once. */
2cd58942 2741 serial_close (remote_desc);
9b74d5d3 2742 remote_desc = NULL;
c906108c
SS
2743 perror_with_name (name);
2744 }
2745 }
2746
2cd58942 2747 serial_raw (remote_desc);
c906108c
SS
2748
2749 /* If there is something sitting in the buffer we might take it as a
2750 response to a command, which would be bad. */
2cd58942 2751 serial_flush_input (remote_desc);
c906108c
SS
2752
2753 if (from_tty)
2754 {
2755 puts_filtered ("Remote debugging using ");
2756 puts_filtered (name);
2757 puts_filtered ("\n");
2758 }
23860348 2759 push_target (target); /* Switch to using remote target now. */
c906108c 2760
2d717e4f
DJ
2761 /* Assume that the target is running, unless we learn otherwise. */
2762 target_mark_running (target);
2763
be2a5f71
DJ
2764 /* Reset the target state; these things will be queried either by
2765 remote_query_supported or as they are needed. */
d471ea57 2766 init_all_packet_configs ();
be2a5f71 2767 rs->explicit_packet_size = 0;
802188a7 2768
79d7f229
PA
2769 general_thread = not_sent_ptid;
2770 continue_thread = not_sent_ptid;
c906108c 2771
9d1f7ab2
MS
2772 /* Probe for ability to use "ThreadInfo" query, as required. */
2773 use_threadinfo_query = 1;
2774 use_threadextra_query = 1;
2775
be2a5f71
DJ
2776 /* The first packet we send to the target is the optional "supported
2777 packets" request. If the target can answer this, it will tell us
2778 which later probes to skip. */
2779 remote_query_supported ();
2780
424163ea
DJ
2781 /* Next, if the target can specify a description, read it. We do
2782 this before anything involving memory or registers. */
2783 target_find_description ();
2784
75c99385 2785 if (remote_async_permitted)
92d1e331 2786 {
23860348 2787 /* With this target we start out by owning the terminal. */
92d1e331
DJ
2788 remote_async_terminal_ours_p = 1;
2789
2790 /* FIXME: cagney/1999-09-23: During the initial connection it is
2791 assumed that the target is already ready and able to respond to
2792 requests. Unfortunately remote_start_remote() eventually calls
2793 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
2794 around this. Eventually a mechanism that allows
2795 wait_for_inferior() to expect/get timeouts will be
23860348 2796 implemented. */
92d1e331
DJ
2797 wait_forever_enabled_p = 0;
2798 }
2799
23860348 2800 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 2801 no_shared_libraries (NULL, 0);
f78f6cf1 2802
36918e70 2803 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
2804 target (we'd otherwise be in an inconsistent state) and then
2805 propogate the error on up the exception chain. This ensures that
2806 the caller doesn't stumble along blindly assuming that the
2807 function succeeded. The CLI doesn't have this problem but other
2808 UI's, such as MI do.
36918e70
AC
2809
2810 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
2811 this function should return an error indication letting the
ce2826aa 2812 caller restore the previous state. Unfortunately the command
36918e70
AC
2813 ``target remote'' is directly wired to this function making that
2814 impossible. On a positive note, the CLI side of this problem has
2815 been fixed - the function set_cmd_context() makes it possible for
2816 all the ``target ....'' commands to share a common callback
2817 function. See cli-dump.c. */
109c3e39 2818 {
2d717e4f
DJ
2819 struct gdb_exception ex;
2820 struct start_remote_args args;
2821
2822 args.from_tty = from_tty;
2823 args.target = target;
2824 args.extended_p = extended_p;
2825
2826 ex = catch_exception (uiout, remote_start_remote, &args, RETURN_MASK_ALL);
109c3e39
AC
2827 if (ex.reason < 0)
2828 {
2829 pop_target ();
75c99385 2830 if (remote_async_permitted)
109c3e39
AC
2831 wait_forever_enabled_p = 1;
2832 throw_exception (ex);
2833 }
2834 }
c906108c 2835
75c99385 2836 if (remote_async_permitted)
92d1e331 2837 wait_forever_enabled_p = 1;
6426a772
JM
2838
2839 if (extended_p)
43ff13b4 2840 {
6240bebf 2841 /* Tell the remote that we are using the extended protocol. */
6426a772 2842 putpkt ("!");
6d820c5c 2843 getpkt (&rs->buf, &rs->buf_size, 0);
43ff13b4 2844 }
a77053c2 2845
2d717e4f
DJ
2846 /* If we connected to a live target, do some additional setup. */
2847 if (target_has_execution)
2848 {
2849 if (exec_bfd) /* No use without an exec file. */
2850 remote_check_symbols (symfile_objfile);
2851 }
43ff13b4
JM
2852}
2853
c906108c
SS
2854/* This takes a program previously attached to and detaches it. After
2855 this is done, GDB can be used to debug some other program. We
2856 better not have left any breakpoints in the target program or it'll
2857 die when it hits one. */
2858
2859static void
2d717e4f 2860remote_detach_1 (char *args, int from_tty, int extended)
c906108c 2861{
d01949b6 2862 struct remote_state *rs = get_remote_state ();
c906108c
SS
2863
2864 if (args)
8a3fe4f8 2865 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 2866
2d717e4f
DJ
2867 if (!target_has_execution)
2868 error (_("No process to detach from."));
2869
c906108c 2870 /* Tell the remote target to detach. */
6d820c5c 2871 strcpy (rs->buf, "D");
4ddda9b5
PA
2872 putpkt (rs->buf);
2873 getpkt (&rs->buf, &rs->buf_size, 0);
2874
2875 if (rs->buf[0] == 'E')
2876 error (_("Can't detach process."));
c906108c 2877
23860348 2878 /* Unregister the file descriptor from the event loop. */
6ad8ae5c
DJ
2879 if (target_is_async_p ())
2880 serial_async (remote_desc, NULL, 0);
2881
cca728d0 2882 target_mourn_inferior ();
c906108c 2883 if (from_tty)
2d717e4f
DJ
2884 {
2885 if (extended)
2886 puts_filtered ("Detached from remote process.\n");
2887 else
2888 puts_filtered ("Ending remote debugging.\n");
2889 }
2890}
2891
2892static void
2893remote_detach (char *args, int from_tty)
2894{
2895 remote_detach_1 (args, from_tty, 0);
2896}
2897
2898static void
2899extended_remote_detach (char *args, int from_tty)
2900{
2901 remote_detach_1 (args, from_tty, 1);
c906108c
SS
2902}
2903
6ad8ae5c
DJ
2904/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
2905
43ff13b4 2906static void
597320e7 2907remote_disconnect (struct target_ops *target, char *args, int from_tty)
43ff13b4 2908{
43ff13b4 2909 if (args)
2d717e4f 2910 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 2911
23860348 2912 /* Unregister the file descriptor from the event loop. */
ed9a39eb 2913 if (target_is_async_p ())
2cd58942 2914 serial_async (remote_desc, NULL, 0);
43ff13b4 2915
2d717e4f
DJ
2916 /* Make sure we unpush even the extended remote targets; mourn
2917 won't do it. So call remote_mourn_1 directly instead of
2918 target_mourn_inferior. */
2919 remote_mourn_1 (target);
2920
43ff13b4
JM
2921 if (from_tty)
2922 puts_filtered ("Ending remote debugging.\n");
2923}
2924
2d717e4f
DJ
2925/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
2926 be chatty about it. */
2927
2928static void
2929extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
2930{
2931 struct remote_state *rs = get_remote_state ();
be86555c 2932 int pid;
2d717e4f 2933 char *dummy;
96ef3384 2934 char *wait_status = NULL;
2d717e4f
DJ
2935
2936 if (!args)
2937 error_no_arg (_("process-id to attach"));
2938
2939 dummy = args;
2940 pid = strtol (args, &dummy, 0);
2941 /* Some targets don't set errno on errors, grrr! */
2942 if (pid == 0 && args == dummy)
2943 error (_("Illegal process-id: %s."), args);
2944
2945 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
2946 error (_("This target does not support attaching to a process"));
2947
2948 sprintf (rs->buf, "vAttach;%x", pid);
2949 putpkt (rs->buf);
2950 getpkt (&rs->buf, &rs->buf_size, 0);
2951
2952 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
2953 {
2954 if (from_tty)
2955 printf_unfiltered (_("Attached to %s\n"),
2956 target_pid_to_str (pid_to_ptid (pid)));
2957
96ef3384
UW
2958 /* Save the reply for later. */
2959 wait_status = alloca (strlen (rs->buf) + 1);
2960 strcpy (wait_status, rs->buf);
2d717e4f
DJ
2961 }
2962 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
2963 error (_("This target does not support attaching to a process"));
2964 else
2965 error (_("Attaching to %s failed"),
2966 target_pid_to_str (pid_to_ptid (pid)));
2967
2968 target_mark_running (target);
2969 inferior_ptid = pid_to_ptid (pid);
79d7f229
PA
2970
2971 /* Now, if we have thread information, update inferior_ptid. */
2972 inferior_ptid = remote_current_thread (inferior_ptid);
2973
c0a2216e
PA
2974 /* Now, add the main thread to the thread list. */
2975 add_thread_silent (inferior_ptid);
2976
df7df359 2977 attach_flag = 1;
96ef3384
UW
2978
2979 /* Next, if the target can specify a description, read it. We do
2980 this before anything involving memory or registers. */
2981 target_find_description ();
2982
2983 /* Use the previously fetched status. */
2984 gdb_assert (wait_status != NULL);
2985 strcpy (rs->buf, wait_status);
2986 rs->cached_wait_status = 1;
2d717e4f
DJ
2987}
2988
2989static void
2990extended_remote_attach (char *args, int from_tty)
2991{
2992 extended_remote_attach_1 (&extended_remote_ops, args, from_tty);
2993}
2994
c906108c
SS
2995/* Convert hex digit A to a number. */
2996
30559e10 2997static int
fba45db2 2998fromhex (int a)
c906108c
SS
2999{
3000 if (a >= '0' && a <= '9')
3001 return a - '0';
3002 else if (a >= 'a' && a <= 'f')
3003 return a - 'a' + 10;
3004 else if (a >= 'A' && a <= 'F')
3005 return a - 'A' + 10;
c5aa993b 3006 else
8a3fe4f8 3007 error (_("Reply contains invalid hex digit %d"), a);
c906108c
SS
3008}
3009
30559e10 3010static int
cfd77fa1 3011hex2bin (const char *hex, gdb_byte *bin, int count)
30559e10
MS
3012{
3013 int i;
3014
30559e10
MS
3015 for (i = 0; i < count; i++)
3016 {
3017 if (hex[0] == 0 || hex[1] == 0)
3018 {
3019 /* Hex string is short, or of uneven length.
23860348 3020 Return the count that has been converted so far. */
30559e10
MS
3021 return i;
3022 }
3023 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
3024 hex += 2;
3025 }
3026 return i;
3027}
3028
c906108c
SS
3029/* Convert number NIB to a hex digit. */
3030
3031static int
fba45db2 3032tohex (int nib)
c906108c
SS
3033{
3034 if (nib < 10)
c5aa993b 3035 return '0' + nib;
c906108c 3036 else
c5aa993b 3037 return 'a' + nib - 10;
c906108c 3038}
30559e10
MS
3039
3040static int
cfd77fa1 3041bin2hex (const gdb_byte *bin, char *hex, int count)
30559e10
MS
3042{
3043 int i;
23860348 3044 /* May use a length, or a nul-terminated string as input. */
30559e10 3045 if (count == 0)
cfd77fa1 3046 count = strlen ((char *) bin);
30559e10
MS
3047
3048 for (i = 0; i < count; i++)
3049 {
3050 *hex++ = tohex ((*bin >> 4) & 0xf);
3051 *hex++ = tohex (*bin++ & 0xf);
3052 }
3053 *hex = 0;
3054 return i;
3055}
c906108c 3056\f
506fb367
DJ
3057/* Check for the availability of vCont. This function should also check
3058 the response. */
c906108c
SS
3059
3060static void
6d820c5c 3061remote_vcont_probe (struct remote_state *rs)
c906108c 3062{
2e9f7625 3063 char *buf;
6d820c5c 3064
2e9f7625
DJ
3065 strcpy (rs->buf, "vCont?");
3066 putpkt (rs->buf);
6d820c5c 3067 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3068 buf = rs->buf;
c906108c 3069
506fb367
DJ
3070 /* Make sure that the features we assume are supported. */
3071 if (strncmp (buf, "vCont", 5) == 0)
3072 {
3073 char *p = &buf[5];
3074 int support_s, support_S, support_c, support_C;
3075
3076 support_s = 0;
3077 support_S = 0;
3078 support_c = 0;
3079 support_C = 0;
3080 while (p && *p == ';')
3081 {
3082 p++;
3083 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
3084 support_s = 1;
3085 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
3086 support_S = 1;
3087 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
3088 support_c = 1;
3089 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
3090 support_C = 1;
3091
3092 p = strchr (p, ';');
3093 }
c906108c 3094
506fb367
DJ
3095 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
3096 BUF will make packet_ok disable the packet. */
3097 if (!support_s || !support_S || !support_c || !support_C)
3098 buf[0] = 0;
3099 }
c906108c 3100
444abaca 3101 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 3102}
c906108c 3103
506fb367
DJ
3104/* Resume the remote inferior by using a "vCont" packet. The thread
3105 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
3106 resumed thread should be single-stepped and/or signalled. If PTID
3107 equals minus_one_ptid, then all threads are resumed; the thread to
3108 be stepped and/or signalled is given in the global INFERIOR_PTID.
3109 This function returns non-zero iff it resumes the inferior.
44eaed12 3110
506fb367
DJ
3111 This function issues a strict subset of all possible vCont commands at the
3112 moment. */
44eaed12 3113
506fb367
DJ
3114static int
3115remote_vcont_resume (ptid_t ptid, int step, enum target_signal siggnal)
3116{
3117 struct remote_state *rs = get_remote_state ();
2d717e4f 3118 char *outbuf;
506fb367 3119 struct cleanup *old_cleanup;
44eaed12 3120
444abaca 3121 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
6d820c5c 3122 remote_vcont_probe (rs);
44eaed12 3123
444abaca 3124 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
6d820c5c 3125 return 0;
44eaed12 3126
506fb367
DJ
3127 /* If we could generate a wider range of packets, we'd have to worry
3128 about overflowing BUF. Should there be a generic
3129 "multi-part-packet" packet? */
3130
79d7f229 3131 if (ptid_equal (ptid, magic_null_ptid))
c906108c 3132 {
79d7f229
PA
3133 /* MAGIC_NULL_PTID means that we don't have any active threads,
3134 so we don't have any TID numbers the inferior will
3135 understand. Make sure to only send forms that do not specify
3136 a TID. */
506fb367 3137 if (step && siggnal != TARGET_SIGNAL_0)
2963ee1d 3138 outbuf = xstrprintf ("vCont;S%02x", siggnal);
506fb367 3139 else if (step)
2963ee1d 3140 outbuf = xstrprintf ("vCont;s");
506fb367 3141 else if (siggnal != TARGET_SIGNAL_0)
2963ee1d 3142 outbuf = xstrprintf ("vCont;C%02x", siggnal);
506fb367 3143 else
2963ee1d 3144 outbuf = xstrprintf ("vCont;c");
506fb367 3145 }
79d7f229 3146 else if (ptid_equal (ptid, minus_one_ptid))
506fb367
DJ
3147 {
3148 /* Resume all threads, with preference for INFERIOR_PTID. */
79d7f229 3149 int tid = ptid_get_tid (inferior_ptid);
506fb367 3150 if (step && siggnal != TARGET_SIGNAL_0)
79d7f229 3151 outbuf = xstrprintf ("vCont;S%02x:%x;c", siggnal, tid);
506fb367 3152 else if (step)
79d7f229 3153 outbuf = xstrprintf ("vCont;s:%x;c", tid);
506fb367 3154 else if (siggnal != TARGET_SIGNAL_0)
79d7f229 3155 outbuf = xstrprintf ("vCont;C%02x:%x;c", siggnal, tid);
506fb367 3156 else
2963ee1d 3157 outbuf = xstrprintf ("vCont;c");
c906108c
SS
3158 }
3159 else
506fb367
DJ
3160 {
3161 /* Scheduler locking; resume only PTID. */
79d7f229 3162 int tid = ptid_get_tid (ptid);
506fb367 3163 if (step && siggnal != TARGET_SIGNAL_0)
79d7f229 3164 outbuf = xstrprintf ("vCont;S%02x:%x", siggnal, tid);
506fb367 3165 else if (step)
79d7f229 3166 outbuf = xstrprintf ("vCont;s:%x", tid);
506fb367 3167 else if (siggnal != TARGET_SIGNAL_0)
79d7f229 3168 outbuf = xstrprintf ("vCont;C%02x:%x", siggnal, tid);
506fb367 3169 else
79d7f229 3170 outbuf = xstrprintf ("vCont;c:%x", tid);
506fb367 3171 }
c906108c 3172
ea9c271d 3173 gdb_assert (outbuf && strlen (outbuf) < get_remote_packet_size ());
6d820c5c 3174 old_cleanup = make_cleanup (xfree, outbuf);
2963ee1d
DJ
3175
3176 putpkt (outbuf);
506fb367
DJ
3177
3178 do_cleanups (old_cleanup);
3179
3180 return 1;
c906108c 3181}
43ff13b4 3182
506fb367
DJ
3183/* Tell the remote machine to resume. */
3184
3185static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
3186
3187static int last_sent_step;
3188
43ff13b4 3189static void
506fb367 3190remote_resume (ptid_t ptid, int step, enum target_signal siggnal)
43ff13b4 3191{
d01949b6 3192 struct remote_state *rs = get_remote_state ();
2e9f7625 3193 char *buf;
43ff13b4 3194
43ff13b4
JM
3195 last_sent_signal = siggnal;
3196 last_sent_step = step;
3197
89be2091
DJ
3198 /* Update the inferior on signals to silently pass, if they've changed. */
3199 remote_pass_signals ();
3200
506fb367
DJ
3201 /* The vCont packet doesn't need to specify threads via Hc. */
3202 if (remote_vcont_resume (ptid, step, siggnal))
75c99385 3203 goto done;
506fb367 3204
79d7f229
PA
3205 /* All other supported resume packets do use Hc, so set the continue
3206 thread. */
3207 if (ptid_equal (ptid, minus_one_ptid))
3208 set_continue_thread (any_thread_ptid);
506fb367 3209 else
79d7f229 3210 set_continue_thread (ptid);
506fb367 3211
2e9f7625 3212 buf = rs->buf;
43ff13b4
JM
3213 if (siggnal != TARGET_SIGNAL_0)
3214 {
3215 buf[0] = step ? 'S' : 'C';
c5aa993b 3216 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 3217 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
3218 buf[3] = '\0';
3219 }
3220 else
c5aa993b 3221 strcpy (buf, step ? "s" : "c");
506fb367 3222
44eaed12 3223 putpkt (buf);
43ff13b4 3224
75c99385 3225 done:
2acceee2
JM
3226 /* We are about to start executing the inferior, let's register it
3227 with the event loop. NOTE: this is the one place where all the
3228 execution commands end up. We could alternatively do this in each
23860348 3229 of the execution commands in infcmd.c. */
2acceee2
JM
3230 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
3231 into infcmd.c in order to allow inferior function calls to work
23860348 3232 NOT asynchronously. */
362646f5 3233 if (target_can_async_p ())
2acceee2 3234 target_async (inferior_event_handler, 0);
23860348 3235 /* Tell the world that the target is now executing. */
2acceee2
JM
3236 /* FIXME: cagney/1999-09-23: Is it the targets responsibility to set
3237 this? Instead, should the client of target just assume (for
3238 async targets) that the target is going to start executing? Is
3239 this information already found in the continuation block? */
ed9a39eb 3240 if (target_is_async_p ())
2acceee2 3241 target_executing = 1;
43ff13b4 3242}
c906108c 3243\f
43ff13b4
JM
3244
3245/* Set up the signal handler for SIGINT, while the target is
23860348 3246 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 3247static void
fba45db2 3248initialize_sigint_signal_handler (void)
43ff13b4 3249{
43ff13b4
JM
3250 signal (SIGINT, handle_remote_sigint);
3251}
3252
23860348 3253/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 3254static void
fba45db2 3255handle_remote_sigint (int sig)
43ff13b4
JM
3256{
3257 signal (sig, handle_remote_sigint_twice);
43ff13b4
JM
3258 mark_async_signal_handler_wrapper (sigint_remote_token);
3259}
3260
3261/* Signal handler for SIGINT, installed after SIGINT has already been
3262 sent once. It will take effect the second time that the user sends
23860348 3263 a ^C. */
43ff13b4 3264static void
fba45db2 3265handle_remote_sigint_twice (int sig)
43ff13b4 3266{
b803fb0f 3267 signal (sig, handle_remote_sigint);
43ff13b4
JM
3268 mark_async_signal_handler_wrapper (sigint_remote_twice_token);
3269}
3270
6426a772 3271/* Perform the real interruption of the target execution, in response
23860348 3272 to a ^C. */
c5aa993b 3273static void
fba45db2 3274async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
3275{
3276 if (remote_debug)
3277 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
3278
3279 target_stop ();
3280}
3281
3282/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 3283 up on the target alltogether. */
2df3850c 3284void
fba45db2 3285async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 3286{
2df3850c
JM
3287 if (remote_debug)
3288 fprintf_unfiltered (gdb_stdlog, "remote_interrupt_twice called\n");
b803fb0f
DJ
3289
3290 interrupt_query ();
43ff13b4
JM
3291}
3292
3293/* Reinstall the usual SIGINT handlers, after the target has
23860348 3294 stopped. */
6426a772
JM
3295static void
3296cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
3297{
3298 signal (SIGINT, handle_sigint);
43ff13b4
JM
3299}
3300
c906108c
SS
3301/* Send ^C to target to halt it. Target will respond, and send us a
3302 packet. */
507f3c78 3303static void (*ofunc) (int);
c906108c 3304
7a292a7a
SS
3305/* The command line interface's stop routine. This function is installed
3306 as a signal handler for SIGINT. The first time a user requests a
3307 stop, we call remote_stop to send a break or ^C. If there is no
3308 response from the target (it didn't stop when the user requested it),
23860348 3309 we ask the user if he'd like to detach from the target. */
c906108c 3310static void
fba45db2 3311remote_interrupt (int signo)
c906108c 3312{
23860348 3313 /* If this doesn't work, try more severe steps. */
7a292a7a
SS
3314 signal (signo, remote_interrupt_twice);
3315
b803fb0f 3316 gdb_call_async_signal_handler (sigint_remote_token, 1);
7a292a7a
SS
3317}
3318
3319/* The user typed ^C twice. */
3320
3321static void
fba45db2 3322remote_interrupt_twice (int signo)
7a292a7a
SS
3323{
3324 signal (signo, ofunc);
b803fb0f 3325 gdb_call_async_signal_handler (sigint_remote_twice_token, 1);
c906108c
SS
3326 signal (signo, remote_interrupt);
3327}
7a292a7a
SS
3328
3329/* This is the generic stop called via the target vector. When a target
3330 interrupt is requested, either by the command line or the GUI, we
23860348 3331 will eventually end up here. */
c906108c 3332static void
fba45db2 3333remote_stop (void)
c906108c 3334{
7a292a7a
SS
3335 /* Send a break or a ^C, depending on user preference. */
3336 if (remote_debug)
0f71a2f6 3337 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 3338
7a292a7a 3339 if (remote_break)
2cd58942 3340 serial_send_break (remote_desc);
c906108c 3341 else
2cd58942 3342 serial_write (remote_desc, "\003", 1);
c906108c
SS
3343}
3344
3345/* Ask the user what to do when an interrupt is received. */
3346
3347static void
fba45db2 3348interrupt_query (void)
c906108c
SS
3349{
3350 target_terminal_ours ();
3351
3352 if (query ("Interrupted while waiting for the program.\n\
3353Give up (and stop debugging it)? "))
3354 {
3355 target_mourn_inferior ();
b803fb0f 3356 signal (SIGINT, handle_sigint);
315a522e 3357 deprecated_throw_reason (RETURN_QUIT);
c906108c
SS
3358 }
3359
3360 target_terminal_inferior ();
3361}
3362
6426a772
JM
3363/* Enable/disable target terminal ownership. Most targets can use
3364 terminal groups to control terminal ownership. Remote targets are
3365 different in that explicit transfer of ownership to/from GDB/target
23860348 3366 is required. */
6426a772
JM
3367
3368static void
75c99385 3369remote_terminal_inferior (void)
6426a772 3370{
75c99385
PA
3371 if (!remote_async_permitted)
3372 /* Nothing to do. */
3373 return;
3374
6426a772
JM
3375 /* FIXME: cagney/1999-09-27: Shouldn't need to test for
3376 sync_execution here. This function should only be called when
3377 GDB is resuming the inferior in the forground. A background
3378 resume (``run&'') should leave GDB in control of the terminal and
23860348 3379 consequently should not call this code. */
6426a772
JM
3380 if (!sync_execution)
3381 return;
3382 /* FIXME: cagney/1999-09-27: Closely related to the above. Make
3383 calls target_terminal_*() idenpotent. The event-loop GDB talking
3384 to an asynchronous target with a synchronous command calls this
3385 function from both event-top.c and infrun.c/infcmd.c. Once GDB
3386 stops trying to transfer the terminal to the target when it
3387 shouldn't this guard can go away. */
3388 if (!remote_async_terminal_ours_p)
3389 return;
3390 delete_file_handler (input_fd);
3391 remote_async_terminal_ours_p = 0;
3392 initialize_sigint_signal_handler ();
3393 /* NOTE: At this point we could also register our selves as the
3394 recipient of all input. Any characters typed could then be
23860348 3395 passed on down to the target. */
6426a772
JM
3396}
3397
3398static void
75c99385 3399remote_terminal_ours (void)
6426a772 3400{
75c99385
PA
3401 if (!remote_async_permitted)
3402 /* Nothing to do. */
3403 return;
3404
3405 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
3406 if (!sync_execution)
3407 return;
75c99385 3408 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
3409 if (remote_async_terminal_ours_p)
3410 return;
3411 cleanup_sigint_signal_handler (NULL);
3412 add_file_handler (input_fd, stdin_event_handler, 0);
3413 remote_async_terminal_ours_p = 1;
3414}
3415
c906108c 3416void
917317f4 3417remote_console_output (char *msg)
c906108c
SS
3418{
3419 char *p;
3420
c5aa993b 3421 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
3422 {
3423 char tb[2];
3424 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
3425 tb[0] = c;
3426 tb[1] = 0;
43ff13b4 3427 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 3428 }
917317f4 3429 gdb_flush (gdb_stdtarg);
c906108c
SS
3430}
3431
0f71a2f6 3432/* Wait until the remote machine stops, then return,
79d7f229 3433 storing status in STATUS just as `wait' would. */
c906108c 3434
39f77062
KB
3435static ptid_t
3436remote_wait (ptid_t ptid, struct target_waitstatus *status)
c906108c 3437{
d01949b6 3438 struct remote_state *rs = get_remote_state ();
ea9c271d 3439 struct remote_arch_state *rsa = get_remote_arch_state ();
b2dd6311 3440 ULONGEST thread_num = -1;
79d7f229 3441 ULONGEST process_num = -1;
3c3bea1c 3442 ULONGEST addr;
cfa9d6d9 3443 int solibs_changed = 0;
c906108c
SS
3444
3445 status->kind = TARGET_WAITKIND_EXITED;
3446 status->value.integer = 0;
3447
43ff13b4
JM
3448 while (1)
3449 {
2e9f7625 3450 char *buf, *p;
c5aa993b 3451
2d717e4f
DJ
3452 if (rs->cached_wait_status)
3453 /* Use the cached wait status, but only once. */
3454 rs->cached_wait_status = 0;
3455 else
9fa2223d 3456 {
2d717e4f 3457 if (!target_is_async_p ())
9fa2223d 3458 {
2d717e4f
DJ
3459 ofunc = signal (SIGINT, remote_interrupt);
3460 /* If the user hit C-c before this packet, or between packets,
3461 pretend that it was hit right here. */
3462 if (quit_flag)
3463 {
3464 quit_flag = 0;
3465 remote_interrupt (SIGINT);
3466 }
9fa2223d 3467 }
2d717e4f
DJ
3468 /* FIXME: cagney/1999-09-27: If we're in async mode we should
3469 _never_ wait for ever -> test on target_is_async_p().
3470 However, before we do that we need to ensure that the caller
3471 knows how to take the target into/out of async mode. */
3472 getpkt (&rs->buf, &rs->buf_size, wait_forever_enabled_p);
3473 if (!target_is_async_p ())
3474 signal (SIGINT, ofunc);
9fa2223d 3475 }
43ff13b4 3476
2e9f7625
DJ
3477 buf = rs->buf;
3478
75c99385
PA
3479 remote_stopped_by_watchpoint_p = 0;
3480
43ff13b4
JM
3481 switch (buf[0])
3482 {
23860348 3483 case 'E': /* Error of some sort. */
20b4711e
DJ
3484 /* We're out of sync with the target now. Did it continue or not?
3485 Not is more likely, so report a stop. */
8a3fe4f8 3486 warning (_("Remote failure reply: %s"), buf);
20b4711e
DJ
3487 status->kind = TARGET_WAITKIND_STOPPED;
3488 status->value.sig = TARGET_SIGNAL_0;
3489 goto got_status;
23860348 3490 case 'F': /* File-I/O request. */
449092f6
CV
3491 remote_fileio_request (buf);
3492 continue;
23860348 3493 case 'T': /* Status with PC, SP, FP, ... */
43ff13b4 3494 {
cfd77fa1 3495 gdb_byte regs[MAX_REGISTER_SIZE];
43ff13b4 3496
23860348 3497 /* Expedited reply, containing Signal, {regno, reg} repeat. */
43ff13b4 3498 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
c5aa993b
JM
3499 ss = signal number
3500 n... = register number
3501 r... = register contents
3502 */
43ff13b4
JM
3503 p = &buf[3]; /* after Txx */
3504
3505 while (*p)
3506 {
cfd77fa1 3507 char *p1;
43ff13b4 3508 char *p_temp;
6c3f2dbf 3509 int fieldsize;
75c99385 3510 LONGEST pnum = 0;
43ff13b4 3511
23860348
MS
3512 /* If the packet contains a register number, save it
3513 in pnum and set p1 to point to the character
3514 following it. Otherwise p1 points to p. */
3c3bea1c 3515
75c99385
PA
3516 /* If this packet is an awatch packet, don't parse the
3517 'a' as a register number. */
802188a7 3518
cfa9d6d9 3519 if (strncmp (p, "awatch", strlen("awatch")) != 0)
3c3bea1c 3520 {
75c99385 3521 /* Read the ``P'' register number. */
3c3bea1c 3522 pnum = strtol (p, &p_temp, 16);
cfd77fa1 3523 p1 = p_temp;
3c3bea1c 3524 }
802188a7 3525 else
3c3bea1c 3526 p1 = p;
43ff13b4 3527
23860348 3528 if (p1 == p) /* No register number present here. */
43ff13b4 3529 {
cfd77fa1 3530 p1 = strchr (p, ':');
43ff13b4 3531 if (p1 == NULL)
8a3fe4f8
AC
3532 error (_("Malformed packet(a) (missing colon): %s\n\
3533Packet: '%s'\n"),
3fcb8548 3534 p, buf);
3c3bea1c 3535 if (strncmp (p, "thread", p1 - p) == 0)
43ff13b4
JM
3536 {
3537 p_temp = unpack_varlen_hex (++p1, &thread_num);
cfd77fa1 3538 p = p_temp;
43ff13b4 3539 }
3c3bea1c
GS
3540 else if ((strncmp (p, "watch", p1 - p) == 0)
3541 || (strncmp (p, "rwatch", p1 - p) == 0)
3542 || (strncmp (p, "awatch", p1 - p) == 0))
3543 {
3544 remote_stopped_by_watchpoint_p = 1;
3545 p = unpack_varlen_hex (++p1, &addr);
3546 remote_watch_data_address = (CORE_ADDR)addr;
3547 }
cfa9d6d9
DJ
3548 else if (strncmp (p, "library", p1 - p) == 0)
3549 {
3550 p1++;
3551 p_temp = p1;
3552 while (*p_temp && *p_temp != ';')
3553 p_temp++;
3554
3555 solibs_changed = 1;
3556 p = p_temp;
3557 }
3c3bea1c
GS
3558 else
3559 {
3560 /* Silently skip unknown optional info. */
cfd77fa1 3561 p_temp = strchr (p1 + 1, ';');
3c3bea1c
GS
3562 if (p_temp)
3563 p = p_temp;
3564 }
43ff13b4
JM
3565 }
3566 else
3567 {
ea9c271d 3568 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
43ff13b4 3569 p = p1;
75c99385 3570
b4f62b57 3571 if (*p != ':')
8a3fe4f8
AC
3572 error (_("Malformed packet(b) (missing colon): %s\n\
3573Packet: '%s'\n"),
3fcb8548 3574 p, buf);
b4f62b57 3575 ++p;
43ff13b4 3576
ad10f812 3577 if (reg == NULL)
75c99385 3578 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 3579Packet: '%s'\n"),
75c99385 3580 phex_nz (pnum, 0), p, buf);
43ff13b4 3581
cfd77fa1 3582 fieldsize = hex2bin (p, regs,
2bc416ba 3583 register_size (current_gdbarch,
23860348 3584 reg->regnum));
6c3f2dbf 3585 p += 2 * fieldsize;
2bc416ba 3586 if (fieldsize < register_size (current_gdbarch,
23860348 3587 reg->regnum))
8a3fe4f8 3588 warning (_("Remote reply is too short: %s"), buf);
594f7785
UW
3589 regcache_raw_supply (get_current_regcache (),
3590 reg->regnum, regs);
43ff13b4
JM
3591 }
3592
b4f62b57 3593 if (*p != ';')
8a3fe4f8 3594 error (_("Remote register badly formatted: %s\nhere: %s"),
0a2cfde4 3595 buf, p);
b4f62b57 3596 ++p;
43ff13b4
JM
3597 }
3598 }
3599 /* fall through */
23860348 3600 case 'S': /* Old style status, just signal only. */
cfa9d6d9
DJ
3601 if (solibs_changed)
3602 status->kind = TARGET_WAITKIND_LOADED;
3603 else
3604 {
3605 status->kind = TARGET_WAITKIND_STOPPED;
3606 status->value.sig = (enum target_signal)
3607 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3608 }
43ff13b4 3609 goto got_status;
23860348 3610 case 'W': /* Target exited. */
43ff13b4
JM
3611 {
3612 /* The remote process exited. */
3613 status->kind = TARGET_WAITKIND_EXITED;
3614 status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
3615 goto got_status;
3616 }
3617 case 'X':
3618 status->kind = TARGET_WAITKIND_SIGNALLED;
3619 status->value.sig = (enum target_signal)
3620 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
43ff13b4
JM
3621
3622 goto got_status;
23860348 3623 case 'O': /* Console output. */
43ff13b4 3624 remote_console_output (buf + 1);
75c99385
PA
3625 if (target_can_async_p ())
3626 {
3627 /* Return immediately to the event loop. The event loop
3628 will still be waiting on the inferior afterwards. */
3629 status->kind = TARGET_WAITKIND_IGNORE;
3630 goto got_status;
3631 }
3632 else
3633 continue;
43ff13b4
JM
3634 case '\0':
3635 if (last_sent_signal != TARGET_SIGNAL_0)
3636 {
3637 /* Zero length reply means that we tried 'S' or 'C' and
c5aa993b 3638 the remote system doesn't support it. */
43ff13b4
JM
3639 target_terminal_ours_for_output ();
3640 printf_filtered
3641 ("Can't send signals to this remote system. %s not sent.\n",
3642 target_signal_to_name (last_sent_signal));
3643 last_sent_signal = TARGET_SIGNAL_0;
3644 target_terminal_inferior ();
3645
3646 strcpy ((char *) buf, last_sent_step ? "s" : "c");
3647 putpkt ((char *) buf);
3648 continue;
3649 }
3650 /* else fallthrough */
3651 default:
8a3fe4f8 3652 warning (_("Invalid remote reply: %s"), buf);
43ff13b4
JM
3653 continue;
3654 }
3655 }
c5aa993b 3656got_status:
43ff13b4
JM
3657 if (thread_num != -1)
3658 {
79d7f229
PA
3659 ptid_t ptid;
3660 ptid = ptid_build (ptid_get_pid (inferior_ptid), 0, thread_num);
3661 record_currthread (ptid);
3662 return ptid;
43ff13b4 3663 }
79d7f229 3664
39f77062 3665 return inferior_ptid;
43ff13b4
JM
3666}
3667
74ca34ce 3668/* Fetch a single register using a 'p' packet. */
c906108c 3669
b96ec7ac 3670static int
56be3814 3671fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
3672{
3673 struct remote_state *rs = get_remote_state ();
2e9f7625 3674 char *buf, *p;
b96ec7ac
AC
3675 char regp[MAX_REGISTER_SIZE];
3676 int i;
3677
74ca34ce
DJ
3678 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
3679 return 0;
3680
3681 if (reg->pnum == -1)
3682 return 0;
3683
2e9f7625 3684 p = rs->buf;
fcad0fa4 3685 *p++ = 'p';
74ca34ce 3686 p += hexnumstr (p, reg->pnum);
fcad0fa4 3687 *p++ = '\0';
6d820c5c 3688 remote_send (&rs->buf, &rs->buf_size);
3f9a994c 3689
2e9f7625
DJ
3690 buf = rs->buf;
3691
74ca34ce
DJ
3692 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
3693 {
3694 case PACKET_OK:
3695 break;
3696 case PACKET_UNKNOWN:
3697 return 0;
3698 case PACKET_ERROR:
3699 error (_("Could not fetch register \"%s\""),
4a22f64d 3700 gdbarch_register_name (get_regcache_arch (regcache), reg->regnum));
74ca34ce 3701 }
3f9a994c
JB
3702
3703 /* If this register is unfetchable, tell the regcache. */
3704 if (buf[0] == 'x')
8480adf2 3705 {
56be3814 3706 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 3707 return 1;
b96ec7ac 3708 }
b96ec7ac 3709
3f9a994c
JB
3710 /* Otherwise, parse and supply the value. */
3711 p = buf;
3712 i = 0;
3713 while (p[0] != 0)
3714 {
3715 if (p[1] == 0)
74ca34ce 3716 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
3717
3718 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
3719 p += 2;
3720 }
56be3814 3721 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 3722 return 1;
b96ec7ac
AC
3723}
3724
74ca34ce
DJ
3725/* Fetch the registers included in the target's 'g' packet. */
3726
29709017
DJ
3727static int
3728send_g_packet (void)
c906108c 3729{
d01949b6 3730 struct remote_state *rs = get_remote_state ();
74ca34ce 3731 int i, buf_len;
c906108c 3732 char *p;
74ca34ce 3733 char *regs;
c906108c 3734
74ca34ce
DJ
3735 sprintf (rs->buf, "g");
3736 remote_send (&rs->buf, &rs->buf_size);
c906108c 3737
29709017
DJ
3738 /* We can get out of synch in various cases. If the first character
3739 in the buffer is not a hex character, assume that has happened
3740 and try to fetch another packet to read. */
3741 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
3742 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
3743 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
3744 && rs->buf[0] != 'x') /* New: unavailable register value. */
3745 {
3746 if (remote_debug)
3747 fprintf_unfiltered (gdb_stdlog,
3748 "Bad register packet; fetching a new packet\n");
3749 getpkt (&rs->buf, &rs->buf_size, 0);
3750 }
3751
74ca34ce
DJ
3752 buf_len = strlen (rs->buf);
3753
3754 /* Sanity check the received packet. */
3755 if (buf_len % 2 != 0)
3756 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
3757
3758 return buf_len / 2;
3759}
3760
3761static void
56be3814 3762process_g_packet (struct regcache *regcache)
29709017 3763{
4a22f64d 3764 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
3765 struct remote_state *rs = get_remote_state ();
3766 struct remote_arch_state *rsa = get_remote_arch_state ();
3767 int i, buf_len;
3768 char *p;
3769 char *regs;
3770
3771 buf_len = strlen (rs->buf);
3772
3773 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
3774 if (buf_len > 2 * rsa->sizeof_g_packet)
3775 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
3776
3777 /* Save the size of the packet sent to us by the target. It is used
3778 as a heuristic when determining the max size of packets that the
3779 target can safely receive. */
3780 if (rsa->actual_register_packet_size == 0)
3781 rsa->actual_register_packet_size = buf_len;
3782
3783 /* If this is smaller than we guessed the 'g' packet would be,
3784 update our records. A 'g' reply that doesn't include a register's
3785 value implies either that the register is not available, or that
3786 the 'p' packet must be used. */
3787 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 3788 {
74ca34ce
DJ
3789 rsa->sizeof_g_packet = buf_len / 2;
3790
4a22f64d 3791 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 3792 {
74ca34ce
DJ
3793 if (rsa->regs[i].pnum == -1)
3794 continue;
3795
3796 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
3797 rsa->regs[i].in_g_packet = 0;
b96ec7ac 3798 else
74ca34ce 3799 rsa->regs[i].in_g_packet = 1;
b96ec7ac 3800 }
74ca34ce 3801 }
b323314b 3802
74ca34ce 3803 regs = alloca (rsa->sizeof_g_packet);
c906108c
SS
3804
3805 /* Unimplemented registers read as all bits zero. */
ea9c271d 3806 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 3807
c906108c
SS
3808 /* Reply describes registers byte by byte, each byte encoded as two
3809 hex characters. Suck them all up, then supply them to the
3810 register cacheing/storage mechanism. */
3811
74ca34ce 3812 p = rs->buf;
ea9c271d 3813 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 3814 {
74ca34ce
DJ
3815 if (p[0] == 0 || p[1] == 0)
3816 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
3817 internal_error (__FILE__, __LINE__,
3818 "unexpected end of 'g' packet reply");
3819
c906108c 3820 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 3821 regs[i] = 0; /* 'x' */
c906108c
SS
3822 else
3823 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
3824 p += 2;
3825 }
3826
ad10f812 3827 {
b323314b 3828 int i;
4a22f64d 3829 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
ad10f812 3830 {
ea9c271d 3831 struct packet_reg *r = &rsa->regs[i];
b323314b
AC
3832 if (r->in_g_packet)
3833 {
74ca34ce
DJ
3834 if (r->offset * 2 >= strlen (rs->buf))
3835 /* This shouldn't happen - we adjusted in_g_packet above. */
3836 internal_error (__FILE__, __LINE__,
3837 "unexpected end of 'g' packet reply");
3838 else if (rs->buf[r->offset * 2] == 'x')
8ccc1287 3839 {
74ca34ce 3840 gdb_assert (r->offset * 2 < strlen (rs->buf));
8ccc1287
AC
3841 /* The register isn't available, mark it as such (at
3842 the same time setting the value to zero). */
56be3814 3843 regcache_raw_supply (regcache, r->regnum, NULL);
8ccc1287
AC
3844 }
3845 else
56be3814 3846 regcache_raw_supply (regcache, r->regnum,
8ccc1287 3847 regs + r->offset);
b323314b 3848 }
ad10f812
AC
3849 }
3850 }
c906108c
SS
3851}
3852
29709017 3853static void
56be3814 3854fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
3855{
3856 send_g_packet ();
56be3814 3857 process_g_packet (regcache);
29709017
DJ
3858}
3859
74ca34ce 3860static void
56be3814 3861remote_fetch_registers (struct regcache *regcache, int regnum)
74ca34ce
DJ
3862{
3863 struct remote_state *rs = get_remote_state ();
3864 struct remote_arch_state *rsa = get_remote_arch_state ();
3865 int i;
3866
79d7f229 3867 set_general_thread (inferior_ptid);
74ca34ce
DJ
3868
3869 if (regnum >= 0)
3870 {
3871 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
3872 gdb_assert (reg != NULL);
3873
3874 /* If this register might be in the 'g' packet, try that first -
3875 we are likely to read more than one register. If this is the
3876 first 'g' packet, we might be overly optimistic about its
3877 contents, so fall back to 'p'. */
3878 if (reg->in_g_packet)
3879 {
56be3814 3880 fetch_registers_using_g (regcache);
74ca34ce
DJ
3881 if (reg->in_g_packet)
3882 return;
3883 }
3884
56be3814 3885 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
3886 return;
3887
3888 /* This register is not available. */
56be3814 3889 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
3890
3891 return;
3892 }
3893
56be3814 3894 fetch_registers_using_g (regcache);
74ca34ce 3895
4a22f64d 3896 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 3897 if (!rsa->regs[i].in_g_packet)
56be3814 3898 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
3899 {
3900 /* This register is not available. */
56be3814 3901 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
3902 }
3903}
3904
c906108c
SS
3905/* Prepare to store registers. Since we may send them all (using a
3906 'G' request), we have to read out the ones we don't want to change
3907 first. */
3908
c5aa993b 3909static void
316f2060 3910remote_prepare_to_store (struct regcache *regcache)
c906108c 3911{
ea9c271d 3912 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 3913 int i;
cfd77fa1 3914 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 3915
c906108c 3916 /* Make sure the entire registers array is valid. */
444abaca 3917 switch (remote_protocol_packets[PACKET_P].support)
5a2468f5
JM
3918 {
3919 case PACKET_DISABLE:
3920 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 3921 /* Make sure all the necessary registers are cached. */
4a22f64d 3922 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 3923 if (rsa->regs[i].in_g_packet)
316f2060 3924 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
3925 break;
3926 case PACKET_ENABLE:
3927 break;
3928 }
3929}
3930
ad10f812 3931/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 3932 packet was not recognized. */
5a2468f5
JM
3933
3934static int
56be3814 3935store_register_using_P (const struct regcache *regcache, struct packet_reg *reg)
5a2468f5 3936{
4a22f64d 3937 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 3938 struct remote_state *rs = get_remote_state ();
ea9c271d 3939 struct remote_arch_state *rsa = get_remote_arch_state ();
5a2468f5 3940 /* Try storing a single register. */
6d820c5c 3941 char *buf = rs->buf;
cfd77fa1 3942 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 3943 char *p;
5a2468f5 3944
74ca34ce
DJ
3945 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
3946 return 0;
3947
3948 if (reg->pnum == -1)
3949 return 0;
3950
ea9c271d 3951 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 3952 p = buf + strlen (buf);
56be3814 3953 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 3954 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
6d820c5c 3955 remote_send (&rs->buf, &rs->buf_size);
5a2468f5 3956
74ca34ce
DJ
3957 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
3958 {
3959 case PACKET_OK:
3960 return 1;
3961 case PACKET_ERROR:
3962 error (_("Could not write register \"%s\""),
4a22f64d 3963 gdbarch_register_name (gdbarch, reg->regnum));
74ca34ce
DJ
3964 case PACKET_UNKNOWN:
3965 return 0;
3966 default:
3967 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
3968 }
c906108c
SS
3969}
3970
23860348
MS
3971/* Store register REGNUM, or all registers if REGNUM == -1, from the
3972 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
3973
3974static void
56be3814 3975store_registers_using_G (const struct regcache *regcache)
c906108c 3976{
d01949b6 3977 struct remote_state *rs = get_remote_state ();
ea9c271d 3978 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 3979 gdb_byte *regs;
c906108c
SS
3980 char *p;
3981
193cb69f
AC
3982 /* Extract all the registers in the regcache copying them into a
3983 local buffer. */
3984 {
b323314b 3985 int i;
ea9c271d
DJ
3986 regs = alloca (rsa->sizeof_g_packet);
3987 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 3988 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 3989 {
ea9c271d 3990 struct packet_reg *r = &rsa->regs[i];
b323314b 3991 if (r->in_g_packet)
56be3814 3992 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
3993 }
3994 }
c906108c
SS
3995
3996 /* Command describes registers byte by byte,
3997 each byte encoded as two hex characters. */
6d820c5c 3998 p = rs->buf;
193cb69f 3999 *p++ = 'G';
74ca34ce
DJ
4000 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
4001 updated. */
4002 bin2hex (regs, p, rsa->sizeof_g_packet);
6d820c5c 4003 remote_send (&rs->buf, &rs->buf_size);
c906108c 4004}
74ca34ce
DJ
4005
4006/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
4007 of the register cache buffer. FIXME: ignores errors. */
4008
4009static void
56be3814 4010remote_store_registers (struct regcache *regcache, int regnum)
74ca34ce
DJ
4011{
4012 struct remote_state *rs = get_remote_state ();
4013 struct remote_arch_state *rsa = get_remote_arch_state ();
4014 int i;
4015
79d7f229 4016 set_general_thread (inferior_ptid);
74ca34ce
DJ
4017
4018 if (regnum >= 0)
4019 {
4020 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
4021 gdb_assert (reg != NULL);
4022
4023 /* Always prefer to store registers using the 'P' packet if
4024 possible; we often change only a small number of registers.
4025 Sometimes we change a larger number; we'd need help from a
4026 higher layer to know to use 'G'. */
56be3814 4027 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
4028 return;
4029
4030 /* For now, don't complain if we have no way to write the
4031 register. GDB loses track of unavailable registers too
4032 easily. Some day, this may be an error. We don't have
4033 any way to read the register, either... */
4034 if (!reg->in_g_packet)
4035 return;
4036
56be3814 4037 store_registers_using_G (regcache);
74ca34ce
DJ
4038 return;
4039 }
4040
56be3814 4041 store_registers_using_G (regcache);
74ca34ce 4042
4a22f64d 4043 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 4044 if (!rsa->regs[i].in_g_packet)
56be3814 4045 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
4046 /* See above for why we do not issue an error here. */
4047 continue;
4048}
c906108c
SS
4049\f
4050
4051/* Return the number of hex digits in num. */
4052
4053static int
fba45db2 4054hexnumlen (ULONGEST num)
c906108c
SS
4055{
4056 int i;
4057
4058 for (i = 0; num != 0; i++)
4059 num >>= 4;
4060
4061 return max (i, 1);
4062}
4063
2df3850c 4064/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
4065
4066static int
fba45db2 4067hexnumstr (char *buf, ULONGEST num)
c906108c 4068{
c906108c 4069 int len = hexnumlen (num);
2df3850c
JM
4070 return hexnumnstr (buf, num, len);
4071}
4072
c906108c 4073
2df3850c 4074/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 4075
2df3850c 4076static int
fba45db2 4077hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
4078{
4079 int i;
4080
4081 buf[width] = '\0';
4082
4083 for (i = width - 1; i >= 0; i--)
c906108c 4084 {
c5aa993b 4085 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
4086 num >>= 4;
4087 }
4088
2df3850c 4089 return width;
c906108c
SS
4090}
4091
23860348 4092/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
4093
4094static CORE_ADDR
fba45db2 4095remote_address_masked (CORE_ADDR addr)
c906108c 4096{
911c95a5
UW
4097 int address_size = remote_address_size;
4098 /* If "remoteaddresssize" was not set, default to target address size. */
4099 if (!address_size)
4100 address_size = gdbarch_addr_bit (current_gdbarch);
4101
4102 if (address_size > 0
4103 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
4104 {
4105 /* Only create a mask when that mask can safely be constructed
23860348 4106 in a ULONGEST variable. */
c906108c 4107 ULONGEST mask = 1;
911c95a5 4108 mask = (mask << address_size) - 1;
c906108c
SS
4109 addr &= mask;
4110 }
4111 return addr;
4112}
4113
a31ea83d
DJ
4114/* Convert BUFFER, binary data at least LEN bytes long, into escaped
4115 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
4116 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
4117 (which may be more than *OUT_LEN due to escape characters). The
4118 total number of bytes in the output buffer will be at most
4119 OUT_MAXLEN. */
4120
4121static int
4122remote_escape_output (const gdb_byte *buffer, int len,
4123 gdb_byte *out_buf, int *out_len,
4124 int out_maxlen)
4125{
4126 int input_index, output_index;
4127
4128 output_index = 0;
4129 for (input_index = 0; input_index < len; input_index++)
4130 {
4131 gdb_byte b = buffer[input_index];
4132
4133 if (b == '$' || b == '#' || b == '}')
4134 {
4135 /* These must be escaped. */
4136 if (output_index + 2 > out_maxlen)
4137 break;
4138 out_buf[output_index++] = '}';
4139 out_buf[output_index++] = b ^ 0x20;
4140 }
4141 else
4142 {
4143 if (output_index + 1 > out_maxlen)
4144 break;
4145 out_buf[output_index++] = b;
4146 }
4147 }
4148
4149 *out_len = input_index;
4150 return output_index;
4151}
4152
0876f84a
DJ
4153/* Convert BUFFER, escaped data LEN bytes long, into binary data
4154 in OUT_BUF. Return the number of bytes written to OUT_BUF.
4155 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
4156
4157 This function reverses remote_escape_output. It allows more
4158 escaped characters than that function does, in particular because
4159 '*' must be escaped to avoid the run-length encoding processing
4160 in reading packets. */
4161
4162static int
4163remote_unescape_input (const gdb_byte *buffer, int len,
4164 gdb_byte *out_buf, int out_maxlen)
4165{
4166 int input_index, output_index;
4167 int escaped;
4168
4169 output_index = 0;
4170 escaped = 0;
4171 for (input_index = 0; input_index < len; input_index++)
4172 {
4173 gdb_byte b = buffer[input_index];
4174
4175 if (output_index + 1 > out_maxlen)
4176 {
4177 warning (_("Received too much data from remote target;"
4178 " ignoring overflow."));
4179 return output_index;
4180 }
4181
4182 if (escaped)
4183 {
4184 out_buf[output_index++] = b ^ 0x20;
4185 escaped = 0;
4186 }
4187 else if (b == '}')
4188 escaped = 1;
4189 else
4190 out_buf[output_index++] = b;
4191 }
4192
4193 if (escaped)
4194 error (_("Unmatched escape character in target response."));
4195
4196 return output_index;
4197}
4198
c906108c
SS
4199/* Determine whether the remote target supports binary downloading.
4200 This is accomplished by sending a no-op memory write of zero length
4201 to the target at the specified address. It does not suffice to send
23860348
MS
4202 the whole packet, since many stubs strip the eighth bit and
4203 subsequently compute a wrong checksum, which causes real havoc with
4204 remote_write_bytes.
7a292a7a 4205
96baa820
JM
4206 NOTE: This can still lose if the serial line is not eight-bit
4207 clean. In cases like this, the user should clear "remote
23860348 4208 X-packet". */
96baa820 4209
c906108c 4210static void
fba45db2 4211check_binary_download (CORE_ADDR addr)
c906108c 4212{
d01949b6 4213 struct remote_state *rs = get_remote_state ();
24b06219 4214
444abaca 4215 switch (remote_protocol_packets[PACKET_X].support)
c906108c 4216 {
96baa820
JM
4217 case PACKET_DISABLE:
4218 break;
4219 case PACKET_ENABLE:
4220 break;
4221 case PACKET_SUPPORT_UNKNOWN:
4222 {
96baa820 4223 char *p;
802188a7 4224
2e9f7625 4225 p = rs->buf;
96baa820
JM
4226 *p++ = 'X';
4227 p += hexnumstr (p, (ULONGEST) addr);
4228 *p++ = ',';
4229 p += hexnumstr (p, (ULONGEST) 0);
4230 *p++ = ':';
4231 *p = '\0';
802188a7 4232
2e9f7625 4233 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 4234 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 4235
2e9f7625 4236 if (rs->buf[0] == '\0')
96baa820
JM
4237 {
4238 if (remote_debug)
4239 fprintf_unfiltered (gdb_stdlog,
4240 "binary downloading NOT suppported by target\n");
444abaca 4241 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
4242 }
4243 else
4244 {
4245 if (remote_debug)
4246 fprintf_unfiltered (gdb_stdlog,
4247 "binary downloading suppported by target\n");
444abaca 4248 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
4249 }
4250 break;
4251 }
c906108c
SS
4252 }
4253}
4254
4255/* Write memory data directly to the remote machine.
4256 This does not inform the data cache; the data cache uses this.
a76d924d 4257 HEADER is the starting part of the packet.
c906108c
SS
4258 MEMADDR is the address in the remote memory space.
4259 MYADDR is the address of the buffer in our space.
4260 LEN is the number of bytes.
a76d924d
DJ
4261 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
4262 should send data as binary ('X'), or hex-encoded ('M').
4263
4264 The function creates packet of the form
4265 <HEADER><ADDRESS>,<LENGTH>:<DATA>
4266
4267 where encoding of <DATA> is termined by PACKET_FORMAT.
4268
4269 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
4270 are omitted.
4271
4272 Returns the number of bytes transferred, or 0 (setting errno) for
23860348 4273 error. Only transfer a single packet. */
c906108c 4274
a76d924d
DJ
4275static int
4276remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
4277 const gdb_byte *myaddr, int len,
4278 char packet_format, int use_length)
c906108c 4279{
6d820c5c 4280 struct remote_state *rs = get_remote_state ();
cfd77fa1 4281 char *p;
a76d924d
DJ
4282 char *plen = NULL;
4283 int plenlen = 0;
917317f4
JM
4284 int todo;
4285 int nr_bytes;
a257b5bb 4286 int payload_size;
6765f3e5 4287 int payload_length;
a76d924d
DJ
4288 int header_length;
4289
4290 if (packet_format != 'X' && packet_format != 'M')
4291 internal_error (__FILE__, __LINE__,
4292 "remote_write_bytes_aux: bad packet format");
c906108c 4293
b2182ed2
DJ
4294 if (len <= 0)
4295 return 0;
4296
3de11b2e 4297 payload_size = get_memory_write_packet_size ();
2bc416ba 4298
6d820c5c
DJ
4299 /* The packet buffer will be large enough for the payload;
4300 get_memory_packet_size ensures this. */
a76d924d 4301 rs->buf[0] = '\0';
c906108c 4302
a257b5bb 4303 /* Compute the size of the actual payload by subtracting out the
3de11b2e
NS
4304 packet header and footer overhead: "$M<memaddr>,<len>:...#nn".
4305 */
a76d924d
DJ
4306 payload_size -= strlen ("$,:#NN");
4307 if (!use_length)
4308 /* The comma won't be used. */
4309 payload_size += 1;
4310 header_length = strlen (header);
4311 payload_size -= header_length;
3de11b2e 4312 payload_size -= hexnumlen (memaddr);
c906108c 4313
a76d924d 4314 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 4315
a76d924d
DJ
4316 strcat (rs->buf, header);
4317 p = rs->buf + strlen (header);
4318
4319 /* Compute a best guess of the number of bytes actually transfered. */
4320 if (packet_format == 'X')
c906108c 4321 {
23860348 4322 /* Best guess at number of bytes that will fit. */
a257b5bb 4323 todo = min (len, payload_size);
a76d924d
DJ
4324 if (use_length)
4325 payload_size -= hexnumlen (todo);
3de11b2e 4326 todo = min (todo, payload_size);
a76d924d
DJ
4327 }
4328 else
4329 {
23860348 4330 /* Num bytes that will fit. */
a257b5bb 4331 todo = min (len, payload_size / 2);
a76d924d
DJ
4332 if (use_length)
4333 payload_size -= hexnumlen (todo);
3de11b2e 4334 todo = min (todo, payload_size / 2);
917317f4 4335 }
a76d924d 4336
3de11b2e
NS
4337 if (todo <= 0)
4338 internal_error (__FILE__, __LINE__,
4339 _("minumum packet size too small to write data"));
802188a7 4340
6765f3e5
DJ
4341 /* If we already need another packet, then try to align the end
4342 of this packet to a useful boundary. */
4343 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
4344 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
4345
a257b5bb 4346 /* Append "<memaddr>". */
917317f4
JM
4347 memaddr = remote_address_masked (memaddr);
4348 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 4349
a76d924d
DJ
4350 if (use_length)
4351 {
4352 /* Append ",". */
4353 *p++ = ',';
802188a7 4354
a76d924d
DJ
4355 /* Append <len>. Retain the location/size of <len>. It may need to
4356 be adjusted once the packet body has been created. */
4357 plen = p;
4358 plenlen = hexnumstr (p, (ULONGEST) todo);
4359 p += plenlen;
4360 }
a257b5bb
AC
4361
4362 /* Append ":". */
917317f4
JM
4363 *p++ = ':';
4364 *p = '\0';
802188a7 4365
a257b5bb 4366 /* Append the packet body. */
a76d924d 4367 if (packet_format == 'X')
917317f4 4368 {
917317f4
JM
4369 /* Binary mode. Send target system values byte by byte, in
4370 increasing byte addresses. Only escape certain critical
4371 characters. */
6765f3e5
DJ
4372 payload_length = remote_escape_output (myaddr, todo, p, &nr_bytes,
4373 payload_size);
4374
4375 /* If not all TODO bytes fit, then we'll need another packet. Make
9b7194bc
DJ
4376 a second try to keep the end of the packet aligned. Don't do
4377 this if the packet is tiny. */
4378 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6765f3e5
DJ
4379 {
4380 int new_nr_bytes;
4381
4382 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
4383 - memaddr);
4384 if (new_nr_bytes != nr_bytes)
4385 payload_length = remote_escape_output (myaddr, new_nr_bytes,
4386 p, &nr_bytes,
4387 payload_size);
4388 }
4389
4390 p += payload_length;
a76d924d 4391 if (use_length && nr_bytes < todo)
c906108c 4392 {
802188a7 4393 /* Escape chars have filled up the buffer prematurely,
917317f4
JM
4394 and we have actually sent fewer bytes than planned.
4395 Fix-up the length field of the packet. Use the same
4396 number of characters as before. */
917317f4
JM
4397 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
4398 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 4399 }
a76d924d
DJ
4400 }
4401 else
4402 {
917317f4
JM
4403 /* Normal mode: Send target system values byte by byte, in
4404 increasing byte addresses. Each byte is encoded as a two hex
4405 value. */
2644f393 4406 nr_bytes = bin2hex (myaddr, p, todo);
aa6c0017 4407 p += 2 * nr_bytes;
c906108c 4408 }
802188a7 4409
2e9f7625 4410 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 4411 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 4412
2e9f7625 4413 if (rs->buf[0] == 'E')
917317f4
JM
4414 {
4415 /* There is no correspondance between what the remote protocol
4416 uses for errors and errno codes. We would like a cleaner way
4417 of representing errors (big enough to include errno codes,
4418 bfd_error codes, and others). But for now just return EIO. */
4419 errno = EIO;
4420 return 0;
4421 }
802188a7 4422
23860348
MS
4423 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
4424 fewer bytes than we'd planned. */
917317f4 4425 return nr_bytes;
c906108c
SS
4426}
4427
a76d924d
DJ
4428/* Write memory data directly to the remote machine.
4429 This does not inform the data cache; the data cache uses this.
4430 MEMADDR is the address in the remote memory space.
4431 MYADDR is the address of the buffer in our space.
4432 LEN is the number of bytes.
4433
4434 Returns number of bytes transferred, or 0 (setting errno) for
4435 error. Only transfer a single packet. */
4436
4437int
4438remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
4439{
4440 char *packet_format = 0;
4441
4442 /* Check whether the target supports binary download. */
4443 check_binary_download (memaddr);
4444
4445 switch (remote_protocol_packets[PACKET_X].support)
4446 {
4447 case PACKET_ENABLE:
4448 packet_format = "X";
4449 break;
4450 case PACKET_DISABLE:
4451 packet_format = "M";
4452 break;
4453 case PACKET_SUPPORT_UNKNOWN:
4454 internal_error (__FILE__, __LINE__,
4455 _("remote_write_bytes: bad internal state"));
4456 default:
4457 internal_error (__FILE__, __LINE__, _("bad switch"));
4458 }
4459
4460 return remote_write_bytes_aux (packet_format,
4461 memaddr, myaddr, len, packet_format[0], 1);
4462}
4463
c906108c
SS
4464/* Read memory data directly from the remote machine.
4465 This does not use the data cache; the data cache uses this.
4466 MEMADDR is the address in the remote memory space.
4467 MYADDR is the address of the buffer in our space.
4468 LEN is the number of bytes.
4469
4470 Returns number of bytes transferred, or 0 for error. */
4471
917317f4
JM
4472/* NOTE: cagney/1999-10-18: This function (and its siblings in other
4473 remote targets) shouldn't attempt to read the entire buffer.
4474 Instead it should read a single packet worth of data and then
4475 return the byte size of that packet to the caller. The caller (its
4476 caller and its callers caller ;-) already contains code for
23860348 4477 handling partial reads. */
917317f4 4478
449092f6 4479int
cfd77fa1 4480remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
c906108c 4481{
6d820c5c 4482 struct remote_state *rs = get_remote_state ();
23860348 4483 int max_buf_size; /* Max size of packet output buffer. */
c906108c
SS
4484 int origlen;
4485
b2182ed2
DJ
4486 if (len <= 0)
4487 return 0;
4488
11cf8741 4489 max_buf_size = get_memory_read_packet_size ();
6d820c5c
DJ
4490 /* The packet buffer will be large enough for the payload;
4491 get_memory_packet_size ensures this. */
c906108c
SS
4492
4493 origlen = len;
4494 while (len > 0)
4495 {
c906108c
SS
4496 char *p;
4497 int todo;
4498 int i;
4499
c5aa993b 4500 todo = min (len, max_buf_size / 2); /* num bytes that will fit */
c906108c
SS
4501
4502 /* construct "m"<memaddr>","<len>" */
2e9f7625 4503 /* sprintf (rs->buf, "m%lx,%x", (unsigned long) memaddr, todo); */
c906108c 4504 memaddr = remote_address_masked (memaddr);
2e9f7625 4505 p = rs->buf;
c906108c
SS
4506 *p++ = 'm';
4507 p += hexnumstr (p, (ULONGEST) memaddr);
4508 *p++ = ',';
4509 p += hexnumstr (p, (ULONGEST) todo);
4510 *p = '\0';
4511
2e9f7625 4512 putpkt (rs->buf);
6d820c5c 4513 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 4514
2e9f7625
DJ
4515 if (rs->buf[0] == 'E'
4516 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
4517 && rs->buf[3] == '\0')
c906108c 4518 {
23860348
MS
4519 /* There is no correspondance between what the remote
4520 protocol uses for errors and errno codes. We would like
4521 a cleaner way of representing errors (big enough to
4522 include errno codes, bfd_error codes, and others). But
4523 for now just return EIO. */
c906108c
SS
4524 errno = EIO;
4525 return 0;
4526 }
4527
c5aa993b
JM
4528 /* Reply describes memory byte by byte,
4529 each byte encoded as two hex characters. */
c906108c 4530
2e9f7625 4531 p = rs->buf;
30559e10 4532 if ((i = hex2bin (p, myaddr, todo)) < todo)
c906108c 4533 {
30559e10 4534 /* Reply is short. This means that we were able to read
23860348 4535 only part of what we wanted to. */
30559e10 4536 return i + (origlen - len);
c906108c
SS
4537 }
4538 myaddr += todo;
4539 memaddr += todo;
4540 len -= todo;
4541 }
4542 return origlen;
4543}
4544\f
4545/* Read or write LEN bytes from inferior memory at MEMADDR,
23860348
MS
4546 transferring to or from debugger address BUFFER. Write to inferior
4547 if SHOULD_WRITE is nonzero. Returns length of data written or
4548 read; 0 for error. TARGET is unused. */
392a587b 4549
c906108c 4550static int
961cb7b5 4551remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
0a65a603 4552 int should_write, struct mem_attrib *attrib,
29e57380 4553 struct target_ops *target)
c906108c 4554{
4930751a
C
4555 int res;
4556
4930751a 4557 if (should_write)
b2182ed2 4558 res = remote_write_bytes (mem_addr, buffer, mem_len);
4930751a 4559 else
b2182ed2 4560 res = remote_read_bytes (mem_addr, buffer, mem_len);
4930751a
C
4561
4562 return res;
c906108c
SS
4563}
4564
a76d924d
DJ
4565/* Sends a packet with content determined by the printf format string
4566 FORMAT and the remaining arguments, then gets the reply. Returns
4567 whether the packet was a success, a failure, or unknown. */
4568
4569enum packet_result
4570remote_send_printf (const char *format, ...)
4571{
4572 struct remote_state *rs = get_remote_state ();
4573 int max_size = get_remote_packet_size ();
4574
4575 va_list ap;
4576 va_start (ap, format);
4577
4578 rs->buf[0] = '\0';
4579 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
4580 internal_error (__FILE__, __LINE__, "Too long remote packet.");
4581
4582 if (putpkt (rs->buf) < 0)
4583 error (_("Communication problem with target."));
4584
4585 rs->buf[0] = '\0';
4586 getpkt (&rs->buf, &rs->buf_size, 0);
4587
4588 return packet_check_result (rs->buf);
4589}
4590
4591static void
4592restore_remote_timeout (void *p)
4593{
4594 int value = *(int *)p;
4595 remote_timeout = value;
4596}
4597
4598/* Flash writing can take quite some time. We'll set
4599 effectively infinite timeout for flash operations.
4600 In future, we'll need to decide on a better approach. */
4601static const int remote_flash_timeout = 1000;
4602
4603static void
4604remote_flash_erase (struct target_ops *ops,
4605 ULONGEST address, LONGEST length)
4606{
4607 int saved_remote_timeout = remote_timeout;
4608 enum packet_result ret;
4609
4610 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
4611 &saved_remote_timeout);
4612 remote_timeout = remote_flash_timeout;
4613
4614 ret = remote_send_printf ("vFlashErase:%s,%s",
4615 paddr (address),
4616 phex (length, 4));
4617 switch (ret)
4618 {
4619 case PACKET_UNKNOWN:
4620 error (_("Remote target does not support flash erase"));
4621 case PACKET_ERROR:
4622 error (_("Error erasing flash with vFlashErase packet"));
4623 default:
4624 break;
4625 }
4626
4627 do_cleanups (back_to);
4628}
4629
4630static LONGEST
4631remote_flash_write (struct target_ops *ops,
4632 ULONGEST address, LONGEST length,
4633 const gdb_byte *data)
4634{
4635 int saved_remote_timeout = remote_timeout;
4636 int ret;
4637 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
4638 &saved_remote_timeout);
4639
4640 remote_timeout = remote_flash_timeout;
4641 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
4642 do_cleanups (back_to);
4643
4644 return ret;
4645}
4646
4647static void
4648remote_flash_done (struct target_ops *ops)
4649{
4650 int saved_remote_timeout = remote_timeout;
4651 int ret;
4652 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
4653 &saved_remote_timeout);
4654
4655 remote_timeout = remote_flash_timeout;
4656 ret = remote_send_printf ("vFlashDone");
4657 do_cleanups (back_to);
4658
4659 switch (ret)
4660 {
4661 case PACKET_UNKNOWN:
4662 error (_("Remote target does not support vFlashDone"));
4663 case PACKET_ERROR:
4664 error (_("Error finishing flash operation"));
4665 default:
4666 break;
4667 }
4668}
4669
c906108c 4670static void
fba45db2 4671remote_files_info (struct target_ops *ignore)
c906108c
SS
4672{
4673 puts_filtered ("Debugging a target over a serial line.\n");
4674}
4675\f
4676/* Stuff for dealing with the packets which are part of this protocol.
4677 See comment at top of file for details. */
4678
0876f84a 4679/* Read a single character from the remote end. */
c906108c
SS
4680
4681static int
fba45db2 4682readchar (int timeout)
c906108c
SS
4683{
4684 int ch;
4685
2cd58942 4686 ch = serial_readchar (remote_desc, timeout);
c906108c 4687
2acceee2 4688 if (ch >= 0)
0876f84a 4689 return ch;
2acceee2
JM
4690
4691 switch ((enum serial_rc) ch)
c906108c
SS
4692 {
4693 case SERIAL_EOF:
2acceee2 4694 target_mourn_inferior ();
8a3fe4f8 4695 error (_("Remote connection closed"));
2acceee2 4696 /* no return */
c906108c 4697 case SERIAL_ERROR:
e2e0b3e5 4698 perror_with_name (_("Remote communication error"));
2acceee2 4699 /* no return */
c906108c 4700 case SERIAL_TIMEOUT:
2acceee2 4701 break;
c906108c 4702 }
2acceee2 4703 return ch;
c906108c
SS
4704}
4705
6d820c5c
DJ
4706/* Send the command in *BUF to the remote machine, and read the reply
4707 into *BUF. Report an error if we get an error reply. Resize
4708 *BUF using xrealloc if necessary to hold the result, and update
4709 *SIZEOF_BUF. */
c906108c
SS
4710
4711static void
6d820c5c
DJ
4712remote_send (char **buf,
4713 long *sizeof_buf)
c906108c 4714{
6d820c5c 4715 putpkt (*buf);
c2d11a7d 4716 getpkt (buf, sizeof_buf, 0);
c906108c 4717
6d820c5c
DJ
4718 if ((*buf)[0] == 'E')
4719 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
4720}
4721
4722/* Display a null-terminated packet on stdout, for debugging, using C
4723 string notation. */
4724
4725static void
fba45db2 4726print_packet (char *buf)
c906108c
SS
4727{
4728 puts_filtered ("\"");
43e526b9 4729 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
4730 puts_filtered ("\"");
4731}
4732
4733int
fba45db2 4734putpkt (char *buf)
c906108c
SS
4735{
4736 return putpkt_binary (buf, strlen (buf));
4737}
4738
4739/* Send a packet to the remote machine, with error checking. The data
23860348 4740 of the packet is in BUF. The string in BUF can be at most
ea9c271d 4741 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
4742 and for a possible /0 if we are debugging (remote_debug) and want
4743 to print the sent packet as a string. */
c906108c
SS
4744
4745static int
fba45db2 4746putpkt_binary (char *buf, int cnt)
c906108c 4747{
2d717e4f 4748 struct remote_state *rs = get_remote_state ();
c906108c
SS
4749 int i;
4750 unsigned char csum = 0;
11cf8741 4751 char *buf2 = alloca (cnt + 6);
085dd6e6 4752
c906108c
SS
4753 int ch;
4754 int tcount = 0;
4755 char *p;
4756
2d717e4f
DJ
4757 /* We're sending out a new packet. Make sure we don't look at a
4758 stale cached response. */
4759 rs->cached_wait_status = 0;
4760
c906108c
SS
4761 /* Copy the packet into buffer BUF2, encapsulating it
4762 and giving it a checksum. */
4763
c906108c
SS
4764 p = buf2;
4765 *p++ = '$';
4766
4767 for (i = 0; i < cnt; i++)
4768 {
4769 csum += buf[i];
4770 *p++ = buf[i];
4771 }
4772 *p++ = '#';
4773 *p++ = tohex ((csum >> 4) & 0xf);
4774 *p++ = tohex (csum & 0xf);
4775
4776 /* Send it over and over until we get a positive ack. */
4777
4778 while (1)
4779 {
4780 int started_error_output = 0;
4781
4782 if (remote_debug)
4783 {
4784 *p = '\0';
43e526b9
JM
4785 fprintf_unfiltered (gdb_stdlog, "Sending packet: ");
4786 fputstrn_unfiltered (buf2, p - buf2, 0, gdb_stdlog);
d4f3574e 4787 fprintf_unfiltered (gdb_stdlog, "...");
0f71a2f6 4788 gdb_flush (gdb_stdlog);
c906108c 4789 }
2cd58942 4790 if (serial_write (remote_desc, buf2, p - buf2))
e2e0b3e5 4791 perror_with_name (_("putpkt: write failed"));
c906108c 4792
23860348 4793 /* Read until either a timeout occurs (-2) or '+' is read. */
c906108c
SS
4794 while (1)
4795 {
4796 ch = readchar (remote_timeout);
4797
c5aa993b 4798 if (remote_debug)
c906108c
SS
4799 {
4800 switch (ch)
4801 {
4802 case '+':
1216fa2c 4803 case '-':
c906108c
SS
4804 case SERIAL_TIMEOUT:
4805 case '$':
4806 if (started_error_output)
4807 {
4808 putchar_unfiltered ('\n');
4809 started_error_output = 0;
4810 }
4811 }
4812 }
4813
4814 switch (ch)
4815 {
4816 case '+':
4817 if (remote_debug)
0f71a2f6 4818 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 4819 return 1;
1216fa2c
AC
4820 case '-':
4821 if (remote_debug)
4822 fprintf_unfiltered (gdb_stdlog, "Nak\n");
c906108c 4823 case SERIAL_TIMEOUT:
c5aa993b 4824 tcount++;
c906108c
SS
4825 if (tcount > 3)
4826 return 0;
23860348 4827 break; /* Retransmit buffer. */
c906108c
SS
4828 case '$':
4829 {
40e3f985 4830 if (remote_debug)
2bc416ba 4831 fprintf_unfiltered (gdb_stdlog,
23860348 4832 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
4833 /* It's probably an old response sent because an ACK
4834 was lost. Gobble up the packet and ack it so it
4835 doesn't get retransmitted when we resend this
4836 packet. */
6d820c5c 4837 skip_frame ();
d6f7abdf 4838 serial_write (remote_desc, "+", 1);
23860348 4839 continue; /* Now, go look for +. */
c906108c
SS
4840 }
4841 default:
4842 if (remote_debug)
4843 {
4844 if (!started_error_output)
4845 {
4846 started_error_output = 1;
0f71a2f6 4847 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 4848 }
0f71a2f6 4849 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
4850 }
4851 continue;
4852 }
23860348 4853 break; /* Here to retransmit. */
c906108c
SS
4854 }
4855
4856#if 0
4857 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
4858 able to get out next time we call QUIT, without anything as
4859 violent as interrupt_query. If we want to provide a way out of
4860 here without getting to the next QUIT, it should be based on
4861 hitting ^C twice as in remote_wait. */
c906108c
SS
4862 if (quit_flag)
4863 {
4864 quit_flag = 0;
4865 interrupt_query ();
4866 }
4867#endif
4868 }
4869}
4870
6d820c5c
DJ
4871/* Come here after finding the start of a frame when we expected an
4872 ack. Do our best to discard the rest of this packet. */
4873
4874static void
4875skip_frame (void)
4876{
4877 int c;
4878
4879 while (1)
4880 {
4881 c = readchar (remote_timeout);
4882 switch (c)
4883 {
4884 case SERIAL_TIMEOUT:
4885 /* Nothing we can do. */
4886 return;
4887 case '#':
4888 /* Discard the two bytes of checksum and stop. */
4889 c = readchar (remote_timeout);
4890 if (c >= 0)
4891 c = readchar (remote_timeout);
4892
4893 return;
4894 case '*': /* Run length encoding. */
4895 /* Discard the repeat count. */
4896 c = readchar (remote_timeout);
4897 if (c < 0)
4898 return;
4899 break;
4900 default:
4901 /* A regular character. */
4902 break;
4903 }
4904 }
4905}
4906
c906108c 4907/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
4908 into *BUF, verifying the checksum, length, and handling run-length
4909 compression. NUL terminate the buffer. If there is not enough room,
4910 expand *BUF using xrealloc.
c906108c 4911
c2d11a7d
JM
4912 Returns -1 on error, number of characters in buffer (ignoring the
4913 trailing NULL) on success. (could be extended to return one of the
23860348 4914 SERIAL status indications). */
c2d11a7d
JM
4915
4916static long
6d820c5c
DJ
4917read_frame (char **buf_p,
4918 long *sizeof_buf)
c906108c
SS
4919{
4920 unsigned char csum;
c2d11a7d 4921 long bc;
c906108c 4922 int c;
6d820c5c 4923 char *buf = *buf_p;
c906108c
SS
4924
4925 csum = 0;
c2d11a7d 4926 bc = 0;
c906108c
SS
4927
4928 while (1)
4929 {
4930 c = readchar (remote_timeout);
c906108c
SS
4931 switch (c)
4932 {
4933 case SERIAL_TIMEOUT:
4934 if (remote_debug)
0f71a2f6 4935 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 4936 return -1;
c906108c
SS
4937 case '$':
4938 if (remote_debug)
0f71a2f6
JM
4939 fputs_filtered ("Saw new packet start in middle of old one\n",
4940 gdb_stdlog);
23860348 4941 return -1; /* Start a new packet, count retries. */
c906108c
SS
4942 case '#':
4943 {
4944 unsigned char pktcsum;
e1b09194
AC
4945 int check_0 = 0;
4946 int check_1 = 0;
c906108c 4947
c2d11a7d 4948 buf[bc] = '\0';
c906108c 4949
e1b09194
AC
4950 check_0 = readchar (remote_timeout);
4951 if (check_0 >= 0)
4952 check_1 = readchar (remote_timeout);
802188a7 4953
e1b09194
AC
4954 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
4955 {
4956 if (remote_debug)
2bc416ba 4957 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 4958 gdb_stdlog);
e1b09194
AC
4959 return -1;
4960 }
4961 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
4962 {
4963 if (remote_debug)
2bc416ba 4964 fputs_filtered ("Communication error in checksum\n",
23860348 4965 gdb_stdlog);
40e3f985
FN
4966 return -1;
4967 }
c906108c 4968
e1b09194 4969 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 4970 if (csum == pktcsum)
c2d11a7d 4971 return bc;
c906108c 4972
c5aa993b 4973 if (remote_debug)
c906108c 4974 {
0f71a2f6 4975 fprintf_filtered (gdb_stdlog,
c5aa993b 4976 "Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
0f71a2f6 4977 pktcsum, csum);
0876f84a 4978 fputstrn_filtered (buf, bc, 0, gdb_stdlog);
0f71a2f6 4979 fputs_filtered ("\n", gdb_stdlog);
c906108c 4980 }
c2d11a7d 4981 /* Number of characters in buffer ignoring trailing
23860348 4982 NULL. */
c2d11a7d 4983 return -1;
c906108c 4984 }
23860348 4985 case '*': /* Run length encoding. */
c2c6d25f
JM
4986 {
4987 int repeat;
4988 csum += c;
c906108c 4989
b4501125
AC
4990 c = readchar (remote_timeout);
4991 csum += c;
23860348 4992 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 4993
23860348 4994 /* The character before ``*'' is repeated. */
c2d11a7d 4995
6d820c5c 4996 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 4997 {
6d820c5c
DJ
4998 if (bc + repeat - 1 >= *sizeof_buf - 1)
4999 {
5000 /* Make some more room in the buffer. */
5001 *sizeof_buf += repeat;
5002 *buf_p = xrealloc (*buf_p, *sizeof_buf);
5003 buf = *buf_p;
5004 }
5005
c2d11a7d
JM
5006 memset (&buf[bc], buf[bc - 1], repeat);
5007 bc += repeat;
c2c6d25f
JM
5008 continue;
5009 }
5010
c2d11a7d 5011 buf[bc] = '\0';
6d820c5c 5012 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 5013 return -1;
c2c6d25f 5014 }
c906108c 5015 default:
6d820c5c 5016 if (bc >= *sizeof_buf - 1)
c906108c 5017 {
6d820c5c
DJ
5018 /* Make some more room in the buffer. */
5019 *sizeof_buf *= 2;
5020 *buf_p = xrealloc (*buf_p, *sizeof_buf);
5021 buf = *buf_p;
c906108c
SS
5022 }
5023
6d820c5c
DJ
5024 buf[bc++] = c;
5025 csum += c;
5026 continue;
c906108c
SS
5027 }
5028 }
5029}
5030
5031/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
5032 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
5033 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
5034 rather than timing out; this is used (in synchronous mode) to wait
5035 for a target that is is executing user code to stop. */
d9fcf2fb
JM
5036/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
5037 don't have to change all the calls to getpkt to deal with the
5038 return value, because at the moment I don't know what the right
23860348 5039 thing to do it for those. */
c906108c 5040void
6d820c5c
DJ
5041getpkt (char **buf,
5042 long *sizeof_buf,
c2d11a7d 5043 int forever)
d9fcf2fb
JM
5044{
5045 int timed_out;
5046
5047 timed_out = getpkt_sane (buf, sizeof_buf, forever);
5048}
5049
5050
5051/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
5052 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
5053 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
5054 rather than timing out; this is used (in synchronous mode) to wait
5055 for a target that is is executing user code to stop. If FOREVER ==
5056 0, this function is allowed to time out gracefully and return an
0876f84a
DJ
5057 indication of this to the caller. Otherwise return the number
5058 of bytes read. */
3172dc30 5059static int
6d820c5c 5060getpkt_sane (char **buf, long *sizeof_buf, int forever)
c906108c 5061{
2d717e4f 5062 struct remote_state *rs = get_remote_state ();
c906108c
SS
5063 int c;
5064 int tries;
5065 int timeout;
5066 int val;
5067
2d717e4f
DJ
5068 /* We're reading a new response. Make sure we don't look at a
5069 previously cached response. */
5070 rs->cached_wait_status = 0;
5071
6d820c5c 5072 strcpy (*buf, "timeout");
c906108c
SS
5073
5074 if (forever)
5075 {
c906108c 5076 timeout = watchdog > 0 ? watchdog : -1;
c906108c
SS
5077 }
5078
5079 else
5080 timeout = remote_timeout;
5081
5082#define MAX_TRIES 3
5083
5084 for (tries = 1; tries <= MAX_TRIES; tries++)
5085 {
5086 /* This can loop forever if the remote side sends us characters
23860348
MS
5087 continuously, but if it pauses, we'll get a zero from
5088 readchar because of timeout. Then we'll count that as a
5089 retry. */
c906108c 5090
23860348
MS
5091 /* Note that we will only wait forever prior to the start of a
5092 packet. After that, we expect characters to arrive at a
5093 brisk pace. They should show up within remote_timeout
5094 intervals. */
c906108c
SS
5095
5096 do
5097 {
5098 c = readchar (timeout);
5099
5100 if (c == SERIAL_TIMEOUT)
5101 {
23860348 5102 if (forever) /* Watchdog went off? Kill the target. */
c906108c 5103 {
2acceee2 5104 QUIT;
c906108c 5105 target_mourn_inferior ();
489eaeba 5106 error (_("Watchdog timeout has expired. Target detached."));
c906108c 5107 }
c906108c 5108 if (remote_debug)
0f71a2f6 5109 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c
SS
5110 goto retry;
5111 }
5112 }
5113 while (c != '$');
5114
5115 /* We've found the start of a packet, now collect the data. */
5116
c2d11a7d 5117 val = read_frame (buf, sizeof_buf);
c906108c 5118
c2d11a7d 5119 if (val >= 0)
c906108c
SS
5120 {
5121 if (remote_debug)
43e526b9
JM
5122 {
5123 fprintf_unfiltered (gdb_stdlog, "Packet received: ");
0876f84a 5124 fputstrn_unfiltered (*buf, val, 0, gdb_stdlog);
43e526b9
JM
5125 fprintf_unfiltered (gdb_stdlog, "\n");
5126 }
2cd58942 5127 serial_write (remote_desc, "+", 1);
0876f84a 5128 return val;
c906108c
SS
5129 }
5130
5131 /* Try the whole thing again. */
5132 retry:
2cd58942 5133 serial_write (remote_desc, "-", 1);
c906108c
SS
5134 }
5135
2bc416ba 5136 /* We have tried hard enough, and just can't receive the packet.
23860348 5137 Give up. */
c906108c 5138
a3f17187 5139 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
2cd58942 5140 serial_write (remote_desc, "+", 1);
0876f84a 5141 return -1;
c906108c
SS
5142}
5143\f
5144static void
fba45db2 5145remote_kill (void)
43ff13b4 5146{
23860348 5147 /* Unregister the file descriptor from the event loop. */
ed9a39eb 5148 if (target_is_async_p ())
2cd58942 5149 serial_async (remote_desc, NULL, 0);
43ff13b4 5150
23860348
MS
5151 /* Use catch_errors so the user can quit from gdb even when we
5152 aren't on speaking terms with the remote system. */
c5aa993b 5153 catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
43ff13b4
JM
5154
5155 /* Don't wait for it to die. I'm not really sure it matters whether
5156 we do or not. For the existing stubs, kill is a noop. */
5157 target_mourn_inferior ();
5158}
5159
c906108c 5160static void
fba45db2 5161remote_mourn (void)
c906108c
SS
5162{
5163 remote_mourn_1 (&remote_ops);
5164}
5165
c906108c
SS
5166/* Worker function for remote_mourn. */
5167static void
fba45db2 5168remote_mourn_1 (struct target_ops *target)
c906108c
SS
5169{
5170 unpush_target (target);
5171 generic_mourn_inferior ();
5172}
5173
2d717e4f
DJ
5174static void
5175extended_remote_mourn_1 (struct target_ops *target)
5176{
5177 struct remote_state *rs = get_remote_state ();
c906108c 5178
2d717e4f
DJ
5179 /* Unlike "target remote", we do not want to unpush the target; then
5180 the next time the user says "run", we won't be connected. */
5181
5182 /* Call common code to mark the inferior as not running. */
5183 generic_mourn_inferior ();
5184
5185 /* Check whether the target is running now - some remote stubs
5186 automatically restart after kill. */
5187 putpkt ("?");
5188 getpkt (&rs->buf, &rs->buf_size, 0);
5189
5190 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
5191 {
5192 /* Assume that the target has been restarted. Set inferior_ptid
5193 so that bits of core GDB realizes there's something here, e.g.,
5194 so that the user can say "kill" again. */
c0a2216e
PA
5195 inferior_ptid = remote_current_thread (magic_null_ptid);
5196 add_thread_silent (inferior_ptid);
2d717e4f
DJ
5197 }
5198 else
5199 {
5200 /* Mark this (still pushed) target as not executable until we
5201 restart it. */
5202 target_mark_exited (target);
5203 }
5204}
c906108c
SS
5205
5206static void
2d717e4f 5207extended_remote_mourn (void)
c906108c 5208{
2d717e4f
DJ
5209 extended_remote_mourn_1 (&extended_remote_ops);
5210}
c906108c 5211
2d717e4f
DJ
5212static int
5213extended_remote_run (char *args)
5214{
5215 struct remote_state *rs = get_remote_state ();
5216 char *p;
5217 int len;
c906108c 5218
2d717e4f
DJ
5219 /* If the user has disabled vRun support, or we have detected that
5220 support is not available, do not try it. */
5221 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
5222 return -1;
424163ea 5223
2d717e4f
DJ
5224 strcpy (rs->buf, "vRun;");
5225 len = strlen (rs->buf);
c906108c 5226
2d717e4f
DJ
5227 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
5228 error (_("Remote file name too long for run packet"));
5229 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
5230
5231 if (*args)
5232 {
5233 struct cleanup *back_to;
5234 int i;
5235 char **argv;
5236
5237 argv = buildargv (args);
5238 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
5239 for (i = 0; argv[i] != NULL; i++)
5240 {
5241 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
5242 error (_("Argument list too long for run packet"));
5243 rs->buf[len++] = ';';
5244 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
5245 }
5246 do_cleanups (back_to);
5247 }
5248
5249 rs->buf[len++] = '\0';
5250
5251 putpkt (rs->buf);
5252 getpkt (&rs->buf, &rs->buf_size, 0);
5253
5254 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
5255 {
5256 /* We have a wait response; we don't need it, though. All is well. */
5257 return 0;
5258 }
5259 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
5260 /* It wasn't disabled before, but it is now. */
5261 return -1;
5262 else
5263 {
5264 if (remote_exec_file[0] == '\0')
5265 error (_("Running the default executable on the remote target failed; "
5266 "try \"set remote exec-file\"?"));
5267 else
5268 error (_("Running \"%s\" on the remote target failed"),
5269 remote_exec_file);
5270 }
c906108c
SS
5271}
5272
2d717e4f
DJ
5273/* In the extended protocol we want to be able to do things like
5274 "run" and have them basically work as expected. So we need
5275 a special create_inferior function. We support changing the
5276 executable file and the command line arguments, but not the
5277 environment. */
5278
43ff13b4 5279static void
2d717e4f 5280extended_remote_create_inferior_1 (char *exec_file, char *args,
75c99385 5281 char **env, int from_tty)
43ff13b4 5282{
43ff13b4 5283 /* If running asynchronously, register the target file descriptor
23860348 5284 with the event loop. */
75c99385 5285 if (target_can_async_p ())
2acceee2 5286 target_async (inferior_event_handler, 0);
43ff13b4
JM
5287
5288 /* Now restart the remote server. */
2d717e4f
DJ
5289 if (extended_remote_run (args) == -1)
5290 {
5291 /* vRun was not supported. Fail if we need it to do what the
5292 user requested. */
5293 if (remote_exec_file[0])
5294 error (_("Remote target does not support \"set remote exec-file\""));
5295 if (args[0])
5296 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 5297
2d717e4f
DJ
5298 /* Fall back to "R". */
5299 extended_remote_restart ();
5300 }
424163ea 5301
45280a52
DJ
5302 /* Clean up from the last time we ran, before we mark the target
5303 running again. This will mark breakpoints uninserted, and
5304 get_offsets may insert breakpoints. */
5305 init_thread_list ();
5306 init_wait_for_inferior ();
5307
2d717e4f 5308 /* Now mark the inferior as running before we do anything else. */
df7df359 5309 attach_flag = 0;
79d7f229 5310 inferior_ptid = magic_null_ptid;
c0a2216e
PA
5311
5312 add_thread_silent (inferior_ptid);
5313
75c99385 5314 target_mark_running (&extended_remote_ops);
2d717e4f
DJ
5315
5316 /* Get updated offsets, if the stub uses qOffsets. */
5317 get_offsets ();
2d717e4f
DJ
5318}
5319
5320static void
5321extended_remote_create_inferior (char *exec_file, char *args,
5322 char **env, int from_tty)
5323{
75c99385 5324 extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
43ff13b4 5325}
c906108c 5326\f
c5aa993b 5327
8181d85f
DJ
5328/* Insert a breakpoint. On targets that have software breakpoint
5329 support, we ask the remote target to do the work; on targets
5330 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
5331
5332static int
8181d85f 5333remote_insert_breakpoint (struct bp_target_info *bp_tgt)
c906108c 5334{
d471ea57
AC
5335 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
5336 If it succeeds, then set the support to PACKET_ENABLE. If it
5337 fails, and the user has explicitly requested the Z support then
23860348 5338 report an error, otherwise, mark it disabled and go on. */
802188a7 5339
444abaca 5340 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
96baa820 5341 {
7c0f6dcc 5342 CORE_ADDR addr = bp_tgt->placed_address;
4fff2411
JZ
5343 struct remote_state *rs;
5344 char *p;
7c0f6dcc 5345 int bpsize;
4fff2411
JZ
5346
5347 gdbarch_breakpoint_from_pc
7c0f6dcc 5348 (current_gdbarch, &addr, &bpsize);
4fff2411
JZ
5349
5350 rs = get_remote_state ();
5351 p = rs->buf;
802188a7 5352
96baa820
JM
5353 *(p++) = 'Z';
5354 *(p++) = '0';
5355 *(p++) = ',';
7c0f6dcc 5356 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 5357 p += hexnumstr (p, addr);
7c0f6dcc 5358 sprintf (p, ",%d", bpsize);
802188a7 5359
6d820c5c
DJ
5360 putpkt (rs->buf);
5361 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 5362
6d820c5c 5363 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 5364 {
d471ea57
AC
5365 case PACKET_ERROR:
5366 return -1;
5367 case PACKET_OK:
7c0f6dcc
JL
5368 bp_tgt->placed_address = addr;
5369 bp_tgt->placed_size = bpsize;
d471ea57
AC
5370 return 0;
5371 case PACKET_UNKNOWN:
5372 break;
96baa820
JM
5373 }
5374 }
c906108c 5375
8181d85f 5376 return memory_insert_breakpoint (bp_tgt);
c906108c
SS
5377}
5378
5379static int
8181d85f 5380remote_remove_breakpoint (struct bp_target_info *bp_tgt)
c906108c 5381{
8181d85f 5382 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 5383 struct remote_state *rs = get_remote_state ();
96baa820
JM
5384 int bp_size;
5385
444abaca 5386 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
96baa820 5387 {
6d820c5c 5388 char *p = rs->buf;
802188a7 5389
96baa820
JM
5390 *(p++) = 'z';
5391 *(p++) = '0';
5392 *(p++) = ',';
5393
8181d85f
DJ
5394 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
5395 p += hexnumstr (p, addr);
5396 sprintf (p, ",%d", bp_tgt->placed_size);
802188a7 5397
6d820c5c
DJ
5398 putpkt (rs->buf);
5399 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 5400
6d820c5c 5401 return (rs->buf[0] == 'E');
96baa820
JM
5402 }
5403
8181d85f 5404 return memory_remove_breakpoint (bp_tgt);
c906108c
SS
5405}
5406
d471ea57
AC
5407static int
5408watchpoint_to_Z_packet (int type)
5409{
5410 switch (type)
5411 {
5412 case hw_write:
bb858e6a 5413 return Z_PACKET_WRITE_WP;
d471ea57
AC
5414 break;
5415 case hw_read:
bb858e6a 5416 return Z_PACKET_READ_WP;
d471ea57
AC
5417 break;
5418 case hw_access:
bb858e6a 5419 return Z_PACKET_ACCESS_WP;
d471ea57
AC
5420 break;
5421 default:
8e65ff28 5422 internal_error (__FILE__, __LINE__,
e2e0b3e5 5423 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
5424 }
5425}
5426
3c3bea1c 5427static int
fba45db2 5428remote_insert_watchpoint (CORE_ADDR addr, int len, int type)
96baa820 5429{
d01949b6 5430 struct remote_state *rs = get_remote_state ();
e514a9d6 5431 char *p;
d471ea57 5432 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 5433
444abaca 5434 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
5cffb350 5435 return -1;
802188a7 5436
6d820c5c
DJ
5437 sprintf (rs->buf, "Z%x,", packet);
5438 p = strchr (rs->buf, '\0');
96baa820
JM
5439 addr = remote_address_masked (addr);
5440 p += hexnumstr (p, (ULONGEST) addr);
d4f3574e 5441 sprintf (p, ",%x", len);
802188a7 5442
6d820c5c
DJ
5443 putpkt (rs->buf);
5444 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 5445
6d820c5c 5446 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
5447 {
5448 case PACKET_ERROR:
5449 case PACKET_UNKNOWN:
5450 return -1;
5451 case PACKET_OK:
5452 return 0;
5453 }
8e65ff28 5454 internal_error (__FILE__, __LINE__,
e2e0b3e5 5455 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
5456}
5457
d471ea57 5458
3c3bea1c 5459static int
fba45db2 5460remote_remove_watchpoint (CORE_ADDR addr, int len, int type)
96baa820 5461{
d01949b6 5462 struct remote_state *rs = get_remote_state ();
e514a9d6 5463 char *p;
d471ea57
AC
5464 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
5465
444abaca 5466 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
5cffb350 5467 return -1;
802188a7 5468
6d820c5c
DJ
5469 sprintf (rs->buf, "z%x,", packet);
5470 p = strchr (rs->buf, '\0');
96baa820
JM
5471 addr = remote_address_masked (addr);
5472 p += hexnumstr (p, (ULONGEST) addr);
d4f3574e 5473 sprintf (p, ",%x", len);
6d820c5c
DJ
5474 putpkt (rs->buf);
5475 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 5476
6d820c5c 5477 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
5478 {
5479 case PACKET_ERROR:
5480 case PACKET_UNKNOWN:
5481 return -1;
5482 case PACKET_OK:
5483 return 0;
5484 }
8e65ff28 5485 internal_error (__FILE__, __LINE__,
e2e0b3e5 5486 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
5487}
5488
3c3bea1c 5489
501eef12
AC
5490int remote_hw_watchpoint_limit = -1;
5491int remote_hw_breakpoint_limit = -1;
d471ea57 5492
b9362cc7 5493static int
3c3bea1c 5494remote_check_watch_resources (int type, int cnt, int ot)
96baa820 5495{
3c3bea1c
GS
5496 if (type == bp_hardware_breakpoint)
5497 {
5498 if (remote_hw_breakpoint_limit == 0)
5499 return 0;
501eef12
AC
5500 else if (remote_hw_breakpoint_limit < 0)
5501 return 1;
3c3bea1c
GS
5502 else if (cnt <= remote_hw_breakpoint_limit)
5503 return 1;
5504 }
5505 else
5506 {
5507 if (remote_hw_watchpoint_limit == 0)
5508 return 0;
501eef12
AC
5509 else if (remote_hw_watchpoint_limit < 0)
5510 return 1;
3c3bea1c
GS
5511 else if (ot)
5512 return -1;
5513 else if (cnt <= remote_hw_watchpoint_limit)
5514 return 1;
5515 }
5516 return -1;
5517}
5518
b9362cc7 5519static int
3c3bea1c
GS
5520remote_stopped_by_watchpoint (void)
5521{
5522 return remote_stopped_by_watchpoint_p;
5523}
5524
4aa7a7f5
JJ
5525static int
5526remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 5527{
4aa7a7f5 5528 int rc = 0;
d983da9c 5529 if (remote_stopped_by_watchpoint ())
4aa7a7f5
JJ
5530 {
5531 *addr_p = remote_watch_data_address;
5532 rc = 1;
5533 }
5534
5535 return rc;
3c3bea1c
GS
5536}
5537
5538
5539static int
8181d85f 5540remote_insert_hw_breakpoint (struct bp_target_info *bp_tgt)
3c3bea1c 5541{
8181d85f 5542 CORE_ADDR addr;
4fff2411
JZ
5543 struct remote_state *rs;
5544 char *p;
802188a7 5545
c8189ed1 5546 /* The length field should be set to the size of a breakpoint
8181d85f 5547 instruction, even though we aren't inserting one ourselves. */
c8189ed1 5548
3b3b875c
UW
5549 gdbarch_breakpoint_from_pc
5550 (current_gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
3c3bea1c 5551
444abaca 5552 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5cffb350 5553 return -1;
2bc416ba 5554
4fff2411
JZ
5555 rs = get_remote_state ();
5556 p = rs->buf;
5557
96baa820
JM
5558 *(p++) = 'Z';
5559 *(p++) = '1';
5560 *(p++) = ',';
802188a7 5561
8181d85f 5562 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 5563 p += hexnumstr (p, (ULONGEST) addr);
8181d85f 5564 sprintf (p, ",%x", bp_tgt->placed_size);
96baa820 5565
6d820c5c
DJ
5566 putpkt (rs->buf);
5567 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 5568
6d820c5c 5569 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
5570 {
5571 case PACKET_ERROR:
5572 case PACKET_UNKNOWN:
5573 return -1;
5574 case PACKET_OK:
5575 return 0;
5576 }
8e65ff28 5577 internal_error (__FILE__, __LINE__,
e2e0b3e5 5578 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
5579}
5580
d471ea57 5581
802188a7 5582static int
8181d85f 5583remote_remove_hw_breakpoint (struct bp_target_info *bp_tgt)
96baa820 5584{
8181d85f 5585 CORE_ADDR addr;
d01949b6 5586 struct remote_state *rs = get_remote_state ();
6d820c5c 5587 char *p = rs->buf;
c8189ed1 5588
444abaca 5589 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5cffb350 5590 return -1;
802188a7 5591
96baa820
JM
5592 *(p++) = 'z';
5593 *(p++) = '1';
5594 *(p++) = ',';
802188a7 5595
8181d85f 5596 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 5597 p += hexnumstr (p, (ULONGEST) addr);
8181d85f 5598 sprintf (p, ",%x", bp_tgt->placed_size);
96baa820 5599
6d820c5c
DJ
5600 putpkt (rs->buf);
5601 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 5602
6d820c5c 5603 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
5604 {
5605 case PACKET_ERROR:
5606 case PACKET_UNKNOWN:
5607 return -1;
5608 case PACKET_OK:
5609 return 0;
5610 }
8e65ff28 5611 internal_error (__FILE__, __LINE__,
e2e0b3e5 5612 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 5613}
96baa820 5614
c906108c
SS
5615/* Some targets are only capable of doing downloads, and afterwards
5616 they switch to the remote serial protocol. This function provides
5617 a clean way to get from the download target to the remote target.
5618 It's basically just a wrapper so that we don't have to expose any
5619 of the internal workings of remote.c.
5620
5621 Prior to calling this routine, you should shutdown the current
5622 target code, else you will get the "A program is being debugged
5623 already..." message. Usually a call to pop_target() suffices. */
5624
5625void
fba45db2 5626push_remote_target (char *name, int from_tty)
c906108c 5627{
a3f17187 5628 printf_filtered (_("Switching to remote protocol\n"));
c906108c
SS
5629 remote_open (name, from_tty);
5630}
5631
23860348 5632/* Table used by the crc32 function to calcuate the checksum. */
c906108c 5633
c5aa993b
JM
5634static unsigned long crc32_table[256] =
5635{0, 0};
c906108c
SS
5636
5637static unsigned long
fba45db2 5638crc32 (unsigned char *buf, int len, unsigned int crc)
c906108c 5639{
c5aa993b 5640 if (!crc32_table[1])
c906108c 5641 {
23860348 5642 /* Initialize the CRC table and the decoding table. */
c906108c
SS
5643 int i, j;
5644 unsigned int c;
5645
5646 for (i = 0; i < 256; i++)
c5aa993b
JM
5647 {
5648 for (c = i << 24, j = 8; j > 0; --j)
5649 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
5650 crc32_table[i] = c;
5651 }
c906108c
SS
5652 }
5653
5654 while (len--)
5655 {
5656 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
5657 buf++;
5658 }
5659 return crc;
5660}
5661
5662/* compare-sections command
5663
5664 With no arguments, compares each loadable section in the exec bfd
5665 with the same memory range on the target, and reports mismatches.
5666 Useful for verifying the image on the target against the exec file.
5667 Depends on the target understanding the new "qCRC:" request. */
5668
e514a9d6
JM
5669/* FIXME: cagney/1999-10-26: This command should be broken down into a
5670 target method (target verify memory) and generic version of the
5671 actual command. This will allow other high-level code (especially
23860348 5672 generic_load()) to make use of this target functionality. */
e514a9d6 5673
c906108c 5674static void
fba45db2 5675compare_sections_command (char *args, int from_tty)
c906108c 5676{
d01949b6 5677 struct remote_state *rs = get_remote_state ();
c906108c
SS
5678 asection *s;
5679 unsigned long host_crc, target_crc;
5680 extern bfd *exec_bfd;
5681 struct cleanup *old_chain;
085dd6e6
JM
5682 char *tmp;
5683 char *sectdata;
ce359b09 5684 const char *sectname;
c906108c
SS
5685 bfd_size_type size;
5686 bfd_vma lma;
5687 int matched = 0;
5688 int mismatched = 0;
5689
5690 if (!exec_bfd)
8a3fe4f8 5691 error (_("command cannot be used without an exec file"));
c906108c
SS
5692 if (!current_target.to_shortname ||
5693 strcmp (current_target.to_shortname, "remote") != 0)
8a3fe4f8 5694 error (_("command can only be used with remote target"));
c906108c 5695
c5aa993b 5696 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
5697 {
5698 if (!(s->flags & SEC_LOAD))
c5aa993b 5699 continue; /* skip non-loadable section */
c906108c 5700
2c500098 5701 size = bfd_get_section_size (s);
c906108c 5702 if (size == 0)
c5aa993b 5703 continue; /* skip zero-length section */
c906108c 5704
ce359b09 5705 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 5706 if (args && strcmp (args, sectname) != 0)
c5aa993b 5707 continue; /* not the section selected by user */
c906108c 5708
c5aa993b 5709 matched = 1; /* do this section */
c906108c 5710 lma = s->lma;
23860348 5711 /* FIXME: assumes lma can fit into long. */
ea9c271d 5712 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
ecbc58df 5713 (long) lma, (long) size);
6d820c5c 5714 putpkt (rs->buf);
c906108c 5715
23860348
MS
5716 /* Be clever; compute the host_crc before waiting for target
5717 reply. */
c906108c 5718 sectdata = xmalloc (size);
b8c9b27d 5719 old_chain = make_cleanup (xfree, sectdata);
c906108c
SS
5720 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
5721 host_crc = crc32 ((unsigned char *) sectdata, size, 0xffffffff);
5722
6d820c5c
DJ
5723 getpkt (&rs->buf, &rs->buf_size, 0);
5724 if (rs->buf[0] == 'E')
8a3fe4f8 5725 error (_("target memory fault, section %s, range 0x%s -- 0x%s"),
823ca731 5726 sectname, paddr (lma), paddr (lma + size));
6d820c5c 5727 if (rs->buf[0] != 'C')
8a3fe4f8 5728 error (_("remote target does not support this operation"));
c906108c 5729
6d820c5c 5730 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
c906108c
SS
5731 target_crc = target_crc * 16 + fromhex (*tmp);
5732
d4f3574e
SS
5733 printf_filtered ("Section %s, range 0x%s -- 0x%s: ",
5734 sectname, paddr (lma), paddr (lma + size));
c906108c
SS
5735 if (host_crc == target_crc)
5736 printf_filtered ("matched.\n");
5737 else
c5aa993b
JM
5738 {
5739 printf_filtered ("MIS-MATCHED!\n");
5740 mismatched++;
5741 }
c906108c
SS
5742
5743 do_cleanups (old_chain);
5744 }
5745 if (mismatched > 0)
8a3fe4f8
AC
5746 warning (_("One or more sections of the remote executable does not match\n\
5747the loaded file\n"));
c906108c 5748 if (args && !matched)
a3f17187 5749 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
5750}
5751
0e7f50da
UW
5752/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
5753 into remote target. The number of bytes written to the remote
5754 target is returned, or -1 for error. */
5755
5756static LONGEST
5757remote_write_qxfer (struct target_ops *ops, const char *object_name,
5758 const char *annex, const gdb_byte *writebuf,
5759 ULONGEST offset, LONGEST len,
5760 struct packet_config *packet)
5761{
5762 int i, buf_len;
5763 ULONGEST n;
5764 gdb_byte *wbuf;
5765 struct remote_state *rs = get_remote_state ();
5766 int max_size = get_memory_write_packet_size ();
5767
5768 if (packet->support == PACKET_DISABLE)
5769 return -1;
5770
5771 /* Insert header. */
5772 i = snprintf (rs->buf, max_size,
5773 "qXfer:%s:write:%s:%s:",
5774 object_name, annex ? annex : "",
5775 phex_nz (offset, sizeof offset));
5776 max_size -= (i + 1);
5777
5778 /* Escape as much data as fits into rs->buf. */
5779 buf_len = remote_escape_output
5780 (writebuf, len, (rs->buf + i), &max_size, max_size);
5781
5782 if (putpkt_binary (rs->buf, i + buf_len) < 0
5783 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
5784 || packet_ok (rs->buf, packet) != PACKET_OK)
5785 return -1;
5786
5787 unpack_varlen_hex (rs->buf, &n);
5788 return n;
5789}
5790
0876f84a
DJ
5791/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
5792 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
5793 number of bytes read is returned, or 0 for EOF, or -1 for error.
5794 The number of bytes read may be less than LEN without indicating an
5795 EOF. PACKET is checked and updated to indicate whether the remote
5796 target supports this object. */
5797
5798static LONGEST
5799remote_read_qxfer (struct target_ops *ops, const char *object_name,
5800 const char *annex,
5801 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
5802 struct packet_config *packet)
5803{
5804 static char *finished_object;
5805 static char *finished_annex;
5806 static ULONGEST finished_offset;
5807
5808 struct remote_state *rs = get_remote_state ();
5809 unsigned int total = 0;
5810 LONGEST i, n, packet_len;
5811
5812 if (packet->support == PACKET_DISABLE)
5813 return -1;
5814
5815 /* Check whether we've cached an end-of-object packet that matches
5816 this request. */
5817 if (finished_object)
5818 {
5819 if (strcmp (object_name, finished_object) == 0
5820 && strcmp (annex ? annex : "", finished_annex) == 0
5821 && offset == finished_offset)
5822 return 0;
5823
5824 /* Otherwise, we're now reading something different. Discard
5825 the cache. */
5826 xfree (finished_object);
5827 xfree (finished_annex);
5828 finished_object = NULL;
5829 finished_annex = NULL;
5830 }
5831
5832 /* Request only enough to fit in a single packet. The actual data
5833 may not, since we don't know how much of it will need to be escaped;
5834 the target is free to respond with slightly less data. We subtract
5835 five to account for the response type and the protocol frame. */
5836 n = min (get_remote_packet_size () - 5, len);
5837 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
5838 object_name, annex ? annex : "",
5839 phex_nz (offset, sizeof offset),
5840 phex_nz (n, sizeof n));
5841 i = putpkt (rs->buf);
5842 if (i < 0)
5843 return -1;
5844
5845 rs->buf[0] = '\0';
5846 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
5847 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
5848 return -1;
5849
5850 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
5851 error (_("Unknown remote qXfer reply: %s"), rs->buf);
5852
5853 /* 'm' means there is (or at least might be) more data after this
5854 batch. That does not make sense unless there's at least one byte
5855 of data in this reply. */
5856 if (rs->buf[0] == 'm' && packet_len == 1)
5857 error (_("Remote qXfer reply contained no data."));
5858
5859 /* Got some data. */
5860 i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
5861
5862 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
5863 or possibly empty. If we have the final block of a non-empty
5864 object, record this fact to bypass a subsequent partial read. */
5865 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a
DJ
5866 {
5867 finished_object = xstrdup (object_name);
5868 finished_annex = xstrdup (annex ? annex : "");
5869 finished_offset = offset + i;
5870 }
5871
5872 return i;
5873}
5874
1e3ff5ad 5875static LONGEST
4b8a223f 5876remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5
MK
5877 const char *annex, gdb_byte *readbuf,
5878 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
c906108c 5879{
d01949b6 5880 struct remote_state *rs = get_remote_state ();
c906108c 5881 int i;
6d820c5c 5882 char *p2;
1e3ff5ad 5883 char query_type;
c906108c 5884
b2182ed2 5885 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
5886 if (object == TARGET_OBJECT_MEMORY)
5887 {
5888 int xfered;
5889 errno = 0;
5890
2d717e4f
DJ
5891 /* If the remote target is connected but not running, we should
5892 pass this request down to a lower stratum (e.g. the executable
5893 file). */
5894 if (!target_has_execution)
5895 return 0;
5896
21e3b9b9 5897 if (writebuf != NULL)
b2182ed2 5898 xfered = remote_write_bytes (offset, writebuf, len);
21e3b9b9 5899 else
b2182ed2 5900 xfered = remote_read_bytes (offset, readbuf, len);
21e3b9b9
DJ
5901
5902 if (xfered > 0)
5903 return xfered;
5904 else if (xfered == 0 && errno == 0)
5905 return 0;
5906 else
5907 return -1;
5908 }
5909
0e7f50da
UW
5910 /* Handle SPU memory using qxfer packets. */
5911 if (object == TARGET_OBJECT_SPU)
5912 {
5913 if (readbuf)
5914 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
5915 &remote_protocol_packets
5916 [PACKET_qXfer_spu_read]);
5917 else
5918 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
5919 &remote_protocol_packets
5920 [PACKET_qXfer_spu_write]);
5921 }
5922
a76d924d
DJ
5923 /* Only handle flash writes. */
5924 if (writebuf != NULL)
5925 {
5926 LONGEST xfered;
5927
5928 switch (object)
5929 {
5930 case TARGET_OBJECT_FLASH:
5931 xfered = remote_flash_write (ops, offset, len, writebuf);
5932
5933 if (xfered > 0)
5934 return xfered;
5935 else if (xfered == 0 && errno == 0)
5936 return 0;
5937 else
5938 return -1;
5939
5940 default:
5941 return -1;
5942 }
5943 }
4b8a223f 5944
1e3ff5ad
AC
5945 /* Map pre-existing objects onto letters. DO NOT do this for new
5946 objects!!! Instead specify new query packets. */
5947 switch (object)
c906108c 5948 {
1e3ff5ad
AC
5949 case TARGET_OBJECT_AVR:
5950 query_type = 'R';
5951 break;
802188a7
RM
5952
5953 case TARGET_OBJECT_AUXV:
0876f84a
DJ
5954 gdb_assert (annex == NULL);
5955 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
5956 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 5957
23181151
DJ
5958 case TARGET_OBJECT_AVAILABLE_FEATURES:
5959 return remote_read_qxfer
5960 (ops, "features", annex, readbuf, offset, len,
5961 &remote_protocol_packets[PACKET_qXfer_features]);
5962
cfa9d6d9
DJ
5963 case TARGET_OBJECT_LIBRARIES:
5964 return remote_read_qxfer
5965 (ops, "libraries", annex, readbuf, offset, len,
5966 &remote_protocol_packets[PACKET_qXfer_libraries]);
5967
fd79ecee
DJ
5968 case TARGET_OBJECT_MEMORY_MAP:
5969 gdb_assert (annex == NULL);
5970 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
5971 &remote_protocol_packets[PACKET_qXfer_memory_map]);
5972
1e3ff5ad 5973 default:
c906108c
SS
5974 return -1;
5975 }
5976
4b8a223f 5977 /* Note: a zero OFFSET and LEN can be used to query the minimum
1e3ff5ad 5978 buffer size. */
4b8a223f 5979 if (offset == 0 && len == 0)
ea9c271d
DJ
5980 return (get_remote_packet_size ());
5981 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 5982 large enough let the caller deal with it. */
ea9c271d 5983 if (len < get_remote_packet_size ())
1e3ff5ad 5984 return -1;
ea9c271d 5985 len = get_remote_packet_size ();
1e3ff5ad 5986
23860348 5987 /* Except for querying the minimum buffer size, target must be open. */
c5aa993b 5988 if (!remote_desc)
8a3fe4f8 5989 error (_("remote query is only available after target open"));
c906108c 5990
1e3ff5ad 5991 gdb_assert (annex != NULL);
4b8a223f 5992 gdb_assert (readbuf != NULL);
c906108c 5993
6d820c5c 5994 p2 = rs->buf;
c906108c
SS
5995 *p2++ = 'q';
5996 *p2++ = query_type;
5997
23860348
MS
5998 /* We used one buffer char for the remote protocol q command and
5999 another for the query type. As the remote protocol encapsulation
6000 uses 4 chars plus one extra in case we are debugging
6001 (remote_debug), we have PBUFZIZ - 7 left to pack the query
6002 string. */
c906108c 6003 i = 0;
ea9c271d 6004 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 6005 {
1e3ff5ad
AC
6006 /* Bad caller may have sent forbidden characters. */
6007 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
6008 *p2++ = annex[i];
c906108c
SS
6009 i++;
6010 }
1e3ff5ad
AC
6011 *p2 = '\0';
6012 gdb_assert (annex[i] == '\0');
c906108c 6013
6d820c5c 6014 i = putpkt (rs->buf);
c5aa993b
JM
6015 if (i < 0)
6016 return i;
c906108c 6017
6d820c5c
DJ
6018 getpkt (&rs->buf, &rs->buf_size, 0);
6019 strcpy ((char *) readbuf, rs->buf);
c906108c 6020
cfd77fa1 6021 return strlen ((char *) readbuf);
c906108c
SS
6022}
6023
08388c79
DE
6024static int
6025remote_search_memory (struct target_ops* ops,
6026 CORE_ADDR start_addr, ULONGEST search_space_len,
6027 const gdb_byte *pattern, ULONGEST pattern_len,
6028 CORE_ADDR *found_addrp)
6029{
6030 struct remote_state *rs = get_remote_state ();
6031 int max_size = get_memory_write_packet_size ();
6032 struct packet_config *packet =
6033 &remote_protocol_packets[PACKET_qSearch_memory];
6034 /* number of packet bytes used to encode the pattern,
6035 this could be more than PATTERN_LEN due to escape characters */
6036 int escaped_pattern_len;
6037 /* amount of pattern that was encodable in the packet */
6038 int used_pattern_len;
6039 int i;
6040 int found;
6041 ULONGEST found_addr;
6042
6043 /* Don't go to the target if we don't have to.
6044 This is done before checking packet->support to avoid the possibility that
6045 a success for this edge case means the facility works in general. */
6046 if (pattern_len > search_space_len)
6047 return 0;
6048 if (pattern_len == 0)
6049 {
6050 *found_addrp = start_addr;
6051 return 1;
6052 }
6053
6054 /* If we already know the packet isn't supported, fall back to the simple
6055 way of searching memory. */
6056
6057 if (packet->support == PACKET_DISABLE)
6058 {
6059 /* Target doesn't provided special support, fall back and use the
6060 standard support (copy memory and do the search here). */
6061 return simple_search_memory (ops, start_addr, search_space_len,
6062 pattern, pattern_len, found_addrp);
6063 }
6064
6065 /* Insert header. */
6066 i = snprintf (rs->buf, max_size,
6067 "qSearch:memory:%s;%s;",
6068 paddr_nz (start_addr),
6069 phex_nz (search_space_len, sizeof (search_space_len)));
6070 max_size -= (i + 1);
6071
6072 /* Escape as much data as fits into rs->buf. */
6073 escaped_pattern_len =
6074 remote_escape_output (pattern, pattern_len, (rs->buf + i),
6075 &used_pattern_len, max_size);
6076
6077 /* Bail if the pattern is too large. */
6078 if (used_pattern_len != pattern_len)
10e0fa18 6079 error ("Pattern is too large to transmit to remote target.");
08388c79
DE
6080
6081 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
6082 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
6083 || packet_ok (rs->buf, packet) != PACKET_OK)
6084 {
6085 /* The request may not have worked because the command is not
6086 supported. If so, fall back to the simple way. */
6087 if (packet->support == PACKET_DISABLE)
6088 {
6089 return simple_search_memory (ops, start_addr, search_space_len,
6090 pattern, pattern_len, found_addrp);
6091 }
6092 return -1;
6093 }
6094
6095 if (rs->buf[0] == '0')
6096 found = 0;
6097 else if (rs->buf[0] == '1')
6098 {
6099 found = 1;
6100 if (rs->buf[1] != ',')
10e0fa18 6101 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
6102 unpack_varlen_hex (rs->buf + 2, &found_addr);
6103 *found_addrp = found_addr;
6104 }
6105 else
10e0fa18 6106 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
6107
6108 return found;
6109}
6110
96baa820
JM
6111static void
6112remote_rcmd (char *command,
d9fcf2fb 6113 struct ui_file *outbuf)
96baa820 6114{
d01949b6 6115 struct remote_state *rs = get_remote_state ();
2e9f7625 6116 char *p = rs->buf;
96baa820
JM
6117
6118 if (!remote_desc)
8a3fe4f8 6119 error (_("remote rcmd is only available after target open"));
96baa820 6120
23860348 6121 /* Send a NULL command across as an empty command. */
7be570e7
JM
6122 if (command == NULL)
6123 command = "";
6124
23860348 6125 /* The query prefix. */
2e9f7625
DJ
6126 strcpy (rs->buf, "qRcmd,");
6127 p = strchr (rs->buf, '\0');
96baa820 6128
2e9f7625 6129 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/) > get_remote_packet_size ())
8a3fe4f8 6130 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 6131
23860348 6132 /* Encode the actual command. */
cfd77fa1 6133 bin2hex ((gdb_byte *) command, p, 0);
96baa820 6134
6d820c5c 6135 if (putpkt (rs->buf) < 0)
8a3fe4f8 6136 error (_("Communication problem with target."));
96baa820
JM
6137
6138 /* get/display the response */
6139 while (1)
6140 {
2e9f7625
DJ
6141 char *buf;
6142
23860348 6143 /* XXX - see also tracepoint.c:remote_get_noisy_reply(). */
2e9f7625 6144 rs->buf[0] = '\0';
6d820c5c 6145 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 6146 buf = rs->buf;
96baa820 6147 if (buf[0] == '\0')
8a3fe4f8 6148 error (_("Target does not support this command."));
96baa820
JM
6149 if (buf[0] == 'O' && buf[1] != 'K')
6150 {
23860348 6151 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
6152 continue;
6153 }
6154 if (strcmp (buf, "OK") == 0)
6155 break;
7be570e7
JM
6156 if (strlen (buf) == 3 && buf[0] == 'E'
6157 && isdigit (buf[1]) && isdigit (buf[2]))
6158 {
8a3fe4f8 6159 error (_("Protocol error with Rcmd"));
7be570e7 6160 }
96baa820
JM
6161 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
6162 {
6163 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
6164 fputc_unfiltered (c, outbuf);
6165 }
6166 break;
6167 }
6168}
6169
fd79ecee
DJ
6170static VEC(mem_region_s) *
6171remote_memory_map (struct target_ops *ops)
6172{
6173 VEC(mem_region_s) *result = NULL;
6174 char *text = target_read_stralloc (&current_target,
6175 TARGET_OBJECT_MEMORY_MAP, NULL);
6176
6177 if (text)
6178 {
6179 struct cleanup *back_to = make_cleanup (xfree, text);
6180 result = parse_memory_map (text);
6181 do_cleanups (back_to);
6182 }
6183
6184 return result;
6185}
6186
c906108c 6187static void
fba45db2 6188packet_command (char *args, int from_tty)
c906108c 6189{
d01949b6 6190 struct remote_state *rs = get_remote_state ();
c906108c 6191
c5aa993b 6192 if (!remote_desc)
8a3fe4f8 6193 error (_("command can only be used with remote target"));
c906108c 6194
c5aa993b 6195 if (!args)
8a3fe4f8 6196 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
6197
6198 puts_filtered ("sending: ");
6199 print_packet (args);
6200 puts_filtered ("\n");
6201 putpkt (args);
6202
6d820c5c 6203 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 6204 puts_filtered ("received: ");
6d820c5c 6205 print_packet (rs->buf);
c906108c
SS
6206 puts_filtered ("\n");
6207}
6208
6209#if 0
23860348 6210/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 6211
a14ed312 6212static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 6213
a14ed312 6214static void threadset_test_cmd (char *cmd, int tty);
c906108c 6215
a14ed312 6216static void threadalive_test (char *cmd, int tty);
c906108c 6217
a14ed312 6218static void threadlist_test_cmd (char *cmd, int tty);
c906108c 6219
23860348 6220int get_and_display_threadinfo (threadref *ref);
c906108c 6221
a14ed312 6222static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 6223
23860348 6224static int thread_display_step (threadref *ref, void *context);
c906108c 6225
a14ed312 6226static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 6227
a14ed312 6228static void init_remote_threadtests (void);
c906108c 6229
23860348 6230#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
6231
6232static void
fba45db2 6233threadset_test_cmd (char *cmd, int tty)
c906108c
SS
6234{
6235 int sample_thread = SAMPLE_THREAD;
6236
a3f17187 6237 printf_filtered (_("Remote threadset test\n"));
79d7f229 6238 set_general_thread (sample_thread);
c906108c
SS
6239}
6240
6241
6242static void
fba45db2 6243threadalive_test (char *cmd, int tty)
c906108c
SS
6244{
6245 int sample_thread = SAMPLE_THREAD;
79d7f229
PA
6246 int pid = ptid_get_pid (inferior_ptid);
6247 ptid_t ptid = ptid_build (pid, 0, sample_thread);
c906108c 6248
79d7f229 6249 if (remote_thread_alive (ptid))
c906108c
SS
6250 printf_filtered ("PASS: Thread alive test\n");
6251 else
6252 printf_filtered ("FAIL: Thread alive test\n");
6253}
6254
23860348 6255void output_threadid (char *title, threadref *ref);
c906108c
SS
6256
6257void
fba45db2 6258output_threadid (char *title, threadref *ref)
c906108c
SS
6259{
6260 char hexid[20];
6261
23860348 6262 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
6263 hexid[16] = 0;
6264 printf_filtered ("%s %s\n", title, (&hexid[0]));
6265}
6266
6267static void
fba45db2 6268threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
6269{
6270 int startflag = 1;
6271 threadref nextthread;
6272 int done, result_count;
6273 threadref threadlist[3];
6274
6275 printf_filtered ("Remote Threadlist test\n");
6276 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
6277 &result_count, &threadlist[0]))
6278 printf_filtered ("FAIL: threadlist test\n");
6279 else
6280 {
6281 threadref *scan = threadlist;
6282 threadref *limit = scan + result_count;
6283
6284 while (scan < limit)
6285 output_threadid (" thread ", scan++);
6286 }
6287}
6288
6289void
fba45db2 6290display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
6291{
6292 output_threadid ("Threadid: ", &info->threadid);
6293 printf_filtered ("Name: %s\n ", info->shortname);
6294 printf_filtered ("State: %s\n", info->display);
6295 printf_filtered ("other: %s\n\n", info->more_display);
6296}
6297
6298int
fba45db2 6299get_and_display_threadinfo (threadref *ref)
c906108c
SS
6300{
6301 int result;
6302 int set;
6303 struct gdb_ext_thread_info threadinfo;
6304
6305 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
6306 | TAG_MOREDISPLAY | TAG_DISPLAY;
6307 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
6308 display_thread_info (&threadinfo);
6309 return result;
6310}
6311
6312static void
fba45db2 6313threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
6314{
6315 int athread = SAMPLE_THREAD;
6316 threadref thread;
6317 int set;
6318
6319 int_to_threadref (&thread, athread);
6320 printf_filtered ("Remote Threadinfo test\n");
6321 if (!get_and_display_threadinfo (&thread))
6322 printf_filtered ("FAIL cannot get thread info\n");
6323}
6324
6325static int
fba45db2 6326thread_display_step (threadref *ref, void *context)
c906108c
SS
6327{
6328 /* output_threadid(" threadstep ",ref); *//* simple test */
6329 return get_and_display_threadinfo (ref);
6330}
6331
6332static void
fba45db2 6333threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
6334{
6335 printf_filtered ("Remote Threadlist update test\n");
6336 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
6337}
6338
6339static void
6340init_remote_threadtests (void)
6341{
1bedd215
AC
6342 add_com ("tlist", class_obscure, threadlist_test_cmd, _("\
6343Fetch and print the remote list of thread identifiers, one pkt only"));
c906108c 6344 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 6345 _("Fetch and display info about one thread"));
c906108c 6346 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 6347 _("Test setting to a different thread"));
c906108c 6348 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 6349 _("Iterate through updating all remote thread info"));
c906108c 6350 add_com ("talive", class_obscure, threadalive_test,
1bedd215 6351 _(" Remote thread alive test "));
c906108c
SS
6352}
6353
6354#endif /* 0 */
6355
f3fb8c85
MS
6356/* Convert a thread ID to a string. Returns the string in a static
6357 buffer. */
6358
6359static char *
39f77062 6360remote_pid_to_str (ptid_t ptid)
f3fb8c85 6361{
79d7f229 6362 static char buf[64];
f3fb8c85 6363
79d7f229
PA
6364 if (ptid_equal (magic_null_ptid, ptid))
6365 {
6366 xsnprintf (buf, sizeof buf, "Thread <main>");
6367 return buf;
6368 }
6369 else if (ptid_get_tid (ptid) != 0)
6370 {
6371 xsnprintf (buf, sizeof buf, "Thread %ld",
6372 ptid_get_tid (ptid));
6373 return buf;
6374 }
6375
6376 return normal_pid_to_str (ptid);
f3fb8c85
MS
6377}
6378
38691318
KB
6379/* Get the address of the thread local variable in OBJFILE which is
6380 stored at OFFSET within the thread local storage for thread PTID. */
6381
6382static CORE_ADDR
6383remote_get_thread_local_address (ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
6384{
444abaca 6385 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
38691318
KB
6386 {
6387 struct remote_state *rs = get_remote_state ();
6d820c5c 6388 char *p = rs->buf;
571dd617 6389 enum packet_result result;
38691318
KB
6390
6391 strcpy (p, "qGetTLSAddr:");
6392 p += strlen (p);
79d7f229 6393 p += hexnumstr (p, ptid_get_tid (ptid));
38691318
KB
6394 *p++ = ',';
6395 p += hexnumstr (p, offset);
6396 *p++ = ',';
6397 p += hexnumstr (p, lm);
6398 *p++ = '\0';
6399
6d820c5c
DJ
6400 putpkt (rs->buf);
6401 getpkt (&rs->buf, &rs->buf_size, 0);
6402 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 6403 if (result == PACKET_OK)
38691318
KB
6404 {
6405 ULONGEST result;
6406
6d820c5c 6407 unpack_varlen_hex (rs->buf, &result);
38691318
KB
6408 return result;
6409 }
571dd617 6410 else if (result == PACKET_UNKNOWN)
109c3e39
AC
6411 throw_error (TLS_GENERIC_ERROR,
6412 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 6413 else
109c3e39
AC
6414 throw_error (TLS_GENERIC_ERROR,
6415 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
6416 }
6417 else
109c3e39
AC
6418 throw_error (TLS_GENERIC_ERROR,
6419 _("TLS not supported or disabled on this target"));
38691318
KB
6420 /* Not reached. */
6421 return 0;
6422}
6423
29709017
DJ
6424/* Support for inferring a target description based on the current
6425 architecture and the size of a 'g' packet. While the 'g' packet
6426 can have any size (since optional registers can be left off the
6427 end), some sizes are easily recognizable given knowledge of the
6428 approximate architecture. */
6429
6430struct remote_g_packet_guess
6431{
6432 int bytes;
6433 const struct target_desc *tdesc;
6434};
6435typedef struct remote_g_packet_guess remote_g_packet_guess_s;
6436DEF_VEC_O(remote_g_packet_guess_s);
6437
6438struct remote_g_packet_data
6439{
6440 VEC(remote_g_packet_guess_s) *guesses;
6441};
6442
6443static struct gdbarch_data *remote_g_packet_data_handle;
6444
6445static void *
6446remote_g_packet_data_init (struct obstack *obstack)
6447{
6448 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
6449}
6450
6451void
6452register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
6453 const struct target_desc *tdesc)
6454{
6455 struct remote_g_packet_data *data
6456 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
6457 struct remote_g_packet_guess new_guess, *guess;
6458 int ix;
6459
6460 gdb_assert (tdesc != NULL);
6461
6462 for (ix = 0;
6463 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
6464 ix++)
6465 if (guess->bytes == bytes)
6466 internal_error (__FILE__, __LINE__,
6467 "Duplicate g packet description added for size %d",
6468 bytes);
6469
6470 new_guess.bytes = bytes;
6471 new_guess.tdesc = tdesc;
6472 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
6473}
6474
6475static const struct target_desc *
6476remote_read_description (struct target_ops *target)
6477{
6478 struct remote_g_packet_data *data
6479 = gdbarch_data (current_gdbarch, remote_g_packet_data_handle);
6480
6481 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
6482 {
6483 struct remote_g_packet_guess *guess;
6484 int ix;
6485 int bytes = send_g_packet ();
6486
6487 for (ix = 0;
6488 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
6489 ix++)
6490 if (guess->bytes == bytes)
6491 return guess->tdesc;
6492
6493 /* We discard the g packet. A minor optimization would be to
6494 hold on to it, and fill the register cache once we have selected
6495 an architecture, but it's too tricky to do safely. */
6496 }
6497
6498 return NULL;
6499}
6500
a6b151f1
DJ
6501/* Remote file transfer support. This is host-initiated I/O, not
6502 target-initiated; for target-initiated, see remote-fileio.c. */
6503
6504/* If *LEFT is at least the length of STRING, copy STRING to
6505 *BUFFER, update *BUFFER to point to the new end of the buffer, and
6506 decrease *LEFT. Otherwise raise an error. */
6507
6508static void
6509remote_buffer_add_string (char **buffer, int *left, char *string)
6510{
6511 int len = strlen (string);
6512
6513 if (len > *left)
6514 error (_("Packet too long for target."));
6515
6516 memcpy (*buffer, string, len);
6517 *buffer += len;
6518 *left -= len;
6519
6520 /* NUL-terminate the buffer as a convenience, if there is
6521 room. */
6522 if (*left)
6523 **buffer = '\0';
6524}
6525
6526/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
6527 *BUFFER, update *BUFFER to point to the new end of the buffer, and
6528 decrease *LEFT. Otherwise raise an error. */
6529
6530static void
6531remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
6532 int len)
6533{
6534 if (2 * len > *left)
6535 error (_("Packet too long for target."));
6536
6537 bin2hex (bytes, *buffer, len);
6538 *buffer += 2 * len;
6539 *left -= 2 * len;
6540
6541 /* NUL-terminate the buffer as a convenience, if there is
6542 room. */
6543 if (*left)
6544 **buffer = '\0';
6545}
6546
6547/* If *LEFT is large enough, convert VALUE to hex and add it to
6548 *BUFFER, update *BUFFER to point to the new end of the buffer, and
6549 decrease *LEFT. Otherwise raise an error. */
6550
6551static void
6552remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
6553{
6554 int len = hexnumlen (value);
6555
6556 if (len > *left)
6557 error (_("Packet too long for target."));
6558
6559 hexnumstr (*buffer, value);
6560 *buffer += len;
6561 *left -= len;
6562
6563 /* NUL-terminate the buffer as a convenience, if there is
6564 room. */
6565 if (*left)
6566 **buffer = '\0';
6567}
6568
6569/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
6570 value, *REMOTE_ERRNO to the remote error number or zero if none
6571 was included, and *ATTACHMENT to point to the start of the annex
6572 if any. The length of the packet isn't needed here; there may
6573 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
6574
6575 Return 0 if the packet could be parsed, -1 if it could not. If
6576 -1 is returned, the other variables may not be initialized. */
6577
6578static int
6579remote_hostio_parse_result (char *buffer, int *retcode,
6580 int *remote_errno, char **attachment)
6581{
6582 char *p, *p2;
6583
6584 *remote_errno = 0;
6585 *attachment = NULL;
6586
6587 if (buffer[0] != 'F')
6588 return -1;
6589
6590 errno = 0;
6591 *retcode = strtol (&buffer[1], &p, 16);
6592 if (errno != 0 || p == &buffer[1])
6593 return -1;
6594
6595 /* Check for ",errno". */
6596 if (*p == ',')
6597 {
6598 errno = 0;
6599 *remote_errno = strtol (p + 1, &p2, 16);
6600 if (errno != 0 || p + 1 == p2)
6601 return -1;
6602 p = p2;
6603 }
6604
6605 /* Check for ";attachment". If there is no attachment, the
6606 packet should end here. */
6607 if (*p == ';')
6608 {
6609 *attachment = p + 1;
6610 return 0;
6611 }
6612 else if (*p == '\0')
6613 return 0;
6614 else
6615 return -1;
6616}
6617
6618/* Send a prepared I/O packet to the target and read its response.
6619 The prepared packet is in the global RS->BUF before this function
6620 is called, and the answer is there when we return.
6621
6622 COMMAND_BYTES is the length of the request to send, which may include
6623 binary data. WHICH_PACKET is the packet configuration to check
6624 before attempting a packet. If an error occurs, *REMOTE_ERRNO
6625 is set to the error number and -1 is returned. Otherwise the value
6626 returned by the function is returned.
6627
6628 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
6629 attachment is expected; an error will be reported if there's a
6630 mismatch. If one is found, *ATTACHMENT will be set to point into
6631 the packet buffer and *ATTACHMENT_LEN will be set to the
6632 attachment's length. */
6633
6634static int
6635remote_hostio_send_command (int command_bytes, int which_packet,
6636 int *remote_errno, char **attachment,
6637 int *attachment_len)
6638{
6639 struct remote_state *rs = get_remote_state ();
6640 int ret, bytes_read;
6641 char *attachment_tmp;
6642
6643 if (remote_protocol_packets[which_packet].support == PACKET_DISABLE)
6644 {
6645 *remote_errno = FILEIO_ENOSYS;
6646 return -1;
6647 }
6648
6649 putpkt_binary (rs->buf, command_bytes);
6650 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
6651
6652 /* If it timed out, something is wrong. Don't try to parse the
6653 buffer. */
6654 if (bytes_read < 0)
6655 {
6656 *remote_errno = FILEIO_EINVAL;
6657 return -1;
6658 }
6659
6660 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
6661 {
6662 case PACKET_ERROR:
6663 *remote_errno = FILEIO_EINVAL;
6664 return -1;
6665 case PACKET_UNKNOWN:
6666 *remote_errno = FILEIO_ENOSYS;
6667 return -1;
6668 case PACKET_OK:
6669 break;
6670 }
6671
6672 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
6673 &attachment_tmp))
6674 {
6675 *remote_errno = FILEIO_EINVAL;
6676 return -1;
6677 }
6678
6679 /* Make sure we saw an attachment if and only if we expected one. */
6680 if ((attachment_tmp == NULL && attachment != NULL)
6681 || (attachment_tmp != NULL && attachment == NULL))
6682 {
6683 *remote_errno = FILEIO_EINVAL;
6684 return -1;
6685 }
6686
6687 /* If an attachment was found, it must point into the packet buffer;
6688 work out how many bytes there were. */
6689 if (attachment_tmp != NULL)
6690 {
6691 *attachment = attachment_tmp;
6692 *attachment_len = bytes_read - (*attachment - rs->buf);
6693 }
6694
6695 return ret;
6696}
6697
6698/* Open FILENAME on the remote target, using FLAGS and MODE. Return a
6699 remote file descriptor, or -1 if an error occurs (and set
6700 *REMOTE_ERRNO). */
6701
6702static int
6703remote_hostio_open (const char *filename, int flags, int mode,
6704 int *remote_errno)
6705{
6706 struct remote_state *rs = get_remote_state ();
6707 char *p = rs->buf;
6708 int left = get_remote_packet_size () - 1;
6709
6710 remote_buffer_add_string (&p, &left, "vFile:open:");
6711
6712 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
6713 strlen (filename));
6714 remote_buffer_add_string (&p, &left, ",");
6715
6716 remote_buffer_add_int (&p, &left, flags);
6717 remote_buffer_add_string (&p, &left, ",");
6718
6719 remote_buffer_add_int (&p, &left, mode);
6720
6721 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
6722 remote_errno, NULL, NULL);
6723}
6724
6725/* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
6726 Return the number of bytes written, or -1 if an error occurs (and
6727 set *REMOTE_ERRNO). */
6728
6729static int
6730remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
6731 ULONGEST offset, int *remote_errno)
6732{
6733 struct remote_state *rs = get_remote_state ();
6734 char *p = rs->buf;
6735 int left = get_remote_packet_size ();
6736 int out_len;
6737
6738 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
6739
6740 remote_buffer_add_int (&p, &left, fd);
6741 remote_buffer_add_string (&p, &left, ",");
6742
6743 remote_buffer_add_int (&p, &left, offset);
6744 remote_buffer_add_string (&p, &left, ",");
6745
6746 p += remote_escape_output (write_buf, len, p, &out_len,
6747 get_remote_packet_size () - (p - rs->buf));
6748
6749 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
6750 remote_errno, NULL, NULL);
6751}
6752
6753/* Read up to LEN bytes FD on the remote target into READ_BUF
6754 Return the number of bytes read, or -1 if an error occurs (and
6755 set *REMOTE_ERRNO). */
6756
6757static int
6758remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
6759 ULONGEST offset, int *remote_errno)
6760{
6761 struct remote_state *rs = get_remote_state ();
6762 char *p = rs->buf;
6763 char *attachment;
6764 int left = get_remote_packet_size ();
6765 int ret, attachment_len;
6766 int read_len;
6767
6768 remote_buffer_add_string (&p, &left, "vFile:pread:");
6769
6770 remote_buffer_add_int (&p, &left, fd);
6771 remote_buffer_add_string (&p, &left, ",");
6772
6773 remote_buffer_add_int (&p, &left, len);
6774 remote_buffer_add_string (&p, &left, ",");
6775
6776 remote_buffer_add_int (&p, &left, offset);
6777
6778 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
6779 remote_errno, &attachment,
6780 &attachment_len);
6781
6782 if (ret < 0)
6783 return ret;
6784
6785 read_len = remote_unescape_input (attachment, attachment_len,
6786 read_buf, len);
6787 if (read_len != ret)
6788 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
6789
6790 return ret;
6791}
6792
6793/* Close FD on the remote target. Return 0, or -1 if an error occurs
6794 (and set *REMOTE_ERRNO). */
6795
6796static int
6797remote_hostio_close (int fd, int *remote_errno)
6798{
6799 struct remote_state *rs = get_remote_state ();
6800 char *p = rs->buf;
6801 int left = get_remote_packet_size () - 1;
6802
6803 remote_buffer_add_string (&p, &left, "vFile:close:");
6804
6805 remote_buffer_add_int (&p, &left, fd);
6806
6807 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
6808 remote_errno, NULL, NULL);
6809}
6810
6811/* Unlink FILENAME on the remote target. Return 0, or -1 if an error
6812 occurs (and set *REMOTE_ERRNO). */
6813
6814static int
6815remote_hostio_unlink (const char *filename, int *remote_errno)
6816{
6817 struct remote_state *rs = get_remote_state ();
6818 char *p = rs->buf;
6819 int left = get_remote_packet_size () - 1;
6820
6821 remote_buffer_add_string (&p, &left, "vFile:unlink:");
6822
6823 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
6824 strlen (filename));
6825
6826 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
6827 remote_errno, NULL, NULL);
6828}
6829
6830static int
6831remote_fileio_errno_to_host (int errnum)
6832{
6833 switch (errnum)
6834 {
6835 case FILEIO_EPERM:
6836 return EPERM;
6837 case FILEIO_ENOENT:
6838 return ENOENT;
6839 case FILEIO_EINTR:
6840 return EINTR;
6841 case FILEIO_EIO:
6842 return EIO;
6843 case FILEIO_EBADF:
6844 return EBADF;
6845 case FILEIO_EACCES:
6846 return EACCES;
6847 case FILEIO_EFAULT:
6848 return EFAULT;
6849 case FILEIO_EBUSY:
6850 return EBUSY;
6851 case FILEIO_EEXIST:
6852 return EEXIST;
6853 case FILEIO_ENODEV:
6854 return ENODEV;
6855 case FILEIO_ENOTDIR:
6856 return ENOTDIR;
6857 case FILEIO_EISDIR:
6858 return EISDIR;
6859 case FILEIO_EINVAL:
6860 return EINVAL;
6861 case FILEIO_ENFILE:
6862 return ENFILE;
6863 case FILEIO_EMFILE:
6864 return EMFILE;
6865 case FILEIO_EFBIG:
6866 return EFBIG;
6867 case FILEIO_ENOSPC:
6868 return ENOSPC;
6869 case FILEIO_ESPIPE:
6870 return ESPIPE;
6871 case FILEIO_EROFS:
6872 return EROFS;
6873 case FILEIO_ENOSYS:
6874 return ENOSYS;
6875 case FILEIO_ENAMETOOLONG:
6876 return ENAMETOOLONG;
6877 }
6878 return -1;
6879}
6880
6881static char *
6882remote_hostio_error (int errnum)
6883{
6884 int host_error = remote_fileio_errno_to_host (errnum);
6885
6886 if (host_error == -1)
6887 error (_("Unknown remote I/O error %d"), errnum);
6888 else
6889 error (_("Remote I/O error: %s"), safe_strerror (host_error));
6890}
6891
6892static void
6893fclose_cleanup (void *file)
6894{
6895 fclose (file);
6896}
6897
6898static void
6899remote_hostio_close_cleanup (void *opaque)
6900{
6901 int fd = *(int *) opaque;
6902 int remote_errno;
6903
6904 remote_hostio_close (fd, &remote_errno);
6905}
6906
6907void
6908remote_file_put (const char *local_file, const char *remote_file, int from_tty)
6909{
6910 struct cleanup *back_to, *close_cleanup;
6911 int retcode, fd, remote_errno, bytes, io_size;
6912 FILE *file;
6913 gdb_byte *buffer;
6914 int bytes_in_buffer;
6915 int saw_eof;
6916 ULONGEST offset;
6917
6918 if (!remote_desc)
6919 error (_("command can only be used with remote target"));
6920
6921 file = fopen (local_file, "rb");
6922 if (file == NULL)
6923 perror_with_name (local_file);
6924 back_to = make_cleanup (fclose_cleanup, file);
6925
6926 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
6927 | FILEIO_O_TRUNC),
6928 0700, &remote_errno);
6929 if (fd == -1)
6930 remote_hostio_error (remote_errno);
6931
6932 /* Send up to this many bytes at once. They won't all fit in the
6933 remote packet limit, so we'll transfer slightly fewer. */
6934 io_size = get_remote_packet_size ();
6935 buffer = xmalloc (io_size);
6936 make_cleanup (xfree, buffer);
6937
6938 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
6939
6940 bytes_in_buffer = 0;
6941 saw_eof = 0;
6942 offset = 0;
6943 while (bytes_in_buffer || !saw_eof)
6944 {
6945 if (!saw_eof)
6946 {
6947 bytes = fread (buffer + bytes_in_buffer, 1, io_size - bytes_in_buffer,
6948 file);
6949 if (bytes == 0)
6950 {
6951 if (ferror (file))
6952 error (_("Error reading %s."), local_file);
6953 else
6954 {
6955 /* EOF. Unless there is something still in the
6956 buffer from the last iteration, we are done. */
6957 saw_eof = 1;
6958 if (bytes_in_buffer == 0)
6959 break;
6960 }
6961 }
6962 }
6963 else
6964 bytes = 0;
6965
6966 bytes += bytes_in_buffer;
6967 bytes_in_buffer = 0;
6968
6969 retcode = remote_hostio_pwrite (fd, buffer, bytes, offset, &remote_errno);
6970
6971 if (retcode < 0)
6972 remote_hostio_error (remote_errno);
6973 else if (retcode == 0)
6974 error (_("Remote write of %d bytes returned 0!"), bytes);
6975 else if (retcode < bytes)
6976 {
6977 /* Short write. Save the rest of the read data for the next
6978 write. */
6979 bytes_in_buffer = bytes - retcode;
6980 memmove (buffer, buffer + retcode, bytes_in_buffer);
6981 }
6982
6983 offset += retcode;
6984 }
6985
6986 discard_cleanups (close_cleanup);
6987 if (remote_hostio_close (fd, &remote_errno))
6988 remote_hostio_error (remote_errno);
6989
6990 if (from_tty)
6991 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
6992 do_cleanups (back_to);
6993}
6994
6995void
6996remote_file_get (const char *remote_file, const char *local_file, int from_tty)
6997{
6998 struct cleanup *back_to, *close_cleanup;
6999 int retcode, fd, remote_errno, bytes, io_size;
7000 FILE *file;
7001 gdb_byte *buffer;
7002 ULONGEST offset;
7003
7004 if (!remote_desc)
7005 error (_("command can only be used with remote target"));
7006
7007 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
7008 if (fd == -1)
7009 remote_hostio_error (remote_errno);
7010
7011 file = fopen (local_file, "wb");
7012 if (file == NULL)
7013 perror_with_name (local_file);
7014 back_to = make_cleanup (fclose_cleanup, file);
7015
7016 /* Send up to this many bytes at once. They won't all fit in the
7017 remote packet limit, so we'll transfer slightly fewer. */
7018 io_size = get_remote_packet_size ();
7019 buffer = xmalloc (io_size);
7020 make_cleanup (xfree, buffer);
7021
7022 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
7023
7024 offset = 0;
7025 while (1)
7026 {
7027 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
7028 if (bytes == 0)
7029 /* Success, but no bytes, means end-of-file. */
7030 break;
7031 if (bytes == -1)
7032 remote_hostio_error (remote_errno);
7033
7034 offset += bytes;
7035
7036 bytes = fwrite (buffer, 1, bytes, file);
7037 if (bytes == 0)
7038 perror_with_name (local_file);
7039 }
7040
7041 discard_cleanups (close_cleanup);
7042 if (remote_hostio_close (fd, &remote_errno))
7043 remote_hostio_error (remote_errno);
7044
7045 if (from_tty)
7046 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
7047 do_cleanups (back_to);
7048}
7049
7050void
7051remote_file_delete (const char *remote_file, int from_tty)
7052{
7053 int retcode, remote_errno;
7054
7055 if (!remote_desc)
7056 error (_("command can only be used with remote target"));
7057
7058 retcode = remote_hostio_unlink (remote_file, &remote_errno);
7059 if (retcode == -1)
7060 remote_hostio_error (remote_errno);
7061
7062 if (from_tty)
7063 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
7064}
7065
7066static void
7067remote_put_command (char *args, int from_tty)
7068{
7069 struct cleanup *back_to;
7070 char **argv;
7071
7072 argv = buildargv (args);
7073 if (argv == NULL)
7074 nomem (0);
7075 back_to = make_cleanup_freeargv (argv);
7076 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
7077 error (_("Invalid parameters to remote put"));
7078
7079 remote_file_put (argv[0], argv[1], from_tty);
7080
7081 do_cleanups (back_to);
7082}
7083
7084static void
7085remote_get_command (char *args, int from_tty)
7086{
7087 struct cleanup *back_to;
7088 char **argv;
7089
7090 argv = buildargv (args);
7091 if (argv == NULL)
7092 nomem (0);
7093 back_to = make_cleanup_freeargv (argv);
7094 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
7095 error (_("Invalid parameters to remote get"));
7096
7097 remote_file_get (argv[0], argv[1], from_tty);
7098
7099 do_cleanups (back_to);
7100}
7101
7102static void
7103remote_delete_command (char *args, int from_tty)
7104{
7105 struct cleanup *back_to;
7106 char **argv;
7107
7108 argv = buildargv (args);
7109 if (argv == NULL)
7110 nomem (0);
7111 back_to = make_cleanup_freeargv (argv);
7112 if (argv[0] == NULL || argv[1] != NULL)
7113 error (_("Invalid parameters to remote delete"));
7114
7115 remote_file_delete (argv[0], from_tty);
7116
7117 do_cleanups (back_to);
7118}
7119
7120static void
7121remote_command (char *args, int from_tty)
7122{
7123 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
7124}
7125
c906108c 7126static void
fba45db2 7127init_remote_ops (void)
c906108c 7128{
c5aa993b 7129 remote_ops.to_shortname = "remote";
c906108c 7130 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 7131 remote_ops.to_doc =
c906108c 7132 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
7133Specify the serial device it is connected to\n\
7134(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
7135 remote_ops.to_open = remote_open;
7136 remote_ops.to_close = remote_close;
c906108c 7137 remote_ops.to_detach = remote_detach;
6ad8ae5c 7138 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 7139 remote_ops.to_resume = remote_resume;
c906108c
SS
7140 remote_ops.to_wait = remote_wait;
7141 remote_ops.to_fetch_registers = remote_fetch_registers;
7142 remote_ops.to_store_registers = remote_store_registers;
7143 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c8e73a31 7144 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
c5aa993b 7145 remote_ops.to_files_info = remote_files_info;
c906108c
SS
7146 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
7147 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
3c3bea1c
GS
7148 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
7149 remote_ops.to_stopped_data_address = remote_stopped_data_address;
7150 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
7151 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
7152 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
7153 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
7154 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b
JM
7155 remote_ops.to_kill = remote_kill;
7156 remote_ops.to_load = generic_load;
c906108c
SS
7157 remote_ops.to_mourn_inferior = remote_mourn;
7158 remote_ops.to_thread_alive = remote_thread_alive;
0f71a2f6 7159 remote_ops.to_find_new_threads = remote_threads_info;
0caabb7e 7160 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 7161 remote_ops.to_extra_thread_info = remote_threads_extra_info;
c906108c 7162 remote_ops.to_stop = remote_stop;
4b8a223f 7163 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 7164 remote_ops.to_rcmd = remote_rcmd;
49d03eab 7165 remote_ops.to_log_command = serial_log_command;
38691318 7166 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 7167 remote_ops.to_stratum = process_stratum;
c5aa993b
JM
7168 remote_ops.to_has_all_memory = 1;
7169 remote_ops.to_has_memory = 1;
7170 remote_ops.to_has_stack = 1;
7171 remote_ops.to_has_registers = 1;
7172 remote_ops.to_has_execution = 1;
7173 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
7174 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 7175 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
7176 remote_ops.to_flash_erase = remote_flash_erase;
7177 remote_ops.to_flash_done = remote_flash_done;
29709017 7178 remote_ops.to_read_description = remote_read_description;
08388c79 7179 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
7180 remote_ops.to_can_async_p = remote_can_async_p;
7181 remote_ops.to_is_async_p = remote_is_async_p;
7182 remote_ops.to_async = remote_async;
7183 remote_ops.to_async_mask = remote_async_mask;
7184 remote_ops.to_terminal_inferior = remote_terminal_inferior;
7185 remote_ops.to_terminal_ours = remote_terminal_ours;
c906108c
SS
7186}
7187
7188/* Set up the extended remote vector by making a copy of the standard
7189 remote vector and adding to it. */
7190
7191static void
fba45db2 7192init_extended_remote_ops (void)
c906108c
SS
7193{
7194 extended_remote_ops = remote_ops;
7195
0f71a2f6 7196 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 7197 extended_remote_ops.to_longname =
c906108c 7198 "Extended remote serial target in gdb-specific protocol";
c5aa993b 7199 extended_remote_ops.to_doc =
c906108c 7200 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
7201Specify the serial device it is connected to (e.g. /dev/ttya).";
7202 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
7203 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
7204 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
7205 extended_remote_ops.to_detach = extended_remote_detach;
7206 extended_remote_ops.to_attach = extended_remote_attach;
0f71a2f6
JM
7207}
7208
6426a772
JM
7209static int
7210remote_can_async_p (void)
7211{
75c99385
PA
7212 if (!remote_async_permitted)
7213 /* We only enable async when the user specifically asks for it. */
7214 return 0;
7215
23860348 7216 /* We're async whenever the serial device is. */
b84876c2 7217 return remote_async_mask_value && serial_can_async_p (remote_desc);
6426a772
JM
7218}
7219
7220static int
7221remote_is_async_p (void)
7222{
75c99385
PA
7223 if (!remote_async_permitted)
7224 /* We only enable async when the user specifically asks for it. */
7225 return 0;
7226
23860348 7227 /* We're async whenever the serial device is. */
b84876c2 7228 return remote_async_mask_value && serial_is_async_p (remote_desc);
6426a772
JM
7229}
7230
2acceee2
JM
7231/* Pass the SERIAL event on and up to the client. One day this code
7232 will be able to delay notifying the client of an event until the
23860348 7233 point where an entire packet has been received. */
2acceee2 7234
2bc416ba 7235static void (*async_client_callback) (enum inferior_event_type event_type,
23860348 7236 void *context);
2acceee2
JM
7237static void *async_client_context;
7238static serial_event_ftype remote_async_serial_handler;
7239
6426a772 7240static void
819cc324 7241remote_async_serial_handler (struct serial *scb, void *context)
6426a772 7242{
2acceee2
JM
7243 /* Don't propogate error information up to the client. Instead let
7244 the client find out about the error by querying the target. */
7245 async_client_callback (INF_REG_EVENT, async_client_context);
7246}
7247
7248static void
2bc416ba 7249remote_async (void (*callback) (enum inferior_event_type event_type,
23860348 7250 void *context), void *context)
2acceee2 7251{
b84876c2 7252 if (remote_async_mask_value == 0)
8e65ff28 7253 internal_error (__FILE__, __LINE__,
e2e0b3e5 7254 _("Calling remote_async when async is masked"));
ed9a39eb 7255
2acceee2
JM
7256 if (callback != NULL)
7257 {
2cd58942 7258 serial_async (remote_desc, remote_async_serial_handler, NULL);
2acceee2
JM
7259 async_client_callback = callback;
7260 async_client_context = context;
7261 }
7262 else
2cd58942 7263 serial_async (remote_desc, NULL, NULL);
6426a772
JM
7264}
7265
b84876c2
PA
7266static int
7267remote_async_mask (int new_mask)
7268{
7269 int curr_mask = remote_async_mask_value;
7270 remote_async_mask_value = new_mask;
7271 return curr_mask;
7272}
7273
5a2468f5 7274static void
c2d11a7d 7275set_remote_cmd (char *args, int from_tty)
5a2468f5 7276{
427c3a89 7277 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
5a2468f5
JM
7278}
7279
d471ea57
AC
7280static void
7281show_remote_cmd (char *args, int from_tty)
7282{
37a105a1 7283 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 7284 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
7285 struct cleanup *showlist_chain;
7286 struct cmd_list_element *list = remote_show_cmdlist;
7287
7288 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
7289 for (; list != NULL; list = list->next)
7290 if (strcmp (list->name, "Z-packet") == 0)
7291 continue;
427c3a89
DJ
7292 else if (list->type == not_set_cmd)
7293 /* Alias commands are exactly like the original, except they
7294 don't have the normal type. */
7295 continue;
7296 else
37a105a1
DJ
7297 {
7298 struct cleanup *option_chain
7299 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
7300 ui_out_field_string (uiout, "name", list->name);
7301 ui_out_text (uiout, ": ");
427c3a89
DJ
7302 if (list->type == show_cmd)
7303 do_setshow_command ((char *) NULL, from_tty, list);
7304 else
7305 cmd_func (list, NULL, from_tty);
37a105a1
DJ
7306 /* Close the tuple. */
7307 do_cleanups (option_chain);
7308 }
427c3a89
DJ
7309
7310 /* Close the tuple. */
7311 do_cleanups (showlist_chain);
d471ea57 7312}
5a2468f5 7313
0f71a2f6 7314
23860348 7315/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
7316static void
7317remote_new_objfile (struct objfile *objfile)
7318{
23860348 7319 if (remote_desc != 0) /* Have a remote connection. */
06d3b283 7320 remote_check_symbols (objfile);
dc8acb97
MS
7321}
7322
c906108c 7323void
fba45db2 7324_initialize_remote (void)
c906108c 7325{
ea9c271d
DJ
7326 struct remote_state *rs;
7327
0f71a2f6 7328 /* architecture specific data */
2bc416ba 7329 remote_gdbarch_data_handle =
23860348 7330 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
7331 remote_g_packet_data_handle =
7332 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 7333
ea9c271d
DJ
7334 /* Initialize the per-target state. At the moment there is only one
7335 of these, not one per target. Only one target is active at a
7336 time. The default buffer size is unimportant; it will be expanded
7337 whenever a larger buffer is needed. */
0b83947e 7338 rs = get_remote_state_raw ();
ea9c271d
DJ
7339 rs->buf_size = 400;
7340 rs->buf = xmalloc (rs->buf_size);
7341
c906108c
SS
7342 init_remote_ops ();
7343 add_target (&remote_ops);
7344
7345 init_extended_remote_ops ();
7346 add_target (&extended_remote_ops);
cce74817 7347
dc8acb97 7348 /* Hook into new objfile notification. */
06d3b283 7349 observer_attach_new_objfile (remote_new_objfile);
dc8acb97 7350
b803fb0f
DJ
7351 /* Set up signal handlers. */
7352 sigint_remote_token =
7353 create_async_signal_handler (async_remote_interrupt, NULL);
7354 sigint_remote_twice_token =
7355 create_async_signal_handler (inferior_event_handler_wrapper, NULL);
7356
c906108c
SS
7357#if 0
7358 init_remote_threadtests ();
7359#endif
7360
23860348 7361 /* set/show remote ... */
d471ea57 7362
1bedd215 7363 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
7364Remote protocol specific variables\n\
7365Configure various remote-protocol specific variables such as\n\
1bedd215 7366the packets being used"),
cff3e48b 7367 &remote_set_cmdlist, "set remote ",
23860348 7368 0 /* allow-unknown */, &setlist);
1bedd215 7369 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
7370Remote protocol specific variables\n\
7371Configure various remote-protocol specific variables such as\n\
1bedd215 7372the packets being used"),
cff3e48b 7373 &remote_show_cmdlist, "show remote ",
23860348 7374 0 /* allow-unknown */, &showlist);
5a2468f5 7375
1a966eab
AC
7376 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
7377Compare section data on target to the exec file.\n\
7378Argument is a single section name (default: all loaded sections)."),
c906108c
SS
7379 &cmdlist);
7380
1a966eab
AC
7381 add_cmd ("packet", class_maintenance, packet_command, _("\
7382Send an arbitrary packet to a remote target.\n\
c906108c
SS
7383 maintenance packet TEXT\n\
7384If GDB is talking to an inferior via the GDB serial protocol, then\n\
7385this command sends the string TEXT to the inferior, and displays the\n\
7386response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 7387terminating `#' character and checksum."),
c906108c
SS
7388 &maintenancelist);
7389
7915a72c
AC
7390 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
7391Set whether to send break if interrupted."), _("\
7392Show whether to send break if interrupted."), _("\
7393If set, a break, instead of a cntrl-c, is sent to the remote target."),
2c5b56ce 7394 NULL, NULL, /* FIXME: i18n: Whether to send break if interrupted is %s. */
e707bbc2 7395 &setlist, &showlist);
c906108c 7396
23860348 7397 /* Install commands for configuring memory read/write packets. */
11cf8741 7398
1a966eab
AC
7399 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
7400Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 7401 &setlist);
1a966eab
AC
7402 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
7403Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
7404 &showlist);
7405 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
7406 set_memory_write_packet_size, _("\
7407Set the maximum number of bytes per memory-write packet.\n\
7408Specify the number of bytes in a packet or 0 (zero) for the\n\
7409default packet size. The actual limit is further reduced\n\
7410dependent on the target. Specify ``fixed'' to disable the\n\
7411further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
7412 &remote_set_cmdlist);
7413 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
7414 set_memory_read_packet_size, _("\
7415Set the maximum number of bytes per memory-read packet.\n\
7416Specify the number of bytes in a packet or 0 (zero) for the\n\
7417default packet size. The actual limit is further reduced\n\
7418dependent on the target. Specify ``fixed'' to disable the\n\
7419further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
7420 &remote_set_cmdlist);
7421 add_cmd ("memory-write-packet-size", no_class,
7422 show_memory_write_packet_size,
1a966eab 7423 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
7424 &remote_show_cmdlist);
7425 add_cmd ("memory-read-packet-size", no_class,
7426 show_memory_read_packet_size,
1a966eab 7427 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 7428 &remote_show_cmdlist);
c906108c 7429
b3f42336 7430 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
7431 &remote_hw_watchpoint_limit, _("\
7432Set the maximum number of target hardware watchpoints."), _("\
7433Show the maximum number of target hardware watchpoints."), _("\
7434Specify a negative limit for unlimited."),
2c5b56ce 7435 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware watchpoints is %s. */
b3f42336
AC
7436 &remote_set_cmdlist, &remote_show_cmdlist);
7437 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
7438 &remote_hw_breakpoint_limit, _("\
7439Set the maximum number of target hardware breakpoints."), _("\
7440Show the maximum number of target hardware breakpoints."), _("\
7441Specify a negative limit for unlimited."),
2c5b56ce 7442 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware breakpoints is %s. */
b3f42336 7443 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 7444
4d28ad1e
AC
7445 add_setshow_integer_cmd ("remoteaddresssize", class_obscure,
7446 &remote_address_size, _("\
7447Set the maximum size of the address (in bits) in a memory packet."), _("\
7448Show the maximum size of the address (in bits) in a memory packet."), NULL,
7449 NULL,
7450 NULL, /* FIXME: i18n: */
7451 &setlist, &showlist);
c906108c 7452
444abaca 7453 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 7454 "X", "binary-download", 1);
0f71a2f6 7455
444abaca 7456 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 7457 "vCont", "verbose-resume", 0);
506fb367 7458
89be2091
DJ
7459 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
7460 "QPassSignals", "pass-signals", 0);
7461
444abaca 7462 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 7463 "qSymbol", "symbol-lookup", 0);
dc8acb97 7464
444abaca 7465 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 7466 "P", "set-register", 1);
d471ea57 7467
444abaca 7468 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 7469 "p", "fetch-register", 1);
b96ec7ac 7470
444abaca 7471 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 7472 "Z0", "software-breakpoint", 0);
d471ea57 7473
444abaca 7474 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 7475 "Z1", "hardware-breakpoint", 0);
d471ea57 7476
444abaca 7477 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 7478 "Z2", "write-watchpoint", 0);
d471ea57 7479
444abaca 7480 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 7481 "Z3", "read-watchpoint", 0);
d471ea57 7482
444abaca 7483 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 7484 "Z4", "access-watchpoint", 0);
d471ea57 7485
0876f84a
DJ
7486 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
7487 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 7488
23181151
DJ
7489 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
7490 "qXfer:features:read", "target-features", 0);
7491
cfa9d6d9
DJ
7492 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
7493 "qXfer:libraries:read", "library-info", 0);
7494
fd79ecee
DJ
7495 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
7496 "qXfer:memory-map:read", "memory-map", 0);
7497
0e7f50da
UW
7498 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
7499 "qXfer:spu:read", "read-spu-object", 0);
7500
7501 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
7502 "qXfer:spu:write", "write-spu-object", 0);
7503
444abaca 7504 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 7505 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
7506 0);
7507
be2a5f71
DJ
7508 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
7509 "qSupported", "supported-packets", 0);
7510
08388c79
DE
7511 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
7512 "qSearch:memory", "search-memory", 0);
7513
a6b151f1
DJ
7514 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
7515 "vFile:open", "hostio-open", 0);
7516
7517 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
7518 "vFile:pread", "hostio-pread", 0);
7519
7520 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
7521 "vFile:pwrite", "hostio-pwrite", 0);
7522
7523 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
7524 "vFile:close", "hostio-close", 0);
7525
7526 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
7527 "vFile:unlink", "hostio-unlink", 0);
7528
2d717e4f
DJ
7529 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
7530 "vAttach", "attach", 0);
7531
7532 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
7533 "vRun", "run", 0);
7534
37a105a1
DJ
7535 /* Keep the old ``set remote Z-packet ...'' working. Each individual
7536 Z sub-packet has its own set and show commands, but users may
7537 have sets to this variable in their .gdbinit files (or in their
7538 documentation). */
e9e68a56 7539 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
7540 &remote_Z_packet_detect, _("\
7541Set use of remote protocol `Z' packets"), _("\
7542Show use of remote protocol `Z' packets "), _("\
3b64bf98 7543When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 7544packets."),
e9e68a56 7545 set_remote_protocol_Z_packet_cmd,
2c5b56ce 7546 show_remote_protocol_Z_packet_cmd, /* FIXME: i18n: Use of remote protocol `Z' packets is %s. */
e9e68a56 7547 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 7548
a6b151f1
DJ
7549 add_prefix_cmd ("remote", class_files, remote_command, _("\
7550Manipulate files on the remote system\n\
7551Transfer files to and from the remote target system."),
7552 &remote_cmdlist, "remote ",
7553 0 /* allow-unknown */, &cmdlist);
7554
7555 add_cmd ("put", class_files, remote_put_command,
7556 _("Copy a local file to the remote system."),
7557 &remote_cmdlist);
7558
7559 add_cmd ("get", class_files, remote_get_command,
7560 _("Copy a remote file to the local system."),
7561 &remote_cmdlist);
7562
7563 add_cmd ("delete", class_files, remote_delete_command,
7564 _("Delete a remote file."),
7565 &remote_cmdlist);
7566
2d717e4f
DJ
7567 remote_exec_file = xstrdup ("");
7568 add_setshow_string_noescape_cmd ("exec-file", class_files,
7569 &remote_exec_file, _("\
7570Set the remote pathname for \"run\""), _("\
7571Show the remote pathname for \"run\""), NULL, NULL, NULL,
7572 &remote_set_cmdlist, &remote_show_cmdlist);
7573
75c99385
PA
7574 add_setshow_boolean_cmd ("remote-async", class_maintenance,
7575 &remote_async_permitted_set, _("\
7576Set whether gdb controls the remote inferior in asynchronous mode."), _("\
7577Show whether gdb controls the remote inferior in asynchronous mode."), _("\
7578Tells gdb whether to control the remote inferior in asynchronous mode."),
7579 set_maintenance_remote_async_permitted,
7580 show_maintenance_remote_async_permitted,
7581 &maintenance_set_cmdlist,
7582 &maintenance_show_cmdlist);
7583
7584
449092f6
CV
7585 /* Eventually initialize fileio. See fileio.c */
7586 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229
PA
7587
7588 /* Take advantage of the fact that the LWP field is not used, to tag
7589 special ptids with it set to != 0. */
7590 magic_null_ptid = ptid_build (0, 1, -1);
7591 not_sent_ptid = ptid_build (0, 1, -2);
7592 any_thread_ptid = ptid_build (0, 1, 0);
c906108c 7593}
This page took 1.349772 seconds and 4 git commands to generate.