段错误,但在 valgrind 或 gdb 中没有出现。

3
在我的项目中,有一个库包含了使用Autodesk的FBX SDK 2017.1加载fbx文件的代码。
在调试和发布时,加载fbx会导致崩溃。崩溃有两种不同的方式出现,并且似乎是随机的:
1. 崩溃通常只是“Segmentation fault”。 2. 崩溃可能涉及到所有可能与之相关的库的转储,并且还提到一个realloc()调用的问题(偶尔出现)。从消息的上下文来看,我无法确定哪个realloc()可能是问题所在(消息后面跟着所有链接的库的转储)。
代码确实包含了realloc()调用,特别是在自定义的FbxStream中使用的缓冲区分配中。
大部分的代码路径对于Windows是完全相同的,只有一些特定于平台的部分已被重新实现。在Windows上,它可以正常运行。
引起我的注意的是,如果我在gdb或valgrind中运行程序,崩溃就消失了!因此,我开始查找未初始化的成员/值,但到目前为止,我没有发现任何可疑的地方。我使用了CppDepend / CppCheck和VS2012代码分析,但都没有发现未初始化的变量/成员。
为了更好地理解FBX加载的背景,FBX SDK有多种处理不同类型资源(obj、3ds、fbx等)的方式。它们可以从文件或流中加载。对于支持大文件,流选项是更相关的选择。下面的代码远非完美,但目前最让我感兴趣的是valgrind/gdb不会崩溃的原因。我在ReadString之上保留了SDK文档,因为它是最复杂的一个。
class MyFbxStream : public FbxStream{
    uint32 m_FormatID;
    uint32 m_Error;
    EState m_State;
    size_t m_Pos;
    size_t m_Size;
    const Engine::Buffer* const m_Buffer;
    MyFbxStream& operator = (const MyFbxStream& other) const;
public:
    MyFbxStream(const Engine::Buffer* const buffer) 
    : m_FormatID(0)
    , m_Error(0)
    , m_State(eClosed)
    , m_Pos(0)
    , m_Size(0)
    , m_Buffer(buffer) {};
    virtual ~MyFbxStream() {};
    virtual bool Open(void* pStreamData) {
        m_FormatID = *(uint32*)pStreamData;
        m_Pos = 0;
        m_State = eOpen;
        m_Size = m_Buffer->GetSize();
        return true;
    }
    virtual bool Close() {
        m_Pos = m_Size = 0;
        m_State = eClosed;
        return true;
    }
    virtual int Read(void* pData, int pSize) const  {
        const unsigned char* data = (m_Buffer->GetBase(m_Pos));
        const size_t bytesRead = m_Pos + pSize > m_Buffer->GetSize() ? (m_Buffer->GetSize() - m_Pos) : pSize;
        const_cast<MyFbxStream*>(this)->m_Pos += bytesRead;
        memcpy(pData, data, bytesRead);
        return (int)bytesRead;
    }
    /** Read a string from the stream.
    * The default implementation is written in terms of Read() but does not cope with DOS line endings.
    * Subclasses may need to override this if DOS line endings are to be supported.
    * \param pBuffer Pointer to the memory block where the read bytes are stored.
    * \param pMaxSize Maximum number of bytes to be read from the stream.
    * \param pStopAtFirstWhiteSpace Stop reading when any whitespace is encountered. Otherwise read to end of line (like fgets()).
    * \return pBuffer, if successful, else NULL.
    * \remark The default implementation terminates the \e pBuffer with a null character and assumes there is enough room for it.
    * For example, a call with \e pMaxSize = 1 will fill \e pBuffer with the null character only. */
    virtual char* ReadString(char* pBuffer, int pMaxSize, bool pStopAtFirstWhiteSpace = false) {
        assert(!pStopAtFirstWhiteSpace); // "Not supported"
        const size_t pSize = pMaxSize - 1;
        if (pSize) {
            const char* const base = (const char* const)m_Buffer->GetBase();
            char* cBuffer = pBuffer;
            const size_t totalSize = std::min(m_Buffer->GetSize(), (m_Pos + pSize));
            const char* const maxSize = base + totalSize;
            const char* sum = base + m_Pos;
            bool done = false;
            // first align the copy on alignment boundary (4byte)
            while ((((size_t)sum & 0x3) != 0) && (sum < maxSize)) {
                const unsigned char c = *sum++;
                *cBuffer++ = c;
                if ((c == '\n') || (c == '\r')) {
                    done = true;
                    break;
            }   }
            // copy from alignment boundary to boundary (4byte)
            if (!done) {
                int64 newBytesRead = 0;
                uint32* dBuffer = (uint32*)cBuffer;
                const uint32* dBase = (uint32*)sum;
                const uint32* const dmaxSize = ((uint32*)maxSize) - 1;
                while (dBase < dmaxSize) {
                    const uint32 data = *(const uint32*const)dBase++;
                    *dBuffer++ = data;
                    if (((data & 0xff) == 0x0a) || ((data & 0xff) == 0x0d)) { // third bytes, 4 bytes read..
                        newBytesRead -= 3;
                        done = true;
                        break;
                    } else {
                        const uint32 shiftedData8 = data & 0xff00;
                        if ((shiftedData8 == 0x0a00) || (shiftedData8 == 0x0d00)) { // third bytes, 3 bytes read..
                            newBytesRead -= 2;
                            done = true;
                            break;
                        } else {
                            const uint32 shiftedData16 = data & 0xff0000;
                            if ((shiftedData16 == 0x0a0000) || (shiftedData16 == 0x0d0000)) { // second byte, 2 bytes read..
                                newBytesRead -= 1;
                                done = true;
                                break;
                            } else {
                                const uint32 shiftedData24 = data & 0xff000000;
                                if ((shiftedData24 == 0x0a000000) || (shiftedData24 == 0x0d000000)) { // first byte, 1 bytes read..
                                    done = true;
                                    break;
                }   }   }   }   }
                newBytesRead += (int64)dBuffer - (int64)cBuffer;
                if (newBytesRead) {
                    sum += newBytesRead;
                    cBuffer += newBytesRead;
            }   }
            // copy anything beyond the last alignment boundary (4byte)
            if (!done) {
                while (sum < maxSize) {                 
                    const unsigned char c = *sum++;
                    *cBuffer++ = c;
                    if ((c == '\n') || (c == '\r')) {
                        done = true;
                        break;
            }   }   }
            const size_t bytesRead = cBuffer - pBuffer;
            if (bytesRead) {
                const_cast<MyFbxStream*>(this)->m_Pos += bytesRead;
                pBuffer[bytesRead] = 0;
                return pBuffer;
        }   }       
        pBuffer = NULL;
        return NULL;
    }
    virtual void Seek(const FbxInt64& pOffset, const FbxFile::ESeekPos& pSeekPos) {
        switch (pSeekPos) {
            case FbxFile::ESeekPos::eBegin:     m_Pos = pOffset; break;
            case FbxFile::ESeekPos::eCurrent:   m_Pos += pOffset; break;
            case FbxFile::ESeekPos::eEnd:       m_Pos = m_Size - pOffset; break;
        }
    }
    virtual long GetPosition() const        {   return (long)m_Pos; }
    virtual void SetPosition(long position) {   m_Pos = position;   }
    virtual void ClearError()               {   m_Error = 0;    }
    virtual int GetError() const            {   return m_Error; }
    virtual EState GetState()               {   return m_State; }
    virtual int GetReaderID() const         {   return m_FormatID;  }
    virtual int GetWriterID() const         {   return -1;  }                       // readonly stream
    virtual bool Flush()                    {   return true;    }                   // readonly stream
    virtual int Write(const void* /*d*/, int /*s*/) {   assert(false);  return 0; } // readonly stream
};

