OpenCores
URL https://opencores.org/ocsvn/scarts/scarts/trunk

Subversion Repositories scarts

[/] [scarts/] [trunk/] [toolchain/] [scarts-gdb/] [gdb-6.8/] [gdb/] [remote.c] - Blame information for rev 25

Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.