    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Microsoft Visual C++ and Win32 Structured Exception
Handling</title>
        <link>https://members.accu.org/index.php/articles/245</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #63 - Oct 2004</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c149/">63</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-149/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+149/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Microsoft Visual C++ and Win32 Structured Exception
Handling</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 01 October 2004 16:25:39 +01:00 or Fri, 01 October 2004 16:25:39 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e18" id="d0e18"></a></h2>
</div>
<p>In an earlier article [<a href="#Orr2004">Orr2004</a>] I
described some performance measurements when using exceptions in
various languages on Windows.</p>
<p>A couple of people since then have asked me questions about how
the windows exception model actually works and how it is used to
implement <tt class="literal">try...catch</tt> constructs in
MSVC.</p>
<p>That's quite a big question to answer, and this article is a
start. There is quite a lot written about how to use these language
features safely; but much less written about how they are
implemented. There are several good reasons for this:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>lessons learned about the language features themselves apply to
all versions of standard C++, whatever the platform, whereas
details of the implementation are specific to both the vendor and
the platform.</p>
</li>
<li>
<p>knowing how it works is not necessary to using it</p>
</li>
<li>
<p>the details are very sketchily documented and not guaranteed by
Microsoft to remain unchanged</p>
</li>
</ul>
</div>
<p>On the other hand I for one like to know what is going on &quot;under
the covers&quot; so that:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>I can satisfy my 'how do they do that?' curiosity</p>
</li>
<li>
<p>I can understand the flow of control when trying to debug
application problems</p>
</li>
<li>
<p>I can perhaps provide some platform specific value-added
services.</p>
</li>
</ul>
</div>
<p>In order to give some motivation to the investigation here's my
task: I want to develop an 'exception helper' so I can print out a
simple call stack for a caught C++ exception. Java and C# both let
you print the stack trace for the exception, but standard C++ does
not provide a way to do this. Although I understand why this
feature is not part of the language I do miss it in C++ and would
like to do what I can towards providing it for a specific platform,
in this case MSVC.</p>
<p>There are some, rather intrusive, source level solutions
involving adding code to the constructors of all exception types
used in your application or adding code to each use of throw. This
sort of solution means you must change the way exceptions are used
throughout the code base which can be a large task even if you have
access to all the source code, and impossible if not.</p>
<p>I'll describe writing a class for the MSVC compiler so that this
code:</p>
<pre class="programlisting">
void testStackTrace() {
  ExceptionStackTrace helper;
  try {
    doSomethingWhichMightThrow();
  }
  catch(std::exception &amp; ex) {
    std::cerr &lt;&lt; &quot;Exception occurred: &quot;
              &lt;&lt; ex.what() &lt;&lt; std::endl;
    helper.printStackTrace( std::cerr );
  }
}
</pre>
<p>prints out a stack trace for the exception:</p>
<pre class="literallayout">
Exception occurred: A sample error...
  Frame       Code address
  0x0012FE70  0x7C57E592 RaiseException+0x55
  0x0012FEB0  0x7C359AED CxxThrowException+0x34
  0x0012FF10  0x004013CA throwIt+0x4a at
                    teststacktrace.cpp(32)
  0x0012FF18  0x004013E8
                    doSomethingWhichMightThrow+0x8
                    at teststacktrace.cpp(37)
  0x0012FF58  0x0040142A testStackTrace+0x3a at
                    teststacktrace.cpp(45)
  0x0012FF60  0x004014A8 main+0x8 at
                    teststacktrace.cpp(57)
  0x0012FFC0  0x00404E87 mainCRTStartup+0x143 at
                    crtexe.c(398)
  0x0012FFF0  0x7C581AF6 OpenEventA+0x63d
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e66" id="d0e66"></a>Processing the
Stack Trace</h2>
</div>
<p>Microsoft provide a debugging library, <tt class=
"filename">DbgHelp.dll</tt>, which provides among other things
functions to walk up the stack and print out the return addresses.
A full description of <tt class="filename">DbgHelp.dll</tt> is
outside the scope of this article - I refer you to Matt Peitrek's
MSJ article [<a href="#Pietrek2">Pietrek2</a>] or John Robbins'
book [<a href="#Robbins">Robbins</a>] if you want more details.</p>
<p>The <tt class="function">StackWalk()</tt> function provided by
<tt class="filename">DbgHelp.dll</tt> takes nine parameters, but
the key ones are a <i class="parameter"><tt>StackFrame</tt></i> and
a <i class="parameter"><tt>ContextRecord</tt></i>. The <i class=
"parameter"><tt>StackFrame</tt></i> is an in/out parameter used to
contain data for successive stack frames and the <i class=
"parameter"><tt>ContextRecord</tt></i> contains the thread state in
a platform dependent manner. (Different definitions of the
structure are given in WinNt.h and the correct one is picked by the
C++ preprocessor). The <i class=
"parameter"><tt>ContextRecord</tt></i> is technically optional, but
contains enough information to initialise the <i class=
"parameter"><tt>StackFrame</tt></i> and also improve the
reliability of the <tt class="function">StackWalk</tt> function so
it is preferable to require one.</p>
<p>So here is a function prototype for a simple stack trace routine
implemented using the functionality of <tt class=
"filename">DbgHelp.dll</tt>:</p>
<pre class="programlisting">
void SimpleSymbolEngine::StackTrace(
                     CONTEXT *pContextRecord,
                     std::ostream &amp; os);
