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