c++32/64位编译器简单获取cpuid低32位代码

来源:互联网 发布:网络软文推广公司 编辑:程序博客网 时间:2024/04/30 04:01

64位使用的是shellcode进行内联汇编代码,32位的编译器直接使用内联汇编就行了。

UINT64 GetCpuID(){#if defined(_WIN64)//64位编译器    UCHAR shellcode[] =         "\xB8\x01\x00\x00\x00" //mov eax 1         "\x0F\xA2"             //cpuid         "\xC3";                //ret    PVOID p = NULL;    //有dep保护机制 所以不能用malloc申请的堆内存中运行执行代码否则会触发异常     if (nullptr==(p = VirtualAlloc(NULL, sizeof(shellcode), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE)))        fprintf(stderr,"VirtualAlloc Failed!!!");    if (nullptr==(memcpy(p, shellcode, sizeof(shellcode))))        fprintf(stderr, "WriteMemory Failed!!!");    typedef UINT64(*SCFN)(void);    SCFN code = (SCFN)p;    //利用函数跳转的特性运行shellcode,shellcode 结尾必须有 ret指令 否则会会运行混乱崩溃。    UINT64 ret=code();    VirtualFree(p, sizeof(shellcode), MEM_RELEASE | MEM_COMMIT);    return ret;#else    volatile UINT hcpu = 0U;    __asm     {        mov eax,1        cpuid        mov hcpu,eax    }    return hcpu;#endif}
原创粉丝点击