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