Example #1
0
/* main program entry point */
int __cdecl main( int argc, char **argv ) 

{
    /* local variables */
#if WIN32
    const char* rgchLibraryFile = "dllmain";
    char        szFunction[] = "_GetDetachCount@0";
#else
#if defined(__APPLE__)
    const char* rgchLibraryFile = "dllmain.dylib";
#else   // __APPLE__
    const char* rgchLibraryFile = "dllmain.so";
#endif  // __APPLE__
    char        szFunction[] = "GetDetachCount";
#endif

    HANDLE      hLib = NULL;
    LPTESTFUNC  pFunc;
    int         detachCount1 = 0;
    int         detachCount2 = 0;
    
    HANDLE      hThread = NULL;
    DWORD       IDThread;

    /* initialize the PAL */
    if( PAL_Initialize(argc, argv) != 0 )
    {
	    return( FAIL );
    }
    
    /* Load the test library */
    hLib = LoadLibrary( rgchLibraryFile );
    if(hLib == NULL)
    {
        Fail("ERROR: Unable to load library %s\n", rgchLibraryFile );
    }
    

    /* Get the address of our test function in the dll */
    pFunc = (LPTESTFUNC)GetProcAddress( hLib, szFunction );
    if( pFunc == NULL )
    {
        Trace( "ERROR:%lu%:Unable to load function \"%s\" library \"%s\"\n",
                GetLastError(),
                szFunction,
                rgchLibraryFile );
        if( ! FreeLibrary( hLib ) ) {
            Trace( "FreeLibrary() failed with error code %lu\n",
                    GetLastError() );
        }
        Fail( "Exiting\n" );
    }
    
    /* Execute the test function to get the detach count */
    detachCount1 = pFunc();
    
    /* run another dummy thread to cause notification of the library       */
    hThread = CreateThread(    NULL,             /* no security attributes */
                               0,                /* use default stack size */
      (LPTHREAD_START_ROUTINE) ThreadFunc,       /* thread function        */
                      (LPVOID) NULL,             /* pass thread index as   */
                                                 /* function argument      */
                               CREATE_SUSPENDED, /* create suspended       */
                               &IDThread );      /* returns thread id      */

    /* Check the return value for success. */
    if( hThread == NULL )
    {
        /* error creating thread */
        Trace( "Unexpected CreateThread error %d\n",
              GetLastError() );
        if( ! FreeLibrary( hLib ) ) {
            Trace( "FreeLibrary() failed with error code %lu\n",
                    GetLastError() );
        }
        Fail( "Exiting\n" );
    }
    
    /* Resume the suspended thread */
    ResumeThread( hThread );

    /* wait for the thread to complete */
    WaitForSingleObject( hThread, INFINITE );

    /* Execute the test function to get the new detach count */
    detachCount2 = pFunc();
    
    /* Unload the test library */ 
    if( !FreeLibrary( hLib ) )
    {
        Fail( "ERROR:%u: Unable to free library \"%s\"\n",
                GetLastError(),
                rgchLibraryFile );
    }
    
    /* validate the result */
    if( detachCount2 != (detachCount1 + 1) )
    {
        Fail( "FAIL: unexpected DLL detach count %d, expected %d\n",
                detachCount2,
                (detachCount1 + 1) );
    }
    
    
    /* terminate the PAL */
    PAL_Terminate();
    
    /* return success */
    return PASS; 
}
Example #2
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;
}
Example #3
0
int __cdecl main(int argc, char *argv[])
{
    WORD VersionRequested = MAKEWORD(2,2);
    WSADATA WsaData;
    int err;
    int socketID;
    struct sockaddr_in mySockaddr;
    const char *data = "sendto and recvfrom test";
    int nBuffer=strlen(data);

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

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

    /*create a stream socket in 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("");
    }

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


    err=sendto(socketID,data,nBuffer,0,(struct sockaddr *)&mySockaddr,
        sizeof(struct sockaddr));
    if(SOCKET_ERROR == err)
    {
        Trace("\nFailed to call sendto API to send data to a 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(""); 
        }
        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;
}
Example #4
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;
}
Example #5
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;
}
Example #6
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;
}
Example #7
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);
}
Example #8
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;
}
Example #9
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;

}
int __cdecl main(int argc, char **argv)
{

    FILETIME UTCTime, LocalTime;
    ULONG64 FullFileTime, FullLocalTime, CorrectTime;
    TIME_ZONE_INFORMATION ZoneInfo;
    int DeltaBetweenLocalAndUTC;
    int result;

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

    /* This is a valid UTC file time generated with GetFileTime */
    UTCTime.dwLowDateTime = 1867954880;
    UTCTime.dwHighDateTime = 29437095;
  
    /* Call the function */
    result = FileTimeToLocalFileTime(&UTCTime,&LocalTime);
  
    if(result == 0) 
    {
        Fail("ERROR: FileTimeToLocalTime has returned zero, which "
               "indicates that it failed.");
    }

    /* We need to get the time zone that the user is running in. */
    result = GetTimeZoneInformation(&ZoneInfo);

    /* Use the Time Zone Information to construct the delta between UTC
       and local time -- in hours.
    */
    
    if(result == TIME_ZONE_ID_STANDARD)
    {
        DeltaBetweenLocalAndUTC = 
            (ZoneInfo.Bias + ZoneInfo.StandardBias);  
    }
    else if (result == TIME_ZONE_ID_DAYLIGHT) 
    {
        DeltaBetweenLocalAndUTC = 
            (ZoneInfo.Bias + ZoneInfo.DaylightBias); 
    }
    else 
    {
        DeltaBetweenLocalAndUTC = (ZoneInfo.Bias);
    }
 
    /* Change the UTC and Local FILETIME structures into ULONG64 
       types 
    */
  
    FullFileTime = ((((ULONG64)UTCTime.dwHighDateTime)<<32) | 
                    ((ULONG64)UTCTime.dwLowDateTime));
  
    FullLocalTime = ((((ULONG64)LocalTime.dwHighDateTime)<<32) | 
                     ((ULONG64)LocalTime.dwLowDateTime));

    /* This magic number is 10000000 * 60 * 60 -- which is the
       number of 100s of Nanseconds in a second, multiplied by the number
       of seconds in a minute, multiplied by the number of minutes in an
       hour.
     
       The correct time is the delta in hundreds of nanoseconds between
       Local and UTC times.
    */
  
    CorrectTime = 600000000 * ((ULONG64)DeltaBetweenLocalAndUTC);
  
    /* Now check to ensure that the difference between the Local and UTC
       times that was calculated with the function equals what it should be.
    */
    if((FullFileTime - FullLocalTime) != CorrectTime)
    {
        Fail("ERROR: The LocalFileTime that was returned is not equal to "
               "what the LocalFileTime should have been.");
    } 
  
    PAL_Terminate();
    return PASS;
}
Example #11
0
int __cdecl main(int argc, char *argv[])
{
    WORD VersionRequested = MAKEWORD(2, 2);
    WSADATA WsaData;
    int err;
    int socketID;
    struct sockaddr_in mySockaddr;
    int nLength;
    char data[BUFFERSIZE];
    u_long argp = 1;/*set the non-blocking flag*/


    /*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 create a datagram socket!\n");
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    /*set the socket as non-blocking*/
    err = ioctlsocket(socketID, FIONBIO, &argp);
    if(SOCKET_ERROR == err)
    {
        Trace("\nFailed to call ioctlsocket API to set "
            "non-blocking socket!\n");

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

    /*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);
    nLength = sizeof(struct sockaddr);

    memset(data,0,BUFFERSIZE);
    /*receive data from this socket which is not bound*/
    err = recvfrom(socketID, data, BUFFERSIZE, 0,
            (struct sockaddr*)&mySockaddr,&nLength);
    if(WSAEINVAL != GetLastError() || SOCKET_ERROR != err)
    {
        Trace("\nFailed to call recvfrom API for a negative test "
            "with an unbound socket!\n");
        err = closesocket(socketID);
        if(SOCKET_ERROR == err)
        {    
            Trace("\nFailed to call closesocket API!\n");
        }
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

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

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

    PAL_Terminate();
    return PASS;
}
Example #12
0
int __cdecl main(int argc, char **argv)
{
    FILETIME Creation;
    FILETIME LastAccess;
    FILETIME LastWrite;
    HANDLE hFile;
    ULONG64 FirstWrite;
    ULONG64 SecondWrite;
    ULONG64 FirstAccess;
    ULONG64 SecondAccess;
    ULONG64 FirstCreationTime;
    ULONG64 SecondCreationTime;
    DWORD temp;
    const char* someText = "1234567890123456789012345678901234567890";

    if (0 != PAL_Initialize(argc,argv))
    {
        return FAIL;
    }
  
    /* Open the file to get a HANDLE */
    hFile = CreateFile("test.tmp",
        GENERIC_READ|GENERIC_WRITE,  
        0,                           
        NULL,                        
        CREATE_ALWAYS,                 
        FILE_ATTRIBUTE_NORMAL,       
        NULL);                       
    
    if(hFile == INVALID_HANDLE_VALUE) 
    {
        Fail("ERROR: Failed to create the file.  The error number "
               "returned was %u.\n",
               GetLastError());
    }

     /* Write to the file -- this should change write access and
       last access 
    */
    if(!WriteFile(hFile, someText, strlen(someText), &temp, NULL)) 
    {
        Trace("ERROR: Failed to write to file. The file must be "
               "written to in order to test that the write time is "
               "updated. GetLastError returned %u.\n", 
                GetLastError());
        /* Close the File */
        if(!CloseHandle(hFile)) 
        {
            Trace("ERROR: Failed to close the file handle. "
                "GetLastError returned %u.\n", 
                GetLastError());
        }
        Fail("");
    }

    /* Flush the buffers */
    if(!FlushFileBuffers(hFile)) 
    {
        Trace("ERROR: The FlushFileBuffers function failed. "
               "GetLastError returned %u.\n",
               GetLastError());
        /* Close the File */
        if(!CloseHandle(hFile)) 
        {
            Trace("ERROR: Failed to close the file handle. "
                "GetLastError returned %u.\n", 
                GetLastError());
        }
        Fail("");
    }

    /* Get the Last Write, Creation and Access File time of that File */
    if(!GetFileTime(hFile, &Creation, &LastAccess, &LastWrite))
    {
        Trace("ERROR: GetFileTime returned 0, indicating failure."
            " GetLastError returned %u\n",
            GetLastError());
        /* Close the File */
        if(!CloseHandle(hFile)) 
        {
            Trace("ERROR: Failed to close the file handle. "
                "GetLastError returned %u.\n", 
                GetLastError());
        }
        Fail("");
    }

    /* Convert the structures to an ULONG64 */
    FirstCreationTime = ((((ULONG64)Creation.dwHighDateTime)<<32) | 
                         ((ULONG64)Creation.dwLowDateTime));
    
    FirstWrite =        ((((ULONG64)LastWrite.dwHighDateTime)<<32) | 
                         ((ULONG64)LastWrite.dwLowDateTime));

    FirstAccess =        ((((ULONG64)LastAccess.dwHighDateTime)<<32) | 
                         ((ULONG64)LastAccess.dwLowDateTime));

    /* Sleep for 3 seconds, this will ensure the time changes */
    Sleep(3000);

    /* Write to the file again so we have something to flush */
    if(!WriteFile(hFile, someText, strlen(someText), &temp, NULL)) 
    {
        Trace("ERROR: Failed to write to file. The file must be "
               "written to in order to test that the write time is "
               "updated. GetLastError returned %u.\n", 
                GetLastError());
        /* Close the File */
        if(!CloseHandle(hFile)) 
        {
            Trace("ERROR: Failed to close the file handle. "
                "GetLastError returned %u.\n", 
                GetLastError());
        }
        Fail("");
    }
  
    /* Flush the buffers forcing the access/mod time to change */
    if(!FlushFileBuffers(hFile)) 
    {
        Trace("ERROR: The FlushFileBuffers function failed. "
               "GetLastError returned %u.\n",
               GetLastError());
        /* Close the File */
        if(!CloseHandle(hFile)) 
        {
            Trace("ERROR: Failed to close the file handle. "
                "GetLastError returned %u.\n", 
                GetLastError());
        }
        Fail("");
    }


    /* Call GetFileTime again */
    if(!GetFileTime(hFile,&Creation,&LastAccess,&LastWrite))
    {
        Trace("ERROR: GetFileTime returned 0, indicating failure."
            "GetLastError returned %u.\n", 
            GetLastError());
        /* Close the File */
        if(!CloseHandle(hFile)) 
        {
            Trace("ERROR: Failed to close the file handle. "
                "GetLastError returned %u.\n", 
                GetLastError());
        }
        Fail("");
    }  
    
    /* Store the results in a ULONG64 */
    
    SecondCreationTime = ( (((ULONG64)Creation.dwHighDateTime)<<32) | 
                           ((ULONG64)Creation.dwLowDateTime));
  
    SecondWrite = ( (((ULONG64)LastWrite.dwHighDateTime)<<32) | 
                    ((ULONG64)LastWrite.dwLowDateTime));
  
    SecondAccess = ((((ULONG64)LastAccess.dwHighDateTime)<<32) | 
                    ((ULONG64)LastAccess.dwLowDateTime));

  
    /* Now -- to test.  We'll ensure that the Second
       LastWrite and access times are larger than the first.
       It tells us that time is passing, which is good! 
    */

    if(FirstWrite >= SecondWrite) 
    {
        /* Close the File */
        if(!CloseHandle(hFile)) 
        {
            Trace("ERROR: Failed to close the file handle. "
                "GetLastError returned %u.\n", 
                GetLastError());
        }
        Fail("ERROR: The write-file-time (%I64d) after the first flush "
            "should be less than the write-file-time (%I64d) after the second "
               "flush.\n",
               FirstWrite, 
               LastWrite);

    }

    
    if(SecondAccess < FirstAccess) 
    {
        /* Close the File */
        if(!CloseHandle(hFile)) 
        {
            Trace("ERROR: Failed to close the file handle. "
                "GetLastError returned %u.\n", 
                GetLastError());
        }
        Fail("ERROR: The access-file-time (%I64d) after the first flush "
            "should be less than or equal to the access-file-time (%I64d) "
               "after the second flush.\n",
               FirstAccess, 
               LastAccess);
    }

#if WIN32
    /* Then we can check to make sure that the creation time
       hasn't changed.  This should always stay the same.
    */
    
    if(FirstCreationTime != SecondCreationTime) 
    {
        /* Close the File */
        if(!CloseHandle(hFile)) 
        {
            Trace("ERROR: Failed to close the file handle. "
                "GetLastError returned %u.\n", 
                GetLastError());
        }
        Fail("ERROR: The creation time after writing should not "
               "not change from the original.  The second value should be "
               "equal.\n");
    }
#else
    /* Then we can check to make sure that the creation time
       has changed.  Under FreeBSD it changes whenever the file is
       access or written.
    */
    
    if(FirstCreationTime >= SecondCreationTime) 
    {
        /* Close the File */
        if(!CloseHandle(hFile)) 
        {
            Trace("ERROR: Failed to close the file handle. "
                "GetLastError returned %u.\n", 
                GetLastError());
        }
        Fail("ERROR: The creation time after writing should be "
               "greater than the original.  The second value should be "
               "larger.\n");
    }
    
#endif
    
    /* Close the File */
    if(!CloseHandle(hFile)) 
    {
        Fail("ERROR: Failed to close the file handle. "
            "GetLastError returned %u.\n", 
            GetLastError());
    }

    PAL_Terminate();
    return PASS;
}
Example #13
0
int __cdecl main(int argc, char *argv[])
{
    const char* szTestDir = {"test_directory"};
    const char* szDotDir = {".dotDirectory"};
    BOOL bRc = FALSE;
    BOOL bSuccess = FALSE;
    const int buf_size = CREATE_MAX_PATH_SIZE + 10;
    char szDirName[CREATE_MAX_PATH_SIZE + 10];
    char buffer[CREATE_MAX_PATH_SIZE + 10];
    WCHAR* pTemp = NULL;
    DWORD curDirLen;
    DWORD curDirectory = 1024;
    
    if (0 != PAL_Initialize(argc,argv))
    {
        return FAIL;
    }

    
    /* directory does not exist */ 
    bRc = CreateDirectoryA(szTestDir, NULL);
    if (bRc == FALSE)
    {
        Fail("CreateDirectoryA: Failed to create \"%s\" with error code %ld\n",
            szTestDir,
            GetLastError());
    }

    
    /* directory exists should fail */
    bRc = CreateDirectoryA(szTestDir, NULL);
    if (bRc == TRUE)
    {
        pTemp = convert((LPSTR)szTestDir);
        bRc = RemoveDirectoryW(pTemp);
        free(pTemp);
        if (!bRc)
        {
            Trace("CreateDirectoryA: RemoveDirectoryW failed to remove "
                "\"%s\" with the error code %ld.\n",
                szTestDir,
                GetLastError());
        }
        Fail("CreateDirectoryA: Succeeded creating the directory"
            "\"%s\" when it exists already.\n",
            szTestDir);
    }
    else 
    {
        pTemp = convert((LPSTR)szTestDir);
        bRc = RemoveDirectoryW(pTemp);
        free(pTemp);
        if (!bRc)
        {
            Fail("CreateDirectoryA: RemoveDirectoryW failed to remove "
                "\"%s\" with the error code %ld.\n",
                szTestDir,
                GetLastError());
        }
    }

   
    /* long directory names (CREATE_MAX_PATH_SIZE - 1, CREATE_MAX_PATH_SIZE  
       and CREATE_MAX_PATH_SIZE + 1 characters 
      including terminating null char) */

    curDirLen = GetCurrentDirectoryA(0, NULL);

    memset(szDirName, 0, buf_size);
    memset(szDirName, 'a', CREATE_MAX_PATH_SIZE - 2 - curDirLen);
    bRc = CreateDirectoryA(szDirName, NULL);
    if (bRc == FALSE)
    {
        Fail("CreateDirectoryA: Failed to create a directory"
            " name %d chars long with the error code %ld\n", 
            strlen(szDirName),
            GetLastError());
    }
    else
    {
        /* Check to see if it's possible to navigate to directory */
        GetCurrentDirectoryA(curDirectory, buffer);
        bSuccess = SetCurrentDirectoryA(szDirName);
        if(!bSuccess)
        {
            Fail("CreateDirectoryA: SetCurrentDirectoryA failed to "
                "navigate to the newly created directory with error "
                "code %u.\n", GetLastError());
        }

        /* Set directory back to initial directory */
        SetCurrentDirectoryA(buffer);

        pTemp = convert((LPSTR)szDirName);
        bRc = RemoveDirectoryW(pTemp);
        free(pTemp);
        if (!bRc)
        {
            Fail("CreateDirectoryA: RemoveDirectoryW failed to remove "
                "\"%s\" with the error code %ld.\n",
                szDirName,
                GetLastError());
        }
    }


    memset(szDirName, 0, buf_size);
    memset(szDirName, 'a', CREATE_MAX_PATH_SIZE - 1 - curDirLen);
    bRc = CreateDirectoryA(szDirName, NULL);
    if (bRc == FALSE)
    {
        Fail("CreateDirectoryA: Failed to create a directory"
            " name %d chars long with error code %ld\n", 
            strlen(szDirName),
            GetLastError());
    }
    else
    {
        /* Check to see if it's possible to navigate to directory */
        GetCurrentDirectoryA(curDirectory, buffer);
        bSuccess = SetCurrentDirectoryA(szDirName);
        if(!bSuccess)
        {
            Fail("CreateDirectoryA: SetCurrentDirectoryA failed to "
                "navigate to the newly created directory with error "
                "code %u.\n", GetLastError());
        }

        /* Set Directroy back to initial directory */
        SetCurrentDirectoryA(buffer);
        
        pTemp = convert(szDirName);
        bRc = RemoveDirectoryW(pTemp);
        free(pTemp);
        if (!bRc)
        {
            Fail("CreateDirectoryA: RemoveDirectoryW failed to remove "
                "\"%s\" with the error code %ld.\n",
                szDirName,
                GetLastError());
        }
    }

    memset(szDirName, 0, buf_size);
    memset(szDirName, 'a', CREATE_MAX_PATH_SIZE - curDirLen);
    bRc = CreateDirectoryA(szDirName, NULL);
    if (bRc != FALSE)
    {
        /* Check to see if it's possible to navigate to directory */
        GetCurrentDirectoryA(curDirectory, buffer);
        bSuccess = SetCurrentDirectoryA(szDirName);
        if(!bSuccess)
        {
            Fail("CreateDirectoryA: SetCurrentDirectoryA failed to "
                "navigate to the newly created directory with error "
                "code %u.\n", GetLastError());
        }

        /* set directory back to initial directory */
        SetCurrentDirectoryA(buffer);

        pTemp = convert(szDirName);
        bRc = RemoveDirectoryW(pTemp);
        free(pTemp);
        if (!bRc)
        {
            Trace("CreateDirectoryA: RemoveDirectoryW failed to remove "
                "\"%s\" with the error code %ld.\n",
                szDirName,
                GetLastError());
        }
        Fail("CreateDirectoryA: Failed because it created a directory"
            " name 1 character longer (%d chars) than the max dir size "
            "allowed\n", 
            strlen(szDirName));
    }


    /* long directory name CREATE_MAX_PATH_SIZE + 3 chars including "..\" 
       (real path length <= CREATE_MAX_PATH_SIZE) */
    memset(szDirName, 0, buf_size);
    memset(szDirName, 'a', CREATE_MAX_PATH_SIZE + 3 - 1 - curDirLen);
    szDirName[0] = '.';
    szDirName[1] = '.';
    szDirName[2] = '\\';
    bRc = CreateDirectoryA(szDirName, NULL);
    if (bRc == FALSE)
    {
        Fail("CreateDirectoryA: Failed to create a directory name more "
            "than %d chars long and its real path name is less "
            "than %d chars, error %u\n",
            CREATE_MAX_PATH_SIZE,
            CREATE_MAX_PATH_SIZE, GetLastError());
    }
    else
    {
        /* Check to see if it's possible to navigate to directory */
        GetCurrentDirectoryA(curDirectory, buffer);
        bSuccess = SetCurrentDirectoryA(szDirName);
        if(!bSuccess)
        {
            Fail("CreateDirectoryA: SetCurrentDirectoryA failed to "
                "navigate to the newly created directory with error "
                "code %u.\n", GetLastError());
        }

        /* set directory back to initial directory */
        SetCurrentDirectoryA(buffer);

        pTemp = convert(szDirName);
        bRc = RemoveDirectoryW(pTemp);
        free(pTemp);
        if (!bRc)
        {
            Fail("CreateDirectoryA: RemoveDirectoryW failed to remove "
                " \"%s\" with the error code %ld.\n",
                szDirName,
                GetLastError());
        }
    }


    /* directories with dots  */
    memset(szDirName, 0, buf_size);
    sprintf(szDirName, szDotDir);
    bRc = CreateDirectoryA(szDirName, NULL);
    if (bRc == FALSE)
    {
        Fail("CreateDirectoryA: Failed to create \"%s\" with error code %ld\n",
            szDotDir,
            GetLastError());
    }
    else
    {
        
        /* Check to see if it's possible to navigate to directory */
        GetCurrentDirectoryA(curDirectory, buffer);
        bSuccess = SetCurrentDirectoryA(szDirName);
        if(!bSuccess)
        {
            Fail("CreateDirectoryA: SetCurrentDirectoryA failed to "
                "navigate to the newly created directory with error "
                "code %u.\n", GetLastError());
        }

        /* set directory back to initial directory */
        SetCurrentDirectoryA(buffer);
        
        pTemp = convert((LPSTR)szDotDir);
        bRc = RemoveDirectoryW(pTemp);
        free(pTemp);
        if (!bRc)
        {
            Fail("CreateDirectoryA: RemoveDirectoryW failed to remove "
                " \"%s\" with the error code %ld.\n",
                szDotDir,
                GetLastError());
        }
    }


    PAL_Terminate();  
    return PASS;
}
Example #14
0
int __cdecl main(int argc, char *argv[]) 
{

#if WIN32

    return PASS;

#else

    /* Define some buffers needed for the function */
    WCHAR * pResultBuffer = NULL;

    WCHAR FirstEnvironmentVariable[] = {'P','A','L','T','E','S','T','\0'};
    WCHAR FirstEnvironmentValue[] = {'F','I','R','S','T','\0'};

    WCHAR SecondEnvironmentVariable[] = {'p','a','l','t','e','s','t','\0'};
    WCHAR SecondEnvironmentValue[] = {'S','E','C','O','N','D','\0'};

    DWORD size = 0;
    BOOL bRc = TRUE;

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

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }
  
    /* Set the first environment variable */
    bRc = SetEnvironmentVariableW(FirstEnvironmentVariable,
                            FirstEnvironmentValue);

    if(!bRc)
    {
        Fail("ERROR: SetEnvironmentVariable failed to set a "
            "proper environment variable with error %u.\n", GetLastError());
    }

    /* Normal case, PATH should fit into this buffer */
    size = GetEnvironmentVariableW(FirstEnvironmentVariable,        
                                  pResultBuffer,    
                                  0);                 

    /* To account for the nul character at the end of the string */
    size = size + 1;
    
    pResultBuffer = malloc(sizeof(WCHAR)*size);
    if ( pResultBuffer == NULL )
    {
	    Fail("ERROR: Failed to allocate memory for pResultBuffer pointer.\n");
    }

    /* Try to retrieve the value of the first environment variable */
    GetEnvironmentVariableW(FirstEnvironmentVariable,
                           pResultBuffer,
                           size);

    if ( pResultBuffer == NULL )
    {
	    free(pResultBuffer);
        Fail("ERROR: GetEnvironmentVariable failed to return a value "
            "from a proper environment variable with error %u.\n",
            GetLastError());
    }

    /* Compare the strings to see that the correct variable was returned */
    if(wcsncmp(pResultBuffer,FirstEnvironmentValue,wcslen(pResultBuffer)) != 0)
    {
        free(pResultBuffer);    
        Fail("ERROR: The value in the buffer should have been '%S' but "
             "was really '%S'.\n",FirstEnvironmentValue, pResultBuffer);          
    }

    free(pResultBuffer);

    /* Set the second environment Variable */
    bRc = SetEnvironmentVariableW(SecondEnvironmentVariable,
                            SecondEnvironmentValue);

    if(!bRc)
    {
        Fail("ERROR: SetEnvironmentVariable failed to set a "
            "proper environment variable with error %u.\n",
            GetLastError());
    }

    /* Reallocate the memory for the string */
    pResultBuffer = malloc(sizeof(WCHAR)*size);
    if ( pResultBuffer == NULL )
    {
	    Fail("ERROR: Failed to allocate memory for pResultBuffer pointer.\n");
    }

    /* Try retrieving the value of the first variable, even though the
    second variable has the same spelling and only differs in case */
    GetEnvironmentVariableW(FirstEnvironmentVariable,
                           pResultBuffer,
                           size);

    if ( pResultBuffer == NULL )
    {
	    free(pResultBuffer);
        Fail("ERROR: GetEnvironmentVariable failed to return a value "
            "from a proper environment variable with error %u.\n",
            GetLastError());
    }

    /* Compare the two strings to confirm that the right value is returned */
    if(wcsncmp(pResultBuffer,FirstEnvironmentValue,wcslen(pResultBuffer)) != 0) 
    {
        free(pResultBuffer);    
        Fail("ERROR: The value in the buffer should have been '%S' but "
             "was really '%S'.\n",FirstEnvironmentValue,pResultBuffer);          
    }
  
    free(pResultBuffer);
    
    PAL_Terminate();
    return PASS;

#endif
}
Example #15
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;
}
Example #16
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;
}
Example #17
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;
}
Example #18
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;
}
Example #19
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;
};
Example #20
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);
}
Example #21
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;
}
Example #22
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;
}
Example #23
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;
}
Example #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 );
}
Example #25
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;
}
Example #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;
}
Example #27
0
int __cdecl main(int argc, char **argv)
{
    int i;
    BOOL  bFailed = FALSE;
    DWORD result;

    char * NormalDirectoryName          = "normal_test_directory";
    char * ReadOnlyDirectoryName        = "ro_test_directory";
    char * ReadWriteDirectoryName       = "rw_directory";
    char * HiddenDirectoryName          = ".hidden_directory";
    char * HiddenReadOnlyDirectoryName  = ".hidden_ro_directory";
    char * NoDirectoryName              = "no_directory";

    char * NormalFileName               = "normal_test_file";
    char * ReadOnlyFileName             = "ro_test_file";  
    char * ReadWriteFileName            = "rw_file";
    char * HiddenFileName               = ".hidden_file";
    char * HiddenReadOnlyFileName       = ".hidden_ro_file";
    char * NotReallyAFileName           = "not_really_a_file";

    /* Tests on directory */
    gfaTestsDir[0].name    = NormalDirectoryName;
    gfaTestsDir[0].expectedAttribs = FILE_ATTRIBUTE_DIRECTORY;
    gfaTestsDir[0].isFile  = TYPE_DIR;
    
    gfaTestsDir[1].name    = ReadOnlyDirectoryName;
    gfaTestsDir[1].expectedAttribs = FILE_ATTRIBUTE_DIRECTORY | 
                          FILE_ATTRIBUTE_READONLY;
    gfaTestsDir[1].isFile  = TYPE_DIR;

    gfaTestsDir[2].name    = ReadWriteDirectoryName;
    gfaTestsDir[2].expectedAttribs = FILE_ATTRIBUTE_DIRECTORY;
    gfaTestsDir[2].isFile  = TYPE_DIR;

    gfaTestsDir[3].name    = HiddenDirectoryName;
    gfaTestsDir[3].expectedAttribs = FILE_ATTRIBUTE_DIRECTORY; //| 
                          //FILE_ATTRIBUTE_HIDDEN;
    gfaTestsDir[3].isFile  = TYPE_DIR;
    
    gfaTestsDir[4].name    = HiddenReadOnlyDirectoryName;
    gfaTestsDir[4].expectedAttribs = FILE_ATTRIBUTE_DIRECTORY | 
                          FILE_ATTRIBUTE_READONLY; //|
                          //FILE_ATTRIBUTE_HIDDEN;
    gfaTestsDir[4].isFile  = TYPE_DIR;

    gfaTestsDir[5].name    = NoDirectoryName;
    gfaTestsDir[5].expectedAttribs = INVALID_FILE_ATTRIBUTES;
    gfaTestsDir[5].isFile  = TYPE_DIR;

    /* Tests on file */
    gfaTestsFile[0].name    = NormalFileName;
    gfaTestsFile[0].expectedAttribs = FILE_ATTRIBUTE_NORMAL;
    gfaTestsFile[0].isFile  = TYPE_FILE;


    gfaTestsFile[1].name    = ReadOnlyFileName;
    gfaTestsFile[1].expectedAttribs = FILE_ATTRIBUTE_READONLY;
    gfaTestsFile[1].isFile  = TYPE_FILE;

    gfaTestsFile[2].name    = ReadWriteFileName;
    gfaTestsFile[2].expectedAttribs = FILE_ATTRIBUTE_NORMAL;
    gfaTestsFile[2].isFile  = TYPE_FILE;

    gfaTestsFile[3].name    = HiddenFileName;
    gfaTestsFile[3].expectedAttribs = FILE_ATTRIBUTE_NORMAL; //FILE_ATTRIBUTE_HIDDEN;
    gfaTestsFile[3].isFile  = TYPE_FILE;

    gfaTestsFile[4].name    = HiddenReadOnlyFileName;
    gfaTestsFile[4].expectedAttribs = FILE_ATTRIBUTE_READONLY; //|
                           //FILE_ATTRIBUTE_HIDDEN;
    gfaTestsFile[4].isFile  = TYPE_FILE;


    gfaTestsFile[5].name    = NotReallyAFileName;
    gfaTestsFile[5].expectedAttribs =  INVALID_FILE_ATTRIBUTES;
    gfaTestsFile[5].isFile  = TYPE_FILE;    

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

    if(!CleanUpFiles())
    {
        Fail("GetFileAttributesA: Pre-Clean Up Files Failed\n");
    }

    if(0 == SetUpFiles())
    {
        Fail("GetFileAttributesA: SetUp Files Failed\n");
    }

    if(!CleanUpDirs())
    {
        Fail("GetFileAttributesA: Pre-Clean Up Directories Failed\n");
    }

    if(!SetUpDirs())
    {
        Fail("GetFileAttributesA: SetUp Directories Failed\n");
    }

    /* 
     * Go through all the test cases above,
     * call GetFileAttributesA on the name and
     * make sure the return value is the one expected
     */
    for( i = 0; i < numFileTests; i++ )
    {
        result = GetFileAttributesA(gfaTestsFile[i].name);

        if( result != gfaTestsFile[i].expectedAttribs )
        {
            bFailed = TRUE;

            Trace("ERROR: GetFileAttributesA Test#%u on %s "
                  "returned %u instead of %u. \n",
                  i,
                  gfaTestsFile[i].name,
                  result,
                  gfaTestsFile[i].expectedAttribs);

        }
    }


    for( i = 0; i < numDirTests; i++ )
    {
        result = GetFileAttributesA(gfaTestsDir[i].name);

        if( result != gfaTestsDir[i].expectedAttribs )
        {
            bFailed = TRUE;

            Trace("ERROR: GetFileAttributesA on Directories Test#%u on %s "
                  "returned %u instead of %u. \n",
                  i,
                  gfaTestsDir[i].name,
                  result,
                  gfaTestsDir[i].expectedAttribs);

        }
    }

    if(!CleanUpFiles())
    {
        Fail("GetFileAttributesA: Post-Clean Up Files Failed\n");
    }

    if(!CleanUpDirs())
    {
        Fail("GetFileAttributesA: Post-Clean Up Directories Failed\n");
    }

    /* If any errors, just call Fail() */
    if( bFailed )
    {
        Fail("");
    }

    PAL_Terminate();
    return PASS;
}
Example #28
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;
}
Example #29
0
int __cdecl main(int argc, char *argv[])
{
    int err;
    WCHAR *wpFormat;
    LPCSTR lpString = "gg";
    CONST SYSTEMTIME *lpDate = NULL;
    LCID DefaultLocale;
    DWORD dwFlags;
    int DateSize;
    WCHAR *wpBuffer = NULL;

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

    /*convert to a wide character string*/
    wpFormat = convert((char *)lpString);

    dwFlags = DATE_USE_ALT_CALENDAR; /*set the flags*/


    DateSize = 0;

    /*retrieve the buffer size*/
    DateSize = GetDateFormatW(
                   DefaultLocale, /*system default locale*/
                   dwFlags,       /*function option*/
                   (SYSTEMTIME *)lpDate,        /*always is NULL*/
                   wpFormat,      /*pointer to a picture string*/
                   wpBuffer,      /*out buffer*/
                   DateSize);     /*buffer size*/

    if(DateSize <= 0)
    {
        free(wpFormat);
        Fail("\nRetrieved an invalid buffer size\n");
    }

    wpBuffer = malloc((DateSize + 1)*sizeof(WCHAR));
    if(NULL == wpBuffer)
    {
        free(wpFormat);
        Fail("\nFailed to allocate memory to store the formatted string\n");
    }

    /*format a date by passing an invalid locale indentifier*/
    err = GetDateFormatW(
              -1,            /*invalid locale identifier*/
              dwFlags,       /*function option*/
              (SYSTEMTIME *)lpDate,        /*always is NULL, or use system date*/
              wpFormat,      /*pointer to a picture string*/
              wpBuffer,      /*out buffer*/
              DateSize);     /*buffer size*/

    free(wpBuffer);
    free(wpFormat);

    if(0 != err || GetLastError() != ERROR_INVALID_PARAMETER)
    {
        Fail("\nFailed to call GetDateFormatW for a negative test by "
             "passing an invalid parameter, error code=%d\n", GetLastError());
    }

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

    WORD VersionRequested = MAKEWORD(2, 2);
    WSADATA WsaData;

    int err;
    int socketID;
    struct sockaddr OutSockaddr;
    int size;

    /*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 )
    {
        Trace("\nFailed to find a usable WinSock DLL!, error code=%d\n",
                GetLastError());
    }

    /*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!, error code=%d\n",
                GetLastError());
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!, error code=%d\n",
                GetLastError());
        }
        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!, error code=%d\n", GetLastError());
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }


    /*no bind operation for this socket*/
    size = sizeof(struct sockaddr);

    /*retrieve the local name for an unbound socket*/
    err = getsockname(socketID, &OutSockaddr, &size);

    if(WSAEINVAL != GetLastError() || SOCKET_ERROR != err)
    {
        Trace("\nFailed to call getsockname API for a negative test "
            "by passing an unbound socket!, error code=%d\n",
                GetLastError());
        err = closesocket(socketID);
        if(SOCKET_ERROR == err)
        {    
            Trace("\nFailed to call closesocket API!, error code=%d\n",
                GetLastError());
        }
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!, error code=%d\n",
                GetLastError());
        }
        Fail("");
    }

    err = closesocket(socketID);
    if(SOCKET_ERROR == err)
    {
        Trace("\nFailed to call closesocket API!, error code=%d\n",
                GetLastError());
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!, error code=%d\n",
                GetLastError());
        }
        Fail("");
    }

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

    PAL_Terminate();
    return PASS;
}