</pre>
<p>The implementation of this function sets up <i class=
"structfield"><tt>AddrPC</tt></i>, <i class=
"structfield"><tt>AddrFrame</tt></i> and <i class=
"structfield"><tt>AddrStack</tt></i> in a <span class=
"structname">StackFrame</span> record from the <tt class=
"literal">Eip</tt>, <tt class="literal">Ebp</tt> and <tt class=
"literal">Esp</tt> registers in the context record and then calls
<tt class="function">StackWalk</tt> repeatedly until the stack walk
is completed. Each frame address is printed, together with the
return address. Two functions in the <tt class=
"filename">DbgHelp</tt> library (<tt class=
"function">SymGetSymFromAddr</tt> and <tt class=
"function">SymGetLineFromAddr</tt>) are called to get any symbolic
information available for the return address. Note that even if you
don't have debug symbols for your program (and DLLs) <tt class=
"filename">DbgHelp</tt> will try to provide information based on
any exported names from in DLLs.</p>
<p>A context record can be obtained in a variety of ways. As it is
simply a snapshot of the thread state it could be built up manually
using inline assembler to populate the various fields from CPU
registers - or more easily by using the <tt class=
"function">GetThreadContext</tt> call. The operating system also
uses them in various places when managing thread state and finally
they also crop up in exception handling.</p>
<p>The main reason to write the <tt class=
"classname">ExceptionHelper</tt> class is to obtain the context
record of the thread state when the exception occurred. We can then
use this key piece of data to extract the stack trace. Let's look
at Microsoft's implementation of try, throw and catch in Win32 C++
to see how it lets us build something to extract this
information.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e167" id="d0e167"></a>Structured
Exception Handling</h2>
</div>
<p>Microsoft integrated standard C++ exception handling with
window's own exception handling model: so-called &quot;structured
exception handling&quot; or &quot;SEH&quot; and this section tries to give an
overview of what is happening inside SEH from an application's
viewpoint - however you don't need to completely understand the
principles to follow the <tt class="classname">ExceptionHelper</tt>
code.</p>
<p>The definitive article about Win32 structured exception handling
is by Matt Peitrek [<a href="#Pietrek1">Pietrek1</a>] and I refer
interested readers there. However, his article focuses on the
Microsoft extensions to support SEH: <tt class="literal">_try</tt>,
<tt class="literal">_except</tt> and <tt class=
"literal">_finally</tt> and less on the language native concepts
embodied in <tt class="literal">try</tt>, <tt class=
"literal">throw</tt>, etc. Other articles, such as [<a href=
"#Gordon">Gordon</a>], focus on what is happening at the assembler
level which is great for the minority of programmers who understand
assembler but not for the rest.</p>
<p>There is a relatively natural fit between the SEH exception
model and the <tt class="literal">try...catch</tt> exception model
in programming languages such as C++ so it is not too surprising
that Microsoft decided to use this operating system level
structured exception handling to provide the basis for their C++
exception handling code. However other implementors of C++ on the
Win32 platform have not necessarily followed the same pattern.</p>
<p>Windows provides a portable exception architecture which
recognises two main type of exceptions: 'system' exceptions such as
an access violation or an integer divide by zero, which are also
known as 'asynchronous' exceptions, and 'user' exceptions generated
by a call to <tt class="function">RaiseException()</tt>, which are
also known as 'synchronous' exceptions. Each thread contains a
linked list of exception handlers and when an exception occurs
information about the exception and a context record for the thread
are passed to each exception handler in the chain in turn for
possible processing. There are several things each handler can do;
the commonest cases are:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>return 'keep looking' (and the next exception handler will be
called)</p>
</li>
<li>
<p>unwind the thread context back to a known state and execute a
failure path (in C++, a catch block).</p>
</li>
</ul>
</div>
<p>If the context is to be unwound then each exception handler
which is unwound off the stack is called so it can perform any
required tidy-up. If all of the exception handlers return 'keep
looking' the operating system has a final, process wide, exception
handler which by default produces one of the 'Application Error'
popups.</p>
<p>(Note that this is a slight simplification of the full
picture)</p>
<p>Each handler has a signature like this:</p>
<pre class="programlisting">
DWORD exceptionHandler(
           EXCEPTION_RECORD *pException,
           EXCEPTION_REGISTRATION_RECORD
                        *pRegistrationRecord,
           CONTEXT *pContext);
