ole32: Fix memory leaks in the storage test.
[wine] / dlls / kernel32 / tests / file.c
1 /*
2  * Unit tests for file functions in Wine
3  *
4  * Copyright (c) 2002, 2004 Jakob Eriksson
5  * Copyright (c) 2008 Jeff Zaroyko
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  *
21  */
22
23 /* ReplaceFile requires Windows 2000 or newer */
24 #define _WIN32_WINNT 0x0500
25
26 #include <stdarg.h>
27 #include <stdlib.h>
28 #include <time.h>
29 #include <stdio.h>
30
31 #include "wine/test.h"
32 #include "windef.h"
33 #include "winbase.h"
34 #include "winerror.h"
35
36 static HANDLE (WINAPI *pFindFirstFileExA)(LPCSTR,FINDEX_INFO_LEVELS,LPVOID,FINDEX_SEARCH_OPS,LPVOID,DWORD);
37 static BOOL (WINAPI *pReplaceFileA)(LPCSTR, LPCSTR, LPCSTR, DWORD, LPVOID, LPVOID);
38 static BOOL (WINAPI *pReplaceFileW)(LPCWSTR, LPCWSTR, LPCWSTR, DWORD, LPVOID, LPVOID);
39 static UINT (WINAPI *pGetSystemWindowsDirectoryA)(LPSTR, UINT);
40 static BOOL (WINAPI *pGetVolumeNameForVolumeMountPointA)(LPCSTR, LPSTR, DWORD);
41
42 /* keep filename and filenameW the same */
43 static const char filename[] = "testfile.xxx";
44 static const WCHAR filenameW[] = { 't','e','s','t','f','i','l','e','.','x','x','x',0 };
45 static const char sillytext[] =
46 "en larvig liten text dx \033 gx hej 84 hej 4484 ! \001\033 bla bl\na.. bla bla."
47 "1234 43 4kljf lf &%%%&&&&&& 34 4 34   3############# 33 3 3 3 # 3## 3"
48 "1234 43 4kljf lf &%%%&&&&&& 34 4 34   3############# 33 3 3 3 # 3## 3"
49 "1234 43 4kljf lf &%%%&&&&&& 34 4 34   3############# 33 3 3 3 # 3## 3"
50 "1234 43 4kljf lf &%%%&&&&&& 34 4 34   3############# 33 3 3 3 # 3## 3"
51 "1234 43 4kljf lf &%%%&&&&&& 34 4 34   3############# 33 3 3 3 # 3## 3"
52 "1234 43 4kljf lf &%%%&&&&&& 34 4 34   3############# 33 3 3 3 # 3## 3"
53 "1234 43 4kljf lf &%%%&&&&&& 34 4 34   3############# 33 3 3 3 # 3## 3"
54 "1234 43 4kljf lf &%%%&&&&&& 34 4 34   3############# 33 3 3 3 # 3## 3"
55 "sdlkfjasdlkfj a dslkj adsklf  \n  \nasdklf askldfa sdlkf \nsadklf asdklf asdf ";
56
57 struct test_list {
58     const char *file;           /* file string to test */
59     const DWORD err;            /* Win NT and further error code */
60     const LONG err2;            /* Win 9x & ME error code  or -1 */
61     const DWORD options;        /* option flag to use for open */
62     const BOOL todo_flag;       /* todo_wine indicator */
63 } ;
64
65 static void InitFunctionPointers(void)
66 {
67     HMODULE hkernel32 = GetModuleHandleA("kernel32");
68
69     pFindFirstFileExA=(void*)GetProcAddress(hkernel32, "FindFirstFileExA");
70     pReplaceFileA=(void*)GetProcAddress(hkernel32, "ReplaceFileA");
71     pReplaceFileW=(void*)GetProcAddress(hkernel32, "ReplaceFileW");
72     pGetSystemWindowsDirectoryA=(void*)GetProcAddress(hkernel32, "GetSystemWindowsDirectoryA");
73     pGetVolumeNameForVolumeMountPointA = (void *) GetProcAddress(hkernel32, "GetVolumeNameForVolumeMountPointA");
74 }
75
76 static void test__hread( void )
77 {
78     HFILE filehandle;
79     char buffer[10000];
80     LONG bytes_read;
81     LONG bytes_wanted;
82     LONG i;
83     BOOL ret;
84
85     SetFileAttributesA(filename,FILE_ATTRIBUTE_NORMAL); /* be sure to remove stale files */
86     DeleteFileA( filename );
87     filehandle = _lcreat( filename, 0 );
88     if (filehandle == HFILE_ERROR)
89     {
90         ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
91         return;
92     }
93
94     ok( HFILE_ERROR != _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite complains\n" );
95
96     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
97
98     filehandle = _lopen( filename, OF_READ );
99
100     ok( HFILE_ERROR != filehandle, "couldn't open file \"%s\" again (err=%d)\n", filename, GetLastError(  ) );
101
102     bytes_read = _hread( filehandle, buffer, 2 * strlen( sillytext ) );
103
104     ok( lstrlenA( sillytext ) == bytes_read, "file read size error\n" );
105
106     for (bytes_wanted = 0; bytes_wanted < lstrlenA( sillytext ); bytes_wanted++)
107     {
108         ok( 0 == _llseek( filehandle, 0, FILE_BEGIN ), "_llseek complains\n" );
109         ok( _hread( filehandle, buffer, bytes_wanted ) == bytes_wanted, "erratic _hread return value\n" );
110         for (i = 0; i < bytes_wanted; i++)
111         {
112             ok( buffer[i] == sillytext[i], "that's not what's written\n" );
113         }
114     }
115
116     ok( HFILE_ERROR != _lclose( filehandle ), "_lclose complains\n" );
117
118     ret = DeleteFileA( filename );
119     ok( ret != 0, "DeleteFile failed (%d)\n", GetLastError(  ) );
120 }
121
122
123 static void test__hwrite( void )
124 {
125     HFILE filehandle;
126     char buffer[10000];
127     LONG bytes_read;
128     LONG bytes_written;
129     ULONG blocks;
130     LONG i;
131     char *contents;
132     HLOCAL memory_object;
133     char checksum[1];
134     BOOL ret;
135
136     filehandle = _lcreat( filename, 0 );
137     if (filehandle == HFILE_ERROR)
138     {
139         ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
140         return;
141     }
142
143     ok( HFILE_ERROR != _hwrite( filehandle, "", 0 ), "_hwrite complains\n" );
144
145     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
146
147     filehandle = _lopen( filename, OF_READ );
148
149     bytes_read = _hread( filehandle, buffer, 1);
150
151     ok( 0 == bytes_read, "file read size error\n" );
152
153     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
154
155     filehandle = _lopen( filename, OF_READWRITE );
156
157     bytes_written = 0;
158     checksum[0] = '\0';
159     srand( (unsigned)time( NULL ) );
160     for (blocks = 0; blocks < 100; blocks++)
161     {
162         for (i = 0; i < (LONG)sizeof( buffer ); i++)
163         {
164             buffer[i] = rand(  );
165             checksum[0] = checksum[0] + buffer[i];
166         }
167         ok( HFILE_ERROR != _hwrite( filehandle, buffer, sizeof( buffer ) ), "_hwrite complains\n" );
168         bytes_written = bytes_written + sizeof( buffer );
169     }
170
171     ok( HFILE_ERROR != _hwrite( filehandle, checksum, 1 ), "_hwrite complains\n" );
172     bytes_written++;
173
174     ok( HFILE_ERROR != _lclose( filehandle ), "_lclose complains\n" );
175
176     memory_object = LocalAlloc( LPTR, bytes_written );
177
178     ok( 0 != memory_object, "LocalAlloc fails. (Could be out of memory.)\n" );
179
180     contents = LocalLock( memory_object );
181
182     filehandle = _lopen( filename, OF_READ );
183
184     contents = LocalLock( memory_object );
185
186     ok( NULL != contents, "LocalLock whines\n" );
187
188     ok( bytes_written == _hread( filehandle, contents, bytes_written), "read length differ from write length\n" );
189
190     checksum[0] = '\0';
191     i = 0;
192     do
193     {
194         checksum[0] = checksum[0] + contents[i];
195         i++;
196     }
197     while (i < bytes_written - 1);
198
199     ok( checksum[0] == contents[i], "stored checksum differ from computed checksum\n" );
200
201     ok( HFILE_ERROR != _lclose( filehandle ), "_lclose complains\n" );
202
203     ret = DeleteFileA( filename );
204     ok( ret != 0, "DeleteFile failed (%d)\n", GetLastError(  ) );
205 }
206
207
208 static void test__lclose( void )
209 {
210     HFILE filehandle;
211     BOOL ret;
212
213     filehandle = _lcreat( filename, 0 );
214     if (filehandle == HFILE_ERROR)
215     {
216         ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
217         return;
218     }
219
220     ok( HFILE_ERROR != _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite complains\n" );
221
222     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
223
224     ret = DeleteFileA( filename );
225     ok( ret != 0, "DeleteFile failed (%d)\n", GetLastError(  ) );
226 }
227
228
229 static void test__lcreat( void )
230 {
231     HFILE filehandle;
232     char buffer[10000];
233     WIN32_FIND_DATAA search_results;
234     char slashname[] = "testfi/";
235     int err;
236     HANDLE find;
237     BOOL ret;
238
239     filehandle = _lcreat( filename, 0 );
240     if (filehandle == HFILE_ERROR)
241     {
242         ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
243         return;
244     }
245
246     ok( HFILE_ERROR != _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite complains\n" );
247
248     ok( 0 == _llseek( filehandle, 0, FILE_BEGIN ), "_llseek complains\n" );
249
250     ok( _hread( filehandle, buffer, strlen( sillytext ) ) ==  lstrlenA( sillytext ), "erratic _hread return value\n" );
251
252     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
253
254     ok( INVALID_HANDLE_VALUE != FindFirstFileA( filename, &search_results ), "should be able to find file\n" );
255
256     ret = DeleteFileA(filename);
257     ok( ret != 0, "DeleteFile failed (%d)\n", GetLastError());
258
259     filehandle = _lcreat( filename, 1 ); /* readonly */
260     ok( HFILE_ERROR != filehandle, "couldn't create file \"%s\" (err=%d)\n", filename, GetLastError(  ) );
261
262     ok( HFILE_ERROR != _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite shouldn't be able to write never the less\n" );
263
264     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
265
266     ok( INVALID_HANDLE_VALUE != FindFirstFileA( filename, &search_results ), "should be able to find file\n" );
267
268     ok( 0 == DeleteFileA( filename ), "shouldn't be able to delete a readonly file\n" );
269
270     ok( SetFileAttributesA(filename, FILE_ATTRIBUTE_NORMAL ) != 0, "couldn't change attributes on file\n" );
271
272     ok( DeleteFileA( filename ) != 0, "now it should be possible to delete the file!\n" );
273
274     filehandle = _lcreat( filename, 2 );
275     ok( HFILE_ERROR != filehandle, "couldn't create file \"%s\" (err=%d)\n", filename, GetLastError(  ) );
276
277     ok( HFILE_ERROR != _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite complains\n" );
278
279     ok( 0 == _llseek( filehandle, 0, FILE_BEGIN ), "_llseek complains\n" );
280
281     ok( _hread( filehandle, buffer, strlen( sillytext ) ) ==  lstrlenA( sillytext ), "erratic _hread return value\n" );
282
283     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
284
285     ok( INVALID_HANDLE_VALUE != FindFirstFileA( filename, &search_results ), "should STILL be able to find file\n" );
286
287     ret = DeleteFileA( filename );
288     ok( ret, "DeleteFile failed (%d)\n", GetLastError(  ) );
289
290     filehandle = _lcreat( filename, 4 ); /* SYSTEM file */
291     ok( HFILE_ERROR != filehandle, "couldn't create file \"%s\" (err=%d)\n", filename, GetLastError(  ) );
292
293     ok( HFILE_ERROR != _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite complains\n" );
294
295     ok( 0 == _llseek( filehandle, 0, FILE_BEGIN ), "_llseek complains\n" );
296
297     ok( _hread( filehandle, buffer, strlen( sillytext ) ) ==  lstrlenA( sillytext ), "erratic _hread return value\n" );
298
299     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
300
301     ok( INVALID_HANDLE_VALUE != FindFirstFileA( filename, &search_results ), "should STILL be able to find file\n" );
302
303     ret = DeleteFileA( filename );
304     ok( ret, "DeleteFile failed (%d)\n", GetLastError(  ) );
305
306     filehandle=_lcreat (slashname, 0); /* illegal name */
307     if (HFILE_ERROR==filehandle) {
308       err=GetLastError ();
309       ok (err==ERROR_INVALID_NAME || err==ERROR_PATH_NOT_FOUND,
310           "creating file \"%s\" failed with error %d\n", slashname, err);
311     } else { /* only NT succeeds */
312       _lclose(filehandle);
313       find=FindFirstFileA (slashname, &search_results);
314       if (INVALID_HANDLE_VALUE!=find)
315       {
316         ret = FindClose (find);
317         ok (0 != ret, "FindClose complains (%d)\n", GetLastError ());
318         slashname[strlen(slashname)-1]=0;
319         ok (!strcmp (slashname, search_results.cFileName),
320             "found unexpected name \"%s\"\n", search_results.cFileName);
321         ok (FILE_ATTRIBUTE_ARCHIVE==search_results.dwFileAttributes,
322             "attributes of file \"%s\" are 0x%04x\n", search_results.cFileName,
323             search_results.dwFileAttributes);
324       }
325     ret = DeleteFileA( slashname );
326     ok( ret, "DeleteFile failed (%d)\n", GetLastError(  ) );
327     }
328
329     filehandle=_lcreat (filename, 8); /* illegal attribute */
330     if (HFILE_ERROR==filehandle)
331       ok (0, "couldn't create volume label \"%s\"\n", filename);
332     else {
333       _lclose(filehandle);
334       find=FindFirstFileA (filename, &search_results);
335       if (INVALID_HANDLE_VALUE==find)
336         ok (0, "file \"%s\" not found\n", filename);
337       else {
338         ret = FindClose(find);
339         ok ( 0 != ret, "FindClose complains (%d)\n", GetLastError ());
340         ok (!strcmp (filename, search_results.cFileName),
341             "found unexpected name \"%s\"\n", search_results.cFileName);
342         search_results.dwFileAttributes &= ~FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
343         ok (FILE_ATTRIBUTE_ARCHIVE==search_results.dwFileAttributes,
344             "attributes of file \"%s\" are 0x%04x\n", search_results.cFileName,
345             search_results.dwFileAttributes);
346       }
347     ret = DeleteFileA( filename );
348     ok( ret, "DeleteFile failed (%d)\n", GetLastError(  ) );
349     }
350 }
351
352
353 static void test__llseek( void )
354 {
355     INT i;
356     HFILE filehandle;
357     char buffer[1];
358     LONG bytes_read;
359     BOOL ret;
360
361     filehandle = _lcreat( filename, 0 );
362     if (filehandle == HFILE_ERROR)
363     {
364         ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
365         return;
366     }
367
368     for (i = 0; i < 400; i++)
369     {
370         ok( _hwrite( filehandle, sillytext, strlen( sillytext ) ) != -1, "_hwrite complains\n" );
371     }
372     ok( _llseek( filehandle, 400 * strlen( sillytext ), FILE_CURRENT ) != -1, "should be able to seek\n" );
373     ok( _llseek( filehandle, 27 + 35 * strlen( sillytext ), FILE_BEGIN ) != -1, "should be able to seek\n" );
374
375     bytes_read = _hread( filehandle, buffer, 1);
376     ok( 1 == bytes_read, "file read size error\n" );
377     ok( buffer[0] == sillytext[27], "_llseek error, it got lost seeking\n" );
378     ok( _llseek( filehandle, -400 * (LONG)strlen( sillytext ), FILE_END ) != -1, "should be able to seek\n" );
379
380     bytes_read = _hread( filehandle, buffer, 1);
381     ok( 1 == bytes_read, "file read size error\n" );
382     ok( buffer[0] == sillytext[0], "_llseek error, it got lost seeking\n" );
383     ok( _llseek( filehandle, 1000000, FILE_END ) != -1, "should be able to seek past file; poor, poor Windows programmers\n" );
384     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
385
386     ret = DeleteFileA( filename );
387     ok( ret, "DeleteFile failed (%d)\n", GetLastError(  ) );
388 }
389
390
391 static void test__llopen( void )
392 {
393     HFILE filehandle;
394     UINT bytes_read;
395     char buffer[10000];
396     BOOL ret;
397
398     filehandle = _lcreat( filename, 0 );
399     if (filehandle == HFILE_ERROR)
400     {
401         ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
402         return;
403     }
404
405     ok( HFILE_ERROR != _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite complains\n" );
406     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
407
408     filehandle = _lopen( filename, OF_READ );
409     ok( HFILE_ERROR == _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite shouldn't be able to write!\n" );
410     bytes_read = _hread( filehandle, buffer, strlen( sillytext ) );
411     ok( strlen( sillytext )  == bytes_read, "file read size error\n" );
412     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
413
414     filehandle = _lopen( filename, OF_READWRITE );
415     bytes_read = _hread( filehandle, buffer, 2 * strlen( sillytext ) );
416     ok( strlen( sillytext )  == bytes_read, "file read size error\n" );
417     ok( HFILE_ERROR != _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite should write just fine\n" );
418     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
419
420     filehandle = _lopen( filename, OF_WRITE );
421     ok( HFILE_ERROR == _hread( filehandle, buffer, 1 ), "you should only be able to write this file\n" );
422     ok( HFILE_ERROR != _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite should write just fine\n" );
423     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
424
425     ret = DeleteFileA( filename );
426     ok( ret, "DeleteFile failed (%d)\n", GetLastError(  ) );
427     /* TODO - add tests for the SHARE modes  -  use two processes to pull this one off */
428 }
429
430
431 static void test__lread( void )
432 {
433     HFILE filehandle;
434     char buffer[10000];
435     UINT bytes_read;
436     UINT bytes_wanted;
437     UINT i;
438     BOOL ret;
439
440     filehandle = _lcreat( filename, 0 );
441     if (filehandle == HFILE_ERROR)
442     {
443         ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
444         return;
445     }
446
447     ok( HFILE_ERROR != _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite complains\n" );
448
449     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
450
451     filehandle = _lopen( filename, OF_READ );
452
453     ok( HFILE_ERROR != filehandle, "couldn't open file \"%s\" again (err=%d)\n", filename, GetLastError());
454
455     bytes_read = _lread( filehandle, buffer, 2 * strlen( sillytext ) );
456
457     ok( lstrlenA( sillytext ) == bytes_read, "file read size error\n" );
458
459     for (bytes_wanted = 0; bytes_wanted < strlen( sillytext ); bytes_wanted++)
460     {
461         ok( 0 == _llseek( filehandle, 0, FILE_BEGIN ), "_llseek complains\n" );
462         ok( _lread( filehandle, buffer, bytes_wanted ) == bytes_wanted, "erratic _hread return value\n" );
463         for (i = 0; i < bytes_wanted; i++)
464         {
465             ok( buffer[i] == sillytext[i], "that's not what's written\n" );
466         }
467     }
468
469     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
470
471     ret = DeleteFileA( filename );
472     ok( ret, "DeleteFile failed (%d)\n", GetLastError(  ) );
473 }
474
475
476 static void test__lwrite( void )
477 {
478     HFILE filehandle;
479     char buffer[10000];
480     UINT bytes_read;
481     UINT bytes_written;
482     UINT blocks;
483     INT i;
484     char *contents;
485     HLOCAL memory_object;
486     char checksum[1];
487     BOOL ret;
488
489     filehandle = _lcreat( filename, 0 );
490     if (filehandle == HFILE_ERROR)
491     {
492         ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
493         return;
494     }
495
496     ok( HFILE_ERROR != _lwrite( filehandle, "", 0 ), "_hwrite complains\n" );
497
498     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
499
500     filehandle = _lopen( filename, OF_READ );
501
502     bytes_read = _hread( filehandle, buffer, 1);
503
504     ok( 0 == bytes_read, "file read size error\n" );
505
506     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
507
508     filehandle = _lopen( filename, OF_READWRITE );
509
510     bytes_written = 0;
511     checksum[0] = '\0';
512     srand( (unsigned)time( NULL ) );
513     for (blocks = 0; blocks < 100; blocks++)
514     {
515         for (i = 0; i < (INT)sizeof( buffer ); i++)
516         {
517             buffer[i] = rand(  );
518             checksum[0] = checksum[0] + buffer[i];
519         }
520         ok( HFILE_ERROR != _lwrite( filehandle, buffer, sizeof( buffer ) ), "_hwrite complains\n" );
521         bytes_written = bytes_written + sizeof( buffer );
522     }
523
524     ok( HFILE_ERROR != _lwrite( filehandle, checksum, 1 ), "_hwrite complains\n" );
525     bytes_written++;
526
527     ok( HFILE_ERROR != _lclose( filehandle ), "_lclose complains\n" );
528
529     memory_object = LocalAlloc( LPTR, bytes_written );
530
531     ok( 0 != memory_object, "LocalAlloc fails, could be out of memory\n" );
532
533     contents = LocalLock( memory_object );
534
535     filehandle = _lopen( filename, OF_READ );
536
537     contents = LocalLock( memory_object );
538
539     ok( NULL != contents, "LocalLock whines\n" );
540
541     ok( bytes_written == _hread( filehandle, contents, bytes_written), "read length differ from write length\n" );
542
543     checksum[0] = '\0';
544     i = 0;
545     do
546     {
547         checksum[0] += contents[i];
548         i++;
549     }
550     while (i < bytes_written - 1);
551
552     ok( checksum[0] == contents[i], "stored checksum differ from computed checksum\n" );
553
554     ok( HFILE_ERROR != _lclose( filehandle ), "_lclose complains\n" );
555
556     ret = DeleteFileA( filename );
557     ok( ret, "DeleteFile failed (%d)\n", GetLastError(  ) );
558 }
559
560 static void test_CopyFileA(void)
561 {
562     char temp_path[MAX_PATH];
563     char source[MAX_PATH], dest[MAX_PATH];
564     static const char prefix[] = "pfx";
565     HANDLE hfile;
566     HANDLE hmapfile;
567     FILETIME ft1, ft2;
568     char buf[10];
569     DWORD ret;
570     BOOL retok;
571
572     ret = GetTempPathA(MAX_PATH, temp_path);
573     ok(ret != 0, "GetTempPathA error %d\n", GetLastError());
574     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
575
576     ret = GetTempFileNameA(temp_path, prefix, 0, source);
577     ok(ret != 0, "GetTempFileNameA error %d\n", GetLastError());
578
579     ret = MoveFileA(source, source);
580     todo_wine ok(ret, "MoveFileA: failed, error %d\n", GetLastError());
581
582     /* make the source have not zero size */
583     hfile = CreateFileA(source, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0 );
584     ok(hfile != INVALID_HANDLE_VALUE, "failed to open source file\n");
585     retok = WriteFile(hfile, prefix, sizeof(prefix), &ret, NULL );
586     ok( retok && ret == sizeof(prefix),
587        "WriteFile error %d\n", GetLastError());
588     ok(GetFileSize(hfile, NULL) == sizeof(prefix), "source file has wrong size\n");
589     /* get the file time and change it to prove the difference */
590     ret = GetFileTime(hfile, NULL, NULL, &ft1);
591     ok( ret, "GetFileTime error %d\n", GetLastError());
592     ft1.dwLowDateTime -= 600000000; /* 60 second */
593     ret = SetFileTime(hfile, NULL, NULL, &ft1);
594     ok( ret, "SetFileTime error %d\n", GetLastError());
595     GetFileTime(hfile, NULL, NULL, &ft1);  /* get the actual time back */
596     CloseHandle(hfile);
597
598     ret = GetTempFileNameA(temp_path, prefix, 0, dest);
599     ok(ret != 0, "GetTempFileNameA error %d\n", GetLastError());
600
601     SetLastError(0xdeadbeef);
602     ret = CopyFileA(source, dest, TRUE);
603     ok(!ret && GetLastError() == ERROR_FILE_EXISTS,
604        "CopyFileA: unexpected error %d\n", GetLastError());
605
606     ret = CopyFileA(source, dest, FALSE);
607     ok(ret, "CopyFileA: error %d\n", GetLastError());
608
609     /* make sure that destination has correct size */
610     hfile = CreateFileA(dest, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
611     ok(hfile != INVALID_HANDLE_VALUE, "failed to open destination file\n");
612     ret = GetFileSize(hfile, NULL);
613     ok(ret == sizeof(prefix), "destination file has wrong size %d\n", ret);
614
615     /* make sure that destination has the same filetime */
616     ret = GetFileTime(hfile, NULL, NULL, &ft2);
617     ok( ret, "GetFileTime error %d\n", GetLastError());
618     ok(CompareFileTime(&ft1, &ft2) == 0, "destination file has wrong filetime\n");
619
620     SetLastError(0xdeadbeef);
621     ret = CopyFileA(source, dest, FALSE);
622     ok(!ret && GetLastError() == ERROR_SHARING_VIOLATION,
623        "CopyFileA: ret = %d, unexpected error %d\n", ret, GetLastError());
624
625     /* make sure that destination still has correct size */
626     ret = GetFileSize(hfile, NULL);
627     ok(ret == sizeof(prefix), "destination file has wrong size %d\n", ret);
628     retok = ReadFile(hfile, buf, sizeof(buf), &ret, NULL);
629     ok( retok && ret == sizeof(prefix),
630        "ReadFile: error %d\n", GetLastError());
631     ok(!memcmp(prefix, buf, sizeof(prefix)), "buffer contents mismatch\n");
632
633     /* check error on copying over a mapped file that was opened with FILE_SHARE_READ */
634     hmapfile = CreateFileMapping(hfile, NULL, PAGE_READONLY | SEC_COMMIT, 0, 0, NULL);
635     ok(hmapfile != NULL, "CreateFileMapping: error %d\n", GetLastError());
636
637     ret = CopyFileA(source, dest, FALSE);
638     ok(!ret && GetLastError() == ERROR_SHARING_VIOLATION,
639        "CopyFileA with mapped dest file: expected ERROR_SHARING_VIOLATION, got %d\n", GetLastError());
640
641     CloseHandle(hmapfile);
642     CloseHandle(hfile);
643
644     hfile = CreateFileA(dest, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0);
645     ok(hfile != INVALID_HANDLE_VALUE, "failed to open destination file\n");
646
647     /* check error on copying over a mapped file that was opened with FILE_SHARE_WRITE */
648     hmapfile = CreateFileMapping(hfile, NULL, PAGE_READONLY | SEC_COMMIT, 0, 0, NULL);
649     ok(hmapfile != NULL, "CreateFileMapping: error %d\n", GetLastError());
650
651     ret = CopyFileA(source, dest, FALSE);
652     ok(!ret, "CopyFileA: expected failure\n");
653     ok(GetLastError() == ERROR_USER_MAPPED_FILE ||
654        broken(GetLastError() == ERROR_SHARING_VIOLATION), /* Win9x */
655        "CopyFileA with mapped dest file: expected ERROR_USER_MAPPED_FILE, got %d\n", GetLastError());
656
657     CloseHandle(hmapfile);
658     CloseHandle(hfile);
659
660     ret = DeleteFileA(source);
661     ok(ret, "DeleteFileA: error %d\n", GetLastError());
662     ret = DeleteFileA(dest);
663     ok(ret, "DeleteFileA: error %d\n", GetLastError());
664 }
665
666 static void test_CopyFileW(void)
667 {
668     WCHAR temp_path[MAX_PATH];
669     WCHAR source[MAX_PATH], dest[MAX_PATH];
670     static const WCHAR prefix[] = {'p','f','x',0};
671     DWORD ret;
672
673     ret = GetTempPathW(MAX_PATH, temp_path);
674     if (ret == 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
675     {
676         win_skip("GetTempPathW is not available\n");
677         return;
678     }
679     ok(ret != 0, "GetTempPathW error %d\n", GetLastError());
680     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
681
682     ret = GetTempFileNameW(temp_path, prefix, 0, source);
683     ok(ret != 0, "GetTempFileNameW error %d\n", GetLastError());
684
685     ret = GetTempFileNameW(temp_path, prefix, 0, dest);
686     ok(ret != 0, "GetTempFileNameW error %d\n", GetLastError());
687
688     ret = CopyFileW(source, dest, TRUE);
689     ok(!ret && GetLastError() == ERROR_FILE_EXISTS,
690        "CopyFileW: unexpected error %d\n", GetLastError());
691
692     ret = CopyFileW(source, dest, FALSE);
693     ok(ret, "CopyFileW: error %d\n", GetLastError());
694
695     ret = DeleteFileW(source);
696     ok(ret, "DeleteFileW: error %d\n", GetLastError());
697     ret = DeleteFileW(dest);
698     ok(ret, "DeleteFileW: error %d\n", GetLastError());
699 }
700
701
702 /*
703  *   Debugging routine to dump a buffer in a hexdump-like fashion.
704  */
705 static void dumpmem(unsigned char* mem, int len) {
706     int x,y;
707     char buf[200];
708     int ln=0;
709
710     for (x=0; x<len; x+=16) {
711         ln += sprintf(buf+ln, "%04x: ",x);
712         for (y=0; y<16; y++) {
713             if ((x+y)>len) {
714                 ln += sprintf(buf+ln, "   ");
715             } else {
716                 ln += sprintf(buf+ln, "%02hhx ",mem[x+y]);
717             }
718         }
719         ln += sprintf(buf+ln, "- ");
720         for (y=0; y<16; y++) {
721             if ((x+y)<=len) {
722                 if (mem[x+y]<32 || mem[x+y]>127) {
723                     ln += sprintf(buf+ln, ".");
724                 } else {
725                     ln += sprintf(buf+ln, "%c",mem[x+y]);
726                 }
727             }
728         }
729         sprintf(buf+ln, "\n");
730         trace(buf);
731         ln = 0;
732     }
733 }
734
735 static void test_CreateFileA(void)
736 {
737     HANDLE hFile;
738     char temp_path[MAX_PATH], dirname[MAX_PATH];
739     char filename[MAX_PATH];
740     static const char prefix[] = "pfx";
741     char windowsdir[MAX_PATH];
742     char Volume_1[MAX_PATH];
743     unsigned char buffer[512];
744     char directory[] = "removeme";
745     static const char nt_drive[] = "\\\\?\\A:";
746     DWORD i, ret, len;
747     struct test_list p[] = {
748     {"", ERROR_PATH_NOT_FOUND, -1, FILE_ATTRIBUTE_NORMAL, TRUE }, /* dir as file w \ */
749     {"", ERROR_SUCCESS, ERROR_PATH_NOT_FOUND, FILE_FLAG_BACKUP_SEMANTICS, FALSE }, /* dir as dir w \ */
750     {"a", ERROR_FILE_NOT_FOUND, -1, FILE_ATTRIBUTE_NORMAL, FALSE }, /* non-exist file */
751     {"a\\", ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND, FILE_ATTRIBUTE_NORMAL, FALSE }, /* non-exist dir */
752     {"removeme", ERROR_ACCESS_DENIED, -1, FILE_ATTRIBUTE_NORMAL, FALSE }, /* exist dir w/o \ */
753     {"removeme\\", ERROR_PATH_NOT_FOUND, -1, FILE_ATTRIBUTE_NORMAL, TRUE }, /* exst dir w \ */
754     {"c:", ERROR_ACCESS_DENIED, ERROR_PATH_NOT_FOUND, FILE_ATTRIBUTE_NORMAL, FALSE }, /* device in file namespace */
755     {"c:", ERROR_SUCCESS, ERROR_PATH_NOT_FOUND, FILE_FLAG_BACKUP_SEMANTICS, FALSE }, /* device in file namespace as dir */
756     {"c:\\", ERROR_PATH_NOT_FOUND, ERROR_ACCESS_DENIED, FILE_ATTRIBUTE_NORMAL, TRUE }, /* root dir w \ */
757     {"c:\\", ERROR_SUCCESS, ERROR_ACCESS_DENIED, FILE_FLAG_BACKUP_SEMANTICS, FALSE }, /* root dir w \ as dir */
758     {"\\\\?\\c:", ERROR_SUCCESS, ERROR_BAD_NETPATH, FILE_ATTRIBUTE_NORMAL,FALSE }, /* dev namespace drive */
759     {"\\\\?\\c:\\", ERROR_PATH_NOT_FOUND, ERROR_BAD_NETPATH, FILE_ATTRIBUTE_NORMAL, TRUE }, /* dev namespace drive w \ */
760     {NULL, 0, -1, 0, FALSE}
761     };
762     BY_HANDLE_FILE_INFORMATION  Finfo;
763
764     ret = GetTempPathA(MAX_PATH, temp_path);
765     ok(ret != 0, "GetTempPathA error %d\n", GetLastError());
766     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
767
768     ret = GetTempFileNameA(temp_path, prefix, 0, filename);
769     ok(ret != 0, "GetTempFileNameA error %d\n", GetLastError());
770
771     SetLastError(0xdeadbeef);
772     hFile = CreateFileA(filename, GENERIC_READ, 0, NULL,
773                         CREATE_NEW, FILE_FLAG_RANDOM_ACCESS, 0);
774     ok(hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_FILE_EXISTS,
775         "CREATE_NEW should fail if file exists and last error value should be ERROR_FILE_EXISTS\n");
776
777     SetLastError(0xdeadbeef);
778     hFile = CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ, NULL,
779                         CREATE_ALWAYS, FILE_FLAG_RANDOM_ACCESS, 0);
780     ok(hFile != INVALID_HANDLE_VALUE && GetLastError() == ERROR_ALREADY_EXISTS,
781        "hFile %p, last error %u\n", hFile, GetLastError());
782
783     CloseHandle(hFile);
784
785     SetLastError(0xdeadbeef);
786     hFile = CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ, NULL,
787                         OPEN_ALWAYS, FILE_FLAG_RANDOM_ACCESS, 0);
788     ok(hFile != INVALID_HANDLE_VALUE && GetLastError() == ERROR_ALREADY_EXISTS,
789        "hFile %p, last error %u\n", hFile, GetLastError());
790
791     CloseHandle(hFile);
792
793     ret = DeleteFileA(filename);
794     ok(ret, "DeleteFileA: error %d\n", GetLastError());
795
796     SetLastError(0xdeadbeef);
797     hFile = CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ, NULL,
798                         OPEN_ALWAYS, FILE_FLAG_RANDOM_ACCESS, 0);
799     ok(hFile != INVALID_HANDLE_VALUE && GetLastError() == 0,
800        "hFile %p, last error %u\n", hFile, GetLastError());
801
802     CloseHandle(hFile);
803
804     ret = DeleteFileA(filename);
805     ok(ret, "DeleteFileA: error %d\n", GetLastError());
806
807     /* get windows drive letter */
808     ret = GetWindowsDirectory(windowsdir, sizeof(windowsdir));
809     ok(ret < sizeof(windowsdir), "windowsdir is abnormally long!\n");
810     ok(ret != 0, "GetWindowsDirectory: error %d\n", GetLastError());
811
812     /* test error return codes from CreateFile for some cases */
813     ret = GetTempPathA(MAX_PATH, temp_path);
814     ok(ret != 0, "GetTempPathA error %d\n", GetLastError());
815     strcpy(dirname, temp_path);
816     strcat(dirname, directory);
817     ret = CreateDirectory(dirname, NULL);
818     ok( ret, "Createdirectory failed, gle=%d\n", GetLastError() );
819     /* set current drive & directory to known location */
820     SetCurrentDirectoryA( temp_path );
821     i = 0;
822     while (p[i].file)
823     {
824         filename[0] = 0;
825         /* update the drive id in the table entry with the current one */
826         if (p[i].file[1] == ':')
827         {
828             strcpy(filename, p[i].file);
829             filename[0] = windowsdir[0];
830         }
831         else if (p[i].file[0] == '\\' && p[i].file[5] == ':')
832         {
833             strcpy(filename, p[i].file);
834             filename[4] = windowsdir[0];
835         }
836         else
837         {
838             /* prefix the table entry with the current temp directory */
839             strcpy(filename, temp_path);
840             strcat(filename, p[i].file);
841         }
842         hFile = CreateFileA( filename, GENERIC_READ | GENERIC_WRITE,
843                         FILE_SHARE_READ | FILE_SHARE_WRITE,
844                         NULL, OPEN_EXISTING,
845                         p[i].options, NULL );
846         /* if we get ACCESS_DENIED when we do not expect it, assume
847          * no access to the volume
848          */
849         if (hFile == INVALID_HANDLE_VALUE &&
850             GetLastError() == ERROR_ACCESS_DENIED &&
851             p[i].err != ERROR_ACCESS_DENIED)
852         {
853             if (p[i].todo_flag)
854                 skip("Either no authority to volume, or is todo_wine for %s err=%d should be %d\n", filename, GetLastError(), p[i].err);
855             else
856                 skip("Do not have authority to access volumes. Test for %s skipped\n", filename);
857         }
858         /* otherwise validate results with expectations */
859         else if (p[i].todo_flag)
860             todo_wine ok(
861                 (hFile == INVALID_HANDLE_VALUE &&
862                   (p[i].err == GetLastError() || p[i].err2 == GetLastError())) ||
863                 (hFile != INVALID_HANDLE_VALUE && p[i].err == ERROR_SUCCESS),
864                 "CreateFileA failed on %s, hFile %p, err=%u, should be %u\n",
865                 filename, hFile, GetLastError(), p[i].err);
866         else
867             ok(
868                 (hFile == INVALID_HANDLE_VALUE &&
869                  (p[i].err == GetLastError() || p[i].err2 == GetLastError())) ||
870                 (hFile != INVALID_HANDLE_VALUE && p[i].err == ERROR_SUCCESS),
871                 "CreateFileA failed on %s, hFile %p, err=%u, should be %u\n",
872                 filename, hFile, GetLastError(), p[i].err);
873         if (hFile != INVALID_HANDLE_VALUE)
874             CloseHandle( hFile );
875         i++;
876     }
877     ret = RemoveDirectoryA(dirname);
878     ok(ret, "RemoveDirectoryA: error %d\n", GetLastError());
879
880
881     /* test opening directory as a directory */
882     hFile = CreateFileA( temp_path, GENERIC_READ,
883                         FILE_SHARE_READ,
884                         NULL,
885                         OPEN_EXISTING,
886                         FILE_FLAG_BACKUP_SEMANTICS, NULL );
887     if (hFile != INVALID_HANDLE_VALUE && GetLastError() != ERROR_PATH_NOT_FOUND)
888     {
889         ok(hFile != INVALID_HANDLE_VALUE && GetLastError() == ERROR_SUCCESS,
890             "CreateFileA did not work, last error %u on volume <%s>\n",
891              GetLastError(), temp_path );
892
893         if (hFile != INVALID_HANDLE_VALUE)
894         {
895             ret = GetFileInformationByHandle( hFile, &Finfo );
896             if (ret)
897             {
898                 ok(Finfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY,
899                     "CreateFileA probably did not open temp directory %s correctly\n   file information does not include FILE_ATTRIBUTE_DIRECTORY, actual=0x%08x\n",
900                 temp_path, Finfo.dwFileAttributes);
901             }
902             CloseHandle( hFile );
903         }
904     }
905     else
906         skip("Probable Win9x, got ERROR_PATH_NOT_FOUND w/ FILE_FLAG_BACKUP_SEMANTICS or %s\n", temp_path);
907
908
909     /* ***  Test opening volumes/devices using drive letter  ***         */
910
911     /* test using drive letter in non-rewrite format without trailing \  */
912     /* this should work                                                  */
913     strcpy(filename, nt_drive);
914     filename[4] = windowsdir[0];
915     hFile = CreateFileA( filename, GENERIC_READ | GENERIC_WRITE,
916                         FILE_SHARE_READ | FILE_SHARE_WRITE,
917                         NULL, OPEN_EXISTING,
918                         FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING, NULL );
919     if (hFile != INVALID_HANDLE_VALUE ||
920         (GetLastError() != ERROR_ACCESS_DENIED && GetLastError() != ERROR_BAD_NETPATH))
921     {
922         /* if we have adm rights to volume, then try rest of tests */
923         ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA did not open %s, last error=%u\n",
924             filename, GetLastError());
925         if (hFile != INVALID_HANDLE_VALUE)
926         {
927             /* if we opened the volume/device, try to read it. Since it  */
928             /* opened, we should be able to read it.  We don't care about*/
929             /* what the data is at this time.                            */
930             len = 512;
931             ret = ReadFile( hFile, buffer, len, &len, NULL );
932             todo_wine ok(ret, "Failed to read volume, last error %u, %u, for %s\n",
933                 GetLastError(), ret, filename);
934             if (ret)
935             {
936                 trace("buffer is\n");
937                 dumpmem(buffer, 64);
938             }
939             CloseHandle( hFile );
940         }
941
942         /* test using drive letter with trailing \ and in non-rewrite   */
943         /* this should not work                                         */
944         strcpy(filename, nt_drive);
945         filename[4] = windowsdir[0];
946         strcat( filename, "\\" );
947         hFile = CreateFileA( filename, GENERIC_READ | GENERIC_WRITE,
948                         FILE_SHARE_READ | FILE_SHARE_WRITE,
949                         NULL, OPEN_EXISTING,
950                         FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING, NULL );
951         todo_wine
952         ok(hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_PATH_NOT_FOUND,
953             "CreateFileA should have returned ERROR_PATH_NOT_FOUND on %s, but got %u\n",
954             filename, GetLastError());
955         if (hFile != INVALID_HANDLE_VALUE)
956             CloseHandle( hFile );
957
958         /* test using temp path with trailing \ and in non-rewrite as dir */
959         /* this should work                                               */
960         strcpy(filename, nt_drive);
961         filename[4] = 0;
962         strcat( filename, temp_path );
963         hFile = CreateFileA( filename, GENERIC_READ | GENERIC_WRITE,
964                         FILE_SHARE_READ | FILE_SHARE_WRITE,
965                         NULL, OPEN_EXISTING,
966                         FILE_FLAG_BACKUP_SEMANTICS, NULL );
967         ok(hFile != INVALID_HANDLE_VALUE,
968             "CreateFileA should have worked on %s, but got %u\n",
969             filename, GetLastError());
970         if (hFile != INVALID_HANDLE_VALUE)
971             CloseHandle( hFile );
972
973         /* test using drive letter without trailing \ and in device ns  */
974         /* this should work                                             */
975         strcpy(filename, nt_drive);
976         filename[4] = windowsdir[0];
977         filename[2] = '.';
978         hFile = CreateFileA( filename, GENERIC_READ | GENERIC_WRITE,
979                         FILE_SHARE_READ | FILE_SHARE_WRITE,
980                         NULL, OPEN_EXISTING,
981                         FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING, NULL );
982         ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA did not open %s, last error=%u\n",
983             filename, GetLastError());
984         if (hFile != INVALID_HANDLE_VALUE)
985             CloseHandle( hFile );
986     }
987     /* If we see ERROR_BAD_NETPATH then on Win9x or WinME, so skip */
988     else if (GetLastError() == ERROR_BAD_NETPATH)
989         skip("Probable Win9x, got ERROR_BAD_NETPATH (53)\n");
990     else
991         skip("Do not have authority to access volumes. Tests skipped\n");
992
993
994     /* ***  Test opening volumes/devices using GUID  ***           */
995
996     if (pGetVolumeNameForVolumeMountPointA)
997     {
998         strcpy(filename, "c:\\");
999         filename[0] = windowsdir[0];
1000         ret = pGetVolumeNameForVolumeMountPointA( filename, Volume_1, MAX_PATH );
1001         ok(ret, "GetVolumeNameForVolumeMountPointA failed, for %s, last error=%d\n", filename, GetLastError());
1002         if (ret)
1003         {
1004             ok(strlen(Volume_1) == 49, "GetVolumeNameForVolumeMountPointA returned wrong length name <%s>\n", Volume_1);
1005
1006             /* test the result of opening a unique volume name (GUID)
1007              *  with the trailing \
1008              *  this should error out
1009              */
1010             strcpy(filename, Volume_1);
1011             hFile = CreateFileA( filename, GENERIC_READ | GENERIC_WRITE,
1012                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1013                         NULL, OPEN_EXISTING,
1014                         FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING, NULL );
1015             todo_wine
1016             ok(hFile == INVALID_HANDLE_VALUE,
1017                 "CreateFileA should not have opened %s, hFile %p\n",
1018                 filename, hFile);
1019             todo_wine
1020             ok(hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_PATH_NOT_FOUND,
1021                 "CreateFileA should have returned ERROR_PATH_NOT_FOUND on %s, but got %u\n",
1022                 filename, GetLastError());
1023             if (hFile != INVALID_HANDLE_VALUE)
1024                 CloseHandle( hFile );
1025
1026             /* test the result of opening a unique volume name (GUID)
1027              * with the temp path string as dir
1028              * this should work
1029              */
1030             strcpy(filename, Volume_1);
1031             strcat(filename, temp_path+3);
1032             hFile = CreateFileA( filename, GENERIC_READ | GENERIC_WRITE,
1033                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1034                         NULL, OPEN_EXISTING,
1035                         FILE_FLAG_BACKUP_SEMANTICS, NULL );
1036             todo_wine
1037             ok(hFile != INVALID_HANDLE_VALUE,
1038                 "CreateFileA should have opened %s, but got %u\n",
1039                 filename, GetLastError());
1040             if (hFile != INVALID_HANDLE_VALUE)
1041                 CloseHandle( hFile );
1042
1043             /* test the result of opening a unique volume name (GUID)
1044              * without the trailing \ and in device namespace
1045              * this should work
1046              */
1047             strcpy(filename, Volume_1);
1048             filename[2] = '.';
1049             filename[48] = 0;
1050             hFile = CreateFileA( filename, GENERIC_READ | GENERIC_WRITE,
1051                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1052                         NULL, OPEN_EXISTING,
1053                         FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING, NULL );
1054             if (hFile != INVALID_HANDLE_VALUE || GetLastError() != ERROR_ACCESS_DENIED)
1055             {
1056                 /* if we have adm rights to volume, then try rest of tests */
1057                 ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA did not open %s, last error=%u\n",
1058                     filename, GetLastError());
1059                 if (hFile != INVALID_HANDLE_VALUE)
1060                 {
1061                     /* if we opened the volume/device, try to read it. Since it  */
1062                     /* opened, we should be able to read it.  We don't care about*/
1063                     /* what the data is at this time.                            */
1064                     len = 512;
1065                     ret = ReadFile( hFile, buffer, len, &len, NULL );
1066                     todo_wine ok(ret, "Failed to read volume, last error %u, %u, for %s\n",
1067                         GetLastError(), ret, filename);
1068                     if (ret)
1069                     {
1070                         trace("buffer is\n");
1071                         dumpmem(buffer, 64);
1072                     }
1073                     CloseHandle( hFile );
1074                 }
1075             }
1076             else
1077                 skip("Do not have authority to access volumes. Tests skipped\n");
1078         }
1079         else
1080             win_skip("GetVolumeNameForVolumeMountPointA not functioning\n");
1081     }
1082     else
1083         win_skip("GetVolumeNameForVolumeMountPointA not found\n");
1084 }
1085
1086 static void test_CreateFileW(void)
1087 {
1088     HANDLE hFile;
1089     WCHAR temp_path[MAX_PATH];
1090     WCHAR filename[MAX_PATH];
1091     static const WCHAR emptyW[]={'\0'};
1092     static const WCHAR prefix[] = {'p','f','x',0};
1093     static const WCHAR bogus[] = { '\\', '\\', '.', '\\', 'B', 'O', 'G', 'U', 'S', 0 };
1094     DWORD ret;
1095
1096     ret = GetTempPathW(MAX_PATH, temp_path);
1097     if (ret == 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
1098     {
1099         win_skip("GetTempPathW is not available\n");
1100         return;
1101     }
1102     ok(ret != 0, "GetTempPathW error %d\n", GetLastError());
1103     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
1104
1105     ret = GetTempFileNameW(temp_path, prefix, 0, filename);
1106     ok(ret != 0, "GetTempFileNameW error %d\n", GetLastError());
1107
1108     SetLastError(0xdeadbeef);
1109     hFile = CreateFileW(filename, GENERIC_READ, 0, NULL,
1110                         CREATE_NEW, FILE_FLAG_RANDOM_ACCESS, 0);
1111     ok(hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_FILE_EXISTS,
1112         "CREATE_NEW should fail if file exists and last error value should be ERROR_FILE_EXISTS\n");
1113
1114     SetLastError(0xdeadbeef);
1115     hFile = CreateFileW(filename, GENERIC_READ, FILE_SHARE_READ, NULL,
1116                         CREATE_ALWAYS, FILE_FLAG_RANDOM_ACCESS, 0);
1117     ok(hFile != INVALID_HANDLE_VALUE && GetLastError() == ERROR_ALREADY_EXISTS,
1118        "hFile %p, last error %u\n", hFile, GetLastError());
1119
1120     CloseHandle(hFile);
1121
1122     SetLastError(0xdeadbeef);
1123     hFile = CreateFileW(filename, GENERIC_READ, FILE_SHARE_READ, NULL,
1124                         OPEN_ALWAYS, FILE_FLAG_RANDOM_ACCESS, 0);
1125     ok(hFile != INVALID_HANDLE_VALUE && GetLastError() == ERROR_ALREADY_EXISTS,
1126        "hFile %p, last error %u\n", hFile, GetLastError());
1127
1128     CloseHandle(hFile);
1129
1130     ret = DeleteFileW(filename);
1131     ok(ret, "DeleteFileW: error %d\n", GetLastError());
1132
1133     SetLastError(0xdeadbeef);
1134     hFile = CreateFileW(filename, GENERIC_READ, FILE_SHARE_READ, NULL,
1135                         OPEN_ALWAYS, FILE_FLAG_RANDOM_ACCESS, 0);
1136     ok(hFile != INVALID_HANDLE_VALUE && GetLastError() == 0,
1137        "hFile %p, last error %u\n", hFile, GetLastError());
1138
1139     CloseHandle(hFile);
1140
1141     ret = DeleteFileW(filename);
1142     ok(ret, "DeleteFileW: error %d\n", GetLastError());
1143
1144     if (0)
1145     {
1146         /* this crashes on NT4.0 */
1147         hFile = CreateFileW(NULL, GENERIC_READ, 0, NULL,
1148                             CREATE_NEW, FILE_FLAG_RANDOM_ACCESS, 0);
1149         ok(hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_PATH_NOT_FOUND,
1150            "CreateFileW(NULL) returned ret=%p error=%u\n",hFile,GetLastError());
1151     }
1152
1153     hFile = CreateFileW(emptyW, GENERIC_READ, 0, NULL,
1154                         CREATE_NEW, FILE_FLAG_RANDOM_ACCESS, 0);
1155     ok(hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_PATH_NOT_FOUND,
1156        "CreateFileW(\"\") returned ret=%p error=%d\n",hFile,GetLastError());
1157
1158     /* test the result of opening a nonexistent driver name */
1159     hFile = CreateFileW(bogus, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1160                         OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1161     ok(hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_FILE_NOT_FOUND,
1162        "CreateFileW on invalid VxD name returned ret=%p error=%d\n",hFile,GetLastError());
1163
1164     ret = CreateDirectoryW(filename, NULL);
1165     ok(ret == TRUE, "couldn't create temporary directory\n");
1166     hFile = CreateFileW(filename, GENERIC_READ | GENERIC_WRITE, 0, NULL,
1167                         OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, NULL);
1168     ok(hFile != INVALID_HANDLE_VALUE,
1169        "expected CreateFile to succeed on existing directory, error: %d\n", GetLastError());
1170     CloseHandle(hFile);
1171     ret = RemoveDirectoryW(filename);
1172     ok(ret, "DeleteFileW: error %d\n", GetLastError());
1173 }
1174
1175 static void test_GetTempFileNameA(void)
1176 {
1177     UINT result;
1178     char out[MAX_PATH];
1179     char expected[MAX_PATH + 10];
1180     char windowsdir[MAX_PATH + 10];
1181     char windowsdrive[3];
1182
1183     result = GetWindowsDirectory(windowsdir, sizeof(windowsdir));
1184     ok(result < sizeof(windowsdir), "windowsdir is abnormally long!\n");
1185     ok(result != 0, "GetWindowsDirectory: error %d\n", GetLastError());
1186
1187     /* If the Windows directory is the root directory, it ends in backslash, not else. */
1188     if (strlen(windowsdir) != 3) /* As in  "C:\"  or  "F:\"  */
1189     {
1190         strcat(windowsdir, "\\");
1191     }
1192
1193     windowsdrive[0] = windowsdir[0];
1194     windowsdrive[1] = windowsdir[1];
1195     windowsdrive[2] = '\0';
1196
1197     result = GetTempFileNameA(windowsdrive, "abc", 1, out);
1198     ok(result != 0, "GetTempFileNameA: error %d\n", GetLastError());
1199     ok(((out[0] == windowsdrive[0]) && (out[1] == ':')) && (out[2] == '\\'),
1200        "GetTempFileNameA: first three characters should be %c:\\, string was actually %s\n",
1201        windowsdrive[0], out);
1202
1203     result = GetTempFileNameA(windowsdir, "abc", 2, out);
1204     ok(result != 0, "GetTempFileNameA: error %d\n", GetLastError());
1205     expected[0] = '\0';
1206     strcat(expected, windowsdir);
1207     strcat(expected, "abc2.tmp");
1208     ok(lstrcmpiA(out, expected) == 0, "GetTempFileNameA: Unexpected output \"%s\" vs \"%s\"\n",
1209        out, expected);
1210 }
1211
1212 static void test_DeleteFileA( void )
1213 {
1214     BOOL ret;
1215
1216     ret = DeleteFileA(NULL);
1217     ok(!ret && (GetLastError() == ERROR_INVALID_PARAMETER ||
1218                 GetLastError() == ERROR_PATH_NOT_FOUND),
1219        "DeleteFileA(NULL) returned ret=%d error=%d\n",ret,GetLastError());
1220
1221     ret = DeleteFileA("");
1222     ok(!ret && (GetLastError() == ERROR_PATH_NOT_FOUND ||
1223                 GetLastError() == ERROR_BAD_PATHNAME),
1224        "DeleteFileA(\"\") returned ret=%d error=%d\n",ret,GetLastError());
1225
1226     ret = DeleteFileA("nul");
1227     ok(!ret && (GetLastError() == ERROR_FILE_NOT_FOUND ||
1228                 GetLastError() == ERROR_INVALID_PARAMETER ||
1229                 GetLastError() == ERROR_ACCESS_DENIED ||
1230                 GetLastError() == ERROR_INVALID_FUNCTION),
1231        "DeleteFileA(\"nul\") returned ret=%d error=%d\n",ret,GetLastError());
1232 }
1233
1234 static void test_DeleteFileW( void )
1235 {
1236     BOOL ret;
1237     WCHAR pathW[MAX_PATH];
1238     WCHAR pathsubW[MAX_PATH];
1239     static const WCHAR dirW[] = {'d','e','l','e','t','e','f','i','l','e',0};
1240     static const WCHAR subdirW[] = {'\\','s','u','b',0};
1241     static const WCHAR emptyW[]={'\0'};
1242
1243     ret = DeleteFileW(NULL);
1244     if (ret == 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
1245     {
1246         win_skip("DeleteFileW is not available\n");
1247         return;
1248     }
1249     ok(!ret && GetLastError() == ERROR_PATH_NOT_FOUND,
1250        "DeleteFileW(NULL) returned ret=%d error=%d\n",ret,GetLastError());
1251
1252     ret = DeleteFileW(emptyW);
1253     ok(!ret && GetLastError() == ERROR_PATH_NOT_FOUND,
1254        "DeleteFileW(\"\") returned ret=%d error=%d\n",ret,GetLastError());
1255
1256     /* test DeleteFile on empty directory */
1257     ret = GetTempPathW(MAX_PATH, pathW);
1258     if (ret + sizeof(dirW)/sizeof(WCHAR)-1 + sizeof(subdirW)/sizeof(WCHAR)-1 >= MAX_PATH)
1259     {
1260         ok(0, "MAX_PATH exceeded in constructing paths\n");
1261         return;
1262     }
1263     lstrcatW(pathW, dirW);
1264     lstrcpyW(pathsubW, pathW);
1265     lstrcatW(pathsubW, subdirW);
1266     ret = CreateDirectoryW(pathW, NULL);
1267     ok(ret == TRUE, "couldn't create directory deletefile\n");
1268     ret = DeleteFileW(pathW);
1269     ok(ret == FALSE, "DeleteFile should fail for empty directories\n");
1270     ret = RemoveDirectoryW(pathW);
1271     ok(ret == TRUE, "expected to remove directory deletefile\n");
1272
1273     /* test DeleteFile on non-empty directory */
1274     ret = CreateDirectoryW(pathW, NULL);
1275     ok(ret == TRUE, "couldn't create directory deletefile\n");
1276     ret = CreateDirectoryW(pathsubW, NULL);
1277     ok(ret == TRUE, "couldn't create directory deletefile\\sub\n");
1278     ret = DeleteFileW(pathW);
1279     ok(ret == FALSE, "DeleteFile should fail for non-empty directories\n");
1280     ret = RemoveDirectoryW(pathsubW);
1281     ok(ret == TRUE, "expected to remove directory deletefile\\sub\n");
1282     ret = RemoveDirectoryW(pathW);
1283     ok(ret == TRUE, "expected to remove directory deletefile\n");
1284 }
1285
1286 #define IsDotDir(x)     ((x[0] == '.') && ((x[1] == 0) || ((x[1] == '.') && (x[2] == 0))))
1287
1288 static void test_MoveFileA(void)
1289 {
1290     char tempdir[MAX_PATH];
1291     char source[MAX_PATH], dest[MAX_PATH];
1292     static const char prefix[] = "pfx";
1293     HANDLE hfile;
1294     HANDLE hmapfile;
1295     DWORD ret;
1296     BOOL retok;
1297
1298     ret = GetTempPathA(MAX_PATH, tempdir);
1299     ok(ret != 0, "GetTempPathA error %d\n", GetLastError());
1300     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
1301
1302     ret = GetTempFileNameA(tempdir, prefix, 0, source);
1303     ok(ret != 0, "GetTempFileNameA error %d\n", GetLastError());
1304
1305     ret = GetTempFileNameA(tempdir, prefix, 0, dest);
1306     ok(ret != 0, "GetTempFileNameA error %d\n", GetLastError());
1307
1308     ret = MoveFileA(source, dest);
1309     ok(!ret && GetLastError() == ERROR_ALREADY_EXISTS,
1310        "MoveFileA: unexpected error %d\n", GetLastError());
1311
1312     ret = DeleteFileA(dest);
1313     ok(ret, "DeleteFileA: error %d\n", GetLastError());
1314
1315     hfile = CreateFileA(source, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0);
1316     ok(hfile != INVALID_HANDLE_VALUE, "failed to open source file\n");
1317
1318     retok = WriteFile(hfile, prefix, sizeof(prefix), &ret, NULL );
1319     ok( retok && ret == sizeof(prefix),
1320        "WriteFile error %d\n", GetLastError());
1321
1322     hmapfile = CreateFileMapping(hfile, NULL, PAGE_READONLY | SEC_COMMIT, 0, 0, NULL);
1323     ok(hmapfile != NULL, "CreateFileMapping: error %d\n", GetLastError());
1324
1325     ret = MoveFileA(source, dest);
1326     todo_wine {
1327         ok(!ret, "MoveFileA: expected failure\n");
1328         ok(GetLastError() == ERROR_SHARING_VIOLATION ||
1329            broken(GetLastError() == ERROR_ACCESS_DENIED), /* Win9x and WinMe */
1330            "MoveFileA: expected ERROR_SHARING_VIOLATION, got %d\n", GetLastError());
1331     }
1332
1333     CloseHandle(hmapfile);
1334     CloseHandle(hfile);
1335
1336     /* if MoveFile succeeded, move back to dest */
1337     if (ret) MoveFile(dest, source);
1338
1339     hfile = CreateFileA(source, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
1340     ok(hfile != INVALID_HANDLE_VALUE, "failed to open source file\n");
1341
1342     hmapfile = CreateFileMapping(hfile, NULL, PAGE_READONLY | SEC_COMMIT, 0, 0, NULL);
1343     ok(hmapfile != NULL, "CreateFileMapping: error %d\n", GetLastError());
1344
1345     ret = MoveFileA(source, dest);
1346     todo_wine {
1347         ok(!ret, "MoveFileA: expected failure\n");
1348         ok(GetLastError() == ERROR_SHARING_VIOLATION ||
1349            broken(GetLastError() == ERROR_ACCESS_DENIED), /* Win9x and WinMe */
1350            "MoveFileA: expected ERROR_SHARING_VIOLATION, got %d\n", GetLastError());
1351     }
1352
1353     CloseHandle(hmapfile);
1354     CloseHandle(hfile);
1355
1356     /* if MoveFile succeeded, move back to dest */
1357     if (ret) MoveFile(dest, source);
1358
1359     ret = MoveFileA(source, dest);
1360     ok(ret, "MoveFileA: failed, error %d\n", GetLastError());
1361
1362     lstrcatA(tempdir, "Remove Me");
1363     ret = CreateDirectoryA(tempdir, NULL);
1364     ok(ret == TRUE, "CreateDirectoryA failed\n");
1365
1366     lstrcpyA(source, dest);
1367     lstrcpyA(dest, tempdir);
1368     lstrcatA(dest, "\\wild?.*");
1369     /* FIXME: if we create a file with wildcards we can't delete it now that DeleteFile works correctly */
1370     ret = MoveFileA(source, dest);
1371     ok(!ret, "MoveFileA: shouldn't move to wildcard file\n");
1372     ok(GetLastError() == ERROR_INVALID_NAME || /* NT */
1373        GetLastError() == ERROR_FILE_NOT_FOUND, /* Win9x */
1374        "MoveFileA: with wildcards, unexpected error %d\n", GetLastError());
1375     if (ret || (GetLastError() != ERROR_INVALID_NAME))
1376     {
1377         WIN32_FIND_DATAA fd;
1378         char temppath[MAX_PATH];
1379         HANDLE hFind;
1380
1381         lstrcpyA(temppath, tempdir);
1382         lstrcatA(temppath, "\\*.*");
1383         hFind = FindFirstFileA(temppath, &fd);
1384         if (INVALID_HANDLE_VALUE != hFind)
1385         {
1386           LPSTR lpName;
1387           do
1388           {
1389             lpName = fd.cAlternateFileName;
1390             if (!lpName[0])
1391               lpName = fd.cFileName;
1392             ok(IsDotDir(lpName), "MoveFileA: wildcards file created!\n");
1393           }
1394           while (FindNextFileA(hFind, &fd));
1395           FindClose(hFind);
1396         }
1397     }
1398     ret = DeleteFileA(source);
1399     ok(ret, "DeleteFileA: error %d\n", GetLastError());
1400     ret = DeleteFileA(dest);
1401     ok(!ret, "DeleteFileA: error %d\n", GetLastError());
1402     ret = RemoveDirectoryA(tempdir);
1403     ok(ret, "DeleteDirectoryA: error %d\n", GetLastError());
1404 }
1405
1406 static void test_MoveFileW(void)
1407 {
1408     WCHAR temp_path[MAX_PATH];
1409     WCHAR source[MAX_PATH], dest[MAX_PATH];
1410     static const WCHAR prefix[] = {'p','f','x',0};
1411     DWORD ret;
1412
1413     ret = GetTempPathW(MAX_PATH, temp_path);
1414     if (ret == 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
1415     {
1416         win_skip("GetTempPathW is not available\n");
1417         return;
1418     }
1419     ok(ret != 0, "GetTempPathW error %d\n", GetLastError());
1420     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
1421
1422     ret = GetTempFileNameW(temp_path, prefix, 0, source);
1423     ok(ret != 0, "GetTempFileNameW error %d\n", GetLastError());
1424
1425     ret = GetTempFileNameW(temp_path, prefix, 0, dest);
1426     ok(ret != 0, "GetTempFileNameW error %d\n", GetLastError());
1427
1428     ret = MoveFileW(source, dest);
1429     ok(!ret && GetLastError() == ERROR_ALREADY_EXISTS,
1430        "CopyFileW: unexpected error %d\n", GetLastError());
1431
1432     ret = DeleteFileW(source);
1433     ok(ret, "DeleteFileW: error %d\n", GetLastError());
1434     ret = DeleteFileW(dest);
1435     ok(ret, "DeleteFileW: error %d\n", GetLastError());
1436 }
1437
1438 #define PATTERN_OFFSET 0x10
1439
1440 static void test_offset_in_overlapped_structure(void)
1441 {
1442     HANDLE hFile;
1443     OVERLAPPED ov;
1444     DWORD done, offset;
1445     BOOL rc;
1446     BYTE buf[256], pattern[] = "TeSt";
1447     UINT i;
1448     char temp_path[MAX_PATH], temp_fname[MAX_PATH];
1449     BOOL ret;
1450
1451     ret =GetTempPathA(MAX_PATH, temp_path);
1452     ok( ret, "GetTempPathA error %d\n", GetLastError());
1453     ret =GetTempFileNameA(temp_path, "pfx", 0, temp_fname);
1454     ok( ret, "GetTempFileNameA error %d\n", GetLastError());
1455
1456     /*** Write File *****************************************************/
1457
1458     hFile = CreateFileA(temp_fname, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
1459     ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA error %d\n", GetLastError());
1460
1461     for(i = 0; i < sizeof(buf); i++) buf[i] = i;
1462     ret = WriteFile(hFile, buf, sizeof(buf), &done, NULL);
1463     ok( ret, "WriteFile error %d\n", GetLastError());
1464     ok(done == sizeof(buf), "expected number of bytes written %u\n", done);
1465
1466     memset(&ov, 0, sizeof(ov));
1467     S(U(ov)).Offset = PATTERN_OFFSET;
1468     S(U(ov)).OffsetHigh = 0;
1469     rc=WriteFile(hFile, pattern, sizeof(pattern), &done, &ov);
1470     /* Win 9x does not support the overlapped I/O on files */
1471     if (rc || GetLastError()!=ERROR_INVALID_PARAMETER) {
1472         ok(rc, "WriteFile error %d\n", GetLastError());
1473         ok(done == sizeof(pattern), "expected number of bytes written %u\n", done);
1474         offset = SetFilePointer(hFile, 0, NULL, FILE_CURRENT);
1475         ok(offset == PATTERN_OFFSET + sizeof(pattern), "wrong file offset %d\n", offset);
1476
1477         S(U(ov)).Offset = sizeof(buf) * 2;
1478         S(U(ov)).OffsetHigh = 0;
1479         ret = WriteFile(hFile, pattern, sizeof(pattern), &done, &ov);
1480         ok( ret, "WriteFile error %d\n", GetLastError());
1481         ok(done == sizeof(pattern), "expected number of bytes written %u\n", done);
1482         offset = SetFilePointer(hFile, 0, NULL, FILE_CURRENT);
1483         ok(offset == sizeof(buf) * 2 + sizeof(pattern), "wrong file offset %d\n", offset);
1484     }
1485
1486     CloseHandle(hFile);
1487
1488     /*** Read File *****************************************************/
1489
1490     hFile = CreateFileA(temp_fname, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, 0);
1491     ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA error %d\n", GetLastError());
1492
1493     memset(buf, 0, sizeof(buf));
1494     memset(&ov, 0, sizeof(ov));
1495     S(U(ov)).Offset = PATTERN_OFFSET;
1496     S(U(ov)).OffsetHigh = 0;
1497     rc=ReadFile(hFile, buf, sizeof(pattern), &done, &ov);
1498     /* Win 9x does not support the overlapped I/O on files */
1499     if (rc || GetLastError()!=ERROR_INVALID_PARAMETER) {
1500         ok(rc, "ReadFile error %d\n", GetLastError());
1501         ok(done == sizeof(pattern), "expected number of bytes read %u\n", done);
1502         offset = SetFilePointer(hFile, 0, NULL, FILE_CURRENT);
1503         ok(offset == PATTERN_OFFSET + sizeof(pattern), "wrong file offset %d\n", offset);
1504         ok(!memcmp(buf, pattern, sizeof(pattern)), "pattern match failed\n");
1505     }
1506
1507     CloseHandle(hFile);
1508
1509     ret = DeleteFileA(temp_fname);
1510     ok( ret, "DeleteFileA error %d\n", GetLastError());
1511 }
1512
1513 static void test_LockFile(void)
1514 {
1515     HANDLE handle;
1516     DWORD written;
1517     OVERLAPPED overlapped;
1518     int limited_LockFile;
1519     int limited_UnLockFile;
1520     BOOL ret;
1521
1522     handle = CreateFileA( filename, GENERIC_READ | GENERIC_WRITE,
1523                           FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1524                           CREATE_ALWAYS, 0, 0 );
1525     if (handle == INVALID_HANDLE_VALUE)
1526     {
1527         ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
1528         return;
1529     }
1530     ok( WriteFile( handle, sillytext, strlen(sillytext), &written, NULL ), "write failed\n" );
1531
1532     ok( LockFile( handle, 0, 0, 0, 0 ), "LockFile failed\n" );
1533     ok( UnlockFile( handle, 0, 0, 0, 0 ), "UnlockFile failed\n" );
1534
1535     limited_UnLockFile = 0;
1536     if (UnlockFile( handle, 0, 0, 0, 0 ))
1537     {
1538         limited_UnLockFile = 1;
1539     }
1540
1541     ok( LockFile( handle, 10, 0, 20, 0 ), "LockFile 10,20 failed\n" );
1542     /* overlapping locks must fail */
1543     ok( !LockFile( handle, 12, 0, 10, 0 ), "LockFile 12,10 succeeded\n" );
1544     ok( !LockFile( handle, 5, 0, 6, 0 ), "LockFile 5,6 succeeded\n" );
1545     /* non-overlapping locks must succeed */
1546     ok( LockFile( handle, 5, 0, 5, 0 ), "LockFile 5,5 failed\n" );
1547
1548     ok( !UnlockFile( handle, 10, 0, 10, 0 ), "UnlockFile 10,10 succeeded\n" );
1549     ok( UnlockFile( handle, 10, 0, 20, 0 ), "UnlockFile 10,20 failed\n" );
1550     ok( !UnlockFile( handle, 10, 0, 20, 0 ), "UnlockFile 10,20 again succeeded\n" );
1551     ok( UnlockFile( handle, 5, 0, 5, 0 ), "UnlockFile 5,5 failed\n" );
1552
1553     S(U(overlapped)).Offset = 100;
1554     S(U(overlapped)).OffsetHigh = 0;
1555     overlapped.hEvent = 0;
1556
1557     /* Test for broken LockFileEx a la Windows 95 OSR2. */
1558     if (LockFileEx( handle, 0, 0, 100, 0, &overlapped ))
1559     {
1560         /* LockFileEx is probably OK, test it more. */
1561         ok( LockFileEx( handle, 0, 0, 100, 0, &overlapped ),
1562             "LockFileEx 100,100 failed\n" );
1563     }
1564
1565     /* overlapping shared locks are OK */
1566     S(U(overlapped)).Offset = 150;
1567     limited_UnLockFile || ok( LockFileEx( handle, 0, 0, 100, 0, &overlapped ), "LockFileEx 150,100 failed\n" );
1568
1569     /* but exclusive is not */
1570     ok( !LockFileEx( handle, LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1571                      0, 50, 0, &overlapped ),
1572         "LockFileEx exclusive 150,50 succeeded\n" );
1573     if (!UnlockFileEx( handle, 0, 100, 0, &overlapped ))
1574     { /* UnLockFile is capable. */
1575         S(U(overlapped)).Offset = 100;
1576         ok( !UnlockFileEx( handle, 0, 100, 0, &overlapped ),
1577             "UnlockFileEx 150,100 again succeeded\n" );
1578     }
1579
1580     ret = LockFile( handle, 0, 0x10000000, 0, 0xf0000000 );
1581     if (ret)
1582     {
1583         ok( !LockFile( handle, ~0, ~0, 1, 0 ), "LockFile ~0,1 succeeded\n" );
1584         ok( !LockFile( handle, 0, 0x20000000, 20, 0 ), "LockFile 0x20000000,20 succeeded\n" );
1585         ok( UnlockFile( handle, 0, 0x10000000, 0, 0xf0000000 ), "UnlockFile failed\n" );
1586     }
1587     else  /* win9x */
1588         ok( GetLastError() == ERROR_INVALID_PARAMETER, "wrong LockFile error %u\n", GetLastError() );
1589
1590     /* wrap-around lock should not do anything */
1591     /* (but still succeeds on NT4 so we don't check result) */
1592     LockFile( handle, 0, 0x10000000, 0, 0xf0000001 );
1593
1594     limited_LockFile = 0;
1595     if (!LockFile( handle, ~0, ~0, 1, 0 ))
1596     {
1597         limited_LockFile = 1;
1598     }
1599
1600     limited_UnLockFile || ok( UnlockFile( handle, ~0, ~0, 1, 0 ), "Unlockfile ~0,1 failed\n" );
1601
1602     /* zero-byte lock */
1603     ok( LockFile( handle, 100, 0, 0, 0 ), "LockFile 100,0 failed\n" );
1604     limited_LockFile || ok( !LockFile( handle, 98, 0, 4, 0 ), "LockFile 98,4 succeeded\n" );
1605     ok( LockFile( handle, 90, 0, 10, 0 ), "LockFile 90,10 failed\n" );
1606     limited_LockFile || ok( !LockFile( handle, 100, 0, 10, 0 ), "LockFile 100,10 failed\n" );
1607
1608     ok( UnlockFile( handle, 90, 0, 10, 0 ), "UnlockFile 90,10 failed\n" );
1609     !ok( UnlockFile( handle, 100, 0, 10, 0 ), "UnlockFile 100,10 failed\n" );
1610
1611     ok( UnlockFile( handle, 100, 0, 0, 0 ), "UnlockFile 100,0 failed\n" );
1612
1613     CloseHandle( handle );
1614     DeleteFileA( filename );
1615 }
1616
1617 static BOOL create_fake_dll( LPCSTR filename )
1618 {
1619     IMAGE_DOS_HEADER *dos;
1620     IMAGE_NT_HEADERS *nt;
1621     IMAGE_SECTION_HEADER *sec;
1622     BYTE *buffer;
1623     DWORD lfanew = sizeof(*dos);
1624     DWORD size = lfanew + sizeof(*nt) + sizeof(*sec);
1625     DWORD written;
1626     BOOL ret;
1627
1628     HANDLE file = CreateFileA( filename, GENERIC_READ|GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0 );
1629     if (file == INVALID_HANDLE_VALUE) return FALSE;
1630
1631     buffer = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size );
1632
1633     dos = (IMAGE_DOS_HEADER *)buffer;
1634     dos->e_magic    = IMAGE_DOS_SIGNATURE;
1635     dos->e_cblp     = sizeof(*dos);
1636     dos->e_cp       = 1;
1637     dos->e_cparhdr  = lfanew / 16;
1638     dos->e_minalloc = 0;
1639     dos->e_maxalloc = 0xffff;
1640     dos->e_ss       = 0x0000;
1641     dos->e_sp       = 0x00b8;
1642     dos->e_lfarlc   = lfanew;
1643     dos->e_lfanew   = lfanew;
1644
1645     nt = (IMAGE_NT_HEADERS *)(buffer + lfanew);
1646     nt->Signature = IMAGE_NT_SIGNATURE;
1647 #if defined __i386__
1648     nt->FileHeader.Machine = IMAGE_FILE_MACHINE_I386;
1649 #elif defined __x86_64__
1650     nt->FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64;
1651 #elif defined __powerpc__
1652     nt->FileHeader.Machine = IMAGE_FILE_MACHINE_POWERPC;
1653 #else
1654 # error You must specify the machine type
1655 #endif
1656     nt->FileHeader.NumberOfSections = 1;
1657     nt->FileHeader.SizeOfOptionalHeader = IMAGE_SIZEOF_NT_OPTIONAL_HEADER;
1658     nt->FileHeader.Characteristics = IMAGE_FILE_DLL | IMAGE_FILE_EXECUTABLE_IMAGE;
1659     nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR_MAGIC;
1660     nt->OptionalHeader.MajorLinkerVersion = 1;
1661     nt->OptionalHeader.MinorLinkerVersion = 0;
1662     nt->OptionalHeader.ImageBase = 0x10000000;
1663     nt->OptionalHeader.SectionAlignment = 0x1000;
1664     nt->OptionalHeader.FileAlignment = 0x1000;
1665     nt->OptionalHeader.MajorOperatingSystemVersion = 1;
1666     nt->OptionalHeader.MinorOperatingSystemVersion = 0;
1667     nt->OptionalHeader.MajorImageVersion = 1;
1668     nt->OptionalHeader.MinorImageVersion = 0;
1669     nt->OptionalHeader.MajorSubsystemVersion = 4;
1670     nt->OptionalHeader.MinorSubsystemVersion = 0;
1671     nt->OptionalHeader.SizeOfImage = 0x2000;
1672     nt->OptionalHeader.SizeOfHeaders = size;
1673     nt->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_GUI;
1674     nt->OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
1675
1676     sec = (IMAGE_SECTION_HEADER *)(nt + 1);
1677     memcpy( sec->Name, ".rodata", sizeof(".rodata") );
1678     sec->Misc.VirtualSize = 0x1000;
1679     sec->VirtualAddress   = 0x1000;
1680     sec->SizeOfRawData    = 0;
1681     sec->PointerToRawData = 0;
1682     sec->Characteristics  = IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE;
1683
1684     ret = WriteFile( file, buffer, size, &written, NULL ) && written == size;
1685     HeapFree( GetProcessHeap(), 0, buffer );
1686     CloseHandle( file );
1687     return ret;
1688 }
1689
1690 static int is_sharing_compatible( DWORD access1, DWORD sharing1, DWORD access2, DWORD sharing2, BOOL is_win9x )
1691 {
1692     if (!is_win9x)
1693     {
1694         if (!access1) sharing1 = FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE;
1695         if (!access2) sharing2 = FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE;
1696     }
1697     else
1698     {
1699         access1 &= ~DELETE;
1700         if (!access1) access1 = GENERIC_READ;
1701
1702         access2 &= ~DELETE;
1703         if (!access2) access2 = GENERIC_READ;
1704     }
1705
1706     if ((access1 & GENERIC_READ) && !(sharing2 & FILE_SHARE_READ)) return 0;
1707     if ((access1 & GENERIC_WRITE) && !(sharing2 & FILE_SHARE_WRITE)) return 0;
1708     if ((access1 & DELETE) && !(sharing2 & FILE_SHARE_DELETE)) return 0;
1709     if ((access2 & GENERIC_READ) && !(sharing1 & FILE_SHARE_READ)) return 0;
1710     if ((access2 & GENERIC_WRITE) && !(sharing1 & FILE_SHARE_WRITE)) return 0;
1711     if ((access2 & DELETE) && !(sharing1 & FILE_SHARE_DELETE)) return 0;
1712     return 1;
1713 }
1714
1715 static int is_sharing_map_compatible( DWORD map_access, DWORD access2, DWORD sharing2 )
1716 {
1717     if ((map_access == PAGE_READWRITE || map_access == PAGE_EXECUTE_READWRITE) &&
1718         !(sharing2 & FILE_SHARE_WRITE)) return 0;
1719     if ((map_access & SEC_IMAGE) && (access2 & GENERIC_WRITE)) return 0;
1720     return 1;
1721 }
1722
1723 static void test_file_sharing(void)
1724 {
1725     static const DWORD access_modes[] =
1726         { 0, GENERIC_READ, GENERIC_WRITE, GENERIC_READ|GENERIC_WRITE,
1727           DELETE, GENERIC_READ|DELETE, GENERIC_WRITE|DELETE, GENERIC_READ|GENERIC_WRITE|DELETE };
1728     static const DWORD sharing_modes[] =
1729         { 0, FILE_SHARE_READ,
1730           FILE_SHARE_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
1731           FILE_SHARE_DELETE, FILE_SHARE_READ|FILE_SHARE_DELETE,
1732           FILE_SHARE_WRITE|FILE_SHARE_DELETE, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE };
1733     static const DWORD mapping_modes[] =
1734         { PAGE_READONLY, PAGE_WRITECOPY, PAGE_READWRITE, SEC_IMAGE | PAGE_WRITECOPY };
1735     int a1, s1, a2, s2;
1736     int ret;
1737     HANDLE h, h2;
1738     BOOL is_win9x = FALSE;
1739
1740     /* make sure the file exists */
1741     if (!create_fake_dll( filename ))
1742     {
1743         ok(0, "couldn't create file \"%s\" (err=%d)\n", filename, GetLastError());
1744         return;
1745     }
1746     is_win9x = GetFileAttributesW(filenameW) == INVALID_FILE_ATTRIBUTES;
1747
1748     for (a1 = 0; a1 < sizeof(access_modes)/sizeof(access_modes[0]); a1++)
1749     {
1750         for (s1 = 0; s1 < sizeof(sharing_modes)/sizeof(sharing_modes[0]); s1++)
1751         {
1752             /* Win9x doesn't support FILE_SHARE_DELETE */
1753             if (is_win9x && (sharing_modes[s1] & FILE_SHARE_DELETE))
1754                 continue;
1755
1756             SetLastError(0xdeadbeef);
1757             h = CreateFileA( filename, access_modes[a1], sharing_modes[s1],
1758                              NULL, OPEN_EXISTING, 0, 0 );
1759             if (h == INVALID_HANDLE_VALUE)
1760             {
1761                 ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
1762                 return;
1763             }
1764             for (a2 = 0; a2 < sizeof(access_modes)/sizeof(access_modes[0]); a2++)
1765             {
1766                 for (s2 = 0; s2 < sizeof(sharing_modes)/sizeof(sharing_modes[0]); s2++)
1767                 {
1768                     /* Win9x doesn't support FILE_SHARE_DELETE */
1769                     if (is_win9x && (sharing_modes[s2] & FILE_SHARE_DELETE))
1770                         continue;
1771
1772                     SetLastError(0xdeadbeef);
1773                     h2 = CreateFileA( filename, access_modes[a2], sharing_modes[s2],
1774                                       NULL, OPEN_EXISTING, 0, 0 );
1775                     ret = GetLastError();
1776                     if (is_sharing_compatible( access_modes[a1], sharing_modes[s1],
1777                                                access_modes[a2], sharing_modes[s2], is_win9x ))
1778                     {
1779                         ok( h2 != INVALID_HANDLE_VALUE,
1780                             "open failed for modes %x/%x/%x/%x\n",
1781                             access_modes[a1], sharing_modes[s1],
1782                             access_modes[a2], sharing_modes[s2] );
1783                         ok( ret == 0xdeadbeef /* Win9x */ ||
1784                             ret == 0, /* XP */
1785                              "wrong error code %d\n", ret );
1786                     }
1787                     else
1788                     {
1789                         ok( h2 == INVALID_HANDLE_VALUE,
1790                             "open succeeded for modes %x/%x/%x/%x\n",
1791                             access_modes[a1], sharing_modes[s1],
1792                             access_modes[a2], sharing_modes[s2] );
1793                          ok( ret == ERROR_SHARING_VIOLATION,
1794                              "wrong error code %d\n", ret );
1795                     }
1796                     if (h2 != INVALID_HANDLE_VALUE) CloseHandle( h2 );
1797                 }
1798             }
1799             CloseHandle( h );
1800         }
1801     }
1802
1803     for (a1 = 0; a1 < sizeof(mapping_modes)/sizeof(mapping_modes[0]); a1++)
1804     {
1805         HANDLE m;
1806
1807         create_fake_dll( filename );
1808         SetLastError(0xdeadbeef);
1809         h = CreateFileA( filename, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0 );
1810         if (h == INVALID_HANDLE_VALUE)
1811         {
1812             ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
1813             return;
1814         }
1815         m = CreateFileMappingA( h, NULL, mapping_modes[a1], 0, 0, NULL );
1816         ok( m != 0, "failed to create mapping %x err %u\n", mapping_modes[a1], GetLastError() );
1817         CloseHandle( h );
1818         if (!m) continue;
1819
1820         for (a2 = 0; a2 < sizeof(access_modes)/sizeof(access_modes[0]); a2++)
1821         {
1822             for (s2 = 0; s2 < sizeof(sharing_modes)/sizeof(sharing_modes[0]); s2++)
1823             {
1824                 /* Win9x doesn't support FILE_SHARE_DELETE */
1825                 if (is_win9x && (sharing_modes[s2] & FILE_SHARE_DELETE))
1826                     continue;
1827
1828                 SetLastError(0xdeadbeef);
1829                 h2 = CreateFileA( filename, access_modes[a2], sharing_modes[s2],
1830                                   NULL, OPEN_EXISTING, 0, 0 );
1831
1832                 ret = GetLastError();
1833                 if (h2 == INVALID_HANDLE_VALUE)
1834                 {
1835                     if (is_sharing_map_compatible(mapping_modes[a1], access_modes[a2], sharing_modes[s2]))
1836                         ok( is_win9x, /* there's no sharing at all with a mapping on win9x */
1837                             "open failed for modes map %x/%x/%x\n",
1838                             mapping_modes[a1], access_modes[a2], sharing_modes[s2] );
1839                     ok( ret == ERROR_SHARING_VIOLATION,
1840                         "wrong error code %d\n", ret );
1841                 }
1842                 else
1843                 {
1844                     if (!is_sharing_map_compatible(mapping_modes[a1], access_modes[a2], sharing_modes[s2]))
1845                         ok( broken(1),  /* no checking on nt4 */
1846                             "open succeeded for modes map %x/%x/%x\n",
1847                             mapping_modes[a1], access_modes[a2], sharing_modes[s2] );
1848                     ok( ret == 0xdeadbeef /* Win9x */ ||
1849                         ret == 0, /* XP */
1850                         "wrong error code %d\n", ret );
1851                     CloseHandle( h2 );
1852                 }
1853             }
1854         }
1855
1856         /* try CREATE_ALWAYS over an existing mapping */
1857         SetLastError(0xdeadbeef);
1858         h2 = CreateFileA( filename, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
1859                           NULL, CREATE_ALWAYS, 0, 0 );
1860         ret = GetLastError();
1861         if ((mapping_modes[a1] & SEC_IMAGE) || is_win9x)
1862         {
1863             ok( h2 == INVALID_HANDLE_VALUE, "create succeeded for map %x\n", mapping_modes[a1] );
1864             ok( ret == ERROR_SHARING_VIOLATION, "wrong error code %d for %x\n", ret, mapping_modes[a1] );
1865         }
1866         else
1867         {
1868             ok( h2 == INVALID_HANDLE_VALUE, "create succeeded for map %x\n", mapping_modes[a1] );
1869             ok( ret == ERROR_USER_MAPPED_FILE, "wrong error code %d for %x\n", ret, mapping_modes[a1] );
1870         }
1871         if (h2 != INVALID_HANDLE_VALUE) CloseHandle( h2 );
1872
1873         /* try DELETE_ON_CLOSE over an existing mapping */
1874         SetLastError(0xdeadbeef);
1875         h2 = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
1876                           NULL, OPEN_EXISTING, FILE_FLAG_DELETE_ON_CLOSE, 0 );
1877         ret = GetLastError();
1878         if (is_win9x)
1879         {
1880             ok( h2 == INVALID_HANDLE_VALUE, "create succeeded for map %x\n", mapping_modes[a1] );
1881             ok( ret == ERROR_SHARING_VIOLATION, "wrong error code %d for %x\n", ret, mapping_modes[a1] );
1882         }
1883         else if (mapping_modes[a1] & SEC_IMAGE)
1884         {
1885             ok( h2 == INVALID_HANDLE_VALUE, "create succeeded for map %x\n", mapping_modes[a1] );
1886             ok( ret == ERROR_ACCESS_DENIED, "wrong error code %d for %x\n", ret, mapping_modes[a1] );
1887         }
1888         else
1889         {
1890             ok( h2 != INVALID_HANDLE_VALUE, "open failed for map %x err %u\n", mapping_modes[a1], ret );
1891         }
1892         if (h2 != INVALID_HANDLE_VALUE) CloseHandle( h2 );
1893
1894         CloseHandle( m );
1895     }
1896
1897     SetLastError(0xdeadbeef);
1898     h = CreateFileA( filename, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, 0, 0 );
1899     ok( h != INVALID_HANDLE_VALUE, "CreateFileA error %d\n", GetLastError() );
1900
1901     SetLastError(0xdeadbeef);
1902     h2 = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
1903     ok( h2 == INVALID_HANDLE_VALUE, "CreateFileA should fail\n");
1904     ok( GetLastError() == ERROR_SHARING_VIOLATION, "wrong error code %d\n", GetLastError() );
1905
1906     h2 = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0 );
1907     ok( h2 != INVALID_HANDLE_VALUE, "CreateFileA error %d\n", GetLastError() );
1908
1909     CloseHandle(h);
1910     CloseHandle(h2);
1911
1912     DeleteFileA( filename );
1913 }
1914
1915 static char get_windows_drive(void)
1916 {
1917     char windowsdir[MAX_PATH];
1918     GetWindowsDirectory(windowsdir, sizeof(windowsdir));
1919     return windowsdir[0];
1920 }
1921
1922 static void test_FindFirstFileA(void)
1923 {
1924     HANDLE handle;
1925     WIN32_FIND_DATAA data;
1926     int err;
1927     char buffer[5] = "C:\\";
1928     char buffer2[100];
1929     char nonexistent[MAX_PATH];
1930
1931     /* try FindFirstFileA on "C:\" */
1932     buffer[0] = get_windows_drive();
1933     
1934     SetLastError( 0xdeadbeaf );
1935     handle = FindFirstFileA(buffer, &data);
1936     err = GetLastError();
1937     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on root directory should fail\n" );
1938     ok ( err == ERROR_FILE_NOT_FOUND, "Bad Error number %d\n", err );
1939
1940     /* try FindFirstFileA on "C:\*" */
1941     strcpy(buffer2, buffer);
1942     strcat(buffer2, "*");
1943     handle = FindFirstFileA(buffer2, &data);
1944     ok ( handle != INVALID_HANDLE_VALUE, "FindFirstFile on %s should succeed\n", buffer2 );
1945     ok ( strcmp( data.cFileName, "." ) && strcmp( data.cFileName, ".." ),
1946          "FindFirstFile shouldn't return '%s' in drive root\n", data.cFileName );
1947     if (FindNextFileA( handle, &data ))
1948         ok ( strcmp( data.cFileName, "." ) && strcmp( data.cFileName, ".." ),
1949              "FindNextFile shouldn't return '%s' in drive root\n", data.cFileName );
1950     ok ( FindClose(handle) == TRUE, "Failed to close handle %s\n", buffer2 );
1951
1952     /* try FindFirstFileA on windows dir */
1953     GetWindowsDirectory( buffer2, sizeof(buffer2) );
1954     strcat(buffer2, "\\*");
1955     handle = FindFirstFileA(buffer2, &data);
1956     ok( handle != INVALID_HANDLE_VALUE, "FindFirstFile on %s should succeed\n", buffer2 );
1957     ok( !strcmp( data.cFileName, "." ), "FindFirstFile should return '.' first\n" );
1958     ok( FindNextFileA( handle, &data ), "FindNextFile failed\n" );
1959     ok( !strcmp( data.cFileName, ".." ), "FindNextFile should return '..' as second entry\n" );
1960     while (FindNextFileA( handle, &data ))
1961         ok ( strcmp( data.cFileName, "." ) && strcmp( data.cFileName, ".." ),
1962              "FindNextFile shouldn't return '%s'\n", data.cFileName );
1963     ok ( FindClose(handle) == TRUE, "Failed to close handle %s\n", buffer2 );
1964
1965     /* try FindFirstFileA on "C:\foo\" */
1966     SetLastError( 0xdeadbeaf );
1967     if (!GetTempFileNameA( buffer, "foo", 0, nonexistent ) && GetLastError() == ERROR_ACCESS_DENIED)
1968     {
1969         char tmp[MAX_PATH];
1970         GetTempPathA( sizeof(tmp), tmp );
1971         GetTempFileNameA( tmp, "foo", 0, nonexistent );
1972     }
1973     DeleteFileA( nonexistent );
1974     strcpy(buffer2, nonexistent);
1975     strcat(buffer2, "\\");
1976     handle = FindFirstFileA(buffer2, &data);
1977     err = GetLastError();
1978     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
1979     todo_wine {
1980         ok ( err == ERROR_PATH_NOT_FOUND, "Bad Error number %d\n", err );
1981     }
1982
1983     /* try FindFirstFileA on "C:\foo\bar.txt" */
1984     SetLastError( 0xdeadbeaf );
1985     strcpy(buffer2, nonexistent);
1986     strcat(buffer2, "\\bar.txt");
1987     handle = FindFirstFileA(buffer2, &data);
1988     err = GetLastError();
1989     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
1990     ok ( err == ERROR_PATH_NOT_FOUND, "Bad Error number %d\n", err );
1991
1992     /* try FindFirstFileA on "C:\foo\*.*" */
1993     SetLastError( 0xdeadbeaf );
1994     strcpy(buffer2, nonexistent);
1995     strcat(buffer2, "\\*.*");
1996     handle = FindFirstFileA(buffer2, &data);
1997     err = GetLastError();
1998     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
1999     ok ( err == ERROR_PATH_NOT_FOUND, "Bad Error number %d\n", err );
2000
2001     /* try FindFirstFileA on "foo\bar.txt" */
2002     SetLastError( 0xdeadbeaf );
2003     strcpy(buffer2, nonexistent + 3);
2004     strcat(buffer2, "\\bar.txt");
2005     handle = FindFirstFileA(buffer2, &data);
2006     err = GetLastError();
2007     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
2008     ok ( err == ERROR_PATH_NOT_FOUND, "Bad Error number %d\n", err );
2009
2010     /* try FindFirstFileA on "c:\nul" */
2011     SetLastError( 0xdeadbeaf );
2012     strcpy(buffer2, buffer);
2013     strcat(buffer2, "nul");
2014     handle = FindFirstFileA(buffer2, &data);
2015     err = GetLastError();
2016     ok( handle != INVALID_HANDLE_VALUE, "FindFirstFile on %s failed\n", buffer2 );
2017     ok( 0 == lstrcmpiA(data.cFileName, "nul"), "wrong name %s\n", data.cFileName );
2018     ok( FILE_ATTRIBUTE_ARCHIVE == data.dwFileAttributes ||
2019         FILE_ATTRIBUTE_DEVICE == data.dwFileAttributes /* Win9x */,
2020         "wrong attributes %x\n", data.dwFileAttributes );
2021     if (data.dwFileAttributes == FILE_ATTRIBUTE_ARCHIVE)
2022     {
2023         ok( 0 == data.nFileSizeHigh, "wrong size %d\n", data.nFileSizeHigh );
2024         ok( 0 == data.nFileSizeLow, "wrong size %d\n", data.nFileSizeLow );
2025     }
2026     SetLastError( 0xdeadbeaf );
2027     ok( !FindNextFileA( handle, &data ), "FindNextFileA succeeded\n" );
2028     ok( GetLastError() == ERROR_NO_MORE_FILES, "bad error %d\n", GetLastError() );
2029     ok( FindClose( handle ), "failed to close handle\n" );
2030
2031     /* try FindFirstFileA on "lpt1" */
2032     SetLastError( 0xdeadbeaf );
2033     strcpy(buffer2, "lpt1");
2034     handle = FindFirstFileA(buffer2, &data);
2035     err = GetLastError();
2036     ok( handle != INVALID_HANDLE_VALUE, "FindFirstFile on %s failed\n", buffer2 );
2037     ok( 0 == lstrcmpiA(data.cFileName, "lpt1"), "wrong name %s\n", data.cFileName );
2038     ok( FILE_ATTRIBUTE_ARCHIVE == data.dwFileAttributes ||
2039         FILE_ATTRIBUTE_DEVICE == data.dwFileAttributes /* Win9x */,
2040         "wrong attributes %x\n", data.dwFileAttributes );
2041     if (data.dwFileAttributes == FILE_ATTRIBUTE_ARCHIVE)
2042     {
2043         ok( 0 == data.nFileSizeHigh, "wrong size %d\n", data.nFileSizeHigh );
2044         ok( 0 == data.nFileSizeLow, "wrong size %d\n", data.nFileSizeLow );
2045     }
2046     SetLastError( 0xdeadbeaf );
2047     ok( !FindNextFileA( handle, &data ), "FindNextFileA succeeded\n" );
2048     ok( GetLastError() == ERROR_NO_MORE_FILES, "bad error %d\n", GetLastError() );
2049     ok( FindClose( handle ), "failed to close handle\n" );
2050
2051     /* try FindFirstFileA on "c:\nul\*" */
2052     SetLastError( 0xdeadbeaf );
2053     strcpy(buffer2, buffer);
2054     strcat(buffer2, "nul\\*");
2055     handle = FindFirstFileA(buffer2, &data);
2056     err = GetLastError();
2057     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
2058     ok ( err == ERROR_PATH_NOT_FOUND, "Bad Error number %d\n", err );
2059
2060     /* try FindFirstFileA on "c:\nul*" */
2061     SetLastError( 0xdeadbeaf );
2062     strcpy(buffer2, buffer);
2063     strcat(buffer2, "nul*");
2064     handle = FindFirstFileA(buffer2, &data);
2065     err = GetLastError();
2066     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
2067     ok ( err == ERROR_FILE_NOT_FOUND, "Bad Error number %d\n", err );
2068
2069     /* try FindFirstFileA on "c:\foo\bar\nul" */
2070     SetLastError( 0xdeadbeaf );
2071     strcpy(buffer2, buffer);
2072     strcat(buffer2, "foo\\bar\\nul");
2073     handle = FindFirstFileA(buffer2, &data);
2074     err = GetLastError();
2075     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
2076     ok ( err == ERROR_PATH_NOT_FOUND, "Bad Error number %d\n", err );
2077
2078     /* try FindFirstFileA on "c:\foo\nul\bar" */
2079     SetLastError( 0xdeadbeaf );
2080     strcpy(buffer2, buffer);
2081     strcat(buffer2, "foo\\nul\\bar");
2082     handle = FindFirstFileA(buffer2, &data);
2083     err = GetLastError();
2084     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
2085     ok ( err == ERROR_PATH_NOT_FOUND, "Bad Error number %d\n", err );
2086 }
2087
2088 static void test_FindNextFileA(void)
2089 {
2090     HANDLE handle;
2091     WIN32_FIND_DATAA search_results;
2092     int err;
2093     char buffer[5] = "C:\\*";
2094
2095     buffer[0] = get_windows_drive();
2096     handle = FindFirstFileA(buffer,&search_results);
2097     ok ( handle != INVALID_HANDLE_VALUE, "FindFirstFile on C:\\* should succeed\n" );
2098     while (FindNextFile(handle, &search_results))
2099     {
2100         /* get to the end of the files */
2101     }
2102     ok ( FindClose(handle) == TRUE, "Failed to close handle\n");
2103     err = GetLastError();
2104     ok ( err == ERROR_NO_MORE_FILES, "GetLastError should return ERROR_NO_MORE_FILES\n");
2105 }
2106
2107 static void test_FindFirstFileExA(FINDEX_SEARCH_OPS search_ops)
2108 {
2109     WIN32_FIND_DATAA search_results;
2110     HANDLE handle;
2111     BOOL ret;
2112
2113     if (!pFindFirstFileExA)
2114     {
2115         win_skip("FindFirstFileExA() is missing\n");
2116         return;
2117     }
2118
2119     CreateDirectoryA("test-dir", NULL);
2120     _lclose(_lcreat("test-dir\\file1", 0));
2121     _lclose(_lcreat("test-dir\\file2", 0));
2122     CreateDirectoryA("test-dir\\dir1", NULL);
2123     SetLastError(0xdeadbeef);
2124     handle = pFindFirstFileExA("test-dir\\*", FindExInfoStandard, &search_results, search_ops, NULL, 0);
2125     if (handle == INVALID_HANDLE_VALUE && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2126     {
2127         win_skip("FindFirstFileExA is not implemented\n");
2128         goto cleanup;
2129     }
2130     ok(handle != INVALID_HANDLE_VALUE, "FindFirstFile failed (err=%u)\n", GetLastError());
2131     ok(strcmp(search_results.cFileName, ".") == 0, "First entry should be '.', is %s\n", search_results.cFileName);
2132
2133 #define CHECK_NAME(fn) (strcmp((fn), "file1") == 0 || strcmp((fn), "file2") == 0 || strcmp((fn), "dir1") == 0)
2134
2135     ok(FindNextFile(handle, &search_results), "Fetching second file failed\n");
2136     ok(strcmp(search_results.cFileName, "..") == 0, "Second entry should be '..' is %s\n", search_results.cFileName);
2137
2138     ok(FindNextFile(handle, &search_results), "Fetching third file failed\n");
2139     ok(CHECK_NAME(search_results.cFileName), "Invalid third entry - %s\n", search_results.cFileName);
2140
2141     SetLastError(0xdeadbeef);
2142     ret = FindNextFile(handle, &search_results);
2143     if (!ret && (GetLastError() == ERROR_NO_MORE_FILES) && (search_ops == FindExSearchLimitToDirectories))
2144     {
2145         skip("File system supports directory filtering\n");
2146         /* Results from the previous call are not cleared */
2147         ok(strcmp(search_results.cFileName, "dir1") == 0, "Third entry should be 'dir1' is %s\n", search_results.cFileName);
2148         FindClose( handle );
2149         goto cleanup;
2150     }
2151
2152     ok(ret, "Fetching fourth file failed\n");
2153     ok(CHECK_NAME(search_results.cFileName), "Invalid fourth entry - %s\n", search_results.cFileName);
2154
2155     ok(FindNextFile(handle, &search_results), "Fetching fifth file failed\n");
2156     ok(CHECK_NAME(search_results.cFileName), "Invalid fifth entry - %s\n", search_results.cFileName);
2157
2158 #undef CHECK_NAME
2159
2160     ok(FindNextFile(handle, &search_results) == FALSE, "Fetching sixth file should fail\n");
2161
2162     FindClose( handle );
2163
2164 cleanup:
2165     DeleteFileA("test-dir\\file1");
2166     DeleteFileA("test-dir\\file2");
2167     RemoveDirectoryA("test-dir\\dir1");
2168     RemoveDirectoryA("test-dir");
2169 }
2170
2171 static int test_Mapfile_createtemp(HANDLE *handle)
2172 {
2173     SetFileAttributesA(filename,FILE_ATTRIBUTE_NORMAL);
2174     DeleteFile(filename);
2175     *handle = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, 0,
2176                          CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2177     if (*handle != INVALID_HANDLE_VALUE) {
2178
2179         return 1;
2180     }
2181
2182     return 0;
2183 }
2184
2185 static void test_MapFile(void)
2186 {
2187     HANDLE handle;
2188     HANDLE hmap;
2189
2190     ok(test_Mapfile_createtemp(&handle), "Couldn't create test file.\n");
2191
2192     hmap = CreateFileMapping( handle, NULL, PAGE_READWRITE, 0, 0x1000, "named_file_map" );
2193     ok( hmap != NULL, "mapping should work, I named it!\n" );
2194
2195     ok( CloseHandle( hmap ), "can't close mapping handle\n");
2196
2197     /* We have to close file before we try new stuff with mapping again.
2198        Else we would always succeed on XP or block descriptors on 95. */
2199     hmap = CreateFileMapping( handle, NULL, PAGE_READWRITE, 0, 0, NULL );
2200     ok( hmap != NULL, "We should still be able to map!\n" );
2201     ok( CloseHandle( hmap ), "can't close mapping handle\n");
2202     ok( CloseHandle( handle ), "can't close file handle\n");
2203     handle = NULL;
2204
2205     ok(test_Mapfile_createtemp(&handle), "Couldn't create test file.\n");
2206
2207     hmap = CreateFileMapping( handle, NULL, PAGE_READWRITE, 0, 0, NULL );
2208     ok( hmap == NULL, "mapped zero size file\n");
2209     ok( GetLastError() == ERROR_FILE_INVALID, "not ERROR_FILE_INVALID\n");
2210
2211     hmap = CreateFileMapping( handle, NULL, PAGE_READWRITE, 0x80000000, 0, NULL );
2212     ok( hmap == NULL || broken(hmap != NULL) /* NT4 */, "mapping should fail\n");
2213     /* GetLastError() varies between win9x and WinNT and also depends on the filesystem */
2214     if ( hmap )
2215         CloseHandle( hmap );
2216
2217     hmap = CreateFileMapping( handle, NULL, PAGE_READWRITE, 0x80000000, 0x10000, NULL );
2218     ok( hmap == NULL || broken(hmap != NULL) /* NT4 */, "mapping should fail\n");
2219     /* GetLastError() varies between win9x and WinNT and also depends on the filesystem */
2220     if ( hmap )
2221         CloseHandle( hmap );
2222
2223     /* On XP you can now map again, on Win 95 you cannot. */
2224
2225     ok( CloseHandle( handle ), "can't close file handle\n");
2226     ok( DeleteFileA( filename ), "DeleteFile failed after map\n" );
2227 }
2228
2229 static void test_GetFileType(void)
2230 {
2231     DWORD type;
2232     HANDLE h = CreateFileA( filename, GENERIC_READ|GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0 );
2233     ok( h != INVALID_HANDLE_VALUE, "open %s failed\n", filename );
2234     type = GetFileType(h);
2235     ok( type == FILE_TYPE_DISK, "expected type disk got %d\n", type );
2236     CloseHandle( h );
2237     h = CreateFileA( "nul", GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0 );
2238     ok( h != INVALID_HANDLE_VALUE, "open nul failed\n" );
2239     type = GetFileType(h);
2240     ok( type == FILE_TYPE_CHAR, "expected type char for nul got %d\n", type );
2241     CloseHandle( h );
2242     DeleteFileA( filename );
2243 }
2244
2245 static int completion_count;
2246
2247 static void CALLBACK FileIOComplete(DWORD dwError, DWORD dwBytes, LPOVERLAPPED ovl)
2248 {
2249 /*      printf("(%ld, %ld, %p { %ld, %ld, %ld, %ld, %p })\n", dwError, dwBytes, ovl, ovl->Internal, ovl->InternalHigh, ovl->Offset, ovl->OffsetHigh, ovl->hEvent);*/
2250         ReleaseSemaphore(ovl->hEvent, 1, NULL);
2251         completion_count++;
2252 }
2253
2254 static void test_async_file_errors(void)
2255 {
2256     char szFile[MAX_PATH];
2257     HANDLE hSem = CreateSemaphoreW(NULL, 1, 1, NULL);
2258     HANDLE hFile;
2259     LPVOID lpBuffer = HeapAlloc(GetProcessHeap(), 0, 4096);
2260     OVERLAPPED ovl;
2261     S(U(ovl)).Offset = 0;
2262     S(U(ovl)).OffsetHigh = 0;
2263     ovl.hEvent = hSem;
2264     completion_count = 0;
2265     szFile[0] = '\0';
2266     GetWindowsDirectoryA(szFile, sizeof(szFile)/sizeof(szFile[0])-1-strlen("\\win.ini"));
2267     strcat(szFile, "\\win.ini");
2268     hFile = CreateFileA(szFile, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2269                         NULL, OPEN_ALWAYS, FILE_FLAG_OVERLAPPED, NULL);
2270     if (hFile == INVALID_HANDLE_VALUE)  /* win9x doesn't like FILE_SHARE_DELETE */
2271         hFile = CreateFileA(szFile, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
2272                             NULL, OPEN_ALWAYS, FILE_FLAG_OVERLAPPED, NULL);
2273     ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA(%s ...) failed\n", szFile);
2274     while (TRUE)
2275     {
2276         BOOL res;
2277         DWORD count;
2278         while (WaitForSingleObjectEx(hSem, INFINITE, TRUE) == WAIT_IO_COMPLETION)
2279             ;
2280         res = ReadFileEx(hFile, lpBuffer, 4096, &ovl, FileIOComplete);
2281         /*printf("Offset = %ld, result = %s\n", ovl.Offset, res ? "TRUE" : "FALSE");*/
2282         if (!res)
2283             break;
2284         if (!GetOverlappedResult(hFile, &ovl, &count, FALSE))
2285             break;
2286         S(U(ovl)).Offset += count;
2287         /* i/o completion routine only called if ReadFileEx returned success.
2288          * we only care about violations of this rule so undo what should have
2289          * been done */
2290         completion_count--;
2291     }
2292     ok(completion_count == 0, "completion routine should only be called when ReadFileEx succeeds (this rule was violated %d times)\n", completion_count);
2293     /*printf("Error = %ld\n", GetLastError());*/
2294     HeapFree(GetProcessHeap(), 0, lpBuffer);
2295 }
2296
2297 static void test_read_write(void)
2298 {
2299     DWORD bytes, ret, old_prot;
2300     HANDLE hFile;
2301     char temp_path[MAX_PATH];
2302     char filename[MAX_PATH];
2303     char *mem;
2304     static const char prefix[] = "pfx";
2305
2306     ret = GetTempPathA(MAX_PATH, temp_path);
2307     ok(ret != 0, "GetTempPathA error %d\n", GetLastError());
2308     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
2309
2310     ret = GetTempFileNameA(temp_path, prefix, 0, filename);
2311     ok(ret != 0, "GetTempFileNameA error %d\n", GetLastError());
2312
2313     hFile = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE, 0, NULL,
2314                         CREATE_ALWAYS, FILE_FLAG_RANDOM_ACCESS, 0);
2315     ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA: error %d\n", GetLastError());
2316
2317     SetLastError(12345678);
2318     bytes = 12345678;
2319     ret = WriteFile(hFile, NULL, 0, &bytes, NULL);
2320     ok(ret && GetLastError() == 12345678,
2321         "ret = %d, error %d\n", ret, GetLastError());
2322     ok(!bytes, "bytes = %d\n", bytes);
2323
2324     SetLastError(12345678);
2325     bytes = 12345678;
2326     ret = WriteFile(hFile, NULL, 10, &bytes, NULL);
2327     ok((!ret && GetLastError() == ERROR_INVALID_USER_BUFFER) || /* Win2k */
2328         (ret && GetLastError() == 12345678), /* Win9x */
2329         "ret = %d, error %d\n", ret, GetLastError());
2330     ok(!bytes || /* Win2k */
2331         bytes == 10, /* Win9x */
2332         "bytes = %d\n", bytes);
2333
2334     /* make sure the file contains data */
2335     WriteFile(hFile, "this is the test data", 21, &bytes, NULL);
2336     SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
2337
2338     SetLastError(12345678);
2339     bytes = 12345678;
2340     ret = ReadFile(hFile, NULL, 0, &bytes, NULL);
2341     ok(ret && GetLastError() == 12345678,
2342         "ret = %d, error %d\n", ret, GetLastError());
2343     ok(!bytes, "bytes = %d\n", bytes);
2344
2345     SetLastError(12345678);
2346     bytes = 12345678;
2347     ret = ReadFile(hFile, NULL, 10, &bytes, NULL);
2348     ok(!ret && (GetLastError() == ERROR_NOACCESS || /* Win2k */
2349                 GetLastError() == ERROR_INVALID_PARAMETER), /* Win9x */
2350         "ret = %d, error %d\n", ret, GetLastError());
2351     ok(!bytes, "bytes = %d\n", bytes);
2352
2353     /* test passing protected memory as buffer */
2354
2355     mem = VirtualAlloc( NULL, 0x4000, MEM_COMMIT, PAGE_READWRITE );
2356     ok( mem != NULL, "failed to allocate virtual mem error %u\n", GetLastError() );
2357
2358     ret = WriteFile( hFile, mem, 0x4000, &bytes, NULL );
2359     ok( ret, "WriteFile failed error %u\n", GetLastError() );
2360     ok( bytes == 0x4000, "only wrote %x bytes\n", bytes );
2361
2362     ret = VirtualProtect( mem + 0x2000, 0x2000, PAGE_NOACCESS, &old_prot );
2363     ok( ret, "VirtualProtect failed error %u\n", GetLastError() );
2364
2365     ret = WriteFile( hFile, mem, 0x4000, &bytes, NULL );
2366     ok( !ret, "WriteFile succeeded\n" );
2367     ok( GetLastError() == ERROR_INVALID_USER_BUFFER ||
2368         GetLastError() == ERROR_INVALID_PARAMETER,  /* win9x */
2369         "wrong error %u\n", GetLastError() );
2370     ok( bytes == 0, "wrote %x bytes\n", bytes );
2371
2372     ret = WriteFile( (HANDLE)0xdead, mem, 0x4000, &bytes, NULL );
2373     ok( !ret, "WriteFile succeeded\n" );
2374     ok( GetLastError() == ERROR_INVALID_HANDLE || /* handle is checked before buffer on NT */
2375         GetLastError() == ERROR_INVALID_PARAMETER,  /* win9x */
2376         "wrong error %u\n", GetLastError() );
2377     ok( bytes == 0, "wrote %x bytes\n", bytes );
2378
2379     ret = VirtualProtect( mem, 0x2000, PAGE_NOACCESS, &old_prot );
2380     ok( ret, "VirtualProtect failed error %u\n", GetLastError() );
2381
2382     ret = WriteFile( hFile, mem, 0x4000, &bytes, NULL );
2383     ok( !ret, "WriteFile succeeded\n" );
2384     ok( GetLastError() == ERROR_INVALID_USER_BUFFER ||
2385         GetLastError() == ERROR_INVALID_PARAMETER,  /* win9x */
2386         "wrong error %u\n", GetLastError() );
2387     ok( bytes == 0, "wrote %x bytes\n", bytes );
2388
2389     SetFilePointer( hFile, 0, NULL, FILE_BEGIN );
2390
2391     ret = ReadFile( hFile, mem, 0x4000, &bytes, NULL );
2392     ok( !ret, "ReadFile succeeded\n" );
2393     ok( GetLastError() == ERROR_NOACCESS ||
2394         GetLastError() == ERROR_INVALID_PARAMETER,  /* win9x */
2395         "wrong error %u\n", GetLastError() );
2396     ok( bytes == 0, "read %x bytes\n", bytes );
2397
2398     ret = VirtualProtect( mem, 0x2000, PAGE_READONLY, &old_prot );
2399     ok( ret, "VirtualProtect failed error %u\n", GetLastError() );
2400
2401     ret = ReadFile( hFile, mem, 0x4000, &bytes, NULL );
2402     ok( !ret, "ReadFile succeeded\n" );
2403     ok( GetLastError() == ERROR_NOACCESS ||
2404         GetLastError() == ERROR_INVALID_PARAMETER,  /* win9x */
2405         "wrong error %u\n", GetLastError() );
2406     ok( bytes == 0, "read %x bytes\n", bytes );
2407
2408     ret = VirtualProtect( mem, 0x2000, PAGE_READWRITE, &old_prot );
2409     ok( ret, "VirtualProtect failed error %u\n", GetLastError() );
2410
2411     ret = ReadFile( hFile, mem, 0x4000, &bytes, NULL );
2412     ok( !ret, "ReadFile succeeded\n" );
2413     ok( GetLastError() == ERROR_NOACCESS ||
2414         GetLastError() == ERROR_INVALID_PARAMETER,  /* win9x */
2415         "wrong error %u\n", GetLastError() );
2416     ok( bytes == 0, "read %x bytes\n", bytes );
2417
2418     SetFilePointer( hFile, 0x1234, NULL, FILE_BEGIN );
2419     SetEndOfFile( hFile );
2420     SetFilePointer( hFile, 0, NULL, FILE_BEGIN );
2421
2422     ret = ReadFile( hFile, mem, 0x4000, &bytes, NULL );
2423     ok( !ret, "ReadFile succeeded\n" );
2424     ok( GetLastError() == ERROR_NOACCESS ||
2425         GetLastError() == ERROR_INVALID_PARAMETER,  /* win9x */
2426         "wrong error %u\n", GetLastError() );
2427     ok( bytes == 0, "read %x bytes\n", bytes );
2428
2429     ret = ReadFile( hFile, mem, 0x2000, &bytes, NULL );
2430     ok( ret, "ReadFile failed error %u\n", GetLastError() );
2431     ok( bytes == 0x1234, "read %x bytes\n", bytes );
2432
2433     ret = ReadFile( hFile, NULL, 1, &bytes, NULL );
2434     ok( !ret, "ReadFile succeeded\n" );
2435     ok( GetLastError() == ERROR_NOACCESS ||
2436         GetLastError() == ERROR_INVALID_PARAMETER,  /* win9x */
2437         "wrong error %u\n", GetLastError() );
2438     ok( bytes == 0, "read %x bytes\n", bytes );
2439
2440     VirtualFree( mem, 0, MEM_FREE );
2441
2442     ret = CloseHandle(hFile);
2443     ok( ret, "CloseHandle: error %d\n", GetLastError());
2444     ret = DeleteFileA(filename);
2445     ok( ret, "DeleteFileA: error %d\n", GetLastError());
2446 }
2447
2448 static void test_OpenFile(void)
2449 {
2450     HFILE hFile;
2451     OFSTRUCT ofs;
2452     BOOL ret;
2453     DWORD retval;
2454     
2455     static const char file[] = "regedit.exe";
2456     static const char foo[] = ".\\foo-bar-foo.baz";
2457     static const char *foo_too_long = ".\\foo-bar-foo.baz+++++++++++++++"
2458         "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
2459         "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
2460         "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
2461         "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
2462         "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2463     char buff[MAX_PATH];
2464     char buff_long[4*MAX_PATH];
2465     char filled_0xA5[OFS_MAXPATHNAME];
2466     char *p;
2467     UINT length;
2468     
2469     /* Check for existing file */
2470     if (!pGetSystemWindowsDirectoryA)
2471         length = GetWindowsDirectoryA(buff, MAX_PATH);
2472     else
2473         length = pGetSystemWindowsDirectoryA(buff, MAX_PATH);
2474
2475     if (length + sizeof(file) < MAX_PATH)
2476     {
2477         p = buff + strlen(buff);
2478         if (p > buff && p[-1] != '\\') *p++ = '\\';
2479         strcpy( p, file );
2480         memset(&ofs, 0xA5, sizeof(ofs));
2481         SetLastError(0xfaceabee);
2482
2483         hFile = OpenFile(buff, &ofs, OF_EXIST);
2484         ok( hFile == TRUE, "%s not found : %d\n", buff, GetLastError() );
2485         ok( GetLastError() == 0xfaceabee || GetLastError() == ERROR_SUCCESS, 
2486             "GetLastError() returns %d\n", GetLastError() );
2487         ok( ofs.cBytes == sizeof(ofs), "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
2488         ok( ofs.nErrCode == ERROR_SUCCESS, "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
2489         ok( lstrcmpiA(ofs.szPathName, buff) == 0,
2490             "OpenFile returned '%s', but was expected to return '%s' or string filled with 0xA5\n",
2491             ofs.szPathName, buff );
2492     }
2493
2494     memset(&filled_0xA5, 0xA5, OFS_MAXPATHNAME);
2495     length = GetCurrentDirectoryA(MAX_PATH, buff);
2496
2497     /* Check for nonexistent file */
2498     if (length + sizeof(foo) < MAX_PATH)
2499     {
2500         p = buff + strlen(buff);
2501         if (p > buff && p[-1] != '\\') *p++ = '\\';
2502         strcpy( p, foo + 2 );
2503         memset(&ofs, 0xA5, sizeof(ofs));
2504         SetLastError(0xfaceabee);
2505
2506         hFile = OpenFile(foo, &ofs, OF_EXIST);
2507         ok( hFile == HFILE_ERROR, "hFile != HFILE_ERROR : %d\n", GetLastError());
2508         ok( GetLastError() == ERROR_FILE_NOT_FOUND, "GetLastError() returns %d\n", GetLastError() );
2509         todo_wine
2510         ok( ofs.cBytes == 0xA5, "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
2511         ok( ofs.nErrCode == ERROR_FILE_NOT_FOUND, "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
2512         ok( lstrcmpiA(ofs.szPathName, buff) == 0 || strncmp(ofs.szPathName, filled_0xA5, OFS_MAXPATHNAME) == 0,
2513             "OpenFile returned '%s', but was expected to return '%s' or string filled with 0xA5\n", 
2514             ofs.szPathName, buff );
2515     }
2516
2517     length = GetCurrentDirectoryA(MAX_PATH, buff_long);
2518     length += lstrlenA(foo_too_long + 1);
2519
2520     /* Check for nonexistent file with too long filename */ 
2521     if (length >= OFS_MAXPATHNAME && length < sizeof(buff_long)) 
2522     {
2523         lstrcatA(buff_long, foo_too_long + 1); /* Avoid '.' during concatenation */
2524         memset(&ofs, 0xA5, sizeof(ofs));
2525         SetLastError(0xfaceabee);
2526
2527         hFile = OpenFile(foo_too_long, &ofs, OF_EXIST);
2528         ok( hFile == HFILE_ERROR, "hFile != HFILE_ERROR : %d\n", GetLastError());
2529         ok( GetLastError() == ERROR_INVALID_DATA || GetLastError() == ERROR_FILENAME_EXCED_RANGE, 
2530             "GetLastError() returns %d\n", GetLastError() );
2531         todo_wine
2532         ok( ofs.cBytes == 0xA5, "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
2533         ok( ofs.nErrCode == ERROR_INVALID_DATA || ofs.nErrCode == ERROR_FILENAME_EXCED_RANGE,
2534             "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
2535         ok( strncmp(ofs.szPathName, filled_0xA5, OFS_MAXPATHNAME) == 0, 
2536             "OpenFile returned '%s', but was expected to return string filled with 0xA5\n", 
2537             ofs.szPathName );
2538     }
2539
2540     length = GetCurrentDirectoryA(MAX_PATH, buff) + sizeof(filename);
2541
2542     if (length >= MAX_PATH) 
2543     {
2544         trace("Buffer too small, requested length = %d, but MAX_PATH = %d.  Skipping test.\n", length, MAX_PATH);
2545         return;
2546     }
2547     p = buff + strlen(buff);
2548     if (p > buff && p[-1] != '\\') *p++ = '\\';
2549     strcpy( p, filename );
2550
2551     memset(&ofs, 0xA5, sizeof(ofs));
2552     SetLastError(0xfaceabee);
2553     /* Create an empty file */
2554     hFile = OpenFile(filename, &ofs, OF_CREATE);
2555     ok( hFile != HFILE_ERROR, "OpenFile failed to create nonexistent file\n" );
2556     ok( GetLastError() == 0xfaceabee || GetLastError() == ERROR_SUCCESS, 
2557         "GetLastError() returns %d\n", GetLastError() );
2558     ok( ofs.cBytes == sizeof(OFSTRUCT), "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
2559     ok( ofs.nErrCode == ERROR_SUCCESS || broken(ofs.nErrCode != ERROR_SUCCESS) /* win9x */,
2560         "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
2561     ret = _lclose(hFile);
2562     ok( !ret, "_lclose() returns %d\n", ret );
2563     retval = GetFileAttributesA(filename);
2564     ok( retval != INVALID_FILE_ATTRIBUTES, "GetFileAttributesA: error %d\n", GetLastError() );
2565
2566     memset(&ofs, 0xA5, sizeof(ofs));
2567     SetLastError(0xfaceabee);
2568     /* Check various opening options: */
2569     /* for reading only, */
2570     hFile = OpenFile(filename, &ofs, OF_READ);
2571     ok( hFile != HFILE_ERROR, "OpenFile failed on read\n" );
2572     ok( GetLastError() == 0xfaceabee || GetLastError() == ERROR_SUCCESS, 
2573         "GetLastError() returns %d\n", GetLastError() );
2574     ok( ofs.cBytes == sizeof(OFSTRUCT), "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
2575     ok( ofs.nErrCode == ERROR_SUCCESS || broken(ofs.nErrCode != ERROR_SUCCESS) /* win9x */,
2576         "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
2577     ok( lstrcmpiA(ofs.szPathName, buff) == 0,
2578         "OpenFile returned '%s', but was expected to return '%s'\n", ofs.szPathName, buff );
2579     ret = _lclose(hFile);
2580     ok( !ret, "_lclose() returns %d\n", ret );
2581
2582     memset(&ofs, 0xA5, sizeof(ofs));
2583     SetLastError(0xfaceabee);
2584     /* for writing only, */
2585     hFile = OpenFile(filename, &ofs, OF_WRITE);
2586     ok( hFile != HFILE_ERROR, "OpenFile failed on write\n" );
2587     ok( GetLastError() == 0xfaceabee || GetLastError() == ERROR_SUCCESS, 
2588         "GetLastError() returns %d\n", GetLastError() );
2589     ok( ofs.cBytes == sizeof(OFSTRUCT), "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
2590     ok( ofs.nErrCode == ERROR_SUCCESS || broken(ofs.nErrCode != ERROR_SUCCESS) /* win9x */,
2591         "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
2592     ok( lstrcmpiA(ofs.szPathName, buff) == 0,
2593         "OpenFile returned '%s', but was expected to return '%s'\n", ofs.szPathName, buff );
2594     ret = _lclose(hFile);
2595     ok( !ret, "_lclose() returns %d\n", ret );
2596
2597     memset(&ofs, 0xA5, sizeof(ofs));
2598     SetLastError(0xfaceabee);
2599     /* for reading and writing, */
2600     hFile = OpenFile(filename, &ofs, OF_READWRITE);
2601     ok( hFile != HFILE_ERROR, "OpenFile failed on read/write\n" );
2602     ok( GetLastError() == 0xfaceabee || GetLastError() == ERROR_SUCCESS, 
2603         "GetLastError() returns %d\n", GetLastError() );
2604     ok( ofs.cBytes == sizeof(OFSTRUCT), "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
2605     ok( ofs.nErrCode == ERROR_SUCCESS || broken(ofs.nErrCode != ERROR_SUCCESS) /* win9x */,
2606         "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
2607     ok( lstrcmpiA(ofs.szPathName, buff) == 0,
2608         "OpenFile returned '%s', but was expected to return '%s'\n", ofs.szPathName, buff );
2609     ret = _lclose(hFile);
2610     ok( !ret, "_lclose() returns %d\n", ret );
2611
2612     memset(&ofs, 0xA5, sizeof(ofs));
2613     SetLastError(0xfaceabee);
2614     /* for checking file presence. */
2615     hFile = OpenFile(filename, &ofs, OF_EXIST);
2616     ok( hFile == 1, "OpenFile failed on finding our created file\n" );
2617     ok( GetLastError() == 0xfaceabee || GetLastError() == ERROR_SUCCESS, 
2618         "GetLastError() returns %d\n", GetLastError() );
2619     ok( ofs.cBytes == sizeof(OFSTRUCT), "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
2620     ok( ofs.nErrCode == ERROR_SUCCESS || broken(ofs.nErrCode != ERROR_SUCCESS) /* win9x */,
2621         "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
2622     ok( lstrcmpiA(ofs.szPathName, buff) == 0,
2623         "OpenFile returned '%s', but was expected to return '%s'\n", ofs.szPathName, buff );
2624
2625     memset(&ofs, 0xA5, sizeof(ofs));
2626     SetLastError(0xfaceabee);
2627     /* Delete the file and make sure it doesn't exist anymore */
2628     hFile = OpenFile(filename, &ofs, OF_DELETE);
2629     ok( hFile == 1, "OpenFile failed on delete (%d)\n", hFile );
2630     ok( GetLastError() == 0xfaceabee || GetLastError() == ERROR_SUCCESS, 
2631         "GetLastError() returns %d\n", GetLastError() );
2632     ok( ofs.cBytes == sizeof(OFSTRUCT), "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
2633     ok( ofs.nErrCode == ERROR_SUCCESS || broken(ofs.nErrCode != ERROR_SUCCESS) /* win9x */,
2634         "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
2635     ok( lstrcmpiA(ofs.szPathName, buff) == 0,
2636         "OpenFile returned '%s', but was expected to return '%s'\n", ofs.szPathName, buff );
2637
2638     retval = GetFileAttributesA(filename);
2639     ok( retval == INVALID_FILE_ATTRIBUTES, "GetFileAttributesA succeeded on deleted file\n" );
2640 }
2641
2642 static void test_overlapped(void)
2643 {
2644     OVERLAPPED ov;
2645     DWORD r, result;
2646
2647     /* GetOverlappedResult crashes if the 2nd or 3rd param are NULL */
2648     if (0) /* tested: WinXP */
2649     {
2650         GetOverlappedResult(0, NULL, &result, FALSE);
2651         GetOverlappedResult(0, &ov, NULL, FALSE);
2652         GetOverlappedResult(0, NULL, NULL, FALSE);
2653     }
2654
2655     memset( &ov, 0,  sizeof ov );
2656     result = 1;
2657     r = GetOverlappedResult(0, &ov, &result, 0);
2658     if (r)
2659         ok( result == 0, "wrong result %u\n", result );
2660     else  /* win9x */
2661         ok( GetLastError() == ERROR_INVALID_HANDLE, "wrong error %u\n", GetLastError() );
2662
2663     result = 0;
2664     ov.Internal = 0;
2665     ov.InternalHigh = 0xabcd;
2666     r = GetOverlappedResult(0, &ov, &result, 0);
2667     if (r)
2668         ok( result == 0xabcd, "wrong result %u\n", result );
2669     else  /* win9x */
2670         ok( GetLastError() == ERROR_INVALID_HANDLE, "wrong error %u\n", GetLastError() );
2671
2672     SetLastError( 0xb00 );
2673     result = 0;
2674     ov.Internal = STATUS_INVALID_HANDLE;
2675     ov.InternalHigh = 0xabcd;
2676     r = GetOverlappedResult(0, &ov, &result, 0);
2677     ok( GetLastError() == ERROR_INVALID_HANDLE, "wrong error %u\n", GetLastError() );
2678     ok( r == FALSE, "should return false\n");
2679     ok( result == 0xabcd || result == 0 /* win9x */, "wrong result %u\n", result );
2680
2681     SetLastError( 0xb00 );
2682     result = 0;
2683     ov.Internal = STATUS_PENDING;
2684     ov.InternalHigh = 0xabcd;
2685     r = GetOverlappedResult(0, &ov, &result, 0);
2686     ok( GetLastError() == ERROR_IO_INCOMPLETE || GetLastError() == ERROR_INVALID_HANDLE /* win9x */,
2687         "wrong error %u\n", GetLastError() );
2688     ok( r == FALSE, "should return false\n");
2689     ok( result == 0, "wrong result %u\n", result );
2690
2691     SetLastError( 0xb00 );
2692     ov.hEvent = CreateEvent( NULL, 1, 1, NULL );
2693     ov.Internal = STATUS_PENDING;
2694     ov.InternalHigh = 0xabcd;
2695     r = GetOverlappedResult(0, &ov, &result, 0);
2696     ok( GetLastError() == ERROR_IO_INCOMPLETE || GetLastError() == ERROR_INVALID_HANDLE /* win9x */,
2697         "wrong error %u\n", GetLastError() );
2698     ok( r == FALSE, "should return false\n");
2699
2700     ResetEvent( ov.hEvent );
2701
2702     SetLastError( 0xb00 );
2703     ov.Internal = STATUS_PENDING;
2704     ov.InternalHigh = 0;
2705     r = GetOverlappedResult(0, &ov, &result, 0);
2706     ok( GetLastError() == ERROR_IO_INCOMPLETE || GetLastError() == ERROR_INVALID_HANDLE /* win9x */,
2707         "wrong error %u\n", GetLastError() );
2708     ok( r == FALSE, "should return false\n");
2709
2710     r = CloseHandle( ov.hEvent );
2711     ok( r == TRUE, "close handle failed\n");
2712 }
2713
2714 static void test_RemoveDirectory(void)
2715 {
2716     int rc;
2717     char directory[] = "removeme";
2718
2719     rc = CreateDirectory(directory, NULL);
2720     ok( rc, "Createdirectory failed, gle=%d\n", GetLastError() );
2721
2722     rc = SetCurrentDirectory(directory);
2723     ok( rc, "SetCurrentDirectory failed, gle=%d\n", GetLastError() );
2724
2725     rc = RemoveDirectory(".");
2726     if (!rc)
2727     {
2728         rc = SetCurrentDirectory("..");
2729         ok( rc, "SetCurrentDirectory failed, gle=%d\n", GetLastError() );
2730
2731         rc = RemoveDirectory(directory);
2732         ok( rc, "RemoveDirectory failed, gle=%d\n", GetLastError() );
2733     }
2734 }
2735
2736 static BOOL check_file_time( const FILETIME *ft1, const FILETIME *ft2, UINT tolerance )
2737 {
2738     ULONGLONG t1 = ((ULONGLONG)ft1->dwHighDateTime << 32) | ft1->dwLowDateTime;
2739     ULONGLONG t2 = ((ULONGLONG)ft2->dwHighDateTime << 32) | ft2->dwLowDateTime;
2740     return abs(t1 - t2) <= tolerance;
2741 }
2742
2743 static void test_ReplaceFileA(void)
2744 {
2745     char replaced[MAX_PATH], replacement[MAX_PATH], backup[MAX_PATH];
2746     HANDLE hReplacedFile, hReplacementFile, hBackupFile;
2747     static const char replacedData[] = "file-to-replace";
2748     static const char replacementData[] = "new-file";
2749     static const char backupData[] = "backup-file";
2750     FILETIME ftReplaced, ftReplacement, ftBackup;
2751     static const char prefix[] = "pfx";
2752     char temp_path[MAX_PATH];
2753     DWORD ret;
2754     BOOL retok, removeBackup = FALSE;
2755
2756     if (!pReplaceFileA)
2757     {
2758         win_skip("ReplaceFileA() is missing\n");
2759         return;
2760     }
2761
2762     ret = GetTempPathA(MAX_PATH, temp_path);
2763     ok(ret != 0, "GetTempPathA error %d\n", GetLastError());
2764     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
2765
2766     ret = GetTempFileNameA(temp_path, prefix, 0, replaced);
2767     ok(ret != 0, "GetTempFileNameA error (replaced) %d\n", GetLastError());
2768
2769     ret = GetTempFileNameA(temp_path, prefix, 0, replacement);
2770     ok(ret != 0, "GetTempFileNameA error (replacement) %d\n", GetLastError());
2771
2772     ret = GetTempFileNameA(temp_path, prefix, 0, backup);
2773     ok(ret != 0, "GetTempFileNameA error (backup) %d\n", GetLastError());
2774
2775     /* place predictable data in the file to be replaced */
2776     hReplacedFile = CreateFileA(replaced, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0 );
2777     ok(hReplacedFile != INVALID_HANDLE_VALUE,
2778         "failed to open replaced file\n");
2779     retok = WriteFile(hReplacedFile, replacedData, sizeof(replacedData), &ret, NULL );
2780     ok( retok && ret == sizeof(replacedData),
2781        "WriteFile error (replaced) %d\n", GetLastError());
2782     ok(GetFileSize(hReplacedFile, NULL) == sizeof(replacedData),
2783         "replaced file has wrong size\n");
2784     /* place predictable data in the file to be the replacement */
2785     hReplacementFile = CreateFileA(replacement, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0 );
2786     ok(hReplacementFile != INVALID_HANDLE_VALUE,
2787         "failed to open replacement file\n");
2788     retok = WriteFile(hReplacementFile, replacementData, sizeof(replacementData), &ret, NULL );
2789     ok( retok && ret == sizeof(replacementData),
2790        "WriteFile error (replacement) %d\n", GetLastError());
2791     ok(GetFileSize(hReplacementFile, NULL) == sizeof(replacementData),
2792         "replacement file has wrong size\n");
2793     /* place predictable data in the backup file (to be over-written) */
2794     hBackupFile = CreateFileA(backup, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0 );
2795     ok(hBackupFile != INVALID_HANDLE_VALUE,
2796         "failed to open backup file\n");
2797     retok = WriteFile(hBackupFile, backupData, sizeof(backupData), &ret, NULL );
2798     ok( retok && ret == sizeof(backupData),
2799        "WriteFile error (replacement) %d\n", GetLastError());
2800     ok(GetFileSize(hBackupFile, NULL) == sizeof(backupData),
2801         "backup file has wrong size\n");
2802     /* change the filetime on the "replaced" file to ensure that it changes */
2803     ret = GetFileTime(hReplacedFile, NULL, NULL, &ftReplaced);
2804     ok( ret, "GetFileTime error (replaced) %d\n", GetLastError());
2805     ftReplaced.dwLowDateTime -= 600000000; /* 60 second */
2806     ret = SetFileTime(hReplacedFile, NULL, NULL, &ftReplaced);
2807     ok( ret, "SetFileTime error (replaced) %d\n", GetLastError());
2808     GetFileTime(hReplacedFile, NULL, NULL, &ftReplaced);  /* get the actual time back */
2809     CloseHandle(hReplacedFile);
2810     /* change the filetime on the backup to ensure that it changes */
2811     ret = GetFileTime(hBackupFile, NULL, NULL, &ftBackup);
2812     ok( ret, "GetFileTime error (backup) %d\n", GetLastError());
2813     ftBackup.dwLowDateTime -= 1200000000; /* 120 second */
2814     ret = SetFileTime(hBackupFile, NULL, NULL, &ftBackup);
2815     ok( ret, "SetFileTime error (backup) %d\n", GetLastError());
2816     GetFileTime(hBackupFile, NULL, NULL, &ftBackup);  /* get the actual time back */
2817     CloseHandle(hBackupFile);
2818     /* get the filetime on the replacement file to perform checks */
2819     ret = GetFileTime(hReplacementFile, NULL, NULL, &ftReplacement);
2820     ok( ret, "GetFileTime error (replacement) %d\n", GetLastError());
2821     CloseHandle(hReplacementFile);
2822
2823     /* perform replacement w/ backup
2824      * TODO: flags are not implemented
2825      */
2826     SetLastError(0xdeadbeef);
2827     ret = pReplaceFileA(replaced, replacement, backup, 0, 0, 0);
2828     ok(ret, "ReplaceFileA: unexpected error %d\n", GetLastError());
2829     /* make sure that the backup has the size of the old "replaced" file */
2830     hBackupFile = CreateFileA(backup, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
2831     ok(hBackupFile != INVALID_HANDLE_VALUE,
2832         "failed to open backup file\n");
2833     ret = GetFileSize(hBackupFile, NULL);
2834     ok(ret == sizeof(replacedData),
2835         "backup file has wrong size %d\n", ret);
2836     /* make sure that the "replaced" file has the size of the replacement file */
2837     hReplacedFile = CreateFileA(replaced, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
2838     ok(hReplacedFile != INVALID_HANDLE_VALUE,
2839         "failed to open replaced file: %d\n", GetLastError());
2840     if (hReplacedFile != INVALID_HANDLE_VALUE)
2841     {
2842         ret = GetFileSize(hReplacedFile, NULL);
2843         ok(ret == sizeof(replacementData),
2844             "replaced file has wrong size %d\n", ret);
2845         /* make sure that the replacement file no-longer exists */
2846         hReplacementFile = CreateFileA(replacement, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
2847         ok(hReplacementFile == INVALID_HANDLE_VALUE,
2848            "unexpected error, replacement file should not exist %d\n", GetLastError());
2849         /* make sure that the backup has the old "replaced" filetime */
2850         ret = GetFileTime(hBackupFile, NULL, NULL, &ftBackup);
2851         ok( ret, "GetFileTime error (backup %d\n", GetLastError());
2852         ok(check_file_time(&ftBackup, &ftReplaced, 20000000), "backup file has wrong filetime\n");
2853         CloseHandle(hBackupFile);
2854         /* make sure that the "replaced" has the old replacement filetime */
2855         ret = GetFileTime(hReplacedFile, NULL, NULL, &ftReplaced);
2856         ok( ret, "GetFileTime error (backup %d\n", GetLastError());
2857         ok(check_file_time(&ftReplaced, &ftReplacement, 20000000),
2858            "replaced file has wrong filetime %x%08x / %x%08x\n",
2859            ftReplaced.dwHighDateTime, ftReplaced.dwLowDateTime,
2860            ftReplacement.dwHighDateTime, ftReplacement.dwLowDateTime );
2861         CloseHandle(hReplacedFile);
2862     }
2863     else
2864         skip("couldn't open replacement file, skipping tests\n");
2865
2866     /* re-create replacement file for pass w/o backup (blank) */
2867     ret = GetTempFileNameA(temp_path, prefix, 0, replacement);
2868     ok(ret != 0, "GetTempFileNameA error (replacement) %d\n", GetLastError());
2869     /* perform replacement w/o backup
2870      * TODO: flags are not implemented
2871      */
2872     SetLastError(0xdeadbeef);
2873     ret = pReplaceFileA(replaced, replacement, NULL, 0, 0, 0);
2874     ok(ret || GetLastError() == ERROR_ACCESS_DENIED,
2875        "ReplaceFileA: unexpected error %d\n", GetLastError());
2876
2877     /* re-create replacement file for pass w/ backup (backup-file not existing) */
2878     ret = GetTempFileNameA(temp_path, prefix, 0, replacement);
2879     ok(ret != 0, "GetTempFileNameA error (replacement) %d\n", GetLastError());
2880     ret = DeleteFileA(backup);
2881     ok(ret, "DeleteFileA: error (backup) %d\n", GetLastError());
2882     /* perform replacement w/ backup (no pre-existing backup)
2883      * TODO: flags are not implemented
2884      */
2885     SetLastError(0xdeadbeef);
2886     ret = pReplaceFileA(replaced, replacement, backup, 0, 0, 0);
2887     ok(ret || GetLastError() == ERROR_ACCESS_DENIED,
2888        "ReplaceFileA: unexpected error %d\n", GetLastError());
2889     if (ret)
2890         removeBackup = TRUE;
2891
2892     /* re-create replacement file for pass w/ no permissions to "replaced" */
2893     ret = GetTempFileNameA(temp_path, prefix, 0, replacement);
2894     ok(ret != 0, "GetTempFileNameA error (replacement) %d\n", GetLastError());
2895     ret = SetFileAttributesA(replaced, FILE_ATTRIBUTE_READONLY);
2896     ok(ret || GetLastError() == ERROR_ACCESS_DENIED,
2897        "SetFileAttributesA: error setting to read only %d\n", GetLastError());
2898     /* perform replacement w/ backup (no permission to "replaced")
2899      * TODO: flags are not implemented
2900      */
2901     SetLastError(0xdeadbeef);
2902     ret = pReplaceFileA(replaced, replacement, backup, 0, 0, 0);
2903     ok(ret != ERROR_UNABLE_TO_REMOVE_REPLACED, "ReplaceFileA: unexpected error %d\n", GetLastError());
2904     /* make sure that the replacement file still exists */
2905     hReplacementFile = CreateFileA(replacement, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
2906     ok(hReplacementFile != INVALID_HANDLE_VALUE ||
2907        broken(GetLastError() == ERROR_FILE_NOT_FOUND), /* win2k */
2908        "unexpected error, replacement file should still exist %d\n", GetLastError());
2909     CloseHandle(hReplacementFile);
2910     ret = SetFileAttributesA(replaced, FILE_ATTRIBUTE_NORMAL);
2911     ok(ret || GetLastError() == ERROR_ACCESS_DENIED,
2912        "SetFileAttributesA: error setting to normal %d\n", GetLastError());
2913
2914     /* replacement file still exists, make pass w/o "replaced" */
2915     ret = DeleteFileA(replaced);
2916     ok(ret || GetLastError() == ERROR_ACCESS_DENIED,
2917        "DeleteFileA: error (replaced) %d\n", GetLastError());
2918     /* perform replacement w/ backup (no pre-existing backup or "replaced")
2919      * TODO: flags are not implemented
2920      */
2921     SetLastError(0xdeadbeef);
2922     ret = pReplaceFileA(replaced, replacement, backup, 0, 0, 0);
2923     ok(!ret && (GetLastError() == ERROR_FILE_NOT_FOUND ||
2924        GetLastError() == ERROR_ACCESS_DENIED),
2925        "ReplaceFileA: unexpected error %d\n", GetLastError());
2926
2927     /* perform replacement w/o existing "replacement" file
2928      * TODO: flags are not implemented
2929      */
2930     SetLastError(0xdeadbeef);
2931     ret = pReplaceFileA(replaced, replacement, NULL, 0, 0, 0);
2932     ok(!ret && (GetLastError() == ERROR_FILE_NOT_FOUND ||
2933         GetLastError() == ERROR_ACCESS_DENIED),
2934         "ReplaceFileA: unexpected error %d\n", GetLastError());
2935
2936     /*
2937      * if the first round (w/ backup) worked then as long as there is no
2938      * failure then there is no need to check this round (w/ backup is the
2939      * more complete case)
2940      */
2941
2942     /* delete temporary files, replacement and replaced are already deleted */
2943     if (removeBackup)
2944     {
2945         ret = DeleteFileA(backup);
2946         ok(ret ||
2947            broken(GetLastError() == ERROR_ACCESS_DENIED), /* win2k */
2948            "DeleteFileA: error (backup) %d\n", GetLastError());
2949     }
2950 }
2951
2952 /*
2953  * ReplaceFileW is a simpler case of ReplaceFileA, there is no
2954  * need to be as thorough.
2955  */
2956 static void test_ReplaceFileW(void)
2957 {
2958     WCHAR replaced[MAX_PATH], replacement[MAX_PATH], backup[MAX_PATH];
2959     static const WCHAR prefix[] = {'p','f','x',0};
2960     WCHAR temp_path[MAX_PATH];
2961     DWORD ret;
2962     BOOL removeBackup = FALSE;
2963
2964     if (!pReplaceFileW)
2965     {
2966         win_skip("ReplaceFileW() is missing\n");
2967         return;
2968     }
2969
2970     ret = GetTempPathW(MAX_PATH, temp_path);
2971     if (ret == 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2972     {
2973         win_skip("GetTempPathW is not available\n");
2974         return;
2975     }
2976     ok(ret != 0, "GetTempPathW error %d\n", GetLastError());
2977     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
2978
2979     ret = GetTempFileNameW(temp_path, prefix, 0, replaced);
2980     ok(ret != 0, "GetTempFileNameW error (replaced) %d\n", GetLastError());
2981
2982     ret = GetTempFileNameW(temp_path, prefix, 0, replacement);
2983     ok(ret != 0, "GetTempFileNameW error (replacement) %d\n", GetLastError());
2984
2985     ret = GetTempFileNameW(temp_path, prefix, 0, backup);
2986     ok(ret != 0, "GetTempFileNameW error (backup) %d\n", GetLastError());
2987
2988     ret = pReplaceFileW(replaced, replacement, backup, 0, 0, 0);
2989     ok(ret, "ReplaceFileW: error %d\n", GetLastError());
2990
2991     ret = GetTempFileNameW(temp_path, prefix, 0, replacement);
2992     ok(ret != 0, "GetTempFileNameW error (replacement) %d\n", GetLastError());
2993     ret = pReplaceFileW(replaced, replacement, NULL, 0, 0, 0);
2994     ok(ret || GetLastError() == ERROR_ACCESS_DENIED,
2995        "ReplaceFileW: error %d\n", GetLastError());
2996
2997     ret = GetTempFileNameW(temp_path, prefix, 0, replacement);
2998     ok(ret != 0, "GetTempFileNameW error (replacement) %d\n", GetLastError());
2999     ret = DeleteFileW(backup);
3000     ok(ret, "DeleteFileW: error (backup) %d\n", GetLastError());
3001     ret = pReplaceFileW(replaced, replacement, backup, 0, 0, 0);
3002     ok(ret || GetLastError() == ERROR_ACCESS_DENIED,
3003        "ReplaceFileW: error %d\n", GetLastError());
3004
3005     ret = GetTempFileNameW(temp_path, prefix, 0, replacement);
3006     ok(ret != 0, "GetTempFileNameW error (replacement) %d\n", GetLastError());
3007     ret = SetFileAttributesW(replaced, FILE_ATTRIBUTE_READONLY);
3008     ok(ret || GetLastError() == ERROR_ACCESS_DENIED,
3009        "SetFileAttributesW: error setting to read only %d\n", GetLastError());
3010
3011     ret = pReplaceFileW(replaced, replacement, backup, 0, 0, 0);
3012     ok(ret != ERROR_UNABLE_TO_REMOVE_REPLACED,
3013         "ReplaceFileW: unexpected error %d\n", GetLastError());
3014     ret = SetFileAttributesW(replaced, FILE_ATTRIBUTE_NORMAL);
3015     ok(ret || GetLastError() == ERROR_ACCESS_DENIED,
3016        "SetFileAttributesW: error setting to normal %d\n", GetLastError());
3017     if (ret)
3018         removeBackup = TRUE;
3019
3020     ret = DeleteFileW(replaced);
3021     ok(ret, "DeleteFileW: error (replaced) %d\n", GetLastError());
3022     ret = pReplaceFileW(replaced, replacement, backup, 0, 0, 0);
3023     ok(!ret, "ReplaceFileW: error %d\n", GetLastError());
3024
3025     ret = pReplaceFileW(replaced, replacement, NULL, 0, 0, 0);
3026     ok(!ret && (GetLastError() == ERROR_FILE_NOT_FOUND ||
3027        GetLastError() == ERROR_ACCESS_DENIED),
3028         "ReplaceFileW: unexpected error %d\n", GetLastError());
3029
3030     if (removeBackup)
3031     {
3032         ret = DeleteFileW(backup);
3033         ok(ret ||
3034            broken(GetLastError() == ERROR_ACCESS_DENIED), /* win2k */
3035            "DeleteFileW: error (backup) %d\n", GetLastError());
3036     }
3037 }
3038
3039 START_TEST(file)
3040 {
3041     InitFunctionPointers();
3042
3043     test__hread(  );
3044     test__hwrite(  );
3045     test__lclose(  );
3046     test__lcreat(  );
3047     test__llseek(  );
3048     test__llopen(  );
3049     test__lread(  );
3050     test__lwrite(  );
3051     test_GetTempFileNameA();
3052     test_CopyFileA();
3053     test_CopyFileW();
3054     test_CreateFileA();
3055     test_CreateFileW();
3056     test_DeleteFileA();
3057     test_DeleteFileW();
3058     test_MoveFileA();
3059     test_MoveFileW();
3060     test_FindFirstFileA();
3061     test_FindNextFileA();
3062     test_FindFirstFileExA(0);
3063     /* FindExLimitToDirectories is ignored if the file system doesn't support directory filtering */
3064     test_FindFirstFileExA(FindExSearchLimitToDirectories);
3065     test_LockFile();
3066     test_file_sharing();
3067     test_offset_in_overlapped_structure();
3068     test_MapFile();
3069     test_GetFileType();
3070     test_async_file_errors();
3071     test_read_write();
3072     test_OpenFile();
3073     test_overlapped();
3074     test_RemoveDirectory();
3075     test_ReplaceFileA();
3076     test_ReplaceFileW();
3077 }