我认为与malloc/free/realloc相关的未定义行为可能与gdb无关。但如果是这种情况,我也预计Windows二进制文件会出现问题。
此外,我不知道这是否相关,但当我跟踪Open()函数并打印“m_Buffer”指针的值(或者“this”),我得到的指针值以0xfffffff开头,对于Windows程序员来说看起来像是一个问题。然而,在Linux中也看到了这种情况发生在静态函数调用等地方,我能得出同样的结论吗?
1个回答

8
如果我在gdb或valgrind中运行程序,崩溃就会消失!
有两种可能的解释:
1.存在多个线程,代码表现出数据竞争,并且GDB和Valgrind都显着影响执行时间。
2.GDB禁用地址随机化;Valgrind显着影响程序布局,并且崩溃对确切布局敏感。
我会采取以下步骤:
1.设置,运行程序并使其转储,然后在GDB中进行事后分析。
2.在GDB下运行程序,使用,看看是否可以通过这种方式到达崩溃点。
3.使用HelgrindDRD,Valgrind的线程错误检测器运行程序。

布局可能性较小;Windows也采用这种技巧,使病毒代码更难攻击。但您的另一个建议看起来是一个不错的选择。GL驱动程序似乎正在运行多个线程,我怀疑GL堆栈只是在处理抛出给它们的API调用时有所不同。 - StarShine
获取核心转储对于找到问题至关重要。结果发现是标准的Fbx分配器,更具体地说是FbxRealloc()似乎滥用printf样式的格式,并因未知原因而失败。一旦我用自己的替换了默认分配器,问题就得到了解决。很可能是两个分配器系统之间存在不匹配,一个用于使用我的自定义流的系统,另一个来自库内部的系统,在内存布局中造成混乱。 - StarShine

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接