Do we need to increment thread-local variable atomically? - c++

Below is a function from LLVM's libcxxabi:
void *__cxa_current_primary_exception() throw() {
// get the current exception
__cxa_eh_globals* globals = __cxa_get_globals_fast();
if (NULL == globals)
return NULL; // If there are no globals, there is no exception
__cxa_exception* exception_header = globals->caughtExceptions;
if (NULL == exception_header)
return NULL; // No current exception
if (!isOurExceptionClass(&exception_header->unwindHeader))
return NULL; // Can't capture a foreign exception (no way to refcount it)
if (isDependentException(&exception_header->unwindHeader)) {
__cxa_dependent_exception* dep_exception_header =
reinterpret_cast<__cxa_dependent_exception*>(exception_header);
exception_header = cxa_exception_from_thrown_object(dep_exception_header->primaryException);
}
void* thrown_object = thrown_object_from_cxa_exception(exception_header);
__cxa_increment_exception_refcount(thrown_object);
return thrown_object;
}
globals is a thread-local storage variable, and therefore the thrown_object is also specific for a thread. My understanding is that thrown_object is an exception thrown in a thread - each thread may throw its own exception.
But the function __cxa_increment_exception_refcount() performs increment atomically - why? What's the scenario that requires increment to be performed atomically?

You can call std::current_exception and get a smart-pointer to the exception:
std::exception_ptr is a nullable pointer-like type that manages an exception object which has been thrown and captured with std::current_exception. An instance of std::exception_ptr may be passed to another function, possibly on another thread, where the exception may be rethrown and handled with a catch clause.
...
std::exception_ptr is a shared-ownership smart pointer.
Because std::exception_ptr can be passed to another thread the reference counter maintenance must use atomic increment/decrement.
The reference counter is embedded into the exception object, like for boost::intrusive_ptr and unlike std::shared_ptr.

Related

Is destroying the last std::exception_ptr pointing to an exception after calling std::rethrow_exception portable?

