PageRenderTime 153ms CodeModel.GetById 82ms app.highlight 65ms RepoModel.GetById 1ms app.codeStats 0ms

/thirdparty/breakpad/processor/stackwalker_x86.cc

http://github.com/tomahawk-player/tomahawk
C++ | 604 lines | 278 code | 63 blank | 263 comment | 57 complexity | 56aee0e7d611424e4c99c0f7a6a5a9ea MD5 | raw file
  1// Copyright (c) 2010 Google Inc.
  2// All rights reserved.
  3//
  4// Redistribution and use in source and binary forms, with or without
  5// modification, are permitted provided that the following conditions are
  6// met:
  7//
  8//     * Redistributions of source code must retain the above copyright
  9// notice, this list of conditions and the following disclaimer.
 10//     * Redistributions in binary form must reproduce the above
 11// copyright notice, this list of conditions and the following disclaimer
 12// in the documentation and/or other materials provided with the
 13// distribution.
 14//     * Neither the name of Google Inc. nor the names of its
 15// contributors may be used to endorse or promote products derived from
 16// this software without specific prior written permission.
 17//
 18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 29
 30// stackwalker_x86.cc: x86-specific stackwalker.
 31//
 32// See stackwalker_x86.h for documentation.
 33//
 34// Author: Mark Mentovai
 35
 36
 37#include "processor/postfix_evaluator-inl.h"
 38
 39#include "google_breakpad/processor/call_stack.h"
 40#include "google_breakpad/processor/code_modules.h"
 41#include "google_breakpad/processor/memory_region.h"
 42#include "google_breakpad/processor/source_line_resolver_interface.h"
 43#include "google_breakpad/processor/stack_frame_cpu.h"
 44#include "processor/logging.h"
 45#include "processor/scoped_ptr.h"
 46#include "processor/stackwalker_x86.h"
 47#include "processor/windows_frame_info.h"
 48#include "processor/cfi_frame_info.h"
 49
 50namespace google_breakpad {
 51
 52
 53const StackwalkerX86::CFIWalker::RegisterSet
 54StackwalkerX86::cfi_register_map_[] = {
 55  // It may seem like $eip and $esp are callee-saves, because (with Unix or
 56  // cdecl calling conventions) the callee is responsible for having them
 57  // restored upon return. But the callee_saves flags here really means
 58  // that the walker should assume they're unchanged if the CFI doesn't
 59  // mention them, which is clearly wrong for $eip and $esp.
 60  { "$eip", ".ra",  false,
 61    StackFrameX86::CONTEXT_VALID_EIP, &MDRawContextX86::eip },
 62  { "$esp", ".cfa", false,
 63    StackFrameX86::CONTEXT_VALID_ESP, &MDRawContextX86::esp },
 64  { "$ebp", NULL,   true,
 65    StackFrameX86::CONTEXT_VALID_EBP, &MDRawContextX86::ebp },
 66  { "$eax", NULL,   false,
 67    StackFrameX86::CONTEXT_VALID_EAX, &MDRawContextX86::eax },
 68  { "$ebx", NULL,   true,
 69    StackFrameX86::CONTEXT_VALID_EBX, &MDRawContextX86::ebx },
 70  { "$ecx", NULL,   false,
 71    StackFrameX86::CONTEXT_VALID_ECX, &MDRawContextX86::ecx },
 72  { "$edx", NULL,   false,
 73    StackFrameX86::CONTEXT_VALID_EDX, &MDRawContextX86::edx },
 74  { "$esi", NULL,   true,
 75    StackFrameX86::CONTEXT_VALID_ESI, &MDRawContextX86::esi },
 76  { "$edi", NULL,   true,
 77    StackFrameX86::CONTEXT_VALID_EDI, &MDRawContextX86::edi },
 78};
 79
 80StackwalkerX86::StackwalkerX86(const SystemInfo *system_info,
 81                               const MDRawContextX86 *context,
 82                               MemoryRegion *memory,
 83                               const CodeModules *modules,
 84                               SymbolSupplier *supplier,
 85                               SourceLineResolverInterface *resolver)
 86    : Stackwalker(system_info, memory, modules, supplier, resolver),
 87      context_(context),
 88      cfi_walker_(cfi_register_map_,
 89                  (sizeof(cfi_register_map_) / sizeof(cfi_register_map_[0]))) {
 90  if (memory_->GetBase() + memory_->GetSize() - 1 > 0xffffffff) {
 91    // The x86 is a 32-bit CPU, the limits of the supplied stack are invalid.
 92    // Mark memory_ = NULL, which will cause stackwalking to fail.
 93    BPLOG(ERROR) << "Memory out of range for stackwalking: " <<
 94                    HexString(memory_->GetBase()) << "+" <<
 95                    HexString(memory_->GetSize());
 96    memory_ = NULL;
 97  }
 98}
 99
100StackFrameX86::~StackFrameX86() {
101  if (windows_frame_info)
102    delete windows_frame_info;
103  windows_frame_info = NULL;
104  if (cfi_frame_info)
105    delete cfi_frame_info;
106  cfi_frame_info = NULL;
107}
108
109StackFrame *StackwalkerX86::GetContextFrame() {
110  if (!context_ || !memory_) {
111    BPLOG(ERROR) << "Can't get context frame without context or memory";
112    return NULL;
113  }
114
115  StackFrameX86 *frame = new StackFrameX86();
116
117  // The instruction pointer is stored directly in a register, so pull it
118  // straight out of the CPU context structure.
119  frame->context = *context_;
120  frame->context_validity = StackFrameX86::CONTEXT_VALID_ALL;
121  frame->trust = StackFrame::FRAME_TRUST_CONTEXT;
122  frame->instruction = frame->context.eip;
123
124  return frame;
125}
126
127StackFrameX86 *StackwalkerX86::GetCallerByWindowsFrameInfo(
128    const vector<StackFrame *> &frames,
129    WindowsFrameInfo *last_frame_info) {
130  StackFrame::FrameTrust trust = StackFrame::FRAME_TRUST_NONE;
131
132  StackFrameX86 *last_frame = static_cast<StackFrameX86 *>(frames.back());
133
134  // Save the stack walking info we found, in case we need it later to
135  // find the callee of the frame we're constructing now.
136  last_frame->windows_frame_info = last_frame_info;
137
138  // This function only covers the full STACK WIN case. If
139  // last_frame_info is VALID_PARAMETER_SIZE-only, then we should
140  // assume the traditional frame format or use some other strategy.
141  if (last_frame_info->valid != WindowsFrameInfo::VALID_ALL)
142    return NULL;
143
144  // This stackwalker sets each frame's %esp to its value immediately prior
145  // to the CALL into the callee.  This means that %esp points to the last
146  // callee argument pushed onto the stack, which may not be where %esp points
147  // after the callee returns.  Specifically, the value is correct for the
148  // cdecl calling convention, but not other conventions.  The cdecl
149  // convention requires a caller to pop its callee's arguments from the
150  // stack after the callee returns.  This is usually accomplished by adding
151  // the known size of the arguments to %esp.  Other calling conventions,
152  // including stdcall, thiscall, and fastcall, require the callee to pop any
153  // parameters stored on the stack before returning.  This is usually
154  // accomplished by using the RET n instruction, which pops n bytes off
155  // the stack after popping the return address.
156  //
157  // Because each frame's %esp will point to a location on the stack after
158  // callee arguments have been PUSHed, when locating things in a stack frame
159  // relative to %esp, the size of the arguments to the callee need to be
160  // taken into account.  This seems a little bit unclean, but it's better
161  // than the alternative, which would need to take these same things into
162  // account, but only for cdecl functions.  With this implementation, we get
163  // to be agnostic about each function's calling convention.  Furthermore,
164  // this is how Windows debugging tools work, so it means that the %esp
165  // values produced by this stackwalker directly correspond to the %esp
166  // values you'll see there.
167  //
168  // If the last frame has no callee (because it's the context frame), just
169  // set the callee parameter size to 0: the stack pointer can't point to
170  // callee arguments because there's no callee.  This is correct as long
171  // as the context wasn't captured while arguments were being pushed for
172  // a function call.  Note that there may be functions whose parameter sizes
173  // are unknown, 0 is also used in that case.  When that happens, it should
174  // be possible to walk to the next frame without reference to %esp.
175
176  u_int32_t last_frame_callee_parameter_size = 0;
177  int frames_already_walked = frames.size();
178  if (frames_already_walked >= 2) {
179    const StackFrameX86 *last_frame_callee
180        = static_cast<StackFrameX86 *>(frames[frames_already_walked - 2]);
181    WindowsFrameInfo *last_frame_callee_info
182        = last_frame_callee->windows_frame_info;
183    if (last_frame_callee_info &&
184        (last_frame_callee_info->valid
185         & WindowsFrameInfo::VALID_PARAMETER_SIZE)) {
186      last_frame_callee_parameter_size =
187          last_frame_callee_info->parameter_size;
188    }
189  }
190
191  // Set up the dictionary for the PostfixEvaluator.  %ebp and %esp are used
192  // in each program string, and their previous values are known, so set them
193  // here.
194  PostfixEvaluator<u_int32_t>::DictionaryType dictionary;
195  // Provide the current register values.
196  dictionary["$ebp"] = last_frame->context.ebp;
197  dictionary["$esp"] = last_frame->context.esp;
198  // Provide constants from the debug info for last_frame and its callee.
199  // .cbCalleeParams is a Breakpad extension that allows us to use the
200  // PostfixEvaluator engine when certain types of debugging information
201  // are present without having to write the constants into the program
202  // string as literals.
203  dictionary[".cbCalleeParams"] = last_frame_callee_parameter_size;
204  dictionary[".cbSavedRegs"] = last_frame_info->saved_register_size;
205  dictionary[".cbLocals"] = last_frame_info->local_size;
206
207  u_int32_t raSearchStart = last_frame->context.esp +
208                            last_frame_callee_parameter_size +
209                            last_frame_info->local_size +
210                            last_frame_info->saved_register_size;
211
212  u_int32_t raSearchStartOld = raSearchStart;
213  u_int32_t found = 0; // dummy value
214  // Scan up to three words above the calculated search value, in case
215  // the stack was aligned to a quadword boundary.
216  if (ScanForReturnAddress(raSearchStart, &raSearchStart, &found, 3) &&
217      last_frame->trust == StackFrame::FRAME_TRUST_CONTEXT &&
218      last_frame->windows_frame_info != NULL &&
219      last_frame_info->type_ == WindowsFrameInfo::STACK_INFO_FPO &&
220      raSearchStartOld == raSearchStart &&
221      found == last_frame->context.eip) {
222    // The context frame represents an FPO-optimized Windows system call.
223    // On the top of the stack we have a pointer to the current instruction.
224    // This means that the callee has returned but the return address is still
225    // on the top of the stack which is very atypical situaltion.
226    // Skip one slot from the stack and do another scan in order to get the
227    // actual return address.
228    raSearchStart += 4;
229    ScanForReturnAddress(raSearchStart, &raSearchStart, &found, 3);
230  }
231
232  // The difference between raSearch and raSearchStart is unknown,
233  // but making them the same seems to work well in practice.
234  dictionary[".raSearchStart"] = raSearchStart;
235  dictionary[".raSearch"] = raSearchStart;
236
237  dictionary[".cbParams"] = last_frame_info->parameter_size;
238
239  // Decide what type of program string to use. The program string is in
240  // postfix notation and will be passed to PostfixEvaluator::Evaluate.
241  // Given the dictionary and the program string, it is possible to compute
242  // the return address and the values of other registers in the calling
243  // function. Because of bugs described below, the stack may need to be
244  // scanned for these values. The results of program string evaluation
245  // will be used to determine whether to scan for better values.
246  string program_string;
247  bool recover_ebp = true;
248
249  trust = StackFrame::FRAME_TRUST_CFI;
250  if (!last_frame_info->program_string.empty()) {
251    // The FPO data has its own program string, which will tell us how to
252    // get to the caller frame, and may even fill in the values of
253    // nonvolatile registers and provide pointers to local variables and
254    // parameters.  In some cases, particularly with program strings that use
255    // .raSearchStart, the stack may need to be scanned afterward.
256    program_string = last_frame_info->program_string;
257  } else if (last_frame_info->allocates_base_pointer) {
258    // The function corresponding to the last frame doesn't use the frame
259    // pointer for conventional purposes, but it does allocate a new
260    // frame pointer and use it for its own purposes.  Its callee's
261    // information is still accessed relative to %esp, and the previous
262    // value of %ebp can be recovered from a location in its stack frame,
263    // within the saved-register area.
264    //
265    // Functions that fall into this category use the %ebp register for
266    // a purpose other than the frame pointer.  They restore the caller's
267    // %ebp before returning.  These functions create their stack frame
268    // after a CALL by decrementing the stack pointer in an amount
269    // sufficient to store local variables, and then PUSHing saved
270    // registers onto the stack.  Arguments to a callee function, if any,
271    // are PUSHed after that.  Walking up to the caller, therefore,
272    // can be done solely with calculations relative to the stack pointer
273    // (%esp).  The return address is recovered from the memory location
274    // above the known sizes of the callee's parameters, saved registers,
275    // and locals.  The caller's stack pointer (the value of %esp when
276    // the caller executed CALL) is the location immediately above the
277    // saved return address.  The saved value of %ebp to be restored for
278    // the caller is at a known location in the saved-register area of
279    // the stack frame.
280    //
281    // For this type of frame, MSVC 14 (from Visual Studio 8/2005) in
282    // link-time code generation mode (/LTCG and /GL) can generate erroneous
283    // debugging data.  The reported size of saved registers can be 0,
284    // which is clearly an error because these frames must, at the very
285    // least, save %ebp.  For this reason, in addition to those given above
286    // about the use of .raSearchStart, the stack may need to be scanned
287    // for a better return address and a better frame pointer after the
288    // program string is evaluated.
289    //
290    // %eip_new = *(%esp_old + callee_params + saved_regs + locals)
291    // %ebp_new = *(%esp_old + callee_params + saved_regs - 8)
292    // %esp_new = %esp_old + callee_params + saved_regs + locals + 4
293    program_string = "$eip .raSearchStart ^ = "
294        "$ebp $esp .cbCalleeParams + .cbSavedRegs + 8 - ^ = "
295        "$esp .raSearchStart 4 + =";
296  } else {
297    // The function corresponding to the last frame doesn't use %ebp at
298    // all.  The callee frame is located relative to %esp.
299    //
300    // The called procedure's instruction pointer and stack pointer are
301    // recovered in the same way as the case above, except that no
302    // frame pointer (%ebp) is used at all, so it is not saved anywhere
303    // in the callee's stack frame and does not need to be recovered.
304    // Because %ebp wasn't used in the callee, whatever value it has
305    // is the value that it had in the caller, so it can be carried
306    // straight through without bringing its validity into question.
307    //
308    // Because of the use of .raSearchStart, the stack will possibly be
309    // examined to locate a better return address after program string
310    // evaluation.  The stack will not be examined to locate a saved
311    // %ebp value, because these frames do not save (or use) %ebp.
312    //
313    // %eip_new = *(%esp_old + callee_params + saved_regs + locals)
314    // %esp_new = %esp_old + callee_params + saved_regs + locals + 4
315    // %ebp_new = %ebp_old
316    program_string = "$eip .raSearchStart ^ = "
317        "$esp .raSearchStart 4 + =";
318    recover_ebp = false;
319  }
320
321  // Now crank it out, making sure that the program string set at least the
322  // two required variables.
323  PostfixEvaluator<u_int32_t> evaluator =
324      PostfixEvaluator<u_int32_t>(&dictionary, memory_);
325  PostfixEvaluator<u_int32_t>::DictionaryValidityType dictionary_validity;
326  if (!evaluator.Evaluate(program_string, &dictionary_validity) ||
327      dictionary_validity.find("$eip") == dictionary_validity.end() ||
328      dictionary_validity.find("$esp") == dictionary_validity.end()) {
329    // Program string evaluation failed. It may be that %eip is not somewhere
330    // with stack frame info, and %ebp is pointing to non-stack memory, so
331    // our evaluation couldn't succeed. We'll scan the stack for a return
332    // address. This can happen if the stack is in a module for which
333    // we don't have symbols, and that module is compiled without a
334    // frame pointer.
335    u_int32_t location_start = last_frame->context.esp;
336    u_int32_t location, eip;
337    if (!ScanForReturnAddress(location_start, &location, &eip)) {
338      // if we can't find an instruction pointer even with stack scanning,
339      // give up.
340      return NULL;
341    }
342
343    // This seems like a reasonable return address. Since program string
344    // evaluation failed, use it and set %esp to the location above the
345    // one where the return address was found.
346    dictionary["$eip"] = eip;
347    dictionary["$esp"] = location + 4;
348    trust = StackFrame::FRAME_TRUST_SCAN;
349  }
350
351  // Since this stack frame did not use %ebp in a traditional way,
352  // locating the return address isn't entirely deterministic. In that
353  // case, the stack can be scanned to locate the return address.
354  //
355  // However, if program string evaluation resulted in both %eip and
356  // %ebp values of 0, trust that the end of the stack has been
357  // reached and don't scan for anything else.
358  if (dictionary["$eip"] != 0 || dictionary["$ebp"] != 0) {
359    int offset = 0;
360
361    // This scan can only be done if a CodeModules object is available, to
362    // check that candidate return addresses are in fact inside a module.
363    //
364    // TODO(mmentovai): This ignores dynamically-generated code.  One possible
365    // solution is to check the minidump's memory map to see if the candidate
366    // %eip value comes from a mapped executable page, although this would
367    // require dumps that contain MINIDUMP_MEMORY_INFO, which the Breakpad
368    // client doesn't currently write (it would need to call MiniDumpWriteDump
369    // with the MiniDumpWithFullMemoryInfo type bit set).  Even given this
370    // ability, older OSes (pre-XP SP2) and CPUs (pre-P4) don't enforce
371    // an independent execute privilege on memory pages.
372
373    u_int32_t eip = dictionary["$eip"];
374    if (modules_ && !modules_->GetModuleForAddress(eip)) {
375      // The instruction pointer at .raSearchStart was invalid, so start
376      // looking one 32-bit word above that location.
377      u_int32_t location_start = dictionary[".raSearchStart"] + 4;
378      u_int32_t location;
379      if (ScanForReturnAddress(location_start, &location, &eip)) {
380        // This is a better return address that what program string
381        // evaluation found.  Use it, and set %esp to the location above the
382        // one where the return address was found.
383        dictionary["$eip"] = eip;
384        dictionary["$esp"] = location + 4;
385        offset = location - location_start;
386        trust = StackFrame::FRAME_TRUST_CFI_SCAN;
387      }
388    }
389
390    // When trying to recover the previous value of the frame pointer (%ebp),
391    // start looking at the lowest possible address in the saved-register
392    // area, and look at the entire saved register area, increased by the
393    // size of |offset| to account for additional data that may be on the
394    // stack.  The scan is performed from the highest possible address to
395    // the lowest, because we expect that the function's prolog would have
396    // saved %ebp early.
397    u_int32_t ebp = dictionary["$ebp"];
398    u_int32_t value;  // throwaway variable to check pointer validity
399    if (recover_ebp && !memory_->GetMemoryAtAddress(ebp, &value)) {
400      int fp_search_bytes = last_frame_info->saved_register_size + offset;
401      u_int32_t location_end = last_frame->context.esp +
402                               last_frame_callee_parameter_size;
403
404      for (u_int32_t location = location_end + fp_search_bytes;
405           location >= location_end;
406           location -= 4) {
407        if (!memory_->GetMemoryAtAddress(location, &ebp))
408          break;
409
410        if (memory_->GetMemoryAtAddress(ebp, &value)) {
411          // The candidate value is a pointer to the same memory region
412          // (the stack).  Prefer it as a recovered %ebp result.
413          dictionary["$ebp"] = ebp;
414          break;
415        }
416      }
417    }
418  }
419
420  // Create a new stack frame (ownership will be transferred to the caller)
421  // and fill it in.
422  StackFrameX86 *frame = new StackFrameX86();
423
424  frame->trust = trust;
425  frame->context = last_frame->context;
426  frame->context.eip = dictionary["$eip"];
427  frame->context.esp = dictionary["$esp"];
428  frame->context.ebp = dictionary["$ebp"];
429  frame->context_validity = StackFrameX86::CONTEXT_VALID_EIP |
430                                StackFrameX86::CONTEXT_VALID_ESP |
431                                StackFrameX86::CONTEXT_VALID_EBP;
432
433  // These are nonvolatile (callee-save) registers, and the program string
434  // may have filled them in.
435  if (dictionary_validity.find("$ebx") != dictionary_validity.end()) {
436    frame->context.ebx = dictionary["$ebx"];
437    frame->context_validity |= StackFrameX86::CONTEXT_VALID_EBX;
438  }
439  if (dictionary_validity.find("$esi") != dictionary_validity.end()) {
440    frame->context.esi = dictionary["$esi"];
441    frame->context_validity |= StackFrameX86::CONTEXT_VALID_ESI;
442  }
443  if (dictionary_validity.find("$edi") != dictionary_validity.end()) {
444    frame->context.edi = dictionary["$edi"];
445    frame->context_validity |= StackFrameX86::CONTEXT_VALID_EDI;
446  }
447
448  return frame;
449}
450
451StackFrameX86 *StackwalkerX86::GetCallerByCFIFrameInfo(
452    const vector<StackFrame*> &frames,
453    CFIFrameInfo *cfi_frame_info) {
454  StackFrameX86 *last_frame = static_cast<StackFrameX86*>(frames.back());
455  last_frame->cfi_frame_info = cfi_frame_info;
456
457  scoped_ptr<StackFrameX86> frame(new StackFrameX86());
458  if (!cfi_walker_
459      .FindCallerRegisters(*memory_, *cfi_frame_info,
460                           last_frame->context, last_frame->context_validity,
461                           &frame->context, &frame->context_validity))
462    return NULL;
463  
464  // Make sure we recovered all the essentials.
465  static const int essentials = (StackFrameX86::CONTEXT_VALID_EIP
466                                 | StackFrameX86::CONTEXT_VALID_ESP
467                                 | StackFrameX86::CONTEXT_VALID_EBP);
468  if ((frame->context_validity & essentials) != essentials)
469    return NULL;
470
471  frame->trust = StackFrame::FRAME_TRUST_CFI;
472
473  return frame.release();
474}
475
476StackFrameX86 *StackwalkerX86::GetCallerByEBPAtBase(
477    const vector<StackFrame *> &frames) {
478  StackFrame::FrameTrust trust;
479  StackFrameX86 *last_frame = static_cast<StackFrameX86 *>(frames.back());
480  u_int32_t last_esp = last_frame->context.esp;
481  u_int32_t last_ebp = last_frame->context.ebp;
482
483  // Assume that the standard %ebp-using x86 calling convention is in
484  // use.
485  //
486  // The typical x86 calling convention, when frame pointers are present,
487  // is for the calling procedure to use CALL, which pushes the return
488  // address onto the stack and sets the instruction pointer (%eip) to
489  // the entry point of the called routine.  The called routine then
490  // PUSHes the calling routine's frame pointer (%ebp) onto the stack
491  // before copying the stack pointer (%esp) to the frame pointer (%ebp).
492  // Therefore, the calling procedure's frame pointer is always available
493  // by dereferencing the called procedure's frame pointer, and the return
494  // address is always available at the memory location immediately above
495  // the address pointed to by the called procedure's frame pointer.  The
496  // calling procedure's stack pointer (%esp) is 8 higher than the value
497  // of the called procedure's frame pointer at the time the calling
498  // procedure made the CALL: 4 bytes for the return address pushed by the
499  // CALL itself, and 4 bytes for the callee's PUSH of the caller's frame
500  // pointer.
501  //
502  // %eip_new = *(%ebp_old + 4)
503  // %esp_new = %ebp_old + 8
504  // %ebp_new = *(%ebp_old)
505
506  u_int32_t caller_eip, caller_esp, caller_ebp;
507
508  if (memory_->GetMemoryAtAddress(last_ebp + 4, &caller_eip) &&
509      memory_->GetMemoryAtAddress(last_ebp, &caller_ebp)) {
510    caller_esp = last_ebp + 8;
511    trust = StackFrame::FRAME_TRUST_FP;
512  } else {
513    // We couldn't read the memory %ebp refers to. It may be that %ebp
514    // is pointing to non-stack memory. We'll scan the stack for a
515    // return address. This can happen if last_frame is executing code
516    // for a module for which we don't have symbols, and that module
517    // is compiled without a frame pointer.
518    if (!ScanForReturnAddress(last_esp, &caller_esp, &caller_eip)) {
519      // if we can't find an instruction pointer even with stack scanning,
520      // give up.
521      return NULL;
522    }
523
524    // ScanForReturnAddress found a reasonable return address. Advance
525    // %esp to the location above the one where the return address was
526    // found. Assume that %ebp is unchanged.
527    caller_esp += 4;
528    caller_ebp = last_ebp;
529
530    trust = StackFrame::FRAME_TRUST_SCAN;
531  }
532
533  // Create a new stack frame (ownership will be transferred to the caller)
534  // and fill it in.
535  StackFrameX86 *frame = new StackFrameX86();
536
537  frame->trust = trust;
538  frame->context = last_frame->context;
539  frame->context.eip = caller_eip;
540  frame->context.esp = caller_esp;
541  frame->context.ebp = caller_ebp;
542  frame->context_validity = StackFrameX86::CONTEXT_VALID_EIP |
543                            StackFrameX86::CONTEXT_VALID_ESP |
544                            StackFrameX86::CONTEXT_VALID_EBP;
545
546  return frame;
547}
548
549StackFrame *StackwalkerX86::GetCallerFrame(const CallStack *stack) {
550  if (!memory_ || !stack) {
551    BPLOG(ERROR) << "Can't get caller frame without memory or stack";
552    return NULL;
553  }
554
555  const vector<StackFrame *> &frames = *stack->frames();
556  StackFrameX86 *last_frame = static_cast<StackFrameX86 *>(frames.back());
557  scoped_ptr<StackFrameX86> new_frame;
558
559  // If the resolver has Windows stack walking information, use that.
560  WindowsFrameInfo *windows_frame_info
561      = resolver_ ? resolver_->FindWindowsFrameInfo(last_frame) : NULL;
562  if (windows_frame_info)
563    new_frame.reset(GetCallerByWindowsFrameInfo(frames, windows_frame_info));
564
565  // If the resolver has DWARF CFI information, use that.
566  if (!new_frame.get()) {
567    CFIFrameInfo *cfi_frame_info = 
568        resolver_ ? resolver_->FindCFIFrameInfo(last_frame) : NULL;
569    if (cfi_frame_info)
570      new_frame.reset(GetCallerByCFIFrameInfo(frames, cfi_frame_info));
571  }
572
573  // Otherwise, hope that the program was using a traditional frame structure.
574  if (!new_frame.get())
575    new_frame.reset(GetCallerByEBPAtBase(frames));
576
577  // If nothing worked, tell the caller.
578  if (!new_frame.get())
579    return NULL;
580  
581  // Treat an instruction address of 0 as end-of-stack.
582  if (new_frame->context.eip == 0)
583    return NULL;
584
585  // If the new stack pointer is at a lower address than the old, then
586  // that's clearly incorrect. Treat this as end-of-stack to enforce
587  // progress and avoid infinite loops.
588  if (new_frame->context.esp <= last_frame->context.esp)
589    return NULL;
590
591  // new_frame->context.eip is the return address, which is one instruction
592  // past the CALL that caused us to arrive at the callee. Set
593  // new_frame->instruction to one less than that. This won't reference the
594  // beginning of the CALL instruction, but it's guaranteed to be within
595  // the CALL, which is sufficient to get the source line information to
596  // match up with the line that contains a function call. Callers that
597  // require the exact return address value may access the context.eip
598  // field of StackFrameX86.
599  new_frame->instruction = new_frame->context.eip - 1;
600
601  return new_frame.release();
602}
603
604}  // namespace google_breakpad