</pre>
<p>Where:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><i class="parameter"><tt>pException</tt></i> contains
information about the exception being processed, such as the
exception code and the fault address.</p>
</li>
<li>
<p><i class="parameter"><tt>pRegistrationRecord</tt></i> points to
the current node in the list of exception handlers</p>
</li>
<li>
<p><i class="parameter"><tt>pContext</tt></i> contains the
processor-specific thread state when the exception occurred</p>
</li>
</ul>
</div>
<p>Our task is to retain the thread context from the last parameter
so we can use it later in a call to the <tt class=
"function">StackTrace</tt> function.</p>
<p>What makes this exception style 'structured' is that the chain
of exception handlers exists in the thread's own stack. In a
typically block-structured programming language each call to a
function, method or procedure pushes a new activation frame onto
the stack; this frame contains the current arguments, any local
variables and the exception handler for this function (if any).
Additionally, the algorithm which passes the exception along the
chain of handlers naturally moves from the most recently called
function up the stack to the top-most function.</p>
<p>In the Win32 world the <tt class="literal">ESP</tt> register
contains the current stack pointer, by convention the current frame
pointer is usually held in the <tt class="literal">EBP</tt>
register and the <tt class="literal">FS</tt> selector register
holds the base of the thread information block (<tt class=
"literal">TIB</tt>) which holds, among other things, the head of
the exception chain.</p>
<p>To try and make this clearer here is a schematic representation
of the bottom of the stack when function A has called function B
which in turn has called function C.</p>
<p>Functions A and C have an SEH handler, but function B
doesn't.</p>
<div class="c2"><img src="/var/uploads/journals/resources/orr-diag-revised.png" align=
"middle"></div>
<p>Inside the each stack frame the function arguments are above the
frame register (and appear in assembler as [<tt class=
"literal">EBP</tt> + offset]) and local variables are below the
frame register (and appear in assembler as [<tt class=
"literal">EBP</tt> - offset]). In practice things are more
complicated than this - particularly when the optimiser gets
involved - and the frame register <tt class="literal">EBP</tt> can
get used for other purposes. To reduce the complexity of this
article I'm not going to worry about optimised code.</p>
<p>We need insert our own exception helper object into the chain of
exception registration records so we can extract the context record
for the thrown exception.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e280" id="d0e280"></a>MSVC
Exception Handling</h2>
</div>
<p>Before we can write our own exception handler we need to know a
bit about how MSVC makes use of SEH handling to implement C++
exceptions. I've annotated the following code fragment with some of
the key places that SEH handling is involved.</p>
<pre class="programlisting">
void thrower() {
  SomeClass anObject;  // 5
  throw std::runtime_error(&quot;An error&quot;); // 2
}
void catcher() {  // 1
  std::string functionName(&quot;catcher&quot;);
  try {
    thrower();
  }
  catch(std::exception &amp; ex) {  // 3
    std::cerr &lt;&lt; functionName &lt;&lt; &quot;: &quot;
              &lt;&lt; ex.what() &lt;&lt; std::endl;
  }
}  // 4
</pre>
<div class="orderedlist">
<ol type="1">
<li>
<p>When you write a function containing <tt class=
"literal">try...catch</tt> the Microsoft compiler adds code to the
function prolog to register a structured exception handler for this
function at the head of the thread's exception handler chain. The
actual structure created for the exception registration extends the
basic EXCEPTION_REGISTRATION_RECORD; the additional fields are used
for managing the exception handling state and recovering the stack
pointer.</p>
</li>
<li>
<p><tt class="literal">Throw</tt> is implemented by calling
<tt class="function">RaiseException</tt> with a special exception
code 0xe06d7363 (the low bits spell 'msc' in ascii). Other fields
in the exception record are set up to hold the address and run-time
type of the thrown object - in this case a <tt class=
"classname">std::runtime_error</tt> object.</p>
</li>
<li>
<p>The <tt class="literal">catch</tt> code is actually implemented
by the exception handler. If the exception being handled has the
special exception code value then the run-time type information is
extracted and compared to the type of the argument in the
<tt class="literal">catch</tt> statement. If a match is found (or a
conversion is possible) then the exception chain is unwound and the
body of the <tt class="literal">catch</tt> is entered, after which
the execution will continue directly after the <tt class=
"literal">try...catch</tt> block. If a match is not found the
exception handler returns the 'keep looking' value and the new
handler in the chain will be tried.</p>
</li>
<li>
<p>On function exit the exception handler for <tt class=
"function">catcher</tt> is removed from the chain.</p>
</li>
<li>
<p>There's another place that SEH code is needed of course - the
destructor for <tt class="varname">anObject</tt> must be called
during the unwind back to the <tt class="literal">catch</tt>
statement.</p>
<p>So there is actually yet another exception handler registered
for <tt class="function">thrower</tt> too, to deal with ensuring
that <tt class="varname">anObject</tt> gets deleted. This one never
tries to handle the exception but simply ensures local variables
are destructed during the unwind.</p>
</li>
</ol>
</div>
<p>One key thing about the way MSVC exception handling works is
that it involves making extra calls down the stack. At point (2)
the C++ runtime calls <tt class="function">RaiseException</tt>,
which snapshots the exception and thread state and then it in turn
calls the code to work along the exception chain calling exception
handlers. At point (3) when the exception handler for <tt class=
"function">catcher</tt> gets control it is a long way down the
stack. The exception chain is unwound by yet another call, this
time to <tt class="function">RtlUnwind</tt>. This function throws
another exception along the exception chain with a special flag
value EXCEPTION_UNWINDING set, giving each exception handler in
turn a chance to do tidying up before it is removed from the
exception chain. After returning from <tt class=
"function">RtlUnwind</tt> the body of the <tt class=
"literal">catch</tt> statement is then called. When the <tt class=
"literal">catch</tt> body completes control returns back to the C++
runtime which completes tidying up the stack pointer, deletes the
exception object and then resumes execution at the next instruction
after the <tt class="literal">catch</tt> block.</p>
<p>So how does the <tt class="literal">catch</tt> block make use of
the local variable <tt class="varname">functionName</tt> if it is
so far down the stack when it gets control?</p>
<p>What the C++ runtime does is to use the extended exception
registration record (passed to the handler as the second argument)
to recover the value of the frame pointer EBP. Having reset the
frame pointer the code in the <tt class="literal">catch</tt> body
can make use of local variables and function arguments without
difficulty. It is does not affect the function that the stack
pointer is not simply a few bytes below the frame pointer but
several hundred bytes below it.</p>
<p>The upshot is that, when the <tt class="literal">catch</tt> body
is executed, the complete stack down to the location of the throw
is still available in memory. The raw stack pointer will only be
reset when the body of the stack completes, and before this point
the call stack will not be touched. So if we can obtain the address
of the context record that was passed into each exception handler
as the third argument, the pointer will still be valid inside the
body of the <tt class="literal">catch</tt>.</p>
<p>Looking back to the way the chain of exception handlers is
processed we can see that if we can hook our code into the
exception chain just before the compiler written exception handler
we can extract information from the context record and then use
that information inside the <tt class="literal">catch</tt> handler
to allow us print a stack trace. Let's look at how we can do
this.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e392" id="d0e392"></a>Adding to the
Exception Chain</h2>
</div>
<p>The exception chain in Win32 consists of a singly linked list of
<span class="structname">EXCEPTION_REGISTRATION_RECORD</span>s on
the stack. Unfortunately Microsoft do not provide a C++ definition
for this structure (possibly because it is different on each
hardware platform running Windows) but they do provide one in an
assembler include file <tt class="filename">EXSUP.INC</tt> which
can be translated into C++ like this:</p>
<pre class="programlisting">
/** Typedef for the exception handler function
    prototype */