I have a portability question concerning the lifetime of exception. In the code below, an exception is thrown in one thread (mySlave) and transferred to another thread (myMaster) using a std::exception_ptr. myMaster is always waiting for different events via a std::condition_variable. An exception in mySlave is such an event. In the predicate function of the wait in myMaster, I check if the exception pointer is null. If an exception has been thrown in mySlave, I copy the exception pointer to a temporary variable in myMaster, set the original exception pointer to null and rethrow it in myMaster. This way, the original exception pointer is ready to serve in the predicate function once the program has recovered from the exception.
This works fine with VC14, but the final software is likely to be ported to other platforms in the future. In my code, all exception_ptr references to the exception will run out of scope after the rethrow, thus the original exception will be destroyed. My concern is if std::rethrow_exception is guaranteed to always generate a copy of the exception when rethrowing it, or if it could also use a reference to the exception, causing it to be no longer valid when I try to catch if in myMaster?
#include <mutex>
#include <thread>
#include <atomic>
#include <exception>
#include <iostream>
#include <memory>
class SomeClass
{
public:
/*...*/
void MaseterFunction();
void SlaveFunction();
private:
/*...*/
std::mutex mutex_gotEvent;
std::condition_variable condVar_gotEvent;
std::exception_ptr slaveLoopException;
/*...*/
std::atomic<bool> running = true;
};
class MyException : public std::runtime_error
{
public:
MyException() : std::runtime_error("Ooops") {}
};
void SomeClass::SlaveFunction()
{
try
{
throw MyException();
}catch(const std::exception& e)
{
std::unique_lock<std::mutex> lock(mutex_gotEvent);
slaveLoopException = std::current_exception();
condVar_gotEvent.notify_all();
}
}
void SomeClass::MaseterFunction()
{
while (running)
{
try
{
{
/*Wait for something interesting to happen*/
std::unique_lock<std::mutex> lock(mutex_gotEvent);
condVar_gotEvent.wait(lock, [=]()->bool {
return !(slaveLoopException == nullptr); // Real code waits for several events
});
}
/*Care for events*/
/*...*/
if (slaveLoopException)
{
std::exception_ptr temp_ptr = slaveLoopException;
slaveLoopException = nullptr;
std::rethrow_exception(temp_ptr);
}
}
catch (const MyException& e)
{
std::cout << e.what();
running = false;
}
}
}
int main()
{
std::shared_ptr<SomeClass> someClass = std::make_shared<SomeClass>();
std::thread myMaster([someClass]() {someClass->MaseterFunction(); });
std::thread mySlave([someClass]() {someClass->SlaveFunction(); });
std::cin.ignore();
if (myMaster.joinable())
{
myMaster.join();
}
if (mySlave.joinable())
{
mySlave.join();
}
return 0;
}
I thought about declaring temp_ptr at class level or use a std::atomic<bool> variable in addition to the exception pointer to be used in the predicate function. However both of these solutions would keep the exception alive after it is no longer used, which seem not very elegant to me. It would also be possible to set the exception pointer to null in each catch block in myMaster, but I think that this is likely to introduce bugs when new exceptions are added later on and the programmer forgets to null the exception pointer.
EDIT:
I found the following statements on this subject:
Statement 1:
The exception object referenced by an std::exception_ptr remains valid
as long as there remains at least one std::exception_ptr that is
referencing it
Statement 2:
The VS implementation of rethrow_exception appears to make a copy of
the exception. Clang and gcc do not make copies.
Statement 3
The exception object is destroyed after either the last remaining
active handler for the exception exits by any means other than
rethrowing, or the last object of type std::exception_ptr (§18.8.5)
that refers to the exception object is destroyed, whichever is later.
From (1) I would expect the exception to be destroyed too early. From (2) I would expect this to be of no effect when using VC as a copy is used anyway. From 3, I can't tell if this could save me when using gcc or clang. I mean, the exit takes place by rethrowing, but it is not rethrown from a handler. Is the new handler already considered active when the temporary pointer is destroyed or is the pointer destroyed first and with it the exception, leaving the follow up catch blocks with an invalid exception reference?
CppRef states that rethrow_exception -- Throws the previously captured exception object. I haven't checked the standard myself (but see below), but:
Speculation
It seems likely to me that from the point onwards where you rethrow the exception, exception handling is "back to normal", i.e. it is the job of the implementation to keep the thrown object around, and the language doesn't care whether you threw via a normal throwor via a rethrow_exception.
Stated differently: The exception_ptr needs to be valid at the point of rethrow_exception, after this, the thrown exception is the same as any other and whether or not it shares with the original exception pointer shouldn't matter.
OP provided a good link with a standard quote:
4/ The memory for the exception object is allocated in an unspecified way, except as noted in §3.7.4.1. If a handler exits by rethrowing, control is passed to another handler for the same exception. The exception object is destroyed after either the last remaining active handler for the exception exits by any means other than rethrowing, or the last object of type std::exception_ptr (§18.8.5) that refers to the exception object is destroyed, whichever is later. In the former case, the destruction occurs when the handler exits, immediately after the destruction of the object declared in the exception-declaration in the handler, if any. In the latter case, the destruction occurs before the destructor of std::exception_ptr returns. The implementation may then deallocate the memory for the exception object; any such deallocation is done in an unspecified way. [ Note: a thrown exception does not propagate to other threads unless caught, stored, and rethrown using appropriate library functions; see §18.8.5 and §30.6. —end note ]
Which seems to imply what I wrote above: The exception object lives as long as necessary: the whichever is later part of the quote seems to explicitly call this out.
Update: I missed that OP doesn't re-throw from the handler, so I am also unsure what is supposed to happen here.
I do believe that after rethrow_exception the (new) exception in flight should be treated as-if it was generated by a normal throw expression - anything else makes little sense.
The way I speculate here is that even prior to std::exception_ptr every implementation had an internal mechanism that was similar to std::exception_ptr in that it had to keep the thrown exception object (copy or not) alive outside of normal stack frames until it was no longer needed by any handler up the stack. So I can speculate that clang or gcc would not do a copy, but instead hold an "internal exception_ptr" as soon as you invoke throw/rethrow_exception.

Why should i use catch by reference when exception pointers are thrown

