Upgrade GDB from 7.0 and 7.2 on the vendor branch
[dragonfly.git] / contrib / gdb-7 / gdb / python / py-auto-load.c
1 /* GDB routines for supporting auto-loaded scripts.
2
3    Copyright (C) 2010 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 "gdb_string.h"
22 #include "gdb_regex.h"
23 #include "top.h"
24 #include "exceptions.h"
25 #include "command.h"
26 #include "gdbcmd.h"
27 #include "observer.h"
28 #include "progspace.h"
29 #include "objfiles.h"
30 #include "python.h"
31 #include "cli/cli-cmds.h"
32
33 /* Internal-use flag to enable/disable auto-loading.
34    This is true if we should auto-load python code when an objfile is opened,
35    false otherwise.
36
37    Both gdbpy_auto_load && gdbpy_global_auto_load must be true to enable
38    auto-loading.
39
40    This flag exists to facilitate deferring auto-loading during start-up
41    until after ./.gdbinit has been read; it may augment the search directories
42    used to find the scripts.  */
43 int gdbpy_global_auto_load = 1;
44
45 #ifdef HAVE_PYTHON
46
47 #include "python-internal.h"
48
49 /* NOTE: It's trivial to also support auto-loading normal gdb scripts.
50    There has yet to be a need so it's not implemented.  */
51
52 /* The suffix of per-objfile scripts to auto-load.
53    E.g. When the program loads libfoo.so, look for libfoo-gdb.py.  */
54 #define GDBPY_AUTO_FILE_NAME "-gdb.py"
55
56 /* The section to look for scripts (in file formats that support sections).
57    Each entry in this section is a byte of value 1, and then the nul-terminated
58    name of the script.  The script name may include a directory.
59    The leading byte is to allow upward compatible extensions.  */
60 #define GDBPY_AUTO_SECTION_NAME ".debug_gdb_scripts"
61
62 /* For scripts specified in .debug_gdb_scripts, multiple objfiles may load
63    the same script.  There's no point in loading the script multiple times,
64    and there can be a lot of objfiles and scripts, so we keep track of scripts
65    loaded this way.  */
66
67 struct auto_load_pspace_info
68 {
69   /* For each program space we keep track of loaded scripts.  */
70   struct htab *loaded_scripts;
71 };
72
73 /* Objects of this type are stored in the loaded script hash table.  */
74
75 struct loaded_script_entry
76 {
77   /* Name as provided by the objfile.  */
78   const char *name;
79   /* Full path name or NULL if script wasn't found (or was otherwise
80      inaccessible).  */
81   const char *full_path;
82 };
83
84 /* User-settable option to enable/disable auto-loading:
85    maint set python auto-load on|off
86    This is true if we should auto-load python code when an objfile is opened,
87    false otherwise.  */
88 static int gdbpy_auto_load = 1;
89
90 /* Per-program-space data key.  */
91 static const struct program_space_data *auto_load_pspace_data;
92
93 static void
94 auto_load_pspace_data_cleanup (struct program_space *pspace, void *arg)
95 {
96   struct auto_load_pspace_info *info;
97
98   info = program_space_data (pspace, auto_load_pspace_data);
99   if (info != NULL)
100     {
101       if (info->loaded_scripts)
102         htab_delete (info->loaded_scripts);
103       xfree (info);
104     }
105 }
106
107 /* Get the current autoload data.  If none is found yet, add it now.  This
108    function always returns a valid object.  */
109
110 static struct auto_load_pspace_info *
111 get_auto_load_pspace_data (struct program_space *pspace)
112 {
113   struct auto_load_pspace_info *info;
114
115   info = program_space_data (pspace, auto_load_pspace_data);
116   if (info == NULL)
117     {
118       info = XZALLOC (struct auto_load_pspace_info);
119       set_program_space_data (pspace, auto_load_pspace_data, info);
120     }
121
122   return info;
123 }
124
125 /* Hash function for the loaded script hash.  */
126
127 static hashval_t
128 hash_loaded_script_entry (const void *data)
129 {
130   const struct loaded_script_entry *e = data;
131
132   return htab_hash_string (e->name);
133 }
134
135 /* Equality function for the loaded script hash.  */
136
137 static int
138 eq_loaded_script_entry (const void *a, const void *b)
139 {
140   const struct loaded_script_entry *ea = a;
141   const struct loaded_script_entry *eb = b;
142
143   return strcmp (ea->name, eb->name) == 0;
144 }
145
146 /* Create the hash table used for loaded scripts.
147    Each entry is hashed by the full path name.  */
148
149 static void
150 create_loaded_scripts_hash (struct auto_load_pspace_info *pspace_info)
151 {
152   /* Choose 31 as the starting size of the hash table, somewhat arbitrarily.
153      Space for each entry is obtained with one malloc so we can free them
154      easily.  */
155
156   pspace_info->loaded_scripts = htab_create (31,
157                                              hash_loaded_script_entry,
158                                              eq_loaded_script_entry,
159                                              xfree);
160 }
161
162 /* Load scripts specified in OBJFILE.
163    START,END delimit a buffer containing a list of nul-terminated
164    file names.
165    SOURCE_NAME is used in error messages.
166
167    Scripts are found per normal "source -s" command processing.
168    First the script is looked for in $cwd.  If not found there the
169    source search path is used.
170
171    The section contains a list of path names of files containing
172    python code to load.  Each path is null-terminated.  */
173
174 static void
175 source_section_scripts (struct objfile *objfile, const char *source_name,
176                         const char *start, const char *end)
177 {
178   const char *p;
179   struct auto_load_pspace_info *pspace_info;
180   struct loaded_script_entry **slot, entry;
181
182   pspace_info = get_auto_load_pspace_data (current_program_space);
183   if (pspace_info->loaded_scripts == NULL)
184     create_loaded_scripts_hash (pspace_info);
185
186   for (p = start; p < end; ++p)
187     {
188       const char *file;
189       FILE *stream;
190       char *full_path;
191       int opened, in_hash_table;
192
193       if (*p != 1)
194         {
195           warning (_("Invalid entry in %s section"), GDBPY_AUTO_SECTION_NAME);
196           /* We could try various heuristics to find the next valid entry,
197              but it's safer to just punt.  */
198           break;
199         }
200       file = ++p;
201
202       while (p < end && *p != '\0')
203         ++p;
204       if (p == end)
205         {
206           char *buf = alloca (p - file + 1);
207
208           memcpy (buf, file, p - file);
209           buf[p - file] = '\0';
210           warning (_("Non-null-terminated path in %s: %s"),
211                    source_name, buf);
212           /* Don't load it.  */
213           break;
214         }
215       if (p == file)
216         {
217           warning (_("Empty path in %s"), source_name);
218           continue;
219         }
220
221       opened = find_and_open_script (file, 1 /*search_path*/,
222                                      &stream, &full_path);
223
224       /* If the file is not found, we still record the file in the hash table,
225          we only want to print an error message once.
226          IWBN if complaints.c were more general-purpose.  */
227
228       entry.name = file;
229       if (opened)
230         entry.full_path = full_path;
231       else
232         entry.full_path = NULL;
233       slot = ((struct loaded_script_entry **)
234               htab_find_slot (pspace_info->loaded_scripts,
235                               &entry, INSERT));
236       in_hash_table = *slot != NULL;
237
238       /* If this file is not in the hash table, add it.  */
239       if (! in_hash_table)
240         {
241           char *p;
242
243           *slot = xmalloc (sizeof (**slot)
244                            + strlen (file) + 1
245                            + (opened ? (strlen (full_path) + 1) : 0));
246           p = ((char*) *slot) + sizeof (**slot);
247           strcpy (p, file);
248           (*slot)->name = p;
249           if (opened)
250             {
251               p += strlen (p) + 1;
252               strcpy (p, full_path);
253               (*slot)->full_path = p;
254             }
255           else
256             (*slot)->full_path = NULL;
257         }
258
259       if (opened)
260         free (full_path);
261
262       if (! opened)
263         {
264           /* We don't throw an error, the program is still debuggable.
265              Check in_hash_table to only print the warning once.  */
266           if (! in_hash_table)
267             warning (_("%s (referenced in %s): %s"),
268                      file, GDBPY_AUTO_SECTION_NAME, safe_strerror (errno));
269           continue;
270         }
271
272       /* If this file is not currently loaded, load it.  */
273       if (! in_hash_table)
274         source_python_script_for_objfile (objfile, stream, file);
275     }
276 }
277
278 /* Load scripts specified in section SECTION_NAME of OBJFILE.  */
279
280 static void
281 auto_load_section_scripts (struct objfile *objfile, const char *section_name)
282 {
283   bfd *abfd = objfile->obfd;
284   asection *scripts_sect;
285   bfd_size_type size;
286   char *p;
287   struct cleanup *cleanups;
288
289   scripts_sect = bfd_get_section_by_name (abfd, section_name);
290   if (scripts_sect == NULL)
291     return;
292
293   size = bfd_get_section_size (scripts_sect);
294   p = xmalloc (size);
295   
296   cleanups = make_cleanup (xfree, p);
297
298   if (bfd_get_section_contents (abfd, scripts_sect, p, (file_ptr) 0, size))
299     source_section_scripts (objfile, section_name, p, p + size);
300   else
301     warning (_("Couldn't read %s section of %s"),
302              section_name, bfd_get_filename (abfd));
303
304   do_cleanups (cleanups);
305 }
306
307 /* Clear the table of loaded section scripts.  */
308
309 static void
310 clear_section_scripts (void)
311 {
312   struct program_space *pspace = current_program_space;
313   struct auto_load_pspace_info *info;
314
315   info = program_space_data (pspace, auto_load_pspace_data);
316   if (info != NULL && info->loaded_scripts != NULL)
317     {
318       htab_delete (info->loaded_scripts);
319       info->loaded_scripts = NULL;
320     }
321 }
322
323 /* Look for the auto-load script associated with OBJFILE and load it.  */
324
325 static void
326 auto_load_objfile_script (struct objfile *objfile, const char *suffix)
327 {
328   char *realname;
329   char *filename, *debugfile;
330   int len;
331   FILE *input;
332   struct cleanup *cleanups;
333
334   realname = gdb_realpath (objfile->name);
335   len = strlen (realname);
336   filename = xmalloc (len + strlen (suffix) + 1);
337   memcpy (filename, realname, len);
338   strcpy (filename + len, suffix);
339
340   cleanups = make_cleanup (xfree, filename);
341   make_cleanup (xfree, realname);
342
343   input = fopen (filename, "r");
344   debugfile = filename;
345
346   if (!input && debug_file_directory)
347     {
348       /* Also try the same file in the separate debug info directory.  */
349       debugfile = xmalloc (strlen (filename)
350                            + strlen (debug_file_directory) + 1);
351       strcpy (debugfile, debug_file_directory);
352       /* FILENAME is absolute, so we don't need a "/" here.  */
353       strcat (debugfile, filename);
354
355       make_cleanup (xfree, debugfile);
356       input = fopen (debugfile, "r");
357     }
358
359   if (!input && gdb_datadir)
360     {
361       /* Also try the same file in a subdirectory of gdb's data
362          directory.  */
363       debugfile = xmalloc (strlen (gdb_datadir) + strlen (filename)
364                            + strlen ("/auto-load") + 1);
365       strcpy (debugfile, gdb_datadir);
366       strcat (debugfile, "/auto-load");
367       /* FILENAME is absolute, so we don't need a "/" here.  */
368       strcat (debugfile, filename);
369
370       make_cleanup (xfree, debugfile);
371       input = fopen (debugfile, "r");
372     }
373
374   if (input)
375     {
376       source_python_script_for_objfile (objfile, input, debugfile);
377       fclose (input);
378     }
379
380   do_cleanups (cleanups);
381 }
382
383 /* This is a new_objfile observer callback to auto-load scripts.
384
385    Two flavors of auto-loaded scripts are supported.
386    1) based on the path to the objfile
387    2) from .debug_gdb_scripts section  */
388
389 static void
390 auto_load_new_objfile (struct objfile *objfile)
391 {
392   if (!objfile)
393     {
394       /* OBJFILE is NULL when loading a new "main" symbol-file.  */
395       clear_section_scripts ();
396       return;
397     }
398   if (!objfile->name)
399     return;
400
401   load_auto_scripts_for_objfile (objfile);
402 }
403
404 /* Load any auto-loaded scripts for OBJFILE.  */
405
406 void
407 load_auto_scripts_for_objfile (struct objfile *objfile)
408 {
409   if (gdbpy_auto_load && gdbpy_global_auto_load)
410     {
411       auto_load_objfile_script (objfile, GDBPY_AUTO_FILE_NAME);
412       auto_load_section_scripts (objfile, GDBPY_AUTO_SECTION_NAME);
413     }
414 }
415 \f
416 /* Traversal function for htab_traverse.
417    Print the entry if specified in the regex.  */
418
419 static int
420 maybe_print_section_script (void **slot, void *info)
421 {
422   struct loaded_script_entry *entry = *slot;
423
424   if (re_exec (entry->name))
425     {
426       printf_filtered (_("Script name: %s\n"), entry->name);
427       printf_filtered (_("  Full name: %s\n"),
428                        entry->full_path ? entry->full_path : _("unknown"));
429     }
430
431   return 1;
432 }
433
434 /* "maint print section-scripts" command.  */
435
436 static void
437 maintenance_print_section_scripts (char *pattern, int from_tty)
438 {
439   struct auto_load_pspace_info *pspace_info;
440
441   dont_repeat ();
442
443   if (pattern && *pattern)
444     {
445       char *re_err = re_comp (pattern);
446
447       if (re_err)
448         error (_("Invalid regexp: %s"), re_err);
449
450       printf_filtered (_("Objfile scripts matching %s:\n"), pattern);
451     }
452   else
453     {
454       re_comp ("");
455       printf_filtered (_("Objfile scripts:\n"));
456     }
457
458   pspace_info = get_auto_load_pspace_data (current_program_space);
459   if (pspace_info == NULL || pspace_info->loaded_scripts == NULL)
460     return;
461
462   immediate_quit++;
463   htab_traverse_noresize (pspace_info->loaded_scripts,
464                           maybe_print_section_script, NULL);
465   immediate_quit--;
466 }
467 \f
468 void
469 gdbpy_initialize_auto_load (void)
470 {
471   auto_load_pspace_data
472     = register_program_space_data_with_cleanup (auto_load_pspace_data_cleanup);
473
474   observer_attach_new_objfile (auto_load_new_objfile);
475
476   add_setshow_boolean_cmd ("auto-load", class_maintenance,
477                            &gdbpy_auto_load, _("\
478 Enable or disable auto-loading of Python code when an object is opened."), _("\
479 Show whether Python code will be auto-loaded when an object is opened."), _("\
480 Enables or disables auto-loading of Python code when an object is opened."),
481                            NULL, NULL,
482                            &set_python_list,
483                            &show_python_list);
484
485   add_cmd ("section-scripts", class_maintenance, maintenance_print_section_scripts,
486            _("Print dump of auto-loaded section scripts matching REGEXP."),
487            &maintenanceprintlist);
488 }
489
490 #else /* ! HAVE_PYTHON */
491
492 void
493 load_auto_scripts_for_objfile (struct objfile *objfile)
494 {
495 }
496
497 #endif /* ! HAVE_PYTHON */