通过指向不正确的函数类型的函数调用函数(未知)

时间:2017-04-05 02:47:50

标签: c++ pointers undefined-behavior ubsan

我有一个动态链接库的程序。 程序传递一个指向该库的函数指针来执行。

但是ubsan(Undefined Behavior Sanitizer)指定指针位于不正确的函数类型上。而这只发生

  • 如果回调函数具有类作为参数
  • 如果回调函数有一个类作为参数,但只有前向声明
  • 如果我指定编译标志:-fvisibility = hidden。

我使用clang来编译我的项目。

这是clang undefined行为消毒剂中的一个错误吗?

以下代码简化为一个简单的测试用例。检查评论,看看我们可以采取行动删除一些警告

申请代码:

Main.cxx

... and "Min Temp" is not null and "Min Temp" <> "" ... etc.

图书馆文件的代码是:

Caller.cxx:

#include "Caller.h"
#include "Param.h"

static void FctVoid()
{
}
static void FctInt(int _param)
{
   static_cast<void>(&_param);
}
static void FctCaller(Caller &_caller)
{
   static_cast<void>(&_caller);
}
static void FctParam(Param const &_param)
{
   static_cast<void>(&_param);
}

int main()
{
   Param param;
   Caller::CallVoid(&FctVoid);
   Caller::CallInt(&FctInt);
   Caller::CallThis(&FctCaller);
   Caller::CallParam(&FctParam, param);
   return 0;
}

Caller.h

#include "Caller.h"
// To uncomment to fix one warning
//#include "Param.h"
void Caller::CallVoid(FctVoidT _fct)
{
   _fct();
}
void Caller::CallInt(FctIntT _fct)
{
   _fct(32);
}
void Caller::CallThis(FctThisT _fct)
{
   Caller caller;
   _fct(caller);
}
void Caller::CallParam(FctParamT const &_fct, Param const &_param)
{
   _fct(_param);
}

Param.h

#ifndef __Caller_h_
#define __Caller_h_
#include "owExport.h"

class Param;
class EXPORT_Library Caller
{
public:
   typedef void(*FctVoidT)();
   static void CallVoid(FctVoidT _fct);
   typedef void(*FctIntT)(int);
   static void CallInt(FctIntT _fct);
   typedef void(*FctThisT)(Caller &);
   static void CallThis(FctThisT _fct);
   typedef void(*FctParamT)(Param const &);
   static void CallParam(FctParamT const &_fct, Param const &_param);
};
#endif

owExport.h

#ifndef __Param_h_
#define __Param_h_
#include "owExport.h"
class EXPORT_Library Param
{
public:
};
#endif

配置项目的CMakeLists.txt:

#ifndef __owExport_h_
#define __owExport_h_
#define OW_EXPORT __attribute__ ((visibility("default")))
#define OW_IMPORT
// Use this one to fix one warning
#define OW_IMPORT __attribute__ ((visibility("default")))
#ifdef Library_EXPORTS
#  define EXPORT_Library OW_EXPORT
#else
#  define EXPORT_Library OW_IMPORT
#endif
#endif

1 个答案:

答案 0 :(得分:0)

首先:如果您编辑问题以添加修复程序,那就不好了。这很难回答。

对于您的问题:您基本上有两个问题:首先,使用符号Caller, second with Param`,两者基本上是相同的。

对于问题的根源:UBSAN将指针的typeinfo与预期的typeinfo比较。如果typeinfo不同,则显示错误。 typeinfo比较是通过指针比较完成的。这对于提高速度非常有用,但会带来一个微妙的问题:即使实际类型实际上是相同的,它们也可能不会共享相同的typeinfo。当您从共享库中抛出一个类型并想将其捕获到可执行文件中时,这也很重要(反之亦然):捕获是通过typeinfo比较来完成的,并且两种类型不完全相同(共享相同的typeinfo)你不会抓住它的。

因此,您的第一个问题是class EXPORT_Library Caller:您有条件地将EXPORT_Library定义为“未导出”。如果它是从多个DSO导出的,则typeinfo将被合并。在您的情况下,可以将其导出到共享库中,而不是导出到可执行文件中,以免合并。您可以为此使用BOOST_SYMBOL_EXPORTOW_EXPORT

第二个问题是相反的(假设EXPORT_Library==OW_EXPORT):当包含Param.h标头时,将导出Param,而标头仅由可执行文件而不是共享库完成。同样,typeinfos没有合并->与RTTI系统的类型不同。

底线:在DSO边界上导出要使用的所有类。

相关问题