When catching an exception by reference is the only advantage that i get is avoiding a copy of the exception object being made? Basically the difference between
try
{
CString a_csSQL = _T("SELECT * FROM Library");
CDatabase aDB;
aDB.OpenEx(g_csConnectionStringWdDSN,CDatabase::noOdbcDialog));
aDB.ExecuteSQL(a_csSQL);
}
catch(CDBException *& ex)
{
ex->Delete();
}
AND
try
{
CString a_csSQL = _T("SELECT * FROM Library");
CDatabase aDB;
aDB.OpenEx(g_csConnectionStringWdDSN,CDatabase::noOdbcDialog))
aDB.ExecuteSQL(a_csSQL);
}
catch(CDBException * ex)
{
ex->Delete();
}
The difference between the two codes you posted is that the first one catches a pointer to an exception by reference, and the second one catches a pointer to an exception by value. In neither case is an exception copied, since you're dealing with pointers.
In general, exceptions should be thrown by value, and caught by reference. The C++ standard library is designed with this expectation in mind. However, older libraries, (MFC for instance) throw exceptions by pointer as you do here, and are expected to be caught by pointer.
There's no effective difference between catching a pointer by value and by reference, except that if you catch by reference that gives you the (completely useless) option of deleting the exception, allocating a new exception with that same pointer, and rethrowing the same exception-pointer.
If the exception is throw by a pointer you can avoid using reference.
References are really required if the exception is thrown by value.

Can exceptions be "duplicated" via exception pointers?

For some multithreaded code, I would like to capture all exceptions and pass a them to a single exception handling thread. Here's the message passing framework:
#include <exception>
struct message
{
virtual ~message() = default;
virtual void act() = 0;
};
struct exception_message : message
{
std::exception_ptr ep;
virtual void act()
{
std::rethrow_exception(ep);
}
// ...
};
Here's the use case:
try
{
// ...
}
catch (...)
{
exception_message em { std::current_exception(); }
handler_thread.post_message(em);
}
The handler thread goes through all its messages and calls act(), and it can install its own try/catch block to handle all the posted exceptions.
Now I was wondering what happens if I send copies this message to multiple receivers. In general, mes­sa­ges may have any number of recipients, and so I don't want to put arbitrary restrictions on exception pro­pa­ga­tion messages. The exception_ptr is documented as a "shared-ownership" smart pointer, and rethrow_exception "does not introduce a data race".
So my question: Is it legitimate to duplicate an active exception by storing it in an exception_ptr, copy­ing the pointer, and calling rethrow_exception multiple times?
From my understanding of the Standard, it is legitimate. However I would note that the rethrow does not duplicate the exception, and therefore the shared exception object itself is submitted to data races should you modify it and access it from other threads meantime. If the exception is read-only (once thrown), then you should not have any issue.
Regarding storage duration:
15.1 Throwing an exception [except.throw]
4 The memory for the exception object is allocated in an unspecified way, except as noted in 3.7.4.1. If a handler exits by rethrowing, control is passed to another handler for the same exception. The exception object is destroyed after either the last remaining active handler for the exception exits by any means other than rethrowing, or the last object of type std::exception_ptr (18.8.5) that refers to the exception object is
destroyed, whichever is later. In the former case, the destruction occurs when the handler exits, immediately after the destruction of the object declared in the exception-declaration in the handler, if any. In the latter case, the destruction occurs before the destructor of std::exception_ptr returns.
Regarding data races:
18.8.5 Exception propagation [propagation]
7 For purposes of determining the presence of a data race, operations on exception_ptr objects shall access and modify only the exception_ptr objects themselves and not the exceptions they refer to. Use of rethrow_exception on exception_ptr objects that refer to the same exception object shall not introduce a data race. [ Note: if rethrow_exception rethrows the same exception object (rather than a copy), concurrent access to that rethrown exception object may introduce a data race. Changes in the number of exception_ptr objects that refer to a particular exception do not introduce a data
race. —end note ]
Regarding rethrow:
[[noreturn]] void rethrow_exception(exception_ptr p);
9 Requires: p shall not be a null pointer.
10 Throws: the exception object to which p refers.

Throwing, catching, scoping stl::string.c_str() exceptions

