void CThreadQueue::run() { if(__rhoCurrentCategory.getName() == "NO_LOGGING") m_logThreadId = getThreadID(); LOG(INFO) + "Starting main routine..."; int nLastPollInterval = getLastPollInterval(); while( !isStopping() ) { unsigned int nWait = m_nPollInterval > 0 ? m_nPollInterval : QUEUE_POLL_INTERVAL_INFINITE; if ( m_nPollInterval > 0 && nLastPollInterval > 0 ) { int nWait2 = m_nPollInterval - nLastPollInterval; if ( nWait2 <= 0 ) nWait = QUEUE_STARTUP_INTERVAL_SECONDS; else nWait = nWait2; } if ( !m_bNoThreaded && !isStopping() && isNoCommands() ) { LOG(INFO) + "ThreadQueue blocked for " + nWait + " seconds..."; if ( wait(nWait*1000) == 1 ) onTimeout(); } nLastPollInterval = 0; if ( !m_bNoThreaded && !isStopping() ) processCommands(); } LOG(INFO) + "Thread shutdown"; }
bool SignalHandler::assignEvent(EventRecord &ev) { assert(eventlock->depth()); bool can_assign = false; // after we get the lock, the handler thread should be either idle, or waiting // for some event. if (idle()) { can_assign = true; } else if (waitingForCallback() && ev.type == evtShutDown) { can_assign = true; } if (can_assign) { signal_printf("%s[%d]: assigning event to handler %s\n", FILE__, __LINE__, getThreadStr(getThreadID())); events_to_handle.push_back(ev); waitLock->_Lock(FILE__, __LINE__); if (waitingForWakeup_) { waitLock->_Broadcast(FILE__, __LINE__); } waitLock->_Unlock(FILE__, __LINE__); return true; } // Otherwise we already assigned an event but the SH hasn't run yet. return false; }
bool SignalHandler::waitingForCallback() { // Processing... well, if we're waiting on a callback, then we're not processing. // Previously we set wait_flag inside the call to waitForEvent, but that was called // after this was checked. Whoopsie. return (wait_cb != NULL); #if 0 CallbackBase *cb = getMailbox()->runningInsideCallback(); signal_printf("%s[%d]: running inside callback: %p... \n", FILE__, __LINE__, cb); if (cb == NULL) return false; if (wait_cb == cb) { signal_printf("%s[%d]: signal handler %s waiting on callback\n", FILE__, __LINE__, getThreadStr(getThreadID())); return true; } else { signal_printf("%s[%d]: running inside callback %p different from stored %p, odd case\n", FILE__, __LINE__, cb, wait_cb); } return false; #endif }
void foo(unsigned int N, int *x) { unsigned int i = getThreadID(); if(i < N) x[i] = i; }
//Start the time measurement of a specific kernel void elapsd::startTimer(const int KernelID, const int DeviceID) { t_elapsd_id elapsd_id = getElapsdID( (uint32_t)(getThreadID() - getThreadGroupID()), (uint16_t)KernelID, (uint16_t)DeviceID ); //Retrieve a relative ID #pragma omp critical { if (thr_map.find(elapsd_id) == thr_map.end()) { thr_map[elapsd_id] = id_relative; id_relative++; } } uint64_t id = thr_map[elapsd_id]; if (id > max_units) { throw std::runtime_error("Thread overflow."); } DMSG("TMR START K: " << getElapsdKernelID(elapsd_id) << " D: " << getElapsdDeviceID(elapsd_id) << " T: " << getElapsdThreadID(elapsd_id) << " EID: " << std::hex << elapsd_id << std::dec << " ID: " << id); data[id].push_back(elapsdData()); data[id].back().startAllTimers(); };
/* This method performs the actual injection. It gets an appropriate thread id, loads the dll, gets the address of the inject method, then calls SetWindowsHookEx. */ int processInject(int pid) { DWORD processID = (DWORD)pid; TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>"); HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID); if (NULL != hProcess) { HMODULE hMod; DWORD cbNeeded; if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), &cbNeeded) ) { GetModuleBaseName( hProcess, hMod, szProcessName, sizeof(szProcessName)/sizeof(TCHAR) ); } } _tprintf( TEXT("Injecting into process %s PID: %u\n"), szProcessName, processID); DWORD threadID = getThreadID(processID); printf( "Using Thread ID %u\n", threadID); if(threadID == (DWORD)0) { puts("Cannot find thread"); return -1; } HMODULE dll = LoadLibrary("inject.dll"); if(dll == NULL) { puts("Cannot find DLL"); return -1; } HOOKPROC addr = (HOOKPROC)GetProcAddress(dll, "Test"); if(addr == NULL) { puts("Cannot find the function"); return -1; } //Uses the threadID from getThreadID to inject into specific process //HHOOK handle = SetWindowsHookEx(WH_MOUSE, addr, dll, threadID); HHOOK handle = SetWindowsHookEx(WH_KEYBOARD, addr, dll, threadID); if(handle == NULL) { puts("Couldn't hook the keyboard"); } getchar(); getchar(); getchar(); UnhookWindowsHookEx(handle); return 0; }
bool SignalHandler::processing() { signal_printf("%s[%d]: checking whether processing for SH %s: idle_flag %d, waiting for callback %d, wait_flag %d\n", FILE__, __LINE__, getThreadStr(getThreadID()), idle(), waitingForCallback(), wait_flag); if (idle()) return false; if (waitingForCallback()) return false; if (wait_flag) return false; return true; }
void System::getProcessInfo(PsInfo* dest) { uint32_t tid = getThreadID(); syscall_set_ps_dump(); PsInfo buf; while (syscall_read_ps_dump(&buf) == M_OK) { if (buf.tid == tid) { // Don't break here, which causes kernel memory leak. *dest = buf; } } return; }
double elapsd::getLastWallTime(const int KernelID, const int DeviceID) const { t_elapsd_id elapsd_id = getElapsdID( (uint32_t)(getThreadID() - getThreadGroupID()), (uint16_t)KernelID, (uint16_t)DeviceID ); thr_map_type::const_iterator it = thr_map.find(elapsd_id); if (it == thr_map.end()) { throw std::runtime_error("Could not find ID in thr_map."); } uint64_t id = it->second; return (&(data[id].back()))->timestamp.getTimeDifference(); }
TCB createNewTCB() { TCB newTCB = (TCB)malloc(sizeof(struct ThreadNodes)); if(newTCB == NULL) { free(newTCB); return NULL; } else { newTCB->threadContext.uc_stack.ss_sp = malloc(STACKSIZE); if(newTCB->threadContext.uc_stack.ss_sp == NULL) { free(newTCB); return NULL; } else { newTCB->threadContext.uc_stack.ss_size = STACKSIZE; newTCB->threadContext.uc_stack.ss_flags = 0; newTCB->nextThread = NULL; newTCB->threadContext.uc_link = 0; newTCB->threadCompleted = 0; newTCB->waitingThread = NULL; newTCB->threadBlocked = 0; newTCB->threadsWaiting = 0; newTCB->roundRobin = 0; newTCB->sort = 0; newTCB->initialTicket = 0; newTCB->finalTicket = 0; newTCB->warningLevel = 0; newTCB->ultimateWarningLevel = 0; newTCB->limitTime = 0; newTCB->detach = 0; newTCB->startQuantum = 0; newTCB->threadID = getThreadID(); return newTCB; } } }
//Stop the time measurement and save the measured time void elapsd::stopTimer(const int KernelID, const int DeviceID) { t_elapsd_id elapsd_id = getElapsdID( (uint32_t)(getThreadID() - getThreadGroupID()), (uint16_t)KernelID, (uint16_t)DeviceID ); uint64_t id = thr_map[elapsd_id]; DMSG("TMR STOP K: " << getElapsdKernelID(elapsd_id) << " D: " << getElapsdDeviceID(elapsd_id) << " T: " << getElapsdThreadID(elapsd_id) << " EID: " << std::hex << elapsd_id << std::dec << " ID: " << id); elapsdData *edata = &(data[id].back()); edata->stopAllTimers(); edata->KernelID = getElapsdKernelID(elapsd_id); edata->DeviceID = getElapsdDeviceID(elapsd_id); edata->ThreadID = getElapsdThreadID(elapsd_id); }
float ofxTimeMeasurements::stopMeasuring(const string & ID, bool accumulate){ if (!enabled) return 0.0f; float ret = 0.0f; string localID = ID; uint64_t timeNow = TM_GET_MICROS(); //get the time before the lock() to avoid affecting ThreadId thread = getThreadID(); bool bIsMainThread = isMainThread(thread); mutex.lock(); unordered_map<ThreadId, ThreadInfo>::iterator threadIt = threadInfo.find(thread); if(threadIt == threadInfo.end()){ //thread not found! mutex.unlock(); return 0.0f; } ThreadInfo & tinfo = threadIt->second; if(tinfo.order > 0){ localID = "T" + ofToString(tinfo.order) + ":" + localID; } core::tree<string> & tr = tinfo.tree; //easier to read, tr is our tree from now on core::tree<string>::iterator & tit = tinfo.tit; if (tit.out() != tr.end()){ tit = tit.out(); }else{ ofLogError("ofxTimeMeasurements") << "tree climbing too high up! (" << localID << ")"; } unordered_map<string,TimeMeasurement*>::iterator it; it = times.find(localID); if ( it == times.end() ){ //not found! ofLogWarning("ofxTimeMeasurements") << "ID ("<< localID << ")not found at stopMeasuring(). Make sure you called startMeasuring with that ID first."; }else{ TimeMeasurement* t = it->second; if ( t->measuring ){ t->measuring = false; t->thread = thread; t->error = false; t->acrossFrames = (bIsMainThread && t->frame != currentFrameNum); //we only care about across-frames in main thread t->microsecondsStop = timeNow; ret = t->duration = timeNow - t->microsecondsStart; if (!freeze) { if (!averaging) { t->avgDuration = t->duration; } else { t->avgDuration = (1.0f - timeAveragePercent) * t->avgDuration + t->duration * timeAveragePercent; } } if (accumulate && !freeze){ t->microsecondsAccum += t->avgDuration; } }else{ //wrong use, start first, then stop t->error = true; ofLogWarning("ofxTimeMeasurements") << "Can't stopMeasuring(" << localID << "). Make sure you called startMeasuring() with that ID first."; } } mutex.unlock(); if(internalBenchmark){ wastedTimeThisFrame += TM_GET_MICROS() - timeNow; } return ret / 1000.0f; //convert to ms }
ofxTimeMeasurements::ofxTimeMeasurements(){ currentFrameNum = 0; uiScale = 1.0; desiredFrameRate = 60.0f; //assume 60 enabled = true; timeAveragePercent = 0.02; averaging = false; msPrecision = 1; maxW = 27; drawAuto = true; internalBenchmark = false; #if defined(USE_OFX_FONTSTASH) useFontStash = false; #endif #if defined(USE_OFX_HISTORYPLOT) plotHeight = 60; numAllocatdPlots = 0; plotBaseY = 0; plotResolution = 1; maxPlotSamples = 4096; numActivePlots = 0; allPlotsTogether = true; #endif mainThreadID = getThreadID(); bgColor = ofColor(0); hilightColor = ofColor(44,77,255) * 1.5; disabledTextColor = ofColor(255,0,128); measuringColor = ofColor(0,130,0); frozenColor = hilightColor * 1.5; dimColorA = 40; freeze = false; idleTimeColorFadePercent = 0.5; idleTimeColorDecay = 0.96; deadThreadExtendedLifeDecSpeed = 0.975; longestLabel = 0; selection = TIME_MEASUREMENTS_UPDATE_KEY; drawLocation = TIME_MEASUREMENTS_BOTTOM_RIGHT; numVisible = 0; enableKey = TIME_MEASUREMENTS_GLOBAL_TOGGLE_KEY; activateKey = TIME_MEASUREMENTS_INTERACT_KEY; toggleSampleKey = TIME_MEASUREMENTS_TOGGLE_SAMPLE_KEY; menuActive = false; drawLines.reserve(50); int numHues = 7; float brightness = 190.0f; for (int i = 0; i < numHues; i++) { float hue = fmod( i * (255.0f / float(numHues)), 255.0f); ofColor c = ofColor::fromHsb(hue, 255.0f, brightness, 255.0f); threadColorTable.push_back(c); } numThreads = 0; configsDir = "."; removeExpiredThreads = true; removeExpiredTimings = false; settingsLoaded = false; drawPercentageAsGraph = true; charW = 8; //ofBitmap font char w charH = TIME_MEASUREMENTS_LINE_HEIGHT; //used for internal benchmark ('B') wastedTimeThisFrame = wastedTimeAvg = 0; wastedTimeDrawingThisFrame = wastedTimeDrawingAvg = 0; addEventHooks(); }
bool PythonScript::executeImpl() { TemporaryValue holder(m_threadID, getThreadID()); return executeString(); }
DWORD demoSuspendInjectResume64(PCWSTR pszLibFile, DWORD dwProcessId) { void *stub; unsigned long threadID, oldprot; HANDLE hThread; CONTEXT ctx; DWORD64 stubLen = sizeof(sc); wprintf(TEXT("[+] Shellcode Length is: %d\n"), stubLen); HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessId); if (hProcess == NULL) { wprintf(L"[-] Error: Could not open process for PID (%d).\n", dwProcessId); return(1); } DWORD64 LoadLibraryAddress = (DWORD64)GetProcAddress(GetModuleHandle(L"kernel32.dll"), "LoadLibraryW"); if (LoadLibraryAddress == NULL) { wprintf(L"[-] Error: Could not find LoadLibraryA function inside kernel32.dll library.\n"); exit(1); } SIZE_T dwSize = (wcslen(pszLibFile) + 1) * sizeof(wchar_t); LPVOID lpDllAddr = VirtualAllocEx(hProcess, NULL, dwSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (lpDllAddr == NULL) { wprintf(L"[-] Error: Could not allocate memory inside PID (%d).\n", dwProcessId); exit(1); } stub = VirtualAllocEx(hProcess, NULL, stubLen, MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (stub == NULL) { wprintf(L"[-] Error: Could not allocate memory for stub.\n"); exit(1); } SIZE_T nBytesWritten = 0; BOOL bStatus = WriteProcessMemory(hProcess, lpDllAddr, pszLibFile, dwSize, &nBytesWritten); if (bStatus == 0) { wprintf(L"[-] Error: Could not write any bytes into the PID (%d) address space.\n", dwProcessId); return(1); } if (nBytesWritten != dwSize) wprintf(TEXT("[-] Something is wrong!\n")); threadID = getThreadID(dwProcessId); hThread = OpenThread((THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_SUSPEND_RESUME), false, threadID); if (hThread != NULL) { SuspendThread(hThread); } else wprintf(L"[-] Could not open thread\n"); ctx.ContextFlags = CONTEXT_CONTROL; GetThreadContext(hThread, &ctx); DWORD64 oldIP = ctx.Rip; ctx.Rip = (DWORD64)stub; ctx.ContextFlags = CONTEXT_CONTROL; memcpy(sc + 3, &oldIP, sizeof(oldIP)); memcpy(sc + 41, &lpDllAddr, sizeof(lpDllAddr)); memcpy(sc + 51, &LoadLibraryAddress, sizeof(LoadLibraryAddress)); #ifdef _DEBUG wprintf(TEXT("[+] Shellcode Launcher Code:\n\t")); for (int i = 0; i < stubLen; i++) wprintf(TEXT("%02x "), sc[i]); wprintf(TEXT("\n")); #endif WriteProcessMemory(hProcess, (void *)stub, &sc, stubLen, NULL); SetThreadContext(hThread, &ctx); ResumeThread(hThread); Sleep(8000); VirtualFreeEx(hProcess, lpDllAddr, dwSize, MEM_DECOMMIT); VirtualFreeEx(hProcess, stub, stubLen, MEM_DECOMMIT); CloseHandle(hProcess); CloseHandle(hThread); return(0); }
DWORD demoSuspendInjectResume(PCWSTR pszLibFile, DWORD dwProcessId) { void *stub; unsigned long threadID, oldIP, oldprot; HANDLE hThread; CONTEXT ctx; DWORD stubLen = sizeof(sc); HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessId); if (hProcess == NULL) { wprintf(L"[-] Error: Could not open process for PID (%d).\n", dwProcessId); return(1); } DWORD LoadLibraryAddress = (DWORD)GetProcAddress(GetModuleHandle(L"kernel32.dll"), "LoadLibraryW"); if (LoadLibraryAddress == NULL) { wprintf(L"[-] Error: Could not find LoadLibraryA function inside kernel32.dll library.\n"); exit(1); } SIZE_T dwSize = (wcslen(pszLibFile) + 1) * sizeof(wchar_t); LPVOID lpDllAddr = VirtualAllocEx(hProcess, NULL, dwSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (lpDllAddr == NULL) { wprintf(L"[-] Error: Could not allocate memory inside PID (%d).\n", dwProcessId); exit(1); } stub = VirtualAllocEx(hProcess, NULL, stubLen, MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (stub == NULL) { wprintf(L"[-] Error: Could not allocate memory for stub.\n"); exit(1); } BOOL bStatus = WriteProcessMemory(hProcess, lpDllAddr, pszLibFile, dwSize, NULL); if (bStatus == 0) { wprintf(L"[-] Error: Could not write any bytes into the PID (%d) address space.\n", dwProcessId); return(1); } threadID = getThreadID(dwProcessId); hThread = OpenThread((THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_SUSPEND_RESUME), false, threadID); if (hThread != NULL) { SuspendThread(hThread); } else printf("could not open thread\n"); ctx.ContextFlags = CONTEXT_CONTROL; GetThreadContext(hThread, &ctx); oldIP = ctx.Eip; ctx.Eip = (DWORD)stub; ctx.ContextFlags = CONTEXT_CONTROL; VirtualProtect(sc, stubLen, PAGE_EXECUTE_READWRITE, &oldprot); memcpy((void *)((unsigned long)sc + 1), &oldIP, 4); memcpy((void *)((unsigned long)sc + 8), &lpDllAddr, 4); memcpy((void *)((unsigned long)sc + 13), &LoadLibraryAddress, 4); WriteProcessMemory(hProcess, stub, sc, stubLen, NULL); SetThreadContext(hThread, &ctx); ResumeThread(hThread); Sleep(8000); VirtualFreeEx(hProcess, lpDllAddr, dwSize, MEM_DECOMMIT); VirtualFreeEx(hProcess, stub, stubLen, MEM_DECOMMIT); CloseHandle(hProcess); CloseHandle(hThread); return(0); }
bool ofxTimeMeasurements::startMeasuring(const string & ID, bool accumulate, bool ifClause){ string localID = ID; if (!enabled) return true; uint64_t wastedTime; if(internalBenchmark){ wastedTime = TM_GET_MICROS(); } if (!settingsLoaded){ loadSettings(); settingsLoaded = true; } string threadName = "Thread"; ThreadId thread = getThreadID(); bool bIsMainThread = isMainThread(thread); if(!bIsMainThread){ if(Poco::Thread::current()){ threadName = Poco::Thread::current()->getName(); } } mutex.lock(); unordered_map<ThreadId, ThreadInfo>::iterator threadIt = threadInfo.find(thread); ThreadInfo * tinfo = NULL; core::tree<string> *tr = NULL; bool newThread = threadIt == threadInfo.end(); if (newThread){ //new thread! //cout << "NewThread! " << ID << " " << &thread << endl; threadInfo[thread] = ThreadInfo(); tinfo = &threadInfo[thread]; tr = &tinfo->tree; //easier to read, tr is our tree from now on if (!bIsMainThread){ tinfo->color = threadColorTable[numThreads%(threadColorTable.size())]; numThreads++; }else{ //main thread tinfo->color = hilightColor; } tinfo->order = numThreads; string tName = bIsMainThread ? "Main Thread" : ("T" + ofToString(tinfo->order) + ": " + threadName); //init the iterator *tr = tName; //thread name is root tinfo->tit = (core::tree<string>::iterator)*tr; }else{ tinfo = &threadIt->second; tr = &(tinfo->tree); //easier to read, tr is our tree from now on } if(tinfo->order > 0){ localID = "T" + ofToString(tinfo->order) + ":" + localID; } //see if we had an actual measurement, or its a new one unordered_map<string, TimeMeasurement*>::iterator tit = times.find(localID); TimeMeasurement* t; if(tit == times.end()){ //if it wasnt in the tree, append it times[localID] = t = new TimeMeasurement(); unordered_map<string, TimeMeasurementSettings>::iterator it2 = settings.find(localID); if (it2 != settings.end()){ t->settings = settings[localID]; if(tinfo->tit.out() == tinfo->tit.end()){ //if we are the tree root - we cant be hidden! t->settings.visible = true; } } tinfo->tit = tinfo->tit.push_back(localID); }else{ core::tree<string>::iterator temptit = tr->tree_find_depth(localID); if(temptit != tr->end()){ tinfo->tit = temptit; }else{ //cout << "gotcha!" << endl; //this is the rare case where we already had a measurement for this ID, //but it must be assigned to another old thread bc we cant find it! //so we re-add that ID for this thread and update the tree iterator tinfo->tit = tinfo->tit.push_back(localID); } t = tit->second; } t->key = localID; t->life = 1.0f; // t->measuring = true; t->ifClause = ifClause; t->microsecondsStop = 0; t->accumulating = accumulate; if(accumulate) t->numAccumulations++; t->error = false; t->frame = currentFrameNum; t->updatedLastFrame = true; t->microsecondsStart = TM_GET_MICROS(); t->thread = thread; mutex.unlock(); if(internalBenchmark){ wastedTimeThisFrame += t->microsecondsStart - wastedTime; } return t->settings.enabled; }