]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/valgrind/src/valgrind-3.6.0-svn/coregrind/m_debuginfo/debuginfo.c
Inital import
[l4.git] / l4 / pkg / valgrind / src / valgrind-3.6.0-svn / coregrind / m_debuginfo / debuginfo.c
1
2 /*--------------------------------------------------------------------*/
3 /*--- Top level management of symbols and debugging information.   ---*/
4 /*---                                                  debuginfo.c ---*/
5 /*--------------------------------------------------------------------*/
6
7 /*
8    This file is part of Valgrind, a dynamic binary instrumentation
9    framework.
10
11    Copyright (C) 2000-2010 Julian Seward 
12       jseward@acm.org
13
14    This program is free software; you can redistribute it and/or
15    modify it under the terms of the GNU General Public License as
16    published by the Free Software Foundation; either version 2 of the
17    License, or (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful, but
20    WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22    General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program; if not, write to the Free Software
26    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
27    02111-1307, USA.
28
29    The GNU General Public License is contained in the file COPYING.
30 */
31
32 #include "pub_core_basics.h"
33 #include "pub_core_vki.h"
34 #include "pub_core_threadstate.h"
35 #include "pub_core_debuginfo.h"  /* self */
36 #include "pub_core_demangle.h"
37 #include "pub_core_libcbase.h"
38 #include "pub_core_libcassert.h"
39 #include "pub_core_libcprint.h"
40 #include "pub_core_libcfile.h"
41 #include "pub_core_libcproc.h"   // VG_(getenv)
42 #include "pub_core_seqmatch.h"
43 #include "pub_core_options.h"
44 #include "pub_core_redir.h"      // VG_(redir_notify_{new,delete}_SegInfo)
45 #include "pub_core_aspacemgr.h"
46 #include "pub_core_machine.h"    // VG_PLAT_USES_PPCTOC
47 #include "pub_core_xarray.h"
48 #include "pub_core_oset.h"
49 #include "pub_core_stacktrace.h" // VG_(get_StackTrace) XXX: circular dependency
50 #include "pub_core_ume.h"
51
52 #include "priv_misc.h"           /* dinfo_zalloc/free */
53 #include "priv_d3basics.h"       /* ML_(pp_GX) */
54 #include "priv_tytypes.h"
55 #include "priv_storage.h"
56 #include "priv_readdwarf.h"
57 #include "priv_readstabs.h"
58 #if defined(VGO_linux)
59 # include "priv_readelf.h"
60 # include "priv_readdwarf3.h"
61 # include "priv_readpdb.h"
62 #elif defined(VGO_aix5)
63 # include "pub_core_debuglog.h"
64 # include "pub_core_libcproc.h"
65 # include "pub_core_libcfile.h"
66 # include "priv_readxcoff.h"
67 #elif defined(VGO_darwin)
68 # include "priv_readmacho.h"
69 # include "priv_readpdb.h"
70 #endif
71
72
73 /*------------------------------------------------------------*/
74 /*--- The _svma / _avma / _image / _bias naming scheme     ---*/
75 /*------------------------------------------------------------*/
76
77 /* JRS 11 Jan 07: I find the different kinds of addresses involved in
78    debuginfo reading confusing.  Recently I arrived at some
79    terminology which makes it clearer (to me, at least).  There are 3
80    kinds of address used in the debuginfo reading process:
81  
82    stated VMAs - the address where (eg) a .so says a symbol is, that
83                  is, what it tells you if you consider the .so in
84                  isolation
85  
86    actual VMAs - the address where (eg) said symbol really wound up
87                  after the .so was mapped into memory
88  
89    image addresses - pointers into the copy of the .so (etc)
90                      transiently mmaped aboard whilst we read its info
91
92    Additionally I use the term 'bias' to denote the difference
93    between stated and actual VMAs for a given entity.
94
95    This terminology is not used consistently, but a start has been
96    made.  readelf.c and the call-frame info reader in readdwarf.c now
97    use it.  Specifically, various variables and structure fields have
98    been annotated with _avma / _svma / _image / _bias.  In places _img
99    is used instead of _image for the sake of brevity.
100 */
101
102
103 /*------------------------------------------------------------*/
104 /*--- fwdses                                               ---*/
105 /*------------------------------------------------------------*/
106
107 static void cfsi_cache__invalidate ( void );
108
109
110 /*------------------------------------------------------------*/
111 /*--- Root structure                                       ---*/
112 /*------------------------------------------------------------*/
113
114 /* The root structure for the entire debug info system.  It is a
115    linked list of DebugInfos. */
116 static DebugInfo* debugInfo_list = NULL;
117
118
119 /* Find 'di' in the debugInfo_list and move it one step closer the the
120    front of the list, so as to make subsequent searches for it
121    cheaper.  When used in a controlled way, makes a major improvement
122    in some DebugInfo-search-intensive situations, most notably stack
123    unwinding on amd64-linux. */
124 static void move_DebugInfo_one_step_forward ( DebugInfo* di )
125 {
126    DebugInfo *di0, *di1, *di2;
127    if (di == debugInfo_list)
128       return; /* already at head of list */
129    vg_assert(di != NULL);
130    di0 = debugInfo_list;
131    di1 = NULL;
132    di2 = NULL;
133    while (True) {
134       if (di0 == NULL || di0 == di) break;
135       di2 = di1;
136       di1 = di0;
137       di0 = di0->next;
138    }
139    vg_assert(di0 == di);
140    if (di0 != NULL && di1 != NULL && di2 != NULL) {
141       DebugInfo* tmp;
142       /* di0 points to di, di1 to its predecessor, and di2 to di1's
143          predecessor.  Swap di0 and di1, that is, move di0 one step
144          closer to the start of the list. */
145       vg_assert(di2->next == di1);
146       vg_assert(di1->next == di0);
147       tmp = di0->next;
148       di2->next = di0;
149       di0->next = di1;
150       di1->next = tmp;
151    }
152    else
153    if (di0 != NULL && di1 != NULL && di2 == NULL) {
154       /* it's second in the list. */
155       vg_assert(debugInfo_list == di1);
156       vg_assert(di1->next == di0);
157       di1->next = di0->next;
158       di0->next = di1;
159       debugInfo_list = di0;
160    }
161 }
162
163
164 /*------------------------------------------------------------*/
165 /*--- Notification (acquire/discard) helpers               ---*/
166 /*------------------------------------------------------------*/
167
168 /* Gives out unique abstract handles for allocated DebugInfos.  See
169    comment in priv_storage.h, declaration of struct _DebugInfo, for
170    details. */
171 static ULong handle_counter = 1;
172
173 /* Allocate and zero out a new DebugInfo record. */
174 static 
175 DebugInfo* alloc_DebugInfo( const UChar* filename,
176                             const UChar* memname )
177 {
178    Bool       traceme;
179    DebugInfo* di;
180
181    vg_assert(filename);
182
183    di = ML_(dinfo_zalloc)("di.debuginfo.aDI.1", sizeof(DebugInfo));
184    di->handle    = handle_counter++;
185    di->filename  = ML_(dinfo_strdup)("di.debuginfo.aDI.2", filename);
186    di->memname   = memname ? ML_(dinfo_strdup)("di.debuginfo.aDI.3", memname)
187                            : NULL;
188
189    /* Everything else -- pointers, sizes, arrays -- is zeroed by calloc.
190       Now set up the debugging-output flags. */
191    traceme 
192       = VG_(string_match)( VG_(clo_trace_symtab_patt), filename )
193         || (memname && VG_(string_match)( VG_(clo_trace_symtab_patt), 
194                                           memname ));
195    if (traceme) {
196       di->trace_symtab = VG_(clo_trace_symtab);
197       di->trace_cfi    = VG_(clo_trace_cfi);
198       di->ddump_syms   = VG_(clo_debug_dump_syms);
199       di->ddump_line   = VG_(clo_debug_dump_line);
200       di->ddump_frames = VG_(clo_debug_dump_frames);
201    }
202
203    return di;
204 }
205
206
207 /* Free a DebugInfo, and also all the stuff hanging off it. */
208 static void free_DebugInfo ( DebugInfo* di )
209 {
210    Word i, j, n;
211    struct strchunk *chunk, *next;
212    TyEnt* ent;
213    GExpr* gexpr;
214
215    vg_assert(di != NULL);
216    if (di->filename)   ML_(dinfo_free)(di->filename);
217    if (di->symtab)     ML_(dinfo_free)(di->symtab);
218    if (di->loctab)     ML_(dinfo_free)(di->loctab);
219    if (di->cfsi)       ML_(dinfo_free)(di->cfsi);
220    if (di->cfsi_exprs) VG_(deleteXA)(di->cfsi_exprs);
221    if (di->fpo)        ML_(dinfo_free)(di->fpo);
222
223    for (chunk = di->strchunks; chunk != NULL; chunk = next) {
224       next = chunk->next;
225       ML_(dinfo_free)(chunk);
226    }
227
228    /* Delete the two admin arrays.  These lists exist primarily so
229       that we can visit each object exactly once when we need to
230       delete them. */
231    if (di->admin_tyents) {
232       n = VG_(sizeXA)(di->admin_tyents);
233       for (i = 0; i < n; i++) {
234          ent = (TyEnt*)VG_(indexXA)(di->admin_tyents, i);
235          /* Dump anything hanging off this ent */
236          ML_(TyEnt__make_EMPTY)(ent);
237       }
238       VG_(deleteXA)(di->admin_tyents);
239       di->admin_tyents = NULL;
240    }
241
242    if (di->admin_gexprs) {
243       n = VG_(sizeXA)(di->admin_gexprs);
244       for (i = 0; i < n; i++) {
245          gexpr = *(GExpr**)VG_(indexXA)(di->admin_gexprs, i);
246          ML_(dinfo_free)(gexpr);
247       }
248       VG_(deleteXA)(di->admin_gexprs);
249       di->admin_gexprs = NULL;
250    }
251
252    /* Dump the variable info.  This is kinda complex: we must take
253       care not to free items which reside in either the admin lists
254       (as we have just freed them) or which reside in the DebugInfo's
255       string table. */
256    if (di->varinfo) {
257       for (i = 0; i < VG_(sizeXA)(di->varinfo); i++) {
258          OSet* scope = *(OSet**)VG_(indexXA)(di->varinfo, i);
259          if (!scope) continue;
260          /* iterate over all entries in 'scope' */
261          VG_(OSetGen_ResetIter)(scope);
262          while (True) {
263             DiAddrRange* arange = VG_(OSetGen_Next)(scope);
264             if (!arange) break;
265             /* for each var in 'arange' */
266             vg_assert(arange->vars);
267             for (j = 0; j < VG_(sizeXA)( arange->vars ); j++) {
268                DiVariable* var = (DiVariable*)VG_(indexXA)(arange->vars,j);
269                vg_assert(var);
270                /* Nothing to free in var: all the pointer fields refer
271                   to stuff either on an admin list, or in
272                   .strchunks */
273             }
274             VG_(deleteXA)(arange->vars);
275             /* Don't free arange itself, as OSetGen_Destroy does
276                that */
277          }
278          VG_(OSetGen_Destroy)(scope);
279       }
280       VG_(deleteXA)(di->varinfo);
281    }
282
283    ML_(dinfo_free)(di);
284 }
285
286
287 /* 'si' is a member of debugInfo_list.  Find it, remove it from the
288    list, notify m_redir that this has happened, and free all storage
289    reachable from it.
290 */
291 static void discard_DebugInfo ( DebugInfo* di )
292 {
293 #  if defined(VGP_ppc32_aix5)
294    HChar* reason = "__unload";
295 #  elif defined(VGP_ppc64_aix5)
296    HChar* reason = "kunload64";
297 #  else
298    HChar* reason = "munmap";
299 #  endif
300
301    DebugInfo** prev_next_ptr = &debugInfo_list;
302    DebugInfo*  curr          =  debugInfo_list;
303
304    while (curr) {
305       if (curr == di) {
306          /* Found it;  remove from list and free it. */
307          if (curr->have_dinfo
308              && (VG_(clo_verbosity) > 1 || VG_(clo_trace_redir)))
309             VG_(message)(Vg_DebugMsg, 
310                          "Discarding syms at %#lx-%#lx in %s due to %s()\n",
311                          di->text_avma, 
312                          di->text_avma + di->text_size,
313                          curr->filename ? curr->filename : (UChar*)"???",
314                          reason);
315          vg_assert(*prev_next_ptr == curr);
316          *prev_next_ptr = curr->next;
317          if (curr->have_dinfo)
318             VG_(redir_notify_delete_DebugInfo)( curr );
319          free_DebugInfo(curr);
320          return;
321       }
322       prev_next_ptr = &curr->next;
323       curr          =  curr->next;
324    }
325
326    /* Not found. */
327 }
328
329
330 /* Repeatedly scan debugInfo_list, looking for DebugInfos with text
331    AVMAs intersecting [start,start+length), and call discard_DebugInfo
332    to get rid of them.  This modifies the list, hence the multiple
333    iterations.  Returns True iff any such DebugInfos were found.
334 */
335 static Bool discard_syms_in_range ( Addr start, SizeT length )
336 {
337    Bool       anyFound = False;
338    Bool       found;
339    DebugInfo* curr;
340
341    while (True) {
342       found = False;
343
344       curr = debugInfo_list;
345       while (True) {
346          if (curr == NULL)
347             break;
348          if (curr->text_present
349              && curr->text_size > 0
350              && (start+length - 1 < curr->text_avma 
351                  || curr->text_avma + curr->text_size - 1 < start)) {
352             /* no overlap */
353          } else {
354             found = True;
355             break;
356          }
357          curr = curr->next;
358       }
359
360       if (!found) break;
361       anyFound = True;
362       discard_DebugInfo( curr );
363    }
364
365    return anyFound;
366 }
367
368
369 /* Does [s1,+len1) overlap [s2,+len2) ?  Note: does not handle
370    wraparound at the end of the address space -- just asserts in that
371    case. */
372 static Bool ranges_overlap (Addr s1, SizeT len1, Addr s2, SizeT len2 )
373 {
374    Addr e1, e2;
375    if (len1 == 0 || len2 == 0) 
376       return False;
377    e1 = s1 + len1 - 1;
378    e2 = s2 + len2 - 1;
379    /* Assert that we don't have wraparound.  If we do it would imply
380       that file sections are getting mapped around the end of the
381       address space, which sounds unlikely. */
382    vg_assert(s1 <= e1);
383    vg_assert(s2 <= e2);
384    if (e1 < s2 || e2 < s1) return False;
385    return True;
386 }
387
388
389 /* Do the basic rx_ and rw_ mappings of the two DebugInfos overlap in
390    any way? */
391 static Bool do_DebugInfos_overlap ( DebugInfo* di1, DebugInfo* di2 )
392 {
393    vg_assert(di1);
394    vg_assert(di2);
395
396    if (di1->have_rx_map && di2->have_rx_map
397        && ranges_overlap(di1->rx_map_avma, di1->rx_map_size,
398                          di2->rx_map_avma, di2->rx_map_size))
399       return True;
400
401    if (di1->have_rx_map && di2->have_rw_map
402        && ranges_overlap(di1->rx_map_avma, di1->rx_map_size,
403                          di2->rw_map_avma, di2->rw_map_size))
404       return True;
405
406    if (di1->have_rw_map && di2->have_rx_map
407        && ranges_overlap(di1->rw_map_avma, di1->rw_map_size,
408                          di2->rx_map_avma, di2->rx_map_size))
409       return True;
410
411    if (di1->have_rw_map && di2->have_rw_map
412        && ranges_overlap(di1->rw_map_avma, di1->rw_map_size,
413                          di2->rw_map_avma, di2->rw_map_size))
414       return True;
415
416    return False;
417 }
418
419
420 /* Discard all elements of debugInfo_list whose .mark bit is set.
421 */
422 static void discard_marked_DebugInfos ( void )
423 {
424    DebugInfo* curr;
425
426    while (True) {
427
428       curr = debugInfo_list;
429       while (True) {
430          if (!curr)
431             break;
432          if (curr->mark)
433             break;
434          curr = curr->next;
435       }
436
437       if (!curr) break;
438       discard_DebugInfo( curr );
439
440    }
441 }
442
443
444 /* Discard any elements of debugInfo_list which overlap with diRef.
445    Clearly diRef must have its rx_ and rw_ mapping information set to
446    something sane. */
447 #if defined(VGO_aix5)
448 __attribute__((unused))
449 #endif
450 static void discard_DebugInfos_which_overlap_with ( DebugInfo* diRef )
451 {
452    DebugInfo* di;
453    /* Mark all the DebugInfos in debugInfo_list that need to be
454       deleted.  First, clear all the mark bits; then set them if they
455       overlap with siRef.  Since siRef itself is in this list we at
456       least expect its own mark bit to be set. */
457    for (di = debugInfo_list; di; di = di->next) {
458       di->mark = do_DebugInfos_overlap( di, diRef );
459       if (di == diRef) {
460          vg_assert(di->mark);
461          di->mark = False;
462       }
463    }
464    discard_marked_DebugInfos();
465 }
466
467
468 /* Find the existing DebugInfo for (memname,filename) or if not found,
469    create one.  In the latter case memname and filename are strdup'd
470    into VG_AR_DINFO, and the new DebugInfo is added to
471    debugInfo_list. */
472 static
473 DebugInfo* find_or_create_DebugInfo_for ( UChar* filename, UChar* memname )
474 {
475    DebugInfo* di;
476    vg_assert(filename);
477    for (di = debugInfo_list; di; di = di->next) {
478       vg_assert(di->filename);
479       if (0==VG_(strcmp)(di->filename, filename)
480           && ( (memname && di->memname) 
481                   ? 0==VG_(strcmp)(memname, di->memname)
482                   : True ))
483          break;
484    }
485    if (!di) {
486       di = alloc_DebugInfo(filename, memname);
487       vg_assert(di);
488       di->next = debugInfo_list;
489       debugInfo_list = di;
490    }
491    return di;
492 }
493
494
495 /* Debuginfo reading for 'di' has just been successfully completed.
496    Check that the invariants stated in
497    "Comment_on_IMPORTANT_CFSI_REPRESENTATIONAL_INVARIANTS" in
498    priv_storage.h are observed. */
499 static void check_CFSI_related_invariants ( DebugInfo* di )
500 {
501    DebugInfo* di2 = NULL;
502    vg_assert(di);
503    /* This fn isn't called until after debuginfo for this object has
504       been successfully read.  And that shouldn't happen until we have
505       both a r-x and rw- mapping for the object.  Hence: */
506    vg_assert(di->have_rx_map);
507    vg_assert(di->have_rw_map);
508    /* degenerate case: r-x section is empty */
509    if (di->rx_map_size == 0) {
510       vg_assert(di->cfsi == NULL);
511       return;
512    }
513    /* normal case: r-x section is nonempty */
514    /* invariant (0) */
515    vg_assert(di->rx_map_size > 0);
516    /* invariant (1) */
517    for (di2 = debugInfo_list; di2; di2 = di2->next) {
518       if (di2 == di)
519          continue;
520       if (di2->rx_map_size == 0)
521          continue;
522       vg_assert(di->rx_map_avma + di->rx_map_size <= di2->rx_map_avma
523                 || di2->rx_map_avma + di2->rx_map_size <= di->rx_map_avma);
524    }
525    di2 = NULL;
526    /* invariant (2) */
527    if (di->cfsi) {
528       vg_assert(di->cfsi_minavma <= di->cfsi_maxavma); /* duh! */
529       vg_assert(di->cfsi_minavma >= di->rx_map_avma);
530       vg_assert(di->cfsi_maxavma < di->rx_map_avma + di->rx_map_size);
531    }
532    /* invariants (3) and (4) */
533    if (di->cfsi) {
534       Word i;
535       vg_assert(di->cfsi_used > 0);
536       vg_assert(di->cfsi_size > 0);
537       for (i = 0; i < di->cfsi_used; i++) {
538          DiCfSI* cfsi = &di->cfsi[i];
539          vg_assert(cfsi->len > 0);
540          vg_assert(cfsi->base >= di->cfsi_minavma);
541          vg_assert(cfsi->base + cfsi->len - 1 <= di->cfsi_maxavma);
542          if (i > 0) {
543             DiCfSI* cfsip = &di->cfsi[i-1];
544             vg_assert(cfsip->base + cfsip->len <= cfsi->base);
545          }
546       }
547    } else {
548       vg_assert(di->cfsi_used == 0);
549       vg_assert(di->cfsi_size == 0);
550    }
551 }
552
553
554 /*--------------------------------------------------------------*/
555 /*---                                                        ---*/
556 /*--- TOP LEVEL: INITIALISE THE DEBUGINFO SYSTEM             ---*/
557 /*---                                                        ---*/
558 /*--------------------------------------------------------------*/
559
560 void VG_(di_initialise) ( void )
561 {
562    /* There's actually very little to do here, since everything
563       centers around the DebugInfos in debugInfo_list, they are
564       created and destroyed on demand, and each one is treated more or
565       less independently. */
566    vg_assert(debugInfo_list == NULL);
567
568    /* flush the CFI fast query cache. */
569    cfsi_cache__invalidate();
570 }
571
572
573 /*--------------------------------------------------------------*/
574 /*---                                                        ---*/
575 /*--- TOP LEVEL: NOTIFICATION (ACQUIRE/DISCARD INFO) (LINUX) ---*/
576 /*---                                                        ---*/
577 /*--------------------------------------------------------------*/
578
579 #if defined(VGO_linux)  ||  defined(VGO_darwin) || defined(VGO_l4re)
580
581 /* The debug info system is driven by notifications that a text
582    segment has been mapped in, or unmapped.  When that happens it
583    tries to acquire/discard whatever info is available for the
584    corresponding object.  This section contains the notification
585    handlers. */
586
587 /* Notify the debuginfo system about a new mapping.  This is the way
588    new debug information gets loaded.  If allow_SkFileV is True, it
589    will try load debug info if the mapping at 'a' belongs to Valgrind;
590    whereas normally (False) it will not do that.  This allows us to
591    carefully control when the thing will read symbols from the
592    Valgrind executable itself.
593
594    If a call to VG_(di_notify_mmap) causes debug info to be read, then
595    the returned ULong is an abstract handle which can later be used to
596    refer to the debuginfo read as a result of this specific mapping,
597    in later queries to m_debuginfo.  In this case the handle value
598    will be one or above.  If the returned value is zero, no debug info
599    was read. */
600
601 ULong VG_(di_notify_mmap)( Addr a, Bool allow_SkFileV )
602 {
603    NSegment const * seg;
604    HChar*     filename;
605    Bool       ok, is_rx_map, is_rw_map;
606    DebugInfo* di;
607    ULong      di_handle;
608    SysRes     fd;
609    Int        nread;
610    HChar      buf1k[1024];
611    Bool       debug = False;
612    SysRes     statres;
613    struct vg_stat statbuf;
614
615    /* In short, figure out if this mapping is of interest to us, and
616       if so, try to guess what ld.so is doing and when/if we should
617       read debug info. */
618    seg = VG_(am_find_nsegment)(a);
619    vg_assert(seg);
620
621    if (debug) {
622       VG_(printf)("di_notify_mmap-1: %#lx-%#lx %c%c%c\n",
623                   seg->start, seg->end, 
624                   seg->hasR ? 'r' : '-',
625                   seg->hasW ? 'w' : '-',seg->hasX ? 'x' : '-' );
626 #if defined(VGO_l4re)
627       VG_(printf)("    segment kind: %d (%s)\n", seg->kind,
628                   vcap_segknd_str(seg->kind));
629 #endif
630    }
631
632    /* guaranteed by aspacemgr-linux.c, sane_NSegment() */
633    vg_assert(seg->end > seg->start);
634
635    /* Ignore non-file mappings */
636    if ( ! (seg->kind == SkFileC
637            || (seg->kind == SkFileV && allow_SkFileV)) )
638       return 0;
639
640    /* If the file doesn't have a name, we're hosed.  Give up. */
641    filename = VG_(am_get_filename)( (NSegment*)seg );
642    if (!filename)
643       return 0;
644
645    if (debug)
646       VG_(printf)("di_notify_mmap-2: %s\n", filename);
647
648    /* Only try to read debug information from regular files.  */
649    statres = VG_(stat)(filename, &statbuf);
650
651    /* stat dereferences symlinks, so we don't expect it to succeed and
652       yet produce something that is a symlink. */
653    vg_assert(sr_isError(statres) || ! VKI_S_ISLNK(statbuf.mode));
654
655    /* Don't let the stat call fail silently.  Filter out some known
656       sources of noise before complaining, though. */
657    if (sr_isError(statres)) {
658       DebugInfo fake_di;
659       Bool quiet = VG_(strstr)(filename, "/var/run/nscd/") != NULL;
660       if (!quiet && VG_(clo_verbosity) > 1) {
661          VG_(memset)(&fake_di, 0, sizeof(fake_di));
662          fake_di.filename = filename;
663          ML_(symerr)(&fake_di, True, "failed to stat64/stat this file");
664       }
665       return 0;
666    }
667
668    /* Finally, the point of all this stattery: if it's not a regular file,
669       don't try to read debug info from it. */
670    if (! VKI_S_ISREG(statbuf.mode)) {
671       VG_(printf)("not a regular file\n");
672       return 0;
673    }
674
675    /* no uses of statbuf below here. */
676
677    /* Now we have to guess if this is a text-like mapping, a data-like
678       mapping, neither or both.  The rules are:
679
680         text if:   x86-linux    r and x
681                    other-linux  r and x and not w
682
683         data if:   x86-linux    r and w
684                    other-linux  r and w and not x
685
686       Background: On x86-linux, objects are typically mapped twice:
687
688       1b8fb000-1b8ff000 r-xp 00000000 08:02 4471477 vgpreload_memcheck.so
689       1b8ff000-1b900000 rw-p 00004000 08:02 4471477 vgpreload_memcheck.so
690
691       whereas ppc32-linux mysteriously does this:
692
693       118a6000-118ad000 r-xp 00000000 08:05 14209428 vgpreload_memcheck.so
694       118ad000-118b6000 ---p 00007000 08:05 14209428 vgpreload_memcheck.so
695       118b6000-118bd000 rwxp 00000000 08:05 14209428 vgpreload_memcheck.so
696
697       The third mapping should not be considered to have executable
698       code in.  Therefore a test which works for both is: r and x and
699       NOT w.  Reading symbols from the rwx segment -- which overlaps
700       the r-x segment in the file -- causes the redirection mechanism
701       to redirect to addresses in that third segment, which is wrong
702       and causes crashes.
703
704       JRS 28 Dec 05: unfortunately icc 8.1 on x86 has been seen to
705       produce executables with a single rwx segment rather than a
706       (r-x,rw-) pair. That means the rules have to be modified thusly:
707
708       x86-linux:   consider if r and x
709       all others:  consider if r and x and not w
710
711       2009 Aug 16: apply similar kludge to ppc32-linux.
712       See http://bugs.kde.org/show_bug.cgi?id=190820
713    */
714    is_rx_map = False;
715    is_rw_map = False;
716 #  if defined(VGA_x86) || defined(VGA_ppc32)
717    is_rx_map = seg->hasR && seg->hasX;
718    is_rw_map = seg->hasR && seg->hasW;
719 #  elif defined(VGA_amd64) || defined(VGA_ppc64) || defined(VGA_arm)
720    is_rx_map = seg->hasR && seg->hasX && !seg->hasW;
721    is_rw_map = seg->hasR && seg->hasW && !seg->hasX;
722 #  else
723 #    error "Unknown platform"
724 #  endif
725
726    if (debug)
727       VG_(printf)("di_notify_mmap-3: is_rx_map %d, is_rw_map %d\n",
728                   (Int)is_rx_map, (Int)is_rw_map);
729
730    /* If it is neither text-ish nor data-ish, we're not interested. */
731    if (!(is_rx_map || is_rw_map))
732       return 0;
733
734    /* Peer at the first few bytes of the file, to see if it is an ELF */
735    /* object file. Ignore the file if we do not have read permission. */
736    VG_(memset)(buf1k, 0, sizeof(buf1k));
737    fd = VG_(open)( filename, VKI_O_RDONLY, 0 );
738    if (sr_isError(fd)) {
739       if (sr_Err(fd) != VKI_EACCES) {
740          DebugInfo fake_di;
741          VG_(memset)(&fake_di, 0, sizeof(fake_di));
742          fake_di.filename = filename;
743          ML_(symerr)(&fake_di, True, "can't open file to inspect ELF header");
744       }
745       return 0;
746    }
747    nread = VG_(read)( sr_Res(fd), buf1k, sizeof(buf1k) );
748    VG_(close)( sr_Res(fd) );
749
750    if (nread == 0)
751       return 0;
752    if (nread < 0) {
753       DebugInfo fake_di;
754       VG_(memset)(&fake_di, 0, sizeof(fake_di));
755       fake_di.filename = filename;
756       ML_(symerr)(&fake_di, True, "can't read file to inspect ELF header");
757       return 0;
758    }
759    vg_assert(nread > 0 && nread <= sizeof(buf1k) );
760
761    /* We're only interested in mappings of object files. */
762    // Nb: AIX5 doesn't use this file and so isn't represented here.
763 #if defined(VGO_linux) || defined(VGO_l4re)
764    if (!ML_(is_elf_object_file)( buf1k, (SizeT)nread ))
765       return 0;
766 #elif defined(VGO_darwin)
767    if (!ML_(is_macho_object_file)( buf1k, (SizeT)nread ))
768       return 0;
769 #else
770 #  error "unknown OS"
771 #endif
772
773    /* See if we have a DebugInfo for this filename.  If not,
774       create one. */
775    di = find_or_create_DebugInfo_for( filename, NULL/*membername*/ );
776    vg_assert(di);
777
778    if (is_rx_map) {
779       /* We have a text-like mapping.  Note the details. */
780       if (!di->have_rx_map) {
781          di->have_rx_map = True;
782          di->rx_map_avma = a;
783          di->rx_map_size = seg->end + 1 - seg->start;
784          di->rx_map_foff = seg->offset;
785       } else {
786          /* FIXME: complain about a second text-like mapping */
787       }
788    }
789
790    if (is_rw_map) {
791       /* We have a data-like mapping.  Note the details. */
792       if (!di->have_rw_map) {
793          di->have_rw_map = True;
794          di->rw_map_avma = a;
795          di->rw_map_size = seg->end + 1 - seg->start;
796          di->rw_map_foff = seg->offset;
797       } else {
798          /* FIXME: complain about a second data-like mapping */
799       }
800    }
801
802    /* If we don't have an rx and rw mapping, or if we already have
803       debuginfo for this mapping for whatever reason, go no
804       further. */
805    if ( ! (di->have_rx_map && di->have_rw_map && !di->have_dinfo) )
806       return 0;
807
808    /* Ok, so, finally, let's try to read the debuginfo. */
809    vg_assert(di->filename);
810    TRACE_SYMTAB("\n");
811    TRACE_SYMTAB("------ start ELF OBJECT "
812                 "------------------------------\n");
813    TRACE_SYMTAB("------ name = %s\n", di->filename);
814    TRACE_SYMTAB("\n");
815
816    /* We're going to read symbols and debug info for the avma
817       ranges [rx_map_avma, +rx_map_size) and [rw_map_avma,
818       +rw_map_size).  First get rid of any other DebugInfos which
819       overlap either of those ranges (to avoid total confusion). */
820    discard_DebugInfos_which_overlap_with( di );
821
822    /* .. and acquire new info. */
823    // Nb: AIX5 doesn't use this file and so isn't represented here.
824 #if defined(VGO_linux) || defined(VGO_l4re)
825    ok = ML_(read_elf_debug_info)( di );
826 #elif defined(VGO_darwin)
827    ok = ML_(read_macho_debug_info)( di );
828 #else
829 #  error "unknown OS"
830 #endif
831
832    if (ok) {
833
834       TRACE_SYMTAB("\n------ Canonicalising the "
835                    "acquired info ------\n");
836       /* invalidate the CFI unwind cache. */
837       cfsi_cache__invalidate();
838       /* prepare read data for use */
839       ML_(canonicaliseTables)( di );
840       /* notify m_redir about it */
841       TRACE_SYMTAB("\n------ Notifying m_redir ------\n");
842       VG_(redir_notify_new_DebugInfo)( di );
843       /* Note that we succeeded */
844       di->have_dinfo = True;
845       tl_assert(di->handle > 0);
846       di_handle = di->handle;
847       /* Check invariants listed in
848          Comment_on_IMPORTANT_REPRESENTATIONAL_INVARIANTS in
849          priv_storage.h. */
850       check_CFSI_related_invariants(di);
851
852    } else {
853       TRACE_SYMTAB("\n------ ELF reading failed ------\n");
854       /* Something went wrong (eg. bad ELF file).  Should we delete
855          this DebugInfo?  No - it contains info on the rw/rx
856          mappings, at least. */
857       di_handle = 0;
858       vg_assert(di->have_dinfo == False);
859    }
860
861    TRACE_SYMTAB("\n");
862    TRACE_SYMTAB("------ name = %s\n", di->filename);
863    TRACE_SYMTAB("------ end ELF OBJECT "
864                 "------------------------------\n");
865    TRACE_SYMTAB("\n");
866
867    return di_handle;
868 }
869
870
871 /* Unmap is simpler - throw away any SegInfos intersecting 
872    [a, a+len).  */
873 void VG_(di_notify_munmap)( Addr a, SizeT len )
874 {
875    Bool anyFound;
876    if (0) VG_(printf)("DISCARD %#lx %#lx\n", a, a+len);
877    anyFound = discard_syms_in_range(a, len);
878    if (anyFound)
879       cfsi_cache__invalidate();
880 }
881
882
883 /* Uh, this doesn't do anything at all.  IIRC glibc (or ld.so, I don't
884    remember) does a bunch of mprotects on itself, and if we follow
885    through here, it causes the debug info for that object to get
886    discarded. */
887 void VG_(di_notify_mprotect)( Addr a, SizeT len, UInt prot )
888 {
889    Bool exe_ok = toBool(prot & VKI_PROT_EXEC);
890 #  if defined(VGA_x86)
891    exe_ok = exe_ok || toBool(prot & VKI_PROT_READ);
892 #  endif
893    if (0 && !exe_ok) {
894       Bool anyFound = discard_syms_in_range(a, len);
895       if (anyFound)
896          cfsi_cache__invalidate();
897    }
898 }
899
900 /*--------- PDB (windows debug info) reading --------- */
901
902 /* this should really return ULong, as per VG_(di_notify_mmap). */
903 void VG_(di_notify_pdb_debuginfo)( Int fd_obj, Addr avma_obj,
904                                    SizeT total_size,
905                                    PtrdiffT unknown_purpose__reloc )
906 {
907    Int    i, r, sz_exename;
908    ULong  obj_mtime, pdb_mtime;
909    Char   exename[VKI_PATH_MAX];
910    Char*  pdbname = NULL;
911    Char*  dot;
912    SysRes sres;
913    Int    fd_pdbimage;
914    SizeT  n_pdbimage;
915    struct vg_stat stat_buf;
916
917    if (VG_(clo_verbosity) > 0) {
918       VG_(message)(Vg_UserMsg, "\n");
919       VG_(message)(Vg_UserMsg,
920          "LOAD_PDB_DEBUGINFO(fd=%d, avma=%#lx, total_size=%lu, "
921          "uu_reloc=%#lx)\n", 
922          fd_obj, avma_obj, total_size, unknown_purpose__reloc
923       );
924    }
925
926    /* 'fd' refers to the .exe/.dll we're dealing with.  Get its modification
927       time into obj_mtime. */
928    r = VG_(fstat)(fd_obj, &stat_buf);
929    if (r == -1)
930       goto out; /* stat failed ?! */
931    vg_assert(r == 0);
932    obj_mtime = stat_buf.mtime;
933
934    /* and get its name into exename[]. */
935    vg_assert(VKI_PATH_MAX > 100); /* to ensure /proc/self/fd/%d is safe */
936    VG_(memset)(exename, 0, sizeof(exename));
937    VG_(sprintf)(exename, "/proc/self/fd/%d", fd_obj);
938    /* convert exename from a symlink to real name .. overwrites the
939       old contents of the buffer.  Ick. */
940    sz_exename = VG_(readlink)(exename, exename, sizeof(exename)-2 );
941    if (sz_exename == -1)
942       goto out; /* readlink failed ?! */
943    vg_assert(sz_exename >= 0 && sz_exename < sizeof(exename));
944    vg_assert(exename[sizeof(exename)-1] == 0);
945
946    if (VG_(clo_verbosity) > 0) {
947       VG_(message)(Vg_UserMsg, "LOAD_PDB_DEBUGINFO: objname: %s\n", exename);
948    }
949
950    /* Try to get the PDB file name from the executable. */
951    pdbname = ML_(find_name_of_pdb_file)(exename);
952    if (pdbname) {
953       vg_assert(VG_(strlen)(pdbname) >= 5); /* 5 = strlen("X.pdb") */
954       /* So we successfully extracted a name from the PE file.  But it's
955          likely to be of the form
956             e:\foo\bar\xyzzy\wibble.pdb
957          and we need to change it into something we can actually open
958          in Wine-world, which basically means turning it into
959             $HOME/.wine/drive_e/foo/bar/xyzzy/wibble.pdb
960          We also take into account $WINEPREFIX, if it is set.
961          For the moment, if the name isn't fully qualified, just forget it
962          (we'd have to root around to find where the pdb actually is)
963       */
964       /* Change all the backslashes to forward slashes */
965       for (i = 0; pdbname[i]; i++) {
966          if (pdbname[i] == '\\')
967             pdbname[i] = '/';
968       }
969       Bool is_quald
970          = ('a' <= VG_(tolower)(pdbname[0]) && VG_(tolower)(pdbname[0]) <= 'z')
971            && pdbname[1] == ':'
972            && pdbname[2] == '/';
973       HChar* home = VG_(getenv)("HOME");
974       HChar* wpfx = VG_(getenv)("WINEPREFIX");
975       if (is_quald && wpfx) {
976          /* Change e:/foo/bar/xyzzy/wibble.pdb
977                 to $WINEPREFIX/drive_e/foo/bar/xyzzy/wibble.pdb
978          */
979          Int mashedSzB = VG_(strlen)(pdbname) + VG_(strlen)(wpfx) + 50/*misc*/;
980          HChar* mashed = ML_(dinfo_zalloc)("di.debuginfo.dnpdi.1", mashedSzB);
981          VG_(sprintf)(mashed, "%s/drive_%c%s",
982                       wpfx, pdbname[0], &pdbname[2]);
983          vg_assert(mashed[mashedSzB-1] == 0);
984          ML_(dinfo_free)(pdbname);
985          pdbname = mashed;
986       }
987       else if (is_quald && home && !wpfx) {
988          /* Change e:/foo/bar/xyzzy/wibble.pdb
989                 to $HOME/.wine/drive_e/foo/bar/xyzzy/wibble.pdb
990          */
991          Int mashedSzB = VG_(strlen)(pdbname) + VG_(strlen)(home) + 50/*misc*/;
992          HChar* mashed = ML_(dinfo_zalloc)("di.debuginfo.dnpdi.2", mashedSzB);
993          VG_(sprintf)(mashed, "%s/.wine/drive_%c%s",
994                       home, pdbname[0], &pdbname[2]);
995          vg_assert(mashed[mashedSzB-1] == 0);
996          ML_(dinfo_free)(pdbname);
997          pdbname = mashed;
998       } else {
999          /* It's not a fully qualified path, or neither $HOME nor $WINE
1000             are set (strange).  Give up. */
1001          ML_(dinfo_free)(pdbname);
1002          pdbname = NULL;
1003       }
1004    }
1005
1006    /* Try s/exe/pdb/ if we don't have a valid pdbname. */
1007    if (!pdbname) {
1008       /* Try to find a matching PDB file from which to read debuginfo.
1009          Windows PE files have symbol tables and line number information,
1010          but MSVC doesn't seem to use them. */
1011       /* Why +5 ?  Because in the worst case, we could find a dot as the
1012          last character of pdbname, and we'd then put "pdb" right after
1013          it, hence extending it a bit. */
1014       pdbname = ML_(dinfo_zalloc)("di.debuginfo.lpd1", sz_exename+5);
1015       VG_(strcpy)(pdbname, exename);
1016       vg_assert(pdbname[sz_exename+5-1] == 0);
1017       dot = VG_(strrchr)(pdbname, '.');
1018       if (!dot)
1019          goto out; /* there's no dot in the exe's name ?! */
1020       if (dot[1] == 0)
1021          goto out; /* hmm, path ends in "." */
1022
1023       if ('A' <= dot[1] && dot[1] <= 'Z')
1024          VG_(strcpy)(dot, ".PDB");
1025       else
1026          VG_(strcpy)(dot, ".pdb");
1027
1028       vg_assert(pdbname[sz_exename+5-1] == 0);
1029    }
1030
1031    /* See if we can find it, and check it's in-dateness. */
1032    sres = VG_(stat)(pdbname, &stat_buf);
1033    if (sr_isError(sres)) {
1034       VG_(message)(Vg_UserMsg, "Warning: Missing or un-stat-able %s\n",
1035                                pdbname);
1036    if (VG_(clo_verbosity) > 0)
1037       VG_(message)(Vg_UserMsg, "LOAD_PDB_DEBUGINFO: missing: %s\n", pdbname);
1038       goto out;
1039    }
1040    pdb_mtime = stat_buf.mtime;
1041    if (obj_mtime > pdb_mtime + 60UL) {
1042       /* PDB file is older than PE file - ignore it or we will either
1043          (a) print wrong stack traces or more likely (b) crash. */
1044       VG_(message)(Vg_UserMsg,
1045                    "Warning:       %s (mtime = %llu)\n"
1046                    " is older than %s (mtime = %llu)\n",
1047                    pdbname, pdb_mtime, exename, obj_mtime);
1048    }
1049
1050    sres = VG_(open)(pdbname, VKI_O_RDONLY, 0);
1051    if (sr_isError(sres)) {
1052       VG_(message)(Vg_UserMsg, "Warning: Can't open %s\n", pdbname);
1053       goto out;
1054    }
1055
1056    /* Looks promising; go on to try and read stuff from it. */
1057    fd_pdbimage = sr_Res(sres);
1058    n_pdbimage  = stat_buf.size;
1059    sres = VG_(am_mmap_file_float_valgrind)( n_pdbimage, VKI_PROT_READ,
1060                                             fd_pdbimage, 0 );
1061    if (sr_isError(sres)) {
1062       VG_(close)(fd_pdbimage);
1063       goto out;
1064    }
1065
1066    if (VG_(clo_verbosity) > 0)
1067       VG_(message)(Vg_UserMsg, "LOAD_PDB_DEBUGINFO: pdbname: %s\n", pdbname);
1068
1069    /* play safe; always invalidate the CFI cache.  I don't know if
1070       this is necessary, but anyway .. */
1071    cfsi_cache__invalidate();
1072    /* dump old info for this range, if any */
1073    discard_syms_in_range( avma_obj, total_size );
1074
1075    { void* pdbimage = (void*)sr_Res(sres);
1076      DebugInfo* di = find_or_create_DebugInfo_for(exename, NULL/*membername*/ );
1077
1078      /* this di must be new, since we just nuked any old stuff in the range */
1079      vg_assert(di && !di->have_rx_map && !di->have_rw_map);
1080      vg_assert(!di->have_dinfo);
1081
1082      /* don't set up any of the di-> fields; let
1083         ML_(read_pdb_debug_info) do it. */
1084      ML_(read_pdb_debug_info)( di, avma_obj, unknown_purpose__reloc,
1085                                pdbimage, n_pdbimage, pdbname, pdb_mtime );
1086      // JRS fixme: take notice of return value from read_pdb_debug_info,
1087      // and handle failure
1088      vg_assert(di->have_dinfo); // fails if PDB read failed
1089      VG_(am_munmap_valgrind)( (Addr)pdbimage, n_pdbimage );
1090      VG_(close)(fd_pdbimage);
1091    }
1092
1093   out:
1094    if (pdbname) ML_(dinfo_free)(pdbname);
1095 }
1096
1097 #endif /* defined(VGO_linux) || defined(VGO_darwin) */
1098
1099
1100 /*-------------------------------------------------------------*/
1101 /*---                                                       ---*/
1102 /*--- TOP LEVEL: NOTIFICATION (ACQUIRE/DISCARD INFO) (AIX5) ---*/
1103 /*---                                                       ---*/
1104 /*-------------------------------------------------------------*/
1105
1106 #if defined(VGO_aix5)
1107
1108 /* The supplied parameters describe a code segment and its associated
1109    data segment, that have recently been mapped in -- so we need to
1110    read debug info for it -- or conversely, have recently been dumped,
1111    in which case the relevant debug info has to be unloaded. */
1112
1113 ULong VG_(di_aix5_notify_segchange)( 
1114                Addr   code_start,
1115                Word   code_len,
1116                Addr   data_start,
1117                Word   data_len,
1118                UChar* file_name,
1119                UChar* mem_name,
1120                Bool   is_mainexe,
1121                Bool   acquire )
1122 {
1123    ULong hdl = 0;
1124
1125    /* play safe; always invalidate the CFI cache.  Not
1126       that it should be used on AIX, but still .. */
1127    cfsi_cache__invalidate();
1128
1129    if (acquire) {
1130
1131       Bool       ok;
1132       DebugInfo* di;
1133       di = find_or_create_DebugInfo_for( file_name, mem_name );
1134       vg_assert(di);
1135
1136       if (code_len > 0) {
1137          di->text_present = True;
1138          di->text_svma = 0; /* don't know yet */
1139          di->text_bias = 0; /* don't know yet */
1140          di->text_avma = code_start;
1141          di->text_size = code_len;
1142       }
1143       if (data_len > 0) {
1144          di->data_present = True;
1145          di->data_svma = 0; /* don't know yet */
1146          di->data_bias = 0; /* don't know yet */
1147          di->data_avma = data_start;
1148          di->data_size = data_len;
1149       }
1150
1151       /* These need to be filled in in order to keep various
1152          assertions in storage.c happy.  In particular see
1153          "Comment_Regarding_Text_Range_Checks" in that file. */
1154       di->have_rx_map = True;
1155       di->rx_map_avma = code_start;
1156       di->rx_map_size = code_len;
1157       di->have_rw_map = True;
1158       di->rw_map_avma = data_start;
1159       di->rw_map_size = data_len;
1160
1161       ok = ML_(read_xcoff_debug_info) ( di, is_mainexe );
1162
1163       if (ok) {
1164          /* prepare read data for use */
1165          ML_(canonicaliseTables)( di );
1166          /* notify m_redir about it */
1167          VG_(redir_notify_new_DebugInfo)( di );
1168          /* Note that we succeeded */
1169          di->have_dinfo = True;
1170          hdl = di->handle;
1171          vg_assert(hdl > 0);
1172          /* Check invariants listed in
1173             Comment_on_IMPORTANT_REPRESENTATIONAL_INVARIANTS in
1174             priv_storage.h. */
1175          check_CFSI_related_invariants(di);
1176       } else {
1177          /*  Something went wrong (eg. bad XCOFF file). */
1178          discard_DebugInfo( di );
1179          di = NULL;
1180       }
1181
1182    } else {
1183
1184       /* Dump all the debugInfos whose text segments intersect
1185          code_start/code_len. */
1186       /* CFI cache is always invalidated at start of this routine.
1187          Hence it's safe to ignore the return value of
1188          discard_syms_in_range. */
1189       if (code_len > 0)
1190          (void)discard_syms_in_range( code_start, code_len );
1191
1192    }
1193
1194    return hdl;
1195 }
1196         
1197
1198 #endif /* defined(VGO_aix5) */
1199
1200
1201 /*------------------------------------------------------------*/
1202 /*---                                                      ---*/
1203 /*--- TOP LEVEL: QUERYING EXISTING DEBUG INFO              ---*/
1204 /*---                                                      ---*/
1205 /*------------------------------------------------------------*/
1206
1207 void VG_(di_discard_ALL_debuginfo)( void )
1208 {
1209    DebugInfo *di, *di2;
1210    di = debugInfo_list;
1211    while (di) {
1212       di2 = di->next;
1213       VG_(printf)("XXX rm %p\n", di);
1214       free_DebugInfo( di );
1215       di = di2;
1216    }
1217 }
1218
1219
1220 /*------------------------------------------------------------*/
1221 /*--- Use of symbol table & location info to create        ---*/
1222 /*--- plausible-looking stack dumps.                       ---*/
1223 /*------------------------------------------------------------*/
1224
1225 /* Search all symtabs that we know about to locate ptr.  If found, set
1226    *pdi to the relevant DebugInfo, and *symno to the symtab entry
1227    *number within that.  If not found, *psi is set to NULL.
1228    If findText==True,  only text symbols are searched for.
1229    If findText==False, only data symbols are searched for.
1230 */
1231 static void search_all_symtabs ( Addr ptr, /*OUT*/DebugInfo** pdi,
1232                                            /*OUT*/Word* symno,
1233                                  Bool match_anywhere_in_sym,
1234                                  Bool findText )
1235 {
1236    Word       sno;
1237    DebugInfo* di;
1238    Bool       inRange;
1239
1240    for (di = debugInfo_list; di != NULL; di = di->next) {
1241
1242       if (findText) {
1243          /* Consider any symbol in the r-x mapped area to be text.
1244             See Comment_Regarding_Text_Range_Checks in storage.c for
1245             details. */
1246          inRange = di->have_rx_map
1247                    && di->rx_map_size > 0
1248                    && di->rx_map_avma <= ptr
1249                    && ptr < di->rx_map_avma + di->rx_map_size;
1250       } else {
1251          inRange = (di->data_present
1252                     && di->data_size > 0
1253                     && di->data_avma <= ptr 
1254                     && ptr < di->data_avma + di->data_size)
1255                    ||
1256                    (di->sdata_present
1257                     && di->sdata_size > 0
1258                     && di->sdata_avma <= ptr 
1259                     && ptr < di->sdata_avma + di->sdata_size)
1260                    ||
1261                    (di->bss_present
1262                     && di->bss_size > 0
1263                     && di->bss_avma <= ptr 
1264                     && ptr < di->bss_avma + di->bss_size)
1265                    ||
1266                    (di->sbss_present
1267                     && di->sbss_size > 0
1268                     && di->sbss_avma <= ptr 
1269                     && ptr < di->sbss_avma + di->sbss_size)
1270                    ||
1271                    (di->rodata_present
1272                     && di->rodata_size > 0
1273                     && di->rodata_avma <= ptr 
1274                     && ptr < di->rodata_avma + di->rodata_size);
1275       }
1276
1277       if (!inRange) continue;
1278
1279       sno = ML_(search_one_symtab) ( 
1280                di, ptr, match_anywhere_in_sym, findText );
1281       if (sno == -1) goto not_found;
1282       *symno = sno;
1283       *pdi = di;
1284       return;
1285
1286    }
1287   not_found:
1288    *pdi = NULL;
1289 }
1290
1291
1292 /* Search all loctabs that we know about to locate ptr.  If found, set
1293    *pdi to the relevant DebugInfo, and *locno to the loctab entry
1294    *number within that.  If not found, *pdi is set to NULL. */
1295 static void search_all_loctabs ( Addr ptr, /*OUT*/DebugInfo** pdi,
1296                                            /*OUT*/Word* locno )
1297 {
1298    Word       lno;
1299    DebugInfo* di;
1300    for (di = debugInfo_list; di != NULL; di = di->next) {
1301       if (di->text_present
1302           && di->text_size > 0
1303           && di->text_avma <= ptr 
1304           && ptr < di->text_avma + di->text_size) {
1305          lno = ML_(search_one_loctab) ( di, ptr );
1306          if (lno == -1) goto not_found;
1307          *locno = lno;
1308          *pdi = di;
1309          return;
1310       }
1311    }
1312   not_found:
1313    *pdi = NULL;
1314 }
1315
1316
1317 /* The whole point of this whole big deal: map a code address to a
1318    plausible symbol name.  Returns False if no idea; otherwise True.
1319    Caller supplies buf and nbuf.  If do_cxx_demangling is False, don't do
1320    C++ demangling, regardless of VG_(clo_demangle) -- probably because the
1321    call has come from VG_(get_fnname_raw)().  findText
1322    indicates whether we're looking for a text symbol or a data symbol
1323    -- caller must choose one kind or the other. */
1324 static
1325 Bool get_sym_name ( Bool do_cxx_demangling, Bool do_z_demangling,
1326                     Bool do_below_main_renaming,
1327                     Addr a, Char* buf, Int nbuf,
1328                     Bool match_anywhere_in_sym, Bool show_offset,
1329                     Bool findText, /*OUT*/PtrdiffT* offsetP )
1330 {
1331    DebugInfo* di;
1332    Word       sno;
1333    PtrdiffT   offset;
1334
1335    search_all_symtabs ( a, &di, &sno, match_anywhere_in_sym, findText );
1336    if (di == NULL) 
1337       return False;
1338
1339    VG_(demangle) ( do_cxx_demangling, do_z_demangling,
1340                    di->symtab[sno].name, buf, nbuf );
1341
1342    /* Do the below-main hack */
1343    // To reduce the endless nuisance of multiple different names 
1344    // for "the frame below main()" screwing up the testsuite, change all
1345    // known incarnations of said into a single name, "(below main)", if
1346    // --show-below-main=yes.
1347    if ( do_below_main_renaming && ! VG_(clo_show_below_main) &&
1348         Vg_FnNameBelowMain == VG_(get_fnname_kind)(buf) )
1349    {
1350       VG_(strncpy_safely)(buf, "(below main)", nbuf);
1351    }
1352    offset = a - di->symtab[sno].addr;
1353    if (offsetP) *offsetP = offset;
1354
1355    if (show_offset && offset != 0) {
1356       Char     buf2[12];
1357       Char*    symend = buf + VG_(strlen)(buf);
1358       Char*    end = buf + nbuf;
1359       Int      len;
1360
1361       len = VG_(sprintf)(buf2, "%c%ld",
1362                          offset < 0 ? '-' : '+',
1363                          offset < 0 ? -offset : offset);
1364       vg_assert(len < (Int)sizeof(buf2));
1365
1366       if (len < (end - symend)) {
1367          Char *cp = buf2;
1368          VG_(memcpy)(symend, cp, len+1);
1369       }
1370    }
1371
1372    buf[nbuf-1] = 0; /* paranoia */
1373
1374    return True;
1375 }
1376
1377 /* ppc64-linux only: find the TOC pointer (R2 value) that should be in
1378    force at the entry point address of the function containing
1379    guest_code_addr.  Returns 0 if not known. */
1380 Addr VG_(get_tocptr) ( Addr guest_code_addr )
1381 {
1382    DebugInfo* si;
1383    Word       sno;
1384    search_all_symtabs ( guest_code_addr, 
1385                         &si, &sno,
1386                         True/*match_anywhere_in_fun*/,
1387                         True/*consider text symbols only*/ );
1388    if (si == NULL) 
1389       return 0;
1390    else
1391       return si->symtab[sno].tocptr;
1392 }
1393
1394 /* This is available to tools... always demangle C++ names,
1395    match anywhere in function, but don't show offsets. */
1396 Bool VG_(get_fnname) ( Addr a, Char* buf, Int nbuf )
1397 {
1398    return get_sym_name ( /*C++-demangle*/True, /*Z-demangle*/True,
1399                          /*below-main-renaming*/True,
1400                          a, buf, nbuf,
1401                          /*match_anywhere_in_fun*/True, 
1402                          /*show offset?*/False,
1403                          /*text syms only*/True,
1404                          /*offsetP*/NULL );
1405 }
1406
1407 /* This is available to tools... always demangle C++ names,
1408    match anywhere in function, and show offset if nonzero. */
1409 Bool VG_(get_fnname_w_offset) ( Addr a, Char* buf, Int nbuf )
1410 {
1411    return get_sym_name ( /*C++-demangle*/True, /*Z-demangle*/True,
1412                          /*below-main-renaming*/True,
1413                          a, buf, nbuf,
1414                          /*match_anywhere_in_fun*/True, 
1415                          /*show offset?*/True,
1416                          /*text syms only*/True,
1417                          /*offsetP*/NULL );
1418 }
1419
1420 /* This is available to tools... always demangle C++ names,
1421    only succeed if 'a' matches first instruction of function,
1422    and don't show offsets. */
1423 Bool VG_(get_fnname_if_entry) ( Addr a, Char* buf, Int nbuf )
1424 {
1425    return get_sym_name ( /*C++-demangle*/True, /*Z-demangle*/True,
1426                          /*below-main-renaming*/True,
1427                          a, buf, nbuf,
1428                          /*match_anywhere_in_fun*/False, 
1429                          /*show offset?*/False,
1430                          /*text syms only*/True,
1431                          /*offsetP*/NULL );
1432 }
1433
1434 /* This is only available to core... don't C++-demangle, don't Z-demangle,
1435    don't rename below-main, match anywhere in function, and don't show
1436    offsets. */
1437 Bool VG_(get_fnname_raw) ( Addr a, Char* buf, Int nbuf )
1438 {
1439    return get_sym_name ( /*C++-demangle*/False, /*Z-demangle*/False,
1440                          /*below-main-renaming*/False,
1441                          a, buf, nbuf,
1442                          /*match_anywhere_in_fun*/True, 
1443                          /*show offset?*/False,
1444                          /*text syms only*/True,
1445                          /*offsetP*/NULL );
1446 }
1447
1448 /* This is only available to core... don't demangle C++ names, but do
1449    do Z-demangling and below-main-renaming, match anywhere in function, and
1450    don't show offsets. */
1451 Bool VG_(get_fnname_no_cxx_demangle) ( Addr a, Char* buf, Int nbuf )
1452 {
1453    return get_sym_name ( /*C++-demangle*/False, /*Z-demangle*/True,
1454                          /*below-main-renaming*/True,
1455                          a, buf, nbuf,
1456                          /*match_anywhere_in_fun*/True, 
1457                          /*show offset?*/False,
1458                          /*text syms only*/True,
1459                          /*offsetP*/NULL );
1460 }
1461
1462 Vg_FnNameKind VG_(get_fnname_kind) ( Char* name )
1463 {
1464    if (VG_STREQ("main", name)) {
1465       return Vg_FnNameMain;
1466
1467    } else if (
1468 #      if defined(VGO_linux) || defined(VGO_l4re)
1469        VG_STREQ("__libc_start_main",  name) ||  // glibc glibness
1470        VG_STREQ("generic_start_main", name) ||  // Yellow Dog doggedness
1471 #      elif defined(VGO_aix5)
1472        VG_STREQ("__start", name)            ||  // AIX aches
1473 #      elif defined(VGO_darwin)
1474        // See readmacho.c for an explanation of this.
1475        VG_STREQ("start_according_to_valgrind", name) ||  // Darwin, darling
1476 #      else
1477 #        error "Unknown OS"
1478 #      endif
1479        0) {
1480       return Vg_FnNameBelowMain;
1481
1482    } else {
1483       return Vg_FnNameNormal;
1484    }
1485 }
1486
1487 Vg_FnNameKind VG_(get_fnname_kind_from_IP) ( Addr ip )
1488 {
1489    // We don't need a big buffer;  all the special names are small.
1490    #define BUFLEN 50
1491    Char buf[50];
1492
1493    // We don't demangle, because it's faster not to, and the special names
1494    // we're looking for won't be demangled.
1495    if (VG_(get_fnname_raw) ( ip, buf, BUFLEN )) {
1496       buf[BUFLEN-1] = '\0';      // paranoia
1497       return VG_(get_fnname_kind)(buf);
1498    } else {
1499       return Vg_FnNameNormal;    // Don't know the name, treat it as normal.
1500    }
1501 }
1502
1503 /* Looks up data_addr in the collection of data symbols, and if found
1504    puts its name (or as much as will fit) into dname[0 .. n_dname-1],
1505    which is guaranteed to be zero terminated.  Also data_addr's offset
1506    from the symbol start is put into *offset. */
1507 Bool VG_(get_datasym_and_offset)( Addr data_addr,
1508                                   /*OUT*/Char* dname, Int n_dname,
1509                                   /*OUT*/PtrdiffT* offset )
1510 {
1511    Bool ok;
1512    vg_assert(n_dname > 1);
1513    ok = get_sym_name ( /*C++-demangle*/False, /*Z-demangle*/False,
1514                        /*below-main-renaming*/False,
1515                        data_addr, dname, n_dname,
1516                        /*match_anywhere_in_sym*/True, 
1517                        /*show offset?*/False,
1518                        /*data syms only please*/False,
1519                        offset );
1520    if (!ok)
1521       return False;
1522    dname[n_dname-1] = 0;
1523    return True;
1524 }
1525
1526 /* Map a code address to the name of a shared object file or the
1527    executable.  Returns False if no idea; otherwise True.  Doesn't
1528    require debug info.  Caller supplies buf and nbuf. */
1529 Bool VG_(get_objname) ( Addr a, Char* buf, Int nbuf )
1530 {
1531    Int used;
1532    DebugInfo* di;
1533    const NSegment *seg;
1534    HChar* filename;
1535    vg_assert(nbuf > 0);
1536    /* Look in the debugInfo_list to find the name.  In most cases we
1537       expect this to produce a result. */
1538    for (di = debugInfo_list; di != NULL; di = di->next) {
1539       if (di->text_present
1540           && di->text_size > 0
1541           && di->text_avma <= a 
1542           && a < di->text_avma + di->text_size) {
1543          VG_(strncpy_safely)(buf, di->filename, nbuf);
1544          if (di->memname) {
1545             used = VG_(strlen)(buf);
1546             if (used < nbuf) 
1547                VG_(strncpy_safely)(&buf[used], "(", nbuf-used);
1548             used = VG_(strlen)(buf);
1549             if (used < nbuf) 
1550                VG_(strncpy_safely)(&buf[used], di->memname, nbuf-used);
1551             used = VG_(strlen)(buf);
1552             if (used < nbuf) 
1553                VG_(strncpy_safely)(&buf[used], ")", nbuf-used);
1554          }
1555          buf[nbuf-1] = 0;
1556          return True;
1557       }
1558    }
1559    /* Last-ditch fallback position: if we don't find the address in
1560       the debugInfo_list, ask the address space manager whether it
1561       knows the name of the file associated with this mapping.  This
1562       allows us to print the names of exe/dll files in the stack trace
1563       when running programs under wine. */
1564    if ( (seg = VG_(am_find_nsegment(a))) != NULL 
1565         && (filename = VG_(am_get_filename)(seg)) != NULL ) {
1566       VG_(strncpy_safely)(buf, filename, nbuf);
1567       return True;
1568    }
1569    return False;
1570 }
1571
1572 /* Map a code address to its DebugInfo.  Returns NULL if not found.  Doesn't
1573    require debug info. */
1574 DebugInfo* VG_(find_DebugInfo) ( Addr a )
1575 {
1576    static UWord n_search = 0;
1577    DebugInfo* di;
1578    n_search++;
1579    for (di = debugInfo_list; di != NULL; di = di->next) {
1580       if (di->text_present
1581           && di->text_size > 0
1582           && di->text_avma <= a 
1583           && a < di->text_avma + di->text_size) {
1584          if (0 == (n_search & 0xF))
1585             move_DebugInfo_one_step_forward( di );
1586          return di;
1587       }
1588    }
1589    return NULL;
1590 }
1591
1592 /* Map a code address to a filename.  Returns True if successful.  */
1593 Bool VG_(get_filename)( Addr a, Char* filename, Int n_filename )
1594 {
1595    DebugInfo* si;
1596    Word       locno;
1597    search_all_loctabs ( a, &si, &locno );
1598    if (si == NULL) 
1599       return False;
1600    VG_(strncpy_safely)(filename, si->loctab[locno].filename, n_filename);
1601    return True;
1602 }
1603
1604 /* Map a code address to a line number.  Returns True if successful. */
1605 Bool VG_(get_linenum)( Addr a, UInt* lineno )
1606 {
1607    DebugInfo* si;
1608    Word       locno;
1609    search_all_loctabs ( a, &si, &locno );
1610    if (si == NULL) 
1611       return False;
1612    *lineno = si->loctab[locno].lineno;
1613
1614    return True;
1615 }
1616
1617 /* Map a code address to a filename/line number/dir name info.
1618    See prototype for detailed description of behaviour.
1619 */
1620 Bool VG_(get_filename_linenum) ( Addr a, 
1621                                  /*OUT*/Char* filename, Int n_filename,
1622                                  /*OUT*/Char* dirname,  Int n_dirname,
1623                                  /*OUT*/Bool* dirname_available,
1624                                  /*OUT*/UInt* lineno )
1625 {
1626    DebugInfo* si;
1627    Word       locno;
1628
1629    vg_assert( (dirname == NULL && dirname_available == NULL)
1630               ||
1631               (dirname != NULL && dirname_available != NULL) );
1632
1633    search_all_loctabs ( a, &si, &locno );
1634    if (si == NULL) {
1635       if (dirname_available) {
1636          *dirname_available = False;
1637          *dirname = 0;
1638       }
1639       return False;
1640    }
1641
1642    VG_(strncpy_safely)(filename, si->loctab[locno].filename, n_filename);
1643    *lineno = si->loctab[locno].lineno;
1644
1645    if (dirname) {
1646       /* caller wants directory info too .. */
1647       vg_assert(n_dirname > 0);
1648       if (si->loctab[locno].dirname) {
1649          /* .. and we have some */
1650          *dirname_available = True;
1651          VG_(strncpy_safely)(dirname, si->loctab[locno].dirname,
1652                                       n_dirname);
1653       } else {
1654          /* .. but we don't have any */
1655          *dirname_available = False;
1656          *dirname = 0;
1657       }
1658    }
1659
1660    return True;
1661 }
1662
1663
1664 /* Map a function name to its entry point and toc pointer.  Is done by
1665    sequential search of all symbol tables, so is very slow.  To
1666    mitigate the worst performance effects, you may specify a soname
1667    pattern, and only objects matching that pattern are searched.
1668    Therefore specify "*" to search all the objects.  On TOC-afflicted
1669    platforms, a symbol is deemed to be found only if it has a nonzero
1670    TOC pointer.  */
1671 Bool VG_(lookup_symbol_SLOW)(UChar* sopatt, UChar* name, 
1672                              Addr* pEnt, Addr* pToc)
1673 {
1674    Bool     require_pToc = False;
1675    Int      i;
1676    DebugInfo* si;
1677    Bool     debug = False;
1678 #  if defined(VG_PLAT_USES_PPCTOC)
1679    require_pToc = True;
1680 #  endif
1681    for (si = debugInfo_list; si; si = si->next) {
1682       if (debug)
1683          VG_(printf)("lookup_symbol_SLOW: considering %s\n", si->soname);
1684       if (!VG_(string_match)(sopatt, si->soname)) {
1685          if (debug)
1686             VG_(printf)(" ... skip\n");
1687          continue;
1688       }
1689       for (i = 0; i < si->symtab_used; i++) {
1690          if (0==VG_(strcmp)(name, si->symtab[i].name)
1691              && (require_pToc ? si->symtab[i].tocptr : True)) {
1692             *pEnt = si->symtab[i].addr;
1693             *pToc = si->symtab[i].tocptr;
1694             return True;
1695          }
1696       }
1697    }
1698    return False;
1699 }
1700
1701
1702 /* VG_(describe_IP): print into buf info on code address, function
1703    name and filename. */
1704
1705 /* Copy str into buf starting at n, but not going past buf[n_buf-1]
1706    and always ensuring that buf is zero-terminated. */
1707
1708 static Int putStr ( Int n, Int n_buf, Char* buf, Char* str ) 
1709 {
1710    vg_assert(n_buf > 0);
1711    vg_assert(n >= 0 && n < n_buf);
1712    for (; n < n_buf-1 && *str != 0; n++,str++)
1713       buf[n] = *str;
1714    vg_assert(n >= 0 && n < n_buf);
1715    buf[n] = '\0';
1716    return n;
1717 }
1718
1719 /* Same as putStr, but escaping chars for XML output, and
1720    also not adding more than count chars to n_buf. */
1721
1722 static Int putStrEsc ( Int n, Int n_buf, Int count, Char* buf, Char* str ) 
1723 {
1724    Char alt[2];
1725    vg_assert(n_buf > 0);
1726    vg_assert(count >= 0 && count < n_buf);
1727    vg_assert(n >= 0 && n < n_buf);
1728    for (; *str != 0; str++) {
1729       vg_assert(count >= 0);
1730       if (count <= 0)
1731          goto done;
1732       switch (*str) {
1733          case '&': 
1734             if (count < 5) goto done;
1735             n = putStr( n, n_buf, buf, "&amp;"); 
1736             count -= 5;
1737             break;
1738          case '<': 
1739             if (count < 4) goto done;
1740             n = putStr( n, n_buf, buf, "&lt;"); 
1741             count -= 4;
1742             break;
1743          case '>': 
1744             if (count < 4) goto done;
1745             n = putStr( n, n_buf, buf, "&gt;"); 
1746             count -= 4;
1747             break;
1748          default:
1749             if (count < 1) goto done;
1750             alt[0] = *str;
1751             alt[1] = 0;
1752             n = putStr( n, n_buf, buf, alt );
1753             count -= 1;
1754             break;
1755       }
1756    }
1757   done:
1758    vg_assert(count >= 0); /* should not go -ve in loop */
1759    vg_assert(n >= 0 && n < n_buf);
1760    return n;
1761 }
1762
1763 Char* VG_(describe_IP)(Addr eip, Char* buf, Int n_buf)
1764 {
1765 #  define APPEND(_str) \
1766       n = putStr(n, n_buf, buf, _str)
1767 #  define APPEND_ESC(_count,_str) \
1768       n = putStrEsc(n, n_buf, (_count), buf, (_str))
1769 #  define BUF_LEN    4096
1770
1771    UInt  lineno; 
1772    UChar ibuf[50];
1773    Int   n = 0;
1774    static UChar buf_fn[BUF_LEN];
1775    static UChar buf_obj[BUF_LEN];
1776    static UChar buf_srcloc[BUF_LEN];
1777    static UChar buf_dirname[BUF_LEN];
1778    Bool  know_dirinfo = False;
1779    Bool  know_fnname  = VG_(clo_sym_offsets)
1780                         ? VG_(get_fnname_w_offset) (eip, buf_fn, BUF_LEN)
1781                         : VG_(get_fnname) (eip, buf_fn, BUF_LEN);
1782    Bool  know_objname = VG_(get_objname)(eip, buf_obj, BUF_LEN);
1783    Bool  know_srcloc  = VG_(get_filename_linenum)(
1784                            eip, 
1785                            buf_srcloc,  BUF_LEN, 
1786                            buf_dirname, BUF_LEN, &know_dirinfo,
1787                            &lineno 
1788                         );
1789
1790    if (VG_(clo_xml)) {
1791
1792       Bool   human_readable = True;
1793       HChar* maybe_newline  = human_readable ? "\n      " : "";
1794       HChar* maybe_newline2 = human_readable ? "\n    "   : "";
1795
1796       /* Print in XML format, dumping in as much info as we know.
1797          Ensure all tags are balanced even if the individual strings
1798          are too long.  Allocate 1/10 of BUF_LEN to the object name,
1799          6/10s to the function name, 1/10 to the directory name and
1800          1/10 to the file name, leaving 1/10 for all the fixed-length
1801          stuff. */
1802       APPEND("<frame>");
1803       VG_(sprintf)(ibuf,"<ip>0x%llX</ip>", (ULong)eip);
1804       APPEND(maybe_newline);
1805       APPEND(ibuf);
1806       if (know_objname) {
1807          APPEND(maybe_newline);
1808          APPEND("<obj>");
1809          APPEND_ESC(1*BUF_LEN/10, buf_obj);
1810          APPEND("</obj>");
1811       }
1812       if (know_fnname) {
1813          APPEND(maybe_newline);
1814          APPEND("<fn>");
1815          APPEND_ESC(6*BUF_LEN/10, buf_fn);
1816          APPEND("</fn>");
1817       }
1818       if (know_srcloc) {
1819          if (know_dirinfo) {
1820             APPEND(maybe_newline);
1821             APPEND("<dir>");
1822             APPEND_ESC(1*BUF_LEN/10, buf_dirname);
1823             APPEND("</dir>");
1824          }
1825          APPEND(maybe_newline);
1826          APPEND("<file>");
1827          APPEND_ESC(1*BUF_LEN/10, buf_srcloc);
1828          APPEND("</file>");
1829          APPEND(maybe_newline);
1830          APPEND("<line>");
1831          VG_(sprintf)(ibuf,"%d",lineno);
1832          APPEND(ibuf);
1833          APPEND("</line>");
1834       }
1835       APPEND(maybe_newline2);
1836       APPEND("</frame>");
1837
1838    } else {
1839
1840       /* Print for humans to read */
1841       //
1842       // Possible forms:
1843       //
1844       //   0x80483BF: really (a.c:20)
1845       //   0x80483BF: really (in /foo/a.out)
1846       //   0x80483BF: really (in ???)
1847       //   0x80483BF: ??? (in /foo/a.out)
1848       //   0x80483BF: ??? (a.c:20)
1849       //   0x80483BF: ???
1850       //
1851       VG_(sprintf)(ibuf,"0x%llX: ", (ULong)eip);
1852
1853       APPEND(ibuf);
1854       if (know_fnname) {
1855          APPEND(buf_fn);
1856       } else {
1857          APPEND("???");
1858       }
1859       if (know_srcloc) {
1860          APPEND(" (");
1861          APPEND(buf_dirname);
1862          APPEND("/");
1863          APPEND(buf_srcloc);
1864          APPEND(":");
1865          VG_(sprintf)(ibuf,"%d",lineno);
1866          APPEND(ibuf);
1867          APPEND(")");
1868       } else if (know_objname) {
1869          APPEND(" (in ");
1870          APPEND(buf_obj);
1871          APPEND(")");
1872       } else if (know_fnname) {
1873          // Nb: do this in two steps because "??)" is a trigraph!
1874          APPEND(" (in ???");
1875          APPEND(")");
1876       }
1877
1878    }
1879    return buf;
1880
1881 #  undef APPEND
1882 #  undef APPEND_ESC
1883 #  undef BUF_LEN
1884 }
1885
1886
1887 /*--------------------------------------------------------------*/
1888 /*---                                                        ---*/
1889 /*--- TOP LEVEL: FOR UNWINDING THE STACK USING               ---*/
1890 /*---            DWARF3 .eh_frame INFO                       ---*/
1891 /*---                                                        ---*/
1892 /*--------------------------------------------------------------*/
1893
1894 /* Gather up all the constant pieces of info needed to evaluate
1895    a CfiExpr into one convenient struct. */
1896 typedef
1897    struct {
1898       D3UnwindRegs* uregs;
1899       Addr          min_accessible;
1900       Addr          max_accessible;
1901    }
1902    CfiExprEvalContext;
1903
1904 /* Evaluate the CfiExpr rooted at ix in exprs given the context eec.
1905    *ok is set to False on failure, but not to True on success.  The
1906    caller must set it to True before calling. */
1907 __attribute__((noinline))
1908 static
1909 UWord evalCfiExpr ( XArray* exprs, Int ix, 
1910                     CfiExprEvalContext* eec, Bool* ok )
1911 {
1912    UWord wL, wR;
1913    Addr  a;
1914    CfiExpr* e;
1915    vg_assert(sizeof(Addr) == sizeof(UWord));
1916    e = VG_(indexXA)( exprs, ix );
1917    switch (e->tag) {
1918       case Cex_Binop:
1919          wL = evalCfiExpr( exprs, e->Cex.Binop.ixL, eec, ok );
1920          if (!(*ok)) return 0;
1921          wR = evalCfiExpr( exprs, e->Cex.Binop.ixR, eec, ok );
1922          if (!(*ok)) return 0;
1923          switch (e->Cex.Binop.op) {
1924             case Cop_Add: return wL + wR;
1925             case Cop_Sub: return wL - wR;
1926             case Cop_And: return wL & wR;
1927             case Cop_Mul: return wL * wR;
1928             default: goto unhandled;
1929          }
1930          /*NOTREACHED*/
1931       case Cex_CfiReg:
1932          switch (e->Cex.CfiReg.reg) {
1933 #           if defined(VGA_x86) || defined(VGA_amd64)
1934             case Creg_IA_IP: return eec->uregs->xip;
1935             case Creg_IA_SP: return eec->uregs->xsp;
1936             case Creg_IA_BP: return eec->uregs->xbp;
1937 #           elif defined(VGA_arm)
1938             case Creg_ARM_R13: return eec->uregs->r13;
1939             case Creg_ARM_R12: return eec->uregs->r12;
1940             case Creg_ARM_R15: return eec->uregs->r15;
1941             case Creg_ARM_R14: return eec->uregs->r14;
1942 #           elif defined(VGA_ppc32) || defined(VGA_ppc64)
1943 #           else
1944 #             error "Unsupported arch"
1945 #           endif
1946             default: goto unhandled;
1947          }
1948          /*NOTREACHED*/
1949       case Cex_Const:
1950          return e->Cex.Const.con;
1951       case Cex_Deref:
1952          a = evalCfiExpr( exprs, e->Cex.Deref.ixAddr, eec, ok );
1953          if (!(*ok)) return 0;
1954          if (a < eec->min_accessible
1955              || (a + sizeof(UWord) - 1) > eec->max_accessible) {
1956             *ok = False;
1957             return 0;
1958          }
1959          /* let's hope it doesn't trap! */
1960          return * ((UWord*)a);
1961       default: 
1962          goto unhandled;
1963    }
1964    /*NOTREACHED*/
1965   unhandled:
1966    VG_(printf)("\n\nevalCfiExpr: unhandled\n");
1967    ML_(ppCfiExpr)( exprs, ix );
1968    VG_(printf)("\n");
1969    vg_assert(0);
1970    /*NOTREACHED*/
1971    return 0;
1972 }
1973
1974
1975 /* Search all the DebugInfos in the entire system, to find the DiCfSI
1976    that pertains to 'ip'. 
1977
1978    If found, set *diP to the DebugInfo in which it resides, and
1979    *ixP to the index in that DebugInfo's cfsi array.
1980
1981    If not found, set *diP to (DebugInfo*)1 and *ixP to zero.
1982 */
1983 __attribute__((noinline))
1984 static void find_DiCfSI ( /*OUT*/DebugInfo** diP, 
1985                           /*OUT*/Word* ixP,
1986                           Addr ip )
1987 {
1988    DebugInfo* di;
1989    Word       i = -1;
1990
1991    static UWord n_search = 0;
1992    static UWord n_steps = 0;
1993    n_search++;
1994
1995    if (0) VG_(printf)("search for %#lx\n", ip);
1996
1997    for (di = debugInfo_list; di != NULL; di = di->next) {
1998       Word j;
1999       n_steps++;
2000
2001       /* Use the per-DebugInfo summary address ranges to skip
2002          inapplicable DebugInfos quickly. */
2003       if (di->cfsi_used == 0)
2004          continue;
2005       if (ip < di->cfsi_minavma || ip > di->cfsi_maxavma)
2006          continue;
2007
2008       /* It might be in this DebugInfo.  Search it. */
2009       j = ML_(search_one_cfitab)( di, ip );
2010       vg_assert(j >= -1 && j < (Word)di->cfsi_used);
2011
2012       if (j != -1) {
2013          i = j;
2014          break; /* found it */
2015       }
2016    }
2017
2018    if (i == -1) {
2019
2020       /* we didn't find it. */
2021       *diP = (DebugInfo*)1;
2022       *ixP = 0;
2023
2024    } else {
2025
2026       /* found it. */
2027       /* ensure that di is 4-aligned (at least), so it can't possibly
2028          be equal to (DebugInfo*)1. */
2029       vg_assert(di && VG_IS_4_ALIGNED(di));
2030       vg_assert(i >= 0 && i < di->cfsi_used);
2031       *diP = di;
2032       *ixP = i;
2033
2034       /* Start of performance-enhancing hack: once every 64 (chosen
2035          hackily after profiling) successful searches, move the found
2036          DebugInfo one step closer to the start of the list.  This
2037          makes future searches cheaper.  For starting konqueror on
2038          amd64, this in fact reduces the total amount of searching
2039          done by the above find-the-right-DebugInfo loop by more than
2040          a factor of 20. */
2041       if ((n_search & 0xF) == 0) {
2042          /* Move di one step closer to the start of the list. */
2043          move_DebugInfo_one_step_forward( di );
2044       }
2045       /* End of performance-enhancing hack. */
2046
2047       if (0 && ((n_search & 0x7FFFF) == 0))
2048          VG_(printf)("find_DiCfSI: %lu searches, "
2049                      "%lu DebugInfos looked at\n", 
2050                      n_search, n_steps);
2051
2052    }
2053
2054 }
2055
2056
2057 /* Now follows a mechanism for caching queries to find_DiCfSI, since
2058    they are extremely frequent on amd64-linux, during stack unwinding.
2059
2060    Each cache entry binds an ip value to a (di, ix) pair.  Possible
2061    values:
2062
2063    di is non-null, ix >= 0  ==>  cache slot in use, "di->cfsi[ix]"
2064    di is (DebugInfo*)1      ==>  cache slot in use, no associated di
2065    di is NULL               ==>  cache slot not in use
2066
2067    Hence simply zeroing out the entire cache invalidates all
2068    entries.
2069
2070    Why not map ip values directly to DiCfSI*'s?  Because this would
2071    cause problems if/when the cfsi array is moved due to resizing.
2072    Instead we cache .cfsi array index value, which should be invariant
2073    across resizing.  (That said, I don't think the current
2074    implementation will resize whilst during queries, since the DiCfSI
2075    records are added all at once, when the debuginfo for an object is
2076    read, and is not changed ever thereafter. */
2077
2078 #define N_CFSI_CACHE 511
2079
2080 typedef
2081    struct { Addr ip; DebugInfo* di; Word ix; }
2082    CFSICacheEnt;
2083
2084 static CFSICacheEnt cfsi_cache[N_CFSI_CACHE];
2085
2086 static void cfsi_cache__invalidate ( void ) {
2087    VG_(memset)(&cfsi_cache, 0, sizeof(cfsi_cache));
2088 }
2089
2090
2091 static inline CFSICacheEnt* cfsi_cache__find ( Addr ip )
2092 {
2093    UWord         hash = ip % N_CFSI_CACHE;
2094    CFSICacheEnt* ce = &cfsi_cache[hash];
2095    static UWord  n_q = 0, n_m = 0;
2096
2097    n_q++;
2098    if (0 && 0 == (n_q & 0x1FFFFF))
2099       VG_(printf)("QQQ %lu %lu\n", n_q, n_m);
2100
2101    if (LIKELY(ce->ip == ip) && LIKELY(ce->di != NULL)) {
2102       /* found an entry in the cache .. */
2103    } else {
2104       /* not found in cache.  Search and update. */
2105       n_m++;
2106       ce->ip = ip;
2107       find_DiCfSI( &ce->di, &ce->ix, ip );
2108    }
2109
2110    if (UNLIKELY(ce->di == (DebugInfo*)1)) {
2111       /* no DiCfSI for this address */
2112       return NULL;
2113    } else {
2114       /* found a DiCfSI for this address */
2115       return ce;
2116    }
2117 }
2118
2119
2120 inline
2121 static Addr compute_cfa ( D3UnwindRegs* uregs,
2122                           Addr min_accessible, Addr max_accessible,
2123                           DebugInfo* di, DiCfSI* cfsi )
2124 {
2125    CfiExprEvalContext eec;
2126    Addr               cfa;
2127    Bool               ok;
2128
2129    /* Compute the CFA. */
2130    cfa = 0;
2131    switch (cfsi->cfa_how) {
2132 #     if defined(VGA_x86) || defined(VGA_amd64)
2133       case CFIC_IA_SPREL: 
2134          cfa = cfsi->cfa_off + uregs->xsp;
2135          break;
2136       case CFIC_IA_BPREL: 
2137          cfa = cfsi->cfa_off + uregs->xbp;
2138          break;
2139 #     elif defined(VGA_arm)
2140       case CFIC_ARM_R13REL: 
2141          cfa = cfsi->cfa_off + uregs->r13;
2142          break;
2143       case CFIC_ARM_R12REL: 
2144          cfa = cfsi->cfa_off + uregs->r12;
2145          break;
2146       case CFIC_ARM_R11REL: 
2147          cfa = cfsi->cfa_off + uregs->r11;
2148          break;
2149 #     elif defined(VGA_ppc32) || defined(VGA_ppc64)
2150 #     else
2151 #       error "Unsupported arch"
2152 #     endif
2153       case CFIC_EXPR: /* available on all archs */
2154          if (0) {
2155             VG_(printf)("CFIC_EXPR: ");
2156             ML_(ppCfiExpr)(di->cfsi_exprs, cfsi->cfa_off);
2157             VG_(printf)("\n");
2158          }
2159          eec.uregs          = uregs;
2160          eec.min_accessible = min_accessible;
2161          eec.max_accessible = max_accessible;
2162          ok = True;
2163          cfa = evalCfiExpr(di->cfsi_exprs, cfsi->cfa_off, &eec, &ok );
2164          if (!ok) return 0;
2165          break;
2166       default: 
2167          vg_assert(0);
2168    }
2169    return cfa;
2170 }
2171
2172
2173 /* Get the call frame address (CFA) given an IP/SP/FP triple. */
2174 /* NOTE: This function may rearrange the order of entries in the
2175    DebugInfo list. */
2176 Addr ML_(get_CFA) ( Addr ip, Addr sp, Addr fp,
2177                     Addr min_accessible, Addr max_accessible )
2178 {
2179    CFSICacheEnt* ce;
2180    DebugInfo*    di;
2181    DiCfSI*       cfsi;
2182
2183    ce = cfsi_cache__find(ip);
2184
2185    if (UNLIKELY(ce == NULL))
2186       return 0; /* no info.  Nothing we can do. */
2187
2188    di = ce->di;
2189    cfsi = &di->cfsi[ ce->ix ];
2190
2191    /* Temporary impedance-matching kludge so that this keeps working
2192       on x86-linux and amd64-linux. */
2193 #  if defined(VGA_x86) || defined(VGA_amd64)
2194    { D3UnwindRegs uregs;
2195      uregs.xip = ip;
2196      uregs.xsp = sp;
2197      uregs.xbp = fp;
2198      return compute_cfa(&uregs,
2199                         min_accessible,  max_accessible, di, cfsi);
2200    }
2201 #  else
2202    return 0; /* indicates failure */
2203 #  endif
2204 }
2205
2206
2207 /* The main function for DWARF2/3 CFI-based stack unwinding.  Given a
2208    set of registers in UREGS, modify it to hold the register values
2209    for the previous frame, if possible.  Returns True if successful.
2210    If not successful, *UREGS is not changed.
2211
2212    For x86 and amd64, the unwound registers are: {E,R}IP,
2213    {E,R}SP, {E,R}BP.
2214
2215    For arm, the unwound registers are: R11 R12 R13 R14 R15.
2216 */
2217 Bool VG_(use_CF_info) ( /*MOD*/D3UnwindRegs* uregsHere,
2218                         Addr min_accessible,
2219                         Addr max_accessible )
2220 {
2221    Bool               ok;
2222    DebugInfo*         di;
2223    DiCfSI*            cfsi = NULL;
2224    Addr               cfa, ipHere = 0;
2225    CFSICacheEnt*      ce;
2226    CfiExprEvalContext eec;
2227    D3UnwindRegs       uregsPrev;
2228
2229 #  if defined(VGA_x86) || defined(VGA_amd64)
2230    ipHere = uregsHere->xip;
2231 #  elif defined(VGA_arm)
2232    ipHere = uregsHere->r15;
2233 #  elif defined(VGA_ppc32) || defined(VGA_ppc64)
2234 #  else
2235 #    error "Unknown arch"
2236 #  endif
2237    ce = cfsi_cache__find(ipHere);
2238
2239    if (UNLIKELY(ce == NULL))
2240       return False; /* no info.  Nothing we can do. */
2241
2242    di = ce->di;
2243    cfsi = &di->cfsi[ ce->ix ];
2244
2245    if (0) {
2246       VG_(printf)("found cfisi: "); 
2247       ML_(ppDiCfSI)(di->cfsi_exprs, cfsi);
2248    }
2249
2250    VG_(bzero_inline)(&uregsPrev, sizeof(uregsPrev));
2251
2252    /* First compute the CFA. */
2253    cfa = compute_cfa(uregsHere,
2254                      min_accessible, max_accessible, di, cfsi);
2255    if (UNLIKELY(cfa == 0))
2256       return False;
2257
2258    /* Now we know the CFA, use it to roll back the registers we're
2259       interested in. */
2260
2261 #  define COMPUTE(_prev, _here, _how, _off)             \
2262       do {                                              \
2263          switch (_how) {                                \
2264             case CFIR_UNKNOWN:                          \
2265                return False;                            \
2266             case CFIR_SAME:                             \
2267                _prev = _here; break;                    \
2268             case CFIR_MEMCFAREL: {                      \
2269                Addr a = cfa + (Word)_off;               \
2270                if (a < min_accessible                   \
2271                    || a > max_accessible-sizeof(Addr))  \
2272                   return False;                         \
2273                _prev = *(Addr*)a;                       \
2274                break;                                   \
2275             }                                           \
2276             case CFIR_CFAREL:                           \
2277                _prev = cfa + (Word)_off;                \
2278                break;                                   \
2279             case CFIR_EXPR:                             \
2280                if (0)                                   \
2281                   ML_(ppCfiExpr)(di->cfsi_exprs,_off);  \
2282                eec.uregs = uregsHere;                   \
2283                eec.min_accessible = min_accessible;     \
2284                eec.max_accessible = max_accessible;     \
2285                ok = True;                               \
2286                _prev = evalCfiExpr(di->cfsi_exprs, _off, &eec, &ok ); \
2287                if (!ok) return False;                   \
2288                break;                                   \
2289             default:                                    \
2290                vg_assert(0);                            \
2291          }                                              \
2292       } while (0)
2293
2294 #  if defined(VGA_x86) || defined(VGA_amd64)
2295    COMPUTE(uregsPrev.xip, uregsHere->xip, cfsi->ra_how, cfsi->ra_off);
2296    COMPUTE(uregsPrev.xsp, uregsHere->xsp, cfsi->sp_how, cfsi->sp_off);
2297    COMPUTE(uregsPrev.xbp, uregsHere->xbp, cfsi->bp_how, cfsi->bp_off);
2298 #  elif defined(VGA_arm)
2299    COMPUTE(uregsPrev.r15, uregsHere->r15, cfsi->ra_how,  cfsi->ra_off);
2300    COMPUTE(uregsPrev.r14, uregsHere->r14, cfsi->r14_how, cfsi->r14_off);
2301    COMPUTE(uregsPrev.r13, uregsHere->r13, cfsi->r13_how, cfsi->r13_off);
2302    COMPUTE(uregsPrev.r12, uregsHere->r12, cfsi->r12_how, cfsi->r12_off);
2303    COMPUTE(uregsPrev.r11, uregsHere->r11, cfsi->r11_how, cfsi->r11_off);
2304 #  elif defined(VGA_ppc32) || defined(VGA_ppc64)
2305 #  else
2306 #    error "Unknown arch"
2307 #  endif
2308
2309 #  undef COMPUTE
2310
2311    *uregsHere = uregsPrev;
2312    return True;
2313 }
2314
2315
2316 /*--------------------------------------------------------------*/
2317 /*---                                                        ---*/
2318 /*--- TOP LEVEL: FOR UNWINDING THE STACK USING               ---*/
2319 /*---            MSVC FPO INFO                               ---*/
2320 /*---                                                        ---*/
2321 /*--------------------------------------------------------------*/
2322
2323 Bool VG_(use_FPO_info) ( /*MOD*/Addr* ipP,
2324                          /*MOD*/Addr* spP,
2325                          /*MOD*/Addr* fpP,
2326                          Addr min_accessible,
2327                          Addr max_accessible )
2328 {
2329    Word       i;
2330    DebugInfo* di;
2331    FPO_DATA*  fpo = NULL;
2332    Addr       spHere;
2333
2334    static UWord n_search = 0;
2335    static UWord n_steps = 0;
2336    n_search++;
2337
2338    if (0) VG_(printf)("search FPO for %#lx\n", *ipP);
2339
2340    for (di = debugInfo_list; di != NULL; di = di->next) {
2341       n_steps++;
2342
2343       /* Use the per-DebugInfo summary address ranges to skip
2344          inapplicable DebugInfos quickly. */
2345       if (di->fpo == NULL)
2346          continue;
2347       if (*ipP < di->fpo_minavma || *ipP > di->fpo_maxavma)
2348          continue;
2349
2350       i = ML_(search_one_fpotab)( di, *ipP );
2351       if (i != -1) {
2352          Word j;
2353          if (0) {
2354             /* debug printing only */
2355             VG_(printf)("look for %#lx  size %ld i %ld\n",
2356                         *ipP, di->fpo_size, i);
2357             for (j = 0; j < di->fpo_size; j++)
2358                VG_(printf)("[%02ld] %#x %d\n", 
2359                             j, di->fpo[j].ulOffStart, di->fpo[j].cbProcSize);
2360          }
2361          vg_assert(i >= 0 && i < di->fpo_size);
2362          fpo = &di->fpo[i];
2363          break;
2364       }
2365    }
2366
2367    if (fpo == NULL)
2368       return False;
2369
2370    if (0 && ((n_search & 0x7FFFF) == 0))
2371       VG_(printf)("VG_(use_FPO_info): %lu searches, "
2372                   "%lu DebugInfos looked at\n",
2373                   n_search, n_steps);
2374
2375
2376    /* Start of performance-enhancing hack: once every 64 (chosen
2377       hackily after profiling) successful searches, move the found
2378       DebugInfo one step closer to the start of the list.  This makes
2379       future searches cheaper.  For starting konqueror on amd64, this
2380       in fact reduces the total amount of searching done by the above
2381       find-the-right-DebugInfo loop by more than a factor of 20. */
2382    if ((n_search & 0x3F) == 0) {
2383       /* Move si one step closer to the start of the list. */
2384       //move_DebugInfo_one_step_forward( di );
2385    }
2386    /* End of performance-enhancing hack. */
2387
2388    if (0) {
2389       VG_(printf)("found fpo: ");
2390       //ML_(ppFPO)(fpo);
2391    }
2392
2393    /*
2394    Stack layout is:
2395    %esp->
2396       4*.cbRegs  {%edi, %esi, %ebp, %ebx}
2397       4*.cdwLocals
2398       return_pc
2399       4*.cdwParams
2400    prior_%esp->
2401
2402    Typical code looks like:
2403       sub $4*.cdwLocals,%esp
2404          Alternative to above for >=4KB (and sometimes for smaller):
2405             mov $size,%eax
2406             call __chkstk  # WinNT performs page-by-page probe!
2407                __chkstk is much like alloc(), except that on return
2408                %eax= 5+ &CALL.  Thus it could be used as part of
2409                Position Independent Code to locate the Global Offset Table.
2410       push %ebx
2411       push %ebp
2412       push %esi
2413          Other once-only instructions often scheduled >here<.
2414       push %edi
2415
2416    If the pc is within the first .cbProlog bytes of the function,
2417    then you must disassemble to see how many registers have been pushed,
2418    because instructions in the prolog may be scheduled for performance.
2419    The order of PUSH is always %ebx, %ebp, %esi, %edi, with trailing
2420    registers not pushed when .cbRegs < 4.  This seems somewhat strange
2421    because %ebp is the register whose usage you want to minimize,
2422    yet it is in the first half of the PUSH list.
2423
2424    I don't know what happens when the compiler constructs an outgoing CALL.
2425    %esp could move if outgoing parameters are PUSHed, and this affects
2426    traceback for errors during the PUSHes. */
2427  
2428    spHere = *spP;
2429
2430    *ipP = *(Addr *)(spHere + 4*(fpo->cbRegs + fpo->cdwLocals));
2431    *spP =           spHere + 4*(fpo->cbRegs + fpo->cdwLocals + 1 
2432                                             + fpo->cdwParams);
2433    *fpP = *(Addr *)(spHere + 4*2);
2434    return True;
2435 }
2436
2437
2438 /*--------------------------------------------------------------*/
2439 /*---                                                        ---*/
2440 /*--- TOP LEVEL: GENERATE DESCRIPTION OF DATA ADDRESSES      ---*/
2441 /*---            FROM DWARF3 DEBUG INFO                      ---*/
2442 /*---                                                        ---*/
2443 /*--------------------------------------------------------------*/
2444
2445 /* Try to make p2XA(dst, fmt, args..) turn into
2446    VG_(xaprintf_no_f_c)(dst, fmt, args) without having to resort to
2447    vararg macros.  As usual with everything to do with varargs, it's
2448    an ugly hack.
2449
2450    //#define p2XA(dstxa, format, args...)
2451    //   VG_(xaprintf_no_f_c)(dstxa, format, ##args)
2452 */
2453 #define  p2XA  VG_(xaprintf_no_f_c)
2454
2455 /* Add a zero-terminating byte to DST, which must be an XArray* of
2456    HChar. */
2457 static void zterm_XA ( XArray* dst )
2458 {
2459    HChar zero = 0;
2460    (void) VG_(addBytesToXA)( dst, &zero, 1 );
2461 }
2462
2463
2464 /* Evaluate the location expression/list for var, to see whether or
2465    not data_addr falls within the variable.  If so also return the
2466    offset of data_addr from the start of the variable.  Note that
2467    regs, which supplies ip,sp,fp values, will be NULL for global
2468    variables, and non-NULL for local variables. */
2469 static Bool data_address_is_in_var ( /*OUT*/PtrdiffT* offset,
2470                                      XArray* /* TyEnt */ tyents,
2471                                      DiVariable*   var,
2472                                      RegSummary*   regs,
2473                                      Addr          data_addr,
2474                                      const DebugInfo* di )
2475 {
2476    MaybeULong mul;
2477    SizeT      var_szB;
2478    GXResult   res;
2479    Bool       show = False;
2480
2481    vg_assert(var->name);
2482    vg_assert(var->gexpr);
2483
2484    /* Figure out how big the variable is. */
2485    mul = ML_(sizeOfType)(tyents, var->typeR);
2486    /* If this var has a type whose size is unknown, zero, or
2487       impossibly large, it should never have been added.  ML_(addVar)
2488       should have rejected it. */
2489    vg_assert(mul.b == True);
2490    vg_assert(mul.ul > 0);
2491    if (sizeof(void*) == 4) vg_assert(mul.ul < (1ULL << 32));
2492    /* After this point, we assume we can truncate mul.ul to a host word
2493       safely (without loss of info). */
2494
2495    var_szB = (SizeT)mul.ul; /* NB: truncate to host word */
2496
2497    if (show) {
2498       VG_(printf)("VVVV: data_address_%#lx_is_in_var: %s :: ",
2499                   data_addr, var->name );
2500       ML_(pp_TyEnt_C_ishly)( tyents, var->typeR );
2501       VG_(printf)("\n");
2502    }
2503
2504    /* ignore zero-sized vars; they can never match anything. */
2505    if (var_szB == 0) {
2506       if (show)
2507          VG_(printf)("VVVV: -> Fail (variable is zero sized)\n");
2508       return False;
2509    }
2510
2511    res = ML_(evaluate_GX)( var->gexpr, var->fbGX, regs, di );
2512
2513    if (show) {
2514       VG_(printf)("VVVV: -> ");
2515       ML_(pp_GXResult)( res );
2516       VG_(printf)("\n");
2517    }
2518
2519    if (res.kind == GXR_Addr 
2520        && res.word <= data_addr
2521        && data_addr < res.word + var_szB) {
2522       *offset = data_addr - res.word;
2523       return True;
2524    } else {
2525       return False;
2526    }
2527 }
2528
2529
2530 /* Format the acquired information into DN(AME)1 and DN(AME)2, which
2531    are XArray*s of HChar, that have been initialised by the caller.
2532    Resulting strings will be zero terminated.  Information is
2533    formatted in an understandable way.  Not so easy.  If frameNo is
2534    -1, this is assumed to be a global variable; else a local
2535    variable. */
2536 static void format_message ( /*MOD*/XArray* /* of HChar */ dn1,
2537                              /*MOD*/XArray* /* of HChar */ dn2,
2538                              Addr     data_addr,
2539                              DiVariable* var,
2540                              PtrdiffT var_offset,
2541                              PtrdiffT residual_offset,
2542                              XArray* /*UChar*/ described,
2543                              Int      frameNo, 
2544                              ThreadId tid )
2545 {
2546    Bool   have_descr, have_srcloc;
2547    Bool   xml       = VG_(clo_xml);
2548    UChar* vo_plural = var_offset == 1 ? "" : "s";
2549    UChar* ro_plural = residual_offset == 1 ? "" : "s";
2550    UChar* basetag   = "auxwhat"; /* a constant */
2551    UChar tagL[32], tagR[32], xagL[32], xagR[32];
2552
2553    vg_assert(frameNo >= -1);
2554    vg_assert(dn1 && dn2);
2555    vg_assert(described);
2556    vg_assert(var && var->name);
2557    have_descr = VG_(sizeXA)(described) > 0
2558                 && *(UChar*)VG_(indexXA)(described,0) != '\0';
2559    have_srcloc = var->fileName && var->lineNo > 0;
2560
2561    tagL[0] = tagR[0] = xagL[0] = xagR[0] = 0;
2562    if (xml) {
2563       VG_(sprintf)(tagL, "<%s>",   basetag); // <auxwhat>
2564       VG_(sprintf)(tagR, "</%s>",  basetag); // </auxwhat>
2565       VG_(sprintf)(xagL, "<x%s>",  basetag); // <xauxwhat>
2566       VG_(sprintf)(xagR, "</x%s>", basetag); // </xauxwhat>
2567    }
2568
2569 #  define TAGL(_xa) p2XA(_xa, "%s", tagL)
2570 #  define TAGR(_xa) p2XA(_xa, "%s", tagR)
2571 #  define XAGL(_xa) p2XA(_xa, "%s", xagL)
2572 #  define XAGR(_xa) p2XA(_xa, "%s", xagR)
2573 #  define TXTL(_xa) p2XA(_xa, "%s", "<text>")
2574 #  define TXTR(_xa) p2XA(_xa, "%s", "</text>")
2575
2576    /* ------ local cases ------ */
2577
2578    if ( frameNo >= 0 && (!have_srcloc) && (!have_descr) ) {
2579       /* no srcloc, no description:
2580          Location 0x7fefff6cf is 543 bytes inside local var "a",
2581          in frame #1 of thread 1
2582       */
2583       if (xml) {
2584          TAGL( dn1 );
2585          p2XA( dn1,
2586                "Location 0x%lx is %lu byte%s inside local var \"%t\",",
2587                data_addr, var_offset, vo_plural, var->name );
2588          TAGR( dn1 );
2589          TAGL( dn2 );
2590          p2XA( dn2,
2591                "in frame #%d of thread %d", frameNo, (Int)tid );
2592          TAGR( dn2 );
2593       } else {
2594          p2XA( dn1,
2595                "Location 0x%lx is %lu byte%s inside local var \"%s\",",
2596                data_addr, var_offset, vo_plural, var->name );
2597          p2XA( dn2,
2598                "in frame #%d of thread %d", frameNo, (Int)tid );
2599       }
2600    } 
2601    else
2602    if ( frameNo >= 0 && have_srcloc && (!have_descr) ) {
2603       /* no description:
2604          Location 0x7fefff6cf is 543 bytes inside local var "a"
2605          declared at dsyms7.c:17, in frame #1 of thread 1
2606       */
2607       if (xml) {
2608          TAGL( dn1 );
2609          p2XA( dn1,
2610                "Location 0x%lx is %lu byte%s inside local var \"%t\"",
2611                data_addr, var_offset, vo_plural, var->name );
2612          TAGR( dn1 );
2613          XAGL( dn2 );
2614          TXTL( dn2 );
2615          p2XA( dn2,
2616                "declared at %t:%d, in frame #%d of thread %d",
2617                var->fileName, var->lineNo, frameNo, (Int)tid );
2618          TXTR( dn2 );
2619          // FIXME: also do <dir>
2620          p2XA( dn2,
2621                " <file>%t</file> <line>%d</line> ", 
2622                var->fileName, var->lineNo );
2623          XAGR( dn2 );
2624       } else {
2625          p2XA( dn1,
2626                "Location 0x%lx is %lu byte%s inside local var \"%s\"",
2627                data_addr, var_offset, vo_plural, var->name );
2628          p2XA( dn2,
2629                "declared at %s:%d, in frame #%d of thread %d",
2630                var->fileName, var->lineNo, frameNo, (Int)tid );
2631       }
2632    }
2633    else
2634    if ( frameNo >= 0 && (!have_srcloc) && have_descr ) {
2635       /* no srcloc:
2636          Location 0x7fefff6cf is 2 bytes inside a[3].xyzzy[21].c2
2637          in frame #1 of thread 1
2638       */
2639       if (xml) {
2640          TAGL( dn1 );
2641          p2XA( dn1,
2642                "Location 0x%lx is %lu byte%s inside %t%t",
2643                data_addr, residual_offset, ro_plural, var->name,
2644                (HChar*)(VG_(indexXA)(described,0)) );
2645          TAGR( dn1 );
2646          TAGL( dn2 );
2647          p2XA( dn2,
2648                "in frame #%d of thread %d", frameNo, (Int)tid );
2649          TAGR( dn2 );
2650       } else {
2651          p2XA( dn1,
2652                "Location 0x%lx is %lu byte%s inside %s%s",
2653                data_addr, residual_offset, ro_plural, var->name,
2654                (HChar*)(VG_(indexXA)(described,0)) );
2655          p2XA( dn2,
2656                "in frame #%d of thread %d", frameNo, (Int)tid );
2657       }
2658    } 
2659    else
2660    if ( frameNo >= 0 && have_srcloc && have_descr ) {
2661       /* Location 0x7fefff6cf is 2 bytes inside a[3].xyzzy[21].c2,
2662          declared at dsyms7.c:17, in frame #1 of thread 1 */
2663       if (xml) {
2664          TAGL( dn1 );
2665          p2XA( dn1,
2666                "Location 0x%lx is %lu byte%s inside %t%t,",
2667                data_addr, residual_offset, ro_plural, var->name,
2668                (HChar*)(VG_(indexXA)(described,0)) );
2669          TAGR( dn1 );
2670          XAGL( dn2 );
2671          TXTL( dn2 );
2672          p2XA( dn2,
2673                "declared at %t:%d, in frame #%d of thread %d",
2674                var->fileName, var->lineNo, frameNo, (Int)tid );
2675          TXTR( dn2 );
2676          // FIXME: also do <dir>
2677          p2XA( dn2,
2678                " <file>%t</file> <line>%d</line> ",
2679                var->fileName, var->lineNo );
2680          XAGR( dn2 );
2681       } else {
2682          p2XA( dn1,
2683                "Location 0x%lx is %lu byte%s inside %s%s,",
2684                data_addr, residual_offset, ro_plural, var->name,
2685                (HChar*)(VG_(indexXA)(described,0)) );
2686          p2XA( dn2,
2687                "declared at %s:%d, in frame #%d of thread %d",
2688                var->fileName, var->lineNo, frameNo, (Int)tid );
2689       }
2690    }
2691    else
2692    /* ------ global cases ------ */
2693    if ( frameNo >= -1 && (!have_srcloc) && (!have_descr) ) {
2694       /* no srcloc, no description:
2695          Location 0x7fefff6cf is 543 bytes inside global var "a"
2696       */
2697       if (xml) {
2698          TAGL( dn1 );
2699          p2XA( dn1,
2700                "Location 0x%lx is %lu byte%s inside global var \"%t\"",
2701                data_addr, var_offset, vo_plural, var->name );
2702          TAGR( dn1 );
2703       } else {
2704          p2XA( dn1,
2705                "Location 0x%lx is %lu byte%s inside global var \"%s\"",
2706                data_addr, var_offset, vo_plural, var->name );
2707       }
2708    } 
2709    else
2710    if ( frameNo >= -1 && have_srcloc && (!have_descr) ) {
2711       /* no description:
2712          Location 0x7fefff6cf is 543 bytes inside global var "a"
2713          declared at dsyms7.c:17
2714       */
2715       if (xml) {
2716          TAGL( dn1 );
2717          p2XA( dn1,
2718                "Location 0x%lx is %lu byte%s inside global var \"%t\"",
2719                data_addr, var_offset, vo_plural, var->name );
2720          TAGR( dn1 );
2721          XAGL( dn2 );
2722          TXTL( dn2 );
2723          p2XA( dn2,
2724                "declared at %t:%d",
2725                var->fileName, var->lineNo);
2726          TXTR( dn2 );
2727          // FIXME: also do <dir>
2728          p2XA( dn2,
2729                " <file>%t</file> <line>%d</line> ",
2730                var->fileName, var->lineNo );
2731          XAGR( dn2 );
2732       } else {
2733          p2XA( dn1,
2734                "Location 0x%lx is %lu byte%s inside global var \"%s\"",
2735                data_addr, var_offset, vo_plural, var->name );
2736          p2XA( dn2,
2737                "declared at %s:%d",
2738                var->fileName, var->lineNo);
2739       }
2740    }
2741    else
2742    if ( frameNo >= -1 && (!have_srcloc) && have_descr ) {
2743       /* no srcloc:
2744          Location 0x7fefff6cf is 2 bytes inside a[3].xyzzy[21].c2,
2745          a global variable
2746       */
2747       if (xml) {
2748          TAGL( dn1 );
2749          p2XA( dn1,
2750                "Location 0x%lx is %lu byte%s inside %t%t,",
2751                data_addr, residual_offset, ro_plural, var->name,
2752                (HChar*)(VG_(indexXA)(described,0)) );
2753          TAGR( dn1 );
2754          TAGL( dn2 );
2755          p2XA( dn2,
2756                "a global variable");
2757          TAGR( dn2 );
2758       } else {
2759          p2XA( dn1,
2760                "Location 0x%lx is %lu byte%s inside %s%s,",
2761                data_addr, residual_offset, ro_plural, var->name,
2762                (char*)(VG_(indexXA)(described,0)) );
2763          p2XA( dn2,
2764                "a global variable");
2765       }
2766    } 
2767    else
2768    if ( frameNo >= -1 && have_srcloc && have_descr ) {
2769       /* Location 0x7fefff6cf is 2 bytes inside a[3].xyzzy[21].c2,
2770          a global variable declared at dsyms7.c:17 */
2771       if (xml) {
2772          TAGL( dn1 );
2773          p2XA( dn1,
2774                "Location 0x%lx is %lu byte%s inside %t%t,",
2775                data_addr, residual_offset, ro_plural, var->name,
2776                (HChar*)(VG_(indexXA)(described,0)) );
2777          TAGR( dn1 );
2778          XAGL( dn2 );
2779          TXTL( dn2 );
2780          p2XA( dn2,
2781                "a global variable declared at %t:%d",
2782                var->fileName, var->lineNo);
2783          TXTR( dn2 );
2784          // FIXME: also do <dir>
2785          p2XA( dn2,
2786                " <file>%t</file> <line>%d</line> ",
2787                var->fileName, var->lineNo );
2788          XAGR( dn2 );
2789       } else {
2790          p2XA( dn1,
2791                "Location 0x%lx is %lu byte%s inside %s%s,",
2792                data_addr, residual_offset, ro_plural, var->name,
2793                (HChar*)(VG_(indexXA)(described,0)) );
2794          p2XA( dn2,
2795                "a global variable declared at %s:%d",
2796                var->fileName, var->lineNo);
2797       }
2798    }
2799    else 
2800       vg_assert(0);
2801
2802    /* Zero terminate both strings */
2803    zterm_XA( dn1 );
2804    zterm_XA( dn2 );
2805
2806 #  undef TAGL
2807 #  undef TAGR
2808 #  undef XAGL
2809 #  undef XAGR
2810 #  undef TXTL
2811 #  undef TXTR
2812 }
2813
2814
2815 /* Determine if data_addr is a local variable in the frame
2816    characterised by (ip,sp,fp), and if so write its description at the
2817    ends of DNAME{1,2}, which are XArray*s of HChar, that have been
2818    initialised by the caller, zero terminate both, and return True.
2819    If it's not a local variable in said frame, return False. */
2820 static 
2821 Bool consider_vars_in_frame ( /*MOD*/XArray* /* of HChar */ dname1,
2822                               /*MOD*/XArray* /* of HChar */ dname2,
2823                               Addr data_addr,
2824                               Addr ip, Addr sp, Addr fp,
2825                               /* shown to user: */
2826                               ThreadId tid, Int frameNo )
2827 {
2828    Word       i;
2829    DebugInfo* di;
2830    RegSummary regs;
2831    Bool debug = False;
2832
2833    static UInt n_search = 0;
2834    static UInt n_steps = 0;
2835    n_search++;
2836    if (debug)
2837       VG_(printf)("QQQQ: cvif: ip,sp,fp %#lx,%#lx,%#lx\n", ip,sp,fp);
2838    /* first, find the DebugInfo that pertains to 'ip'. */
2839    for (di = debugInfo_list; di; di = di->next) {
2840       n_steps++;
2841       /* text segment missing? unlikely, but handle it .. */
2842       if (!di->text_present || di->text_size == 0)
2843          continue;
2844       /* Ok.  So does this text mapping bracket the ip? */
2845       if (di->text_avma <= ip && ip < di->text_avma + di->text_size)
2846          break;
2847    }
2848  
2849    /* Didn't find it.  Strange -- means ip is a code address outside
2850       of any mapped text segment.  Unlikely but not impossible -- app
2851       could be generating code to run. */
2852    if (!di)
2853       return False;
2854
2855    if (0 && ((n_search & 0x1) == 0))
2856       VG_(printf)("consider_vars_in_frame: %u searches, "
2857                   "%u DebugInfos looked at\n", 
2858                   n_search, n_steps);
2859    /* Start of performance-enhancing hack: once every ??? (chosen
2860       hackily after profiling) successful searches, move the found
2861       DebugInfo one step closer to the start of the list.  This makes
2862       future searches cheaper. */
2863    if ((n_search & 0xFFFF) == 0) {
2864       /* Move si one step closer to the start of the list. */
2865       move_DebugInfo_one_step_forward( di );
2866    }
2867    /* End of performance-enhancing hack. */
2868
2869    /* any var info at all? */
2870    if (!di->varinfo)
2871       return False;
2872
2873    /* Work through the scopes from most deeply nested outwards,
2874       looking for code address ranges that bracket 'ip'.  The
2875       variables on each such address range found are in scope right
2876       now.  Don't descend to level zero as that is the global
2877       scope. */
2878    regs.ip = ip;
2879    regs.sp = sp;
2880    regs.fp = fp;
2881
2882    /* "for each scope, working outwards ..." */
2883    for (i = VG_(sizeXA)(di->varinfo) - 1; i >= 1; i--) {
2884       XArray*      vars;
2885       Word         j;
2886       DiAddrRange* arange;
2887       OSet*        this_scope 
2888          = *(OSet**)VG_(indexXA)( di->varinfo, i );
2889       if (debug)
2890          VG_(printf)("QQQQ:   considering scope %ld\n", (Word)i);
2891       if (!this_scope)
2892          continue;
2893       /* Find the set of variables in this scope that
2894          bracket the program counter. */
2895       arange = VG_(OSetGen_LookupWithCmp)(
2896                   this_scope, &ip, 
2897                   ML_(cmp_for_DiAddrRange_range)
2898                );
2899       if (!arange)
2900          continue;
2901       /* stay sane */
2902       vg_assert(arange->aMin <= arange->aMax);
2903       /* It must bracket the ip we asked for, else
2904          ML_(cmp_for_DiAddrRange_range) is somehow broken. */
2905       vg_assert(arange->aMin <= ip && ip <= arange->aMax);
2906       /* It must have an attached XArray of DiVariables. */
2907       vars = arange->vars;
2908       vg_assert(vars);
2909       /* But it mustn't cover the entire address range.  We only
2910          expect that to happen for the global scope (level 0), which
2911          we're not looking at here.  Except, it may cover the entire
2912          address range, but in that case the vars array must be
2913          empty. */
2914       vg_assert(! (arange->aMin == (Addr)0
2915                    && arange->aMax == ~(Addr)0
2916                    && VG_(sizeXA)(vars) > 0) );
2917       for (j = 0; j < VG_(sizeXA)( vars ); j++) {
2918          DiVariable* var = (DiVariable*)VG_(indexXA)( vars, j );
2919          PtrdiffT    offset;
2920          if (debug)
2921             VG_(printf)("QQQQ:    var:name=%s %#lx-%#lx %#lx\n",
2922                         var->name,arange->aMin,arange->aMax,ip);
2923          if (data_address_is_in_var( &offset, di->admin_tyents,
2924                                      var, &regs,
2925                                      data_addr, di )) {
2926             PtrdiffT residual_offset = 0;
2927             XArray* described = ML_(describe_type)( &residual_offset,
2928                                                     di->admin_tyents, 
2929                                                     var->typeR, offset );
2930             format_message( dname1, dname2,
2931                             data_addr, var, offset, residual_offset,
2932                             described, frameNo, tid );
2933             VG_(deleteXA)( described );
2934             return True;
2935          }
2936       }
2937    }
2938
2939    return False;
2940 }
2941
2942 /* Try to form some description of DATA_ADDR by looking at the DWARF3
2943    debug info we have.  This considers all global variables, and all
2944    frames in the stacks of all threads.  Result is written at the ends
2945    of DNAME{1,2}V, which are XArray*s of HChar, that have been
2946    initialised by the caller, and True is returned.  If no description
2947    is created, False is returned.  Regardless of the return value,
2948    DNAME{1,2}V are guaranteed to be zero terminated after the call.
2949
2950    Note that after the call, DNAME{1,2} may have more than one
2951    trailing zero, so callers should establish the useful text length
2952    using VG_(strlen) on the contents, rather than VG_(sizeXA) on the
2953    XArray itself.
2954 */
2955 Bool VG_(get_data_description)( 
2956         /*MOD*/ void* /* really, XArray* of HChar */ dname1v,
2957         /*MOD*/ void* /* really, XArray* of HChar */ dname2v,
2958         Addr data_addr
2959      )
2960 {
2961 #  define N_FRAMES 8
2962    Addr ips[N_FRAMES], sps[N_FRAMES], fps[N_FRAMES];
2963    UInt n_frames;
2964
2965    Addr       stack_min, stack_max;
2966    ThreadId   tid;
2967    Bool       found;
2968    DebugInfo* di;
2969    Word       j;
2970
2971    XArray*    dname1 = (XArray*)dname1v;
2972    XArray*    dname2 = (XArray*)dname2v;
2973
2974    if (0) VG_(printf)("get_data_description: dataaddr %#lx\n", data_addr);
2975    /* First, see if data_addr is (or is part of) a global variable.
2976       Loop over the DebugInfos we have.  Check data_addr against the
2977       outermost scope of all of them, as that should be a global
2978       scope. */
2979    for (di = debugInfo_list; di != NULL; di = di->next) {
2980       OSet*        global_scope;
2981       Word         gs_size;
2982       Addr         zero;
2983       DiAddrRange* global_arange;
2984       Word         i;
2985       XArray*      vars;
2986
2987       /* text segment missing? unlikely, but handle it .. */
2988       if (!di->text_present || di->text_size == 0)
2989          continue;
2990       /* any var info at all? */
2991       if (!di->varinfo)
2992          continue;
2993       /* perhaps this object didn't contribute any vars at all? */
2994       if (VG_(sizeXA)( di->varinfo ) == 0)
2995          continue;
2996       global_scope = *(OSet**)VG_(indexXA)( di->varinfo, 0 );
2997       vg_assert(global_scope);
2998       gs_size = VG_(OSetGen_Size)( global_scope );
2999       /* The global scope might be completely empty if this
3000          compilation unit declared locals but nothing global. */
3001       if (gs_size == 0)
3002           continue;
3003       /* But if it isn't empty, then it must contain exactly one
3004          element, which covers the entire address range. */
3005       vg_assert(gs_size == 1);
3006       /* Fish out the global scope and check it is as expected. */
3007       zero = 0;
3008       global_arange 
3009          = VG_(OSetGen_Lookup)( global_scope, &zero );
3010       /* The global range from (Addr)0 to ~(Addr)0 must exist */
3011       vg_assert(global_arange);
3012       vg_assert(global_arange->aMin == (Addr)0
3013                 && global_arange->aMax == ~(Addr)0);
3014       /* Any vars in this range? */
3015       if (!global_arange->vars)
3016          continue;
3017       /* Ok, there are some vars in the global scope of this
3018          DebugInfo.  Wade through them and see if the data addresses
3019          of any of them bracket data_addr. */
3020       vars = global_arange->vars;
3021       for (i = 0; i < VG_(sizeXA)( vars ); i++) {
3022          PtrdiffT offset;
3023          DiVariable* var = (DiVariable*)VG_(indexXA)( vars, i );
3024          vg_assert(var->name);
3025          /* Note we use a NULL RegSummary* here.  It can't make any
3026             sense for a global variable to have a location expression
3027             which depends on a SP/FP/IP value.  So don't supply any.
3028             This means, if the evaluation of the location
3029             expression/list requires a register, we have to let it
3030             fail. */
3031          if (data_address_is_in_var( &offset, di->admin_tyents, var, 
3032                                      NULL/* RegSummary* */, 
3033                                      data_addr, di )) {
3034             PtrdiffT residual_offset = 0;
3035             XArray* described = ML_(describe_type)( &residual_offset,
3036                                                     di->admin_tyents,
3037                                                     var->typeR, offset );
3038             format_message( dname1, dname2,
3039                             data_addr, var, offset, residual_offset,
3040                             described, -1/*frameNo*/, tid );
3041             VG_(deleteXA)( described );
3042             zterm_XA( dname1 );
3043             zterm_XA( dname2 );
3044             return True;
3045          }
3046       }
3047    }
3048
3049    /* Ok, well it's not a global variable.  So now let's snoop around
3050       in the stacks of all the threads.  First try to figure out which
3051       thread's stack data_addr is in. */
3052
3053    /* --- KLUDGE --- Try examining the top frame of all thread stacks.
3054       This finds variables which are not stack allocated but are not
3055       globally visible either; specifically it appears to pick up
3056       variables which are visible only within a compilation unit.
3057       These will have the address range of the compilation unit and
3058       tend to live at Scope level 1. */
3059    VG_(thread_stack_reset_iter)(&tid);
3060    while ( VG_(thread_stack_next)(&tid, &stack_min, &stack_max) ) {
3061       if (stack_min >= stack_max)
3062          continue; /* ignore obviously stupid cases */
3063       if (consider_vars_in_frame( dname1, dname2,
3064                                   data_addr,
3065                                   VG_(get_IP)(tid),
3066                                   VG_(get_SP)(tid), 
3067                                   VG_(get_FP)(tid), tid, 0 )) {
3068          zterm_XA( dname1 );
3069          zterm_XA( dname2 );
3070          return True;
3071       }
3072    }
3073    /* --- end KLUDGE --- */
3074
3075    /* Perhaps it's on a thread's stack? */
3076    found = False;
3077    VG_(thread_stack_reset_iter)(&tid);
3078    while ( VG_(thread_stack_next)(&tid, &stack_min, &stack_max) ) {
3079       if (stack_min >= stack_max)
3080          continue; /* ignore obviously stupid cases */
3081       if (stack_min - VG_STACK_REDZONE_SZB <= data_addr
3082           && data_addr <= stack_max) {
3083          found = True;
3084          break;
3085       }
3086    }
3087    if (!found) {
3088       zterm_XA( dname1 );
3089       zterm_XA( dname2 );
3090       return False;
3091    }
3092
3093    /* We conclude data_addr is in thread tid's stack.  Unwind the
3094       stack to get a bunch of (ip,sp,fp) triples describing the
3095       frames, and for each frame, consider the local variables. */
3096    n_frames = VG_(get_StackTrace)( tid, ips, N_FRAMES,
3097                                    sps, fps, 0/*first_ip_delta*/ );
3098
3099    /* As a result of KLUDGE above, starting the loop at j = 0
3100       duplicates examination of the top frame and so isn't necessary.
3101       Oh well. */
3102    vg_assert(n_frames >= 0 && n_frames <= N_FRAMES);
3103    for (j = 0; j < n_frames; j++) {
3104       if (consider_vars_in_frame( dname1, dname2,
3105                                   data_addr,
3106                                   ips[j], 
3107                                   sps[j], fps[j], tid, j )) {
3108          zterm_XA( dname1 );
3109          zterm_XA( dname2 );
3110          return True;
3111       }
3112       /* Now, it appears that gcc sometimes appears to produce
3113          location lists whose ranges don't actually cover the call
3114          instruction, even though the address of the variable in
3115          question is passed as a parameter in the call.  AFAICS this
3116          is simply a bug in gcc - how can the variable be claimed not
3117          exist in memory (on the stack) for the duration of a call in
3118          which its address is passed?  But anyway, in the particular
3119          case I investigated (memcheck/tests/varinfo6.c, call to croak
3120          on line 2999, local var budget declared at line 3115
3121          appearing not to exist across the call to mainSort on line
3122          3143, "gcc.orig (GCC) 3.4.4 20050721 (Red Hat 3.4.4-2)" on
3123          amd64), the variable's location list does claim it exists
3124          starting at the first byte of the first instruction after the
3125          call instruction.  So, call consider_vars_in_frame a second
3126          time, but this time add 1 to the IP.  GDB handles this
3127          example with no difficulty, which leads me to believe that
3128          either (1) I misunderstood something, or (2) GDB has an
3129          equivalent kludge. */
3130       if (j > 0 /* this is a non-innermost frame */
3131           && consider_vars_in_frame( dname1, dname2,
3132                                      data_addr,
3133                                      ips[j] + 1, 
3134                                      sps[j], fps[j], tid, j )) {
3135          zterm_XA( dname1 );
3136          zterm_XA( dname2 );
3137          return True;
3138       }
3139    }
3140
3141    /* We didn't find anything useful. */
3142    zterm_XA( dname1 );
3143    zterm_XA( dname2 );
3144    return False;
3145 #  undef N_FRAMES
3146 }
3147
3148
3149 //////////////////////////////////////////////////////////////////
3150 //                                                              //
3151 // Support for other kinds of queries to the Dwarf3 var info    //
3152 //                                                              //
3153 //////////////////////////////////////////////////////////////////
3154
3155 /* Figure out if the variable 'var' has a location that is linearly
3156    dependent on a stack pointer value, or a frame pointer value, and
3157    if it is, add a description of it to 'blocks'.  Otherwise ignore
3158    it.  If 'arrays_only' is True, also ignore it unless it has an
3159    array type. */
3160
3161 static 
3162 void analyse_deps ( /*MOD*/XArray* /* of FrameBlock */ blocks,
3163                     XArray* /* TyEnt */ tyents,
3164                     Addr ip, const DebugInfo* di, DiVariable* var,
3165                     Bool arrays_only )
3166 {
3167    GXResult   res_sp_6k, res_sp_7k, res_fp_6k, res_fp_7k;
3168    RegSummary regs;
3169    MaybeULong mul;
3170    Bool       isVec;
3171    TyEnt*     ty;
3172
3173    Bool debug = False;
3174    if (0&&debug)
3175       VG_(printf)("adeps: var %s\n", var->name );
3176
3177    /* Figure out how big the variable is. */
3178    mul = ML_(sizeOfType)(tyents, var->typeR);
3179    /* If this var has a type whose size is unknown, zero, or
3180       impossibly large, it should never have been added.  ML_(addVar)
3181       should have rejected it. */
3182    vg_assert(mul.b == True);
3183    vg_assert(mul.ul > 0);
3184    if (sizeof(void*) == 4) vg_assert(mul.ul < (1ULL << 32));
3185    /* After this point, we assume we can truncate mul.ul to a host word
3186       safely (without loss of info). */
3187
3188    /* skip if non-array and we're only interested in arrays */
3189    ty = ML_(TyEnts__index_by_cuOff)( tyents, NULL, var->typeR );
3190    vg_assert(ty);
3191    vg_assert(ty->tag == Te_UNKNOWN || ML_(TyEnt__is_type)(ty));
3192    if (ty->tag == Te_UNKNOWN)
3193       return; /* perhaps we should complain in this case? */
3194    isVec = ty->tag == Te_TyArray;
3195    if (arrays_only && !isVec)
3196       return;
3197
3198    if (0) {ML_(pp_TyEnt_C_ishly)(tyents, var->typeR);
3199            VG_(printf)("  %s\n", var->name);}
3200
3201    /* Do some test evaluations of the variable's location expression,
3202       in order to guess whether it is sp-relative, fp-relative, or
3203       none.  A crude hack, which can be interpreted roughly as finding
3204       the first derivative of the location expression w.r.t. the
3205       supplied frame and stack pointer values. */
3206    regs.fp   = 0;
3207    regs.ip   = ip;
3208    regs.sp   = 6 * 1024;
3209    res_sp_6k = ML_(evaluate_GX)( var->gexpr, var->fbGX, &regs, di );
3210
3211    regs.fp   = 0;
3212    regs.ip   = ip;
3213    regs.sp   = 7 * 1024;
3214    res_sp_7k = ML_(evaluate_GX)( var->gexpr, var->fbGX, &regs, di );
3215
3216    regs.fp   = 6 * 1024;
3217    regs.ip   = ip;
3218    regs.sp   = 0;
3219    res_fp_6k = ML_(evaluate_GX)( var->gexpr, var->fbGX, &regs, di );
3220
3221    regs.fp   = 7 * 1024;
3222    regs.ip   = ip;
3223    regs.sp   = 0;
3224    res_fp_7k = ML_(evaluate_GX)( var->gexpr, var->fbGX, &regs, di );
3225
3226    vg_assert(res_sp_6k.kind == res_sp_7k.kind);
3227    vg_assert(res_sp_6k.kind == res_fp_6k.kind);
3228    vg_assert(res_sp_6k.kind == res_fp_7k.kind);
3229
3230    if (res_sp_6k.kind == GXR_Addr) {
3231       StackBlock block;
3232       GXResult res;
3233       UWord sp_delta = res_sp_7k.word - res_sp_6k.word;
3234       UWord fp_delta = res_fp_7k.word - res_fp_6k.word;
3235       tl_assert(sp_delta == 0 || sp_delta == 1024);
3236       tl_assert(fp_delta == 0 || fp_delta == 1024);
3237
3238       if (sp_delta == 0 && fp_delta == 0) {
3239          /* depends neither on sp nor fp, so it can't be a stack
3240             local.  Ignore it. */
3241       }
3242       else
3243       if (sp_delta == 1024 && fp_delta == 0) {
3244          regs.sp = regs.fp = 0;
3245          regs.ip = ip;
3246          res = ML_(evaluate_GX)( var->gexpr, var->fbGX, &regs, di );
3247          tl_assert(res.kind == GXR_Addr);
3248          if (debug)
3249          VG_(printf)("   %5ld .. %5ld (sp) %s\n",
3250                      res.word, res.word + ((UWord)mul.ul) - 1, var->name);
3251          block.base  = res.word;
3252          block.szB   = (SizeT)mul.ul;
3253          block.spRel = True;
3254          block.isVec = isVec;
3255          VG_(memset)( &block.name[0], 0, sizeof(block.name) );
3256          if (var->name)
3257             VG_(strncpy)( &block.name[0], var->name, sizeof(block.name)-1 );
3258          block.name[ sizeof(block.name)-1 ] = 0;
3259          VG_(addToXA)( blocks, &block );
3260       }
3261       else
3262       if (sp_delta == 0 && fp_delta == 1024) {
3263          regs.sp = regs.fp = 0;
3264          regs.ip = ip;
3265          res = ML_(evaluate_GX)( var->gexpr, var->fbGX, &regs, di );
3266          tl_assert(res.kind == GXR_Addr);
3267          if (debug)
3268          VG_(printf)("   %5ld .. %5ld (FP) %s\n",
3269                      res.word, res.word + ((UWord)mul.ul) - 1, var->name);
3270          block.base  = res.word;
3271          block.szB   = (SizeT)mul.ul;
3272          block.spRel = False;
3273          block.isVec = isVec;
3274          VG_(memset)( &block.name[0], 0, sizeof(block.name) );
3275          if (var->name)
3276             VG_(strncpy)( &block.name[0], var->name, sizeof(block.name)-1 );
3277          block.name[ sizeof(block.name)-1 ] = 0;
3278          VG_(addToXA)( blocks, &block );
3279       }
3280       else {
3281          vg_assert(0);
3282       }
3283    }
3284 }
3285
3286
3287 /* Get an XArray of StackBlock which describe the stack (auto) blocks
3288    for this ip.  The caller is expected to free the XArray at some
3289    point.  If 'arrays_only' is True, only array-typed blocks are
3290    returned; otherwise blocks of all types are returned. */
3291
3292 void* /* really, XArray* of StackBlock */
3293       VG_(di_get_stack_blocks_at_ip)( Addr ip, Bool arrays_only )
3294 {
3295    /* This is a derivation of consider_vars_in_frame() above. */
3296    Word       i;
3297    DebugInfo* di;
3298    RegSummary regs;
3299    Bool debug = False;
3300
3301    XArray* res = VG_(newXA)( ML_(dinfo_zalloc), "di.debuginfo.dgsbai.1",
3302                              ML_(dinfo_free),
3303                              sizeof(StackBlock) );
3304
3305    static UInt n_search = 0;
3306    static UInt n_steps = 0;
3307    n_search++;
3308    if (debug)
3309       VG_(printf)("QQQQ: dgsbai: ip %#lx\n", ip);
3310    /* first, find the DebugInfo that pertains to 'ip'. */
3311    for (di = debugInfo_list; di; di = di->next) {
3312       n_steps++;
3313       /* text segment missing? unlikely, but handle it .. */
3314       if (!di->text_present || di->text_size == 0)
3315          continue;
3316       /* Ok.  So does this text mapping bracket the ip? */
3317       if (di->text_avma <= ip && ip < di->text_avma + di->text_size)
3318          break;
3319    }
3320  
3321    /* Didn't find it.  Strange -- means ip is a code address outside
3322       of any mapped text segment.  Unlikely but not impossible -- app
3323       could be generating code to run. */
3324    if (!di)
3325       return res; /* currently empty */
3326
3327    if (0 && ((n_search & 0x1) == 0))
3328       VG_(printf)("VG_(di_get_stack_blocks_at_ip): %u searches, "
3329                   "%u DebugInfos looked at\n", 
3330                   n_search, n_steps);
3331    /* Start of performance-enhancing hack: once every ??? (chosen
3332       hackily after profiling) successful searches, move the found
3333       DebugInfo one step closer to the start of the list.  This makes
3334       future searches cheaper. */
3335    if ((n_search & 0xFFFF) == 0) {
3336       /* Move si one step closer to the start of the list. */
3337       move_DebugInfo_one_step_forward( di );
3338    }
3339    /* End of performance-enhancing hack. */
3340
3341    /* any var info at all? */
3342    if (!di->varinfo)
3343       return res; /* currently empty */
3344
3345    /* Work through the scopes from most deeply nested outwards,
3346       looking for code address ranges that bracket 'ip'.  The
3347       variables on each such address range found are in scope right
3348       now.  Don't descend to level zero as that is the global
3349       scope. */
3350    regs.ip = ip;
3351    regs.sp = 0;
3352    regs.fp = 0;
3353
3354    /* "for each scope, working outwards ..." */
3355    for (i = VG_(sizeXA)(di->varinfo) - 1; i >= 1; i--) {
3356       XArray*      vars;
3357       Word         j;
3358       DiAddrRange* arange;
3359       OSet*        this_scope 
3360          = *(OSet**)VG_(indexXA)( di->varinfo, i );
3361       if (debug)
3362          VG_(printf)("QQQQ:   considering scope %ld\n", (Word)i);
3363       if (!this_scope)
3364          continue;
3365       /* Find the set of variables in this scope that
3366          bracket the program counter. */
3367       arange = VG_(OSetGen_LookupWithCmp)(
3368                   this_scope, &ip, 
3369                   ML_(cmp_for_DiAddrRange_range)
3370                );
3371       if (!arange)
3372          continue;
3373       /* stay sane */
3374       vg_assert(arange->aMin <= arange->aMax);
3375       /* It must bracket the ip we asked for, else
3376          ML_(cmp_for_DiAddrRange_range) is somehow broken. */
3377       vg_assert(arange->aMin <= ip && ip <= arange->aMax);
3378       /* It must have an attached XArray of DiVariables. */
3379       vars = arange->vars;
3380       vg_assert(vars);
3381       /* But it mustn't cover the entire address range.  We only
3382          expect that to happen for the global scope (level 0), which
3383          we're not looking at here.  Except, it may cover the entire
3384          address range, but in that case the vars array must be
3385          empty. */
3386       vg_assert(! (arange->aMin == (Addr)0
3387                    && arange->aMax == ~(Addr)0
3388                    && VG_(sizeXA)(vars) > 0) );
3389       for (j = 0; j < VG_(sizeXA)( vars ); j++) {
3390          DiVariable* var = (DiVariable*)VG_(indexXA)( vars, j );
3391          if (debug)
3392             VG_(printf)("QQQQ:    var:name=%s %#lx-%#lx %#lx\n", 
3393                         var->name,arange->aMin,arange->aMax,ip);
3394          analyse_deps( res, di->admin_tyents, ip,
3395                        di, var, arrays_only );
3396       }
3397    }
3398
3399    return res;
3400 }
3401
3402
3403 /* Get an array of GlobalBlock which describe the global blocks owned
3404    by the shared object characterised by the given di_handle.  Asserts
3405    if the handle is invalid.  The caller is responsible for freeing
3406    the array at some point.  If 'arrays_only' is True, only
3407    array-typed blocks are returned; otherwise blocks of all types are
3408    returned. */
3409
3410 void* /* really, XArray* of GlobalBlock */
3411       VG_(di_get_global_blocks_from_dihandle) ( ULong di_handle,
3412                                                 Bool  arrays_only )
3413 {
3414    /* This is a derivation of consider_vars_in_frame() above. */
3415
3416    DebugInfo* di;
3417    XArray* gvars; /* XArray* of GlobalBlock */
3418    Word nScopes, scopeIx;
3419
3420    /* The first thing to do is find the DebugInfo that
3421       pertains to 'di_handle'. */
3422    tl_assert(di_handle > 0);
3423    for (di = debugInfo_list; di; di = di->next) {
3424       if (di->handle == di_handle)
3425          break;
3426    }
3427
3428    /* If this fails, we were unable to find any DebugInfo with the
3429       given handle.  This is considered an error on the part of the
3430       caller. */
3431    tl_assert(di != NULL);
3432
3433    /* we'll put the collected variables in here. */
3434    gvars = VG_(newXA)( ML_(dinfo_zalloc), "di.debuginfo.dggbfd.1",
3435                        ML_(dinfo_free), sizeof(GlobalBlock) );
3436    tl_assert(gvars);
3437
3438    /* any var info at all? */
3439    if (!di->varinfo)
3440       return gvars;
3441
3442    /* we'll iterate over all the variables we can find, even if
3443       it seems senseless to visit stack-allocated variables */
3444    /* Iterate over all scopes */
3445    nScopes = VG_(sizeXA)( di->varinfo );
3446    for (scopeIx = 0; scopeIx < nScopes; scopeIx++) {
3447
3448       /* Iterate over each (code) address range at the current scope */
3449       DiAddrRange* range;
3450       OSet* /* of DiAddrInfo */ scope
3451          = *(OSet**)VG_(indexXA)( di->varinfo, scopeIx );
3452       tl_assert(scope);
3453       VG_(OSetGen_ResetIter)(scope);
3454       while ( (range = VG_(OSetGen_Next)(scope)) ) {
3455
3456          /* Iterate over each variable in the current address range */
3457          Word nVars, varIx;
3458          tl_assert(range->vars);
3459          nVars = VG_(sizeXA)( range->vars );
3460          for (varIx = 0; varIx < nVars; varIx++) {
3461
3462             Bool        isVec;
3463             GXResult    res;
3464             MaybeULong  mul;
3465             GlobalBlock gb;
3466             TyEnt*      ty;
3467             DiVariable* var = VG_(indexXA)( range->vars, varIx );
3468             tl_assert(var->name);
3469             if (0) VG_(printf)("at depth %ld var %s ", scopeIx, var->name );
3470
3471             /* Now figure out if this variable has a constant address
3472                (that is, independent of FP, SP, phase of moon, etc),
3473                and if so, what the address is.  Any variable with a
3474                constant address is deemed to be a global so we collect
3475                it. */
3476             if (0) { VG_(printf)("EVAL: "); ML_(pp_GX)(var->gexpr);
3477                      VG_(printf)("\n"); }
3478             res = ML_(evaluate_trivial_GX)( var->gexpr, di );
3479
3480             /* Not a constant address => not interesting */
3481             if (res.kind != GXR_Addr) {
3482                if (0) VG_(printf)("FAIL\n");
3483                continue;
3484             }
3485
3486             /* Ok, it's a constant address.  See if we want to collect
3487                it. */
3488             if (0) VG_(printf)("%#lx\n", res.word);
3489
3490             /* Figure out how big the variable is. */
3491             mul = ML_(sizeOfType)(di->admin_tyents, var->typeR);
3492
3493             /* If this var has a type whose size is unknown, zero, or
3494                impossibly large, it should never have been added.
3495                ML_(addVar) should have rejected it. */
3496             vg_assert(mul.b == True);
3497             vg_assert(mul.ul > 0);
3498             if (sizeof(void*) == 4) vg_assert(mul.ul < (1ULL << 32));
3499             /* After this point, we assume we can truncate mul.ul to a
3500                host word safely (without loss of info). */
3501
3502             /* skip if non-array and we're only interested in
3503                arrays */
3504             ty = ML_(TyEnts__index_by_cuOff)( di->admin_tyents, NULL,
3505                                               var->typeR );
3506             vg_assert(ty);
3507             vg_assert(ty->tag == Te_UNKNOWN || ML_(TyEnt__is_type)(ty));
3508             if (ty->tag == Te_UNKNOWN)
3509                continue; /* perhaps we should complain in this case? */
3510
3511             isVec = ty->tag == Te_TyArray;
3512             if (arrays_only && !isVec) continue;
3513
3514             /* Ok, so collect it! */
3515             tl_assert(var->name);
3516             tl_assert(di->soname);
3517             if (0) VG_(printf)("XXXX %s %s %d\n", var->name,
3518                                 var->fileName?(HChar*)var->fileName
3519                                              :"??",var->lineNo);
3520             VG_(memset)(&gb, 0, sizeof(gb));
3521             gb.addr  = res.word;
3522             gb.szB   = (SizeT)mul.ul;
3523             gb.isVec = isVec;
3524             VG_(strncpy)(&gb.name[0], var->name, sizeof(gb.name)-1);
3525             VG_(strncpy)(&gb.soname[0], di->soname, sizeof(gb.soname)-1);
3526             tl_assert(gb.name[ sizeof(gb.name)-1 ] == 0);
3527             tl_assert(gb.soname[ sizeof(gb.soname)-1 ] == 0);
3528
3529             VG_(addToXA)( gvars, &gb );
3530
3531          } /* for (varIx = 0; varIx < nVars; varIx++) */
3532
3533       } /* while ( (range = VG_(OSetGen_Next)(scope)) ) */
3534
3535    } /* for (scopeIx = 0; scopeIx < nScopes; scopeIx++) */
3536
3537    return gvars;
3538 }
3539
3540
3541 /*------------------------------------------------------------*/
3542 /*--- DebugInfo accessor functions                         ---*/
3543 /*------------------------------------------------------------*/
3544
3545 const DebugInfo* VG_(next_DebugInfo)(const DebugInfo* di)
3546 {
3547    if (di == NULL)
3548       return debugInfo_list;
3549    return di->next;
3550 }
3551
3552 Addr VG_(DebugInfo_get_text_avma)(const DebugInfo* di)
3553 {
3554    return di->text_present ? di->text_avma : 0; 
3555 }
3556
3557 SizeT VG_(DebugInfo_get_text_size)(const DebugInfo* di)
3558 {
3559    return di->text_present ? di->text_size : 0; 
3560 }
3561
3562 Addr VG_(DebugInfo_get_plt_avma)(const DebugInfo* di)
3563 {
3564    return di->plt_present ? di->plt_avma : 0; 
3565 }
3566
3567 SizeT VG_(DebugInfo_get_plt_size)(const DebugInfo* di)
3568 {
3569    return di->plt_present ? di->plt_size : 0; 
3570 }
3571
3572 Addr VG_(DebugInfo_get_gotplt_avma)(const DebugInfo* di)
3573 {
3574    return di->gotplt_present ? di->gotplt_avma : 0; 
3575 }
3576
3577 SizeT VG_(DebugInfo_get_gotplt_size)(const DebugInfo* di)
3578 {
3579    return di->gotplt_present ? di->gotplt_size : 0; 
3580 }
3581
3582 const UChar* VG_(DebugInfo_get_soname)(const DebugInfo* di)
3583 {
3584    return di->soname;
3585 }
3586
3587 const UChar* VG_(DebugInfo_get_filename)(const DebugInfo* di)
3588 {
3589    return di->filename;
3590 }
3591
3592 PtrdiffT VG_(DebugInfo_get_text_bias)(const DebugInfo* di)
3593 {
3594    return di->text_present ? di->text_bias : 0;
3595 }
3596
3597 Int VG_(DebugInfo_syms_howmany) ( const DebugInfo *si )
3598 {
3599    return si->symtab_used;
3600 }
3601
3602 void VG_(DebugInfo_syms_getidx) ( const DebugInfo *si, 
3603                                         Int idx,
3604                                   /*OUT*/Addr*   avma,
3605                                   /*OUT*/Addr*   tocptr,
3606                                   /*OUT*/UInt*   size,
3607                                   /*OUT*/HChar** name,
3608                                   /*OUT*/Bool*   isText,
3609                                   /*OUT*/Bool*   isIFunc )
3610 {
3611    vg_assert(idx >= 0 && idx < si->symtab_used);
3612    if (avma)    *avma    = si->symtab[idx].addr;
3613    if (tocptr)  *tocptr  = si->symtab[idx].tocptr;
3614    if (size)    *size    = si->symtab[idx].size;
3615    if (name)    *name    = (HChar*)si->symtab[idx].name;
3616    if (isText)  *isText  = si->symtab[idx].isText;
3617    if (isIFunc) *isIFunc = si->symtab[idx].isIFunc;
3618 }
3619
3620
3621 /*------------------------------------------------------------*/
3622 /*--- SectKind query functions                             ---*/
3623 /*------------------------------------------------------------*/
3624
3625 /* Convert a VgSectKind to a string, which must be copied if you want
3626    to change it. */
3627 const HChar* VG_(pp_SectKind)( VgSectKind kind )
3628 {
3629    switch (kind) {
3630       case Vg_SectUnknown: return "Unknown";
3631       case Vg_SectText:    return "Text";
3632       case Vg_SectData:    return "Data";
3633       case Vg_SectBSS:     return "BSS";
3634       case Vg_SectGOT:     return "GOT";
3635       case Vg_SectPLT:     return "PLT";
3636       case Vg_SectOPD:     return "OPD";
3637       case Vg_SectGOTPLT:  return "GOTPLT";
3638       default:             vg_assert(0);
3639    }
3640 }
3641
3642 /* Given an address 'a', make a guess of which section of which object
3643    it comes from.  If name is non-NULL, then the last n_name-1
3644    characters of the object's name is put in name[0 .. n_name-2], and
3645    name[n_name-1] is set to zero (guaranteed zero terminated). */
3646
3647 VgSectKind VG_(DebugInfo_sect_kind)( /*OUT*/UChar* name, SizeT n_name, 
3648                                      Addr a)
3649 {
3650    DebugInfo* di;
3651    VgSectKind res = Vg_SectUnknown;
3652
3653    for (di = debugInfo_list; di != NULL; di = di->next) {
3654
3655       if (0)
3656          VG_(printf)(
3657             "addr=%#lx di=%p %s got=%#lx,%ld plt=%#lx,%ld "
3658             "data=%#lx,%ld bss=%#lx,%ld\n",
3659             a, di, di->filename,
3660             di->got_avma,  di->got_size,
3661             di->plt_avma,  di->plt_size,
3662             di->data_avma, di->data_size,
3663             di->bss_avma,  di->bss_size);
3664
3665       if (di->text_present
3666           && di->text_size > 0
3667           && a >= di->text_avma && a < di->text_avma + di->text_size) {
3668          res = Vg_SectText;
3669          break;
3670       }
3671       if (di->data_present
3672           && di->data_size > 0
3673           && a >= di->data_avma && a < di->data_avma + di->data_size) {
3674          res = Vg_SectData;
3675          break;
3676       }
3677       if (di->sdata_present
3678           && di->sdata_size > 0
3679           && a >= di->sdata_avma && a < di->sdata_avma + di->sdata_size) {
3680          res = Vg_SectData;
3681          break;
3682       }
3683       if (di->bss_present
3684           && di->bss_size > 0
3685           && a >= di->bss_avma && a < di->bss_avma + di->bss_size) {
3686          res = Vg_SectBSS;
3687          break;
3688       }
3689       if (di->sbss_present
3690           && di->sbss_size > 0
3691           && a >= di->sbss_avma && a < di->sbss_avma + di->sbss_size) {
3692          res = Vg_SectBSS;
3693          break;
3694       }
3695       if (di->plt_present
3696           && di->plt_size > 0
3697           && a >= di->plt_avma && a < di->plt_avma + di->plt_size) {
3698          res = Vg_SectPLT;
3699          break;
3700       }
3701       if (di->got_present
3702           && di->got_size > 0
3703           && a >= di->got_avma && a < di->got_avma + di->got_size) {
3704          res = Vg_SectGOT;
3705          break;
3706       }
3707       if (di->gotplt_present
3708           && di->gotplt_size > 0
3709           && a >= di->gotplt_avma && a < di->gotplt_avma + di->gotplt_size) {
3710          res = Vg_SectGOTPLT;
3711          break;
3712       }
3713       if (di->opd_present
3714           && di->opd_size > 0
3715           && a >= di->opd_avma && a < di->opd_avma + di->opd_size) {
3716          res = Vg_SectOPD;
3717          break;
3718       }
3719       /* we could also check for .eh_frame, if anyone really cares */
3720    }
3721
3722    vg_assert( (di == NULL && res == Vg_SectUnknown)
3723               || (di != NULL && res != Vg_SectUnknown) );
3724
3725    if (name) {
3726
3727       vg_assert(n_name >= 8);
3728
3729       if (di && di->filename) {
3730          Int i, j;
3731          Int fnlen = VG_(strlen)(di->filename);
3732          Int start_at = 1 + fnlen - n_name;
3733          if (start_at < 0) start_at = 0;
3734          vg_assert(start_at < fnlen);
3735          i = start_at; j = 0;
3736          while (True) {
3737             vg_assert(j >= 0 && j < n_name);
3738             vg_assert(i >= 0 && i <= fnlen);
3739             name[j] = di->filename[i];
3740             if (di->filename[i] == 0) break;
3741             i++; j++;
3742          }
3743          vg_assert(i == fnlen);
3744       } else {
3745          VG_(snprintf)(name, n_name, "%s", "???");
3746       }
3747
3748       name[n_name-1] = 0;
3749    }
3750
3751    return res;
3752
3753 }
3754
3755 /*--------------------------------------------------------------------*/
3756 /*--- end                                                          ---*/
3757 /*--------------------------------------------------------------------*/