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