【发布时间】:2017-08-30 11:05:30
【问题描述】:
我有一个动态链接库的程序。 程序将函数指针传递给该库以执行。
但是 ubsan (Undefined Behavior Sanitizer) 指定指针位于不正确的函数类型上。而这种情况只会发生
- 如果回调函数有一个类作为参数
- 如果回调函数有一个类作为参数,但只前向声明
- 如果我指定编译标志:-fvisibility=hidden。
我使用 clang 编译我的项目。
这是 clang 未定义行为清理程序中的错误吗?
下面的代码被简化为一个简单的测试用例。检查 cmets 看看我们可以在哪里采取行动来消除一些警告
应用程序代码:
Main.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;
}
库文件的代码是:
来电者.cxx:
#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);
}
caller.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
参数.h
#ifndef __Param_h_
#define __Param_h_
#include "owExport.h"
class EXPORT_Library Param
{
public:
};
#endif
owExport.h
#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
配置项目的CMakeLists.txt:
cmake_minimum_required(VERSION 3.0.0)
project(TestFunction)
set(BUILD_SHARED_LIBS ON)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -fsanitize=undefined ")
# Act here to for the call of function through pointer to incorrect function type
# set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden")
add_library(Library Caller.cxx Param.cxx)
add_executable(TestWithLib Main.cxx)
target_link_libraries(TestWithLib Library)
【问题讨论】:
-
您是否有可能在 ODR 方面搞砸了? clang.llvm.org/docs/LTOVisibility.html
-
该文档似乎与我的问题相对应。不幸的是,我测试了所有标志组合,但没有发现可以解决问题。
-
在将Caller.cxx编译成共享库时,是否定义了Library_EXPORTS?
-
我用我正在使用的 CMakeLists.txt 更新了这个问题。 Library_EXPORTS 由 CMake 使用 add_library 自动定义。
-
是的,这是我不得不解决一段时间的 Clang 错误。第一个创建 sscce 并将其报告为错误的获胜!
标签: c++ pointers undefined-behavior ubsan