strings.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. /* strings -- print the strings of printable characters in files
  2. Copyright (C) 1993-2015 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 3, or (at your option)
  6. any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software
  13. Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
  14. 02110-1301, USA. */
  15. /* Usage: strings [options] file...
  16. Options:
  17. --all
  18. -a
  19. - Scan each file in its entirety.
  20. --data
  21. -d Scan only the initialized data section(s) of object files.
  22. --print-file-name
  23. -f Print the name of the file before each string.
  24. --bytes=min-len
  25. -n min-len
  26. -min-len Print graphic char sequences, MIN-LEN or more bytes long,
  27. that are followed by a NUL or a newline. Default is 4.
  28. --radix={o,x,d}
  29. -t {o,x,d} Print the offset within the file before each string,
  30. in octal/hex/decimal.
  31. --include-all-whitespace
  32. -w By default tab and space are the only whitepace included in graphic
  33. char sequences. This option considers all of isspace() valid.
  34. -o Like -to. (Some other implementations have -o like -to,
  35. others like -td. We chose one arbitrarily.)
  36. --encoding={s,S,b,l,B,L}
  37. -e {s,S,b,l,B,L}
  38. Select character encoding: 7-bit-character, 8-bit-character,
  39. bigendian 16-bit, littleendian 16-bit, bigendian 32-bit,
  40. littleendian 32-bit.
  41. --target=BFDNAME
  42. -T {bfdname}
  43. Specify a non-default object file format.
  44. --output-separator=sep_string
  45. -s sep_string String used to separate parsed strings in output.
  46. Default is newline.
  47. --help
  48. -h Print the usage message on the standard output.
  49. --version
  50. -V
  51. -v Print the program version number.
  52. Written by Richard Stallman <rms@gnu.ai.mit.edu>
  53. and David MacKenzie <djm@gnu.ai.mit.edu>. */
  54. #include "sysdep.h"
  55. #include "bfd.h"
  56. #include "getopt.h"
  57. #include "libiberty.h"
  58. #include "safe-ctype.h"
  59. #include "bucomm.h"
  60. #define STRING_ISGRAPHIC(c) \
  61. ( (c) >= 0 \
  62. && (c) <= 255 \
  63. && ((c) == '\t' || ISPRINT (c) || (encoding == 'S' && (c) > 127) \
  64. || (include_all_whitespace == TRUE && ISSPACE (c))) \
  65. )
  66. #ifndef errno
  67. extern int errno;
  68. #endif
  69. /* The BFD section flags that identify an initialized data section. */
  70. #define DATA_FLAGS (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS)
  71. /* Radix for printing addresses (must be 8, 10 or 16). */
  72. static int address_radix;
  73. /* Minimum length of sequence of graphic chars to trigger output. */
  74. static int string_min;
  75. /* Whether or not we include all whitespace as a graphic char. */
  76. static bfd_boolean include_all_whitespace;
  77. /* TRUE means print address within file for each string. */
  78. static bfd_boolean print_addresses;
  79. /* TRUE means print filename for each string. */
  80. static bfd_boolean print_filenames;
  81. /* TRUE means for object files scan only the data section. */
  82. static bfd_boolean datasection_only;
  83. /* TRUE if we found an initialized data section in the current file. */
  84. static bfd_boolean got_a_section;
  85. /* The BFD object file format. */
  86. static char *target;
  87. /* The character encoding format. */
  88. static char encoding;
  89. static int encoding_bytes;
  90. /* Output string used to separate parsed strings */
  91. static char *output_separator;
  92. static struct option long_options[] =
  93. {
  94. {"all", no_argument, NULL, 'a'},
  95. {"data", no_argument, NULL, 'd'},
  96. {"print-file-name", no_argument, NULL, 'f'},
  97. {"bytes", required_argument, NULL, 'n'},
  98. {"radix", required_argument, NULL, 't'},
  99. {"include-all-whitespace", required_argument, NULL, 'w'},
  100. {"encoding", required_argument, NULL, 'e'},
  101. {"target", required_argument, NULL, 'T'},
  102. {"output-separator", required_argument, NULL, 's'},
  103. {"help", no_argument, NULL, 'h'},
  104. {"version", no_argument, NULL, 'v'},
  105. {NULL, 0, NULL, 0}
  106. };
  107. /* Records the size of a named file so that we
  108. do not repeatedly run bfd_stat() on it. */
  109. typedef struct
  110. {
  111. const char * filename;
  112. bfd_size_type filesize;
  113. } filename_and_size_t;
  114. static void strings_a_section (bfd *, asection *, void *);
  115. static bfd_boolean strings_object_file (const char *);
  116. static bfd_boolean strings_file (char *);
  117. static void print_strings (const char *, FILE *, file_ptr, int, int, char *);
  118. static void usage (FILE *, int);
  119. static long get_char (FILE *, file_ptr *, int *, char **);
  120. int main (int, char **);
  121. int
  122. main (int argc, char **argv)
  123. {
  124. int optc;
  125. int exit_status = 0;
  126. bfd_boolean files_given = FALSE;
  127. char *s;
  128. int numeric_opt = 0;
  129. #if defined (HAVE_SETLOCALE)
  130. setlocale (LC_ALL, "");
  131. #endif
  132. bindtextdomain (PACKAGE, LOCALEDIR);
  133. textdomain (PACKAGE);
  134. program_name = argv[0];
  135. xmalloc_set_program_name (program_name);
  136. bfd_set_error_program_name (program_name);
  137. expandargv (&argc, &argv);
  138. string_min = 4;
  139. include_all_whitespace = FALSE;
  140. print_addresses = FALSE;
  141. print_filenames = FALSE;
  142. if (DEFAULT_STRINGS_ALL)
  143. datasection_only = FALSE;
  144. else
  145. datasection_only = TRUE;
  146. target = NULL;
  147. encoding = 's';
  148. output_separator = NULL;
  149. while ((optc = getopt_long (argc, argv, "adfhHn:wot:e:T:s:Vv0123456789",
  150. long_options, (int *) 0)) != EOF)
  151. {
  152. switch (optc)
  153. {
  154. case 'a':
  155. datasection_only = FALSE;
  156. break;
  157. case 'd':
  158. datasection_only = TRUE;
  159. break;
  160. case 'f':
  161. print_filenames = TRUE;
  162. break;
  163. case 'H':
  164. case 'h':
  165. usage (stdout, 0);
  166. case 'n':
  167. string_min = (int) strtoul (optarg, &s, 0);
  168. if (s != NULL && *s != 0)
  169. fatal (_("invalid integer argument %s"), optarg);
  170. break;
  171. case 'w':
  172. include_all_whitespace = TRUE;
  173. break;
  174. case 'o':
  175. print_addresses = TRUE;
  176. address_radix = 8;
  177. break;
  178. case 't':
  179. print_addresses = TRUE;
  180. if (optarg[1] != '\0')
  181. usage (stderr, 1);
  182. switch (optarg[0])
  183. {
  184. case 'o':
  185. address_radix = 8;
  186. break;
  187. case 'd':
  188. address_radix = 10;
  189. break;
  190. case 'x':
  191. address_radix = 16;
  192. break;
  193. default:
  194. usage (stderr, 1);
  195. }
  196. break;
  197. case 'T':
  198. target = optarg;
  199. break;
  200. case 'e':
  201. if (optarg[1] != '\0')
  202. usage (stderr, 1);
  203. encoding = optarg[0];
  204. break;
  205. case 's':
  206. output_separator = optarg;
  207. break;
  208. case 'V':
  209. case 'v':
  210. print_version ("strings");
  211. break;
  212. case '?':
  213. usage (stderr, 1);
  214. default:
  215. numeric_opt = optind;
  216. break;
  217. }
  218. }
  219. if (numeric_opt != 0)
  220. {
  221. string_min = (int) strtoul (argv[numeric_opt - 1] + 1, &s, 0);
  222. if (s != NULL && *s != 0)
  223. fatal (_("invalid integer argument %s"), argv[numeric_opt - 1] + 1);
  224. }
  225. if (string_min < 1)
  226. fatal (_("invalid minimum string length %d"), string_min);
  227. switch (encoding)
  228. {
  229. case 'S':
  230. case 's':
  231. encoding_bytes = 1;
  232. break;
  233. case 'b':
  234. case 'l':
  235. encoding_bytes = 2;
  236. break;
  237. case 'B':
  238. case 'L':
  239. encoding_bytes = 4;
  240. break;
  241. default:
  242. usage (stderr, 1);
  243. }
  244. bfd_init ();
  245. set_default_bfd_target ();
  246. if (optind >= argc)
  247. {
  248. datasection_only = FALSE;
  249. SET_BINARY (fileno (stdin));
  250. print_strings ("{standard input}", stdin, 0, 0, 0, (char *) NULL);
  251. files_given = TRUE;
  252. }
  253. else
  254. {
  255. for (; optind < argc; ++optind)
  256. {
  257. if (strcmp (argv[optind], "-") == 0)
  258. datasection_only = FALSE;
  259. else
  260. {
  261. files_given = TRUE;
  262. exit_status |= strings_file (argv[optind]) == FALSE;
  263. }
  264. }
  265. }
  266. if (!files_given)
  267. usage (stderr, 1);
  268. return (exit_status);
  269. }
  270. /* Scan section SECT of the file ABFD, whose printable name is in
  271. ARG->filename and whose size might be in ARG->filesize. If it
  272. contains initialized data set `got_a_section' and print the
  273. strings in it.
  274. FIXME: We ought to be able to return error codes/messages for
  275. certain conditions. */
  276. static void
  277. strings_a_section (bfd *abfd, asection *sect, void *arg)
  278. {
  279. filename_and_size_t * filename_and_sizep;
  280. bfd_size_type *filesizep;
  281. bfd_size_type sectsize;
  282. void *mem;
  283. if ((sect->flags & DATA_FLAGS) != DATA_FLAGS)
  284. return;
  285. sectsize = bfd_get_section_size (sect);
  286. if (sectsize <= 0)
  287. return;
  288. /* Get the size of the file. This might have been cached for us. */
  289. filename_and_sizep = (filename_and_size_t *) arg;
  290. filesizep = & filename_and_sizep->filesize;
  291. if (*filesizep == 0)
  292. {
  293. struct stat st;
  294. if (bfd_stat (abfd, &st))
  295. return;
  296. /* Cache the result so that we do not repeatedly stat this file. */
  297. *filesizep = st.st_size;
  298. }
  299. /* Compare the size of the section against the size of the file.
  300. If the section is bigger then the file must be corrupt and
  301. we should not try dumping it. */
  302. if (sectsize >= *filesizep)
  303. return;
  304. mem = xmalloc (sectsize);
  305. if (bfd_get_section_contents (abfd, sect, mem, (file_ptr) 0, sectsize))
  306. {
  307. got_a_section = TRUE;
  308. print_strings (filename_and_sizep->filename, NULL, sect->filepos,
  309. 0, sectsize, (char *) mem);
  310. }
  311. free (mem);
  312. }
  313. /* Scan all of the sections in FILE, and print the strings
  314. in the initialized data section(s).
  315. Return TRUE if successful,
  316. FALSE if not (such as if FILE is not an object file). */
  317. static bfd_boolean
  318. strings_object_file (const char *file)
  319. {
  320. filename_and_size_t filename_and_size;
  321. bfd *abfd;
  322. abfd = bfd_openr (file, target);
  323. if (abfd == NULL)
  324. /* Treat the file as a non-object file. */
  325. return FALSE;
  326. /* This call is mainly for its side effect of reading in the sections.
  327. We follow the traditional behavior of `strings' in that we don't
  328. complain if we don't recognize a file to be an object file. */
  329. if (!bfd_check_format (abfd, bfd_object))
  330. {
  331. bfd_close (abfd);
  332. return FALSE;
  333. }
  334. got_a_section = FALSE;
  335. filename_and_size.filename = file;
  336. filename_and_size.filesize = 0;
  337. bfd_map_over_sections (abfd, strings_a_section, & filename_and_size);
  338. if (!bfd_close (abfd))
  339. {
  340. bfd_nonfatal (file);
  341. return FALSE;
  342. }
  343. return got_a_section;
  344. }
  345. /* Print the strings in FILE. Return TRUE if ok, FALSE if an error occurs. */
  346. static bfd_boolean
  347. strings_file (char *file)
  348. {
  349. struct stat st;
  350. /* get_file_size does not support non-S_ISREG files. */
  351. if (stat (file, &st) < 0)
  352. {
  353. if (errno == ENOENT)
  354. non_fatal (_("'%s': No such file"), file);
  355. else
  356. non_fatal (_("Warning: could not locate '%s'. reason: %s"),
  357. file, strerror (errno));
  358. return FALSE;
  359. }
  360. /* If we weren't told to scan the whole file,
  361. try to open it as an object file and only look at
  362. initialized data sections. If that fails, fall back to the
  363. whole file. */
  364. if (!datasection_only || !strings_object_file (file))
  365. {
  366. FILE *stream;
  367. stream = fopen (file, FOPEN_RB);
  368. if (stream == NULL)
  369. {
  370. fprintf (stderr, "%s: ", program_name);
  371. perror (file);
  372. return FALSE;
  373. }
  374. print_strings (file, stream, (file_ptr) 0, 0, 0, (char *) 0);
  375. if (fclose (stream) == EOF)
  376. {
  377. fprintf (stderr, "%s: ", program_name);
  378. perror (file);
  379. return FALSE;
  380. }
  381. }
  382. return TRUE;
  383. }
  384. /* Read the next character, return EOF if none available.
  385. Assume that STREAM is positioned so that the next byte read
  386. is at address ADDRESS in the file.
  387. If STREAM is NULL, do not read from it.
  388. The caller can supply a buffer of characters
  389. to be processed before the data in STREAM.
  390. MAGIC is the address of the buffer and
  391. MAGICCOUNT is how many characters are in it. */
  392. static long
  393. get_char (FILE *stream, file_ptr *address, int *magiccount, char **magic)
  394. {
  395. int c, i;
  396. long r = 0;
  397. for (i = 0; i < encoding_bytes; i++)
  398. {
  399. if (*magiccount)
  400. {
  401. (*magiccount)--;
  402. c = *(*magic)++;
  403. }
  404. else
  405. {
  406. if (stream == NULL)
  407. return EOF;
  408. /* Only use getc_unlocked if we found a declaration for it.
  409. Otherwise, libc is not thread safe by default, and we
  410. should not use it. */
  411. #if defined(HAVE_GETC_UNLOCKED) && HAVE_DECL_GETC_UNLOCKED
  412. c = getc_unlocked (stream);
  413. #else
  414. c = getc (stream);
  415. #endif
  416. if (c == EOF)
  417. return EOF;
  418. }
  419. (*address)++;
  420. r = (r << 8) | (c & 0xff);
  421. }
  422. switch (encoding)
  423. {
  424. default:
  425. break;
  426. case 'l':
  427. r = ((r & 0xff) << 8) | ((r & 0xff00) >> 8);
  428. break;
  429. case 'L':
  430. r = (((r & 0xff) << 24) | ((r & 0xff00) << 8)
  431. | ((r & 0xff0000) >> 8) | ((r & 0xff000000) >> 24));
  432. break;
  433. }
  434. return r;
  435. }
  436. /* Find the strings in file FILENAME, read from STREAM.
  437. Assume that STREAM is positioned so that the next byte read
  438. is at address ADDRESS in the file.
  439. Stop reading at address STOP_POINT in the file, if nonzero.
  440. If STREAM is NULL, do not read from it.
  441. The caller can supply a buffer of characters
  442. to be processed before the data in STREAM.
  443. MAGIC is the address of the buffer and
  444. MAGICCOUNT is how many characters are in it.
  445. Those characters come at address ADDRESS and the data in STREAM follow. */
  446. static void
  447. print_strings (const char *filename, FILE *stream, file_ptr address,
  448. int stop_point, int magiccount, char *magic)
  449. {
  450. char *buf = (char *) xmalloc (sizeof (char) * (string_min + 1));
  451. while (1)
  452. {
  453. file_ptr start;
  454. int i;
  455. long c;
  456. /* See if the next `string_min' chars are all graphic chars. */
  457. tryline:
  458. if (stop_point && address >= stop_point)
  459. break;
  460. start = address;
  461. for (i = 0; i < string_min; i++)
  462. {
  463. c = get_char (stream, &address, &magiccount, &magic);
  464. if (c == EOF)
  465. {
  466. free (buf);
  467. return;
  468. }
  469. if (! STRING_ISGRAPHIC (c))
  470. /* Found a non-graphic. Try again starting with next char. */
  471. goto tryline;
  472. buf[i] = c;
  473. }
  474. /* We found a run of `string_min' graphic characters. Print up
  475. to the next non-graphic character. */
  476. if (print_filenames)
  477. printf ("%s: ", filename);
  478. if (print_addresses)
  479. switch (address_radix)
  480. {
  481. case 8:
  482. #ifdef HAVE_LONG_LONG
  483. if (sizeof (start) > sizeof (long))
  484. {
  485. # ifndef __MSVCRT__
  486. printf ("%7llo ", (unsigned long long) start);
  487. # else
  488. printf ("%7I64o ", (unsigned long long) start);
  489. # endif
  490. }
  491. else
  492. #elif !BFD_HOST_64BIT_LONG
  493. if (start != (unsigned long) start)
  494. printf ("++%7lo ", (unsigned long) start);
  495. else
  496. #endif
  497. printf ("%7lo ", (unsigned long) start);
  498. break;
  499. case 10:
  500. #ifdef HAVE_LONG_LONG
  501. if (sizeof (start) > sizeof (long))
  502. {
  503. # ifndef __MSVCRT__
  504. printf ("%7lld ", (unsigned long long) start);
  505. # else
  506. printf ("%7I64d ", (unsigned long long) start);
  507. # endif
  508. }
  509. else
  510. #elif !BFD_HOST_64BIT_LONG
  511. if (start != (unsigned long) start)
  512. printf ("++%7ld ", (unsigned long) start);
  513. else
  514. #endif
  515. printf ("%7ld ", (long) start);
  516. break;
  517. case 16:
  518. #ifdef HAVE_LONG_LONG
  519. if (sizeof (start) > sizeof (long))
  520. {
  521. # ifndef __MSVCRT__
  522. printf ("%7llx ", (unsigned long long) start);
  523. # else
  524. printf ("%7I64x ", (unsigned long long) start);
  525. # endif
  526. }
  527. else
  528. #elif !BFD_HOST_64BIT_LONG
  529. if (start != (unsigned long) start)
  530. printf ("%lx%8.8lx ", (unsigned long) (start >> 32),
  531. (unsigned long) (start & 0xffffffff));
  532. else
  533. #endif
  534. printf ("%7lx ", (unsigned long) start);
  535. break;
  536. }
  537. buf[i] = '\0';
  538. fputs (buf, stdout);
  539. while (1)
  540. {
  541. c = get_char (stream, &address, &magiccount, &magic);
  542. if (c == EOF)
  543. break;
  544. if (! STRING_ISGRAPHIC (c))
  545. break;
  546. putchar (c);
  547. }
  548. if (output_separator)
  549. fputs (output_separator, stdout);
  550. else
  551. putchar ('\n');
  552. }
  553. free (buf);
  554. }
  555. static void
  556. usage (FILE *stream, int status)
  557. {
  558. fprintf (stream, _("Usage: %s [option(s)] [file(s)]\n"), program_name);
  559. fprintf (stream, _(" Display printable strings in [file(s)] (stdin by default)\n"));
  560. fprintf (stream, _(" The options are:\n"));
  561. if (DEFAULT_STRINGS_ALL)
  562. fprintf (stream, _("\
  563. -a - --all Scan the entire file, not just the data section [default]\n\
  564. -d --data Only scan the data sections in the file\n"));
  565. else
  566. fprintf (stream, _("\
  567. -a - --all Scan the entire file, not just the data section\n\
  568. -d --data Only scan the data sections in the file [default]\n"));
  569. fprintf (stream, _("\
  570. -f --print-file-name Print the name of the file before each string\n\
  571. -n --bytes=[number] Locate & print any NUL-terminated sequence of at\n\
  572. -<number> least [number] characters (default 4).\n\
  573. -t --radix={o,d,x} Print the location of the string in base 8, 10 or 16\n\
  574. -w --include-all-whitespace Include all whitespace as valid string characters\n\
  575. -o An alias for --radix=o\n\
  576. -T --target=<BFDNAME> Specify the binary file format\n\
  577. -e --encoding={s,S,b,l,B,L} Select character size and endianness:\n\
  578. s = 7-bit, S = 8-bit, {b,l} = 16-bit, {B,L} = 32-bit\n\
  579. -s --output-separator=<string> String used to separate strings in output.\n\
  580. @<file> Read options from <file>\n\
  581. -h --help Display this information\n\
  582. -v -V --version Print the program's version number\n"));
  583. list_supported_targets (program_name, stream);
  584. if (REPORT_BUGS_TO[0] && status == 0)
  585. fprintf (stream, _("Report bugs to %s\n"), REPORT_BUGS_TO);
  586. exit (status);
  587. }