summaryrefslogtreecommitdiff
path: root/general/cancel/exe/testapp.c
blob: f6c27fe9304250d2fc053a47d59fb9888f8c0faa (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
/*++

Copyright (c) Microsoft Corporation.  All rights reserved.

    THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
    KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
    PURPOSE.

Module Name:

    testapp.c

Abstract:

Environment:

    User mode Win32 console application

--*/

//
// Annotation to indicate to prefast that this is nondriver user-mode code.
//
                                                  
#include <DriverSpecs.h>
_Analysis_mode_(_Analysis_code_type_user_code_)  

#include <windows.h>
#include <winioctl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <strsafe.h>

#include "testapp.h"

//
// Globals
//

HANDLE hDevice;
BOOLEAN ExitFlag = FALSE;
HANDLE hThreads[MAXTHREADS];

//
// function prototypes
//

VOID CALLBACK CompletionRoutine(
    DWORD errorcode,
    DWORD bytesTransfered,
    LPOVERLAPPED ov
    );

DWORD
WINAPI Reader(
    PVOID
    );

BOOLEAN
SetupDriverName(
    _Inout_updates_all_(BufferLength) PCHAR DriverLocation,
    _In_ ULONG BufferLength
    );

//
// Main function
//

VOID __cdecl
main(
    _In_ ULONG argc,
    _In_reads_(argc) PCHAR argv[]
    )
{
    ULONG i, Id;
    ULONG   NumberOfThreads = 1;
    DWORD errNum = 0;
    TCHAR driverLocation[MAX_PATH] = {'\0'};


    if (argc >= 2  && (argv[1][0] == '-' || isalpha((unsigned char)argv[1][0])))
    {
        puts("Usage:testapp <NumberOfThreads>\n");
        return;
    }
    else if (argc >= 2 && ((NumberOfThreads = atoi(argv[1])) > MAXTHREADS))
    {
        printf("Invalid option:Only a maximun of %d threads allowed.\n",
                    MAXTHREADS);
        return;

    }

    //
    // Try to connect to driver.  If this fails, try to load the driver
    // dynamically.
    //

    if ((hDevice = CreateFile("\\\\.\\CancelSamp",
                                 GENERIC_READ,
                                 0,
                                 NULL,
                                 OPEN_EXISTING,
                                 FILE_FLAG_OVERLAPPED,
                                 NULL
                                 )) == INVALID_HANDLE_VALUE) {

        errNum = GetLastError();

        if (errNum != ERROR_FILE_NOT_FOUND) {

            printf("CreateFile failed!  Error = %d\n", errNum);

            return ;
        }

        //
        // Setup full path to driver name.
        //

        if (!SetupDriverName(driverLocation, sizeof(driverLocation))) {

            return ;
        }


        //
        // Install driver.
        //

        if (!ManageDriver(DRIVER_NAME,
                          driverLocation,
                          DRIVER_FUNC_INSTALL
                          )) {

            printf("Unable to install driver. \n");

            //
            // Error - remove driver.
            //

            ManageDriver(DRIVER_NAME,
                         driverLocation,
                         DRIVER_FUNC_REMOVE
                         );

            return;
        }
        //
        // Try to open the newly installed driver.
        //

        hDevice = CreateFile( "\\\\.\\CancelSamp",
                GENERIC_READ,
                0,
                NULL,
                OPEN_EXISTING,
                FILE_FLAG_OVERLAPPED,
                NULL);

        if ( hDevice == INVALID_HANDLE_VALUE ){
            printf ( "Error: CreatFile Failed : %d\n", GetLastError());
            return;
        }
    }

    printf("Number of threads : %d\n", NumberOfThreads);


    printf("Enter 'q' to exit gracefully:");

    for(i=0; i < NumberOfThreads; i++)
    {
        hThreads[i] = CreateThread( NULL,      // security attributes
                                    0,         // initial stack size
                                    Reader,    // Main() function
                                    NULL,      // arg to Reader thread
                                    0,         // creation flags
                                    (LPDWORD)&Id); // returned thread id

        if ( NULL == hThreads[i] ) {
            printf( " Error CreateThread[%d] Failed: %d\n", i, GetLastError());
            ExitProcess ( 1 );
        }

    }


    if (getchar() == 'q')
    {
        ExitFlag = TRUE;

        WaitForMultipleObjects( NumberOfThreads, hThreads, TRUE, INFINITE);

        for(i=0; i < NumberOfThreads; i++)
            CloseHandle(hThreads[i]);

    }

    CloseHandle(hDevice);

    //
    // Unload the driver.  Ignore any errors.
    //

    ManageDriver(DRIVER_NAME,
                 driverLocation,
                 DRIVER_FUNC_REMOVE
                 );

    ExitProcess(1);

}


DWORD WINAPI Reader(PVOID dummy )
{
    ULONG data;
    OVERLAPPED ov;

    UNREFERENCED_PARAMETER(dummy);

    while(!ExitFlag)
    {
        ZeroMemory( &ov, sizeof(ov) );
        ov.Offset = 0;
        ov.OffsetHigh = 0;

        if (!ReadFileEx(hDevice, (PVOID)&data, sizeof(ULONG),  &ov, CompletionRoutine))
        {
            printf ( "Error: Read Failed: %d\n", GetLastError());
            ExitProcess ( 1 );
        }
        SleepEx(INFINITE, TRUE);
    }

    printf("Exiting thread %d \n", GetCurrentThreadId());
    ExitThread(0);
}


VOID CALLBACK CompletionRoutine(
    DWORD errorcode,
    DWORD bytesTransfered,
    LPOVERLAPPED ov
    )
{

    UNREFERENCED_PARAMETER(errorcode);
    UNREFERENCED_PARAMETER(ov);

    fprintf(stdout, "Thread %d read: %d bytes\n",
           GetCurrentThreadId(), bytesTransfered);
    return;
}


BOOLEAN
SetupDriverName(
    _Inout_updates_all_(BufferLength) PCHAR DriverLocation,
    _In_ ULONG BufferLength
    )
{
    HANDLE fileHandle;
    DWORD driverLocLen = 0;

    //
    // Get the current directory.
    //

    driverLocLen = GetCurrentDirectory(BufferLength,
                                       DriverLocation
                                       );

    if (driverLocLen == 0) {

        printf("GetCurrentDirectory failed!  Error = %d \n", GetLastError());

        return FALSE;
    }

    //
    // Setup path name to driver file.
    //
    if (FAILED( StringCbCat(DriverLocation, BufferLength, "\\"DRIVER_NAME".sys") )) {
        return FALSE;
    }

    //
    // Insure driver file is in the specified directory.
    //

    if ((fileHandle = CreateFile(DriverLocation,
                                 GENERIC_READ,
                                 0,
                                 NULL,
                                 OPEN_EXISTING,
                                 FILE_ATTRIBUTE_NORMAL,
                                 NULL
                                 )) == INVALID_HANDLE_VALUE) {


        printf("%s.sys is not loaded.\n", DRIVER_NAME);

        //
        // Indicate failure.
        //

        return FALSE;
    }

    //
    // Close open file handle.
    //

    if (fileHandle) {

        CloseHandle(fileHandle);
    }

    //
    // Indicate success.
    //

    return TRUE;


}   // SetupDriverName