source-cache.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. /* Cache of styled source file text
  2. Copyright (C) 2018-2022 Free Software Foundation, Inc.
  3. This file is part of GDB.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  14. #include "defs.h"
  15. #include "source-cache.h"
  16. #include "gdbsupport/scoped_fd.h"
  17. #include "source.h"
  18. #include "cli/cli-style.h"
  19. #include "symtab.h"
  20. #include "gdbsupport/selftest.h"
  21. #include "objfiles.h"
  22. #include "exec.h"
  23. #include "cli/cli-cmds.h"
  24. #ifdef HAVE_SOURCE_HIGHLIGHT
  25. /* If Gnulib redirects 'open' and 'close' to its replacements
  26. 'rpl_open' and 'rpl_close' via cpp macros, including <fstream>
  27. below with those macros in effect will cause unresolved externals
  28. when GDB is linked. Happens, e.g., in the MinGW build. */
  29. #undef open
  30. #undef close
  31. #include <sstream>
  32. #include <srchilite/sourcehighlight.h>
  33. #include <srchilite/langmap.h>
  34. #endif
  35. /* The number of source files we'll cache. */
  36. #define MAX_ENTRIES 5
  37. /* See source-cache.h. */
  38. source_cache g_source_cache;
  39. /* When this is true we will use the GNU Source Highlight to add styling to
  40. source code (assuming the library is available). This is initialized to
  41. true (if appropriate) in _initialize_source_cache below. */
  42. static bool use_gnu_source_highlight;
  43. /* The "maint show gnu-source-highlight enabled" command. */
  44. static void
  45. show_use_gnu_source_highlight_enabled (struct ui_file *file, int from_tty,
  46. struct cmd_list_element *c,
  47. const char *value)
  48. {
  49. gdb_printf (file,
  50. _("Use of GNU Source Highlight library is \"%s\".\n"),
  51. value);
  52. }
  53. /* The "maint set gnu-source-highlight enabled" command. */
  54. static void
  55. set_use_gnu_source_highlight_enabled (const char *ignore_args,
  56. int from_tty,
  57. struct cmd_list_element *c)
  58. {
  59. #ifndef HAVE_SOURCE_HIGHLIGHT
  60. /* If the library is not available and the user tried to enable use of
  61. the library, then disable use of the library, and give an error. */
  62. if (use_gnu_source_highlight)
  63. {
  64. use_gnu_source_highlight = false;
  65. error (_("the GNU Source Highlight library is not available"));
  66. }
  67. #else
  68. /* We (might) have just changed how we style source code, discard any
  69. previously cached contents. */
  70. forget_cached_source_info ();
  71. #endif
  72. }
  73. /* See source-cache.h. */
  74. std::string
  75. source_cache::get_plain_source_lines (struct symtab *s,
  76. const std::string &fullname)
  77. {
  78. scoped_fd desc (open_source_file (s));
  79. if (desc.get () < 0)
  80. perror_with_name (symtab_to_filename_for_display (s));
  81. struct stat st;
  82. if (fstat (desc.get (), &st) < 0)
  83. perror_with_name (symtab_to_filename_for_display (s));
  84. std::string lines;
  85. lines.resize (st.st_size);
  86. if (myread (desc.get (), &lines[0], lines.size ()) < 0)
  87. perror_with_name (symtab_to_filename_for_display (s));
  88. time_t mtime = 0;
  89. if (s->compunit ()->objfile () != NULL
  90. && s->compunit ()->objfile ()->obfd != NULL)
  91. mtime = s->compunit ()->objfile ()->mtime;
  92. else if (current_program_space->exec_bfd ())
  93. mtime = current_program_space->ebfd_mtime;
  94. if (mtime && mtime < st.st_mtime)
  95. warning (_("Source file is more recent than executable."));
  96. std::vector<off_t> offsets;
  97. offsets.push_back (0);
  98. for (size_t offset = lines.find ('\n');
  99. offset != std::string::npos;
  100. offset = lines.find ('\n', offset))
  101. {
  102. ++offset;
  103. /* A newline at the end does not start a new line. It would
  104. seem simpler to just strip the newline in this function, but
  105. then "list" won't print the final newline. */
  106. if (offset != lines.size ())
  107. offsets.push_back (offset);
  108. }
  109. offsets.shrink_to_fit ();
  110. m_offset_cache.emplace (fullname, std::move (offsets));
  111. return lines;
  112. }
  113. #ifdef HAVE_SOURCE_HIGHLIGHT
  114. /* Return the Source Highlight language name, given a gdb language
  115. LANG. Returns NULL if the language is not known. */
  116. static const char *
  117. get_language_name (enum language lang)
  118. {
  119. switch (lang)
  120. {
  121. case language_c:
  122. case language_objc:
  123. return "c.lang";
  124. case language_cplus:
  125. return "cpp.lang";
  126. case language_d:
  127. return "d.lang";
  128. case language_go:
  129. return "go.lang";
  130. case language_fortran:
  131. return "fortran.lang";
  132. case language_m2:
  133. /* Not handled by Source Highlight. */
  134. break;
  135. case language_asm:
  136. return "asm.lang";
  137. case language_pascal:
  138. return "pascal.lang";
  139. case language_opencl:
  140. /* Not handled by Source Highlight. */
  141. break;
  142. case language_rust:
  143. return "rust.lang";
  144. case language_ada:
  145. return "ada.lang";
  146. default:
  147. break;
  148. }
  149. return nullptr;
  150. }
  151. #endif /* HAVE_SOURCE_HIGHLIGHT */
  152. /* See source-cache.h. */
  153. bool
  154. source_cache::ensure (struct symtab *s)
  155. {
  156. std::string fullname = symtab_to_fullname (s);
  157. size_t size = m_source_map.size ();
  158. for (int i = 0; i < size; ++i)
  159. {
  160. if (m_source_map[i].fullname == fullname)
  161. {
  162. /* This should always hold, because we create the file offsets
  163. when reading the file. */
  164. gdb_assert (m_offset_cache.find (fullname)
  165. != m_offset_cache.end ());
  166. /* Not strictly LRU, but at least ensure that the most
  167. recently used entry is always the last candidate for
  168. deletion. Note that this property is relied upon by at
  169. least one caller. */
  170. if (i != size - 1)
  171. std::swap (m_source_map[i], m_source_map[size - 1]);
  172. return true;
  173. }
  174. }
  175. std::string contents;
  176. try
  177. {
  178. contents = get_plain_source_lines (s, fullname);
  179. }
  180. catch (const gdb_exception_error &e)
  181. {
  182. /* If 's' is not found, an exception is thrown. */
  183. return false;
  184. }
  185. if (source_styling && gdb_stdout->can_emit_style_escape ())
  186. {
  187. #ifdef HAVE_SOURCE_HIGHLIGHT
  188. bool already_styled = false;
  189. const char *lang_name = get_language_name (s->language ());
  190. if (lang_name != nullptr && use_gnu_source_highlight)
  191. {
  192. /* The global source highlight object, or null if one was
  193. never constructed. This is stored here rather than in
  194. the class so that we don't need to include anything or do
  195. conditional compilation in source-cache.h. */
  196. static srchilite::SourceHighlight *highlighter;
  197. try
  198. {
  199. if (highlighter == nullptr)
  200. {
  201. highlighter = new srchilite::SourceHighlight ("esc.outlang");
  202. highlighter->setStyleFile ("esc.style");
  203. }
  204. std::istringstream input (contents);
  205. std::ostringstream output;
  206. highlighter->highlight (input, output, lang_name, fullname);
  207. contents = output.str ();
  208. already_styled = true;
  209. }
  210. catch (...)
  211. {
  212. /* Source Highlight will throw an exception if
  213. highlighting fails. One possible reason it can fail
  214. is if the language is unknown -- which matters to gdb
  215. because Rust support wasn't added until after 3.1.8.
  216. Ignore exceptions here and fall back to
  217. un-highlighted text. */
  218. }
  219. }
  220. if (!already_styled)
  221. #endif /* HAVE_SOURCE_HIGHLIGHT */
  222. {
  223. gdb::optional<std::string> ext_contents;
  224. ext_contents = ext_lang_colorize (fullname, contents);
  225. if (ext_contents.has_value ())
  226. contents = std::move (*ext_contents);
  227. }
  228. }
  229. source_text result = { std::move (fullname), std::move (contents) };
  230. m_source_map.push_back (std::move (result));
  231. if (m_source_map.size () > MAX_ENTRIES)
  232. {
  233. auto iter = m_source_map.begin ();
  234. m_offset_cache.erase (iter->fullname);
  235. m_source_map.erase (iter);
  236. }
  237. return true;
  238. }
  239. /* See source-cache.h. */
  240. bool
  241. source_cache::get_line_charpos (struct symtab *s,
  242. const std::vector<off_t> **offsets)
  243. {
  244. std::string fullname = symtab_to_fullname (s);
  245. auto iter = m_offset_cache.find (fullname);
  246. if (iter == m_offset_cache.end ())
  247. {
  248. if (!ensure (s))
  249. return false;
  250. iter = m_offset_cache.find (fullname);
  251. /* cache_source_text ensured this was entered. */
  252. gdb_assert (iter != m_offset_cache.end ());
  253. }
  254. *offsets = &iter->second;
  255. return true;
  256. }
  257. /* A helper function that extracts the desired source lines from TEXT,
  258. putting them into LINES_OUT. The arguments are as for
  259. get_source_lines. Returns true on success, false if the line
  260. numbers are invalid. */
  261. static bool
  262. extract_lines (const std::string &text, int first_line, int last_line,
  263. std::string *lines_out)
  264. {
  265. int lineno = 1;
  266. std::string::size_type pos = 0;
  267. std::string::size_type first_pos = std::string::npos;
  268. while (pos != std::string::npos && lineno <= last_line)
  269. {
  270. std::string::size_type new_pos = text.find ('\n', pos);
  271. if (lineno == first_line)
  272. first_pos = pos;
  273. pos = new_pos;
  274. if (lineno == last_line || pos == std::string::npos)
  275. {
  276. /* A newline at the end does not start a new line. */
  277. if (first_pos == std::string::npos
  278. || first_pos == text.size ())
  279. return false;
  280. if (pos == std::string::npos)
  281. pos = text.size ();
  282. else
  283. ++pos;
  284. *lines_out = text.substr (first_pos, pos - first_pos);
  285. return true;
  286. }
  287. ++lineno;
  288. ++pos;
  289. }
  290. return false;
  291. }
  292. /* See source-cache.h. */
  293. bool
  294. source_cache::get_source_lines (struct symtab *s, int first_line,
  295. int last_line, std::string *lines)
  296. {
  297. if (first_line < 1 || last_line < 1 || first_line > last_line)
  298. return false;
  299. if (!ensure (s))
  300. return false;
  301. return extract_lines (m_source_map.back ().contents,
  302. first_line, last_line, lines);
  303. }
  304. /* Implement 'maint flush source-cache' command. */
  305. static void
  306. source_cache_flush_command (const char *command, int from_tty)
  307. {
  308. forget_cached_source_info ();
  309. gdb_printf (_("Source cache flushed.\n"));
  310. }
  311. #if GDB_SELF_TEST
  312. namespace selftests
  313. {
  314. static void extract_lines_test ()
  315. {
  316. std::string input_text = "abc\ndef\nghi\njkl\n";
  317. std::string result;
  318. SELF_CHECK (extract_lines (input_text, 1, 1, &result)
  319. && result == "abc\n");
  320. SELF_CHECK (!extract_lines (input_text, 2, 1, &result));
  321. SELF_CHECK (extract_lines (input_text, 1, 2, &result)
  322. && result == "abc\ndef\n");
  323. SELF_CHECK (extract_lines ("abc", 1, 1, &result)
  324. && result == "abc");
  325. }
  326. }
  327. #endif
  328. void _initialize_source_cache ();
  329. void
  330. _initialize_source_cache ()
  331. {
  332. add_cmd ("source-cache", class_maintenance, source_cache_flush_command,
  333. _("Force gdb to flush its source code cache."),
  334. &maintenanceflushlist);
  335. /* All the 'maint set|show gnu-source-highlight' sub-commands. */
  336. static struct cmd_list_element *maint_set_gnu_source_highlight_cmdlist;
  337. static struct cmd_list_element *maint_show_gnu_source_highlight_cmdlist;
  338. /* Adds 'maint set|show gnu-source-highlight'. */
  339. add_setshow_prefix_cmd ("gnu-source-highlight", class_maintenance,
  340. _("Set gnu-source-highlight specific variables."),
  341. _("Show gnu-source-highlight specific variables."),
  342. &maint_set_gnu_source_highlight_cmdlist,
  343. &maint_show_gnu_source_highlight_cmdlist,
  344. &maintenance_set_cmdlist,
  345. &maintenance_show_cmdlist);
  346. /* Adds 'maint set|show gnu-source-highlight enabled'. */
  347. add_setshow_boolean_cmd ("enabled", class_maintenance,
  348. &use_gnu_source_highlight, _("\
  349. Set whether the GNU Source Highlight library should be used."), _("\
  350. Show whether the GNU Source Highlight library is being used."),_("\
  351. When enabled, GDB will use the GNU Source Highlight library to apply\n\
  352. styling to source code lines that are shown."),
  353. set_use_gnu_source_highlight_enabled,
  354. show_use_gnu_source_highlight_enabled,
  355. &maint_set_gnu_source_highlight_cmdlist,
  356. &maint_show_gnu_source_highlight_cmdlist);
  357. /* Enable use of GNU Source Highlight library, if we have it. */
  358. #ifdef HAVE_SOURCE_HIGHLIGHT
  359. use_gnu_source_highlight = true;
  360. #endif
  361. #if GDB_SELF_TEST
  362. selftests::register_test ("source-cache", selftests::extract_lines_test);
  363. #endif
  364. }