How to find out what is throwing an exception using windbg - debugging
I have a c# windows service that is throwing an exception.
I have launched this service using windbg and have let it run until the exception is thrown.
WHen the debugger stops I do:
prefer_dml 1
!threads. This prints out the threads and I click on the Exception in question.
I click on the _message and it displays:
0:018> !DumpObj /d 0105e134
Name: System.String
MethodTable: 79b9f9ac
EEClass: 798d8bb0
Size: 120(0x78) bytes
File: C:\WINDOWS\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll
String: Object reference not set to an instance of an object.
THen I do: !clrstack and get the following:
06f8e090 04d48299 AD.Intellex.DriverService.ServerComponentManager.StopCrossFire()
06f8e098 04d48214 AD.Intellex.DriverService.WindowsService.OnStop()
76b5e8\System.ServiceProcess.ni.dll
06f8e108 04d48177 AD.Intellex.DriverService.WindowsService.UnhandledExceptionEventHandler(System.Object, System.UnhandledExceptionEventArgs)
06f8e4cc 791421db [GCFrame: 06f8e4cc]
06f8e568 791421db [GCFrame: 06f8e568]
06f8e63c 791421db [GCFrame: 06f8e63c]
06f8e740 791421db [GCFrame: 06f8e740]
06f8f234 791421db [HelperMethodFrame_PROTECTOBJ: 06f8f234] System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode, CleanupCode, System.Object)
06f8ec78 04d47f23 AD.HardwareInterface.IntellexHardwareInterface.ObjectProcessor.CameraAlarmActivate(Int32, SoftwareHouse.CrossFire.Common.DataServiceLayer.DataServiceObject, AD.Common.VideoObjectDefinitions.CameraAlertStatus, Boolean, System.DateTime, System.Collections.Generic.Dictionary`2 ByRef)
06f8edb8 04d46db3 AD.HardwareInterface.IntellexHardwareInterface.IntellexProcessor.ProcessCameraAlarm(System.Object)
06f8edf4 79b2d871 System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(System.Object)
06f8edfc 79ab4db5 System.Threading.ExecutionContext.runTryCode(System.Object)
06f8f234 791421db [HelperMethodFrame_PROTECTOBJ: 06f8f234] System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode, CleanupCode, System.Object)
06f8f298 79ab4cba System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
06f8f2b0 79ab7fc2 System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
06f8f2d4 79af2b66 System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
06f8f2e8 79af23f3 System.Threading.ThreadPoolWorkQueue.Dispatch()
06f8f334 79af2299 System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
06f8f6f4 791421db [DebuggerU2MCatchHandlerFrame: 06f8f6f4]
If you read up the ways you will see that the function that throws the exception is ObjectProcessor.CameraAlarmActivate
The code for this function is as follows:
public override void CameraAlarmActivate(int cameraNumber, DataServiceObject dso, AD.Common.VideoObjectDefinitions.CameraAlertStatus status, bool isBegin, DateTime time, out Dictionary<string, object> msgFormatParameters)
{
msgFormatParameters = null;
try
{
_alarmMutex.WaitOne();
Type type = TypeManager.Instance["SoftwareHouse.NextGen.Common.SecurityObjects.VideoCamera"];
if (type == null) return;
DataServiceObject camera = ClientServerConnection.Instance.FindObject(type, "Number = ? AND ServerID = ?", new object[] { cameraNumber, (int)dso[CameraKey.ObjectID] }, true) as DataServiceObject;
if (camera != null)
{
string alert = status.ToString();
List<string> alarmList = CheckIntellexCameraContainer(camera, dso, alert);
if(alarmList != null && alarmList.Count > 0)
{
bool alarmToJournal = false;
// If alarm is Motion...
if (status == AD.Common.VideoObjectDefinitions.CameraAlertStatus.Motion && alarmList.Contains("motion"))
{
alarmToJournal = true;
if (isBegin)
{
// Set the Motion property to true.
camera["Motion"] = true;
ClientServerConnection.Instance.UpdateObject(camera.ObjectKey, new string[] { "Motion" }, new object[] { true });
}
else
{
// Set the Motion property to false.
camera["Motion"] = false;
ClientServerConnection.Instance.UpdateObject(camera.ObjectKey, new string[] { "Motion" }, new object[] { false });
}
}
// If alarm is VideoLoss...
if (status == AD.Common.VideoObjectDefinitions.CameraAlertStatus.VideoLoss && alarmList.Contains(status.ToString().ToLower()))
{
alarmToJournal = true;
if (isBegin)
{
// Set the Videoloss property to true.
camera[CameraKey.Videoloss] = true;
ClientServerConnection.Instance.UpdateObject(camera.ObjectKey, new string[] { CameraKey.Videoloss }, new object[] { true });
}
else
{
// Set the Videoloss property to false;
camera[CameraKey.Videoloss] = false;
ClientServerConnection.Instance.UpdateObject(camera.ObjectKey, new string[] { CameraKey.Videoloss }, new object[] { false });
}
}
// If alarm is Light...
if (status == AD.Common.VideoObjectDefinitions.CameraAlertStatus.LightChange && alarmList.Contains("light"))
{
alarmToJournal = true;
if (isBegin)
{
// Set the Light property to true.
camera["Light"] = true;
ClientServerConnection.Instance.UpdateObject(camera.ObjectKey, new string[] { "Light" }, new object[] { true });
}
else
{
// Set the Light property to false;
camera["Light"] = false;
ClientServerConnection.Instance.UpdateObject(camera.ObjectKey, new string[] { "Light" }, new object[] { false });
}
}
// If alarm is Perimeter...
if (status == AD.Common.VideoObjectDefinitions.CameraAlertStatus.PerimeterProtection && alarmList.Contains("perimeter"))
{
alarmToJournal = true;
if (isBegin)
{
// Set the Perimeter property to true.
camera["Perimeter"] = true;
ClientServerConnection.Instance.UpdateObject(camera.ObjectKey, new string[] { "Perimeter" }, new object[] { true });
}
else
{
// Set the Light property to false;
camera["Perimeter"] = false;
ClientServerConnection.Instance.UpdateObject(camera.ObjectKey, new string[] { "Perimeter" }, new object[] { false });
}
}
// If alarm is AlarmIn(DryContact)...
if ((status == AD.Common.VideoObjectDefinitions.CameraAlertStatus.ExternalAlarm || status == AD.Common.VideoObjectDefinitions.CameraAlertStatus.DryContact) && alarmList.Contains("alarmin"))
{
alarmToJournal = true;
if (isBegin)
{
// Set the AlarmIn property to true.
camera["Alarmin"] = true;
ClientServerConnection.Instance.UpdateObject(camera.ObjectKey, new string[] { "Alarmin" }, new object[] { true });
}
else
{
// Set the AlarmIn property to false;
camera["Alarmin"] = false;
ClientServerConnection.Instance.UpdateObject(camera.ObjectKey, new string[] { "Alarmin" }, new object[] { false });
}
}
if(alarmToJournal)
msgFormatParameters = CreateMessageParameters(status, camera, dso, time);
}
}
}
catch (Exception)
{
}
finally
{
_alarmMutex.ReleaseMutex();
}
}
I want to look at this function in the debugger so I select the IP value for the function from the output of !clrstack. (04d47f23)
I get the following:
0:018> !U /d 04d47f23
Normal JIT generated code
AD.HardwareInterface.IntellexHardwareInterface.ObjectProcessor.CameraAlarmActivate(Int32, SoftwareHouse.CrossFire.Common.DataServiceLayer.DataServiceObject, AD.Common.VideoObjectDefinitions.CameraAlertStatus, Boolean, System.DateTime, System.Collections.Generic.Dictionary`2<System.String,System.Object> ByRef)
Begin 04d474d0, size a79
04d474d0 55 push ebp
04d474d1 8bec mov ebp,esp
04d474d3 57 push edi
04d474d4 56 push esi
04d474d5 53 push ebx
04d474d6 81ec10010000 sub esp,110h
04d474dc 8bf1 mov esi,ecx
04d474de 8dbd78ffffff lea edi,[ebp-88h]
04d474e4 b91e000000 mov ecx,1Eh
04d474e9 33c0 xor eax,eax
04d474eb f3ab rep stos dword ptr es:[edi]
04d474ed 8bce mov ecx,esi
04d474ef 33c0 xor eax,eax
04d474f1 8945e8 mov dword ptr [ebp-18h],eax
04d474f4 898d74ffffff mov dword ptr [ebp-8Ch],ecx
04d474fa 8bfa mov edi,edx
04d474fc 8b5d18 mov ebx,dword ptr [ebp+18h]
04d474ff 8b4508 mov eax,dword ptr [ebp+8]
04d47502 33d2 xor edx,edx
04d47504 8910 mov dword ptr [eax],edx
04d47506 8b8574ffffff mov eax,dword ptr [ebp-8Ch]
04d4750c 8b4834 mov ecx,dword ptr [eax+34h]
04d4750f 8b01 mov eax,dword ptr [ecx]
04d47511 8b402c mov eax,dword ptr [eax+2Ch]
04d47514 ff500c call dword ptr [eax+0Ch]
04d47517 e8d4ad4bfe call 032022f0 (SoftwareHouse.CrossFire.Common.Core.TypeManager.get_Instance(), mdToken: 010ACF2C)
04d4751c 8bc8 mov ecx,eax
04d4751e 8b158c28b501 mov edx,dword ptr ds:[1B5288Ch] ("SoftwareHouse.NextGen.Common.SecurityObjects.VideoCamera")
04d47524 3909 cmp dword ptr [ecx],ecx
04d47526 e8e5d04bfe call 03204610 (SoftwareHouse.CrossFire.Common.Core.TypeManager.get_Item(System.String), mdToken: 010ACF2C)
04d4752b 8945dc mov dword ptr [ebp-24h],eax
04d4752e 8bc8 mov ecx,eax
04d47530 33d2 xor edx,edx
04d47532 e853134274 call clr!RuntimeTypeHandle::TypeEQ (7916888a)
04d47537 85c0 test eax,eax
04d47539 7418 je <Unloaded_avcodec-53.dll>+0x8e7553 (04d47553)
04d4753b c745e400000000 mov dword ptr [ebp-1Ch],0
04d47542 c745e8fc000000 mov dword ptr [ebp-18h],0FCh
04d47549 68377fd404 push offset <Unloaded_avcodec-53.dll>+0x8e7f37 (04d47f37)
04d4754e e9c7090000 jmp <Unloaded_avcodec-53.dll>+0x8e7f1a (04d47f1a)
04d47553 e878ca4bfe call 03203fd0 (SoftwareHouse.CrossFire.Common.ClientInterfaceLayer.ClientServerConnection.get_Instance(), mdToken: 010ACF2C)
04d47558 898534ffffff mov dword ptr [ebp-0CCh],eax
04d4755e ba02000000 mov edx,2
04d47563 b9e2428879 mov ecx,offset mscorlib_ni+0x42e2 (798842e2)
04d47568 e853acc3fb call 009821c0 (JitHelp: CORINFO_HELP_NEWARR_1_OBJ)
04d4756d 89856cffffff mov dword ptr [ebp-94h],eax
04d47573 b97829ba79 mov ecx,offset mscorlib_ni+0x322978 (79ba2978) (MT: System.Int32)
04d47578 e8a3aac3fb call 00982020 (JitHelp: CORINFO_HELP_NEWSFAST)
04d4757d 8bf0 mov esi,eax
04d4757f 8b856cffffff mov eax,dword ptr [ebp-94h]
04d47585 8945b0 mov dword ptr [ebp-50h],eax
04d47588 897e04 mov dword ptr [esi+4],edi
04d4758b 56 push esi
04d4758c 8b8d6cffffff mov ecx,dword ptr [ebp-94h]
04d47592 33d2 xor edx,edx
04d47594 e8fb584574 call clr!JIT_Stelem_Ref (7919ce94)
04d47599 8b15002ab501 mov edx,dword ptr ds:[1B52A00h] ("ObjectID")
04d4759f 8b4d1c mov ecx,dword ptr [ebp+1Ch]
04d475a2 8b01 mov eax,dword ptr [ecx]
04d475a4 8b4034 mov eax,dword ptr [eax+34h]
04d475a7 ff5014 call dword ptr [eax+14h]
04d475aa 8bf8 mov edi,eax
04d475ac 813f7829ba79 cmp dword ptr [edi],offset mscorlib_ni+0x322978 (79ba2978)
04d475b2 740c je <Unloaded_avcodec-53.dll>+0x8e75c0 (04d475c0)
04d475b4 8bd7 mov edx,edi
04d475b6 b97829ba79 mov ecx,offset mscorlib_ni+0x322978 (79ba2978) (MT: System.Int32)
04d475bb e85e614274 call clr!JIT_Unbox (7916d71e)
04d475c0 b97829ba79 mov ecx,offset mscorlib_ni+0x322978 (79ba2978) (MT: System.Int32)
04d475c5 e856aac3fb call 00982020 (JitHelp: CORINFO_HELP_NEWSFAST)
04d475ca 8bf0 mov esi,eax
04d475cc 8b856cffffff mov eax,dword ptr [ebp-94h]
04d475d2 8945ac mov dword ptr [ebp-54h],eax
04d475d5 8b4704 mov eax,dword ptr [edi+4]
04d475d8 894604 mov dword ptr [esi+4],eax
04d475db 56 push esi
04d475dc 8b8d6cffffff mov ecx,dword ptr [ebp-94h]
04d475e2 ba01000000 mov edx,1
04d475e7 e8a8584574 call clr!JIT_Stelem_Ref (7919ce94)
04d475ec 8b8534ffffff mov eax,dword ptr [ebp-0CCh]
04d475f2 3900 cmp dword ptr [eax],eax
04d475f4 ff358833b101 push dword ptr ds:[1B13388h] ("Number = ? AND ServerID = ?")
04d475fa ffb56cffffff push dword ptr [ebp-94h]
04d47600 6a01 push 1
04d47602 6a00 push 0
04d47604 8b55dc mov edx,dword ptr [ebp-24h]
04d47607 8bc8 mov ecx,eax
04d47609 ff15c05a9900 call dword ptr ds:[995AC0h] (SoftwareHouse.CrossFire.Common.ClientInterfaceLayer.ClientServerConnection.FindObject(System.Type, System.String, System.Object[], Boolean, SoftwareHouse.CrossFire.Common.Core.RemoteProxyOption), mdToken: 010ACF2C)
04d4760f 8bd0 mov edx,eax
04d47611 b9a0576e03 mov ecx,36E57A0h (MT: SoftwareHouse.CrossFire.Common.DataServiceLayer.DataServiceObject)
04d47616 e8b7584574 call clr!JIT_IsInstanceOfClass (7919ced2)
04d4761b 8bf8 mov edi,eax
04d4761d 85ff test edi,edi
04d4761f 0f84e0080000 je <Unloaded_avcodec-53.dll>+0x8e7f05 (04d47f05)
04d47625 b918889503 mov ecx,3958818h (MT: AD.Common.VideoObjectDefinitions.CameraAlertStatus)
04d4762a e8f1a9c3fb call 00982020 (JitHelp: CORINFO_HELP_NEWSFAST)
04d4762f 8bf0 mov esi,eax
Is there any way from this that I can tell what could be throwing the exception???
Since you have the debugger catching the exception and have determined that the Exception is being thrown by the method named 'CameraAlarmActivate', then you could set a breakpoint at the top of the method and step through it until the Exception hits. You can then inspect the variables and troubleshoot accordingly.
From the Exception object you can also get more information.
// Get stack trace for the exception with source file information
var st = new StackTrace(ex, true);
// Get the top stack frame
var frame = st.GetFrame(0);
// Get the line number from the stack frame
var line = frame.GetFileLineNumber();
From here: C# - get line number which threw exception
In general it isn't very good practice to have empty exception handler's because errors can go unnoticed. I would suggest at least integrating a logging library so your application has its own log file and then writing an error log entry from all exceptions. You can also write other verbose type of logs that can help you trace through the applications state via the log file after an error has occurred. This is especially helpful from a Windows Service or any background based job where errors can happen at any place. Log4net is a good logging library that is easy to use: http://logging.apache.org/log4net/
Other than that, a wild guess from a quick look at your code would be that your client connection could be dropping at some point and ClientServerConnection or ClientServerConnection.Instance could become NULL at some point. That would be a good example of something you can do within the exception block. You could catch that specific exception and then re-connect and re-try.
Lastly, you might be missing certain symbols to debug that function with more detail, or you may have to enable some of the options your project related to debugging with unmanaged code.
Related
Function returning 0 works, returning > 0 will crash the Programm
Im making a call to a function in an if statement if (function(...)) { do some stuff... } else { do something else... } the problem now is that when the function returns 0 the else { ... } block executes perfectly fine, but if the function returns something > 0 the programm will crash. the function in question: BOOL fnCheckRegistryKeyW( _In_ LPCWSTR lpSubKey, _In_ LPCWSTR lpValueName, _In_ DWORD dwEType, _In_ BYTE bEValue ) { HKEY hKey; DWORD dwType; BYTE bValue; DWORD dwlen = sizeof(DWORD); BOOL bReturn = FALSE; LSTATUS lsRKey = RegOpenKeyEx(HKEY_LOCAL_MACHINE, lpSubKey, 0, KEY_READ | KEY_WOW64_32KEY, &hKey); if (!lsRKey) { LSTATUS lsRVal = RegQueryValueEx(hKey, lpValueName, 0, &dwType, (PBYTE)&bValue, &dwlen); if (!lsRVal) { if (dwType == dwEType && bValue == bEValue) { RegCloseKey(hKey); return TRUE; } else { } } else { } } else { } // If HKLM can't be read try HKCU hKey = NULL; lsRKey = RegOpenKeyEx(HKEY_CURRENT_USER, lpSubKey, 0, KEY_READ | KEY_WOW64_32KEY, &hKey); if (!lsRKey) { LSTATUS lsRVal = RegQueryValueEx(hKey, lpValueName, 0, &dwType, (PBYTE)&bValue, &dwlen); if (!lsRVal) { if (dwType == dwEType && bValue == bEValue) { RegCloseKey(hKey); return TRUE; } else { } } else { } } else { } RegCloseKey(hKey); return FALSE; } The function itself works fine, but it crashes the pragramm as soon as it has returned a value > 0 and due to that the Codeblock inside the if statement dosen't get executed.
You are passing a pointer to a single BYTE as the buffer for RegQueryValueEx() to write to, but you are setting dwLen to sizeof(DWORD) (4), allowing RegQueryValueEx() to write up to 4 bytes to a buffer that can only hold 1 byte. You need to change bValue from a BYTE to a DWORD, or else set dwLen to sizeof(BYTE) (1) instead. Otherwise, allocate the buffer dynamically. Call RegQueryValueEx() once with its lpData parameter set to NULL, then allocate the buffer using the byte size reported on output, then call RegQueryValueEx() again with that buffer.
Fastcall function crashes
trying to call a process function using fastcall convention from my program, but got a crash everytime trying to. Have passed so much time on it and can't solve that... need some help please... Here's all needed informations and my trying: The picture shows the instruction context after a breakpoint when the function's program is running... And here's my code source: typedef void (__fastcall * MyFoo)(void * client,DWORD trash, DWORD ConstantD, DWORD objBattid, DWORD zeroParam, DWORD thousParam, float fVal,DWORD targetID); MyFoo launchMe; DWORD getProcessBaseAdress(DWORD ProcessID); char *flyffServer = "insanity flyff\0"; HWND neuzWindow = NULL; DWORD neuzProcessID = NULL; DWORD neuzRamAdress = NULL; HANDLE neuzHandle = NULL; DWORD clientAdr = NULL; int main(){ neuzWindow = FindWindowA(0,flyffServer); //-------------------------------------- if(neuzWindow){ GetWindowThreadProcessId(neuzWindow,&neuzProcessID); if(neuzProcessID){ neuzHandle = OpenProcess(PROCESS_ALL_ACCESS,false,neuzProcessID); if(neuzHandle){ neuzRamAdress = getProcessBaseAdress(neuzProcessID); // Extracting Neuz's base address if(neuzRamAdress){ launchMe = (MyFoo)((DWORD)neuzRamAdress + 0x5C400); clientAdr = (DWORD)neuzRamAdress + 0x8D0DC0; printf("Instruction: 0x%08X\n",launchMe); printf("Client ADR: 0x%08X\n",clientAdr); for(;;Sleep(100)){ //------------ init params ------------ void * client = (void*)clientAdr; DWORD trashDX = (DWORD)0x0000000B; DWORD msge = (DWORD)0x0000001D; DWORD selectedBattID = 0x04D4A929; DWORD zeroParam = (DWORD) 0x00000000; DWORD milleParam = 0x00010000; float speedAtt = 0.07f; DWORD targetID = 0x0089B964; printf("0x%08X\n0x%08X\n0x%08X\n0x%08X\n0x%08X\n0x%08X\n%f\n0x%08X\n", client, trashDX, msge, selectedBattID, zeroParam, thousParam, speedAtt, targetID ); launchMe(client,trashDX,msge,selectedBattID,zeroParam,milleParam,speedAtt,targetID); // -> Error scanf("%d",&trashDX); // for blocking the program return 0; } } else printf("Unable to access to Neuz's Ram Adress\n"); } else printf("Unable to obtain neuz's handle\n"); } else printf("Unable to detect neuz's process ID\n"); } else printf("Unable to detect neuz's window\n"); return 0; } DWORD getProcessBaseAdress(DWORD ProcessID){ HANDLE hModuleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, ProcessID); MODULEENTRY32 me32; me32.dwSize = sizeof(MODULEENTRY32); Module32First(hModuleSnap,&me32); return (DWORD) me32.modBaseAddr; } Thanks in advance :) ...
As said IInspectable in his comment, the problem came from accessing virtual space of another process. Checking Windows memory management and DLL injection have solved the problem for me ... maybe anyone would face that in the futur.
Double-checked locking and the Singleton pattern
Does the Visual Studio 2015 compiler insert double-checked locking? I would like do make my Singleton (GOF) pattern thread safe (lock-free). Singleton& Singleton::getInstance() { static Singleton instance; return instance; } Is it possible to produce the assembler code and check?
You can access disassembly in Debug->Windows->Disassembly. For class: class S { public: static S& getInstance() { static S instance; return instance; } }; You get disassembly: 47: 48: class S 49: { 50: public: 51: static S& getInstance() 52: { push ebp mov ebp,esp sub esp,0C0h push ebx push esi push edi lea edi,[ebp-0C0h] mov ecx,30h mov eax,0CCCCCCCCh rep stos dword ptr es:[edi] 53: static S instance; 54: return instance; mov eax,offset instance (0D9471h) 55: } pop edi pop esi pop ebx mov esp,ebp pop ebp ret
Process32First is not returning TRUE even if process is running
I am trying to find the process running and killing it from my application. Below is my code. bool ProcessKill() { PROCESSENTRY32 process; Logger::getInstance()->test(L" checking the call kill status"); ZeroMemory(&process, sizeof(process)); process.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if( snapshot == INVALID_HANDLE_VALUE ) { Logger::getInstance()->test( TEXT(" CreateToolhelp32Snapshot (of processes)") ); return( FALSE ); } Logger::getInstance()->test(L" checking the call kill status 2222"); if (Process32First(snapshot, & process) != FALSE) { Logger::getInstance()->test(L"checking the kill status"); while(Process32Next(snapshot, &process) == TRUE) { Logger::getInstance()->test(L"1111"); if (wcsicmp(process.szExeFile, L"kill.exe") == 0) { Logger::getInstance()->test(L"found kill running"); HANDLE hProcess_Name = OpenProcess(PROCESS_ALL_ACCESS, FALSE, process.th32ProcessID); DWORD dwRet = ::WaitForSingleObject(hProcess_Name, 5000); if (dwRet == WAIT_OBJECT_0) dwRet = ERROR_SUCCESS; //Logger::getInstance()->test(L"kill is running"); else { ::TerminateProcess(hProcess_Name, 1); ::CloseHandle(hProcess_Name); Logger::getInstance()->test(L"kill is terminated"); CloseHandle(snapshot); return 1; } } } } else { Logger::getInstance()->test(L" Process32First the call kill status 333"); } CloseHandle(snapshot); return 0; } What I am observing that Process32First is failing it is returning false. Can any one let me know what is the reason behind the failure and how it can be fixed. Any work around for this.
Add bellow statement before if (Process32First(snapshot, & process) != FALSE) : pe32.dwSize = sizeof(PROCESSENTRY32W); As said in MSDN : tagPROCESSENTRY32 struct : typedef struct tagPROCESSENTRY32 { DWORD dwSize; DWORD cntUsage; DWORD th32ProcessID; ULONG_PTR th32DefaultHeapID; DWORD th32ModuleID; DWORD cntThreads; DWORD th32ParentProcessID; LONG pcPriClassBase; DWORD dwFlags; CHAR szExeFile[MAX_PATH]; } PROCESSENTRY32; dwSize Before calling the Process32First function, set this member to sizeof(PROCESSENTRY32). If you do not initialize dwSize, Process32First fails.
Win32 GUARD Memory : How can I use PAGE_GUARD to implement stack
I'm writing a tiny byte-code, interpreted language (or framework? vm?). I know Windows use PAGE_GUARD on stack, and I want to use this. First, I reserve virtual memory and do MEM_COMMIT/PAGE_GUARD on one page. pStack->end = VirtualAlloc(NULL, MaxSize, MEM_RESERVE, PAGE_READWRITE); if (pStack->end != NULL) { pStack->bp = pStack->sp = pStack->base = pStack->end + MaxSize; if (VirtualAlloc(pStack->base - PageSize, PageSize, MEM_COMMIT, PAGE_READWRITE | PAGE_GUARD) != NULL) (I know I should commit (non PAGE_GUARD) one page, but it's for testing PAGE_GUARD.) and I write __except as follows: __except (StackOnSEHExcept(GetExceptionInformation())) {} /* A */ ... DWORD StackOnSEHExcept(PEXCEPTION_POINTERS exc) { if (exc->ExceptionRecord->ExceptionCode == STATUS_GUARD_PAGE_VIOLATION) { return EXCEPTION_CONTINUE_EXECUTION; } else { return EXCEPTION_CONTINUE_SEARCH; } } (I also know I should commit/guard the next page, but it's for testing, too.) When I touch memory of stack, STATUS_GUARD_PAGE_VIOLATION is occured. but after that, /* A */ is run; Doesn't Windows unmark PAGE_GUARD after exception occur? and why doesn't this code work well? And, I don't know how to do this part: (I also know I should commit/guard the next page, but it's for testing, too.). How can I do? I think I should 1. get guarded-page's address 2. commit/guard the next page, but I don't know how to do 1. edit: I know how to do 1. the guarded address is here: exc->ExceptionRecord->ExceptionInformation[1] Thanks for all your help!
Doesn't Windows unmark PAGE_GUARD after exception occur? http://msdn.microsoft.com/en-us/library/windows/desktop/aa366786(v=vs.85).aspx ... Pages in the region become guard pages. Any attempt to access a guard page causes the system to raise a STATUS_GUARD_PAGE_VIOLATION exception and turn off the guard page status. Guard pages thus act as a one-time access alarm. Try this: DWORD OnSEH() { ::OutputDebugString( L"SEH!\n" ); return (DWORD) EXCEPTION_CONTINUE_EXECUTION; } static void Test() { const DWORD pageSize = 4096; void* baseAddr = ::VirtualAlloc(NULL, pageSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE ); DWORD oldAttr = 0; void* protectedAddr = baseAddr; BOOL ok = ::VirtualProtect( protectedAddr, pageSize, PAGE_READWRITE | PAGE_GUARD, &oldAttr ); if( !ok ) { int lastError = ::GetLastError(); lastError; return; } ::OutputDebugString( L"Reading the guarded page\n" ); __try { int* testAddr = static_cast<int*>( protectedAddr ); int value = *testAddr; value; ::OutputDebugString( L"Continue execution\n" ); } __except( OnSEH() ) {}