コード例 #1
0
ファイル: datetime.hpp プロジェクト: Firebie/FarManager
inline uint64_t GetCurrentUTCTimeInUI64()
{
	FILETIME Timestamp;
	GetSystemTimeAsFileTime(&Timestamp); // in UTC
	return FileTimeToUI64(Timestamp);
}
コード例 #2
0
int NaClGetTimeOfDayIntern(struct nacl_abi_timeval *tv,
                           struct NaClTimeState    *ntsp) {
  FILETIME  ft_now;
  DWORD     ms_counter_now;
  uint64_t  t_ms;
  DWORD     ms_counter_at_ft_now;
  uint32_t  ms_counter_diff;
  uint64_t  unix_time_ms;

  GetSystemTimeAsFileTime(&ft_now);
  ms_counter_now = timeGetTime();
  t_ms = NaClFileTimeToMs(&ft_now);

  NaClMutexLock(&ntsp->mu);

  NaClLog(5, "ms_counter_now       %"NACL_PRIu32"\n",
          (uint32_t) ms_counter_now);
  NaClLog(5, "t_ms                 %"NACL_PRId64"\n", t_ms);
  NaClLog(5, "system_time_start_ms %"NACL_PRIu64"\n",
          ntsp->system_time_start_ms);

  ms_counter_at_ft_now = (DWORD)
      (ntsp->ms_counter_start +
       (uint32_t) (t_ms - ntsp->system_time_start_ms));

  NaClLog(5, "ms_counter_at_ft_now %"NACL_PRIu32"\n",
          (uint32_t) ms_counter_at_ft_now);

  ms_counter_diff = ms_counter_now - (uint32_t) ms_counter_at_ft_now;

  NaClLog(5, "ms_counter_diff      %"NACL_PRIu32"\n", ms_counter_diff);

  if (ms_counter_diff <= kMaxMillsecondDriftBeforeRecalibration) {
    t_ms = t_ms + ms_counter_diff;
  } else {
    NaClCalibrateWindowsClockMu(ntsp);
    t_ms = ntsp->system_time_start_ms;
  }

  NaClLog(5, "adjusted t_ms =      %"NACL_PRIu64"\n", t_ms);

  unix_time_ms = t_ms - ntsp->epoch_start_ms;

  /*
   * Time is monotonically non-decreasing.
   */
  if (unix_time_ms < ntsp->last_reported_time_ms) {
    unix_time_ms = ntsp->last_reported_time_ms;
  } else {
    ntsp->last_reported_time_ms = unix_time_ms;
  }

  NaClMutexUnlock(&ntsp->mu);

  NaClLog(5, "unix_time_ms  =      %"NACL_PRId64"\n", unix_time_ms);
  /*
   * Unix time is measured relative to a different epoch, Jan 1, 1970.
   * See the module initialization for epoch_start_ms.
   */

  tv->nacl_abi_tv_sec = (nacl_abi_time_t) (unix_time_ms / 1000);
  tv->nacl_abi_tv_usec = (nacl_abi_suseconds_t) ((unix_time_ms % 1000) * 1000);

  NaClLog(5, "nacl_avi_tv_sec =    %"NACL_PRIdNACL_TIME"\n",
          tv->nacl_abi_tv_sec);
  NaClLog(5, "nacl_avi_tv_usec =   %"NACL_PRId32"\n", tv->nacl_abi_tv_usec);

  return 0;
}
コード例 #3
0
ファイル: platform.c プロジェクト: tavianator/dimension
void
dmnsn_get_times(dmnsn_timer *timer)
{
#if DMNSN_GETRUSAGE
  struct timeval real;
  gettimeofday(&real, NULL);

  struct rusage usage;
  if (getrusage(RUSAGE_SELF, &usage) == 0) {
    timer->real   = dmnsn_timeval2double(real);
    timer->user   = dmnsn_timeval2double(usage.ru_utime);
    timer->system = dmnsn_timeval2double(usage.ru_stime);
  } else {
    dmnsn_warning("getrusage() failed.");
    timer->real = timer->user = timer->system = 0.0;
  }
#elif DMNSN_TIMES
  static long clk_tck = 0;

  // Figure out the clock ticks per second
  if (!clk_tck) {
    clk_tck = sysconf(_SC_CLK_TCK);
    if (clk_tck == -1) {
      dmnsn_warning("sysconf(_SC_CLK_TCK) failed.");
      clk_tck = 1000000L;
    }
  }

  struct tms buf;
  clock_t real = times(&buf);
  if (real == (clock_t)-1) {
    dmnsn_warning("times() failed.");
    timer->real = timer->user = timer->system = 0.0;
  } else {
    timer->real   = (double)real/clk_tck;
    timer->user   = (double)buf.tms_utime/clk_tck;
    timer->system = (double)buf.tms_stime/clk_tck;
  }
#elif defined(_WIN32)
  FILETIME real;
  GetSystemTimeAsFileTime(&real);

  FILETIME user, system, creation, exit;
  HANDLE current_process = GetCurrentProcess();
  if (GetProcessTimes(current_process,
                      &creation, &exit, &system, &user) != 0)
  {
    timer->real
      = (((uint64_t)real.dwHighDateTime << 32) + real.dwLowDateTime)/1.0e7;
    timer->user
      = (((uint64_t)user.dwHighDateTime << 32) + user.dwLowDateTime)/1.0e7;
    timer->system
      = (((uint64_t)system.dwHighDateTime << 32) + system.dwLowDateTime)/1.0e7;
  } else {
    dmnsn_warning("GetProcessTimes() failed.");
    timer->real = timer->user = timer->system = 0.0;
  }
#else
  timer->real = timer->user = timer->system = 0.0;
#endif
}
コード例 #4
0
#include "CommonUtility.h"
#include "INIReader.h"
#include <Knownfolders.h>
#include <Shlobj.h>
#include <Pathcch.h>
#include <sstream>

// Mandatory initialization of static class variable outside the header file.
static FILETIME local;
FILETIME EditRecordTimer::lastUpdatedTimeStamp = (GetSystemTimeAsFileTime(&local), local);
ManageWakaTimeConfigFile gConfigFileManager;
static const std::wstring pythoncmd = L"python.exe";
static const std::wstring WAKATIME_CONFIG_NAME(L".wakatime.cfg");

