是否有与 RtlSecureZeroMemory / SecureZeroMemory 等效的 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 pages 不要声明它的不会被优化器删除。
避免使用 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__
(
"%=:\n\t" /* generate a unique label for TOP */
#if (__WORDSIZE == 64)
"subq $1, %2\n\t" /* 0-based index */
#elif (__WORDSIZE == 32)
"subl $1, %2\n\t" /* 0-based index */
#elif (__WORDSIZE == 16)
"subw $1, %2\n\t" /* 0-based index */
#else
# error Unknown machine word size
#endif
"lea (%1, %2), %0\n\t" /* calcualte ptr[idx] */
"movb $0, (%0)\n\t" /* 0 -> ptr[size - 1] .. ptr[0] */
"jnz %=b\n\t" /* 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;
}