wordpad: Allow objects & images to be added with native riched20.
[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     /* get windows drive letter */
878     ret = GetWindowsDirectory(windowsdir, sizeof(windowsdir));
879     ok(ret < sizeof(windowsdir), "windowsdir is abnormally long!\n");
880     ok(ret != 0, "GetWindowsDirectory: error %d\n", GetLastError());
881
882     /* test error return codes from CreateFile for some cases */
883     ret = GetTempPathA(MAX_PATH, temp_path);
884     ok(ret != 0, "GetTempPathA error %d\n", GetLastError());
885     strcpy(dirname, temp_path);
886     strcat(dirname, directory);
887     ret = CreateDirectory(dirname, NULL);
888     ok( ret, "Createdirectory failed, gle=%d\n", GetLastError() );
889     /* set current drive & directory to known location */
890     SetCurrentDirectoryA( temp_path );
891     i = 0;
892     while (p[i].file)
893     {
894         filename[0] = 0;
895         /* update the drive id in the table entry with the current one */
896         if (p[i].file[1] == ':')
897         {
898             strcpy(filename, p[i].file);
899             filename[0] = windowsdir[0];
900         }
901         else if (p[i].file[0] == '\\' && p[i].file[5] == ':')
902         {
903             strcpy(filename, p[i].file);
904             filename[4] = windowsdir[0];
905         }
906         else
907         {
908             /* prefix the table entry with the current temp directory */
909             strcpy(filename, temp_path);
910             strcat(filename, p[i].file);
911         }
912         hFile = CreateFileA( filename, GENERIC_READ | GENERIC_WRITE,
913                         FILE_SHARE_READ | FILE_SHARE_WRITE,
914                         NULL, OPEN_EXISTING,
915                         p[i].options, NULL );
916         /* if we get ACCESS_DENIED when we do not expect it, assume
917          * no access to the volume
918          */
919         if (hFile == INVALID_HANDLE_VALUE &&
920             GetLastError() == ERROR_ACCESS_DENIED &&
921             p[i].err != ERROR_ACCESS_DENIED)
922         {
923             if (p[i].todo_flag)
924                 skip("Either no authority to volume, or is todo_wine for %s err=%d should be %d\n", filename, GetLastError(), p[i].err);
925             else
926                 skip("Do not have authority to access volumes. Test for %s skipped\n", filename);
927         }
928         /* otherwise validate results with expectations */
929         else if (p[i].todo_flag)
930             todo_wine ok(
931                 (hFile == INVALID_HANDLE_VALUE &&
932                   (p[i].err == GetLastError() || p[i].err2 == GetLastError())) ||
933                 (hFile != INVALID_HANDLE_VALUE && p[i].err == ERROR_SUCCESS),
934                 "CreateFileA failed on %s, hFile %p, err=%u, should be %u\n",
935                 filename, hFile, GetLastError(), p[i].err);
936         else
937             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         if (hFile != INVALID_HANDLE_VALUE)
944             CloseHandle( hFile );
945         i++;
946     }
947     ret = RemoveDirectoryA(dirname);
948     ok(ret, "RemoveDirectoryA: error %d\n", GetLastError());
949
950
951     /* test opening directory as a directory */
952     hFile = CreateFileA( temp_path, GENERIC_READ,
953                         FILE_SHARE_READ,
954                         NULL,
955                         OPEN_EXISTING,
956                         FILE_FLAG_BACKUP_SEMANTICS, NULL );
957     if (hFile != INVALID_HANDLE_VALUE && GetLastError() != ERROR_PATH_NOT_FOUND)
958     {
959         ok(hFile != INVALID_HANDLE_VALUE && GetLastError() == ERROR_SUCCESS,
960             "CreateFileA did not work, last error %u on volume <%s>\n",
961              GetLastError(), temp_path );
962
963         if (hFile != INVALID_HANDLE_VALUE)
964         {
965             ret = GetFileInformationByHandle( hFile, &Finfo );
966             if (ret)
967             {
968                 ok(Finfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY,
969                     "CreateFileA probably did not open temp directory %s correctly\n   file information does not include FILE_ATTRIBUTE_DIRECTORY, actual=0x%08x\n",
970                 temp_path, Finfo.dwFileAttributes);
971             }
972             CloseHandle( hFile );
973         }
974     }
975     else
976         skip("Probable Win9x, got ERROR_PATH_NOT_FOUND w/ FILE_FLAG_BACKUP_SEMANTICS or %s\n", temp_path);
977
978
979     /* ***  Test opening volumes/devices using drive letter  ***         */
980
981     /* test using drive letter in non-rewrite format without trailing \  */
982     /* this should work                                                  */
983     strcpy(filename, nt_drive);
984     filename[4] = windowsdir[0];
985     hFile = CreateFileA( filename, GENERIC_READ | GENERIC_WRITE,
986                         FILE_SHARE_READ | FILE_SHARE_WRITE,
987                         NULL, OPEN_EXISTING,
988                         FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING, NULL );
989     if (hFile != INVALID_HANDLE_VALUE ||
990         (GetLastError() != ERROR_ACCESS_DENIED && GetLastError() != ERROR_BAD_NETPATH))
991     {
992         /* if we have adm rights to volume, then try rest of tests */
993         ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA did not open %s, last error=%u\n",
994             filename, GetLastError());
995         if (hFile != INVALID_HANDLE_VALUE)
996         {
997             /* if we opened the volume/device, try to read it. Since it  */
998             /* opened, we should be able to read it.  We don't care about*/
999             /* what the data is at this time.                            */
1000             len = 512;
1001             ret = ReadFile( hFile, buffer, len, &len, NULL );
1002             todo_wine ok(ret, "Failed to read volume, last error %u, %u, for %s\n",
1003                 GetLastError(), ret, filename);
1004             if (ret)
1005             {
1006                 trace("buffer is\n");
1007                 dumpmem(buffer, 64);
1008             }
1009             CloseHandle( hFile );
1010         }
1011
1012         /* test using drive letter with trailing \ and in non-rewrite   */
1013         /* this should not work                                         */
1014         strcpy(filename, nt_drive);
1015         filename[4] = windowsdir[0];
1016         strcat( filename, "\\" );
1017         hFile = CreateFileA( filename, GENERIC_READ | GENERIC_WRITE,
1018                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1019                         NULL, OPEN_EXISTING,
1020                         FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING, NULL );
1021         todo_wine
1022         ok(hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_PATH_NOT_FOUND,
1023             "CreateFileA should have returned ERROR_PATH_NOT_FOUND on %s, but got %u\n",
1024             filename, GetLastError());
1025         if (hFile != INVALID_HANDLE_VALUE)
1026             CloseHandle( hFile );
1027
1028         /* test using temp path with trailing \ and in non-rewrite as dir */
1029         /* this should work                                               */
1030         strcpy(filename, nt_drive);
1031         filename[4] = 0;
1032         strcat( filename, temp_path );
1033         hFile = CreateFileA( filename, GENERIC_READ | GENERIC_WRITE,
1034                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1035                         NULL, OPEN_EXISTING,
1036                         FILE_FLAG_BACKUP_SEMANTICS, NULL );
1037         ok(hFile != INVALID_HANDLE_VALUE,
1038             "CreateFileA should have worked on %s, but got %u\n",
1039             filename, GetLastError());
1040         if (hFile != INVALID_HANDLE_VALUE)
1041             CloseHandle( hFile );
1042
1043         /* test using drive letter without trailing \ and in device ns  */
1044         /* this should work                                             */
1045         strcpy(filename, nt_drive);
1046         filename[4] = windowsdir[0];
1047         filename[2] = '.';
1048         hFile = CreateFileA( filename, GENERIC_READ | GENERIC_WRITE,
1049                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1050                         NULL, OPEN_EXISTING,
1051                         FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING, NULL );
1052         ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA did not open %s, last error=%u\n",
1053             filename, GetLastError());
1054         if (hFile != INVALID_HANDLE_VALUE)
1055             CloseHandle( hFile );
1056     }
1057     /* If we see ERROR_BAD_NETPATH then on Win9x or WinME, so skip */
1058     else if (GetLastError() == ERROR_BAD_NETPATH)
1059         skip("Probable Win9x, got ERROR_BAD_NETPATH (53)\n");
1060     else
1061         skip("Do not have authority to access volumes. Tests skipped\n");
1062
1063
1064     /* ***  Test opening volumes/devices using GUID  ***           */
1065
1066     if (pGetVolumeNameForVolumeMountPointA)
1067     {
1068         strcpy(filename, "c:\\");
1069         filename[0] = windowsdir[0];
1070         ret = pGetVolumeNameForVolumeMountPointA( filename, Volume_1, MAX_PATH );
1071         ok(ret, "GetVolumeNameForVolumeMountPointA failed, for %s, last error=%d\n", filename, GetLastError());
1072         if (ret)
1073         {
1074             ok(strlen(Volume_1) == 49, "GetVolumeNameForVolumeMountPointA returned wrong length name <%s>\n", Volume_1);
1075
1076             /* test the result of opening a unique volume name (GUID)
1077              *  with the trailing \
1078              *  this should error out
1079              */
1080             strcpy(filename, Volume_1);
1081             hFile = CreateFileA( filename, GENERIC_READ | GENERIC_WRITE,
1082                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1083                         NULL, OPEN_EXISTING,
1084                         FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING, NULL );
1085             todo_wine
1086             ok(hFile == INVALID_HANDLE_VALUE,
1087                 "CreateFileA should not have opened %s, hFile %p\n",
1088                 filename, hFile);
1089             todo_wine
1090             ok(hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_PATH_NOT_FOUND,
1091                 "CreateFileA should have returned ERROR_PATH_NOT_FOUND on %s, but got %u\n",
1092                 filename, GetLastError());
1093             if (hFile != INVALID_HANDLE_VALUE)
1094                 CloseHandle( hFile );
1095
1096             /* test the result of opening a unique volume name (GUID)
1097              * with the temp path string as dir
1098              * this should work
1099              */
1100             strcpy(filename, Volume_1);
1101             strcat(filename, temp_path+3);
1102             hFile = CreateFileA( filename, GENERIC_READ | GENERIC_WRITE,
1103                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1104                         NULL, OPEN_EXISTING,
1105                         FILE_FLAG_BACKUP_SEMANTICS, NULL );
1106             todo_wine
1107             ok(hFile != INVALID_HANDLE_VALUE,
1108                 "CreateFileA should have opened %s, but got %u\n",
1109                 filename, GetLastError());
1110             if (hFile != INVALID_HANDLE_VALUE)
1111                 CloseHandle( hFile );
1112
1113             /* test the result of opening a unique volume name (GUID)
1114              * without the trailing \ and in device namespace
1115              * this should work
1116              */
1117             strcpy(filename, Volume_1);
1118             filename[2] = '.';
1119             filename[48] = 0;
1120             hFile = CreateFileA( filename, GENERIC_READ | GENERIC_WRITE,
1121                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1122                         NULL, OPEN_EXISTING,
1123                         FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING, NULL );
1124             if (hFile != INVALID_HANDLE_VALUE || GetLastError() != ERROR_ACCESS_DENIED)
1125             {
1126                 /* if we have adm rights to volume, then try rest of tests */
1127                 ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA did not open %s, last error=%u\n",
1128                     filename, GetLastError());
1129                 if (hFile != INVALID_HANDLE_VALUE)
1130                 {
1131                     /* if we opened the volume/device, try to read it. Since it  */
1132                     /* opened, we should be able to read it.  We don't care about*/
1133                     /* what the data is at this time.                            */
1134                     len = 512;
1135                     ret = ReadFile( hFile, buffer, len, &len, NULL );
1136                     todo_wine ok(ret, "Failed to read volume, last error %u, %u, for %s\n",
1137                         GetLastError(), ret, filename);
1138                     if (ret)
1139                     {
1140                         trace("buffer is\n");
1141                         dumpmem(buffer, 64);
1142                     }
1143                     CloseHandle( hFile );
1144                 }
1145             }
1146             else
1147                 skip("Do not have authority to access volumes. Tests skipped\n");
1148         }
1149         else
1150             win_skip("GetVolumeNameForVolumeMountPointA not functioning\n");
1151     }
1152     else
1153         win_skip("GetVolumeNameForVolumeMountPointA not found\n");
1154 }
1155
1156 static void test_CreateFileW(void)
1157 {
1158     HANDLE hFile;
1159     WCHAR temp_path[MAX_PATH];
1160     WCHAR filename[MAX_PATH];
1161     static const WCHAR emptyW[]={'\0'};
1162     static const WCHAR prefix[] = {'p','f','x',0};
1163     static const WCHAR bogus[] = { '\\', '\\', '.', '\\', 'B', 'O', 'G', 'U', 'S', 0 };
1164     DWORD ret;
1165
1166     ret = GetTempPathW(MAX_PATH, temp_path);
1167     if (ret == 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
1168     {
1169         win_skip("GetTempPathW is not available\n");
1170         return;
1171     }
1172     ok(ret != 0, "GetTempPathW error %d\n", GetLastError());
1173     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
1174
1175     ret = GetTempFileNameW(temp_path, prefix, 0, filename);
1176     ok(ret != 0, "GetTempFileNameW error %d\n", GetLastError());
1177
1178     SetLastError(0xdeadbeef);
1179     hFile = CreateFileW(filename, GENERIC_READ, 0, NULL,
1180                         CREATE_NEW, FILE_FLAG_RANDOM_ACCESS, 0);
1181     ok(hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_FILE_EXISTS,
1182         "CREATE_NEW should fail if file exists and last error value should be ERROR_FILE_EXISTS\n");
1183
1184     SetLastError(0xdeadbeef);
1185     hFile = CreateFileW(filename, GENERIC_READ, FILE_SHARE_READ, NULL,
1186                         CREATE_ALWAYS, FILE_FLAG_RANDOM_ACCESS, 0);
1187     ok(hFile != INVALID_HANDLE_VALUE && GetLastError() == ERROR_ALREADY_EXISTS,
1188        "hFile %p, last error %u\n", hFile, GetLastError());
1189
1190     CloseHandle(hFile);
1191
1192     SetLastError(0xdeadbeef);
1193     hFile = CreateFileW(filename, GENERIC_READ, FILE_SHARE_READ, NULL,
1194                         OPEN_ALWAYS, FILE_FLAG_RANDOM_ACCESS, 0);
1195     ok(hFile != INVALID_HANDLE_VALUE && GetLastError() == ERROR_ALREADY_EXISTS,
1196        "hFile %p, last error %u\n", hFile, GetLastError());
1197
1198     CloseHandle(hFile);
1199
1200     ret = DeleteFileW(filename);
1201     ok(ret, "DeleteFileW: error %d\n", GetLastError());
1202
1203     SetLastError(0xdeadbeef);
1204     hFile = CreateFileW(filename, GENERIC_READ, FILE_SHARE_READ, NULL,
1205                         OPEN_ALWAYS, FILE_FLAG_RANDOM_ACCESS, 0);
1206     ok(hFile != INVALID_HANDLE_VALUE && GetLastError() == 0,
1207        "hFile %p, last error %u\n", hFile, GetLastError());
1208
1209     CloseHandle(hFile);
1210
1211     ret = DeleteFileW(filename);
1212     ok(ret, "DeleteFileW: error %d\n", GetLastError());
1213
1214     if (0)
1215     {
1216         /* this crashes on NT4.0 */
1217         hFile = CreateFileW(NULL, GENERIC_READ, 0, NULL,
1218                             CREATE_NEW, FILE_FLAG_RANDOM_ACCESS, 0);
1219         ok(hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_PATH_NOT_FOUND,
1220            "CreateFileW(NULL) returned ret=%p error=%u\n",hFile,GetLastError());
1221     }
1222
1223     hFile = CreateFileW(emptyW, GENERIC_READ, 0, NULL,
1224                         CREATE_NEW, FILE_FLAG_RANDOM_ACCESS, 0);
1225     ok(hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_PATH_NOT_FOUND,
1226        "CreateFileW(\"\") returned ret=%p error=%d\n",hFile,GetLastError());
1227
1228     /* test the result of opening a nonexistent driver name */
1229     hFile = CreateFileW(bogus, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1230                         OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1231     ok(hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_FILE_NOT_FOUND,
1232        "CreateFileW on invalid VxD name returned ret=%p error=%d\n",hFile,GetLastError());
1233
1234     ret = CreateDirectoryW(filename, NULL);
1235     ok(ret == TRUE, "couldn't create temporary directory\n");
1236     hFile = CreateFileW(filename, GENERIC_READ | GENERIC_WRITE, 0, NULL,
1237                         OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, NULL);
1238     ok(hFile != INVALID_HANDLE_VALUE,
1239        "expected CreateFile to succeed on existing directory, error: %d\n", GetLastError());
1240     CloseHandle(hFile);
1241     ret = RemoveDirectoryW(filename);
1242     ok(ret, "DeleteFileW: error %d\n", GetLastError());
1243 }
1244
1245 static void test_GetTempFileNameA(void)
1246 {
1247     UINT result;
1248     char out[MAX_PATH];
1249     char expected[MAX_PATH + 10];
1250     char windowsdir[MAX_PATH + 10];
1251     char windowsdrive[3];
1252
1253     result = GetWindowsDirectory(windowsdir, sizeof(windowsdir));
1254     ok(result < sizeof(windowsdir), "windowsdir is abnormally long!\n");
1255     ok(result != 0, "GetWindowsDirectory: error %d\n", GetLastError());
1256
1257     /* If the Windows directory is the root directory, it ends in backslash, not else. */
1258     if (strlen(windowsdir) != 3) /* As in  "C:\"  or  "F:\"  */
1259     {
1260         strcat(windowsdir, "\\");
1261     }
1262
1263     windowsdrive[0] = windowsdir[0];
1264     windowsdrive[1] = windowsdir[1];
1265     windowsdrive[2] = '\0';
1266
1267     result = GetTempFileNameA(windowsdrive, "abc", 1, out);
1268     ok(result != 0, "GetTempFileNameA: error %d\n", GetLastError());
1269     ok(((out[0] == windowsdrive[0]) && (out[1] == ':')) && (out[2] == '\\'),
1270        "GetTempFileNameA: first three characters should be %c:\\, string was actually %s\n",
1271        windowsdrive[0], out);
1272
1273     result = GetTempFileNameA(windowsdir, "abc", 2, out);
1274     ok(result != 0, "GetTempFileNameA: error %d\n", GetLastError());
1275     expected[0] = '\0';
1276     strcat(expected, windowsdir);
1277     strcat(expected, "abc2.tmp");
1278     ok(lstrcmpiA(out, expected) == 0, "GetTempFileNameA: Unexpected output \"%s\" vs \"%s\"\n",
1279        out, expected);
1280 }
1281
1282 static void test_DeleteFileA( void )
1283 {
1284     BOOL ret;
1285
1286     ret = DeleteFileA(NULL);
1287     ok(!ret && (GetLastError() == ERROR_INVALID_PARAMETER ||
1288                 GetLastError() == ERROR_PATH_NOT_FOUND),
1289        "DeleteFileA(NULL) returned ret=%d error=%d\n",ret,GetLastError());
1290
1291     ret = DeleteFileA("");
1292     ok(!ret && (GetLastError() == ERROR_PATH_NOT_FOUND ||
1293                 GetLastError() == ERROR_BAD_PATHNAME),
1294        "DeleteFileA(\"\") returned ret=%d error=%d\n",ret,GetLastError());
1295
1296     ret = DeleteFileA("nul");
1297     ok(!ret && (GetLastError() == ERROR_FILE_NOT_FOUND ||
1298                 GetLastError() == ERROR_INVALID_PARAMETER ||
1299                 GetLastError() == ERROR_ACCESS_DENIED ||
1300                 GetLastError() == ERROR_INVALID_FUNCTION),
1301        "DeleteFileA(\"nul\") returned ret=%d error=%d\n",ret,GetLastError());
1302 }
1303
1304 static void test_DeleteFileW( void )
1305 {
1306     BOOL ret;
1307     WCHAR pathW[MAX_PATH];
1308     WCHAR pathsubW[MAX_PATH];
1309     static const WCHAR dirW[] = {'d','e','l','e','t','e','f','i','l','e',0};
1310     static const WCHAR subdirW[] = {'\\','s','u','b',0};
1311     static const WCHAR emptyW[]={'\0'};
1312
1313     ret = DeleteFileW(NULL);
1314     if (ret == 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
1315     {
1316         win_skip("DeleteFileW is not available\n");
1317         return;
1318     }
1319     ok(!ret && GetLastError() == ERROR_PATH_NOT_FOUND,
1320        "DeleteFileW(NULL) returned ret=%d error=%d\n",ret,GetLastError());
1321
1322     ret = DeleteFileW(emptyW);
1323     ok(!ret && GetLastError() == ERROR_PATH_NOT_FOUND,
1324        "DeleteFileW(\"\") returned ret=%d error=%d\n",ret,GetLastError());
1325
1326     /* test DeleteFile on empty directory */
1327     ret = GetTempPathW(MAX_PATH, pathW);
1328     if (ret + sizeof(dirW)/sizeof(WCHAR)-1 + sizeof(subdirW)/sizeof(WCHAR)-1 >= MAX_PATH)
1329     {
1330         ok(0, "MAX_PATH exceeded in constructing paths\n");
1331         return;
1332     }
1333     lstrcatW(pathW, dirW);
1334     lstrcpyW(pathsubW, pathW);
1335     lstrcatW(pathsubW, subdirW);
1336     ret = CreateDirectoryW(pathW, NULL);
1337     ok(ret == TRUE, "couldn't create directory deletefile\n");
1338     ret = DeleteFileW(pathW);
1339     ok(ret == FALSE, "DeleteFile should fail for empty directories\n");
1340     ret = RemoveDirectoryW(pathW);
1341     ok(ret == TRUE, "expected to remove directory deletefile\n");
1342
1343     /* test DeleteFile on non-empty directory */
1344     ret = CreateDirectoryW(pathW, NULL);
1345     ok(ret == TRUE, "couldn't create directory deletefile\n");
1346     ret = CreateDirectoryW(pathsubW, NULL);
1347     ok(ret == TRUE, "couldn't create directory deletefile\\sub\n");
1348     ret = DeleteFileW(pathW);
1349     ok(ret == FALSE, "DeleteFile should fail for non-empty directories\n");
1350     ret = RemoveDirectoryW(pathsubW);
1351     ok(ret == TRUE, "expected to remove directory deletefile\\sub\n");
1352     ret = RemoveDirectoryW(pathW);
1353     ok(ret == TRUE, "expected to remove directory deletefile\n");
1354 }
1355
1356 #define IsDotDir(x)     ((x[0] == '.') && ((x[1] == 0) || ((x[1] == '.') && (x[2] == 0))))
1357
1358 static void test_MoveFileA(void)
1359 {
1360     char tempdir[MAX_PATH];
1361     char source[MAX_PATH], dest[MAX_PATH];
1362     static const char prefix[] = "pfx";
1363     HANDLE hfile;
1364     HANDLE hmapfile;
1365     DWORD ret;
1366     BOOL retok;
1367
1368     ret = GetTempPathA(MAX_PATH, tempdir);
1369     ok(ret != 0, "GetTempPathA error %d\n", GetLastError());
1370     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
1371
1372     ret = GetTempFileNameA(tempdir, prefix, 0, source);
1373     ok(ret != 0, "GetTempFileNameA error %d\n", GetLastError());
1374
1375     ret = GetTempFileNameA(tempdir, prefix, 0, dest);
1376     ok(ret != 0, "GetTempFileNameA error %d\n", GetLastError());
1377
1378     ret = MoveFileA(source, dest);
1379     ok(!ret && GetLastError() == ERROR_ALREADY_EXISTS,
1380        "MoveFileA: unexpected error %d\n", GetLastError());
1381
1382     ret = DeleteFileA(dest);
1383     ok(ret, "DeleteFileA: error %d\n", GetLastError());
1384
1385     hfile = CreateFileA(source, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0);
1386     ok(hfile != INVALID_HANDLE_VALUE, "failed to open source file\n");
1387
1388     retok = WriteFile(hfile, prefix, sizeof(prefix), &ret, NULL );
1389     ok( retok && ret == sizeof(prefix),
1390        "WriteFile error %d\n", GetLastError());
1391
1392     hmapfile = CreateFileMapping(hfile, NULL, PAGE_READONLY | SEC_COMMIT, 0, 0, NULL);
1393     ok(hmapfile != NULL, "CreateFileMapping: error %d\n", GetLastError());
1394
1395     ret = MoveFileA(source, dest);
1396     todo_wine {
1397         ok(!ret, "MoveFileA: expected failure\n");
1398         ok(GetLastError() == ERROR_SHARING_VIOLATION ||
1399            broken(GetLastError() == ERROR_ACCESS_DENIED), /* Win9x and WinMe */
1400            "MoveFileA: expected ERROR_SHARING_VIOLATION, got %d\n", GetLastError());
1401     }
1402
1403     CloseHandle(hmapfile);
1404     CloseHandle(hfile);
1405
1406     /* if MoveFile succeeded, move back to dest */
1407     if (ret) MoveFile(dest, source);
1408
1409     hfile = CreateFileA(source, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
1410     ok(hfile != INVALID_HANDLE_VALUE, "failed to open source file\n");
1411
1412     hmapfile = CreateFileMapping(hfile, NULL, PAGE_READONLY | SEC_COMMIT, 0, 0, NULL);
1413     ok(hmapfile != NULL, "CreateFileMapping: error %d\n", GetLastError());
1414
1415     ret = MoveFileA(source, dest);
1416     todo_wine {
1417         ok(!ret, "MoveFileA: expected failure\n");
1418         ok(GetLastError() == ERROR_SHARING_VIOLATION ||
1419            broken(GetLastError() == ERROR_ACCESS_DENIED), /* Win9x and WinMe */
1420            "MoveFileA: expected ERROR_SHARING_VIOLATION, got %d\n", GetLastError());
1421     }
1422
1423     CloseHandle(hmapfile);
1424     CloseHandle(hfile);
1425
1426     /* if MoveFile succeeded, move back to dest */
1427     if (ret) MoveFile(dest, source);
1428
1429     ret = MoveFileA(source, dest);
1430     ok(ret, "MoveFileA: failed, error %d\n", GetLastError());
1431
1432     lstrcatA(tempdir, "Remove Me");
1433     ret = CreateDirectoryA(tempdir, NULL);
1434     ok(ret == TRUE, "CreateDirectoryA failed\n");
1435
1436     lstrcpyA(source, dest);
1437     lstrcpyA(dest, tempdir);
1438     lstrcatA(dest, "\\wild?.*");
1439     /* FIXME: if we create a file with wildcards we can't delete it now that DeleteFile works correctly */
1440     ret = MoveFileA(source, dest);
1441     ok(!ret, "MoveFileA: shouldn't move to wildcard file\n");
1442     ok(GetLastError() == ERROR_INVALID_NAME || /* NT */
1443        GetLastError() == ERROR_FILE_NOT_FOUND, /* Win9x */
1444        "MoveFileA: with wildcards, unexpected error %d\n", GetLastError());
1445     if (ret || (GetLastError() != ERROR_INVALID_NAME))
1446     {
1447         WIN32_FIND_DATAA fd;
1448         char temppath[MAX_PATH];
1449         HANDLE hFind;
1450
1451         lstrcpyA(temppath, tempdir);
1452         lstrcatA(temppath, "\\*.*");
1453         hFind = FindFirstFileA(temppath, &fd);
1454         if (INVALID_HANDLE_VALUE != hFind)
1455         {
1456           LPSTR lpName;
1457           do
1458           {
1459             lpName = fd.cAlternateFileName;
1460             if (!lpName[0])
1461               lpName = fd.cFileName;
1462             ok(IsDotDir(lpName), "MoveFileA: wildcards file created!\n");
1463           }
1464           while (FindNextFileA(hFind, &fd));
1465           FindClose(hFind);
1466         }
1467     }
1468     ret = DeleteFileA(source);
1469     ok(ret, "DeleteFileA: error %d\n", GetLastError());
1470     ret = DeleteFileA(dest);
1471     ok(!ret, "DeleteFileA: error %d\n", GetLastError());
1472     ret = RemoveDirectoryA(tempdir);
1473     ok(ret, "DeleteDirectoryA: error %d\n", GetLastError());
1474 }
1475
1476 static void test_MoveFileW(void)
1477 {
1478     WCHAR temp_path[MAX_PATH];
1479     WCHAR source[MAX_PATH], dest[MAX_PATH];
1480     static const WCHAR prefix[] = {'p','f','x',0};
1481     DWORD ret;
1482
1483     ret = GetTempPathW(MAX_PATH, temp_path);
1484     if (ret == 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
1485     {
1486         win_skip("GetTempPathW is not available\n");
1487         return;
1488     }
1489     ok(ret != 0, "GetTempPathW error %d\n", GetLastError());
1490     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
1491
1492     ret = GetTempFileNameW(temp_path, prefix, 0, source);
1493     ok(ret != 0, "GetTempFileNameW error %d\n", GetLastError());
1494
1495     ret = GetTempFileNameW(temp_path, prefix, 0, dest);
1496     ok(ret != 0, "GetTempFileNameW error %d\n", GetLastError());
1497
1498     ret = MoveFileW(source, dest);
1499     ok(!ret && GetLastError() == ERROR_ALREADY_EXISTS,
1500        "CopyFileW: unexpected error %d\n", GetLastError());
1501
1502     ret = DeleteFileW(source);
1503     ok(ret, "DeleteFileW: error %d\n", GetLastError());
1504     ret = DeleteFileW(dest);
1505     ok(ret, "DeleteFileW: error %d\n", GetLastError());
1506 }
1507
1508 #define PATTERN_OFFSET 0x10
1509
1510 static void test_offset_in_overlapped_structure(void)
1511 {
1512     HANDLE hFile;
1513     OVERLAPPED ov;
1514     DWORD done, offset;
1515     BOOL rc;
1516     BYTE buf[256], pattern[] = "TeSt";
1517     UINT i;
1518     char temp_path[MAX_PATH], temp_fname[MAX_PATH];
1519     BOOL ret;
1520
1521     ret =GetTempPathA(MAX_PATH, temp_path);
1522     ok( ret, "GetTempPathA error %d\n", GetLastError());
1523     ret =GetTempFileNameA(temp_path, "pfx", 0, temp_fname);
1524     ok( ret, "GetTempFileNameA error %d\n", GetLastError());
1525
1526     /*** Write File *****************************************************/
1527
1528     hFile = CreateFileA(temp_fname, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
1529     ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA error %d\n", GetLastError());
1530
1531     for(i = 0; i < sizeof(buf); i++) buf[i] = i;
1532     ret = WriteFile(hFile, buf, sizeof(buf), &done, NULL);
1533     ok( ret, "WriteFile error %d\n", GetLastError());
1534     ok(done == sizeof(buf), "expected number of bytes written %u\n", done);
1535
1536     memset(&ov, 0, sizeof(ov));
1537     S(U(ov)).Offset = PATTERN_OFFSET;
1538     S(U(ov)).OffsetHigh = 0;
1539     rc=WriteFile(hFile, pattern, sizeof(pattern), &done, &ov);
1540     /* Win 9x does not support the overlapped I/O on files */
1541     if (rc || GetLastError()!=ERROR_INVALID_PARAMETER) {
1542         ok(rc, "WriteFile error %d\n", GetLastError());
1543         ok(done == sizeof(pattern), "expected number of bytes written %u\n", done);
1544         offset = SetFilePointer(hFile, 0, NULL, FILE_CURRENT);
1545         ok(offset == PATTERN_OFFSET + sizeof(pattern), "wrong file offset %d\n", offset);
1546
1547         S(U(ov)).Offset = sizeof(buf) * 2;
1548         S(U(ov)).OffsetHigh = 0;
1549         ret = WriteFile(hFile, pattern, sizeof(pattern), &done, &ov);
1550         ok( ret, "WriteFile error %d\n", GetLastError());
1551         ok(done == sizeof(pattern), "expected number of bytes written %u\n", done);
1552         offset = SetFilePointer(hFile, 0, NULL, FILE_CURRENT);
1553         ok(offset == sizeof(buf) * 2 + sizeof(pattern), "wrong file offset %d\n", offset);
1554     }
1555
1556     CloseHandle(hFile);
1557
1558     /*** Read File *****************************************************/
1559
1560     hFile = CreateFileA(temp_fname, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, 0);
1561     ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA error %d\n", GetLastError());
1562
1563     memset(buf, 0, sizeof(buf));
1564     memset(&ov, 0, sizeof(ov));
1565     S(U(ov)).Offset = PATTERN_OFFSET;
1566     S(U(ov)).OffsetHigh = 0;
1567     rc=ReadFile(hFile, buf, sizeof(pattern), &done, &ov);
1568     /* Win 9x does not support the overlapped I/O on files */
1569     if (rc || GetLastError()!=ERROR_INVALID_PARAMETER) {
1570         ok(rc, "ReadFile error %d\n", GetLastError());
1571         ok(done == sizeof(pattern), "expected number of bytes read %u\n", done);
1572         offset = SetFilePointer(hFile, 0, NULL, FILE_CURRENT);
1573         ok(offset == PATTERN_OFFSET + sizeof(pattern), "wrong file offset %d\n", offset);
1574         ok(!memcmp(buf, pattern, sizeof(pattern)), "pattern match failed\n");
1575     }
1576
1577     CloseHandle(hFile);
1578
1579     ret = DeleteFileA(temp_fname);
1580     ok( ret, "DeleteFileA error %d\n", GetLastError());
1581 }
1582
1583 static void test_LockFile(void)
1584 {
1585     HANDLE handle;
1586     DWORD written;
1587     OVERLAPPED overlapped;
1588     int limited_LockFile;
1589     int limited_UnLockFile;
1590     BOOL ret;
1591
1592     handle = CreateFileA( filename, GENERIC_READ | GENERIC_WRITE,
1593                           FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1594                           CREATE_ALWAYS, 0, 0 );
1595     if (handle == INVALID_HANDLE_VALUE)
1596     {
1597         ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
1598         return;
1599     }
1600     ok( WriteFile( handle, sillytext, strlen(sillytext), &written, NULL ), "write failed\n" );
1601
1602     ok( LockFile( handle, 0, 0, 0, 0 ), "LockFile failed\n" );
1603     ok( UnlockFile( handle, 0, 0, 0, 0 ), "UnlockFile failed\n" );
1604
1605     limited_UnLockFile = 0;
1606     if (UnlockFile( handle, 0, 0, 0, 0 ))
1607     {
1608         limited_UnLockFile = 1;
1609     }
1610
1611     ok( LockFile( handle, 10, 0, 20, 0 ), "LockFile 10,20 failed\n" );
1612     /* overlapping locks must fail */
1613     ok( !LockFile( handle, 12, 0, 10, 0 ), "LockFile 12,10 succeeded\n" );
1614     ok( !LockFile( handle, 5, 0, 6, 0 ), "LockFile 5,6 succeeded\n" );
1615     /* non-overlapping locks must succeed */
1616     ok( LockFile( handle, 5, 0, 5, 0 ), "LockFile 5,5 failed\n" );
1617
1618     ok( !UnlockFile( handle, 10, 0, 10, 0 ), "UnlockFile 10,10 succeeded\n" );
1619     ok( UnlockFile( handle, 10, 0, 20, 0 ), "UnlockFile 10,20 failed\n" );
1620     ok( !UnlockFile( handle, 10, 0, 20, 0 ), "UnlockFile 10,20 again succeeded\n" );
1621     ok( UnlockFile( handle, 5, 0, 5, 0 ), "UnlockFile 5,5 failed\n" );
1622
1623     S(U(overlapped)).Offset = 100;
1624     S(U(overlapped)).OffsetHigh = 0;
1625     overlapped.hEvent = 0;
1626
1627     /* Test for broken LockFileEx a la Windows 95 OSR2. */
1628     if (LockFileEx( handle, 0, 0, 100, 0, &overlapped ))
1629     {
1630         /* LockFileEx is probably OK, test it more. */
1631         ok( LockFileEx( handle, 0, 0, 100, 0, &overlapped ),
1632             "LockFileEx 100,100 failed\n" );
1633     }
1634
1635     /* overlapping shared locks are OK */
1636     S(U(overlapped)).Offset = 150;
1637     limited_UnLockFile || ok( LockFileEx( handle, 0, 0, 100, 0, &overlapped ), "LockFileEx 150,100 failed\n" );
1638
1639     /* but exclusive is not */
1640     ok( !LockFileEx( handle, LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1641                      0, 50, 0, &overlapped ),
1642         "LockFileEx exclusive 150,50 succeeded\n" );
1643     if (!UnlockFileEx( handle, 0, 100, 0, &overlapped ))
1644     { /* UnLockFile is capable. */
1645         S(U(overlapped)).Offset = 100;
1646         ok( !UnlockFileEx( handle, 0, 100, 0, &overlapped ),
1647             "UnlockFileEx 150,100 again succeeded\n" );
1648     }
1649
1650     ret = LockFile( handle, 0, 0x10000000, 0, 0xf0000000 );
1651     if (ret)
1652     {
1653         ok( !LockFile( handle, ~0, ~0, 1, 0 ), "LockFile ~0,1 succeeded\n" );
1654         ok( !LockFile( handle, 0, 0x20000000, 20, 0 ), "LockFile 0x20000000,20 succeeded\n" );
1655         ok( UnlockFile( handle, 0, 0x10000000, 0, 0xf0000000 ), "UnlockFile failed\n" );
1656     }
1657     else  /* win9x */
1658         ok( GetLastError() == ERROR_INVALID_PARAMETER, "wrong LockFile error %u\n", GetLastError() );
1659
1660     /* wrap-around lock should not do anything */
1661     /* (but still succeeds on NT4 so we don't check result) */
1662     LockFile( handle, 0, 0x10000000, 0, 0xf0000001 );
1663
1664     limited_LockFile = 0;
1665     if (!LockFile( handle, ~0, ~0, 1, 0 ))
1666     {
1667         limited_LockFile = 1;
1668     }
1669
1670     limited_UnLockFile || ok( UnlockFile( handle, ~0, ~0, 1, 0 ), "Unlockfile ~0,1 failed\n" );
1671
1672     /* zero-byte lock */
1673     ok( LockFile( handle, 100, 0, 0, 0 ), "LockFile 100,0 failed\n" );
1674     if (!limited_LockFile) ok( !LockFile( handle, 98, 0, 4, 0 ), "LockFile 98,4 succeeded\n" );
1675     ok( LockFile( handle, 90, 0, 10, 0 ), "LockFile 90,10 failed\n" );
1676     if (!limited_LockFile) ok( !LockFile( handle, 100, 0, 10, 0 ), "LockFile 100,10 failed\n" );
1677
1678     ok( UnlockFile( handle, 90, 0, 10, 0 ), "UnlockFile 90,10 failed\n" );
1679     ok( !UnlockFile( handle, 100, 0, 10, 0 ), "UnlockFile 100,10 succeeded\n" );
1680
1681     ok( UnlockFile( handle, 100, 0, 0, 0 ), "UnlockFile 100,0 failed\n" );
1682
1683     CloseHandle( handle );
1684     DeleteFileA( filename );
1685 }
1686
1687 static BOOL create_fake_dll( LPCSTR filename )
1688 {
1689     IMAGE_DOS_HEADER *dos;
1690     IMAGE_NT_HEADERS *nt;
1691     IMAGE_SECTION_HEADER *sec;
1692     BYTE *buffer;
1693     DWORD lfanew = sizeof(*dos);
1694     DWORD size = lfanew + sizeof(*nt) + sizeof(*sec);
1695     DWORD written;
1696     BOOL ret;
1697
1698     HANDLE file = CreateFileA( filename, GENERIC_READ|GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0 );
1699     if (file == INVALID_HANDLE_VALUE) return FALSE;
1700
1701     buffer = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size );
1702
1703     dos = (IMAGE_DOS_HEADER *)buffer;
1704     dos->e_magic    = IMAGE_DOS_SIGNATURE;
1705     dos->e_cblp     = sizeof(*dos);
1706     dos->e_cp       = 1;
1707     dos->e_cparhdr  = lfanew / 16;
1708     dos->e_minalloc = 0;
1709     dos->e_maxalloc = 0xffff;
1710     dos->e_ss       = 0x0000;
1711     dos->e_sp       = 0x00b8;
1712     dos->e_lfarlc   = lfanew;
1713     dos->e_lfanew   = lfanew;
1714
1715     nt = (IMAGE_NT_HEADERS *)(buffer + lfanew);
1716     nt->Signature = IMAGE_NT_SIGNATURE;
1717 #if defined __i386__
1718     nt->FileHeader.Machine = IMAGE_FILE_MACHINE_I386;
1719 #elif defined __x86_64__
1720     nt->FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64;
1721 #elif defined __powerpc__
1722     nt->FileHeader.Machine = IMAGE_FILE_MACHINE_POWERPC;
1723 #else
1724 # error You must specify the machine type
1725 #endif
1726     nt->FileHeader.NumberOfSections = 1;
1727     nt->FileHeader.SizeOfOptionalHeader = IMAGE_SIZEOF_NT_OPTIONAL_HEADER;
1728     nt->FileHeader.Characteristics = IMAGE_FILE_DLL | IMAGE_FILE_EXECUTABLE_IMAGE;
1729     nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR_MAGIC;
1730     nt->OptionalHeader.MajorLinkerVersion = 1;
1731     nt->OptionalHeader.MinorLinkerVersion = 0;
1732     nt->OptionalHeader.ImageBase = 0x10000000;
1733     nt->OptionalHeader.SectionAlignment = 0x1000;
1734     nt->OptionalHeader.FileAlignment = 0x1000;
1735     nt->OptionalHeader.MajorOperatingSystemVersion = 1;
1736     nt->OptionalHeader.MinorOperatingSystemVersion = 0;
1737     nt->OptionalHeader.MajorImageVersion = 1;
1738     nt->OptionalHeader.MinorImageVersion = 0;
1739     nt->OptionalHeader.MajorSubsystemVersion = 4;
1740     nt->OptionalHeader.MinorSubsystemVersion = 0;
1741     nt->OptionalHeader.SizeOfImage = 0x2000;
1742     nt->OptionalHeader.SizeOfHeaders = size;
1743     nt->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_GUI;
1744     nt->OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
1745
1746     sec = (IMAGE_SECTION_HEADER *)(nt + 1);
1747     memcpy( sec->Name, ".rodata", sizeof(".rodata") );
1748     sec->Misc.VirtualSize = 0x1000;
1749     sec->VirtualAddress   = 0x1000;
1750     sec->SizeOfRawData    = 0;
1751     sec->PointerToRawData = 0;
1752     sec->Characteristics  = IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE;
1753
1754     ret = WriteFile( file, buffer, size, &written, NULL ) && written == size;
1755     HeapFree( GetProcessHeap(), 0, buffer );
1756     CloseHandle( file );
1757     return ret;
1758 }
1759
1760 static int is_sharing_compatible( DWORD access1, DWORD sharing1, DWORD access2, DWORD sharing2, BOOL is_win9x )
1761 {
1762     if (!is_win9x)
1763     {
1764         if (!access1) sharing1 = FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE;
1765         if (!access2) sharing2 = FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE;
1766     }
1767     else
1768     {
1769         access1 &= ~DELETE;
1770         if (!access1) access1 = GENERIC_READ;
1771
1772         access2 &= ~DELETE;
1773         if (!access2) access2 = GENERIC_READ;
1774     }
1775
1776     if ((access1 & GENERIC_READ) && !(sharing2 & FILE_SHARE_READ)) return 0;
1777     if ((access1 & GENERIC_WRITE) && !(sharing2 & FILE_SHARE_WRITE)) return 0;
1778     if ((access1 & DELETE) && !(sharing2 & FILE_SHARE_DELETE)) return 0;
1779     if ((access2 & GENERIC_READ) && !(sharing1 & FILE_SHARE_READ)) return 0;
1780     if ((access2 & GENERIC_WRITE) && !(sharing1 & FILE_SHARE_WRITE)) return 0;
1781     if ((access2 & DELETE) && !(sharing1 & FILE_SHARE_DELETE)) return 0;
1782     return 1;
1783 }
1784
1785 static int is_sharing_map_compatible( DWORD map_access, DWORD access2, DWORD sharing2 )
1786 {
1787     if ((map_access == PAGE_READWRITE || map_access == PAGE_EXECUTE_READWRITE) &&
1788         !(sharing2 & FILE_SHARE_WRITE)) return 0;
1789     if ((map_access & SEC_IMAGE) && (access2 & GENERIC_WRITE)) return 0;
1790     return 1;
1791 }
1792
1793 static void test_file_sharing(void)
1794 {
1795     static const DWORD access_modes[] =
1796         { 0, GENERIC_READ, GENERIC_WRITE, GENERIC_READ|GENERIC_WRITE,
1797           DELETE, GENERIC_READ|DELETE, GENERIC_WRITE|DELETE, GENERIC_READ|GENERIC_WRITE|DELETE };
1798     static const DWORD sharing_modes[] =
1799         { 0, FILE_SHARE_READ,
1800           FILE_SHARE_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
1801           FILE_SHARE_DELETE, FILE_SHARE_READ|FILE_SHARE_DELETE,
1802           FILE_SHARE_WRITE|FILE_SHARE_DELETE, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE };
1803     static const DWORD mapping_modes[] =
1804         { PAGE_READONLY, PAGE_WRITECOPY, PAGE_READWRITE, SEC_IMAGE | PAGE_WRITECOPY };
1805     int a1, s1, a2, s2;
1806     int ret;
1807     HANDLE h, h2;
1808     BOOL is_win9x = FALSE;
1809
1810     /* make sure the file exists */
1811     if (!create_fake_dll( filename ))
1812     {
1813         ok(0, "couldn't create file \"%s\" (err=%d)\n", filename, GetLastError());
1814         return;
1815     }
1816     is_win9x = GetFileAttributesW(filenameW) == INVALID_FILE_ATTRIBUTES;
1817
1818     for (a1 = 0; a1 < sizeof(access_modes)/sizeof(access_modes[0]); a1++)
1819     {
1820         for (s1 = 0; s1 < sizeof(sharing_modes)/sizeof(sharing_modes[0]); s1++)
1821         {
1822             /* Win9x doesn't support FILE_SHARE_DELETE */
1823             if (is_win9x && (sharing_modes[s1] & FILE_SHARE_DELETE))
1824                 continue;
1825
1826             SetLastError(0xdeadbeef);
1827             h = CreateFileA( filename, access_modes[a1], sharing_modes[s1],
1828                              NULL, OPEN_EXISTING, 0, 0 );
1829             if (h == INVALID_HANDLE_VALUE)
1830             {
1831                 ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
1832                 return;
1833             }
1834             for (a2 = 0; a2 < sizeof(access_modes)/sizeof(access_modes[0]); a2++)
1835             {
1836                 for (s2 = 0; s2 < sizeof(sharing_modes)/sizeof(sharing_modes[0]); s2++)
1837                 {
1838                     /* Win9x doesn't support FILE_SHARE_DELETE */
1839                     if (is_win9x && (sharing_modes[s2] & FILE_SHARE_DELETE))
1840                         continue;
1841
1842                     SetLastError(0xdeadbeef);
1843                     h2 = CreateFileA( filename, access_modes[a2], sharing_modes[s2],
1844                                       NULL, OPEN_EXISTING, 0, 0 );
1845                     ret = GetLastError();
1846                     if (is_sharing_compatible( access_modes[a1], sharing_modes[s1],
1847                                                access_modes[a2], sharing_modes[s2], is_win9x ))
1848                     {
1849                         ok( h2 != INVALID_HANDLE_VALUE,
1850                             "open failed for modes %x/%x/%x/%x\n",
1851                             access_modes[a1], sharing_modes[s1],
1852                             access_modes[a2], sharing_modes[s2] );
1853                         ok( ret == 0xdeadbeef /* Win9x */ ||
1854                             ret == 0, /* XP */
1855                              "wrong error code %d\n", ret );
1856                     }
1857                     else
1858                     {
1859                         ok( h2 == INVALID_HANDLE_VALUE,
1860                             "open succeeded for modes %x/%x/%x/%x\n",
1861                             access_modes[a1], sharing_modes[s1],
1862                             access_modes[a2], sharing_modes[s2] );
1863                          ok( ret == ERROR_SHARING_VIOLATION,
1864                              "wrong error code %d\n", ret );
1865                     }
1866                     if (h2 != INVALID_HANDLE_VALUE) CloseHandle( h2 );
1867                 }
1868             }
1869             CloseHandle( h );
1870         }
1871     }
1872
1873     for (a1 = 0; a1 < sizeof(mapping_modes)/sizeof(mapping_modes[0]); a1++)
1874     {
1875         HANDLE m;
1876
1877         create_fake_dll( filename );
1878         SetLastError(0xdeadbeef);
1879         h = CreateFileA( filename, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0 );
1880         if (h == INVALID_HANDLE_VALUE)
1881         {
1882             ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
1883             return;
1884         }
1885         m = CreateFileMappingA( h, NULL, mapping_modes[a1], 0, 0, NULL );
1886         ok( m != 0, "failed to create mapping %x err %u\n", mapping_modes[a1], GetLastError() );
1887         CloseHandle( h );
1888         if (!m) continue;
1889
1890         for (a2 = 0; a2 < sizeof(access_modes)/sizeof(access_modes[0]); a2++)
1891         {
1892             for (s2 = 0; s2 < sizeof(sharing_modes)/sizeof(sharing_modes[0]); s2++)
1893             {
1894                 /* Win9x doesn't support FILE_SHARE_DELETE */
1895                 if (is_win9x && (sharing_modes[s2] & FILE_SHARE_DELETE))
1896                     continue;
1897
1898                 SetLastError(0xdeadbeef);
1899                 h2 = CreateFileA( filename, access_modes[a2], sharing_modes[s2],
1900                                   NULL, OPEN_EXISTING, 0, 0 );
1901
1902                 ret = GetLastError();
1903                 if (h2 == INVALID_HANDLE_VALUE)
1904                 {
1905                     if (is_sharing_map_compatible(mapping_modes[a1], access_modes[a2], sharing_modes[s2]))
1906                         ok( is_win9x, /* there's no sharing at all with a mapping on win9x */
1907                             "open failed for modes map %x/%x/%x\n",
1908                             mapping_modes[a1], access_modes[a2], sharing_modes[s2] );
1909                     ok( ret == ERROR_SHARING_VIOLATION,
1910                         "wrong error code %d\n", ret );
1911                 }
1912                 else
1913                 {
1914                     if (!is_sharing_map_compatible(mapping_modes[a1], access_modes[a2], sharing_modes[s2]))
1915                         ok( broken(1),  /* no checking on nt4 */
1916                             "open succeeded for modes map %x/%x/%x\n",
1917                             mapping_modes[a1], access_modes[a2], sharing_modes[s2] );
1918                     ok( ret == 0xdeadbeef /* Win9x */ ||
1919                         ret == 0, /* XP */
1920                         "wrong error code %d\n", ret );
1921                     CloseHandle( h2 );
1922                 }
1923             }
1924         }
1925
1926         /* try CREATE_ALWAYS over an existing mapping */
1927         SetLastError(0xdeadbeef);
1928         h2 = CreateFileA( filename, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
1929                           NULL, CREATE_ALWAYS, 0, 0 );
1930         ret = GetLastError();
1931         if ((mapping_modes[a1] & SEC_IMAGE) || is_win9x)
1932         {
1933             ok( h2 == INVALID_HANDLE_VALUE, "create succeeded for map %x\n", mapping_modes[a1] );
1934             ok( ret == ERROR_SHARING_VIOLATION, "wrong error code %d for %x\n", ret, mapping_modes[a1] );
1935         }
1936         else
1937         {
1938             ok( h2 == INVALID_HANDLE_VALUE, "create succeeded for map %x\n", mapping_modes[a1] );
1939             ok( ret == ERROR_USER_MAPPED_FILE, "wrong error code %d for %x\n", ret, mapping_modes[a1] );
1940         }
1941         if (h2 != INVALID_HANDLE_VALUE) CloseHandle( h2 );
1942
1943         /* try DELETE_ON_CLOSE over an existing mapping */
1944         SetLastError(0xdeadbeef);
1945         h2 = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
1946                           NULL, OPEN_EXISTING, FILE_FLAG_DELETE_ON_CLOSE, 0 );
1947         ret = GetLastError();
1948         if (is_win9x)
1949         {
1950             ok( h2 == INVALID_HANDLE_VALUE, "create succeeded for map %x\n", mapping_modes[a1] );
1951             ok( ret == ERROR_SHARING_VIOLATION, "wrong error code %d for %x\n", ret, mapping_modes[a1] );
1952         }
1953         else if (mapping_modes[a1] & SEC_IMAGE)
1954         {
1955             ok( h2 == INVALID_HANDLE_VALUE, "create succeeded for map %x\n", mapping_modes[a1] );
1956             ok( ret == ERROR_ACCESS_DENIED, "wrong error code %d for %x\n", ret, mapping_modes[a1] );
1957         }
1958         else
1959         {
1960             ok( h2 != INVALID_HANDLE_VALUE, "open failed for map %x err %u\n", mapping_modes[a1], ret );
1961         }
1962         if (h2 != INVALID_HANDLE_VALUE) CloseHandle( h2 );
1963
1964         CloseHandle( m );
1965     }
1966
1967     SetLastError(0xdeadbeef);
1968     h = CreateFileA( filename, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, 0, 0 );
1969     ok( h != INVALID_HANDLE_VALUE, "CreateFileA error %d\n", GetLastError() );
1970
1971     SetLastError(0xdeadbeef);
1972     h2 = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
1973     ok( h2 == INVALID_HANDLE_VALUE, "CreateFileA should fail\n");
1974     ok( GetLastError() == ERROR_SHARING_VIOLATION, "wrong error code %d\n", GetLastError() );
1975
1976     h2 = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0 );
1977     ok( h2 != INVALID_HANDLE_VALUE, "CreateFileA error %d\n", GetLastError() );
1978
1979     CloseHandle(h);
1980     CloseHandle(h2);
1981
1982     DeleteFileA( filename );
1983 }
1984
1985 static char get_windows_drive(void)
1986 {
1987     char windowsdir[MAX_PATH];
1988     GetWindowsDirectory(windowsdir, sizeof(windowsdir));
1989     return windowsdir[0];
1990 }
1991
1992 static void test_FindFirstFileA(void)
1993 {
1994     HANDLE handle;
1995     WIN32_FIND_DATAA data;
1996     int err;
1997     char buffer[5] = "C:\\";
1998     char buffer2[100];
1999     char nonexistent[MAX_PATH];
2000
2001     /* try FindFirstFileA on "C:\" */
2002     buffer[0] = get_windows_drive();
2003     
2004     SetLastError( 0xdeadbeaf );
2005     handle = FindFirstFileA(buffer, &data);
2006     err = GetLastError();
2007     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on root directory should fail\n" );
2008     ok ( err == ERROR_FILE_NOT_FOUND, "Bad Error number %d\n", err );
2009
2010     /* try FindFirstFileA on "C:\*" */
2011     strcpy(buffer2, buffer);
2012     strcat(buffer2, "*");
2013     handle = FindFirstFileA(buffer2, &data);
2014     ok ( handle != INVALID_HANDLE_VALUE, "FindFirstFile on %s should succeed\n", buffer2 );
2015     ok ( strcmp( data.cFileName, "." ) && strcmp( data.cFileName, ".." ),
2016          "FindFirstFile shouldn't return '%s' in drive root\n", data.cFileName );
2017     if (FindNextFileA( handle, &data ))
2018         ok ( strcmp( data.cFileName, "." ) && strcmp( data.cFileName, ".." ),
2019              "FindNextFile shouldn't return '%s' in drive root\n", data.cFileName );
2020     ok ( FindClose(handle) == TRUE, "Failed to close handle %s\n", buffer2 );
2021
2022     /* try FindFirstFileA on windows dir */
2023     GetWindowsDirectory( buffer2, sizeof(buffer2) );
2024     strcat(buffer2, "\\*");
2025     handle = FindFirstFileA(buffer2, &data);
2026     ok( handle != INVALID_HANDLE_VALUE, "FindFirstFile on %s should succeed\n", buffer2 );
2027     ok( !strcmp( data.cFileName, "." ), "FindFirstFile should return '.' first\n" );
2028     ok( FindNextFileA( handle, &data ), "FindNextFile failed\n" );
2029     ok( !strcmp( data.cFileName, ".." ), "FindNextFile should return '..' as second entry\n" );
2030     while (FindNextFileA( handle, &data ))
2031         ok ( strcmp( data.cFileName, "." ) && strcmp( data.cFileName, ".." ),
2032              "FindNextFile shouldn't return '%s'\n", data.cFileName );
2033     ok ( FindClose(handle) == TRUE, "Failed to close handle %s\n", buffer2 );
2034
2035     /* try FindFirstFileA on "C:\foo\" */
2036     SetLastError( 0xdeadbeaf );
2037     if (!GetTempFileNameA( buffer, "foo", 0, nonexistent ) && GetLastError() == ERROR_ACCESS_DENIED)
2038     {
2039         char tmp[MAX_PATH];
2040         GetTempPathA( sizeof(tmp), tmp );
2041         GetTempFileNameA( tmp, "foo", 0, nonexistent );
2042     }
2043     DeleteFileA( nonexistent );
2044     strcpy(buffer2, nonexistent);
2045     strcat(buffer2, "\\");
2046     handle = FindFirstFileA(buffer2, &data);
2047     err = GetLastError();
2048     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
2049     todo_wine {
2050         ok ( err == ERROR_PATH_NOT_FOUND, "Bad Error number %d\n", err );
2051     }
2052
2053     /* try FindFirstFileA on "C:\foo\bar.txt" */
2054     SetLastError( 0xdeadbeaf );
2055     strcpy(buffer2, nonexistent);
2056     strcat(buffer2, "\\bar.txt");
2057     handle = FindFirstFileA(buffer2, &data);
2058     err = GetLastError();
2059     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
2060     ok ( err == ERROR_PATH_NOT_FOUND, "Bad Error number %d\n", err );
2061
2062     /* try FindFirstFileA on "C:\foo\*.*" */
2063     SetLastError( 0xdeadbeaf );
2064     strcpy(buffer2, nonexistent);
2065     strcat(buffer2, "\\*.*");
2066     handle = FindFirstFileA(buffer2, &data);
2067     err = GetLastError();
2068     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
2069     ok ( err == ERROR_PATH_NOT_FOUND, "Bad Error number %d\n", err );
2070
2071     /* try FindFirstFileA on "foo\bar.txt" */
2072     SetLastError( 0xdeadbeaf );
2073     strcpy(buffer2, nonexistent + 3);
2074     strcat(buffer2, "\\bar.txt");
2075     handle = FindFirstFileA(buffer2, &data);
2076     err = GetLastError();
2077     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
2078     ok ( err == ERROR_PATH_NOT_FOUND, "Bad Error number %d\n", err );
2079
2080     /* try FindFirstFileA on "c:\nul" */
2081     SetLastError( 0xdeadbeaf );
2082     strcpy(buffer2, buffer);
2083     strcat(buffer2, "nul");
2084     handle = FindFirstFileA(buffer2, &data);
2085     err = GetLastError();
2086     ok( handle != INVALID_HANDLE_VALUE, "FindFirstFile on %s failed\n", buffer2 );
2087     ok( 0 == lstrcmpiA(data.cFileName, "nul"), "wrong name %s\n", data.cFileName );
2088     ok( FILE_ATTRIBUTE_ARCHIVE == data.dwFileAttributes ||
2089         FILE_ATTRIBUTE_DEVICE == data.dwFileAttributes /* Win9x */,
2090         "wrong attributes %x\n", data.dwFileAttributes );
2091     if (data.dwFileAttributes == FILE_ATTRIBUTE_ARCHIVE)
2092     {
2093         ok( 0 == data.nFileSizeHigh, "wrong size %d\n", data.nFileSizeHigh );
2094         ok( 0 == data.nFileSizeLow, "wrong size %d\n", data.nFileSizeLow );
2095     }
2096     SetLastError( 0xdeadbeaf );
2097     ok( !FindNextFileA( handle, &data ), "FindNextFileA succeeded\n" );
2098     ok( GetLastError() == ERROR_NO_MORE_FILES, "bad error %d\n", GetLastError() );
2099     ok( FindClose( handle ), "failed to close handle\n" );
2100
2101     /* try FindFirstFileA on "lpt1" */
2102     SetLastError( 0xdeadbeaf );
2103     strcpy(buffer2, "lpt1");
2104     handle = FindFirstFileA(buffer2, &data);
2105     err = GetLastError();
2106     ok( handle != INVALID_HANDLE_VALUE, "FindFirstFile on %s failed\n", buffer2 );
2107     ok( 0 == lstrcmpiA(data.cFileName, "lpt1"), "wrong name %s\n", data.cFileName );
2108     ok( FILE_ATTRIBUTE_ARCHIVE == data.dwFileAttributes ||
2109         FILE_ATTRIBUTE_DEVICE == data.dwFileAttributes /* Win9x */,
2110         "wrong attributes %x\n", data.dwFileAttributes );
2111     if (data.dwFileAttributes == FILE_ATTRIBUTE_ARCHIVE)
2112     {
2113         ok( 0 == data.nFileSizeHigh, "wrong size %d\n", data.nFileSizeHigh );
2114         ok( 0 == data.nFileSizeLow, "wrong size %d\n", data.nFileSizeLow );
2115     }
2116     SetLastError( 0xdeadbeaf );
2117     ok( !FindNextFileA( handle, &data ), "FindNextFileA succeeded\n" );
2118     ok( GetLastError() == ERROR_NO_MORE_FILES, "bad error %d\n", GetLastError() );
2119     ok( FindClose( handle ), "failed to close handle\n" );
2120
2121     /* try FindFirstFileA on "c:\nul\*" */
2122     SetLastError( 0xdeadbeaf );
2123     strcpy(buffer2, buffer);
2124     strcat(buffer2, "nul\\*");
2125     handle = FindFirstFileA(buffer2, &data);
2126     err = GetLastError();
2127     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
2128     ok ( err == ERROR_PATH_NOT_FOUND, "Bad Error number %d\n", err );
2129
2130     /* try FindFirstFileA on "c:\nul*" */
2131     SetLastError( 0xdeadbeaf );
2132     strcpy(buffer2, buffer);
2133     strcat(buffer2, "nul*");
2134     handle = FindFirstFileA(buffer2, &data);
2135     err = GetLastError();
2136     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
2137     ok ( err == ERROR_FILE_NOT_FOUND, "Bad Error number %d\n", err );
2138
2139     /* try FindFirstFileA on "c:\foo\bar\nul" */
2140     SetLastError( 0xdeadbeaf );
2141     strcpy(buffer2, buffer);
2142     strcat(buffer2, "foo\\bar\\nul");
2143     handle = FindFirstFileA(buffer2, &data);
2144     err = GetLastError();
2145     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
2146     ok ( err == ERROR_PATH_NOT_FOUND, "Bad Error number %d\n", err );
2147
2148     /* try FindFirstFileA on "c:\foo\nul\bar" */
2149     SetLastError( 0xdeadbeaf );
2150     strcpy(buffer2, buffer);
2151     strcat(buffer2, "foo\\nul\\bar");
2152     handle = FindFirstFileA(buffer2, &data);
2153     err = GetLastError();
2154     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
2155     ok ( err == ERROR_PATH_NOT_FOUND, "Bad Error number %d\n", err );
2156 }
2157
2158 static void test_FindNextFileA(void)
2159 {
2160     HANDLE handle;
2161     WIN32_FIND_DATAA search_results;
2162     int err;
2163     char buffer[5] = "C:\\*";
2164
2165     buffer[0] = get_windows_drive();
2166     handle = FindFirstFileA(buffer,&search_results);
2167     ok ( handle != INVALID_HANDLE_VALUE, "FindFirstFile on C:\\* should succeed\n" );
2168     while (FindNextFile(handle, &search_results))
2169     {
2170         /* get to the end of the files */
2171     }
2172     ok ( FindClose(handle) == TRUE, "Failed to close handle\n");
2173     err = GetLastError();
2174     ok ( err == ERROR_NO_MORE_FILES, "GetLastError should return ERROR_NO_MORE_FILES\n");
2175 }
2176
2177 static void test_FindFirstFileExA(FINDEX_SEARCH_OPS search_ops)
2178 {
2179     WIN32_FIND_DATAA search_results;
2180     HANDLE handle;
2181     BOOL ret;
2182
2183     if (!pFindFirstFileExA)
2184     {
2185         win_skip("FindFirstFileExA() is missing\n");
2186         return;
2187     }
2188
2189     CreateDirectoryA("test-dir", NULL);
2190     _lclose(_lcreat("test-dir\\file1", 0));
2191     _lclose(_lcreat("test-dir\\file2", 0));
2192     CreateDirectoryA("test-dir\\dir1", NULL);
2193     SetLastError(0xdeadbeef);
2194     handle = pFindFirstFileExA("test-dir\\*", FindExInfoStandard, &search_results, search_ops, NULL, 0);
2195     if (handle == INVALID_HANDLE_VALUE && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2196     {
2197         win_skip("FindFirstFileExA is not implemented\n");
2198         goto cleanup;
2199     }
2200     ok(handle != INVALID_HANDLE_VALUE, "FindFirstFile failed (err=%u)\n", GetLastError());
2201     ok(strcmp(search_results.cFileName, ".") == 0, "First entry should be '.', is %s\n", search_results.cFileName);
2202
2203 #define CHECK_NAME(fn) (strcmp((fn), "file1") == 0 || strcmp((fn), "file2") == 0 || strcmp((fn), "dir1") == 0)
2204
2205     ok(FindNextFile(handle, &search_results), "Fetching second file failed\n");
2206     ok(strcmp(search_results.cFileName, "..") == 0, "Second entry should be '..' is %s\n", search_results.cFileName);
2207
2208     ok(FindNextFile(handle, &search_results), "Fetching third file failed\n");
2209     ok(CHECK_NAME(search_results.cFileName), "Invalid third entry - %s\n", search_results.cFileName);
2210
2211     SetLastError(0xdeadbeef);
2212     ret = FindNextFile(handle, &search_results);
2213     if (!ret && (GetLastError() == ERROR_NO_MORE_FILES) && (search_ops == FindExSearchLimitToDirectories))
2214     {
2215         skip("File system supports directory filtering\n");
2216         /* Results from the previous call are not cleared */
2217         ok(strcmp(search_results.cFileName, "dir1") == 0, "Third entry should be 'dir1' is %s\n", search_results.cFileName);
2218         FindClose( handle );
2219         goto cleanup;
2220     }
2221
2222     ok(ret, "Fetching fourth file failed\n");
2223     ok(CHECK_NAME(search_results.cFileName), "Invalid fourth entry - %s\n", search_results.cFileName);
2224
2225     ok(FindNextFile(handle, &search_results), "Fetching fifth file failed\n");
2226     ok(CHECK_NAME(search_results.cFileName), "Invalid fifth entry - %s\n", search_results.cFileName);
2227
2228 #undef CHECK_NAME
2229
2230     ok(FindNextFile(handle, &search_results) == FALSE, "Fetching sixth file should fail\n");
2231
2232     FindClose( handle );
2233
2234 cleanup:
2235     DeleteFileA("test-dir\\file1");
2236     DeleteFileA("test-dir\\file2");
2237     RemoveDirectoryA("test-dir\\dir1");
2238     RemoveDirectoryA("test-dir");
2239 }
2240
2241 static int test_Mapfile_createtemp(HANDLE *handle)
2242 {
2243     SetFileAttributesA(filename,FILE_ATTRIBUTE_NORMAL);
2244     DeleteFile(filename);
2245     *handle = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, 0,
2246                          CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2247     if (*handle != INVALID_HANDLE_VALUE) {
2248
2249         return 1;
2250     }
2251
2252     return 0;
2253 }
2254
2255 static void test_MapFile(void)
2256 {
2257     HANDLE handle;
2258     HANDLE hmap;
2259
2260     ok(test_Mapfile_createtemp(&handle), "Couldn't create test file.\n");
2261
2262     hmap = CreateFileMapping( handle, NULL, PAGE_READWRITE, 0, 0x1000, "named_file_map" );
2263     ok( hmap != NULL, "mapping should work, I named it!\n" );
2264
2265     ok( CloseHandle( hmap ), "can't close mapping handle\n");
2266
2267     /* We have to close file before we try new stuff with mapping again.
2268        Else we would always succeed on XP or block descriptors on 95. */
2269     hmap = CreateFileMapping( handle, NULL, PAGE_READWRITE, 0, 0, NULL );
2270     ok( hmap != NULL, "We should still be able to map!\n" );
2271     ok( CloseHandle( hmap ), "can't close mapping handle\n");
2272     ok( CloseHandle( handle ), "can't close file handle\n");
2273     handle = NULL;
2274
2275     ok(test_Mapfile_createtemp(&handle), "Couldn't create test file.\n");
2276
2277     hmap = CreateFileMapping( handle, NULL, PAGE_READWRITE, 0, 0, NULL );
2278     ok( hmap == NULL, "mapped zero size file\n");
2279     ok( GetLastError() == ERROR_FILE_INVALID, "not ERROR_FILE_INVALID\n");
2280
2281     hmap = CreateFileMapping( handle, NULL, PAGE_READWRITE, 0x80000000, 0, NULL );
2282     ok( hmap == NULL || broken(hmap != NULL) /* NT4 */, "mapping should fail\n");
2283     /* GetLastError() varies between win9x and WinNT and also depends on the filesystem */
2284     if ( hmap )
2285         CloseHandle( hmap );
2286
2287     hmap = CreateFileMapping( handle, NULL, PAGE_READWRITE, 0x80000000, 0x10000, NULL );
2288     ok( hmap == NULL || broken(hmap != NULL) /* NT4 */, "mapping should fail\n");
2289     /* GetLastError() varies between win9x and WinNT and also depends on the filesystem */
2290     if ( hmap )
2291         CloseHandle( hmap );
2292
2293     /* On XP you can now map again, on Win 95 you cannot. */
2294
2295     ok( CloseHandle( handle ), "can't close file handle\n");
2296     ok( DeleteFileA( filename ), "DeleteFile failed after map\n" );
2297 }
2298
2299 static void test_GetFileType(void)
2300 {
2301     DWORD type;
2302     HANDLE h = CreateFileA( filename, GENERIC_READ|GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0 );
2303     ok( h != INVALID_HANDLE_VALUE, "open %s failed\n", filename );
2304     type = GetFileType(h);
2305     ok( type == FILE_TYPE_DISK, "expected type disk got %d\n", type );
2306     CloseHandle( h );
2307     h = CreateFileA( "nul", GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0 );
2308     ok( h != INVALID_HANDLE_VALUE, "open nul failed\n" );
2309     type = GetFileType(h);
2310     ok( type == FILE_TYPE_CHAR, "expected type char for nul got %d\n", type );
2311     CloseHandle( h );
2312     DeleteFileA( filename );
2313 }
2314
2315 static int completion_count;
2316
2317 static void CALLBACK FileIOComplete(DWORD dwError, DWORD dwBytes, LPOVERLAPPED ovl)
2318 {
2319 /*      printf("(%ld, %ld, %p { %ld, %ld, %ld, %ld, %p })\n", dwError, dwBytes, ovl, ovl->Internal, ovl->InternalHigh, ovl->Offset, ovl->OffsetHigh, ovl->hEvent);*/
2320         ReleaseSemaphore(ovl->hEvent, 1, NULL);
2321         completion_count++;
2322 }
2323
2324 static void test_async_file_errors(void)
2325 {
2326     char szFile[MAX_PATH];
2327     HANDLE hSem = CreateSemaphoreW(NULL, 1, 1, NULL);
2328     HANDLE hFile;
2329     LPVOID lpBuffer = HeapAlloc(GetProcessHeap(), 0, 4096);
2330     OVERLAPPED ovl;
2331     S(U(ovl)).Offset = 0;
2332     S(U(ovl)).OffsetHigh = 0;
2333     ovl.hEvent = hSem;
2334     completion_count = 0;
2335     szFile[0] = '\0';
2336     GetWindowsDirectoryA(szFile, sizeof(szFile)/sizeof(szFile[0])-1-strlen("\\win.ini"));
2337     strcat(szFile, "\\win.ini");
2338     hFile = CreateFileA(szFile, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2339                         NULL, OPEN_ALWAYS, FILE_FLAG_OVERLAPPED, NULL);
2340     if (hFile == INVALID_HANDLE_VALUE)  /* win9x doesn't like FILE_SHARE_DELETE */
2341         hFile = CreateFileA(szFile, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
2342                             NULL, OPEN_ALWAYS, FILE_FLAG_OVERLAPPED, NULL);
2343     ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA(%s ...) failed\n", szFile);
2344     while (TRUE)
2345     {
2346         BOOL res;
2347         DWORD count;
2348         while (WaitForSingleObjectEx(hSem, INFINITE, TRUE) == WAIT_IO_COMPLETION)
2349             ;
2350         res = ReadFileEx(hFile, lpBuffer, 4096, &ovl, FileIOComplete);
2351         /*printf("Offset = %ld, result = %s\n", ovl.Offset, res ? "TRUE" : "FALSE");*/
2352         if (!res)
2353             break;
2354         if (!GetOverlappedResult(hFile, &ovl, &count, FALSE))
2355             break;
2356         S(U(ovl)).Offset += count;
2357         /* i/o completion routine only called if ReadFileEx returned success.
2358          * we only care about violations of this rule so undo what should have
2359          * been done */
2360         completion_count--;
2361     }
2362     ok(completion_count == 0, "completion routine should only be called when ReadFileEx succeeds (this rule was violated %d times)\n", completion_count);
2363     /*printf("Error = %ld\n", GetLastError());*/
2364     HeapFree(GetProcessHeap(), 0, lpBuffer);
2365 }
2366
2367 static void test_read_write(void)
2368 {
2369     DWORD bytes, ret, old_prot;
2370     HANDLE hFile;
2371     char temp_path[MAX_PATH];
2372     char filename[MAX_PATH];
2373     char *mem;
2374     static const char prefix[] = "pfx";
2375
2376     ret = GetTempPathA(MAX_PATH, temp_path);
2377     ok(ret != 0, "GetTempPathA error %d\n", GetLastError());
2378     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
2379
2380     ret = GetTempFileNameA(temp_path, prefix, 0, filename);
2381     ok(ret != 0, "GetTempFileNameA error %d\n", GetLastError());
2382
2383     hFile = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE, 0, NULL,
2384                         CREATE_ALWAYS, FILE_FLAG_RANDOM_ACCESS, 0);
2385     ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA: error %d\n", GetLastError());
2386
2387     SetLastError(12345678);
2388     bytes = 12345678;
2389     ret = WriteFile(hFile, NULL, 0, &bytes, NULL);
2390     ok(ret && GetLastError() == 12345678,
2391         "ret = %d, error %d\n", ret, GetLastError());
2392     ok(!bytes, "bytes = %d\n", bytes);
2393
2394     SetLastError(12345678);
2395     bytes = 12345678;
2396     ret = WriteFile(hFile, NULL, 10, &bytes, NULL);
2397     ok((!ret && GetLastError() == ERROR_INVALID_USER_BUFFER) || /* Win2k */
2398         (ret && GetLastError() == 12345678), /* Win9x */
2399         "ret = %d, error %d\n", ret, GetLastError());
2400     ok(!bytes || /* Win2k */
2401         bytes == 10, /* Win9x */
2402         "bytes = %d\n", bytes);
2403
2404     /* make sure the file contains data */
2405     WriteFile(hFile, "this is the test data", 21, &bytes, NULL);
2406     SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
2407
2408     SetLastError(12345678);
2409     bytes = 12345678;
2410     ret = ReadFile(hFile, NULL, 0, &bytes, NULL);
2411     ok(ret && GetLastError() == 12345678,
2412         "ret = %d, error %d\n", ret, GetLastError());
2413     ok(!bytes, "bytes = %d\n", bytes);
2414
2415     SetLastError(12345678);
2416     bytes = 12345678;
2417     ret = ReadFile(hFile, NULL, 10, &bytes, NULL);
2418     ok(!ret && (GetLastError() == ERROR_NOACCESS || /* Win2k */
2419                 GetLastError() == ERROR_INVALID_PARAMETER), /* Win9x */
2420         "ret = %d, error %d\n", ret, GetLastError());
2421     ok(!bytes, "bytes = %d\n", bytes);
2422
2423     /* test passing protected memory as buffer */
2424
2425     mem = VirtualAlloc( NULL, 0x4000, MEM_COMMIT, PAGE_READWRITE );
2426     ok( mem != NULL, "failed to allocate virtual mem error %u\n", GetLastError() );
2427
2428     ret = WriteFile( hFile, mem, 0x4000, &bytes, NULL );
2429     ok( ret, "WriteFile failed error %u\n", GetLastError() );
2430     ok( bytes == 0x4000, "only wrote %x bytes\n", bytes );
2431
2432     ret = VirtualProtect( mem + 0x2000, 0x2000, PAGE_NOACCESS, &old_prot );
2433     ok( ret, "VirtualProtect failed error %u\n", GetLastError() );
2434
2435     ret = WriteFile( hFile, mem, 0x4000, &bytes, NULL );
2436     ok( !ret, "WriteFile succeeded\n" );
2437     ok( GetLastError() == ERROR_INVALID_USER_BUFFER ||
2438         GetLastError() == ERROR_INVALID_PARAMETER,  /* win9x */
2439         "wrong error %u\n", GetLastError() );
2440     ok( bytes == 0, "wrote %x bytes\n", bytes );
2441
2442     ret = WriteFile( (HANDLE)0xdead, mem, 0x4000, &bytes, NULL );
2443     ok( !ret, "WriteFile succeeded\n" );
2444     ok( GetLastError() == ERROR_INVALID_HANDLE || /* handle is checked before buffer on NT */
2445         GetLastError() == ERROR_INVALID_PARAMETER,  /* win9x */
2446         "wrong error %u\n", GetLastError() );
2447     ok( bytes == 0, "wrote %x bytes\n", bytes );
2448
2449     ret = VirtualProtect( mem, 0x2000, PAGE_NOACCESS, &old_prot );
2450     ok( ret, "VirtualProtect failed error %u\n", GetLastError() );
2451
2452     ret = WriteFile( hFile, mem, 0x4000, &bytes, NULL );
2453     ok( !ret, "WriteFile succeeded\n" );
2454     ok( GetLastError() == ERROR_INVALID_USER_BUFFER ||
2455         GetLastError() == ERROR_INVALID_PARAMETER,  /* win9x */
2456         "wrong error %u\n", GetLastError() );
2457     ok( bytes == 0, "wrote %x bytes\n", bytes );
2458
2459     SetFilePointer( hFile, 0, NULL, FILE_BEGIN );
2460
2461     ret = ReadFile( hFile, mem, 0x4000, &bytes, NULL );
2462     ok( !ret, "ReadFile succeeded\n" );
2463     ok( GetLastError() == ERROR_NOACCESS ||
2464         GetLastError() == ERROR_INVALID_PARAMETER,  /* win9x */
2465         "wrong error %u\n", GetLastError() );
2466     ok( bytes == 0, "read %x bytes\n", bytes );
2467
2468     ret = VirtualProtect( mem, 0x2000, PAGE_READONLY, &old_prot );
2469     ok( ret, "VirtualProtect failed error %u\n", GetLastError() );
2470
2471     ret = ReadFile( hFile, mem, 0x4000, &bytes, NULL );
2472     ok( !ret, "ReadFile succeeded\n" );
2473     ok( GetLastError() == ERROR_NOACCESS ||
2474         GetLastError() == ERROR_INVALID_PARAMETER,  /* win9x */
2475         "wrong error %u\n", GetLastError() );
2476     ok( bytes == 0, "read %x bytes\n", bytes );
2477
2478     ret = VirtualProtect( mem, 0x2000, PAGE_READWRITE, &old_prot );
2479     ok( ret, "VirtualProtect failed error %u\n", GetLastError() );
2480
2481     ret = ReadFile( hFile, mem, 0x4000, &bytes, NULL );
2482     ok( !ret, "ReadFile succeeded\n" );
2483     ok( GetLastError() == ERROR_NOACCESS ||
2484         GetLastError() == ERROR_INVALID_PARAMETER,  /* win9x */
2485         "wrong error %u\n", GetLastError() );
2486     ok( bytes == 0, "read %x bytes\n", bytes );
2487
2488     SetFilePointer( hFile, 0x1234, NULL, FILE_BEGIN );
2489     SetEndOfFile( hFile );
2490     SetFilePointer( hFile, 0, NULL, FILE_BEGIN );
2491
2492     ret = ReadFile( hFile, mem, 0x4000, &bytes, NULL );
2493     ok( !ret, "ReadFile succeeded\n" );
2494     ok( GetLastError() == ERROR_NOACCESS ||
2495         GetLastError() == ERROR_INVALID_PARAMETER,  /* win9x */
2496         "wrong error %u\n", GetLastError() );
2497     ok( bytes == 0, "read %x bytes\n", bytes );
2498
2499     ret = ReadFile( hFile, mem, 0x2000, &bytes, NULL );
2500     ok( ret, "ReadFile failed error %u\n", GetLastError() );
2501     ok( bytes == 0x1234, "read %x bytes\n", bytes );
2502
2503     ret = ReadFile( hFile, NULL, 1, &bytes, NULL );
2504     ok( !ret, "ReadFile succeeded\n" );
2505     ok( GetLastError() == ERROR_NOACCESS ||
2506         GetLastError() == ERROR_INVALID_PARAMETER,  /* win9x */
2507         "wrong error %u\n", GetLastError() );
2508     ok( bytes == 0, "read %x bytes\n", bytes );
2509
2510     VirtualFree( mem, 0, MEM_FREE );
2511
2512     ret = CloseHandle(hFile);
2513     ok( ret, "CloseHandle: error %d\n", GetLastError());
2514     ret = DeleteFileA(filename);
2515     ok( ret, "DeleteFileA: error %d\n", GetLastError());
2516 }
2517
2518 static void test_OpenFile(void)
2519 {
2520     HFILE hFile;
2521     OFSTRUCT ofs;
2522     BOOL ret;
2523     DWORD retval;
2524     
2525     static const char file[] = "regedit.exe";
2526     static const char foo[] = ".\\foo-bar-foo.baz";
2527     static const char *foo_too_long = ".\\foo-bar-foo.baz+++++++++++++++"
2528         "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
2529         "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
2530         "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
2531         "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
2532         "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2533     char buff[MAX_PATH];
2534     char buff_long[4*MAX_PATH];
2535     char filled_0xA5[OFS_MAXPATHNAME];
2536     char *p;
2537     UINT length;
2538     
2539     /* Check for existing file */
2540     if (!pGetSystemWindowsDirectoryA)
2541         length = GetWindowsDirectoryA(buff, MAX_PATH);
2542     else
2543         length = pGetSystemWindowsDirectoryA(buff, MAX_PATH);
2544
2545     if (length + sizeof(file) < MAX_PATH)
2546     {
2547         p = buff + strlen(buff);
2548         if (p > buff && p[-1] != '\\') *p++ = '\\';
2549         strcpy( p, file );
2550         memset(&ofs, 0xA5, sizeof(ofs));
2551         SetLastError(0xfaceabee);
2552
2553         hFile = OpenFile(buff, &ofs, OF_EXIST);
2554         ok( hFile == TRUE, "%s not found : %d\n", buff, GetLastError() );
2555         ok( GetLastError() == 0xfaceabee || GetLastError() == ERROR_SUCCESS, 
2556             "GetLastError() returns %d\n", GetLastError() );
2557         ok( ofs.cBytes == sizeof(ofs), "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
2558         ok( ofs.nErrCode == ERROR_SUCCESS, "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
2559         ok( lstrcmpiA(ofs.szPathName, buff) == 0,
2560             "OpenFile returned '%s', but was expected to return '%s' or string filled with 0xA5\n",
2561             ofs.szPathName, buff );
2562     }
2563
2564     memset(&filled_0xA5, 0xA5, OFS_MAXPATHNAME);
2565     length = GetCurrentDirectoryA(MAX_PATH, buff);
2566
2567     /* Check for nonexistent file */
2568     if (length + sizeof(foo) < MAX_PATH)
2569     {
2570         p = buff + strlen(buff);
2571         if (p > buff && p[-1] != '\\') *p++ = '\\';
2572         strcpy( p, foo + 2 );
2573         memset(&ofs, 0xA5, sizeof(ofs));
2574         SetLastError(0xfaceabee);
2575
2576         hFile = OpenFile(foo, &ofs, OF_EXIST);
2577         ok( hFile == HFILE_ERROR, "hFile != HFILE_ERROR : %d\n", GetLastError());
2578         ok( GetLastError() == ERROR_FILE_NOT_FOUND, "GetLastError() returns %d\n", GetLastError() );
2579         todo_wine
2580         ok( ofs.cBytes == 0xA5, "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
2581         ok( ofs.nErrCode == ERROR_FILE_NOT_FOUND, "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
2582         ok( lstrcmpiA(ofs.szPathName, buff) == 0 || strncmp(ofs.szPathName, filled_0xA5, OFS_MAXPATHNAME) == 0,
2583             "OpenFile returned '%s', but was expected to return '%s' or string filled with 0xA5\n", 
2584             ofs.szPathName, buff );
2585     }
2586
2587     length = GetCurrentDirectoryA(MAX_PATH, buff_long);
2588     length += lstrlenA(foo_too_long + 1);
2589
2590     /* Check for nonexistent file with too long filename */ 
2591     if (length >= OFS_MAXPATHNAME && length < sizeof(buff_long)) 
2592     {
2593         lstrcatA(buff_long, foo_too_long + 1); /* Avoid '.' during concatenation */
2594         memset(&ofs, 0xA5, sizeof(ofs));
2595         SetLastError(0xfaceabee);
2596
2597         hFile = OpenFile(foo_too_long, &ofs, OF_EXIST);
2598         ok( hFile == HFILE_ERROR, "hFile != HFILE_ERROR : %d\n", GetLastError());
2599         ok( GetLastError() == ERROR_INVALID_DATA || GetLastError() == ERROR_FILENAME_EXCED_RANGE, 
2600             "GetLastError() returns %d\n", GetLastError() );
2601         todo_wine
2602         ok( ofs.cBytes == 0xA5, "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
2603         ok( ofs.nErrCode == ERROR_INVALID_DATA || ofs.nErrCode == ERROR_FILENAME_EXCED_RANGE,
2604             "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
2605         ok( strncmp(ofs.szPathName, filled_0xA5, OFS_MAXPATHNAME) == 0, 
2606             "OpenFile returned '%s', but was expected to return string filled with 0xA5\n", 
2607             ofs.szPathName );
2608     }
2609
2610     length = GetCurrentDirectoryA(MAX_PATH, buff) + sizeof(filename);
2611
2612     if (length >= MAX_PATH) 
2613     {
2614         trace("Buffer too small, requested length = %d, but MAX_PATH = %d.  Skipping test.\n", length, MAX_PATH);
2615         return;
2616     }
2617     p = buff + strlen(buff);
2618     if (p > buff && p[-1] != '\\') *p++ = '\\';
2619     strcpy( p, filename );
2620
2621     memset(&ofs, 0xA5, sizeof(ofs));
2622     SetLastError(0xfaceabee);
2623     /* Create an empty file */
2624     hFile = OpenFile(filename, &ofs, OF_CREATE);
2625     ok( hFile != HFILE_ERROR, "OpenFile failed to create nonexistent file\n" );
2626     ok( GetLastError() == 0xfaceabee || GetLastError() == ERROR_SUCCESS, 
2627         "GetLastError() returns %d\n", GetLastError() );
2628     ok( ofs.cBytes == sizeof(OFSTRUCT), "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
2629     ok( ofs.nErrCode == ERROR_SUCCESS || broken(ofs.nErrCode != ERROR_SUCCESS) /* win9x */,
2630         "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
2631     ret = _lclose(hFile);
2632     ok( !ret, "_lclose() returns %d\n", ret );
2633     retval = GetFileAttributesA(filename);
2634     ok( retval != INVALID_FILE_ATTRIBUTES, "GetFileAttributesA: error %d\n", GetLastError() );
2635
2636     memset(&ofs, 0xA5, sizeof(ofs));
2637     SetLastError(0xfaceabee);
2638     /* Check various opening options: */
2639     /* for reading only, */
2640     hFile = OpenFile(filename, &ofs, OF_READ);
2641     ok( hFile != HFILE_ERROR, "OpenFile failed on read\n" );
2642     ok( GetLastError() == 0xfaceabee || GetLastError() == ERROR_SUCCESS, 
2643         "GetLastError() returns %d\n", GetLastError() );
2644     ok( ofs.cBytes == sizeof(OFSTRUCT), "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
2645     ok( ofs.nErrCode == ERROR_SUCCESS || broken(ofs.nErrCode != ERROR_SUCCESS) /* win9x */,
2646         "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
2647     ok( lstrcmpiA(ofs.szPathName, buff) == 0,
2648         "OpenFile returned '%s', but was expected to return '%s'\n", ofs.szPathName, buff );
2649     ret = _lclose(hFile);
2650     ok( !ret, "_lclose() returns %d\n", ret );
2651
2652     memset(&ofs, 0xA5, sizeof(ofs));
2653     SetLastError(0xfaceabee);
2654     /* for writing only, */
2655     hFile = OpenFile(filename, &ofs, OF_WRITE);
2656     ok( hFile != HFILE_ERROR, "OpenFile failed on write\n" );
2657     ok( GetLastError() == 0xfaceabee || GetLastError() == ERROR_SUCCESS, 
2658         "GetLastError() returns %d\n", GetLastError() );
2659     ok( ofs.cBytes == sizeof(OFSTRUCT), "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
2660     ok( ofs.nErrCode == ERROR_SUCCESS || broken(ofs.nErrCode != ERROR_SUCCESS) /* win9x */,
2661         "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
2662     ok( lstrcmpiA(ofs.szPathName, buff) == 0,
2663         "OpenFile returned '%s', but was expected to return '%s'\n", ofs.szPathName, buff );
2664     ret = _lclose(hFile);
2665     ok( !ret, "_lclose() returns %d\n", ret );
2666
2667     memset(&ofs, 0xA5, sizeof(ofs));
2668     SetLastError(0xfaceabee);
2669     /* for reading and writing, */
2670     hFile = OpenFile(filename, &ofs, OF_READWRITE);
2671     ok( hFile != HFILE_ERROR, "OpenFile failed on read/write\n" );
2672     ok( GetLastError() == 0xfaceabee || GetLastError() == ERROR_SUCCESS, 
2673         "GetLastError() returns %d\n", GetLastError() );
2674     ok( ofs.cBytes == sizeof(OFSTRUCT), "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
2675     ok( ofs.nErrCode == ERROR_SUCCESS || broken(ofs.nErrCode != ERROR_SUCCESS) /* win9x */,
2676         "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
2677     ok( lstrcmpiA(ofs.szPathName, buff) == 0,
2678         "OpenFile returned '%s', but was expected to return '%s'\n", ofs.szPathName, buff );
2679     ret = _lclose(hFile);
2680     ok( !ret, "_lclose() returns %d\n", ret );
2681
2682     memset(&ofs, 0xA5, sizeof(ofs));
2683     SetLastError(0xfaceabee);
2684     /* for checking file presence. */
2685     hFile = OpenFile(filename, &ofs, OF_EXIST);
2686     ok( hFile == 1, "OpenFile failed on finding our created file\n" );
2687     ok( GetLastError() == 0xfaceabee || GetLastError() == ERROR_SUCCESS, 
2688         "GetLastError() returns %d\n", GetLastError() );
2689     ok( ofs.cBytes == sizeof(OFSTRUCT), "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
2690     ok( ofs.nErrCode == ERROR_SUCCESS || broken(ofs.nErrCode != ERROR_SUCCESS) /* win9x */,
2691         "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
2692     ok( lstrcmpiA(ofs.szPathName, buff) == 0,
2693         "OpenFile returned '%s', but was expected to return '%s'\n", ofs.szPathName, buff );
2694
2695     memset(&ofs, 0xA5, sizeof(ofs));
2696     SetLastError(0xfaceabee);
2697     /* Delete the file and make sure it doesn't exist anymore */
2698     hFile = OpenFile(filename, &ofs, OF_DELETE);
2699     ok( hFile == 1, "OpenFile failed on delete (%d)\n", hFile );
2700     ok( GetLastError() == 0xfaceabee || GetLastError() == ERROR_SUCCESS, 
2701         "GetLastError() returns %d\n", GetLastError() );
2702     ok( ofs.cBytes == sizeof(OFSTRUCT), "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
2703     ok( ofs.nErrCode == ERROR_SUCCESS || broken(ofs.nErrCode != ERROR_SUCCESS) /* win9x */,
2704         "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
2705     ok( lstrcmpiA(ofs.szPathName, buff) == 0,
2706         "OpenFile returned '%s', but was expected to return '%s'\n", ofs.szPathName, buff );
2707
2708     retval = GetFileAttributesA(filename);
2709     ok( retval == INVALID_FILE_ATTRIBUTES, "GetFileAttributesA succeeded on deleted file\n" );
2710 }
2711
2712 static void test_overlapped(void)
2713 {
2714     OVERLAPPED ov;
2715     DWORD r, result;
2716
2717     /* GetOverlappedResult crashes if the 2nd or 3rd param are NULL */
2718     if (0) /* tested: WinXP */
2719     {
2720         GetOverlappedResult(0, NULL, &result, FALSE);
2721         GetOverlappedResult(0, &ov, NULL, FALSE);
2722         GetOverlappedResult(0, NULL, NULL, FALSE);
2723     }
2724
2725     memset( &ov, 0,  sizeof ov );
2726     result = 1;
2727     r = GetOverlappedResult(0, &ov, &result, 0);
2728     if (r)
2729         ok( result == 0, "wrong result %u\n", result );
2730     else  /* win9x */
2731         ok( GetLastError() == ERROR_INVALID_HANDLE, "wrong error %u\n", GetLastError() );
2732
2733     result = 0;
2734     ov.Internal = 0;
2735     ov.InternalHigh = 0xabcd;
2736     r = GetOverlappedResult(0, &ov, &result, 0);
2737     if (r)
2738         ok( result == 0xabcd, "wrong result %u\n", result );
2739     else  /* win9x */
2740         ok( GetLastError() == ERROR_INVALID_HANDLE, "wrong error %u\n", GetLastError() );
2741
2742     SetLastError( 0xb00 );
2743     result = 0;
2744     ov.Internal = STATUS_INVALID_HANDLE;
2745     ov.InternalHigh = 0xabcd;
2746     r = GetOverlappedResult(0, &ov, &result, 0);
2747     ok( GetLastError() == ERROR_INVALID_HANDLE, "wrong error %u\n", GetLastError() );
2748     ok( r == FALSE, "should return false\n");
2749     ok( result == 0xabcd || result == 0 /* win9x */, "wrong result %u\n", result );
2750
2751     SetLastError( 0xb00 );
2752     result = 0;
2753     ov.Internal = STATUS_PENDING;
2754     ov.InternalHigh = 0xabcd;
2755     r = GetOverlappedResult(0, &ov, &result, 0);
2756     ok( GetLastError() == ERROR_IO_INCOMPLETE || GetLastError() == ERROR_INVALID_HANDLE /* win9x */,
2757         "wrong error %u\n", GetLastError() );
2758     ok( r == FALSE, "should return false\n");
2759     ok( result == 0, "wrong result %u\n", result );
2760
2761     SetLastError( 0xb00 );
2762     ov.hEvent = CreateEvent( NULL, 1, 1, NULL );
2763     ov.Internal = STATUS_PENDING;
2764     ov.InternalHigh = 0xabcd;
2765     r = GetOverlappedResult(0, &ov, &result, 0);
2766     ok( GetLastError() == ERROR_IO_INCOMPLETE || GetLastError() == ERROR_INVALID_HANDLE /* win9x */,
2767         "wrong error %u\n", GetLastError() );
2768     ok( r == FALSE, "should return false\n");
2769
2770     ResetEvent( ov.hEvent );
2771
2772     SetLastError( 0xb00 );
2773     ov.Internal = STATUS_PENDING;
2774     ov.InternalHigh = 0;
2775     r = GetOverlappedResult(0, &ov, &result, 0);
2776     ok( GetLastError() == ERROR_IO_INCOMPLETE || GetLastError() == ERROR_INVALID_HANDLE /* win9x */,
2777         "wrong error %u\n", GetLastError() );
2778     ok( r == FALSE, "should return false\n");
2779
2780     r = CloseHandle( ov.hEvent );
2781     ok( r == TRUE, "close handle failed\n");
2782 }
2783
2784 static void test_RemoveDirectory(void)
2785 {
2786     int rc;
2787     char directory[] = "removeme";
2788
2789     rc = CreateDirectory(directory, NULL);
2790     ok( rc, "Createdirectory failed, gle=%d\n", GetLastError() );
2791
2792     rc = SetCurrentDirectory(directory);
2793     ok( rc, "SetCurrentDirectory failed, gle=%d\n", GetLastError() );
2794
2795     rc = RemoveDirectory(".");
2796     if (!rc)
2797     {
2798         rc = SetCurrentDirectory("..");
2799         ok( rc, "SetCurrentDirectory failed, gle=%d\n", GetLastError() );
2800
2801         rc = RemoveDirectory(directory);
2802         ok( rc, "RemoveDirectory failed, gle=%d\n", GetLastError() );
2803     }
2804 }
2805
2806 static BOOL check_file_time( const FILETIME *ft1, const FILETIME *ft2, UINT tolerance )
2807 {
2808     ULONGLONG t1 = ((ULONGLONG)ft1->dwHighDateTime << 32) | ft1->dwLowDateTime;
2809     ULONGLONG t2 = ((ULONGLONG)ft2->dwHighDateTime << 32) | ft2->dwLowDateTime;
2810     return abs(t1 - t2) <= tolerance;
2811 }
2812
2813 static void test_ReplaceFileA(void)
2814 {
2815     char replaced[MAX_PATH], replacement[MAX_PATH], backup[MAX_PATH];
2816     HANDLE hReplacedFile, hReplacementFile, hBackupFile;
2817     static const char replacedData[] = "file-to-replace";
2818     static const char replacementData[] = "new-file";
2819     static const char backupData[] = "backup-file";
2820     FILETIME ftReplaced, ftReplacement, ftBackup;
2821     static const char prefix[] = "pfx";
2822     char temp_path[MAX_PATH];
2823     DWORD ret;
2824     BOOL retok, removeBackup = FALSE;
2825
2826     if (!pReplaceFileA)
2827     {
2828         win_skip("ReplaceFileA() is missing\n");
2829         return;
2830     }
2831
2832     ret = GetTempPathA(MAX_PATH, temp_path);
2833     ok(ret != 0, "GetTempPathA error %d\n", GetLastError());
2834     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
2835
2836     ret = GetTempFileNameA(temp_path, prefix, 0, replaced);
2837     ok(ret != 0, "GetTempFileNameA error (replaced) %d\n", GetLastError());
2838
2839     ret = GetTempFileNameA(temp_path, prefix, 0, replacement);
2840     ok(ret != 0, "GetTempFileNameA error (replacement) %d\n", GetLastError());
2841
2842     ret = GetTempFileNameA(temp_path, prefix, 0, backup);
2843     ok(ret != 0, "GetTempFileNameA error (backup) %d\n", GetLastError());
2844
2845     /* place predictable data in the file to be replaced */
2846     hReplacedFile = CreateFileA(replaced, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0 );
2847     ok(hReplacedFile != INVALID_HANDLE_VALUE,
2848         "failed to open replaced file\n");
2849     retok = WriteFile(hReplacedFile, replacedData, sizeof(replacedData), &ret, NULL );
2850     ok( retok && ret == sizeof(replacedData),
2851        "WriteFile error (replaced) %d\n", GetLastError());
2852     ok(GetFileSize(hReplacedFile, NULL) == sizeof(replacedData),
2853         "replaced file has wrong size\n");
2854     /* place predictable data in the file to be the replacement */
2855     hReplacementFile = CreateFileA(replacement, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0 );
2856     ok(hReplacementFile != INVALID_HANDLE_VALUE,
2857         "failed to open replacement file\n");
2858     retok = WriteFile(hReplacementFile, replacementData, sizeof(replacementData), &ret, NULL );
2859     ok( retok && ret == sizeof(replacementData),
2860        "WriteFile error (replacement) %d\n", GetLastError());
2861     ok(GetFileSize(hReplacementFile, NULL) == sizeof(replacementData),
2862         "replacement file has wrong size\n");
2863     /* place predictable data in the backup file (to be over-written) */
2864     hBackupFile = CreateFileA(backup, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0 );
2865     ok(hBackupFile != INVALID_HANDLE_VALUE,
2866         "failed to open backup file\n");
2867     retok = WriteFile(hBackupFile, backupData, sizeof(backupData), &ret, NULL );
2868     ok( retok && ret == sizeof(backupData),
2869        "WriteFile error (replacement) %d\n", GetLastError());
2870     ok(GetFileSize(hBackupFile, NULL) == sizeof(backupData),
2871         "backup file has wrong size\n");
2872     /* change the filetime on the "replaced" file to ensure that it changes */
2873     ret = GetFileTime(hReplacedFile, NULL, NULL, &ftReplaced);
2874     ok( ret, "GetFileTime error (replaced) %d\n", GetLastError());
2875     ftReplaced.dwLowDateTime -= 600000000; /* 60 second */
2876     ret = SetFileTime(hReplacedFile, NULL, NULL, &ftReplaced);
2877     ok( ret, "SetFileTime error (replaced) %d\n", GetLastError());
2878     GetFileTime(hReplacedFile, NULL, NULL, &ftReplaced);  /* get the actual time back */
2879     CloseHandle(hReplacedFile);
2880     /* change the filetime on the backup to ensure that it changes */
2881     ret = GetFileTime(hBackupFile, NULL, NULL, &ftBackup);
2882     ok( ret, "GetFileTime error (backup) %d\n", GetLastError());
2883     ftBackup.dwLowDateTime -= 1200000000; /* 120 second */
2884     ret = SetFileTime(hBackupFile, NULL, NULL, &ftBackup);
2885     ok( ret, "SetFileTime error (backup) %d\n", GetLastError());
2886     GetFileTime(hBackupFile, NULL, NULL, &ftBackup);  /* get the actual time back */
2887     CloseHandle(hBackupFile);
2888     /* get the filetime on the replacement file to perform checks */
2889     ret = GetFileTime(hReplacementFile, NULL, NULL, &ftReplacement);
2890     ok( ret, "GetFileTime error (replacement) %d\n", GetLastError());
2891     CloseHandle(hReplacementFile);
2892
2893     /* perform replacement w/ backup
2894      * TODO: flags are not implemented
2895      */
2896     SetLastError(0xdeadbeef);
2897     ret = pReplaceFileA(replaced, replacement, backup, 0, 0, 0);
2898     ok(ret, "ReplaceFileA: unexpected error %d\n", GetLastError());
2899     /* make sure that the backup has the size of the old "replaced" file */
2900     hBackupFile = CreateFileA(backup, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
2901     ok(hBackupFile != INVALID_HANDLE_VALUE,
2902         "failed to open backup file\n");
2903     ret = GetFileSize(hBackupFile, NULL);
2904     ok(ret == sizeof(replacedData),
2905         "backup file has wrong size %d\n", ret);
2906     /* make sure that the "replaced" file has the size of the replacement file */
2907     hReplacedFile = CreateFileA(replaced, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
2908     ok(hReplacedFile != INVALID_HANDLE_VALUE,
2909         "failed to open replaced file: %d\n", GetLastError());
2910     if (hReplacedFile != INVALID_HANDLE_VALUE)
2911     {
2912         ret = GetFileSize(hReplacedFile, NULL);
2913         ok(ret == sizeof(replacementData),
2914             "replaced file has wrong size %d\n", ret);
2915         /* make sure that the replacement file no-longer exists */
2916         hReplacementFile = CreateFileA(replacement, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
2917         ok(hReplacementFile == INVALID_HANDLE_VALUE,
2918            "unexpected error, replacement file should not exist %d\n", GetLastError());
2919         /* make sure that the backup has the old "replaced" filetime */
2920         ret = GetFileTime(hBackupFile, NULL, NULL, &ftBackup);
2921         ok( ret, "GetFileTime error (backup %d\n", GetLastError());
2922         ok(check_file_time(&ftBackup, &ftReplaced, 20000000), "backup file has wrong filetime\n");
2923         CloseHandle(hBackupFile);
2924         /* make sure that the "replaced" has the old replacement filetime */
2925         ret = GetFileTime(hReplacedFile, NULL, NULL, &ftReplaced);
2926         ok( ret, "GetFileTime error (backup %d\n", GetLastError());
2927         ok(check_file_time(&ftReplaced, &ftReplacement, 20000000),
2928            "replaced file has wrong filetime %x%08x / %x%08x\n",
2929            ftReplaced.dwHighDateTime, ftReplaced.dwLowDateTime,
2930            ftReplacement.dwHighDateTime, ftReplacement.dwLowDateTime );
2931         CloseHandle(hReplacedFile);
2932     }
2933     else
2934         skip("couldn't open replacement file, skipping tests\n");
2935
2936     /* re-create replacement file for pass w/o backup (blank) */
2937     ret = GetTempFileNameA(temp_path, prefix, 0, replacement);
2938     ok(ret != 0, "GetTempFileNameA error (replacement) %d\n", GetLastError());
2939     /* perform replacement w/o backup
2940      * TODO: flags are not implemented
2941      */
2942     SetLastError(0xdeadbeef);
2943     ret = pReplaceFileA(replaced, replacement, NULL, 0, 0, 0);
2944     ok(ret || GetLastError() == ERROR_ACCESS_DENIED,
2945        "ReplaceFileA: unexpected error %d\n", GetLastError());
2946
2947     /* re-create replacement file for pass w/ backup (backup-file not existing) */
2948     ret = GetTempFileNameA(temp_path, prefix, 0, replacement);
2949     ok(ret != 0, "GetTempFileNameA error (replacement) %d\n", GetLastError());
2950     ret = DeleteFileA(backup);
2951     ok(ret, "DeleteFileA: error (backup) %d\n", GetLastError());
2952     /* perform replacement w/ backup (no pre-existing backup)
2953      * TODO: flags are not implemented
2954      */
2955     SetLastError(0xdeadbeef);
2956     ret = pReplaceFileA(replaced, replacement, backup, 0, 0, 0);
2957     ok(ret || GetLastError() == ERROR_ACCESS_DENIED,
2958        "ReplaceFileA: unexpected error %d\n", GetLastError());
2959     if (ret)
2960         removeBackup = TRUE;
2961
2962     /* re-create replacement file for pass w/ no permissions to "replaced" */
2963     ret = GetTempFileNameA(temp_path, prefix, 0, replacement);
2964     ok(ret != 0, "GetTempFileNameA error (replacement) %d\n", GetLastError());
2965     ret = SetFileAttributesA(replaced, FILE_ATTRIBUTE_READONLY);
2966     ok(ret || GetLastError() == ERROR_ACCESS_DENIED,
2967        "SetFileAttributesA: error setting to read only %d\n", GetLastError());
2968     /* perform replacement w/ backup (no permission to "replaced")
2969      * TODO: flags are not implemented
2970      */
2971     SetLastError(0xdeadbeef);
2972     ret = pReplaceFileA(replaced, replacement, backup, 0, 0, 0);
2973     ok(ret != ERROR_UNABLE_TO_REMOVE_REPLACED, "ReplaceFileA: unexpected error %d\n", GetLastError());
2974     /* make sure that the replacement file still exists */
2975     hReplacementFile = CreateFileA(replacement, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
2976     ok(hReplacementFile != INVALID_HANDLE_VALUE ||
2977        broken(GetLastError() == ERROR_FILE_NOT_FOUND), /* win2k */
2978        "unexpected error, replacement file should still exist %d\n", GetLastError());
2979     CloseHandle(hReplacementFile);
2980     ret = SetFileAttributesA(replaced, FILE_ATTRIBUTE_NORMAL);
2981     ok(ret || GetLastError() == ERROR_ACCESS_DENIED,
2982        "SetFileAttributesA: error setting to normal %d\n", GetLastError());
2983
2984     /* replacement file still exists, make pass w/o "replaced" */
2985     ret = DeleteFileA(replaced);
2986     ok(ret || GetLastError() == ERROR_ACCESS_DENIED,
2987        "DeleteFileA: error (replaced) %d\n", GetLastError());
2988     /* perform replacement w/ backup (no pre-existing backup or "replaced")
2989      * TODO: flags are not implemented
2990      */
2991     SetLastError(0xdeadbeef);
2992     ret = pReplaceFileA(replaced, replacement, backup, 0, 0, 0);
2993     ok(!ret && (GetLastError() == ERROR_FILE_NOT_FOUND ||
2994        GetLastError() == ERROR_ACCESS_DENIED),
2995        "ReplaceFileA: unexpected error %d\n", GetLastError());
2996
2997     /* perform replacement w/o existing "replacement" file
2998      * TODO: flags are not implemented
2999      */
3000     SetLastError(0xdeadbeef);
3001     ret = pReplaceFileA(replaced, replacement, NULL, 0, 0, 0);
3002     ok(!ret && (GetLastError() == ERROR_FILE_NOT_FOUND ||
3003         GetLastError() == ERROR_ACCESS_DENIED),
3004         "ReplaceFileA: unexpected error %d\n", GetLastError());
3005
3006     /*
3007      * if the first round (w/ backup) worked then as long as there is no
3008      * failure then there is no need to check this round (w/ backup is the
3009      * more complete case)
3010      */
3011
3012     /* delete temporary files, replacement and replaced are already deleted */
3013     if (removeBackup)
3014     {
3015         ret = DeleteFileA(backup);
3016         ok(ret ||
3017            broken(GetLastError() == ERROR_ACCESS_DENIED), /* win2k */
3018            "DeleteFileA: error (backup) %d\n", GetLastError());
3019     }
3020 }
3021
3022 /*
3023  * ReplaceFileW is a simpler case of ReplaceFileA, there is no
3024  * need to be as thorough.
3025  */
3026 static void test_ReplaceFileW(void)
3027 {
3028     WCHAR replaced[MAX_PATH], replacement[MAX_PATH], backup[MAX_PATH];
3029     static const WCHAR prefix[] = {'p','f','x',0};
3030     WCHAR temp_path[MAX_PATH];
3031     DWORD ret;
3032     BOOL removeBackup = FALSE;
3033
3034     if (!pReplaceFileW)
3035     {
3036         win_skip("ReplaceFileW() is missing\n");
3037         return;
3038     }
3039
3040     ret = GetTempPathW(MAX_PATH, temp_path);
3041     if (ret == 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3042     {
3043         win_skip("GetTempPathW is not available\n");
3044         return;
3045     }
3046     ok(ret != 0, "GetTempPathW error %d\n", GetLastError());
3047     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
3048
3049     ret = GetTempFileNameW(temp_path, prefix, 0, replaced);
3050     ok(ret != 0, "GetTempFileNameW error (replaced) %d\n", GetLastError());
3051
3052     ret = GetTempFileNameW(temp_path, prefix, 0, replacement);
3053     ok(ret != 0, "GetTempFileNameW error (replacement) %d\n", GetLastError());
3054
3055     ret = GetTempFileNameW(temp_path, prefix, 0, backup);
3056     ok(ret != 0, "GetTempFileNameW error (backup) %d\n", GetLastError());
3057
3058     ret = pReplaceFileW(replaced, replacement, backup, 0, 0, 0);
3059     ok(ret, "ReplaceFileW: error %d\n", GetLastError());
3060
3061     ret = GetTempFileNameW(temp_path, prefix, 0, replacement);
3062     ok(ret != 0, "GetTempFileNameW error (replacement) %d\n", GetLastError());
3063     ret = pReplaceFileW(replaced, replacement, NULL, 0, 0, 0);
3064     ok(ret || GetLastError() == ERROR_ACCESS_DENIED,
3065        "ReplaceFileW: error %d\n", GetLastError());
3066
3067     ret = GetTempFileNameW(temp_path, prefix, 0, replacement);
3068     ok(ret != 0, "GetTempFileNameW error (replacement) %d\n", GetLastError());
3069     ret = DeleteFileW(backup);
3070     ok(ret, "DeleteFileW: error (backup) %d\n", GetLastError());
3071     ret = pReplaceFileW(replaced, replacement, backup, 0, 0, 0);
3072     ok(ret || GetLastError() == ERROR_ACCESS_DENIED,
3073        "ReplaceFileW: error %d\n", GetLastError());
3074
3075     ret = GetTempFileNameW(temp_path, prefix, 0, replacement);
3076     ok(ret != 0, "GetTempFileNameW error (replacement) %d\n", GetLastError());
3077     ret = SetFileAttributesW(replaced, FILE_ATTRIBUTE_READONLY);
3078     ok(ret || GetLastError() == ERROR_ACCESS_DENIED,
3079        "SetFileAttributesW: error setting to read only %d\n", GetLastError());
3080
3081     ret = pReplaceFileW(replaced, replacement, backup, 0, 0, 0);
3082     ok(ret != ERROR_UNABLE_TO_REMOVE_REPLACED,
3083         "ReplaceFileW: unexpected error %d\n", GetLastError());
3084     ret = SetFileAttributesW(replaced, FILE_ATTRIBUTE_NORMAL);
3085     ok(ret || GetLastError() == ERROR_ACCESS_DENIED,
3086        "SetFileAttributesW: error setting to normal %d\n", GetLastError());
3087     if (ret)
3088         removeBackup = TRUE;
3089
3090     ret = DeleteFileW(replaced);
3091     ok(ret, "DeleteFileW: error (replaced) %d\n", GetLastError());
3092     ret = pReplaceFileW(replaced, replacement, backup, 0, 0, 0);
3093     ok(!ret, "ReplaceFileW: error %d\n", GetLastError());
3094
3095     ret = pReplaceFileW(replaced, replacement, NULL, 0, 0, 0);
3096     ok(!ret && (GetLastError() == ERROR_FILE_NOT_FOUND ||
3097        GetLastError() == ERROR_ACCESS_DENIED),
3098         "ReplaceFileW: unexpected error %d\n", GetLastError());
3099
3100     if (removeBackup)
3101     {
3102         ret = DeleteFileW(backup);
3103         ok(ret ||
3104            broken(GetLastError() == ERROR_ACCESS_DENIED), /* win2k */
3105            "DeleteFileW: error (backup) %d\n", GetLastError());
3106     }
3107 }
3108
3109 START_TEST(file)
3110 {
3111     InitFunctionPointers();
3112
3113     test__hread(  );
3114     test__hwrite(  );
3115     test__lclose(  );
3116     test__lcreat(  );
3117     test__llseek(  );
3118     test__llopen(  );
3119     test__lread(  );
3120     test__lwrite(  );
3121     test_GetTempFileNameA();
3122     test_CopyFileA();
3123     test_CopyFileW();
3124     test_CreateFileA();
3125     test_CreateFileW();
3126     test_DeleteFileA();
3127     test_DeleteFileW();
3128     test_MoveFileA();
3129     test_MoveFileW();
3130     test_FindFirstFileA();
3131     test_FindNextFileA();
3132     test_FindFirstFileExA(0);
3133     /* FindExLimitToDirectories is ignored if the file system doesn't support directory filtering */
3134     test_FindFirstFileExA(FindExSearchLimitToDirectories);
3135     test_LockFile();
3136     test_file_sharing();
3137     test_offset_in_overlapped_structure();
3138     test_MapFile();
3139     test_GetFileType();
3140     test_async_file_errors();
3141     test_read_write();
3142     test_OpenFile();
3143     test_overlapped();
3144     test_RemoveDirectory();
3145     test_ReplaceFileA();
3146     test_ReplaceFileW();
3147 }