acd46da0881d4f25d2ac208ffab8e598e52ef716
[platform/upstream/binutils.git] / gdb / solib-frv.c
1 /* Handle FR-V (FDPIC) shared libraries for GDB, the GNU Debugger.
2    Copyright (C) 2004-2014 Free Software Foundation, Inc.
3
4    This file is part of GDB.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18
19
20 #include "defs.h"
21 #include <string.h>
22 #include "inferior.h"
23 #include "gdbcore.h"
24 #include "solib.h"
25 #include "solist.h"
26 #include "frv-tdep.h"
27 #include "objfiles.h"
28 #include "symtab.h"
29 #include "language.h"
30 #include "command.h"
31 #include "gdbcmd.h"
32 #include "elf/frv.h"
33 #include "exceptions.h"
34 #include "gdb_bfd.h"
35
36 /* Flag which indicates whether internal debug messages should be printed.  */
37 static unsigned int solib_frv_debug;
38
39 /* FR-V pointers are four bytes wide.  */
40 enum { FRV_PTR_SIZE = 4 };
41
42 /* Representation of loadmap and related structs for the FR-V FDPIC ABI.  */
43
44 /* External versions; the size and alignment of the fields should be
45    the same as those on the target.  When loaded, the placement of
46    the bits in each field will be the same as on the target.  */
47 typedef gdb_byte ext_Elf32_Half[2];
48 typedef gdb_byte ext_Elf32_Addr[4];
49 typedef gdb_byte ext_Elf32_Word[4];
50
51 struct ext_elf32_fdpic_loadseg
52 {
53   /* Core address to which the segment is mapped.  */
54   ext_Elf32_Addr addr;
55   /* VMA recorded in the program header.  */
56   ext_Elf32_Addr p_vaddr;
57   /* Size of this segment in memory.  */
58   ext_Elf32_Word p_memsz;
59 };
60
61 struct ext_elf32_fdpic_loadmap {
62   /* Protocol version number, must be zero.  */
63   ext_Elf32_Half version;
64   /* Number of segments in this map.  */
65   ext_Elf32_Half nsegs;
66   /* The actual memory map.  */
67   struct ext_elf32_fdpic_loadseg segs[1 /* nsegs, actually */];
68 };
69
70 /* Internal versions; the types are GDB types and the data in each
71    of the fields is (or will be) decoded from the external struct
72    for ease of consumption.  */
73 struct int_elf32_fdpic_loadseg
74 {
75   /* Core address to which the segment is mapped.  */
76   CORE_ADDR addr;
77   /* VMA recorded in the program header.  */
78   CORE_ADDR p_vaddr;
79   /* Size of this segment in memory.  */
80   long p_memsz;
81 };
82
83 struct int_elf32_fdpic_loadmap {
84   /* Protocol version number, must be zero.  */
85   int version;
86   /* Number of segments in this map.  */
87   int nsegs;
88   /* The actual memory map.  */
89   struct int_elf32_fdpic_loadseg segs[1 /* nsegs, actually */];
90 };
91
92 /* Given address LDMADDR, fetch and decode the loadmap at that address.
93    Return NULL if there is a problem reading the target memory or if
94    there doesn't appear to be a loadmap at the given address.  The
95    allocated space (representing the loadmap) returned by this
96    function may be freed via a single call to xfree().  */
97
98 static struct int_elf32_fdpic_loadmap *
99 fetch_loadmap (CORE_ADDR ldmaddr)
100 {
101   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
102   struct ext_elf32_fdpic_loadmap ext_ldmbuf_partial;
103   struct ext_elf32_fdpic_loadmap *ext_ldmbuf;
104   struct int_elf32_fdpic_loadmap *int_ldmbuf;
105   int ext_ldmbuf_size, int_ldmbuf_size;
106   int version, seg, nsegs;
107
108   /* Fetch initial portion of the loadmap.  */
109   if (target_read_memory (ldmaddr, (gdb_byte *) &ext_ldmbuf_partial,
110                           sizeof ext_ldmbuf_partial))
111     {
112       /* Problem reading the target's memory.  */
113       return NULL;
114     }
115
116   /* Extract the version.  */
117   version = extract_unsigned_integer (ext_ldmbuf_partial.version,
118                                       sizeof ext_ldmbuf_partial.version,
119                                       byte_order);
120   if (version != 0)
121     {
122       /* We only handle version 0.  */
123       return NULL;
124     }
125
126   /* Extract the number of segments.  */
127   nsegs = extract_unsigned_integer (ext_ldmbuf_partial.nsegs,
128                                     sizeof ext_ldmbuf_partial.nsegs,
129                                     byte_order);
130
131   if (nsegs <= 0)
132     return NULL;
133
134   /* Allocate space for the complete (external) loadmap.  */
135   ext_ldmbuf_size = sizeof (struct ext_elf32_fdpic_loadmap)
136                + (nsegs - 1) * sizeof (struct ext_elf32_fdpic_loadseg);
137   ext_ldmbuf = xmalloc (ext_ldmbuf_size);
138
139   /* Copy over the portion of the loadmap that's already been read.  */
140   memcpy (ext_ldmbuf, &ext_ldmbuf_partial, sizeof ext_ldmbuf_partial);
141
142   /* Read the rest of the loadmap from the target.  */
143   if (target_read_memory (ldmaddr + sizeof ext_ldmbuf_partial,
144                           (gdb_byte *) ext_ldmbuf + sizeof ext_ldmbuf_partial,
145                           ext_ldmbuf_size - sizeof ext_ldmbuf_partial))
146     {
147       /* Couldn't read rest of the loadmap.  */
148       xfree (ext_ldmbuf);
149       return NULL;
150     }
151
152   /* Allocate space into which to put information extract from the
153      external loadsegs.  I.e, allocate the internal loadsegs.  */
154   int_ldmbuf_size = sizeof (struct int_elf32_fdpic_loadmap)
155                + (nsegs - 1) * sizeof (struct int_elf32_fdpic_loadseg);
156   int_ldmbuf = xmalloc (int_ldmbuf_size);
157
158   /* Place extracted information in internal structs.  */
159   int_ldmbuf->version = version;
160   int_ldmbuf->nsegs = nsegs;
161   for (seg = 0; seg < nsegs; seg++)
162     {
163       int_ldmbuf->segs[seg].addr
164         = extract_unsigned_integer (ext_ldmbuf->segs[seg].addr,
165                                     sizeof (ext_ldmbuf->segs[seg].addr),
166                                     byte_order);
167       int_ldmbuf->segs[seg].p_vaddr
168         = extract_unsigned_integer (ext_ldmbuf->segs[seg].p_vaddr,
169                                     sizeof (ext_ldmbuf->segs[seg].p_vaddr),
170                                     byte_order);
171       int_ldmbuf->segs[seg].p_memsz
172         = extract_unsigned_integer (ext_ldmbuf->segs[seg].p_memsz,
173                                     sizeof (ext_ldmbuf->segs[seg].p_memsz),
174                                     byte_order);
175     }
176
177   xfree (ext_ldmbuf);
178   return int_ldmbuf;
179 }
180
181 /* External link_map and elf32_fdpic_loadaddr struct definitions.  */
182
183 typedef gdb_byte ext_ptr[4];
184
185 struct ext_elf32_fdpic_loadaddr
186 {
187   ext_ptr map;                  /* struct elf32_fdpic_loadmap *map; */
188   ext_ptr got_value;            /* void *got_value; */
189 };
190
191 struct ext_link_map
192 {
193   struct ext_elf32_fdpic_loadaddr l_addr;
194
195   /* Absolute file name object was found in.  */
196   ext_ptr l_name;               /* char *l_name; */
197
198   /* Dynamic section of the shared object.  */
199   ext_ptr l_ld;                 /* ElfW(Dyn) *l_ld; */
200
201   /* Chain of loaded objects.  */
202   ext_ptr l_next, l_prev;       /* struct link_map *l_next, *l_prev; */
203 };
204
205 /* Link map info to include in an allocated so_list entry.  */
206
207 struct lm_info
208   {
209     /* The loadmap, digested into an easier to use form.  */
210     struct int_elf32_fdpic_loadmap *map;
211     /* The GOT address for this link map entry.  */
212     CORE_ADDR got_value;
213     /* The link map address, needed for frv_fetch_objfile_link_map().  */
214     CORE_ADDR lm_addr;
215
216     /* Cached dynamic symbol table and dynamic relocs initialized and
217        used only by find_canonical_descriptor_in_load_object().
218
219        Note: kevinb/2004-02-26: It appears that calls to
220        bfd_canonicalize_dynamic_reloc() will use the same symbols as
221        those supplied to the first call to this function.  Therefore,
222        it's important to NOT free the asymbol ** data structure
223        supplied to the first call.  Thus the caching of the dynamic
224        symbols (dyn_syms) is critical for correct operation.  The
225        caching of the dynamic relocations could be dispensed with.  */
226     asymbol **dyn_syms;
227     arelent **dyn_relocs;
228     int dyn_reloc_count;        /* Number of dynamic relocs.  */
229
230   };
231
232 /* The load map, got value, etc. are not available from the chain
233    of loaded shared objects.  ``main_executable_lm_info'' provides
234    a way to get at this information so that it doesn't need to be
235    frequently recomputed.  Initialized by frv_relocate_main_executable().  */
236 static struct lm_info *main_executable_lm_info;
237
238 static void frv_relocate_main_executable (void);
239 static CORE_ADDR main_got (void);
240 static int enable_break2 (void);
241
242 /* Implement the "open_symbol_file_object" target_so_ops method.  */
243
244 static int
245 open_symbol_file_object (void *from_ttyp)
246 {
247   /* Unimplemented.  */
248   return 0;
249 }
250
251 /* Cached value for lm_base(), below.  */
252 static CORE_ADDR lm_base_cache = 0;
253
254 /* Link map address for main module.  */
255 static CORE_ADDR main_lm_addr = 0;
256
257 /* Return the address from which the link map chain may be found.  On
258    the FR-V, this may be found in a number of ways.  Assuming that the
259    main executable has already been relocated, the easiest way to find
260    this value is to look up the address of _GLOBAL_OFFSET_TABLE_.  A
261    pointer to the start of the link map will be located at the word found
262    at _GLOBAL_OFFSET_TABLE_ + 8.  (This is part of the dynamic linker
263    reserve area mandated by the ABI.)  */
264
265 static CORE_ADDR
266 lm_base (void)
267 {
268   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
269   struct minimal_symbol *got_sym;
270   CORE_ADDR addr;
271   gdb_byte buf[FRV_PTR_SIZE];
272
273   /* One of our assumptions is that the main executable has been relocated.
274      Bail out if this has not happened.  (Note that post_create_inferior()
275      in infcmd.c will call solib_add prior to solib_create_inferior_hook().
276      If we allow this to happen, lm_base_cache will be initialized with
277      a bogus value.  */
278   if (main_executable_lm_info == 0)
279     return 0;
280
281   /* If we already have a cached value, return it.  */
282   if (lm_base_cache)
283     return lm_base_cache;
284
285   got_sym = lookup_minimal_symbol ("_GLOBAL_OFFSET_TABLE_", NULL,
286                                    symfile_objfile);
287   if (got_sym == 0)
288     {
289       if (solib_frv_debug)
290         fprintf_unfiltered (gdb_stdlog,
291                             "lm_base: _GLOBAL_OFFSET_TABLE_ not found.\n");
292       return 0;
293     }
294
295   addr = MSYMBOL_VALUE_ADDRESS (got_sym) + 8;
296
297   if (solib_frv_debug)
298     fprintf_unfiltered (gdb_stdlog,
299                         "lm_base: _GLOBAL_OFFSET_TABLE_ + 8 = %s\n",
300                         hex_string_custom (addr, 8));
301
302   if (target_read_memory (addr, buf, sizeof buf) != 0)
303     return 0;
304   lm_base_cache = extract_unsigned_integer (buf, sizeof buf, byte_order);
305
306   if (solib_frv_debug)
307     fprintf_unfiltered (gdb_stdlog,
308                         "lm_base: lm_base_cache = %s\n",
309                         hex_string_custom (lm_base_cache, 8));
310
311   return lm_base_cache;
312 }
313
314
315 /* Implement the "current_sos" target_so_ops method.  */
316
317 static struct so_list *
318 frv_current_sos (void)
319 {
320   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
321   CORE_ADDR lm_addr, mgot;
322   struct so_list *sos_head = NULL;
323   struct so_list **sos_next_ptr = &sos_head;
324
325   /* Make sure that the main executable has been relocated.  This is
326      required in order to find the address of the global offset table,
327      which in turn is used to find the link map info.  (See lm_base()
328      for details.)
329
330      Note that the relocation of the main executable is also performed
331      by solib_create_inferior_hook(), however, in the case of core
332      files, this hook is called too late in order to be of benefit to
333      solib_add.  solib_add eventually calls this this function,
334      frv_current_sos, and also precedes the call to
335      solib_create_inferior_hook().   (See post_create_inferior() in
336      infcmd.c.)  */
337   if (main_executable_lm_info == 0 && core_bfd != NULL)
338     frv_relocate_main_executable ();
339
340   /* Fetch the GOT corresponding to the main executable.  */
341   mgot = main_got ();
342
343   /* Locate the address of the first link map struct.  */
344   lm_addr = lm_base ();
345
346   /* We have at least one link map entry.  Fetch the lot of them,
347      building the solist chain.  */
348   while (lm_addr)
349     {
350       struct ext_link_map lm_buf;
351       CORE_ADDR got_addr;
352
353       if (solib_frv_debug)
354         fprintf_unfiltered (gdb_stdlog,
355                             "current_sos: reading link_map entry at %s\n",
356                             hex_string_custom (lm_addr, 8));
357
358       if (target_read_memory (lm_addr, (gdb_byte *) &lm_buf,
359                               sizeof (lm_buf)) != 0)
360         {
361           warning (_("frv_current_sos: Unable to read link map entry.  "
362                      "Shared object chain may be incomplete."));
363           break;
364         }
365
366       got_addr
367         = extract_unsigned_integer (lm_buf.l_addr.got_value,
368                                     sizeof (lm_buf.l_addr.got_value),
369                                     byte_order);
370       /* If the got_addr is the same as mgotr, then we're looking at the
371          entry for the main executable.  By convention, we don't include
372          this in the list of shared objects.  */
373       if (got_addr != mgot)
374         {
375           int errcode;
376           char *name_buf;
377           struct int_elf32_fdpic_loadmap *loadmap;
378           struct so_list *sop;
379           CORE_ADDR addr;
380
381           /* Fetch the load map address.  */
382           addr = extract_unsigned_integer (lm_buf.l_addr.map,
383                                            sizeof lm_buf.l_addr.map,
384                                            byte_order);
385           loadmap = fetch_loadmap (addr);
386           if (loadmap == NULL)
387             {
388               warning (_("frv_current_sos: Unable to fetch load map.  "
389                          "Shared object chain may be incomplete."));
390               break;
391             }
392
393           sop = xcalloc (1, sizeof (struct so_list));
394           sop->lm_info = xcalloc (1, sizeof (struct lm_info));
395           sop->lm_info->map = loadmap;
396           sop->lm_info->got_value = got_addr;
397           sop->lm_info->lm_addr = lm_addr;
398           /* Fetch the name.  */
399           addr = extract_unsigned_integer (lm_buf.l_name,
400                                            sizeof (lm_buf.l_name),
401                                            byte_order);
402           target_read_string (addr, &name_buf, SO_NAME_MAX_PATH_SIZE - 1,
403                               &errcode);
404
405           if (solib_frv_debug)
406             fprintf_unfiltered (gdb_stdlog, "current_sos: name = %s\n",
407                                 name_buf);
408           
409           if (errcode != 0)
410             warning (_("Can't read pathname for link map entry: %s."),
411                      safe_strerror (errcode));
412           else
413             {
414               strncpy (sop->so_name, name_buf, SO_NAME_MAX_PATH_SIZE - 1);
415               sop->so_name[SO_NAME_MAX_PATH_SIZE - 1] = '\0';
416               xfree (name_buf);
417               strcpy (sop->so_original_name, sop->so_name);
418             }
419
420           *sos_next_ptr = sop;
421           sos_next_ptr = &sop->next;
422         }
423       else
424         {
425           main_lm_addr = lm_addr;
426         }
427
428       lm_addr = extract_unsigned_integer (lm_buf.l_next,
429                                           sizeof (lm_buf.l_next), byte_order);
430     }
431
432   enable_break2 ();
433
434   return sos_head;
435 }
436
437
438 /* Return 1 if PC lies in the dynamic symbol resolution code of the
439    run time loader.  */
440
441 static CORE_ADDR interp_text_sect_low;
442 static CORE_ADDR interp_text_sect_high;
443 static CORE_ADDR interp_plt_sect_low;
444 static CORE_ADDR interp_plt_sect_high;
445
446 static int
447 frv_in_dynsym_resolve_code (CORE_ADDR pc)
448 {
449   return ((pc >= interp_text_sect_low && pc < interp_text_sect_high)
450           || (pc >= interp_plt_sect_low && pc < interp_plt_sect_high)
451           || in_plt_section (pc));
452 }
453
454 /* Given a loadmap and an address, return the displacement needed
455    to relocate the address.  */
456
457 static CORE_ADDR
458 displacement_from_map (struct int_elf32_fdpic_loadmap *map,
459                        CORE_ADDR addr)
460 {
461   int seg;
462
463   for (seg = 0; seg < map->nsegs; seg++)
464     {
465       if (map->segs[seg].p_vaddr <= addr
466           && addr < map->segs[seg].p_vaddr + map->segs[seg].p_memsz)
467         {
468           return map->segs[seg].addr - map->segs[seg].p_vaddr;
469         }
470     }
471
472   return 0;
473 }
474
475 /* Print a warning about being unable to set the dynamic linker
476    breakpoint.  */
477
478 static void
479 enable_break_failure_warning (void)
480 {
481   warning (_("Unable to find dynamic linker breakpoint function.\n"
482            "GDB will be unable to debug shared library initializers\n"
483            "and track explicitly loaded dynamic code."));
484 }
485
486 /* Helper function for gdb_bfd_lookup_symbol.  */
487
488 static int
489 cmp_name (asymbol *sym, void *data)
490 {
491   return (strcmp (sym->name, (const char *) data) == 0);
492 }
493
494 /* Arrange for dynamic linker to hit breakpoint.
495
496    The dynamic linkers has, as part of its debugger interface, support
497    for arranging for the inferior to hit a breakpoint after mapping in
498    the shared libraries.  This function enables that breakpoint.
499
500    On the FR-V, using the shared library (FDPIC) ABI, the symbol
501    _dl_debug_addr points to the r_debug struct which contains
502    a field called r_brk.  r_brk is the address of the function
503    descriptor upon which a breakpoint must be placed.  Being a
504    function descriptor, we must extract the entry point in order
505    to set the breakpoint.
506
507    Our strategy will be to get the .interp section from the
508    executable.  This section will provide us with the name of the
509    interpreter.  We'll open the interpreter and then look up
510    the address of _dl_debug_addr.  We then relocate this address
511    using the interpreter's loadmap.  Once the relocated address
512    is known, we fetch the value (address) corresponding to r_brk
513    and then use that value to fetch the entry point of the function
514    we're interested in.  */
515
516 static int enable_break2_done = 0;
517
518 static int
519 enable_break2 (void)
520 {
521   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
522   int success = 0;
523   char **bkpt_namep;
524   asection *interp_sect;
525
526   if (enable_break2_done)
527     return 1;
528
529   interp_text_sect_low = interp_text_sect_high = 0;
530   interp_plt_sect_low = interp_plt_sect_high = 0;
531
532   /* Find the .interp section; if not found, warn the user and drop
533      into the old breakpoint at symbol code.  */
534   interp_sect = bfd_get_section_by_name (exec_bfd, ".interp");
535   if (interp_sect)
536     {
537       unsigned int interp_sect_size;
538       char *buf;
539       bfd *tmp_bfd = NULL;
540       int status;
541       CORE_ADDR addr, interp_loadmap_addr;
542       gdb_byte addr_buf[FRV_PTR_SIZE];
543       struct int_elf32_fdpic_loadmap *ldm;
544       volatile struct gdb_exception ex;
545
546       /* Read the contents of the .interp section into a local buffer;
547          the contents specify the dynamic linker this program uses.  */
548       interp_sect_size = bfd_section_size (exec_bfd, interp_sect);
549       buf = alloca (interp_sect_size);
550       bfd_get_section_contents (exec_bfd, interp_sect,
551                                 buf, 0, interp_sect_size);
552
553       /* Now we need to figure out where the dynamic linker was
554          loaded so that we can load its symbols and place a breakpoint
555          in the dynamic linker itself.
556
557          This address is stored on the stack.  However, I've been unable
558          to find any magic formula to find it for Solaris (appears to
559          be trivial on GNU/Linux).  Therefore, we have to try an alternate
560          mechanism to find the dynamic linker's base address.  */
561
562       TRY_CATCH (ex, RETURN_MASK_ALL)
563         {
564           tmp_bfd = solib_bfd_open (buf);
565         }
566       if (tmp_bfd == NULL)
567         {
568           enable_break_failure_warning ();
569           return 0;
570         }
571
572       status = frv_fdpic_loadmap_addresses (target_gdbarch (),
573                                             &interp_loadmap_addr, 0);
574       if (status < 0)
575         {
576           warning (_("Unable to determine dynamic linker loadmap address."));
577           enable_break_failure_warning ();
578           gdb_bfd_unref (tmp_bfd);
579           return 0;
580         }
581
582       if (solib_frv_debug)
583         fprintf_unfiltered (gdb_stdlog,
584                             "enable_break: interp_loadmap_addr = %s\n",
585                             hex_string_custom (interp_loadmap_addr, 8));
586
587       ldm = fetch_loadmap (interp_loadmap_addr);
588       if (ldm == NULL)
589         {
590           warning (_("Unable to load dynamic linker loadmap at address %s."),
591                    hex_string_custom (interp_loadmap_addr, 8));
592           enable_break_failure_warning ();
593           gdb_bfd_unref (tmp_bfd);
594           return 0;
595         }
596
597       /* Record the relocated start and end address of the dynamic linker
598          text and plt section for svr4_in_dynsym_resolve_code.  */
599       interp_sect = bfd_get_section_by_name (tmp_bfd, ".text");
600       if (interp_sect)
601         {
602           interp_text_sect_low
603             = bfd_section_vma (tmp_bfd, interp_sect);
604           interp_text_sect_low
605             += displacement_from_map (ldm, interp_text_sect_low);
606           interp_text_sect_high
607             = interp_text_sect_low + bfd_section_size (tmp_bfd, interp_sect);
608         }
609       interp_sect = bfd_get_section_by_name (tmp_bfd, ".plt");
610       if (interp_sect)
611         {
612           interp_plt_sect_low =
613             bfd_section_vma (tmp_bfd, interp_sect);
614           interp_plt_sect_low
615             += displacement_from_map (ldm, interp_plt_sect_low);
616           interp_plt_sect_high =
617             interp_plt_sect_low + bfd_section_size (tmp_bfd, interp_sect);
618         }
619
620       addr = gdb_bfd_lookup_symbol (tmp_bfd, cmp_name, "_dl_debug_addr");
621
622       if (addr == 0)
623         {
624           warning (_("Could not find symbol _dl_debug_addr "
625                      "in dynamic linker"));
626           enable_break_failure_warning ();
627           gdb_bfd_unref (tmp_bfd);
628           return 0;
629         }
630
631       if (solib_frv_debug)
632         fprintf_unfiltered (gdb_stdlog,
633                             "enable_break: _dl_debug_addr "
634                             "(prior to relocation) = %s\n",
635                             hex_string_custom (addr, 8));
636
637       addr += displacement_from_map (ldm, addr);
638
639       if (solib_frv_debug)
640         fprintf_unfiltered (gdb_stdlog,
641                             "enable_break: _dl_debug_addr "
642                             "(after relocation) = %s\n",
643                             hex_string_custom (addr, 8));
644
645       /* Fetch the address of the r_debug struct.  */
646       if (target_read_memory (addr, addr_buf, sizeof addr_buf) != 0)
647         {
648           warning (_("Unable to fetch contents of _dl_debug_addr "
649                      "(at address %s) from dynamic linker"),
650                    hex_string_custom (addr, 8));
651         }
652       addr = extract_unsigned_integer (addr_buf, sizeof addr_buf, byte_order);
653
654       if (solib_frv_debug)
655         fprintf_unfiltered (gdb_stdlog,
656                             "enable_break: _dl_debug_addr[0..3] = %s\n",
657                             hex_string_custom (addr, 8));
658
659       /* If it's zero, then the ldso hasn't initialized yet, and so
660          there are no shared libs yet loaded.  */
661       if (addr == 0)
662         {
663           if (solib_frv_debug)
664             fprintf_unfiltered (gdb_stdlog,
665                                 "enable_break: ldso not yet initialized\n");
666           /* Do not warn, but mark to run again.  */
667           return 0;
668         }
669
670       /* Fetch the r_brk field.  It's 8 bytes from the start of
671          _dl_debug_addr.  */
672       if (target_read_memory (addr + 8, addr_buf, sizeof addr_buf) != 0)
673         {
674           warning (_("Unable to fetch _dl_debug_addr->r_brk "
675                      "(at address %s) from dynamic linker"),
676                    hex_string_custom (addr + 8, 8));
677           enable_break_failure_warning ();
678           gdb_bfd_unref (tmp_bfd);
679           return 0;
680         }
681       addr = extract_unsigned_integer (addr_buf, sizeof addr_buf, byte_order);
682
683       /* Now fetch the function entry point.  */
684       if (target_read_memory (addr, addr_buf, sizeof addr_buf) != 0)
685         {
686           warning (_("Unable to fetch _dl_debug_addr->.r_brk entry point "
687                      "(at address %s) from dynamic linker"),
688                    hex_string_custom (addr, 8));
689           enable_break_failure_warning ();
690           gdb_bfd_unref (tmp_bfd);
691           return 0;
692         }
693       addr = extract_unsigned_integer (addr_buf, sizeof addr_buf, byte_order);
694
695       /* We're done with the temporary bfd.  */
696       gdb_bfd_unref (tmp_bfd);
697
698       /* We're also done with the loadmap.  */
699       xfree (ldm);
700
701       /* Remove all the solib event breakpoints.  Their addresses
702          may have changed since the last time we ran the program.  */
703       remove_solib_event_breakpoints ();
704
705       /* Now (finally!) create the solib breakpoint.  */
706       create_solib_event_breakpoint (target_gdbarch (), addr);
707
708       enable_break2_done = 1;
709
710       return 1;
711     }
712
713   /* Tell the user we couldn't set a dynamic linker breakpoint.  */
714   enable_break_failure_warning ();
715
716   /* Failure return.  */
717   return 0;
718 }
719
720 static int
721 enable_break (void)
722 {
723   asection *interp_sect;
724   CORE_ADDR entry_point;
725
726   if (symfile_objfile == NULL)
727     {
728       if (solib_frv_debug)
729         fprintf_unfiltered (gdb_stdlog,
730                             "enable_break: No symbol file found.\n");
731       return 0;
732     }
733
734   if (!entry_point_address_query (&entry_point))
735     {
736       if (solib_frv_debug)
737         fprintf_unfiltered (gdb_stdlog,
738                             "enable_break: Symbol file has no entry point.\n");
739       return 0;
740     }
741
742   /* Check for the presence of a .interp section.  If there is no
743      such section, the executable is statically linked.  */
744
745   interp_sect = bfd_get_section_by_name (exec_bfd, ".interp");
746
747   if (interp_sect == NULL)
748     {
749       if (solib_frv_debug)
750         fprintf_unfiltered (gdb_stdlog,
751                             "enable_break: No .interp section found.\n");
752       return 0;
753     }
754
755   create_solib_event_breakpoint (target_gdbarch (), entry_point);
756
757   if (solib_frv_debug)
758     fprintf_unfiltered (gdb_stdlog,
759                         "enable_break: solib event breakpoint "
760                         "placed at entry point: %s\n",
761                         hex_string_custom (entry_point, 8));
762   return 1;
763 }
764
765 /* Implement the "special_symbol_handling" target_so_ops method.  */
766
767 static void
768 frv_special_symbol_handling (void)
769 {
770   /* Nothing needed for FRV.  */
771 }
772
773 static void
774 frv_relocate_main_executable (void)
775 {
776   int status;
777   CORE_ADDR exec_addr, interp_addr;
778   struct int_elf32_fdpic_loadmap *ldm;
779   struct cleanup *old_chain;
780   struct section_offsets *new_offsets;
781   int changed;
782   struct obj_section *osect;
783
784   status = frv_fdpic_loadmap_addresses (target_gdbarch (),
785                                         &interp_addr, &exec_addr);
786
787   if (status < 0 || (exec_addr == 0 && interp_addr == 0))
788     {
789       /* Not using FDPIC ABI, so do nothing.  */
790       return;
791     }
792
793   /* Fetch the loadmap located at ``exec_addr''.  */
794   ldm = fetch_loadmap (exec_addr);
795   if (ldm == NULL)
796     error (_("Unable to load the executable's loadmap."));
797
798   if (main_executable_lm_info)
799     xfree (main_executable_lm_info);
800   main_executable_lm_info = xcalloc (1, sizeof (struct lm_info));
801   main_executable_lm_info->map = ldm;
802
803   new_offsets = xcalloc (symfile_objfile->num_sections,
804                          sizeof (struct section_offsets));
805   old_chain = make_cleanup (xfree, new_offsets);
806   changed = 0;
807
808   ALL_OBJFILE_OSECTIONS (symfile_objfile, osect)
809     {
810       CORE_ADDR orig_addr, addr, offset;
811       int osect_idx;
812       int seg;
813       
814       osect_idx = osect - symfile_objfile->sections;
815
816       /* Current address of section.  */
817       addr = obj_section_addr (osect);
818       /* Offset from where this section started.  */
819       offset = ANOFFSET (symfile_objfile->section_offsets, osect_idx);
820       /* Original address prior to any past relocations.  */
821       orig_addr = addr - offset;
822
823       for (seg = 0; seg < ldm->nsegs; seg++)
824         {
825           if (ldm->segs[seg].p_vaddr <= orig_addr
826               && orig_addr < ldm->segs[seg].p_vaddr + ldm->segs[seg].p_memsz)
827             {
828               new_offsets->offsets[osect_idx]
829                 = ldm->segs[seg].addr - ldm->segs[seg].p_vaddr;
830
831               if (new_offsets->offsets[osect_idx] != offset)
832                 changed = 1;
833               break;
834             }
835         }
836     }
837
838   if (changed)
839     objfile_relocate (symfile_objfile, new_offsets);
840
841   do_cleanups (old_chain);
842
843   /* Now that symfile_objfile has been relocated, we can compute the
844      GOT value and stash it away.  */
845   main_executable_lm_info->got_value = main_got ();
846 }
847
848 /* Implement the "create_inferior_hook" target_solib_ops method.
849
850    For the FR-V shared library ABI (FDPIC), the main executable needs
851    to be relocated.  The shared library breakpoints also need to be
852    enabled.  */
853
854 static void
855 frv_solib_create_inferior_hook (int from_tty)
856 {
857   /* Relocate main executable.  */
858   frv_relocate_main_executable ();
859
860   /* Enable shared library breakpoints.  */
861   if (!enable_break ())
862     {
863       warning (_("shared library handler failed to enable breakpoint"));
864       return;
865     }
866 }
867
868 static void
869 frv_clear_solib (void)
870 {
871   lm_base_cache = 0;
872   enable_break2_done = 0;
873   main_lm_addr = 0;
874   if (main_executable_lm_info != 0)
875     {
876       xfree (main_executable_lm_info->map);
877       xfree (main_executable_lm_info->dyn_syms);
878       xfree (main_executable_lm_info->dyn_relocs);
879       xfree (main_executable_lm_info);
880       main_executable_lm_info = 0;
881     }
882 }
883
884 static void
885 frv_free_so (struct so_list *so)
886 {
887   xfree (so->lm_info->map);
888   xfree (so->lm_info->dyn_syms);
889   xfree (so->lm_info->dyn_relocs);
890   xfree (so->lm_info);
891 }
892
893 static void
894 frv_relocate_section_addresses (struct so_list *so,
895                                  struct target_section *sec)
896 {
897   int seg;
898   struct int_elf32_fdpic_loadmap *map;
899
900   map = so->lm_info->map;
901
902   for (seg = 0; seg < map->nsegs; seg++)
903     {
904       if (map->segs[seg].p_vaddr <= sec->addr
905           && sec->addr < map->segs[seg].p_vaddr + map->segs[seg].p_memsz)
906         {
907           CORE_ADDR displ = map->segs[seg].addr - map->segs[seg].p_vaddr;
908
909           sec->addr += displ;
910           sec->endaddr += displ;
911           break;
912         }
913     }
914 }
915
916 /* Return the GOT address associated with the main executable.  Return
917    0 if it can't be found.  */
918
919 static CORE_ADDR
920 main_got (void)
921 {
922   struct minimal_symbol *got_sym;
923
924   got_sym = lookup_minimal_symbol ("_GLOBAL_OFFSET_TABLE_",
925                                    NULL, symfile_objfile);
926   if (got_sym == 0)
927     return 0;
928
929   return MSYMBOL_VALUE_ADDRESS (got_sym);
930 }
931
932 /* Find the global pointer for the given function address ADDR.  */
933
934 CORE_ADDR
935 frv_fdpic_find_global_pointer (CORE_ADDR addr)
936 {
937   struct so_list *so;
938
939   so = master_so_list ();
940   while (so)
941     {
942       int seg;
943       struct int_elf32_fdpic_loadmap *map;
944
945       map = so->lm_info->map;
946
947       for (seg = 0; seg < map->nsegs; seg++)
948         {
949           if (map->segs[seg].addr <= addr
950               && addr < map->segs[seg].addr + map->segs[seg].p_memsz)
951             return so->lm_info->got_value;
952         }
953
954       so = so->next;
955     }
956
957   /* Didn't find it in any of the shared objects.  So assume it's in the
958      main executable.  */
959   return main_got ();
960 }
961
962 /* Forward declarations for frv_fdpic_find_canonical_descriptor().  */
963 static CORE_ADDR find_canonical_descriptor_in_load_object
964   (CORE_ADDR, CORE_ADDR, const char *, bfd *, struct lm_info *);
965
966 /* Given a function entry point, attempt to find the canonical descriptor
967    associated with that entry point.  Return 0 if no canonical descriptor
968    could be found.  */
969
970 CORE_ADDR
971 frv_fdpic_find_canonical_descriptor (CORE_ADDR entry_point)
972 {
973   const char *name;
974   CORE_ADDR addr;
975   CORE_ADDR got_value;
976   struct int_elf32_fdpic_loadmap *ldm = 0;
977   struct symbol *sym;
978
979   /* Fetch the corresponding global pointer for the entry point.  */
980   got_value = frv_fdpic_find_global_pointer (entry_point);
981
982   /* Attempt to find the name of the function.  If the name is available,
983      it'll be used as an aid in finding matching functions in the dynamic
984      symbol table.  */
985   sym = find_pc_function (entry_point);
986   if (sym == 0)
987     name = 0;
988   else
989     name = SYMBOL_LINKAGE_NAME (sym);
990
991   /* Check the main executable.  */
992   addr = find_canonical_descriptor_in_load_object
993            (entry_point, got_value, name, symfile_objfile->obfd,
994             main_executable_lm_info);
995
996   /* If descriptor not found via main executable, check each load object
997      in list of shared objects.  */
998   if (addr == 0)
999     {
1000       struct so_list *so;
1001
1002       so = master_so_list ();
1003       while (so)
1004         {
1005           addr = find_canonical_descriptor_in_load_object
1006                    (entry_point, got_value, name, so->abfd, so->lm_info);
1007
1008           if (addr != 0)
1009             break;
1010
1011           so = so->next;
1012         }
1013     }
1014
1015   return addr;
1016 }
1017
1018 static CORE_ADDR
1019 find_canonical_descriptor_in_load_object
1020   (CORE_ADDR entry_point, CORE_ADDR got_value, const char *name, bfd *abfd,
1021    struct lm_info *lm)
1022 {
1023   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
1024   arelent *rel;
1025   unsigned int i;
1026   CORE_ADDR addr = 0;
1027
1028   /* Nothing to do if no bfd.  */
1029   if (abfd == 0)
1030     return 0;
1031
1032   /* Nothing to do if no link map.  */
1033   if (lm == 0)
1034     return 0;
1035
1036   /* We want to scan the dynamic relocs for R_FRV_FUNCDESC relocations.
1037      (More about this later.)  But in order to fetch the relocs, we
1038      need to first fetch the dynamic symbols.  These symbols need to
1039      be cached due to the way that bfd_canonicalize_dynamic_reloc()
1040      works.  (See the comments in the declaration of struct lm_info
1041      for more information.)  */
1042   if (lm->dyn_syms == NULL)
1043     {
1044       long storage_needed;
1045       unsigned int number_of_symbols;
1046
1047       /* Determine amount of space needed to hold the dynamic symbol table.  */
1048       storage_needed = bfd_get_dynamic_symtab_upper_bound (abfd);
1049
1050       /* If there are no dynamic symbols, there's nothing to do.  */
1051       if (storage_needed <= 0)
1052         return 0;
1053
1054       /* Allocate space for the dynamic symbol table.  */
1055       lm->dyn_syms = (asymbol **) xmalloc (storage_needed);
1056
1057       /* Fetch the dynamic symbol table.  */
1058       number_of_symbols = bfd_canonicalize_dynamic_symtab (abfd, lm->dyn_syms);
1059
1060       if (number_of_symbols == 0)
1061         return 0;
1062     }
1063
1064   /* Fetch the dynamic relocations if not already cached.  */
1065   if (lm->dyn_relocs == NULL)
1066     {
1067       long storage_needed;
1068
1069       /* Determine amount of space needed to hold the dynamic relocs.  */
1070       storage_needed = bfd_get_dynamic_reloc_upper_bound (abfd);
1071
1072       /* Bail out if there are no dynamic relocs.  */
1073       if (storage_needed <= 0)
1074         return 0;
1075
1076       /* Allocate space for the relocs.  */
1077       lm->dyn_relocs = (arelent **) xmalloc (storage_needed);
1078
1079       /* Fetch the dynamic relocs.  */
1080       lm->dyn_reloc_count 
1081         = bfd_canonicalize_dynamic_reloc (abfd, lm->dyn_relocs, lm->dyn_syms);
1082     }
1083
1084   /* Search the dynamic relocs.  */
1085   for (i = 0; i < lm->dyn_reloc_count; i++)
1086     {
1087       rel = lm->dyn_relocs[i];
1088
1089       /* Relocs of interest are those which meet the following
1090          criteria:
1091
1092            - the names match (assuming the caller could provide
1093              a name which matches ``entry_point'').
1094            - the relocation type must be R_FRV_FUNCDESC.  Relocs
1095              of this type are used (by the dynamic linker) to
1096              look up the address of a canonical descriptor (allocating
1097              it if need be) and initializing the GOT entry referred
1098              to by the offset to the address of the descriptor.
1099
1100          These relocs of interest may be used to obtain a
1101          candidate descriptor by first adjusting the reloc's
1102          address according to the link map and then dereferencing
1103          this address (which is a GOT entry) to obtain a descriptor
1104          address.  */
1105       if ((name == 0 || strcmp (name, (*rel->sym_ptr_ptr)->name) == 0)
1106           && rel->howto->type == R_FRV_FUNCDESC)
1107         {
1108           gdb_byte buf [FRV_PTR_SIZE];
1109
1110           /* Compute address of address of candidate descriptor.  */
1111           addr = rel->address + displacement_from_map (lm->map, rel->address);
1112
1113           /* Fetch address of candidate descriptor.  */
1114           if (target_read_memory (addr, buf, sizeof buf) != 0)
1115             continue;
1116           addr = extract_unsigned_integer (buf, sizeof buf, byte_order);
1117
1118           /* Check for matching entry point.  */
1119           if (target_read_memory (addr, buf, sizeof buf) != 0)
1120             continue;
1121           if (extract_unsigned_integer (buf, sizeof buf, byte_order)
1122               != entry_point)
1123             continue;
1124
1125           /* Check for matching got value.  */
1126           if (target_read_memory (addr + 4, buf, sizeof buf) != 0)
1127             continue;
1128           if (extract_unsigned_integer (buf, sizeof buf, byte_order)
1129               != got_value)
1130             continue;
1131
1132           /* Match was successful!  Exit loop.  */
1133           break;
1134         }
1135     }
1136
1137   return addr;
1138 }
1139
1140 /* Given an objfile, return the address of its link map.  This value is
1141    needed for TLS support.  */
1142 CORE_ADDR
1143 frv_fetch_objfile_link_map (struct objfile *objfile)
1144 {
1145   struct so_list *so;
1146
1147   /* Cause frv_current_sos() to be run if it hasn't been already.  */
1148   if (main_lm_addr == 0)
1149     solib_add (0, 0, 0, 1);
1150
1151   /* frv_current_sos() will set main_lm_addr for the main executable.  */
1152   if (objfile == symfile_objfile)
1153     return main_lm_addr;
1154
1155   /* The other link map addresses may be found by examining the list
1156      of shared libraries.  */
1157   for (so = master_so_list (); so; so = so->next)
1158     {
1159       if (so->objfile == objfile)
1160         return so->lm_info->lm_addr;
1161     }
1162
1163   /* Not found!  */
1164   return 0;
1165 }
1166
1167 struct target_so_ops frv_so_ops;
1168
1169 /* Provide a prototype to silence -Wmissing-prototypes.  */
1170 extern initialize_file_ftype _initialize_frv_solib;
1171
1172 void
1173 _initialize_frv_solib (void)
1174 {
1175   frv_so_ops.relocate_section_addresses = frv_relocate_section_addresses;
1176   frv_so_ops.free_so = frv_free_so;
1177   frv_so_ops.clear_solib = frv_clear_solib;
1178   frv_so_ops.solib_create_inferior_hook = frv_solib_create_inferior_hook;
1179   frv_so_ops.special_symbol_handling = frv_special_symbol_handling;
1180   frv_so_ops.current_sos = frv_current_sos;
1181   frv_so_ops.open_symbol_file_object = open_symbol_file_object;
1182   frv_so_ops.in_dynsym_resolve_code = frv_in_dynsym_resolve_code;
1183   frv_so_ops.bfd_open = solib_bfd_open;
1184
1185   /* Debug this file's internals.  */
1186   add_setshow_zuinteger_cmd ("solib-frv", class_maintenance,
1187                              &solib_frv_debug, _("\
1188 Set internal debugging of shared library code for FR-V."), _("\
1189 Show internal debugging of shared library code for FR-V."), _("\
1190 When non-zero, FR-V solib specific internal debugging is enabled."),
1191                              NULL,
1192                              NULL, /* FIXME: i18n: */
1193                              &setdebuglist, &showdebuglist);
1194 }