Why isn't Darwin's strtod thread safe? - c++

The following test always produces failures or bus errors for me on my Intel Mac Mini.
Compiler:
uname -a:
Darwin vogon13 9.8.0 Darwin Kernel Version 9.8.0: Wed Jul 15 16:55:01 PDT 2009; root:xnu-1228.15.4~1/RELEASE_I386 i386
g++ -v:
Target: i686-apple-darwin9
Configured with: /var/tmp/gcc/gcc-5493~1/src/configure
--disable-checking -enable-werror --prefix=/usr --mandir=/share/man
--enable-languages=c,objc,c++,obj-c++
--program-transform-name=/^[cg][^.-]*$/s/$/-4.0/
--with-gxx-include-dir=/include/c++/4.0.0 --with-slibdir=/usr/lib
--build=i686-apple-darwin9 --with-arch=apple --with-tune=generic
--host=i686-apple-darwin9 --target=i686-apple-darwin9
Thread model: posix
gcc version 4.0.1 (Apple Inc. build 5493)
Compile commands:
"g++" -ftemplate-depth-128 -O3 -finline-functions -Wno-inline -Wall
-pedantic -g -no-cpp-precomp -gdwarf-2 -Wno-long-double -Wno-long-long -fPIC
-DBOOST_DATE_TIME_NO_LIB=1 -DBOOST_THREAD_NO_LIB=1 -DBOOST_THREAD_USE_LIB=1
-DDATE_TIME_INLINE -DNDEBUG -I"." -c -o "strtod_test.o" "strtod_test.cpp"
"g++" -o "strtod_test" "strtod_test.o"
"libboost_thread-xgcc40-mt-s.a" "libboost_date_time-xgcc40-mt-s.a"
-g -nodefaultlibs -shared-libgcc -lstdc++-static -lgcc_eh -lgcc -lSystem
-Wl,-dead_strip -no_dead_strip_inits_and_terms -fPIC
Source code:
#include "boost/thread/thread.hpp"
#include "boost/thread/barrier.hpp"
#include <iostream>
using namespace std;
void testThreadSafetyWorker(boost::barrier* testBarrier)
{
testBarrier->wait(); // wait until all threads have started
try
{
const char* str = "1234.5678";
const char* end = str;
double result = strtod(str, const_cast<char**>(&end));
if (fabs(result-1234.5678) > 1e-6)
throw runtime_error("result is wrong!");
}
catch (exception& e) {cerr << "Exception in worker thread: " << e.what() << endl;}
catch (...) {cerr << "Unhandled exception in worker thread." << endl;}
}
void testThreadSafety(const int& testThreadCount)
{
boost::barrier testBarrier(testThreadCount);
boost::thread_group testThreadGroup;
for (int i=0; i < testThreadCount; ++i)
testThreadGroup.add_thread(new boost::thread(&testThreadSafetyWorker, &testBarrier));
testThreadGroup.join_all();
}
int main(int argc, char* argv[])
{
try
{
testThreadSafety(2);
testThreadSafety(4);
testThreadSafety(8);
testThreadSafety(16);
return 0;
}
catch (exception& e) {cerr << e.what() << endl;}
catch (...) {cerr << "Unhandled exception in main thread." << endl;}
return 1;
}
Stack trace:
(gdb) bt
#0 0x950c8f30 in strlen ()
#1 0x9518c16d in strtod_l$UNIX2003 ()
#2 0x9518d2e0 in strtod$UNIX2003 ()
#3 0x00001950 in testThreadSafetyWorker (testBarrier=0xbffff850) at strtod_test.cpp:21
#4 0x0000545d in thread_proxy (param=0xffffffff) at boost_1_43_0/libs/thread/src/pthread/thread.cpp:12? ?1
#5 0x950f1155 in _pthread_start () #6 0x950f1012 in thread_start ()

strtod is not thread safe. It's never been stated in any specs that it was thread-safe. You should be using strtod_l, which takes a locale. In all likelehood there is a shared data structure that is being clobbered by it's use in the threaded code.
locale_t c_locale = newlocale (LC_ALL_MASK, "C", 0);
r = strtod_l(nptr, endptr, c_locale);
freelocale (c_locale);

Related

How to clone function from another module and set it AlwaysInline on LLVM pass?

