Пример #1
0
int __cdecl main(int argc, char *argv[])
{
    char    testString[] = "this is a test string";
    WCHAR   lpObjectName[] = {'m','y','O','b','j','e','c','t','\0'};
    char    results[2048];
    int     RetVal = PASS;
    
    HANDLE hFileMapRW;
    LPVOID lpMapViewRW;
    LPVOID lpMapViewRO;

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

    /* Initialize the buffers.
     */
    memset(results,  0, MAPPINGSIZE);

    /* Create a named file-mapping object with file handle FileHandle
     * and with PAGE_READWRITE protection.
    */
    hFileMapRW = CreateFileMapping(
                            SWAP_HANDLE,
                            NULL,               /*not inherited*/
                            PAGE_READWRITE,     /*read write*/
                            0,                  /*high-order size*/
                            MAPPINGSIZE,        /*low-order size*/
                            lpObjectName);      /*unnamed object*/

    if(NULL == hFileMapRW)
    {
        Fail("ERROR:%u: Failed to create File Mapping.\n", 
             GetLastError());
    }

    /* Create a map view to the READWRITE file mapping.
     */
    lpMapViewRW = MapViewOfFile(
                            hFileMapRW,
                            FILE_MAP_ALL_ACCESS,/* access code */
                            0,                  /* high order offset*/
                            0,                  /* low order offset*/
                            MAPPINGSIZE);       /* number of bytes for map */

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


    /* Create a map view to the READWRITE file mapping.
     */
    lpMapViewRO = MapViewOfFile(
                            hFileMapRW,
                            FILE_MAP_READ,        /* access code */
                            0,                    /* high order offset*/
                            0,                    /* low order offset*/
                            MAPPINGSIZE);         /* number of bytes for map */

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

    /* Write the test string to the Map view.
    */    
    memcpy(lpMapViewRW, testString, strlen(testString));

    /* Read from the second Map view.
    */
    memcpy(results, (LPCSTR)lpMapViewRO, MAPPINGSIZE);

    /* Verify the contents of the file mapping,
     * by comparing what was written to what was read.
     */
    if (memcmp(results, testString, strlen(testString))!= 0)
    {
        Trace("ERROR: MapViewOfFile not equal to file contents "
              "retrieved \"%s\", expected \"%s\".\n",
              results,
              testString);
        RetVal = FAIL;
        goto CleanUpThree;
    }

    /* Test successful.
     */
    RetVal = PASS;

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

CleanUpTwo:

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


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


    /* Terminate the PAL.
     */ 
    PAL_TerminateEx(RetVal);
    return RetVal;
}
Пример #2
0
int __cdecl main(int argc, char **argv)
{
    
    int TheReturn;
    HANDLE TheFileHandle;
    DWORD temp;
    DWORD originalSize=10000;
    DWORD finalSize=10000;
    const char* fileName="the_file";

    /*                          1         2         3         4*/
    char * SomeText = "1234567890123456789012345678901234567890";
    

    if (0 != PAL_Initialize(argc,argv))
    {
        return FAIL;
    }
  
    
    /* Open the file to get a HANDLE */    
    TheFileHandle = 
        CreateFile(
            fileName,                 
            GENERIC_READ|GENERIC_WRITE,  
            FILE_SHARE_READ,                           
            NULL,                        
            OPEN_ALWAYS,                 
            FILE_ATTRIBUTE_NORMAL,       
            NULL);                       

    if(TheFileHandle == INVALID_HANDLE_VALUE) 
    {
        Fail("ERROR: CreateFile failed.  Test depends on this function.");
    }
  
    /* get the file size */
    originalSize = GetFileSize (TheFileHandle, NULL) ; 
    if(originalSize == INVALID_FILE_SIZE)
    {
         Fail("ERROR: call to GetFileSize faild with error "
             "The GetLastError is %d.",GetLastError());
    }
    
    /* Write something too the HANDLE.  Should be buffered */    
    TheReturn = WriteFile(TheFileHandle,     
                          SomeText,        
                           strlen(SomeText),
                          &temp,  
                          NULL);
    
    if(TheReturn == 0) 
    {
        Fail("ERROR: WriteFile failed.  Test depends on this function.");
    }

    /* Test to see that FlushFileBuffers returns a success value */
    TheReturn = FlushFileBuffers(TheFileHandle);
    if(TheReturn == 0) 
    {
        Fail("ERROR: The FlushFileBuffers function returned 0, which "
               "indicates failure, when trying to flush a valid HANDLE.  "
               "The GetLastError is %d.",GetLastError());
    }
  
    /* test if flush modified the file */
    finalSize = GetFileSize (TheFileHandle, NULL) ; 
    if(finalSize==INVALID_FILE_SIZE)
    {
        Fail("ERROR: call to GetFileSize faild with error "
             "The GetLastError is %d.",GetLastError());
    }
    if(finalSize!=(originalSize+strlen(SomeText)))
    {
        Fail("ERROR: FlushFileBuffers failed. data was not written to the file");
    }
  
  
    /* Close the Handle */
    TheReturn = CloseHandle(TheFileHandle);
    if(TheReturn == 0) 
    {
        Fail("ERROR: CloseHandle failed.  This function depends "
               "upon it.");
    }
    

    /* Test to see that FlushFileBuffers returns a failure value */
    TheReturn = FlushFileBuffers(TheFileHandle);
    if(TheReturn != 0) 
    {
        Fail("ERROR: The FlushFileBuffers function returned non-zero, "
               "which indicates success, when trying to flush an invalid "
               "HANDLE.");
    }  

    /* make sure file does not exist */
    if(DeleteFileA(fileName)== 0 )
    {
         Fail("ERROR: call to DeleteFileA faild with error "
             "The GetLastError is %d.",GetLastError());
    }
    PAL_Terminate();
    return PASS;
}
Пример #3
0
int __cdecl main(int argc, char *argv[])
{

    PROCESS_INFORMATION pi;
    STARTUPINFO si;
    HANDLE hEvToHelper;
    HANDLE hEvFromHelper;
    DWORD dwExitCode;
    

    DWORD dwRet;
    char cmdComposeBuf[MAX_PATH];
    PWCHAR uniString;

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

    /* Create the signals we need for cross process communication */
    hEvToHelper = CreateEvent(NULL, TRUE, FALSE, szcToHelperEvName);
    if (!hEvToHelper) 
    {
        Fail("WriteProcessMemory: CreateEvent of '%S' failed. "
             "GetLastError() returned %d.\n", szcToHelperEvName, 
             GetLastError());
    }
    if (GetLastError() == ERROR_ALREADY_EXISTS) 
    {
        Fail("WriteProcessMemory: CreateEvent of '%S' failed. "
             "(already exists!)\n", szcToHelperEvName);
    }
    hEvFromHelper = CreateEvent(NULL, TRUE, FALSE, szcFromHelperEvName);
    if (!hEvToHelper) 
    {
        Fail("WriteProcessMemory: CreateEvent of '%S' failed. "
             "GetLastError() returned %d.\n", szcFromHelperEvName, 
             GetLastError());
    }
    if (GetLastError() == ERROR_ALREADY_EXISTS) 
    {
        Fail("WriteProcessMemory: CreateEvent of '%S' failed. "
             "(already exists!)\n", szcFromHelperEvName);
    }
    ResetEvent(hEvFromHelper);
    ResetEvent(hEvToHelper);
    
    if (!sprintf_s(cmdComposeBuf, _countof(cmdComposeBuf), "helper %s", commsFileName)) 
    {
        Fail("Could not convert command line\n");
    }
    uniString = convert(cmdComposeBuf);

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );
    
    /* Create a new process.  This is the process that will ask for
     * memory munging */
    if(!CreateProcess( NULL, uniString, NULL, NULL, 
                        FALSE, 0, NULL, NULL, &si, &pi)) 
    {
        Trace("ERROR: CreateProcess failed to load executable '%S'.  "
             "GetLastError() returned %u.\n",
              uniString, GetLastError());
        free(uniString);
        Fail("");
    }
    free(uniString);

    while(1) 
    {
        FILE *commsFile;
        char* pSrcMemory;
        char* pDestMemory;
        int Count;
        SIZE_T wpmCount;
        char incomingCMDBuffer[MAX_PATH + 1];

        /* wait until the helper tells us that it has given us
         * something to do */
        dwRet = WaitForSingleObject(hEvFromHelper, TIMEOUT);
        if (dwRet != WAIT_OBJECT_0)
        {
            Trace("test1 WaitForSingleObjectTest:  WaitForSingleObject "
                  "failed (%u)\n", GetLastError());
            break; /* no more work incoming */
        }

        /* get the parameters to test WriteProcessMemory with */
        if (!(commsFile = fopen(commsFileName, "r")))
        {
            /* no file means there is no more work */
            break;
        }
        if ( NULL == fgets(incomingCMDBuffer, MAX_PATH, commsFile))
        {
            Fail ("unable to read from communication file %s "
                  "for reasons %u & %u\n",
                  errno, GetLastError());
        }
        PEDANTIC1(fclose,(commsFile));
        sscanf(incomingCMDBuffer, "%u %u", &pDestMemory, &Count);
        if (argc > 1) 
        {
            Trace("Preparing to write to %u bytes @ %u ('%s')\n", 
                  Count, pDestMemory, incomingCMDBuffer);
        }

        /* compose some data to write to the client process */
        if (!(pSrcMemory = (char*)malloc(Count)))
        {
            Trace("could not dynamically allocate memory to copy from "
                  "for reasons %u & %u\n",
                  errno, GetLastError());
            goto doneIteration;
        }
        memset(pSrcMemory, nextValue, Count);

        /* do the work */
        dwRet = WriteProcessMemory(pi.hProcess, 
                           pDestMemory,
                           pSrcMemory,
                           Count,
                           &wpmCount);
        if (!dwRet)
        {
            Trace("%s: Problem: on a write to %u bytes @ %u ('%s')\n", 
                  argv[0], Count, pDestMemory, incomingCMDBuffer);
            Trace("test1 WriteProcessMemory returned a%u(!=0) (GLE=%u)\n", 
                  GetLastError());
        }
        if(Count != wpmCount)
        {
            Trace("%s: Problem: on a write to %u bytes @ %u ('%s')\n", 
                  argv[0], Count, pDestMemory, incomingCMDBuffer);
            Trace("The number of bytes written should have been "
                 "%u, but was reported as %u.\n", Count, wpmCount);
        }
        free(pSrcMemory);

    doneIteration: 
        PEDANTIC(ResetEvent, (hEvFromHelper));
        PEDANTIC(SetEvent, (hEvToHelper));
    }
            
    /* wait for the child process to complete */
    WaitForSingleObject ( pi.hProcess, TIMEOUT );
    /* this may return a failure code on a success path */

    /* check the exit code from the process */
    if( ! GetExitCodeProcess( pi.hProcess, &dwExitCode ) )
    {
        Trace( "GetExitCodeProcess call failed with error code %u\n", 
              GetLastError() ); 
        dwExitCode = FAIL;
    }


    PEDANTIC(CloseHandle, (hEvToHelper));
    PEDANTIC(CloseHandle, (hEvFromHelper));
    PEDANTIC(CloseHandle, (pi.hThread));
    PEDANTIC(CloseHandle, (pi.hProcess));

    PAL_TerminateEx(dwExitCode);
    return dwExitCode;
}
Пример #4
0
int __cdecl main(int argc, char **argv)
{
    HANDLE  hFile;
    HANDLE  hDupFile;
    char    buf[256];
    char    teststr[]    = "A uNiQuE tEsT sTrInG";
    char    lpFileName[] = "testfile.txt";
    DWORD   dwBytesWritten;
    DWORD   dwBytesRead;
    BOOL    bRetVal;

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

    /*Create a file handle with CreateFile*/
    hFile = CreateFile(lpFileName,
                GENERIC_WRITE|GENERIC_READ,
                FILE_SHARE_WRITE|FILE_SHARE_READ,
                NULL, 
                OPEN_ALWAYS,
                FILE_ATTRIBUTE_NORMAL, 
                NULL);
    if (hFile == INVALID_HANDLE_VALUE)
    {
        Fail("ERROR: %u :unable to create file \"%s\".\n",
            GetLastError(),
            lpFileName);
    }

    /*Write test string to the file.*/    
    bRetVal = WriteFile(hFile,      // handle to file
                teststr,            // data buffer
                strlen(teststr),    // number of bytes to write
                &dwBytesWritten,    // number of bytes written
                NULL);              // overlapped buffer

    if (bRetVal == FALSE)
    {
        Trace("ERROR: %u : unable to write to file handle "
                "hFile=0x%lx\n",
                GetLastError(),
                hFile);
        CloseHandle(hFile);
        Fail("");
    }

    /*Create a duplicate handle with DuplicateHandle.*/
    if (!(DuplicateHandle(
            GetCurrentProcess(), 
            hFile,
            GetCurrentProcess(), 
            &hDupFile,
            GENERIC_READ|GENERIC_WRITE,
            FALSE, 
            DUPLICATE_SAME_ACCESS)))
    {
        Trace("ERROR: %u : Fail to create the duplicate handle"
             " to hFile=0x%lx\n",
             GetLastError(),
             hFile);
        CloseHandle(hFile);
        Fail("");
    }

    memset(buf, 0, 256);

    /*Read from the Duplicated handle.*/
    bRetVal = ReadFile(hDupFile,
                       buf,
                       256,
                       &dwBytesRead,
                       NULL);
    if (bRetVal == FALSE)
    {
        Trace("ERROR: %u :unable to read from file handle "
                "hFile=0x%lx\n",
                GetLastError(),
                hFile);
        CloseHandle(hFile);
        CloseHandle(hDupFile);
        Fail("");
    }

    /*Compare what was written to what was read.*/
    if (memcmp(teststr, buf, dwBytesRead) != 0)
    {
        Trace("ERROR: expected %s, got %s\n", teststr, buf);
        CloseHandle(hFile);
        CloseHandle(hDupFile);
        Fail("");
    }

    /*Close the handles*/
    CloseHandle(hFile);
    CloseHandle(hDupFile);

    /*Failure test: Create DuplicateHandle to a closed handle*/
    if ((DuplicateHandle(
            GetCurrentProcess(), 
            hFile,
            GetCurrentProcess(), 
            &hDupFile,
            GENERIC_READ|GENERIC_WRITE,
            FALSE, 
            DUPLICATE_SAME_ACCESS)))
    {
        Fail("ERROR: %u :Created a duplicate handle to"
             " a closed handle hFile=0x%lx\n",
             GetLastError(),
             hFile);
    }

    /*Failure test: Create DuplicateHandle to a NULL handle*/
    hFile = NULL;
    if ((DuplicateHandle(
            GetCurrentProcess(),
            hFile,
            GetCurrentProcess(),
            &hDupFile,
            GENERIC_READ|GENERIC_WRITE,
            FALSE, 
            DUPLICATE_SAME_ACCESS)))
    {
        Fail("ERROR: %u :Created a duplicate handle to "
             " a NULL handle hFile=0x%lx\n", 
             GetLastError(),
             hFile);
    }

    PAL_Terminate();
    return (PASS);
}
Пример #5
0
int __cdecl main(int argc, char **argv)
{
#if WIN32
    FILETIME Creation;
#endif
    FILETIME LastWrite,LastAccess;
    HANDLE TheFileHandle;


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

    /* Populate some FILETIME structures with values
       These values are valid Creation, Access and Write times
       which I generated, and should work properly.

       These values aren't being used for comparison, so they should
       work ok, even though they weren't generated specifically for
       FreeBSD or WIN32 ...
    */
#if WIN32
    Creation.dwLowDateTime = 458108416;
    Creation.dwHighDateTime = 29436904;
#endif
    LastAccess.dwLowDateTime = 341368832;
    LastAccess.dwHighDateTime = 29436808;

    LastWrite.dwLowDateTime = -1995099136;
    LastWrite.dwHighDateTime = 29436915;

    /* Open the file to get a HANDLE */
    TheFileHandle =
        CreateFile(
            "the_file",
            GENERIC_READ|GENERIC_WRITE,
            0,
            NULL,
            OPEN_ALWAYS,
            FILE_ATTRIBUTE_NORMAL,
            NULL);


    if(TheFileHandle == INVALID_HANDLE_VALUE)
    {
        Fail("ERROR: Failed to open the file.  The error number "
             "returned was %d.",GetLastError());
    }

    /* Pass all NULLs, this is useless but should still work. */
    if(SetFileTime(TheFileHandle,NULL,NULL,NULL)==0)
    {
        Fail("ERROR: SetFileTime returned 0, indicating failure. "
             "Three of the params were NULL in this case, did they "
             "cause the problem?");
    }

#if WIN32
    /* Set the Creation time of the File */
    if(SetFileTime(TheFileHandle,&Creation,NULL,NULL)==0)
    {
        Fail("ERROR: SetFileTime returned 0, indicating failure. "
             "Two of the params were NULL in this case, did they "
             "cause the problem?");
    }
#endif

#if WIN32
    /* Set the Creation, LastWrite time of the File */
    if(SetFileTime(TheFileHandle,&Creation,&LastWrite,NULL)==0)
#else
    /* Set the LastWrite time of the File */
    if(SetFileTime(TheFileHandle,NULL,&LastWrite,NULL)==0)
#endif
    {
        Fail("ERROR: SetFileTime returned 0, indicating failure. "
             "One of the params were NULL in this case, did it "
             "cause the problem?");
    }


    PAL_Terminate();
    return PASS;
}
Пример #6
0
int __cdecl main(int argc, char *argv[])
{
    int err;
    int index = 0;
    LCID Locale = LOCALE_USER_DEFAULT;
    CALID Calendar;
    CALTYPE CalType = CAL_ITWODIGITYEARMAX|CAL_RETURN_NUMBER;
    DWORD dwValue;
    char *CalendarID[]={"CAL_GREGORIAN",
                        "CAL_GREGORIAN_US",
                        "CAL_JAPAN",
                        "CAL_TAIWAN",
                        "CAL_KOREA",
                        "CAL_HIJRI",
                        "CAL_THAI",
                        "CAL_HEBREW",
                        "CAL_GREGORIAN_ME_FRENCH",
                        "CAL_GREGORIAN_ARABIC",
                        "CAL_GREGORIAN_XLIT_ENGLISH",
                        "CAL_GREGORIAN_XLIT_FRENCH",
                        "CAL_JULIAN"};
        
    char errBuffer[1024];               


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

    for(index=0; index<13; index++)
    {
        Calendar = index + 1;
        /*retrieve the specified calendar info*/
        err = GetCalendarInfoW(Locale,/*locale idendifier*/
                            Calendar, /*calendar identifier*/
                            CalType,  /*calendar tyope*/
                            NULL,     /*buffer to store the retreive info*/
                            0,        /*alwayse zero*/
                            &dwValue);/*to store the requrest data*/               
        if(0 == err)
        {
            strcat(errBuffer, CalendarID[index]);
            strcat(errBuffer, ", ");           
        }
    }


    if(strlen(errBuffer) > 0)
    {
        Fail("\nFailed to call GetCalendarInfoW API by passing %s"
             " Calendar identifier(s)\n",errBuffer);
    }
    

    PAL_Terminate();
    return PASS;
}
Пример #7
0
int __cdecl main(int argc, char *argv[])
{
     
    BOOL  success = TRUE;  /* assume success */
    DWORD dwRet;
    DWORD dwProcessId;
    char szEventName[MAX_LONGPATH];
    PWCHAR uniString;

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

    /* Open the event to let test thread tell us to get started. */
    uniString = convert(szcHelperProcessStartEvName);
    hProcessStartEvent = OpenEventW(EVENT_ALL_ACCESS, 0, uniString);
    free(uniString);
    if (!hProcessStartEvent) 
    {
        Fail("helper.main: OpenEvent of '%S' failed (%u). "
             "(the event should already exist!)\n", 
             szcHelperProcessStartEvName, GetLastError());
    }

    /* Wait for signal from test thread. */
    dwRet = WaitForSingleObject(hProcessStartEvent, TIMEOUT);
    if (dwRet != WAIT_OBJECT_0)
    {
        Fail("helper.main: WaitForSingleObject '%s' failed\n"
                "LastError:(%u)\n", szcHelperProcessStartEvName, GetLastError());
    }

    dwProcessId = GetCurrentProcessId();
    
    if ( 0 >= dwProcessId ) 
    {
        Fail ("helper.main: %s has invalid pid %d\n", argv[0], dwProcessId );
    }

    /* Open the event to tell test thread we are ready. */
    if (sprintf_s(szEventName, MAX_LONGPATH-1, "%s%d", szcHelperProcessReadyEvName, dwProcessId) < 0)
    {
        Fail ("helper.main: Insufficient event name string length for pid=%d\n", dwProcessId);
    }

    uniString = convert(szEventName);

    hProcessReadyEvent = OpenEventW(EVENT_ALL_ACCESS, 0, uniString);
    free(uniString);
    if (!hProcessReadyEvent) 
    {
        Fail("helper.main: OpenEvent of '%s' failed (%u). "
             "(the event should already exist!)\n", 
             szEventName, GetLastError());
    }

    /* Open the event to let test thread tell us to exit. */
    if (sprintf_s(szEventName, MAX_LONGPATH-1, "%s%d", szcHelperProcessFinishEvName, dwProcessId) < 0)
    {
        Fail ("helper.main: Insufficient event name string length for pid=%d\n", dwProcessId);
    }

    uniString = convert(szEventName);

    hProcessFinishEvent = OpenEventW(EVENT_ALL_ACCESS, 0, uniString);
    free(uniString);
    if (!hProcessFinishEvent) 
    {
        Fail("helper.main: OpenEvent of '%s' failed LastError:(%u).\n",
             szEventName, GetLastError());
    }

    /* Tell the test thread we are ready. */
    if (!SetEvent(hProcessReadyEvent))
    {
        Fail("helper.main: SetEvent '%s' failed LastError:(%u)\n",
            hProcessReadyEvent, GetLastError());
    }

    /* Wait for signal from test thread before exit. */
    dwRet = WaitForSingleObject(hProcessFinishEvent, TIMEOUT);
    if (WAIT_OBJECT_0 != dwRet)
    {
        Fail("helper.main: WaitForSingleObject '%s' failed pid=%d\n"
            "LastError:(%u)\n", 
            szcHelperProcessFinishEvName, dwProcessId, GetLastError());
    }

    PEDANTIC(CloseHandle, (hProcessStartEvent));
    PEDANTIC(CloseHandle, (hProcessReadyEvent));
    PEDANTIC(CloseHandle, (hProcessFinishEvent));

    PAL_Terminate();

    return success ? PASS : FAIL;
}
Пример #8
0
int __cdecl main(int argc, char *argv[]) {
    int ret = FAIL;

    //Test is failing unreliably, so for now we always return pass.
    if (TRUE){
        ret = PASS;
        goto EXIT;
    }   

    LONG64 Actual, Expected, Delta = 850000000;
    Actual = 0;
    Expected = 0;
    const LONG64 MSEC_TO_NSEC = 1000000;

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

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

    HANDLE cThread = GetCurrentThread();

    int i;
    /* Take 2000 tiny measurements */
    for (i = 0; i < 2000; i++){
        ULONG64 FirstCount, SecondCount;
        LONG64 Init;
        
        Sleep(1);

        /* Grab a FirstCount, then loop for a bit to make the clock increase */
        if (!QueryThreadCycleTime(cThread, (PULONG64)&FirstCount))
        {
            Fail("ERROR: QueryThreadCycleTime returned failure.\n");
        }
        
        LONG64 x;
        /* Init is in milliseconds, so we will convert later */
        Init = (LONG64)GetTickCount();
        x = Init + 3;
        volatile int counter;
        do {
            for (counter = 0; counter < 100000; counter++)
            {
                // spin to consume CPU time
            }

        } while (x > GetTickCount());
        Expected += (GetTickCount() - Init) * MSEC_TO_NSEC;
        /* Get a second count */
        if (!QueryThreadCycleTime(cThread, (PULONG64)&SecondCount))
        {
            Fail("ERROR: QueryThreadCycleTime returned failure.\n");
        }

        LONG64 trial = (LONG64)SecondCount - (LONG64)FirstCount;
        if (trial < 0){
            printf("Negative value %llu measured", trial);
        }
        Actual += (trial);

    }



    if(labs(Expected - Actual) > Delta)
    {
        Fail("ERROR: The measured time (%llu millisecs) was not within Delta %llu "
            "of the expected time (%llu millisecs).\n",
             (Actual / MSEC_TO_NSEC), (Delta / MSEC_TO_NSEC), (Expected / MSEC_TO_NSEC));
    }
    //printf("%llu, %llu\n", Expected, Actual);
    PAL_Terminate();
    ret = PASS;

EXIT:
    return ret;
}
Пример #9
0
int __cdecl main(int argc, char *argv[]) 
{

#if WIN32

    return PASS;

#else

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

    char FirstEnvironmentVariable[] = {"PALTEST"};
    char FirstEnvironmentValue[] = {"FIRST"};

    char SecondEnvironmentVariable[] = {"paltest"};
    char SecondEnvironmentValue[] = {"SECOND"};

    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 = SetEnvironmentVariableA(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 = GetEnvironmentVariableA(FirstEnvironmentVariable,        
                                  pResultBuffer,    
                                  0);                 

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

    /* Try to retrieve the value of the first environment variable */
    GetEnvironmentVariableA(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(strcmp(pResultBuffer,FirstEnvironmentValue) != 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 = SetEnvironmentVariableA(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(char)*size);
    if ( pResultBuffer == NULL )
    {
	    Fail("ERROR: Failed to allocate memory for pResultBuffer pointer.");
    }

    /* Try retrieving the value of the first variable, even though the
    second variable has the same spelling and only differs in case */
    GetEnvironmentVariableA(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(strcmp(pResultBuffer,FirstEnvironmentValue) != 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
}
Пример #10
0
int __cdecl main(int argc, char *argv[])
{
    HMODULE ModuleHandle;
    int err;
    DWORD ModuleNameLength;
    char ModuleFileNameBuf[MODULENAMEBUFFERSIZE]="";
    char* TempBuf = NULL;
    char* LastBuf = NULL;

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


    //load a module
    ModuleHandle = LoadLibrary(ModuleName);
    if(!ModuleHandle)
    {
        Fail("Failed to call LoadLibrary API!\n");
    }


    //retrieve the specified module full path and file name
    ModuleNameLength = GetModuleFileName(
                ModuleHandle,//specified module handle
                ModuleFileNameBuf,//buffer for module file name
                MODULENAMEBUFFERSIZE);

    //strip out all full path
    TempBuf = strtok(ModuleFileNameBuf,Delimiter);
    LastBuf = TempBuf;
    while(NULL != TempBuf)
    {
        LastBuf = TempBuf;
        TempBuf = strtok(NULL,Delimiter);
    }


    if(0 == ModuleNameLength || strcmp(ModuleName,LastBuf))
    {
        Trace("\nFailed to all GetModuleFileName API!\n");
        err = FreeLibrary(ModuleHandle);
        if(0 == err)
        {
            Fail("\nFailed to all FreeLibrary API!\n");
        }
        Fail("");
    }

        //decrement the reference count of the loaded dll
    err = FreeLibrary(ModuleHandle);
    if(0 == err)
    {
        Fail("\nFailed to all FreeLibrary API!\n");
    }

    PAL_Terminate();
    return PASS;
}
Пример #11
0
/**
 * main
 * 
 * executable entry point
 */
INT __cdecl main(INT argc, CHAR **argv)
{
    int     i;
    int     err;    
    int     addrlen = sizeof(struct sockaddr);
    struct  sockaddr_in mySockaddr;
    WSADATA wsaData;
    HANDLE  hReadEvent;
    DWORD   waitResult;

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

    HANDLE hThreadEvent; 

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

    SOCKET testSockets[2];

    /* variable for iocltsocket */
    u_long argp;

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

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

    /* Variables needed for WSARecv */
    WSABUF        wsaBuf;
    DWORD         dwNbrOfBuf  = 1;
    DWORD         dwNbrOfByteSent;
    DWORD         dwRecvFlags = 0;
    WSAOVERLAPPED wsaRecvOverlapped;
    
    /* Variable used to store transmitted data */
    unsigned char myBuffer[255];
    unsigned char myData[500][255];
    unsigned char* pMyData;   

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

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

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

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

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

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

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

        Fail("");
    }

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

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


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

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

        Fail("");
    }

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

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

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

        Fail("");
    }

    /* 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("ERROR: Unexpected failure: "
              "bind() socket with local address "
              "returned %d\n",
              GetLastError() );

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

        Fail("");
    }

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

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

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

        Fail("");
    }
    
    /* Create a Event with initial owner. */
    hThreadEvent = CreateEvent( NULL, /* no security   */
                             FALSE,   /* reset type    */
                             FALSE,   /* initial state */
                             "EventClientServer" );  /* object name   */

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

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

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

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

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

        Fail("");
    }
    
    /* set the server waiting time as 10 seconds */
    waitTime.tv_sec = 10L;
    waitTime.tv_usec = 0L;

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

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

    /* monitor the readable socket set 
       to determine when a connection is ready to be accepted
    */
    socketFds = select( 0,
                        &readFds,
                        NULL,
                        NULL,
                        &waitTime);
    

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

        WaitForClientThreadToFinish(hThreadClient);

        CloseThreadHandle(hThreadClient);

        CloseEventHandle(hThreadEvent);

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

        Fail("");
    }

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

        WaitForClientThreadToFinish(hThreadClient);

        CloseThreadHandle(hThreadClient);

        CloseEventHandle(hThreadEvent);   

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

        Fail("");
    }

    if(CloseEventHandle(hThreadEvent)==0)
    {
        WaitForClientThreadToFinish(hThreadClient);

        CloseThreadHandle(hThreadClient);        

        Fail("");
    }

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

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

        WaitForClientThreadToFinish(hThreadClient);

        CloseThreadHandle(hThreadClient);        

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

        Fail("");
    }

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

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

        WaitForClientThreadToFinish(hThreadClient);

        CloseThreadHandle(hThreadClient);        

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

        Fail("");
    }

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

        WaitForClientThreadToFinish(hThreadClient);        

        CloseThreadHandle(hThreadClient);        

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

        Fail("");
        
    }



   /* Initialize the WSABUF structure */
    memset(myBuffer, 0, 255);

    wsaBuf.buf = myBuffer;
    wsaBuf.len = 255;    
    
    bufferCounter = 0;
    pMyData = (unsigned char*)myData;
    
    for(i=0;i<500;i++)
    {
        /* Initialize the WSAOVERLAPPED to 0 */
        memset(&wsaRecvOverlapped, 0, sizeof(WSAOVERLAPPED));

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

         /* reset the buffer used by WSARecv */
        memset(myBuffer, 0, 255);
        
         /* Prepare to receive data */
        err = WSARecvFrom( testSockets[1],
                   &wsaBuf,
                   dwNbrOfBuf,
                   &dwNbrOfByteSent,
                   &dwRecvFlags,
                   NULL,
                   NULL,
                   &wsaRecvOverlapped,
                   0 );   

        if( err != SOCKET_ERROR )
        {
            ResetEvent(hReadEvent);
            if(dwNbrOfByteSent==0)
            {
                /*
                 Socket as been closed normally
                */
                break;
            }
            else
            {
                /* no error the server can continue receiving other buffer */
            }
        }
        else
        {
            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(hReadEvent);
                
                /* Do some cleanup */
                DoWSATestCleanup( testSockets,
                                numSockets );
        
                Fail("");
            }
            /* Wait 10 seconds for ReadEvent to be signaled 
                from the pending operation
            */
            waitResult = WaitForSingleObject( hReadEvent, 
                                              10000 );    
            
            if (waitResult!=WAIT_OBJECT_0)
            {           
                Trace("Server error: Unexpected failure: "
                    "WaitForSingleObject has timed out \n");

                WaitForClientThreadToFinish(hThreadClient);                

                CloseThreadHandle(hThreadClient);

                CloseEventHandle(hReadEvent);                

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

                Fail("");
            }
        }    

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

            /* increment the position where we can write data on the array*/
            pMyData+=wsaRecvOverlapped.InternalHigh;
        }
        else
        {
            Trace("Server error: Array out of bound "
                "while writing buffer received in myData.\n");

            WaitForClientThreadToFinish(hThreadClient);                

            CloseThreadHandle(hThreadClient);

            CloseEventHandle(hReadEvent);                

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

            Fail("");            
        }

        /* Increment bufferCounter to keep track of the number 
           of byte received */
        bufferCounter += wsaRecvOverlapped.InternalHigh; 
        
    } /* end of the for loop */

    if(!WaitForClientThreadToFinish(hThreadClient))
    {
        CloseThreadHandle(hThreadClient);

        CloseEventHandle(hReadEvent);

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

        Fail("");
    }

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


    /* verify that all data in the data array are as expected */
    pMyData=(unsigned char*)myData;
    for(i=0;i<bufferCounter;i++)
    {
        if(*pMyData!=(i%255))
        {
            Trace("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;
}
Пример #12
0
int __cdecl main(int argc, char *argv[])
{    
  int testStatus = PASS;

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

  /* Use WideCharToMultiByte to convert the string in code page CP_ACP.
   * Note that the resulting string will be different on Windows PAL and 
   * Unix PAL. On Windows, the default best fit behavior will map C with 
   * circumflex to C. 
   * 
   *   testStatus |= TestWideCharToMultiByte(CP_ACP, 0, NULL, lpBestFitRes);
   *
   * On Unix, where there is no support for finding best fit, it will be 
   * mapped to a '?'. In addition, it will trigger an ASSERT in the dbg/chk
   * builds.
   *
   *   testStatus |= TestWideCharToMultiByte(CP_ACP, 0, NULL, lpResStr1);
   */

  /* Use WideCharToMultiByte with WC_NO_BEST_FIR_CHARS to convert the string 
   * in CP_ACP (1252 by default). This will prevent it from mapping the C 
   * with circumflex to its closest match in the ANSI code page: C
   */
  testStatus |= TestWideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, NULL, lpResStr1);


  /* Use WideCharToMultiByte with WC_NO_BEST_FIR_CHARS and a default character 
   * to convert the string. This will prevent it from mapping the C with 
   * circumflex to its closest match in the ANSI code page: C. It will be
   * replaced with the specified default character.
   */
  testStatus |= TestWideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, &myDefaultChar, lpResStr2);

  /* Use WideCharToMultiByte to convert the string in code page 1253 
   * Note that the resulting string will be different on Windows PAL and 
   * Unix PAL. On Windows, the default best fit behavior will map C with 
   * circumflex to C. 
   * 
   *   testStatus |= TestWideCharToMultiByte(1253, 0, NULL, lpBestFitRes);
   *
   * On Unix, where there is no support for finding best fit, it will be 
   * mapped to a '?'. In addition, it will trigger an ASSERT in the dbg/chk
   * builds.
   *
   *   testStatus |= TestWideCharToMultiByte(1253, 0, NULL, lpResStr1);
   */

  /* Use WideCharToMultiByte with WC_NO_BEST_FIR_CHARS to convert the string 
   * in 1253. This will prevent it from mapping the C 
   * with circumflex to its closest match in the ANSI code page: C
   */
  testStatus |= TestWideCharToMultiByte(1253, WC_NO_BEST_FIT_CHARS, NULL, lpResStr1);

  /* Use WideCharToMultiByte with WC_NO_BEST_FIR_CHARS and a default 
   * character to convert the string in 1253. This will prevent it from 
   * mapping the C with circumflex to its closest match in the ANSI code 
   * page: C. It will be replaced with the specified default character.
   */
  testStatus |= TestWideCharToMultiByte(1253, WC_NO_BEST_FIT_CHARS, &myDefaultChar, lpResStr2);

  PAL_TerminateEx(testStatus);

  return testStatus;
}
Пример #13
0
int __cdecl main(int argc, char *argv[])
{

    BOOL bRc = TRUE;
    char* szSrcExisting = "src_existing.tmp";
    FILE* tempFile = NULL;
    DWORD temp;
    int retCode;
    
    if (0 != PAL_Initialize(argc,argv))
    {
        return FAIL;
    }

   /* create the src_existing file */
    tempFile = fopen(szSrcExisting, "w");
    if (tempFile != NULL)
    {
        retCode = fputs("CopyFileA test file: src_existing.tmp ", tempFile);
        if(retCode < 0)
        {
            Fail("CopyFileA: ERROR-> Couldn't write to %s with error "
                "%u.\n", szSrcExisting, GetLastError());
        }
        retCode = fclose(tempFile);
        if(retCode != 0)
        {
            Fail("CopyFileA: ERROR-> Couldn't close file: %s with error "
                "%u.\n", szSrcExisting, GetLastError());
        }

    }
    else
    {
        Fail("CopyFileA: ERROR-> Couldn't create %s with "
            "error %ld\n",szSrcExisting,GetLastError());
    }

    /* Get file attributes of source */
    temp = GetFileAttributes(szSrcExisting);
    if (temp == -1)
    {
        Fail("CopyFileA: GetFileAttributes of source file "
            "failed with error code %ld. \n",
            GetLastError());
    }
    
    /* make sure a file can't copy to itself
    first testing with IfFileExists flag set to true */
    bRc = CopyFileA(szSrcExisting,szSrcExisting,TRUE);
    if(bRc)
    {
        Fail("ERROR: Cannot copy a file to itself, %u",GetLastError());
    }
    
    /* try to get file attributes of desitnation */
    if (GetFileAttributesA(szSrcExisting) == -1)
    {
        Fail("CopyFileA: GetFileAttributes of destination file "
            "failed with error code %ld. \n",
            GetLastError());  
    }
    else
    {
        /* verify attributes of destination file to source file*/               
     
        if(temp != GetFileAttributes(szSrcExisting))
        {
            Fail("CopyFileA : The file attributes of the "
                "destination file do not match the file "
                "attributes of the source file.\n");
        }
    }

    /* testing with IfFileExists flags set to false
    should fail in Windows and pass in UNIX */
    bRc = CopyFileA(szSrcExisting,szSrcExisting,FALSE);
    if(bRc && (GetLastError() != ERROR_ALREADY_EXISTS))
    {
        Fail("ERROR: Cannot copy a file to itself, %u",GetLastError());
    }
    
    if (GetFileAttributesA(szSrcExisting) == -1)
    {
        Fail("CopyFileA: GetFileAttributes of destination file "
            "failed with error code %ld. \n",
            GetLastError());
    }
    else
    {
        /* verify attributes of destination file to source file*/               
     
        if(temp != GetFileAttributes(szSrcExisting))
        {
            Fail("CopyFileA : The file attributes of the "
                "destination file do not match the file "
                "attributes of the source file.\n");
        }
    }

    PAL_Terminate();
    return PASS;
}
Пример #14
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];    
    
    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;   

    /* 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 = WSARecvFrom( testSockets[0],
                       &wsaBuf,
                       dwNbrOfBuf,
                       &dwNbrOfByteSent,
                       &dwRecvFlags,
                       (struct sockaddr FAR *) NULL,
                       (int) NULL,
                       &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)
            {
                /* Packet dropped, UDP is not reliable 
                   we just stop receiving
                */
                break;
     
            }

            /* 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,
                                            1000 );
            
            if (waitResult!=WAIT_OBJECT_0)
            {   
                /* Packet dropped, UDP is not reliable 
                   we just stop receiving
                */
                break;     
            }
        }        
        
        /* 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("");
        }
        
        /* 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("");
    }    

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

    if(bufferCounter==0)
    {
        Trace("Server error: 0 byte has been received on UDP socket");
        Fail("");
    }

    PAL_Terminate();
    return PASS;
}
Пример #15
0
int __cdecl main(int argc, char *argv[])
{
    DWORD   dwRc = 0;
    char    szReturnedPath[_MAX_DIR+1];
    char    szFullFileName[_MAX_DIR+1];
    char    szDirectory[256];
    char*   szCreatedDir = {"test_directory"};
    WCHAR   *szCreatedDirW;
    LPSTR   pPathPtr;
    HANDLE  hFile = NULL;
    BOOL    bRetVal = FAIL;

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

    /* Initialize the buffer.
     */
    memset(szDirectory, '\0', 256);

    /* Create the path to the next level of directory to create.
     */
    strcat( szDirectory, szDotDot );        /* ..                  */
    strcat( szDirectory, szSeperator );     /* ../                 */
    strcat( szDirectory, szCreatedDir );    /* ../test_directory   */

    /* Create a test directory.
     */
    if ( !CreateDirectoryA( szDirectory, NULL ) )
    {
        Fail("ERROR:%u: Unable to create directories \"%s\".\n",
             GetLastError(),
             szDirectory);
    }

    /* Initialize the receiving char buffers.
     */
    memset(szReturnedPath, 0, _MAX_DIR+1);
    memset(szFullFileName, 0, _MAX_DIR+1);

    /* Create Full filename to pass, will include '..\'
     * in the middle of the path.
     */
    strcat( szFullFileName, szDotDot );     /* ..                            */
    strcat( szFullFileName, szSeperator );  /* ../                           */
    strcat( szFullFileName, szCreatedDir ); /* ../test_directory             */
    strcat( szFullFileName, szSeperator );  /* ../test_directory/            */
    strcat( szFullFileName, szFileName );   /* ../test_directory/testing.tmp */

    /* Get the full path to the filename.
     */
    dwRc = GetFullPathNameA(szFullFileName, 
                            _MAX_DIR,
                            szReturnedPath, 
                            &pPathPtr);
    if (dwRc == 0)
    {
        Trace("ERROR :%ld: GetFullPathName failed to "
              "retrieve the path of \"%s\".\n",
              GetLastError(),
              szFileName);
        bRetVal = FAIL;
        goto cleanUpOne;
    }

    /* The returned value should be the parent directory with the 
     * file name appended. */
    hFile = CreateFileA(szReturnedPath,
                        GENERIC_READ,
                        FILE_SHARE_READ,
                        NULL,
                        CREATE_ALWAYS,
                        FILE_ATTRIBUTE_NORMAL,
                        NULL);

    if (hFile == INVALID_HANDLE_VALUE)
    {
        Trace("ERROR :%ld: CreateFileA failed to create \"%s\".\n", 
              GetLastError(),
              szReturnedPath);
        bRetVal = FAIL;
        goto cleanUpOne;
    }

    /* Close the handle to the created file.
     */
    if (CloseHandle(hFile) != TRUE)
    {
        Trace("ERROR :%ld: CloseHandle failed close hFile=0x%lx.\n",
              GetLastError());
        bRetVal = FAIL;
        goto cleanUpTwo;
    }

    /* Verify that the file was created, attempt to create 
     * the file again. */
    hFile = CreateFileA(szReturnedPath,
                        GENERIC_READ,
                        FILE_SHARE_READ,
                        NULL,
                        CREATE_NEW,
                        FILE_ATTRIBUTE_NORMAL,
                        NULL);
    if ((hFile != INVALID_HANDLE_VALUE) && 
        (GetLastError() != ERROR_ALREADY_EXISTS))
    {
        Trace("ERROR :%ld: CreateFileA succeeded to create file "
              "\"%s\", that already existed.\n",
              GetLastError(),
              szFullFileName);
        bRetVal = FAIL;
        goto cleanUpTwo;
    }

    /* Verify that the returned filename is the same as the supplied.
     */
    if (strcmp(pPathPtr, szFileName) != 0)
    {
        Trace("ERROR : Returned filename \"%s\" is not equal to "
             "supplied filename \"%s\".\n",
             pPathPtr, 
             szFileName);
        bRetVal = FAIL;
        goto cleanUpTwo;
    }

    /* Successful test.
     */
    bRetVal = PASS;