typedef DWORD (fnExceptionHandler)
      (EXCEPTION_RECORD *pException,
       struct _EXCEPTION_REGISTRATION_RECORD
                       *pRegistrationRecord,
       CONTEXT *pContext );
/** Definition of 'raw' WinNt exception
    registration record - this ought to be in
    WinNt.h */
struct _EXCEPTION_REGISTRATION_RECORD {
  struct _EXCEPTION_REGISTRATION_RECORD
          *PrevExceptionRegistrationRecord;
          // Chain to previous record
  fnExceptionHandler *ExceptionHandler;
          // Handler function being registered
};
</pre>
<p>So all we need to do, it seems, is to create an <span class=
"structname">_EXCEPTION_REGISTRATION_RECORD</span>, point
<tt class="classname">ExceptionHandler</tt> to our exception
handling function and insert the record at the top of the exception
chain. Almost. There are some complexities with registering your
own exception handlers.</p>
<p>Firstly, the code which walks the exception chain requires (on
some but not all versions of Windows) that the nodes in the chain
are registered in strict address order. Fortunately the compiler
always puts local variables below the exception registration record
so by using a local variable for our exception helper we should
always be able to insert it into the chain before the compiler
generated exception registration record.</p>
<p>Secondly, I want to register the exception handler in a
constructor. This function too has a compiler-generated exception
handler. I must ensure that the handler is registered in the chain
above the record for the constructor or my exception handler will
be unregistered when the constructor completes! Additionally I want
the code to work properly should there be two or more exception
helper objects in a single function, and it is not in general
possible to fix the offsets in the stack frame assigned by the
compiler for local variables.</p>
<p>Lastly, as part of the security improvements included with
Visual Studio .NET 2003 and Windows Server 2003/Windows XP service
pack 2, the exception handling function to be called must be marked
with a special attribute (<tt class="varname">SAFESEH</tt>) at link
time so it will appear in the &quot;Safe Exception Handler Table&quot; in the
load configuration record. Failure to do this results in a security
exception occurring at runtime which usually terminates the
process. This check has been added to Windows to prevent security
exploits that use buffer overrun in order to replace the exception
handler address on the stack with a pointer to injected code. The
<tt class="varname">SAFESEH</tt> attribute can only be granted by
assembler code so it is therefore necessary, when using Visual
Studio .NET 2003, to make use of a very simple piece of assembler
code to add this attribute to the exception handling function.</p>
<p>Note: the assembler ml.exe provided with the first Beta edition
of Visual Studio 2005 access violates when using /safeseh [<a href=
"#MSDN">MSDN</a>] and that from 2003 must be used.</p>
<p>One mechanism I've found that provides good ease of use under
the above constraints is to create a common base class for my own
exception handlers. This class contains a static exception handling
function which can be marked, once and for all, with the <tt class=
"varname">SAFESEH</tt> attribute. This common handler then makes a
virtual call into the derived class for the specific action
required for exception handling.</p>
<pre class="programlisting">
class ExceptionHelperBase : public _EXCEPTION_REGISTRATION_RECORD {
public:
  /** Construct helper object */
  ExceptionHelperBase();
  /** Make safe to extend */
  virtual ~ExceptionHelperBase() {}
  /** Allow subclass to hook exception */
  virtual void onException(
                EXCEPTION_RECORD *pException,
                CONTEXT *pContext) = 0;
private:
  // Disable copy and assign
  ExceptionHelperBase(
                ExceptionHelperBase const &amp;);
  ExceptionHelperBase&amp; operator=(
                ExceptionHelperBase const &amp;);
  // The one and only exception handler function
  static fnExceptionHandler exceptionHandler;
};
</pre>
<p>The exception handling function simply casts the exception
registration record back to an <tt class=
"classname">ExceptionHelperBase</tt> and invokes <tt class=
"methodname">onException</tt>:</p>
<pre class="programlisting">
DWORD ExceptionHelperBase::exceptionHandler(
      EXCEPTION_RECORD *pException,
      struct _EXCEPTION_REGISTRATION_RECORD
                         *pRegistrationRecord,
      CONTEXT *pContext) {
  ExceptionHelperBase &amp;self =
      static_cast&lt;ExceptionHelperBase&amp;&gt;(
                      *pRegistrationRecord);
  self.onException(pException, pContext);
  return ExceptionContinueSearch;
}
</pre>
<p>I would like my exception class to register itself in the
constructor and deregister itself in the destructor. Unfortunately
I can't simply do this in the <tt class=
"classname">ExceptionHelperBase</tt> constructor and destructor
without risking problems if I get an exception during the
constructor/destructor code itself.</p>
<p>However, a use of the 'curiously recurring template pattern'
fixes this problem and ensures registration happens last in the
constructor and first in the destructor:</p>
<pre class="programlisting">
template &lt;typename RegistrationRecord&gt;
class AutoRegister : public RegistrationRecord {
public:
  /** Auto-register an exception record for
      'RegistrationRecord' */
  AutoRegister() : RegistrationRecord() {
    registerHandler(this);
  }
  /** Unregister and destroy an exception
      record */
  ~AutoRegister() {
    unregisterHandler(this);
  }
};
</pre>
<p>Where <tt class="function">registerHandler</tt> will install the
handler in the exception chain and unregisterHandler will remove it
from the chain by using standard logic for singly-linked lists. The
list head is held in the <span class="structname">NT_TIB</span>
structure pointed to by the <tt class="literal">FS</tt> register
and the list tail is the value -1.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e467" id="d0e467"></a>Processing
the Exception</h2>
</div>
<p>The first derived class simply prints out the exception
information to demonstrate that things are working properly:</p>
<pre class="programlisting">
class ExceptionHelperImpl1
             : public ExceptionHelperBase {
  /** Print the address of the exception
      records */
  virtual void onException(
                EXCEPTION_RECORD *pException,
                CONTEXT *pContext) {
    printf(&quot;pException: %p (code: %p,
               flags: %x), pContext: %p\n&quot;,
           pException,
           pException-&gt;ExceptionCode,
           pException-&gt;ExceptionFlags,
           pContext);
  }
};

