Exemple #1
0
 int __cdecl main(INT argc, CHAR **argv)
{
    unsigned int i = 0;
    HANDLE hThread[MAXIMUM_WAIT_OBJECTS];
    DWORD  threadId[MAXIMUM_WAIT_OBJECTS];
   
    char ObjName[MAX_PATH] = "SHARED_MUTEX";
    DWORD dwParam = 0;

    int returnCode = 0;
    
    /* Variables to capture the file name and the file pointer*/
    char fileName[MAX_PATH];
    FILE *pFile = NULL;
    struct statistics* buffer = NULL;
    int statisticsSize = 0;

    /* Variables to capture the file name and the file pointer at process level*/
    char processFileName[MAX_PATH];
    FILE *pProcessFile = NULL;   
    struct ProcessStats processStats;
    DWORD dwStartTime;

    testStatus = PASS;

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return ( FAIL );
    }

    ZeroMemory( objectSuffix, MAX_PATH );

    if(GetParameters(argc, argv))
    {
        Fail("Error in obtaining the parameters\n");
    }
//    Trace("Process created, value of process count is [%d]\n", USE_PROCESS_COUNT);

    if(argc == 5)
    {
        strncat(ObjName, objectSuffix, MAX_PATH - (sizeof(ObjName) + 1) );
    }

     /* Register the start time */  
    dwStartTime = GetTickCount();
    processStats.relationId = RELATION_ID;
    processStats.processId  = USE_PROCESS_COUNT;

    _snprintf(processFileName, MAX_PATH, "%d_process_mutex_%d_.txt", USE_PROCESS_COUNT, RELATION_ID);
    pProcessFile = fopen(processFileName, "w+");
    if(pProcessFile == NULL)
    { 
        Fail("Error in opening process File file for write for process [%d]\n", USE_PROCESS_COUNT);
    }    statisticsSize = sizeof(struct statistics);

    _snprintf(fileName, MAX_PATH, "%d_thread_mutex_%d_.txt", USE_PROCESS_COUNT, RELATION_ID);
    pFile = fopen(fileName, "w+");
    if(pFile == NULL)
    { 
        Fail("Error in opening file for write for process [%d]\n", USE_PROCESS_COUNT);
    }
    // For each thread we will log operations failed (int), passed (int), total (int)
    // and number of ticks (DWORD) for the operations
    resultBuffer = new ResultBuffer( THREAD_COUNT, statisticsSize);
    
    /* Create StartTest Event */
    StartTestsEvHandle  = CreateEvent( NULL, /* lpEventAttributes*/
                                        TRUE,  /* bManualReset */
                                        FALSE,   /* bInitialState */
                                        NULL);  /* name of Event */

    if( StartTestsEvHandle  == NULL )
    {
        Fail("Error:%d: Unexpected failure "
            "to create %s Event for process count %d\n", GetLastError(), sTmpEventName, USE_PROCESS_COUNT );
  
    }

    hMutexHandle = CreateMutex(
                                NULL,
                                FALSE, /* bInitialOwner, owns initially */
                                ObjName  
                               );
    
    if( (hMutexHandle == NULL)|| (GetLastError() != ERROR_ALREADY_EXISTS))
    {
        Fail("Unable to create Mutex handle for process id [%d], returned error [%d], expected ERROR_ALREADY_EXISTS\n", i, GetLastError());
    }
    /* We already assume that the mutex was created previously*/

    for( i = 0; i < THREAD_COUNT; i++ )
    {
        dwParam = (int) i;
        //Create thread
        hThread[i] = CreateThread(
                                    NULL,                   /* no security attributes */
                                    0,                      /* use default stack size */
                                    (LPTHREAD_START_ROUTINE)Run_Thread,/* thread function */
                                    (LPVOID)dwParam,  /* argument to thread function */
                                    0,                      /* use default creation flags  */
                                    &threadId[i]     /* returns the thread identifier*/                                  
                                  );
    
        if(hThread[i] == NULL)
        {
            Fail("Create Thread failed for %d process, and GetLastError value is %d\n", USE_PROCESS_COUNT, GetLastError());
        }    
    
    }
    
    if (!SetEvent(StartTestsEvHandle))
    {
        Fail("Set Event for Start Tests failed for %d process, and GetLastError value is %d\n", USE_PROCESS_COUNT, GetLastError());           
    }

    /* Test running */
    returnCode = WaitForMultipleObjects( THREAD_COUNT, hThread, TRUE, INFINITE);  

    if( WAIT_OBJECT_0 != returnCode )
    {
        Trace("Wait for Object(s) for %d process returned %d, and GetLastError value is %d\n", USE_PROCESS_COUNT, returnCode, GetLastError());
        testStatus = FAIL;
    }
    
    processStats.operationTime = GetTimeDiff(dwStartTime); 
    
    /* Write to a file*/
    if(pFile!= NULL)
    { 
        for( i = 0; i < THREAD_COUNT; i++ )
        {  
            buffer = (struct statistics *)resultBuffer->getResultBuffer(i);
            returnCode = fprintf(pFile, "%d,%d,%d,%d,%lu,%d\n", buffer->processId, buffer->operationsFailed, buffer->operationsPassed, buffer->operationsTotal, buffer->operationTime, buffer->relationId );
//            Trace("Iteration %d over\n", i);
            
        }
    }
    fclose(pFile);
    
    fprintf(pProcessFile, "%d,%d,%d\n", USE_PROCESS_COUNT, processStats.operationTime, processStats.relationId );
    fclose(pProcessFile);

    /* Logging for the test case over, clean up the handles */
   