Say I've written some function myFunc that can throw const char* exceptions:
void myFunc()
{
int returnCode = whatever();
if (!returnCode)
{
std::string msg;
msg.append("whatever function failed");
std::cerr << msg << std::endl; // print warning message
throw msg.c_str(); // throw warning message as exception
}
}
And later I'm using it like so:
void myProgram()
{
try
{
myFunc();
}
catch(const char* str)
{
// is 'str' string memory valid here?
}
}
I realize this isn't really a good strategy for exception usage: better to throw and catch exception classes, not strings. But I'm curious about the scoping involved here.
msg.str() returns a temporary std::string. As temporaries are deleted at the end of a statement ;, the contents of the character string returned by c_str() become undefined when the throw ... ; statement terminates by leaving the scope via the exception mechanism.
(The lifetime of the const char* temporary is obviously extended to reach to the catch handler, but that does not help since the underlying buffer is gone).
Throwing std::string (i.e. throw msg.str();) would work, the lifetime of the temporary would be extended as intended.
Indeed the c_str() call is acting on a temporary (string) object and the pointer will be invalid when you catch it.
Not only that, but since the stringstream and stringcould do allocation, you need to make sure that you're not throwing because of heap problems. If you're at that point due to being out of memory you may bomb out even worse trying to create your exception. You generally want to avoid heap allocation during exceptional cases.
Are you unable to use say runtime_error or create your own exception type?
Note that if you had said:
throw "error";
you would be OK because the lifetime of the string literal is the lifetime of the program. But don't do it, anyway!
Something Alexander Gessler did not mention in his answer, is the possibility of an exception being thrown by by std::string itself during the creation of the temporary string object.
std::exception is guaranteed not to throw an exception during construction, std::string has no such guarantee.
An alternative approach (for classes) is to declare a private std::string object in your class. Assemble the error message prior to the throw, and then throw the c_str(). This will throw a const char* exception, the error message being valid until the next exception is thrown from that class (which would presumably modify the error string again.)
A simple example can be found here: http://ideone.com/d9HhX
Although this was answered over ten years ago, I would give some supplement:
https://learn.microsoft.com/en-us/cpp/cpp/exceptions-and-stack-unwinding-in-cpp
In the C++ exception mechanism, control moves from the throw statement to the first catch statement that can handle the thrown type. When the catch statement is reached, all of the automatic variables that are in scope between the throw and catch statements are destroyed in a process that is known as stack unwinding.
That's to say, any variables in the stack, including object variable, or basic type(int, char, etc) will be destroyed.
When throw an object in c++, c++ will actually make a cloned object by invoking the object copy constructor, the cloned object lifetime will valid through throw-catch.
reference:
C++: Throwing an exception invokes the copy constructor?
Now, return to the OP question, so, "throw msg.c_str();" is invalid because the msg object
is deleted (it's a auto variable), it happens to work because the memory is still there but actually freed.
So, just as #AlexanderGessler, #MarkB suggested,
the best c++ practice is: always throw string object, runtime_error, instead of throwing string.c_str()

catching exception objects by reference, temporaries, lifetime issues

Consider the following code:
#include <iostream>
#include <stdexcept>
void foo()
{
throw std::runtime_error("How long do I live?");
}
int main()
{
try
{
foo();
}
catch (std::runtime_error& e)
{
std::cout << e.what() << std::endl;
}
}
Why can I catch the exception by reference, isn't std::runtime_error("How long do I live?") an rvalue?
How come the exception object is still alive in the catch block?
Where exactly are thrown exception objects stored? What is their lifetime?
In the C++ standard, paragraph 15.1.4:
The memory for the temporary copy of
the exception being thrown is
allocated in an unspecified way,
except as noted in 3.7.3.1. The
temporary persists as long as there is
a handler being executed for that
exception. In particular, if a
handler exits by executing a throw;
statement, that passes control to
another handler for the same
exception, so the temporary remains.
When the last handler being executed
for the exception exits by any means
other than throw; the temporary object
is destroyed and the implementation
may deallocate the memory for the
temporary object; any such
deallocation is done in an unspecified
way. The destruction occurs
immediately after the destruction of
the object declared in the
exception-declaration in the handler.
Note that, in C++-standard talk, a handler denote a catch block with the correct argument type.
A thrown exception is not a temporary - the compiler-generated exception code keeps a permanent copy of it. So you can bind it to a non-const reference.
[edit]
I just check the standard and it actually refers to a temporary copy. However, the lifetime of the temporary is guaranteed to be at least as long as that of the exception handler.
As Neil said, there is internal compiler magic going on. Also, be aware that the compiler is allowed to create any number of copies of the exception object.
Kudos for trying to understand the details of the language. At the same time, IMHO, it is far more important to understand why you should catch an exception by reference (and throw it by value), than why you can.
People typically use a hierarchy of exception classes, and catching by reference allows you to leverage polymorphism, and catch an exception of the base class, when there is no need to handle individual exception types separately. If you couldn't catch by reference, you would have had to write a catch clause for every possible type of exception that can be thrown in the try clause.