#include <Shlwapi.h>
bool ManageWakaTimeConfigFile::ReadWakaTimeConfigFile()
{
	// Read the wakatime.cfg file under users home directory if it exists.
	WCHAR* path;
	bool status = false;
	if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Profile, SHGFP_TYPE_CURRENT, 0, &path)))
	{
		WCHAR fullPath[MAX_PATH];
#pragma  warning(disable : 4995)
		if (SUCCEEDED(PathCombine(fullPath, path, WAKATIME_CONFIG_NAME.c_str())))
		{
			m_FileName = fullPath;
			status = true;
		}

		CoTaskMemFree(path);
コード例 #5
0
ファイル: main.c プロジェクト: devyn/wine
/***********************************************************************
 *		CertTrustFinalPolicy (CRYPTDLG.@)
 */
HRESULT WINAPI CertTrustFinalPolicy(CRYPT_PROVIDER_DATA *data)
{
    BOOL ret;
    DWORD err = S_OK;
    CERT_VERIFY_CERTIFICATE_TRUST *pCert = CRYPTDLG_GetVerifyData(data);

    TRACE("(%p)\n", data);

    if (data->pWintrustData->dwUIChoice != WTD_UI_NONE)
        FIXME("unimplemented for UI choice %d\n",
         data->pWintrustData->dwUIChoice);
    if (pCert)
    {
        DWORD flags = 0;
        CERT_CHAIN_PARA chainPara;
        HCERTCHAINENGINE engine;

        memset(&chainPara, 0, sizeof(chainPara));
        chainPara.cbSize = sizeof(chainPara);
        if (CRYPTDLG_CheckOnlineCRL())
            flags |= CERT_CHAIN_REVOCATION_CHECK_END_CERT;
        engine = CRYPTDLG_MakeEngine(pCert);
        GetSystemTimeAsFileTime(&data->sftSystemTime);
        ret = CRYPTDLG_IsCertAllowed(pCert->pccert);
        if (ret)
        {
            PCCERT_CHAIN_CONTEXT chain;

            ret = CertGetCertificateChain(engine, pCert->pccert,
             &data->sftSystemTime, NULL, &chainPara, flags, NULL, &chain);
            if (ret)
            {
                if (chain->cChain != 1)
                {
                    FIXME("unimplemented for more than 1 simple chain\n");
                    err = TRUST_E_SUBJECT_FORM_UNKNOWN;
                    ret = FALSE;
                }
                else if ((ret = CRYPTDLG_CopyChain(data, chain)))
                {
                    if (CertVerifyTimeValidity(&data->sftSystemTime,
                     pCert->pccert->pCertInfo))
                    {
                        ret = FALSE;
                        err = CERT_E_EXPIRED;
                    }
                }
                else
                    err = TRUST_E_SYSTEM_ERROR;
                CertFreeCertificateChain(chain);
            }
            else
                err = TRUST_E_SUBJECT_NOT_TRUSTED;
        }
        CertFreeCertificateChainEngine(engine);
    }
    else
    {
        ret = FALSE;
        err = TRUST_E_NOSIGNATURE;
    }
    /* Oddly, native doesn't set the error in the trust step error location,
     * probably because this action is more advisory than anything else.
     * Instead it stores it as the final error, but the function "succeeds" in
     * any case.
     */
    if (!ret)
        data->dwFinalError = err;
    TRACE("returning %d (%08x)\n", S_OK, data->dwFinalError);
    return S_OK;
}
コード例 #6
0
ファイル: docfile.cpp プロジェクト: maerson/windbg
BOOL

LoadFile(
    int doc
    )
{
    LPDOCREC d =&Docs[doc];
    char line[MAX_USER_LINE + 1];
    int offset; //Current offset of storage in block
    int lineLen;
    BYTE prevLength; //Previous line size
    HCURSOR hSaveCursor;
    WORD res;
    WORD nbLines = 0;

    //
    // Documents are now always read only. Because WinDbg is no longer and IDE, it
    // is strictly a debugger now.
    //

    hFileDoc = CreateFile(d->szFileName, GENERIC_READ, FILE_SHARE_READ, 
        NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

    if (INVALID_HANDLE_VALUE == hFileDoc) {
        ErrorBox( ERR_File_Open, (LPSTR)d->szFileName );
        return FALSE;
    }

    d->readOnly = TRUE;

    //Store file date

    if (!GetFileTimeByName( d->szFileName, NULL, NULL, &d->time ) ) {
        GetSystemTimeAsFileTime(&d->time);
    }

    if ((pszBufferDoc = DocAlloc(DISK_BLOCK_SIZE)) == NULL) {
        ErrorBox(SYS_Allocate_Memory);
        goto error1;
    }

    //Alloc first block

    if (!AllocateBlock(NULL, NULL, &d->FirstBlock)) {
        return FALSE;
    }

    //If we are in reload mode, and a message box shows up, a repaint
    //of the document being loaded is done, so force number of lines
    //to a value != 0

    d->NbLines = MAX_LINE_NUMBER;

    d->LastBlock = d->FirstBlock;
    dwBytesReadDoc = DISK_BLOCK_SIZE;
    dwOffsetDoc = DISK_BLOCK_SIZE;
    offset = 0;
    prevLength = 0;

    //Set the Hour glass cursor

    hSaveCursor = SetCursor (LoadCursor(NULL, IDC_WAIT));

    //Read file line after line

    res = LoadLine(line, &lineLen, nbLines);
    while (res == END_OF_LINE) {

        //Truncate a file too large

        if (nbLines >= MAX_LINE_NUMBER - 1) {
            ErrorBox(ERR_Truncate_Doc);
            res = END_OF_FILE;
            break;
        }

        if (!StoreLine(line, lineLen, &offset, &prevLength, &d->LastBlock)) {
            res = END_ABORT;
            break;
        }

        res = LoadLine(line, &lineLen, ++nbLines);
    }

    //Take decisions

    switch (res) {

      case END_OF_FILE:

        //Store last line

        if (StoreLine(line, lineLen, &offset, &prevLength, &d->LastBlock)) {

            nbLines++;

            //Free memory

            if (!DocFree(pszBufferDoc))
                  InternalErrorBox(SYS_Free_Memory);

            //Restore cursor

            SetCursor(hSaveCursor);

            CloseHandle(hFileDoc);
            d->NbLines = nbLines;
            return TRUE;
        } else
              goto abort;

      case ERR_File_Read:
      case ERR_Not_A_Text_File:
        ErrorBox(res, (LPSTR)d->szFileName);
        //Fall through

      case END_ABORT:
        {
            LPBLOCKDEF pB;

          abort:
            while (TRUE) {

                pB = (d->LastBlock)->PrevBlock;
                if (!DocFree((LPSTR)d->LastBlock))
                      InternalErrorBox(SYS_Free_Memory);
                d->LastBlock = pB;
                if (pB == NULL)
                      break;
            }
            SetCursor(hSaveCursor);
            break;
        }

      default:
        Assert(FALSE);
        break;
    }

    //Restore cursor

    SetCursor(hSaveCursor);

    if (!DocFree(pszBufferDoc))
          InternalErrorBox(SYS_Free_Memory);

  error1: {
        CloseHandle(hFileDoc);
    }

    return FALSE;
}                                       /* LoadFile() */
コード例 #7
0
ファイル: cookie.cpp プロジェクト: seledka/syslib
    static void Cookie_Parse(HTTP_SESSION_HANDLE *lpSession,WCHAR *lpCookieDomain,WCHAR *lpCookiePath,WCHAR *lpCookieName,WCHAR *lpData)
    {
        WCHAR *lpPtr=lpData,
              *lpPorts=NULL;

        DWORD dwCookieFlags=0,
              dwFlags=0,
              dwPortsCount=0;

        FILETIME ftExpiry={0};
        while (true)
        {
            if (!(lpPtr=StrChrW(lpPtr,L';')))
                break;

            *lpPtr++=0;

            while ((*lpPtr) && (*lpPtr == L' '))
                lpPtr++;

            if (IsKnownParam(dcrW_c7ed8bb1("domain"),6))
            {
                lpPtr=GetCookieParamValuePtr(lpPtr);
                lpCookieDomain=lpPtr;
            }
            else if (IsKnownParam(dcrW_1ab74e01("path"),4))
            {
                lpPtr=GetCookieParamValuePtr(lpPtr);
                lpCookiePath=lpPtr;
            }
            else if (IsKnownParam(dcrW_a3df71ef("expires"),7))
            {
                lpPtr=GetCookieParamValuePtr(lpPtr);
                if ((!(dwCookieFlags & COOKIE_FLAG_EXPIRES_SET)) && (!(dwFlags & COOKIE_HANDLER_MAXAGE_SET)))
                {
                    SYSTEMTIME st;
                    if (InternetTimeToSystemTimeW(lpPtr,&st,0))
                    {
                        dwCookieFlags|=COOKIE_FLAG_EXPIRES_SET;
                        SystemTimeToFileTime(&st,&ftExpiry);
                        FILETIME tm;
                        GetSystemTimeAsFileTime(&tm);

                        if (CompareFileTime(&tm,&ftExpiry) > 0)
                            dwFlags|=COOKIE_HANDLER_EXPIRED;
                    }
                }
            }
            else if (IsKnownParam(dcrW_77b02e79("secure"),6))
            {
                lpPtr=GetCookieParamValuePtr(lpPtr);
                dwCookieFlags|=COOKIE_FLAG_SECURE;
            }
            else if (IsKnownParam(dcrW_60249e06("discard"),7))
            {
                lpPtr=GetCookieParamValuePtr(lpPtr);
                dwCookieFlags|=COOKIE_FLAG_DISCARD;
            }
            else if (IsKnownParam(dcrW_53e691c9("max-age"),7))
            {
                lpPtr=GetCookieParamValuePtr(lpPtr);
                GetSystemTimeAsFileTime(&ftExpiry);

                /**
                    MSDN:
                    It is not recommended that you add and subtract values from the FILETIME structure to obtain relative times.
                    Instead, you should copy the low- and high-order parts of the file time to a LARGE_INTEGER structure, perform
                    64-bit arithmetic on the QuadPart member, and copy the LowPart and HighPart members into the FILETIME structure.

                    Do not cast a pointer to a FILETIME structure to either a LARGE_INTEGER* or __int64* value because it can cause
                    alignment faults on 64-bit Windows.
                **/

                LARGE_INTEGER liTime={ftExpiry.dwLowDateTime,ftExpiry.dwHighDateTime};
                liTime.QuadPart+=StrToIntW(lpPtr)*_100NS_IN_SEC;
                ftExpiry.dwLowDateTime=liTime.LowPart;
                ftExpiry.dwHighDateTime=liTime.HighPart;

                dwFlags|=COOKIE_HANDLER_MAXAGE_SET;
                dwCookieFlags|=COOKIE_FLAG_EXPIRES_SET;
            }
            else if (IsKnownParam(dcrW_f98fd7e9("port"),4))
            {
                lpPtr=GetCookieParamValuePtr(lpPtr);
                do
                {
                    if (dwCookieFlags & COOKIE_FLAG_PORT_SET)
                        break;

                    if (*lpPtr != L'"')
                        break;

                    WCHAR *lpPortsStart=lpPtr+1,
                          *lpPortsEnd=StrChrW(lpPortsStart,L'"');

                    if (!lpPortsEnd)
                        break;

                    dwPortsCount=1;
                    WCHAR *lpCurPort=lpPortsStart;
                    while (true)
                    {
                        lpCurPort=StrChrW(lpCurPort,L',');
                        if (!lpCurPort)
                            break;

                        if (lpCurPort > lpPortsEnd)
                            break;

                        dwPortsCount++;
                        lpCurPort++;
                    }

                    lpPorts=lpPortsStart;
                    dwCookieFlags|=COOKIE_FLAG_PORT_SET;
                }
                while (false);
            }
        }

        do
        {
            COOKIE_DOMAIN *lpDomain=Cookie_FindDomain(lpSession,lpCookieDomain,lpCookiePath,false,NULL);
            if ((!lpDomain) && (!(dwFlags & COOKIE_HANDLER_EXPIRED)))
                lpDomain=Cookie_AddDomain(lpSession,lpCookieDomain,lpCookiePath);

            if (!lpDomain)
                break;

            COOKIE *lpCookie=Cookie_Find(lpDomain,lpCookieName);
            if (lpCookie)
                Cookie_Delete(lpCookie,(!(dwFlags & COOKIE_HANDLER_EXPIRED)));

            if (!(dwFlags & COOKIE_HANDLER_EXPIRED))
            {
                COOKIE *lpCookie=Cookie_Add(lpDomain,lpCookieName,lpData);
                if (!lpCookie)
                    break;

                lpCookie->ftExpiry=ftExpiry;
                lpCookie->dwCookieFlags=dwCookieFlags;

                if (dwCookieFlags & COOKIE_FLAG_PORT_SET)
                {
                    lpCookie->lpPortsList=(WORD*)MemQuickAlloc(dwPortsCount*sizeof(WORD));
                    if (lpCookie->lpPortsList)
                    {
                        lpCookie->dwPortsCount&=~COOKIE_FLAG_PORT_SET;
                        break;
                    }

                    lpCookie->dwPortsCount=dwPortsCount;

                    WCHAR *lpCurPort=lpPorts;
                    for (DWORD i=0; i < dwPortsCount; i++)
                    {
                        lpCookie->lpPortsList[i]=StrToIntW(lpCurPort);

                        lpCurPort=StrChrW(lpCurPort,L',');
                        lpCurPort++;
                    }
                }
            }
        }
        while (false);
        return;
    }
コード例 #8
0
ファイル: keystore.c プロジェクト: 0x00dec0de/GMbot
//
//	Adds a new pressed key information into the key store.
//
WINERROR KeyStoreAdd(
	PKEY_INFO	pKeyInfo
	)
{
	WINERROR		Status = ERROR_NOT_ENOUGH_MEMORY;
	ULONG			KeyHandle;
	PKEY_CONTEXT	Ctx;
	BOOL            bDeref = FALSE;

	KeyHandle = Crc32((PCHAR)&pKeyInfo->Client, sizeof(CLIENT_INFO));
	
	if (Ctx = GetContext(KeyHandle))
	{
		bDeref = Ctx->bDirty;		
		if (Ctx->bDirty == FALSE) // just created
		{
			// Context has just been created, initializing
			HANDLE	hProcess;

			// Resolving process path
			if (hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pKeyInfo->Client.ProcessId))
			{
				GetModuleFileNameExW(hProcess, NULL, (LPWSTR)&Ctx->ProcessPath, MAX_PATH);
				CloseHandle(hProcess);
			}

			Ctx->bActive = TRUE;

			// Saving current date and time
			GetSystemTimeAsFileTime(&Ctx->Time);
			
			// Resolving parent window text
			GetWindowTextW(pKeyInfo->Client.ParentWindow, (LPWSTR)&Ctx->WindowText, MAX_WINDOW_TEXT);
		}	// if (Ctx->bDirty == FALSE) // just created

		Ctx->bDirty = TRUE;

		if (Ctx->bActive)
		{
			if (pKeyInfo->wChar && Ctx->Count < MAX_KEY_BUFFER_SIZE)
			{
				if (pKeyInfo->wChar == VK_BACK)
				{
					if (Ctx->Count)
						Ctx->Count -= 1;
				}
				else
				{
					Ctx->KeyBuffer[Ctx->Count] = pKeyInfo->wChar;
					Ctx->Count += 1;
					DbgPrint("KEYLOG: Adding key to a buffer: 0x%x, %C\n", pKeyInfo->wChar, pKeyInfo->wChar);
				}
				Status = NO_ERROR;
			}	// if (Ctx->Count < MAX_KEY_BUFFER_SIZE)
			else
				Status = ERROR_BUFFER_OVERFLOW;

			if ( pKeyInfo->clipboard )
			{
				PCLIPBOARD_ENTRY Entry = (PCLIPBOARD_ENTRY)AppAlloc( sizeof(CLIPBOARD_ENTRY) );
				if ( Entry )
				{
					// Saving current date and time
					GetSystemTimeAsFileTime(&Entry->Time);
					Entry->Buffer = pKeyInfo->clipboard;
					pKeyInfo->clipboard = NULL; // we'll free it later
					InsertTailList(&Ctx->ClipboardChain,&Entry->qLink);
				}
			}	// if ( pKeyInfo->clipboard )
		}	// if (Ctx->bActive)

		if ( bDeref )
			// Context has been reused, dereferencing it
			ReleaseContext(Ctx);
	}	// if (Ctx = GetContext(KeyHandle))

	return(Status);
}
コード例 #9
0
ファイル: prmjtime.c プロジェクト: 84danielwhite/smartos-live
JSInt64
PRMJ_Now(void)
{
#ifdef XP_OS2
    JSInt64 s, us, ms2us, s2us;
    struct timeb b;
#endif
#ifdef XP_WIN
    JSInt64 s, us,
    win2un = JSLL_INIT(0x19DB1DE, 0xD53E8000),
    ten = JSLL_INIT(0, 10);
    FILETIME time, midnight;
#endif
#if defined(XP_UNIX) || defined(XP_BEOS)
    struct timeval tv;
    JSInt64 s, us, s2us;
#endif /* XP_UNIX */

#ifdef XP_OS2
    ftime(&b);
    JSLL_UI2L(ms2us, PRMJ_USEC_PER_MSEC);
    JSLL_UI2L(s2us, PRMJ_USEC_PER_SEC);
    JSLL_UI2L(s, b.time);
    JSLL_UI2L(us, b.millitm);
    JSLL_MUL(us, us, ms2us);
    JSLL_MUL(s, s, s2us);
    JSLL_ADD(s, s, us);
    return s;
#endif
#ifdef XP_WIN
    /* The windows epoch is around 1600. The unix epoch is around 1970.
       win2un is the difference (in windows time units which are 10 times
       more precise than the JS time unit) */
    GetSystemTimeAsFileTime(&time);
    /* Win9x gets confused at midnight
       http://support.microsoft.com/default.aspx?scid=KB;en-us;q224423
       So if the low part (precision <8mins) is 0 then we get the time
       again. */
    if (!time.dwLowDateTime) {
        GetSystemTimeAsFileTime(&midnight);
        time.dwHighDateTime = midnight.dwHighDateTime;
    }
    JSLL_UI2L(s, time.dwHighDateTime);
    JSLL_UI2L(us, time.dwLowDateTime);
    JSLL_SHL(s, s, 32);
    JSLL_ADD(s, s, us);
    JSLL_SUB(s, s, win2un);
    JSLL_DIV(s, s, ten);
    return s;
#endif

#if defined(XP_UNIX) || defined(XP_BEOS)
#ifdef _SVID_GETTOD   /* Defined only on Solaris, see Solaris <sys/types.h> */
    gettimeofday(&tv);
#else
    gettimeofday(&tv, 0);
#endif /* _SVID_GETTOD */
    JSLL_UI2L(s2us, PRMJ_USEC_PER_SEC);
    JSLL_UI2L(s, tv.tv_sec);
    JSLL_UI2L(us, tv.tv_usec);
    JSLL_MUL(s, s, s2us);
    JSLL_ADD(s, s, us);
    return s;
#endif /* XP_UNIX */
}
コード例 #10
0
ファイル: prog.c プロジェクト: tigros/HookTools
/* init_global_prog_store()
Initialize the global program store by storing command line arguments, OS version, etc.

This function must only be called from the main thread.
For now there is only one program store implemented and it's a global store (G->prog).
*/
void init_global_prog_store( 
	int argc,   // in
	char **argv   // in deref
)
{
	unsigned offsetof_cHandleEntries = 0;
	
	FAIL_IF( !G );   // The global store must exist.
	
	FAIL_IF( G->prog->init_time );   // Fail if this store has already been initialized.
	
	
	/* get_SharedInfo() or die.
	This function loads user32.dll and must be called before any other pointer to GUI related info 
	is initialized.
	*/
	G->prog->pSharedInfo = get_SharedInfo();
	
	
	G->prog->argc = argc;
	G->prog->argv = argv;
	
	/* point pszBasename to this program's basename */
	if( argc && argv[ 0 ][ 0 ] )
	{
		char *clip = NULL;
		
		clip = strrchr( argv[ 0 ], '\\' );
		if( clip )
			++clip;
		
		G->prog->pszBasename = ( clip && *clip ) ? clip : argv[ 0 ];
	}
	else
		G->prog->pszBasename = "<unknown>";
	
	
	/* main thread id */
	G->prog->dwMainThreadId = GetCurrentThreadId();
	
	/* operating system version and platform */
	G->prog->dwOSVersion = GetVersion();
	G->prog->dwOSMajorVersion = (BYTE)G->prog->dwOSVersion;
	G->prog->dwOSMinorVersion = (BYTE)( G->prog->dwOSVersion >> 8 );
	G->prog->dwOSBuild = 
		( G->prog->dwOSVersion < 0x80000000 ) ? ( G->prog->dwOSVersion >> 16 ) : 0;
	
	/* the name of this program's window station */
	if( !get_user_obj_name( &G->prog->pwszWinstaName, GetProcessWindowStation() ) )
	{
		MSG_FATAL_GLE( "get_user_obj_name() failed." );
		printf( "Failed to get this program's window station name.\n" );
		printf( "If you can reproduce this error contact [email protected]\n" );
		exit( 1 );
	}
	
	
	/* Determine the offset of cHandleEntries in SERVERINFO.
	In NT4 the offset is 4 but this program isn't for NT4 so ignore.
	In Win2k and XP the offset is 8.
	In Vista and Win7 the offset is 4.
	*/
	offsetof_cHandleEntries = ( G->prog->dwOSMajorVersion >= 6 ) ? 4 : 8;
	
	offsetof_cHandleEntries = 8;

	/* The first member of SHAREDINFO is pointer to SERVERINFO.
	Add offsetof_cHandleEntries to the SERVERINFO pointer to get the address of cHandleEntries.
	*/
	G->prog->pcHandleEntries = 
		(volatile DWORD *)( (char *)G->prog->pSharedInfo->psi + offsetof_cHandleEntries );
	
	
	/* G->prog has been initialized */
	GetSystemTimeAsFileTime( (FILETIME *)&G->prog->init_time );
	return;
}
コード例 #11
0
ファイル: StPlayList.cpp プロジェクト: KindDragon/sview
bool StPlayList::walkToNext(const bool theToForce) {
    StMutexAuto anAutoLock(myMutex);
    if(myCurrent == NULL
    || (myToLoopSingle && !theToForce)) {
        return false;
    } else if(myIsShuffle && myItemsCount >= 3) {
        StPlayItem* aPrev = myCurrent;
        if(!myStackNext.empty()) {
            myCurrent = myStackNext.front();
            myStackNext.pop_front();
        } else {
            if((myPlayedCount >= (myItemsCount - 1)) || (myPlayedCount == 0)) {
                // reset the playback counter
            #ifdef _WIN32
                FILETIME aTime;
                GetSystemTimeAsFileTime(&aTime);
                myRandGen.setSeed(aTime.dwLowDateTime);
            #else
                timeval aTime;
                gettimeofday(&aTime, NULL);
                myRandGen.setSeed(aTime.tv_usec);
            #endif
                myPlayedCount = 0;
                myCurrent->setPlayedFlag(!myCurrent->getPlayedFlag());
                ST_DEBUG_LOG("Restart the shuffle");
            }

            // determine next random position
            const size_t aCurrPos  = myCurrent->getPosition();
            bool         aCurrFlag = myCurrent->getPlayedFlag();
            StPlayItem*  aNextItem = myCurrent;
            const size_t aNextPos  = stMin(size_t(myRandGen.next() * myItemsCount), myItemsCount - 1);
            if(aNextPos > aCurrPos) {
                // forward direction
                for(size_t aNextDiff = aNextPos - aCurrPos; aNextItem != NULL && aNextDiff != 0; --aNextDiff) {
                    aNextItem = aNextItem->getNext();
                }
            } else {
                // backward direction
                for(size_t aNextDiff = aCurrPos - aNextPos; aNextItem != NULL && aNextDiff != 0; --aNextDiff) {
                    aNextItem = aNextItem->getPrev();
                }
            }
            if(aCurrFlag == aNextItem->getPlayedFlag()) {
                // find nearest position not yet played - prefer item farther from current one
                StPlayItem* aNextItem1 = aNextPos > aCurrPos ? aNextItem->getNext() : aNextItem->getPrev();
                StPlayItem* aNextItem2 = aNextPos > aCurrPos ? aNextItem->getPrev() : aNextItem->getNext();
                for(; aNextItem1 != NULL || aNextItem2 != NULL;) {
                    if(aNextItem1 != NULL) {
                        if(aCurrFlag != aNextItem1->getPlayedFlag()) {
                            aNextItem = aNextItem1;
                            break;
                        }
                        aNextItem1 = aNextPos > aCurrPos ? aNextItem1->getNext() : aNextItem1->getPrev();
                    }
                    if(aNextItem2 != NULL) {
                        if(aCurrFlag != aNextItem2->getPlayedFlag()) {
                            aNextItem = aNextItem2;
                            break;
                        }
                        aNextItem2 = aNextPos > aCurrPos ? aNextItem2->getPrev() : aNextItem2->getNext();
                    }
                }
                if(aCurrFlag == aNextItem->getPlayedFlag()) {
                    // something wrong!
                    ST_DEBUG_LOG("Disaster - next shuffle position not found!");
                    aCurrFlag     = !aCurrFlag;
                    myPlayedCount = 0;
                }
            }

            ST_DEBUG_LOG(aCurrPos + " -> " + aNextItem->getPosition());
            ++myPlayedCount;

            aNextItem->setPlayedFlag(aCurrFlag);
            myCurrent = aNextItem;
        }

        if(aPrev != myCurrent
        && aPrev != NULL) {
            myStackPrev.push_back(aPrev);
            if(myStackPrev.size() > THE_UNDO_LIMIT) {
                myStackPrev.pop_front();
            }
        }

        const size_t anItemId = myCurrent->getPosition();
        anAutoLock.unlock();
        signals.onPositionChange(anItemId);
        return true;
    } else if(myCurrent != myLast) {
        myCurrent = myCurrent->getNext();
        const size_t anItemId = myCurrent->getPosition();
        anAutoLock.unlock();
        signals.onPositionChange(anItemId);
        return true;
    } else if(myIsLoopFlag) {
        return walkToFirst();
    }
    return false;
}
コード例 #12
0
ファイル: skse64.cpp プロジェクト: kassent/SkyrimSouls-SE
void SKSE64_Initialize(void)
{
	if(isInit) return;
	isInit = true;

	gLog.OpenRelative(CSIDL_MYDOCUMENTS, "\\My Games\\Skyrim Special Edition\\SKSE\\skse64.log");

#ifndef _DEBUG
	__try {
#endif

		FILETIME	now;
		GetSystemTimeAsFileTime(&now);

		_MESSAGE("SKSE64 runtime: initialize (version = %d.%d.%d %08X %08X%08X, os = %s)",
			SKSE_VERSION_INTEGER, SKSE_VERSION_INTEGER_MINOR, SKSE_VERSION_INTEGER_BETA, RUNTIME_VERSION,
			now.dwHighDateTime, now.dwLowDateTime, GetOSInfoStr().c_str());

		_MESSAGE("imagebase = %016I64X", GetModuleHandle(NULL));
		_MESSAGE("reloc mgr imagebase = %016I64X", RelocationManager::s_baseAddr);

#ifdef _DEBUG
		SetPriorityClass(GetCurrentProcess(), IDLE_PRIORITY_CLASS);

		WaitForDebugger();
#endif

		if(!g_branchTrampoline.Create(1024 * 64))
		{
			_ERROR("couldn't create branch trampoline. this is fatal. skipping remainder of init process.");
			return;
		}

		if(!g_localTrampoline.Create(1024 * 64, g_moduleHandle))
		{
			_ERROR("couldn't create codegen buffer. this is fatal. skipping remainder of init process.");
			return;
		}

		// Add Hooks_XXX_Init calls here
		Hooks_Debug_Init();
		Hooks_ObScript_Init();
		Hooks_Papyrus_Init();
		Hooks_NetImmerse_Init();
		Hooks_Threads_Init();
		Hooks_Handlers_Init();

		g_pluginManager.Init();

		// Add Hooks_XXX_Commit calls here in the same order
		Hooks_Debug_Commit();
		Hooks_ObScript_Commit();
		Hooks_Papyrus_Commit();
		Hooks_UI_Commit();
		Hooks_Camera_Commit();
		Hooks_NetImmerse_Commit();
		Hooks_Threads_Commit();
		Hooks_Handlers_Commit();
		Hooks_Scaleform_Commit();
		Hooks_Gameplay_Commit();
		Hooks_Event_Commit();
		Hooks_SaveLoad_Commit();
		Hooks_Data_Commit();
		Init_CoreSerialization_Callbacks();
		Hooks_DirectInput_Commit();
		
		FlushInstructionCache(GetCurrentProcess(), NULL, 0);

#ifndef _DEBUG
	}
	__except(EXCEPTION_EXECUTE_HANDLER)
	{
		_ERROR("exception thrown during startup");
	}
#endif

	_MESSAGE("init complete");
}
コード例 #13
0
BOOL CALLBACK TabCtrlProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	struct TabCtrlData *dat;
	dat = (struct TabCtrlData *) GetWindowLong(hwnd, GWL_USERDATA);
    switch(msg) {
        case WM_MBUTTONDOWN:
		{
			TCITEM tci;
			int tabId;
			struct MessageWindowData *mwd;
			TCHITTESTINFO thinfo;
			thinfo.pt.x = (lParam<<16)>>16;
			thinfo.pt.y = lParam>>16;
			tabId = TabCtrl_HitTest(hwnd, &thinfo);
			if (tabId >= 0) {
				tci.mask = TCIF_PARAM;
				TabCtrl_GetItem(hwnd, tabId, &tci);
				mwd = (struct MessageWindowData *) tci.lParam;
				if (mwd != NULL) {
					SendMessage(mwd->hwnd, WM_CLOSE, 0, 0);
    			}
			}
	        return TRUE;
        }
		case WM_LBUTTONDBLCLK:
		{
			TCHITTESTINFO thinfo;
			int tabId;
			thinfo.pt.x = (lParam<<16)>>16;
			thinfo.pt.y = lParam>>16;
			tabId = TabCtrl_HitTest(hwnd, &thinfo);
			if (tabId >=0 ) {
				void * clickChild = GetChildFromTab(hwnd, tabId)->hwnd;
				if (clickChild == dat->lastClickChild) {
					SendMessage(clickChild, WM_CLOSE, 0, 0);
				}
			}
			dat->lastClickChild = NULL;
		}
		break;
		case WM_LBUTTONDOWN:
		{
			if (!dat->bDragging) {
				FILETIME ft;
				TCHITTESTINFO thinfo;
				GetSystemTimeAsFileTime(&ft);
				thinfo.pt.x = (lParam<<16)>>16;
				thinfo.pt.y = lParam>>16;
				dat->srcTab = dat->destTab = TabCtrl_HitTest(hwnd, &thinfo);
				if (dat->srcTab >=0 ) {
					dat->lastClickChild = GetChildFromTab(hwnd, dat->srcTab)->hwnd;
				} else {
					dat->lastClickChild = NULL;
				}
				dat->bDragging = TRUE;
				dat->bDragged = FALSE;
				dat->clickLParam = lParam;
				dat->clickWParam = wParam;
				dat->lastClickTime = ft.dwLowDateTime;
				dat->mouseLBDownPos.x = thinfo.pt.x;
				dat->mouseLBDownPos.y = thinfo.pt.y;
				SetCapture(hwnd);
				return 0;
			}
		}
		break;
		case WM_CAPTURECHANGED:
		case WM_LBUTTONUP:
			if (dat->bDragging) {
				TCHITTESTINFO thinfo;
				thinfo.pt.x = (lParam<<16)>>16;
				thinfo.pt.y = lParam>>16;
				if (dat->bDragged) {
					ImageList_DragLeave(GetDesktopWindow());
					ImageList_EndDrag();
					ImageList_Destroy(dat->hDragImageList);
					SetCursor(LoadCursor(NULL, IDC_ARROW));
					dat->destTab = TabCtrl_HitTest(hwnd, &thinfo);
					if (thinfo.flags != TCHT_NOWHERE && dat->destTab != dat->srcTab)  {
						NMHDR nmh;
						TCHAR  sBuffer[501];
						TCITEM item;
						int curSel;
						curSel = TabCtrl_GetCurSel(hwnd);
						item.mask = TCIF_IMAGE | TCIF_PARAM | TCIF_TEXT;
						item.pszText = sBuffer;
						item.cchTextMax = sizeof(sBuffer)/sizeof(TCHAR);
						TabCtrl_GetItem(hwnd, dat->srcTab, &item);
						sBuffer[sizeof(sBuffer)/sizeof(TCHAR)-1] = '\0';
						if (curSel == dat->srcTab) {
							curSel = dat->destTab;
						} else {
							if (curSel > dat->srcTab && curSel <= dat->destTab) {
								curSel--;
							} else if (curSel < dat->srcTab && curSel >= dat->destTab) {
								curSel++;
							}
						}
						TabCtrl_DeleteItem(hwnd, dat->srcTab);
						TabCtrl_InsertItem(hwnd, dat->destTab, &item );
						TabCtrl_SetCurSel(hwnd, curSel);
						nmh.hwndFrom = hwnd;
						nmh.idFrom = GetDlgCtrlID(hwnd);
						nmh.code = TCN_SELCHANGE;
						SendMessage(GetParent(hwnd), WM_NOTIFY, nmh.idFrom, (LPARAM)&nmh);
						UpdateWindow(hwnd);
					}
				} else {
					SendMessage(hwnd, WM_LBUTTONDOWN, dat->clickWParam, dat->clickLParam);
				}
				dat->bDragged = FALSE;
				dat->bDragging = FALSE;
				ReleaseCapture();
			}
コード例 #14
0
ファイル: sqlite.cpp プロジェクト: reupen/ipod_manager
int xOpen(sqlite3_vfs*, const char *zName, sqlite3_file* p_file,int flags, int *pOutFlags)
{
	sqlite3_file_fb2k * p_fb2kfile = static_cast<sqlite3_file_fb2k*>(p_file);
	p_fb2kfile->pMethods = &xIoMethod;
	p_fb2kfile->m_file = NULL;
	filesystem::t_open_mode fb2kMode = filesystem::open_mode_read;
	pfc::string8 temp;
	if (!zName)
	{
		uGetTempPath(temp);
		temp;// << "\\";
		FILETIME ft;
		GetSystemTimeAsFileTime(&ft);
		srand(ft.dwLowDateTime);
		temp << (unsigned) ft.dwHighDateTime << (unsigned) ft.dwLowDateTime << rand() << ".dop.temp";
		zName = temp.get_ptr();
	}
	if (flags & SQLITE_OPEN_READONLY)
	{
		fb2kMode = filesystem::open_mode_read;
		if (pOutFlags)
			*pOutFlags = SQLITE_OPEN_READONLY;
	}
	else if (flags & SQLITE_OPEN_READWRITE)
	{
		fb2kMode = filesystem::open_mode_write_existing;
		if (pOutFlags)
			*pOutFlags = SQLITE_OPEN_READWRITE;
	}
	else if ( (flags & (SQLITE_OPEN_CREATE|SQLITE_OPEN_EXCLUSIVE)) == (SQLITE_OPEN_CREATE|SQLITE_OPEN_EXCLUSIVE) )
	{
		fb2kMode = filesystem::open_mode_write_new;
		*pOutFlags = SQLITE_OPEN_CREATE|SQLITE_OPEN_EXCLUSIVE;
	}
	else if (flags & (SQLITE_OPEN_CREATE))
	{
		fb2kMode = filesystem::open_mode_write_existing;
		*pOutFlags = SQLITE_OPEN_CREATE;
	}
	else return SQLITE_NOLFS;

	try
	{
		file::ptr ptr;
		try {
		filesystem::g_open(ptr, zName, fb2kMode, abort_callback_dummy());
		}
		catch (exception_io_not_found const &)
		{
			if (flags & (SQLITE_OPEN_CREATE))
			{
				filesystem::g_open_write_new(ptr, zName, abort_callback_dummy());
				if (pOutFlags)
					*pOutFlags |= SQLITE_OPEN_CREATE;
			}
			else throw;			
		}

		p_fb2kfile->m_file = new file::ptr(ptr.get_ptr());
	}
	catch (const exception_io & ex) 
	{
		console::formatter() << "iPod manager: xOpen error: " << ex.what();
		return SQLITE_IOERR;
	}

	return SQLITE_OK;
}
コード例 #15
0
/*
	The following block is copied from the Java source code. It documents the counters array.

	 * @param counters the results are returned in this array.
	 * <ol>
	 * <li>working set in bytes for this process
	 * <li>peak working set in bytes for this process
	 * <li>elapsed time in milliseconds
	 * <li>user time in milliseconds
	 * <li>kernel time in milliseconds
	 * <li>page faults for the process
	 * <li>commit charge total in bytes (working set for the entire machine). On some 
	 * machines we have problems getting this value so we return -1 in that case.
	 * <li>number of GDI objects in the process
	 * <li>number of USER objects in the process
	 * <li>number of open handles in the process. returns -1 if this information is not available
	 * <li>Number of read operations
	 * <li>Number of write operations
	 * <li>Number of bytes read
	 * <li>Number of bytes written
	 * </ol>

*/
JNIEXPORT jboolean JNICALL Java_org_eclipse_perfmsr_core_PerformanceMonitor_nativeGetPerformanceCounters
  (JNIEnv * jniEnv, jclass jniClass, jlongArray counters)
{
	FILETIME creationTime, exitTime, kernelTime, userTime, systemTime;
	ULARGE_INTEGER uliCreation, uliSystem, uliKernel, uliUser;
	ULONGLONG diff;
	IO_COUNTERS ioCounters;

	jboolean result = TRUE;
	jsize len = (*jniEnv)->GetArrayLength(jniEnv, counters);
	jlong *body = (*jniEnv)->GetLongArrayElements(jniEnv, counters, 0);
	HANDLE me = GetCurrentProcess();
	PROCESS_MEMORY_COUNTERS memCounters;
	DWORD cb = sizeof(PROCESS_MEMORY_COUNTERS);
	BOOL rc = GetProcessMemoryInfo(me, &memCounters, cb);
	if (rc != 0)
	{
		body[0] = memCounters.WorkingSetSize;
		body[1] = memCounters.PeakWorkingSetSize;
		body[5] = memCounters.PageFaultCount;
	}
	else
	{
		handleSystemError(jniEnv);
		return FALSE;
	}

	if (!GetProcessTimes(me, &creationTime, &exitTime, &kernelTime, &userTime))
	{
		handleSystemError(jniEnv);
		return FALSE;
	}
	GetSystemTimeAsFileTime(&systemTime);

	memcpy(&uliCreation, &creationTime, sizeof(uliCreation));  
	memcpy(&uliSystem, &systemTime, sizeof(uliSystem));
	memcpy(&uliKernel, &kernelTime, sizeof(uliSystem));
	memcpy(&uliUser, &userTime, sizeof(ULARGE_INTEGER));
	diff = uliSystem.QuadPart - uliCreation.QuadPart;
	body[2] = diff / 10000;
	body[3] = uliUser.QuadPart / 10000;
	body[4] = uliKernel.QuadPart / 10000;
	body[6] = getTotalCommitted(jniEnv);

	body[7] = GetGuiResources(me, GR_GDIOBJECTS);
	body[8] = GetGuiResources(me, GR_USEROBJECTS);
	body[9] = getHandleCount(jniEnv, me);

	if (!GetProcessIoCounters(me, &ioCounters))
	{
		handleSystemError(jniEnv);
		return FALSE;
	}
	body[10] = ioCounters.ReadOperationCount;
	body[11] = ioCounters.WriteOperationCount;
	body[12] = ioCounters.ReadTransferCount;
	body[13] = ioCounters.WriteTransferCount;

	(*jniEnv)->ReleaseLongArrayElements(jniEnv, counters, body, 0);

	return result;
}
コード例 #16
0
ファイル: pcapio.c プロジェクト: flaub/HotFuzz
gboolean
libpcap_write_interface_statistics_block(FILE *fp,
                                         guint32 interface_id,
                                         pcap_t *pd,
                                         long *bytes_written,
                                         int *err)
{
	struct isb isb;
#ifdef _WIN32
	FILETIME now;
#else
	struct timeval now;
#endif
	struct option option;
	struct pcap_stat stats;
	guint32 block_total_length;
	guint64 timestamp;
	guint64 counter;
	gboolean stats_retrieved;
	
#ifdef _WIN32
	/*
	 * Current time, represented as 100-nanosecond intervals since
	 * January 1, 1601, 00:00:00 UTC.
	 *
	 * I think DWORD might be signed, so cast both parts of "now"
	 * to guint32 so that the sign bit doesn't get treated specially.
	 */
	GetSystemTimeAsFileTime(&now);
	timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
	            (guint32)now.dwLowDateTime;

	/*
	 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
	 * intervals.
	 */
	timestamp /= 10;

	/*
	 * Subtract difference, in microseconds, between January 1, 1601
	 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
	 */
	timestamp -= G_GINT64_CONSTANT(11644473600000000U);
#else
	/*
	 * Current time, represented as seconds and microseconds since
	 * January 1, 1970, 00:00:00 UTC.
	 */
	gettimeofday(&now, NULL);

	/*
	 * Convert to delta in microseconds.
	 */
	timestamp = (guint64)(now.tv_sec) * 1000000 +
	            (guint64)(now.tv_usec);
#endif
	if (pcap_stats(pd, &stats) < 0) {
		stats_retrieved = FALSE;
		g_warning("pcap_stats() failed.");
	} else {
		stats_retrieved = TRUE;
	}
	block_total_length = sizeof(struct isb) +
	                     sizeof(guint32);
	if (stats_retrieved) {
		block_total_length += 3 * sizeof(struct option) + 2 * sizeof(guint64);
	}
	isb.block_type = INTERFACE_STATISTICS_BLOCK_TYPE;
	isb.block_total_length = block_total_length;
	isb.interface_id = interface_id;
	isb.timestamp_high = (guint32)((timestamp>>32) & 0xffffffff);
	isb.timestamp_low = (guint32)(timestamp & 0xffffffff);
	WRITE_DATA(fp, &isb, sizeof(struct isb), *bytes_written, err);
	if (stats_retrieved) {
		/* */
		option.type = ISB_IFRECV;
		option.value_length = sizeof(guint64);
		counter = stats.ps_recv;
		WRITE_DATA(fp, &option, sizeof(struct option), *bytes_written, err);
		WRITE_DATA(fp, &counter, sizeof(guint64), *bytes_written, err);
		/* */
		option.type = ISB_IFDROP;
		option.value_length = sizeof(guint64);
		counter = stats.ps_drop;
		WRITE_DATA(fp, &option, sizeof(struct option), *bytes_written, err);
		WRITE_DATA(fp, &counter, sizeof(guint64), *bytes_written, err);
		/* last option */
		option.type = OPT_ENDOFOPT;
		option.value_length = 0;
		WRITE_DATA(fp, &option, sizeof(struct option), *bytes_written, err);
	}
	WRITE_DATA(fp, &block_total_length, sizeof(guint32), *bytes_written, err);
	
	return TRUE;
}
コード例 #17
0
ファイル: docfile.cpp プロジェクト: maerson/windbg
//Save document with (possibly) a new file name
BOOL FAR  SaveDocument(int doc, LPSTR FileName)
{
    LPLINEREC pl;
    LPBLOCKDEF pb;
    long y;
    register WORD i;
    WORD len;
    HCURSOR hSaveCursor;
    LPDOCREC d = &Docs[doc];

    //Set the Hour glass cursor
    hSaveCursor = SetCursor(LoadCursor(NULL, IDC_WAIT));

    //Create file
    if (HFILE_ERROR == (hFileDoc = _lcreat(FileName, 0)) ) {
        ErrorBox(ERR_File_Create, (LPSTR)FileName);
        goto error0;
    }

    //Allocate space for Disk Buffer

    if ((pszBufferDoc = DocAlloc(DISK_BLOCK_SIZE)) == NULL) {
        ErrorBox(SYS_Allocate_Memory);
        goto error1;
    }

    dwOffsetDoc = 0; y = 0;

    //Get first line
    if (!FirstLine (doc, &pl, &y, &pb))
          return FALSE;

    //Save each line of file
    while (TRUE) {

        //Remove trailing blanks
        len = (WORD) (pl->Length - LHD);
        {
            TCHAR *pch1;

            pch1 = pl->Text + (pl->Length - LHD);

            while (pch1 > pl->Text) {
                pch1 = CharPrev(pl->Text, pch1);
                if (*pch1 != ' ' && *pch1 != TAB) {
                    break;
                }
                len --;
            }
        }

        //Write line
        i = 0;
        while (i < len) {

            PutChar(FileName, pl->Text[i]);
            i++;
        }

        if (y >= d->NbLines) {
            if (dwOffsetDoc && !Flush(FileName))
                goto error2;
            break;
        }
        else {
            PutChar (FileName, CR);
            PutChar (FileName, LF);
            if (!NextLine (doc, &pl, &y, &pb))
                  goto error2;
        }
    }

    CloseHandle (hFileDoc);

    //Update internal file date
    GetSystemTimeAsFileTime(&d->time);

    CloseLine(doc, &pl, y, &pb);

    d->ismodified = FALSE;
    RefreshWindowsTitle(doc);

    SetCursor (hSaveCursor);

    return TRUE;

  error2:
    CloseLine(doc, &pl, y, &pb);
    if (!DocFree(pszBufferDoc))
          InternalErrorBox(SYS_Free_Memory);

  error1:
    CloseHandle (hFileDoc);

  error0:
    SetCursor (hSaveCursor);
    return FALSE;
}                                       /* SaveDocument() */
コード例 #18
0
ファイル: timer.c プロジェクト: gitter-badger/OpenVML
/**
 * Returns the real time, in seconds, or -1.0 if an error occurred.
 *
 * Time is measured since an arbitrary and OS-dependent start time.
 * The returned real time is only useful for computing an elapsed time
 * between two calls to this function.
 */
double getRealTime( )
{
#if defined(_WIN32)
  FILETIME tm;
  ULONGLONG t;
#if defined(NTDDI_WIN8) && NTDDI_VERSION >= NTDDI_WIN8
  /* Windows 8, Windows Server 2012 and later. ---------------- */
  GetSystemTimePreciseAsFileTime( &tm );
#else
  /* Windows 2000 and later. ---------------------------------- */
  GetSystemTimeAsFileTime( &tm );
#endif
  t = ((ULONGLONG)tm.dwHighDateTime << 32) | (ULONGLONG)tm.dwLowDateTime;
  return (double)t / 10000000.0;

#elif (defined(__hpux) || defined(hpux)) || ((defined(__sun__) || defined(__sun) || defined(sun)) && (defined(__SVR4) || defined(__svr4__)))
  /* HP-UX, Solaris. ------------------------------------------ */
  return (double)gethrtime( ) / 1000000000.0;

#elif defined(__MACH__) && defined(__APPLE__)
  /* OSX. ----------------------------------------------------- */
  static double timeConvert = 0.0;
  if ( timeConvert == 0.0 )
    {
      mach_timebase_info_data_t timeBase;
      (void)mach_timebase_info( &timeBase );
      timeConvert = (double)timeBase.numer /
	(double)timeBase.denom /
	1000000000.0;
    }
  return (double)mach_absolute_time( ) * timeConvert;

#elif defined(_POSIX_VERSION)
  /* POSIX. --------------------------------------------------- */
#if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0)
  {
    struct timespec ts;
#if defined(CLOCK_MONOTONIC_PRECISE)
    /* BSD. --------------------------------------------- */
    const clockid_t id = CLOCK_MONOTONIC_PRECISE;
#elif defined(CLOCK_MONOTONIC_RAW)
    /* Linux. ------------------------------------------- */
    const clockid_t id = CLOCK_MONOTONIC_RAW;
#elif defined(CLOCK_HIGHRES)
    /* Solaris. ----------------------------------------- */
    const clockid_t id = CLOCK_HIGHRES;
#elif defined(CLOCK_MONOTONIC)
    /* AIX, BSD, Linux, POSIX, Solaris. ----------------- */
    const clockid_t id = CLOCK_MONOTONIC;
#elif defined(CLOCK_REALTIME)
    /* AIX, BSD, HP-UX, Linux, POSIX. ------------------- */
    const clockid_t id = CLOCK_REALTIME;
#else
    const clockid_t id = (clockid_t)-1;/* Unknown. */
#endif /* CLOCK_* */
    if ( id != (clockid_t)-1 && clock_gettime( id, &ts ) != -1 )
      return (double)ts.tv_sec +
	(double)ts.tv_nsec / 1000000000.0;
    /* Fall thru. */
  }
#endif /* _POSIX_TIMERS */

  /* AIX, BSD, Cygwin, HP-UX, Linux, OSX, POSIX, Solaris. ----- */
  struct timeval tm;
  gettimeofday( &tm, NULL );
  return (double)tm.tv_sec + (double)tm.tv_usec / 1000000.0;
#else
  return -1.0;/* Failed. */
#endif
}
コード例 #19
0
ファイル: docfile.cpp プロジェクト: maerson/windbg
int 
OpenDocument(
    WORD    mode,
    WORD    type,
    int     doc,
    LPSTR   FileName,
    int     dupView,
    int     Preference,
    BOOL    bUserActivated
    )

/*++

Routine Description:

    This routine is used to create a new document or to duplicate
    the view of an existing document.

Arguments:

    mode        - Supplies MODE_DUPLICATE if the document is to be duplicated
                           MODE_RELOAD if the file is to be reloaded
                           MODE_CREATE if the document is to be created
    type        - Supplies the document type
    doc         - Supplies
    FileName    - Supplies a pointer to the name of the file for the document
    dupView     - Supplies the view to be duplicated (mode == MODE_DUPLICATE)
    Preference  - Supplies the view preference (-1 if none)
    bUserActivated - Indicates whether this action was initiated by the
                user or by windbg. The value is to determine the Z order of
                any windows that are opened.

Return Value:

    -1 on failure
    view number on success (>= 0)
    return-value - Description of conditions needed to return value. - or -

--*/

{
    LPLINEREC   pl;
    int         nView = 0;
    BOOL        create;
    int         n;
    int         language;
    LPDOCREC    d;
    LPVIEWREC   views;

    //
    //  In mode duplicate, we create a new nView being a copy of the previous
    //  nView of the same document
    //

    if (mode == MODE_DUPLICATE) {

        //
        // Search a free entry for the nView we will create
        //

        if ( (Preference != -1) && Views[ Preference ].Doc == -1 ) {
            nView = Preference;
        } else {
            for (nView = 0; (nView < MAX_VIEWS) && (Views[nView].Doc != -1); nView++);
        }

        if (nView == MAX_VIEWS) {
            ErrorBox(ERR_Too_Many_Opened_Views);
            return -1;
        }

        //
        // Copy parameters from previous nView
        //

        Assert( Docs[Views[dupView].Doc].FirstView >= 0);

        //
        //      Find the last nView for this document
        //

        n = dupView;
        while (Views[n].NextView != -1) {
            n = Views[n].NextView;
        }

        Assert(n < MAX_VIEWS);

        //
        //     Attach new nView to last one found
        //

        Views[nView] = Views[n];
        Views[n].NextView = nView;
        Views[nView].hwndClient = NULL;

        //
        //
        //

        Views[nView].iYTop = Views[dupView].iYTop;

        //
        //     Enlist nView in window menu
        //

        AddWindowMenuItem(Views[dupView].Doc, nView);

        return nView;

    } else if (mode == MODE_RELOAD) {
        nView = Docs[doc].FirstView;
    }

    //
    // First search a free entry for the document
    //

    if (mode != MODE_RELOAD) {
        for (doc = 0; (doc < MAX_DOCUMENTS) && (Docs[doc].FirstView != -1); doc++);
    }

    if (doc >= MAX_DOCUMENTS) {
        ErrorBox(ERR_Too_Many_Opened_Documents);
        return -1;
    }

    d = &Docs[doc];

    if (type == DOC_WIN) {

        //
        //      Check if file is not already loaded
        //

        if (mode == MODE_RELOAD) {
            DestroyDocument(doc);
            language = SetLanguage(doc);
        } else {
            if (FileName != NULL) {
                TCHAR szAbsolutePath[_MAX_PATH] = {0};

                Assert(sizeof(szAbsolutePath) == sizeof(d->szFileName));

                // We may have a relative path name to a file. Try to get the absolute path.
                if ( _fullpath(szAbsolutePath, FileName, sizeof(szAbsolutePath) ) ) {
                    // success
                    _tcscpy(d->szFileName, szAbsolutePath);
                } else {
                    // error. Use as is.
                    _tcscpy(d->szFileName, FileName);
                }

                for (n = 0; n < MAX_DOCUMENTS; n++) {
                    if (Docs[n].FirstView != -1
                        && _strcmpi(Docs[n].szFileName, d->szFileName) == 0) {

                        SetMessageText_StatusBar(ERR_File_Already_Loaded, STATUS_INFOTEXT, FileName);
                        MessageBeep(0);

                        //
                        //  Reactivate window
                        //

                        //SendMessage(g_hwndMDIClient, WM_MDIACTIVATE, (WPARAM) Views[Docs[n].FirstView].hwndFrame, 0L);
                        ActivateMDIChild(Views[Docs[n].FirstView].hwndFrame, bUserActivated);
                        return -1;
                    }
                }

                language = SetLanguage(doc);

            } else {
                // shouldn't happen anymore
                Assert(0);
// BUGBUG - dead code - kcarlos
#if 0
                //
                //  Initialize document record and first nView
                //

                register int i, j;

                for (i = 0; i < MAX_DOCUMENTS; i++) {
                    CreateUntitled(d->FileName, i + 1);
                    for (j = 0; j < MAX_DOCUMENTS; j++) {
                        if (j != doc &&
                            _strcmpi (d->szFileName, Docs[j].szFileName) == 0) {
                            break;
                        }
                    }
                    if (j >= MAX_DOCUMENTS) {
                        break;
                    }
                }

                language = C_LANGUAGE;
#endif
            }
        }
    } else {

        WORD winTitle;
        char rgch[MAX_MSG_TXT];

        language = NO_LANGUAGE;

        //
        //  Non Document type, Load window title from ressource
        //

        switch (type) {

        case DISASM_WIN:
            winTitle = SYS_DisasmWin_Title;
            break;       
        case COMMAND_WIN:
            winTitle = SYS_CmdWin_Title;
            break;
        case MEMORY_WIN:
            winTitle = SYS_MemoryWin_Title;
            break;
        default:
            Assert(FALSE);
            return -1;
            break;
        }
        Dbg(LoadString(g_hInst, winTitle, rgch, MAX_MSG_TXT));
        RemoveMnemonic(rgch, d->szFileName);

        if (type == MEMORY_WIN) {
            lstrcat (d->szFileName,"(");
            lstrcat (d->szFileName,TempMemWinDesc.szAddress);
            lstrcat (d->szFileName,")");
        }
    }

    //
    //  Then search a free entry for the first nView we will create
    //

    if (mode != MODE_RELOAD) {

        if ( (Preference != -1) && Views[ Preference ].Doc == -1 ) {
            nView = Preference;
        } else {
            for (nView = 0; nView < MAX_VIEWS && Views[nView].Doc != -1; nView++);
        }
        if (nView == MAX_VIEWS) {
            ErrorBox(ERR_Too_Many_Opened_Views);
            return -1;
        }
    }

    //
    // Check if file exist
    //

    if (mode == MODE_CREATE || type != DOC_WIN) {
        create = TRUE;
    } else {
        if (mode == MODE_OPEN || FileExist(FileName)) {
            create = FALSE;
        } else {
            if (mode == MODE_OPENCREATE) {
                // Tell the user that the file does not exist.

                // kcarlos
                // BUGBUG
                // Quick hack. To fix a bug, hopefully this all disappear soon.
                VarMsgBox(hwndFrame, SYS_Does_Not_Exist_Create, MB_OK, FileName);
                return -1;
            } else {
                create = FALSE;
            }
        }
    }

    d->readOnly = FALSE;
    d->docType = type;
    d->language = (WORD) language;
    d->untitled = (FileName == NULL);
    d->ismodified = FALSE;

    if (create) {

        LPBLOCKDEF pb;

        //
        //  Initialize the file with a null-string
        //


        d->LastBlock = d->FirstBlock = (LPBLOCKDEF)DocAlloc(sizeof(BLOCKDEF));
        GetSystemTimeAsFileTime(&d->time);

        if (d->FirstBlock == NULL) {
            ErrorBox(SYS_Allocate_Memory);
            return -1;
        }

        pb = d->FirstBlock;

        //
        //  Initialize first block
        //

        pb->PrevBlock = pb->NextBlock = NULL;
        pb->LastLineOffset = 0;

        //
        // Initialize first line
        //

        pl = (LPLINEREC)pb->Data;
        pl->PrevLength = 0;
        pl->Length = LHD;
        pl->Status = 0;

        d->NbLines = 1;         // We start with one null line

    } else {

        //
        // Load the file and check if it's a valid one
        //

        if (!LoadFile(doc)) {
            return -1;
        }
    }

    //
    // Initialize current pointers
    //

    d->CurrentBlock = d->FirstBlock;
    d->CurrentLine = 0;
    d->CurrentLineOffset = 0;
    pl = (LPLINEREC)(d->FirstBlock->Data);
    ExpandTabs(&pl);

    //
    // Undo/redo part
    //

    d->undo.h = 0;
    d->redo.h = 0;
    d->playCount = REC_CANNOTUNDO;
    if (g_contGlobalPreferences_WkSp.m_dwUndoResize == 0 || type != DOC_WIN) {
        d->recType = REC_STOPPED;
    } else {
        d->recType = REC_UNDO;
    }
    CreateRecBuf(doc, REC_UNDO, g_contGlobalPreferences_WkSp.m_dwUndoResize);

    if (mode == MODE_RELOAD) {
        RefreshWindowsTitle(doc);
    } else {

        //
        //  Initialize nView part
        //

        views = &Views[nView];
        views->NextView = -1;
        views->X = views->Y = 0;
        views->hwndClient = views->hwndFrame = NULL;
        views->hScrollBar = g_contGlobalPreferences_WkSp.m_bHorzScrollBars;
        views->vScrollBar = g_contGlobalPreferences_WkSp.m_bVertScrollBars;
        views->scrollFactor = 0;
        views->iYTop = -1;

        //
        //  Everything is OK, add title in window menu and return the nView
        //

        d->FirstView = nView;
        views->Doc = doc;
        AddWindowMenuItem(doc, nView);
    }

    //
    // Check syntax if C
    //

    if (d->language == C_LANGUAGE) {
        d->lineTop = 0;
        d->lineBottom = d->NbLines;
        CheckSyntax(doc);
    }

    return nView;
}                                       // OpenDocument()
コード例 #20
0
ファイル: wincache_fcnotify.c プロジェクト: juokaz/wincache
/* This method will either create a new entry altogether or modify an existing entry */
static int create_fcnotify_data(fcnotify_context * pnotify, const char * folderpath, fcnotify_value ** ppvalue)
{
    int               result    = NONFATAL;
    fcnotify_value *  pvalue    = NULL;
    alloc_context *   palloc    = NULL;
    unsigned int      pathlen   = 0;
    char *            paddr     = NULL;
    unsigned int      fshare    = 0;
    unsigned int      flags     = 0;
    unsigned int      rdcresult = 0;
    fcnotify_listen * plistener = NULL;

    dprintverbose("start create_fcnotify_data");

    _ASSERT(pnotify    != NULL);
    _ASSERT(folderpath != NULL);
    _ASSERT(ppvalue    != NULL);

    palloc = pnotify->fcalloc;
    pathlen = strlen(folderpath);

    /* Allocate memory only if its not already allocated */
    if(*ppvalue == NULL)
    {
        pvalue = (fcnotify_value *)alloc_smalloc(palloc, sizeof(fcnotify_value) + ALIGNDWORD(pathlen + 1));
        if(pvalue == NULL)
        {
            result = FATAL_OUT_OF_SMEMORY;
            goto Finished;
        }

        /* Set these to 0 only if a new structure is created */
        pvalue->reusecount  = 0;
        pvalue->folder_path = 0;
        pvalue->refcount    = 0;
        pvalue->prev_value  = 0;
        pvalue->next_value  = 0;

        /* Set folderpath only if memory is just allocated */
        paddr = (char *)(pvalue + 1);
        memcpy_s(paddr, pathlen, folderpath, pathlen);
        *(paddr + pathlen) = 0;
        pvalue->folder_path = ((char *)paddr) - pnotify->fcmemaddr;
    }
    else
    {
        pvalue = *ppvalue;
    }

    pvalue->owner_pid = pnotify->processid;
    pvalue->palivechk = GetTickCount();
    pvalue->plistener = NULL;

    pvalue->listen_time.dwHighDateTime = 0;
    pvalue->listen_time.dwLowDateTime  = 0;

    /* Allocate memory for listener locally */
    plistener = (fcnotify_listen *)alloc_pemalloc(sizeof(fcnotify_listen));
    if(plistener == NULL)
    {
        result = FATAL_OUT_OF_LMEMORY;
        goto Finished;
    }

    ZeroMemory(plistener, sizeof(fcnotify_listen));

    /* Set initial refcount and pointer to fcnotify_value */
    plistener->lrefcount  = 0;
    plistener->pfcnvalue  = pvalue;

    /* Open folder_path and attach it to completion port */
    fshare = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
    flags = FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED;

    plistener->folder_handle = CreateFile(folderpath, FILE_LIST_DIRECTORY, fshare, NULL, OPEN_EXISTING, flags, NULL);
    if(plistener->folder_handle == INVALID_HANDLE_VALUE)
    {
        result = FATAL_FCNOTIFY_CREATEFILE;
        goto Finished;
    }

    plistener->folder_path = alloc_pestrdup(folderpath);

    if(CreateIoCompletionPort(plistener->folder_handle, pnotify->port_handle, (ULONG_PTR)0, 0) == NULL)
    {
        result = FATAL_FCNOTIFY_COMPPORT;
        goto Finished;
    }

    rdcresult = register_directory_changes(pnotify, plistener);
    if(!rdcresult)
    {
        result = FATAL_FCNOTIFY_RDCFAILURE;
        goto Finished;
    }

    pvalue->plistener = plistener;
    plistener = NULL;

    /* Update the time when the listener was set */
    GetSystemTimeAsFileTime(&pvalue->listen_time);
    
    pvalue->reusecount++;
    *ppvalue = pvalue;

Finished:

    if(FAILED(result))
    {
        dprintimportant("failure %d in create_fcnotify_data", result);
        _ASSERT(result > WARNING_COMMON_BASE);

        if(pvalue != NULL)
        {
            if(pvalue->plistener != NULL)
            {
                if(pvalue->plistener->folder_path != NULL)
                {
                    alloc_pefree(pvalue->plistener->folder_path);
                    pvalue->plistener->folder_path = NULL;
                }

                if(pvalue->plistener->folder_handle != INVALID_HANDLE_VALUE)
                {
                    CloseHandle(pvalue->plistener->folder_handle);
                    pvalue->plistener->folder_handle = INVALID_HANDLE_VALUE;
                }

                alloc_pefree(pvalue->plistener);
                pvalue->plistener = NULL;
            }

            alloc_sfree(palloc, pvalue);
            pvalue = NULL;
        }
    }

    dprintverbose("end create_fcnotify_data");

    return result;
}
コード例 #21
0
ファイル: cookie.cpp プロジェクト: seledka/syslib
    static bool Cookie_Get(HTTP_SESSION_HANDLE *lpSession,WCHAR *lpHost,WCHAR *lpPath,WCHAR **lppCookiesHdr,bool bSecure,WORD wPort)
    {
        DWORD dwCookiesCount=0;

        FILETIME tm;
        GetSystemTimeAsFileTime(&tm);

        DWORD dwCurSize=sizeof("Cookie: ")-1;
        WCHAR *lpCookiesHdr=StrDuplicateW(dcrW_46ceba8e("Cookie: "),0);
        *lppCookiesHdr=NULL;

        COOKIE_DOMAIN *lpDomain=NULL;
        while (lpDomain=Cookie_FindDomain(lpSession,lpHost,lpPath,true,lpDomain))
        {
            COOKIE *lpCookie=lpDomain->lpCookies;
            while (lpCookie)
            {
                COOKIE *lpCurCookie=lpCookie;
                lpCookie=lpCookie->lpNext;

                if ((lpCurCookie->dwCookieFlags & COOKIE_FLAG_EXPIRES_SET) && (CompareFileTime(&tm,&lpCurCookie->ftExpiry) > 0))
                {
                    Cookie_Delete(lpCurCookie,false);
                    continue;
                }

                if ((lpCurCookie->dwCookieFlags & COOKIE_FLAG_SECURE) && (!bSecure))
                    continue;

                if (lpCurCookie->dwCookieFlags & COOKIE_FLAG_PORT_SET)
                {
                    bool bGoodCookie=false;
                    for (DWORD i=0; i < lpCurCookie->dwPortsCount; i++)
                    {
                        if (lpCurCookie->lpPortsList[i] == wPort)
                        {
                            bGoodCookie=true;
                            break;
                        }
                    }

                    if (!bGoodCookie)
                        continue;
                }

                if (dwCookiesCount)
                    dwCurSize=StrCatFormatExW(&lpCookiesHdr,dwCurSize,dcrW_cefd71e7("; %s"),lpCurCookie->lpCookieName);
                else
                    dwCurSize=StrCatExW(&lpCookiesHdr,lpCurCookie->lpCookieName,0);

                if (lpCurCookie->lpCookieValue)
                    dwCurSize=StrCatFormatExW(&lpCookiesHdr,dwCurSize,dcrW_21840aef("=%s"),lpCurCookie->lpCookieValue);

                dwCookiesCount++;

                if (!lpCookiesHdr)
                    break;
            }
        }

        if (!lpCookiesHdr)
            dwCookiesCount=0;
        else
        {
            StrCatExW(&lpCookiesHdr,dcrW_0f7b6850("\r\n"),2);
            *lppCookiesHdr=lpCookiesHdr;
        }
        return (dwCookiesCount != 0);
    }
コード例 #22
0
ファイル: pytime.c プロジェクト: 3lnc/cpython
static int
pygettimeofday(_PyTime_t *tp, _Py_clock_info_t *info, int raise)
{
#ifdef MS_WINDOWS
    FILETIME system_time;
    ULARGE_INTEGER large;

    assert(info == NULL || raise);

    GetSystemTimeAsFileTime(&system_time);
    large.u.LowPart = system_time.dwLowDateTime;
    large.u.HighPart = system_time.dwHighDateTime;
    /* 11,644,473,600,000,000,000: number of nanoseconds between
       the 1st january 1601 and the 1st january 1970 (369 years + 89 leap
       days). */
    *tp = large.QuadPart * 100 - 11644473600000000000;
    if (info) {
        DWORD timeAdjustment, timeIncrement;
        BOOL isTimeAdjustmentDisabled, ok;

        info->implementation = "GetSystemTimeAsFileTime()";
        info->monotonic = 0;
        ok = GetSystemTimeAdjustment(&timeAdjustment, &timeIncrement,
                                     &isTimeAdjustmentDisabled);
        if (!ok) {
            PyErr_SetFromWindowsErr(0);
            return -1;
        }
        info->resolution = timeIncrement * 1e-7;
        info->adjustable = 1;
    }

#else   /* MS_WINDOWS */
    int err;
#ifdef HAVE_CLOCK_GETTIME
    struct timespec ts;
#else
    struct timeval tv;
#endif

    assert(info == NULL || raise);

#ifdef HAVE_CLOCK_GETTIME
    err = clock_gettime(CLOCK_REALTIME, &ts);
    if (err) {
        if (raise)
            PyErr_SetFromErrno(PyExc_OSError);
        return -1;
    }
    if (_PyTime_FromTimespec(tp, &ts, raise) < 0)
        return -1;

    if (info) {
        struct timespec res;
        info->implementation = "clock_gettime(CLOCK_REALTIME)";
        info->monotonic = 0;
        info->adjustable = 1;
        if (clock_getres(CLOCK_REALTIME, &res) == 0)
            info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
        else
            info->resolution = 1e-9;
    }
#else   /* HAVE_CLOCK_GETTIME */

     /* test gettimeofday() */
#ifdef GETTIMEOFDAY_NO_TZ
    err = gettimeofday(&tv);
#else
    err = gettimeofday(&tv, (struct timezone *)NULL);
#endif
    if (err) {
        if (raise)
            PyErr_SetFromErrno(PyExc_OSError);
        return -1;
    }
    if (_PyTime_FromTimeval(tp, &tv, raise) < 0)
        return -1;

    if (info) {
        info->implementation = "gettimeofday()";
        info->resolution = 1e-6;
        info->monotonic = 0;
        info->adjustable = 1;
    }
#endif   /* !HAVE_CLOCK_GETTIME */
#endif   /* !MS_WINDOWS */
    return 0;
}
コード例 #23
0
ファイル: log4z.cpp プロジェクト: maydayzm/zsummerX
bool CLogerManager::PushLog(LoggerId id, int level, const char * log)
{
	if (id < 0 || id >= LOG4Z_LOGGER_MAX)
	{
		return false;
	}
	if (!m_bRuning || !m_loggers[id]._enable)
	{
		return false;
	}
	if (level < m_loggers[id]._level)
	{
		return true;
	}

	LogData * pLog = new LogData;
	pLog->_id =id;
	pLog->_level = level;

	{
#ifdef WIN32
		FILETIME ft;
		GetSystemTimeAsFileTime(&ft);
		unsigned long long now = ft.dwHighDateTime;
		now <<= 32;
		now |= ft.dwLowDateTime;
		now /=10;
		now -=11644473600000000Ui64;
		now /=1000;
		pLog->_time = now/1000;
		pLog->_precise = (unsigned int)(now%1000);
#else
		struct timeval tm;
		gettimeofday(&tm, NULL);
		pLog->_time = tm.tv_sec;
		pLog->_precise = tm.tv_usec/1000;
#endif
	}

	if (m_loggers[pLog->_id]._display && LOG4Z_ALL_SYNCHRONOUS_DISPLAY)
	{
		tm tt;
		if (!TimeToTm(pLog->_time, &tt))
		{
			memset(&tt, 0, sizeof(tt));
		}
		std::string text;
		sprintf(pLog->_content, "%d-%02d-%02d %02d:%02d:%02d.%03d %s ", 
			tt.tm_year+1900, tt.tm_mon+1, tt.tm_mday, tt.tm_hour, tt.tm_min, tt.tm_sec, pLog->_precise,
			LOG_STRING[pLog->_level]);
		text = pLog->_content;
		text += log;
		text += " \r\n";
		ShowColorText(text.c_str(), pLog->_level);
	}

	int len = (int) strlen(log);
	if (len >= LOG4Z_LOG_BUF_SIZE)
	{
		memcpy(pLog->_content, log, LOG4Z_LOG_BUF_SIZE);
		pLog->_content[LOG4Z_LOG_BUF_SIZE-1] = '\0';
	}
	else
	{
		memcpy(pLog->_content, log, len+1);
	}
	CAutoLock l(m_lock);
	m_logs.push_back(pLog);
	m_ullStatusTotalPushLog ++;
	return true;
}
コード例 #24
0
ファイル: now.c プロジェクト: EdgarChen/mozilla-cvs-history
int main(int argc, char **argv)
{
#if defined(OMIT_LIB_BUILD_TIME)
    /*
     * Some platforms don't have any 64-bit integer type
     * such as 'long long'.  Because we can't use NSPR's
     * PR_snprintf in this program, it is difficult to
     * print a static initializer for PRInt64 (a struct).
     * So we print nothing.  The makefiles that build the
     * shared libraries will detect the empty output string
     * of this program and omit the library build time
     * in PRVersionDescription.
     */
#elif defined(VMS)
    long long now;
    struct timeb b;
    ftime(&b);
    now = b.time;
    now *= 1000000;
    now += (1000 * b.millitm);
    fprintf(stdout, "%Ld", now);
#elif defined(XP_UNIX) || defined(XP_OS2) || defined(XP_BEOS)
    long long now;
    struct timeval tv;
#ifdef HAVE_SVID_GETTOD
    gettimeofday(&tv);
#else
    gettimeofday(&tv, NULL);
#endif
    now = ((1000000LL) * tv.tv_sec) + (long long)tv.tv_usec;
#if defined(OSF1)
    fprintf(stdout, "%ld", now);
#elif defined(BEOS) && defined(__POWERPC__)
    fprintf(stdout, "%Ld", now);  /* Metroworks on BeOS PPC */
#else
    fprintf(stdout, "%lld", now);
#endif

#elif defined(WIN32)
    __int64 now;
    FILETIME ft;
    GetSystemTimeAsFileTime(&ft);
    CopyMemory(&now, &ft, sizeof(now));
    /*
     * 116444736000000000 is the number of 100-nanosecond intervals
     * between Jan. 1, 1601 and Jan. 1, 1970.
     */
#ifdef __GNUC__
    now = (now - 116444736000000000LL) / 10LL;
    fprintf(stdout, "%lld", now);
#else
    now = (now - 116444736000000000i64) / 10i64;
    fprintf(stdout, "%I64d", now);
#endif

#else
#error "Architecture not supported"
#endif

    return 0;
}  /* main */
コード例 #25
0
ファイル: gettimeofday.c プロジェクト: bygreencn/acl
int gettimeofday(struct timeval *tv, struct timezone *tz)
{
	FILETIME        ft;
	LARGE_INTEGER   li;
	__int64         t;
	int             nnested = 0;
	LARGE_INTEGER stamp;
	time_t now;
	TIME_CTX_T *ctx = tls_calloc(sizeof(TIME_CTX_T));

	/* 每个线程调用此函数时都需要进行初始化,但为了防止开机时间太长
	 * 而造成时钟计数归零溢出,所以每隔 1 天校对一次基准时间
	 */
#define DAY_SEC	(3600 * 24)

	time(&now);
	if (now - ctx->last_init > DAY_SEC) {
		ctx->last_init = now;

		/* 获得CPU的时钟频率 */
		if (!QueryPerformanceFrequency(&ctx->frequency))
			acl_msg_fatal("%s(%d): Unable to get System Frequency(%s)",
				__FILE__, __LINE__, acl_last_serror());
		/* 获得系统时间(自 1970 至今) */
		GetSystemTimeAsFileTime(&ft);
		li.LowPart  = ft.dwLowDateTime;
		li.HighPart = ft.dwHighDateTime;
		t  = li.QuadPart;       /* In 100-nanosecond intervals */
		t -= EPOCHFILETIME;     /* Offset to the Epoch time */
		t /= 10;                /* In microseconds */

		/* 转换成本次开机后的基准时间 */
		ctx->tvbase.tv_sec  = (long)(t / 1000000);
		ctx->tvbase.tv_usec = (long)(t % 1000000);

		/* 获得本次开机后到现在的时钟计数 */
		if (!QueryPerformanceCounter(&ctx->stamp))
			acl_msg_fatal("%s(%d): unable to get System time(%s)",
				__FILE__, __LINE__, acl_last_serror());
	}

	/* 开始获得现在的时间截 */

	if (tv) {
		/* 获得本次开机后至现在的时钟计数  */
		if (!QueryPerformanceCounter(&stamp))
			acl_msg_fatal("%s(%d): unable to get System time(%s)",
				__FILE__, __LINE__, acl_last_serror());

		/* 计算当前精确时间截 */
		t = (stamp.QuadPart - ctx->stamp.QuadPart) * 1000000 / ctx->frequency.QuadPart;
		tv->tv_sec = ctx->tvbase.tv_sec + (long)(t / 1000000);
		tv->tv_usec = ctx->tvbase.tv_usec + (long)(t % 1000000);
	}

	if (tz) {
		if (!ctx->tzflag) {
			_tzset();
			ctx->tzflag++;
		}
		tz->tz_minuteswest = _timezone / 60;
		tz->tz_dsttime = _daylight;
	}

	return (0);
}
コード例 #26
0
ファイル: main.cpp プロジェクト: AlexLuya/HPCC-Platform
int main(int argc, char** argv)
{
#if !defined(_WIN32) && !defined(_WIN64)
    printf("Only Windows OS is supported.\n");
#else
    if(argc < 3)
    {
        printf("usage: %s <dir> <command>\n", argv[0]);
        return -1;
    }

    char path[512];
    sprintf_s(path, 511, "%s\\%s.pid", argv[1], argv[2]);

    DWORD pid = 0;
    FILE* f = NULL;
    fopen_s(&f, path, "r");
    if(!f)
    {
        fprintf(stderr, "Can't open file %s\n", path);
    }
    else
    {   
        char* pidbuf[32];
        int numread = fread(pidbuf, sizeof(char), 31, f);
        if(numread > 0)
        {
            pidbuf[numread] = '\0';
            pid = atoi((const char*)pidbuf);
        }
    }
    if(pid > 0)
    {
        printf("ProcessID: %d\n", pid);
        HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, false, pid);
        if(h <= 0)
        {
            fprintf(stderr, "Process %d can't be opened.\n", pid);
            printf("ProcessUpTime: \n");
        }
        else
        {
            //Process elapsed time.
            BIGTIME CreateTime, ExitTime, ElapsedTime, Now;
            FILETIME KernelTime, UserTime;
            GetProcessTimes(h, &CreateTime.ft, &ExitTime.ft, &KernelTime, &UserTime);
            if(ExitTime.li > CreateTime.li)
                ElapsedTime.li = ExitTime.li - CreateTime.li;
            else
            {
                GetSystemTimeAsFileTime(&Now.ft);
                ElapsedTime.li = Now.li - CreateTime.li;
            }
            unsigned elapsedsecs = (unsigned)(ElapsedTime.li/10000000);
            TSpan span(elapsedsecs);
            printf("ProcessUpTime: %d-%02d:%02d:%02d\n", span.d, span.h, span.m, span.s);
        }
    }
    else
    {
        printf("ProcessID: \nProcessUpTime: \n");
    }

    //CPU usage
    BIGTIME idle1, kernel1, user1, idle2, kernel2, user2;
    GetSystemTimes(&idle1.ft, &kernel1.ft, &user1.ft);
    Sleep(1000);
    GetSystemTimes(&idle2.ft, &kernel2.ft, &user2.ft);
    int IdleTime = (int)(idle2.li - idle1.li);
    int TotalTime = (int)((kernel2.li + user2.li) - (kernel1.li + user1.li));
    int idleRate = (int)(100.0 * IdleTime / TotalTime);
    printf("CPU-Idle: %d%%\n", idleRate);

    //Computer uptime
    LARGE_INTEGER ticks, unit;
    QueryPerformanceCounter(&ticks);
    QueryPerformanceFrequency(&unit);
    int secs = (int)(ticks.QuadPart/unit.QuadPart);
    TSpan u((int)secs);
    printf("ComputerUpTime: %d days, %d:%d\n", u.d, u.h, u.m);

    printf("---SpaceUsedAndFree---\n");

    //Physical and virtual memory usage.
    MEMORYSTATUS memstatus;
    GlobalMemoryStatus(&memstatus);
    printf("Physical Memory: %d %d\nVirtual Memory: %d %d\n", 
        (memstatus.dwTotalPhys - memstatus.dwAvailPhys)/1024, memstatus.dwAvailPhys/1024,
        (memstatus.dwTotalVirtual - memstatus.dwAvailVirtual)/1024, memstatus.dwAvailVirtual/1024);

    // Disk Usage
    char        drivePath[] = "?:\\";
    char        driveName;
    for( driveName = 'A'; driveName <= 'Z'; driveName++ ) 
    {
        drivePath[0] = driveName;
        int dtype = GetDriveTypeA(drivePath);
        if(dtype == DRIVE_FIXED || dtype == DRIVE_RAMDISK || dtype == DRIVE_REMOVABLE || dtype == DRIVE_CDROM) 
        {
            ULARGE_INTEGER diskAvailStruct;
            ULARGE_INTEGER diskTotalStruct;
            diskAvailStruct.QuadPart = 0;
            diskTotalStruct.QuadPart = 0;
            GetDiskFreeSpaceExA(drivePath, &diskAvailStruct, &diskTotalStruct, 0);
            double DiskSize = diskTotalStruct.QuadPart / 1024.0; 
            double FreeSize = diskAvailStruct.QuadPart / 1024.0;
            printf("%s: %.0f %.0f\n", drivePath, DiskSize - FreeSize, FreeSize);
        }
    }
#endif
    return 0;
}
コード例 #27
0
ファイル: sntp.c プロジェクト: h16o2u9u/rtoss
/*---------------------------------------------------
	set system time to received data
---------------------------------------------------*/
void SynchronizeSystemTime(DWORD seconds, DWORD fractions)
{
	FILETIME ft, ftold;
	SYSTEMTIME st, st_dif, lt;
	char s[1024];
	DWORD sr_time;
	DWORDLONG dif;
	BOOL b;

	// timeout ?
	sr_time = GetTickCount() - dwTickCountOnSend;
	if(sr_time >= (DWORD)nTimeout)
	{
		wsprintf(s, "timeout (%04d)", sr_time);
		Log(s); return;
	}

	// current time
	GetSystemTimeAsFileTime(&ftold);

	// NTP data -> FILETIME
	*(DWORDLONG*)&ft =
		// seconds from 1900/01/01 �� 100 nano-seconds from 1601/01/01
		M32x32to64(seconds, 10000000) + 94354848000000000i64;

	// difference
	if(nMinuteDif > 0)
		*(DWORDLONG*)&ft += M32x32to64(nMinuteDif * 60, 10000000);
	else if(nMinuteDif < 0)
		*(DWORDLONG*)&ft -= M32x32to64(-nMinuteDif * 60, 10000000);

	// set system time
	b = FileTimeToSystemTime(&ft, &st);
	if(b)
	{
		/* fractions: (2 ** 32 / 1000) */
		st.wMilliseconds = (WORD)(fractions / 4294967);
		b = SetSystemTime(&st);
	}
	if(!b)
	{
		Log("failed to set time"); return;
	}

	GetLocalTime(&lt);
	nLastDay = lt.wDay;
	SetMyRegLong("SNTP", "LastDay", nLastDay);

	SystemTimeToFileTime(&st, &ft);
	// delayed or advanced
	b = (*(DWORDLONG*)&ft > *(DWORDLONG*)&ftold);
	// get difference
	if(b) dif = *(DWORDLONG*)&ft - *(DWORDLONG*)&ftold;
	else  dif = *(DWORDLONG*)&ftold - *(DWORDLONG*)&ft;
	FileTimeToSystemTime((FILETIME*)&dif, &st_dif);

	// save log
	strcpy(s, "synchronized ");
	if(st_dif.wYear == 1601 && st_dif.wMonth == 1 &&
		st_dif.wDay == 1 && st_dif.wHour == 0)
	{
		strcat(s, b?"+":"-");
		wsprintf(s + strlen(s), "%02d:%02d.%03d ",
			st_dif.wMinute, st_dif.wSecond, st_dif.wMilliseconds);
	}
	wsprintf(s + strlen(s), "(%04d)", sr_time);
	Log(s);

	GetMyRegStr("SNTP", "Sound", s, 1024, "");
	PlayFile(g_hwndMain, s, 0);
}
コード例 #28
0
ファイル: helper.cpp プロジェクト: beyerch/SardineCAN-Win32
unsigned long GetTime()
{
	FILETIME t;
	GetSystemTimeAsFileTime(&t);
	return t.dwLowDateTime;
}
コード例 #29
0
ファイル: clock_gettime.c プロジェクト: nbourdau/drawtk
static void gettimespec(struct timespec* tp)
{
	FILETIME curr;
	GetSystemTimeAsFileTime(&curr);
	convert_filetime_to_timespec(&curr, tp, 0);
}
コード例 #30
0
ファイル: main.cpp プロジェクト: m3lawren/ClothDemo
// this is the function used to render a single frame
void render_frame(void)
{
	static const int NBUKKIT = 200;
	static ULARGE_INTEGER bukkits[NBUKKIT];
	static int bukidx = 0;	
	int nbuk = (bukidx + 1) % NBUKKIT;
	int pbuk = (bukidx + NBUKKIT - 1) % NBUKKIT;
	int ntick = 0;	
	FILETIME curFrame;	

	GetSystemTimeAsFileTime(&curFrame);
	bukkits[bukidx].HighPart = curFrame.dwHighDateTime;
	bukkits[bukidx].LowPart = curFrame.dwLowDateTime;

	if (bukkits[pbuk].QuadPart != 0) {
		ntick = bukkits[bukidx].LowPart / 10000 - bukkits[pbuk].LowPart / 10000;
	}

    d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(255, 255, 255), 1.0f, 0);
	d3ddev->Clear(0, NULL, D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);

	CUSTOMVERTEX* Vertices;
	v_buffer->Lock(0, 0, (void**)&Vertices, 0);
	for (unsigned i = 0; i < g_Sim.numPoints(); i++) {
		const Cloth::Point& p = g_Sim.point(i);
		Vertices[i].X = p.x();
		Vertices[i].Y = p.y();
		Vertices[i].Z = p.z();
		Vertices[i].COLOR = D3DCOLOR_XRGB(0, 0, 0);
	}
	v_buffer->Unlock();

    d3ddev->BeginScene();

    // select which vertex format we are using
    d3ddev->SetFVF(CUSTOMFVF);

	RECT r;
	r.left = 0; 
	r.top = 0;
	r.bottom = 0;
	r.right = 0;

	
	char buff[1024];
	if (bukkits[nbuk].QuadPart != 0) {		
		double fps = (float)NBUKKIT * (10000000.0 / (double)(bukkits[bukidx].QuadPart - bukkits[nbuk].QuadPart));
		sprintf_s(buff, 1024, "FPS: %0.1f", fps);
	} else {
		strcpy_s(buff, 1024, "FPS: ??");
	}
	font->DrawText(NULL, buff, -1, &r, DT_CALCRECT, D3DCOLOR_XRGB(1, 1, 1));
	font->DrawText(NULL, buff, -1, &r, 0, D3DCOLOR_XRGB(0, 255, 0));

    // SET UP THE PIPELINE    

    D3DXMATRIX matView;    // the view transform matrix

    D3DXMatrixLookAtLH(&matView,
                       &D3DXVECTOR3 (0.0f, 0.0f, -15.0f),    // the camera position
                       &D3DXVECTOR3 (0.0f, 0.0f, 0.0f),    // the look-at position
                       &D3DXVECTOR3 (0.0f, 1.0f, 0.0f));    // the up direction

    d3ddev->SetTransform(D3DTS_VIEW, &matView);    // set the view transform to matView

    D3DXMATRIX matProjection;     // the projection transform matrix

    D3DXMatrixPerspectiveFovLH(&matProjection,
                               D3DXToRadian(45),    // the horizontal field of view
                               (FLOAT)SCREEN_WIDTH / (FLOAT)SCREEN_HEIGHT, // aspect ratio
                               1.0f,    // the near view-plane
                               100.0f);    // the far view-plane

    d3ddev->SetTransform(D3DTS_PROJECTION, &matProjection);    // set the projection
    
	D3DXMATRIX matIdentity;
	D3DXMatrixIdentity(&matIdentity);

	d3ddev->SetTransform(D3DTS_WORLD, &matIdentity);	

	d3ddev->SetStreamSource(0, v_bordbuffer, 0, sizeof(CUSTOMVERTEX));
	d3ddev->DrawPrimitive(D3DPT_LINESTRIP, 0, 4);

	d3ddev->SetStreamSource(0, v_buffer, 0, sizeof(CUSTOMVERTEX));
	d3ddev->SetIndices(i_buffer);

	unsigned remaining = g_Sim.numConstraints();
	unsigned off = 0;
	while (remaining) {
		unsigned toDraw = (remaining > 128) ? 128 : remaining;
		d3ddev->DrawIndexedPrimitive(D3DPT_LINELIST, 0, 0, g_Sim.numPoints(), off, toDraw);
		off += toDraw * 2;
		remaining -= toDraw;
	}
	//d3ddev->DrawIndexedPrimitive(D3DPT_LINELIST, 0, 0, g_Sim.numConstraints() * 2, 0, g_Sim.numConstraints());

    d3ddev->EndScene();

    d3ddev->Present(NULL, NULL, NULL, NULL);

	bukidx++;
	bukidx %= NBUKKIT;
}