/* Find the strings of printing characters in a file or files.
   Copyright (C) 1986 Richard M. Stallman

		       NO WARRANTY

  BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW.  EXCEPT
WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS"
WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY
AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.

 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
WHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE
LIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
OTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS
PROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.

		GENERAL PUBLIC LICENSE TO COPY

  1. You may copy and distribute verbatim copies of this source file
as you receive it, in any medium, provided that you conspicuously
and appropriately publish on each copy a valid copyright notice
"Copyright (C) 1986 Richard M. Stallman"; and include following the
copyright notice a verbatim copy of the above disclaimer of warranty
and of this License.

  2. You may modify your copy or copies of this source file or
any portion of it, and copy and distribute such modifications under
the terms of Paragraph 1 above, provided that you also do the following:

    a) cause the modified files to carry prominent notices stating
    that you changed the files and the date of any change; and

    b) cause the whole of any work that you distribute or publish,
    that in whole or in part contains or is a derivative of this
    program or any part thereof, to be freely distributed
    and licensed to all third parties on terms identical to those
    contained in this License Agreement (except that you may choose
    to grant more extensive warranty protection to third parties,
    at your option).

  3. You may copy and distribute this program or any portion of it in
compiled, executable or object code form under the terms of Paragraphs
1 and 2 above provided that you do the following:

    a) cause each such copy to be accompanied by the
    corresponding machine-readable source code, which must
    be distributed under the terms of Paragraphs 1 and 2 above; or,

    b) cause each such copy to be accompanied by a
    written offer, with no time limit, to give any third party
    free (except for a nominal shipping charge) a machine readable
    copy of the corresponding source code, to be distributed
    under the terms of Paragraphs 1 and 2 above; or,

    c) in the case of a recipient of this program in compiled, executable
    or object code form (without the corresponding source code) you
    shall cause copies you distribute to be accompanied by a copy
    of the written offer of source code which you received along
    with the copy you received.

  4. You may not copy, sublicense, distribute or transfer this program
except as expressly provided under this License Agreement.  Any attempt
otherwise to copy, sublicense, distribute or transfer this program is void and
your rights to use the program under this License agreement shall be
automatically terminated.  However, parties who have received computer
software programs from you with this License Agreement will not have
their licenses terminated so long as such parties remain in full compliance.

 In other words, you are welcome to use, share and improve this program.
 You are forbidden to forbid anyone else to use, share and improve
 what you give them.   Help stamp out software-hoarding!  */

#include <stdio.h>
#include <a.out.h>

/* Radix for printing addresses (must be 8, 10 or 16) */

int address_radix;

/* Minimum length of sequence
  of graphic chars to trigger output.  */

int stringmin;

/* Nonzero means print address within file for each string.  */

int addressflag;

/* Nonzero means for object files scan only the data section.  */

int datasection;

char *concat ();

main (argc, argv)
     int argc;
     char **argv;
{
  int i;
  stringmin = 4;
  addressflag = 0;
  datasection = 1;

  for (i = 1; i < argc; i++)
    {
      if (!strcmp (argv[i], "-"))
	datasection = 0;
      else if (!strcmp (argv[i], "-o"))
	addressflag = 1;
      else if (argv[i][0] == '-')
	stringmin = integer_arg (argv[i] + 1);
      else
	break;	/* We have reached a non-switch. */
    }
  while (i < argc)
    {
      FILE *stream = fopen (argv[i], "r");
      if (!stream)
	perror_with_name (argv[i]);
      else if (!datasection)
	{
	  dump_strings (stream, 0, 0, 0, 0);
	  fclose (stream);
	}
      else
	{
	  struct exec header;
	  int nread = fread (&header, sizeof (header), 1, stream);
	  if (!nread || N_BADMAG(header))
	    dump_strings (stream, 0, 0, sizeof (header), &header);
	  else
	    {
	      xseek (stream, sizeof (header), N_TXTOFF(header) + header.a_text);
	      dump_strings (stream, N_TXTOFF(header) + header.a_text,
			    N_TXTOFF(header) + header.a_text + header.a_data,
			    0, 0);
	    }
	  fclose (stream);
	}
      i++;
    }
}

/* Like `fseek', but works on non-random-access streams
 by reading and discarding `to - from' bytes.  */

xseek (stream, from, to)
     FILE *stream;
     int from, to;
{
  if (fseek (stream, to, 0))
    {
      char buffer[1024];
      int skip = to - from;
      while (skip > 1024)
	{
	  fread (buffer, 1024, 1, stream);
	  skip -= 1024;
	}
      fread (buffer, 1, skip, stream);
    }
}


/* Return 1 if `c' is an ASCII graphic character */

int
graphicp (c)
     unsigned char c;
{
  return (c >= 040 && c < 0177) ||
      c == '\t' || c == '\b' || c == '\f' || c == '\r';
}

