LONG MiniDumper::TopLevelFilter(struct _EXCEPTION_POINTERS *exceptionInfo) { LONG result = EXCEPTION_CONTINUE_SEARCH; if (CreateMiniDump(_T("Mini"), exceptionInfo, MiniDumpNormal) && CreateMiniDump(_T("Midi"), exceptionInfo, MiniDumpWithPrivateReadWriteMemory)) { MessageBox(NULL, _T("Sorry, Launchy seems to have crashed. To help us work out what went wrong, crash dumps have been created in your temp directory. Please send them to us via the SourceForge forums."), m_appName, MB_OK | MB_ICONEXCLAMATION); result = EXCEPTION_EXECUTE_HANDLER; } return result; }
LONG WINAPI GPTUnhandledExceptionFilter(PEXCEPTION_POINTERS pExceptionInfo) { //得到当前时间 INFO_LOG("Core dump."); SYSTEMTIME st; ::GetLocalTime(&st); std::string strPath; eSDKTool::getCurrentPath(strPath); const int PATH_LENGTH = 2048; char szFileName[PATH_LENGTH]={0}; (void)sprintf_s(szFileName,PATH_LENGTH-1,("%s\\core-%04d%02d%02d-%02d%02d-%02d-%02d.dmp"),strPath.c_str(), st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds); CreateMiniDump(pExceptionInfo, szFileName); //std::cerr << "unknown error:" << (*pExceptionInfo->ExceptionRecord) << std::endl; if(NULL != pExceptionInfo) { if(NULL != pExceptionInfo->ExceptionRecord) { exit((int)(pExceptionInfo->ExceptionRecord->ExceptionCode)); } else { exit(0); } } else { exit(0); } }
/******************************************************** parseFieldCodes -- parse IIS and others field codes #Fields: time c-ip cs-method cs-uri-stem sc-status ********************************************************/ void parseFieldCodes(applSettings *SettingsPtr,char *buf) { char *ptr=buf; int i,status; try { //Ignore first '#Field' status=sscanf_s(ptr,"%s",&(SettingsPtr->fieldCodes[0][0]),sizeof(SettingsPtr->fieldCodes[0])); if (status!=1) { //failed SettingsPtr->fieldCodes[0][0]='\0'; return; } ptr+=strlen(SettingsPtr->fieldCodes[0])+1; for(i=0;i<32;i++) { status=sscanf_s(ptr,"%s",&(SettingsPtr->fieldCodes[i][0]),sizeof(SettingsPtr->fieldCodes[i])); if (status!=1) { SettingsPtr->fieldCodes[i][0]='\0'; break; } if (SettingsPtr->fieldCodes[i]=="s-sitename") SettingsPtr->fieldCodeProcessIsPresent=true; ptr+=strlen(SettingsPtr->fieldCodes[i])+1; } if (i>0) { DEBUGAPPLPARSE(Informational,"Identified %d field codes in application log for %s.",i,SettingsPtr->ApplicationName); } } catch (...) { logger(Error,"Exception in Application parsings parseFieldCodes. Application logging of %s cannot continue due to exception. The line being parsed:%s",SettingsPtr->ApplicationName,buf); CreateMiniDump(NULL); AfxEndThread(0,true); } }
// This method collects required crash files (minidump, screenshot etc.) // and then sends the error report over the Internet. void CErrorReportSender::DoWorkAssync() { m_Assync.Reset(); if(m_Action&COLLECT_CRASH_INFO) { m_Assync.SetProgress(_T("Start collecting information about the crash..."), 0, false); // First take a screenshot of user's desktop (if needed). TakeDesktopScreenshot(); if(m_Assync.IsCancelled()) { m_Assync.SetProgress(_T("[exit_silently]"), 0, false); return; } // Create crash dump. CreateMiniDump(); if(m_Assync.IsCancelled()) { m_Assync.SetProgress(_T("[exit_silently]"), 0, false); return; } // Notify the parent process that we have finished with minidump, // so the parent process is able to unblock and terminate itself. CString sEventName; sEventName.Format(_T("Local\\CrashRptEvent_%s"), g_CrashInfo.m_sCrashGUID); HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, sEventName); if(hEvent!=NULL) SetEvent(hEvent); // Copy user-provided files. CollectCrashFiles(); if(m_Assync.IsCancelled()) { m_Assync.SetProgress(_T("[exit_silently]"), 0, false); return; } m_Assync.SetProgress(_T("[confirm_send_report]"), 100, false); } if(m_Action&COMPRESS_REPORT) { // Compress error report files CompressReportFiles(); } if(m_Action&SEND_REPORT) { // Send the error report. SendReport(); } // Done return; }
long WINAPI top_level_exception_filter(_EXCEPTION_POINTERS *exceptioninfo) { CreateMiniDump(exceptioninfo); logger(Error,"Exception! Top level exception handler called. Writing dump file and rethrowing exception!"); return EXCEPTION_CONTINUE_SEARCH; //We did not handle the problem. //return EXCEPTION_CONTINUE_EXECUTION means we handled the problem. }
void myfilterWorker(PEXCEPTION_POINTERS exc_ptr, bool notify) { TCHAR path[MAX_PATH]; SYSTEMTIME st; HANDLE hDumpFile = NULL; GetLocalTime(&st); CreateDirectoryTree(CrashLogFolder); __try { if (dtsubfldr) { mir_sntprintf(path, MAX_PATH, TEXT("%s\\%02d.%02d.%02d"), CrashLogFolder, st.wYear, st.wMonth, st.wDay); CreateDirectory(path, NULL); mir_sntprintf(path, MAX_PATH, TEXT("%s\\%02d.%02d.%02d\\crash%02d%02d%02d%02d%02d%02d.mdmp"), CrashLogFolder, st.wYear, st.wMonth, st.wDay, st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); } else mir_sntprintf(path, MAX_PATH, TEXT("%s\\crash%02d%02d%02d%02d%02d%02d.mdmp"), CrashLogFolder, st.wYear, st.wMonth, st.wDay, st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); hDumpFile = CreateFile(path, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (hDumpFile != INVALID_HANDLE_VALUE) CreateMiniDump(hDumpFile, exc_ptr); else if (GetLastError() != ERROR_ALREADY_EXISTS) MessageBox(NULL, TranslateT("Crash Report write location is inaccesible"), TEXT("Miranda Crash Dumper"), MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_TOPMOST); } __except(EXCEPTION_EXECUTE_HANDLER) {} bool empty = GetFileSize(hDumpFile, NULL) == 0; CloseHandle(hDumpFile); if (empty) DeleteFile(path); __try { if (dtsubfldr) { mir_sntprintf(path, MAX_PATH, TEXT("%s\\%02d.%02d.%02d"), CrashLogFolder, st.wYear, st.wMonth, st.wDay); CreateDirectory(path, NULL); mir_sntprintf(path, MAX_PATH, TEXT("%s\\%02d.%02d.%02d\\crash%02d%02d%02d%02d%02d%02d.txt"), CrashLogFolder, st.wYear, st.wMonth, st.wDay, st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); } else mir_sntprintf(path, MAX_PATH, TEXT("%s\\crash%02d%02d%02d%02d%02d%02d.txt"), CrashLogFolder, st.wYear, st.wMonth, st.wDay, st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); hDumpFile = CreateFile(path, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); mir_sntprintf(path, MAX_PATH, TranslateT("Miranda crashed. Crash report stored in the folder:\n %s\n\n Would you like store it in the clipboard as well?"), CrashLogFolder); if (hDumpFile != INVALID_HANDLE_VALUE) CreateCrashReport(hDumpFile, exc_ptr, notify ? path : NULL); } __except(myDebugFilter(GetExceptionCode(), GetExceptionInformation())) {} bool empty1 = GetFileSize(hDumpFile, NULL) == 0; CloseHandle(hDumpFile); if (empty1) DeleteFile(path); }
int malloc_fail_handler(size_t amountwanted) { #ifndef _DEBUG CreateMiniDump(NULL); #endif free(printfworkingspace); sprintf(tempmsg,"Out of memory: failed to allocate %ld bytes (at PP=%d)",amountwanted, our_eip); quit(tempmsg); return 0; }
// Structured exception handler LONG WINAPI CCrashHandler::SehHandler(PEXCEPTION_POINTERS pExceptionPtrs) { // Write minidump file CreateMiniDump(pExceptionPtrs); // Terminate process TerminateProcess(GetCurrentProcess(), 1); // Unreacheable code return EXCEPTION_EXECUTE_HANDLER; }
// CRT SIGSEGV signal handler void CCrashHandler::SigsegvHandler(int) { // Invalid storage access (SIGSEGV) PEXCEPTION_POINTERS pExceptionPtrs = (PEXCEPTION_POINTERS)_pxcptinfoptrs; // Write minidump file CreateMiniDump(pExceptionPtrs); // Terminate process TerminateProcess(GetCurrentProcess(), 1); }
// CRT SIGFPE signal handler void CCrashHandler::SigfpeHandler(int /*code*/, int subcode) { // Floating point exception (SIGFPE) EXCEPTION_POINTERS* pExceptionPtrs = (PEXCEPTION_POINTERS)_pxcptinfoptrs; // Write minidump file CreateMiniDump(pExceptionPtrs); // Terminate process TerminateProcess(GetCurrentProcess(), 1); }
// CRT unexpected() call handler void __cdecl CCrashHandler::UnexpectedHandler() { // Unexpected error (unexpected() function was called) // Retrieve exception information EXCEPTION_POINTERS* pExceptionPtrs = NULL; GetExceptionPointers(0, &pExceptionPtrs); // Write minidump file CreateMiniDump(pExceptionPtrs); // Terminate process TerminateProcess(GetCurrentProcess(), 1); }
// CRT sigill signal handler void CCrashHandler::SigillHandler(int) { // Illegal instruction (SIGILL) // Retrieve exception information EXCEPTION_POINTERS* pExceptionPtrs = NULL; GetExceptionPointers(0, &pExceptionPtrs); // Write minidump file CreateMiniDump(pExceptionPtrs); // Terminate process TerminateProcess(GetCurrentProcess(), 1); }
// CRT SIGABRT signal handler void CCrashHandler::SigabrtHandler(int) { // Caught SIGABRT C++ signal // Retrieve exception information EXCEPTION_POINTERS* pExceptionPtrs = NULL; GetExceptionPointers(0, &pExceptionPtrs); // Write minidump file CreateMiniDump(pExceptionPtrs); // Terminate process TerminateProcess(GetCurrentProcess(), 1); }
// CRT Pure virtual method call handler void __cdecl CCrashHandler::PureCallHandler() { // Pure virtual function call // Retrieve exception information EXCEPTION_POINTERS* pExceptionPtrs = NULL; GetExceptionPointers(0, &pExceptionPtrs); // Write minidump file CreateMiniDump(pExceptionPtrs); // Terminate process TerminateProcess(GetCurrentProcess(), 1); }
// CRT SIGTERM signal handler void CCrashHandler::SigtermHandler(int) { // Termination request (SIGTERM) // Retrieve exception information EXCEPTION_POINTERS* pExceptionPtrs = NULL; GetExceptionPointers(0, &pExceptionPtrs); // Write minidump file CreateMiniDump(pExceptionPtrs); // Terminate process TerminateProcess(GetCurrentProcess(), 1); }
// CRT new operator fault handler int __cdecl CCrashHandler::NewHandler(size_t) { // 'new' operator memory allocation exception // Retrieve exception information EXCEPTION_POINTERS* pExceptionPtrs = NULL; GetExceptionPointers(0, &pExceptionPtrs); // Write minidump file CreateMiniDump(pExceptionPtrs); // Terminate process TerminateProcess(GetCurrentProcess(), 1); // Unreacheable code return 0; }
bool testUnicode(char *filename) { char a,b; FILE *test=NULL; try { test= _wfsopen(T2W(filename),T2W("rb"), _SH_DENYNO); if(test==NULL ){ logger(Error,"Failed to open input file %s to inspect unicode status. Error code %d. Assuming non unicode. Problem with log file access?",filename, errno); return false; } a=getc(test); //NOT getwc! b=getc(test); // Empty file produces -1 and -1 (EOF twice) if ((a==-1)&(b==-2)) { //actually 0xFF 0xFE //is unicode fclose(test); test=0; DEBUGAPPLPARSE(Informational,"Log file %s is in unicode format.",filename); return true; } else { fclose(test); test=0; DEBUGAPPLPARSE(Informational,"Log file %s is not unicode format.",filename); return false; } } catch(SE_Exception e) { logger(Error,"SEH Exception in testUnicode for log file %s. Assuming non unicode log file. Error code %u.",filename,e.getSeNumber()); } catch(...) { CreateMiniDump(NULL); logger(Error, "Exception when detecting unicode status on log file %s. Dump file written.",filename); if (test!=NULL) fclose(test); } return false; }
// CRT invalid parameter handler void __cdecl CCrashHandler::InvalidParameterHandler( const wchar_t* expression, const wchar_t* function, const wchar_t* file, unsigned int line, uintptr_t pReserved) { pReserved; // Invalid parameter exception // Retrieve exception information EXCEPTION_POINTERS* pExceptionPtrs = NULL; GetExceptionPointers(0, &pExceptionPtrs); // Write minidump file CreateMiniDump(pExceptionPtrs); // Terminate process TerminateProcess(GetCurrentProcess(), 1); }
int __stdcall WinMain(HINSTANCE instance, HINSTANCE prev_instance, LPSTR cmdLine, int show) { int result = 0; #if !defined(_DEBUG) __try #endif { g_tos = (char *) &result; g_instance = instance; _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_LEAK_CHECK_DF); result = main(__argc, __argv); } #if !defined(_DEBUG) __except (CreateMiniDump(GetExceptionInformation()), EXCEPTION_EXECUTE_HANDLER) { result = -1; } #endif return result; }
static LONG WINAPI GPTUnhandledExceptionFilter(PEXCEPTION_POINTERS pExceptionInfo) { CreateMiniDump(pExceptionInfo); exit(pExceptionInfo->ExceptionRecord->ExceptionCode); return EXCEPTION_EXECUTE_HANDLER; }
/*********************************************************************** * parseMessage * * return 1 for success, 0 for fail ************************************************************************/ int parseMessage(unsigned char* input,unsigned char* output,applSettings *loggerInformation) { // vanligt indata: 2004-09-03 02:48:27.25 spid3 Server name is '2000SERVER'. [SQL server] // vanligt indata: #Fields: date time c-ip cs-username s-ip s-port cs-method cs-uri-stem cs-uri-query sc-status cs(User-Agent) // vanligt indata: 2004-08-25 23:14:14 192.168.0.69 - 192.168.0.70 80 HEAD /iuident.cab 0408260814 404 Industry+Update+Control // vanligt indata: 23:14:14 2004-08-25 192.168.0.69 - 192.168.0.70 80 HEAD /iuident.cab 0408260814 404 Industry+Update+Control // facit: <82>Sep 18 13:57:42 192.168.0.12 SyslogGen This is a test CString date,time,host,UserID,facilityString,SeverityString="I",ServerIP,Process,nonMatchingFields,ClientIP,SeverityFullString; bool dateFound,timeFound,FoundSeverity,ClientIPFound,FoundServerName,FoundServerIP,FoundUserID,FoundProcess,FoundWin32Severity,hostFound; unsigned char field[32][1024],tempStr[1024]; int charsParsed,i,nbrOfFields=0,status,EventId=0; CTime DaTime= CTime::GetCurrentTime(); int facilityAndSeverityValue=loggerInformation->Facility*8+6; //information output[0]='\0'; unsigned char* startpos=input, *endpos=input+strlen((char*)input); dateFound=timeFound=FoundSeverity=ClientIPFound=hostFound=FoundServerIP=FoundServerName=FoundUserID=FoundProcess=FoundWin32Severity=false; try { DEBUGAPPLPARSE(Informational,"Appl line to parse:[%s]",input); //prepare host if (!loggerInformation->ParseHost) { hostFound=true; host=applHostName; FoundServerIP=true; FoundServerName=true; } else { hostFound=false; } //prepare severity if (!loggerInformation->ParseSeverity) { FoundSeverity=true; facilityAndSeverityValue=loggerInformation->Facility*8+loggerInformation->SeverityLevel; //severity SeverityString="I"; if (loggerInformation->SeverityLevel<6) SeverityString="W"; if (loggerInformation->SeverityLevel<4) SeverityString="E"; } else { FoundSeverity=false; } //prepare process if (!loggerInformation->ParseProcess) { FoundProcess=true; Process=loggerInformation->ProcessName; } else { FoundProcess=false; } //parse Date, time if (loggerInformation->ParseDate==false) { date=DaTime.Format("%b %d"); time=DaTime.Format("%H:%M:%S"); dateFound=true; timeFound=true; } //Read line into field[] do { status=sscanf_s((char*)input, "%1023s",(char*)&tempStr,sizeof(tempStr)); //misses multiple spaces... if (status<1) break; strncpy_s((char*)&field[nbrOfFields],sizeof(field[nbrOfFields]),(char*)&tempStr,sizeof(field[0])); input+=strlen((char*)&field[nbrOfFields])+1; while ((unsigned int)*input==32) { strncat_s((char*)&field[nbrOfFields],sizeof(field[nbrOfFields]),(char*)" ",sizeof(" ")); input++; } nbrOfFields++; } while((input<endpos)&(nbrOfFields<31)); if ((*startpos)=='#') { //Headerline in file. If so, skip field identification and assignment. i=nbrOfFields; nonMatchingFields.Append((char*)startpos); } else { i=0; } //Not used ClientIPFound=FoundUserID=true; //Go through all fieldCodes - fill matches with data charsParsed=0; for (i;i<nbrOfFields;i++) { if (loggerInformation->fieldCodes[i][0]!='\0') { //Fields has been identified if((!dateFound)&&(strcmp("date",(char*)&(loggerInformation->fieldCodes[i][0]))==0)) { identifyDate(&(field[i][0]),&date); dateFound=true; continue; } else if((!timeFound)&&(strcmp("time",(char*)&(loggerInformation->fieldCodes[i][0]))==0)) { identifyTime(&(field[i][0]),&time); timeFound=true; continue; } else if((!ClientIPFound)&&(strcmp("c-ip",(char*)&(loggerInformation->fieldCodes[i][0]))==0)) { ClientIP=field[i]; ClientIPFound=true; continue; } else if((!FoundServerName)&&(strcmp("s-computername",(char*)&(loggerInformation->fieldCodes[i][0]))==0)) { FoundServerName=true; if (loggerInformation->ParseHost) { //Syslog use. Ignores if hostFounf was true! Trust the s-computername hostFound=true; host=field[i]; } continue; } else if((!FoundServerIP)&&(strcmp("s-ip",(char*)&(loggerInformation->fieldCodes[i][0]))==0)) { ServerIP=field[i]; FoundServerIP=true; if ((loggerInformation->ParseHost)&(hostFound==false)) { //Syslog use hostFound=true; host=field[i]; } continue; } else if((!FoundUserID)&&(strcmp("cs-username",(char*)&(loggerInformation->fieldCodes[i][0]))==0)) { UserID=field[i]; FoundUserID=true; continue; } else if((!FoundProcess)&&(strcmp("s-sitename",(char*)&(loggerInformation->fieldCodes[i][0]))==0)) { Process=field[i]; FoundProcess=true; continue; } //For severity, two fields are interesting! else if((!FoundWin32Severity)&&(loggerInformation->ParseSeverity)&&(strcmp("sc-win32-status",(char*)&(loggerInformation->fieldCodes[i][0]))==0)) { sscanf_s((char*)&(field[i][0]),"%d",&status); if (status!=0) { SeverityString="E"; facilityAndSeverityValue=loggerInformation->Facility*8+3; //Error } FoundWin32Severity=true; nonMatchingFields.Append((char*)&(field[i][0])); nonMatchingFields.Append(" "); continue; } else if(strcmp("sc-status",(char*)&(loggerInformation->fieldCodes[i][0]))==0) { //sscanf(field[i],"%d",&status); EventId=atoi((char*)&(field[i][0])); if ((!FoundSeverity)&(loggerInformation->ParseSeverity)) if ((field[i][0]>'3')) { SeverityString="E"; facilityAndSeverityValue=loggerInformation->Facility*8+3; //Error } FoundSeverity=true; nonMatchingFields.Append((char*)&(field[i][0])); nonMatchingFields.Append(" "); continue; } } //end if fieldcodes if ((!dateFound)&&(identifyDate(&(field[i][0]),&date))) { dateFound=true; continue; } if ((!timeFound)&&(identifyTime(&(field[i][0]),&time))) { timeFound=true; continue; } if ((!hostFound)&&(identifyHost(&(field[i][0]),&host))) { hostFound=true; continue; } //fieldCodeProcessIsPresent: shows if a valid process info will show up - don't parse first best name if ((!FoundProcess)&&(!loggerInformation->fieldCodeProcessIsPresent)&&(identifyProcess(&(field[i][0]),&Process))) { FoundProcess=true; continue; } //no match nonMatchingFields.Append((char*)&(field[i][0])); nonMatchingFields.Append(" "); } //Should parse, but nothing found if (dateFound==false) { date=DaTime.Format("%b %d"); loggerInformation->failedToParseDate=true; } if (timeFound==false) { time=DaTime.Format("%H:%M:%S"); loggerInformation->failedToParseTime=true; } if (FoundSeverity==false) { facilityAndSeverityValue=loggerInformation->Facility*8+6; //Information loggerInformation->failedToParseSeverity=true; } if (SeverityString=="E") SeverityFullString="error"; else if (SeverityString=="W") SeverityFullString="warning"; else SeverityFullString="info"; if (host=="") { loggerInformation->failedToParseHost=true; host=applHostName; } if (FoundProcess==false) { loggerInformation->failedToParseProcess=true; Process="Unknown"; } //just stoppat in [info] under, för att få parsern i Syslogservern att förstå mellanslag i processnamnet.... Bättre lösning? //sprintf((char*)output,"<%d>%s %s %s %s[%s] %s%s",facilityAndSeverityValue,date.GetBuffer(),time.GetBuffer(),host.GetBuffer(),process.GetBuffer(),SeverityFullString.GetBuffer(),nonMatchingFields.GetBuffer(),(char*)(input+charsParsed)); _snprintf_s((char*)output,1024,_TRUNCATE,"<%d>%s %s %s %s[%s] %s",facilityAndSeverityValue,date.GetBuffer(),time.GetBuffer(),host.GetBuffer(),Process.GetBuffer(),SeverityFullString.GetBuffer(),nonMatchingFields.GetBuffer()); output[1022]=(char)10; //Force cr if full buffert was filled output[1023]=(char)0; if (output[1021]==(char)10) { //Special case output[1023]=(char)0; } DEBUGAPPLPARSE(Informational,"Appl parse done:[%s]",output); } catch(SE_Exception e) { logger(Informational,"SEH Exception in parsing application log. Error code %u. The line was not inserted. Application logging continues. The line not inserted:%s",e.getSeNumber(),(char*)input); CreateMiniDump(NULL); Sleep(1000); return 0; } catch (...) { logger(Informational,"Exception in parsing application log. The line was not inserted. Application logging continues. The line not inserted:%s",(char*)input); CreateMiniDump(NULL); Sleep(1000); return 0; } return 1; }
/*--------------------------[ eventlog_read_events ]-------------------------- * Read messages from the event log * * Returns: * success (0) * error (-1) *----------------------------------------------------------------------------*/ int eventlog_read_events(eventlog_data* eventlog, uint32 *lastrun,uint32 *thisrun){ //char buffer[EVENTLOG_BUFFER_LEN]; uint32 bytes; uint32 next; // EVENTLOGRECORD *record = (EVENTLOGRECORD *)eventBuffer; HANDLE hLog; int status; DWORD recordCounter=1; //used to indicate where to read next from eventlog. It does *not* neccessarily mean that post is to be added;eventlog->Recordoffset takes care of that. DWORD startPos; ntsl_event *event; char *source; char *computer; char *strings; struct tm _time,*time; bool ThisIsInitialLoop=true; __try { time=&_time; LabelForResettedEventLog: if ( (lastrun == NULL) || (thisrun == NULL) || (service_halting()) ) return(-1); if ((hLog = OpenEventLog(NULL, eventlog->name)) == NULL) { //ntsl_log_error(NTSL_ERROR_EVENT_LOG_ACCESS, eventlog->name); DEBUGSERVICE(Message,"Failed to open event log %s. Error: %s", eventlog->name,GetLastError()); return(-1); } DEBUGPARSE(Header,"Reading %s event log starting at offset %u.", eventlog->name,eventlog->recordOffset); //find start position if (eventlog->recordOffset==0) { startPos=FindFirstReadPos(eventlog->name,*lastrun); if (startPos==0) { //no help status=ernoReadEventLog(hLog, EVENTLOG_FORWARDS_READ | EVENTLOG_SEQUENTIAL_READ,0, &bytes, &next); } else { status=ernoReadEventLog(hLog, EVENTLOG_FORWARDS_READ | EVENTLOG_SEEK_READ,startPos, &bytes, &next); } if ((status==0)&& (GetLastError() != ERROR_INSUFFICIENT_BUFFER)) { //totally empty eventlog, or error; eject CloseEventLog(hLog); return(0); } eventlog->recordOffset=record->RecordNumber; eventlog->verificationTime=record->TimeGenerated; recordCounter=eventlog->recordOffset; } else { recordCounter=max(eventlog->recordOffset,0); //-1 so that a valid entry is read unless the enventlog has been wiped. } //big loop while ((status=ernoReadEventLog(hLog, EVENTLOG_FORWARDS_READ | EVENTLOG_SEEK_READ,recordCounter, &bytes, &next))){ DEBUGPARSE(Message,"Read %u bytes at position %u with return status %d.",bytes,recordCounter, status); if ((ThisIsInitialLoop)&&(eventlog->verificationTime!=record->TimeGenerated)) { //same id as before, but new time! Start from scratch since eventlog has been rotated/deleted DEBUGPARSE(Message,"Verification time mismatch! EventLog cleared? starting from the beginning."); eventlog->recordOffset=0; ThisIsInitialLoop=false; CloseEventLog(hLog); goto LabelForResettedEventLog; //erno only solution to a complete rewrite...(?) } ThisIsInitialLoop=false; //Read successful, hence set to false for the future if (service_halting()) return(-1); while (bytes > 0) { /* If this event happened between the last time we ran, and the current time, and it is one we are interested in, then fill in an ntsl_event structure, and pass it to the engine to log. */ //If match with registry list of filtered event id's, ignore. //record->EventID &=0x0000FFFF; Dum, dum idé. Utan unika, högre delarena blir matchningen mellan id och dll'ens id inte unika--> problem. if ( (record->TimeWritten >= (uint32)*lastrun) && (record->TimeWritten < (uint32)*thisrun) && (eventlog_check_event(eventlog, record->EventType)) && (thisEventIsFilteredOut(record->EventID)==false)) { source = (LPSTR) ((LPBYTE) record + sizeof(EVENTLOGRECORD)); computer = source + strlen(source) + 1; strings = (LPSTR) ((LPBYTE) record + record->StringOffset); __time64_t _TimeGenerated=record->TimeGenerated; localtime_s(time,&_TimeGenerated); //DEBUGPARSE(Message,"Nasta startposition %u. Record %u adderades. lastrun: %u thisrun: %u TimeWritten: %u",eventlog->recordOffset,record->RecordNumber,(uint32)*lastrun,(uint32)*thisrun,record->TimeWritten); if ( (event = (ntsl_event*)malloc0(sizeof(ntsl_event))) == NULL){ ntsl_log_error(NTSL_ERROR_EVENT_MALLOC); return(-1); } event->msg[0] = 0; //erno2005 strcpy_s(event->facilityName,sizeof(event->facilityName),eventlog->name); event->time1970format=record->TimeGenerated; strftime(event->date, NTSL_DATE_LEN, "%b %d %H:%M:%S", time); if (event->date[4] == '0') // Unix style formatting event->date[4] = ' '; strcpy_s(event->host, eventlog_lcase(computer)); strcpy_s(event->source, eventlog_lcase(source)); eventlog_set_event_type(event, record->EventType); eventlog_set_event_priority(event, record->EventType, eventlog); eventlog_set_event_msg(event, eventlog->name, record->EventID, strings, record->NumStrings); eventlog_set_user(event, ((LPBYTE) record + record->UserSidOffset), record->UserSidLength); DEBUGPARSE(Message,"Sending parsed record %u to output: %s",record->RecordNumber, event->msg); engine_process_event(event); event = NULL; } else { //DEBUGPARSE(Message,"Next start position %u. Record %u ignored. lastrun: %u thisrun: %u TimeWritten: %u",eventlog->recordOffset,record->RecordNumber,(uint32)*lastrun,(uint32)*thisrun,record->TimeWritten); } bytes -= record->Length; //DEBUGPARSE(Message,"Bytes remaining in buffer to read is %u.",bytes); if (record->TimeWritten < (uint32)*thisrun) { eventlog->recordOffset=record->RecordNumber; eventlog->verificationTime=record->TimeGenerated; } record = (EVENTLOGRECORD *) ((LPBYTE) record + record->Length); recordCounter++; } //End loop parse received messages in buffer DEBUGPARSE(EndHeader,""); //record = (EVENTLOGRECORD *)eventBuffer; } //end big while loop if ((status==0)&&(ThisIsInitialLoop)) { //this only happens if an entry has been removed, i.e. deleted from eventLog. Start from scratch. DEBUGPARSE(Message,"Id not found! EventLog cleared? starting from the beginning."); eventlog->recordOffset=0; ThisIsInitialLoop=false; CloseEventLog(hLog); goto LabelForResettedEventLog; //erno only solution to a complete rewrite...(?) } } __except( CreateMiniDump( GetExceptionInformation() ), EXCEPTION_EXECUTE_HANDLER ) { logger(Error,"Exception when reading events from %s! Will reattempt reading. Current or previous event text is:%s", eventlog->name, event->msg); Sleep(3000); }
// This method collects required crash report files (minidump, screenshot etc.) // and then sends the error report over the Internet. BOOL CErrorReportExporter::DoWork(int Action) { // Reset the completion event m_Assync.Reset(); if(Action&COLLECT_CRASH_INFO) // Collect crash report files { // Add a message to log m_Assync.SetProgress(_T("Start collecting information about the crash..."), 0, false); // First take a screenshot of user's desktop (if needed). TakeDesktopScreenshot(); if(m_Assync.IsCancelled()) // Check if user-cancelled { // Parent process can now terminate UnblockParentProcess(); // Add a message to log m_Assync.SetProgress(_T("[exit_silently]"), 0, false); return FALSE; } // Create crash dump. CreateMiniDump(); // Create StackWalker Info. CreateStackWalkerInfo(); //+ if(m_Assync.IsCancelled()) // Check if user-cancelled { // Parent process can now terminate UnblockParentProcess(); // Add a message to log m_Assync.SetProgress(_T("[exit_silently]"), 0, false); return FALSE; } // Notify the parent process that we have finished with minidump, // so the parent process is able to unblock and terminate itself. UnblockParentProcess(); // Copy user-provided files. CollectCrashFiles(); if(m_Assync.IsCancelled()) // Check if user-cancelled { // Add a message to log m_Assync.SetProgress(_T("[exit_silently]"), 0, false); return FALSE; } if(m_Assync.IsCancelled()) // Check if user-cancelled { // Add a message to log m_Assync.SetProgress(_T("[exit_silently]"), 0, false); return FALSE; } // Create crash description XML CreateCrashDescriptionXML(*m_CrashInfo.GetReport(0)); // Add a message to log m_Assync.SetProgress(_T("[confirm_send_report]"), 100, false); } if(Action&RESTART_APP) // We need to restart the parent process { // Restart the application RestartApp(); } if(Action&COMPRESS_REPORT) // We have to compress error report file into ZIP archive { // Compress error report files BOOL bCompress = CompressReportFiles(m_CrashInfo.GetReport(m_nCurReport)); if(!bCompress) { // Add a message to log m_Assync.SetProgress(_T("[status_failed]"), 100, false); return FALSE; // Error compressing files } } // Done return TRUE; }
static void ProcessException( EXCEPTION_POINTERS* pExceptionPtrs ) { int rc; UINT uiMBFlags = 0 | MB_SYSTEMMODAL | MB_TOPMOST | MB_SETFOREGROUND ; HWND hwndMBOwner = FindConsoleHandle(); if (!hwndMBOwner || !IsWindowVisible(hwndMBOwner)) hwndMBOwner = GetDesktopWindow(); if ( !g_pfnMiniDumpWriteDumpFunc ) { MsgBox ( hwndMBOwner, _T("The creation of a crash dump for analysis by the Hercules ") _T("development team is NOT possible\nbecause the required 'DbgHelp.dll' ") _T("is missing or is not installed or was otherwise not located.") ,_T("OOPS! Hercules has crashed!"), uiMBFlags | MB_ICONERROR | MB_OK ,0 // (default/neutral language) ,(15 * 1000) // (timeout == 15 seconds) ); return; } if ( IDYES == ( rc = MsgBox ( hwndMBOwner, _T("The creation of a crash dump for further analysis by ") _T("the Hercules development team is strongly suggested.\n\n") _T("Would you like to create a crash dump for ") _T("the Hercules development team to analyze?") ,_T("OOPS! Hercules has crashed!"), uiMBFlags | MB_ICONERROR | MB_YESNO ,0 // (default/neutral language) ,(10 * 1000) // (timeout == 10 seconds) )) || MB_TIMEDOUT == rc ) { if ( CreateMiniDump( pExceptionPtrs ) && MB_TIMEDOUT != rc ) { MsgBox ( hwndMBOwner, _T("Please send the dump to the Hercules development team for analysis.") ,_T("Dump Complete"), uiMBFlags | MB_ICONEXCLAMATION | MB_OK ,0 // (default/neutral language) ,(5 * 1000) // (timeout == 5 seconds) ); } } }
LONG __stdcall MyCustomFilter( EXCEPTION_POINTERS* pep ) { CreateMiniDump( pep ); return EXCEPTION_EXECUTE_HANDLER; }
//Called by _set_se_translator void trans_func( unsigned int u, EXCEPTION_POINTERS* pExp ) { logger(Error, "SEH Exception, caught in trans_func by _set_se_translator. writing dump file and rethrowing exception."); CreateMiniDump(pExp); throw SE_Exception(u); }