cleanUpTwo:
    
    /* Delete the create file. 
     */
    if (DeleteFileA(szReturnedPath) != TRUE)
    {
        Fail("ERROR :%ld: DeleteFileA failed to delete \"%s\".\n",
             GetLastError(),
             szFileName);
    }

cleanUpOne:

    /* Remove the empty directory.
     */
    szCreatedDirW = convert((LPSTR)szDirectory);
    if (!RemoveDirectoryW(szCreatedDirW))
    {
        free (szCreatedDirW);
        Fail("ERROR:%u: Unable to remove directory \"%s\".\n",
             GetLastError(),
             szCreatedDir);
    }
    free (szCreatedDirW);

    /* Terminate the PAL.*/
    PAL_Terminate();
    return bRetVal;
}
Пример #16
0
/*
 * NaN: any double with maximum exponent (0x7ff) and non-zero fraction
 */
int __cdecl main(int argc, char *argv[])
{
    UINT64 PosInf=0;
    UINT64 NegInf=0;
    UINT64 val=0;

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


    PosInf = 0x7ff00000;
    PosInf <<=32;

    NegInf = 0xfff00000;
    NegInf <<=32;

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

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

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

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


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

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

    PAL_Terminate();

    return PASS;
}
Пример #17
0
int __cdecl main(int argc, char *argv[]) {

    WCHAR* lpPath        = NULL;
    WCHAR* lpFileName    = NULL;
    WCHAR* lpExtension   = NULL;
    DWORD  nBufferLength = 0;
    WCHAR  lpBuffer[_MAX_PATH];
    WCHAR** lpFilePart    = NULL;
    DWORD  error         = 0;
    DWORD  result        = 0;

    HANDLE hsearchfile;
    char fname[_MAX_FNAME];
    char ext[_MAX_EXT];
    char   fullPath[_MAX_DIR];
	char drive[_MAX_DRIVE];
    char dir[_MAX_DIR];


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

   /* Initalize the buffer.
     */
    memset(fullPath, 0, _MAX_DIR);

    if (GetTempPathA(_MAX_DIR, fullPath) == 0)
    {
        Fail("ERROR: GetTempPathA failed to get a path\n");
    }

    memset(fileloc, 0, _MAX_PATH);
    sprintf_s(fileloc, _countof(fileloc), "%s%s", fullPath, szFileNameExistsWithExt);

    RemoveAll();

    hsearchfile = CreateFileA(fileloc, GENERIC_WRITE, 0, 0, CREATE_ALWAYS,                        
                            FILE_ATTRIBUTE_NORMAL, 0);

    if (hsearchfile == NULL)
    {
        Trace("ERROR[%ul]: couldn't create %s\n", GetLastError(), fileloc);
        return FAIL;    
    }

    CloseHandle(hsearchfile);

    //
    // find a file that doesn't exist
    //
    ZeroMemory( lpBuffer, sizeof(lpBuffer));
    lpPath        = convert((LPSTR)fullPath);
    lpFileName    = convert((LPSTR)szNoFileName);
    lpExtension   = NULL;

    if( SearchPathW( lpPath, lpFileName, lpExtension, nBufferLength, lpBuffer, lpFilePart) != 0 ){
        error = GetLastError();
        free(lpPath);
        free(lpFileName);
        Fail ("SearchPathW: ERROR1 -> Found invalid file[%s][%s][%s][%d]\n", lpPath, szNoFileName, szNoFileNameExt, error);
    }

    free(lpPath);
    free(lpFileName);

    //
    // find a file that exists, when path is mentioned explicitly
    //
    ZeroMemory( lpBuffer, sizeof(lpBuffer));
    lpPath        = convert((LPSTR)fullPath);
    lpFileName    = convert((LPSTR)szFileNameExistsWithExt);
    lpExtension   = NULL;

    result  = SearchPathW( lpPath, lpFileName, lpExtension, nBufferLength, lpBuffer, lpFilePart);

    if( result == 0 ){
        error = GetLastError();
        free(lpPath);
        free(lpFileName);
        Fail ("SearchPathA: ERROR2 -> Did not Find valid file[%s][%s][%d]\n", lpPath, szFileNameExistsWithExt, error);
    }

    free(lpPath);
    free(lpFileName);

    RemoveAll();

    PAL_Terminate();
    return PASS; 
}
Пример #18
0
int __cdecl main(int argc, char *argv[])
{
    HANDLE hFile = NULL;
    DWORD dwOffset = 1;
    DWORD dwHighWord = 1;
    DWORD dwReturnedOffset = 0;
    DWORD dwReturnedHighWord = 0;
    DWORD dwRc = 0;
    DWORD dwError = 0;
    BOOL bRc = FALSE;


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

    /* create a test file */
    hFile = CreateFile(szTextFile,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    if(hFile == INVALID_HANDLE_VALUE)
    {
        dwError = GetLastError();
        Fail("SetFilePointer: ERROR -> Unable to create file \"%s\".\n with "
            "error %ld",
            szTextFile,
            GetLastError());
    }



    /* move -1 from beginning which should fail */
    dwRc = SetFilePointer(hFile, -1, &dwHighWord, FILE_BEGIN);
    if (dwRc != INVALID_SET_FILE_POINTER)
    {
        Trace("SetFilePointer: ERROR -> Succeeded to move the pointer "
            "before the beginning of the file using the high word.\n");
        bRc = CloseHandle(hFile);
        if (bRc != TRUE)
        {
            Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n",
                szTextFile);
        }
        if (!DeleteFileA(szTextFile))
        {
            Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n",
                szTextFile);
        }
        PAL_Terminate();
        return FAIL;
    }

    /* set the pointer past the end of the file and verify */
    dwRc = SetFilePointer(hFile, dwOffset, &dwHighWord, FILE_BEGIN);
    if ((dwRc == INVALID_SET_FILE_POINTER) &&
        ((dwError = GetLastError()) != ERROR_SUCCESS))
    {
        Trace("SetFilePointer: ERROR -> Failed to move pointer past EOF.\n");
        bRc = CloseHandle(hFile);
        if (bRc != TRUE)
        {
            Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n",
                szTextFile);
        }
        if (!DeleteFileA(szTextFile))
        {
            Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n",
                szTextFile);
        }
        PAL_Terminate();
        return FAIL;
    }
    else
    {
        /* verify */
        bRc = SetEndOfFile(hFile);
        if (bRc != TRUE)
        {
            dwError = GetLastError();
            if (dwError == 112)
            {
                Trace("SetFilePointer: ERROR -> SetEndOfFile failed due to "
                    "lack of disk space\n");
            }
            else
            {
                Trace("SetFilePointer: ERROR -> SetEndOfFile call failed with "
                    "error %ld\n", dwError);
            }
            bRc = CloseHandle(hFile);
            if (bRc != TRUE)
            {
                Trace("SetFilePointer: ERROR -> Unable to close file"
                      " \"%s\".\n", szTextFile);
            }
            if (!DeleteFileA(szTextFile))
            {
                Trace("SetFilePointer: ERROR -> Unable to delete file"
                      " \"%s\".\n", szTextFile);
            }
            PAL_Terminate();
            return FAIL;
        }

        dwReturnedOffset = GetFileSize(hFile, &dwReturnedHighWord);
        if ((dwOffset != dwReturnedOffset) ||
           (dwHighWord != dwReturnedHighWord))
        {
            Trace("SetFilePointer: ERROR -> Failed to move pointer past"
                  " EOF.\n");
            bRc = CloseHandle(hFile);
            if (bRc != TRUE)
            {
                Trace("SetFilePointer: ERROR -> Unable to close file"
                      " \"%s\".\n", szTextFile);
            }
            if (!DeleteFileA(szTextFile))
            {
                Trace("SetFilePointer: ERROR -> Unable to delete file"
                      " \"%s\".\n", szTextFile);
            }
            PAL_Terminate();
            return FAIL;
        }
    }

    bRc = CloseHandle(hFile);
    if (bRc != TRUE)
    {
        Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", 
            szTextFile);
        if (!DeleteFileA(szTextFile))
        {
            Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", 
                szTextFile);
        }
        PAL_Terminate();
        return FAIL;
    }

    if (!DeleteFileA(szTextFile))
    {
        Fail("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", 
            szTextFile);
    }

    PAL_Terminate();
    return PASS;
}
Пример #19
0
int __cdecl main(int argc, char *argv[])
{
    char szFileName[] = {"test1.tmp"};
    const char text[] = 
        {"The quick brown fox jumped over the lazy dog's back."};
    FILE* pFile = NULL;
    int nChar = 65; /* 'A' */
    int nRc = 0;
    int itemsExpected;
    int itemsWritten;

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

    /* create the file */
    pFile = fopen(szFileName, "w");
    if (pFile == NULL)
    {
        Fail("ungetc: ERROR -> fopen failed to create the file \"%s\""
            " as write-only.\n",
            szFileName);
    }

    /* write to the file */
    itemsExpected = sizeof(text);
    itemsWritten = fwrite(text, sizeof(text[0]), sizeof(text), pFile);  
    if (itemsWritten == 0)
    {
        Trace("ungetc: ERROR -> fwrite failed to write to the file \"%s\"\n",
            szFileName);

        if (fclose(pFile) != 0)
        {
            Fail("ungetc: ERROR -> fclose failed to close the file.\n");
        }
        Fail("");

    }
    else if (itemsWritten != itemsExpected) 
    {
        Trace("ungetc: ERROR -> fwrite failed to write the correct number "
            "of characters to the file \"%s\"\n",
            szFileName);

        if (fclose(pFile) != 0)
        {
            Fail("ungetc: ERROR -> fclose failed to close the file.\n");
        }
        Fail("");
    }

    /* Close the file */
    if (fclose(pFile) != 0)
    {
        Fail("ungetc: ERROR -> fclose failed to close the file.\n");
    }

    /*
    ** open the file in write only mode and
    ** attempt to push an unread character back on the stream
    */


    /* open the file write-only */
    pFile = fopen(szFileName, "a");
    if (pFile == NULL)
    {
        Fail("ungetc: ERROR -> fopen failed to open the file \"%s\""
            " as write-only.\n",
            szFileName);
    }

    /* move the file pointer back to the beginning of the file */
    if (fseek(pFile, 1, SEEK_SET) != 0)
    {

        Trace("ungetc: ERROR -> fseek failed to move the file pointer to the "
            "beginning of the file.\n");
        if (fclose(pFile) != 0)
        {
            Trace("ungetc: ERROR -> fclose failed to close the file.\n");
        }
        Fail("");
    }

    /* call ungetc on a write-only file which should fail */
    if ((nRc = ungetc(nChar, pFile)) != EOF)
    {
        Trace("ungetc: ERROR -> ungetc returned \"%c\" when run on "
            "an write-only file.\n", nChar);
        if (fclose(pFile) != 0)
        {
            Trace("ungetc: ERROR -> fclose failed to close the file.\n");
        }
        Fail("");
    }

    if (fclose(pFile) != 0)
    {
        Fail("ungetc: ERROR -> fclose failed to close the file.\n");
    }

    
    PAL_Terminate();
    return PASS;
}
Пример #20
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;
}
Пример #21
0
int __cdecl main(int argc, char *argv[])
{
    WORD VersionRequested = MAKEWORD(2, 2);
    WSADATA WsaData;
    int err;
    int SocketID;
    int size;
    BOOL bValue;

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

    size = sizeof(BOOL);

    /*retrive socket option 0x3101 which is not supported*/
    err = getsockopt(SocketID, SOL_SOCKET, 0x3101, (char *)&bValue, &size);
    if(WSAENOPROTOOPT != GetLastError() || SOCKET_ERROR != err)
    {    
        /*no error occured*/
        Trace("\nFailed to call getsockopt API for negative test "
            "by passing wrong socket option, 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!, error code=%d\n",
            GetLastError());
    }

    PAL_Terminate();
    return PASS;
}
Пример #22
0
/**
 * main
 * 
 * executable entry point
 */
