    <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  :: C++ Exceptions and Linux Dynamic Libraries</title>
        <link>https://members.accu.org/index.php/articles/404</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 #48 - Apr 2002</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/c197/">48</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+197/">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;C++ Exceptions and Linux Dynamic Libraries</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 April 2002 17:46:09 +01:00 or Fri, 26 April 2002 17:46:09 +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>A Cautionary
Tale</h2>
</div>
<p>Once upon a time there was a bright young C++ programmer&hellip;
Well, not so young, actually. And, sadly, not bright enough to know
how to use C++ member functions in a Linux dynamic library. I'll
tell you his poignant story in the hope that you can avoid his
mistakes.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e23" id="d0e23"></a>A Little
Knowledge</h2>
</div>
<p>I will call this programmer &quot;Phil&quot; (not his real name,
apparently). Now, Phil had read the manual and he knew how to build
a shared library using gcc. Just pass the <tt class=
"literal">-fPIC</tt> flag to the compiler (to generate
position-independent code) and pass the <tt class=
"literal">-shared</tt> flag to the linker (to generate a shared
library). He also knew how to load the library into his main
program using <tt class="function">dlload()</tt>, get the address
of a function or data item in the library using <tt class=
"function">dlsym()</tt>, check for errors using <tt class=
"function">dlerror()</tt> and close the library using <tt class=
"function">dlclose()</tt>. Now, <tt class="function">dlsym()</tt>
takes the name of a symbol and returns its address. But what is the
name of a C++ member function? Typically, it is a mangled version
of something like &quot;<tt class="methodname">Isotek::SignalMonitor*
Isotek::SignalMonitor::create()</tt>&quot;. Not only is this quite a lot
of typing, it is also tricky to find the mangled name and it will
change with the slightest change to the function's name or
interface.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e52" id="d0e52"></a>Clever
Clogs</h2>
</div>
<p>&quot;No sweat,&quot; thought Phil, for he had solved that problem when
creating plug-in libraries for Win32 operating systems. The trick
is to have the plug-in library insert its objects into a suitable
registry when it loads. The main program creates the registry,
loads the plug-in library and uses the objects that magically
appear in the registry. No symbol look-ups required. Perfect.</p>
<p>Well, not quite. There was a two-way dependency between the main
program and the plug-in library which, in Win32, meant that linking
was a real pain. But Phil had another trick up his sleeve. Move the
registry into its own shared library. Now both the main program and
the plug-in library can be linked with the registry library in the
normal way. The operating system automatically loads the registry
library when the main program is started and it's already there
when the plug-in library loads.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e59" id="d0e59"></a>Pride Before
The Fall</h2>
</div>
<p>So, Phil built the registry library, the plug-in library and the
main program, ran a test and saw that it was good. The main program
found the object created by the plug-in library and correctly
called its member functions. The problem of calling C++ functions
with mangled names in Linux plug-in libraries was solved.</p>
<p>Then Phil tested an error condition (as every good programmer
does). A function in the plug-in library detected the error and
threw an exception; the exception handler in the main program
failed to catch the exception and aborted. Phil checked his code
carefully, but there was no obvious coding error. He poked around
in the debugger, he tried to think of explanations for this
behaviour, he discussed it with a colleague, but to no avail. So,
finally, as an experiment, he tried to catch the exception within
the function that threw it. The program still crashed. Exception
handlers were not invoked for exceptions thrown from a function in
the plug-in library.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e66" id="d0e66"></a>Back To The
Drawing Board</h2>
</div>
<p>This was serious. Exceptions are often a good way of handling
error conditions. The C++ standard library throws exceptions. Even
the core language throws exceptions (<tt class=
"exceptionname">bad_alloc</tt> and <tt class=
"exceptionname">bad_cast</tt>). Did this mean that we could only
use a subset of C++ in dynamic libraries? After more discussions
and a search on the Web Phil discovered that the problem had been
mentioned in a newsgroup post. The newsgroup thread contained just
two messages. The first provided code that demonstrates the
problem; the second said &quot;but, it works for me&quot;. The difference had
to be the compiler/linker switches. Sure enough, in a stripped-down
sample program, exceptions were not caught when the <tt class=
"literal">-nostartfiles</tt> switch was provided, but were caught
when this switch was absent.</p>
<p>Unfortunately, Phil needed the <tt class=
"literal">-nostartfiles</tt> switch. His strategy relies on the
plug-in registering its objects when it loads. To do this, the
programmer provides a function with C linkage called <tt class=
"function">_init()</tt> and the operating system calls this
function when the library loads. The programmer may also provide a
<tt class="function">_fini()</tt> function called when the library
is unloaded. But, the C/C++ start-up files contain <tt class=
"function">_init()</tt> and <tt class="function">_fini()</tt>
functions, too<sup>[<a name="d0e97" href="#ftn.d0e97" id=
"d0e97">1</a>]</sup>. The <tt class="literal">-nostartfiles</tt>
switch prevents &quot;multiple definition&quot; errors from the linker by
suppressing the inclusion of the standard start-up files in the
executable file.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e110" id="d0e110"></a>The
Punch-Line</h2>
</div>
<p>The moral of this story? Don't supply your own <tt class=
"function">_init()</tt> or <tt class="function">_fini()</tt>
function in Linux dynamic libraries containing C++ functions that
may throw exceptions. That rules out C++ functions that use
<tt class="literal">new</tt>, <tt class=
"classname">std::vector</tt>, <tt class=
"classname">std::string</tt> (to name but three), either directly
or indirectly. And that doesn't leave very much.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e130" id="d0e130"></a>Codicil</h2>
</div>
<p>Phil fixed his problem by removing the leading underscore from
the <tt class="function">_init()</tt> and <tt class=
"function">_fini()</tt> functions in the library. The renamed
functions must now be called explicitly using <tt class=
"function">dlsym()</tt> to look up their addresses. Note, however,
that only these two functions need to be looked up by name and they
are both simple functions with C linkage and unmangled
names<sup>[<a name="d0e144" href="#ftn.d0e144" id=
"d0e144">2</a>]</sup>.</p>
</div>
<div class="footnotes"><br>
<hr class="c2" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e97" href="#d0e97" id=
"ftn.d0e97">1</a>]</sup> I confess I don't know what the <tt class=
"function">_init()</tt> and <tt class="function">_fini()</tt>
functions in the start-up files do. Presumably they perform some
initialisation of the C/C++ library and this includes
initialisation of the exception handling mechanism.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e144" href="#d0e144" id=
"ftn.d0e144">2</a>]</sup> Thaddeus Frogley suggested a simple class
that loads a dynamic library and makes the <tt class=
"function">init()</tt>/<tt class="function">fini()</tt> calls via
<tt class="function">dlsym()</tt>. Good idea. Thanks, Thad.</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
