Esempio n. 1
0
int __cdecl main(int argc, char *argv[])

{



    BOOL testPass = TRUE;

    BOOL bRc = TRUE;

    HANDLE hFile; 



    const char* sBadFilePath = "bad/badPath.tmp";

    const char* sBadFileName = "badName.tmp";

    const char* sDest = "dest.tmp";

    const WCHAR wBadFilePath[] = 

        {'w','b','a','d','/','b','a',

        'd','.','t','m','p','\0'};

    const WCHAR wBadFileName[] = 

        {'w','B','a','d','.','t','m','p','\0'};

    const WCHAR wDest[] = 

        {'w','d','e','s','t','.','t','m','p','\0'};





    if (0 != PAL_Initialize(argc,argv))

    {

        return FAIL;

    }



    /*...................Test CopyFileW.............................*/



    /* test with an invalid path */

    bRc = CopyFileW(wBadFilePath,wDest,TRUE);

    if(!bRc)

    {

        if(GetLastError()!= ERROR_PATH_NOT_FOUND)

        {

            Trace("CopyFileW: calling GetLastError() after copying a file"

                " with wrong path returned [%u] while it should return [%u]\n"

                ,GetLastError(), ERROR_PATH_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        testPass = FALSE; 

    }



    /* test with invalid file name */

    bRc = CopyFileW(wBadFileName,wDest,TRUE);

    if(!bRc)

    { 

        if(GetLastError()!= ERROR_FILE_NOT_FOUND)

        {

            Trace("CopyFileW: calling GetLastError() after copying a file"

                " with wrong name returned [%u] while it should return [%u]\n"

                ,GetLastError(), ERROR_FILE_NOT_FOUND);

            testPass = FALSE;

        }



    }

    else

    {

        Trace("CopyFileW: managed to copy a file with wrong name\n");     

        testPass = FALSE;

    }



  



    /*..................CopyFileA...................................*/



    /* test with an invalid path */

    bRc = CopyFileA(sBadFilePath,sDest,TRUE);

    if(! bRc)

    {

        if(GetLastError()!= ERROR_PATH_NOT_FOUND)

        {

            Trace("CopyFileA: calling GetLastError() after copying a file"

                " with wrong path returned [%u] while it should return [%u]\n"

                ,GetLastError(), ERROR_PATH_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        Trace("CopyFileA: managed to copy a file with wrong path\n");     

        testPass = FALSE;

    }



    /* test with an invalid file name */

    bRc = CopyFileA(sBadFileName,sDest,TRUE);

    if(! bRc)

    { 

        if(GetLastError()!= ERROR_FILE_NOT_FOUND)

        {

            Trace("CopyFileA: calling GetLastError() after copying a file"

                " with wrong name returned [%u] while it should return [%u]\n"

                ,GetLastError(), ERROR_FILE_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        Trace("CopyFileA: managed to copy a file with wrong name\n"); 

        testPass = FALSE;

    }



    



    /*............. Test CreateFileA..................................*/



    /* test with an invalid file name */

    hFile = CreateFileA(sBadFileName,          

        GENERIC_READ,              /* open for reading */

        FILE_SHARE_READ,           /* share for reading */

        NULL,                      /* no security */

        OPEN_EXISTING,             /* existing file only */

        FILE_ATTRIBUTE_NORMAL,     /* normal file */ 

        NULL);                     /* no attr. template */



    if (hFile == INVALID_HANDLE_VALUE) 

    { 

        if(GetLastError() != ERROR_FILE_NOT_FOUND)

        {

            Trace("CreateFileA: calling GetLastError() returned [%u] "

                "while it should return [%u] for a bad File Name\n",

                GetLastError(),ERROR_FILE_NOT_FOUND);   

            testPass = FALSE;

        }   



    } 

    else

    {

        Trace("CreateFileA: managed to create a file with an incorrect "

              "filename\n");   

        testPass = FALSE;



        if(!CloseHandle(hFile))

        {

            Trace("CreateFileA: Call to CloseHandle failed with ErrorCode "

                "[%u]\n", GetLastError());



        }

        if(!DeleteFile(sBadFileName))

        {

            Trace("CreateFileA: Call to DeleteFile failed with ErrorCode "

                "[%u]\n", GetLastError());

        }

    }



    /* test with an invalid path */

    hFile = CreateFileA(sBadFilePath,          

        GENERIC_READ,              /* open for reading */

        FILE_SHARE_READ,           /* share for reading */

        NULL,                      /* no security */

        OPEN_EXISTING,             /* existing file only */

        FILE_ATTRIBUTE_NORMAL,     /* normal file */ 

        NULL);                     /* no attr. template */



    if (hFile == INVALID_HANDLE_VALUE) 

    { 

        if(GetLastError() != ERROR_PATH_NOT_FOUND)

        {

            Trace("CreateFileA: calling GetLastError() returned [%u] "

                "while it should return [%u] for a bad file path name\n",

                GetLastError(), ERROR_PATH_NOT_FOUND);   

            testPass = FALSE;

        }   



    } 

    else

    {

        Trace("CreateFileA: managed to create a file with an incorrect "

              "filename\n");   

        testPass = FALSE;

        /*this should not happen*/

        if(!CloseHandle(hFile))

        {

            Trace("CreateFileA: Call to CloseHandle Failed with ErrorCode "

                "[%u]\n", GetLastError());



        }

        if(!DeleteFile(sBadFilePath))

        {

            Trace("CreateFileA: Call to DeleteFile Failed with ErrorCode "

                "[%u]\n", GetLastError());

        }

    }





    



    /*............. Test CreateFileW..................................*/



    /* test with an invalid file name */

    hFile = CreateFileW(wBadFileName,          

        GENERIC_READ,              /* open for reading */

        FILE_SHARE_READ,           /* share for reading */

        NULL,                      /* no security */

        OPEN_EXISTING,             /* existing file only */

        FILE_ATTRIBUTE_NORMAL,     /* normal file */ 

        NULL);                     /* no attr. template */



    if (hFile == INVALID_HANDLE_VALUE) 

    { 

        if(GetLastError() != ERROR_FILE_NOT_FOUND)

        {

            Trace("CreateFileW: calling GetLastError() returned [%u] "

                "while it should return [%u] for a bad filename\n",

                GetLastError(), ERROR_FILE_NOT_FOUND);   

            testPass = FALSE;

        }   



    } 

    else

    {

        Trace("CreateFileW: managed to create a file with an incorrect "

              "filename\n");   

        testPass = FALSE;



        if(!CloseHandle(hFile))

        {

            Trace("CreateFileW: Call to CloseHandle Failed with ErrorCode "

                "[%u]\n", GetLastError());



        }



        if(!DeleteFileW(wBadFileName))

        {

            Trace("CreateFileW: Call to DeleteFile Failed with ErrorCode "

                "[%u]\n", GetLastError());

        }

    }







    /* test with an invalid path */

    hFile = CreateFileW(wBadFilePath,          

        GENERIC_READ,              /* open for reading */

        FILE_SHARE_READ,           /* share for reading */

        NULL,                      /* no security */

        OPEN_EXISTING,             /* existing file only */

        FILE_ATTRIBUTE_NORMAL,     /* normal file */ 

        NULL);                     /* no attr. template */



    if (hFile == INVALID_HANDLE_VALUE) 

    { 



        if(GetLastError() != ERROR_PATH_NOT_FOUND)

        {

            Trace("CreateFileW: calling GetLastError() returned [%u] "

                "while it should return [%u] for a bad file path \n",

                GetLastError(), ERROR_FILE_NOT_FOUND);   

            testPass = FALSE;

        }   



    } 

    else

    {

        Trace("CreateFileW: managed to create a file with an incorrect "

              "filename\n");   

        testPass = FALSE;



        if(!CloseHandle(hFile))

        {

            Trace("CreateFileW: Call to CloseHandle Failed with ErrorCode "

                "[%u]\n", GetLastError());



        }

        if(!DeleteFileW(wBadFilePath))

        {

            Trace("CreateFileW: Call to DeleteFile Failed with ErrorCode "

                "[%u]\n", GetLastError());

        }

    }





    

    /* .............  DeleteFileW..................................*/



    /* test with an invalid path */

    if(DeleteFileW(wBadFilePath))

    {

        Trace("DeleteFileW: Call to DeleteFileW to delete a file"

            " that does not exist succeeded\n");

        testPass = FALSE;



    }

    else

    {

        if(GetLastError() != ERROR_PATH_NOT_FOUND)

        {

            Trace("DeleteFileW: Call GetLastError()returned "

                "[%u] while it should return ERROR_PATH_NOT_FOUND [%u]\n",

                GetLastError(),ERROR_FILE_NOT_FOUND);

            testPass = FALSE;



        }



    }



    /* test with an invalid file name */

    if(DeleteFileW(wBadFileName))

    {

        Trace("DeleteFileW: Call to DeleteFileW to delete a file"

            " that does not exist succeeded\n");

        testPass = FALSE;



    }

    else

    {

        if(GetLastError() != ERROR_FILE_NOT_FOUND)

        {

            Trace("DeleteFileW: Call GetLastError()returned [%u]"

                " while it should return ERROR_FILE_NOT_FOUND [%u]\n",

                GetLastError(),ERROR_FILE_NOT_FOUND);

            testPass = FALSE;



        }



    }





    /* .............  DeleteFileA..................................*/



    /* test with an invalid path */

    if(DeleteFileA(sBadFilePath))

    {

        Trace("DeleteFileA: Call to DeleteFileA to delete a file"

            " that does not exist succeeded\n");

        testPass = FALSE;



    }

    else

    {

        if(GetLastError() != ERROR_PATH_NOT_FOUND)

        {

            Trace("DeleteFileA: Call GetLastError() returned [%u]"

                " while it should return ERROR_PATH_NOT_FOUND [%u]\n",

                GetLastError(),ERROR_FILE_NOT_FOUND);

            testPass = FALSE;



        }



    }



    /* test with an invalid file name */

    if(DeleteFileA(sBadFileName))

    {

        Trace("DeleteFileA: Call to DeleteFileA to delete a file"

            " that does not exist succeeded\n");

        testPass = FALSE;



    }

    else

    {

        if(GetLastError() != ERROR_FILE_NOT_FOUND)

        {

            Trace("DeleteFileA: Call GetLastError() returned [%u]"

                " while it should return ERROR_FILE_NOT_FOUND [%u]\n",

                GetLastError(),ERROR_FILE_NOT_FOUND);

            testPass = FALSE;



        }



    }



  



    if(! testPass)

    {

        Fail("");

    }

    PAL_Terminate();

    return PASS;

}
Esempio n. 2
0
int __cdecl main(int argc, char *argv[])
{
    int err;
    WCHAR *wpBuffer = NULL;
    char *pChar = NULL;
    unsigned long ul = 1234567890UL;
    char *pChar10 = "1234567890";
    char *pChar2 = "1001001100101100000001011010010";
    char *pChar16 = "499602d2";

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

    wpBuffer = malloc(64 * sizeof(WCHAR));
    if(NULL == wpBuffer)
    {
        Fail("\nFail to allocate the buffer to save a converted "
                "wide character string, error code=%d!\n",
                GetLastError());
    }

    /*convert to a 10 base string*/
    _ui64tow(ul, wpBuffer, 10);
    pChar = convertC(wpBuffer);
    if(strcmp(pChar10, pChar))
    {
        free(wpBuffer);
        free(pChar);
        Fail("\nFailed to call _ui64tow API to convert an interger "
                "to a 10 base wide character string, error code=%d\n",
                GetLastError()); 
    }
    free(pChar);
    free(wpBuffer);    

    wpBuffer = malloc(64 * sizeof(WCHAR));
    if(NULL == wpBuffer)
    {
        Fail("\nFail to allocate the buffer to save a converted "
                "wide character string, error code=%d!\n",
                GetLastError());
    }
    
    /*convert to a 16 base string*/
    _ui64tow(ul, wpBuffer, 16);
    pChar = convertC(wpBuffer);
    if(strcmp(pChar16, pChar))
    {
        free(wpBuffer);
        free(pChar);
        Fail("\nFailed to call _ui64tow API to convert an interger "
                "to a 16 base wide character string, error code = %d\n",
                GetLastError()); 
    }
    free(pChar);
    free(wpBuffer);    

    wpBuffer = malloc(64 * sizeof(WCHAR));
    if(NULL == wpBuffer)
    {
        Fail("\nFail to allocate the buffer to save a converted "
                "wide character string, error code=%d!\n",
                GetLastError());
    }
    /*convert to a 2 base string*/
    _ui64tow(ul, wpBuffer, 2);
    pChar = convertC(wpBuffer);
    if(strcmp(pChar2, pChar))
    {
        free(wpBuffer);
        free(pChar);
        Fail("\nFailed to call _ui64tow API to convert an interger "
                "to a 2 base wide character string, error code=%d\n",
                GetLastError()); 
    }
    free(pChar);
    free(wpBuffer);
   
    PAL_Terminate();
    return PASS;
}
Esempio n. 3
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.   
*
*  As soon as the client thread is started it calls WaitForSingleObject
*  and wait for the server to be ready to receive data. 
*
*  If the client fail somewhere it will set a global variable accordingly
*  and will call ExitThread. The main thread (server) will then continue 
*  its execution normally and handle the client error.
*
*    
*
*/
void  PALAPI Thread_Client(LPVOID lpParam)
{     
    int     i;
    int     err;
    struct  sockaddr_in mySockaddr;    

    int byteCounter;

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

    SOCKET testSockets[1];

    /* variable for iocltsocket */
    u_long argp;    
    
    /* Variables for WSASend */

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

    WSAOVERLAPPED wsaOverlapped;

    HANDLE  hWriteEvent;
    DWORD   waitResult;
    
    /* Thread Event handle */
    HANDLE hThreadEvent;

    threadExitCode=THREAD_UNDEFINED;

    /* Create the EventClientServer controled by the server  */     
    hThreadEvent = (HANDLE)CreateEvent( NULL,
        TRUE,                /* ignored */
        FALSE,                /* ignored */
        (LPCSTR)"EventClientServer");  /* name of Event */

    if (hThreadEvent == NULL) 
    {        
        /* Check for error. */
        Trace( "Server Error: Unexpected failure: "
              "CreateEvent() "
              "returned NULL\n");

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }
    
    /* Wait 10 seconds for EventClientServer to be signaled 
       from the server. It will mean that the server is ready
       to receive data or connection.
    */
    waitResult = WaitForSingleObject( hThreadEvent,
                                      10000 );
            
    if (waitResult!=WAIT_OBJECT_0)
    {
        Trace("Client error: Unexpected failure: "
              "WaitForSingleObject has timed out while "
              "waiting for EventClientServer.\n");

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }    
    
    /* Destroy the Event Handle, we don't need it anymore */
    if(!CloseEventHandle(hThreadEvent))
    {       
        /* Trace is done in CloseEventHandle */

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }


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


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

    testSockets[0] = WSASocketA( AF_INET, 
                                 SOCK_DGRAM, 
                                 IPPROTO_UDP,
                                 NULL, 
                                 0, 
                                 WSA_FLAG_OVERLAPPED ); 


    if( testSockets[0] == INVALID_SOCKET )

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

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

     /* enable non blocking socket */
    argp=1;
    err = ioctlsocket(testSockets[0], FIONBIO, (u_long FAR *)&argp);

    if (err==SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure: "
              "ioctlsocket(.., FIONBIO, ..) "
              "returned %d\n",
              GetLastError() );

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );
        
        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("Client error: Unexpected failure: "
              "connect() socket with local server "
              "returned %d\n",
              GetLastError());

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

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }


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

    /* prepare data for the send operation */    

    /* 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());

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

        threadExitCode=THREAD_FAIL;

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

    /*
        That loop will wsasend a 500 buffer of data with UDP datagram to
        the server thread.
    */
    for(i=0;i<500;i++)
    {        
        /* Initialize the WSAOVERLAPPED for every send operation */
        memset(&wsaOverlapped, 0, sizeof(WSAOVERLAPPED));
        wsaOverlapped.hEvent = hWriteEvent;

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


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

                /* Do some cleanup */
                CloseEventHandle(hWriteEvent);

                CloseSocket( testSockets, numSockets );

                threadExitCode=THREAD_FAIL;

                ExitThread(0);
            }

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

                /* Do some cleanup */

                CloseEventHandle(hWriteEvent);                        
                
                CloseSocket( testSockets, numSockets );

                threadExitCode=THREAD_FAIL;

                ExitThread(0);
            }            
        }
        else
        {
            /* WSASend returned immediately */
            if(dwNbrOfByteSent==0)
            {
                Trace("Client error: WSARecv()"
                      "returned dwNbrOfByteSent=0, expected 255.\n");

                /* Do some cleanup */

                CloseEventHandle(hWriteEvent);                        
                
                CloseSocket( testSockets, numSockets );

                threadExitCode=THREAD_FAIL;

                ExitThread(0);
                
            }
            /* Reset event */
            ResetEvent(hWriteEvent);
        }
        
        /* test if number of byte sent is different from 0
           in that case it means that the connection was closed
        */
        if(wsaOverlapped.InternalHigh==0)
        {
            Trace("Client Error: Unexpected failure: "
                  "WSASend overlapped operation sent 0 byte. "
                  "wsaOverlapped.Internal "
                  "= %d\n",wsaOverlapped.InternalHigh);
            
            /* Do some cleanup */
            CloseEventHandle(hWriteEvent);
            
            CloseSocket( testSockets, numSockets );                

            threadExitCode=THREAD_FAIL;

            ExitThread(0);            
        }

        /* 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("Client WSASend has not send the number of byte requested "
                  "wsaSendBuf.len = %d while "
                  "wsaOverlapped.InternalHigh = % d",
                  wsaSendBuf.len, wsaOverlapped.InternalHigh);

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

            CloseEventHandle(hWriteEvent);

            threadExitCode=THREAD_FAIL;

            ExitThread(0);
        }

        /* since it is UDP, it is more safe to wait a bit between 
           each send operation. Otherwise we lose some frame.
        */
        Sleep(10);
    }   
    
    
    if(!CloseEventHandle(hWriteEvent))
    {
        /* Do some cleanup */
        CloseSocket( testSockets, numSockets );

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }
    

    /* Do some cleanup */
    if(!CloseSocket( testSockets, numSockets ))
    {
        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

    /* Expected number of bytes sent is 127500 */
    if(byteCounter!=127500)
    {
        Trace("Client error: Invalid number of byte sent to the server: %d"
               "\n",byteCounter);

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }    

    threadExitCode=THREAD_SUCCESS;

    ExitThread(0);    
} 
Esempio n. 4
0
int __cdecl main(int argc, char **argv)
{  
    time_t LTime;
    char  *DateResult;      
    TIME_ZONE_INFORMATION tzInformation;

    /*
     * Initialize the PAL and return FAILURE if this fails
     */

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

    // Get the current timezone information
    GetTimeZoneInformation(&tzInformation);

    /*
     * Test #1
     */
    
    /* set the valid date in time_t format, adjusted for current time zone*/
    LTime = VAL_SUN_JAN_17_2038 + (tzInformation.Bias * 60);

    /* convert it to string using ctime*/
    DateResult = ctime( &LTime );

    /* if it's null, ctime failed*/
    if (DateResult == NULL)
    {
        Fail ("ERROR: (Test #1) ctime returned NULL. Expected string\n");
    }
    
    /* test if the entire string can ba access normaly    */
    if(IsBadReadPtr(DateResult, STR_TIME_SIZE)==0)
    {
        /* compare result with win2000 result */
        if(strcmp( DateResult, STR_SUN_JAN_17_2038)!=0)
        {
            Fail("ERROR: (Test #1) ctime returned an unexpected string " 
                 "%s, expexted string is %s\n"
                 ,DateResult, STR_SUN_JAN_17_2038);
        }
    }
    else
    {
        Fail ("ERROR: (Test #1) ctime returned a bad pointer.\n");
    }


    /*
     * Test #2
     */

    /* Set the valid date in time_t format, adjusted for current time zone */
    LTime = VAL_FRI_JAN_02_1970 + (tzInformation.Bias * 60);

    /* convert it to string using ctime   */
    DateResult = ctime( &LTime );

    /* if it's null, ctime failed*/
    if (DateResult == NULL)
    {
        Fail ("ERROR: (Test #2) ctime returned NULL. Expected string\n");
    }   

    /* test if the entire string can ba access normaly    */
    if(IsBadReadPtr(DateResult, STR_TIME_SIZE)==0)
    {
        /* compare result with win2000 result  */
        if (strcmp(DateResult, STR_FRI_JAN_02_1970) != 0
            && strcmp(DateResult, STR_FRI_JAN__2_1970) != 0)
        {
            Fail("ERROR: (Test #2) ctime returned an unexpected string " 
                 "%s, expected string is %s\n"
                 ,DateResult, STR_FRI_JAN_02_1970);
        }
    }
    else
    {
        Fail ("ERROR: (Test #2) ctime returned a bad pointer.\n");
    }       


    
    /*
     * Test #3
     */

    /* specify an invalid time  */
    LTime = -1;

    /* try to convert it        */
    DateResult = ctime( &LTime );    

    /* Check the result for errors, should fail in this case */
    if (DateResult != NULL)
    {
        Fail ("ERROR: (Test #3) ctime returned something different from NULL.:"
              "Expected NULL\n");
    }


    PAL_Terminate();
    return PASS;
}
Esempio n. 5
0
int __cdecl main(int argc, char *argv[]) {

    /* Define some buffers needed for the function */
    char * pResultBuffer = NULL;
    int size = 0;
  
    /* A place to stash the returned values */
    int ReturnValueForLargeBuffer = 0;

    /*
     * Initialize the PAL and return FAILURE if this fails
     */

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }
  
    /* Recieve and allocate the correct amount of memory for the buffer */
    size = ReturnValueForLargeBuffer = GetEnvironmentVariable("PATH",        
                                                              pResultBuffer,  
                                                              0);             
    pResultBuffer = malloc(size);
    if ( pResultBuffer == NULL )
     {
	Fail("ERROR: Failed to allocate memory for pResultBuffer pointer. "
	       "Can't properly exec test case without this.\n");
     }
  
  
    /* Normal case, PATH should fit into this buffer */
    ReturnValueForLargeBuffer = GetEnvironmentVariable("PATH",        
                                                       pResultBuffer,  
                                                       size);  
  
    /* Ensure that it returned a positive value */
    if(ReturnValueForLargeBuffer <= 0) 
    {
	free(pResultBuffer);

        Fail("The return was %d, which indicates that the function failed.\n",
             ReturnValueForLargeBuffer);  
    }

    /* Ensure that it succeeded and copied the correct number of characters.
       If this is true, then the return value should be one less of the size of 
       the buffer.  (Doesn't include that NULL byte)
    */

    if(ReturnValueForLargeBuffer != size-1) 
    {
	free(pResultBuffer);

        Fail("The value returned was %d when it should have been %d.  "
             "This should be the number of characters copied, minus the "
             "NULL byte.\n",ReturnValueForLargeBuffer, size-1);  
    }
  
  
    free(pResultBuffer);
    
    PAL_Terminate();
    return PASS;
}
Esempio n. 6
0
int __cdecl main(int argc, char *argv[])
{
    FILE *tempFile = NULL;
    BOOL bRc = FALSE;
    WCHAR* pTemp = NULL;


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

    //
    // deleting an existing file
    //
    tempFile = fopen("testFile01.tmp", "w");
    if (tempFile == NULL)
    {
        Fail ("DeleteFileW: ERROR: Couldn't create \"DeleteFileW's"
            " testFile.tmp\"\n");
    }

    fprintf(tempFile, "DeleteFileW test file.\n");
    fclose(tempFile);

    pTemp = convert("testFile01.tmp");
    bRc = DeleteFileW(pTemp);
    free(pTemp);
    if (bRc != TRUE)
    {
        Fail ("DeleteFileW: ERROR: Couldn't delete DeleteFileW's"
            " \"testFile01.tmp\"\n");
    }


    //
    // deleting a non-existant file : should fail
    //

    pTemp = convert("testFile02.tmp");
    bRc = DeleteFileW(pTemp);
    free(pTemp);
    if (bRc != FALSE)
    {
        Fail ("DeleteFileW: ERROR: Was able to delete the non-existant"
            " file \"testFile02.tmp\"\n");
    }




    //
    // deleting an open file
    //
    tempFile = fopen("testFile03.tmp", "w");
    if (tempFile == NULL)
    {
        Fail("DeleteFileW: ERROR: Couldn't create \"DeleteFileW's"
            " testFile.tmp\"\n");
    }

    fprintf(tempFile, "DeleteFileW test file.\n");
    fclose(tempFile);

    pTemp = convert("testFile03.tmp");
    bRc = DeleteFileW(pTemp);
    if (bRc != TRUE)
    {
        Fail("DeleteFileW: ERROR: Couldn't delete DeleteFileW's"
            " \"testFile01.tmp\"\n");
        free(pTemp);
    }
    bRc = DeleteFileW(pTemp);
    free(pTemp);




    //
    // delete using wild cards
    //

    // create the test file
    tempFile = fopen("testFile04.tmp", "w");
    if (tempFile == NULL)
    {
        Fail("DeleteFileW: ERROR: Couldn't create DeleteFileW's"
            " \"testFile04.tmp\"\n");
    }
    fprintf(tempFile, "DeleteFileW test file.\n");
    fclose(tempFile);

    // delete using '?'
    pTemp = convert("testFile0?.tmp");
    bRc = DeleteFileW(pTemp);
    free(pTemp);
    if (bRc == TRUE)
    {
        Fail("DeleteFileW: ERROR: Was able to delete using the"
            " \'?\' wildcard\n");
    }

    // delete using '*'
    pTemp = convert("testFile*.tmp");
    bRc = DeleteFileW(pTemp);
    free(pTemp);
    if (bRc == TRUE)
    {
        Fail("DeleteFileW: ERROR: Was able to delete using the"
            " \'*\' wildcard\n");
    }

    pTemp = convert("testFile04.tmp");
    bRc = DeleteFileW(pTemp);
    free(pTemp);
    if (bRc != TRUE)
    {
        Fail ("DeleteFileW: ERROR: Couldn't delete DeleteFileW's"
            " \"testFile04.tmp\"\n");
    }

    PAL_Terminate();  
    return PASS;
}
Esempio n. 7
0
/**
 * main
 * 
 * executable entry point
 */
INT __cdecl main(INT argc, CHAR **argv)
{
    int     i;
    int     err;
    struct  sockaddr_in mySockaddr;
    WSADATA wsaData;
    HANDLE  ReadEvent;

    /* 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 WSARecv */
    WSABUF        wsaBuf[RECV_BUF_COUNT];
    DWORD         dwNbrOfBuf  = RECV_BUF_COUNT;
    DWORD         dwNbrOfByteSent;
    DWORD         dwRecvFlags = 0;
    WSAOVERLAPPED wsaOverlapped;

    char myBuffer[RECV_BUF_SIZE]; 
    
    int addrlen = sizeof(struct sockaddr);

    /* 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( "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( testSockets,
                          numSockets );

        Fail("");
    }

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

    testSockets[0] = WSASocketA( AF_INET, 
                           SOCK_DGRAM, 
                           IPPROTO_UDP,
                           NULL, 
                           0, 
                           WSA_FLAG_OVERLAPPED ); 


    if( testSockets[0] == INVALID_SOCKET )

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

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

        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("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(...)"              
              " returned %d\n",
              GetLastError());

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

        Fail("");
    }    
    
    /* create an event */
    ReadEvent = CreateEvent( NULL,    /*  SD */
                             FALSE,    /* reset type */
                             FALSE,    /* initial state */
                             NULL );  /* object name */
                
    if(ReadEvent==NULL)
    {
        Trace("ERROR: Unexpected failure: "
              "CreateEvent(...)"              
              " returned %d\n",
              GetLastError());

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

        Fail("");
    }

    /* Initialize the WSAOVERLAPPED to 0 */
    memset(&wsaOverlapped, 0, sizeof(WSAOVERLAPPED));

    /* Specify which event to signal when data is arrived*/
    wsaOverlapped.hEvent = ReadEvent;

    /* Initialize the WSABUF structure */
    wsaBuf[0].buf = myBuffer;
    wsaBuf[0].len = RECV_BUF_SIZE; 

    /* Prepare to receive data */
    err = WSARecvFrom( testSockets[0],
                       wsaBuf,
                       dwNbrOfBuf,
                       &dwNbrOfByteSent,
                       &dwRecvFlags,
                       (struct sockaddr *)&mySockaddr,
                       &addrlen,
                       &wsaOverlapped,
                       0 );
    
    if( err != SOCKET_ERROR)      
    {
        
        Trace("ERROR: "
              "WSARecvFrom(...) "
              "returned %d, expected SOCKET_ERROR\n",
              err );       
        
        Fail("");
    }      
    else if( GetLastError()!=WSA_IO_PENDING )
    {
         Trace("ERROR: "
              "WSARecvFrom(...) "
              "returned %d, expected WSA_IO_PENDING\n",
              GetLastError() );

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

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

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

    PAL_Terminate();
    return PASS;
};
Esempio n. 8
0
int __cdecl main(int argc, char **argv)
{
    SIZE_T i;
    DWORD dwRetWFSO;
    DWORD dwRetRT;
    BOOL bRet = TRUE;

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

    /* set results array to FALSE */
    for (i = 0; i < NUM_TESTS; i++)
    {
        bResult[i]=FALSE;
        dwThreadId[i]=0;
    }

    for (i = 0; i < NUM_TESTS; i++)
    {
        if (NULL != testCases[i].lpThreadId)
        {
            testCases[i].lpThreadId = &dwThreadId[i];
        }
        /* pass the index as the thread argument */
        hThread[i] = CreateThread( testCases[i].lpThreadAttributes,   
                                   testCases[i].dwStackSize,          
                                   testCases[i].lpStartAddress,       
                                   (LPVOID)i,
                                   testCases[i].dwCreationFlags,      
                                   testCases[i].lpThreadId);  
        if (hThread[i] == NULL)
        {
            Trace("PALSUITE ERROR: CreateThread('%p' '%d' '%p' '%p' '%d' "
                  "'%p') call failed.\nGetLastError returned '%u'.\n", 
                  testCases[i].lpThreadAttributes, testCases[i].dwStackSize,
                  testCases[i].lpStartAddress, (LPVOID)i, 
                  testCases[i].dwCreationFlags, 
                  testCases[i].lpThreadId, GetLastError());
            cleanup(i - 1);
            Fail("");
        } 

        /* Resume suspended threads */
        if (testCases[i].dwCreationFlags == CREATE_SUSPENDED)
        {   
            dwRetRT = ResumeThread (hThread[i]);
            if (dwRetRT != 1)
            {
                Trace ("PALSUITE ERROR: ResumeThread(%p) "
                       "call returned %d it should have returned %d.\n"
                       "GetLastError returned %u.\n", hThread[i], dwRetRT,
                       1, GetLastError());
                cleanup(i);
                Fail("");
            }
        }
    }

    /* cleanup */
    for (i = 0; i < NUM_TESTS; i++)
    {
        dwRetWFSO = WaitForSingleObject(hThread[i], 10000);
        if (dwRetWFSO != WAIT_OBJECT_0)
        {
            Trace ("PALSUITE ERROR: WaitForSingleObject('%p' '%d') "
                   "call returned %d instead of WAIT_OBJECT_0 ('%d').\n"
                   "GetLastError returned %u.\n", hThread[i], 10000, 
                   dwRetWFSO, WAIT_OBJECT_0, GetLastError());
            cleanup(i);
            Fail("");
        }
    }
    if(!cleanup(NUM_TESTS))
    {
        Fail("");
    }

    for (i = 0; i < NUM_TESTS; i++)
    {
        /* 
         * check to see that all threads were created and were passed 
         * the array index as an argument. 
         */
        if (FALSE == bResult[i])
        {
            bRet = FALSE;
            Trace("PALSUITE ERROR: result[%d]=%d.  It should be %d\n", i, 
                  FALSE, TRUE);
        }
        /* 
         * check to see that lpThreadId received the correct value. 
         */
        if (0 != dwThreadId[i])
        {
            if (dwThreadId[i] != dwThreadId1[i])
            {
                bRet = FALSE;
                Trace("PALSUITE ERROR: dwThreadId[%d]=%p and dwThreadId1[%d]"
                      "=%p\nThese values should be identical.\n",  i, 
                      dwThreadId[i], i, dwThreadId1[i]);
            }
        }
    }  
    if (!bRet)
    {
        cleanup(NUM_TESTS);
        Fail("");
    }

    PAL_Terminate();
    return (PASS);
}
Esempio n. 9
0
int __cdecl main(int argc, char *argv[])
{
    HANDLE  FileMappingHandle;
    HANDLE  OpenFileMappingHandle;
    HANDLE  lpMapViewAddress;
    HANDLE  OpenFileMappingHandle2;
    HANDLE  lpMapViewAddress2;
    const   int LOWORDERSIZE = 1024;
    char    MapObject[] = "myMappingObject";
    char    buf[] = "this is a test";
    char    ch[1024];
    int     RetVal = PASS;


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

    /* Create a named file-mapping object with file handle FileHandle.
     */
    FileMappingHandle = CreateFileMapping(
                                INVALID_HANDLE_VALUE,
                                NULL,               /* not inherited */
                                PAGE_READWRITE,     /* read and write */
                                0,                  /* high-order size */
                                LOWORDERSIZE,       /* low-order size */
                                MapObject);         /* named object */


    if(NULL == FileMappingHandle) 
    {
        Fail("\nFailed to call CreateFileMapping to create "
             "a mapping object!\n");
    }
    if(GetLastError() == ERROR_ALREADY_EXISTS)
    {
        Trace("\nFile mapping object already exists!\n");
        RetVal = FAIL;
        goto CleanUpOne;
    }

    /* Open a named file-mapping object with FILE_MAP_WRITE access.
     */
    OpenFileMappingHandle =  OpenFileMapping(
                                    FILE_MAP_WRITE,
                                    FALSE,
                                    MapObject);

    if(NULL == OpenFileMappingHandle)
    {
        Trace("\nFailed to Call OpenFileMapping API!\n");
        RetVal = FAIL;
        goto CleanUpOne;
    }

    /* Open a named file-mapping object with 
     * FILE_MAP_ALL_ACCESS access, to verify
     * the FILE_MAP_WRITE access map.
     */
    OpenFileMappingHandle2 =  OpenFileMapping(
                                    FILE_MAP_ALL_ACCESS,
                                    FALSE,
                                    MapObject);

    if(NULL == OpenFileMappingHandle2)
    {
        Trace("\nFailed to Call OpenFileMapping API!\n");
        RetVal = FAIL;
        goto CleanUpTwo;
    }

    /* Create map view of the open mapping that has
     * FILE_MAP_WRITE access.
     */
    lpMapViewAddress = MapViewOfFile(
                            OpenFileMappingHandle,
                            FILE_MAP_WRITE,      /* access code */
                            0,                   /* high order offset */
                            0,                   /* low order offset */
                            LOWORDERSIZE);       /* number of bytes for map */

    if(NULL == lpMapViewAddress)
    {
        Trace("ERROR:%u: Failed to call MapViewOfFile "
              "API to map a view of file!\n", 
              GetLastError());
        RetVal = FAIL;
        goto CleanUpThree;
    }

    /* Create map view of the open mapping that has
     * FILE_MAP_ALL_ACCESS access.
     */
    lpMapViewAddress2 = MapViewOfFile(
                            OpenFileMappingHandle2,
                            FILE_MAP_ALL_ACCESS, /* access code */
                            0,                   /* high order offset */
                            0,                   /* low order offset */
                            LOWORDERSIZE);       /* number of bytes for map */

    if(NULL == lpMapViewAddress2)
    {
        Trace("ERROR:%u: Failed to call MapViewOfFile "
              "API to map a view of file!\n", 
              GetLastError());
        RetVal = FAIL;
        goto CleanUpFour;
    }

    /* Write to the Map View.
     */
    memcpy(lpMapViewAddress, buf, strlen(buf));
    
    /* Read from the Map View.
    */
    memcpy(ch, (LPCSTR)lpMapViewAddress, LOWORDERSIZE); 
    
    /* Compare what was written to the Map View,
     * to what was read.
     */
    if (memcmp(ch, buf, strlen(buf))!= 0)
    {
        Fail("ERROR: MapViewOfFile not equal to file contents "
             "retrieved \"%s\", expected \"%s\".\n",
             ch, buf);
        RetVal = FAIL;
        goto CleanUpFive;
    }

CleanUpFive:
        
        /* Unmap the view of file.
         */
        if ( UnmapViewOfFile(lpMapViewAddress2) == FALSE )
        {
            Trace("ERROR:%u: Failed to UnmapViewOfFile of \"%0x%lx\".\n",
                  GetLastError(),
                  lpMapViewAddress2);
            RetVal = FAIL;
        }

CleanUpFour:
        
        /* Unmap the view of file.
         */
        if ( UnmapViewOfFile(lpMapViewAddress) == FALSE )
        {
            Trace("ERROR:%u: Failed to UnmapViewOfFile of \"%0x%lx\".\n",
                  GetLastError(),
                  lpMapViewAddress);
            RetVal = FAIL;
        }

CleanUpThree:

        /* Close Handle to opened file mapping.
         */
        if ( CloseHandle(OpenFileMappingHandle2) == 0 )
        {
            Trace("ERROR:%u: Failed to CloseHandle \"0x%lx\".\n",
                  GetLastError(),
                  OpenFileMappingHandle2);
            RetVal = FAIL;
        }

CleanUpTwo:

        /* Close Handle to opened file mapping.
         */
        if ( CloseHandle(OpenFileMappingHandle) == 0 )
        {
            Trace("ERROR:%u: Failed to CloseHandle \"0x%lx\".\n",
                  GetLastError(),
                  OpenFileMappingHandle);
            RetVal = FAIL;
        }

CleanUpOne:
        
        /* Close Handle to create file mapping.
         */
        if ( CloseHandle(FileMappingHandle) == 0 )
        {
            Trace("ERROR:%u: Failed to CloseHandle \"0x%lx\".\n",
                  GetLastError(),
                  FileMappingHandle);
            RetVal = FAIL;
        }
    

    /* Terminate the PAL.
     */
    PAL_TerminateEx(RetVal);
    return RetVal;
}
Esempio n. 10
0
// We assume ext has been zero-initialized by its constructor and otherwise
// not modified.
//
// TODO(perf): This sorting of extensions should be be moved into the
// certificate decoder so that the results are cached with the certificate, so
// that the decoding doesn't have to happen more than once per cert.
Result
BackCert::Init(const SECItem& certDER)
{
  // XXX: Currently-known uses of mozilla::pkix create CERTCertificate objects
  // for all certs anyway, so the overhead of CERT_NewTempCertificate will be
  // reduced to a lookup in NSS's SECItem* -> CERTCertificate cache and
  // a CERT_DupCertificate. Eventually, we should parse the certificate using
  // mozilla::pkix::der and avoid the need to create a CERTCertificate at all.
  nssCert = CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
                                    const_cast<SECItem*>(&certDER),
                                    nullptr, false, true);
  if (!nssCert) {
    return MapSECStatus(SECFailure);
  }

  const CERTCertExtension* const* exts = nssCert->extensions;
  if (!exts) {
    return Success;
  }
  // We only decode v3 extensions for v3 certificates for two reasons.
  // 1. They make no sense in non-v3 certs
  // 2. An invalid cert can embed a basic constraints extension and the
  //    check basic constrains will asume that this is valid. Making it
  //    posible to create chains with v1 and v2 intermediates with is
  //    not desirable.
  if (! (nssCert->version.len == 1 &&
      nssCert->version.data[0] == mozilla::pkix::der::Version::v3)) {
    return Fail(RecoverableError, SEC_ERROR_EXTENSION_VALUE_INVALID);
  }

  const SECItem* dummyEncodedSubjectKeyIdentifier = nullptr;
  const SECItem* dummyEncodedAuthorityKeyIdentifier = nullptr;
  const SECItem* dummyEncodedAuthorityInfoAccess = nullptr;
  const SECItem* dummyEncodedSubjectAltName = nullptr;

  for (const CERTCertExtension* ext = *exts; ext; ext = *++exts) {
    const SECItem** out = nullptr;

    // python DottedOIDToCode.py id-ce 2.5.29
    static const uint8_t id_ce[] = {
      0x55, 0x1d
    };

    // python DottedOIDToCode.py id-pe-authorityInfoAccess 1.3.6.1.5.5.7.1.1
    static const uint8_t id_pe_authorityInfoAccess[] = {
      0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x01, 0x01
    };

    if (ext->id.len == PR_ARRAY_SIZE(id_ce) + 1 &&
        !memcmp(ext->id.data, id_ce, PR_ARRAY_SIZE(id_ce))) {
      switch (ext->id.data[ext->id.len - 1]) {
        case 14: out = &dummyEncodedSubjectKeyIdentifier; break; // bug 965136
        case 15: out = &encodedKeyUsage; break;
        case 17: out = &dummyEncodedSubjectAltName; break; // bug 970542
        case 19: out = &encodedBasicConstraints; break;
        case 30: out = &encodedNameConstraints; break;
        case 32: out = &encodedCertificatePolicies; break;
        case 35: out = &dummyEncodedAuthorityKeyIdentifier; break; // bug 965136
        case 37: out = &encodedExtendedKeyUsage; break;
        case 54: out = &encodedInhibitAnyPolicy; break; // Bug 989051
      }
    } else if (ext->id.len == PR_ARRAY_SIZE(id_pe_authorityInfoAccess) &&
               !memcmp(ext->id.data, id_pe_authorityInfoAccess,
                       PR_ARRAY_SIZE(id_pe_authorityInfoAccess))) {
      // We should remember the value of the encoded AIA extension here, but
      // since our TrustDomain implementations get the OCSP URI using
      // CERT_GetOCSPAuthorityInfoAccessLocation, we currently don't need to.
      out = &dummyEncodedAuthorityInfoAccess;
    }

    // If this is an extension we don't understand and it's marked critical,
    // we must reject this certificate.
    // (The only valid explicit value of the critical flag is TRUE because
    // it is defined as BOOLEAN DEFAULT FALSE, so we just assume it is true.)
    if (!out && ext->critical.data && ext->critical.len > 0) {
      return Fail(RecoverableError, SEC_ERROR_UNKNOWN_CRITICAL_EXTENSION);
    }

    if (out) {
      // This is an extension we understand. Save it in results unless we've
      // already found the extension previously.
      if (*out) {
        // Duplicate extension
        return Fail(RecoverableError, SEC_ERROR_EXTENSION_VALUE_INVALID);
      }
      *out = &ext->value;
    }
  }

  return Success;
}
Esempio n. 11
0
int __cdecl main(int argc, char *argv[])
{
    WORD VersionRequested = MAKEWORD(2,2);
    WSADATA WsaData;

    int err;
    int socketID = INVALID_SOCKET;
    const char *data = "None-zero length data test";
    int nBuffer;

    /*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 datagram socket in AF_INET domain*/
    socketID = socket(AF_INET, SOCK_DGRAM, 0);
    if(INVALID_SOCKET == socketID)
    {
        Trace("\nFailed to call socket API to creat a datagram socket!\n");
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }
   
    nBuffer = strlen(data);

    /*call send without calling bind*/  
    err = send(socketID, data, nBuffer, 0);

    if(WSAENOTCONN != GetLastError() || SOCKET_ERROR != err)
    {
        Trace("\nFailed to call send API for a negative test, "
            "call send without calling bind, an error "
            "WSAENOTCONN is expected, but no error or no expected "
            "error is detected, error code = %u\n",GetLastError());

        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)
        {
            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;
}
Esempio n. 12
0
// Recursively build the path from the given subject certificate to the root.
//
// Be very careful about changing the order of checks. The order is significant
// because it affects which error we return when a certificate or certificate
// chain has multiple problems. See the error ranking documentation in
// pkix/pkix.h.
static Result
BuildForward(TrustDomain& trustDomain,
             BackCert& subject,
             PRTime time,
             EndEntityOrCA endEntityOrCA,
             KeyUsages requiredKeyUsagesIfPresent,
             KeyPurposeId requiredEKUIfPresent,
             const CertPolicyId& requiredPolicy,
             /*optional*/ const SECItem* stapledOCSPResponse,
             unsigned int subCACount,
             /*out*/ ScopedCERTCertList& results)
{
  Result rv;

  TrustLevel trustLevel;
  // If this is an end-entity and not a trust anchor, we defer reporting
  // any error found here until after attempting to find a valid chain.
  // See the explanation of error prioritization in pkix.h.
  rv = CheckIssuerIndependentProperties(trustDomain, subject, time,
                                        endEntityOrCA,
                                        requiredKeyUsagesIfPresent,
                                        requiredEKUIfPresent, requiredPolicy,
                                        subCACount, &trustLevel);
  PRErrorCode deferredEndEntityError = 0;
  if (rv != Success) {
    if (endEntityOrCA == EndEntityOrCA::MustBeEndEntity &&
        trustLevel != TrustLevel::TrustAnchor) {
      deferredEndEntityError = PR_GetError();
    } else {
      return rv;
    }
  }

  if (trustLevel == TrustLevel::TrustAnchor) {
    // End of the recursion.

    // Construct the results cert chain.
    results = CERT_NewCertList();
    if (!results) {
      return MapSECStatus(SECFailure);
    }
    for (BackCert* cert = &subject; cert; cert = cert->childCert) {
      CERTCertificate* dup = CERT_DupCertificate(cert->GetNSSCert());
      if (CERT_AddCertToListHead(results.get(), dup) != SECSuccess) {
        CERT_DestroyCertificate(dup);
        return MapSECStatus(SECFailure);
      }
      // dup is now owned by results.
    }

    // This must be done here, after the chain is built but before any
    // revocation checks have been done.
    SECStatus srv = trustDomain.IsChainValid(results.get());
    if (srv != SECSuccess) {
      return MapSECStatus(srv);
    }

    return Success;
  }

  if (endEntityOrCA == EndEntityOrCA::MustBeCA) {
    // Avoid stack overflows and poor performance by limiting cert chain
    // length.
    static const unsigned int MAX_SUBCA_COUNT = 6;
    if (subCACount >= MAX_SUBCA_COUNT) {
      return Fail(RecoverableError, SEC_ERROR_UNKNOWN_ISSUER);
    }
    ++subCACount;
  } else {
    PR_ASSERT(subCACount == 0);
  }

  // Find a trusted issuer.
  // TODO(bug 965136): Add SKI/AKI matching optimizations
  ScopedCERTCertList candidates;
  if (trustDomain.FindPotentialIssuers(&subject.GetNSSCert()->derIssuer, time,
                                       candidates) != SECSuccess) {
    return MapSECStatus(SECFailure);
  }
  if (!candidates) {
    return Fail(RecoverableError, SEC_ERROR_UNKNOWN_ISSUER);
  }

  PRErrorCode errorToReturn = 0;

  for (CERTCertListNode* n = CERT_LIST_HEAD(candidates);
       !CERT_LIST_END(n, candidates); n = CERT_LIST_NEXT(n)) {
    rv = BuildForwardInner(trustDomain, subject, time, requiredEKUIfPresent,
                           requiredPolicy, n->cert->derCert, subCACount,
                           results);
    if (rv == Success) {
      // If we found a valid chain but deferred reporting an error with the
      // end-entity certificate, report it now.
      if (deferredEndEntityError != 0) {
        return Fail(FatalError, deferredEndEntityError);
      }

      SECStatus srv = trustDomain.CheckRevocation(endEntityOrCA,
                                                  subject.GetNSSCert(),
                                                  n->cert, time,
                                                  stapledOCSPResponse);
      if (srv != SECSuccess) {
        return MapSECStatus(SECFailure);
      }

      // We found a trusted issuer. At this point, we know the cert is valid
      // and results contains the complete cert chain.
      return Success;
    }
    if (rv != RecoverableError) {
      return rv;
    }

    PRErrorCode currentError = PR_GetError();
    switch (currentError) {
      case 0:
        PR_NOT_REACHED("Error code not set!");
        return Fail(FatalError, PR_INVALID_STATE_ERROR);
      case SEC_ERROR_UNTRUSTED_CERT:
        currentError = SEC_ERROR_UNTRUSTED_ISSUER;
        break;
      default:
        break;
    }
    if (errorToReturn == 0) {
      errorToReturn = currentError;
    } else if (errorToReturn != currentError) {
      errorToReturn = SEC_ERROR_UNKNOWN_ISSUER;
    }
  }

  if (errorToReturn == 0) {
    errorToReturn = SEC_ERROR_UNKNOWN_ISSUER;
  }

  return Fail(RecoverableError, errorToReturn);
}
Esempio n. 13
0
static int Launch()
{
  Log(L"Launching browser...");

  DWORD processID;

  // The interface that allows us to activate the browser
  CComPtr<IApplicationActivationManager> activateMgr;
  if (FAILED(CoCreateInstance(CLSID_ApplicationActivationManager, nullptr,
                              CLSCTX_LOCAL_SERVER,
                              IID_IApplicationActivationManager,
                              (void**)&activateMgr))) {
    Fail(false, L"CoCreateInstance CLSID_ApplicationActivationManager failed.");
    return FAILURE;
  }
  
  HRESULT hr;
  WCHAR appModelID[256];
  // Activation is based on the browser's registered app model id
  if (!GetDefaultBrowserAppModelID(appModelID, (sizeof(appModelID)/sizeof(WCHAR)))) {
    Fail(false, L"GetDefaultBrowserAppModelID failed.");
    return FAILURE;
  }
  Log(L"App model id='%s'", appModelID);

  // Hand off focus rights if the terminal has focus to the out-of-process
  // activation server (explorer.exe). Without this the metro interface
  // won't launch.
  hr = CoAllowSetForegroundWindow(activateMgr, nullptr);
  if (FAILED(hr)) {
    // Log but don't fail. This has happened on vms with certain terminals run by
    // QA during mozmill testing.
    Log(L"Windows focus rights hand off failed (HRESULT=0x%X). Ignoring.", hr);
  }

  Log(L"Harness process id: %d", GetCurrentProcessId());

  // If provided, validate the firefox path passed in.
  int binLen = wcslen(kFirefoxExe);
  if (sFirefoxPath.GetLength() && sFirefoxPath.Right(binLen) != kFirefoxExe) {
    Log(L"firefoxpath is missing a valid bin name! Assuming '%s'.", kFirefoxExe);
    if (sFirefoxPath.Right(1) != L"\\") {
      sFirefoxPath += L"\\";
    }
    sFirefoxPath += kFirefoxExe;
  }

  // Because we can't pass command line args, we store params in a
  // tests.ini file in dist/bin which the browser picks up on launch.
  CStringA testFilePath;
  if (sFirefoxPath.GetLength()) {
    // Use the firefoxpath passed to us by the test harness
    int index = sFirefoxPath.ReverseFind('\\');
    if (index == -1) {
      Fail(false, L"Bad firefoxpath path");
      return FAILURE;
    }
    testFilePath = sFirefoxPath.Mid(0, index);
    testFilePath += "\\";
    testFilePath += kMetroTestFile;
  } else {
    // Use the module path
    char path[MAX_PATH];
    if (!GetModuleFileNameA(nullptr, path, MAX_PATH)) {
      Fail(false, L"GetModuleFileNameA errorno=%d", GetLastError());
      return FAILURE;
    }
    char* slash = strrchr(path, '\\');
    if (!slash)
      return FAILURE;
    *slash = '\0'; // no trailing slash
    testFilePath = path;
    testFilePath += "\\";
    sFirefoxPath = testFilePath;
    sFirefoxPath += kFirefoxExe;
    testFilePath += kMetroTestFile;
  }

  // Make sure the firefox bin exists
  if (GetFileAttributesW(sFirefoxPath) == INVALID_FILE_ATTRIBUTES) {
    Fail(false, L"Invalid bin path: '%s'", sFirefoxPath);
    return FAILURE;
  }

  Log(L"Using bin path: '%s'", sFirefoxPath);

  Log(L"Writing out tests.ini to: '%s'", CStringW(testFilePath));
  HANDLE hTestFile = CreateFileA(testFilePath, GENERIC_WRITE,
                                 0, nullptr, CREATE_ALWAYS,
                                 FILE_ATTRIBUTE_NORMAL,
                                 nullptr);
  if (hTestFile == INVALID_HANDLE_VALUE) {
    Fail(false, L"CreateFileA errorno=%d", GetLastError());
    return FAILURE;
  }

  DeleteTestFileHelper dtf(testFilePath);

  // nsAppRunner expects the first param to be the bin path, just like a
  // normal startup. So prepend our bin path to our param string we write.
  CStringA asciiParams = sFirefoxPath;
  asciiParams += " ";
  asciiParams += sAppParams;
  asciiParams.Trim();
  Log(L"Browser command line args: '%s'", CString(asciiParams));
  if (!WriteFile(hTestFile, asciiParams, asciiParams.GetLength(),
                 nullptr, 0)) {
    CloseHandle(hTestFile);
    Fail(false, L"WriteFile errorno=%d", GetLastError());
    return FAILURE;
  }
  FlushFileBuffers(hTestFile);
  CloseHandle(hTestFile);

  // Create a named stdout pipe for the browser
  if (!SetupTestOutputPipe()) {
    Fail(false, L"SetupTestOutputPipe failed (errno=%d)", GetLastError());
    return FAILURE;
  }

  // Launch firefox
  hr = activateMgr->ActivateApplication(appModelID, L"", AO_NOERRORUI, &processID);
  if (FAILED(hr)) {
    Fail(true, L"ActivateApplication result %X", hr);
    return RETRY;
  }

  Log(L"Activation succeeded.");

  // automation.py picks up on this, don't mess with it.
  Log(L"METRO_BROWSER_PROCESS=%d", processID);

  HANDLE child = OpenProcess(SYNCHRONIZE, FALSE, processID);
  if (!child) {
    Fail(false, L"Couldn't find child process. (%d)", GetLastError());
    return FAILURE;
  }

  Log(L"Waiting on child process...");

  MSG msg;
  DWORD waitResult = WAIT_TIMEOUT;
  HANDLE handles[2] = { child, gTestOutputPipe };
  while ((waitResult = MsgWaitForMultipleObjects(2, handles, FALSE, INFINITE, QS_ALLINPUT)) != WAIT_OBJECT_0) {
    if (waitResult == WAIT_FAILED) {
      Log(L"Wait failed (errno=%d)", GetLastError());
      break;
    } else if (waitResult == WAIT_OBJECT_0 + 1) {
      ReadPipe();
    } else if (waitResult == WAIT_OBJECT_0 + 2 &&
               PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }
  }

  ReadPipe();
  CloseHandle(gTestOutputPipe);
  CloseHandle(child);

  Log(L"Exiting.");
  return SUCCESS;
}
Esempio n. 14
0
int __cdecl main(int argc, char *argv[])
{
    BOOL bRc = FALSE;
    char szDirName[252];
    DWORD curDirLen;
    char *szTemp = NULL;
    char *szTemp2 = NULL;
    char szwCurrentDir[MAX_PATH];
    char szwSubDir[MAX_PATH];

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

    /*
     * remove a NULL directory 
     */
    bRc = RemoveDirectoryA(NULL);
    if (bRc != FALSE)
    {
        Fail("Error[%ul]:RemoveDirectoryA: Failed since it was able to remove a"
            " NULL directory name\n", GetLastError());
    }

    /* 
     * remove a directory that does not exist 
     */
    szTemp = (char *) malloc (sizeof("test_directory"));
    sprintf(szTemp, "test_directory");
    bRc = RemoveDirectoryA(szTemp);
    if (bRc != FALSE)
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Failed since it was able to remove"
            " the non-existant directory \"test_directory\"\n", GetLastError());
    }

    /* 
     * remove a symlink to a directory
     */
    bRc = CreateDirectoryA(szTemp, NULL);
    if (bRc != TRUE)
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to create the directory "
            "\"test_directory\".\n", GetLastError());
    }

    char *szSymlinkName = (char *) malloc (sizeof("test_directory_symlink"));
    sprintf(szSymlinkName, "test_directory_symlink");
    if (symlink(szTemp, szSymlinkName) != 0)
    {
        Fail("Error:RemoveDirectoryA: Failed to create a symlink to the directory \"test_directory\".\n");
    }

    bRc = RemoveDirectoryA(szSymlinkName);
    if (bRc != FALSE)
    {
        Fail("Error:RemoveDirectoryA: RemoveDirectoryA should return FALSE when passed a symlink.\n");
    }

    unlink(szSymlinkName);

    /* 
     * remove a directory that exists 
     */
    bRc = RemoveDirectoryA(szTemp);
    if (bRc == FALSE)
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryW: Failed to remove the directory "
            "\"test_directory\"\n",
            GetLastError());
    }
    /* Make sure the directory was removed */
    if( -1 != GetFileAttributesA(szTemp) )
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Able to get the attributes of "
             "the removed directory\n" , GetLastError());
    }
    free(szTemp);

    /* 
     * remove long directory names (245 characters) 
     */
    curDirLen = GetCurrentDirectoryA(0, NULL) + 1;
    memset(szDirName, 0, 252);
    memset(szDirName, 'a', 245 - curDirLen);
    szTemp = (char *) malloc (sizeof(szDirName));
    szTemp = strncpy(szTemp, szDirName, strlen(szDirName) + 1);

    bRc = CreateDirectoryA(szTemp, NULL);
    if (bRc == FALSE)
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to create a directory name "
            "245 chars long\n" , GetLastError());
    }
    bRc = RemoveDirectoryA(szTemp);
    if (bRc == FALSE)
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to remove a 245 char "
            "long directory\n", GetLastError());
    }

    /* Make sure the directory was removed */
    if( -1 != GetFileAttributesA(szTemp) )
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Able to get the attributes of "
             "the removed directory\n", GetLastError());
    }
    free(szTemp);

    /* 
     * directories with dots 
     */
    memset(szDirName, 0, 252);
    sprintf(szDirName, ".dotDirectory");
    szTemp = (char *) malloc (sizeof(szDirName));
    szTemp = strncpy(szTemp, szDirName, strlen(szDirName) + 1);

    bRc = CreateDirectoryA(szTemp, NULL);
    if (bRc == FALSE)
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to create \"%s\"\n", GetLastError(), szDirName);
    }
    bRc = RemoveDirectoryA(szTemp);
    if (bRc == FALSE)
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to remove \"%s\"\n", GetLastError(), szDirName);
    }

    /* Make sure the directory was removed */
    if( -1 != GetFileAttributesA(szTemp) )
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Able to get the attributes of "
             "the removed directory\n", GetLastError());
    }
    free(szTemp);

    /* 
     * Try calling RemoveDirectory with a file name
     */
    memset(szDirName, 0, 252);
    sprintf(szDirName, "removedirectoryw.c");
    szTemp = (char *) malloc (sizeof(szDirName));
    szTemp = strncpy(szTemp, szDirName, strlen(szDirName) + 1);

    bRc = RemoveDirectoryA(szTemp);
    free(szTemp);
    if (bRc != FALSE)
    {
        Fail("Error[%ul]:RemoveDirectoryA: should have failed when "
             "called with a valid file name", GetLastError() );
    }

    /* 
     * remove a non empty directory 
     *
     * To test that, we'll first create non_empty_dir, we'll
     * set the current dir to non_empty_dir in which we'll
     * create sub_dir. We'll go back to the root of non_empty_dir
     * and we'll try to delete it (it shouldn't work).
     * After that we'll cleanup sub_dir and non_empty_dir 
     */

    /* Get the current directory so it is easy to get back
       to it later */
    if( 0 == GetCurrentDirectoryA(MAX_PATH, szwCurrentDir) )
    {
        Fail("RemoveDirectoryA: Failed to get current directory "
            "with GetCurrentDirectoryA.\n");
    }

    /* Create non_empty_dir */
    sprintf( szDirName, "non_empty_dir");
    szTemp = (char *) malloc (sizeof(szDirName));
    szTemp = strncpy(szTemp, szDirName, strlen(szDirName) + 1);
    bRc = CreateDirectoryA(szTemp, NULL);
    if (bRc != TRUE)
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to create the directory "
             "\"non_empty_dir\" when it exists already.\n", GetLastError());
    }

    if( 0 == SetCurrentDirectoryA(szTemp) )
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to set current directory to "
            "\"non_empty_dir\" with SetCurrentDirectoryA.\n", GetLastError());
    }

    /* Get the directory full path so it is easy to get back
       to it later */
    if( 0 == GetCurrentDirectoryA(MAX_PATH, szwSubDir) )
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to get current directory "
            "with GetCurrentDirectoryA.\n", GetLastError());
    }

    /* Create sub_dir */
    sprintf (szDirName, "sub_dir");
    szTemp2 = (char *) malloc (sizeof(szDirName));
    szTemp2 = strncpy(szTemp2, szDirName, strlen(szDirName) + 1);
    bRc = CreateDirectoryA(szTemp2, NULL);
    if (bRc != TRUE)
    {
        free(szTemp);
        free(szTemp2);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to create the directory "
            "\"sub_dir\" when it exists already.\n", GetLastError());
    }

    /* Set the current dir to the parent of non_empty_dir/sub_dir */
    if( 0 == SetCurrentDirectoryA(szwCurrentDir) )
    {
        free(szTemp);
        free(szTemp2);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to set current directory to "
            "\"non_empty_dir\" with SetCurrentDirectoryA.\n", GetLastError());
    }

    /* Try to remove non_empty_dir (shouldn't work) */
    bRc = RemoveDirectoryA(szTemp);
    if (bRc == TRUE)
    {
        free(szTemp);
        free(szTemp2);
        Fail("Error[%ul]:RemoveDirectoryA: shouldn't have been able to remove "
             "the non empty directory \"non_empty_dir\"\n", GetLastError());
    }

    /* Go back to non_empty_dir and remove sub_dir */
    if( 0 == SetCurrentDirectoryA(szwSubDir) )
    {
        free(szTemp);
        free(szTemp2);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to set current directory to "
            "\"non_empty_dir\" with SetCurrentDirectoryA.\n", GetLastError());
    }

    bRc = RemoveDirectoryA(szTemp2);
    if (bRc == FALSE)
    {
        free(szTemp);
        free(szTemp2);
        Fail("Error[%ul]:RemoveDirectoryA: unable to remove "
             "directory \"sub_dir\" \n",
             GetLastError());
    }
    /* Make sure the directory was removed */
    if( -1 != GetFileAttributesA(szTemp2) )
    {
        Fail("Error[%ul]RemoveDirectoryA: Able to get the attributes of "
             "the removed directory\n", GetLastError());
    }
    free(szTemp2);

    /* Go back to parent of non_empty_dir and remove non_empty_dir */
    if( 0 == SetCurrentDirectoryA(szwCurrentDir) )
    {
        free(szTemp);
        Fail("Error[%ul]:RemoveDirectoryA: Failed to set current directory to "
            "\"..\non_empty_dir\" with SetCurrentDirectoryA.\n", GetLastError());
    }
    bRc = RemoveDirectoryA(szTemp);
    if (bRc == FALSE)
    {
        free(szTemp);    
        Fail("Error[%ul]RemoveDirectoryA: unable to remove "
             "the directory \"non_empty_dir\"\n",
             GetLastError());
    }
    /* Make sure the directory was removed */
    if( -1 != GetFileAttributesA(szTemp) )
    {
        Fail("Error[%ul]:RemoveDirectoryA: Able to get the attributes of "
             "the removed directory\n", GetLastError());
    }
    free(szTemp); 


    PAL_Terminate();  
    return PASS;
}
Esempio n. 15
0
int __cdecl main(int argc, char *argv[])
{
    WORD VersionRequested = MAKEWORD(2, 2);
    WSADATA WsaData;

    int nLength;
    int err;
    int InvalidSocketID = -1;
    struct sockaddr_in mySockaddr;
    char data[BUFFERSIZE];

    /*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("");
    }


    nLength = sizeof(struct sockaddr);
    memset(data, 0, BUFFERSIZE);

    /*retrive data with an invalid socket*/ 
    err = recvfrom(InvalidSocketID, data, BUFFERSIZE, 0,
                (struct sockaddr*)&mySockaddr,&nLength);

    if(WSAENOTSOCK != GetLastError() || SOCKET_ERROR != err)
    {
        Trace("\nFailed to call recvfrom API for a negative test "
                "by passing an invalid socket descriptor!\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;
}
Esempio n. 16
0
/*
 * NaN: any double with maximum exponent (0x7ff) and non-zero fraction
 */
int __cdecl main(int argc, char *argv[])
{
    UINT64 PosInf=0;
    UINT64 NegInf=0;
    UINT64 val=0;

    /*
     * Initialize the PAL and return FAIL if this fails
     */
    if (0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }
    /*
     * Try some trivial values
     */
    if (_isnan(0))
    {
        Fail ("_isnan() incorrectly identified %f as NaN!\n", 0);
    }
    if (_isnan(1.2423456))
    {
        Fail ("_isnan() incorrectly identified %f as NaN!\n", 0);
    }
    if (_isnan(42))
    {
        Fail ("_isnan() incorrectly identified %f as NaN!\n", 0);
    }


    PosInf = 0x7ff00000;
    PosInf <<=32;

    NegInf = 0xfff00000;
    NegInf <<=32;

    /*
     * Try positive and negative infinity
     */
    if (_isnan(TO_DOUBLE(PosInf)))
    {
        Fail ("_isnan() incorrectly identified %I64x as NaN!\n", PosInf);
    }

    if (_isnan(TO_DOUBLE(NegInf)))
    {
        Fail ("_isnan() incorrectly identified %I64x as NaN!\n", NegInf);
    }

    /*
     * Try setting the least significant bit of the fraction,
     * positive and negative
     */
    val = PosInf + 1;
    if (!_isnan(TO_DOUBLE(val)))
    {
        Fail ("_isnan() failed to identify %I64x as NaN!\n", val);
    }

    val = NegInf + 1;
    if (!_isnan(TO_DOUBLE(val)))
    {
        Fail ("_isnan() failed to identify %I64x as NaN!\n", val);
    }


    /*
     * Try setting the most significant bit of the fraction,
     * positive and negative
     */
    val = 0x7ff80000;
    val <<=32;
    if (!_isnan(TO_DOUBLE(val)))
    {
        Fail ("_isnan() failed to identify %I64x as NaN!\n", val);
    }

    val = 0xfff80000;
    val <<=32;
    if (!_isnan(TO_DOUBLE(val)))
    {
        Fail ("_isnan() failed to identify %I64x as NaN!\n", val);
    }

    PAL_Terminate();

    return PASS;
}
Esempio n. 17
0
int __cdecl main(int argc, char *argv[])
{
    WORD VersionRequested = MAKEWORD(2,2);
    WSADATA WsaData;
    SOCKET aSocket;
    int optval = 1;/*set the socket option enable flag*/
    int nLength;
    int err;
    int socketID;
    struct sockaddr_in mySockaddr;
    struct sockaddr mySocketaddrConnect;
    int nSocketaddrLength;
    int nBacklogNumber = 1;
    char data[BUFFERSIZE];
    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 readable 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);
   
    err = bind(socketID,(struct sockaddr *)&mySockaddr,
            sizeof(struct sockaddr));
    if(SOCKET_ERROR == err)
    {
        Trace("\nFailed to call bind API to 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("");
        }
        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("");
        }
        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("");
        }
        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("");
        }
        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 = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    /*enalbe the socket option SO_OOBINLINE*/
    err = setsockopt(aSocket,SOL_SOCKET,SO_OOBINLINE,
        (const char *)&optval,sizeof(int));
    if(SOCKET_ERROR == err)
    {
        Trace("\nFailed to call setsockopt API to set socket option!\n");
        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)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    nLength = sizeof(struct sockaddr);
    /*retrive data with specified MSG_OOB*/
    err = recvfrom(aSocket,data,BUFFERSIZE,MSG_OOB,
            (struct sockaddr*)&mySockaddr,&nLength);
    if(WSAEINVAL != GetLastError() || SOCKET_ERROR != err)
    {
        Trace("\nFailed to call recvfrom API for a negative test "
                "with MSG_OOB flag!\n");
        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)
        {
            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;
}
Esempio n. 18
0
int MkView::Execute(int oc, Tcl_Obj *const * ov) {
  struct CmdDef {
    int(MkView:: *proc)();
    int min;
    int max;
    const char *desc;
  };

  static const char *subCmds[] =  {
    "close", "delete", "exists", "find", "get", "properties", "insert", "open",
      "search", "select", "set", "size", "loop", "view", "info",  
      // will be deprecated (use "properties" instead)
    0
  };
  static CmdDef defTab[] =  {
    // the "&MkView::" stuff is required for Mac cwpro2
     {
       &MkView::CloseCmd, 2, 2, "close"
    }
    ,  {
       &MkView::DeleteCmd, 3, 4, "delete cursor ?cursor2?"
    }
    ,  {
       &MkView::ExistsCmd, 3, 0, "exists cursor ?prop ...?"
    }
    ,  {
       &MkView::FindCmd, 2, 0, "find ?prop value ...?"
    }
    ,  {
       &MkView::GetCmd, 3, 0, "get cursor ?prop ...?"
    }
    ,  {
       &MkView::InfoCmd, 2, 2, "properties"
    }
    ,  {
       &MkView::InsertCmd, 3, 0, "insert cursor ?prop ...?"
    }
    ,  {
       &MkView::OpenCmd, 4, 4, "open cursor prop"
    }
    ,  {
       &MkView::SearchCmd, 4, 4, "search prop value"
    }
    ,  {
       &MkView::SelectCmd, 2, 0, "select ?..?"
    }
    ,  {
       &MkView::SetCmd, 3, 0, "set cursor prop ?value prop value ...?"
    }
    ,  {
       &MkView::SizeCmd, 2, 3, "size ?newsize?"
    }
    ,  {
       &MkView::LoopCmd, 3, 0, "loop cursor ?first? ?limit? ?step? body"
    }
    ,  {
       &MkView::ViewCmd, 3, 0, "view option ?args?"
    }
    ,  {
       &MkView::InfoCmd, 2, 2, "info"
    }
    ,  {
      0, 0, 0, 0
    }
    , 
  };
  _error = TCL_OK;

  int id = tcl_GetIndexFromObj(ov[1], subCmds);

  if (id ==  - 1)
    return TCL_ERROR;

  CmdDef &cd = defTab[id];

  objc = oc;
  objv = ov;

  if (oc < cd.min || (cd.max > 0 && oc > cd.max)) {
    msg = "wrong # args: should be \"$obj ";
    msg += cd.desc;
    msg += "\"";

    return Fail(msg);
  }

  return (this->*cd.proc)();
}
Esempio n. 19
0
int __cdecl main(int argc, char *argv[])
{

    HANDLE FileHandle;
    HANDLE FileMappingHandle;
    int err;
    WCHAR *lpFileName = NULL;

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

    //conver string to a unicode one
    lpFileName = convert("temp.txt");


    //create a file and return the file handle
    FileHandle = CreateFile(lpFileName,
        GENERIC_READ,
        FILE_SHARE_READ,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_ARCHIVE,
        NULL);

    //free this memory
    free(lpFileName);
   
    if(INVALID_HANDLE_VALUE == FileHandle)
    {
        Fail("Failed to call CreateFile to create a file\n");
    }

    //create a unnamed file-mapping object with file handle FileHandle
    //and with PAGE_READONLY protection
    //try to map a file which is zero length.
    FileMappingHandle = CreateFileMapping(
        FileHandle,         //File Handle
        NULL,               //not inherited
        PAGE_READONLY,      //access protection 
        0,                  //high-order of object size
        0,                  //low-orger of object size
        NULL);              //unnamed object


    if(NULL != FileMappingHandle || ERROR_FILE_INVALID != GetLastError()) 
    {//no error occured 
        Trace("\nFailed to call CreateFileMapping API for a negative test!\n");
        err = CloseHandle(FileHandle);
        if(0 == err)
        {
            Fail("\nFailed to call CloseHandle API\n");
        }
        err = CloseHandle(FileMappingHandle);
        if(0 == err)
        {
            Fail("\nFailed to call CloseHandle API\n");
        }
        Fail("");
    }
    
    //close the file handle
    err = CloseHandle(FileHandle);
    if(0 == err)
    {
        Fail("\nFailed to call CloseHandle API\n");
    }

    PAL_Terminate();
    return PASS;
}
Esempio n. 20
0
int MkView::SelectCmd() {
  TclSelector sel(interp, view);

  static const char *opts[] =  {
    "-min",  // 0
    "-max",  // 1
    "-exact",  // 2
    "-glob",  // 3
    "-regexp",  // 4
    "-keyword",  // 5
    "-first",  // 6
    "-count",  // 7
    "-sort",  // 8
    "-rsort",  // 9
    "-globnc",  // 10
    0
  };

  while (objc >= 4) {
    objc -= 2; // gobble next two arguments
    objv += 2;

    // at this point, *objv is the next option, and objc >= 2

    int id =  - 1;

    const char *p = Tcl_GetStringFromObj(*objv, 0);
    if (p &&  *p == '-') {
      id = tcl_GetIndexFromObj(*objv, opts);
      if (id < 0)
        return _error;
    }

    switch (id) {
      case  - 1:  { // prop value : case-insensitive match
        _error = sel.AddCondition( - 1, objv[0], objv[1]);
      }
      break;

      case 0:
        // -min prop value : property must be greater or equal to value
      case 1:
        // -max prop value : property must be less or equal to value
      case 2:
        // -exact prop value : exact case-sensitive match
      case 3:
        // -glob prop pattern : match "glob" expression wildcard
      case 4:
        // -regexp prop pattern : match specified regular expression
      case 5:
        // -keyword prop prefix : match keyword in given property
      case 10:
         { // -globnc prop pattern : match "glob", but ignore case
          if (objc < 3)
            return Fail("not enough arguments");

          _error = sel.AddCondition(id, objv[1], objv[2]);

          --objc; // gobble a third argument
          ++objv;
        }
        break;

      case 6:
        // -first pos : searching starts at specified row index
      case 7:
         { // -count num : return no more than this many results
          int n = tcl_GetIntFromObj(objv[1]);
          if (_error)
            return _error;

          if (id == 6)
            sel._first = n;
          else
            sel._count = n;
        }
        break;

      case 8:
        // -sort prop : sort on one or more properties, ascending
      case 9:
         { // -rsort prop : sort on one or more properties, descending
          c4_View props = sel.GetAsProps(objv[1]);
          for (int i = 0; i < props.NumProperties(); ++i) {
            const c4_Property &prop = props.NthProperty(i);

            sel._sortProps.AddProperty(prop);
            if (id == 9)
              sel._sortRevProps.AddProperty(prop);
          }
        }
        break;
    }
  }

  if (_error)
    return _error;

  c4_View nview;
  sel.DoSelect(0, &nview);
  MkView *ncmd = new MkView(interp, nview);
  return tcl_SetObjResult(tcl_NewStringObj(ncmd->CmdName()));
}
Esempio n. 21
0
int __cdecl main(int argc, char **argv)
{
    HANDLE  hReadPipe   = NULL;
    HANDLE  hWritePipe  = NULL;
    BOOL    bRetVal     = FALSE;
    DWORD   dwFileType;
    SECURITY_ATTRIBUTES lpPipeAttributes;

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

    /*
    ** create a pipe and make sure GetFileType returns the correct value
    */

    /*Setup SECURITY_ATTRIBUTES structure for CreatePipe*/
    lpPipeAttributes.nLength              = sizeof(lpPipeAttributes); 
    lpPipeAttributes.lpSecurityDescriptor = NULL; 
    lpPipeAttributes.bInheritHandle       = TRUE; 

    /*Create a Pipe*/
    bRetVal = CreatePipe(&hReadPipe,      /* read handle*/
                &hWritePipe,              /* write handle */
                &lpPipeAttributes,        /* security attributes*/
                0);                       /* pipe size*/
    if (bRetVal == FALSE)
    {
        Fail("ERROR: %u :Unable to create pipe.\n", GetLastError());
    }

    // Get the file type
    dwFileType = GetFileType(hReadPipe);
    if (dwFileType != FILE_TYPE_PIPE)
    {
        if (!CloseHandle(hWritePipe))
        {
            Trace("ERROR: %u : Unable to close write pipe handle "
                "hWritePipe=0x%lx\n", GetLastError(), hWritePipe);
        }
        if (!CloseHandle(hReadPipe))
        {
            Trace("ERROR: %u : Unable to close read pipe handle "
                "hReadPipe=0x%lx\n", GetLastError(), hReadPipe);
        }
        Fail("ERROR: GetFileType returned %u for a pipe instead of the "
            "expected FILE_TYPE_PIPE (%u).\n",
            dwFileType,
            FILE_TYPE_PIPE);
    }

    /*Close write pipe handle*/
    if (!CloseHandle(hWritePipe))
    {
        if (!CloseHandle(hReadPipe))
        {
            Trace("ERROR: %u : Unable to close read pipe handle "
                "hReadPipe=0x%lx\n", GetLastError(), hReadPipe);
        }
        Fail("ERROR: %u : Unable to close write pipe handle "
             "hWritePipe=0x%lx\n", GetLastError(), hWritePipe);
    }

    /*Close Read pipe handle*/
    if (!CloseHandle(hReadPipe))
    {
        Fail("ERROR: %u : Unable to close read pipe handle "
             "hReadPipe=0x%lx\n", GetLastError(), hReadPipe);
    }

    PAL_Terminate();
    return (PASS);
}
Esempio n. 22
0
int MkView::ViewCmd() {
  struct CmdDef {
    int(MkView:: *proc)();
    int min;
    int max;
    const char *desc;
  };

  static const char *subCmds[] =  {
    "blocked", "clone", "concat", "copy", "different", "dup", "flatten", 
      "groupby", "hash", "indexed", "intersect", "join", "map", "minus", 
      "ordered", "pair", "product", "project", "range", "readonly", "rename", 
      "restrict", "union", "unique", 
#if 0
    "==", "!=", "<", ">", "<=", ">=", 
#endif 
    0
  };
  static CmdDef defTab[] =  {
    // the "&MkView::" stuff is required for Mac cwpro2
     {
       &MkView::BlockedCmd, 2, 2, "blocked"
    }
    ,  {
       &MkView::CloneCmd, 2, 2, "clone"
    }
    ,  {
       &MkView::ConcatCmd, 3, 3, "concat view"
    }
    ,  {
       &MkView::CopyCmd, 2, 3, "copy"
    }
    ,  {
       &MkView::DifferentCmd, 3, 3, "different view"
    }
    ,  {
       &MkView::DupCmd, 2, 2, "dup"
    }
    ,  {
       &MkView::FlattenCmd, 3, 3, "flatten prop"
    }
    ,  {
       &MkView::GroupByCmd, 4, 0, "groupby subview prop ?prop ...?"
    }
    ,  {
       &MkView::HashCmd, 3, 4, "hash map ?numkeys?"
    }
    ,  {
       &MkView::IndexedCmd, 5, 0, "indexed map unique prop ?prop ...?"
    }
    ,  {
       &MkView::IntersectCmd, 3, 3, "intersect view"
    }
    ,  {
       &MkView::JoinCmd, 4, 0, "join view prop ?prop ...?"
    }
    ,  {
       &MkView::MapCmd, 3, 3, "map view"
    }
    ,  {
       &MkView::MinusCmd, 3, 3, "minus view"
    }
    ,  {
       &MkView::OrderedCmd, 2, 3, "ordered ?numkeys?"
    }
    ,  {
       &MkView::PairCmd, 3, 3, "pair view"
    }
    ,  {
       &MkView::ProductCmd, 3, 3, "product view"
    }
    ,  {
       &MkView::ProjectCmd, 3, 0, "project prop ?prop ...?"
    }
    ,  {
       &MkView::RangeCmd, 4, 0, "range start finish ?step?"
    }
    ,  {
       &MkView::ReadOnlyCmd, 2, 2, "readonly"
    }
    ,  {
       &MkView::RenameCmd, 4, 4, "rename oprop nprop"
    }
    ,  {
       &MkView::RestrictCmd, 2, 0, "restrict...."
    }
    ,  {
       &MkView::UnionCmd, 3, 3, "union view"
    }
    ,  {
       &MkView::UniqueCmd, 2, 2, "unique"
    }
    , 
#if 0
     {
       &MkView::OperatorCmd, 3, 3, "== view"
    }
    ,  {
       &MkView::OperatorCmd, 3, 3, "!= view"
    }
    ,  {
       &MkView::OperatorCmd, 3, 3, "< view"
    }
    ,  {
       &MkView::OperatorCmd, 3, 3, "> view"
    }
    ,  {
       &MkView::OperatorCmd, 3, 3, "<= view"
    }
    ,  {
       &MkView::OperatorCmd, 3, 3, ">= view"
    }
    , 
#endif 
     {
      0, 0, 0, 0
    }
    , 
  };
  _error = TCL_OK;

  objc--;
  objv++;

  int id = tcl_GetIndexFromObj(objv[1], subCmds);

  if (id ==  - 1)
    return TCL_ERROR;

  CmdDef &cd = defTab[id];

  if (objc < cd.min || (cd.max > 0 && objc > cd.max)) {
    msg = "wrong # args: should be \"$obj view ";
    msg += cd.desc;
    msg += "\"";

    return Fail(msg);
  }

  return (this->*cd.proc)();
}
Esempio n. 23
0
int __cdecl main(int argc, char *argv[])
{
    WORD VersionRequested = MAKEWORD(2,2);
    WSADATA WsaData;
    int err;
    int socketID;
    struct sockaddr_in mySockaddr;
    char 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 AF_INET domain*/
    socketID = socket(AF_INET,SOCK_STREAM,0);

    if(INVALID_SOCKET == socketID)
    {
        Trace("\nFailed to call socket API to creat a steam 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 to a stream server*/
    err = connect(socketID, (struct sockaddr *)&mySockaddr,
                sizeof(struct sockaddr));
    if(SOCKET_ERROR == err)
    {
        Trace("\nFailed to call connect API to connect a stream server!\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("");
    }

   /* make sure the server calls recv before closing the socket. (recv blocks 
      till the server closes the socket or exits */
    if (recv(socketID, &data, sizeof(data), 0) > 0)
    {
        Trace("\nUnexpected value returned by recv()\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 = WSACleanup();
    if(SOCKET_ERROR == err)
    {
        Fail("\nFailed to call WSACleanup API!\n");
    }

    PAL_Terminate();
    return PASS;
}
Esempio n. 24
0
int __cdecl main( int argc, char **argv ) 
{

    /*******************************************
     *  Declarations
     *******************************************/
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    HANDLE hTestStdInR = NULL;
    HANDLE hTestStdInW = NULL;
    HANDLE hTestStdOutR = NULL;
    HANDLE hTestStdOutW = NULL;
    HANDLE hTestStdErrR = NULL;
    HANDLE hTestStdErrW = NULL;

    BOOL bRetVal = FALSE;
    DWORD dwBytesWritten = 0;
    DWORD dwBytesRead = 0;
    DWORD dwExitCode = 0;

    SECURITY_ATTRIBUTES pipeAttributes;

    char szStdOutBuf[BUF_LEN];
    char szStdErrBuf[BUF_LEN];
    char szFullPathNameA[_MAX_PATH];


    /*******************************************
     *  Initialization
     *******************************************/

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

    /*Setup SECURITY_ATTRIBUTES structure for CreatePipe*/
    pipeAttributes.nLength              = sizeof(SECURITY_ATTRIBUTES); 
    pipeAttributes.lpSecurityDescriptor = NULL; 
    pipeAttributes.bInheritHandle       = TRUE; 
    
    
    /*Create a StdIn pipe for child*/
    bRetVal = CreatePipe(&hTestStdInR,      /* read handle*/
                         &hTestStdInW,      /* write handle */
                         &pipeAttributes,   /* security attributes*/
                         1024);                /* pipe size*/

    if (bRetVal == FALSE)
    {
        Fail("ERROR: %ld :Unable to create stdin pipe\n", GetLastError());
    }


    /*Create a StdOut pipe for child*/
    bRetVal = CreatePipe(&hTestStdOutR,     /* read handle*/
                         &hTestStdOutW,     /* write handle */
                         &pipeAttributes,   /* security attributes*/
                         0);                /* pipe size*/

    if (bRetVal == FALSE)
    {
        Fail("ERROR: %ld :Unable to create stdout pipe\n", GetLastError());
    }


    /*Create a StdErr pipe for child*/
    bRetVal = CreatePipe(&hTestStdErrR,     /* read handle*/
                         &hTestStdErrW,     /* write handle */
                         &pipeAttributes,   /* security attributes*/
                         0);                /* pipe size*/

    if (bRetVal == FALSE)
    {
        Fail("ERROR: %ld :Unable to create stderr pipe\n", GetLastError());
    }

    /* Zero the data structure space */
    ZeroMemory ( &pi, sizeof(pi) );
    ZeroMemory ( &si, sizeof(si) );

    /* Set the process flags and standard io handles */
    si.cb = sizeof(si);
    si.dwFlags = STARTF_USESTDHANDLES;
    si.hStdInput = hTestStdInR;
    si.hStdOutput = hTestStdOutW;
    si.hStdError = hTestStdErrW;

    strcpy(szFullPathNameA, szChildFileA);
    strcat(szFullPathNameA, szArgs);

    /*******************************************
     *  Start Testing
     *******************************************/

    /* Launch the child */
    if ( !CreateProcessA (NULL, szFullPathNameA, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi ))
    {
        Fail("ERROR: CreateProcess call failed.  GetLastError returned %d\n", 
             GetLastError() );
    }

    /* Check the returned process information for validity */
    if (pi.hProcess == 0 || pi.hThread == 0)
    {
        Fail("ERROR: CreateProcess Error: Process Handle = %u, Thread Handle = %u\n",
            pi.hProcess, pi.hThread);
    }

    /* Write the Constructed string to stdin pipe for the child process */
    if (WriteFile(hTestStdInW, szTestString, strlen(szTestString), &dwBytesWritten, NULL) == FALSE
        || WriteFile(hTestStdInW, "\n", strlen("\n"), &dwBytesWritten, NULL) == FALSE)
    {
        Fail("ERROR: %ld :unable to write to write pipe handle "
             "hTestStdInW=0x%lx\n", GetLastError(), hTestStdInW);
    }
    
    /* Wait for the child to finish, Max 20 seconds */
    dwExitCode = WaitForSingleObject(pi.hProcess, 20000);

    /* If the child failed then whole thing fails */
    if (dwExitCode != WAIT_OBJECT_0)
    {
        TerminateProcess(pi.hProcess, 0);
        Fail("ERROR: The child failed to run properly.\n");
    }

    /* Check for problems in the child process */
    if (GetExitCodeProcess(pi.hProcess, &dwExitCode) == FALSE)
    {
        Fail("ERROR: Call to GetExitCodeProcess failed.\n");
    }
    else if (dwExitCode == EXIT_ERR_CODE1)
    {
        Fail("ERROR: The Child process could not reead the string "
             "written to the stdin pipe.\n");
    }
    else if (dwExitCode == EXIT_ERR_CODE2)
    {
        Fail("ERROR: The Child process could not write the string "
             "the stdout pipe or stderr pipe.\n");
    }
    else if (dwExitCode == EXIT_ERR_CODE3)
    {
        Fail("ERROR: The Child received the wrong number of "
             "command line arguments.\n");
    }
    else if (dwExitCode == EXIT_ERR_CODE4)
    {
        Fail("ERROR: The Child received the wrong "
             "command line arguments.\n");
    }
    else if (dwExitCode != EXIT_OK_CODE)
    {
        Fail("ERROR: Unexpected exit code returned: %u.  Child process "
             "did not complete its part of the test.\n", dwExitCode);
    }


    /* The child ran ok, so check to see if we received the proper */
    /* strings through the pipes.                                  */

    /* clear our buffers */
    memset(szStdOutBuf, 0, BUF_LEN);
    memset(szStdErrBuf, 0, BUF_LEN);

    /* Read the data back from the child process stdout */
    bRetVal = ReadFile(hTestStdOutR,       /* handle to read pipe*/
                       szStdOutBuf,        /* buffer to write to*/
                       BUF_LEN,            /* number of bytes to read*/
                       &dwBytesRead,       /* number of bytes read*/
                       NULL);              /* overlapped buffer*/

    /*Read the data back from the child process stderr */
    bRetVal = ReadFile(hTestStdErrR,       /* handle to read pipe*/
                       szStdErrBuf,        /* buffer to write to*/
                       BUF_LEN,                /* number of bytes to read*/
                       &dwBytesRead,       /* number of bytes read*/
                       NULL);              /* overlapped buffer*/


    /* Confirm that we recieved the same string that we originally */
    /* wrote to the child and was received on both stdout & stderr.*/
    if (strncmp(szTestString, szStdOutBuf, strlen(szTestString)) != 0
        || strncmp(szTestString, szStdErrBuf, strlen(szTestString)) != 0)
    {
        Fail("ERROR: The data read back from child does not match "
             "what was written. STDOUT: %s  STDERR: %s\n",
             szStdOutBuf, szStdErrBuf);
    }


    /*******************************************
     *  Clean Up
     *******************************************/

    /* Close process and thread handle */
    CloseHandle ( pi.hProcess );
    CloseHandle ( pi.hThread );

    CloseHandle(hTestStdInR);
    CloseHandle(hTestStdInW);
    CloseHandle(hTestStdOutR);
    CloseHandle(hTestStdOutW);
    CloseHandle(hTestStdErrR);
    CloseHandle(hTestStdErrW);

    PAL_Terminate();
    return ( PASS );
}
Esempio n. 25
0
 int __cdecl main(INT argc, CHAR **argv)
{
    unsigned int i = 0;
    HANDLE hProcess[MAXIMUM_WAIT_OBJECTS];
   
    STARTUPINFO si[MAXIMUM_WAIT_OBJECTS];
    PROCESS_INFORMATION pi[MAXIMUM_WAIT_OBJECTS];

    char lpCommandLine[MAX_PATH] = "";

    int returnCode = 0;
    DWORD processReturnCode = 0;
    int testReturnCode = PASS;

    char fileName[MAX_PATH];
    FILE *pFile = NULL;
    DWORD dwStartTime;
    struct TestStats testStats;

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

    if(GetParameters(argc, argv))
    {
        Fail("Error in obtaining the parameters\n");
    }

     /* Register the start time */  
    dwStartTime = GetTickCount();
    testStats.relationId = 0;
    testStats.relationId   = RELATION_ID;
    testStats.processCount = PROCESS_COUNT;
    testStats.threadCount  = THREAD_COUNT;
    testStats.repeatCount  = REPEAT_COUNT;
    testStats.buildNumber  = getBuildNumber();



    _snprintf(fileName, MAX_PATH, "main_wfmo_%d_.txt",testStats.relationId);
    pFile = fopen(fileName, "w+");
    if(pFile == NULL)
    { 
        Fail("Error in opening main file for write\n");
    }

    for( i = 0; i < PROCESS_COUNT; i++ )
    {

        ZeroMemory( lpCommandLine, MAX_PATH );
        if ( _snprintf( lpCommandLine, MAX_PATH-1, "mutex %d %d %d %d %d", i, THREAD_COUNT, REPEAT_COUNT, SLEEP_LENGTH, RELATION_ID) < 0 )
        {
            Trace ("Error: Insufficient commandline string length for for iteration [%d]\n", i);
        }
        
        /* Zero the data structure space */
        ZeroMemory ( &pi[i], sizeof(pi[i]) );
        ZeroMemory ( &si[i], sizeof(si[i]) );

        /* Set the process flags and standard io handles */
        si[i].cb = sizeof(si[i]);
        
        //Create Process
        if(!CreateProcess( NULL, /* lpApplicationName*/
                          lpCommandLine, /* lpCommandLine */
                          NULL, /* lpProcessAttributes  */
                          NULL, /* lpThreadAttributes */
                          TRUE, /* bInheritHandles */
                          0, /* dwCreationFlags, */
                          NULL, /* lpEnvironment  */
                          NULL, /* pCurrentDirectory  */
                          &si[i], /* lpStartupInfo  */
                          &pi[i] /* lpProcessInformation  */
                          ))
        {
            Fail("Process Not created for [%d], the error code is [%d]\n", i, GetLastError());
        }
        else
        {
            hProcess[i] = pi[i].hProcess;
            // Trace("Process created for [%d]\n", i);
        }

    }

    returnCode = WaitForMultipleObjects( PROCESS_COUNT, hProcess, TRUE, INFINITE);  
    if( WAIT_OBJECT_0 != returnCode )
    {
        Trace("Wait for Object(s) @ Main thread for %d processes returned %d, and GetLastError value is %d\n", PROCESS_COUNT, returnCode, GetLastError());
    }
    
    for( i = 0; i < PROCESS_COUNT; i++ )
    {
        /* check the exit code from the process */
        if( ! GetExitCodeProcess( pi[i].hProcess, &processReturnCode ) )
        {
            Trace( "GetExitCodeProcess call failed for iteration %d with error code %u\n", 
                i, GetLastError() ); 
           
            testReturnCode = FAIL;
        }

        if(processReturnCode == FAIL)
        {
            Trace( "Process [%d] failed and returned FAIL\n", i); 
            testReturnCode = FAIL;
        }

        if(!CloseHandle(pi[i].hThread))
        {
            Trace("Error:%d: CloseHandle failed for Process [%d] hThread\n", GetLastError(), i);
        }

        if(!CloseHandle(pi[i].hProcess) )
        {
            Trace("Error:%d: CloseHandle failed for Process [%d] hProcess\n", GetLastError(), i);
        }
    }

    testStats.operationTime = GetTimeDiff(dwStartTime); 
    fprintf(pFile, "%d,%d,%d,%d,%d,%s\n", testStats.operationTime, testStats.relationId, testStats.processCount, testStats.threadCount, testStats.repeatCount, testStats.buildNumber);
    if(fclose(pFile))
    {
        Trace("Error: fclose failed for pFile\n");
        testReturnCode = FAIL;
    }
    
    if( testReturnCode == PASS)
    {
        Trace("Test Passed\n");
    }
    else
    {
        Trace("Test Failed\n");
    }
    PAL_Terminate();
    return testReturnCode;
}
Esempio n. 26
0
int __cdecl main(int argc, char *argv[])
{
    WORD VersionRequested = MAKEWORD(2, 2);
    WSADATA WsaData;
    SOCKET aSocket = INVALID_SOCKET;
    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;
    }

    nSocketaddrLength = sizeof(mySocketaddrConnect);

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

    if(WSANOTINITIALISED != GetLastError() || INVALID_SOCKET != aSocket)
    {
        Fail("\nFailed to call accept API for a negative test "
            "call accept bafore calling WSAStartup, "
            "error code = %u\n", GetLastError());
    }    

    /*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!\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 setup server 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!\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("");
    }

    /*terminate the use of WinSock DLL*/
    err = WSACleanup();
    if(SOCKET_ERROR == err)
    {
        Fail("\nFailed to call WSACleanup API!\n");
    }

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

    if(WSANOTINITIALISED != GetLastError() || INVALID_SOCKET != aSocket)
    {
        Fail("\nFailed to call accept API for a negative test "
            "call accept after calling WSACleanup, "
            "error code=%u\n", GetLastError());
    }    

    PAL_Terminate();
    return PASS;
}
Esempio n. 27
0
int __cdecl main(int argc, char *argv[])
{    
    char mbStr[128];
    WCHAR wideStr[128];
    int ret;
    int i;
    int k;
    BOOL bRet=TRUE;

    /* These codepages are currently supported by the PAL */
    int codePages[] ={
        CP_ACP,
        932,
        949,
        950,
        1252,
        1258,
        CP_UTF8
    };


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

    /* Go through all of the code pages */
    for(i=0; i<(sizeof(codePages)/sizeof(int)); i++)
    {
    
        for (k=0; k<128; k++)
        {
            wideStr[k] = 'a';
            mbStr[k] = 0;
        }

        wideStr[127] = 0;

        /* try with insufficient buffer space */
        ret = WideCharToMultiByte(codePages[i], 0, wideStr, -1, 
                                  mbStr, 10, NULL, NULL);
        if (ret != 0)
        {
            Trace("WideCharToMultiByte did not return an error!\n"
                  "Expected return of 0, got %d for code page %d.\n", ret, 
                  codePages[i]);
            bRet = FALSE;
        }

        ret = GetLastError();
        if (ret != ERROR_INSUFFICIENT_BUFFER)
        {
            Fail("WideCharToMultiByte set the last error to %u instead of "
                 "ERROR_INSUFFICIENT_BUFFER for code page %d.\n",
                 GetLastError(),codePages[i]);
            bRet = FALSE;
        }
    }

    /* Return failure if any of the code pages returned the wrong results */
    if(!bRet)
    {
        return FAIL;
    }

    /* try with a wacky code page */
    ret = WideCharToMultiByte(-1, 0, wideStr, -1, mbStr, 128, NULL, NULL);
    if (ret != 0)
    {
        Fail("WideCharToMultiByte did not return an error!\n"
             "Expected return of 0, got %d for invalid code page.\n", ret);
    }

    ret = GetLastError();
    if (ret != ERROR_INVALID_PARAMETER)
    {
        Fail("WideCharToMultiByte set the last error to %u instead of "
             "ERROR_INVALID_PARAMETER for invalid code page -1.\n",
             GetLastError());
    }

    PAL_Terminate();

    return PASS;
}
Esempio n. 28
0
bool UpdateNode::is_column_nullable(const ColumnID column_id) const { Fail("Update does not output any colums"); }
Esempio n. 29
0
/**
 * main
 * 
 * executable entry point
 * 
 * The main act as a the server. It will create a thread of the client
 * and signal to the thread when it is ready to recv data.
 * Once the client receive the signal, it start sending data.
 * 
 * The server will not stop until the thread it created has exited.
 * For evey return path, error or not, the server will wait for
 * the client to finish its execution. This is to make sure that all
 * resource are being freed and proper error are logged.
 *
 */
INT __cdecl main(INT argc, CHAR **argv)
{
    int     i;
    int     err;    
    struct  sockaddr_in mySockaddr;
    WSADATA wsaData;
    HANDLE  hReadEvent;
    DWORD   waitResult;

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

    HANDLE hThreadEvent; 
    int bClientStarted=0;

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

    /* variable for iocltsocket */
    u_long argp;

    SOCKET testSockets[1];

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

    /* 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(%d) "
              "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_DGRAM,
                                 IPPROTO_UDP,
                                 NULL, 
                                 0, 
                                 WSA_FLAG_OVERLAPPED );


    if( testSockets[0] == INVALID_SOCKET )

    {
        Trace("Server error: Unexpected failure: "
              "WSASocketA"
              "(AF_INET,SOCK_DGRAM,IPPROTO_UDP,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("");
    }

    /* enable non blocking socket */
    argp=1;
    err = ioctlsocket(testSockets[0], FIONBIO, (u_long FAR *)&argp);

    if (err==SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure: "
              "ioctlsocket(.., FIONBIO, ..) "
              "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("Server error: Unexpected failure: "
              "bind() socket with local address "
              "returned %d\n",
              GetLastError() );

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

        Fail("");
    }
    
    /* Create an Event with initial owner. */
    hThreadEvent = (HANDLE)CreateEvent( NULL,
        TRUE,                /* reset type */
        FALSE,                /* initially not signaled */
        (LPCSTR)"EventClientServer");  /* name of Event */

    if (hThreadEvent == NULL) 
    {   
        /* Check for error. */
        Trace( "Server Error: Unexpected failure: "
              "CreateEvent() "
              "returned NULL\n");   

        /* 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());

        CloseEventHandle(hThreadEvent);

        /* 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");

        CloseEventHandle(hThreadEvent);

        CloseEventHandle(hReadEvent);        

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

        Fail( "");
    }
    
    bufferCounter = 0;
    pMyData = (unsigned char*)myData;

    /* This loop call WSARecv 500 times to stress tests UDP data exchange
       over connectionless socket.
       Data received are copied in an array and verified after the all receive
       operation are done.
    */
    for(i=0;i<500;i++)
    {   
        /* reset the buffer used by WSARecv */
        memset(myBuffer, 0, 255); 

        /* Initialize the WSAOVERLAPPED to 0 */
        memset(&wsaRecvOverlapped, 0, sizeof(WSAOVERLAPPED));

        /* Specify which event to signal when data is arrived*/
        wsaRecvOverlapped.hEvent = hReadEvent; 

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

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

        if( err == SOCKET_ERROR )
        {                    
            err = GetLastError();
            /* Only WSA_IO_PENDING is expected */
            if(err!=WSA_IO_PENDING)
            {
                Trace("Server error: WSARecv()"
                      "returned %d, expected WSA_IO_PENDING\n",
                      err );

                WaitForClientThreadToFinish(hThreadClient);

                CloseThreadHandle(hThreadClient);
                
                CloseEventHandle(hThreadEvent);
                
                CloseEventHandle(hReadEvent);
                
                /* Do some cleanup */
                DoWSATestCleanup( testSockets,
                                  numSockets );
        
                Fail("");
            }
        }
        else    /* WSARecv returned immediately */
        {
            /* It can happen in non-blocking mode 
               operation can continue normaly
            */

            if (dwNbrOfByteSent==0)
            {
                Trace("Server error: WSARecv()"
                      "returned dwNbrOfByteSent=0, expected 255.\n");

                WaitForClientThreadToFinish(hThreadClient);

                CloseThreadHandle(hThreadClient);
                
                CloseEventHandle(hThreadEvent);
                
                CloseEventHandle(hReadEvent);
                
                /* Do some cleanup */
                DoWSATestCleanup( testSockets,
                                  numSockets );
        
                Fail("");
            }

            /* Reset event */
            ResetEvent(hReadEvent);
        }            

        /* verify if it needs to start the client thread */
        if(!bClientStarted)
        {
            if(SetEvent(hThreadEvent)==0)
            {
                Trace("Server error: Unexpected failure: "
                        "SetEvent has not set hThreadEvent as expected"
                        "GetLastError returned = %d.\n",GetLastError());

                WaitForClientThreadToFinish(hThreadClient);

                CloseThreadHandle(hThreadClient);

                CloseEventHandle(hThreadEvent);
                
                CloseEventHandle(hReadEvent);                

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

                Fail("");
            }
            bClientStarted=1;
        }

        if(err==WSA_IO_PENDING)
        {
            /* wait for data to be read on the receive buffer */
            waitResult = WaitForSingleObject( hReadEvent,
                                            10000 );
            
            if (waitResult!=WAIT_OBJECT_0)
            {   
                Trace("Server error: Unexpected failure: "
                    "WaitForSingleObject has timed out \n");
                
                WaitForClientThreadToFinish(hThreadClient);

                CloseThreadHandle(hThreadClient);

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

                Fail("");
            }
        }        
        
        /* Verify that the buffer received is not bigger than the 
           the maximum specified in wsaBuf structure
        */
        if(wsaBuf.len<wsaRecvOverlapped.InternalHigh)
        {            
            Trace("Server error: "
                  "WSARecv(...) "
                  "returned wsaRecvOverlapped with InternalHigh of %d" 
                  ", expected value equal ot lower to %d\n",
                  wsaRecvOverlapped.InternalHigh, wsaBuf.len);

            WaitForClientThreadToFinish(hThreadClient);

            CloseThreadHandle(hThreadClient);

            CloseEventHandle(hThreadEvent);
            
            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("Server error: Unexpected, data received exceed "
                  "buffer capacity.\n");
            
            WaitForClientThreadToFinish(hThreadClient);

            CloseThreadHandle(hThreadClient);

            CloseEventHandle(hThreadEvent);
            
            CloseEventHandle(hReadEvent);

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

            Fail("");
        }
        
        /* Increment bufferCounter to keep track of the number 
           of byte received */
        bufferCounter += wsaRecvOverlapped.InternalHigh;        
    }

    if(!WaitForClientThreadToFinish(hThreadClient))
    {
        /* Error waiting for the client thread */

        /* Error message generated in function */

        CloseThreadHandle(hThreadClient);
        
        CloseEventHandle(hThreadEvent);
        
        CloseEventHandle(hReadEvent);

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

        Fail("");
    }

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

    /* Expected number of bytes received is 127500 */
    if(bufferCounter!=127500)
    {        
        Trace("Server error: Invalid number of byte received from the client");

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

        Fail("");

        
    }

    /* verify that all data in the data array are as expected */
    pMyData=(unsigned char*)myData;
    for(i=0;i<bufferCounter;i++)
    {
        if(pMyData>&(myData[500][255]))
        {
            Trace("Server error: invalid access to array myData\n");                   

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

        }

        if(*pMyData!=(i%255))
        {
            Trace("Server error: comparing received data at position %d"
                   " in data array",i);

            /* Do some cleanup */
            DoWSATestCleanup( testSockets,
                              numSockets );
            Fail("");
        }
        pMyData++;
    }
 
    /* Do some cleanup */
    DoWSATestCleanup( testSockets,
                      numSockets );

    PAL_Terminate();
    return PASS;
}
Esempio n. 30
0
int __cdecl main(int argc, char *argv[]) {

    int childPid = -1, childStdinFd = -1, childStdoutFd = -1, childStderrFd = -1;
    FILE *childStdin = NULL, *childStdout = NULL, *childStderr = NULL;
    char* childArgv[3] = { argv[0], "child", NULL };
    int c = 0;

    // Initialize the PAL and return FAILURE if this fails
    if ((PAL_Initialize(argc, argv)) != 0)
    {
        return FAIL;
    }

    // If this is the child process, it'll have an argument.
    if (argc > 1)
    {
        // This is the child.  Receive 'a' from the parent,
        // then send back 'b' on stdout and 'c' on stderr.
        if ((c = getc(stdin)) == EOF ||
            c != 'a' ||
            fputc('b', stdout) == EOF ||
            fflush(stdout) != 0 ||
            fputc('c', stderr) == EOF ||
            fflush(stdout) != 0)
        {
            Fail("Error: Child process failed");
        }
        goto done;
    }

    // Now fork/exec the child process, with the same executable but an extra argument
    if (ForkAndExecProcess(argv[0], childArgv, environ, NULL,
                           1, 1, 1,
                           &childPid, &childStdinFd, &childStdoutFd, &childStderrFd) != 0)
    {
        Fail("Error: ForkAndExecProces failed with errno %d (%s)\n", errno, strerror(errno));
    }
    if (childPid < 0 || childStdinFd < 0 || childStdoutFd < 0 || childStderrFd < 0)
    {
        Fail("Error: ForkAndExecProcess returned childpid=%d, stdinFd=%d, stdoutFd=%d, stderrFd=%d", 
            childPid, childStdinFd, childStdoutFd, childStderrFd);
    }

    // Open files for the child's redirected stdin, stdout, and stderr
    if ((childStdin = _fdopen(childStdinFd, "w")) == NULL ||
        (childStdout = _fdopen(childStdoutFd, "r")) == NULL ||
        (childStderr = _fdopen(childStderrFd, "r")) == NULL)
    {
        Fail("Error: Opening FILE* for stdin, stdout, or stderr resulted in errno %d (%s)", 
            errno, strerror(errno));
    }

    // Send 'a' to the child
    if (fputc('a', childStdin) == EOF ||
        fflush(childStdin) != 0)
    {
        Fail("Writing to the child process failed with errno %d (%s)", errno, strerror(errno));
    }

    // Then receive 'b' from the child's stdout, then 'c' from stderr
    if ((c = getc(childStdout)) != 'b')
    {
        Fail("Received '%c' from child's stdout; expected 'b'", c);
    }
    if ((c = getc(childStderr)) != 'c')
    {
        Fail("Received '%c' from child's stderr; expected 'c'", c);
    }

done:
    PAL_Terminate();
    return PASS;
}