1 /* GDB routines for supporting auto-loaded scripts.
2 
3    Copyright (C) 2012-2024 Free Software Foundation, Inc.
4 
5    This file is part of GDB.
6 
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11 
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16 
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19 
20 #include <ctype.h>
21 #include "auto-load.h"
22 #include "progspace.h"
23 #include "gdbsupport/gdb_regex.h"
24 #include "ui-out.h"
25 #include "filenames.h"
26 #include "command.h"
27 #include "observable.h"
28 #include "objfiles.h"
29 #include "cli/cli-script.h"
30 #include "cli/cli-cmds.h"
31 #include "cli/cli-decode.h"
32 #include "cli/cli-setshow.h"
33 #include "readline/tilde.h"
34 #include "completer.h"
35 #include "fnmatch.h"
36 #include "top.h"
37 #include "gdbsupport/filestuff.h"
38 #include "extension.h"
39 #include "gdb/section-scripts.h"
40 #include <algorithm>
41 #include "gdbsupport/pathstuff.h"
42 #include "cli/cli-style.h"
43 
44 /* The section to look in for auto-loaded scripts (in file formats that
45    support sections).
46    Each entry in this section is a record that begins with a leading byte
47    identifying the record type.
48    At the moment we only support one record type: A leading byte of 1,
49    followed by the path of a python script to load.  */
50 #define AUTO_SECTION_NAME ".debug_gdb_scripts"
51 
52 /* The section to look in for the name of a separate debug file.  */
53 #define DEBUGLINK_SECTION_NAME ".gnu_debuglink"
54 
55 static void maybe_print_unsupported_script_warning
56   (struct auto_load_pspace_info *, struct objfile *objfile,
57    const struct extension_language_defn *language,
58    const char *section_name, unsigned offset);
59 
60 static void maybe_print_script_not_found_warning
61   (struct auto_load_pspace_info *, struct objfile *objfile,
62    const struct extension_language_defn *language,
63    const char *section_name, unsigned offset);
64 
65 /* See auto-load.h.  */
66 
67 bool debug_auto_load = false;
68 
69 /* "show" command for the debug_auto_load configuration variable.  */
70 
71 static void
show_debug_auto_load(struct ui_file * file,int from_tty,struct cmd_list_element * c,const char * value)72 show_debug_auto_load (struct ui_file *file, int from_tty,
73                           struct cmd_list_element *c, const char *value)
74 {
75   gdb_printf (file, _("Debugging output for files "
76                           "of 'set auto-load ...' is %s.\n"),
77                 value);
78 }
79 
80 /* User-settable option to enable/disable auto-loading of GDB_AUTO_FILE_NAME
81    scripts:
82    set auto-load gdb-scripts on|off
83    This is true if we should auto-load associated scripts when an objfile
84    is opened, false otherwise.  */
85 static bool auto_load_gdb_scripts = true;
86 
87 /* "show" command for the auto_load_gdb_scripts configuration variable.  */
88 
89 static void
show_auto_load_gdb_scripts(struct ui_file * file,int from_tty,struct cmd_list_element * c,const char * value)90 show_auto_load_gdb_scripts (struct ui_file *file, int from_tty,
91                                   struct cmd_list_element *c, const char *value)
92 {
93   gdb_printf (file, _("Auto-loading of canned sequences of commands "
94                           "scripts is %s.\n"),
95                 value);
96 }
97 
98 /* See auto-load.h.  */
99 
100 bool
auto_load_gdb_scripts_enabled(const struct extension_language_defn * extlang)101 auto_load_gdb_scripts_enabled (const struct extension_language_defn *extlang)
102 {
103   return auto_load_gdb_scripts;
104 }
105 
106 /* Internal-use flag to enable/disable auto-loading.
107    This is true if we should auto-load python code when an objfile is opened,
108    false otherwise.
109 
110    Both auto_load_scripts && global_auto_load must be true to enable
111    auto-loading.
112 
113    This flag exists to facilitate deferring auto-loading during start-up
114    until after ./.gdbinit has been read; it may augment the search directories
115    used to find the scripts.  */
116 bool global_auto_load = true;
117 
118 /* Auto-load .gdbinit file from the current directory?  */
119 bool auto_load_local_gdbinit = true;
120 
121 /* Absolute pathname to the current directory .gdbinit, if it exists.  */
122 char *auto_load_local_gdbinit_pathname = NULL;
123 
124 /* if AUTO_LOAD_LOCAL_GDBINIT_PATHNAME has been loaded.  */
125 bool auto_load_local_gdbinit_loaded = false;
126 
127 /* "show" command for the auto_load_local_gdbinit configuration variable.  */
128 
129 static void
show_auto_load_local_gdbinit(struct ui_file * file,int from_tty,struct cmd_list_element * c,const char * value)130 show_auto_load_local_gdbinit (struct ui_file *file, int from_tty,
131                                     struct cmd_list_element *c, const char *value)
132 {
133   gdb_printf (file, _("Auto-loading of .gdbinit script from current "
134                           "directory is %s.\n"),
135                 value);
136 }
137 
138 /* Directory list from which to load auto-loaded scripts.  It is not checked
139    for absolute paths but they are strongly recommended.  It is initialized by
140    _initialize_auto_load.  */
141 static std::string auto_load_dir = AUTO_LOAD_DIR;
142 
143 /* "set" command for the auto_load_dir configuration variable.  */
144 
145 static void
set_auto_load_dir(const char * args,int from_tty,struct cmd_list_element * c)146 set_auto_load_dir (const char *args, int from_tty, struct cmd_list_element *c)
147 {
148   /* Setting the variable to "" resets it to the compile time defaults.  */
149   if (auto_load_dir.empty ())
150     auto_load_dir = AUTO_LOAD_DIR;
151 }
152 
153 /* "show" command for the auto_load_dir configuration variable.  */
154 
155 static void
show_auto_load_dir(struct ui_file * file,int from_tty,struct cmd_list_element * c,const char * value)156 show_auto_load_dir (struct ui_file *file, int from_tty,
157                         struct cmd_list_element *c, const char *value)
158 {
159   gdb_printf (file, _("List of directories from which to load "
160                           "auto-loaded scripts is %s.\n"),
161                 value);
162 }
163 
164 /* Directory list safe to hold auto-loaded files.  It is not checked for
165    absolute paths but they are strongly recommended.  It is initialized by
166    _initialize_auto_load.  */
167 static std::string auto_load_safe_path = AUTO_LOAD_SAFE_PATH;
168 
169 /* Vector of directory elements of AUTO_LOAD_SAFE_PATH with each one normalized
170    by tilde_expand and possibly each entries has added its gdb_realpath
171    counterpart.  */
172 static std::vector<gdb::unique_xmalloc_ptr<char>> auto_load_safe_path_vec;
173 
174 /* Expand $datadir and $debugdir in STRING according to the rules of
175    substitute_path_component.  */
176 
177 static std::vector<gdb::unique_xmalloc_ptr<char>>
auto_load_expand_dir_vars(const char * string)178 auto_load_expand_dir_vars (const char *string)
179 {
180   char *s = xstrdup (string);
181   substitute_path_component (&s, "$datadir", gdb_datadir.c_str ());
182   substitute_path_component (&s, "$debugdir", debug_file_directory.c_str ());
183 
184   if (debug_auto_load && strcmp (s, string) != 0)
185     auto_load_debug_printf ("Expanded $-variables to \"%s\".", s);
186 
187   std::vector<gdb::unique_xmalloc_ptr<char>> dir_vec
188     = dirnames_to_char_ptr_vec (s);
189   xfree(s);
190 
191   return dir_vec;
192 }
193 
194 /* Update auto_load_safe_path_vec from current AUTO_LOAD_SAFE_PATH.  */
195 
196 static void
auto_load_safe_path_vec_update(void)197 auto_load_safe_path_vec_update (void)
198 {
199   auto_load_debug_printf ("Updating directories of \"%s\".",
200                                 auto_load_safe_path.c_str ());
201 
202   auto_load_safe_path_vec
203     = auto_load_expand_dir_vars (auto_load_safe_path.c_str ());
204   size_t len = auto_load_safe_path_vec.size ();
205 
206   /* Apply tilde_expand and gdb_realpath to each AUTO_LOAD_SAFE_PATH_VEC
207      element.  */
208   for (size_t i = 0; i < len; i++)
209     {
210       gdb::unique_xmalloc_ptr<char> &in_vec = auto_load_safe_path_vec[i];
211       gdb::unique_xmalloc_ptr<char> expanded (tilde_expand (in_vec.get ()));
212       gdb::unique_xmalloc_ptr<char> real_path = gdb_realpath (expanded.get ());
213 
214       /* Ensure the current entry is at least tilde_expand-ed.  ORIGINAL makes
215            sure we free the original string.  */
216       gdb::unique_xmalloc_ptr<char> original = std::move (in_vec);
217       in_vec = std::move (expanded);
218 
219       if (debug_auto_load)
220           {
221             if (strcmp (in_vec.get (), original.get ()) == 0)
222               auto_load_debug_printf ("Using directory \"%s\".",
223                                             in_vec.get ());
224             else
225               auto_load_debug_printf ("Resolved directory \"%s\" as \"%s\".",
226                                             original.get (), in_vec.get ());
227           }
228 
229       /* If gdb_realpath returns a different content, append it.  */
230       if (strcmp (real_path.get (), in_vec.get ()) != 0)
231           {
232             auto_load_debug_printf ("And canonicalized as \"%s\".",
233                                           real_path.get ());
234 
235             auto_load_safe_path_vec.push_back (std::move (real_path));
236           }
237     }
238 }
239 
240 /* Variable gdb_datadir has been set.  Update content depending on $datadir.  */
241 
242 static void
auto_load_gdb_datadir_changed(void)243 auto_load_gdb_datadir_changed (void)
244 {
245   auto_load_safe_path_vec_update ();
246 }
247 
248 /* "set" command for the auto_load_safe_path configuration variable.  */
249 
250 static void
set_auto_load_safe_path(const char * args,int from_tty,struct cmd_list_element * c)251 set_auto_load_safe_path (const char *args,
252                                int from_tty, struct cmd_list_element *c)
253 {
254   /* Setting the variable to "" resets it to the compile time defaults.  */
255   if (auto_load_safe_path.empty ())
256     auto_load_safe_path = AUTO_LOAD_SAFE_PATH;
257 
258   auto_load_safe_path_vec_update ();
259 }
260 
261 /* "show" command for the auto_load_safe_path configuration variable.  */
262 
263 static void
show_auto_load_safe_path(struct ui_file * file,int from_tty,struct cmd_list_element * c,const char * value)264 show_auto_load_safe_path (struct ui_file *file, int from_tty,
265                                 struct cmd_list_element *c, const char *value)
266 {
267   const char *cs;
268 
269   /* Check if user has entered either "/" or for example ":".
270      But while more complicate content like ":/foo" would still also
271      permit any location do not hide those.  */
272 
273   for (cs = value; *cs && (*cs == DIRNAME_SEPARATOR || IS_DIR_SEPARATOR (*cs));
274        cs++);
275   if (*cs == 0)
276     gdb_printf (file, _("Auto-load files are safe to load from any "
277                               "directory.\n"));
278   else
279     gdb_printf (file, _("List of directories from which it is safe to "
280                               "auto-load files is %s.\n"),
281                     value);
282 }
283 
284 /* "add-auto-load-safe-path" command for the auto_load_safe_path configuration
285    variable.  */
286 
287 static void
add_auto_load_safe_path(const char * args,int from_tty)288 add_auto_load_safe_path (const char *args, int from_tty)
289 {
290   if (args == NULL || *args == 0)
291     error (_("\
292 Directory argument required.\n\
293 Use 'set auto-load safe-path /' for disabling the auto-load safe-path security.\
294 "));
295 
296   auto_load_safe_path = string_printf ("%s%c%s", auto_load_safe_path.c_str (),
297                                                DIRNAME_SEPARATOR, args);
298 
299   auto_load_safe_path_vec_update ();
300 }
301 
302 /* "add-auto-load-scripts-directory" command for the auto_load_dir configuration
303    variable.  */
304 
305 static void
add_auto_load_dir(const char * args,int from_tty)306 add_auto_load_dir (const char *args, int from_tty)
307 {
308   if (args == NULL || *args == 0)
309     error (_("Directory argument required."));
310 
311   auto_load_dir = string_printf ("%s%c%s", auto_load_dir.c_str (),
312                                          DIRNAME_SEPARATOR, args);
313 }
314 
315 /* Implementation for filename_is_in_pattern overwriting the caller's FILENAME
316    and PATTERN.  */
317 
318 static int
filename_is_in_pattern_1(char * filename,char * pattern)319 filename_is_in_pattern_1 (char *filename, char *pattern)
320 {
321   size_t pattern_len = strlen (pattern);
322   size_t filename_len = strlen (filename);
323 
324   auto_load_debug_printf ("Matching file \"%s\" to pattern \"%s\"",
325                                 filename, pattern);
326 
327   /* Trim trailing slashes ("/") from PATTERN.  Even for "d:\" paths as
328      trailing slashes are trimmed also from FILENAME it still matches
329      correctly.  */
330   while (pattern_len && IS_DIR_SEPARATOR (pattern[pattern_len - 1]))
331     pattern_len--;
332   pattern[pattern_len] = '\0';
333 
334   /* Ensure auto_load_safe_path "/" matches any FILENAME.  On MS-Windows
335      platform FILENAME even after gdb_realpath does not have to start with
336      IS_DIR_SEPARATOR character, such as the 'C:\x.exe' filename.  */
337   if (pattern_len == 0)
338     {
339       auto_load_debug_printf ("Matched - empty pattern");
340       return 1;
341     }
342 
343   for (;;)
344     {
345       /* Trim trailing slashes ("/").  PATTERN also has slashes trimmed the
346            same way so they will match.  */
347       while (filename_len && IS_DIR_SEPARATOR (filename[filename_len - 1]))
348           filename_len--;
349       filename[filename_len] = '\0';
350       if (filename_len == 0)
351           {
352             auto_load_debug_printf ("Not matched - pattern \"%s\".", pattern);
353             return 0;
354           }
355 
356       if (gdb_filename_fnmatch (pattern, filename, FNM_FILE_NAME | FNM_NOESCAPE)
357             == 0)
358           {
359             auto_load_debug_printf ("Matched - file \"%s\" to pattern \"%s\".",
360                                           filename, pattern);
361             return 1;
362           }
363 
364       /* Trim trailing FILENAME component.  */
365       while (filename_len > 0 && !IS_DIR_SEPARATOR (filename[filename_len - 1]))
366           filename_len--;
367     }
368 }
369 
370 /* Return 1 if FILENAME matches PATTERN or if FILENAME resides in
371    a subdirectory of a directory that matches PATTERN.  Return 0 otherwise.
372    gdb_realpath normalization is never done here.  */
373 
374 static ATTRIBUTE_PURE int
filename_is_in_pattern(const char * filename,const char * pattern)375 filename_is_in_pattern (const char *filename, const char *pattern)
376 {
377   char *filename_copy, *pattern_copy;
378 
379   filename_copy = (char *) alloca (strlen (filename) + 1);
380   strcpy (filename_copy, filename);
381   pattern_copy = (char *) alloca (strlen (pattern) + 1);
382   strcpy (pattern_copy, pattern);
383 
384   return filename_is_in_pattern_1 (filename_copy, pattern_copy);
385 }
386 
387 /* Return 1 if FILENAME belongs to one of directory components of
388    AUTO_LOAD_SAFE_PATH_VEC.  Return 0 otherwise.
389    auto_load_safe_path_vec_update is never called.
390    *FILENAME_REALP may be updated by gdb_realpath of FILENAME.  */
391 
392 static int
filename_is_in_auto_load_safe_path_vec(const char * filename,gdb::unique_xmalloc_ptr<char> * filename_realp)393 filename_is_in_auto_load_safe_path_vec (const char *filename,
394                                                   gdb::unique_xmalloc_ptr<char> *filename_realp)
395 {
396   const char *pattern = NULL;
397 
398   for (const gdb::unique_xmalloc_ptr<char> &p : auto_load_safe_path_vec)
399     if (*filename_realp == NULL && filename_is_in_pattern (filename, p.get ()))
400       {
401           pattern = p.get ();
402           break;
403       }
404 
405   if (pattern == NULL)
406     {
407       if (*filename_realp == NULL)
408           {
409             *filename_realp = gdb_realpath (filename);
410             if (debug_auto_load && strcmp (filename_realp->get (), filename) != 0)
411               auto_load_debug_printf ("Resolved file \"%s\" as \"%s\".",
412                                             filename, filename_realp->get ());
413           }
414 
415       if (strcmp (filename_realp->get (), filename) != 0)
416           for (const gdb::unique_xmalloc_ptr<char> &p : auto_load_safe_path_vec)
417             if (filename_is_in_pattern (filename_realp->get (), p.get ()))
418               {
419                 pattern = p.get ();
420                 break;
421               }
422     }
423 
424   if (pattern != NULL)
425     {
426       auto_load_debug_printf ("File \"%s\" matches directory \"%s\".",
427                                     filename, pattern);
428       return 1;
429     }
430 
431   return 0;
432 }
433 
434 /* See auto-load.h.  */
435 
436 bool
file_is_auto_load_safe(const char * filename)437 file_is_auto_load_safe (const char *filename)
438 {
439   gdb::unique_xmalloc_ptr<char> filename_real;
440   static bool advice_printed = false;
441 
442   if (filename_is_in_auto_load_safe_path_vec (filename, &filename_real))
443     return true;
444 
445   auto_load_safe_path_vec_update ();
446   if (filename_is_in_auto_load_safe_path_vec (filename, &filename_real))
447     return true;
448 
449   warning (_("File \"%ps\" auto-loading has been declined by your "
450                "`auto-load safe-path' set to \"%s\"."),
451              styled_string (file_name_style.style (), filename_real.get ()),
452              auto_load_safe_path.c_str ());
453 
454   if (!advice_printed)
455     {
456       /* Find the existing home directory config file.  */
457       struct stat buf;
458       std::string home_config = find_gdb_home_config_file (GDBINIT, &buf);
459       if (home_config.empty ())
460           {
461             /* The user doesn't have an existing home directory config file,
462                so we should suggest a suitable path for them to use.  */
463             std::string config_dir_file
464               = get_standard_config_filename (GDBINIT);
465             if (!config_dir_file.empty ())
466               home_config = config_dir_file;
467             else
468               {
469                 const char *homedir = getenv ("HOME");
470                 if (homedir == nullptr)
471                     homedir = "$HOME";
472                 home_config = (std::string (homedir) + SLASH_STRING
473                                    + std::string (GDBINIT));
474               }
475           }
476 
477       gdb_printf (_("\
478 To enable execution of this file add\n\
479 \tadd-auto-load-safe-path %s\n\
480 line to your configuration file \"%ps\".\n\
481 To completely disable this security protection add\n\
482 \tset auto-load safe-path /\n\
483 line to your configuration file \"%ps\".\n\
484 For more information about this security protection see the\n\
485 \"Auto-loading safe path\" section in the GDB manual.  E.g., run from the shell:\n\
486 \tinfo \"(gdb)Auto-loading safe path\"\n"),
487                            filename_real.get (),
488                            styled_string (file_name_style.style (),
489                                               home_config.c_str ()),
490                            styled_string (file_name_style.style (),
491                                               home_config.c_str ()));
492       advice_printed = true;
493     }
494 
495   return false;
496 }
497 
498 /* For scripts specified in .debug_gdb_scripts, multiple objfiles may load
499    the same script.  There's no point in loading the script multiple times,
500    and there can be a lot of objfiles and scripts, so we keep track of scripts
501    loaded this way.  */
502 
503 struct auto_load_pspace_info
504 {
505   /* For each program space we keep track of loaded scripts, both when
506      specified as file names and as scripts to be executed directly.  */
507   htab_up loaded_script_files;
508   htab_up loaded_script_texts;
509 
510   /* Non-zero if we've issued the warning about an auto-load script not being
511      supported.  We only want to issue this warning once.  */
512   bool unsupported_script_warning_printed = false;
513 
514   /* Non-zero if we've issued the warning about an auto-load script not being
515      found.  We only want to issue this warning once.  */
516   bool script_not_found_warning_printed = false;
517 };
518 
519 /* Objects of this type are stored in the loaded_script hash table.  */
520 
521 struct loaded_script
522 {
523   /* Name as provided by the objfile.  */
524   const char *name;
525 
526   /* Full path name or NULL if script wasn't found (or was otherwise
527      inaccessible), or NULL for loaded_script_texts.  */
528   const char *full_path;
529 
530   /* True if this script has been loaded.  */
531   bool loaded;
532 
533   const struct extension_language_defn *language;
534 };
535 
536 /* Per-program-space data key.  */
537 static const registry<program_space>::key<auto_load_pspace_info>
538      auto_load_pspace_data;
539 
540 /* Get the current autoload data.  If none is found yet, add it now.  This
541    function always returns a valid object.  */
542 
543 static struct auto_load_pspace_info *
get_auto_load_pspace_data(struct program_space * pspace)544 get_auto_load_pspace_data (struct program_space *pspace)
545 {
546   struct auto_load_pspace_info *info;
547 
548   info = auto_load_pspace_data.get (pspace);
549   if (info == NULL)
550     info = auto_load_pspace_data.emplace (pspace);
551 
552   return info;
553 }
554 
555 /* Hash function for the loaded script hash.  */
556 
557 static hashval_t
hash_loaded_script_entry(const void * data)558 hash_loaded_script_entry (const void *data)
559 {
560   const struct loaded_script *e = (const struct loaded_script *) data;
561 
562   return htab_hash_string (e->name) ^ htab_hash_pointer (e->language);
563 }
564 
565 /* Equality function for the loaded script hash.  */
566 
567 static int
eq_loaded_script_entry(const void * a,const void * b)568 eq_loaded_script_entry (const void *a, const void *b)
569 {
570   const struct loaded_script *ea = (const struct loaded_script *) a;
571   const struct loaded_script *eb = (const struct loaded_script *) b;
572 
573   return strcmp (ea->name, eb->name) == 0 && ea->language == eb->language;
574 }
575 
576 /* Initialize the table to track loaded scripts.
577    Each entry is hashed by the full path name.  */
578 
579 static void
init_loaded_scripts_info(struct auto_load_pspace_info * pspace_info)580 init_loaded_scripts_info (struct auto_load_pspace_info *pspace_info)
581 {
582   /* Choose 31 as the starting size of the hash table, somewhat arbitrarily.
583      Space for each entry is obtained with one malloc so we can free them
584      easily.  */
585 
586   pspace_info->loaded_script_files.reset
587     (htab_create (31,
588                       hash_loaded_script_entry,
589                       eq_loaded_script_entry,
590                       xfree));
591   pspace_info->loaded_script_texts.reset
592     (htab_create (31,
593                       hash_loaded_script_entry,
594                       eq_loaded_script_entry,
595                       xfree));
596 
597   pspace_info->unsupported_script_warning_printed = false;
598   pspace_info->script_not_found_warning_printed = false;
599 }
600 
601 /* Wrapper on get_auto_load_pspace_data to also allocate the hash table
602    for loading scripts.  */
603 
604 struct auto_load_pspace_info *
get_auto_load_pspace_data_for_loading(struct program_space * pspace)605 get_auto_load_pspace_data_for_loading (struct program_space *pspace)
606 {
607   struct auto_load_pspace_info *info;
608 
609   info = get_auto_load_pspace_data (pspace);
610   if (info->loaded_script_files == NULL)
611     init_loaded_scripts_info (info);
612 
613   return info;
614 }
615 
616 /* Add script file NAME in LANGUAGE to hash table of PSPACE_INFO.
617    LOADED is true if the script has been (is going to) be loaded, false
618    otherwise (such as if it has not been found).
619    FULL_PATH is NULL if the script wasn't found.
620 
621    The result is true if the script was already in the hash table.  */
622 
623 static bool
maybe_add_script_file(struct auto_load_pspace_info * pspace_info,bool loaded,const char * name,const char * full_path,const struct extension_language_defn * language)624 maybe_add_script_file (struct auto_load_pspace_info *pspace_info, bool loaded,
625                            const char *name, const char *full_path,
626                            const struct extension_language_defn *language)
627 {
628   struct htab *htab = pspace_info->loaded_script_files.get ();
629   struct loaded_script **slot, entry;
630 
631   entry.name = name;
632   entry.language = language;
633   slot = (struct loaded_script **) htab_find_slot (htab, &entry, INSERT);
634   bool in_hash_table = *slot != NULL;
635 
636   /* If this script is not in the hash table, add it.  */
637 
638   if (!in_hash_table)
639     {
640       char *p;
641 
642       /* Allocate all space in one chunk so it's easier to free.  */
643       *slot = ((struct loaded_script *)
644                  xmalloc (sizeof (**slot)
645                               + strlen (name) + 1
646                               + (full_path != NULL ? (strlen (full_path) + 1) : 0)));
647       p = ((char*) *slot) + sizeof (**slot);
648       strcpy (p, name);
649       (*slot)->name = p;
650       if (full_path != NULL)
651           {
652             p += strlen (p) + 1;
653             strcpy (p, full_path);
654             (*slot)->full_path = p;
655           }
656       else
657           (*slot)->full_path = NULL;
658       (*slot)->loaded = loaded;
659       (*slot)->language = language;
660     }
661 
662   return in_hash_table;
663 }
664 
665 /* Add script contents NAME in LANGUAGE to hash table of PSPACE_INFO.
666    LOADED is true if the script has been (is going to) be loaded, false
667    otherwise (such as if it has not been found).
668 
669    The result is true if the script was already in the hash table.  */
670 
671 static bool
maybe_add_script_text(struct auto_load_pspace_info * pspace_info,bool loaded,const char * name,const struct extension_language_defn * language)672 maybe_add_script_text (struct auto_load_pspace_info *pspace_info,
673                            bool loaded, const char *name,
674                            const struct extension_language_defn *language)
675 {
676   struct htab *htab = pspace_info->loaded_script_texts.get ();
677   struct loaded_script **slot, entry;
678 
679   entry.name = name;
680   entry.language = language;
681   slot = (struct loaded_script **) htab_find_slot (htab, &entry, INSERT);
682   bool in_hash_table = *slot != NULL;
683 
684   /* If this script is not in the hash table, add it.  */
685 
686   if (!in_hash_table)
687     {
688       char *p;
689 
690       /* Allocate all space in one chunk so it's easier to free.  */
691       *slot = ((struct loaded_script *)
692                  xmalloc (sizeof (**slot) + strlen (name) + 1));
693       p = ((char*) *slot) + sizeof (**slot);
694       strcpy (p, name);
695       (*slot)->name = p;
696       (*slot)->full_path = NULL;
697       (*slot)->loaded = loaded;
698       (*slot)->language = language;
699     }
700 
701   return in_hash_table;
702 }
703 
704 /* Clear the table of loaded section scripts.  */
705 
706 static void
clear_section_scripts(program_space * pspace)707 clear_section_scripts (program_space *pspace)
708 {
709   auto_load_pspace_info *info = auto_load_pspace_data.get (pspace);
710   if (info != NULL && info->loaded_script_files != NULL)
711     auto_load_pspace_data.clear (pspace);
712 }
713 
714 /* Look for the auto-load script in LANGUAGE associated with OBJFILE where
715    OBJFILE's gdb_realpath is REALNAME and load it.  Return 1 if we found any
716    matching script, return 0 otherwise.  */
717 
718 static int
auto_load_objfile_script_1(struct objfile * objfile,const char * realname,const struct extension_language_defn * language)719 auto_load_objfile_script_1 (struct objfile *objfile, const char *realname,
720                                   const struct extension_language_defn *language)
721 {
722   const char *debugfile;
723   int retval;
724   const char *suffix = ext_lang_auto_load_suffix (language);
725 
726   std::string filename = std::string (realname) + suffix;
727 
728   gdb_file_up input = gdb_fopen_cloexec (filename.c_str (), "r");
729   debugfile = filename.c_str ();
730 
731   auto_load_debug_printf ("Attempted file \"%ps\" %s.",
732                                 styled_string (file_name_style.style (), debugfile),
733                                 input != nullptr ? "exists" : "does not exist");
734 
735   std::string debugfile_holder;
736   if (!input)
737     {
738       /* Also try the same file in a subdirectory of gdb's data
739            directory.  */
740 
741       std::vector<gdb::unique_xmalloc_ptr<char>> vec
742           = auto_load_expand_dir_vars (auto_load_dir.c_str ());
743 
744       auto_load_debug_printf
745           ("Searching 'set auto-load scripts-directory' path \"%s\".",
746            auto_load_dir.c_str ());
747 
748       /* Convert Windows file name from c:/dir/file to /c/dir/file.  */
749       if (HAS_DRIVE_SPEC (debugfile))
750           filename = (std::string("\\") + debugfile[0]
751                         + STRIP_DRIVE_SPEC (debugfile));
752 
753       for (const gdb::unique_xmalloc_ptr<char> &dir : vec)
754           {
755             /* FILENAME is absolute, so we don't need a "/" here.  */
756             debugfile_holder = dir.get () + filename;
757             debugfile = debugfile_holder.c_str ();
758 
759             input = gdb_fopen_cloexec (debugfile, "r");
760 
761             auto_load_debug_printf ("Attempted file \"%ps\" %s.",
762                                           styled_string (file_name_style.style (),
763                                                              debugfile),
764                                           (input != nullptr
765                                            ? "exists"
766                                            : "does not exist"));
767 
768             if (input != NULL)
769               break;
770           }
771     }
772 
773   if (input)
774     {
775       struct auto_load_pspace_info *pspace_info;
776 
777       auto_load_debug_printf
778           ("Loading %s script \"%s\" by extension for objfile \"%s\".",
779            ext_lang_name (language), debugfile, objfile_name (objfile));
780 
781       bool is_safe = file_is_auto_load_safe (debugfile);
782 
783       /* Add this script to the hash table too so
784            "info auto-load ${lang}-scripts" can print it.  */
785       pspace_info
786           = get_auto_load_pspace_data_for_loading (objfile->pspace);
787       maybe_add_script_file (pspace_info, is_safe, debugfile, debugfile,
788                                    language);
789 
790       /* To preserve existing behaviour we don't check for whether the
791            script was already in the table, and always load it.
792            It's highly unlikely that we'd ever load it twice,
793            and these scripts are required to be idempotent under multiple
794            loads anyway.  */
795       if (is_safe)
796           {
797             objfile_script_sourcer_func *sourcer
798               = ext_lang_objfile_script_sourcer (language);
799 
800             /* We shouldn't get here if support for the language isn't
801                compiled in.  And the extension language is required to implement
802                this function.  */
803             gdb_assert (sourcer != NULL);
804             sourcer (language, objfile, input.get (), debugfile);
805           }
806 
807       retval = 1;
808     }
809   else
810     retval = 0;
811 
812   return retval;
813 }
814 
815 /* Look for the auto-load script in LANGUAGE associated with OBJFILE and load
816    it.  */
817 
818 void
auto_load_objfile_script(struct objfile * objfile,const struct extension_language_defn * language)819 auto_load_objfile_script (struct objfile *objfile,
820                                 const struct extension_language_defn *language)
821 {
822   gdb::unique_xmalloc_ptr<char> realname
823     = gdb_realpath (objfile_name (objfile));
824 
825   if (auto_load_objfile_script_1 (objfile, realname.get (), language))
826     return;
827 
828   /* For Windows/DOS .exe executables, strip the .exe suffix, so that
829      FOO-gdb.gdb could be used for FOO.exe, and try again.  */
830 
831   size_t len = strlen (realname.get ());
832   const size_t lexe = sizeof (".exe") - 1;
833 
834   if (len > lexe && strcasecmp (realname.get () + len - lexe, ".exe") == 0)
835     {
836       len -= lexe;
837       realname.get ()[len] = '\0';
838 
839       auto_load_debug_printf
840           ("Stripped .exe suffix, retrying with \"%s\".", realname.get ());
841 
842       auto_load_objfile_script_1 (objfile, realname.get (), language);
843       return;
844     }
845 
846   /* If OBJFILE is a separate debug file and its name does not match
847      the name given in the parent's .gnu_debuglink section, try to
848      find the auto-load script using the parent's path and the
849      debuglink name.  */
850 
851   struct objfile *parent = objfile->separate_debug_objfile_backlink;
852   if (parent != nullptr)
853     {
854       uint32_t crc32;
855       gdb::unique_xmalloc_ptr<char> debuglink
856           (bfd_get_debug_link_info (parent->obfd.get (), &crc32));
857 
858       if (debuglink.get () != nullptr
859             && strcmp (debuglink.get (), lbasename (realname.get ())) != 0)
860           {
861             /* Replace the last component of the parent's path with the
862                debuglink name.  */
863 
864             std::string p_realname = gdb_realpath (objfile_name (parent)).get ();
865             size_t last = p_realname.find_last_of ('/');
866 
867             if (last != std::string::npos)
868               {
869                 p_realname.replace (last + 1, std::string::npos,
870                                           debuglink.get ());
871 
872                 auto_load_debug_printf
873                     ("Debug filename mismatch, retrying with \"%s\".",
874                      p_realname.c_str ());
875 
876                 auto_load_objfile_script_1 (objfile,
877                                                     p_realname.c_str (), language);
878               }
879           }
880     }
881 }
882 
883 /* Subroutine of source_section_scripts to simplify it.
884    Load FILE as a script in extension language LANGUAGE.
885    The script is from section SECTION_NAME in OBJFILE at offset OFFSET.  */
886 
887 static void
source_script_file(struct auto_load_pspace_info * pspace_info,struct objfile * objfile,const struct extension_language_defn * language,const char * section_name,unsigned int offset,const char * file)888 source_script_file (struct auto_load_pspace_info *pspace_info,
889                         struct objfile *objfile,
890                         const struct extension_language_defn *language,
891                         const char *section_name, unsigned int offset,
892                         const char *file)
893 {
894   objfile_script_sourcer_func *sourcer;
895 
896   /* Skip this script if support is not compiled in.  */
897   sourcer = ext_lang_objfile_script_sourcer (language);
898   if (sourcer == NULL)
899     {
900       /* We don't throw an error, the program is still debuggable.  */
901       maybe_print_unsupported_script_warning (pspace_info, objfile, language,
902                                                         section_name, offset);
903       /* We *could* still try to open it, but there's no point.  */
904       maybe_add_script_file (pspace_info, 0, file, NULL, language);
905       return;
906     }
907 
908   /* Skip this script if auto-loading it has been disabled.  */
909   if (!ext_lang_auto_load_enabled (language))
910     {
911       /* No message is printed, just skip it.  */
912       return;
913     }
914 
915   std::optional<open_script> opened = find_and_open_script (file,
916                                                                           1 /*search_path*/);
917 
918   if (opened)
919     {
920       auto_load_debug_printf
921           ("Loading %s script \"%s\" from section \"%s\" of objfile \"%s\".",
922            ext_lang_name (language), opened->full_path.get (),
923            section_name, objfile_name (objfile));
924 
925       if (!file_is_auto_load_safe (opened->full_path.get ()))
926           opened.reset ();
927     }
928   else
929     {
930       /* If one script isn't found it's not uncommon for more to not be
931            found either.  We don't want to print a message for each script,
932            too much noise.  Instead, we print the warning once and tell the
933            user how to find the list of scripts that weren't loaded.
934            We don't throw an error, the program is still debuggable.
935 
936            IWBN if complaints.c were more general-purpose.  */
937 
938       maybe_print_script_not_found_warning (pspace_info, objfile, language,
939                                                       section_name, offset);
940     }
941 
942   bool in_hash_table
943     = maybe_add_script_file (pspace_info, bool (opened), file,
944                                    (opened ? opened->full_path.get (): NULL),
945                                    language);
946 
947   /* If this file is not currently loaded, load it.  */
948   if (opened && !in_hash_table)
949     sourcer (language, objfile, opened->stream.get (),
950                opened->full_path.get ());
951 }
952 
953 /* Subroutine of source_section_scripts to simplify it.
954    Execute SCRIPT as a script in extension language LANG.
955    The script is from section SECTION_NAME in OBJFILE at offset OFFSET.  */
956 
957 static void
execute_script_contents(struct auto_load_pspace_info * pspace_info,struct objfile * objfile,const struct extension_language_defn * language,const char * section_name,unsigned int offset,const char * script)958 execute_script_contents (struct auto_load_pspace_info *pspace_info,
959                                struct objfile *objfile,
960                                const struct extension_language_defn *language,
961                                const char *section_name, unsigned int offset,
962                                const char *script)
963 {
964   objfile_script_executor_func *executor;
965   const char *newline, *script_text;
966   const char *name;
967 
968   /* The first line of the script is the name of the script.
969      It must not contain any kind of space character.  */
970   name = NULL;
971   newline = strchr (script, '\n');
972   std::string name_holder;
973   if (newline != NULL)
974     {
975       const char *buf, *p;
976 
977       /* Put the name in a buffer and validate it.  */
978       name_holder = std::string (script, newline - script);
979       buf = name_holder.c_str ();
980       for (p = buf; *p != '\0'; ++p)
981           {
982             if (isspace (*p))
983               break;
984           }
985       /* We don't allow nameless scripts, they're not helpful to the user.  */
986       if (p != buf && *p == '\0')
987           name = buf;
988     }
989   if (name == NULL)
990     {
991       /* We don't throw an error, the program is still debuggable.  */
992       warning (_("\
993 Missing/bad script name in entry at offset %u in section %s\n\
994 of file %ps."),
995                  offset, section_name,
996                  styled_string (file_name_style.style (),
997                                     objfile_name (objfile)));
998       return;
999     }
1000   script_text = newline + 1;
1001 
1002   /* Skip this script if support is not compiled in.  */
1003   executor = ext_lang_objfile_script_executor (language);
1004   if (executor == NULL)
1005     {
1006       /* We don't throw an error, the program is still debuggable.  */
1007       maybe_print_unsupported_script_warning (pspace_info, objfile, language,
1008                                                         section_name, offset);
1009       maybe_add_script_text (pspace_info, 0, name, language);
1010       return;
1011     }
1012 
1013   /* Skip this script if auto-loading it has been disabled.  */
1014   if (!ext_lang_auto_load_enabled (language))
1015     {
1016       /* No message is printed, just skip it.  */
1017       return;
1018     }
1019 
1020   auto_load_debug_printf
1021     ("Loading %s script \"%s\" from section \"%s\" of objfile \"%s\".",
1022      ext_lang_name (language), name, section_name, objfile_name (objfile));
1023 
1024   bool is_safe = file_is_auto_load_safe (objfile_name (objfile));
1025 
1026   bool in_hash_table
1027     = maybe_add_script_text (pspace_info, is_safe, name, language);
1028 
1029   /* If this file is not currently loaded, load it.  */
1030   if (is_safe && !in_hash_table)
1031     executor (language, objfile, name, script_text);
1032 }
1033 
1034 /* Load scripts specified in OBJFILE.
1035    START,END delimit a buffer containing a list of nul-terminated
1036    file names.
1037    SECTION_NAME is used in error messages.
1038 
1039    Scripts specified as file names are found per normal "source -s" command
1040    processing.  First the script is looked for in $cwd.  If not found there
1041    the source search path is used.
1042 
1043    The section contains a list of path names of script files to load or
1044    actual script contents.  Each entry is nul-terminated.  */
1045 
1046 static void
source_section_scripts(struct objfile * objfile,const char * section_name,const char * start,const char * end)1047 source_section_scripts (struct objfile *objfile, const char *section_name,
1048                               const char *start, const char *end)
1049 {
1050   auto_load_pspace_info *pspace_info
1051     = get_auto_load_pspace_data_for_loading (objfile->pspace);
1052 
1053   for (const char *p = start; p < end; ++p)
1054     {
1055       const char *entry;
1056       const struct extension_language_defn *language;
1057       unsigned int offset = p - start;
1058       int code = *p;
1059 
1060       switch (code)
1061           {
1062           case SECTION_SCRIPT_ID_PYTHON_FILE:
1063           case SECTION_SCRIPT_ID_PYTHON_TEXT:
1064             language = get_ext_lang_defn (EXT_LANG_PYTHON);
1065             break;
1066           case SECTION_SCRIPT_ID_SCHEME_FILE:
1067           case SECTION_SCRIPT_ID_SCHEME_TEXT:
1068             language = get_ext_lang_defn (EXT_LANG_GUILE);
1069             break;
1070           default:
1071             warning (_("Invalid entry in %s section"), section_name);
1072             /* We could try various heuristics to find the next valid entry,
1073                but it's safer to just punt.  */
1074             return;
1075           }
1076       entry = ++p;
1077 
1078       while (p < end && *p != '\0')
1079           ++p;
1080       if (p == end)
1081           {
1082             warning (_("Non-nul-terminated entry in %s at offset %u"),
1083                        section_name, offset);
1084             /* Don't load/execute it.  */
1085             break;
1086           }
1087 
1088       switch (code)
1089           {
1090           case SECTION_SCRIPT_ID_PYTHON_FILE:
1091           case SECTION_SCRIPT_ID_SCHEME_FILE:
1092             if (p == entry)
1093               {
1094                 warning (_("Empty entry in %s at offset %u"),
1095                            section_name, offset);
1096                 continue;
1097               }
1098             source_script_file (pspace_info, objfile, language,
1099                                     section_name, offset, entry);
1100             break;
1101           case SECTION_SCRIPT_ID_PYTHON_TEXT:
1102           case SECTION_SCRIPT_ID_SCHEME_TEXT:
1103             execute_script_contents (pspace_info, objfile, language,
1104                                            section_name, offset, entry);
1105             break;
1106           }
1107     }
1108 }
1109 
1110 /* Load scripts specified in section SECTION_NAME of OBJFILE.  */
1111 
1112 static void
auto_load_section_scripts(struct objfile * objfile,const char * section_name)1113 auto_load_section_scripts (struct objfile *objfile, const char *section_name)
1114 {
1115   bfd *abfd = objfile->obfd.get ();
1116   asection *scripts_sect;
1117   bfd_byte *data = NULL;
1118 
1119   scripts_sect = bfd_get_section_by_name (abfd, section_name);
1120   if (scripts_sect == NULL
1121       || (bfd_section_flags (scripts_sect) & SEC_HAS_CONTENTS) == 0)
1122     return;
1123 
1124   if (!bfd_get_full_section_contents (abfd, scripts_sect, &data))
1125     warning (_("Couldn't read %s section of %ps"),
1126                section_name,
1127                styled_string (file_name_style.style (),
1128                                   bfd_get_filename (abfd)));
1129   else
1130     {
1131       gdb::unique_xmalloc_ptr<bfd_byte> data_holder (data);
1132 
1133       char *p = (char *) data;
1134       source_section_scripts (objfile, section_name, p,
1135                                     p + bfd_section_size (scripts_sect));
1136     }
1137 }
1138 
1139 /* Load any auto-loaded scripts for OBJFILE.
1140 
1141    Two flavors of auto-loaded scripts are supported.
1142    1) based on the path to the objfile
1143    2) from .debug_gdb_scripts section  */
1144 
1145 void
load_auto_scripts_for_objfile(struct objfile * objfile)1146 load_auto_scripts_for_objfile (struct objfile *objfile)
1147 {
1148   /* Return immediately if auto-loading has been globally disabled.
1149      This is to handle sequencing of operations during gdb startup.
1150      Also return immediately if OBJFILE was not created from a file
1151      on the local filesystem.  */
1152   if (!global_auto_load
1153       || (objfile->flags & OBJF_NOT_FILENAME) != 0
1154       || is_target_filename (objfile->original_name))
1155     return;
1156 
1157   /* Load any extension language scripts for this objfile.
1158      E.g., foo-gdb.gdb, foo-gdb.py.  */
1159   auto_load_ext_lang_scripts_for_objfile (objfile);
1160 
1161   /* Load any scripts mentioned in AUTO_SECTION_NAME (.debug_gdb_scripts).  */
1162   auto_load_section_scripts (objfile, AUTO_SECTION_NAME);
1163 }
1164 
1165 /* Collect scripts to be printed in a vec.  */
1166 
1167 struct collect_matching_scripts_data
1168 {
collect_matching_scripts_datacollect_matching_scripts_data1169   collect_matching_scripts_data (std::vector<loaded_script *> *scripts_p_,
1170                                          const extension_language_defn *language_)
1171   : scripts_p (scripts_p_), language (language_)
1172   {}
1173 
1174   std::vector<loaded_script *> *scripts_p;
1175   const struct extension_language_defn *language;
1176 };
1177 
1178 /* Traversal function for htab_traverse.
1179    Collect the entry if it matches the regexp.  */
1180 
1181 static int
collect_matching_scripts(void ** slot,void * info)1182 collect_matching_scripts (void **slot, void *info)
1183 {
1184   struct loaded_script *script = (struct loaded_script *) *slot;
1185   struct collect_matching_scripts_data *data
1186     = (struct collect_matching_scripts_data *) info;
1187 
1188   if (script->language == data->language && re_exec (script->name))
1189     data->scripts_p->push_back (script);
1190 
1191   return 1;
1192 }
1193 
1194 /* Print SCRIPT.  */
1195 
1196 static void
print_script(struct loaded_script * script)1197 print_script (struct loaded_script *script)
1198 {
1199   struct ui_out *uiout = current_uiout;
1200 
1201   ui_out_emit_tuple tuple_emitter (uiout, NULL);
1202 
1203   uiout->field_string ("loaded", script->loaded ? "Yes" : "No");
1204   uiout->field_string ("script", script->name);
1205   uiout->text ("\n");
1206 
1207   /* If the name isn't the full path, print it too.  */
1208   if (script->full_path != NULL
1209       && strcmp (script->name, script->full_path) != 0)
1210     {
1211       uiout->text ("\tfull name: ");
1212       uiout->field_string ("full_path", script->full_path);
1213       uiout->text ("\n");
1214     }
1215 }
1216 
1217 /* Helper for info_auto_load_scripts to sort the scripts by name.  */
1218 
1219 static bool
sort_scripts_by_name(loaded_script * a,loaded_script * b)1220 sort_scripts_by_name (loaded_script *a, loaded_script *b)
1221 {
1222   return FILENAME_CMP (a->name, b->name) < 0;
1223 }
1224 
1225 /* Special internal GDB value of auto_load_info_scripts's PATTERN identify
1226    the "info auto-load XXX" command has been executed through the general
1227    "info auto-load" invocation.  Extra newline will be printed if needed.  */
1228 char auto_load_info_scripts_pattern_nl[] = "";
1229 
1230 /* Subroutine of auto_load_info_scripts to simplify it.
1231    Print SCRIPTS.  */
1232 
1233 static void
print_scripts(const std::vector<loaded_script * > & scripts)1234 print_scripts (const std::vector<loaded_script *> &scripts)
1235 {
1236   for (loaded_script *script : scripts)
1237     print_script (script);
1238 }
1239 
1240 /* Implementation for "info auto-load gdb-scripts"
1241    (and "info auto-load python-scripts").  List scripts in LANGUAGE matching
1242    PATTERN.  FROM_TTY is the usual GDB boolean for user interactivity.  */
1243 
1244 void
auto_load_info_scripts(program_space * pspace,const char * pattern,int from_tty,const extension_language_defn * language)1245 auto_load_info_scripts (program_space *pspace, const char *pattern,
1246                               int from_tty, const extension_language_defn *language)
1247 {
1248   struct ui_out *uiout = current_uiout;
1249 
1250   dont_repeat ();
1251 
1252   auto_load_pspace_info *pspace_info = get_auto_load_pspace_data (pspace);
1253 
1254   if (pattern && *pattern)
1255     {
1256       char *re_err = re_comp (pattern);
1257 
1258       if (re_err)
1259           error (_("Invalid regexp: %s"), re_err);
1260     }
1261   else
1262     {
1263       re_comp ("");
1264     }
1265 
1266   /* We need to know the number of rows before we build the table.
1267      Plus we want to sort the scripts by name.
1268      So first traverse the hash table collecting the matching scripts.  */
1269 
1270   std::vector<loaded_script *> script_files, script_texts;
1271 
1272   if (pspace_info != NULL && pspace_info->loaded_script_files != NULL)
1273     {
1274       collect_matching_scripts_data data (&script_files, language);
1275 
1276       /* Pass a pointer to scripts as VEC_safe_push can realloc space.  */
1277       htab_traverse_noresize (pspace_info->loaded_script_files.get (),
1278                                     collect_matching_scripts, &data);
1279 
1280       std::sort (script_files.begin (), script_files.end (),
1281                      sort_scripts_by_name);
1282     }
1283 
1284   if (pspace_info != NULL && pspace_info->loaded_script_texts != NULL)
1285     {
1286       collect_matching_scripts_data data (&script_texts, language);
1287 
1288       /* Pass a pointer to scripts as VEC_safe_push can realloc space.  */
1289       htab_traverse_noresize (pspace_info->loaded_script_texts.get (),
1290                                     collect_matching_scripts, &data);
1291 
1292       std::sort (script_texts.begin (), script_texts.end (),
1293                      sort_scripts_by_name);
1294     }
1295 
1296   int nr_scripts = script_files.size () + script_texts.size ();
1297 
1298   /* Table header shifted right by preceding "gdb-scripts:  " would not match
1299      its columns.  */
1300   if (nr_scripts > 0 && pattern == auto_load_info_scripts_pattern_nl)
1301     uiout->text ("\n");
1302 
1303   {
1304     ui_out_emit_table table_emitter (uiout, 2, nr_scripts,
1305                                              "AutoLoadedScriptsTable");
1306 
1307     uiout->table_header (7, ui_left, "loaded", "Loaded");
1308     uiout->table_header (70, ui_left, "script", "Script");
1309     uiout->table_body ();
1310 
1311     print_scripts (script_files);
1312     print_scripts (script_texts);
1313   }
1314 
1315   if (nr_scripts == 0)
1316     {
1317       if (pattern && *pattern)
1318           uiout->message ("No auto-load scripts matching %s.\n", pattern);
1319       else
1320           uiout->message ("No auto-load scripts.\n");
1321     }
1322 }
1323 
1324 /* Wrapper for "info auto-load gdb-scripts".  */
1325 
1326 static void
info_auto_load_gdb_scripts(const char * pattern,int from_tty)1327 info_auto_load_gdb_scripts (const char *pattern, int from_tty)
1328 {
1329   auto_load_info_scripts (current_program_space, pattern, from_tty,
1330                                 &extension_language_gdb);
1331 }
1332 
1333 /* Implement 'info auto-load local-gdbinit'.  */
1334 
1335 static void
info_auto_load_local_gdbinit(const char * args,int from_tty)1336 info_auto_load_local_gdbinit (const char *args, int from_tty)
1337 {
1338   if (auto_load_local_gdbinit_pathname == NULL)
1339     gdb_printf (_("Local .gdbinit file was not found.\n"));
1340   else if (auto_load_local_gdbinit_loaded)
1341     gdb_printf (_("Local .gdbinit file \"%ps\" has been loaded.\n"),
1342                     styled_string (file_name_style.style (),
1343                                      auto_load_local_gdbinit_pathname));
1344   else
1345     gdb_printf (_("Local .gdbinit file \"%ps\" has not been loaded.\n"),
1346                     styled_string (file_name_style.style (),
1347                                      auto_load_local_gdbinit_pathname));
1348 }
1349 
1350 /* Print an "unsupported script" warning if it has not already been printed.
1351    The script is in language LANGUAGE at offset OFFSET in section SECTION_NAME
1352    of OBJFILE.  */
1353 
1354 static void
maybe_print_unsupported_script_warning(struct auto_load_pspace_info * pspace_info,struct objfile * objfile,const struct extension_language_defn * language,const char * section_name,unsigned offset)1355 maybe_print_unsupported_script_warning
1356   (struct auto_load_pspace_info *pspace_info,
1357    struct objfile *objfile, const struct extension_language_defn *language,
1358    const char *section_name, unsigned offset)
1359 {
1360   if (!pspace_info->unsupported_script_warning_printed)
1361     {
1362       warning (_("\
1363 Unsupported auto-load script at offset %u in section %s\n\
1364 of file %ps.\n\
1365 Use `info auto-load %s-scripts [REGEXP]' to list them."),
1366                  offset, section_name,
1367                  styled_string (file_name_style.style (),
1368                                     objfile_name (objfile)),
1369                  ext_lang_name (language));
1370       pspace_info->unsupported_script_warning_printed = true;
1371     }
1372 }
1373 
1374 /* Return non-zero if SCRIPT_NOT_FOUND_WARNING_PRINTED of PSPACE_INFO was unset
1375    before calling this function.  Always set SCRIPT_NOT_FOUND_WARNING_PRINTED
1376    of PSPACE_INFO.  */
1377 
1378 static void
maybe_print_script_not_found_warning(struct auto_load_pspace_info * pspace_info,struct objfile * objfile,const struct extension_language_defn * language,const char * section_name,unsigned offset)1379 maybe_print_script_not_found_warning
1380   (struct auto_load_pspace_info *pspace_info,
1381    struct objfile *objfile, const struct extension_language_defn *language,
1382    const char *section_name, unsigned offset)
1383 {
1384   if (!pspace_info->script_not_found_warning_printed)
1385     {
1386       warning (_("\
1387 Missing auto-load script at offset %u in section %s\n\
1388 of file %ps.\n\
1389 Use `info auto-load %s-scripts [REGEXP]' to list them."),
1390                  offset, section_name,
1391                  styled_string (file_name_style.style (),
1392                                     objfile_name (objfile)),
1393                  ext_lang_name (language));
1394       pspace_info->script_not_found_warning_printed = true;
1395     }
1396 }
1397 
1398 /* The only valid "set auto-load" argument is off|0|no|disable.  */
1399 
1400 static void
set_auto_load_cmd(const char * args,int from_tty)1401 set_auto_load_cmd (const char *args, int from_tty)
1402 {
1403   struct cmd_list_element *list;
1404   size_t length;
1405 
1406   /* See parse_binary_operation in use by the sub-commands.  */
1407 
1408   length = args ? strlen (args) : 0;
1409 
1410   while (length > 0 && (args[length - 1] == ' ' || args[length - 1] == '\t'))
1411     length--;
1412 
1413   if (length == 0 || (strncmp (args, "off", length) != 0
1414                           && strncmp (args, "0", length) != 0
1415                           && strncmp (args, "no", length) != 0
1416                           && strncmp (args, "disable", length) != 0))
1417     error (_("Valid is only global 'set auto-load no'; "
1418                "otherwise check the auto-load sub-commands."));
1419 
1420   for (list = *auto_load_set_cmdlist_get (); list != NULL; list = list->next)
1421     if (list->var->type () == var_boolean)
1422       {
1423           gdb_assert (list->type == set_cmd);
1424           do_set_command (args, from_tty, list);
1425       }
1426 }
1427 
1428 /* Initialize "set auto-load " commands prefix and return it.  */
1429 
1430 struct cmd_list_element **
auto_load_set_cmdlist_get(void)1431 auto_load_set_cmdlist_get (void)
1432 {
1433   static struct cmd_list_element *retval;
1434 
1435   if (retval == NULL)
1436     add_prefix_cmd ("auto-load", class_maintenance, set_auto_load_cmd, _("\
1437 Auto-loading specific settings.\n\
1438 Configure various auto-load-specific variables such as\n\
1439 automatic loading of Python scripts."),
1440                         &retval, 1/*allow-unknown*/, &setlist);
1441 
1442   return &retval;
1443 }
1444 
1445 /* Initialize "show auto-load " commands prefix and return it.  */
1446 
1447 struct cmd_list_element **
auto_load_show_cmdlist_get(void)1448 auto_load_show_cmdlist_get (void)
1449 {
1450   static struct cmd_list_element *retval;
1451 
1452   if (retval == NULL)
1453     add_show_prefix_cmd ("auto-load", class_maintenance, _("\
1454 Show auto-loading specific settings.\n\
1455 Show configuration of various auto-load-specific variables such as\n\
1456 automatic loading of Python scripts."),
1457                                &retval, 0/*allow-unknown*/, &showlist);
1458 
1459   return &retval;
1460 }
1461 
1462 /* Command "info auto-load" displays whether the various auto-load files have
1463    been loaded.  This is reimplementation of cmd_show_list which inserts
1464    newlines at proper places.  */
1465 
1466 static void
info_auto_load_cmd(const char * args,int from_tty)1467 info_auto_load_cmd (const char *args, int from_tty)
1468 {
1469   struct cmd_list_element *list;
1470   struct ui_out *uiout = current_uiout;
1471 
1472   ui_out_emit_tuple tuple_emitter (uiout, "infolist");
1473 
1474   for (list = *auto_load_info_cmdlist_get (); list != NULL; list = list->next)
1475     {
1476       ui_out_emit_tuple option_emitter (uiout, "option");
1477 
1478       gdb_assert (!list->is_prefix ());
1479       gdb_assert (list->type == not_set_cmd);
1480 
1481       uiout->field_string ("name", list->name);
1482       uiout->text (":  ");
1483       cmd_func (list, auto_load_info_scripts_pattern_nl, from_tty);
1484     }
1485 }
1486 
1487 /* Initialize "info auto-load " commands prefix and return it.  */
1488 
1489 struct cmd_list_element **
auto_load_info_cmdlist_get(void)1490 auto_load_info_cmdlist_get (void)
1491 {
1492   static struct cmd_list_element *retval;
1493 
1494   if (retval == NULL)
1495     add_prefix_cmd ("auto-load", class_info, info_auto_load_cmd, _("\
1496 Print current status of auto-loaded files.\n\
1497 Print whether various files like Python scripts or .gdbinit files have been\n\
1498 found and/or loaded."),
1499                         &retval, 0/*allow-unknown*/, &infolist);
1500 
1501   return &retval;
1502 }
1503 
1504 /* See auto-load.h.  */
1505 
1506 gdb::observers::token auto_load_new_objfile_observer_token;
1507 
1508 void _initialize_auto_load ();
1509 void
_initialize_auto_load()1510 _initialize_auto_load ()
1511 {
1512   struct cmd_list_element *cmd;
1513   gdb::unique_xmalloc_ptr<char> scripts_directory_help, gdb_name_help,
1514     python_name_help, guile_name_help;
1515   const char *suffix;
1516 
1517   gdb::observers::new_objfile.attach (load_auto_scripts_for_objfile,
1518                                               auto_load_new_objfile_observer_token,
1519                                               "auto-load");
1520   gdb::observers::all_objfiles_removed.attach (clear_section_scripts,
1521                                                          "auto-load");
1522   add_setshow_boolean_cmd ("gdb-scripts", class_support,
1523                                  &auto_load_gdb_scripts, _("\
1524 Enable or disable auto-loading of canned sequences of commands scripts."), _("\
1525 Show whether auto-loading of canned sequences of commands scripts is enabled."),
1526                                  _("\
1527 If enabled, canned sequences of commands are loaded when the debugger reads\n\
1528 an executable or shared library.\n\
1529 This option has security implications for untrusted inferiors."),
1530                                  NULL, show_auto_load_gdb_scripts,
1531                                  auto_load_set_cmdlist_get (),
1532                                  auto_load_show_cmdlist_get ());
1533 
1534   add_cmd ("gdb-scripts", class_info, info_auto_load_gdb_scripts,
1535              _("Print the list of automatically loaded sequences of commands.\n\
1536 Usage: info auto-load gdb-scripts [REGEXP]"),
1537              auto_load_info_cmdlist_get ());
1538 
1539   add_setshow_boolean_cmd ("local-gdbinit", class_support,
1540                                  &auto_load_local_gdbinit, _("\
1541 Enable or disable auto-loading of .gdbinit script in current directory."), _("\
1542 Show whether auto-loading .gdbinit script in current directory is enabled."),
1543                                  _("\
1544 If enabled, canned sequences of commands are loaded when debugger starts\n\
1545 from .gdbinit file in current directory.  Such files are deprecated,\n\
1546 use a script associated with inferior executable file instead.\n\
1547 This option has security implications for untrusted inferiors."),
1548                                  NULL, show_auto_load_local_gdbinit,
1549                                  auto_load_set_cmdlist_get (),
1550                                  auto_load_show_cmdlist_get ());
1551 
1552   add_cmd ("local-gdbinit", class_info, info_auto_load_local_gdbinit,
1553              _("Print whether current directory .gdbinit file has been loaded.\n\
1554 Usage: info auto-load local-gdbinit"),
1555              auto_load_info_cmdlist_get ());
1556 
1557   suffix = ext_lang_auto_load_suffix (get_ext_lang_defn (EXT_LANG_GDB));
1558   gdb_name_help
1559     = xstrprintf (_("\
1560 GDB scripts:    OBJFILE%s\n"),
1561                       suffix);
1562   python_name_help = NULL;
1563 #ifdef HAVE_PYTHON
1564   suffix = ext_lang_auto_load_suffix (get_ext_lang_defn (EXT_LANG_PYTHON));
1565   python_name_help
1566     = xstrprintf (_("\
1567 Python scripts: OBJFILE%s\n"),
1568                       suffix);
1569 #endif
1570   guile_name_help = NULL;
1571 #ifdef HAVE_GUILE
1572   suffix = ext_lang_auto_load_suffix (get_ext_lang_defn (EXT_LANG_GUILE));
1573   guile_name_help
1574     = xstrprintf (_("\
1575 Guile scripts:  OBJFILE%s\n"),
1576                       suffix);
1577 #endif
1578   scripts_directory_help
1579     = xstrprintf (_("\
1580 Automatically loaded scripts are located in one of the directories listed\n\
1581 by this option.\n\
1582 \n\
1583 Script names:\n\
1584 %s%s%s\
1585 \n\
1586 This option is ignored for the kinds of scripts \
1587 having 'set auto-load ... off'.\n\
1588 Directories listed here need to be present also \
1589 in the 'set auto-load safe-path'\n\
1590 option."),
1591                       gdb_name_help.get (),
1592                       python_name_help.get () ? python_name_help.get () : "",
1593                       guile_name_help.get () ? guile_name_help.get () : "");
1594 
1595   add_setshow_optional_filename_cmd ("scripts-directory", class_support,
1596                                              &auto_load_dir, _("\
1597 Set the list of directories from which to load auto-loaded scripts."), _("\
1598 Show the list of directories from which to load auto-loaded scripts."),
1599                                              scripts_directory_help.get (),
1600                                              set_auto_load_dir, show_auto_load_dir,
1601                                              auto_load_set_cmdlist_get (),
1602                                              auto_load_show_cmdlist_get ());
1603   auto_load_safe_path_vec_update ();
1604   add_setshow_optional_filename_cmd ("safe-path", class_support,
1605                                              &auto_load_safe_path, _("\
1606 Set the list of files and directories that are safe for auto-loading."), _("\
1607 Show the list of files and directories that are safe for auto-loading."), _("\
1608 Various files loaded automatically for the 'set auto-load ...' options must\n\
1609 be located in one of the directories listed by this option.  Warning will be\n\
1610 printed and file will not be used otherwise.\n\
1611 You can mix both directory and filename entries.\n\
1612 Setting this parameter to an empty list resets it to its default value.\n\
1613 Setting this parameter to '/' (without the quotes) allows any file\n\
1614 for the 'set auto-load ...' options.  Each path entry can be also shell\n\
1615 wildcard pattern; '*' does not match directory separator.\n\
1616 This option is ignored for the kinds of files having 'set auto-load ... off'.\n\
1617 This option has security implications for untrusted inferiors."),
1618                                              set_auto_load_safe_path,
1619                                              show_auto_load_safe_path,
1620                                              auto_load_set_cmdlist_get (),
1621                                              auto_load_show_cmdlist_get ());
1622   gdb::observers::gdb_datadir_changed.attach (auto_load_gdb_datadir_changed,
1623                                                         "auto-load");
1624 
1625   cmd = add_cmd ("add-auto-load-safe-path", class_support,
1626                      add_auto_load_safe_path,
1627                      _("Add entries to the list of directories from which it is safe "
1628                        "to auto-load files.\n\
1629 See the commands 'set auto-load safe-path' and 'show auto-load safe-path' to\n\
1630 access the current full list setting."),
1631                      &cmdlist);
1632   set_cmd_completer (cmd, filename_completer);
1633 
1634   cmd = add_cmd ("add-auto-load-scripts-directory", class_support,
1635                      add_auto_load_dir,
1636                      _("Add entries to the list of directories from which to load "
1637                        "auto-loaded scripts.\n\
1638 See the commands 'set auto-load scripts-directory' and\n\
1639 'show auto-load scripts-directory' to access the current full list setting."),
1640                      &cmdlist);
1641   set_cmd_completer (cmd, filename_completer);
1642 
1643   add_setshow_boolean_cmd ("auto-load", class_maintenance,
1644                                  &debug_auto_load, _("\
1645 Set auto-load verifications debugging."), _("\
1646 Show auto-load verifications debugging."), _("\
1647 When non-zero, debugging output for files of 'set auto-load ...'\n\
1648 is displayed."),
1649                                   NULL, show_debug_auto_load,
1650                                   &setdebuglist, &showdebuglist);
1651 }
1652