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