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