source.c 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049
  1. /* List lines of source files for GDB, the GNU debugger.
  2. Copyright (C) 1986-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 "arch-utils.h"
  16. #include "symtab.h"
  17. #include "expression.h"
  18. #include "language.h"
  19. #include "command.h"
  20. #include "source.h"
  21. #include "gdbcmd.h"
  22. #include "frame.h"
  23. #include "value.h"
  24. #include "gdbsupport/filestuff.h"
  25. #include <sys/types.h>
  26. #include <fcntl.h>
  27. #include "gdbcore.h"
  28. #include "gdbsupport/gdb_regex.h"
  29. #include "symfile.h"
  30. #include "objfiles.h"
  31. #include "annotate.h"
  32. #include "gdbtypes.h"
  33. #include "linespec.h"
  34. #include "filenames.h" /* for DOSish file names */
  35. #include "completer.h"
  36. #include "ui-out.h"
  37. #include "readline/tilde.h"
  38. #include "gdbsupport/enum-flags.h"
  39. #include "gdbsupport/scoped_fd.h"
  40. #include <algorithm>
  41. #include "gdbsupport/pathstuff.h"
  42. #include "source-cache.h"
  43. #include "cli/cli-style.h"
  44. #include "observable.h"
  45. #include "build-id.h"
  46. #include "debuginfod-support.h"
  47. #include "gdbsupport/buildargv.h"
  48. #define OPEN_MODE (O_RDONLY | O_BINARY)
  49. #define FDOPEN_MODE FOPEN_RB
  50. /* Path of directories to search for source files.
  51. Same format as the PATH environment variable's value. */
  52. std::string source_path;
  53. /* Support for source path substitution commands. */
  54. struct substitute_path_rule
  55. {
  56. substitute_path_rule (const char *from_, const char *to_)
  57. : from (from_),
  58. to (to_)
  59. {
  60. }
  61. std::string from;
  62. std::string to;
  63. };
  64. static std::list<substitute_path_rule> substitute_path_rules;
  65. /* An instance of this is attached to each program space. */
  66. struct current_source_location
  67. {
  68. public:
  69. current_source_location () = default;
  70. /* Set the value. */
  71. void set (struct symtab *s, int l)
  72. {
  73. m_symtab = s;
  74. m_line = l;
  75. gdb::observers::current_source_symtab_and_line_changed.notify ();
  76. }
  77. /* Get the symtab. */
  78. struct symtab *symtab () const
  79. {
  80. return m_symtab;
  81. }
  82. /* Get the line number. */
  83. int line () const
  84. {
  85. return m_line;
  86. }
  87. private:
  88. /* Symtab of default file for listing lines of. */
  89. struct symtab *m_symtab = nullptr;
  90. /* Default next line to list. */
  91. int m_line = 0;
  92. };
  93. static program_space_key<current_source_location> current_source_key;
  94. /* Default number of lines to print with commands like "list".
  95. This is based on guessing how many long (i.e. more than chars_per_line
  96. characters) lines there will be. To be completely correct, "list"
  97. and friends should be rewritten to count characters and see where
  98. things are wrapping, but that would be a fair amount of work. */
  99. static int lines_to_list = 10;
  100. static void
  101. show_lines_to_list (struct ui_file *file, int from_tty,
  102. struct cmd_list_element *c, const char *value)
  103. {
  104. gdb_printf (file,
  105. _("Number of source lines gdb "
  106. "will list by default is %s.\n"),
  107. value);
  108. }
  109. /* Possible values of 'set filename-display'. */
  110. static const char filename_display_basename[] = "basename";
  111. static const char filename_display_relative[] = "relative";
  112. static const char filename_display_absolute[] = "absolute";
  113. static const char *const filename_display_kind_names[] = {
  114. filename_display_basename,
  115. filename_display_relative,
  116. filename_display_absolute,
  117. NULL
  118. };
  119. static const char *filename_display_string = filename_display_relative;
  120. static void
  121. show_filename_display_string (struct ui_file *file, int from_tty,
  122. struct cmd_list_element *c, const char *value)
  123. {
  124. gdb_printf (file, _("Filenames are displayed as \"%s\".\n"), value);
  125. }
  126. /* When true GDB will stat and open source files as required, but when
  127. false, GDB will avoid accessing source files as much as possible. */
  128. static bool source_open = true;
  129. /* Implement 'show source open'. */
  130. static void
  131. show_source_open (struct ui_file *file, int from_tty,
  132. struct cmd_list_element *c, const char *value)
  133. {
  134. gdb_printf (file, _("Source opening is \"%s\".\n"), value);
  135. }
  136. /* Line number of last line printed. Default for various commands.
  137. current_source_line is usually, but not always, the same as this. */
  138. static int last_line_listed;
  139. /* First line number listed by last listing command. If 0, then no
  140. source lines have yet been listed since the last time the current
  141. source line was changed. */
  142. static int first_line_listed;
  143. /* Saves the name of the last source file visited and a possible error code.
  144. Used to prevent repeating annoying "No such file or directories" msgs. */
  145. static struct symtab *last_source_visited = NULL;
  146. static bool last_source_error = false;
  147. /* Return the first line listed by print_source_lines.
  148. Used by command interpreters to request listing from
  149. a previous point. */
  150. int
  151. get_first_line_listed (void)
  152. {
  153. return first_line_listed;
  154. }
  155. /* Clear line listed range. This makes the next "list" center the
  156. printed source lines around the current source line. */
  157. static void
  158. clear_lines_listed_range (void)
  159. {
  160. first_line_listed = 0;
  161. last_line_listed = 0;
  162. }
  163. /* Return the default number of lines to print with commands like the
  164. cli "list". The caller of print_source_lines must use this to
  165. calculate the end line and use it in the call to print_source_lines
  166. as it does not automatically use this value. */
  167. int
  168. get_lines_to_list (void)
  169. {
  170. return lines_to_list;
  171. }
  172. /* A helper to return the current source location object for PSPACE,
  173. creating it if it does not exist. */
  174. static current_source_location *
  175. get_source_location (program_space *pspace)
  176. {
  177. current_source_location *loc
  178. = current_source_key.get (pspace);
  179. if (loc == nullptr)
  180. loc = current_source_key.emplace (pspace);
  181. return loc;
  182. }
  183. /* Return the current source file for listing and next line to list.
  184. NOTE: The returned sal pc and end fields are not valid. */
  185. struct symtab_and_line
  186. get_current_source_symtab_and_line (void)
  187. {
  188. symtab_and_line cursal;
  189. current_source_location *loc = get_source_location (current_program_space);
  190. cursal.pspace = current_program_space;
  191. cursal.symtab = loc->symtab ();
  192. cursal.line = loc->line ();
  193. cursal.pc = 0;
  194. cursal.end = 0;
  195. return cursal;
  196. }
  197. /* If the current source file for listing is not set, try and get a default.
  198. Usually called before get_current_source_symtab_and_line() is called.
  199. It may err out if a default cannot be determined.
  200. We must be cautious about where it is called, as it can recurse as the
  201. process of determining a new default may call the caller!
  202. Use get_current_source_symtab_and_line only to get whatever
  203. we have without erroring out or trying to get a default. */
  204. void
  205. set_default_source_symtab_and_line (void)
  206. {
  207. if (!have_full_symbols () && !have_partial_symbols ())
  208. error (_("No symbol table is loaded. Use the \"file\" command."));
  209. /* Pull in a current source symtab if necessary. */
  210. current_source_location *loc = get_source_location (current_program_space);
  211. if (loc->symtab () == nullptr)
  212. select_source_symtab (0);
  213. }
  214. /* Return the current default file for listing and next line to list
  215. (the returned sal pc and end fields are not valid.)
  216. and set the current default to whatever is in SAL.
  217. NOTE: The returned sal pc and end fields are not valid. */
  218. struct symtab_and_line
  219. set_current_source_symtab_and_line (const symtab_and_line &sal)
  220. {
  221. symtab_and_line cursal;
  222. current_source_location *loc = get_source_location (sal.pspace);
  223. cursal.pspace = sal.pspace;
  224. cursal.symtab = loc->symtab ();
  225. cursal.line = loc->line ();
  226. cursal.pc = 0;
  227. cursal.end = 0;
  228. loc->set (sal.symtab, sal.line);
  229. /* Force the next "list" to center around the current line. */
  230. clear_lines_listed_range ();
  231. return cursal;
  232. }
  233. /* Reset any information stored about a default file and line to print. */
  234. void
  235. clear_current_source_symtab_and_line (void)
  236. {
  237. current_source_location *loc = get_source_location (current_program_space);
  238. loc->set (nullptr, 0);
  239. }
  240. /* See source.h. */
  241. void
  242. select_source_symtab (struct symtab *s)
  243. {
  244. if (s)
  245. {
  246. current_source_location *loc
  247. = get_source_location (s->compunit ()->objfile ()->pspace);
  248. loc->set (s, 1);
  249. return;
  250. }
  251. current_source_location *loc = get_source_location (current_program_space);
  252. if (loc->symtab () != nullptr)
  253. return;
  254. /* Make the default place to list be the function `main'
  255. if one exists. */
  256. block_symbol bsym = lookup_symbol (main_name (), 0, VAR_DOMAIN, 0);
  257. if (bsym.symbol != nullptr && bsym.symbol->aclass () == LOC_BLOCK)
  258. {
  259. symtab_and_line sal = find_function_start_sal (bsym.symbol, true);
  260. if (sal.symtab == NULL)
  261. /* We couldn't find the location of `main', possibly due to missing
  262. line number info, fall back to line 1 in the corresponding file. */
  263. loc->set (symbol_symtab (bsym.symbol), 1);
  264. else
  265. loc->set (sal.symtab, std::max (sal.line - (lines_to_list - 1), 1));
  266. return;
  267. }
  268. /* Alright; find the last file in the symtab list (ignoring .h's
  269. and namespace symtabs). */
  270. struct symtab *new_symtab = nullptr;
  271. for (objfile *ofp : current_program_space->objfiles ())
  272. {
  273. for (compunit_symtab *cu : ofp->compunits ())
  274. {
  275. for (symtab *symtab : cu->filetabs ())
  276. {
  277. const char *name = symtab->filename;
  278. int len = strlen (name);
  279. if (!(len > 2 && (strcmp (&name[len - 2], ".h") == 0
  280. || strcmp (name, "<<C++-namespaces>>") == 0)))
  281. new_symtab = symtab;
  282. }
  283. }
  284. }
  285. loc->set (new_symtab, 1);
  286. if (new_symtab != nullptr)
  287. return;
  288. for (objfile *objfile : current_program_space->objfiles ())
  289. {
  290. s = objfile->find_last_source_symtab ();
  291. if (s)
  292. new_symtab = s;
  293. }
  294. if (new_symtab != nullptr)
  295. {
  296. loc->set (new_symtab,1);
  297. return;
  298. }
  299. error (_("Can't find a default source file"));
  300. }
  301. /* Handler for "set directories path-list" command.
  302. "set dir mumble" doesn't prepend paths, it resets the entire
  303. path list. The theory is that set(show(dir)) should be a no-op. */
  304. static void
  305. set_directories_command (const char *args,
  306. int from_tty, struct cmd_list_element *c)
  307. {
  308. /* This is the value that was set.
  309. It needs to be processed to maintain $cdir:$cwd and remove dups. */
  310. std::string set_path = source_path;
  311. /* We preserve the invariant that $cdir:$cwd begins life at the end of
  312. the list by calling init_source_path. If they appear earlier in
  313. SET_PATH then mod_path will move them appropriately.
  314. mod_path will also remove duplicates. */
  315. init_source_path ();
  316. if (!set_path.empty ())
  317. mod_path (set_path.c_str (), source_path);
  318. }
  319. /* Print the list of source directories.
  320. This is used by the "ld" command, so it has the signature of a command
  321. function. */
  322. static void
  323. show_directories_1 (ui_file *file, char *ignore, int from_tty)
  324. {
  325. gdb_puts ("Source directories searched: ", file);
  326. gdb_puts (source_path.c_str (), file);
  327. gdb_puts ("\n", file);
  328. }
  329. /* Handler for "show directories" command. */
  330. static void
  331. show_directories_command (struct ui_file *file, int from_tty,
  332. struct cmd_list_element *c, const char *value)
  333. {
  334. show_directories_1 (file, NULL, from_tty);
  335. }
  336. /* See source.h. */
  337. void
  338. forget_cached_source_info_for_objfile (struct objfile *objfile)
  339. {
  340. for (compunit_symtab *cu : objfile->compunits ())
  341. {
  342. for (symtab *s : cu->filetabs ())
  343. {
  344. if (s->fullname != NULL)
  345. {
  346. xfree (s->fullname);
  347. s->fullname = NULL;
  348. }
  349. }
  350. }
  351. objfile->forget_cached_source_info ();
  352. }
  353. /* See source.h. */
  354. void
  355. forget_cached_source_info (void)
  356. {
  357. for (struct program_space *pspace : program_spaces)
  358. for (objfile *objfile : pspace->objfiles ())
  359. {
  360. forget_cached_source_info_for_objfile (objfile);
  361. }
  362. g_source_cache.clear ();
  363. last_source_visited = NULL;
  364. }
  365. void
  366. init_source_path (void)
  367. {
  368. source_path = string_printf ("$cdir%c$cwd", DIRNAME_SEPARATOR);
  369. forget_cached_source_info ();
  370. }
  371. /* Add zero or more directories to the front of the source path. */
  372. static void
  373. directory_command (const char *dirname, int from_tty)
  374. {
  375. bool value_changed = false;
  376. dont_repeat ();
  377. /* FIXME, this goes to "delete dir"... */
  378. if (dirname == 0)
  379. {
  380. if (!from_tty || query (_("Reinitialize source path to empty? ")))
  381. {
  382. init_source_path ();
  383. value_changed = true;
  384. }
  385. }
  386. else
  387. {
  388. mod_path (dirname, source_path);
  389. forget_cached_source_info ();
  390. value_changed = true;
  391. }
  392. if (value_changed)
  393. {
  394. gdb::observers::command_param_changed.notify ("directories",
  395. source_path.c_str ());
  396. if (from_tty)
  397. show_directories_1 (gdb_stdout, (char *) 0, from_tty);
  398. }
  399. }
  400. /* Add a path given with the -d command line switch.
  401. This will not be quoted so we must not treat spaces as separators. */
  402. void
  403. directory_switch (const char *dirname, int from_tty)
  404. {
  405. add_path (dirname, source_path, 0);
  406. }
  407. /* Add zero or more directories to the front of an arbitrary path. */
  408. void
  409. mod_path (const char *dirname, std::string &which_path)
  410. {
  411. add_path (dirname, which_path, 1);
  412. }
  413. /* Workhorse of mod_path. Takes an extra argument to determine
  414. if dirname should be parsed for separators that indicate multiple
  415. directories. This allows for interfaces that pre-parse the dirname
  416. and allow specification of traditional separator characters such
  417. as space or tab. */
  418. void
  419. add_path (const char *dirname, char **which_path, int parse_separators)
  420. {
  421. char *old = *which_path;
  422. int prefix = 0;
  423. std::vector<gdb::unique_xmalloc_ptr<char>> dir_vec;
  424. if (dirname == 0)
  425. return;
  426. if (parse_separators)
  427. {
  428. /* This will properly parse the space and tab separators
  429. and any quotes that may exist. */
  430. gdb_argv argv (dirname);
  431. for (char *arg : argv)
  432. dirnames_to_char_ptr_vec_append (&dir_vec, arg);
  433. }
  434. else
  435. dir_vec.emplace_back (xstrdup (dirname));
  436. for (const gdb::unique_xmalloc_ptr<char> &name_up : dir_vec)
  437. {
  438. char *name = name_up.get ();
  439. char *p;
  440. struct stat st;
  441. gdb::unique_xmalloc_ptr<char> new_name_holder;
  442. /* Spaces and tabs will have been removed by buildargv().
  443. NAME is the start of the directory.
  444. P is the '\0' following the end. */
  445. p = name + strlen (name);
  446. while (!(IS_DIR_SEPARATOR (*name) && p <= name + 1) /* "/" */
  447. #ifdef HAVE_DOS_BASED_FILE_SYSTEM
  448. /* On MS-DOS and MS-Windows, h:\ is different from h: */
  449. && !(p == name + 3 && name[1] == ':') /* "d:/" */
  450. #endif
  451. && p > name
  452. && IS_DIR_SEPARATOR (p[-1]))
  453. /* Sigh. "foo/" => "foo" */
  454. --p;
  455. *p = '\0';
  456. while (p > name && p[-1] == '.')
  457. {
  458. if (p - name == 1)
  459. {
  460. /* "." => getwd (). */
  461. name = current_directory;
  462. goto append;
  463. }
  464. else if (p > name + 1 && IS_DIR_SEPARATOR (p[-2]))
  465. {
  466. if (p - name == 2)
  467. {
  468. /* "/." => "/". */
  469. *--p = '\0';
  470. goto append;
  471. }
  472. else
  473. {
  474. /* "...foo/." => "...foo". */
  475. p -= 2;
  476. *p = '\0';
  477. continue;
  478. }
  479. }
  480. else
  481. break;
  482. }
  483. if (name[0] == '\0')
  484. goto skip_dup;
  485. if (name[0] == '~')
  486. new_name_holder.reset (tilde_expand (name));
  487. #ifdef HAVE_DOS_BASED_FILE_SYSTEM
  488. else if (IS_ABSOLUTE_PATH (name) && p == name + 2) /* "d:" => "d:." */
  489. new_name_holder.reset (concat (name, ".", (char *) NULL));
  490. #endif
  491. else if (!IS_ABSOLUTE_PATH (name) && name[0] != '$')
  492. new_name_holder = gdb_abspath (name);
  493. else
  494. new_name_holder.reset (savestring (name, p - name));
  495. name = new_name_holder.get ();
  496. /* Unless it's a variable, check existence. */
  497. if (name[0] != '$')
  498. {
  499. /* These are warnings, not errors, since we don't want a
  500. non-existent directory in a .gdbinit file to stop processing
  501. of the .gdbinit file.
  502. Whether they get added to the path is more debatable. Current
  503. answer is yes, in case the user wants to go make the directory
  504. or whatever. If the directory continues to not exist/not be
  505. a directory/etc, then having them in the path should be
  506. harmless. */
  507. if (stat (name, &st) < 0)
  508. {
  509. int save_errno = errno;
  510. gdb_printf (gdb_stderr, "Warning: ");
  511. print_sys_errmsg (name, save_errno);
  512. }
  513. else if ((st.st_mode & S_IFMT) != S_IFDIR)
  514. warning (_("%s is not a directory."), name);
  515. }
  516. append:
  517. {
  518. unsigned int len = strlen (name);
  519. char tinybuf[2];
  520. p = *which_path;
  521. while (1)
  522. {
  523. /* FIXME: we should use realpath() or its work-alike
  524. before comparing. Then all the code above which
  525. removes excess slashes and dots could simply go away. */
  526. if (!filename_ncmp (p, name, len)
  527. && (p[len] == '\0' || p[len] == DIRNAME_SEPARATOR))
  528. {
  529. /* Found it in the search path, remove old copy. */
  530. if (p > *which_path)
  531. {
  532. /* Back over leading separator. */
  533. p--;
  534. }
  535. if (prefix > p - *which_path)
  536. {
  537. /* Same dir twice in one cmd. */
  538. goto skip_dup;
  539. }
  540. /* Copy from next '\0' or ':'. */
  541. memmove (p, &p[len + 1], strlen (&p[len + 1]) + 1);
  542. }
  543. p = strchr (p, DIRNAME_SEPARATOR);
  544. if (p != 0)
  545. ++p;
  546. else
  547. break;
  548. }
  549. tinybuf[0] = DIRNAME_SEPARATOR;
  550. tinybuf[1] = '\0';
  551. /* If we have already tacked on a name(s) in this command,
  552. be sure they stay on the front as we tack on some
  553. more. */
  554. if (prefix)
  555. {
  556. std::string temp = std::string (old, prefix) + tinybuf + name;
  557. *which_path = concat (temp.c_str (), &old[prefix],
  558. (char *) nullptr);
  559. prefix = temp.length ();
  560. }
  561. else
  562. {
  563. *which_path = concat (name, (old[0] ? tinybuf : old),
  564. old, (char *)NULL);
  565. prefix = strlen (name);
  566. }
  567. xfree (old);
  568. old = *which_path;
  569. }
  570. skip_dup:
  571. ;
  572. }
  573. }
  574. /* add_path would need to be re-written to work on an std::string, but this is
  575. not trivial. Hence this overload which copies to a `char *` and back. */
  576. void
  577. add_path (const char *dirname, std::string &which_path, int parse_separators)
  578. {
  579. char *which_path_copy = xstrdup (which_path.data ());
  580. add_path (dirname, &which_path_copy, parse_separators);
  581. which_path = which_path_copy;
  582. xfree (which_path_copy);
  583. }
  584. static void
  585. info_source_command (const char *ignore, int from_tty)
  586. {
  587. current_source_location *loc
  588. = get_source_location (current_program_space);
  589. struct symtab *s = loc->symtab ();
  590. struct compunit_symtab *cust;
  591. if (!s)
  592. {
  593. gdb_printf (_("No current source file.\n"));
  594. return;
  595. }
  596. cust = s->compunit ();
  597. gdb_printf (_("Current source file is %s\n"), s->filename);
  598. if (s->compunit ()->dirname () != NULL)
  599. gdb_printf (_("Compilation directory is %s\n"), s->compunit ()->dirname ());
  600. if (s->fullname)
  601. gdb_printf (_("Located in %s\n"), s->fullname);
  602. const std::vector<off_t> *offsets;
  603. if (g_source_cache.get_line_charpos (s, &offsets))
  604. gdb_printf (_("Contains %d line%s.\n"), (int) offsets->size (),
  605. offsets->size () == 1 ? "" : "s");
  606. gdb_printf (_("Source language is %s.\n"),
  607. language_str (s->language ()));
  608. gdb_printf (_("Producer is %s.\n"),
  609. (cust->producer ()) != nullptr
  610. ? cust->producer () : _("unknown"));
  611. gdb_printf (_("Compiled with %s debugging format.\n"),
  612. cust->debugformat ());
  613. gdb_printf (_("%s preprocessor macro info.\n"),
  614. (cust->macro_table () != nullptr
  615. ? "Includes" : "Does not include"));
  616. }
  617. /* Helper function to remove characters from the start of PATH so that
  618. PATH can then be appended to a directory name. We remove leading drive
  619. letters (for dos) as well as leading '/' characters and './'
  620. sequences. */
  621. static const char *
  622. prepare_path_for_appending (const char *path)
  623. {
  624. /* For dos paths, d:/foo -> /foo, and d:foo -> foo. */
  625. if (HAS_DRIVE_SPEC (path))
  626. path = STRIP_DRIVE_SPEC (path);
  627. const char *old_path;
  628. do
  629. {
  630. old_path = path;
  631. /* /foo => foo, to avoid multiple slashes that Emacs doesn't like. */
  632. while (IS_DIR_SEPARATOR(path[0]))
  633. path++;
  634. /* ./foo => foo */
  635. while (path[0] == '.' && IS_DIR_SEPARATOR (path[1]))
  636. path += 2;
  637. }
  638. while (old_path != path);
  639. return path;
  640. }
  641. /* Open a file named STRING, searching path PATH (dir names sep by some char)
  642. using mode MODE in the calls to open. You cannot use this function to
  643. create files (O_CREAT).
  644. OPTS specifies the function behaviour in specific cases.
  645. If OPF_TRY_CWD_FIRST, try to open ./STRING before searching PATH.
  646. (ie pretend the first element of PATH is "."). This also indicates
  647. that, unless OPF_SEARCH_IN_PATH is also specified, a slash in STRING
  648. disables searching of the path (this is so that "exec-file ./foo" or
  649. "symbol-file ./foo" insures that you get that particular version of
  650. foo or an error message).
  651. If OPTS has OPF_SEARCH_IN_PATH set, absolute names will also be
  652. searched in path (we usually want this for source files but not for
  653. executables).
  654. If FILENAME_OPENED is non-null, set it to a newly allocated string naming
  655. the actual file opened (this string will always start with a "/"). We
  656. have to take special pains to avoid doubling the "/" between the directory
  657. and the file, sigh! Emacs gets confuzzed by this when we print the
  658. source file name!!!
  659. If OPTS has OPF_RETURN_REALPATH set return FILENAME_OPENED resolved by
  660. gdb_realpath. Even without OPF_RETURN_REALPATH this function still returns
  661. filename starting with "/". If FILENAME_OPENED is NULL this option has no
  662. effect.
  663. If a file is found, return the descriptor.
  664. Otherwise, return -1, with errno set for the last name we tried to open. */
  665. /* >>>> This should only allow files of certain types,
  666. >>>> eg executable, non-directory. */
  667. int
  668. openp (const char *path, openp_flags opts, const char *string,
  669. int mode, gdb::unique_xmalloc_ptr<char> *filename_opened)
  670. {
  671. int fd;
  672. char *filename;
  673. int alloclen;
  674. /* The errno set for the last name we tried to open (and
  675. failed). */
  676. int last_errno = 0;
  677. std::vector<gdb::unique_xmalloc_ptr<char>> dir_vec;
  678. /* The open syscall MODE parameter is not specified. */
  679. gdb_assert ((mode & O_CREAT) == 0);
  680. gdb_assert (string != NULL);
  681. /* A file with an empty name cannot possibly exist. Report a failure
  682. without further checking.
  683. This is an optimization which also defends us against buggy
  684. implementations of the "stat" function. For instance, we have
  685. noticed that a MinGW debugger built on Windows XP 32bits crashes
  686. when the debugger is started with an empty argument. */
  687. if (string[0] == '\0')
  688. {
  689. errno = ENOENT;
  690. return -1;
  691. }
  692. if (!path)
  693. path = ".";
  694. mode |= O_BINARY;
  695. if ((opts & OPF_TRY_CWD_FIRST) || IS_ABSOLUTE_PATH (string))
  696. {
  697. int i, reg_file_errno;
  698. if (is_regular_file (string, &reg_file_errno))
  699. {
  700. filename = (char *) alloca (strlen (string) + 1);
  701. strcpy (filename, string);
  702. fd = gdb_open_cloexec (filename, mode, 0).release ();
  703. if (fd >= 0)
  704. goto done;
  705. last_errno = errno;
  706. }
  707. else
  708. {
  709. filename = NULL;
  710. fd = -1;
  711. last_errno = reg_file_errno;
  712. }
  713. if (!(opts & OPF_SEARCH_IN_PATH))
  714. for (i = 0; string[i]; i++)
  715. if (IS_DIR_SEPARATOR (string[i]))
  716. goto done;
  717. }
  718. /* Remove characters from the start of PATH that we don't need when PATH
  719. is appended to a directory name. */
  720. string = prepare_path_for_appending (string);
  721. alloclen = strlen (path) + strlen (string) + 2;
  722. filename = (char *) alloca (alloclen);
  723. fd = -1;
  724. last_errno = ENOENT;
  725. dir_vec = dirnames_to_char_ptr_vec (path);
  726. for (const gdb::unique_xmalloc_ptr<char> &dir_up : dir_vec)
  727. {
  728. char *dir = dir_up.get ();
  729. size_t len = strlen (dir);
  730. int reg_file_errno;
  731. if (strcmp (dir, "$cwd") == 0)
  732. {
  733. /* Name is $cwd -- insert current directory name instead. */
  734. int newlen;
  735. /* First, realloc the filename buffer if too short. */
  736. len = strlen (current_directory);
  737. newlen = len + strlen (string) + 2;
  738. if (newlen > alloclen)
  739. {
  740. alloclen = newlen;
  741. filename = (char *) alloca (alloclen);
  742. }
  743. strcpy (filename, current_directory);
  744. }
  745. else if (strchr(dir, '~'))
  746. {
  747. /* See whether we need to expand the tilde. */
  748. int newlen;
  749. gdb::unique_xmalloc_ptr<char> tilde_expanded (tilde_expand (dir));
  750. /* First, realloc the filename buffer if too short. */
  751. len = strlen (tilde_expanded.get ());
  752. newlen = len + strlen (string) + 2;
  753. if (newlen > alloclen)
  754. {
  755. alloclen = newlen;
  756. filename = (char *) alloca (alloclen);
  757. }
  758. strcpy (filename, tilde_expanded.get ());
  759. }
  760. else
  761. {
  762. /* Normal file name in path -- just use it. */
  763. strcpy (filename, dir);
  764. /* Don't search $cdir. It's also a magic path like $cwd, but we
  765. don't have enough information to expand it. The user *could*
  766. have an actual directory named '$cdir' but handling that would
  767. be confusing, it would mean different things in different
  768. contexts. If the user really has '$cdir' one can use './$cdir'.
  769. We can get $cdir when loading scripts. When loading source files
  770. $cdir must have already been expanded to the correct value. */
  771. if (strcmp (dir, "$cdir") == 0)
  772. continue;
  773. }
  774. /* Remove trailing slashes. */
  775. while (len > 0 && IS_DIR_SEPARATOR (filename[len - 1]))
  776. filename[--len] = 0;
  777. strcat (filename + len, SLASH_STRING);
  778. strcat (filename, string);
  779. if (is_regular_file (filename, &reg_file_errno))
  780. {
  781. fd = gdb_open_cloexec (filename, mode, 0).release ();
  782. if (fd >= 0)
  783. break;
  784. last_errno = errno;
  785. }
  786. else
  787. last_errno = reg_file_errno;
  788. }
  789. done:
  790. if (filename_opened)
  791. {
  792. /* If a file was opened, canonicalize its filename. */
  793. if (fd < 0)
  794. filename_opened->reset (NULL);
  795. else if ((opts & OPF_RETURN_REALPATH) != 0)
  796. *filename_opened = gdb_realpath (filename);
  797. else
  798. *filename_opened = gdb_abspath (filename);
  799. }
  800. errno = last_errno;
  801. return fd;
  802. }
  803. /* This is essentially a convenience, for clients that want the behaviour
  804. of openp, using source_path, but that really don't want the file to be
  805. opened but want instead just to know what the full pathname is (as
  806. qualified against source_path).
  807. The current working directory is searched first.
  808. If the file was found, this function returns 1, and FULL_PATHNAME is
  809. set to the fully-qualified pathname.
  810. Else, this functions returns 0, and FULL_PATHNAME is set to NULL. */
  811. int
  812. source_full_path_of (const char *filename,
  813. gdb::unique_xmalloc_ptr<char> *full_pathname)
  814. {
  815. int fd;
  816. fd = openp (source_path.c_str (),
  817. OPF_TRY_CWD_FIRST | OPF_SEARCH_IN_PATH | OPF_RETURN_REALPATH,
  818. filename, O_RDONLY, full_pathname);
  819. if (fd < 0)
  820. {
  821. full_pathname->reset (NULL);
  822. return 0;
  823. }
  824. close (fd);
  825. return 1;
  826. }
  827. /* Return non-zero if RULE matches PATH, that is if the rule can be
  828. applied to PATH. */
  829. static int
  830. substitute_path_rule_matches (const struct substitute_path_rule *rule,
  831. const char *path)
  832. {
  833. const int from_len = rule->from.length ();
  834. const int path_len = strlen (path);
  835. if (path_len < from_len)
  836. return 0;
  837. /* The substitution rules are anchored at the start of the path,
  838. so the path should start with rule->from. */
  839. if (filename_ncmp (path, rule->from.c_str (), from_len) != 0)
  840. return 0;
  841. /* Make sure that the region in the path that matches the substitution
  842. rule is immediately followed by a directory separator (or the end of
  843. string character). */
  844. if (path[from_len] != '\0' && !IS_DIR_SEPARATOR (path[from_len]))
  845. return 0;
  846. return 1;
  847. }
  848. /* Find the substitute-path rule that applies to PATH and return it.
  849. Return NULL if no rule applies. */
  850. static struct substitute_path_rule *
  851. get_substitute_path_rule (const char *path)
  852. {
  853. for (substitute_path_rule &rule : substitute_path_rules)
  854. if (substitute_path_rule_matches (&rule, path))
  855. return &rule;
  856. return nullptr;
  857. }
  858. /* If the user specified a source path substitution rule that applies
  859. to PATH, then apply it and return the new path.
  860. Return NULL if no substitution rule was specified by the user,
  861. or if no rule applied to the given PATH. */
  862. gdb::unique_xmalloc_ptr<char>
  863. rewrite_source_path (const char *path)
  864. {
  865. const struct substitute_path_rule *rule = get_substitute_path_rule (path);
  866. if (rule == nullptr)
  867. return nullptr;
  868. /* Compute the rewritten path and return it. */
  869. return (gdb::unique_xmalloc_ptr<char>
  870. (concat (rule->to.c_str (), path + rule->from.length (), nullptr)));
  871. }
  872. /* See source.h. */
  873. scoped_fd
  874. find_and_open_source (const char *filename,
  875. const char *dirname,
  876. gdb::unique_xmalloc_ptr<char> *fullname)
  877. {
  878. const char *path = source_path.c_str ();
  879. std::string expanded_path_holder;
  880. const char *p;
  881. /* If reading of source files is disabled then return a result indicating
  882. the attempt to read this source file failed. GDB will then display
  883. the filename and line number instead. */
  884. if (!source_open)
  885. return scoped_fd (-1);
  886. /* Quick way out if we already know its full name. */
  887. if (*fullname)
  888. {
  889. /* The user may have requested that source paths be rewritten
  890. according to substitution rules he provided. If a substitution
  891. rule applies to this path, then apply it. */
  892. gdb::unique_xmalloc_ptr<char> rewritten_fullname
  893. = rewrite_source_path (fullname->get ());
  894. if (rewritten_fullname != NULL)
  895. *fullname = std::move (rewritten_fullname);
  896. scoped_fd result = gdb_open_cloexec (fullname->get (), OPEN_MODE, 0);
  897. if (result.get () >= 0)
  898. {
  899. *fullname = gdb_realpath (fullname->get ());
  900. return result;
  901. }
  902. /* Didn't work -- free old one, try again. */
  903. fullname->reset (NULL);
  904. }
  905. gdb::unique_xmalloc_ptr<char> rewritten_dirname;
  906. if (dirname != NULL)
  907. {
  908. /* If necessary, rewrite the compilation directory name according
  909. to the source path substitution rules specified by the user. */
  910. rewritten_dirname = rewrite_source_path (dirname);
  911. if (rewritten_dirname != NULL)
  912. dirname = rewritten_dirname.get ();
  913. /* Replace a path entry of $cdir with the compilation directory
  914. name. */
  915. #define cdir_len 5
  916. p = strstr (source_path.c_str (), "$cdir");
  917. if (p && (p == path || p[-1] == DIRNAME_SEPARATOR)
  918. && (p[cdir_len] == DIRNAME_SEPARATOR || p[cdir_len] == '\0'))
  919. {
  920. int len = p - source_path.c_str ();
  921. /* Before $cdir */
  922. expanded_path_holder = source_path.substr (0, len);
  923. /* new stuff */
  924. expanded_path_holder += dirname;
  925. /* After $cdir */
  926. expanded_path_holder += source_path.c_str () + len + cdir_len;
  927. path = expanded_path_holder.c_str ();
  928. }
  929. }
  930. gdb::unique_xmalloc_ptr<char> rewritten_filename
  931. = rewrite_source_path (filename);
  932. if (rewritten_filename != NULL)
  933. filename = rewritten_filename.get ();
  934. /* Try to locate file using filename. */
  935. int result = openp (path, OPF_SEARCH_IN_PATH | OPF_RETURN_REALPATH, filename,
  936. OPEN_MODE, fullname);
  937. if (result < 0 && dirname != NULL)
  938. {
  939. /* Remove characters from the start of PATH that we don't need when
  940. PATH is appended to a directory name. */
  941. const char *filename_start = prepare_path_for_appending (filename);
  942. /* Try to locate file using compilation dir + filename. This is
  943. helpful if part of the compilation directory was removed,
  944. e.g. using gcc's -fdebug-prefix-map, and we have added the missing
  945. prefix to source_path. */
  946. std::string cdir_filename (dirname);
  947. /* Remove any trailing directory separators. */
  948. while (IS_DIR_SEPARATOR (cdir_filename.back ()))
  949. cdir_filename.pop_back ();
  950. /* Add our own directory separator. */
  951. cdir_filename.append (SLASH_STRING);
  952. cdir_filename.append (filename_start);
  953. result = openp (path, OPF_SEARCH_IN_PATH | OPF_RETURN_REALPATH,
  954. cdir_filename.c_str (), OPEN_MODE, fullname);
  955. }
  956. if (result < 0)
  957. {
  958. /* Didn't work. Try using just the basename. */
  959. p = lbasename (filename);
  960. if (p != filename)
  961. result = openp (path, OPF_SEARCH_IN_PATH | OPF_RETURN_REALPATH, p,
  962. OPEN_MODE, fullname);
  963. }
  964. return scoped_fd (result);
  965. }
  966. /* Open a source file given a symtab S. Returns a file descriptor or
  967. negative number for error.
  968. This function is a convenience function to find_and_open_source. */
  969. scoped_fd
  970. open_source_file (struct symtab *s)
  971. {
  972. if (!s)
  973. return scoped_fd (-1);
  974. gdb::unique_xmalloc_ptr<char> fullname (s->fullname);
  975. s->fullname = NULL;
  976. scoped_fd fd = find_and_open_source (s->filename, s->compunit ()->dirname (),
  977. &fullname);
  978. if (fd.get () < 0)
  979. {
  980. if (s->compunit () != nullptr)
  981. {
  982. const objfile *ofp = s->compunit ()->objfile ();
  983. std::string srcpath;
  984. if (IS_ABSOLUTE_PATH (s->filename))
  985. srcpath = s->filename;
  986. else if (s->compunit ()->dirname () != nullptr)
  987. {
  988. srcpath = s->compunit ()->dirname ();
  989. srcpath += SLASH_STRING;
  990. srcpath += s->filename;
  991. }
  992. const struct bfd_build_id *build_id = build_id_bfd_get (ofp->obfd);
  993. /* Query debuginfod for the source file. */
  994. if (build_id != nullptr && !srcpath.empty ())
  995. fd = debuginfod_source_query (build_id->data,
  996. build_id->size,
  997. srcpath.c_str (),
  998. &fullname);
  999. }
  1000. }
  1001. s->fullname = fullname.release ();
  1002. return fd;
  1003. }
  1004. /* See source.h. */
  1005. gdb::unique_xmalloc_ptr<char>
  1006. find_source_or_rewrite (const char *filename, const char *dirname)
  1007. {
  1008. gdb::unique_xmalloc_ptr<char> fullname;
  1009. scoped_fd fd = find_and_open_source (filename, dirname, &fullname);
  1010. if (fd.get () < 0)
  1011. {
  1012. /* rewrite_source_path would be applied by find_and_open_source, we
  1013. should report the pathname where GDB tried to find the file. */
  1014. if (dirname == nullptr || IS_ABSOLUTE_PATH (filename))
  1015. fullname.reset (xstrdup (filename));
  1016. else
  1017. fullname.reset (concat (dirname, SLASH_STRING,
  1018. filename, (char *) nullptr));
  1019. gdb::unique_xmalloc_ptr<char> rewritten
  1020. = rewrite_source_path (fullname.get ());
  1021. if (rewritten != nullptr)
  1022. fullname = std::move (rewritten);
  1023. }
  1024. return fullname;
  1025. }
  1026. /* Finds the fullname that a symtab represents.
  1027. This functions finds the fullname and saves it in s->fullname.
  1028. It will also return the value.
  1029. If this function fails to find the file that this symtab represents,
  1030. the expected fullname is used. Therefore the files does not have to
  1031. exist. */
  1032. const char *
  1033. symtab_to_fullname (struct symtab *s)
  1034. {
  1035. /* Use cached copy if we have it.
  1036. We rely on forget_cached_source_info being called appropriately
  1037. to handle cases like the file being moved. */
  1038. if (s->fullname == NULL)
  1039. {
  1040. scoped_fd fd = open_source_file (s);
  1041. if (fd.get () < 0)
  1042. {
  1043. gdb::unique_xmalloc_ptr<char> fullname;
  1044. /* rewrite_source_path would be applied by find_and_open_source, we
  1045. should report the pathname where GDB tried to find the file. */
  1046. if (s->compunit ()->dirname () == nullptr
  1047. || IS_ABSOLUTE_PATH (s->filename))
  1048. fullname.reset (xstrdup (s->filename));
  1049. else
  1050. fullname.reset (concat (s->compunit ()->dirname (), SLASH_STRING,
  1051. s->filename, (char *) NULL));
  1052. s->fullname = rewrite_source_path (fullname.get ()).release ();
  1053. if (s->fullname == NULL)
  1054. s->fullname = fullname.release ();
  1055. }
  1056. }
  1057. return s->fullname;
  1058. }
  1059. /* See commentary in source.h. */
  1060. const char *
  1061. symtab_to_filename_for_display (struct symtab *symtab)
  1062. {
  1063. if (filename_display_string == filename_display_basename)
  1064. return lbasename (symtab->filename);
  1065. else if (filename_display_string == filename_display_absolute)
  1066. return symtab_to_fullname (symtab);
  1067. else if (filename_display_string == filename_display_relative)
  1068. return symtab->filename;
  1069. else
  1070. internal_error (__FILE__, __LINE__, _("invalid filename_display_string"));
  1071. }
  1072. /* Print source lines from the file of symtab S,
  1073. starting with line number LINE and stopping before line number STOPLINE. */
  1074. static void
  1075. print_source_lines_base (struct symtab *s, int line, int stopline,
  1076. print_source_lines_flags flags)
  1077. {
  1078. bool noprint = false;
  1079. int nlines = stopline - line;
  1080. struct ui_out *uiout = current_uiout;
  1081. /* Regardless of whether we can open the file, set current_source_symtab. */
  1082. current_source_location *loc
  1083. = get_source_location (current_program_space);
  1084. loc->set (s, line);
  1085. first_line_listed = line;
  1086. last_line_listed = line;
  1087. /* If printing of source lines is disabled, just print file and line
  1088. number. */
  1089. if (uiout->test_flags (ui_source_list) && source_open)
  1090. {
  1091. /* Only prints "No such file or directory" once. */
  1092. if (s == last_source_visited)
  1093. {
  1094. if (last_source_error)
  1095. {
  1096. flags |= PRINT_SOURCE_LINES_NOERROR;
  1097. noprint = true;
  1098. }
  1099. }
  1100. else
  1101. {
  1102. last_source_visited = s;
  1103. scoped_fd desc = open_source_file (s);
  1104. last_source_error = desc.get () < 0;
  1105. if (last_source_error)
  1106. noprint = true;
  1107. }
  1108. }
  1109. else
  1110. {
  1111. flags |= PRINT_SOURCE_LINES_NOERROR;
  1112. noprint = true;
  1113. }
  1114. if (noprint)
  1115. {
  1116. if (!(flags & PRINT_SOURCE_LINES_NOERROR))
  1117. {
  1118. const char *filename = symtab_to_filename_for_display (s);
  1119. int len = strlen (filename) + 100;
  1120. char *name = (char *) alloca (len);
  1121. xsnprintf (name, len, "%d\t%s", line, filename);
  1122. print_sys_errmsg (name, errno);
  1123. }
  1124. else
  1125. {
  1126. uiout->field_signed ("line", line);
  1127. uiout->text ("\tin ");
  1128. /* CLI expects only the "file" field. TUI expects only the
  1129. "fullname" field (and TUI does break if "file" is printed).
  1130. MI expects both fields. ui_source_list is set only for CLI,
  1131. not for TUI. */
  1132. if (uiout->is_mi_like_p () || uiout->test_flags (ui_source_list))
  1133. uiout->field_string ("file", symtab_to_filename_for_display (s),
  1134. file_name_style.style ());
  1135. if (uiout->is_mi_like_p () || !uiout->test_flags (ui_source_list))
  1136. {
  1137. const char *s_fullname = symtab_to_fullname (s);
  1138. char *local_fullname;
  1139. /* ui_out_field_string may free S_FULLNAME by calling
  1140. open_source_file for it again. See e.g.,
  1141. tui_field_string->tui_show_source. */
  1142. local_fullname = (char *) alloca (strlen (s_fullname) + 1);
  1143. strcpy (local_fullname, s_fullname);
  1144. uiout->field_string ("fullname", local_fullname);
  1145. }
  1146. uiout->text ("\n");
  1147. }
  1148. return;
  1149. }
  1150. /* If the user requested a sequence of lines that seems to go backward
  1151. (from high to low line numbers) then we don't print anything. */
  1152. if (stopline <= line)
  1153. return;
  1154. std::string lines;
  1155. if (!g_source_cache.get_source_lines (s, line, stopline - 1, &lines))
  1156. {
  1157. const std::vector<off_t> *offsets = nullptr;
  1158. g_source_cache.get_line_charpos (s, &offsets);
  1159. error (_("Line number %d out of range; %s has %d lines."),
  1160. line, symtab_to_filename_for_display (s),
  1161. offsets == nullptr ? 0 : (int) offsets->size ());
  1162. }
  1163. const char *iter = lines.c_str ();
  1164. int new_lineno = loc->line ();
  1165. while (nlines-- > 0 && *iter != '\0')
  1166. {
  1167. char buf[20];
  1168. last_line_listed = loc->line ();
  1169. if (flags & PRINT_SOURCE_LINES_FILENAME)
  1170. {
  1171. uiout->text (symtab_to_filename_for_display (s));
  1172. uiout->text (":");
  1173. }
  1174. xsnprintf (buf, sizeof (buf), "%d\t", new_lineno++);
  1175. uiout->text (buf);
  1176. while (*iter != '\0')
  1177. {
  1178. /* Find a run of characters that can be emitted at once.
  1179. This is done so that escape sequences are kept
  1180. together. */
  1181. const char *start = iter;
  1182. while (true)
  1183. {
  1184. int skip_bytes;
  1185. char c = *iter;
  1186. if (c == '\033' && skip_ansi_escape (iter, &skip_bytes))
  1187. iter += skip_bytes;
  1188. else if (c >= 0 && c < 040 && c != '\t')
  1189. break;
  1190. else if (c == 0177)
  1191. break;
  1192. else
  1193. ++iter;
  1194. }
  1195. if (iter > start)
  1196. {
  1197. std::string text (start, iter);
  1198. uiout->text (text);
  1199. }
  1200. if (*iter == '\r')
  1201. {
  1202. /* Treat either \r or \r\n as a single newline. */
  1203. ++iter;
  1204. if (*iter == '\n')
  1205. ++iter;
  1206. break;
  1207. }
  1208. else if (*iter == '\n')
  1209. {
  1210. ++iter;
  1211. break;
  1212. }
  1213. else if (*iter > 0 && *iter < 040)
  1214. {
  1215. xsnprintf (buf, sizeof (buf), "^%c", *iter + 0100);
  1216. uiout->text (buf);
  1217. ++iter;
  1218. }
  1219. else if (*iter == 0177)
  1220. {
  1221. uiout->text ("^?");
  1222. ++iter;
  1223. }
  1224. }
  1225. uiout->text ("\n");
  1226. }
  1227. loc->set (loc->symtab (), new_lineno);
  1228. }
  1229. /* See source.h. */
  1230. void
  1231. print_source_lines (struct symtab *s, int line, int stopline,
  1232. print_source_lines_flags flags)
  1233. {
  1234. print_source_lines_base (s, line, stopline, flags);
  1235. }
  1236. /* See source.h. */
  1237. void
  1238. print_source_lines (struct symtab *s, source_lines_range line_range,
  1239. print_source_lines_flags flags)
  1240. {
  1241. print_source_lines_base (s, line_range.startline (),
  1242. line_range.stopline (), flags);
  1243. }
  1244. /* Print info on range of pc's in a specified line. */
  1245. static void
  1246. info_line_command (const char *arg, int from_tty)
  1247. {
  1248. CORE_ADDR start_pc, end_pc;
  1249. std::vector<symtab_and_line> decoded_sals;
  1250. symtab_and_line curr_sal;
  1251. gdb::array_view<symtab_and_line> sals;
  1252. if (arg == 0)
  1253. {
  1254. current_source_location *loc
  1255. = get_source_location (current_program_space);
  1256. curr_sal.symtab = loc->symtab ();
  1257. curr_sal.pspace = current_program_space;
  1258. if (last_line_listed != 0)
  1259. curr_sal.line = last_line_listed;
  1260. else
  1261. curr_sal.line = loc->line ();
  1262. sals = curr_sal;
  1263. }
  1264. else
  1265. {
  1266. decoded_sals = decode_line_with_last_displayed (arg,
  1267. DECODE_LINE_LIST_MODE);
  1268. sals = decoded_sals;
  1269. dont_repeat ();
  1270. }
  1271. /* C++ More than one line may have been specified, as when the user
  1272. specifies an overloaded function name. Print info on them all. */
  1273. for (const auto &sal : sals)
  1274. {
  1275. if (sal.pspace != current_program_space)
  1276. continue;
  1277. if (sal.symtab == 0)
  1278. {
  1279. struct gdbarch *gdbarch = get_current_arch ();
  1280. gdb_printf (_("No line number information available"));
  1281. if (sal.pc != 0)
  1282. {
  1283. /* This is useful for "info line *0x7f34". If we can't tell the
  1284. user about a source line, at least let them have the symbolic
  1285. address. */
  1286. gdb_printf (" for address ");
  1287. gdb_stdout->wrap_here (2);
  1288. print_address (gdbarch, sal.pc, gdb_stdout);
  1289. }
  1290. else
  1291. gdb_printf (".");
  1292. gdb_printf ("\n");
  1293. }
  1294. else if (sal.line > 0
  1295. && find_line_pc_range (sal, &start_pc, &end_pc))
  1296. {
  1297. gdbarch *gdbarch = sal.symtab->compunit ()->objfile ()->arch ();
  1298. if (start_pc == end_pc)
  1299. {
  1300. gdb_printf ("Line %d of \"%s\"",
  1301. sal.line,
  1302. symtab_to_filename_for_display (sal.symtab));
  1303. gdb_stdout->wrap_here (2);
  1304. gdb_printf (" is at address ");
  1305. print_address (gdbarch, start_pc, gdb_stdout);
  1306. gdb_stdout->wrap_here (2);
  1307. gdb_printf (" but contains no code.\n");
  1308. }
  1309. else
  1310. {
  1311. gdb_printf ("Line %d of \"%s\"",
  1312. sal.line,
  1313. symtab_to_filename_for_display (sal.symtab));
  1314. gdb_stdout->wrap_here (2);
  1315. gdb_printf (" starts at address ");
  1316. print_address (gdbarch, start_pc, gdb_stdout);
  1317. gdb_stdout->wrap_here (2);
  1318. gdb_printf (" and ends at ");
  1319. print_address (gdbarch, end_pc, gdb_stdout);
  1320. gdb_printf (".\n");
  1321. }
  1322. /* x/i should display this line's code. */
  1323. set_next_address (gdbarch, start_pc);
  1324. /* Repeating "info line" should do the following line. */
  1325. last_line_listed = sal.line + 1;
  1326. /* If this is the only line, show the source code. If it could
  1327. not find the file, don't do anything special. */
  1328. if (annotation_level > 0 && sals.size () == 1)
  1329. annotate_source_line (sal.symtab, sal.line, 0, start_pc);
  1330. }
  1331. else
  1332. /* Is there any case in which we get here, and have an address
  1333. which the user would want to see? If we have debugging symbols
  1334. and no line numbers? */
  1335. gdb_printf (_("Line number %d is out of range for \"%s\".\n"),
  1336. sal.line, symtab_to_filename_for_display (sal.symtab));
  1337. }
  1338. }
  1339. /* Commands to search the source file for a regexp. */
  1340. /* Helper for forward_search_command/reverse_search_command. FORWARD
  1341. indicates direction: true for forward, false for
  1342. backward/reverse. */
  1343. static void
  1344. search_command_helper (const char *regex, int from_tty, bool forward)
  1345. {
  1346. const char *msg = re_comp (regex);
  1347. if (msg)
  1348. error (("%s"), msg);
  1349. current_source_location *loc
  1350. = get_source_location (current_program_space);
  1351. if (loc->symtab () == nullptr)
  1352. select_source_symtab (0);
  1353. if (!source_open)
  1354. error (_("source code access disabled"));
  1355. scoped_fd desc (open_source_file (loc->symtab ()));
  1356. if (desc.get () < 0)
  1357. perror_with_name (symtab_to_filename_for_display (loc->symtab ()));
  1358. int line = (forward
  1359. ? last_line_listed + 1
  1360. : last_line_listed - 1);
  1361. const std::vector<off_t> *offsets;
  1362. if (line < 1
  1363. || !g_source_cache.get_line_charpos (loc->symtab (), &offsets)
  1364. || line > offsets->size ())
  1365. error (_("Expression not found"));
  1366. if (lseek (desc.get (), (*offsets)[line - 1], 0) < 0)
  1367. perror_with_name (symtab_to_filename_for_display (loc->symtab ()));
  1368. gdb_file_up stream = desc.to_file (FDOPEN_MODE);
  1369. clearerr (stream.get ());
  1370. gdb::def_vector<char> buf;
  1371. buf.reserve (256);
  1372. while (1)
  1373. {
  1374. buf.resize (0);
  1375. int c = fgetc (stream.get ());
  1376. if (c == EOF)
  1377. break;
  1378. do
  1379. {
  1380. buf.push_back (c);
  1381. }
  1382. while (c != '\n' && (c = fgetc (stream.get ())) >= 0);
  1383. /* Remove the \r, if any, at the end of the line, otherwise
  1384. regular expressions that end with $ or \n won't work. */
  1385. size_t sz = buf.size ();
  1386. if (sz >= 2 && buf[sz - 2] == '\r')
  1387. {
  1388. buf[sz - 2] = '\n';
  1389. buf.resize (sz - 1);
  1390. }
  1391. /* We now have a source line in buf, null terminate and match. */
  1392. buf.push_back ('\0');
  1393. if (re_exec (buf.data ()) > 0)
  1394. {
  1395. /* Match! */
  1396. print_source_lines (loc->symtab (), line, line + 1, 0);
  1397. set_internalvar_integer (lookup_internalvar ("_"), line);
  1398. loc->set (loc->symtab (), std::max (line - lines_to_list / 2, 1));
  1399. return;
  1400. }
  1401. if (forward)
  1402. line++;
  1403. else
  1404. {
  1405. line--;
  1406. if (line < 1)
  1407. break;
  1408. if (fseek (stream.get (), (*offsets)[line - 1], 0) < 0)
  1409. {
  1410. const char *filename
  1411. = symtab_to_filename_for_display (loc->symtab ());
  1412. perror_with_name (filename);
  1413. }
  1414. }
  1415. }
  1416. gdb_printf (_("Expression not found\n"));
  1417. }
  1418. static void
  1419. forward_search_command (const char *regex, int from_tty)
  1420. {
  1421. search_command_helper (regex, from_tty, true);
  1422. }
  1423. static void
  1424. reverse_search_command (const char *regex, int from_tty)
  1425. {
  1426. search_command_helper (regex, from_tty, false);
  1427. }
  1428. /* If the last character of PATH is a directory separator, then strip it. */
  1429. static void
  1430. strip_trailing_directory_separator (char *path)
  1431. {
  1432. const int last = strlen (path) - 1;
  1433. if (last < 0)
  1434. return; /* No stripping is needed if PATH is the empty string. */
  1435. if (IS_DIR_SEPARATOR (path[last]))
  1436. path[last] = '\0';
  1437. }
  1438. /* Add a new substitute-path rule at the end of the current list of rules.
  1439. The new rule will replace FROM into TO. */
  1440. void
  1441. add_substitute_path_rule (const char *from, const char *to)
  1442. {
  1443. substitute_path_rules.emplace_back (from, to);
  1444. }
  1445. /* Implement the "show substitute-path" command. */
  1446. static void
  1447. show_substitute_path_command (const char *args, int from_tty)
  1448. {
  1449. char *from = NULL;
  1450. gdb_argv argv (args);
  1451. /* We expect zero or one argument. */
  1452. if (argv != NULL && argv[0] != NULL && argv[1] != NULL)
  1453. error (_("Too many arguments in command"));
  1454. if (argv != NULL && argv[0] != NULL)
  1455. from = argv[0];
  1456. /* Print the substitution rules. */
  1457. if (from != NULL)
  1458. gdb_printf
  1459. (_("Source path substitution rule matching `%s':\n"), from);
  1460. else
  1461. gdb_printf (_("List of all source path substitution rules:\n"));
  1462. for (substitute_path_rule &rule : substitute_path_rules)
  1463. {
  1464. if (from == NULL || substitute_path_rule_matches (&rule, from) != 0)
  1465. gdb_printf (" `%s' -> `%s'.\n", rule.from.c_str (),
  1466. rule.to.c_str ());
  1467. }
  1468. }
  1469. /* Implement the "unset substitute-path" command. */
  1470. static void
  1471. unset_substitute_path_command (const char *args, int from_tty)
  1472. {
  1473. gdb_argv argv (args);
  1474. char *from = NULL;
  1475. /* This function takes either 0 or 1 argument. */
  1476. if (argv != NULL && argv[0] != NULL && argv[1] != NULL)
  1477. error (_("Incorrect usage, too many arguments in command"));
  1478. if (argv != NULL && argv[0] != NULL)
  1479. from = argv[0];
  1480. /* If the user asked for all the rules to be deleted, ask him
  1481. to confirm and give him a chance to abort before the action
  1482. is performed. */
  1483. if (from == NULL
  1484. && !query (_("Delete all source path substitution rules? ")))
  1485. error (_("Canceled"));
  1486. /* Delete the rule matching the argument. No argument means that
  1487. all rules should be deleted. */
  1488. if (from == nullptr)
  1489. substitute_path_rules.clear ();
  1490. else
  1491. {
  1492. auto iter
  1493. = std::remove_if (substitute_path_rules.begin (),
  1494. substitute_path_rules.end (),
  1495. [&] (const substitute_path_rule &rule)
  1496. {
  1497. return FILENAME_CMP (from,
  1498. rule.from.c_str ()) == 0;
  1499. });
  1500. bool rule_found = iter != substitute_path_rules.end ();
  1501. substitute_path_rules.erase (iter, substitute_path_rules.end ());
  1502. /* If the user asked for a specific rule to be deleted but
  1503. we could not find it, then report an error. */
  1504. if (!rule_found)
  1505. error (_("No substitution rule defined for `%s'"), from);
  1506. }
  1507. forget_cached_source_info ();
  1508. }
  1509. /* Add a new source path substitution rule. */
  1510. static void
  1511. set_substitute_path_command (const char *args, int from_tty)
  1512. {
  1513. gdb_argv argv (args);
  1514. if (argv == NULL || argv[0] == NULL || argv [1] == NULL)
  1515. error (_("Incorrect usage, too few arguments in command"));
  1516. if (argv[2] != NULL)
  1517. error (_("Incorrect usage, too many arguments in command"));
  1518. if (*(argv[0]) == '\0')
  1519. error (_("First argument must be at least one character long"));
  1520. /* Strip any trailing directory separator character in either FROM
  1521. or TO. The substitution rule already implicitly contains them. */
  1522. strip_trailing_directory_separator (argv[0]);
  1523. strip_trailing_directory_separator (argv[1]);
  1524. /* If a rule with the same "from" was previously defined, then
  1525. delete it. This new rule replaces it. */
  1526. auto iter
  1527. = std::remove_if (substitute_path_rules.begin (),
  1528. substitute_path_rules.end (),
  1529. [&] (const substitute_path_rule &rule)
  1530. {
  1531. return FILENAME_CMP (argv[0], rule.from.c_str ()) == 0;
  1532. });
  1533. substitute_path_rules.erase (iter, substitute_path_rules.end ());
  1534. /* Insert the new substitution rule. */
  1535. add_substitute_path_rule (argv[0], argv[1]);
  1536. forget_cached_source_info ();
  1537. }
  1538. /* See source.h. */
  1539. source_lines_range::source_lines_range (int startline,
  1540. source_lines_range::direction dir)
  1541. {
  1542. if (dir == source_lines_range::FORWARD)
  1543. {
  1544. LONGEST end = static_cast <LONGEST> (startline) + get_lines_to_list ();
  1545. if (end > INT_MAX)
  1546. end = INT_MAX;
  1547. m_startline = startline;
  1548. m_stopline = static_cast <int> (end);
  1549. }
  1550. else
  1551. {
  1552. LONGEST start = static_cast <LONGEST> (startline) - get_lines_to_list ();
  1553. if (start < 1)
  1554. start = 1;
  1555. m_startline = static_cast <int> (start);
  1556. m_stopline = startline;
  1557. }
  1558. }
  1559. /* Handle the "set source" base command. */
  1560. static void
  1561. set_source (const char *arg, int from_tty)
  1562. {
  1563. help_list (setsourcelist, "set source ", all_commands, gdb_stdout);
  1564. }
  1565. /* Handle the "show source" base command. */
  1566. static void
  1567. show_source (const char *args, int from_tty)
  1568. {
  1569. help_list (showsourcelist, "show source ", all_commands, gdb_stdout);
  1570. }
  1571. void _initialize_source ();
  1572. void
  1573. _initialize_source ()
  1574. {
  1575. init_source_path ();
  1576. /* The intention is to use POSIX Basic Regular Expressions.
  1577. Always use the GNU regex routine for consistency across all hosts.
  1578. Our current GNU regex.c does not have all the POSIX features, so this is
  1579. just an approximation. */
  1580. re_set_syntax (RE_SYNTAX_GREP);
  1581. cmd_list_element *directory_cmd
  1582. = add_cmd ("directory", class_files, directory_command, _("\
  1583. Add directory DIR to beginning of search path for source files.\n\
  1584. Forget cached info on source file locations and line positions.\n\
  1585. DIR can also be $cwd for the current working directory, or $cdir for the\n\
  1586. directory in which the source file was compiled into object code.\n\
  1587. With no argument, reset the search path to $cdir:$cwd, the default."),
  1588. &cmdlist);
  1589. set_cmd_completer (directory_cmd, filename_completer);
  1590. add_setshow_optional_filename_cmd ("directories",
  1591. class_files,
  1592. &source_path,
  1593. _("\
  1594. Set the search path for finding source files."),
  1595. _("\
  1596. Show the search path for finding source files."),
  1597. _("\
  1598. $cwd in the path means the current working directory.\n\
  1599. $cdir in the path means the compilation directory of the source file.\n\
  1600. GDB ensures the search path always ends with $cdir:$cwd by\n\
  1601. appending these directories if necessary.\n\
  1602. Setting the value to an empty string sets it to $cdir:$cwd, the default."),
  1603. set_directories_command,
  1604. show_directories_command,
  1605. &setlist, &showlist);
  1606. add_info ("source", info_source_command,
  1607. _("Information about the current source file."));
  1608. add_info ("line", info_line_command, _("\
  1609. Core addresses of the code for a source line.\n\
  1610. Line can be specified as\n\
  1611. LINENUM, to list around that line in current file,\n\
  1612. FILE:LINENUM, to list around that line in that file,\n\
  1613. FUNCTION, to list around beginning of that function,\n\
  1614. FILE:FUNCTION, to distinguish among like-named static functions.\n\
  1615. Default is to describe the last source line that was listed.\n\n\
  1616. This sets the default address for \"x\" to the line's first instruction\n\
  1617. so that \"x/i\" suffices to start examining the machine code.\n\
  1618. The address is also stored as the value of \"$_\"."));
  1619. cmd_list_element *forward_search_cmd
  1620. = add_com ("forward-search", class_files, forward_search_command, _("\
  1621. Search for regular expression (see regex(3)) from last line listed.\n\
  1622. The matching line number is also stored as the value of \"$_\"."));
  1623. add_com_alias ("search", forward_search_cmd, class_files, 0);
  1624. add_com_alias ("fo", forward_search_cmd, class_files, 1);
  1625. cmd_list_element *reverse_search_cmd
  1626. = add_com ("reverse-search", class_files, reverse_search_command, _("\
  1627. Search backward for regular expression (see regex(3)) from last line listed.\n\
  1628. The matching line number is also stored as the value of \"$_\"."));
  1629. add_com_alias ("rev", reverse_search_cmd, class_files, 1);
  1630. add_setshow_integer_cmd ("listsize", class_support, &lines_to_list, _("\
  1631. Set number of source lines gdb will list by default."), _("\
  1632. Show number of source lines gdb will list by default."), _("\
  1633. Use this to choose how many source lines the \"list\" displays (unless\n\
  1634. the \"list\" argument explicitly specifies some other number).\n\
  1635. A value of \"unlimited\", or zero, means there's no limit."),
  1636. NULL,
  1637. show_lines_to_list,
  1638. &setlist, &showlist);
  1639. add_cmd ("substitute-path", class_files, set_substitute_path_command,
  1640. _("\
  1641. Add a substitution rule to rewrite the source directories.\n\
  1642. Usage: set substitute-path FROM TO\n\
  1643. The rule is applied only if the directory name starts with FROM\n\
  1644. directly followed by a directory separator.\n\
  1645. If a substitution rule was previously set for FROM, the old rule\n\
  1646. is replaced by the new one."),
  1647. &setlist);
  1648. add_cmd ("substitute-path", class_files, unset_substitute_path_command,
  1649. _("\
  1650. Delete one or all substitution rules rewriting the source directories.\n\
  1651. Usage: unset substitute-path [FROM]\n\
  1652. Delete the rule for substituting FROM in source directories. If FROM\n\
  1653. is not specified, all substituting rules are deleted.\n\
  1654. If the debugger cannot find a rule for FROM, it will display a warning."),
  1655. &unsetlist);
  1656. add_cmd ("substitute-path", class_files, show_substitute_path_command,
  1657. _("\
  1658. Show one or all substitution rules rewriting the source directories.\n\
  1659. Usage: show substitute-path [FROM]\n\
  1660. Print the rule for substituting FROM in source directories. If FROM\n\
  1661. is not specified, print all substitution rules."),
  1662. &showlist);
  1663. add_setshow_enum_cmd ("filename-display", class_files,
  1664. filename_display_kind_names,
  1665. &filename_display_string, _("\
  1666. Set how to display filenames."), _("\
  1667. Show how to display filenames."), _("\
  1668. filename-display can be:\n\
  1669. basename - display only basename of a filename\n\
  1670. relative - display a filename relative to the compilation directory\n\
  1671. absolute - display an absolute filename\n\
  1672. By default, relative filenames are displayed."),
  1673. NULL,
  1674. show_filename_display_string,
  1675. &setlist, &showlist);
  1676. add_prefix_cmd ("source", no_class, set_source,
  1677. _("Generic command for setting how sources are handled."),
  1678. &setsourcelist, 0, &setlist);
  1679. add_prefix_cmd ("source", no_class, show_source,
  1680. _("Generic command for showing source settings."),
  1681. &showsourcelist, 0, &showlist);
  1682. add_setshow_boolean_cmd ("open", class_files, &source_open, _("\
  1683. Set whether GDB should open source files."), _("\
  1684. Show whether GDB should open source files."), _("\
  1685. When this option is on GDB will open source files and display the\n\
  1686. contents when appropriate, for example, when GDB stops, or the list\n\
  1687. command is used.\n\
  1688. When this option is off GDB will not try to open source files, instead\n\
  1689. GDB will print the file and line number that would have been displayed.\n\
  1690. This can be useful if access to source code files is slow, for example\n\
  1691. due to the source being located over a slow network connection."),
  1692. NULL,
  1693. show_source_open,
  1694. &setsourcelist, &showsourcelist);
  1695. }