1/* Handle OSF/1, Digital UNIX, and Tru64 shared libraries
2   for GDB, the GNU Debugger.
3   Copyright (C) 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, 2007
4   Free Software Foundation, Inc.
5
6   This file is part of GDB.
7
8   This program is free software; you can redistribute it and/or modify
9   it under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 3 of the License, or
11   (at your option) any later version.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21/* When handling shared libraries, GDB has to find out the pathnames
22   of all shared libraries that are currently loaded (to read in their
23   symbols) and where the shared libraries are loaded in memory
24   (to relocate them properly from their prelinked addresses to the
25   current load address).
26
27   Under OSF/1 there are two possibilities to get at this information:
28
29   1) Peek around in the runtime loader structures.
30   These are not documented, and they are not defined in the system
31   header files. The definitions below were obtained by experimentation,
32   but they seem stable enough.
33
34   2) Use the libxproc.a library, which contains the equivalent ldr_*
35   routines.  The library is documented in Tru64 5.x, but as of 5.1, it
36   only allows a process to examine itself.  On earlier versions, it
37   may require that the GDB executable be dynamically linked and that
38   NAT_CLIBS include -lxproc -Wl,-expect_unresolved,ldr_process_context
39   for GDB and all applications that are using libgdb.
40
41   We will use the peeking approach until libxproc.a works for other
42   processes.  */
43
44#include "defs.h"
45
46#include <sys/types.h>
47#include <signal.h>
48#include "gdb_string.h"
49
50#include "bfd.h"
51#include "symtab.h"
52#include "symfile.h"
53#include "objfiles.h"
54#include "target.h"
55#include "inferior.h"
56#include "solist.h"
57
58#ifdef USE_LDR_ROUTINES
59# include <loader.h>
60#endif
61
62#ifndef USE_LDR_ROUTINES
63/* Definition of runtime loader structures, found by experimentation.  */
64#define RLD_CONTEXT_ADDRESS	0x3ffc0000000
65
66/* Per-module information structure referenced by ldr_context_t.head.  */
67
68typedef struct
69  {
70    CORE_ADDR next;
71    CORE_ADDR previous;
72    CORE_ADDR unknown1;
73    CORE_ADDR module_name;
74    CORE_ADDR modinfo_addr;	/* used by next_link_map_member() to detect
75				   the end of the shared module list */
76    long module_id;
77    CORE_ADDR unknown2;
78    CORE_ADDR unknown3;
79    long region_count;
80    CORE_ADDR regioninfo_addr;
81  }
82ldr_module_info_t;
83
84/* Per-region structure referenced by ldr_module_info_t.regioninfo_addr.  */
85
86typedef struct
87  {
88    long unknown1;
89    CORE_ADDR regionname_addr;
90    long protection;
91    CORE_ADDR vaddr;
92    CORE_ADDR mapaddr;
93    long size;
94    long unknown2[5];
95  }
96ldr_region_info_t;
97
98/* Structure at RLD_CONTEXT_ADDRESS specifying the start and finish addresses
99   of the shared module list.  */
100
101typedef struct
102  {
103    CORE_ADDR unknown1;
104    CORE_ADDR unknown2;
105    CORE_ADDR head;
106    CORE_ADDR tail;
107  }
108ldr_context_t;
109#endif   /* !USE_LDR_ROUTINES */
110
111/* Per-section information, stored in struct lm_info.secs.  */
112
113struct lm_sec
114  {
115    CORE_ADDR offset;		/* difference between default and actual
116				   virtual addresses of section .name */
117    CORE_ADDR nameaddr;		/* address in inferior of section name */
118    const char *name;		/* name of section, null if not fetched */
119  };
120
121/* Per-module information, stored in struct so_list.lm_info.  */
122
123struct lm_info
124  {
125    int isloader;		/* whether the module is /sbin/loader */
126    int nsecs;			/* length of .secs */
127    struct lm_sec secs[1];	/* variable-length array of sections, sorted
128				   by name */
129  };
130
131/* Context for iterating through the inferior's shared module list.  */
132
133struct read_map_ctxt
134  {
135#ifdef USE_LDR_ROUTINES
136    ldr_process_t proc;
137    ldr_module_t next;
138#else
139    CORE_ADDR next;		/* next element in module list */
140    CORE_ADDR tail;		/* last element in module list */
141#endif
142  };
143
144/* Forward declaration for this module's autoinit function.  */
145
146extern void _initialize_osf_solib (void);
147
148#ifdef USE_LDR_ROUTINES
149# if 0
150/* This routine is intended to be called by ldr_* routines to read memory from
151   the current target.  Usage:
152
153     ldr_process = ldr_core_process ();
154     ldr_set_core_reader (ldr_read_memory);
155     ldr_xdetach (ldr_process);
156     ldr_xattach (ldr_process);
157
158   ldr_core_process() and ldr_read_memory() are neither documented nor
159   declared in system header files.  They work with OSF/1 2.x, and they might
160   work with later versions as well.  */
161
162static int
163ldr_read_memory (CORE_ADDR memaddr, char *myaddr, int len, int readstring)
164{
165  int result;
166  char *buffer;
167
168  if (readstring)
169    {
170      target_read_string (memaddr, &buffer, len, &result);
171      if (result == 0)
172	strcpy (myaddr, buffer);
173      xfree (buffer);
174    }
175  else
176    result = target_read_memory (memaddr, myaddr, len);
177
178  if (result != 0)
179    result = -result;
180  return result;
181}
182# endif   /* 0 */
183#endif   /* USE_LDR_ROUTINES */
184
185/* Comparison for qsort() and bsearch(): return -1, 0, or 1 according to
186   whether lm_sec *P1's name is lexically less than, equal to, or greater
187   than that of *P2.  */
188
189static int
190lm_sec_cmp (const void *p1, const void *p2)
191{
192  const struct lm_sec *lms1 = p1, *lms2 = p2;
193  return strcmp (lms1->name, lms2->name);
194}
195
196/* Sort LMI->secs so that osf_relocate_section_addresses() can binary-search
197   it.  */
198
199static void
200lm_secs_sort (struct lm_info *lmi)
201{
202  qsort (lmi->secs, lmi->nsecs, sizeof *lmi->secs, lm_sec_cmp);
203}
204
205/* Populate name fields of LMI->secs.  */
206
207static void
208fetch_sec_names (struct lm_info *lmi)
209{
210#ifndef USE_LDR_ROUTINES
211  int i, errcode;
212  struct lm_sec *lms;
213  char *name;
214
215  for (i = 0; i < lmi->nsecs; i++)
216    {
217      lms = lmi->secs + i;
218      target_read_string (lms->nameaddr, &name, PATH_MAX, &errcode);
219      if (errcode != 0)
220	{
221	  warning (_("unable to read shared sec name at 0x%lx"), lms->nameaddr);
222	  name = xstrdup ("");
223	}
224      lms->name = name;
225    }
226  lm_secs_sort (lmi);
227#endif
228}
229
230/* target_so_ops callback.  Adjust SEC's addresses after it's been mapped into
231   the process.  */
232
233static void
234osf_relocate_section_addresses (struct so_list *so,
235				struct section_table *sec)
236{
237  struct lm_info *lmi;
238  struct lm_sec lms_key, *lms;
239
240  /* Fetch SO's section names if we haven't done so already.  */
241  lmi = so->lm_info;
242  if (lmi->nsecs && !lmi->secs[0].name)
243    fetch_sec_names (lmi);
244
245  /* Binary-search for offset information corresponding to SEC.  */
246  lms_key.name = sec->the_bfd_section->name;
247  lms = bsearch (&lms_key, lmi->secs, lmi->nsecs, sizeof *lms, lm_sec_cmp);
248  if (lms)
249    {
250      sec->addr += lms->offset;
251      sec->endaddr += lms->offset;
252    }
253}
254
255/* target_so_ops callback.  Free parts of SO allocated by this file.  */
256
257static void
258osf_free_so (struct so_list *so)
259{
260  int i;
261  const char *name;
262
263  for (i = 0; i < so->lm_info->nsecs; i++)
264    {
265      name = so->lm_info->secs[i].name;
266      if (name)
267	xfree ((void *) name);
268    }
269  xfree (so->lm_info);
270}
271
272/* target_so_ops callback.  Discard information accumulated by this file and
273   not freed by osf_free_so().  */
274
275static void
276osf_clear_solib (void)
277{
278  return;
279}
280
281/* target_so_ops callback.  Prepare to handle shared libraries after the
282   inferior process has been created but before it's executed any
283   instructions.
284
285   For a statically bound executable, the inferior's first instruction is the
286   one at "_start", or a similar text label. No further processing is needed
287   in that case.
288
289   For a dynamically bound executable, this first instruction is somewhere
290   in the rld, and the actual user executable is not yet mapped in.
291   We continue the inferior again, rld then maps in the actual user
292   executable and any needed shared libraries and then sends
293   itself a SIGTRAP.
294
295   At that point we discover the names of all shared libraries and
296   read their symbols in.
297
298   FIXME
299
300   This code does not properly handle hitting breakpoints which the
301   user might have set in the rld itself.  Proper handling would have
302   to check if the SIGTRAP happened due to a kill call.
303
304   Also, what if child has exit()ed?  Must exit loop somehow.  */
305
306static void
307osf_solib_create_inferior_hook (void)
308{
309  /* Nothing to do for statically bound executables.  */
310
311  if (symfile_objfile == NULL
312      || symfile_objfile->obfd == NULL
313      || ((bfd_get_file_flags (symfile_objfile->obfd) & DYNAMIC) == 0))
314    return;
315
316  /* Now run the target.  It will eventually get a SIGTRAP, at
317     which point all of the libraries will have been mapped in and we
318     can go groveling around in the rld structures to find
319     out what we need to know about them. */
320
321  clear_proceed_status ();
322  stop_soon = STOP_QUIETLY;
323  stop_signal = TARGET_SIGNAL_0;
324  do
325    {
326      target_resume (minus_one_ptid, 0, stop_signal);
327      wait_for_inferior ();
328    }
329  while (stop_signal != TARGET_SIGNAL_TRAP);
330
331  /*  solib_add will call reinit_frame_cache.
332     But we are stopped in the runtime loader and we do not have symbols
333     for the runtime loader. So heuristic_proc_start will be called
334     and will put out an annoying warning.
335     Delaying the resetting of stop_soon until after symbol loading
336     suppresses the warning.  */
337  solib_add ((char *) 0, 0, (struct target_ops *) 0, auto_solib_add);
338  stop_soon = NO_STOP_QUIETLY;
339
340  /* Enable breakpoints disabled (unnecessarily) by clear_solib().  */
341  re_enable_breakpoints_in_shlibs ();
342}
343
344/* target_so_ops callback.  Do additional symbol handling, lookup, etc. after
345   symbols for a shared object have been loaded.  */
346
347static void
348osf_special_symbol_handling (void)
349{
350  return;
351}
352
353/* Initialize CTXT in preparation for iterating through the inferior's module
354   list using read_map().  Return success.  */
355
356static int
357open_map (struct read_map_ctxt *ctxt)
358{
359#ifdef USE_LDR_ROUTINES
360  /* Note: As originally written, ldr_my_process() was used to obtain
361     the value for ctxt->proc.  This is incorrect, however, since
362     ldr_my_process() retrieves the "unique identifier" associated
363     with the current process (i.e. GDB) and not the one being
364     debugged.  Presumably, the pid of the process being debugged is
365     compatible with the "unique identifier" used by the ldr_
366     routines, so we use that.  */
367  ctxt->proc = ptid_get_pid (inferior_ptid);
368  if (ldr_xattach (ctxt->proc) != 0)
369    return 0;
370  ctxt->next = LDR_NULL_MODULE;
371#else
372  CORE_ADDR ldr_context_addr, prev, next;
373  ldr_context_t ldr_context;
374
375  if (target_read_memory ((CORE_ADDR) RLD_CONTEXT_ADDRESS,
376			  (char *) &ldr_context_addr,
377			  sizeof (CORE_ADDR)) != 0)
378    return 0;
379  if (target_read_memory (ldr_context_addr,
380			  (char *) &ldr_context,
381			  sizeof (ldr_context_t)) != 0)
382    return 0;
383  ctxt->next = ldr_context.head;
384  ctxt->tail = ldr_context.tail;
385#endif
386  return 1;
387}
388
389/* Initialize SO to have module NAME, /sbin/loader indicator ISLOADR, and
390   space for NSECS sections.  */
391
392static void
393init_so (struct so_list *so, char *name, int isloader, int nsecs)
394{
395  int namelen, i;
396
397  /* solib.c requires various fields to be initialized to 0.  */
398  memset (so, 0, sizeof *so);
399
400  /* Copy the name.  */
401  namelen = strlen (name);
402  if (namelen >= SO_NAME_MAX_PATH_SIZE)
403    namelen = SO_NAME_MAX_PATH_SIZE - 1;
404
405  memcpy (so->so_original_name, name, namelen);
406  so->so_original_name[namelen] = '\0';
407  memcpy (so->so_name, so->so_original_name, namelen + 1);
408
409  /* Allocate section space.  */
410  so->lm_info = xmalloc ((unsigned) &(((struct lm_info *)0)->secs) +
411			 nsecs * sizeof *so->lm_info);
412  so->lm_info->isloader = isloader;
413  so->lm_info->nsecs = nsecs;
414  for (i = 0; i < nsecs; i++)
415    so->lm_info->secs[i].name = NULL;
416}
417
418/* Initialize SO's section SECIDX with name address NAMEADDR, name string
419   NAME, default virtual address VADDR, and actual virtual address
420   MAPADDR.  */
421
422static void
423init_sec (struct so_list *so, int secidx, CORE_ADDR nameaddr,
424	  const char *name, CORE_ADDR vaddr, CORE_ADDR mapaddr)
425{
426  struct lm_sec *lms;
427
428  lms = so->lm_info->secs + secidx;
429  lms->nameaddr = nameaddr;
430  lms->name = name;
431  lms->offset = mapaddr - vaddr;
432}
433
434/* If there are more elements starting at CTXT in inferior's module list,
435   store the next element in SO, advance CTXT to the next element, and return
436   1, else return 0.  */
437
438static int
439read_map (struct read_map_ctxt *ctxt, struct so_list *so)
440{
441  ldr_module_info_t minf;
442  ldr_region_info_t rinf;
443
444#ifdef USE_LDR_ROUTINES
445  size_t size;
446  ldr_region_t i;
447
448  /* Retrieve the next element.  */
449  if (ldr_next_module (ctxt->proc, &ctxt->next) != 0)
450    return 0;
451  if (ctxt->next == LDR_NULL_MODULE)
452    return 0;
453  if (ldr_inq_module (ctxt->proc, ctxt->next, &minf, sizeof minf, &size) != 0)
454    return 0;
455
456  /* Initialize the module name and section count.  */
457  init_so (so, minf.lmi_name, 0, minf.lmi_nregion);
458
459  /* Retrieve section names and offsets.  */
460  for (i = 0; i < minf.lmi_nregion; i++)
461    {
462      if (ldr_inq_region (ctxt->proc, ctxt->next, i, &rinf,
463			  sizeof rinf, &size) != 0)
464	goto err;
465      init_sec (so, (int) i, 0, xstrdup (rinf.lri_name),
466		(CORE_ADDR) rinf.lri_vaddr, (CORE_ADDR) rinf.lri_mapaddr);
467    }
468  lm_secs_sort (so->lm_info);
469#else
470  char *name;
471  int errcode, i;
472
473  /* Retrieve the next element.  */
474  if (!ctxt->next)
475    return 0;
476  if (target_read_memory (ctxt->next, (char *) &minf, sizeof minf) != 0)
477    return 0;
478  if (ctxt->next == ctxt->tail)
479    ctxt->next = 0;
480  else
481    ctxt->next = minf.next;
482
483  /* Initialize the module name and section count.  */
484  target_read_string (minf.module_name, &name, PATH_MAX, &errcode);
485  if (errcode != 0)
486    return 0;
487  init_so (so, name, !minf.modinfo_addr, minf.region_count);
488  xfree (name);
489
490  /* Retrieve section names and offsets.  */
491  for (i = 0; i < minf.region_count; i++)
492    {
493      if (target_read_memory (minf.regioninfo_addr + i * sizeof rinf,
494			      (char *) &rinf, sizeof rinf) != 0)
495	goto err;
496      init_sec (so, i, rinf.regionname_addr, NULL, rinf.vaddr, rinf.mapaddr);
497    }
498#endif   /* !USE_LDR_ROUTINES */
499  return 1;
500
501 err:
502  osf_free_so (so);
503  return 0;
504}
505
506/* Free resources allocated by open_map (CTXT).  */
507
508static void
509close_map (struct read_map_ctxt *ctxt)
510{
511#ifdef USE_LDR_ROUTINES
512  ldr_xdetach (ctxt->proc);
513#endif
514}
515
516/* target_so_ops callback.  Return a list of shared objects currently loaded
517   in the inferior.  */
518
519static struct so_list *
520osf_current_sos (void)
521{
522  struct so_list *head = NULL, *tail, *newtail, so;
523  struct read_map_ctxt ctxt;
524  int skipped_main;
525
526  if (!open_map (&ctxt))
527    return NULL;
528
529  /* Read subsequent elements.  */
530  for (skipped_main = 0;;)
531    {
532      if (!read_map (&ctxt, &so))
533	break;
534
535      /* Skip the main program module, which is first in the list after
536         /sbin/loader.  */
537      if (!so.lm_info->isloader && !skipped_main)
538	{
539	  osf_free_so (&so);
540	  skipped_main = 1;
541	  continue;
542	}
543
544      newtail = xmalloc (sizeof *newtail);
545      if (!head)
546	head = newtail;
547      else
548	tail->next = newtail;
549      tail = newtail;
550
551      memcpy (tail, &so, sizeof so);
552      tail->next = NULL;
553    }
554
555  close_map (&ctxt);
556  return head;
557}
558
559/* target_so_ops callback.  Attempt to locate and open the main symbol
560   file.  */
561
562static int
563osf_open_symbol_file_object (void *from_ttyp)
564{
565  struct read_map_ctxt ctxt;
566  struct so_list so;
567  int found;
568
569  if (symfile_objfile)
570    if (!query ("Attempt to reload symbols from process? "))
571      return 0;
572
573  /* The first module after /sbin/loader is the main program.  */
574  if (!open_map (&ctxt))
575    return 0;
576  for (found = 0; !found;)
577    {
578      if (!read_map (&ctxt, &so))
579	break;
580      found = !so.lm_info->isloader;
581      osf_free_so (&so);
582    }
583  close_map (&ctxt);
584
585  if (found)
586    symbol_file_add_main (so.so_name, *(int *) from_ttyp);
587  return found;
588}
589
590/* target_so_ops callback.  Return whether PC is in the dynamic linker.  */
591
592static int
593osf_in_dynsym_resolve_code (CORE_ADDR pc)
594{
595  /* This function currently always return False. This is a temporary
596     solution which only consequence is to introduce a minor incovenience
597     for the user: When stepping inside a subprogram located in a shared
598     library, gdb might stop inside the dynamic loader code instead of
599     inside the subprogram itself. See the explanations in infrun.c about
600     the IN_SOLIB_DYNSYM_RESOLVE_CODE macro for more details. */
601  return 0;
602}
603
604static struct target_so_ops osf_so_ops;
605
606void
607_initialize_osf_solib (void)
608{
609  osf_so_ops.relocate_section_addresses = osf_relocate_section_addresses;
610  osf_so_ops.free_so = osf_free_so;
611  osf_so_ops.clear_solib = osf_clear_solib;
612  osf_so_ops.solib_create_inferior_hook = osf_solib_create_inferior_hook;
613  osf_so_ops.special_symbol_handling = osf_special_symbol_handling;
614  osf_so_ops.current_sos = osf_current_sos;
615  osf_so_ops.open_symbol_file_object = osf_open_symbol_file_object;
616  osf_so_ops.in_dynsym_resolve_code = osf_in_dynsym_resolve_code;
617
618  /* FIXME: Don't do this here.  *_gdbarch_init() should set so_ops. */
619  current_target_so_ops = &osf_so_ops;
620}
621