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