I want to clone a function from another bitcode module and set it AlwaysInline so that it can be inlined.
But an error occurs when applying such custom pass (It seems that the cause is the use of CloneFunction()). How can I fix it?
I'm using LLVM 3.6.0 on OS X and target is Android armeabi-v7a (It should be same on other target).
callee.cpp (compiled to bitcode module callee.bc)
#include <jni.h>
#include <android/log.h>
#ifdef __cplusplus
extern "C" {
#endif
void callee(char *str, int num)
{
__android_log_print(ANDROID_LOG_DEBUG, "target", "%s, 0x%x", str, num);
}
#ifdef __cplusplus
}
#endif
test.cpp (a module custom pass is applied)
#include <jni.h>
#ifdef __cplusplus
extern "C" {
#endif
void caller()
{
}
void Java_com_android_test_TestActivity_test(JNIEnv *env, jobject thiz)
{
caller();
}
#ifdef __cplusplus
}
#endif
TestPass.cpp (a custom pass)
#include "llvm/IR/Module.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
using namespace llvm;
namespace {
struct TestPass : public ModulePass {
static char ID;
TestPass() : ModulePass(ID) {}
virtual bool runOnModule(Module &M)
{
for (Module::iterator F = M.begin(), E = M.end(); F!= E; ++F)
{
if (F->getName() == "caller")
{
inst_iterator I = inst_begin(F);
Instruction *inst = &*I;
SMDiagnostic error;
LLVMContext context;
std::unique_ptr<Module> m = parseIRFile("callee.bc", error, context);
for (Module::iterator f = m->getFunctionList().begin(); f != m->getFunctionList().end(); f++)
{
if (f->getName() == "callee")
{
// Copy callee.bc callee function to current module and set AlwaysInline
ValueToValueMapTy VMap;
Function* callee_clone = CloneFunction(f, VMap, false);
/*
callee_clone->setName("callee_clone");
callee_clone->addFnAttr(Attribute::AlwaysInline);
M.getFunctionList().push_back(callee_clone);
// Add call to copied callee function
GlobalVariable* str = new GlobalVariable(M,
ArrayType::get(IntegerType::get(M.getContext(), 8), 8),
false,
GlobalValue::ExternalLinkage,
0,
"str");
str->setAlignment(1);
Constant* str_init = ConstantDataArray::getString(M.getContext(), "abcdefgh", false);
str->setInitializer(str_init);
ConstantInt* param1_indice1 = ConstantInt::get(M.getContext(), APInt(32, StringRef("0"), 10));
ConstantInt* param1_indice2 = ConstantInt::get(M.getContext(), APInt(32, StringRef("0"), 10));
std::vector<Constant*> param1_indices;
param1_indices.push_back(param1_indice1);
param1_indices.push_back(param1_indice2);
Constant* param1 = ConstantExpr::getGetElementPtr(str, param1_indices);
GlobalVariable* num = new GlobalVariable(M,
IntegerType::get(M.getContext(), 32),
false,
GlobalValue::ExternalLinkage,
0,
"num");
num->setAlignment(4);
ConstantInt* num_init = ConstantInt::get(M.getContext(), APInt(32, StringRef("12345"), 10));
num->setInitializer(num_init);
LoadInst* param2 = new LoadInst(num, "", false, inst);
param2->setAlignment(4);
std::vector<Value*> params;
params.push_back(param1);
params.push_back(param2);
CallInst* ci = CallInst::Create(callee_clone, params, "", inst);
ci->setCallingConv(CallingConv::C);
ci->setTailCall(false);
*/
}
}
}
}
return true;
}
};
}
char TestPass::ID = 0;
static RegisterPass<TestPass> X("TestPass", "TestPass", false, false);
static void registerTestPass(const PassManagerBuilder &, legacy::PassManagerBase &PM)
{
PM.add(new TestPass());
}
static RegisterStandardPasses RegisterTestPass(PassManagerBuilder::EP_ModuleOptimizerEarly, registerTestPass);
Error applying custom pass
[...snip...]
While deleting: [7 x i8]* %.str
Use still stuck around after Def is destroyed:#.str = private unnamed_addr constant [7 x i8] <null operand!>, align 1
Assertion failed: (use_empty() && "Uses remain when a value is destroyed!"), function ~Value, file /private/tmp/llvm/llvm-3.6.0.src/lib/IR/Value.cpp, line 81.
0 clang++ 0x000000011154d909 llvm::sys::PrintStackTrace(__sFILE*) + 57
1 clang++ 0x000000011154e07b SignalHandler(int) + 555
2 libsystem_platform.dylib 0x00007fffb7debb3a _sigtramp + 26
3 libsystem_platform.dylib 0x00000000509ff1d0 _sigtramp + 2562799280
4 clang++ 0x000000011154de36 abort + 22
5 clang++ 0x000000011154de11 __assert_rtn + 81
6 clang++ 0x00000001114f2104 llvm::Value::~Value() + 660
7 clang++ 0x00000001114a63d1 llvm::GlobalVariable::~GlobalVariable() + 97
8 clang++ 0x00000001114e3ba9 llvm::Module::~Module() + 105
9 TestPass.dylib 0x000000011254d7dc (anonymous namespace)::TestPass::runOnModule(llvm::Module&) + 524
10 clang++ 0x00000001114cdc4e llvm::legacy::PassManagerImpl::run(llvm::Module&) + 1054
11 clang++ 0x000000010f43f49a clang::EmitBackendOutput(clang::DiagnosticsEngine&, clang::CodeGenOptions const&, clang::TargetOptions const&, clang::LangOptions const&, llvm::StringRef, llvm::Module*, clang::BackendAction, llvm::raw_ostream*) + 7098
12 clang++ 0x000000010f57433d clang::BackendConsumer::HandleTranslationUnit(clang::ASTContext&) + 509
13 clang++ 0x000000010f609954 clang::ParseAST(clang::Sema&, bool, bool) + 468
14 clang++ 0x000000010f27aa53 clang::FrontendAction::Execute() + 67
15 clang++ 0x000000010f24cb2c clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) + 956
16 clang++ 0x000000010f20763a clang::ExecuteCompilerInvocation(clang::CompilerInstance*) + 4154
17 clang++ 0x000000010f1fe65c cc1_main(llvm::ArrayRef<char const*>, char const*, void*) + 1068
18 clang++ 0x000000010f2057ec main + 11660
19 libdyld.dylib 0x00007fffb7bdc235 start + 1
20 libdyld.dylib 0x0000000000000066 start + 1212300850
Stack dump:
0. Program arguments: /opt/llvm-3.6.0/build/Release+Asserts/bin/clang++ -cc1 -triple thumbv7-none-linux-androideabi -S -disable-free -main-file-name test.cpp -mrelocation-model pic -pic-level 1 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -no-integrated-as -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu cortex-a8 -target-feature +soft-float-abi -target-feature +vfp3 -target-feature +d16 -target-feature -neon -target-abi aapcs-linux -mfloat-abi soft -target-linker-version 253.3 -g -dwarf-column-info -ffunction-sections -coverage-file /opt/test/obj/local/armeabi-v7a/objs/test/test.o -resource-dir /opt/llvm-3.6.0/build/Release+Asserts/bin/../lib/clang/3.6.0 -dependency-file /opt/test/obj/local/armeabi-v7a/objs/test/test.o.d -MT /opt/test/obj/local/armeabi-v7a/objs/test/test.o -MP -D NDEBUG -D ANDROID -I /Applications/android-ndk-r10e/sources/cxx-stl/llvm-libc++/libcxx/include -I /Applications/android-ndk-r10e/sources/cxx-stl/llvm-libc++/../llvm-libc++abi/libcxxabi/include -I /Applications/android-ndk-r10e/sources/cxx-stl/llvm-libc++/../../android/support/include -I /opt/test/jni -I /Applications/android-ndk-r10e/platforms/android-21/arch-arm/usr/include -internal-isystem /usr/local/include -internal-isystem /opt/llvm-3.6.0/build/Release+Asserts/bin/../lib/clang/3.6.0/include -internal-externc-isystem /include -internal-externc-isystem /usr/include -O1 -Wno-invalid-command-line-argument -Wno-unused-command-line-argument -Wformat -Werror=format-security -std=c++11 -fdeprecated-macro -fno-dwarf-directory-asm -fdebug-compilation-dir /opt/test/jni -ferror-limit 19 -fmessage-length 152 -stack-protector 2 -mstackrealign -fno-rtti -fno-signed-char -fobjc-runtime=gcc -fdiagnostics-show-option -fcolor-diagnostics -load /opt/test/TestPass.dylib -mllvm -debug-pass=Structure -o /var/folders/vq/53lxh89j7ts1rtc9gfg_s7f80000gq/T/test-f2326e.s -x c++ /opt/test/jni/test.cpp
1. <eof> parser at end of file
2. Per-module optimization passes
3. Running pass 'TestPass' on module '/opt/test/jni/test.cpp'.
clang++: error: unable to execute command: Illegal instruction: 4
clang++: error: clang frontend command failed due to signal (use -v to see invocation)
clang version 3.6.0 (tags/RELEASE_360/final)
Target: armv7-none-linux-androideabi
Thread model: posix
clang++: note: diagnostic msg: PLEASE submit a bug report to http://llvm.org/bugs/ and include the crash backtrace, preprocessed source, and associated run script.
clang++: note: diagnostic msg:
********************
PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:
Preprocessed source(s) and associated run script(s) are located at:
clang++: note: diagnostic msg: /var/folders/vq/53lxh89j7ts1rtc9gfg_s7f80000gq/T/test-773901.cpp
clang++: note: diagnostic msg: /var/folders/vq/53lxh89j7ts1rtc9gfg_s7f80000gq/T/test-773901.sh
clang++: note: diagnostic msg:
********************
make: *** [/opt/test/obj/local/armeabi-v7a/objs/test/test.o] Error 254

