summaryrefslogtreecommitdiff
path: root/src/pal/tests/palsuite/composite/object_management/mutex/shared/mutex.cpp
blob: ec5d9b37ac6fdd8f71f6bacd4a8ea9b137f896d1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/*============================================================
** 
** This test is for Object Management Test case for Mutex where Object type is shareable.
** 
** Source Code: main.c and mutex.c
**     main.c creates a mutex, creates processes and waits for all processes to get over
**     mutex.c create threads which will contend for the mutex
** 
** This test is for Object Management Test case for Mutex where Object type is not shareable.
** Algorithm
** o	Main Process Creates OBJECT_TYPE Object
** o	Create PROCESS_COUNT processes aware of the Shared Object 
** 
** Author: ShamitP
**
**
**============================================================
*/

#include <palsuite.h>
#include "resultbuffer.h"
#include "resulttime.h"

#define TIMEOUT 5000
/* Test Input Variables */
unsigned int USE_PROCESS_COUNT = 0;
unsigned int THREAD_COUNT = 0;
unsigned int REPEAT_COUNT = 0; 
unsigned int RELATION_ID = 0;


/* Capture statistics at per thread basis */
struct statistics{
    unsigned int processId;
    unsigned int operationsFailed;
    unsigned int operationsPassed;
    unsigned int operationsTotal; 
    DWORD        operationTime;
    unsigned int relationId;
};

struct ProcessStats{
    unsigned int processId;
    DWORD        operationTime;
    unsigned int relationId;
};

HANDLE StartTestsEvHandle = NULL;
HANDLE hMutexHandle = NULL;

/* Results Buffer */
ResultBuffer *resultBuffer = NULL;

int testStatus;

const char sTmpEventName[MAX_PATH] = "StartTestEvent";
char objectSuffix[MAX_PATH];

void PALAPI Run_Thread(LPVOID lpParam);

int GetParameters( int argc, char **argv)
{
    if( (!((argc == 5) || (argc == 6) ) )|| ((argc == 1) && !strcmp(argv[1],"/?")) 
       || !strcmp(argv[1],"/h") || !strcmp(argv[1],"/H"))
    {
        printf("PAL -Composite Object Management event Test\n");
        printf("Usage:\n");
        printf("main\n\t[USE_PROCESS_COUNT (greater than 1)] \n"); 
        printf("\t[THREAD_COUNT (greater than 1)] \n"); 
        printf("\t[REPEAT_COUNT (greater than 1)]\n");
		printf("\t[RELATION_ID  [greater than 1]\n"); 
        printf("\t[Object Name Suffix]\n");

        return -1;
    }

 //   Trace("Args 1 is [%s], Arg 2 is [%s], Arg 3 is [%s]\n", argv[1], argv[2], argv[3]);
    
    USE_PROCESS_COUNT = atoi(argv[1]);
    if( USE_PROCESS_COUNT < 0) 
    {
        printf("\nInvalid USE_PROCESS_COUNT number, Pass greater than 1\n");
        return -1;
    }

    THREAD_COUNT = atoi(argv[2]);
    if( (THREAD_COUNT < 1) || (THREAD_COUNT > MAXIMUM_WAIT_OBJECTS) )
    {
        printf("\nInvalid THREAD_COUNT number, Pass greater than 1 and less than %d\n", MAXIMUM_WAIT_OBJECTS);
        return -1;
    }

    REPEAT_COUNT = atoi(argv[3]);
    if( REPEAT_COUNT < 1) 
    {
        printf("\nInvalid REPEAT_COUNT number, Pass greater than 1\n");
        return -1;
    }

	RELATION_ID = atoi(argv[4]);
    if( RELATION_ID < 1) 
    {
        printf("\nMain Process:Invalid RELATION_ID number, Pass greater than 1\n");
        return -1;
	}

    if(argc == 6)
    {
        strncpy(objectSuffix, argv[5], MAX_PATH-1);
    }

    return 0;
}

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

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

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

    testStatus = PASS;

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

    ZeroMemory( objectSuffix, MAX_PATH );

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

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

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

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

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

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

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

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

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

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

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

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

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

    PAL_Terminate();
    return  testStatus;
}

void  PALAPI Run_Thread (LPVOID lpParam)
{
    unsigned int i = 0;
    DWORD dwWaitResult; 

    struct statistics stats;
    DWORD dwStartTime;

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

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

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

    dwStartTime = GetTickCount();

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

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