Ahmed Jihad
Ahmed Jihad

Reputation: 84

Use CreateThread With Kotlin Native?

I tried to use CreateThread in kernel32 to start a DataCollectorEntry function in new thread but it did not execute any line on the function and the GetLastError return 0 that means everything is right so what is the problem

@OptIn(ExperimentalForeignApi::class)
var instanceHandleModule: HMODULE? = null
@OptIn(ExperimentalForeignApi::class)
var functionThread: HANDLE? = null

@ThreadLocal
var globalValueInternal: HANDLE_PTR = 0xdeadbeefUL

@OptIn(ExperimentalNativeApi::class, ExperimentalForeignApi::class)
fun DataCollectorEntry(lpThreadParameter : LPVOID?): DWORD{
    OutputDebugStringA("Data Collector Entry")
    MessageBoxA(null, "HI", "Test", MB_OK.toUInt())
//    val lpBaseAddress:  COpaquePointer? = malloc(8UL)
//    lpBaseAddress.rawValue
//    val lpBuffer = malloc(8UL)
//    ReadProcessMemory(GetCurrentProcess(), lpBaseAddress, lpBuffer, 8UL, null)

    return 0u
}

@OptIn(ExperimentalNativeApi::class, ExperimentalForeignApi::class)
@CName("DllMain")
fun DllMain(hModule: HMODULE, ul_reason_for_call: DWORD, lpReserved: LPVOID): Boolean {
    when (ul_reason_for_call.toInt()) {
        DLL_PROCESS_ATTACH -> {
            instanceHandleModule = hModule
            OutputDebugStringA("DllMain Attached")
//            val threadFunc2: CPointer<CFunction<(LPVOID?) -> DWORD>> = GetProcAddress(GetModuleHandleA("kernel32"), "CreateThread")!!.reinterpret()

            val threadFunc: CPointer<CFunction<(LPVOID?) -> DWORD>> = staticCFunction(::DataCollectorEntry)
            functionThread = CreateThread(null, 0u, threadFunc, NULL, 0u, null)
            MessageBoxA(null, "Last Error ${GetLastError()} , $functionThread", "Test", MB_OK.toUInt())
//            OutputDebugStringA(GetLastError().toString())
//            OutputDebugStringA("Thread Handle:: ${if (functionThread == null) "It Is Null" else functionThread.toLong()}")
        }

        DLL_PROCESS_DETACH -> {
            // Perform cleanup or finalization tasks here
            OutputDebugStringA("DllMain Detached")
        }
    }
    return true
}

Upvotes: 0

Views: 70

Answers (1)

Ahmed Jihad
Ahmed Jihad

Reputation: 84

So i found that code is right, let me explain when i want to test the dll i openned the dll with the x64dbg directily but in this case the thread created but i did not know why the thread function does not exexuted, but when i tried to inject the dll in other process the function executed so the code is right

Upvotes: 0

Related Questions