//    Trace("Process Count %d over\n",USE_PROCESS_COUNT); 
    
    for( i = 0; i < THREAD_COUNT; i++ )
    {
        if(!CloseHandle(hThread[i]) )
        {
            Trace("Error:%d: CloseHandle failed for Process [%d] hThread[%d]\n", GetLastError(), USE_PROCESS_COUNT, i);
            testStatus = FAIL;
        }
    }

    if(!CloseHandle(StartTestsEvHandle))
    {
        Trace("Error:%d: CloseHandle failed for Process [%d] StartTestsEvHandle\n", GetLastError(), USE_PROCESS_COUNT);
        testStatus = FAIL;
    }

    if(!CloseHandle(hMutexHandle))
    {
        Trace("Error:%d: CloseHandle failed for Process [%d] hMutexHandle\n", GetLastError(), USE_PROCESS_COUNT);
        testStatus = FAIL;
    } 

    PAL_Terminate();
    return  testStatus;
}
Exemple #2
0
void At(char * text)
{
#ifdef TRACE
	Trace("At", text);
#endif
}
Exemple #3
0
void Exit(char * text)
{
#ifdef TRACE_ENTER
	Trace("Exit", text);
#endif
}
Exemple #4
0
void* startThread(void* arg)
{
    /*
    SELECT W.PageID,PageType,URL,ResetCookies,AuthUser,AuthPass,DownloadThreshold,HackingString,ResetCache,ServiceType,SecurityID,WPS.CurrentErrorRef,WPS.AlertCount,AlertLevel2Count,AlertLevel3Count,WPS.ErrorStatus,W.Status,W.IgnoreRudeWords,W.CustomerNo,W.HTTPMethod,W.IgnoreContentErrors,W.DownloadSpeed,W.Referer,W.StoreResultDetail,W.MinSize,W.MaxSize,C.AlertCount,W.CertID,W.StepName,W.AgentString,W.sm_processScript,WPS.OverallAlertCount,W.StoreRequest,W.StoreHeaders,W.StoreHTML,W.StoreDiag,W.ContentType,W.Header1,W.Header2,W.GzipEncoding from WebPage W, Customer C, WebPageStatus WPS where W.PageID=13714 and WPS.PageID=W.PageID and W.CustomerNo=C.CustomerNo and (W.Status=1 or W.Status=3)
    select VariableName, VariableValue, Encode from FormVariables where PageID=13714 order by OrderNo asc
    SELECT Phrase, ID from ContentError
    SELECT Word, ID from ObsceneWord
    SELECT Phrase, ErrorCode from WebPagePhrase where PageID=13714 order by PhraseOrder
    select CookieValue, CookieDomain from Cookies where PageID=13714
    select URL, RequiredText from WebPageExtraFiles where PageID=13714 and Type=0
    select URL, RequiredText from WebPageExtraFiles where PageID=13714 and Type=1
    select URL, RequiredText from WebPageExtraFiles where PageID=13714 and Type=2
    INSERT INTO ResultHeader040303 (ResultID,PageID,TestServer,StartDateTime,ResultCode,DNSTime,FirstByteTime,CompleteTime,TotalBytes,RunID,BatchID,FirstDataTime) VALUES (0,13714,10,'2004-03-03 14:39:20',1,8,9,5309,25291,0,0,15)
    SELECT LAST_INSERT_ID() from ResultHeader040303 where ResultID=LAST_INSERT_ID()
    INSERT INTO ResultDetail040303 (ResultID,StartDateTime,StartOffset,DNSTime,FirstByteTime,FirstDataTime,CompleteTime,ResultCode,TotalBytes,FileName,ComponentNo) VALUES (40,'2004-03-03 14:39:20',0,8,9,15,892,200,4338,'http://192.168.1.5',1)
    INSERT INTO ResultDetail040303 (ResultID,StartDateTime,StartOffset,DNSTime,FirstByteTime,FirstDataTime,CompleteTime,ResultCode,TotalBytes,FileName,ComponentNo) VALUES (40,'2004-03-03 14:39:21',1012,1,1,7,4188,200,6543,'http://192.168.1.5/g/p10.png',2)
    INSERT INTO ResultDetail040303 (ResultID,StartDateTime,StartOffset,DNSTime,FirstByteTime,FirstDataTime,CompleteTime,ResultCode,TotalBytes,FileName,ComponentNo) VALUES (40,'2004-03-03 14:39:21',1025,0,2,3,4185,200,12237,'http://192.168.1.5/g/MYSQLAuthCSP_small.png',3)
    INSERT INTO ResultDetail040303 (ResultID,StartDateTime,StartOffset,DNSTime,FirstByteTime,FirstDataTime,CompleteTime,ResultCode,TotalBytes,FileName,ComponentNo) VALUES (40,'2004-03-03 14:39:21',1008,1,2,6,4301,200,2173,'http://192.168.1.5/g/newlogo.png',4)
    SELECT PageID from WebPageStatus where PageID=13714
    UPDATE WebPageStatus set LastResultID=40,StartDateTime='2004-03-03 14:39:20',LastResultCode=1,CompleteTime=5309 where PageID=13714
    SELECT WS.ErrorStatus,WS.CurrentErrorRef,WS.AlertCount,C.AlertLevel2Count,C.AlertLevel3Count,C.AlertCount,W.OverallAlertCount from Customer C, WebPage W, WebPageStatus WS WHERE C.CustomerNo=W.CustomerNo and W.PageID=WS.PageID and W.PageID=13714
    UPDATE WebPageStatus SET ErrorStatus=0,CurrentErrorRef=0,AlertCount=0 WHERE PageID=13714
    UPDATE WebPageStatus SET OverallAlertCount=0 WHERE PageID=13714
    select ErrorRef from WebPageError where PageID=13714 and Status<>2
    */

    mysql_thread_init();

    Connection* connection;
    Result* result;
    char query[10240];

    for (int repNo = 0; repNo < numRepsPerThreads; ++repNo)
    {
        try
        {
            Trace("Connecting to db", "", repNo);
            connection = new Connection(CConfig::getDBServer(), CConfig::getDBDatabase(),
                                        CConfig::getDBUser(), CConfig::getDBPass(), CConfig::getDBRetryTime());

            // run all the queries here...
            result = connection->Query("SELECT W.PageID,PageType,URL,ResetCookies,AuthUser,AuthPass,DownloadThreshold,HackingString,ResetCache,ServiceType,SecurityID,WPS.CurrentErrorRef,WPS.AlertCount,AlertLevel2Count,AlertLevel3Count,WPS.ErrorStatus,W.Status,W.IgnoreRudeWords,W.CustomerNo,W.HTTPMethod,W.IgnoreContentErrors,W.DownloadSpeed,W.Referer,W.StoreResultDetail,W.MinSize,W.MaxSize,C.AlertCount,W.CertID,W.StepName,W.AgentString,W.sm_processScript,WPS.OverallAlertCount,W.StoreRequest,W.StoreHeaders,W.StoreHTML,W.StoreDiag,W.ContentType,W.Header1,W.Header2,W.GzipEncoding from WebPage W, Customer C, WebPageStatus WPS where W.PageID=13714 and WPS.PageID=W.PageID and W.CustomerNo=C.CustomerNo and (W.Status=1 or W.Status=3)");
            result = connection->Query("select VariableName, VariableValue, Encode from FormVariables where PageID=13714 order by OrderNo asc");
            result = connection->Query("SELECT Phrase, ID from ContentError");
            result = connection->Query("SELECT Word, ID from ObsceneWord");
            result = connection->Query("SELECT Phrase, ErrorCode from WebPagePhrase where PageID=13714 order by PhraseOrder");
            result = connection->Query("select CookieValue, CookieDomain from Cookies where PageID=13714");
            result = connection->Query("select URL, RequiredText from WebPageExtraFiles where PageID=13714 and Type=0");
            result = connection->Query("select URL, RequiredText from WebPageExtraFiles where PageID=13714 and Type=1");
            result = connection->Query("select URL, RequiredText from WebPageExtraFiles where PageID=13714 and Type=2");
            // close the db connection
            connection->Close();
            delete connection;
            connection = NULL;
            Trace("Disonnected from db", "", repNo);

            Trace("Connecting to db", "", repNo);
            connection = new Connection(CConfig::getDBServer(), CConfig::getDBDatabase(),
                                        CConfig::getDBUser(), CConfig::getDBPass(), CConfig::getDBRetryTime());
            result = connection->Query("INSERT INTO ResultHeader040303 (ResultID,PageID,TestServer,StartDateTime,ResultCode,DNSTime,FirstByteTime,CompleteTime,TotalBytes,RunID,BatchID,FirstDataTime) VALUES (0,13714,10,'2004-03-03 14:39:20',1,8,9,5309,25291,0,0,15)");
            result = connection->Query("SELECT LAST_INSERT_ID() from ResultHeader040303 where ResultID=LAST_INSERT_ID()");
            result = connection->Query("INSERT INTO ResultDetail040303 (ResultID,StartDateTime,StartOffset,DNSTime,FirstByteTime,FirstDataTime,CompleteTime,ResultCode,TotalBytes,FileName,ComponentNo) VALUES (40,'2004-03-03 14:39:20',0,8,9,15,892,200,4338,'http://192.168.1.5',1)");
            result = connection->Query("INSERT INTO ResultDetail040303 (ResultID,StartDateTime,StartOffset,DNSTime,FirstByteTime,FirstDataTime,CompleteTime,ResultCode,TotalBytes,FileName,ComponentNo) VALUES (40,'2004-03-03 14:39:21',1012,1,1,7,4188,200,6543,'http://192.168.1.5/g/p10.png',2)");
            result = connection->Query("INSERT INTO ResultDetail040303 (ResultID,StartDateTime,StartOffset,DNSTime,FirstByteTime,FirstDataTime,CompleteTime,ResultCode,TotalBytes,FileName,ComponentNo) VALUES (40,'2004-03-03 14:39:21',1025,0,2,3,4185,200,12237,'http://192.168.1.5/g/MYSQLAuthCSP_small.png',3)");
            result = connection->Query("INSERT INTO ResultDetail040303 (ResultID,StartDateTime,StartOffset,DNSTime,FirstByteTime,FirstDataTime,CompleteTime,ResultCode,TotalBytes,FileName,ComponentNo) VALUES (40,'2004-03-03 14:39:21',1008,1,2,6,4301,200,2173,'http://192.168.1.5/g/newlogo.png',4)");
            result = connection->Query("SELECT PageID from WebPageStatus where PageID=13714");
            result = connection->Query("UPDATE WebPageStatus set LastResultID=40,StartDateTime='2004-03-03 14:39:20',LastResultCode=1,CompleteTime=5309 where PageID=13714");
            result = connection->Query("SELECT WS.ErrorStatus,WS.CurrentErrorRef,WS.AlertCount,C.AlertLevel2Count,C.AlertLevel3Count,C.AlertCount,W.OverallAlertCount from Customer C, WebPage W, WebPageStatus WS WHERE C.CustomerNo=W.CustomerNo and W.PageID=WS.PageID and W.PageID=13714");
            result = connection->Query("UPDATE WebPageStatus SET ErrorStatus=0,CurrentErrorRef=0,AlertCount=0 WHERE PageID=13714");
            result = connection->Query("UPDATE WebPageStatus SET OverallAlertCount=0 WHERE PageID=13714");
            result = connection->Query("select ErrorRef from WebPageError where PageID=13714 and Status<>2");
            // close the db connection
            connection->Close();
            delete connection;
            connection = NULL;
            Trace("Disonnected from db", "", repNo);

        }
        catch (const std::exception &e)
        {
            printf("Exception caught: - %s\r\n", e.what());
            // all done - exit the thread
//			pthread_exit(NULL);
        }

        Trace("Sleeping", "", 100 * sleepTime);
        usleep(100 * sleepTime);
    }

    mysql_thread_end();

    // all done - exit the thread
    pthread_exit(NULL);

    Trace("After Thread end", "", 0);
}
Exemple #5
0
bool nGraphics::InitGraphics()
{
	// Create our base direct3d object
	m_pDirect3D = Direct3DCreate9(D3D_SDK_VERSION);
	if(!m_pDirect3D)
	{
		nMainFrame::LastError("Failed to create direct3d 9, directx 9 not installed?");
		return TraceRet(__FUNCTION__" Failed to create direct3d 9, directx 9 not installed?\n",false);
	}

	// Check if the device support's the caps we will use
	if(!ValidateDevice())
		return false;

	// Get the desktop's display mode
	D3DDISPLAYMODE displayMode;
	if(FAILED(m_pDirect3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &displayMode)))
	{
		nMainFrame::LastError("Failed to get current display adapter mode.");
		return TraceRet(__FUNCTION__" Failed to get current display adapter mode.\n",false);
	}

	// The struct that describes our direct3d device
    ZeroMemory(&m_PresentParameters,sizeof(m_PresentParameters));
	
	m_Fullscreen = !nGetInstance()->GetCommandLineVar("-windowed",SETTINGS_WINDOWED).asBool();

    m_PresentParameters.Windowed               = !m_Fullscreen;
	m_PresentParameters.SwapEffect             = D3DSWAPEFFECT_DISCARD;
	m_PresentParameters.BackBufferFormat       = D3DFMT_X8R8G8B8;
    m_PresentParameters.EnableAutoDepthStencil = TRUE;
    m_PresentParameters.AutoDepthStencilFormat = D3DFMT_D24S8;

	// Check if we should use fsaa
	if(nGetInstance()->GetCommandLineVar("-fsaa",SETTINGS_FSAA).asBool())
	{
		unsigned long samples = 0;

		// Check if multisampling is supported and enable it if it is
		if(SUCCEEDED(m_pDirect3D->CheckDeviceMultiSampleType(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,m_PresentParameters.BackBufferFormat,!m_Fullscreen,D3DMULTISAMPLE_NONMASKABLE,&samples)))
		{
			m_PresentParameters.MultiSampleQuality	 = samples-1;
			m_PresentParameters.MultiSampleType		 = D3DMULTISAMPLE_NONMASKABLE;

			Trace(__FUNCTION__" Using %dx multisampling.\n",samples-1);
		}
	}

	// Check if we should display in fullscreen
	if(m_Fullscreen)
	{
		m_PresentParameters.BackBufferWidth	 = displayMode.Width;
		m_PresentParameters.BackBufferHeight = displayMode.Height;
	}
	else
	{
		nRect rect;
		GetClientRect(nGetInstance()->GetWindowHandle(),(LPRECT)&rect);
		
		m_PresentParameters.BackBufferWidth = rect.GetWidth();
		m_PresentParameters.BackBufferHeight = rect.GetHeight();
	}
	
	// Check if we shouldn't use vsync
	if(!nGetInstance()->GetCommandLineVar("-vsync",SETTINGS_VSYNC).asBool())
		m_PresentParameters.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;

	Trace(__FUNCTION__" Display mode %dx%d.\n",m_PresentParameters.BackBufferWidth,m_PresentParameters.BackBufferHeight);

	// Now create our direct3d device from the base direct3d object
	HRESULT hr = m_pDirect3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,nGetInstance()->GetWindowHandle(),D3DCREATE_SOFTWARE_VERTEXPROCESSING,&m_PresentParameters,&m_pDevice);
	if(FAILED(hr))
		return TraceRet(__FUNCTION__" Failed to create the device.\n",false);

	// Turn on color dithering
	hr = m_pDevice->SetRenderState(D3DRS_DITHERENABLE,TRUE);
	if(FAILED(hr))
		Trace(__FUNCTION__" Display adapter doesn't support color dithering, using default.\n");

	// Turn off culling
	m_pDevice->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE);

	// Enable anisotropic filtering if fsaa is enabled
	//if(flags & RECFLAG_FSAA)
	//	EnableAnisotropic(m_p3DDevice);

	// Create our line drawing object
	hr = D3DXCreateLine(m_pDevice, &m_pLine);
	if(FAILED(hr))
	{
		nMainFrame::LastError("Failed to create line drawing object.");
		return TraceRet(__FUNCTION__" Failed to create line drawing object.\n",false);
	}
	
	// Don't use gl lines
	m_pLine->SetGLLines(false);

	// Init our font
	hr = D3DXCreateFont(m_pDevice,SETTINGS_FONTHEIGHT,0,FW_BOLD,0,FALSE,DEFAULT_CHARSET,OUT_TT_PRECIS,6/*CLEARTYPE_QUALITY*/,DEFAULT_PITCH,SETTINGS_FONTNAME,&m_pFontBold);
	if(FAILED(hr))
	{
		nMainFrame::LastError("Failed to create font. Font not found?");
		return TraceRet(__FUNCTION__" Failed to create font. Font not found?",false);
	}

	// Init our thin font
	hr = D3DXCreateFont(m_pDevice,SETTINGS_FONTHEIGHT,0,FW_NORMAL,0,FALSE,DEFAULT_CHARSET,OUT_TT_PRECIS,6/*CLEARTYPE_QUALITY*/,DEFAULT_PITCH,SETTINGS_FONTNAME,&m_pFontNormal);
	if(FAILED(hr))
	{
		nMainFrame::LastError("Failed to create bold font. Font not found?");
		return TraceRet(__FUNCTION__" Failed to create bold font. Font not found?",false);
	}
	
	// Get the font sizes
	nRect fontSize;
	GetTextRect(GetBoldFont(),"str",&fontSize,NULL);
	m_BoldFontHeight = fontSize.GetHeight();
	GetTextRect(GetNormalFont(),"str",&fontSize,NULL);
	m_NormalFontHeight = fontSize.GetHeight();

	// Create our sprite drawing object
	hr = D3DXCreateSprite(m_pDevice, &m_pSprite);
	if(FAILED(hr))
	{
		nMainFrame::LastError("Failed to create sprite.");
		return TraceRet(__FUNCTION__" Failed to create sprite.\n",false);
	}

	// Turn on texture filtering
	m_pDevice->SetSamplerState(0,D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
	m_pDevice->SetSamplerState(0,D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
	m_pDevice->SetSamplerState(1,D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
	m_pDevice->SetSamplerState(1,D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
	m_pDevice->SetSamplerState(2,D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
	m_pDevice->SetSamplerState(2,D3DSAMP_MINFILTER, D3DTEXF_LINEAR);

	return true;
}
Exemple #6
0
/*******************************************************************
   ��	 ��: laijinhong
   ��	 Ȩ: �����¹����ɷ����޹�˾
   ��������: IC�����
   ��ڲ���:
   �� �� ֵ:
   ��	 ע: 
 ********************************************************************/
s32 OnIccCheck(ST_TRANSFLOW *pstTransFlow) {
    u8 temp[256], IcStatus[8];
    s32 ret = 0;
    u16 len = 0;

#if 0
    Trace("Lai","%%% IC card OnCheck\r\n");
    sdkIccOpenIcDev();
    SDK_ICC_PARAM stIccParam;
    memset(&stIccParam,0,sizeof(stIccParam));

    ret = sdkIccGetCardStatus(&stIccParam,5);
    if(SDK_OK==ret)
    {
        Trace("Lai","11111111 IC1 in slot");
    }
    else
        Trace("Lai","11111111 IC1 Not in slot %d\r\n",ret);

    sdkIccCloseIcDev();
#endif
#if 1
    memset(IcStatus, 0, sizeof(IcStatus));
    memset(temp, 0, sizeof(temp));

    sdkIccOpenIcDev();
    ret = sdkIccIsIccCardIn(5, temp, &len);//IC��

    if (SDK_OK == ret) {
        TraceHex("Lai", "IC card in slot\r\n", temp, len);
        IcStatus[0] = 0x01;
    }
    else if (SDK_TIME_OUT == ret) {
        Trace("Lai", "$$$ IC card timeout\r\n");
    }


#if 0 //del by sujianzhong 2015.01.13
    SDK_ICC_PARAM stIccParam;

    memset(temp, 0, sizeof(temp));
    memset(&stIccParam, 0, sizeof(SDK_ICC_PARAM));
    stIccParam.ucCardMode = SDK_ICC_ICC;
    stIccParam.eCardType = SDK_ICC_PSAM;
    stIccParam.ucCLType=0x01;
    stIccParam.ucSlotNo = 1;//PSAM1
    ret = sdkIccReset(&stIccParam, temp, &len);
    if(SDK_OK==ret)
    {
        TraceHex("Lai","sdkIccReset psam1 ret ok  \r\n",temp,len);
        IcStatus[3] = 0x01;
    }
    else
    {
        Trace("Lai","sdkIccReset psam1 ret %d  \r\n",ret);
    }

    memset(temp, 0, sizeof(temp));
    stIccParam.ucSlotNo = 2;//PSAM2
    ret = sdkIccReset(&stIccParam, temp, &len);
    if(SDK_OK==ret)
    {
        TraceHex("Lai","psam2 ret ok  \r\n",temp,len);
        IcStatus[4] = 0x01;
    }
    else
    {
        Trace("Lai","psam2 not found ret %d  \r\n",ret);
    }
#endif


    sdkIccOpenRfDev();//�ǽ�
    u8 cardtype = SDK_ICC_RFCARD_A | SDK_ICC_RFCARD_B | SDK_ICC_RFCARD_FELICA | SDK_ICC_RFCARD_24G;
    memset(temp, 0, sizeof(temp));
    ret = sdkIccRFQuery(cardtype, temp, 10);
    sdkIccCloseRfDev();

    if (ret > 0) {
        if (temp[0] == 0) {
            Trace("Lai", "@@@ sdkIccRFQuery found RF  ok, cardtype:%2x cardNum%d %d %d %d\r\n",
                  temp[2], temp[3], temp[4], temp[5], temp[6]);
            IcStatus[6] = 0x01;
        }
        else if (temp[0] == 2) {
            Trace("Lai", "@@@ sdkIccRFQuery no RF card  \r\n");
        }
    }
    else {
        Trace("Lai", "@@@ sdkIccRFQuery ret %d  \r\n", ret);
    }

    sdkIccCloseIcDev();

    pstTransFlow->usSendDataLen = 8;
    memcpy(pstTransFlow->heReceiveData, IcStatus, 8);        //0416Send==Recv
#endif
    return INS_SUC;
}
Exemple #7
0
/*******************************************************************
   ��	 ��: laijinhong
   ��	 Ȩ: �����¹����ɷ����޹�˾
   ��������: IC��ͨѶ
   ��ڲ���:
   �� �� ֵ:
   ��	 ע: 
 ********************************************************************/
s32 OnIccCommum(ST_TRANSFLOW *pstTransFlow) {
    Trace("Lai", "OnCommum\r\n");
    u8 cardType = pstTransFlow->heReceiveData[0];
    u16 len;
    u32 ret;
    //u8  tmpBuf[100]={0};
    //s32 outlen=0;
    SDK_ICC_PARAM stIccParam;
    u16 apdulen = 3;

    sdkBcdToU16(&len, &pstTransFlow->heReceiveData[1], 2);

    if (len + 3 != pstTransFlow->ReceiveDataLen) {
        sdkBcdToU16(&len, &pstTransFlow->heReceiveData[2], 2);
        apdulen = 4;
    }

    memset(&stIccParam, 0, sizeof(stIccParam));

    stIccParam.ucCardMode = SDK_ICC_ICC;
    stIccParam.ucCLType = 0x01;

    bool isRfDev = false;

    switch (cardType) {
        case 0:
            stIccParam.eCardType = SDK_ICC_CPU;// CPU���нӴ��ͷǽ�
            stIccParam.ucSlotNo = 0;
            break;
        case 3:
            stIccParam.eCardType = SDK_ICC_PSAM;
            stIccParam.ucSlotNo = 1;
            break;
        case 4:
            stIccParam.eCardType = SDK_ICC_PSAM;
            stIccParam.ucSlotNo = 2;
            break;
        case 6:
            isRfDev = true;
            stIccParam.ucCardMode = SDK_ICC_RF;
            stIccParam.eCardType = SDK_ICC_CPU;
            break;
        case 7:
            isRfDev = true;
            stIccParam.ucCardMode = SDK_ICC_RF;
            stIccParam.eCardType = SDK_ICC_MIFARE;
            break;
        default:
            return INS_PARAM_ERR;

    }
#if 0
    if(!isRfDev)
        sdkIccOpenIcDev();
    else
    {
        sdkIccOpenRfDev();
        u8 cardtype = SDK_ICC_RFCARD_A | SDK_ICC_RFCARD_B | SDK_ICC_RFCARD_FELICA | SDK_ICC_RFCARD_24G;
        memset(tmpBuf, 0, sizeof(tmpBuf));
        ret = sdkIccRFQuery (cardtype, tmpBuf, 10 );

        if(ret>0)
        {
            TraceHex("Lai","sdkIccRFQuery ret data:\r\n",tmpBuf,ret);
        }
        else
            return INS_OTHER_ERR;
    }

    //��Ҫ��λ,������������������ж��ڵ�һ�βŸ�λ�?
    //sdkIccResetIcc

    ret = sdkIccResetIcc(&stIccParam, tmpBuf, &outlen);//sdkIccReset
    if(ret!=SDK_OK)
    {
        Trace("Lai","$$$ sdkIccReset ret:%d\r\n",ret);

//		if(!isRfDev)
//			sdkIccCloseIcDev();
//		else
//			sdkIccCloseRfDev();

        return INS_OTHER_ERR;
    }
    else
    {
        Trace("Lai","sdkIccReset ok..................\r\n");
    }
#endif

    u16 lenOut = 510;
    u8 *pSend = &pstTransFlow->heReceiveData[0];          //0416Send==Recv
    ret = TransferApdu(&pstTransFlow->heReceiveData[apdulen], len, &pSend[2], &lenOut, &stIccParam);

//	if(!isRfDev)
//		sdkIccCloseIcDev();
//	else
//		sdkIccCloseRfDev();

    if (0x9000 == ret) {
        TraceHex("Lai", "apdu:\r\n", &pSend[2], lenOut);
    }
    else {
        Trace("Lai", "$$$ TransferApdu ret:%d\r\n", ret);
        return INS_OTHER_ERR;
    }

    sdkU16ToBcd(&pSend[0], lenOut, 2);

    pstTransFlow->usSendDataLen = lenOut + 2;
    return INS_SUC;
}
Exemple #8
0
int __cdecl main(int argc, char *argv[])
{

    HANDLE hFile = NULL;
    DWORD dwBytesWritten;
    const char* hugeStringTest =
        "1234567890123456789012345678901234567890";
    const char* szWritableFile = "writeable.txt";
    int i =0;
    if (0 != PAL_Initialize(argc,argv))
    {
        return FAIL;
    }

    /* create the test file         */
    hFile = CreateFile(szWritableFile, 
        GENERIC_WRITE,
        FILE_SHARE_WRITE,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    if(hFile == INVALID_HANDLE_VALUE)
    {
        Fail("WriteFile: ERROR -> Unable to create file \"%s\".\n", 
            szWritableFile);
    }   

    /* write 4000 000 chars to the file.*/
    for (i=0; i<100000;i++)
    {
        if( WriteFile(hFile,        /* HANDLE handle to file    */
            hugeStringTest,         /* data buffer              */
            strlen(hugeStringTest), /* number of bytes to write */
            &dwBytesWritten,        /* number of bytes written  */
            NULL)                   /* overlapped buffer        */
            ==0)
        {
            Trace("WriteFile: ERROR -> Unable to write to file error: %ld \n",
                GetLastError());
            CleanUp(hFile,szWritableFile);
            Fail("");

        }
    }

    if(!FlushFileBuffers(hFile))
    {
        Trace("WriteFile: ERROR -> Call to FlushFileBuffers failed"
              "error %ld \n",GetLastError());
        CleanUp(hFile,szWritableFile);        
        Fail("");
    }

    /* test if the size changed properly. */
    if(GetFileSize(hFile,NULL) != 4000000)
    {
        Trace("WriteFile: ERROR -> file size did not change properly"
            " after writing 4000 000 chars to it ( size= %u )\n",                   
            GetFileSize(hFile,NULL));
        CleanUp(hFile,szWritableFile); 
        Fail("");

    }

    if (!CleanUp(hFile,szWritableFile))
    {
        Fail("");
    }

    PAL_Terminate();
    return PASS;
}
Exemple #9
0
int __cdecl main(int argc, char *argv[])
{
    WORD VersionRequested = MAKEWORD(2,2);
    WSADATA WsaData;
    SOCKET aSocket;
    int err;
    int socketID;
    struct sockaddr_in mySockaddr;
    struct sockaddr mySocketaddrConnect;
    int nSocketaddrLength;
    int nBacklogNumber = 1;
    struct timeval waitTime;
    fd_set readFds;
    int socketFds;

    /*Initialize the PAL environment*/
    err = PAL_Initialize(argc, argv);
    if(0 != err)
    {
        return FAIL;
    }

    /*initialize to use winsock2.dll*/
    err = WSAStartup(VersionRequested,&WsaData);
    if ( err != 0 )
    {
        Fail("\nFailed to find a usable WinSock DLL!\n");
    }

    /* Confirm that the WinSock DLL supports 2.2.*/
    if ( LOBYTE( WsaData.wVersion ) != 2 ||
            HIBYTE( WsaData.wVersion ) != 2 )
    {
        Trace("\nFailed to find a usable WinSock DLL!\n");
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    /*create a stream socket in AF_INET domain*/
    socketID = socket(AF_INET,SOCK_STREAM,0);
    if(INVALID_SOCKET == socketID)
    {
        Trace("\nFailed to call socket API to create a stream socket!\n");
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    // Wait for 5 seconds for the client to connect.
    waitTime.tv_sec = 5L;
    waitTime.tv_usec = 0L;

    /*initialize the except socket set*/
    FD_ZERO(&readFds);


    /*prepare the sockaddr_in structure*/
    mySockaddr.sin_family = AF_INET;
    mySockaddr.sin_port = getRotorTestPort();
    mySockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
    memset( &(mySockaddr.sin_zero), 0, 8);

    /*bind the local address to the created socket*/
    err = bind(socketID, (struct sockaddr *)&mySockaddr,
                sizeof(struct sockaddr));
    if(SOCKET_ERROR == err)
    {
        Trace("\nFailed to call bind API bind a socket with "
            "local address!\n");
        err = closesocket(socketID);
        if(SOCKET_ERROR == err)
            {
            Trace("\nFailed to call closesocket API!\n");
        }
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }


    /*to setup the backlog number for a created socket*/
    err = listen(socketID,nBacklogNumber);
    if(SOCKET_ERROR == err)
    {
        Trace("\nFailed to call listen API to set backlog number!\n");
        err = closesocket(socketID);
        if(SOCKET_ERROR == err)
        {    
            Trace("\nFailed to call closesocket API!\n");
        }
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }
    /*add socket to readable socket set*/
    FD_SET(socketID,&readFds);
    /*mornitor the readable socket set*/
    socketFds = select(0,&readFds,NULL,NULL,&waitTime);

    if(SOCKET_ERROR == socketFds)
    {
        Trace("\nFailed to call select API to monitor readable "
            "socket set!\n");
        err = closesocket(socketID);
        if(SOCKET_ERROR == err)
            {
            Trace("\nFailed to call closesocket API!\n");
        }
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }
    if(0 == socketFds)
    {
        Trace("\nSelect waiting time is out!\n");
        err = closesocket(socketID);
        if(SOCKET_ERROR == err)
        {    
            Trace("\nFailed to call closesocket API!\n");
        }
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }


    nSocketaddrLength = sizeof(mySocketaddrConnect);

    /*accept a request from client*/
    aSocket = accept(socketID, (struct sockaddr*)&mySocketaddrConnect,
            &nSocketaddrLength);

    if(INVALID_SOCKET == aSocket)
    {
        Trace("\nFailed to call accept API to accept a client request!\n");
        err = closesocket(socketID);
        if(SOCKET_ERROR == err)
            {
            Trace("\nFailed to call closesocket API!\n");
            }
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }


    err = closesocket(aSocket);
    if(SOCKET_ERROR == err)
    {
        Trace("\nFailed to call closesocket API!\n");
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }
    
    err = closesocket(socketID);
    if(SOCKET_ERROR == err)
    {
        Trace("\nFailed to call closesocket API!\n");
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    err = WSACleanup();
    if(SOCKET_ERROR == err)
    {
        Fail("\nFailed to call WSACleanup API!\n");
    }

    PAL_Terminate();
    return PASS;
}
Exemple #10
0
void NaClEventLoop::wait(const EventTrigger &trigger, EventCallback *callback)
{
	Trace("NaClEventLoop.wait: callback=%p", callback);

	trigger.completion.reset(&m_instance, callback);
}
Exemple #11
0
/**
 * main
 * 
 * executable entry point
 */
INT __cdecl main(INT argc, CHAR **argv)
{
    int     i;
    int     err;
    struct  sockaddr_in mySockaddr;
    WSADATA wsaData;    

    int byteCounter;

    /* Sockets descriptor */
    const int numSockets = 1;    /* number of sockets used in this test */

    SOCKET testSockets[1];    

    
    /* Variables for WSASend */

    WSABUF wsaSendBuf;
    DWORD  dwNbrOfByteSent;
    DWORD  dwNbrOfBuf  = 1;
    DWORD  dwSendFlags = 0;
    
    unsigned char   sendBuffer[255];
    

    WSAOVERLAPPED wsaOverlapped;
    

    /* Socket DLL version */
    const WORD wVersionRequested = MAKEWORD(2,2);

    HANDLE  writeEvent;
    DWORD   waitResult;

    /* Sockets initialization to INVALID_SOCKET */
    for( i = 0; i < numSockets; i++ )
    {
        testSockets[i] = INVALID_SOCKET;
    }

    /* PAL initialization */
    if( PAL_Initialize(argc, argv) != 0 )
    {
        return FAIL;
    }

    /* Initialize to use winsock2.dll */
    err = WSAStartup( wVersionRequested,
                      &wsaData);

    if(err != 0)
    {
        Fail( "ERROR: Unexpected failure: "
              "WSAStartup(%i) "
              "returned %d\n",
              wVersionRequested, 
              GetLastError() );
    }

    /* Confirm that the WinSock DLL supports 2.2.
       Note that if the DLL supports versions greater    
       than 2.2 in addition to 2.2, it will still return
       2.2 in wVersion since that is the version we      
       requested.                                        
    */
    if ( wsaData.wVersion != wVersionRequested ) 
    {
         
        Trace("ERROR: Unexpected failure "
              "to find a usable version of WinSock DLL\n");

        /* Do some cleanup */
        DoWSATestCleanup( 0, 0);

        Fail("");
    }

    /* create an overlapped stream socket in AF_INET domain */

    testSockets[0] = WSASocketA( AF_INET, 
                                 SOCK_STREAM, 
                                 IPPROTO_TCP,
                                 NULL, 
                                 0, 
                                 WSA_FLAG_OVERLAPPED ); 


    if( testSockets[0] == INVALID_SOCKET )

    {
        Trace("ERROR: Unexpected failure: "
              "WSASocketA"
              "(AF_INET,SOCK_STREAM,IPPROTO_TCP,NULL,0,WSA_FLAG_OVERLAPPED)) "
              " returned %d\n",
              GetLastError());

        /* Do some cleanup */
        DoWSATestCleanup( 0, 0);

        Fail("");
    }
    
    /* prepare the sockaddr_in structure */
    mySockaddr.sin_family           = AF_INET;
    mySockaddr.sin_port             = getRotorTestPort();
    mySockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");

    memset( &(mySockaddr.sin_zero), 0, 8);

    /* connect to a server */
    err = connect( testSockets[0], 
                   (struct sockaddr *)&mySockaddr,
                   sizeof(struct sockaddr));

    if( err == SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure: "
              "connect() socket with local server "
              "returned %d\n",
              GetLastError());

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    /* fill the sent buffer with value */
    for (i=0;i<255;i++)
    {
        sendBuffer[i]= i;
    }           

    /* create events */
    writeEvent = CreateEvent( NULL, /* no security */
                             FALSE, /* reset type */
                             FALSE, /* initial state */
                             NULL );  /* object name */
            
    if( writeEvent == NULL )
    {
        Trace("ERROR: Unexpected failure: "
              "CreateEvent() "
              "returned %d\n",
              GetLastError());

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }
    
    
    /* Set the WSABUF structure */
    wsaSendBuf.len = 255;        
    wsaSendBuf.buf = sendBuffer;    
    
    byteCounter = 0;
    
    /*  This loop send a 400 buffer to the server.
        It then shutdown the connection.
    */
    for(i=0;i<400;i++)
    {
        /* Initialize the WSAOVERLAPPED to 0 */
        memset(&wsaOverlapped, 0, sizeof(WSAOVERLAPPED)); 

        wsaOverlapped.hEvent = writeEvent;        

        /* Send some data */
        err = WSASend( testSockets[0],
                       &wsaSendBuf,
                       dwNbrOfBuf,
                       &dwNbrOfByteSent,
                       dwSendFlags,
                       &wsaOverlapped,
                       0 );

        
        if(err == SOCKET_ERROR )
        {
            if(GetLastError()!=WSA_IO_PENDING)
            {
                Trace("ERROR: Unexpected failure: "
                      "WSASend() "
                      "returned %d\n",
                      GetLastError());

                CloseHandle(writeEvent);

                /* Do some cleanup */
                DoWSATestCleanup( testSockets,
                                  numSockets );



                Fail("");
            }

            /* Wait 10 seconds for WriteEvent to be signaled 
               for pending operation
            */
            waitResult = WaitForSingleObject( writeEvent, 
                                              10000 );    
 
            if (waitResult!=WAIT_OBJECT_0)
            {   
                Trace("ERROR: Unexpected failure: "
                      "WaitForSingleObject has timed out \n");

                CloseHandle(writeEvent);
        
                /* Do some cleanup */
                DoWSATestCleanup( testSockets,
                                  numSockets );

                Fail("");
            }  

        }        
        
        

        /* keep track of the number of bytes sent */
        byteCounter += wsaOverlapped.InternalHigh;
 
        /* Verify that the number of bytes sent are the number of byte
           specified in the wsaBuf structure 
        */
        if(wsaSendBuf.len!=wsaOverlapped.InternalHigh)
        {            
            Trace("WSASend has not send the number of byte requested "
                  "wsaSendBuf.len = %d while "
                  "wsaOverlapped.InternalHigh = % d",
                  wsaSendBuf.len, wsaOverlapped.InternalHigh);

            CloseHandle(writeEvent);

            Fail("");
        }        
    }

    /* Disconnect the socket */
    err = shutdown( testSockets[0], 
                    SD_BOTH);
    if (err == SOCKET_ERROR)
    {
        Trace("ERROR: Unexpected failure: "
                "shutdown() socket with local server "
                "returned %d\n",
                GetLastError());

        CloseHandle(writeEvent);

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                            numSockets );

        Fail("");
    }   
         
    /* close the event */
    if( CloseHandle(writeEvent) == 0 )
    {
        Trace("ERROR: Unexpected failure: "
              "CloseHandle() "
              "returned %d\n",
              GetLastError());
    
        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );


        Fail("");
    }   


    /* Expected number of bytes sent is 102000 */
    if(byteCounter!=102000)
    {
        Trace("Invalid number of byte sent to the server");
        
        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }    

    /* Do some cleanup */
    DoWSATestCleanup( testSockets,
                      numSockets );

    PAL_Terminate();
    return PASS;
}
Exemple #12
0
    virtual void externalTransition(const vd::ExternalEventList &events,
                                    vd::Time time) override
    {
        double val, shifting_factor;
        int cnt;

        if (events.size() > 1)
            Trace(context(), 6, "Warning: %s got multiple events at date: %f\n",
                  getModelName().c_str(), time);

        auto it = events.begin();
        while (it != events.end()) {
            val = it->getMap().getDouble("d_val");
            if (INIT == m_state) {
                init_step_number_and_offset(val);
                update_thresholds();
                m_state = RESPONSE;
            } else {
                cnt = 0;
                if ((val > m_upthreshold) || (val < m_downthreshold))
                    Trace(context(), 6, "%s: treating out of bonds val: %f "
                          "(quantizer interval : [%f,%f] at date: %f",
                          getModelName().c_str(), val, m_downthreshold,
                          m_upthreshold, time);

                while ((val >= m_upthreshold) || (val <= m_downthreshold)) {
                    cnt++;
                    if (val >= m_upthreshold) {
                        m_step_number++;
                    } else {
                        m_step_number--;
                    }
                    switch (m_adapt_state) {
                    case IMPOSSIBLE:
                        update_thresholds();
                        break;
                    case POSSIBLE:
                        if (val >= m_upthreshold) {
                            store_change(m_step_size, time);
                        } else {
                            store_change(-m_step_size, time);
                        }
                        shifting_factor = shift_quanta();
                        if (0 > shifting_factor)
                            throw vu::ModellingError(
                                "Bad shifting value (value : %f, "
                                "should be strictly positive)\n",
                                 shifting_factor);
                        if (1 < shifting_factor)
                            throw vu::ModellingError(
                                "Bad shifting value ( value : %f, "
                                "should be less than 1)\n",
                                shifting_factor);;
                        if ((0 != shifting_factor) && (1 != shifting_factor)) {
                            if (val >= m_upthreshold) {
                                update_thresholds(shifting_factor, DOWN);
                            } else {
                                update_thresholds(shifting_factor, UP);
                            }
                            Trace(context(), 6,
                                  "Quantifier %s new quantas while treating new val %f at date %f",
                                  getModelName().c_str(), val, time);

                            Trace(context(), 6,
                                  "Quantizer interval:  [%f, %f], amplitude: %f "
                                  "(default amplitude: %f)", m_downthreshold,
                                  m_upthreshold, (m_upthreshold - m_downthreshold),
                                  (2 * m_step_size));

                            Trace(context(), 6,
                                  "Quantifier %s shifting : %f",
                                  getModelName().c_str(), shifting_factor);

                            m_adapt_state = DONE;
                        } else {
                            update_thresholds();
                        }
                        break;
                    case DONE: // equiv to reinit
                        init_step_number_and_offset(val);
                        // archive.resize(0);
                        m_adapt_state = POSSIBLE;
                        update_thresholds();
                        break;
                    }
                }

                if (cnt > 1)
                    Trace(context(), 6, "Warning : in %s multiple quanta change"
                          " at date : %f %d\n", getModelName().c_str(), time, cnt);

                if (0 == cnt)
                    Trace(context(), 6, "Warning : in %s useless ext transition"
                          "call: no quanta change! input val %f (quantizer "
                          "interval : [%f,%f] at date %f\n", getModelName().c_str(),
                          val, m_downthreshold, m_upthreshold, time);
            }
            ++it;
        }
        m_state = RESPONSE;
    }
Exemple #13
0
int __cdecl main (int argc, char **argv)
{
    HANDLE hThread = NULL;
    int ret;
    int i,j;
    BOOL bResult = FAIL;

    PAPCFUNC APCFuncs[] =
    {
        APCFuncA,
        APCFuncB,
        APCFuncC,
        APCFuncD,
    };

    /* initialize the PAL */
    if (0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }

    ResultPtr = ResultBuffer;

    /* create a pair of synchronization events to coordinate our threads */
    hSyncEvent1 = CreateEvent( NULL, FALSE, FALSE, NULL );
    if( hSyncEvent1 == NULL )
    {
        Trace( "ERROR:%lu:CreateEvent() call failed\n", GetLastError() );
        goto cleanup;
    }

    hSyncEvent2 = CreateEvent( NULL, FALSE, FALSE, NULL );
    if( hSyncEvent2 == NULL )
    {
        Trace( "ERROR:%lu:CreateEvent() call failed\n", GetLastError() );
        goto cleanup;
    }

    /* create a child thread which will call SleepEx */
    hThread = CreateThread( NULL,
                            0,
                            (LPTHREAD_START_ROUTINE)SleeperProc,
                            0,
                            0,
                            &ChildThread);

    if( hThread == NULL )
    {
        Trace( "ERROR:%lu:CreateThread() call failed\n",
            GetLastError());
        goto cleanup;
    }


    /* wait on our synchronization event to ensure the thread is running */
    ret = WaitForSingleObject( hSyncEvent1, 20000 );
    if( ret != WAIT_OBJECT_0 )
    {
        Trace( "ERROR:WaitForSingleObject() returned %lu, "
                "expected WAIT_OBJECT_0\n",
                ret );
        goto cleanup;
    }


    /* queue our user APC functions on the thread */
    for (i=0; i<4; i++)
    {
        for (j=0; j<sizeof(APCFuncs)/sizeof(APCFuncs[0]); j++)
        {
            ret = QueueUserAPC(APCFuncs[j], hThread, '0' + i);
            if (ret == 0)
            {
                Trace( "ERROR:%lu:QueueUserAPC() call failed\n",
                    GetLastError());
                goto cleanup;
            }
        }
    }

    /* signal the child thread to continue */
    if( ! SetEvent( hSyncEvent2 ) )
    {
        Trace( "ERROR:%lu:SetEvent() call failed\n", GetLastError() );
        goto cleanup;
    }


    /* wait on our synchronization event to ensure the other thread is done */
    ret = WaitForSingleObject( hSyncEvent1, 20000 );
    if( ret != WAIT_OBJECT_0 )
    {
        Trace( "ERROR:WaitForSingleObject() returned %lu, "
                "expected WAIT_OBJECT_0\n",
                ret );
        goto cleanup;
    }


    /* check that the thread executed successfully */
    if( bThreadResult == FAIL )
    {
        goto cleanup;
    }


    /* check the result buffer */
    if (strcmp(ExpectedResults, ResultBuffer) != 0)
    {
        Trace( "FAIL:Expected the APC function calls to produce a result of "
            " \"%s\", got \"%s\"\n",
            ExpectedResults,
            ResultBuffer );
        goto cleanup;
    }

    /* success if we get here */
    bResult = PASS;

cleanup:
    /* wait for the other thread to finish */
    if( hThread != NULL )
    {
        ret = WaitForSingleObject( hThread, INFINITE );
        if (ret == WAIT_FAILED)
        {
            Trace( "ERROR:%lu:WaitForSingleObject() returned %lu, "
                    "expected WAIT_OBJECT_0\n",
                    ret );
            bResult = FAIL;
        }
    }

    /* close our synchronization handles */
    if( hSyncEvent1 != NULL )
    {
        if( ! CloseHandle( hSyncEvent1 ) )
        {
            Trace( "ERROR:%lu:CloseHandle() call failed\n", GetLastError() );
            bResult = FAIL;
        }
    }

    if( hSyncEvent2 != NULL )
    {
        if( ! CloseHandle( hSyncEvent2 ) )
        {
            Trace( "ERROR:%lu:CloseHandle() call failed\n", GetLastError() );
            bResult = FAIL;
        }
    }

    if( bResult == FAIL )
    {
        Fail( "test failed\n" );
    }

    /* terminate the PAL */
    PAL_Terminate();

    /* return success */
    return PASS;
}
Exemple #14
0
void  PALAPI Run_Thread (LPVOID lpParam)
{
    unsigned int i = 0;
    DWORD dwWaitResult; 

    struct statistics stats;
    DWORD dwStartTime;

	stats.relationId = RELATION_ID;
    stats.processId = USE_PROCESS_COUNT;
    stats.operationsFailed = 0;
    stats.operationsPassed = 0;
    stats.operationsTotal  = 0;
    stats.operationTime    = 0;

    int Id=(int)lpParam;
    
    dwWaitResult = WaitForSingleObject( 
                            StartTestsEvHandle,   // handle to mutex
                            TIMEOUT);  

    if(dwWaitResult != WAIT_OBJECT_0)
    {
        Trace("Error while waiting for StartTest [email protected] thread %d\n", Id);
        testStatus = FAIL;
    }

    dwStartTime = GetTickCount();

    for( i = 0; i < REPEAT_COUNT; i++ )
    {
        dwWaitResult = WaitForSingleObject( 
                            hMutexHandle,   // handle to mutex
                            TIMEOUT);  

        if(dwWaitResult != WAIT_OBJECT_0)
        {
//            Trace("Error while waiting for onject @ thread %d, # iter %d, Error Returned [%d]\n", Id, i, GetLastError());
            stats.operationsFailed += 1;
            stats.operationsTotal  += 1;
            testStatus = FAIL;
            continue;
        }
        if (! ReleaseMutex(hMutexHandle)) 
        { 
            // Deal with error.
//            Trace("Error while releasing mutex @ thread %d # iter %d\n", Id, i);
            stats.operationsFailed += 1;
            stats.operationsTotal  += 1;
            // Probably need to have while true loop to attempt to release mutex...
            testStatus = FAIL;
            continue;
        } 
    
        stats.operationsTotal  += 1;
        stats.operationsPassed += 1;  
//        Trace("Successs while releasing mutex @ iteration %d -> thread %d -> Process count %d\n", i, Id, USE_PROCESS_COUNT);
        
    }
    stats.operationTime = GetTimeDiff(dwStartTime); 
    if(resultBuffer->LogResult(Id, (char *)&stats))
    {
        Fail("Error:%d: while writing to shared memory, Thread Id is[%d] and Process id is [%d]\n", GetLastError(), Id, USE_PROCESS_COUNT);
    }
}
Exemple #15
0
// Initialize our rendering device
int GLDriver::initialize(IWindow* pWindow)
{
	HWND hwnd;

	Trace("Initializing OpenGL graphics driver");

	hwnd = static_cast< HWND > (pWindow->getWindowHandle());
	
	// Create an OpenGL pixel format descriptor
	PIXELFORMATDESCRIPTOR pfd =
	{	
		sizeof(PIXELFORMATDESCRIPTOR),				// Size Of This Pixel Format Descriptor
		1,											// Version Number
		PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,	// Format Must Support OpenGL and double buffering
		PFD_TYPE_RGBA,								// Request An RGBA Format
		pWindow->getBpp(),							// Select Our Color Depth
		0, 0, 0, 0, 0, 0,							// Color Bits Ignored
		0,											// No Alpha Buffer
		0,											// Shift Bit Ignored
		0,											// No Accumulation Buffer
		0, 0, 0, 0,									// Accumulation Bits Ignored
		16,											// 16Bit Z-Buffer (Depth Buffer)  
		0,											// No Stencil Buffer
		0,											// No Auxiliary Buffer
		PFD_MAIN_PLANE,								// Main Drawing Layer
		0,											// Reserved
		0, 0, 0										// Layer Masks Ignored
	};
	

	// Initialise stuff, and check for errors
	
	Trace("Acquiring device context");
	if (!(hdc = GetDC(hwnd)))
		CEngine::CriticalError("Unable to create GL device context!");

	Trace("Finding pixel format");
	if (!(pixelFormat = ChoosePixelFormat(hdc, &pfd)))
		CEngine::CriticalError("Unable to find a pixel format!");
	
	Trace("Setting pixel format");
	if(!SetPixelFormat(hdc, pixelFormat, &pfd))
		CEngine::CriticalError("Unable to set the pixel format!");
	
	Trace("Acquiring rendering context");
	if(!(hrc = wglCreateContext(hdc)))
		CEngine::CriticalError("Unable to create GL rendering context!");
	
	Trace("Setting current GL window");
	if(!wglMakeCurrent(hdc, hrc))
		CEngine::CriticalError("Unable to activate GL rendering context!");
	
	resize(pWindow->getWidth(), pWindow->getHeight());

	// Set up initial gl parameters
	glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
	glClearDepth(1.0f);
	glEnable(GL_DEPTH_TEST);
	glClearColor(0.0,0.0,0.0,0.0);
	glDepthFunc(GL_LEQUAL);
	glEnable(GL_TEXTURE_2D);
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	glEnableClientState(GL_VERTEX_ARRAY);
	
	// Grab GL vendor information
	Trace("Getting OpenGL driver info ...");
	char* str;

	str = (char*)glGetString(GL_VENDOR);
	vendor.assign(str);
	Trace("OpenGL Vendor: %s", vendor.c_str());

	str = (char*)glGetString(GL_RENDERER);
	renderer.assign(str);
	Trace("OpenGL Renderer: %s", renderer.c_str());

	str = (char*)glGetString(GL_VERSION);
	version.assign(str);
	Trace("OpenGL Version: %s", version.c_str());

	str = (char*)glGetString(GL_EXTENSIONS);
	extensions.assign(str);
	
	// Replace all spaces with newlines
	for(int i = 0; i < extensions.length(); ++i)
	{
		if(extensions[i] == ' ')
			extensions[i] = '\n';
	}


	// Acquire pointer to extension functions

	// Multitexturing
	glActiveTextureARB = (PFNGLACTIVETEXTUREARBPROC)wglGetProcAddress("glActiveTextureARB");
	glClientActiveTextureARB = (PFNGLCLIENTACTIVETEXTUREARBPROC)wglGetProcAddress("glClientActiveTextureARB");
	glMultiTexCoord2fARB = (PFNGLMULTITEXCOORD2FARBPROC)wglGetProcAddress("glMultiTexCoord2fARB");
	
	// CVAs
	glLockArraysEXT = (PFNGLLOCKARRAYSEXTPROC)wglGetProcAddress("glLockArraysEXT");
	glUnlockArraysEXT = (PFNGLUNLOCKARRAYSEXTPROC)wglGetProcAddress("glUnlockArraysEXT");

	glFogCoordfEXT = (PFNGLFOGCOORDFEXTPROC) wglGetProcAddress("glFogCoordfEXT");

#if 0
	glFlushVertexArrayRangeNV = (PFNGLFLUSHVERTEXARRAYRANGENVPROC)wglGetProcAddress("glFlushVertexArrayRangeNV");
	glVertexArrayRangeNV = (PFNGLVERTEXARRAYRANGENVPROC)wglGetProcAddress("glVertexArrayRangeNV");
	wglAllocateMemoryNV = (PFNWGLALLOCATEMEMORYNVPROC)wglGetProcAddress("wglAllocateMemoryNV");
    wglFreeMemoryNV = (PFNWGLFREEMEMORYNVPROC)wglGetProcAddress("wglFreeMemoryNV");

	mem = NULL;
	mem = (unsigned char*)wglAllocateMemoryNV(1024 * 1024 * 5, 0.2f, 0.0f, 0.7f);
	
	if(!mem)
		CEngine::CriticalError("Can't allocate memory");
	
	glVertexArrayRangeNV(1024 * 1024 * 5, mem);
	glEnableClientState(GL_VERTEX_ARRAY_RANGE_NV);
#endif


	// Set up hardware gamma, if we are using it
	if(Config::getBoolValue("UseHardwareGamma"))
	{

		GetDeviceGammaRamp(hdc, &oldGamma);
		float gamma = 2.0f;

		for(int i = 0; i < 3; i++)
		{
			for(int j = 0;j < 256; j++)
			{
				DWORD d = oldGamma[j][i] * gamma;
				if(d > 65535)
					d = 65535;
				newGamma[j][i] = d;
			}
		}

		SetDeviceGammaRamp(hdc, &newGamma);
	}
	
	// Set up the font
	HFONT	oldfont;

	fontDispListBase = glGenLists(FONT_DISPLAY_LIST_SIZE);

	font = CreateFont(-12, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE, ANSI_CHARSET, OUT_TT_PRECIS, 
						CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, FF_DONTCARE | DEFAULT_PITCH, "Courier New");

	oldfont = (HFONT)SelectObject(hdc, font);
	wglUseFontBitmaps(hdc, 32, FONT_DISPLAY_LIST_SIZE, fontDispListBase);
	SelectObject(hdc, oldfont);
	DeleteObject(font);

	return 0;
}
Exemple #16
0
int __cdecl main(int argc, char *argv[]) 
{
    LPVOID TestingPointer = NULL;
    BOOL ResultValue = 0;
  
    /*
     * Initialize the PAL and return FAILURE if this fails
     */

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }
  
    TestingPointer = malloc(MEMORY_AMOUNT); 
    if ( TestingPointer == NULL )
    {
        Fail("ERROR: Failed to allocate memory for TestingPointer pointer. "
           "Can't properly exec test case without this.\n");
    }
 

    /* This should be readable, and return 0 */
    ResultValue = IsBadReadPtr(TestingPointer,MEMORY_AMOUNT);
    if(ResultValue != 0) 
    {
        free(TestingPointer);

        Fail("ERROR: The function returned %d instead of 0, when pointing "
             "at readable memory.\n",ResultValue);    
    }

    /* If we pass 0, the result should be 0 as well */
    ResultValue = IsBadReadPtr(TestingPointer,0);
    if(ResultValue != 0) 
    {
        free(TestingPointer);

        Fail("ERROR: The function returned %d instead of 0, when the "
             "function was passed a range of 0 bytes.\n",ResultValue);
    }
    free(TestingPointer); /* we are done with this */

    /* create a READABLE address */
    TestingPointer =  VirtualAlloc(
        NULL,               /* system selects address */
        80,                 /* size of allocation*/
        MEM_COMMIT,         /* commit */
        PAGE_READONLY);     /* protection = read only */

    if (TestingPointer == NULL )
    {
        Fail("ERROR: call to VirtualAlloc failed\n");
    }

    ResultValue = IsBadReadPtr(TestingPointer,16);
    if(ResultValue != 0)    /* if no access */
    {
        if(!VirtualFree(TestingPointer, 0, MEM_RELEASE))
        {
            Trace("ERROR: Call to VirtualFree failed with error"
                " code[ %u ]\n",GetLastError());  
        }

        Fail("ERROR: The function returned %d instead of 1 when checking "
            "on unreadable memory.\n",ResultValue);
    }

    if(!VirtualFree(TestingPointer,0, MEM_RELEASE))
    {
        Fail("ERROR: Call to VirtualFree failed with error"
            " code[ %u ]\n",GetLastError());  
    }

    /* create an unreadable address */
    TestingPointer =  VirtualAlloc(
        NULL,                 /* system selects address */
        80,                   /* size of allocation */
        MEM_COMMIT,           /* commit */
        PAGE_NOACCESS);       /* protection = no access */

    if (TestingPointer == NULL )
    {
        Fail("ERROR: call to VirtualAlloc failed\n");
    }

    ResultValue = IsBadReadPtr(TestingPointer,16);

    if(ResultValue == 0) /* if access */ 
    {
        if(!VirtualFree(TestingPointer, 0, MEM_RELEASE))
        {
            Trace("ERROR: Call to VirtualFree failed with error"
                " code[ %u ]\n",GetLastError());  
        }

        Fail("ERROR: The function returned %d instead of 1 when checking "
             "on unreadable memory.\n",ResultValue);
    }

    if(!VirtualFree(TestingPointer,0, MEM_RELEASE))
    {
        Fail("ERROR: Call to VirtualFree failed with error"
            " code[ %u ]\n",GetLastError());  
    }


    /* This should be unreadable and return 1 */
    ResultValue = IsBadReadPtr(NULL,16);
    if(ResultValue != 1) 
    {
        Fail("ERROR: The function returned %d instead of 1 when checking "
             "to see if NULL was readable.\n",ResultValue);
    }

    PAL_Terminate();
    return PASS;
}
Exemple #17
0
/*******************************************************************
   ��	 ��: laijinhong
   ��	 Ȩ: �����¹����ɷ����޹�˾
   ��������: �ϵ�
   ��ڲ���:
   �� �� ֵ:
   ��	 ע: 
 ********************************************************************/
s32 OnIccPowerOn(ST_TRANSFLOW *pstTransFlow) {
    //Trace("Lai","OnPowerOn\r\n");
    u8 cardSlot, cardType;
    u8 temp[64];
    s32 ret;
    s32 len;
    bool isRFCard = false;
    SDK_ICC_PARAM *stIccParam;

    u8 *pSend = &pstTransFlow->heReceiveData[0];          //0416Send==Recv

    cardSlot = pstTransFlow->heReceiveData[0];
    cardType = pstTransFlow->heReceiveData[1];

    memset(temp, 0, sizeof(temp));
    stIccParam = sdkGetMem(sizeof(SDK_ICC_PARAM));
    if (stIccParam == NULL) {
        return INS_OTHER_ERR;
    }
    memset(stIccParam, 0, sizeof(SDK_ICC_PARAM));
    stIccParam->ucCardMode = SDK_ICC_ICC;
    stIccParam->ucCLType = 0x01;
    switch (cardSlot) {
        case 0:
            stIccParam->eCardType = SDK_ICC_CPU;// CPU���нӴ��ͷǽ�
            stIccParam->ucSlotNo = 0;
            break;
        case 3:
            stIccParam->eCardType = SDK_ICC_PSAM;
            stIccParam->ucSlotNo = 1;
            break;
        case 4:
            stIccParam->eCardType = SDK_ICC_PSAM;
            stIccParam->ucSlotNo = 2;
            break;
        case 6:
            isRFCard = true;
            stIccParam->ucSlotNo = 3;//���ڷǽ� ������
            stIccParam->ucCardMode = SDK_ICC_RF;
            if (cardType == 0)
                stIccParam->eCardType = SDK_ICC_CPU;
            else if (cardType == 1)
                stIccParam->eCardType = SDK_ICC_MIFARE;
            break;
        default:
            sdkFreeMem(stIccParam);
            return INS_PARAM_ERR;
    }


    if (!isRFCard) {
        sdkIccOpenIcDev();
        ret = sdkIccReset(stIccParam, temp, &len);

        if (SDK_OK == ret) {
            //TraceHex("Lai","sdkIccReset ret ok  \r\n",temp,len);
            if (len > 200)
                len = 200;

            sdkU16ToBcd(&pSend[0], len, 2);
            memcpy(&pSend[2], temp, len);
            pstTransFlow->usSendDataLen = len + 2;
        }
        else {
            Trace("Lai", "sdkIccReset fail:%d\r\n", ret);
        }
    }
    else {
        sdkIccOpenRfDev();//�ǽ�
        memset(temp, 0, sizeof(temp));
        //ret = sdkIccRFQuery (cardtype, temp, 5);
        memset(stIccParam, 0, sizeof(SDK_ICC_PARAM));
        SDK_ICC_TRADE_PARAM stIccTradeParam;

        if (sdkIccTransInit(&stIccTradeParam) != SDK_OK)//IC��������ʼ��
        {
            Trace("Lai", "$$$$$ sdkIccTransInit fail\r\n");
            sdkFreeMem(stIccParam);
            return INS_OTHER_ERR;
        }

        ret = sdkIccPowerOnAndSeek(&stIccTradeParam, stIccParam, temp);
        if (SDK_OK != ret) {
            Trace("Lai", "$$$$$ sdkIccPowerOnAndSeek fail:%d\r\n", ret);
            sdkFreeMem(stIccParam);
            return INS_OTHER_ERR;
        }

        ret = sdkIccReset(stIccParam, temp, &len);
        if (SDK_OK == ret) {
            len = temp[0];
            if (len > 0) {
                TraceHex("Lai", "sdkIccPowerOnAndSeek\r\n", temp, len + 1);
                sdkU16ToBcd(&pSend[0], len, 2);
                memcpy(&pSend[2], &temp[1], len);
                pstTransFlow->usSendDataLen = len + 2;
            }
            else {
                Trace("Lai", "rf reset len=0\r\n");
                sdkU16ToBcd(&pSend[0], 0, 2);
                pstTransFlow->usSendDataLen = 2;
                sdkFreeMem(stIccParam);
                return INS_SUC;
            }
        }
        else {
            Trace("Lai", "$$$$$ sdkIccReset fail:%d\r\n", ret);
            sdkFreeMem(stIccParam);
            return INS_OTHER_ERR;
        }
    }
    sdkFreeMem(stIccParam);
    return INS_SUC;
}
Exemple #18
0
int __cdecl main(int argc, char *argv[]) 
{
    
    LONG TheReturn;
  
    LONG *ptrValue = NULL;
    /*
     * Initialize the PAL and return FAILURE if this fails
     */

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }



#if defined(BIT64)
    ptrValue = (LONG *) malloc(sizeof(LONG));

    if(ptrValue == NULL)
    {
		Fail("Error:%d:Malloc failed for ptrValue\n", GetLastError()); 
	}

	*ptrValue = (LONG) 0;

    TheReturn = InterlockedExchangeAdd( ptrValue, (LONG) 5);
    

    /* Added, it should be 5  now */
    if(*ptrValue != 5) 
    {
        
      Trace("ERROR: After an add operation, the value should be 5, "
             "but it is really %d.", *ptrValue);
      free(ptrValue);
      Fail("");
    }
  
    /* Check to make sure the function returns the original value (5 in this case) */
    if(TheReturn != 0) 
    {
        Trace("ERROR: The function should have returned the new value of %d "
             "but instead returned %d.", *ptrValue, TheReturn);    
        free(ptrValue);
		Fail("");
    }

    TheReturn = InterlockedExchangeAdd( ptrValue, (LONG) 1);


    /* Added twice, it should be 6  now */
    if(*ptrValue != 6) 
    {
        
      Trace("ERROR: After having two add operations, the value should be 6, "
             "but it is really %d.", *ptrValue);
      free(ptrValue);
      Fail("");
    }
  
    /* Check to make sure the function returns the original value (5 in this case) */
    if(TheReturn != 5) 
    {
        Trace("ERROR: The function should have returned the new value of %d "
             "but instead returned %d.", *ptrValue, TheReturn);    
        free(ptrValue);
		Fail("");
    }
    
    free(ptrValue);
#endif
    PAL_Terminate();
    return PASS; 
} 
Exemple #19
0
/*******************************************************************
   ��	 ��: 
   ��	 Ȩ: �����¹����ɷ����޹�˾
   ��������: ����APDU
   ��ڲ���: �������� ����, ������� ����, IC������ز���
   �� �� ֵ:
   ��	 ע: 
 ********************************************************************/
u32 TransferApdu(u8 *datain, u16 inlen, u8 *dataout, u16 *outlen, SDK_ICC_PARAM *pstIccParam) {
    TraceHex("Lai", "TransferApdu\r\n", datain, inlen);

    SDK_ICC_APDU_SEND pstApduSend;
    SDK_ICC_APDU_RESP pstApduResp;
    s32 rlt;
    u8 *temp;
    u16 templen;

    temp = (u8 *) sdkGetMem(512);

    if (temp == NULL) {
        return 0x8E03;
    }
    memset(temp, 0, 512);
    memset(&pstApduSend, 0, sizeof(pstApduSend));
    memset(&pstApduResp, 0, sizeof(pstApduResp));

    if (inlen < 5) {
        sdkFreeMem(temp);
        return 0x8E03;
    }
    else if (inlen == 5) {
        memcpy(pstApduSend.Command, datain, 4);
        pstApduSend.Le = datain[4];
    }
    else {
        memcpy(pstApduSend.Command, datain, 4);
        pstApduSend.Lc = datain[4];

        if (pstApduSend.Lc > inlen - 5) {
            sdkFreeMem(temp);
            return 0x8E03;
        }
        else if (pstApduSend.Lc == inlen - 5) {
            memcpy(pstApduSend.DataIn, datain + 5, pstApduSend.Lc);
        }
        else {
            memcpy(pstApduSend.DataIn, datain + 5, pstApduSend.Lc);
            pstApduSend.Le = datain[inlen - 1];
        }
    }
    rlt = sdkIccDealCardData(pstIccParam, &pstApduSend, &pstApduResp);

    if (rlt == SDK_OK) {
        memcpy(temp, pstApduResp.DataOut, pstApduResp.LenOut);
        temp[pstApduResp.LenOut] = pstApduResp.SWA;
        temp[pstApduResp.LenOut + 1] = pstApduResp.SWB;
        templen = pstApduResp.LenOut + 2;
        //templen = FormTlv(buf, "\xFF\x4D", 2, temp, templen); 

        if (*outlen < templen) {
            sdkFreeMem(temp);
            return 0x8E03;
        }
        memcpy(dataout, temp, templen);
        *outlen = templen;
        sdkFreeMem(temp);
        return 0x9000;
    }
    else {
        sdkFreeMem(temp);
        Trace("", "$$$$$$$$$ 6666666666 %d\r\n", rlt);
        return 0x8E03;
    }
}
Exemple #20
0
/*
 * Done staging file.  Compare accumulated checksum value on stage
 * against value generated during archive.  Upon successful completion
 * return a zero.  Otherwise, this function returns errno.
 */
int
ChecksumCompare(
	int fd,
	sam_id_t *id)
{
	struct sam_perm_inode pi;
	struct sam_ioctl_idstat idstat;
	int i;
	int retval;

	ASSERT(checksum != NULL);

	retval = 0;

	idstat.id = *id;
	idstat.size = sizeof (pi);
	idstat.dp.ptr = &pi;
	if (ioctl(fd, F_IDSTAT, &idstat) != 0) {
		retval = errno;
	}

	if (retval == 0 && checksum != NULL) {
		for (i = 0; i < 4; i++) {
			if (pi.csum.csum_val[i] != checksum->val.csum_val[i]) {
				retval = EDVVCMP;
				break;
			}
		}

		/* Checksum failed.  Try endian repair calculation. */
		if (retval == EDVVCMP && pi.di.cs_algo == CS_SIMPLE) {
			retval = 0;
			Trace(TR_MISC, "Trying alternate-endian checksum "
			    "inode: %d.%d", id->ino, id->gen);
			Trace(TR_FILES, "Checksum inode: %d.%d "
			    "length: %lld cookie: %lld",
			    id->ino, id->gen, (u_longlong_t)pi.di.rm.size,
			    checksum->seed);
			cs_repair((uchar_t *)&pi.csum.csum_val[0],
			    &checksum->seed);
			for (i = 0; i < 4; i++) {
				if (pi.csum.csum_val[i] !=
				    checksum->val.csum_val[i]) {
					retval = EDVVCMP;
					break;
				}
			}
		}

		if (retval == EDVVCMP) {
			SetErrno = 0;		/* set for trace */
			Trace(TR_ERR, "Checksum error inode: %d.%d",
			    id->ino, id->gen);
			Trace(TR_ERR, "Checksum value: %.8x %.8x %.8x %.8x",
			    pi.csum.csum_val[0], pi.csum.csum_val[1],
			    pi.csum.csum_val[2], pi.csum.csum_val[3]);
			Trace(TR_ERR, "Checksum calc: %.8x %.8x %.8x %.8x",
			    checksum->val.csum_val[0],
			    checksum->val.csum_val[1],
			    checksum->val.csum_val[2],
			    checksum->val.csum_val[3]);
		}
	}

	return (retval);
}
int __cdecl main(int argc, char *argv[])
{
    WORD VersionRequested = MAKEWORD(2, 2);
    WSADATA WsaData;
    int err;
    int socketID;
    struct sockaddr_in mySockaddr;
    const char *data = "sendto and recvfrom test";
    int nBuffer=strlen(data);

 
    /*Initialize the PAL environment*/
    err = PAL_Initialize(argc, argv);
    if(0 != err)
    {
        return FAIL;
    }
    /*initialize to use winsock2 .dll*/
    err = WSAStartup(VersionRequested, &WsaData);
    if(err != 0)
    {
        Fail("\nFailed to find a usable WinSock DLL!\n");
    }

    /*Confirm that the WinSock DLL supports 2.2.*/
    if(LOBYTE( WsaData.wVersion ) != 2 ||
            HIBYTE( WsaData.wVersion ) != 2)
    {
        Trace("\nFailed to find a usable WinSock DLL!\n");
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
       }
        Fail("");
    }

    /*create a stream socket in IF_INET domain*/
    socketID = socket(AF_INET, SOCK_STREAM, 0);

    if(INVALID_SOCKET == socketID)
    {
        Trace("\nFailed to call socket API to create a stream socket!\n");
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    /*prepare the sockaddr_in structure*/
    mySockaddr.sin_family = AF_INET;
    mySockaddr.sin_port = getRotorTestPort();
    mySockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
    memset(&(mySockaddr.sin_zero), 0, 8);

    /*connect this socket to specified address*/

    err = connect(socketID, (struct sockaddr *)&mySockaddr, 
                sizeof(struct sockaddr));

    if(SOCKET_ERROR == err)
    {
        Trace("\nFailed to call connect API!\n");
        err = closesocket(socketID);
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call closesocket API!\n");
        }

        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        
        Fail("");
    }

    /*send data to server through a stream socket*/
    err=sendto(socketID, data, nBuffer, 0, (struct sockaddr *)&mySockaddr,
                sizeof(struct sockaddr));
    if(SOCKET_ERROR == err)
    {
        Trace("\nFailed to call sendto API to send data through a "
            "stream socket!\n");
        err = closesocket(socketID);
        if(SOCKET_ERROR == err)
        {    
            Trace("\nFailed to call closesocket API!\n");
        }
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    err = closesocket(socketID);
    if(SOCKET_ERROR == err)
    {
        Trace("\nFailed to call closesocket API!\n");
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    err = WSACleanup();
    if(SOCKET_ERROR == err)
    {
        Fail("\nFailed to call WSACleanup API!\n");
    }

    PAL_Terminate();
    return PASS;
}
void CNetDDESvrApp::OnError(CSocket* /*pSocket*/, int nEvent, int nError)
{
	Trace(TXT("SOCKET_ERROR: %s [%s]"), CWinSock::ErrorToSymbol(nError), CSocket::AsyncEventStr(nEvent));
}
Exemple #23
0
void nGraphics::Render()
{
	// Check if we have a valid render device, if not we don't have anything to render with
	if(!m_pDevice)
		return;

	HRESULT hr = NULL;

	// Check if device ok
	if(FAILED(hr = m_pDevice->TestCooperativeLevel()))
	{
		// Yield some CPU time to other processes
		Trace(__FUNCTION__" Sleeping on test coop level (100 ms).\n");
		Sleep(100);

		// The device has been lost but cannot be reset at this time. 
		// Therefore, rendering is not possible and we'll have to return 
		// and try again at a later time.
		if(hr == D3DERR_DEVICELOST)
		{
			nMainFrame::LastError("Display Device lost.");
			Trace(__FUNCTION__" Display Device lost.\n");
			return;
		}

		// The device has been lost but it can be reset at this time. 
		if(hr == D3DERR_DEVICENOTRESET)
		{
			// If the device can be restored, the application prepares the 
			// device by destroying all video-memory resources and any 
			// swap chains. 
			this->InvalidateDeviceObjects();

			if(FAILED(m_pDevice->Reset(&m_PresentParameters)))
			{
				nMainFrame::LastError("Failed to reset Display Device.");
				Trace(__FUNCTION__" Failed to reset Display Device.\n");
				return;
			}

			Trace(__FUNCTION__" Display Device reset.\n");

			// Finally, a lost device must re-create resources (including  
			// video memory resources) after it has been reset.

			this->RestoreDeviceObjects();
		}
	}

	// Clear the screen with the backgroun color
	m_pDevice->Clear(0,0,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,COLOR_BACKGROUND,1.0f,0);

	// Begin the scene
	if(SUCCEEDED(m_pDevice->BeginScene()))
	{
		// Begin sprite drawing
		SpriteBegin();

		// Draw the game
		nGetInstance()->GetGame()->Render();

		// Draw the status text
		DrawStatusText();

		// End 2D drawing
		SpriteEnd();

		// End the scene
		m_pDevice->EndScene();
	}

	// Present the scene to the user
	m_pDevice->Present(0,0,0,0);
}
Exemple #24
0
/* DWORD  PALAPI Thread_Client(LPVOID lpParam)
   This is a client thread started by the main process.
   It simulate a client connecting to a remote server.
*/
void  PALAPI Thread_Client(LPVOID lpParam)
{
    unsigned int     i;
    int     err;
    struct  sockaddr_in mySockaddr;

    /* Sockets descriptor */
    const int numSockets = 1;    /* number of sockets used in this test */

    SOCKET testSockets[1];


    /* Variables for WSASend */

    WSABUF wsaSendBuf;
    DWORD  dwNbrOfByteSent;
    DWORD  dwNbrOfBuf  = 1;
    DWORD  dwSendFlags = 0;

    unsigned char sendBuffer[255];

    WSAOVERLAPPED wsaOverlapped;

    int byteCounter;

    HANDLE  hWriteEvent;
    DWORD   waitResult;

    threadExitCode=THREAD_UNDEFINED;

    /* Sockets initialization to INVALID_SOCKET */
    for( i = 0; i < (unsigned int)numSockets; i++ )
    {
        testSockets[i] = INVALID_SOCKET;
    }

    /* create an overlapped stream socket in AF_INET domain */

    testSockets[0] = WSASocketA( AF_INET,
                                 SOCK_STREAM,
                                 IPPROTO_TCP,
                                 NULL,
                                 0,
                                 WSA_FLAG_OVERLAPPED );


    if( testSockets[0] == INVALID_SOCKET )

    {
        Trace("Client error: Unexpected failure: "
              "WSASocketA"
              "(AF_INET,SOCK_STREAM,IPPROTO_TCP,NULL,0,WSA_FLAG_OVERLAPPED) "
              " returned %d\n",
              GetLastError());

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

    /* prepare the sockaddr_in structure */
    mySockaddr.sin_family           = AF_INET;
    mySockaddr.sin_port             = getRotorTestPort();
    mySockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");

    memset( &(mySockaddr.sin_zero), 0, 8);

    /* Wait for server to call accept */
    Sleep(500);

    /* connect to a server */
    err = connect( testSockets[0],
                   (struct sockaddr *)&mySockaddr,
                   sizeof(struct sockaddr));

    if( err == SOCKET_ERROR )
    {
        Trace("Client error: Unexpected failure: "
              "connect() socket with local server "
              "returned %d\n",
              GetLastError());

        /* Do some cleanup */
        CloseSocket( testSockets, numSockets );

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }


    /* create events */
    hWriteEvent = CreateEvent( NULL, /* no security   */
                               FALSE,    /* reset type    */
                               FALSE,    /* initial state */
                               NULL );   /* object name   */

    if( hWriteEvent == NULL )
    {
        Trace("Client error: Unexpected failure: "
              "CreateEvent() "
              "returned %d\n",
              GetLastError());

        CloseEventHandle(hWriteEvent);

        /* Do some cleanup */
        CloseSocket( testSockets, numSockets );

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

    /* Initialize the WSAOVERLAPPED to 0 */
    memset(&wsaOverlapped, 0, sizeof(WSAOVERLAPPED));
    wsaOverlapped.hEvent = hWriteEvent;

    /* fill the sent buffer with value */
    for (i=0; i<255; i++)
    {
        sendBuffer[i]=i;
    }

    /* Set the WSABUF structure */
    wsaSendBuf.len = 255;
    wsaSendBuf.buf = sendBuffer;
    byteCounter = 0;

    /* This loop is intended to send 500 buffer (of 255 bytes).
       The server that receive will shutdown connection
       at the 400th recv. The Client should handle that close
       connection gracefully and close its allocated resources
    */
    for(i=0; i<500; i++)
    {
        /* Initialize the WSAOVERLAPPED to 0 */
        memset(&wsaOverlapped, 0, sizeof(WSAOVERLAPPED));
        wsaOverlapped.hEvent = hWriteEvent;

        /* Send some data */
        err = WSASendTo( testSockets[0],
                         &wsaSendBuf,
                         dwNbrOfBuf,
                         &dwNbrOfByteSent,
                         dwSendFlags,
                         (struct sockaddr*)NULL, /* ignored in TCP */
                         (int)NULL, /* ignored in TCP */
                         &wsaOverlapped,
                         0 );

        if(err != SOCKET_ERROR )
        {
            /* Program continue normally, reset the write event */
            ResetEvent(hWriteEvent);
        }
        else
        {
            /* The server shutdown its socket after 400 wsarecv, it is
               impossible to have 401 or more successfull send operation */
            if(GetLastError()==WSAECONNABORTED||GetLastError()==WSAESHUTDOWN)
            {
                if (i<400)
                {
                    if(GetLastError()==WSAESHUTDOWN)
                    {
                        Trace("Unexpected WSAESHUTDOWN");
                    }
                    else
                    {
                        Trace("Unexpected WSAECONNABORTED");
                    }

                    CloseEventHandle(hWriteEvent);

                    CloseSocket( testSockets, numSockets );

                    Fail("");
                }
                else
                {
                    /* the program will terminate normally because
                       connection has been closed by the server.
                    */
                    break;
                }
            }

            /* Handle the overlapped operation */
            if(GetLastError()!=WSA_IO_PENDING)
            {

                Trace("Client error: Unexpected failure: "
                      "WSASend() "
                      "returned %d\n",
                      GetLastError());


                CloseEventHandle(hWriteEvent);

                /* Do some cleanup */
                CloseSocket( testSockets, numSockets );

                threadExitCode=THREAD_FAIL;

                ExitThread(0);
            }

            /* Wait 10 seconds for WriteEvent to be signaled
               by the pending operation
            */
            waitResult = WaitForSingleObject( hWriteEvent,
                                              10000 );

            if (waitResult!=WAIT_OBJECT_0)
            {
                Trace("ERROR: Unexpected failure: "
                      "WaitForSingleObject has timed out \n");

                CloseEventHandle(hWriteEvent);

                /* Do some cleanup */
                CloseSocket( testSockets, numSockets );

                threadExitCode=THREAD_FAIL;

                ExitThread(0);
            }
        }

        /* keep track of the number of bytes sent */
        byteCounter += wsaOverlapped.InternalHigh;

        /* if wsaOverlapped.InternalHigh is 0, it means
           that connection has been closed
        */
        if(wsaOverlapped.InternalHigh==0)
        {
            /* The server shutdown the receiving socket
               after 400 successfull receive.
            */
            if (i<400)
            {
                Trace("Unexpected wsaOverlapped.InternalHigh = 0 "
                      "at WSASend attempt #%d", i);


                CloseEventHandle(hWriteEvent);

                /* Do some cleanup */
                CloseSocket( testSockets, numSockets );

                threadExitCode=THREAD_FAIL;

                ExitThread(0);
            }
        }
    } /* end of loop */



    if(!CloseEventHandle(hWriteEvent)||
            !CloseSocket( testSockets, numSockets ))
    {
        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

    threadExitCode=THREAD_SUCCESS;

    ExitThread(0);
}
Exemple #25
0
int Interpreter::SingleStepInner()
{
  if (HandleFunctionHooking(PC))
  {
    UpdatePC();
    return PPCTables::GetOpInfo(m_prev_inst)->numCycles;
  }

#ifdef USE_GDBSTUB
  if (gdb_active() && gdb_bp_x(PC))
  {
    Host_UpdateDisasmDialog();

    gdb_signal(GDB_SIGTRAP);
    gdb_handle_exception();
  }
#endif

  NPC = PC + sizeof(UGeckoInstruction);
  m_prev_inst.hex = PowerPC::Read_Opcode(PC);

  // Uncomment to trace the interpreter
  // if ((PC & 0xffffff)>=0x0ab54c && (PC & 0xffffff)<=0x0ab624)
  //	startTrace = 1;
  // else
  //	startTrace = 0;

  if (startTrace)
  {
    Trace(m_prev_inst);
  }

  if (m_prev_inst.hex != 0)
  {
    if (IsInvalidPairedSingleExecution(m_prev_inst))
    {
      GenerateProgramException();
      CheckExceptions();
    }
    else if (MSR.FP)
    {
      m_op_table[m_prev_inst.OPCD](m_prev_inst);
      if (PowerPC::ppcState.Exceptions & EXCEPTION_DSI)
      {
        CheckExceptions();
      }
    }
    else
    {
      // check if we have to generate a FPU unavailable exception or a program exception.
      if (PPCTables::UsesFPU(m_prev_inst))
      {
        PowerPC::ppcState.Exceptions |= EXCEPTION_FPU_UNAVAILABLE;
        CheckExceptions();
      }
      else
      {
        m_op_table[m_prev_inst.OPCD](m_prev_inst);
        if (PowerPC::ppcState.Exceptions & EXCEPTION_DSI)
        {
          CheckExceptions();
        }
      }
    }
  }
  else
  {
    // Memory exception on instruction fetch
    CheckExceptions();
  }

  UpdatePC();
  return PPCTables::GetOpInfo(m_prev_inst)->numCycles;
}
Exemple #26
0
/**
 * main
 *
 * executable entry point
 */
INT __cdecl main(INT argc, CHAR **argv)
{
    int     i;
    int     err;
    int     addrlen = sizeof(struct sockaddr);
    struct  sockaddr_in mySockaddr;
    WSADATA wsaData;
    HANDLE  hReadEvent;
    DWORD   waitResult;

    /* Thread variable */
    HANDLE hThreadClient;
    DWORD dwThreadClient;
    DWORD dwClientParam[2];

    /* Sockets descriptor */
    const int numSockets = 2;    /* number of sockets used in this test */

    SOCKET testSockets[2];

    /* Variables needed for setsockopt */
    BOOL bReuseAddr = TRUE;


    /* Variables needed for select */
    struct timeval waitTime;
    fd_set readFds;
    int    socketFds;

    /* Variables needed for WSARecv */
    WSABUF        wsaBuf;
    DWORD         dwNbrOfBuf  = 1;
    DWORD         dwNbrOfByteSent;
    DWORD         dwRecvFlags = 0;
    WSAOVERLAPPED wsaRecvOverlapped;

    /* Variable used to store transmitted data */
    unsigned char myBuffer[255];
    unsigned char myData[500][255];
    unsigned char* pMyData;

    int bufferCounter;

    /* Socket DLL version */
    const WORD wVersionRequested = MAKEWORD(2,2);

    /* Sockets initialization to INVALID_SOCKET */
    for( i = 0; i < numSockets; i++ )
    {
        testSockets[i] = INVALID_SOCKET;
    }

    /* PAL initialization */
    if( PAL_Initialize(argc, argv) != 0 )
    {
        return FAIL;
    }

    /* Initialize to use winsock2.dll */
    err = WSAStartup( wVersionRequested,
                      &wsaData);

    if(err != 0)
    {
        Fail( "Server error: Unexpected failure: "
              "WSAStartup(%i) "
              "returned %d\n",
              wVersionRequested,
              GetLastError() );
    }

    /* Confirm that the WinSock DLL supports 2.2.
       Note that if the DLL supports versions greater
       than 2.2 in addition to 2.2, it will still return
       2.2 in wVersion since that is the version we
       requested.
    */
    if ( wsaData.wVersion != wVersionRequested )
    {
        Trace("Server error: Unexpected failure "
              "to find a usable version of WinSock DLL\n");

        /* Do some cleanup */
        DoWSATestCleanup( 0, 0);

        Fail("");
    }

    /* create an overlapped stream socket in AF_INET domain */

    testSockets[0] = WSASocketA( AF_INET,
                                 SOCK_STREAM,
                                 IPPROTO_TCP,
                                 NULL,
                                 0,
                                 WSA_FLAG_OVERLAPPED );


    if( testSockets[0] == INVALID_SOCKET )
    {
        Trace("Server error: Unexpected failure: "
              "WSASocketA"
              "(AF_INET,SOCK_STREAM,IPPROTO_TCP,NULL,0,WSA_FLAG_OVERLAPPED)) "
              " returned %d\n",
              GetLastError());

        /* Do some cleanup */
        DoWSATestCleanup( 0, 0);

        Fail("");
    }

    /* Allows the socket to be bound to an address that is already in use. */
    err = setsockopt( testSockets[0],
                      SOL_SOCKET,
                      SO_REUSEADDR,
                      (const char *)&bReuseAddr,
                      sizeof( BOOL ) );

    if( err == SOCKET_ERROR )
    {
        Trace("Server error: Unexpected failure: "
              "setsockopt(.., SOL_SOCKET,SO_REUSEADDR, ..) "
              "returned %d\n",
              GetLastError() );

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    /* prepare the sockaddr structure */

    mySockaddr.sin_family           = AF_INET;
    mySockaddr.sin_port             = getRotorTestPort();
    mySockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");

    memset( &(mySockaddr.sin_zero), 0, 8);

    /* bind local address to a socket */
    err = bind( testSockets[0],
                (struct sockaddr *)&mySockaddr,
                sizeof(struct sockaddr) );


    if( err == SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure: "
              "bind() socket with local address "
              "returned %d\n",
              GetLastError() );

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    /* listen to the socket */
    err = listen( testSockets[0],
                  listenBacklog );

    if( err == SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure: "
              "listen() to sockets "
              "returned %d\n",
              GetLastError() );

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    /* create a client thread */

    hThreadClient =
        CreateThread(
            NULL,                        /* no security attributes */
            0,                           /* use default stack size */
            (LPTHREAD_START_ROUTINE)Thread_Client,/* thread function    */
            (LPVOID)&dwClientParam,      /* argument to thread function */
            0,                           /* use default creation flags  */
            &dwThreadClient);            /* returns the thread identifier*/

    if(hThreadClient==NULL)
    {
        Trace( "Server Error: Unexpected failure: "
               "CreateThread() "
               "returned NULL\n");

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    /* set the server waiting time as 10 seconds */
    waitTime.tv_sec = 10L;
    waitTime.tv_usec = 0L;

    /* initialize the except socket set  */
    FD_ZERO( &readFds );

    /* add socket to readable socket set */
    FD_SET( testSockets[0],
            &readFds );

    /* monitor the readable socket set   */
    socketFds = select( 0,
                        &readFds,
                        NULL,
                        NULL,
                        &waitTime);

    if( socketFds == SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure "
              "with select\n");

        WaitForClientThreadToFinish(hThreadClient);

        CloseThreadHandle(hThreadClient);

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    if( socketFds == 0 )
    {
        Trace("ERROR: Unexpected select "
              "timed out\n");

        WaitForClientThreadToFinish(hThreadClient);

        CloseThreadHandle(hThreadClient);

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    /* accept connection */
    testSockets[1] = accept( testSockets[0],
                             (struct sockaddr *)&mySockaddr,
                             &addrlen );

    if( testSockets[1] == INVALID_SOCKET )
    {
        Trace("ERROR: Unexpected failure: "
              "accept() connection on socket "
              "returned %d\n",
              GetLastError());

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    /* create an event */
    hReadEvent = CreateEvent( NULL, /* no security   */
                              FALSE,   /* reset type    */
                              FALSE,   /* initial state */
                              NULL );  /* object name   */

    if( hReadEvent == NULL )
    {
        Trace("Server error: Unexpected failure: "
              "CreateEvent() "
              "returned %d\n",
              GetLastError());

        WaitForClientThreadToFinish(hThreadClient);


        CloseThreadHandle(hThreadClient);

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");

    }

    /* Initialize the WSABUF structure */
    wsaBuf.buf = myBuffer;
    wsaBuf.len = 255;

    bufferCounter = 0;
    pMyData = (unsigned char*)myData;

    /* loop that receive data from client
       It received 400 buffer then proceed to a shutdown
       on the receiving socket.
    */
    for(i=0; i<400; i++)
    {
        /* Initialize the WSAOVERLAPPED to 0 */
        memset(&wsaRecvOverlapped, 0, sizeof(WSAOVERLAPPED));
        /* Specify which event to signal when data is arrived*/
        wsaRecvOverlapped.hEvent = hReadEvent;

        memset(myBuffer, 0, 255);

        /* Prepare to receive data */
        err = WSARecv( testSockets[1],
                       &wsaBuf,
                       dwNbrOfBuf,
                       &dwNbrOfByteSent,
                       &dwRecvFlags,
                       &wsaRecvOverlapped,
                       0 );

        if( err != SOCKET_ERROR )
        {
            if(dwNbrOfByteSent==0)
            {
                Trace("Server error: WSARecv() "
                      "received %d, expected 0.\n",
                      dwNbrOfByteSent);

                WaitForClientThreadToFinish(hThreadClient);

                CloseThreadHandle(hThreadClient);

                CloseEventHandle(hReadEvent);

                /* Do some cleanup */
                DoWSATestCleanup( testSockets,
                                  numSockets );

                Fail("");
            }
            /* reset the event */
            ResetEvent(hReadEvent);
        }
        else if(GetLastError()!=WSA_IO_PENDING)
        {
            Trace("Server error: WSARecv() "
                  "returned %d, expected WSA_IO_PENDING\n",
                  GetLastError() );

            WaitForClientThreadToFinish(hThreadClient);

            CloseThreadHandle(hThreadClient);

            CloseEventHandle(hReadEvent);

            /* Do some cleanup */
            DoWSATestCleanup( testSockets,
                              numSockets );

            Fail("");
        }
        else
        {
            waitResult = WaitForSingleObject( hReadEvent,
                                              10000 );

            if (waitResult!=WAIT_OBJECT_0)
            {
                Trace("Server error: Unexpected failure: "
                      "WaitForSingleObject has timed out \n");

                WaitForClientThreadToFinish(hThreadClient);

                CloseThreadHandle(hThreadClient);

                CloseEventHandle(hReadEvent);

                /* Do some cleanup */
                DoWSATestCleanup( testSockets,
                                  numSockets );

                Fail("");
            }
        }

        /* test if data can be copied to the current position in the
          receiving data array. */
        if( pMyData+wsaRecvOverlapped.InternalHigh <&(myData[500][255]) )
        {
            /* copy buffer to data array */
            memcpy(pMyData,wsaBuf.buf,wsaRecvOverlapped.InternalHigh);

            /* increment the position where we can write data on the array*/
            pMyData+=wsaRecvOverlapped.InternalHigh;
        }
        else
        {
            /* Else the data received exceed buffer capacity */
            Trace("Unexpected, data received exceed buffer capacity.\n");
            WaitForClientThreadToFinish(hThreadClient);

            CloseThreadHandle(hThreadClient);

            CloseEventHandle(hReadEvent);

            /* Do some cleanup */
            DoWSATestCleanup( testSockets,
                              numSockets );

            Fail("");
        }
    }


    if(!WaitForClientThreadToFinish(hThreadClient))
    {

        CloseThreadHandle(hThreadClient);

        CloseEventHandle(hReadEvent);

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    if(!CloseThreadHandle(hThreadClient)||
            !CloseEventHandle(hReadEvent))
    {
        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );
        Fail("");
    }

    /* Do some cleanup */
    DoWSATestCleanup( testSockets,
                      numSockets );

    PAL_Terminate();
    return PASS;
}
Exemple #27
0
void
Enter(char * text) {
#ifdef TRACE_ENTER
	Trace("Enter", text);
#endif
}
Exemple #28
0
int __cdecl main(int argc, char* argv[])
{
    HANDLE  hThread;  
    HANDLE  hCurrentThread;  
    HANDLE  hDupThread;  
    DWORD   dwThreadId = 0;
    LPTHREAD_START_ROUTINE lpStartAddress =  &CreateTestThread;

    int threadPriority;
    int duplicatePriority;
    int finalPriority;

    /* Initialize the PAL.*/
    if ((PAL_Initialize(argc, argv)) != 0)
    {
        return (FAIL);
    }
    
    /* Create a thread.*/
    hThread = CreateThread(NULL,            /* SD*/
                          (DWORD)0,         /* initial stack size*/
                          lpStartAddress,   /* thread function*/
                          NULL,             /* thread argument*/
                          (DWORD)0,         /* creation option*/
                          &dwThreadId);     /* thread identifier*/
    if (hThread == NULL)
    {
        Fail("ERROR:%u: Unable to create thread.\n",
             GetLastError());
    }

    /*Get a psuedo handle to the current thread.*/
    hCurrentThread = GetCurrentThread();

    /* Duplicate the psuedo thread handle.*/
    if (!(DuplicateHandle(GetCurrentProcess(),       /* source handle process*/
                          hCurrentThread,            /* handle to duplicate*/
                          GetCurrentProcess(),       /* target process handle*/
                          &hDupThread,               /* duplicate handle*/
                          (DWORD)0,                  /* requested access*/
                          FALSE,                     /* handle inheritance*/
                          DUPLICATE_SAME_ACCESS)))   /* optional actions*/
    {
        Trace("ERROR: %ld :Fail to create the duplicate handle"
              " to hThread=0x%lx",
              GetLastError(),
              hThread);
        CloseHandle(hThread);
        Fail("");
    }

    /* Get the priority of the thread.*/
    threadPriority = GetThreadPriority(hCurrentThread);
    if(threadPriority != 0)
    {
        Trace("ERROR: Thread priority of hCurrentThread=0x%lx should be "
             "set to normal THREAD_PRIORITY_NORMAL=%d\n",
             hCurrentThread,
             THREAD_PRIORITY_NORMAL);
        CloseHandle(hThread);
        CloseHandle(hDupThread);
        Fail("");
    }

    /* Get the priority of the duplicated handle, and compare it to
     * the priority of the original thread. Should be the same.*/
    duplicatePriority = GetThreadPriority(hCurrentThread);
    if(duplicatePriority != threadPriority)
    {
        Trace("ERROR: Expected priority of hCurrentThread=0x%lx and "
             "hDupThread=0x%lx to be the same. Priorities:hThread="
             "\"%d\":hDupThread=\"%d\"\n",
             hCurrentThread,
             hDupThread,
             threadPriority,
             duplicatePriority);
        CloseHandle(hThread);
        CloseHandle(hDupThread);
        Fail("");
    }

    /* Set the priority of the original thread.*/
    if(!SetThreadPriority (hCurrentThread,THREAD_PRIORITY_HIGHEST))
    {
        Trace("ERROR:%u: SetThreadPriority failed on hCurrentThread=0x%lx\n",
             GetLastError(),
             hCurrentThread);
        CloseHandle(hThread);
        CloseHandle(hDupThread);
        Fail("");
    }

    /* Get the priority of the duplicate thread, and
     * compare it to what the original was set to.*/
    finalPriority = GetThreadPriority(hDupThread);
    if (finalPriority != THREAD_PRIORITY_HIGHEST)
    {
        Trace("ERROR: Expected priority of hCurrentThread=0x%lw and "
             "hDupThread=0x%lw to be set the same. Priorities:"
             "hCurrentThread=\"%d\":hDupThread=\"%d\".\n",
             hCurrentThread,
             hDupThread,
             threadPriority,
             duplicatePriority);
        CloseHandle(hThread);
        CloseHandle(hDupThread);
        Fail("");
    }

    /* Wait on the original thread.*/
    if((WaitForSingleObject(hThread, 100)) != WAIT_OBJECT_0)
    {
        Trace("ERROR:%u: hCurrentThread=0x%lx is in a non-signalled "
              "mode, yet created signalled.\n",
              GetLastError(),
              hThread);
        CloseHandle(hThread);
        CloseHandle(hDupThread);
        Fail("");
    }

    /* Clean-up thread and Terminate the PAL.*/
    CloseHandle(hThread);
    CloseHandle(hDupThread);
    PAL_Terminate();
    return PASS;
}
Exemple #29
0
int __cdecl main(int argc, char *argv[])
{
    BOOL bRc = TRUE;
    BOOL bSuccess = TRUE;
    char results[40];
    FILE* resultsFile = NULL;
    int nCounter = 0;
    int i, j;
    WCHAR* wSource = NULL;
    WCHAR* wDest = NULL;
    WCHAR tempSource[] = {'t','e','m','p','k','.','t','m','p','\0'};
    WCHAR tempDest[] = {'t','e','m','p','2','.','t','m','p','\0'};
    HANDLE hFile;
    DWORD result;

    if (0 != PAL_Initialize(argc,argv))
    {
        return FAIL;
    }

    /* read in the expected results to compare with actual results */
    memset (results, 0, 20);
    resultsFile = fopen("expectedresults.txt", "r");
    if (resultsFile == NULL)
    {
        Fail("MoveFileW ERROR: Unable to open \"expectedresults.txt\"\n");
    }

    fgets(results, 20, resultsFile);
    fclose(resultsFile);

    /* clean the slate */
    removeAll();

    if (createExisting() != 0)
    {
        removeAll();
    }


    /* lpSource loop */
    for (i = 0; i < 4; i++)
    {
        /* lpDestination loop */
        for (j = 0; j < 4; j++)
        {
           
            wSource = convert(lpSource[i]);
            wDest = convert(lpDestination[j]);
            bRc = MoveFileW(wSource, wDest);
            free(wSource);
            free(wDest);
            if (bRc == FALSE)
            {
                if (results[nCounter] == '1')
                {
                    Trace("MoveFileW: FAILED: test[%d][%d]: \"%s\" -> \"%s\"\n", 
                        i, j, lpSource[i], lpDestination[j]);
                    bSuccess = FALSE;
                }
            }
            else
            {
                if (results[nCounter] == '0')
                {
                    Trace("MoveFileW: FAILED: test[%d][%d]: \"%s\" -> \"%s\"\n", 
                        i, j, lpSource[i], lpDestination[j]);
                    bSuccess = FALSE;
                }
            }

            /* undo the last move */
            removeAll();
            createExisting();

            nCounter++;
        }
    }

    removeAll();
    if (bSuccess == FALSE)
    {
        Fail("MoveFileW: Test Failed");
    }

    /* create the temp source file */
    hFile = CreateFileW(tempSource, GENERIC_WRITE, 0, 0, CREATE_ALWAYS,                        
                            FILE_ATTRIBUTE_NORMAL, 0);

    if( hFile == INVALID_HANDLE_VALUE )
    {
        Fail("MoveFileW: CreateFile failed to "
            "create the file correctly.\n");
    }

    bRc = CloseHandle(hFile);
    if(!bRc)
    {
        Trace("MoveFileW: CloseHandle failed to close the "
            "handle correctly. ERROR:%u\n",GetLastError());
        
        /* delete the created file */
        bRc = DeleteFileW(tempSource);
        if(!bRc)
        {
            Fail("MoveFileW: DeleteFileW failed to delete the"
                "file correctly.\n");
        }
        Fail("");
    }

    /* set the file attributes to be readonly */
    bRc = SetFileAttributesW(tempSource, FILE_ATTRIBUTE_READONLY);
    if(!bRc)
    {
        Trace("MoveFileW: SetFileAttributes failed to set file "
            "attributes correctly. GetLastError returned %u\n",GetLastError());
        /* delete the created file */
        bRc = DeleteFileW(tempSource);
        if(!bRc)
        {
            Fail("MoveFileW: DeleteFileW failed to delete the"
                "file correctly.\n");
        }
        Fail("");
    }

    /* move the file to the new location */
    bRc = MoveFileW(tempSource, tempDest);
    if(!bRc)
    {
        /* delete the created file */
        bRc = DeleteFileW(tempSource);
        if(!bRc)
        {
            Fail("MoveFileW: DeleteFileW failed to delete the"
                "file correctly.\n");
    }

        Fail("MoveFileW(%S, %S): GetFileAttributes "
            "failed to get the file's attributes.\n",
            tempSource, tempDest);
    }

    /* check that the newly moved file has the same file attributes
    as the original */
    result = GetFileAttributesW(tempDest);
    if(result == 0)
    {
        /* delete the created file */
        bRc = DeleteFileW(tempDest);
        if(!bRc)
        {
            Fail("MoveFileW: DeleteFileW failed to delete the"
                "file correctly.\n");
        }

        Fail("MoveFileW: GetFileAttributes failed to get "
            "the file's attributes.\n");
    }   

    if((result & FILE_ATTRIBUTE_READONLY) != FILE_ATTRIBUTE_READONLY)
    {
        /* delete the newly moved file */
        bRc = DeleteFileW(tempDest);
        if(!bRc)
        {
            Fail("MoveFileW: DeleteFileW failed to delete the"
                "file correctly.\n");
        }

        Fail("MoveFileW: GetFileAttributes failed to get "
            "the correct file attributes.\n");
    }

    /* set the file attributes back to normal, to be deleted */
    bRc = SetFileAttributesW(tempDest, FILE_ATTRIBUTE_NORMAL);
    if(!bRc)
    {
        /* delete the newly moved file */
        bRc = DeleteFileW(tempDest);
        if(!bRc)
        {
            Fail("MoveFileW: DeleteFileW failed to delete the"
                "file correctly.\n");
        }

        Fail("MoveFileW: SetFileAttributes failed to set "
            "file attributes correctly.\n");
    }

    /* delete the newly moved file */
    bRc = DeleteFileW(tempDest);
    if(!bRc)
    {
        Fail("MoveFileW: DeleteFileW failed to delete the"
            "file correctly.\n");
    }

    PAL_Terminate(); 

    return PASS;
}
Exemple #30
0
BOOL  PALAPI StartThreadTest()
{
    HMODULE hLib;
    HANDLE  hThread;  
    DWORD   dwThreadId;
    LPTHREAD_START_ROUTINE lpStartAddress =  &CreateTestThread;
    LPVOID lpParameter = lpStartAddress;
    DWORD rc = -1;
    /*Load library (DLL).*/
    hLib = LoadLibrary(LibraryName);
    if(hLib == NULL)
    {
        Trace("ERROR: Unable to load library %s\n", LibraryName);
        
        return (FALSE);
    }

    /*Start the test thread*/
    hThread = CreateThread(NULL, 
                            (DWORD)0,
                            lpParameter,
                            hLib,
                            (DWORD)NULL,
                            &dwThreadId);
    if(hThread == NULL)
    {
        Trace("ERROR:%u: Unable to create thread.\n",
                GetLastError());

        FreeLibrary(hLib);
        return (FALSE);
    }

    /*Wait on thread.*/
    rc = WaitForSingleObject(hThread, TIMEOUT);
    if( rc != WAIT_OBJECT_0 )
    {
        Trace("ERROR:%u: hThread=0x%4.4lx not exited by "
            "FreeLibraryAndExitThread, RC[%d]\n",
            GetLastError(),  
            hThread, rc);

// There is a possibility that the other thread might 
// still be using the library VSW:337893
//        FreeLibrary(hLib);
        CloseHandle(hThread);
        return (FALSE);
    }
            
    /*Test access to DLL.*/
    if(!TestDll(hLib, 0))
    {
        Trace("ERROR: TestDll function returned FALSE "
            "expected TRUE\n.");
        
        CloseHandle(hThread);
        return (FALSE);
    }

    FreeLibrary(hLib);
    /*Clean-up thread.*/
    CloseHandle(hThread);

    return (TRUE);
}