为了账号安全,请及时绑定邮箱和手机立即绑定

golang 使用 cgo 调用 c 库时未检测到 sanitizer-leak

golang 使用 cgo 调用 c 库时未检测到 sanitizer-leak

Go
慕桂英3389331 2022-06-01 10:57:17
概括以前我使用 clang-3.8.1 并且使用 AddressSanitizer 时 sanitizer 崩溃了。而leakSanitizer 根本不起作用。然后我尝试使用clang-llvm-10.0,AddressSanitizer可以检测到地址问题并正常工作。但是当golang使用cgo调用C时无法检测到泄漏问题。当golang使用CGO时,是否可以使用leak-sanitizer来检测C/C++库中的内存泄漏问题?例子cgo-sanitizer.go:预计会检测到地址问题。package main// #include <stdlib.h>//// int test()// {//   int *p = (int *)malloc(10 * sizeof(int));//   free(p);//   p[1] = 42;//   return p[1];// }import "C"import "fmt"func main() {  fmt.Println(int(C.test()))  // Output: 42}输出[root@380c7770b175 cplusplus]# CC="clang" CGO_CFLAGS="-O0 -g -fsanitize=address" CGO_LDFLAGS="-fsanitize=address" go run cgo-sanitizer.go===================================================================25680==ERROR: AddressSanitizer: heap-use-after-free on address 0x604000000014 at pc 0x00000054fc2d bp 0x7ffd96a943b0 sp 0x7ffd96a943a8WRITE of size 4 at 0x604000000014 thread T0    #0 0x54fc2c in test (/tmp/go-build237509829/b001/exe/cgo-sanitizer+0x54fc2c)    #1 0x54fcc1 in _cgo_a3187169dba5_Cfunc_test (/tmp/go-build237509829/b001/exe/cgo-sanitizer+0x54fcc1)    #2 0x5159df  (/tmp/go-build237509829/b001/exe/cgo-sanitizer+0x5159df)cgo-sanitizer-leak.go:未检测到泄漏问题。为什么?package main// #include <stdlib.h>//// int *p;// int test()// {//   p = (int *)malloc(10 * sizeof(int));//   p = 0;//   return 52;// }import "C"import "fmt"func main() {  fmt.Println(int(C.test()))  // Output: 52}[root@380c7770b175 cplusplus]# CC="clang" CGO_CFLAGS="-O0 -g -fsanitize=leak" CGO_LDFLAGS="-fsanitize=address" go run cgo-sanitizer-leak.go52环境[root@380c7770b175 cplusplus]# cat /proc/versionLinux version 3.10.0-493.el7.x86_64 (mockbuild@x86-020.build.eng.bos.redhat.com) (gcc version 4.8.5 20150623 (Red Hat 4.8.5-9) (GCC) ) #1 SMP Tue Aug 16 11:45:26 EDT 2016原始问题https://github.com/google/sanitizers/issues/1223
查看完整描述

2 回答

?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

我已经通过__lsan_do_leak_check()在进程退出时显式调用来解决它。

__lsan_do_leak_check() 在

https://github.com/llvm/llvm-project/blob/master/compiler-rt/include/sanitizer/lsan_interface.h

我猜它与 c-main 启动机制有关,并且 __lsan_do_leak_check() 没有为 golang 启动注册。

欢迎任何可以持续挖掘它的人。


查看完整回答
反对 回复 2022-06-01
?
吃鸡游戏

TA贡献1829条经验 获得超7个赞

如果您的主程序是用 Go 编写的,您需要手动调用 __lsan_do_leak_check。如果您的 main 是 C/C++ 并且 Go 作为库调用,则不需要它。


这是一个简单的例子


package main


// #include <stdio.h>

// #include <stdlib.h>

//

// void __lsan_do_leak_check(void);

//

// void leak_a_bit(void)

// {

//     char* p = malloc(2000);

//     printf("%p\n", p);

// }

import "C"


func main() {

        C.leak_a_bit()


        C.__lsan_do_leak_check()

}

像这样编译运行


$ CC=clang CGO_ENABLED=1 CGO_LDFLAGS='-fsanitize=address' CGO_CFLAGS='-fsanitize=address' go build -o main


$ ./main


查看完整回答
反对 回复 2022-06-01
  • 2 回答
  • 0 关注
  • 233 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号