I´m Trying to launch two threads witch calls "DispFrontEnd" function
First thread ended OK, second failed to start jvm.. ??
tks
#include "jni.h"
#include <process.h>
#include "Stdafx.h"
//DISPATCH Thread Check
bool DispatchThreadCreated = FALSE;
if (DispatchThreadCreated == FALSE)
{
HANDLE hDispThread;
hDispThread = (HANDLE)_beginthread(DispFrontEnd,0,(void *)dispatchInputs);
if ((long)hDispThread == -1)
{
log.LogError("Thread DispFrontEnd Returned********BG ", (long)hDispThread);
log.LogError("errno", errno);
log.LogError("_doserrno", _doserrno);
}
else
{
logloc->LogMethod("Dispatch Thread CREATED");
DispatchThreadCreated= TRUE;
//Espera que a thread termine
WaitForSingleObject( hDispThread, INFINITE );
DispatchThreadCreated= FALSE; // 01_02_2010
logloc->LogMethod("Dispatch Thread ENDED");
}
}
if (DispatchThreadCreated == FALSE)
{
HANDLE hDispThread3;
logloc->LogMethod("3 : Dispatch Thread CREATED");
hDispThread3 = (HANDLE)_beginthread(DispFrontEnd,0,(void *)dispatchInputs);
if ((long)hDispThread3 == -1)
{
log.LogError("3 : Thread DispFrontEnd Returned********BG ", (long)hDispThread3);
log.LogError("errno", errno);
log.LogError("_doserrno", _doserrno);
}
else
{
logloc->LogMethod("3 : Dispatch Thread CREATED");
DispatchThreadCreated= TRUE;
//Espera que a thread termine
WaitForSingleObject( hDispThread3, INFINITE );
DispatchThreadCreated= FALSE; // 01_02_2010
logloc->LogMethod("3 : Dispatch Thread ENDED");
}
}
void DispFrontEnd(void * indArr)
{
JNIEnv *env;
JavaVM *jvm;
env = create_vm(&jvm); // return null on second call ???
}
JNIEnv* create_vm(JavaVM ** jvm) {
CString str;
JNIEnv *env;
JavaVMInitArgs vm_args;
JavaVMOption options;
options.optionString = "-Djava.class.path=C:\\dispatch\\lib\\Run.jar;C:\\dispatch\\classes"; //Path to the java source code
vm_args.version = JNI_VERSION_1_6; //JDK version. This indicates version 1.6
vm_args.nOptions = 1;
vm_args.options = &options;
vm_args.ignoreUnrecognized = 0;
int ret = JNI_CreateJavaVM(jvm, (void**)&env, &vm_args);
if(ret < 0)
{
env = NULL;
str.Format("ERROR! create JVM (%d)",ret); // show this on second call!! ?
logloc->LogMethod( str );
}
else
{
str.Format("JVM %x created Success!",env->GetVersion());
logloc->LogMethod( str );
}
return env;
}
Do you really have to start many JVM ? Could you use
jint AttachCurrentThread(JavaVM *vm, JNIEnv **p_env, void *thr_args);
instead ?
The only thing I know is a native thread cannot attach two different JVM at the same time.
Related
The driver I wrote is taken from the Windows Kernel Programming book but for some reason it just doesn't work.
Here is my driver entry:
extern "C" NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) {
UNREFERENCED_PARAMETER(RegistryPath);
auto status = STATUS_SUCCESS;
InitializeListHead(&g_Globals.ItemsHead);
g_Globals.Mutex.Init();
PDEVICE_OBJECT DeviceObject = nullptr;
UNICODE_STRING symLink = RTL_CONSTANT_STRING(L"\\??\\sysmon");
bool symLinkCreated = false;
do {
UNICODE_STRING devName = RTL_CONSTANT_STRING(L"\\Device\\sysmon");
status = IoCreateDevice(DriverObject, 0, &devName,
FILE_DEVICE_UNKNOWN, 0, TRUE, &DeviceObject);
if (!NT_SUCCESS(status)) {
KdPrint((DRIVER_PREFIX "failed to create device (0x%08X)\n",
status));
break;
}
DeviceObject->Flags |= DO_DIRECT_IO;
status = IoCreateSymbolicLink(&symLink, &devName);
if (!NT_SUCCESS(status)) {
KdPrint((DRIVER_PREFIX "failed to create sym link (0x%08X)\n",
status));
break;
}
symLinkCreated = true;
// register for process notifications
status = PsSetCreateProcessNotifyRoutineEx(OnProcessNotify, FALSE);
if (!NT_SUCCESS(status)) {
KdPrint((DRIVER_PREFIX "failed to register process callback (0x%08X)\n",
status));
break;
}
status = PsSetCreateThreadNotifyRoutine(OnThreadNotify);
if (!NT_SUCCESS(status)) {
KdPrint((DRIVER_PREFIX "failed to set thread callbacks (status=%08X)\n", status)\
);
break;
}
} while (false);
if (!NT_SUCCESS(status)) {
if (symLinkCreated)
IoDeleteSymbolicLink(&symLink);
if (DeviceObject)
IoDeleteDevice(DeviceObject);
}
DriverObject->DriverUnload = SysMonUnload;
DriverObject->MajorFunction[IRP_MJ_CREATE] =
DriverObject->MajorFunction[IRP_MJ_CLOSE] = SysMonCreateClose;
DriverObject->MajorFunction[IRP_MJ_READ] = SysMonRead;
return status;
}
now this function works well but i'm pretty sure the problem lies around here.
here is the SysMonCrearteClose function which also fails (I must say that I don't fully understand what I need to code in this function however even without calling it the driver failes, I'm sure there is a problem in here as well):
NTSTATUS SysMonCreateClose(_In_ PDEVICE_OBJECT DeviceObject, _In_ PIRP Irp) {
UNREFERENCED_PARAMETER(DeviceObject);
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return STATUS_SUCCESS;
}
now here is the SysMonUnload function:
void SysMonUnload(PDRIVER_OBJECT DriverObject) {
// unregister process notifications
PsSetCreateProcessNotifyRoutineEx(OnProcessNotify, TRUE);
UNICODE_STRING symLink = RTL_CONSTANT_STRING(L"\\??\\sysmon");
IoDeleteSymbolicLink(&symLink);
IoDeleteDevice(DriverObject->DeviceObject);
// free remaining items
while (!IsListEmpty(&g_Globals.ItemsHead)) {
auto entry = RemoveHeadList(&g_Globals.ItemsHead);
ExFreePool(CONTAINING_RECORD(entry, FullItem<ItemHeader>, Entry));
}
}
Here is the last function that matters, the SysMonRead function:
NTSTATUS SysMonRead(PDEVICE_OBJECT, PIRP Irp) {
UNREFERENCED_PARAMETER(Irp);
auto stack = IoGetCurrentIrpStackLocation(Irp);
auto len = stack->Parameters.Read.Length;
auto status = STATUS_SUCCESS;
auto count = 0;
NT_ASSERT(Irp->MdlAddress); // we're using Direct I/O
auto buffer = (UCHAR*)MmGetSystemAddressForMdlSafe(Irp->MdlAddress,
NormalPagePriority);
if (!buffer) {
status = STATUS_INSUFFICIENT_RESOURCES;
}
else {
AutoLock lock(g_Globals.Mutex);
while (true) {
if (IsListEmpty(&g_Globals.ItemsHead)) // can also check g_Globals.ItemCount
break;
auto entry = RemoveHeadList(&g_Globals.ItemsHead);
auto info = CONTAINING_RECORD(entry, FullItem<ItemHeader>, Entry);
auto size = info->Data.Size;
if (len < size) {
// user's buffer is full, insert item back
InsertHeadList(&g_Globals.ItemsHead, entry);
break;
}
g_Globals.ItemCount--;
::memcpy(buffer, &info->Data, size);
len -= size;
buffer += size;
count += size;
// free data after copy
ExFreePool(info);
}
}
Irp->IoStatus.Status = status;
Irp->IoStatus.Information = count;
IoCompleteRequest(Irp, 0);
return status;
}
throughout the program I allocate memory that is freed in the unload routine and open handles to files and mutexes which I also close. Whenever I load this driver the functionality intended is working properly (when I write to a file it works, the CreateClose function does not work) however when I unload the driver the system crashes. I used windbg to try and see what the issue is to no avail, here is the error message:
*** Fatal System Error: 0x000000ce
(0xFFFFF80260A71390,0x0000000000000010,0xFFFFF80260A71390,0x0000000000000000)
Driver at fault: ProcessThreadMonitorDriver.sys.
Break instruction exception - code 80000003 (first chance)
nt_exe!DbgBreakPointWithStatus:
I noticed sometimes it said something about an invalid memory access but it was inconsistent and unclear.
I am running this g_test where I simply initialize and close a client.
TEST(safIpc, createAndCloseClient)
{
std::shared_ptr<fnv::ipcsvc::IpcSvc> safIpc = std::make_shared<fnv::ipcsvc::IpcSvc>();
const std::string& app1 {"/testApp1"};
const std::string& groupName {"wir_clients"};
fnv::ipcsvc::IpcSvcAttrMq attr(fnv::ipcsvc::IpcSvcAttrType::MQ_CLIENT,
app1,
groupName,
"/server");
std::shared_ptr<IpcSvcTestSafHandler> msgHandler = std::make_shared<IpcSvcTestSafHandler>();
// initialize the ipc library
IpcSvcPriv::SharedPtr ipcPrivData {nullptr};
fnv::ipcsvc::IpcSvcRet ret = safIpc->init(attr, msgHandler, ipcPrivData);
EXPECT_EQ(ret, fnv::ipcsvc::IpcSvcRet::SUCCESS);
EXPECT_NE(ipcPrivData, nullptr);
ret = safIpc->close(ipcPrivData, app1); //HANGS here
EXPECT_EQ(fnv::ipcsvc::IpcSvcRet::SUCCESS, ret);
}
In init I create 3 threads: (here is the relevant part of the init code):
1- A process thread
2- a Receive thread
3- A timer thread
int rc = pthread_create(&m_timerThread,
NULL,
&IpcSvcImpl::timer_start,
this);
if (rc != 0)
{
ipcSvcLog(LOGE, "Failed to create timer thread!");
close(tmpPrivData,
attr.getAppId());
return error;
}
pthread_setname_np(m_timerThread,
"IpcSvcTimerThread");
}
// Start the worker threads
int rc = pthread_create(&m_receiveThread,
NULL,
&IpcSvcImpl::receive,
this);
if (rc != 0)
{
//TODO some error log
close(tmpPrivData,
attr.getAppId());
return error;
}
pthread_setname_np(m_receiveThread,
"IpcSvcReceiveThread");
rc = pthread_create(&m_processThread,
NULL,
&IpcSvcImpl::process,
this);
if (rc != 0)
{
//TODO some error log
close(tmpPrivData,
attr.getAppId());
return error;
}
pthread_setname_np(m_processThread,
"IpcSvcProcessThread");
Here is the close function:
IpcSvcRet IpcSvcImpl::close(IpcSvcPriv::SharedPtr privateData,
const std::string& appId)
{
if (!privateData)
{
//TODO log about client not providing sane private data
return IpcSvcRet::FAIL;
}
// acquire the mutex and set close called to true
{
std::lock_guard<std::mutex> guard(m_closeMtx);
m_closed = true;
}
if (m_msgQueue)
{
m_msgQueue->mutexInit();
// writing dummy message to process thread
std::pair<std::array<uint8_t, IPCSVC_MAX_MSG_SIZE>, ssize_t> queueMsg;
m_msgQueue->enqueue(queueMsg);
}
// writing dummy message to receive thread
uint32_t buffer = 0;
sendData(privateData,
(void*)&buffer,
sizeof(uint32_t),
appId);
pthread_join(m_receiveThread,
NULL);
pthread_join(m_processThread,
NULL);
if (m_isClient)
{
m_cv.notify_one();
printf("timer thread hangs\n"); // HANGS HERE ///////////////////////////////////////
pthread_join(m_timerThread,
NULL);
//This line is never reached..
}
delete m_msgQueue;
m_msgQueue = nullptr;
// close the ipc layer
if (m_ipc)
{
m_ipc->close();
delete m_ipc;
m_ipc = nullptr;
}
m_clientsList.clear();
m_hbManager = { };
return IpcSvcRet::SUCCESS;
}
Here is the timer_start function:
The timer thread is a timer that is keeps looping forever unless the fc->m_closed is set to true. It triggers fc->timerExpiry() every 2 seconds.
// timer thread entry
void* IpcSvcImpl::timer_start(void *arg)
{
if (!arg)
{
return nullptr;
}
printf("starting timer\n");
IpcSvcImpl* fc = static_cast<IpcSvcImpl *>(arg);
std::unique_lock<std::mutex> lock(fc->m_closeMtx);
while (!(fc->m_closed))
{
printf("Entering loop\n");
lock.unlock();
auto expireAt = std::chrono::steady_clock::now() +
std::chrono::seconds(fc->getTimerInterval());
fc->timerExpiry();
lock.lock();
printf("here?\n");
fc->m_cv.wait_until(lock, expireAt);
printf("Here 2\n");
}
printf("Exited loop\n\n");
return nullptr;
}
The output of the unittest:
[----------] 5 tests from safIpc
[ RUN ] safIpc.createAndCloseClient
starting timer
Entering loop
closing..
timer thread hangs
pthread join hangs forever, I am not sure why. The "here" prints are never hit, which seems odd.
Thanks for the help!
i build Simple Anticheat module for a game and i need protect the Thread's from a Suspend (Like Suspend Thread from Processhacker).
Is there any way to automatically resume the thread if is suspended?
Here is my module code:
#include "stdafx.h"
#include "Start.h"
void Msg_Sf_Br(){
MessageBoxA(NULL,"SpeedHack - Detect", load.Nome_das_Janelas, MB_SERVICE_NOTIFICATION | MB_ICONWARNING);
ExitProcess(0);
}
void Msg_Sf_En(){
MessageBoxA(NULL,"SpeedHack - Detect", load.Nome_das_Janelas, MB_SERVICE_NOTIFICATION | MB_ICONWARNING);
ExitProcess(0);
}
void Speed_perf()
{
if( *(unsigned long*)QueryPerformanceCounter != 2337669003 ){
if (load.Log_Txt_Hack == 1){
}
if (load.Message_Warning_En == 1){
ExitProcess(0);
}
if (load.Message_Warning_En == 2){
CreateThread(NULL,NULL,LPTHREAD_START_ROUTINE(Msg_Sf_Br),NULL,0,0);
Sleep(3000);
ExitProcess(0);
}
if (load.Message_Warning_En == 0){
ExitProcess(0);
}
else
ExitProcess(0);
}
}
void performance(){
if (load.Anti_Kill_Scans == 1)
{
again:
Speed_perf();
Sleep(load.Detecta_Speed_PerformanceT);
goto again;
}
else
{
again2:
Speed_perf();
Sleep(load.Detecta_Speed_PerformanceT);
goto again2;
}
}
void SPerformance(){
CreateThread(NULL,NULL,LPTHREAD_START_ROUTINE(performance),NULL,0,0);
}
Any idea?
With a little trick you can hide your thread from any debugger or tools like process hacker.
void func()
{
}
int main()
{
int(__stdcall* ZwCreateThreadEx)(HANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES, HANDLE, PVOID, PVOID, ULONG, ULONG_PTR, SIZE_T, SIZE_T, PVOID) = (decltype(ZwCreateThreadEx))GetProcAddress(GetModuleHandle("ntdll.dll"),"ZwCreateThreadEx");
HANDLE hThread=0;
ZwCreateThreadEx(&hThread,0x1FFFFF,0,GetCurrentProcess(),
(LPTHREAD_START_ROUTINE)func,0, 0x4/*hide flag*/,0,0x1000,0x10000,0);
return 0;
}
You can do it this way:
get list of process thread ids, using CreateToolhelp32Snapshot
go to first thread using methods: Thread32First.
for each found thread (you should check if belong to the given process):
then Open the thread using OpenThread in manner to retrieve handle to the thread from it thread id,
when you have the handle, you can suspend the thread using SuspendThread in manner to retrieve the previous suspension count,
then you can Resume the thread until it suspension count is 0. you must resume at least once in manner to cancel the suspension from the previous step.
if thread are not allowed to be suspended, you can use ResumeThread just to get the suspension count even if it was not suspended.
Close the thread handle using CloseHandle
iterate to next thread use Thread32Next.
In manner to be able to do the whole thing you must run as administrator.
Here is an example:
void TraverseProcessThreads(DWORD pid)
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); //get list of all system thread
if( hSnapshot == INVALID_HANDLE_VALUE)
{
//print error and return;
return;
}
THREADENTRY32 threadEntry;
if( Thread32First( hSnapshot, &threadEntry) )
{
size_t threadsCounter = 0, suspendedThreadsCounter=0;
do{
if(te.th32OwnerProcessID == pid) //we get all threads in system, should filter the relevant pid.
{
threadsCounter ++; //found thread
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS,FALSE,te.th32ThreadID); //get handle to thread from its thread id
if(hThread == NULL) //
{
//print error and break. (will be permission error if not administrator)
break;
}
int suspensionCount = SuspendThread( hThread ) ;//will return previous suspension count. you can also use ResumeThread if there's no way it can be suspended.
if(suspensionCount > 0)
{
//thread was suspended
suspendedThreadsCounter ++;
}
//cancel our suspension...
suspensionCount = ResumeThread(hThread );
/*to resume suspended thread use ResumeThread until it return 1.
do{
suspensionCount = ResumeThread(hThread );
}while (suspensionCount > 1); //similar to Suspend Resume return previous Suspention count.
*/
}
CloseHandle(hThread);
}while(Thread32Next( hSnapshot, &threadEntry) );
//print results:
cout<<"process id"<<pid<<endl<<" has "<<threadsCounter <<" threads " <<endl
<<suspendedThreadsCounter <<" threads was suspended"<<endl;
}
else{
//print some error...
}
CloseHandle(hSnapshot);
}
I am loading JVM in a dll but it fails (indicated in the code where it fails.). I tried the same code in an exe and it works fine.
JavaVMInitArgs vm_args; /* JDK 1.1 VM initialization arguments */
JNIEnv *env;
JavaVMOption options;
options.optionString = "-Djava.class.path=C:\\Core\\bin\\otk-1.4.1-with-dependencies.jar";
vm_args.version = JNI_VERSION_1_6;
vm_args.nOptions = 1;
vm_args.options = &options;
vm_args.ignoreUnrecognized = 0;
jvm_dll = LoadLibrary("C:\\Program Files\\Java\\jdk1.6.0_23\\jre\\bin\\server\\jvm.dll");
if(jvm_dll == NULL)
{
getManager()->log( "InitialiseJava::Can't Load JVM DLL.", HIGH_IMPORTANCE );
return false;
}
JNI_CreateJavaVM_ptr = (JNI_CreateJavaVM_func)GetProcAddress(jvm_dll, "JNI_CreateJavaVM");
if(JNI_CreateJavaVM_ptr == NULL)
{
getManager()->log( "InitialiseJava::Can't create JVM.", HIGH_IMPORTANCE );
return false;
}
int ret = JNI_CreateJavaVM_ptr(jvm, (void**)&env, &vm_args); // fails here
if(ret < 0)
{
getManager()->log( "InitialiseJava::Unable to call JVM.", HIGH_IMPORTANCE );
return false;
}
Please help.
Whenever I try to stop my service through the services manager, I get the following error and the service stays in a started state. "Could not stop the service on Local Computer. The service did not return an error. This could be an internal Windows error or an internal service error."
I've had such trouble with this issue that I tried to follow the logic from Microsoft as best as I could.
http://msdn.microsoft.com/en-us/library/windows/desktop/bb540474(v=vs.85).aspx
There is a similar issue with this in .Net 1.1 that you'll find if you search; however, I'm not using the framweork at all.
void WINAPI serviceCtrlHandler(DWORD dwCtrl )
{
switch(dwCtrl)
{
case SERVICE_CONTROL_STOP:
ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);
SetEvent(stopEvent);
ReportSvcStatus(serviceStatus->dwCurrentState, NO_ERROR, 0);
return;
case SERVICE_CONTROL_INTERROGATE:
break;
default:
break;
}
}
void WINAPI startMain(DWORD argc, LPTSTR *argv)
{
serviceStatusHandle = RegisterServiceCtrlHandler(SERVICE_NAME, serviceCtrlHandler);
serviceStatus->dwServiceType = SERVICE_WIN32_OWN_PROCESS;
serviceStatus->dwServiceSpecificExitCode = NO_ERROR;
if (serviceStatusHandle == 0)
{
debug->DebugMessage(L"RegisterServiceCtrlHandler() failed, error: " + Error::GetErrorMessageW(GetLastError()));
return;
}
ReportSvcStatus(SERVICE_START_PENDING, NO_ERROR, 3000);
if (!SetServiceStatus(serviceStatusHandle, serviceStatus))
{
//debug->DebugMessage(L"SetserviceStatus() failed, error: " + Error::GetErrorMessageW(GetLastError()));
//return;
}
stopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);
boost::thread dust_main_thread(dust_main);
while(1)
{
WaitForSingleObject(stopEvent, INFINITE);
ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);
return;
}
}
VOID ReportSvcStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwWaitHint)
{
static DWORD dwCheckPoint = 1;
serviceStatus->dwCurrentState = dwCurrentState;
serviceStatus->dwWin32ExitCode = dwWin32ExitCode;
serviceStatus->dwWaitHint = dwWaitHint;
if (dwCurrentState == SERVICE_START_PENDING)
serviceStatus->dwControlsAccepted = 0;
else serviceStatus->dwControlsAccepted = SERVICE_ACCEPT_STOP;
if ((dwCurrentState == SERVICE_RUNNING) || (dwCurrentState == SERVICE_STOPPED))
serviceStatus->dwCheckPoint = 0;
else
serviceStatus->dwCheckPoint = dwCheckPoint++;
SetServiceStatus(serviceStatusHandle, serviceStatus);
}
Run the service and then attach the debugger to the running process. Put a breakpoint at the serviceCtrlHandler and after the WaitForSingleObject(stopEvent, INFINITE) -- make sure what you think should happen does.