Wednesday, November 17, 2021

[SOLVED] C++ String Segfault on RHEL 8 with flto (but not RHEL 7)

Issue

I have this sample code:

# CMakeLists.txt

cmake_minimum_required(VERSION 3.18)
project(RHBuildTest CXX)

message(STATUS "C++ Compiler: ${CMAKE_CXX_COMPILER}")

add_executable(script1 script1.cpp)
set_target_properties(script1 PROPERTIES COMPILE_FLAGS "-flto")
// script1.cpp

#include <string>
#include <iostream>

int main()
{
    const std::string msg = "this is a string";

    std::cout << "msg.size():    " << msg.size() << "\n";
    std::cout << "msg:           " << msg << "\n";
    std::cout << "msg.substr(0): " << msg.substr(0) << "\n";

    return 0;
}

We now compile against g++ 10.2.0 on RHEL 7 and RHEL 8, but RHEL 8 gives a segault. If we take out -flto, then RHEL 8 runs just fine. Is this an ABI issue? Do I need to set certain paths so that the correct standard libs are loaded (when using -flto)? What could be causing this issue?


RHEL 7:

[~/code/rh_build_test/build_rh7]$ cat /etc/redhat-release; cmake ..; make; ./script1
Red Hat Enterprise Linux Server release 7.7 (Maipo)
-- C++ Compiler: /app/.../el7.3.10/x86_64-gcc10.2.x/gcc-10.2.0/bin/g++
-- Configuring done
-- Generating done
-- Build files have been written to: ~/code/rh_build_test/build_rh7
[ 50%] Building CXX object CMakeFiles/script1.dir/script1.cpp.o
[100%] Linking CXX executable script1
[100%] Built target script1
msg.size():    16
msg:           this is a string
msg.substr(0): this is a string

RHEL 8:

[~/code/rh_build_test/build_rh8]$ cat /etc/redhat-release; cmake ..; make; ./script1
Red Hat Enterprise Linux release 8.4 (Ootpa)
-- C++ Compiler: /app/.../el8_4.4.18/x86_64-gcc10.2.x/gcc-10.2.0/bin/g++
-- Configuring done
-- Generating done
-- Build files have been written to: ~/code/rh_build_test/build_rh8
[ 50%] Building CXX object CMakeFiles/script1.dir/script1.cpp.o
[100%] Linking CXX executable script1
[100%] Built target script1
Segmentation fault (core dumped)

Sometimes RHEL 8 prints a bit more, but it always fails at substr:

...
[100%] Built target script1
msg.size():    16
msg:           this is a string
Segmentation fault (core dumped)

Solution

This is a known bug in RHEL: Segfault when -flto is used to compile Catch framework tests on RHEL 8.4

To confirm that's the same bug you're running into, see if temporarily downgrading binutils to 2.30-79.el8 makes it work. If so, then it looks like it will be properly fixed when RHEL 8.5 is released. (EDIT: I just confirmed that this is indeed fixed in binutils 2.30-108, which was released with RHEL 8.5.)



Answered By - Joseph Sible-Reinstate Monica