typedef AutoRegister&lt;ExceptionHelperImpl1&gt;
                            ExceptionHelper1;
</pre>
<p>Since this code is executing while an exception is actually
being processed I used <tt class="function">printf()</tt> rather
than <tt class="classname">std::cout</tt> to avoid any potentially
harmful interactions with the standard library.</p>
<p>Sample code:</p>
<pre class="programlisting">
int main() {
  ExceptionHelper1 helper;
  try {
    printf(&quot;About to throw\n&quot;);
    throw std::runtime_error(
                          &quot;basic exception&quot;);
  }
  catch(std::exception &amp; /*ex*/) {
    printf(&quot;In catch handler\n&quot;);
  }
  return 0;
}
</pre>
<p>When executed this program generates output for two
exceptions:</p>
<pre class="literallayout">
About to throw
pException: 0012FBA0 (code: E06D7363, flags:
                        1), pContext: 0012FBC0
pException: 0012FBA0 (code: E06D7363, flags:
                        3), pContext: 0012F670
In catch handler
</pre>
<p>The second call is generated by the Microsoft supplied exception
handler unwinding the exception chain. This is easily identified as
the <tt class="varname">EXCEPTION_UNWINDING</tt> flag (value 2) is
set in <tt class="literal">pException-&gt;ExceptionFlags</tt> for
the second exception. For our purposes we want to extract context
data from the first call since this context describes the thread
state when throw was executed. (Note that our exception handler is
removed from the chain during the exception unwind so would need to
be re-inserted to catch subsequent exceptions in the same
scope)</p>
<p>We now have everything we need for the basic version of the code
to print a stack trace:</p>
<pre class="programlisting">
class ExceptionStackTraceImpl
              : public ExceptionHelperBase {
public:
  ExceptionStackTraceImpl()
                         : pSavedContext(0) {}
  /** Use the saved pointer to print the stack
      trace */
  void printStackTrace(std::ostream &amp; os)
                                     const {
    if(pSavedContext != 0)
      SimpleSymbolEngine::instance()
              .StackTrace(pSavedContext, os);
  }
private:
  /** Capture the thread context when the
      initial exception occurred */
  virtual void onException(
                EXCEPTION_RECORD *pException,
                CONTEXT *pContext) {
    if((pException-&gt;ExceptionFlags
              &amp; EXCEPTION_UNWINDING) == 0) {
      pSavedContext = pContext;
    }
  }
  PCONTEXT pSavedContext;
     // context record from the last exception
};
typedef AutoRegister&lt;ExceptionStackTraceImpl&gt;
                          ExceptionStackTrace;