/* Find the strings in the file read from `stream'.
  Assume that the stream is positioned so that the next byte read
  is at address `address' in the file.

  Optionally the caller can supply a buffer of characters
  to be processed before the data in `stream'.
  `magic' is the address of the buffer and
  `magiccount' is how many characters are in it.
  Those characters come at address `address' and the data in `stream' follow.
*/

dump_strings (stream, address, stop_point, magiccount, magic)
     FILE *stream;
     int address;
     int stop_point;
     int magiccount;
     char *magic;
{
  int bufsize = 100;
  char *buf = (char *) malloc (bufsize);

  while (1)
    {
      int i;
      int c;

      /* See if the next `stringmin' chars are all graphic chars.  */
    tryline:
      if (stop_point && address >= stop_point)
	break;
      for (i = 0; i < stringmin; i++)
	{
	  if (magiccount)
	    magiccount--, c = *magic++;
	  else
	    c = getc (stream);
	  address++;
	  if (c < 0) return;
	  if (!graphicp (c))
	    /* Found a non-graphic.  Try again starting with next char.  */
	    goto tryline;
	  buf [i] = c;
	}
      /* We found a run of `stringmin' graphic characters */
      /* Now see if it is terminated with a null byte or a newline.   */
      while (1)
	{
	  if (i == bufsize)
	    buf = (char *) xrealloc (buf, bufsize *= 2);
	  if (magiccount)
	    magiccount--, c = *magic++;
	  else
	    c = getc (stream);
	  address++;
	  if (c < 0) return;
	  if (c =='\n') break;
	  if (c == 0) break;  /* It is; print this string */
	  if (!graphicp (c))
	    goto tryline;     /* It isn't; give up on this string */
	  buf[i++] = c;       /* String continues; store it all. */
	}
      /* If we get here, the string is all graphics and properly terminated,
	 so print it.  It is all in `buf' and `i' is its length.  */
      buf[i] = 0;
      if (addressflag)
	printf ("%07o ", address - i - 1);
      for (i = 0; c = buf[i]; i++)
	switch (c)
	  {
	  case '\n':
	    printf ("\\n");
	    break;
	  case '\t':
	    printf ("\\t");
	    break;
	  case '\f':
	    printf ("\\f");
	    break;
	  case '\b':
	    printf ("\\b");
	    break;
	  case '\r':
	    printf ("\\r");
	    break;
	  default:
	    putchar (c);
	  }
      putchar ('\n');
    }
}

/* Print error message and exit.  */

fatal (s1, s2)
     char *s1, *s2;
{
  error (s1, s2);
  exit (1);
}

/* Print error message.  `s1' is printf control string, `s2' is arg for it. */

error (s1, s2)
     char *s1, *s2;
{
  printf ("strings: ");
  printf (s1, s2);
  printf ("\n");
}

perror_with_name (name)
     char *name;
{
  extern int errno, sys_nerr;
  extern char *sys_errlist[];
  char *s;

  if (errno < sys_nerr)
    s = concat ("", sys_errlist[errno], " for %s");
  else
    s = "cannot open %s";
  error (s, name);
}

/* Return a newly-allocated string whose contents concatenate those of s1, s2, s3.  */

char *
concat (s1, s2, s3)
     char *s1, *s2, *s3;
{
  int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
  char *result = (char *) xmalloc (len1 + len2 + len3 + 1);

  strcpy (result, s1);
  strcpy (result + len1, s2);
  strcpy (result + len1 + len2, s3);
  *(result + len1 + len2 + len3) = 0;

  return result;
}

/* Like malloc but get fatal error if memory is exhausted.  */

int
xmalloc (size)
     int size;
{
  int result = malloc (size);
  if (!result)
    fatal ("virtual memory exhausted", 0);
  return result;
}


int
xrealloc (ptr, size)
     char *ptr;
     int size;
{
  int result = realloc (ptr, size);
  if (!result)
    fatal ("virtual memory exhausted");
  return result;
}

/* Parse string `s' as an integer, using decimal radix by default,
 but allowing octal and hex numbers as in C.  */

int
integer_arg (s)
     char *s;
{
  int value;
  int radix = 10;
  char *p = s;
  int c;

  if (*p != '0')
    radix = 10;
  else if (*++p == 'x')
    {
      radix = 16;
      p++;
    }
  else
    radix = 8;

  value = 0;
  while (((c = *p++) >= '0' && c <= '9')
	 || (radix == 16 && (c & ~40) >= 'A' && (c & ~40) <= 'Z'))
    {
      value *= radix;
      if (c >= '0' && c <= '9')
	value += c - '0';
      else
	value += (c & ~40) - 'A';
    }

  if (c == 'b')
    value *= 512;
  else if (c == 'B')
    value *= 1024;
  else
    p--;

  if (*p)
    fatal ("invalid integer argument %s", s);
  return value;
}
