1/* String reading
2
3   Copyright (C) 2022-2023 Free Software Foundation, Inc.
4
5   This file is part of GDB.
6
7   This program is free software; you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation; either version 3 of the License, or
10   (at your option) any later version.
11
12   This program is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20#include "gdbsupport/common-defs.h"
21#include "target/target.h"
22
23/* Read LEN bytes of target memory at address MEMADDR, placing the
24   results in GDB's memory at MYADDR.  Returns a count of the bytes
25   actually read, and optionally a target_xfer_status value in the
26   location pointed to by ERRPTR if ERRPTR is non-null.  */
27
28static int
29partial_memory_read (CORE_ADDR memaddr, gdb_byte *myaddr,
30		     int len, int *errptr)
31{
32  int nread;			/* Number of bytes actually read.  */
33  int errcode;			/* Error from last read.  */
34
35  /* First try a complete read.  */
36  errcode = target_read_memory (memaddr, myaddr, len);
37  if (errcode == 0)
38    {
39      /* Got it all.  */
40      nread = len;
41    }
42  else
43    {
44      /* Loop, reading one byte at a time until we get as much as we can.  */
45      for (errcode = 0, nread = 0; len > 0 && errcode == 0; nread++, len--)
46	{
47	  errcode = target_read_memory (memaddr++, myaddr++, 1);
48	}
49      /* If an error, the last read was unsuccessful, so adjust count.  */
50      if (errcode != 0)
51	{
52	  nread--;
53	}
54    }
55  if (errptr != NULL)
56    {
57      *errptr = errcode;
58    }
59  return (nread);
60}
61
62/* See target/target.h.  */
63
64int
65target_read_string (CORE_ADDR addr, int len, int width,
66		    unsigned int fetchlimit,
67		    gdb::unique_xmalloc_ptr<gdb_byte> *buffer,
68		    int *bytes_read)
69{
70  int errcode;			/* Errno returned from bad reads.  */
71  unsigned int nfetch;		/* Chars to fetch / chars fetched.  */
72  gdb_byte *bufptr;		/* Pointer to next available byte in
73				   buffer.  */
74
75  /* Loop until we either have all the characters, or we encounter
76     some error, such as bumping into the end of the address space.  */
77
78  buffer->reset (nullptr);
79
80  if (len > 0)
81    {
82      /* We want fetchlimit chars, so we might as well read them all in
83	 one operation.  */
84      unsigned int fetchlen = std::min ((unsigned) len, fetchlimit);
85
86      buffer->reset ((gdb_byte *) xmalloc (fetchlen * width));
87      bufptr = buffer->get ();
88
89      nfetch = partial_memory_read (addr, bufptr, fetchlen * width, &errcode)
90	/ width;
91      addr += nfetch * width;
92      bufptr += nfetch * width;
93    }
94  else if (len == -1)
95    {
96      unsigned long bufsize = 0;
97      unsigned int chunksize;	/* Size of each fetch, in chars.  */
98      int found_nul;		/* Non-zero if we found the nul char.  */
99      gdb_byte *limit;		/* First location past end of fetch buffer.  */
100
101      found_nul = 0;
102      /* We are looking for a NUL terminator to end the fetching, so we
103	 might as well read in blocks that are large enough to be efficient,
104	 but not so large as to be slow if fetchlimit happens to be large.
105	 So we choose the minimum of 8 and fetchlimit.  We used to use 200
106	 instead of 8 but 200 is way too big for remote debugging over a
107	  serial line.  */
108      chunksize = std::min (8u, fetchlimit);
109
110      do
111	{
112	  nfetch = std::min ((unsigned long) chunksize, fetchlimit - bufsize);
113
114	  if (*buffer == NULL)
115	    buffer->reset ((gdb_byte *) xmalloc (nfetch * width));
116	  else
117	    buffer->reset ((gdb_byte *) xrealloc (buffer->release (),
118						  (nfetch + bufsize) * width));
119
120	  bufptr = buffer->get () + bufsize * width;
121	  bufsize += nfetch;
122
123	  /* Read as much as we can.  */
124	  nfetch = partial_memory_read (addr, bufptr, nfetch * width, &errcode)
125		    / width;
126
127	  /* Scan this chunk for the null character that terminates the string
128	     to print.  If found, we don't need to fetch any more.  Note
129	     that bufptr is explicitly left pointing at the next character
130	     after the null character, or at the next character after the end
131	     of the buffer.  */
132
133	  limit = bufptr + nfetch * width;
134	  while (bufptr < limit)
135	    {
136	      bool found_nonzero = false;
137
138	      for (int i = 0; !found_nonzero && i < width; ++i)
139		if (bufptr[i] != 0)
140		  found_nonzero = true;
141
142	      addr += width;
143	      bufptr += width;
144	      if (!found_nonzero)
145		{
146		  /* We don't care about any error which happened after
147		     the NUL terminator.  */
148		  errcode = 0;
149		  found_nul = 1;
150		  break;
151		}
152	    }
153	}
154      while (errcode == 0	/* no error */
155	     && bufptr - buffer->get () < fetchlimit * width	/* no overrun */
156	     && !found_nul);	/* haven't found NUL yet */
157    }
158  else
159    {				/* Length of string is really 0!  */
160      /* We always allocate *buffer.  */
161      buffer->reset ((gdb_byte *) xmalloc (1));
162      bufptr = buffer->get ();
163      errcode = 0;
164    }
165
166  /* bufptr and addr now point immediately beyond the last byte which we
167     consider part of the string (including a '\0' which ends the string).  */
168  *bytes_read = bufptr - buffer->get ();
169
170  return errcode;
171}
172
173/* See target/target.h.  */
174
175gdb::unique_xmalloc_ptr<char>
176target_read_string (CORE_ADDR memaddr, int len, int *bytes_read)
177{
178  gdb::unique_xmalloc_ptr<gdb_byte> buffer;
179
180  int ignore;
181  if (bytes_read == nullptr)
182    bytes_read = &ignore;
183
184  /* Note that the endian-ness does not matter here.  */
185  int errcode = target_read_string (memaddr, -1, 1, len, &buffer, bytes_read);
186  if (errcode != 0)
187    return {};
188
189  return gdb::unique_xmalloc_ptr<char> ((char *) buffer.release ());
190}
191