How to use this in ffi

0
std::string __cpuid()
{
    char VendorName[49] = {0};
    char VendorID[13] = {0};
    unsigned int a, b, c, d;
__asm xor EBX, EBX;
__asm xor ECX, ECX;
__asm xor EDX, EDX;
__asm mov EAX, 0x80000002;
__asm cpuid;
__asm mov a, EAX;
__asm mov b, EBX;
__asm mov c, ECX;
__asm mov d, EDX;
__asm mov DWORD PTR [VendorName + 0], EAX;
__asm mov DWORD PTR [VendorName + 4], EBX;
__asm mov DWORD PTR [VendorName + 8], ECX;
__asm mov DWORD PTR [VendorName + 12], EDX;
__asm mov EAX, 0x80000003;
__asm cpuid;
__asm mov DWORD PTR [VendorName + 16], EAX;
__asm mov DWORD PTR [VendorName + 20], EBX;
__asm mov DWORD PTR [VendorName + 24], ECX;
__asm mov DWORD PTR [VendorName + 28], EDX;
__asm mov EAX, 0x80000004;
__asm cpuid;
__asm mov DWORD PTR [VendorName + 32], EAX;
__asm mov DWORD PTR [VendorName + 36], EBX;
__asm mov DWORD PTR [VendorName + 40], ECX;
__asm mov DWORD PTR [VendorName + 44], EDX;
__asm mov EAX, 0x00000000;
__asm cpuid;
__asm mov DWORD PTR [VendorID + 0], EBX;
__asm mov DWORD PTR [VendorID + 4], EDX;
__asm mov DWORD PTR [VendorID + 8], ECX;
__asm mov EAX, 0x80000004;
    strcat(VendorName, " ");
    strcat(VendorName, VendorID);
    return string(VendorName);
}

Sirs, how to use this in ffi lua? I'm bad in ffi

I tried to use ffi.cdef, but compiller asked me: declaration specifier expected near 'std'

I tried to use a lot of everything, but im so noob

assembly
lua
jit
luajit
asked on Stack Overflow Aug 24, 2018 by Shuffle Boy • edited Aug 25, 2018 by Egor Skriptunoff

1 Answer

1

This code works on LuaJIT x86
(It doesn't work if LuaJIT was built using MS VisualStudio, use MinGW)

assert(jit.arch =='x86')

local ffi = require("ffi")
local qwords = ffi.typeof("uint64_t[?]")
local dwords = ffi.typeof("uint32_t *")
-- cpuid_EAX_EDX = push EBX / cpuid / pop EBX / ret
local cpuid_EAX_EDX = ffi.cast("__cdecl uint64_t (*)(uint32_t)", "\x53\x0F\xA2\x5B\xC3")
-- cpuid_EBX_ECX = push EBX / cpuid / xchg EAX,ECX / xchg EAX,EDX / xchg EAX,EBX / pop EBX / ret
local cpuid_EBX_ECX = ffi.cast("__cdecl uint64_t (*)(uint32_t)", "\x53\x0F\xA2\x91\x92\x93\x5B\xC3")

local function cpuid(n)
   local arr = ffi.cast(dwords, qwords(2, cpuid_EAX_EDX(n), cpuid_EBX_ECX(n)))
   return ffi.string(arr, 4), ffi.string(arr + 2, 4), ffi.string(arr + 3, 4), ffi.string(arr + 1, 4)
end

local s1 = ""
for n = 0x80000002, 0x80000004 do
   local eax, ebx, ecx, edx = cpuid(n)
   s1 = s1..eax..ebx..ecx..edx
end
s1 = s1:gsub("^%s+", ""):gsub("%z+$", "")  -- remove leading spaces and trailing zeroes

local eax, ebx, ecx, edx = cpuid(0)
local s2 = ebx..edx..ecx
s2 = s2:gsub("^%s+", ""):gsub("%z+$", "")  -- remove leading spaces and trailing zeroes

print(s1.." "..s2)  -- Intel(R) Core(TM) i5-3470 CPU @ 3.20GHz GenuineIntel
answered on Stack Overflow Aug 24, 2018 by Egor Skriptunoff • edited Aug 24, 2018 by Egor Skriptunoff

User contributions licensed under CC BY-SA 3.0