Simplify REGISTRY cleanup usages
[external/binutils.git] / gdb / auto-load.c
1 /* GDB routines for supporting auto-loaded scripts.
2
3    Copyright (C) 2012-2013 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 "auto-load.h"
22 #include "progspace.h"
23 #include "python/python.h"
24 #include "gdb_regex.h"
25 #include "ui-out.h"
26 #include "filenames.h"
27 #include "command.h"
28 #include "observer.h"
29 #include "objfiles.h"
30 #include "exceptions.h"
31 #include "cli/cli-script.h"
32 #include "gdbcmd.h"
33 #include "cli/cli-decode.h"
34 #include "cli/cli-setshow.h"
35 #include "gdb_vecs.h"
36 #include "readline/tilde.h"
37 #include "completer.h"
38 #include "observer.h"
39 #include "fnmatch.h"
40 #include "top.h"
41 #include "filestuff.h"
42
43 /* The suffix of per-objfile scripts to auto-load as non-Python command files.
44    E.g. When the program loads libfoo.so, look for libfoo-gdb.gdb.  */
45 #define GDB_AUTO_FILE_NAME "-gdb.gdb"
46
47 static void source_gdb_script_for_objfile (struct objfile *objfile, FILE *file,
48                                            const char *filename);
49
50 /* Value of the 'set debug auto-load' configuration variable.  */
51 static int debug_auto_load = 0;
52
53 /* "show" command for the debug_auto_load configuration variable.  */
54
55 static void
56 show_debug_auto_load (struct ui_file *file, int from_tty,
57                       struct cmd_list_element *c, const char *value)
58 {
59   fprintf_filtered (file, _("Debugging output for files "
60                             "of 'set auto-load ...' is %s.\n"),
61                     value);
62 }
63
64 /* User-settable option to enable/disable auto-loading of GDB_AUTO_FILE_NAME
65    scripts:
66    set auto-load gdb-scripts on|off
67    This is true if we should auto-load associated scripts when an objfile
68    is opened, false otherwise.  */
69 static int auto_load_gdb_scripts = 1;
70
71 /* "show" command for the auto_load_gdb_scripts configuration variable.  */
72
73 static void
74 show_auto_load_gdb_scripts (struct ui_file *file, int from_tty,
75                             struct cmd_list_element *c, const char *value)
76 {
77   fprintf_filtered (file, _("Auto-loading of canned sequences of commands "
78                             "scripts is %s.\n"),
79                     value);
80 }
81
82 /* Internal-use flag to enable/disable auto-loading.
83    This is true if we should auto-load python code when an objfile is opened,
84    false otherwise.
85
86    Both auto_load_scripts && global_auto_load must be true to enable
87    auto-loading.
88
89    This flag exists to facilitate deferring auto-loading during start-up
90    until after ./.gdbinit has been read; it may augment the search directories
91    used to find the scripts.  */
92 int global_auto_load = 1;
93
94 /* Auto-load .gdbinit file from the current directory?  */
95 int auto_load_local_gdbinit = 1;
96
97 /* Absolute pathname to the current directory .gdbinit, if it exists.  */
98 char *auto_load_local_gdbinit_pathname = NULL;
99
100 /* Boolean value if AUTO_LOAD_LOCAL_GDBINIT_PATHNAME has been loaded.  */
101 int auto_load_local_gdbinit_loaded = 0;
102
103 /* "show" command for the auto_load_local_gdbinit configuration variable.  */
104
105 static void
106 show_auto_load_local_gdbinit (struct ui_file *file, int from_tty,
107                               struct cmd_list_element *c, const char *value)
108 {
109   fprintf_filtered (file, _("Auto-loading of .gdbinit script from current "
110                             "directory is %s.\n"),
111                     value);
112 }
113
114 /* Directory list from which to load auto-loaded scripts.  It is not checked
115    for absolute paths but they are strongly recommended.  It is initialized by
116    _initialize_auto_load.  */
117 static char *auto_load_dir;
118
119 /* "set" command for the auto_load_dir configuration variable.  */
120
121 static void
122 set_auto_load_dir (char *args, int from_tty, struct cmd_list_element *c)
123 {
124   /* Setting the variable to "" resets it to the compile time defaults.  */
125   if (auto_load_dir[0] == '\0')
126     {
127       xfree (auto_load_dir);
128       auto_load_dir = xstrdup (AUTO_LOAD_DIR);
129     }
130 }
131
132 /* "show" command for the auto_load_dir configuration variable.  */
133
134 static void
135 show_auto_load_dir (struct ui_file *file, int from_tty,
136                     struct cmd_list_element *c, const char *value)
137 {
138   fprintf_filtered (file, _("List of directories from which to load "
139                             "auto-loaded scripts is %s.\n"),
140                     value);
141 }
142
143 /* Directory list safe to hold auto-loaded files.  It is not checked for
144    absolute paths but they are strongly recommended.  It is initialized by
145    _initialize_auto_load.  */
146 static char *auto_load_safe_path;
147
148 /* Vector of directory elements of AUTO_LOAD_SAFE_PATH with each one normalized
149    by tilde_expand and possibly each entries has added its gdb_realpath
150    counterpart.  */
151 static VEC (char_ptr) *auto_load_safe_path_vec;
152
153 /* Expand $datadir and $debugdir in STRING according to the rules of
154    substitute_path_component.  Return vector from dirnames_to_char_ptr_vec,
155    this vector must be freed by free_char_ptr_vec by the caller.  */
156
157 static VEC (char_ptr) *
158 auto_load_expand_dir_vars (const char *string)
159 {
160   VEC (char_ptr) *dir_vec;
161   char *s;
162
163   s = xstrdup (string);
164   substitute_path_component (&s, "$datadir", gdb_datadir);
165   substitute_path_component (&s, "$debugdir", debug_file_directory);
166
167   if (debug_auto_load && strcmp (s, string) != 0)
168     fprintf_unfiltered (gdb_stdlog,
169                         _("auto-load: Expanded $-variables to \"%s\".\n"), s);
170
171   dir_vec = dirnames_to_char_ptr_vec (s);
172   xfree(s);
173
174   return dir_vec;
175 }
176
177 /* Update auto_load_safe_path_vec from current AUTO_LOAD_SAFE_PATH.  */
178
179 static void
180 auto_load_safe_path_vec_update (void)
181 {
182   unsigned len;
183   int ix;
184
185   if (debug_auto_load)
186     fprintf_unfiltered (gdb_stdlog,
187                         _("auto-load: Updating directories of \"%s\".\n"),
188                         auto_load_safe_path);
189
190   free_char_ptr_vec (auto_load_safe_path_vec);
191
192   auto_load_safe_path_vec = auto_load_expand_dir_vars (auto_load_safe_path);
193   len = VEC_length (char_ptr, auto_load_safe_path_vec);
194
195   /* Apply tilde_expand and gdb_realpath to each AUTO_LOAD_SAFE_PATH_VEC
196      element.  */
197   for (ix = 0; ix < len; ix++)
198     {
199       char *dir = VEC_index (char_ptr, auto_load_safe_path_vec, ix);
200       char *expanded = tilde_expand (dir);
201       char *real_path = gdb_realpath (expanded);
202
203       /* Ensure the current entry is at least tilde_expand-ed.  */
204       VEC_replace (char_ptr, auto_load_safe_path_vec, ix, expanded);
205
206       if (debug_auto_load)
207         {
208           if (strcmp (expanded, dir) == 0)
209             fprintf_unfiltered (gdb_stdlog,
210                                 _("auto-load: Using directory \"%s\".\n"),
211                                 expanded);
212           else
213             fprintf_unfiltered (gdb_stdlog,
214                                 _("auto-load: Resolved directory \"%s\" "
215                                   "as \"%s\".\n"),
216                                 dir, expanded);
217         }
218       xfree (dir);
219
220       /* If gdb_realpath returns a different content, append it.  */
221       if (strcmp (real_path, expanded) == 0)
222         xfree (real_path);
223       else
224         {
225           VEC_safe_push (char_ptr, auto_load_safe_path_vec, real_path);
226
227           if (debug_auto_load)
228             fprintf_unfiltered (gdb_stdlog,
229                                 _("auto-load: And canonicalized as \"%s\".\n"),
230                                 real_path);
231         }
232     }
233 }
234
235 /* Variable gdb_datadir has been set.  Update content depending on $datadir.  */
236
237 static void
238 auto_load_gdb_datadir_changed (void)
239 {
240   auto_load_safe_path_vec_update ();
241 }
242
243 /* "set" command for the auto_load_safe_path configuration variable.  */
244
245 static void
246 set_auto_load_safe_path (char *args, int from_tty, struct cmd_list_element *c)
247 {
248   /* Setting the variable to "" resets it to the compile time defaults.  */
249   if (auto_load_safe_path[0] == '\0')
250     {
251       xfree (auto_load_safe_path);
252       auto_load_safe_path = xstrdup (AUTO_LOAD_SAFE_PATH);
253     }
254
255   auto_load_safe_path_vec_update ();
256 }
257
258 /* "show" command for the auto_load_safe_path configuration variable.  */
259
260 static void
261 show_auto_load_safe_path (struct ui_file *file, int from_tty,
262                           struct cmd_list_element *c, const char *value)
263 {
264   const char *cs;
265
266   /* Check if user has entered either "/" or for example ":".
267      But while more complicate content like ":/foo" would still also
268      permit any location do not hide those.  */
269
270   for (cs = value; *cs && (*cs == DIRNAME_SEPARATOR || IS_DIR_SEPARATOR (*cs));
271        cs++);
272   if (*cs == 0)
273     fprintf_filtered (file, _("Auto-load files are safe to load from any "
274                               "directory.\n"));
275   else
276     fprintf_filtered (file, _("List of directories from which it is safe to "
277                               "auto-load files is %s.\n"),
278                       value);
279 }
280
281 /* "add-auto-load-safe-path" command for the auto_load_safe_path configuration
282    variable.  */
283
284 static void
285 add_auto_load_safe_path (char *args, int from_tty)
286 {
287   char *s;
288
289   if (args == NULL || *args == 0)
290     error (_("\
291 Directory argument required.\n\
292 Use 'set auto-load safe-path /' for disabling the auto-load safe-path security.\
293 "));
294
295   s = xstrprintf ("%s%c%s", auto_load_safe_path, DIRNAME_SEPARATOR, args);
296   xfree (auto_load_safe_path);
297   auto_load_safe_path = s;
298
299   auto_load_safe_path_vec_update ();
300 }
301
302 /* Implementation for filename_is_in_pattern overwriting the caller's FILENAME
303    and PATTERN.  */
304
305 static int
306 filename_is_in_pattern_1 (char *filename, char *pattern)
307 {
308   size_t pattern_len = strlen (pattern);
309   size_t filename_len = strlen (filename);
310
311   if (debug_auto_load)
312     fprintf_unfiltered (gdb_stdlog, _("auto-load: Matching file \"%s\" "
313                                       "to pattern \"%s\"\n"),
314                         filename, pattern);
315
316   /* Trim trailing slashes ("/") from PATTERN.  Even for "d:\" paths as
317      trailing slashes are trimmed also from FILENAME it still matches
318      correctly.  */
319   while (pattern_len && IS_DIR_SEPARATOR (pattern[pattern_len - 1]))
320     pattern_len--;
321   pattern[pattern_len] = '\0';
322
323   /* Ensure auto_load_safe_path "/" matches any FILENAME.  On MS-Windows
324      platform FILENAME even after gdb_realpath does not have to start with
325      IS_DIR_SEPARATOR character, such as the 'C:\x.exe' filename.  */
326   if (pattern_len == 0)
327     {
328       if (debug_auto_load)
329         fprintf_unfiltered (gdb_stdlog,
330                             _("auto-load: Matched - empty pattern\n"));
331       return 1;
332     }
333
334   for (;;)
335     {
336       /* Trim trailing slashes ("/").  PATTERN also has slashes trimmed the
337          same way so they will match.  */
338       while (filename_len && IS_DIR_SEPARATOR (filename[filename_len - 1]))
339         filename_len--;
340       filename[filename_len] = '\0';
341       if (filename_len == 0)
342         {
343           if (debug_auto_load)
344             fprintf_unfiltered (gdb_stdlog,
345                                 _("auto-load: Not matched - pattern \"%s\".\n"),
346                                 pattern);
347           return 0;
348         }
349
350       if (gdb_filename_fnmatch (pattern, filename, FNM_FILE_NAME | FNM_NOESCAPE)
351           == 0)
352         {
353           if (debug_auto_load)
354             fprintf_unfiltered (gdb_stdlog, _("auto-load: Matched - file "
355                                               "\"%s\" to pattern \"%s\".\n"),
356                                 filename, pattern);
357           return 1;
358         }
359
360       /* Trim trailing FILENAME component.  */
361       while (filename_len > 0 && !IS_DIR_SEPARATOR (filename[filename_len - 1]))
362         filename_len--;
363     }
364 }
365
366 /* Return 1 if FILENAME matches PATTERN or if FILENAME resides in
367    a subdirectory of a directory that matches PATTERN.  Return 0 otherwise.
368    gdb_realpath normalization is never done here.  */
369
370 static ATTRIBUTE_PURE int
371 filename_is_in_pattern (const char *filename, const char *pattern)
372 {
373   char *filename_copy, *pattern_copy;
374
375   filename_copy = alloca (strlen (filename) + 1);
376   strcpy (filename_copy, filename);
377   pattern_copy = alloca (strlen (pattern) + 1);
378   strcpy (pattern_copy, pattern);
379
380   return filename_is_in_pattern_1 (filename_copy, pattern_copy);
381 }
382
383 /* Return 1 if FILENAME belongs to one of directory components of
384    AUTO_LOAD_SAFE_PATH_VEC.  Return 0 otherwise.
385    auto_load_safe_path_vec_update is never called.
386    *FILENAME_REALP may be updated by gdb_realpath of FILENAME - it has to be
387    freed by the caller.  */
388
389 static int
390 filename_is_in_auto_load_safe_path_vec (const char *filename,
391                                         char **filename_realp)
392 {
393   char *pattern;
394   int ix;
395
396   for (ix = 0; VEC_iterate (char_ptr, auto_load_safe_path_vec, ix, pattern);
397        ++ix)
398     if (*filename_realp == NULL && filename_is_in_pattern (filename, pattern))
399       break;
400   
401   if (pattern == NULL)
402     {
403       if (*filename_realp == NULL)
404         {
405           *filename_realp = gdb_realpath (filename);
406           if (debug_auto_load && strcmp (*filename_realp, filename) != 0)
407             fprintf_unfiltered (gdb_stdlog,
408                                 _("auto-load: Resolved "
409                                   "file \"%s\" as \"%s\".\n"),
410                                 filename, *filename_realp);
411         }
412
413       if (strcmp (*filename_realp, filename) != 0)
414         for (ix = 0;
415              VEC_iterate (char_ptr, auto_load_safe_path_vec, ix, pattern); ++ix)
416           if (filename_is_in_pattern (*filename_realp, pattern))
417             break;
418     }
419
420   if (pattern != NULL)
421     {
422       if (debug_auto_load)
423         fprintf_unfiltered (gdb_stdlog, _("auto-load: File \"%s\" matches "
424                                           "directory \"%s\".\n"),
425                             filename, pattern);
426       return 1;
427     }
428
429   return 0;
430 }
431
432 /* Return 1 if FILENAME is located in one of the directories of
433    AUTO_LOAD_SAFE_PATH.  Otherwise call warning and return 0.  FILENAME does
434    not have to be an absolute path.
435
436    Existence of FILENAME is not checked.  Function will still give a warning
437    even if the caller would quietly skip non-existing file in unsafe
438    directory.  */
439
440 int
441 file_is_auto_load_safe (const char *filename, const char *debug_fmt, ...)
442 {
443   char *filename_real = NULL;
444   struct cleanup *back_to;
445   static int advice_printed = 0;
446
447   if (debug_auto_load)
448     {
449       va_list debug_args;
450
451       va_start (debug_args, debug_fmt);
452       vfprintf_unfiltered (gdb_stdlog, debug_fmt, debug_args);
453       va_end (debug_args);
454     }
455
456   back_to = make_cleanup (free_current_contents, &filename_real);
457
458   if (filename_is_in_auto_load_safe_path_vec (filename, &filename_real))
459     {
460       do_cleanups (back_to);
461       return 1;
462     }
463
464   auto_load_safe_path_vec_update ();
465   if (filename_is_in_auto_load_safe_path_vec (filename, &filename_real))
466     {
467       do_cleanups (back_to);
468       return 1;
469     }
470
471   warning (_("File \"%s\" auto-loading has been declined by your "
472              "`auto-load safe-path' set to \"%s\"."),
473            filename_real, auto_load_safe_path);
474
475   if (!advice_printed)
476     {
477       const char *homedir = getenv ("HOME");
478       char *homeinit;
479
480       if (homedir == NULL)
481         homedir = "$HOME";
482       homeinit = xstrprintf ("%s/%s", homedir, gdbinit);
483       make_cleanup (xfree, homeinit);
484
485       printf_filtered (_("\
486 To enable execution of this file add\n\
487 \tadd-auto-load-safe-path %s\n\
488 line to your configuration file \"%s\".\n\
489 To completely disable this security protection add\n\
490 \tset auto-load safe-path /\n\
491 line to your configuration file \"%s\".\n\
492 For more information about this security protection see the\n\
493 \"Auto-loading safe path\" section in the GDB manual.  E.g., run from the shell:\n\
494 \tinfo \"(gdb)Auto-loading safe path\"\n"),
495                        filename_real, homeinit, homeinit);
496       advice_printed = 1;
497     }
498
499   do_cleanups (back_to);
500   return 0;
501 }
502
503 /* Definition of script language for GDB canned sequences of commands.  */
504
505 static const struct script_language script_language_gdb
506   = { GDB_AUTO_FILE_NAME, source_gdb_script_for_objfile };
507
508 static void
509 source_gdb_script_for_objfile (struct objfile *objfile, FILE *file,
510                                const char *filename)
511 {
512   int is_safe;
513   struct auto_load_pspace_info *pspace_info;
514   volatile struct gdb_exception e;
515
516   is_safe = file_is_auto_load_safe (filename, _("auto-load: Loading canned "
517                                                 "sequences of commands script "
518                                                 "\"%s\" for objfile \"%s\".\n"),
519                                     filename, objfile_name (objfile));
520
521   /* Add this script to the hash table too so "info auto-load gdb-scripts"
522      can print it.  */
523   pspace_info = get_auto_load_pspace_data_for_loading (current_program_space);
524   maybe_add_script (pspace_info, is_safe, filename, filename,
525                     &script_language_gdb);
526
527   if (!is_safe)
528     return;
529
530   TRY_CATCH (e, RETURN_MASK_ALL)
531     {
532       script_from_file (file, filename);
533     }
534   exception_print (gdb_stderr, e);
535 }
536
537 /* For scripts specified in .debug_gdb_scripts, multiple objfiles may load
538    the same script.  There's no point in loading the script multiple times,
539    and there can be a lot of objfiles and scripts, so we keep track of scripts
540    loaded this way.  */
541
542 struct auto_load_pspace_info
543 {
544   /* For each program space we keep track of loaded scripts.  */
545   struct htab *loaded_scripts;
546
547   /* Non-zero if we've issued the warning about an auto-load script not being
548      found.  We only want to issue this warning once.  */
549   int script_not_found_warning_printed;
550 };
551
552 /* Objects of this type are stored in the loaded script hash table.  */
553
554 struct loaded_script
555 {
556   /* Name as provided by the objfile.  */
557   const char *name;
558
559   /* Full path name or NULL if script wasn't found (or was otherwise
560      inaccessible).  */
561   const char *full_path;
562
563   /* Non-zero if this script has been loaded.  */
564   int loaded;
565
566   const struct script_language *language;
567 };
568
569 /* Per-program-space data key.  */
570 static const struct program_space_data *auto_load_pspace_data;
571
572 static void
573 auto_load_pspace_data_cleanup (struct program_space *pspace, void *arg)
574 {
575   struct auto_load_pspace_info *info = arg;
576
577   if (info->loaded_scripts)
578     htab_delete (info->loaded_scripts);
579   xfree (info);
580 }
581
582 /* Get the current autoload data.  If none is found yet, add it now.  This
583    function always returns a valid object.  */
584
585 static struct auto_load_pspace_info *
586 get_auto_load_pspace_data (struct program_space *pspace)
587 {
588   struct auto_load_pspace_info *info;
589
590   info = program_space_data (pspace, auto_load_pspace_data);
591   if (info == NULL)
592     {
593       info = XZALLOC (struct auto_load_pspace_info);
594       set_program_space_data (pspace, auto_load_pspace_data, info);
595     }
596
597   return info;
598 }
599
600 /* Hash function for the loaded script hash.  */
601
602 static hashval_t
603 hash_loaded_script_entry (const void *data)
604 {
605   const struct loaded_script *e = data;
606
607   return htab_hash_string (e->name) ^ htab_hash_pointer (e->language);
608 }
609
610 /* Equality function for the loaded script hash.  */
611
612 static int
613 eq_loaded_script_entry (const void *a, const void *b)
614 {
615   const struct loaded_script *ea = a;
616   const struct loaded_script *eb = b;
617
618   return strcmp (ea->name, eb->name) == 0 && ea->language == eb->language;
619 }
620
621 /* Initialize the table to track loaded scripts.
622    Each entry is hashed by the full path name.  */
623
624 static void
625 init_loaded_scripts_info (struct auto_load_pspace_info *pspace_info)
626 {
627   /* Choose 31 as the starting size of the hash table, somewhat arbitrarily.
628      Space for each entry is obtained with one malloc so we can free them
629      easily.  */
630
631   pspace_info->loaded_scripts = htab_create (31,
632                                              hash_loaded_script_entry,
633                                              eq_loaded_script_entry,
634                                              xfree);
635
636   pspace_info->script_not_found_warning_printed = FALSE;
637 }
638
639 /* Wrapper on get_auto_load_pspace_data to also allocate the hash table
640    for loading scripts.  */
641
642 struct auto_load_pspace_info *
643 get_auto_load_pspace_data_for_loading (struct program_space *pspace)
644 {
645   struct auto_load_pspace_info *info;
646
647   info = get_auto_load_pspace_data (pspace);
648   if (info->loaded_scripts == NULL)
649     init_loaded_scripts_info (info);
650
651   return info;
652 }
653
654 /* Add script NAME in LANGUAGE to hash table of PSPACE_INFO.  LOADED 1 if the
655    script has been (is going to) be loaded, 0 otherwise (such as if it has not
656    been found).  FULL_PATH is NULL if the script wasn't found.  The result is
657    true if the script was already in the hash table.  */
658
659 int
660 maybe_add_script (struct auto_load_pspace_info *pspace_info, int loaded,
661                   const char *name, const char *full_path,
662                   const struct script_language *language)
663 {
664   struct htab *htab = pspace_info->loaded_scripts;
665   struct loaded_script **slot, entry;
666   int in_hash_table;
667
668   entry.name = name;
669   entry.language = language;
670   slot = (struct loaded_script **) htab_find_slot (htab, &entry, INSERT);
671   in_hash_table = *slot != NULL;
672
673   /* If this script is not in the hash table, add it.  */
674
675   if (! in_hash_table)
676     {
677       char *p;
678
679       /* Allocate all space in one chunk so it's easier to free.  */
680       *slot = 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 /* Clear the table of loaded section scripts.  */
702
703 static void
704 clear_section_scripts (void)
705 {
706   struct program_space *pspace = current_program_space;
707   struct auto_load_pspace_info *info;
708
709   info = program_space_data (pspace, auto_load_pspace_data);
710   if (info != NULL && info->loaded_scripts != NULL)
711     {
712       htab_delete (info->loaded_scripts);
713       info->loaded_scripts = NULL;
714       info->script_not_found_warning_printed = FALSE;
715     }
716 }
717
718 /* Look for the auto-load script in LANGUAGE associated with OBJFILE where
719    OBJFILE's gdb_realpath is REALNAME and load it.  Return 1 if we found any
720    matching script, return 0 otherwise.  */
721
722 static int
723 auto_load_objfile_script_1 (struct objfile *objfile, const char *realname,
724                             const struct script_language *language)
725 {
726   char *filename, *debugfile;
727   int len, retval;
728   FILE *input;
729   struct cleanup *cleanups;
730
731   len = strlen (realname);
732   filename = xmalloc (len + strlen (language->suffix) + 1);
733   memcpy (filename, realname, len);
734   strcpy (filename + len, language->suffix);
735
736   cleanups = make_cleanup (xfree, filename);
737
738   input = gdb_fopen_cloexec (filename, "r");
739   debugfile = filename;
740   if (debug_auto_load)
741     fprintf_unfiltered (gdb_stdlog, _("auto-load: Attempted file \"%s\" %s.\n"),
742                         debugfile, input ? _("exists") : _("does not exist"));
743
744   if (!input)
745     {
746       VEC (char_ptr) *vec;
747       int ix;
748       char *dir;
749
750       /* Also try the same file in a subdirectory of gdb's data
751          directory.  */
752
753       vec = auto_load_expand_dir_vars (auto_load_dir);
754       make_cleanup_free_char_ptr_vec (vec);
755
756       if (debug_auto_load)
757         fprintf_unfiltered (gdb_stdlog, _("auto-load: Searching 'set auto-load "
758                                           "scripts-directory' path \"%s\".\n"),
759                             auto_load_dir);
760
761       for (ix = 0; VEC_iterate (char_ptr, vec, ix, dir); ++ix)
762         {
763           debugfile = xmalloc (strlen (dir) + strlen (filename) + 1);
764           strcpy (debugfile, dir);
765
766           /* FILENAME is absolute, so we don't need a "/" here.  */
767           strcat (debugfile, filename);
768
769           make_cleanup (xfree, debugfile);
770           input = gdb_fopen_cloexec (debugfile, "r");
771           if (debug_auto_load)
772             fprintf_unfiltered (gdb_stdlog, _("auto-load: Attempted file "
773                                               "\"%s\" %s.\n"),
774                                 debugfile,
775                                 input ? _("exists") : _("does not exist"));
776           if (input != NULL)
777             break;
778         }
779     }
780
781   if (input)
782     {
783       make_cleanup_fclose (input);
784
785       /* To preserve existing behaviour we don't check for whether the
786          script was already in the table, and always load it.
787          It's highly unlikely that we'd ever load it twice,
788          and these scripts are required to be idempotent under multiple
789          loads anyway.  */
790       language->source_script_for_objfile (objfile, input, debugfile);
791
792       retval = 1;
793     }
794   else
795     retval = 0;
796
797   do_cleanups (cleanups);
798   return retval;
799 }
800
801 /* Look for the auto-load script in LANGUAGE associated with OBJFILE and load
802    it.  */
803
804 void
805 auto_load_objfile_script (struct objfile *objfile,
806                           const struct script_language *language)
807 {
808   char *realname = gdb_realpath (objfile_name (objfile));
809   struct cleanup *cleanups = make_cleanup (xfree, realname);
810
811   if (!auto_load_objfile_script_1 (objfile, realname, language))
812     {
813       /* For Windows/DOS .exe executables, strip the .exe suffix, so that
814          FOO-gdb.gdb could be used for FOO.exe, and try again.  */
815
816       size_t len = strlen (realname);
817       const size_t lexe = sizeof (".exe") - 1;
818
819       if (len > lexe && strcasecmp (realname + len - lexe, ".exe") == 0)
820         {
821           len -= lexe;
822           realname[len] = '\0';
823           if (debug_auto_load)
824             fprintf_unfiltered (gdb_stdlog, _("auto-load: Stripped .exe suffix, "
825                                               "retrying with \"%s\".\n"),
826                                 realname);
827           auto_load_objfile_script_1 (objfile, realname, language);
828         }
829     }
830
831   do_cleanups (cleanups);
832 }
833
834 /* Load any auto-loaded scripts for OBJFILE.  */
835
836 void
837 load_auto_scripts_for_objfile (struct objfile *objfile)
838 {
839   if (!global_auto_load || (objfile->flags & OBJF_NOT_FILENAME) != 0)
840     return;
841
842   if (auto_load_gdb_scripts)
843     auto_load_objfile_script (objfile, &script_language_gdb);
844
845   gdbpy_load_auto_scripts_for_objfile (objfile);
846 }
847
848 /* This is a new_objfile observer callback to auto-load scripts.
849
850    Two flavors of auto-loaded scripts are supported.
851    1) based on the path to the objfile
852    2) from .debug_gdb_scripts section  */
853
854 static void
855 auto_load_new_objfile (struct objfile *objfile)
856 {
857   if (!objfile)
858     {
859       /* OBJFILE is NULL when loading a new "main" symbol-file.  */
860       clear_section_scripts ();
861       return;
862     }
863
864   load_auto_scripts_for_objfile (objfile);
865 }
866
867 /* Collect scripts to be printed in a vec.  */
868
869 typedef struct loaded_script *loaded_script_ptr;
870 DEF_VEC_P (loaded_script_ptr);
871
872 struct collect_matching_scripts_data
873 {
874   VEC (loaded_script_ptr) **scripts_p;
875
876   const struct script_language *language;
877 };
878
879 /* Traversal function for htab_traverse.
880    Collect the entry if it matches the regexp.  */
881
882 static int
883 collect_matching_scripts (void **slot, void *info)
884 {
885   struct loaded_script *script = *slot;
886   struct collect_matching_scripts_data *data = info;
887
888   if (script->language == data->language && re_exec (script->name))
889     VEC_safe_push (loaded_script_ptr, *data->scripts_p, script);
890
891   return 1;
892 }
893
894 /* Print SCRIPT.  */
895
896 static void
897 print_script (struct loaded_script *script)
898 {
899   struct ui_out *uiout = current_uiout;
900   struct cleanup *chain;
901
902   chain = make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
903
904   ui_out_field_string (uiout, "loaded", script->loaded ? "Yes" : "No");
905   ui_out_field_string (uiout, "script", script->name);
906   ui_out_text (uiout, "\n");
907
908   /* If the name isn't the full path, print it too.  */
909   if (script->full_path != NULL
910       && strcmp (script->name, script->full_path) != 0)
911     {
912       ui_out_text (uiout, "\tfull name: ");
913       ui_out_field_string (uiout, "full_path", script->full_path);
914       ui_out_text (uiout, "\n");
915     }
916
917   do_cleanups (chain);
918 }
919
920 /* Helper for info_auto_load_scripts to sort the scripts by name.  */
921
922 static int
923 sort_scripts_by_name (const void *ap, const void *bp)
924 {
925   const struct loaded_script *a = *(const struct loaded_script **) ap;
926   const struct loaded_script *b = *(const struct loaded_script **) bp;
927
928   return FILENAME_CMP (a->name, b->name);
929 }
930
931 /* Special internal GDB value of auto_load_info_scripts's PATTERN identify
932    the "info auto-load XXX" command has been executed through the general
933    "info auto-load" invocation.  Extra newline will be printed if needed.  */
934 char auto_load_info_scripts_pattern_nl[] = "";
935
936 /* Implementation for "info auto-load gdb-scripts"
937    (and "info auto-load python-scripts").  List scripts in LANGUAGE matching
938    PATTERN.  FROM_TTY is the usual GDB boolean for user interactivity.  */
939
940 void
941 auto_load_info_scripts (char *pattern, int from_tty,
942                         const struct script_language *language)
943 {
944   struct ui_out *uiout = current_uiout;
945   struct auto_load_pspace_info *pspace_info;
946   struct cleanup *script_chain;
947   VEC (loaded_script_ptr) *scripts;
948   int nr_scripts;
949
950   dont_repeat ();
951
952   pspace_info = get_auto_load_pspace_data (current_program_space);
953
954   if (pattern && *pattern)
955     {
956       char *re_err = re_comp (pattern);
957
958       if (re_err)
959         error (_("Invalid regexp: %s"), re_err);
960     }
961   else
962     {
963       re_comp ("");
964     }
965
966   /* We need to know the number of rows before we build the table.
967      Plus we want to sort the scripts by name.
968      So first traverse the hash table collecting the matching scripts.  */
969
970   scripts = VEC_alloc (loaded_script_ptr, 10);
971   script_chain = make_cleanup (VEC_cleanup (loaded_script_ptr), &scripts);
972
973   if (pspace_info != NULL && pspace_info->loaded_scripts != NULL)
974     {
975       struct collect_matching_scripts_data data = { &scripts, language };
976
977       /* Pass a pointer to scripts as VEC_safe_push can realloc space.  */
978       htab_traverse_noresize (pspace_info->loaded_scripts,
979                               collect_matching_scripts, &data);
980     }
981
982   nr_scripts = VEC_length (loaded_script_ptr, scripts);
983
984   /* Table header shifted right by preceding "gdb-scripts:  " would not match
985      its columns.  */
986   if (nr_scripts > 0 && pattern == auto_load_info_scripts_pattern_nl)
987     ui_out_text (uiout, "\n");
988
989   make_cleanup_ui_out_table_begin_end (uiout, 2, nr_scripts,
990                                        "AutoLoadedScriptsTable");
991
992   ui_out_table_header (uiout, 7, ui_left, "loaded", "Loaded");
993   ui_out_table_header (uiout, 70, ui_left, "script", "Script");
994   ui_out_table_body (uiout);
995
996   if (nr_scripts > 0)
997     {
998       int i;
999       loaded_script_ptr script;
1000
1001       qsort (VEC_address (loaded_script_ptr, scripts),
1002              VEC_length (loaded_script_ptr, scripts),
1003              sizeof (loaded_script_ptr), sort_scripts_by_name);
1004       for (i = 0; VEC_iterate (loaded_script_ptr, scripts, i, script); ++i)
1005         print_script (script);
1006     }
1007
1008   do_cleanups (script_chain);
1009
1010   if (nr_scripts == 0)
1011     {
1012       if (pattern && *pattern)
1013         ui_out_message (uiout, 0, "No auto-load scripts matching %s.\n",
1014                         pattern);
1015       else
1016         ui_out_message (uiout, 0, "No auto-load scripts.\n");
1017     }
1018 }
1019
1020 /* Wrapper for "info auto-load gdb-scripts".  */
1021
1022 static void
1023 info_auto_load_gdb_scripts (char *pattern, int from_tty)
1024 {
1025   auto_load_info_scripts (pattern, from_tty, &script_language_gdb);
1026 }
1027
1028 /* Implement 'info auto-load local-gdbinit'.  */
1029
1030 static void
1031 info_auto_load_local_gdbinit (char *args, int from_tty)
1032 {
1033   if (auto_load_local_gdbinit_pathname == NULL)
1034     printf_filtered (_("Local .gdbinit file was not found.\n"));
1035   else if (auto_load_local_gdbinit_loaded)
1036     printf_filtered (_("Local .gdbinit file \"%s\" has been loaded.\n"),
1037                      auto_load_local_gdbinit_pathname);
1038   else
1039     printf_filtered (_("Local .gdbinit file \"%s\" has not been loaded.\n"),
1040                      auto_load_local_gdbinit_pathname);
1041 }
1042
1043 /* Return non-zero if SCRIPT_NOT_FOUND_WARNING_PRINTED of PSPACE_INFO was unset
1044    before calling this function.  Always set SCRIPT_NOT_FOUND_WARNING_PRINTED
1045    of PSPACE_INFO.  */
1046
1047 int
1048 script_not_found_warning_print (struct auto_load_pspace_info *pspace_info)
1049 {
1050   int retval = !pspace_info->script_not_found_warning_printed;
1051
1052   pspace_info->script_not_found_warning_printed = 1;
1053
1054   return retval;
1055 }
1056
1057 /* The only valid "set auto-load" argument is off|0|no|disable.  */
1058
1059 static void
1060 set_auto_load_cmd (char *args, int from_tty)
1061 {
1062   struct cmd_list_element *list;
1063   size_t length;
1064
1065   /* See parse_binary_operation in use by the sub-commands.  */
1066
1067   length = args ? strlen (args) : 0;
1068
1069   while (length > 0 && (args[length - 1] == ' ' || args[length - 1] == '\t'))
1070     length--;
1071
1072   if (length == 0 || (strncmp (args, "off", length) != 0
1073                       && strncmp (args, "0", length) != 0
1074                       && strncmp (args, "no", length) != 0
1075                       && strncmp (args, "disable", length) != 0))
1076     error (_("Valid is only global 'set auto-load no'; "
1077              "otherwise check the auto-load sub-commands."));
1078
1079   for (list = *auto_load_set_cmdlist_get (); list != NULL; list = list->next)
1080     if (list->var_type == var_boolean)
1081       {
1082         gdb_assert (list->type == set_cmd);
1083         do_set_command (args, from_tty, list);
1084       }
1085 }
1086
1087 /* Initialize "set auto-load " commands prefix and return it.  */
1088
1089 struct cmd_list_element **
1090 auto_load_set_cmdlist_get (void)
1091 {
1092   static struct cmd_list_element *retval;
1093
1094   if (retval == NULL)
1095     add_prefix_cmd ("auto-load", class_maintenance, set_auto_load_cmd, _("\
1096 Auto-loading specific settings.\n\
1097 Configure various auto-load-specific variables such as\n\
1098 automatic loading of Python scripts."),
1099                     &retval, "set auto-load ",
1100                     1/*allow-unknown*/, &setlist);
1101
1102   return &retval;
1103 }
1104
1105 /* Command "show auto-load" displays summary of all the current
1106    "show auto-load " settings.  */
1107
1108 static void
1109 show_auto_load_cmd (char *args, int from_tty)
1110 {
1111   cmd_show_list (*auto_load_show_cmdlist_get (), from_tty, "");
1112 }
1113
1114 /* Initialize "show auto-load " commands prefix and return it.  */
1115
1116 struct cmd_list_element **
1117 auto_load_show_cmdlist_get (void)
1118 {
1119   static struct cmd_list_element *retval;
1120
1121   if (retval == NULL)
1122     add_prefix_cmd ("auto-load", class_maintenance, show_auto_load_cmd, _("\
1123 Show auto-loading specific settings.\n\
1124 Show configuration of various auto-load-specific variables such as\n\
1125 automatic loading of Python scripts."),
1126                     &retval, "show auto-load ",
1127                     0/*allow-unknown*/, &showlist);
1128
1129   return &retval;
1130 }
1131
1132 /* Command "info auto-load" displays whether the various auto-load files have
1133    been loaded.  This is reimplementation of cmd_show_list which inserts
1134    newlines at proper places.  */
1135
1136 static void
1137 info_auto_load_cmd (char *args, int from_tty)
1138 {
1139   struct cmd_list_element *list;
1140   struct cleanup *infolist_chain;
1141   struct ui_out *uiout = current_uiout;
1142
1143   infolist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "infolist");
1144
1145   for (list = *auto_load_info_cmdlist_get (); list != NULL; list = list->next)
1146     {
1147       struct cleanup *option_chain
1148         = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
1149
1150       gdb_assert (!list->prefixlist);
1151       gdb_assert (list->type == not_set_cmd);
1152
1153       ui_out_field_string (uiout, "name", list->name);
1154       ui_out_text (uiout, ":  ");
1155       cmd_func (list, auto_load_info_scripts_pattern_nl, from_tty);
1156
1157       /* Close the tuple.  */
1158       do_cleanups (option_chain);
1159     }
1160
1161   /* Close the tuple.  */
1162   do_cleanups (infolist_chain);
1163 }
1164
1165 /* Initialize "info auto-load " commands prefix and return it.  */
1166
1167 struct cmd_list_element **
1168 auto_load_info_cmdlist_get (void)
1169 {
1170   static struct cmd_list_element *retval;
1171
1172   if (retval == NULL)
1173     add_prefix_cmd ("auto-load", class_info, info_auto_load_cmd, _("\
1174 Print current status of auto-loaded files.\n\
1175 Print whether various files like Python scripts or .gdbinit files have been\n\
1176 found and/or loaded."),
1177                     &retval, "info auto-load ",
1178                     0/*allow-unknown*/, &infolist);
1179
1180   return &retval;
1181 }
1182
1183 void _initialize_auto_load (void);
1184
1185 void
1186 _initialize_auto_load (void)
1187 {
1188   struct cmd_list_element *cmd;
1189   char *scripts_directory_help;
1190
1191   auto_load_pspace_data
1192     = register_program_space_data_with_cleanup (NULL,
1193                                                 auto_load_pspace_data_cleanup);
1194
1195   observer_attach_new_objfile (auto_load_new_objfile);
1196
1197   add_setshow_boolean_cmd ("gdb-scripts", class_support,
1198                            &auto_load_gdb_scripts, _("\
1199 Enable or disable auto-loading of canned sequences of commands scripts."), _("\
1200 Show whether auto-loading of canned sequences of commands scripts is enabled."),
1201                            _("\
1202 If enabled, canned sequences of commands are loaded when the debugger reads\n\
1203 an executable or shared library.\n\
1204 This options has security implications for untrusted inferiors."),
1205                            NULL, show_auto_load_gdb_scripts,
1206                            auto_load_set_cmdlist_get (),
1207                            auto_load_show_cmdlist_get ());
1208
1209   add_cmd ("gdb-scripts", class_info, info_auto_load_gdb_scripts,
1210            _("Print the list of automatically loaded sequences of commands.\n\
1211 Usage: info auto-load gdb-scripts [REGEXP]"),
1212            auto_load_info_cmdlist_get ());
1213
1214   add_setshow_boolean_cmd ("local-gdbinit", class_support,
1215                            &auto_load_local_gdbinit, _("\
1216 Enable or disable auto-loading of .gdbinit script in current directory."), _("\
1217 Show whether auto-loading .gdbinit script in current directory is enabled."),
1218                            _("\
1219 If enabled, canned sequences of commands are loaded when debugger starts\n\
1220 from .gdbinit file in current directory.  Such files are deprecated,\n\
1221 use a script associated with inferior executable file instead.\n\
1222 This options has security implications for untrusted inferiors."),
1223                            NULL, show_auto_load_local_gdbinit,
1224                            auto_load_set_cmdlist_get (),
1225                            auto_load_show_cmdlist_get ());
1226
1227   add_cmd ("local-gdbinit", class_info, info_auto_load_local_gdbinit,
1228            _("Print whether current directory .gdbinit file has been loaded.\n\
1229 Usage: info auto-load local-gdbinit"),
1230            auto_load_info_cmdlist_get ());
1231
1232   auto_load_dir = xstrdup (AUTO_LOAD_DIR);
1233   scripts_directory_help = xstrprintf (
1234 #ifdef HAVE_PYTHON
1235                                        _("\
1236 Automatically loaded Python scripts (named OBJFILE%s) and GDB scripts\n\
1237 (named OBJFILE%s) are located in one of the directories listed by this\n\
1238 option.\n\
1239 %s"),
1240                                        GDBPY_AUTO_FILE_NAME,
1241 #else
1242                                        _("\
1243 Automatically loaded GDB scripts (named OBJFILE%s) are located in one\n\
1244 of the directories listed by this option.\n\
1245 %s"),
1246 #endif
1247                                        GDB_AUTO_FILE_NAME,
1248                                        _("\
1249 This option is ignored for the kinds of scripts \
1250 having 'set auto-load ... off'.\n\
1251 Directories listed here need to be present also \
1252 in the 'set auto-load safe-path'\n\
1253 option."));
1254   add_setshow_optional_filename_cmd ("scripts-directory", class_support,
1255                                      &auto_load_dir, _("\
1256 Set the list of directories from which to load auto-loaded scripts."), _("\
1257 Show the list of directories from which to load auto-loaded scripts."),
1258                                      scripts_directory_help,
1259                                      set_auto_load_dir, show_auto_load_dir,
1260                                      auto_load_set_cmdlist_get (),
1261                                      auto_load_show_cmdlist_get ());
1262   xfree (scripts_directory_help);
1263
1264   auto_load_safe_path = xstrdup (AUTO_LOAD_SAFE_PATH);
1265   auto_load_safe_path_vec_update ();
1266   add_setshow_optional_filename_cmd ("safe-path", class_support,
1267                                      &auto_load_safe_path, _("\
1268 Set the list of files and directories that are safe for auto-loading."), _("\
1269 Show the list of files and directories that are safe for auto-loading."), _("\
1270 Various files loaded automatically for the 'set auto-load ...' options must\n\
1271 be located in one of the directories listed by this option.  Warning will be\n\
1272 printed and file will not be used otherwise.\n\
1273 You can mix both directory and filename entries.\n\
1274 Setting this parameter to an empty list resets it to its default value.\n\
1275 Setting this parameter to '/' (without the quotes) allows any file\n\
1276 for the 'set auto-load ...' options.  Each path entry can be also shell\n\
1277 wildcard pattern; '*' does not match directory separator.\n\
1278 This option is ignored for the kinds of files having 'set auto-load ... off'.\n\
1279 This options has security implications for untrusted inferiors."),
1280                                      set_auto_load_safe_path,
1281                                      show_auto_load_safe_path,
1282                                      auto_load_set_cmdlist_get (),
1283                                      auto_load_show_cmdlist_get ());
1284   observer_attach_gdb_datadir_changed (auto_load_gdb_datadir_changed);
1285
1286   cmd = add_cmd ("add-auto-load-safe-path", class_support,
1287                  add_auto_load_safe_path,
1288                  _("Add entries to the list of directories from which it is safe "
1289                    "to auto-load files.\n\
1290 See the commands 'set auto-load safe-path' and 'show auto-load safe-path' to\n\
1291 access the current full list setting."),
1292                  &cmdlist);
1293   set_cmd_completer (cmd, filename_completer);
1294
1295   add_setshow_boolean_cmd ("auto-load", class_maintenance,
1296                            &debug_auto_load, _("\
1297 Set auto-load verifications debugging."), _("\
1298 Show auto-load verifications debugging."), _("\
1299 When non-zero, debugging output for files of 'set auto-load ...'\n\
1300 is displayed."),
1301                             NULL, show_debug_auto_load,
1302                             &setdebuglist, &showdebuglist);
1303 }