int __cdecl main( int argc, char **argv ) 
{
    /* local variables */
    int err;
    WORD wVersionRequested;
    WSADATA wsaData;
    DWORD dwSocketError;
    u_long one;
    struct  sockaddr_in mySockaddr;

    SOCKET sock = INVALID_SOCKET;

    /* recvfrom operation varaibles*/
    HANDLE hReadEvent;    
    char myBuffer[255];    
    DWORD         dwRecvFlags = 0;
    WSAOVERLAPPED wsaRecvOverlapped;
    int sizeOverlapped;    


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


    /* initialize winsock version 2.2 */
    wVersionRequested = MAKEWORD( 2, 2 );

    err = WSAStartup( wVersionRequested, &wsaData );
    if ( err != 0 )
    {
        Fail( "Unexpected WSAStartup call failed with error code %d\n", 
              err ); 
    }

    /* Confirm that the WinSock DLL supports the specified version. */
    if( LOBYTE( wsaData.wVersion ) != 2 ||
        HIBYTE( wsaData.wVersion ) != 2 )
    {
        /* Tell the user that we could not find a usable winsock DLL. */
        
        if (WSACleanup()==0 )
        {                
            Trace("WSACleanup call failed with error code %u\n",
                GetLastError() ); 
        }

        Fail(   "Requested winsock version unsupported, "
                "returned version %d.%d\n", 
                LOBYTE( wsaData.wVersion ),
                HIBYTE( wsaData.wVersion ) ); 
    }

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


    /* create a stream socket in Internet domain */
    sock = WSASocketA(  AF_INET,
                        SOCK_DGRAM,
                        IPPROTO_UDP,
                        NULL,
                        0,
                        WSA_FLAG_OVERLAPPED
                    );


    if( sock == INVALID_SOCKET )
    {
        /* check the socket-specific error code */    
        dwSocketError = GetLastError();
        
        if (WSACleanup()==0 )
        {                
            Trace("WSACleanup call failed with error code %u\n",
                GetLastError() ); 
        }

        Fail(   "WSASocket call failed with error code %d\n",
                dwSocketError ); 
    }
    
    /* set the socket to non-blocking */
    one = 1;
    err = ioctlsocket( sock, FIONBIO, &one );
    if( err != 0 )
    {
        /* check the socket-specific error code */    
        dwSocketError = GetLastError();
        Fail(   "ioctlsocket call failed with error code %d\n",
                dwSocketError ); 
    }
    
    
    /* bind local address to a socket */
    err = bind( sock,
                (struct sockaddr *)&mySockaddr,
                sizeof(struct sockaddr) );

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

        /* Do some cleanup */
        if (closesocket( sock )==SOCKET_ERROR )
        {
            Trace("Error closing socket\n");                
        }
       
        if (WSACleanup()==0 )
        {                
            Trace("WSACleanup call failed with error code %u\n",
                GetLastError() ); 
        }

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

         /* Do some cleanup */
        if (closesocket( sock )==SOCKET_ERROR )
        {
            Trace("Error closing socket\n");                
        }
        
        if (WSACleanup()==0 )
        {                
            Trace("WSACleanup call failed with error code %u\n",
                GetLastError() ); 
        }

        Fail("");
        
    }

    /* Initialize the WSABUF structure */
    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;

    sizeOverlapped = (int) sizeof(mySockaddr);

    /* Prepare to receive data */
    err = recvfrom( sock,
                myBuffer,
                255,
                dwRecvFlags,
                (struct sockaddr*)&mySockaddr,
                &sizeOverlapped);

    if( err != SOCKET_ERROR )
    {
        Trace("Server error: WSARecv() "
                    "returned  %d, SOCKET_ERROR\n",
                    err ); 

        if (CloseHandle(hReadEvent)==0)
        {
            Trace("Server error: CloseHandle Failed ");                    
        }

        /* Do some cleanup */
        if (closesocket( sock )==SOCKET_ERROR )
        {
            Trace("Error closing socket\n");                
        }
        
        if (WSACleanup()==0 )
        {                
            Trace("WSACleanup call failed with error code %u\n",
                GetLastError() ); 
        }

        Fail("");
    
    }
    else
    {
        err = GetLastError();
        /* Only WSA_IO_PENDING is expected */
        if(err==WSA_IO_PENDING)
        {
            /* Wait 10 seconds for ReadEvent to be signaled 
            from the pending operation
            */
            err = WaitForSingleObject( hReadEvent, 1000 );    
            
            if (err==WAIT_FAILED)
            {           
                Trace("Server error: Unexpected failure: "
                    "WaitForSingleObject failed \n");

                if (CloseHandle(hReadEvent)==0)
                {
                    Trace("Server error: CloseHandle Failed ");                    
                }

                if (closesocket( sock )==SOCKET_ERROR )
                {
                    Trace("Error closing socket\n");                
                }

                if (WSACleanup()==0 )
                {                
                    Trace("WSACleanup call failed with error code %u\n",
                        GetLastError() ); 
                }

                Fail("");
            }
            err = wsaRecvOverlapped.Internal;
        }


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

            if (CloseHandle(hReadEvent)==0)
            {
                Trace("Server error: CloseHandle Failed ");                    
            }
            
            if (closesocket( sock )==SOCKET_ERROR)
            {
                Trace("Error closing socket\n");                
            }

            if (WSACleanup()==0 )
            {                
                Trace("WSACleanup call failed with error code %u\n",
                    GetLastError() ); 
            }
    
            Fail("");
        }     
    }       

    /* close the socket */
    err = closesocket( sock );
    if( err != 0 )
    {
        /* check the socket-specific error code */    
        dwSocketError = GetLastError();

         if (CloseHandle(hReadEvent)==0)
        {
            Trace("Server error: CloseHandle Failed ");      
        }

        if (WSACleanup()==0 )
        {                
            Trace("WSACleanup call failed with error code %u\n",
                GetLastError() ); 
        }

        Fail(   "closesocket call failed with error code %d\n",
                dwSocketError ); 
    }

    if (CloseHandle(hReadEvent)==0)
    {
        Trace("Server error: CloseHandle Failed "); 

        if (WSACleanup()==0 )
        {                
            Trace("WSACleanup call failed with error code %u\n",
                GetLastError() ); 
        }
        Fail("");
    }

    /* cleanup the winsock library */
    err = WSACleanup();
    if( err != 0 )
    {
        /* check the socket-specific error code */    
        dwSocketError = GetLastError();
        Fail(   "WSACleanup call failed with error code %d\n",
                dwSocketError ); 
    }
        
    /* PAL termination */
    PAL_Terminate();
    return PASS; 
}
Пример #23
0
int __cdecl main(int argc, char *argv[]) 
{
  
    /* Define some buffers needed for the function */
    char* VariableBuffer = "PALTEST";
    char* ValueBuffer = "testing";
    int SetResult;

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }
    
    /* Check that it fails if the first param is NULL */
    
    SetResult = SetEnvironmentVariable(NULL,ValueBuffer);
 
    if(SetResult != 0) 
    {
        Fail("ERROR: SetEnvironmentVariable returned a success value, "
             "even though it was passed NULL as the first parameter and "
             "should have failed.\n");    
    }
  
    /* Check that it fails when both params are NULL */
    SetResult = SetEnvironmentVariable(NULL,NULL);
    if(SetResult != 0) 
    {
        Fail("ERROR: SetEnvironmentVariable returned a success value, even "
             "though it was passed NULL as the first and second parameter and "
             "should have failed.\n");
    }

    
    /* First, set the variable, which should be ok.  Then call the 
       function with the second parameter NULL twice -- the first call should
       pass, the second should fail.
    */
 
    SetResult = SetEnvironmentVariable(VariableBuffer,ValueBuffer);
    if(SetResult == 0) 
    {
        Fail("ERROR: SetEnvironmentVariable returned failure, when "
             "attempting to set a valid variable.\n");
    }
    
    SetResult = SetEnvironmentVariable(VariableBuffer,NULL);
    if(SetResult == 0) 
    {
        Fail("ERROR: SetEnvironmentVariable returned failure, when "
             "attempting to delete a variable.\n");
    }

    SetResult = SetEnvironmentVariable(VariableBuffer,NULL);
    if(SetResult != 0) 
    {
        Fail("ERROR: SetEnvironmentVariable returned success, when "
             "attempting to delete a variable which doesn't exist.\n");
    }
  
    PAL_Terminate();
    return PASS;
}
Пример #24
0
int __cdecl main(int argc, char *argv[])
{
    HANDLE TheFile, WaitFile;
    int result = 0;
    char DataBuffer[BUF_SIZE];
    DWORD BytesRead;
    
    if(0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }
    
    /* Open the same file that the parent has opened and locked */
    TheFile = CreateFile(FILENAME,     
                         GENERIC_READ|GENERIC_WRITE, 
                         FILE_SHARE_READ|FILE_SHARE_WRITE,
                         NULL,     
                         OPEN_EXISTING,                 
                         FILE_ATTRIBUTE_NORMAL, 
                         NULL);
    
    if (TheFile == INVALID_HANDLE_VALUE) 
    { 
        Trace("ERROR: Could not open file '%s' with CreateFile.",FILENAME); 
        result = 1;
    }
    
    /* Open up the WaitFile that we're using for IPC */
    WaitFile = CreateFile(WAITFILENAME,     
                          GENERIC_READ|GENERIC_WRITE, 
                          FILE_SHARE_READ|FILE_SHARE_WRITE,
                          NULL,                          
                          OPEN_ALWAYS,                 
                          FILE_ATTRIBUTE_NORMAL, 
                          NULL);
    
    if (WaitFile == INVALID_HANDLE_VALUE) 
    { 
        Trace("ERROR: Could not open file '%s' with CreateFile. "
             "GetLastError() returned %d.",WAITFILENAME,GetLastError()); 
        result = 1;
    }
    
    /* Lock the same file that the parent process locked, but the child
       locks bytes 11 through 20
    */

    if(LockFile(TheFile, 11, 0, 10, 0) == 0)
    {
        Trace("ERROR: LockFile failed in the child proccess.  "
              "GetLastError returns %d.",
              GetLastError());
        result = 1;
    }
    
    /* Check to ensure the parent lock is respected */
    if(ReadFile(TheFile, DataBuffer, 10, &BytesRead, NULL) != 0)
    {
        Trace("ERROR: ReadFile returned success when it should "
             "have failed.  Attempted to read the first 10 bytes "
             "of a file which was locked by the parent process.");
        result = 1;
    }

    /* Check to ensure the lock put on by this proccess doesn't restrict
       access
    */

    if(SetFilePointer(TheFile, 11, 0, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
    {
        Trace("ERROR: SetFilePointer was unable to move the file pointer to "
              "the 11th byte in the file, within the child proccess.  "
              "GetLastError() returned %d.",GetLastError());
        result = 1;
    }

    if(ReadFile(TheFile, DataBuffer, 10, &BytesRead, NULL) == 0)
    {
        Trace("ERROR: ReadFile failed when attempting to read a section of "
             "the file which was locked by the current process.  It should "
             "have been able to read this.  GetLastError() returned %d.",
             GetLastError());
        result = 1;
    }

    // Sleep for a bit to give the parent a chance to block before we do.
    Sleep(1000);

    /* Switch back to the parent, so it can check the child's locks */
    SignalAndBusyWait(WaitFile);

    if(UnlockFile(TheFile, 11, 0, 10, 0) == 0)
    {
        Fail("ERROR: Failed to Unlock bytes 11-20 in the file.  "
             "GetLastError returned %d.",GetLastError());
    }
    
    PAL_Terminate();
    return result;
}
Пример #25
0
int __cdecl main(int argc, char *argv[]) 
{
	
    OSVERSIONINFO TheVersionInfo;
    OSVERSIONINFO* pVersionInfo = &TheVersionInfo;
 
    /*
     * Initialize the PAL and return FAILURE if this fails
     */

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

    /* This needs to be done before using GetVersionEx */
    pVersionInfo->dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  
    /* If GetVersionEx fails, then the test fails */
    if(GetVersionEx(pVersionInfo) == 0) 
    {
        Fail("ERROR: The GetVersionEx function returned 0, which indicates " 
             "failure.");
    }
  
    /* These values are fixed, ensure they're set properly */
    if(pVersionInfo->dwMajorVersion != 5) 
    {
        Fail("ERROR: The fixed value of dwMajorVersion shoud be 5, but is "
             " really %d.",pVersionInfo->dwMajorVersion);
    }

    /* The minor version values for Win2k and XP are different 
       for Win2k minor version equals 0 and for XP minor version
       equals 1.  Both values are excepted here. */
    if((pVersionInfo->dwMinorVersion != 0) && 
       (pVersionInfo->dwMinorVersion != 1)) 
    {
        Fail("ERROR: The fixed value of dwMinorVersion shoud be 0 or 1, "
             "but is really %d.",pVersionInfo->dwMinorVersion);
    }

    if(pVersionInfo->dwBuildNumber_PAL_Undefined < 0) 
    {
        Fail("ERROR: The value of dwBuildNumber shoud be at least 0, but is "
             "really %d.",pVersionInfo->dwBuildNumber_PAL_Undefined);
    }

#if !WIN32


    /* Under BSD, the PlatformID should be UNIX and the Service Pack
       version should be set to "".
    */

    if(pVersionInfo->dwPlatformId != VER_PLATFORM_UNIX ||
       pVersionInfo->szCSDVersion_PAL_Undefined[0] != 0) 
    {
        Fail("ERROR: The dwPlatformId should be %d but is really %d.  And the "
             "szCSDVerion should be NULL.",VER_PLATFORM_UNIX,
             pVersionInfo->dwPlatformId);
    }
#endif
  
    
    PAL_Terminate();
    return PASS;
}
Пример #26
0
int __cdecl main(int argc, char **argv)
{
    DWORD TheResult;
    HANDLE TheFile;
    WCHAR FileName[MAX_PATH];
    
    if (0 != PAL_Initialize(argc,argv))
    {
        return FAIL;
    }
    
    /* Make a wide character string for the file name */
    
    MultiByteToWideChar(CP_ACP,
                        0,
                        "test_file",
                        -1,
                        FileName,
                        MAX_PATH);
    
    
    /* Try to set the file to Read-only */

    TheResult = SetFileAttributes(FileName,FILE_ATTRIBUTE_READONLY);
    
    if(TheResult == 0)
    {
        Fail("ERROR: SetFileAttributes returned 0, failure, when trying "
               "to set the FILE_ATTRIBUTE_READONLY attribute.");
    }

    /* Attempt to open this READONLY file with WRITE access,
       The open should fail and the HANDLE should be invalid.
    */

    TheFile = CreateFile(
        FileName,                         // file name
        GENERIC_READ|GENERIC_WRITE,       // access mode
        0,                                // share mode
        NULL,                             // SD
        OPEN_ALWAYS,                      // how to create
        FILE_ATTRIBUTE_NORMAL,            // file attributes
        NULL                              // handle to template file
        );

    if(TheFile != INVALID_HANDLE_VALUE) 
    {
        Fail("ERROR: Tried to open a file that was created as "
               "READONLY with the GENERIC_WRITE access mode.  This should"
               " cause CreateFile to return an INVALID_HANDLE_VALUE.");
    }

    /* Try to open the file with READ access, this should be ok.
       The HANDLE will be valid.
    */

    TheFile = CreateFile(
        FileName,                         // file name
        GENERIC_READ,                     // access mode
        0,                                // share mode
        NULL,                             // SD
        OPEN_ALWAYS,                      // how to create
        FILE_ATTRIBUTE_NORMAL,            // file attributes
        NULL                              // handle to template file
        );

    if(TheFile == INVALID_HANDLE_VALUE) 
    {
        Fail("ERROR: Tried to open a file that was created as "
               "READONLY with the GENERIC_READ access mode.  This should"
               " cause CreateFile to return an valid handle, but "
               "INVALID_HANDLE_VALUE was returned!.");
    }
    
    /* Close that HANDLE */

    TheResult = CloseHandle(TheFile);

    if(TheResult == 0) 
    {
        Fail("ERROR: CloseHandle failed.  This tests relies upon it "
               "working properly.");
    }

    /* Set the file to NORMAL */

    TheResult = SetFileAttributes(FileName,FILE_ATTRIBUTE_NORMAL);
     
    if(TheResult == 0)
    {
        Fail("ERROR: SetFileAttributes returned 0, failure, when trying "
               "to set the FILE_ATTRIBUTE_NORMAL attribute.");
    }

    /* To ensure that the set worked correctly, try to open the file
       with WRITE access again -- this time it should succeed.
    */

    TheFile = CreateFile(
        FileName,                         // file name
        GENERIC_READ|GENERIC_WRITE,       // access mode
        0,                                // share mode
        NULL,                             // SD
        OPEN_ALWAYS,                      // how to create
        FILE_ATTRIBUTE_NORMAL,            // file attributes
        NULL                              // handle to template file
        );
     
    if(TheFile == INVALID_HANDLE_VALUE) 
    {
        Fail("ERROR: Tried to open a file that was created as "
               "NORMAL with the GENERIC_WRITE access mode.  This should"
               " cause CreateFile to return an valid handle, but "
               "INVALID_HANDLE_VALUE was returned!.");
    }

    
    PAL_Terminate();
    return PASS;
}
Пример #27
0
int __cdecl main(int argc, char *argv[])
{

    const   int MAPPINGSIZE = 2048;
    HANDLE  hFileMapping;
    LPVOID  lpMapViewAddress;
    HANDLE  hReadPipe   = NULL;
    HANDLE  hWritePipe  = NULL;
    BOOL    bRetVal;

    SECURITY_ATTRIBUTES lpPipeAttributes;

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


    /* Attempt to create a MapViewOfFile with a NULL handle.
     */
    hFileMapping = NULL;
    
    lpMapViewAddress = MapViewOfFile(
                            hFileMapping,
                            FILE_MAP_WRITE, /* access code */
                            0,              /* high order offset */
                            0,              /* low order offset */
                            MAPPINGSIZE);   /* number of bytes for map */

    if((NULL != lpMapViewAddress) && 
       (GetLastError() != ERROR_INVALID_HANDLE))
    {
        Trace("ERROR:%u: Able to create a MapViewOfFile with "
              "hFileMapping=0x%lx.\n",
              GetLastError());
        UnmapViewOfFile(lpMapViewAddress);
        Fail("");
    }

    /* Attempt to create a MapViewOfFile with an invalid handle.
     */
    hFileMapping = INVALID_HANDLE_VALUE;
    
    lpMapViewAddress = MapViewOfFile(
                            hFileMapping,
                            FILE_MAP_WRITE, /* access code */
                            0,              /* high order offset */
                            0,              /* low order offset */
                            MAPPINGSIZE);   /* number of bytes for map */

    if((NULL != lpMapViewAddress) && 
       (GetLastError() != ERROR_INVALID_HANDLE))
    {
        Trace("ERROR:%u: Able to create a MapViewOfFile with "
              "hFileMapping=0x%lx.\n",
              GetLastError());
        UnmapViewOfFile(lpMapViewAddress);
        Fail("");
    }

    /* 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: %ld :Unable to create pipe\n", 
             GetLastError());
    }

    /* Attempt creating a MapViewOfFile with a Pipe Handle.
     */
    lpMapViewAddress = MapViewOfFile(
                            hReadPipe,
                            FILE_MAP_WRITE, /* access code */
                            0,              /* high order offset */
                            0,              /* low order offset */
                            MAPPINGSIZE);   /* number of bytes for map */

    if((NULL != lpMapViewAddress) && 
       (GetLastError() != ERROR_INVALID_HANDLE))
    {
        Trace("ERROR:%u: Able to create a MapViewOfFile with "
              "hFileMapping=0x%lx.\n",
              GetLastError());
        CloseHandle(hReadPipe);
        CloseHandle(hWritePipe);
        UnmapViewOfFile(lpMapViewAddress);
        Fail("");
    }

    /* Clean-up and Terminate the PAL.
    */
    CloseHandle(hReadPipe);
    CloseHandle(hWritePipe);
    PAL_Terminate();
    return PASS;
}
Пример #28
0
int __cdecl main (int argc, char **argv) 
{
    HANDLE hThread;
    DWORD dwThreadId;
    DWORD dwRet;

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return (bTestResult);
    }
    
    /*
     * Create critical section object and enter it
     */
    InitializeCriticalSection ( &CriticalSection );
    EnterCriticalSection(&CriticalSection);

    /*
     * Create a suspended thread 
     */
    hThread = CreateThread(NULL,
                           0,
                           &Thread,
                           (LPVOID) NULL,
                           CREATE_SUSPENDED,
                           &dwThreadId);

    if (hThread == NULL)
    {
        Trace("PALSUITE ERROR: CreateThread call failed.  GetLastError "
             "returned %d.\n", GetLastError());
        LeaveCriticalSection(&CriticalSection);
        DeleteCriticalSection(&CriticalSection);
        Fail("");
    }

    EnterCriticalSection(&CriticalSection);
    /* 
     * Set priority of the thread to greater than that of the currently
     * running thread so it is guaranteed to run.
     */
    dwRet = (DWORD) SetThreadPriority(hThread, THREAD_PRIORITY_ABOVE_NORMAL);

    if (0 == dwRet)
    {
        Trace("PALSUITE ERROR: SetThreadPriority (%p, %d) call failed.\n"
             "GetLastError returned %d.\n", hThread, 
             THREAD_PRIORITY_NORMAL, GetLastError());
    LeaveCriticalSection(&CriticalSection);
        CloseHandle(hThread);
        DeleteCriticalSection(&CriticalSection);
        Fail("");
    }

    dwRet = ResumeThread(hThread);
     
    if (-1 == dwRet)
    {
        Trace("PALSUITE ERROR: ResumeThread(%p) call failed.\nGetLastError "
             "returned %d.\n", hThread, GetLastError());
        LeaveCriticalSection(&CriticalSection);
        CloseHandle(hThread);
        DeleteCriticalSection(&CriticalSection);
        Fail("");
    }
    /* 
     * Sleep until we know the thread has been invoked.  This sleep in 
     * combination with the higher priority of the other thread should 
     * guarantee both threads block on the critical section.
     */
    while (t1_aflag == FAIL)
    {
        Sleep(1);
    }

    LeaveCriticalSection(&CriticalSection);

    switch ((WaitForSingleObject(
        hThread,
        10000)))      /* Wait 10 seconds */
    {
    case WAIT_OBJECT_0: 
        /* Object (thread) is signaled */
        LeaveCriticalSection(&CriticalSection);
        CloseHandle(hThread);
        DeleteCriticalSection(&CriticalSection);
        Fail("PALSUITE ERROR: WaitForSingleObject(%p,%d) should have "
             "returned\nWAIT_TIMEOUT ('%d'), instead it returned "
             "WAIT_OBJECT_0 ('%d').\nA nested LeaveCriticalSection(%p) "
             "call released both threads that were waiting on it!\n", 
             hThread, 10000, WAIT_TIMEOUT, WAIT_OBJECT_0, &CriticalSection);
        break;
    case WAIT_ABANDONED: 
        /*
         * Object was mutex object whose owning
         * thread has terminated.  Shouldn't occur.
         */
        Trace("PALSUITE ERROR: WaitForSingleObject(%p,%d) should have "
             "returned\nWAIT_TIMEOUT ('%d'), instead it returned "
             "WAIT_ABANDONED ('%d').\nGetLastError returned '%d'\n", 
             hThread, 10000, WAIT_TIMEOUT, WAIT_ABANDONED, GetLastError());
        LeaveCriticalSection(&CriticalSection);
        CloseHandle(hThread);
        DeleteCriticalSection(&CriticalSection);
        Fail("");
        break;
    case WAIT_FAILED:    /* WaitForSingleObject function failed */
        Trace("PALSUITE ERROR: WaitForSingleObject(%p,%d) should have "
             "returned\nWAIT_TIMEOUT ('%d'), instead it returned "
             "WAIT_FAILED ('%d').\nGetLastError returned '%d'\n", 
             hThread, 10000, WAIT_TIMEOUT, WAIT_FAILED, GetLastError());
        LeaveCriticalSection(&CriticalSection);
        CloseHandle(hThread);
        DeleteCriticalSection(&CriticalSection);
        Fail("");
        break;
    case WAIT_TIMEOUT: 
        /* 
         * We expect this thread to timeout waiting for the 
         * critical section object to become available.
         */
        t0_tflag = PASS;
        break;  
    }

    LeaveCriticalSection(&CriticalSection);

    if (WAIT_OBJECT_0 != WaitForSingleObject (hThread, 10000)) 
    {
        if (0 == CloseHandle(hThread))
        {
            Trace("PALSUITE ERROR: CloseHandle(%p) call failed.\n"
                 "WaitForSingleObject(%p,%d) should have returned "
                 "WAIT_OBJECT_0 ('%d').\nBoth calls failed.  "
                 "Deleted CRITICAL_SECTION object which likely means\n"
                 "thread %p is now in an undefined state.  GetLastError "
                 "returned '%d'.\n", hThread, hThread, 10000, WAIT_OBJECT_0, 
                 hThread, GetLastError());
            DeleteCriticalSection(&CriticalSection);
            Fail("");
        }
        else 
        {
            Trace("PALSUITE ERROR: WaitForSingleObject(%p,%d) should have "
                 "returned WAIT_OBJECT_0 ('%d').\n  GetLastError returned "
                 "'%d'.\n", hThread, hThread, 10000, WAIT_OBJECT_0, 
                 hThread, GetLastError());
            DeleteCriticalSection(&CriticalSection);
            Fail("");
        }
    }    

    if (0 == CloseHandle(hThread))
    {
        Trace("PALSUITE ERROR: CloseHandle(%p) call failed.\n"
             "Deleted CRITICAL_SECTION object which likely means\n"
             "thread %p is now in an undefined state.  GetLastError "
             "returned '%d'.\n", hThread, hThread, GetLastError());
        DeleteCriticalSection(&CriticalSection);
        Fail("");

    }
    DeleteCriticalSection(&CriticalSection);
    /* 
     * Ensure both thread 0 experienced a wait timeout and thread 1 
     * accessed the critical section or fail the test, otherwise pass it.
     */
    if ((t0_tflag == FAIL) || (t1_cflag == FAIL))
    {
        Trace("PALSUITE ERROR: Thread 0 returned %d when %d was expected.\n"
              "Thread 1 returned %d when %d was expected.\n", t0_tflag, 
              PASS, t1_cflag, PASS); 
        bTestResult=FAIL;
    }
    else 
    {
        bTestResult=PASS;
    }
    
    PAL_TerminateEx(bTestResult);
    return (bTestResult);
}
Пример #29
0
int __cdecl main(int argc, char *argv[])
{

    PROCESS_INFORMATION pi;
    STARTUPINFO si;
    DEBUG_EVENT DebugEv;
    DWORD dwContinueStatus = DBG_CONTINUE;
    int Count, ret;
    char* DataBuffer[4096];
    char* Memory;

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

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    memset(DataBuffer, 'z', 4096);

    /* Create a new process.  This is the process to be Debugged */
    if(!CreateProcess( NULL, "helper", NULL, NULL,
                       FALSE, 0, NULL, NULL, &si, &pi))
    {
        Fail("ERROR: CreateProcess failed to load executable 'helper'.  "
             "GetLastError() returned %d.\n",GetLastError());
    }

    /* Call DebugActiveProcess, because the process wasn't created as a
       debug process.
    */
    if(DebugActiveProcess(pi.dwProcessId) == 0)
    {
        Fail("ERROR: Failed calling DebugActiveProcess on the process "
             "which was created to debug.  GetLastError() returned %d.\n",
             GetLastError());
    }


    /* Call WaitForDebugEvent, which will wait until the helper process
       raises an exception.
    */

    while(1)
    {
        if(WaitForDebugEvent(&DebugEv, INFINITE) == 0)
        {
            Fail("ERROR: WaitForDebugEvent returned 0, indicating failure.  "
                 "GetLastError() returned %d.\n",GetLastError());
        }

        /* We're waiting for the helper process to send this exception.
           When it does, we call WriteProcess.  If it gets called more than
           once, it is ignored.
        */

        if(DebugEv.u.Exception.ExceptionRecord.ExceptionCode == MY_EXCEPTION)
        {

            Memory = (LPVOID)
                     DebugEv.u.Exception.ExceptionRecord.ExceptionInformation[0];

            /* Write to this memory which we have no access to. */

            ret = WriteProcessMemory(pi.hProcess,
                                     Memory,
                                     DataBuffer,
                                     4096,
                                     &Count);

            if(ret != 0)
            {
                Fail("ERROR: WriteProcessMemory should have failed, as "
                     "it attempted to write to a range of memory which was "
                     "not accessible.\n");
            }

            if(GetLastError() != ERROR_NOACCESS)
            {
                Fail("ERROR: GetLastError() should have returned "
                     "ERROR_NOACCESS , but intead it returned "
                     "%d.\n",GetLastError());
            }
        }

        if(DebugEv.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
        {
            break;
        }

        if(ContinueDebugEvent(DebugEv.dwProcessId,
                              DebugEv.dwThreadId, dwContinueStatus) == 0)
        {
            Fail("ERROR: ContinueDebugEvent failed to continue the thread "
                 "which had a debug event.  GetLastError() returned %d.\n",
                 GetLastError());
        }
    }


    PAL_Terminate();
    return PASS;
}
Пример #30
0
int __cdecl main(int argc, char **argv)
{

    int i;
    char *variableValue;
   
    if (0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }
    
    for (i = 0; i < (sizeof(TestCases)/sizeof(struct TestElement)) ; i++) 
    {
        if((_putenv(TestCases[i]._putenvString) == -1) && 
           ( TestCases[i].bValidString == TRUE))
        {
            Fail("ERROR: _putenv failed to set an environment "
                 "variable with a valid format.\n  Call was"
                 "_putenv(%s)\n", TestCases[i]._putenvString);
        }
        /* 
         * For valid _putenvString values, check to see the variable was set
         */
        if (TestCases[i].bValidString == TRUE)
        {       
            variableValue = getenv(TestCases[i].varName);
        
            if (variableValue == NULL)
            { 
                if (*TestCases[i].varValue != '\0')
                {
                    Fail("ERROR: getenv(%s) call returned NULL.\nThe call "
                         "should have returned \"%s\"\n", TestCases[i].varName
                         , TestCases[i].varValue);
                }
            }  
            else if ( strcmp(variableValue, TestCases[i].varValue) != 0) 
            {
                Fail("ERROR: _putenv(%s)\nshould have set the variable "
                     "%s\n to \"%s\".\nA subsequent call to getenv(%s)\n"
                     "returned \"%s\" instead.\n", TestCases[i]._putenvString
                     , TestCases[i].varName, TestCases[i].varValue
                     , TestCases[i].varName, variableValue);
            }
        }
        else 
            /*
             * Check to see that putenv fails for malformed _putenvString values
             */
        {
            variableValue = getenv(TestCases[i].varName);
        
            if (variableValue != NULL)
            { 
                Fail("ERROR: getenv(%s) call should have returned NULL.\n"
                     "Instead it returned \"%s\".\n", TestCases[i].varName
                     , TestCases[i].varValue);
            }
        }
    }

    PAL_Terminate();
    return PASS;
}