gpt4 book ai didi

c++ - 中毒某些 API 函数(不是维护者)

转载 作者:可可西里 更新时间:2023-11-01 15:27:44 38 4
gpt4 key购买 nike

相关例如: How to poison an identifier in VC++?
What does it mean to "poison a function" in C++?

有没有办法“正确地”毒化一些声明(或实现)不受我控制的函数?

具体来说,我试图防止意外使用某些可能导致意外结果的 Windows API 函数,例如CreateFileA(使用 T 宏隐藏了您混合使用 ANSI 和 Unicode 的事实)或 SetWindowLong(这将导致您的程序无声地失败,没有错误,也没有有机会知道在 64 位系统上出了什么问题)。

我对“正确”投毒的定义是,尝试调用函数会破坏构建并出现可读错误(如果错误发生在源代码中的正确位置,则加分)。
最好,这应该是可移植的,并且至少它必须与 GCC 和 clang 一起工作。

到目前为止我尝试过/看过的内容:

预处理器

最简单、最直接的解决方案是利用预处理器:

#define CreateFileA __poison_ANSI_CreateFileA

这对于一个特定的功能以及其他几个功能都非常有效,完全按预期工作,并有一个精确的错误提示问题并指向源代码中的正确位置:

error: no matching function for call to '__poison_ANSI_CreateFileA'
note: expanded from macro 'CreateFile'
note: expanded from ... (precise location in source)

对于不同的功能,需要为每个功能起一个唯一的名称,以避免定义冲突的错误,这很繁琐但很容易做到。到目前为止一切顺利,除了它不适用于 MinGW-w64 header 本身使用可变参数宏篡改名称的函数,例如 CreateWindowSetWindowLong。无论如何,无论是否中毒,这些编译都很好。

语用

#pragma GCC poison,clang 恰好也能理解(并且还具有自己的版本),看起来和听起来应该完全按照我的意愿行事,并且以尽可能地道的方式. las,它不起作用。或者更确切地说,它太好了
当中毒名称出现在声明中时,使用 pragma 指令中毒的函数已经触发错误,这意味着......每次,在每个包含 header 的构建中。这对写程序不是很有帮助!

属性

这些有一个巨大的缺点,即您必须准确地复制类型定义,以免一方面在合法调用中出现“模糊函数调用”错误。另一方面,它们不起作用。 clang 提示 __attribute__((__error__)) 但忽略 gnu::__error__gnu::error 以及 gnu::已弃用。此外,标准的 [[deprecated]] 一切都很好,但似乎什么也没做(编译很好,甚至没有警告?!)。

有什么我可以做的吗?

最佳答案

已找到一种通过在命名空间中添加同一函数的另一个声明来加强歧义的方法。没有使用 pragmas 或 attrbiutes,应该可以移植到任何 C++11 编译器:

#include <stdio.h>

#define POISONED_BY_NAME(name) \
namespace Poisoned \
{ \
using function_type = decltype(::name); \
extern function_type* name; \
} \
using namespace Poisoned;


POISONED_BY_NAME(puts)

int main()
{
puts("Hello");
}

Visual Studio 消息:

error C2872: 'puts': ambiguous symbol
1>c:\program files\windows kits\10\include\10.0.17763.0\ucrt\stdio.h(353): note: could be 'int puts(const char *)'
1>c:\test.cpp(43): note: or 'Poisoned::function_type (__cdecl *__cdecl Poisoned::puts)'

海湾合作委员会消息:

main.cpp: In function 'int main()':
main.cpp:16:5: error: reference to 'puts' is ambiguous
puts("Hello");
^~~~
main.cpp:12:22: note: candidates are: 'int (* Poisoned::puts)(const char*)'
POISONED_BY_NAME(puts)
^~~~
main.cpp:7:35: note: in definition of macro 'POISONED_BY_NAME'
extern function_type* name; \
^~~~
In file included from main.cpp:1:
/usr/include/stdio.h:695:12: note: 'int puts(const char*)'
extern int puts (const char *__s);
^~~~

关于c++ - 中毒某些 API 函数(不是维护者),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41858089/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com