XCode unable to find zmq.h even though it's in /usr/local/include and the header search path

I just installed the ZMQ library via brew and I can see the files in /usr/local/include and /usr/local/bin, however when I add those paths to the Header Search Path and Library Search Path in XCode I am unable to use #include as it continues to tell me it can't find the find.
Even when I add /usr/local/Cellar/zeromq/4.1.4/include (where the actual library is installed) to the Header Search Path it still won't find zmq.h even though the file is present in there.
What should I do?
Edit:
The full source is simply a example file from ZMQ themselfe,
//
// Hello World client in C++
// Connects REQ socket to tcp://localhost:5555
// Sends "Hello" to server, expects "World" back
//
#include <zmq.h>
#include <string>
#include <iostream>
int main ()
{
// Prepare our context and socket
zmq::context_t context (1);
zmq::socket_t socket (context, ZMQ_REQ);
std::cout << "Connecting to hello world server…" << std::endl;
socket.connect ("tcp://localhost:5555");
// Do 10 requests, waiting each time for a response
for (int request_nbr = 0; request_nbr != 10; request_nbr++) {
zmq::message_t request (5);
memcpy (request.data (), "Hello", 5);
std::cout << "Sending Hello " << request_nbr << "…" << std::endl;
socket.send (request);
// Get the reply.
zmq::message_t reply;
socket.recv (&reply);
std::cout << "Received World " << request_nbr << std::endl;
}
return 0;
}
The exact error is simply "lexical or Preprocessor issue, 'zmq.h' file not found main.cpp"
CompileC /Users/zezioen/Library/Developer/Xcode/DerivedData/ndovTest-bktygajikpscajfbqwlwhyjknvzq/Build/Intermediates/ndovTest.build/Debug/ndovTest.build/Objects-normal/x86_64/main.o ndovTest/main.cpp normal x86_64 c++ com.apple.compilers.llvm.clang.1_0.compiler
cd /Users/zezioen/stack/Projecten/CPP/ndovTest
export LANG=en_US.US-ASCII
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -x c++ -arch x86_64 -fmessage-length=0 -fdiagnostics-show-note-include-stack -fmacro-backtrace-limit=0 -std=gnu++11 -stdlib=libc++ -fmodules -gmodules -fmodules-cache-path=/Users/zezioen/Library/Developer/Xcode/DerivedData/ModuleCache -fmodules-prune-interval=86400 -fmodules-prune-after=345600 -fbuild-session-file=/Users/zezioen/Library/Developer/Xcode/DerivedData/ModuleCache/Session.modulevalidation -fmodules-validate-once-per-build-session -Wnon-modular-include-in-framework-module -Werror=non-modular-include-in-framework-module -Wno-trigraphs -fpascal-strings -O0 -fno-common -Wno-missing-field-initializers -Wno-missing-prototypes -Werror=return-type -Wunreachable-code -Werror=deprecated-objc-isa-usage -Werror=objc-root-class -Wno-non-virtual-dtor -Wno-overloaded-virtual -Wno-exit-time-destructors -Wno-missing-braces -Wparentheses -Wswitch -Wunused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wempty-body -Wconditional-uninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wconstant-conversion -Wint-conversion -Wbool-conversion -Wenum-conversion -Wshorten-64-to-32 -Wno-newline-eof -Wno-c++11-extensions -DDEBUG=1 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk -fasm-blocks -fstrict-aliasing -Wdeprecated-declarations -Winvalid-offsetof -mmacosx-version-min=10.11 -g -fvisibility-inlines-hidden -Wno-sign-conversion -I/Users/zezioen/Library/Developer/Xcode/DerivedData/ndovTest-bktygajikpscajfbqwlwhyjknvzq/Build/Intermediates/ndovTest.build/Debug/ndovTest.build/ndovTest.hmap -I/Users/zezioen/Library/Developer/Xcode/DerivedData/ndovTest-bktygajikpscajfbqwlwhyjknvzq/Build/Products/Debug/include -Iusr/local/include -I/Users/zezioen/Library/Developer/Xcode/DerivedData/ndovTest-bktygajikpscajfbqwlwhyjknvzq/Build/Intermediates/ndovTest.build/Debug/ndovTest.build/DerivedSources/x86_64 -I/Users/zezioen/Library/Developer/Xcode/DerivedData/ndovTest-bktygajikpscajfbqwlwhyjknvzq/Build/Intermediates/ndovTest.build/Debug/ndovTest.build/DerivedSources -F/Users/zezioen/Library/Developer/Xcode/DerivedData/ndovTest-bktygajikpscajfbqwlwhyjknvzq/Build/Products/Debug -MMD -MT dependencies -MF /Users/zezioen/Library/Developer/Xcode/DerivedData/ndovTest-bktygajikpscajfbqwlwhyjknvzq/Build/Intermediates/ndovTest.build/Debug/ndovTest.build/Objects-normal/x86_64/main.d --serialize-diagnostics /Users/zezioen/Library/Developer/Xcode/DerivedData/ndovTest-bktygajikpscajfbqwlwhyjknvzq/Build/Intermediates/ndovTest.build/Debug/ndovTest.build/Objects-normal/x86_64/main.dia -c /Users/zezioen/stack/Projecten/CPP/ndovTest/ndovTest/main.cpp -o /Users/zezioen/Library/Developer/Xcode/DerivedData/ndovTest-bktygajikpscajfbqwlwhyjknvzq/Build/Intermediates/ndovTest.build/Debug/ndovTest.build/Objects-normal/x86_64/main.o
/Users/zezioen/stack/Projecten/CPP/ndovTest/ndovTest/main.cpp:6:10: fatal error: 'zmq.h' file not found
#include <zmq.h>
^
1 error generated.
Edit 2:
I have no idea what happened but I just re-created the entire project, did the exact same steps as before and now it compiles and runs like it should.
The project I used was from a while ago so there may have been something else that was causing issues.
Check your build configuration for Search Path -> Always search for user paths and under your project name should say "yes"

