是否有Mac OS X等效的RtlSecureZeroMemory
/SecureZeroMemory
,该函数可将内存的块归零,但是编译器不会优化调用?
写下自己的功能:
void secure_zero(void *s, size_t n)
{
volatile char *p = s;
while (n--) *p++ = 0;
}
编辑:在评论中的问题上,为什么不 memset
?如果数组对象未访问,则可以由编译器优化memset
函数调用。
请注意,C11添加了(可选)函数memset_s
,并且标准保证该功能调用无法优化:
(C11,K.3.7.4.1p4)" [...]与MEMSET不同,任何对MEMSET_S函数的调用均应根据(5.1.2.3)所述的抽象机器的规则严格评估。IS,任何对MEMSET_S函数的调用都应假定S和N指示的内存可能会在将来访问,因此必须包含C。"
。" 。
是否有RTLSecureZureMemory/Secure zeromemory的Mac OS X等效,该函数可归零一个内存的函数,但是编译器不会优化调用?
在C运行时的最新版本中,您有memset_s
。它保证不优化。
#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>
errno_t memset_s(void * restrict s, rsize_t smax, int c, rsize_t n)
OS X还包括bzero
功能。但是 bzero(3)
man页面否 受优化器删除。
避免使用volatile
预选赛的技巧,因为它无法便携。它可以按照Windows的预期工作,但是GCC的人们将volatile
解释为I/O的硬件支持的内存。因此,您不应该使用volatile
驯服优化器。
这是您可以使用的内联装配实现。奇怪的是,ASM语句和块上的__volatile__
还可以。它在OS X上工作正常(这是最初写的地方)。
// g++ -Og -g3 -m64 wipe.cpp -o wipe.exe
// g++ -Og -g3 -m32 wipe.cpp -o wipe.exe
// g++ -Os -g2 -S -m64 wipe.cpp -o wipe.exe.S
// g++ -Os -g2 -S -m32 wipe.cpp -o wipe.exe.S
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
string s("Hello world");
cout << "S: " << s << endl;
char* ptr = &s[0];
size_t size = s.length();
if(ptr && size)
{
/* Needed because we can't just say to GCC, */
/* "give me a register that you choose". */
void* dummy;
__asm__ __volatile__
(
"%=:nt" /* generate a unique label for TOP */
#if (__WORDSIZE == 64)
"subq $1, %2nt" /* 0-based index */
#elif (__WORDSIZE == 32)
"subl $1, %2nt" /* 0-based index */
#elif (__WORDSIZE == 16)
"subw $1, %2nt" /* 0-based index */
#else
# error Unknown machine word size
#endif
"lea (%1, %2), %0nt" /* calcualte ptr[idx] */
"movb $0, (%0)nt" /* 0 -> ptr[size - 1] .. ptr[0] */
"jnz %=bnt" /* Back to TOP if non-zero */
: "=&r" (dummy)
: "r" (ptr), "r" (size)
: "0", "1", "2", "cc"
);
}
#if 0
cout.setf(ios::hex, ios::basefield);
cout.fill('0');
for(size_t i = 0; i < s.length(); i++)
cout << "0x" << setw(2) << ((int)s[i] & 0xff) << " ";
cout << endl;
#endif
cout << "S: " << s << endl;
return 0;
}