</pre>
<p>We have now achieved the original aim of be able to print a
stack trace in the catch block.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e504" id="d0e504"></a>Interaction
With Normal SEH</h2>
</div>
<p>This method of 'hooking' in to the MSVC handling of C++
exceptions means that the exception handler is also called for
every other SEH exception, such as access violation. In released
versions of MSVC the implementation of <tt class=
"literal">catch(...)</tt> also processed these types of exceptions.
Although this seems at first sight to be a good thing it actually
tends to cause more problems than it solves.</p>
<p>One particular issue is that genuine problems such as corrupt
memory, I/O errors on the paging file or load time problems with
DLLs get handled in the same way as a C++ exception of unknown
type, by code not written to deal with these error conditions. For
current versions of MSVC it is usually best to avoid use of
<tt class="literal">catch(...)</tt> unless either the code
re-throws the exception or terminates the process.</p>
<p>Visual Studio 2005 Beta 1 handles non-C++ SEH exceptions in a
<tt class="literal">catch(...)</tt> only when the compiler flag
/EHa is set, which is a great improvement and gives maximum
flexibility.</p>
<p>Whether or not /EHa is specified we can use ExceptionHelper to
extract information about the OS exception. Microsoft provide some
other ways to achieve a similar end, <tt class=
"literal">__try</tt>/<tt class="literal">__except</tt> and
<tt class="literal">_set_se_translator</tt>, but they are not total
solutions. Also not all compler vendors provide such extensions and
the <tt class="classname">ExceptionHelper</tt> code could still be
used to extract information about the exception.</p>
<p>For example I modified <tt class=
"classname">ExceptionHelper1</tt> class for gcc on win32 (a couple
of minor changes were required for a clean compile). Since gcc does
not seem to use SEH for C++ exception handling <tt class=
"classname">ExceptionHelper1</tt> did not capture information for
such exceptions but it did do so for Win32 exceptions, such as
access violations. For a &quot;proof of concept&quot; I changed the exception
handler to throw a <tt class="classname">std::runtime</tt>
exception rather than printing the exception information and was
successful in mapping an SEH exception into a C++ exception, thus
allowing additional tidyup to be performed before the program
exited.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e547" id=
"d0e547"></a>Conclusion</h2>
</div>
<p>I have given a brief overview of how the Microsoft compilers on
Win32 implement C++ exception handling. Using this information
we've seen a simple class which enables additional information to
be obtained about the exception during program execution.</p>
<p>What is the main strength and weakness of this approach?</p>
<p>On the positive side it enables better diagnostic information to
be produced at runtime for MSVC on Win32. This can significantly
reduce the cost of finding bugs, since enough information might be
gathered in the field to identify the root cause. Without this
extra information it might be necessary to try and reproduce the
problem under a debugger, with potential difficultly of getting the
right execution environment to enure the problem does in fact
appear.</p>
<p>The main weakness is that the code is platform specific and
relies on undocumented behaviour of the compiler. Other compilers
under Win32 do not use the SEH mechanism to handle C++ exceptions
so this code is useless should your code need to be portable to
them. The implementation of the exception mechanism even under 64
bit Windows is not the same as for 32 bit Windows, so the technique
described here will not work unchanged (if at all) in that
environment even for Microsoft compilers.</p>
<p>The decision depends on the relative balance between these two
items. However, having isolated the logic into a single class
<tt class="classname">ExceptionStackTrace</tt> it can be
conditionally compiled to a do-nothing implementation on other
platforms, or if may even be possible to re-implement the logic for
another platform.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e563" id="d0e563"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Orr2004" id="Orr2004"></a>
<p class="bibliomixed">[Orr2004] Roger Orr, &quot;Efficient
Exceptions?&quot;, <span class="citetitle"><i class="citetitle">Overload
61</i></span>, June 2004</p>
</div>
<div class="bibliomixed"><a name="Pietrek1" id="Pietrek1"></a>
<p class="bibliomixed">[Pietrek1] Matt Pietrek, <span class=
"citetitle"><i class="citetitle">A Crash Course on the Depths of
Win32&trade; Structured Exception Handling</i></span>, <span class=
"bibliomisc"><a href=
"http://www.microsoft.com/msj/0197/Exception/Exception.aspx"
target="_top">http://www.microsoft.com/msj/0197/Exception/Exception.aspx</a></span></p>
</div>
<div class="bibliomixed"><a name="Gordon" id="Gordon"></a>
<p class="bibliomixed">[Gordon] Jeremy Gordon, <span class=
"citetitle"><i class="citetitle">Win32 Exception handling for
assembler programmers</i></span>, <span class="bibliomisc"><a href=
"http://www.jorgon.freeserve.co.uk/%20Except/Except.htm" target=
"_top">http://www.jorgon.freeserve.co.uk/
Except/Except.htm</a></span></p>
</div>
<div class="bibliomixed"><a name="MSDN" id="MSDN"></a>
<p class="bibliomixed">[MSDN] MSDN Product Feedback Center,
<span class="bibliomisc"><a href=
"http://lab.msdn.microsoft.com/ProductFeedback" target=
"_top">http://lab.msdn.microsoft.com/ProductFeedback</a></span>,
search on keyword &quot;FDBK12741&quot;</p>
</div>
<div class="bibliomixed"><a name="Pietrek2" id="Pietrek2"></a>
<p class="bibliomixed">[Pietrek2] Matt Pietrek, <span class=
"citetitle"><i class="citetitle">Improved Error Reporting with
DBGHELP 5.1 APIs</i></span>, <span class="bibliomisc"><a href=
"http://msdn.microsoft.com/msdnmag/issues/02/03/hood/default.aspx"
target=
"_top">http://msdn.microsoft.com/msdnmag/issues/02/03/hood/default.aspx</a></span></p>
</div>
<div class="bibliomixed"><a name="Robbins" id="Robbins"></a>
<p class="bibliomixed">[Robbins] John Robbins, <span class=
"citetitle"><i class="citetitle">Debugging Applications for
Microsoft .NET and Microsoft Windows</i></span>, Microsoft
Press</p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;microsoft visual c++, structured exception handling.</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