clang try catch not working on OSX

$clang --version
Apple LLVM version 6.0 (clang-600.0.51) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin13.3.0
Thread model: posix
magick_wrapper.cpp
#include <Magick++.h>
#include <iostream>
#include <stdexcept>
#include "magick_wrapper.h"
using namespace std;
using namespace Magick;
void hello_world() {
cout << "hello world" << endl;
}
void initialize_imagick() {
static int isInitialized = 0;
if(!isInitialized) {
InitializeMagick(NULL);
isInitialized = 1;
}
}
void throw_exception_test() {
try {
throw runtime_error("just a test");
} catch (exception &error) {
cout << "error occured: " << error.what() << endl;
} catch (...) {
cout << "an exception has rasie" << ", but we don't know what it is" << endl;
}
}
haskell code with ffi
{-# LANGUAGE ForeignFunctionInterface #-}
module Main where
import Foreign.C
import Foreign.Ptr
foreign import ccall "hello_world"
c_hello_world :: IO ()
foreign import ccall "throw_exception_test"
c_throw_exception_test :: IO ()
main = do
c_hello_world
c_throw_exception_test
main.cpp
#include <iostream>
#include "magick_wrapper.h"
using namespace std;
int main() {
cout << "main start" << endl;
throw_exception_test();
cout << "main ends" << endl;
return 0;
}
make file
CC=clang
all: test testc
testc: magick_wrapper.o main.o
$(CC) -o testc main.o magick_wrapper.o `Magick++-config --cppflags --cxxflags --ldflags --libs` -lc++
main.o: main.cpp
$(CC) -c main.cpp
test: test.hs magick_wrapper.o
ghc -v -o test test.hs magick_wrapper.o `Magick++-config --ldflags --libs` -lc++
magick_wrapper.o: magick_wrapper.cpp
$(CC) -c `Magick++-config --cppflags --cxxflags` magick_wrapper.cpp -stdlib=libc++
clean:
rm *o *hi test testc
std output from test (haskell ffi)
$ ./test
hello world
libc++abi.dylib: terminating with uncaught exception of type std::runtime_error: just a test
Abort trap: 6
std ouptut from testc (pure c)
$ ./testc
main start
error occured: just a test
main ends
ghc verbose output
*** C Compiler:
clang -m64 -fno-stack-protector -DTABLES_NEXT_TO_CODE -c /var/folders/kp/f2t2ps216tl3p4t6jsplr9400000gn/T/ghc26839_0/ghc26839_4.c -o /var/folders/kp/f2t2ps216tl3p4t6jsplr9400000gn/T/ghc26839_0/ghc26839_5.o -I/usr/local/Cellar/ghc/7.8.3/lib/ghc-7.8.3/include
*** Linker:
clang -m64 -fno-stack-protector -DTABLES_NEXT_TO_CODE -m64 -o test -Wl,-no_compact_unwind test.o -L/usr/local/Cellar/imagemagick/6.8.9-7/lib -L/usr/local/Cellar/imagemagick/6.8.9-7/lib magick_wrapper.o '-lMagick++-6.Q16' -lMagickWand-6.Q16 -lMagickCore-6.Q16 '-lMagick++-6.Q16' -lMagickWand-6.Q16 -lMagickCore-6.Q16 '-lc++' -L/usr/local/Cellar/ghc/7.8.3/lib/ghc-7.8.3/base-4.7.0.1 -L/usr/local/Cellar/ghc/7.8.3/lib/ghc-7.8.3/integer-gmp-0.5.1.0 -L/usr/local/Cellar/ghc/7.8.3/lib/ghc-7.8.3/ghc-prim-0.3.1.0 -L/usr/local/Cellar/ghc/7.8.3/lib/ghc-7.8.3/rts-1.0 /var/folders/kp/f2t2ps216tl3p4t6jsplr9400000gn/T/ghc26839_0/ghc26839_5.o -Wl,-u,_ghczmprim_GHCziTypes_Izh_static_info -Wl,-u,_ghczmprim_GHCziTypes_Czh_static_info -Wl,-u,_ghczmprim_GHCziTypes_Fzh_static_info -Wl,-u,_ghczmprim_GHCziTypes_Dzh_static_info -Wl,-u,_base_GHCziPtr_Ptr_static_info -Wl,-u,_ghczmprim_GHCziTypes_Wzh_static_info -Wl,-u,_base_GHCziInt_I8zh_static_info -Wl,-u,_base_GHCziInt_I16zh_static_info -Wl,-u,_base_GHCziInt_I32zh_static_info -Wl,-u,_base_GHCziInt_I64zh_static_info -Wl,-u,_base_GHCziWord_W8zh_static_info -Wl,-u,_base_GHCziWord_W16zh_static_info -Wl,-u,_base_GHCziWord_W32zh_static_info -Wl,-u,_base_GHCziWord_W64zh_static_info -Wl,-u,_base_GHCziStable_StablePtr_static_info -Wl,-u,_ghczmprim_GHCziTypes_Izh_con_info -Wl,-u,_ghczmprim_GHCziTypes_Czh_con_info -Wl,-u,_ghczmprim_GHCziTypes_Fzh_con_info -Wl,-u,_ghczmprim_GHCziTypes_Dzh_con_info -Wl,-u,_base_GHCziPtr_Ptr_con_info -Wl,-u,_base_GHCziPtr_FunPtr_con_info -Wl,-u,_base_GHCziStable_StablePtr_con_info -Wl,-u,_ghczmprim_GHCziTypes_False_closure -Wl,-u,_ghczmprim_GHCziTypes_True_closure -Wl,-u,_base_GHCziPack_unpackCString_closure -Wl,-u,_base_GHCziIOziException_stackOverflow_closure -Wl,-u,_base_GHCziIOziException_heapOverflow_closure -Wl,-u,_base_ControlziExceptionziBase_nonTermination_closure -Wl,-u,_base_GHCziIOziException_blockedIndefinitelyOnMVar_closure -Wl,-u,_base_GHCziIOziException_blockedIndefinitelyOnSTM_closure -Wl,-u,_base_ControlziExceptionziBase_nestedAtomically_closure -Wl,-u,_base_GHCziWeak_runFinalizzerBatch_closure -Wl,-u,_base_GHCziTopHandler_flushStdHandles_closure -Wl,-u,_base_GHCziTopHandler_runIO_closure -Wl,-u,_base_GHCziTopHandler_runNonIO_closure -Wl,-u,_base_GHCziConcziIO_ensureIOManagerIsRunning_closure -Wl,-u,_base_GHCziConcziIO_ioManagerCapabilitiesChanged_closure -Wl,-u,_base_GHCziConcziSync_runSparks_closure -Wl,-u,_base_GHCziConcziSignal_runHandlers_closure -Wl,-search_paths_first -lHSbase-4.7.0.1 -lHSinteger-gmp-0.5.1.0 -lHSghc-prim-0.3.1.0 -lHSrts -lCffi -liconv -lgmp -lm -ldl
link: done
it seems during unwind, catch code was ignored by some reason. this behavior seems can only repeated under OSX with clang. I have tried gcc under Linux which works perfectly fine.

Segmentation fault in std::thread::id's std::operator==

I have encountered an issue which I am not sure how to resolve. I believe it's an issue in GCC and/or libstdc++.
I am running Ubuntu 14.04 LTS with GCC 4.8.2-19ubuntu1, libstdc++3.4.19 (I believe? How do you find what version of libstdc++ library is installed on your linux machine?), and boost 1.55.
Here's the code:
// http://www.boost.org/doc/libs/1_54_0/libs/log/doc/html/log/tutorial.html
// with a slight modification to ensure we're testing with threads too
// g++ -g -O0 --std=c++11 staticlinktest.cpp -lboost_log_setup -lboost_log -lboost_system -lboost_filesystem -lboost_thread -lpthread
#define BOOST_ALL_DYN_LINK 1
#include <boost/log/trivial.hpp>
#include <thread>
#include <atomic>
#include <vector>
int main(int, char*[])
{
BOOST_LOG_TRIVIAL(trace) << "A trace severity message";
BOOST_LOG_TRIVIAL(debug) << "A debug severity message";
BOOST_LOG_TRIVIAL(info) << "An informational severity message";
BOOST_LOG_TRIVIAL(warning) << "A warning severity message";
BOOST_LOG_TRIVIAL(error) << "An error severity message";
BOOST_LOG_TRIVIAL(fatal) << "A fatal severity message";
std::atomic<bool> exiting(false);
std::vector<std::thread> threads;
for ( int i = 0; i < 8; ++i ) {
threads.push_back(std::thread([&exiting](){
while (!exiting)
BOOST_LOG_TRIVIAL(trace) << "thread " << std::this_thread::get_id() << " trace";
}));
}
usleep(1000000);
exiting = true;
std::for_each(threads.begin(), threads.end(), [](std::thread& t){
t.join();
});
return 0;
}
The issue:
Using the command line at the top, I would build with dynamic linking. Everything seems to work great. I see apparently-valid output complete with thread IDs and tracing information.
However, in my project I need to be able to use static linking. So I add in the "-static" switch to the g++ command, and comment out the #define for BOOST_ALL_DYN_LINK. It builds just fine. But when I execute the program, it runs up until the first thread gets created, then segfaults. The backtrace seems to always be the same:
#0 0x0000000000000000 in ?? ()
#1 0x0000000000402805 in __gthread_equal (__t1=140737354118912, __t2=0) at /usr/include/x86_64-linux-gnu/c++/4.8/bits/gthr-default.h:680
#2 0x0000000000404116 in std::operator== (__x=..., __y=...) at /usr/include/c++/4.8/thread:84
#3 0x0000000000404c03 in std::operator<< <char, std::char_traits<char> > (__out=..., __id=...) at /usr/include/c++/4.8/thread:234
#4 0x000000000040467e in boost::log::v2s_mt_posix::operator<< <char, std::char_traits<char>, std::allocator<char>, std::thread::id> (strm=...,
value=...) at /usr/include/boost/log/utility/formatting_ostream.hpp:710
#5 0x0000000000402939 in __lambda0::operator() (__closure=0x7bb5e0) at staticlinktest.cpp:27
#6 0x0000000000403ea8 in std::_Bind_simple<main(int, char**)::__lambda0()>::_M_invoke<>(std::_Index_tuple<>) (this=0x7bb5e0)
at /usr/include/c++/4.8/functional:1732
#7 0x0000000000403dff in std::_Bind_simple<main(int, char**)::__lambda0()>::operator()(void) (this=0x7bb5e0)
at /usr/include/c++/4.8/functional:1720
#8 0x0000000000403d98 in std::thread::_Impl<std::_Bind_simple<main(int, char**)::__lambda0()> >::_M_run(void) (this=0x7bb5c8)
at /usr/include/c++/4.8/thread:115
#9 0x000000000047ce60 in execute_native_thread_routine ()
#10 0x000000000042a962 in start_thread (arg=0x7ffff7ffb700) at pthread_create.c:312
#11 0x00000000004e5ba9 in clone ()
It looks to me as if it's trying to call a null function pointer and only when linked statically. Any thoughts? Am I doing something wrong?
Statically linking libpthread into your applications is a really bad idea.
Nevertheless, here is how to do it.
I first fixed the compile errors (I suspect that you aren't showing us the code that you are actually compiling, or boost pollutes the namespace that much), then removed the irrelevant boost stuff, that only adds noise to the question. Here is the code:
#include <atomic>
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
int main(int, char*[])
{
std::atomic<bool> exiting(false);
std::vector<std::thread> threads;
for ( int i = 0; i < 8; ++i ) {
threads.push_back(std::thread([&exiting](){
while (!exiting)
std::cout << "thread " << std::this_thread::get_id() << " trace\n";
}));
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
exiting = true;
for(auto& t : threads){
t.join();
};
return 0;
}
It runs fine if I dynamically link but crashes when statically linked:
terminate called after throwing an instance of 'std::system_error'
what(): Operation not permitted
Aborted (core dumped)
According to this e-mail the libstdc++ has to be configured appropriately if you use threads and statically link. Here are the magic flags to make it work with static linking:
g++ -std=c++11 -pedantic -pthread threads.cpp -static -Wl,--whole-archive -lpthread -Wl,--no-whole-archive
As I said before, statically linking libpthread into your application is asking for trouble.

boost::program_options::positional_options_description termination

The following program aborts with pointer being freed was not allocated:
#include <boost/program_options.hpp>
int main(int argc, char* argv[])
{
boost::program_options::positional_options_description positional;
return 0;
}
I compiled and linked the program with Boost 1.46.1, which I built myself into /usr/local, on OS X 10.6.7. I can't find any installed libboost_program_options other than the one I'm (supposedly) linking against.
Any idea what causes this crash?
Edit: As for stacktrace, the program
#include <boost/program_options.hpp>
#include <execinfo.h>
int main(int argc, char* argv[])
{
boost::program_options::positional_options_description positional;
void* callstack[128];
int i, frames = backtrace(callstack, 128);
char** strs = backtrace_symbols(callstack, frames);
for (i = 0; i < frames; ++i) {
printf("%s\n", strs[i]);
}
free(strs);
return 0;
}
built as
g++ -Wp,-MMD,.make-debug/main.dd -Wall -g3 -I/usr/local/include -c main.cc -o .make-debug/main.o
g++ -o sandbox .make-debug/main.o -lboost_program_options -L/usr/local/lib
and run as ./sandbox produces the output
0 sandbox 0x00000001000017bf main + 57
1 sandbox 0x0000000100001764 start + 52
2 ??? 0x0000000000000001 0x0 + 1
sandbox(50587) malloc: *** error for object 0x7fff70506500: pointer being freed was not al
located
*** set a breakpoint in malloc_error_break to debug
Command terminated
As for building Boost:
$ cd boost_1_46_1
$ ./bootstrap.sh --prefix=/usr/local
$ ./bjam toolset=darwin-4.2
And here's my ~/user-config.jam:
using darwin : 4.0 : g++-4.0 ;
using darwin : 4.2 : g++-4.2 ;
using darwin : 4.5.1 : /Users/matan/usr/bin/g++ ;
I am unable to reproduce
macmini:stackoverflow samm$ cat po.cc
#include <boost/program_options.hpp>
#include <boost/version.hpp>
#include <iostream>
int
main(int argc, char* argv[])
{
std::cout << BOOST_LIB_VERSION << std::endl;
boost::program_options::positional_options_description positional;
return 0;
}
macmini:stackoverflow samm$ g++ -I /opt/local/include -L/opt/local/lib -lboost_program_options po.cc
macmini:stackoverflow samm$ ./a.out
1_46_1
macmini:stackoverflow samm$
you should update your question with the steps you used to build boost, particularly the arguments to bjam.
I think I resolved the issue, but I'm not happy with my solution. I neglected to mention that I previously installed gcc 4.6.0 with --program-suffix=-4.6 in /usr/local. Uninstalling it and rebuilding Boost solved the issue. I then had no compilers installed other than gcc-4.0 and gcc-4.2 which came with XCode. Presumably gcc-4.6 files interfered with gcc-4.0 files or the darwin toolset.