Revert "winex11.drv: Optimise getting the bits of a DIB after calling SetDIBits."
[wine] / dlls / kernel32 / tests / file.c
1 /*
2  * Unit tests for file functions in Wine
3  *
4  * Copyright (c) 2002, 2004 Jakob Eriksson
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  */
21
22 #include <stdarg.h>
23 #include <stdlib.h>
24 #include <time.h>
25
26 /* ReplaceFile requires Windows 2000 or newer */
27 #define _WIN32_WINNT 0x0500
28
29 #include "wine/test.h"
30 #include "windef.h"
31 #include "winbase.h"
32 #include "winerror.h"
33
34 static HANDLE (WINAPI *pFindFirstFileExA)(LPCSTR,FINDEX_INFO_LEVELS,LPVOID,FINDEX_SEARCH_OPS,LPVOID,DWORD);
35 static BOOL (WINAPI *pReplaceFileA)(LPCSTR, LPCSTR, LPCSTR, DWORD, LPVOID, LPVOID);
36 static BOOL (WINAPI *pReplaceFileW)(LPCWSTR, LPCWSTR, LPCWSTR, DWORD, LPVOID, LPVOID);
37
38 /* keep filename and filenameW the same */
39 static const char filename[] = "testfile.xxx";
40 static const WCHAR filenameW[] = { 't','e','s','t','f','i','l','e','.','x','x','x',0 };
41 static const char sillytext[] =
42 "en larvig liten text dx \033 gx hej 84 hej 4484 ! \001\033 bla bl\na.. bla bla."
43 "1234 43 4kljf lf &%%%&&&&&& 34 4 34   3############# 33 3 3 3 # 3## 3"
44 "1234 43 4kljf lf &%%%&&&&&& 34 4 34   3############# 33 3 3 3 # 3## 3"
45 "1234 43 4kljf lf &%%%&&&&&& 34 4 34   3############# 33 3 3 3 # 3## 3"
46 "1234 43 4kljf lf &%%%&&&&&& 34 4 34   3############# 33 3 3 3 # 3## 3"
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 "sdlkfjasdlkfj a dslkj adsklf  \n  \nasdklf askldfa sdlkf \nsadklf asdklf asdf ";
52
53 static void InitFunctionPointers(void)
54 {
55     HMODULE hkernel32 = GetModuleHandleA("kernel32");
56
57     pFindFirstFileExA=(void*)GetProcAddress(hkernel32, "FindFirstFileExA");
58     pReplaceFileA=(void*)GetProcAddress(hkernel32, "ReplaceFileA");
59     pReplaceFileW=(void*)GetProcAddress(hkernel32, "ReplaceFileW");
60 }
61
62 static void test__hread( void )
63 {
64     HFILE filehandle;
65     char buffer[10000];
66     long bytes_read;
67     long bytes_wanted;
68     long i;
69     BOOL ret;
70
71     SetFileAttributesA(filename,FILE_ATTRIBUTE_NORMAL); /* be sure to remove stale files */
72     DeleteFileA( filename );
73     filehandle = _lcreat( filename, 0 );
74     if (filehandle == HFILE_ERROR)
75     {
76         ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
77         return;
78     }
79
80     ok( HFILE_ERROR != _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite complains\n" );
81
82     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
83
84     filehandle = _lopen( filename, OF_READ );
85
86     ok( HFILE_ERROR != filehandle, "couldn't open file \"%s\" again (err=%d)\n", filename, GetLastError(  ) );
87
88     bytes_read = _hread( filehandle, buffer, 2 * strlen( sillytext ) );
89
90     ok( lstrlenA( sillytext ) == bytes_read, "file read size error\n" );
91
92     for (bytes_wanted = 0; bytes_wanted < lstrlenA( sillytext ); bytes_wanted++)
93     {
94         ok( 0 == _llseek( filehandle, 0, FILE_BEGIN ), "_llseek complains\n" );
95         ok( _hread( filehandle, buffer, bytes_wanted ) == bytes_wanted, "erratic _hread return value\n" );
96         for (i = 0; i < bytes_wanted; i++)
97         {
98             ok( buffer[i] == sillytext[i], "that's not what's written\n" );
99         }
100     }
101
102     ok( HFILE_ERROR != _lclose( filehandle ), "_lclose complains\n" );
103
104     ret = DeleteFileA( filename );
105     ok( ret != 0, "DeleteFile failed (%d)\n", GetLastError(  ) );
106 }
107
108
109 static void test__hwrite( void )
110 {
111     HFILE filehandle;
112     char buffer[10000];
113     long bytes_read;
114     long bytes_written;
115     long blocks;
116     long i;
117     char *contents;
118     HLOCAL memory_object;
119     char checksum[1];
120     BOOL ret;
121
122     filehandle = _lcreat( filename, 0 );
123     if (filehandle == HFILE_ERROR)
124     {
125         ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
126         return;
127     }
128
129     ok( HFILE_ERROR != _hwrite( filehandle, "", 0 ), "_hwrite complains\n" );
130
131     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
132
133     filehandle = _lopen( filename, OF_READ );
134
135     bytes_read = _hread( filehandle, buffer, 1);
136
137     ok( 0 == bytes_read, "file read size error\n" );
138
139     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
140
141     filehandle = _lopen( filename, OF_READWRITE );
142
143     bytes_written = 0;
144     checksum[0] = '\0';
145     srand( (unsigned)time( NULL ) );
146     for (blocks = 0; blocks < 100; blocks++)
147     {
148         for (i = 0; i < (long)sizeof( buffer ); i++)
149         {
150             buffer[i] = rand(  );
151             checksum[0] = checksum[0] + buffer[i];
152         }
153         ok( HFILE_ERROR != _hwrite( filehandle, buffer, sizeof( buffer ) ), "_hwrite complains\n" );
154         bytes_written = bytes_written + sizeof( buffer );
155     }
156
157     ok( HFILE_ERROR != _hwrite( filehandle, checksum, 1 ), "_hwrite complains\n" );
158     bytes_written++;
159
160     ok( HFILE_ERROR != _lclose( filehandle ), "_lclose complains\n" );
161
162     memory_object = LocalAlloc( LPTR, bytes_written );
163
164     ok( 0 != memory_object, "LocalAlloc fails. (Could be out of memory.)\n" );
165
166     contents = LocalLock( memory_object );
167
168     filehandle = _lopen( filename, OF_READ );
169
170     contents = LocalLock( memory_object );
171
172     ok( NULL != contents, "LocalLock whines\n" );
173
174     ok( bytes_written == _hread( filehandle, contents, bytes_written), "read length differ from write length\n" );
175
176     checksum[0] = '\0';
177     i = 0;
178     do
179     {
180         checksum[0] = checksum[0] + contents[i];
181         i++;
182     }
183     while (i < bytes_written - 1);
184
185     ok( checksum[0] == contents[i], "stored checksum differ from computed checksum\n" );
186
187     ok( HFILE_ERROR != _lclose( filehandle ), "_lclose complains\n" );
188
189     ret = DeleteFileA( filename );
190     ok( ret != 0, "DeleteFile failed (%d)\n", GetLastError(  ) );
191 }
192
193
194 static void test__lclose( void )
195 {
196     HFILE filehandle;
197     BOOL ret;
198
199     filehandle = _lcreat( filename, 0 );
200     if (filehandle == HFILE_ERROR)
201     {
202         ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
203         return;
204     }
205
206     ok( HFILE_ERROR != _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite complains\n" );
207
208     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
209
210     ret = DeleteFileA( filename );
211     ok( ret != 0, "DeleteFile failed (%d)\n", GetLastError(  ) );
212 }
213
214
215 static void test__lcreat( void )
216 {
217     HFILE filehandle;
218     char buffer[10000];
219     WIN32_FIND_DATAA search_results;
220     char slashname[] = "testfi/";
221     int err;
222     HANDLE find;
223     BOOL ret;
224
225     filehandle = _lcreat( filename, 0 );
226     if (filehandle == HFILE_ERROR)
227     {
228         ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
229         return;
230     }
231
232     ok( HFILE_ERROR != _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite complains\n" );
233
234     ok( 0 == _llseek( filehandle, 0, FILE_BEGIN ), "_llseek complains\n" );
235
236     ok( _hread( filehandle, buffer, strlen( sillytext ) ) ==  lstrlenA( sillytext ), "erratic _hread return value\n" );
237
238     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
239
240     ok( INVALID_HANDLE_VALUE != FindFirstFileA( filename, &search_results ), "should be able to find file\n" );
241
242     ret = DeleteFileA(filename);
243     ok( ret != 0, "DeleteFile failed (%d)\n", GetLastError());
244
245     filehandle = _lcreat( filename, 1 ); /* readonly */
246     ok( HFILE_ERROR != filehandle, "couldn't create file \"%s\" (err=%d)\n", filename, GetLastError(  ) );
247
248     ok( HFILE_ERROR != _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite shouldn't be able to write never the less\n" );
249
250     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
251
252     ok( INVALID_HANDLE_VALUE != FindFirstFileA( filename, &search_results ), "should be able to find file\n" );
253
254     ok( 0 == DeleteFileA( filename ), "shouldn't be able to delete a readonly file\n" );
255
256     ok( SetFileAttributesA(filename, FILE_ATTRIBUTE_NORMAL ) != 0, "couldn't change attributes on file\n" );
257
258     ok( DeleteFileA( filename ) != 0, "now it should be possible to delete the file!\n" );
259
260     filehandle = _lcreat( filename, 2 );
261     ok( HFILE_ERROR != filehandle, "couldn't create file \"%s\" (err=%d)\n", filename, GetLastError(  ) );
262
263     ok( HFILE_ERROR != _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite complains\n" );
264
265     ok( 0 == _llseek( filehandle, 0, FILE_BEGIN ), "_llseek complains\n" );
266
267     ok( _hread( filehandle, buffer, strlen( sillytext ) ) ==  lstrlenA( sillytext ), "erratic _hread return value\n" );
268
269     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
270
271     ok( INVALID_HANDLE_VALUE != FindFirstFileA( filename, &search_results ), "should STILL be able to find file\n" );
272
273     ret = DeleteFileA( filename );
274     ok( ret, "DeleteFile failed (%d)\n", GetLastError(  ) );
275
276     filehandle = _lcreat( filename, 4 ); /* SYSTEM file */
277     ok( HFILE_ERROR != filehandle, "couldn't create file \"%s\" (err=%d)\n", filename, GetLastError(  ) );
278
279     ok( HFILE_ERROR != _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite complains\n" );
280
281     ok( 0 == _llseek( filehandle, 0, FILE_BEGIN ), "_llseek complains\n" );
282
283     ok( _hread( filehandle, buffer, strlen( sillytext ) ) ==  lstrlenA( sillytext ), "erratic _hread return value\n" );
284
285     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
286
287     ok( INVALID_HANDLE_VALUE != FindFirstFileA( filename, &search_results ), "should STILL be able to find file\n" );
288
289     ret = DeleteFileA( filename );
290     ok( ret, "DeleteFile failed (%d)\n", GetLastError(  ) );
291
292     filehandle=_lcreat (slashname, 0); /* illegal name */
293     if (HFILE_ERROR==filehandle) {
294       err=GetLastError ();
295       ok (err==ERROR_INVALID_NAME || err==ERROR_PATH_NOT_FOUND,
296           "creating file \"%s\" failed with error %d\n", slashname, err);
297     } else { /* only NT succeeds */
298       _lclose(filehandle);
299       find=FindFirstFileA (slashname, &search_results);
300       if (INVALID_HANDLE_VALUE!=find)
301       {
302         ret = FindClose (find);
303         ok (0 != ret, "FindClose complains (%d)\n", GetLastError ());
304         slashname[strlen(slashname)-1]=0;
305         ok (!strcmp (slashname, search_results.cFileName),
306             "found unexpected name \"%s\"\n", search_results.cFileName);
307         ok (FILE_ATTRIBUTE_ARCHIVE==search_results.dwFileAttributes,
308             "attributes of file \"%s\" are 0x%04x\n", search_results.cFileName,
309             search_results.dwFileAttributes);
310       }
311     ret = DeleteFileA( slashname );
312     ok( ret, "DeleteFile failed (%d)\n", GetLastError(  ) );
313     }
314
315     filehandle=_lcreat (filename, 8); /* illegal attribute */
316     if (HFILE_ERROR==filehandle)
317       ok (0, "couldn't create volume label \"%s\"\n", filename);
318     else {
319       _lclose(filehandle);
320       find=FindFirstFileA (filename, &search_results);
321       if (INVALID_HANDLE_VALUE==find)
322         ok (0, "file \"%s\" not found\n", filename);
323       else {
324         ret = FindClose(find);
325         ok ( 0 != ret, "FindClose complains (%d)\n", GetLastError ());
326         ok (!strcmp (filename, search_results.cFileName),
327             "found unexpected name \"%s\"\n", search_results.cFileName);
328         search_results.dwFileAttributes &= ~FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
329         ok (FILE_ATTRIBUTE_ARCHIVE==search_results.dwFileAttributes,
330             "attributes of file \"%s\" are 0x%04x\n", search_results.cFileName,
331             search_results.dwFileAttributes);
332       }
333     ret = DeleteFileA( filename );
334     ok( ret, "DeleteFile failed (%d)\n", GetLastError(  ) );
335     }
336 }
337
338
339 static void test__llseek( void )
340 {
341     INT i;
342     HFILE filehandle;
343     char buffer[1];
344     long bytes_read;
345     BOOL ret;
346
347     filehandle = _lcreat( filename, 0 );
348     if (filehandle == HFILE_ERROR)
349     {
350         ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
351         return;
352     }
353
354     for (i = 0; i < 400; i++)
355     {
356         ok( HFILE_ERROR != _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite complains\n" );
357     }
358     ok( HFILE_ERROR != _llseek( filehandle, 400 * strlen( sillytext ), FILE_CURRENT ), "should be able to seek\n" );
359     ok( HFILE_ERROR != _llseek( filehandle, 27 + 35 * strlen( sillytext ), FILE_BEGIN ), "should be able to seek\n" );
360
361     bytes_read = _hread( filehandle, buffer, 1);
362     ok( 1 == bytes_read, "file read size error\n" );
363     ok( buffer[0] == sillytext[27], "_llseek error, it got lost seeking\n" );
364     ok( HFILE_ERROR != _llseek( filehandle, -400 * strlen( sillytext ), FILE_END ), "should be able to seek\n" );
365
366     bytes_read = _hread( filehandle, buffer, 1);
367     ok( 1 == bytes_read, "file read size error\n" );
368     ok( buffer[0] == sillytext[0], "_llseek error, it got lost seeking\n" );
369     ok( HFILE_ERROR != _llseek( filehandle, 1000000, FILE_END ), "should be able to seek past file; poor, poor Windows programmers\n" );
370     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
371
372     ret = DeleteFileA( filename );
373     ok( ret, "DeleteFile failed (%d)\n", GetLastError(  ) );
374 }
375
376
377 static void test__llopen( void )
378 {
379     HFILE filehandle;
380     UINT bytes_read;
381     char buffer[10000];
382     BOOL ret;
383
384     filehandle = _lcreat( filename, 0 );
385     if (filehandle == HFILE_ERROR)
386     {
387         ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
388         return;
389     }
390
391     ok( HFILE_ERROR != _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite complains\n" );
392     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
393
394     filehandle = _lopen( filename, OF_READ );
395     ok( HFILE_ERROR == _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite shouldn't be able to write!\n" );
396     bytes_read = _hread( filehandle, buffer, strlen( sillytext ) );
397     ok( strlen( sillytext )  == bytes_read, "file read size error\n" );
398     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
399
400     filehandle = _lopen( filename, OF_READWRITE );
401     bytes_read = _hread( filehandle, buffer, 2 * strlen( sillytext ) );
402     ok( strlen( sillytext )  == bytes_read, "file read size error\n" );
403     ok( HFILE_ERROR != _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite should write just fine\n" );
404     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
405
406     filehandle = _lopen( filename, OF_WRITE );
407     ok( HFILE_ERROR == _hread( filehandle, buffer, 1 ), "you should only be able to write this file\n" );
408     ok( HFILE_ERROR != _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite should write just fine\n" );
409     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
410
411     ret = DeleteFileA( filename );
412     ok( ret, "DeleteFile failed (%d)\n", GetLastError(  ) );
413     /* TODO - add tests for the SHARE modes  -  use two processes to pull this one off */
414 }
415
416
417 static void test__lread( void )
418 {
419     HFILE filehandle;
420     char buffer[10000];
421     long bytes_read;
422     UINT bytes_wanted;
423     UINT i;
424     BOOL ret;
425
426     filehandle = _lcreat( filename, 0 );
427     if (filehandle == HFILE_ERROR)
428     {
429         ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
430         return;
431     }
432
433     ok( HFILE_ERROR != _hwrite( filehandle, sillytext, strlen( sillytext ) ), "_hwrite complains\n" );
434
435     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
436
437     filehandle = _lopen( filename, OF_READ );
438
439     ok( HFILE_ERROR != filehandle, "couldn't open file \"%s\" again (err=%d)\n", filename, GetLastError());
440
441     bytes_read = _lread( filehandle, buffer, 2 * strlen( sillytext ) );
442
443     ok( lstrlenA( sillytext ) == bytes_read, "file read size error\n" );
444
445     for (bytes_wanted = 0; bytes_wanted < strlen( sillytext ); bytes_wanted++)
446     {
447         ok( 0 == _llseek( filehandle, 0, FILE_BEGIN ), "_llseek complains\n" );
448         ok( _lread( filehandle, buffer, bytes_wanted ) == bytes_wanted, "erratic _hread return value\n" );
449         for (i = 0; i < bytes_wanted; i++)
450         {
451             ok( buffer[i] == sillytext[i], "that's not what's written\n" );
452         }
453     }
454
455     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
456
457     ret = DeleteFileA( filename );
458     ok( ret, "DeleteFile failed (%d)\n", GetLastError(  ) );
459 }
460
461
462 static void test__lwrite( void )
463 {
464     HFILE filehandle;
465     char buffer[10000];
466     long bytes_read;
467     long bytes_written;
468     long blocks;
469     long i;
470     char *contents;
471     HLOCAL memory_object;
472     char checksum[1];
473     BOOL ret;
474
475     filehandle = _lcreat( filename, 0 );
476     if (filehandle == HFILE_ERROR)
477     {
478         ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
479         return;
480     }
481
482     ok( HFILE_ERROR != _lwrite( filehandle, "", 0 ), "_hwrite complains\n" );
483
484     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
485
486     filehandle = _lopen( filename, OF_READ );
487
488     bytes_read = _hread( filehandle, buffer, 1);
489
490     ok( 0 == bytes_read, "file read size error\n" );
491
492     ok( HFILE_ERROR != _lclose(filehandle), "_lclose complains\n" );
493
494     filehandle = _lopen( filename, OF_READWRITE );
495
496     bytes_written = 0;
497     checksum[0] = '\0';
498     srand( (unsigned)time( NULL ) );
499     for (blocks = 0; blocks < 100; blocks++)
500     {
501         for (i = 0; i < (long)sizeof( buffer ); i++)
502         {
503             buffer[i] = rand(  );
504             checksum[0] = checksum[0] + buffer[i];
505         }
506         ok( HFILE_ERROR != _lwrite( filehandle, buffer, sizeof( buffer ) ), "_hwrite complains\n" );
507         bytes_written = bytes_written + sizeof( buffer );
508     }
509
510     ok( HFILE_ERROR != _lwrite( filehandle, checksum, 1 ), "_hwrite complains\n" );
511     bytes_written++;
512
513     ok( HFILE_ERROR != _lclose( filehandle ), "_lclose complains\n" );
514
515     memory_object = LocalAlloc( LPTR, bytes_written );
516
517     ok( 0 != memory_object, "LocalAlloc fails, could be out of memory\n" );
518
519     contents = LocalLock( memory_object );
520
521     filehandle = _lopen( filename, OF_READ );
522
523     contents = LocalLock( memory_object );
524
525     ok( NULL != contents, "LocalLock whines\n" );
526
527     ok( bytes_written == _hread( filehandle, contents, bytes_written), "read length differ from write length\n" );
528
529     checksum[0] = '\0';
530     i = 0;
531     do
532     {
533         checksum[0] += contents[i];
534         i++;
535     }
536     while (i < bytes_written - 1);
537
538     ok( checksum[0] == contents[i], "stored checksum differ from computed checksum\n" );
539
540     ok( HFILE_ERROR != _lclose( filehandle ), "_lclose complains\n" );
541
542     ret = DeleteFileA( filename );
543     ok( ret, "DeleteFile failed (%d)\n", GetLastError(  ) );
544 }
545
546 static void test_CopyFileA(void)
547 {
548     char temp_path[MAX_PATH];
549     char source[MAX_PATH], dest[MAX_PATH];
550     static const char prefix[] = "pfx";
551     HANDLE hfile;
552     FILETIME ft1, ft2;
553     char buf[10];
554     DWORD ret;
555     BOOL retok;
556
557     ret = GetTempPathA(MAX_PATH, temp_path);
558     ok(ret != 0, "GetTempPathA error %d\n", GetLastError());
559     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
560
561     ret = GetTempFileNameA(temp_path, prefix, 0, source);
562     ok(ret != 0, "GetTempFileNameA error %d\n", GetLastError());
563
564     /* make the source have not zero size */
565     hfile = CreateFileA(source, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0 );
566     ok(hfile != INVALID_HANDLE_VALUE, "failed to open source file\n");
567     retok = WriteFile(hfile, prefix, sizeof(prefix), &ret, NULL );
568     ok( retok && ret == sizeof(prefix),
569        "WriteFile error %d\n", GetLastError());
570     ok(GetFileSize(hfile, NULL) == sizeof(prefix), "source file has wrong size\n");
571     /* get the file time and change it to prove the difference */
572     ret = GetFileTime(hfile, NULL, NULL, &ft1);
573     ok( ret, "GetFileTime error %d\n", GetLastError());
574     ft1.dwLowDateTime -= 600000000; /* 60 second */
575     ret = SetFileTime(hfile, NULL, NULL, &ft1);
576     ok( ret, "SetFileTime error %d\n", GetLastError());
577     GetFileTime(hfile, NULL, NULL, &ft1);  /* get the actual time back */
578     CloseHandle(hfile);
579
580     ret = GetTempFileNameA(temp_path, prefix, 0, dest);
581     ok(ret != 0, "GetTempFileNameA error %d\n", GetLastError());
582
583     SetLastError(0xdeadbeef);
584     ret = CopyFileA(source, dest, TRUE);
585     ok(!ret && GetLastError() == ERROR_FILE_EXISTS,
586        "CopyFileA: unexpected error %d\n", GetLastError());
587
588     ret = CopyFileA(source, dest, FALSE);
589     ok(ret, "CopyFileA: error %d\n", GetLastError());
590
591     /* make sure that destination has correct size */
592     hfile = CreateFileA(dest, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
593     ok(hfile != INVALID_HANDLE_VALUE, "failed to open destination file\n");
594     ret = GetFileSize(hfile, NULL);
595     ok(ret == sizeof(prefix), "destination file has wrong size %d\n", ret);
596
597     /* make sure that destination has the same filetime */
598     ret = GetFileTime(hfile, NULL, NULL, &ft2);
599     ok( ret, "GetFileTime error %d\n", GetLastError());
600     ok(CompareFileTime(&ft1, &ft2) == 0, "destination file has wrong filetime\n");
601
602     SetLastError(0xdeadbeef);
603     ret = CopyFileA(source, dest, FALSE);
604     ok(!ret && GetLastError() == ERROR_SHARING_VIOLATION,
605        "CopyFileA: ret = %d, unexpected error %d\n", ret, GetLastError());
606
607     /* make sure that destination still has correct size */
608     ret = GetFileSize(hfile, NULL);
609     ok(ret == sizeof(prefix), "destination file has wrong size %d\n", ret);
610     retok = ReadFile(hfile, buf, sizeof(buf), &ret, NULL);
611     ok( retok && ret == sizeof(prefix),
612        "ReadFile: error %d\n", GetLastError());
613     ok(!memcmp(prefix, buf, sizeof(prefix)), "buffer contents mismatch\n");
614     CloseHandle(hfile);
615
616     ret = DeleteFileA(source);
617     ok(ret, "DeleteFileA: error %d\n", GetLastError());
618     ret = DeleteFileA(dest);
619     ok(ret, "DeleteFileA: error %d\n", GetLastError());
620 }
621
622 static void test_CopyFileW(void)
623 {
624     WCHAR temp_path[MAX_PATH];
625     WCHAR source[MAX_PATH], dest[MAX_PATH];
626     static const WCHAR prefix[] = {'p','f','x',0};
627     DWORD ret;
628
629     ret = GetTempPathW(MAX_PATH, temp_path);
630     if (ret==0 && GetLastError()==ERROR_CALL_NOT_IMPLEMENTED)
631         return;
632     ok(ret != 0, "GetTempPathW error %d\n", GetLastError());
633     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
634
635     ret = GetTempFileNameW(temp_path, prefix, 0, source);
636     ok(ret != 0, "GetTempFileNameW error %d\n", GetLastError());
637
638     ret = GetTempFileNameW(temp_path, prefix, 0, dest);
639     ok(ret != 0, "GetTempFileNameW error %d\n", GetLastError());
640
641     ret = CopyFileW(source, dest, TRUE);
642     ok(!ret && GetLastError() == ERROR_FILE_EXISTS,
643        "CopyFileW: unexpected error %d\n", GetLastError());
644
645     ret = CopyFileW(source, dest, FALSE);
646     ok(ret, "CopyFileW: error %d\n", GetLastError());
647
648     ret = DeleteFileW(source);
649     ok(ret, "DeleteFileW: error %d\n", GetLastError());
650     ret = DeleteFileW(dest);
651     ok(ret, "DeleteFileW: error %d\n", GetLastError());
652 }
653
654 static void test_CreateFileA(void)
655 {
656     HANDLE hFile;
657     char temp_path[MAX_PATH];
658     char filename[MAX_PATH];
659     static const char prefix[] = "pfx";
660     DWORD ret;
661
662     ret = GetTempPathA(MAX_PATH, temp_path);
663     ok(ret != 0, "GetTempPathA error %d\n", GetLastError());
664     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
665
666     ret = GetTempFileNameA(temp_path, prefix, 0, filename);
667     ok(ret != 0, "GetTempFileNameA error %d\n", GetLastError());
668
669     SetLastError(0xdeadbeef);
670     hFile = CreateFileA(filename, GENERIC_READ, 0, NULL,
671                         CREATE_NEW, FILE_FLAG_RANDOM_ACCESS, 0);
672     ok(hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_FILE_EXISTS,
673         "CREATE_NEW should fail if file exists and last error value should be ERROR_FILE_EXISTS\n");
674
675     SetLastError(0xdeadbeef);
676     hFile = CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ, NULL,
677                         CREATE_ALWAYS, FILE_FLAG_RANDOM_ACCESS, 0);
678     ok(hFile != INVALID_HANDLE_VALUE && GetLastError() == ERROR_ALREADY_EXISTS,
679        "hFile %p, last error %u\n", hFile, GetLastError());
680
681     CloseHandle(hFile);
682
683     SetLastError(0xdeadbeef);
684     hFile = CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ, NULL,
685                         OPEN_ALWAYS, FILE_FLAG_RANDOM_ACCESS, 0);
686     ok(hFile != INVALID_HANDLE_VALUE && GetLastError() == ERROR_ALREADY_EXISTS,
687        "hFile %p, last error %u\n", hFile, GetLastError());
688
689     CloseHandle(hFile);
690
691     ret = DeleteFileA(filename);
692     ok(ret, "DeleteFileA: error %d\n", GetLastError());
693
694     SetLastError(0xdeadbeef);
695     hFile = CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ, NULL,
696                         OPEN_ALWAYS, FILE_FLAG_RANDOM_ACCESS, 0);
697     ok(hFile != INVALID_HANDLE_VALUE && GetLastError() == 0,
698        "hFile %p, last error %u\n", hFile, GetLastError());
699
700     CloseHandle(hFile);
701
702     ret = DeleteFileA(filename);
703     ok(ret, "DeleteFileA: error %d\n", GetLastError());
704 }
705
706 static void test_CreateFileW(void)
707 {
708     HANDLE hFile;
709     WCHAR temp_path[MAX_PATH];
710     WCHAR filename[MAX_PATH];
711     static const WCHAR emptyW[]={'\0'};
712     static const WCHAR prefix[] = {'p','f','x',0};
713     static const WCHAR bogus[] = { '\\', '\\', '.', '\\', 'B', 'O', 'G', 'U', 'S', 0 };
714     DWORD ret;
715
716     ret = GetTempPathW(MAX_PATH, temp_path);
717     if (ret==0 && GetLastError()==ERROR_CALL_NOT_IMPLEMENTED)
718         return;
719     ok(ret != 0, "GetTempPathW error %d\n", GetLastError());
720     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
721
722     ret = GetTempFileNameW(temp_path, prefix, 0, filename);
723     ok(ret != 0, "GetTempFileNameW error %d\n", GetLastError());
724
725     SetLastError(0xdeadbeef);
726     hFile = CreateFileW(filename, GENERIC_READ, 0, NULL,
727                         CREATE_NEW, FILE_FLAG_RANDOM_ACCESS, 0);
728     ok(hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_FILE_EXISTS,
729         "CREATE_NEW should fail if file exists and last error value should be ERROR_FILE_EXISTS\n");
730
731     SetLastError(0xdeadbeef);
732     hFile = CreateFileW(filename, GENERIC_READ, FILE_SHARE_READ, NULL,
733                         CREATE_ALWAYS, FILE_FLAG_RANDOM_ACCESS, 0);
734     ok(hFile != INVALID_HANDLE_VALUE && GetLastError() == ERROR_ALREADY_EXISTS,
735        "hFile %p, last error %u\n", hFile, GetLastError());
736
737     CloseHandle(hFile);
738
739     SetLastError(0xdeadbeef);
740     hFile = CreateFileW(filename, GENERIC_READ, FILE_SHARE_READ, NULL,
741                         OPEN_ALWAYS, FILE_FLAG_RANDOM_ACCESS, 0);
742     ok(hFile != INVALID_HANDLE_VALUE && GetLastError() == ERROR_ALREADY_EXISTS,
743        "hFile %p, last error %u\n", hFile, GetLastError());
744
745     CloseHandle(hFile);
746
747     ret = DeleteFileW(filename);
748     ok(ret, "DeleteFileW: error %d\n", GetLastError());
749
750     SetLastError(0xdeadbeef);
751     hFile = CreateFileW(filename, GENERIC_READ, FILE_SHARE_READ, NULL,
752                         OPEN_ALWAYS, FILE_FLAG_RANDOM_ACCESS, 0);
753     ok(hFile != INVALID_HANDLE_VALUE && GetLastError() == 0,
754        "hFile %p, last error %u\n", hFile, GetLastError());
755
756     CloseHandle(hFile);
757
758     ret = DeleteFileW(filename);
759     ok(ret, "DeleteFileW: error %d\n", GetLastError());
760
761     if (0)
762     {
763         /* this crashes on NT4.0 */
764         hFile = CreateFileW(NULL, GENERIC_READ, 0, NULL,
765                             CREATE_NEW, FILE_FLAG_RANDOM_ACCESS, 0);
766         ok(hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_PATH_NOT_FOUND,
767            "CreateFileW(NULL) returned ret=%p error=%u\n",hFile,GetLastError());
768     }
769
770     hFile = CreateFileW(emptyW, GENERIC_READ, 0, NULL,
771                         CREATE_NEW, FILE_FLAG_RANDOM_ACCESS, 0);
772     ok(hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_PATH_NOT_FOUND,
773        "CreateFileW(\"\") returned ret=%p error=%d\n",hFile,GetLastError());
774
775     /* test the result of opening a nonexistent driver name */
776     hFile = CreateFileW(bogus, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
777                         OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
778     ok(hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_FILE_NOT_FOUND,
779        "CreateFileW on invalid VxD name returned ret=%p error=%d\n",hFile,GetLastError());
780 }
781
782 static void test_GetTempFileNameA(void)
783 {
784     UINT result;
785     char out[MAX_PATH];
786     char expected[MAX_PATH + 10];
787     char windowsdir[MAX_PATH + 10];
788     char windowsdrive[3];
789
790     result = GetWindowsDirectory(windowsdir, sizeof(windowsdir));
791     ok(result < sizeof(windowsdir), "windowsdir is abnormally long!\n");
792     ok(result != 0, "GetWindowsDirectory: error %d\n", GetLastError());
793
794     /* If the Windows directory is the root directory, it ends in backslash, not else. */
795     if (strlen(windowsdir) != 3) /* As in  "C:\"  or  "F:\"  */
796     {
797         strcat(windowsdir, "\\");
798     }
799
800     windowsdrive[0] = windowsdir[0];
801     windowsdrive[1] = windowsdir[1];
802     windowsdrive[2] = '\0';
803
804     result = GetTempFileNameA(windowsdrive, "abc", 1, out);
805     ok(result != 0, "GetTempFileNameA: error %d\n", GetLastError());
806     ok(((out[0] == windowsdrive[0]) && (out[1] == ':')) && (out[2] == '\\'),
807        "GetTempFileNameA: first three characters should be %c:\\, string was actually %s\n",
808        windowsdrive[0], out);
809
810     result = GetTempFileNameA(windowsdir, "abc", 2, out);
811     ok(result != 0, "GetTempFileNameA: error %d\n", GetLastError());
812     expected[0] = '\0';
813     strcat(expected, windowsdir);
814     strcat(expected, "abc2.tmp");
815     ok(lstrcmpiA(out, expected) == 0, "GetTempFileNameA: Unexpected output \"%s\" vs \"%s\"\n",
816        out, expected);
817 }
818
819 static void test_DeleteFileA( void )
820 {
821     BOOL ret;
822
823     ret = DeleteFileA(NULL);
824     ok(!ret && (GetLastError() == ERROR_INVALID_PARAMETER ||
825                 GetLastError() == ERROR_PATH_NOT_FOUND),
826        "DeleteFileA(NULL) returned ret=%d error=%d\n",ret,GetLastError());
827
828     ret = DeleteFileA("");
829     ok(!ret && (GetLastError() == ERROR_PATH_NOT_FOUND ||
830                 GetLastError() == ERROR_BAD_PATHNAME),
831        "DeleteFileA(\"\") returned ret=%d error=%d\n",ret,GetLastError());
832
833     ret = DeleteFileA("nul");
834     ok(!ret && (GetLastError() == ERROR_FILE_NOT_FOUND ||
835                 GetLastError() == ERROR_INVALID_PARAMETER ||
836                 GetLastError() == ERROR_ACCESS_DENIED ||
837                 GetLastError() == ERROR_INVALID_FUNCTION),
838        "DeleteFileA(\"nul\") returned ret=%d error=%d\n",ret,GetLastError());
839 }
840
841 static void test_DeleteFileW( void )
842 {
843     BOOL ret;
844     static const WCHAR emptyW[]={'\0'};
845
846     ret = DeleteFileW(NULL);
847     if (ret==0 && GetLastError()==ERROR_CALL_NOT_IMPLEMENTED)
848         return;
849     ok(!ret && GetLastError() == ERROR_PATH_NOT_FOUND,
850        "DeleteFileW(NULL) returned ret=%d error=%d\n",ret,GetLastError());
851
852     ret = DeleteFileW(emptyW);
853     ok(!ret && GetLastError() == ERROR_PATH_NOT_FOUND,
854        "DeleteFileW(\"\") returned ret=%d error=%d\n",ret,GetLastError());
855 }
856
857 #define IsDotDir(x)     ((x[0] == '.') && ((x[1] == 0) || ((x[1] == '.') && (x[2] == 0))))
858
859 static void test_MoveFileA(void)
860 {
861     char tempdir[MAX_PATH];
862     char source[MAX_PATH], dest[MAX_PATH];
863     static const char prefix[] = "pfx";
864     DWORD ret;
865
866     ret = GetTempPathA(MAX_PATH, tempdir);
867     ok(ret != 0, "GetTempPathA error %d\n", GetLastError());
868     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
869
870     ret = GetTempFileNameA(tempdir, prefix, 0, source);
871     ok(ret != 0, "GetTempFileNameA error %d\n", GetLastError());
872
873     ret = GetTempFileNameA(tempdir, prefix, 0, dest);
874     ok(ret != 0, "GetTempFileNameA error %d\n", GetLastError());
875
876     ret = MoveFileA(source, dest);
877     ok(!ret && GetLastError() == ERROR_ALREADY_EXISTS,
878        "MoveFileA: unexpected error %d\n", GetLastError());
879
880     ret = DeleteFileA(dest);
881     ok(ret, "DeleteFileA: error %d\n", GetLastError());
882
883     ret = MoveFileA(source, dest);
884     ok(ret, "MoveFileA: failed, error %d\n", GetLastError());
885
886     lstrcatA(tempdir, "Remove Me");
887     ret = CreateDirectoryA(tempdir, NULL);
888     ok(ret == TRUE, "CreateDirectoryA failed\n");
889
890     lstrcpyA(source, dest);
891     lstrcpyA(dest, tempdir);
892     lstrcatA(dest, "\\wild?.*");
893     /* FIXME: if we create a file with wildcards we can't delete it now that DeleteFile works correctly */
894     ret = MoveFileA(source, dest);
895     ok(!ret, "MoveFileA: shouldn't move to wildcard file\n");
896     ok(GetLastError() == ERROR_INVALID_NAME || /* NT */
897        GetLastError() == ERROR_FILE_NOT_FOUND, /* Win9x */
898        "MoveFileA: with wildcards, unexpected error %d\n", GetLastError());
899     if (ret || (GetLastError() != ERROR_INVALID_NAME))
900     {
901         WIN32_FIND_DATAA fd;
902         char temppath[MAX_PATH];
903         HANDLE hFind;
904
905         lstrcpyA(temppath, tempdir);
906         lstrcatA(temppath, "\\*.*");
907         hFind = FindFirstFileA(temppath, &fd);
908         if (INVALID_HANDLE_VALUE != hFind)
909         {
910           LPSTR lpName;
911           do
912           {
913             lpName = fd.cAlternateFileName;
914             if (!lpName[0])
915               lpName = fd.cFileName;
916             ok(IsDotDir(lpName), "MoveFileA: wildcards file created!\n");
917           }
918           while (FindNextFileA(hFind, &fd));
919           FindClose(hFind);
920         }
921     }
922     ret = DeleteFileA(source);
923     ok(ret, "DeleteFileA: error %d\n", GetLastError());
924     ret = DeleteFileA(dest);
925     ok(!ret, "DeleteFileA: error %d\n", GetLastError());
926     ret = RemoveDirectoryA(tempdir);
927     ok(ret, "DeleteDirectoryA: error %d\n", GetLastError());
928 }
929
930 static void test_MoveFileW(void)
931 {
932     WCHAR temp_path[MAX_PATH];
933     WCHAR source[MAX_PATH], dest[MAX_PATH];
934     static const WCHAR prefix[] = {'p','f','x',0};
935     DWORD ret;
936
937     ret = GetTempPathW(MAX_PATH, temp_path);
938     if (ret==0 && GetLastError()==ERROR_CALL_NOT_IMPLEMENTED)
939         return;
940     ok(ret != 0, "GetTempPathW error %d\n", GetLastError());
941     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
942
943     ret = GetTempFileNameW(temp_path, prefix, 0, source);
944     ok(ret != 0, "GetTempFileNameW error %d\n", GetLastError());
945
946     ret = GetTempFileNameW(temp_path, prefix, 0, dest);
947     ok(ret != 0, "GetTempFileNameW error %d\n", GetLastError());
948
949     ret = MoveFileW(source, dest);
950     ok(!ret && GetLastError() == ERROR_ALREADY_EXISTS,
951        "CopyFileW: unexpected error %d\n", GetLastError());
952
953     ret = DeleteFileW(source);
954     ok(ret, "DeleteFileW: error %d\n", GetLastError());
955     ret = DeleteFileW(dest);
956     ok(ret, "DeleteFileW: error %d\n", GetLastError());
957 }
958
959 #define PATTERN_OFFSET 0x10
960
961 static void test_offset_in_overlapped_structure(void)
962 {
963     HANDLE hFile;
964     OVERLAPPED ov;
965     DWORD done, offset;
966     BOOL rc;
967     BYTE buf[256], pattern[] = "TeSt";
968     UINT i;
969     char temp_path[MAX_PATH], temp_fname[MAX_PATH];
970     BOOL ret;
971
972     ret =GetTempPathA(MAX_PATH, temp_path);
973     ok( ret, "GetTempPathA error %d\n", GetLastError());
974     ret =GetTempFileNameA(temp_path, "pfx", 0, temp_fname);
975     ok( ret, "GetTempFileNameA error %d\n", GetLastError());
976
977     /*** Write File *****************************************************/
978
979     hFile = CreateFileA(temp_fname, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
980     ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA error %d\n", GetLastError());
981
982     for(i = 0; i < sizeof(buf); i++) buf[i] = i;
983     ret = WriteFile(hFile, buf, sizeof(buf), &done, NULL);
984     ok( ret, "WriteFile error %d\n", GetLastError());
985     ok(done == sizeof(buf), "expected number of bytes written %u\n", done);
986
987     memset(&ov, 0, sizeof(ov));
988     S(U(ov)).Offset = PATTERN_OFFSET;
989     S(U(ov)).OffsetHigh = 0;
990     rc=WriteFile(hFile, pattern, sizeof(pattern), &done, &ov);
991     /* Win 9x does not support the overlapped I/O on files */
992     if (rc || GetLastError()!=ERROR_INVALID_PARAMETER) {
993         ok(rc, "WriteFile error %d\n", GetLastError());
994         ok(done == sizeof(pattern), "expected number of bytes written %u\n", done);
995         offset = SetFilePointer(hFile, 0, NULL, FILE_CURRENT);
996         ok(offset == PATTERN_OFFSET + sizeof(pattern), "wrong file offset %d\n", offset);
997
998         S(U(ov)).Offset = sizeof(buf) * 2;
999         S(U(ov)).OffsetHigh = 0;
1000         ret = WriteFile(hFile, pattern, sizeof(pattern), &done, &ov);
1001         ok( ret, "WriteFile error %d\n", GetLastError());
1002         ok(done == sizeof(pattern), "expected number of bytes written %u\n", done);
1003         offset = SetFilePointer(hFile, 0, NULL, FILE_CURRENT);
1004         ok(offset == sizeof(buf) * 2 + sizeof(pattern), "wrong file offset %d\n", offset);
1005     }
1006
1007     CloseHandle(hFile);
1008
1009     /*** Read File *****************************************************/
1010
1011     hFile = CreateFileA(temp_fname, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, 0);
1012     ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA error %d\n", GetLastError());
1013
1014     memset(buf, 0, sizeof(buf));
1015     memset(&ov, 0, sizeof(ov));
1016     S(U(ov)).Offset = PATTERN_OFFSET;
1017     S(U(ov)).OffsetHigh = 0;
1018     rc=ReadFile(hFile, buf, sizeof(pattern), &done, &ov);
1019     /* Win 9x does not support the overlapped I/O on files */
1020     if (rc || GetLastError()!=ERROR_INVALID_PARAMETER) {
1021         ok(rc, "ReadFile error %d\n", GetLastError());
1022         ok(done == sizeof(pattern), "expected number of bytes read %u\n", done);
1023         offset = SetFilePointer(hFile, 0, NULL, FILE_CURRENT);
1024         ok(offset == PATTERN_OFFSET + sizeof(pattern), "wrong file offset %d\n", offset);
1025         ok(!memcmp(buf, pattern, sizeof(pattern)), "pattern match failed\n");
1026     }
1027
1028     CloseHandle(hFile);
1029
1030     ret = DeleteFileA(temp_fname);
1031     ok( ret, "DeleteFileA error %d\n", GetLastError());
1032 }
1033
1034 static void test_LockFile(void)
1035 {
1036     HANDLE handle;
1037     DWORD written;
1038     OVERLAPPED overlapped;
1039     int limited_LockFile;
1040     int limited_UnLockFile;
1041
1042     handle = CreateFileA( filename, GENERIC_READ | GENERIC_WRITE,
1043                           FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1044                           CREATE_ALWAYS, 0, 0 );
1045     if (handle == INVALID_HANDLE_VALUE)
1046     {
1047         ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
1048         return;
1049     }
1050     ok( WriteFile( handle, sillytext, strlen(sillytext), &written, NULL ), "write failed\n" );
1051
1052     ok( LockFile( handle, 0, 0, 0, 0 ), "LockFile failed\n" );
1053     ok( UnlockFile( handle, 0, 0, 0, 0 ), "UnlockFile failed\n" );
1054
1055     limited_UnLockFile = 0;
1056     if (UnlockFile( handle, 0, 0, 0, 0 ))
1057     {
1058         limited_UnLockFile = 1;
1059     }
1060
1061     ok( LockFile( handle, 10, 0, 20, 0 ), "LockFile 10,20 failed\n" );
1062     /* overlapping locks must fail */
1063     ok( !LockFile( handle, 12, 0, 10, 0 ), "LockFile 12,10 succeeded\n" );
1064     ok( !LockFile( handle, 5, 0, 6, 0 ), "LockFile 5,6 succeeded\n" );
1065     /* non-overlapping locks must succeed */
1066     ok( LockFile( handle, 5, 0, 5, 0 ), "LockFile 5,5 failed\n" );
1067
1068     ok( !UnlockFile( handle, 10, 0, 10, 0 ), "UnlockFile 10,10 succeeded\n" );
1069     ok( UnlockFile( handle, 10, 0, 20, 0 ), "UnlockFile 10,20 failed\n" );
1070     ok( !UnlockFile( handle, 10, 0, 20, 0 ), "UnlockFile 10,20 again succeeded\n" );
1071     ok( UnlockFile( handle, 5, 0, 5, 0 ), "UnlockFile 5,5 failed\n" );
1072
1073     S(U(overlapped)).Offset = 100;
1074     S(U(overlapped)).OffsetHigh = 0;
1075     overlapped.hEvent = 0;
1076
1077     /* Test for broken LockFileEx a la Windows 95 OSR2. */
1078     if (LockFileEx( handle, 0, 0, 100, 0, &overlapped ))
1079     {
1080         /* LockFileEx is probably OK, test it more. */
1081         ok( LockFileEx( handle, 0, 0, 100, 0, &overlapped ),
1082             "LockFileEx 100,100 failed\n" );
1083     }
1084
1085     /* overlapping shared locks are OK */
1086     S(U(overlapped)).Offset = 150;
1087     limited_UnLockFile || ok( LockFileEx( handle, 0, 0, 100, 0, &overlapped ), "LockFileEx 150,100 failed\n" );
1088
1089     /* but exclusive is not */
1090     ok( !LockFileEx( handle, LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1091                      0, 50, 0, &overlapped ),
1092         "LockFileEx exclusive 150,50 succeeded\n" );
1093     if (!UnlockFileEx( handle, 0, 100, 0, &overlapped ))
1094     { /* UnLockFile is capable. */
1095         S(U(overlapped)).Offset = 100;
1096         ok( !UnlockFileEx( handle, 0, 100, 0, &overlapped ),
1097             "UnlockFileEx 150,100 again succeeded\n" );
1098     }
1099
1100     ok( LockFile( handle, 0, 0x10000000, 0, 0xf0000000 ), "LockFile failed\n" );
1101     ok( !LockFile( handle, ~0, ~0, 1, 0 ), "LockFile ~0,1 succeeded\n" );
1102     ok( !LockFile( handle, 0, 0x20000000, 20, 0 ), "LockFile 0x20000000,20 succeeded\n" );
1103     ok( UnlockFile( handle, 0, 0x10000000, 0, 0xf0000000 ), "UnlockFile failed\n" );
1104
1105     /* wrap-around lock should not do anything */
1106     /* (but still succeeds on NT4 so we don't check result) */
1107     LockFile( handle, 0, 0x10000000, 0, 0xf0000001 );
1108
1109     limited_LockFile = 0;
1110     if (!LockFile( handle, ~0, ~0, 1, 0 ))
1111     {
1112         limited_LockFile = 1;
1113     }
1114
1115     limited_UnLockFile || ok( UnlockFile( handle, ~0, ~0, 1, 0 ), "Unlockfile ~0,1 failed\n" );
1116
1117     /* zero-byte lock */
1118     ok( LockFile( handle, 100, 0, 0, 0 ), "LockFile 100,0 failed\n" );
1119     limited_LockFile || ok( !LockFile( handle, 98, 0, 4, 0 ), "LockFile 98,4 succeeded\n" );
1120     ok( LockFile( handle, 90, 0, 10, 0 ), "LockFile 90,10 failed\n" );
1121     limited_LockFile || ok( !LockFile( handle, 100, 0, 10, 0 ), "LockFile 100,10 failed\n" );
1122
1123     ok( UnlockFile( handle, 90, 0, 10, 0 ), "UnlockFile 90,10 failed\n" );
1124     !ok( UnlockFile( handle, 100, 0, 10, 0 ), "UnlockFile 100,10 failed\n" );
1125
1126     ok( UnlockFile( handle, 100, 0, 0, 0 ), "UnlockFile 100,0 failed\n" );
1127
1128     CloseHandle( handle );
1129     DeleteFileA( filename );
1130 }
1131
1132 static inline int is_sharing_compatible( DWORD access1, DWORD sharing1, DWORD access2, DWORD sharing2, BOOL is_win9x )
1133 {
1134     if (!is_win9x)
1135     {
1136         if (!access1) sharing1 = FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE;
1137         if (!access2) sharing2 = FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE;
1138     }
1139     else
1140     {
1141         access1 &= ~DELETE;
1142         if (!access1) access1 = GENERIC_READ;
1143
1144         access2 &= ~DELETE;
1145         if (!access2) access2 = GENERIC_READ;
1146     }
1147
1148     if ((access1 & GENERIC_READ) && !(sharing2 & FILE_SHARE_READ)) return 0;
1149     if ((access1 & GENERIC_WRITE) && !(sharing2 & FILE_SHARE_WRITE)) return 0;
1150     if ((access1 & DELETE) && !(sharing2 & FILE_SHARE_DELETE)) return 0;
1151     if ((access2 & GENERIC_READ) && !(sharing1 & FILE_SHARE_READ)) return 0;
1152     if ((access2 & GENERIC_WRITE) && !(sharing1 & FILE_SHARE_WRITE)) return 0;
1153     if ((access2 & DELETE) && !(sharing1 & FILE_SHARE_DELETE)) return 0;
1154     return 1;
1155 }
1156
1157 static void test_file_sharing(void)
1158 {
1159     static const DWORD access_modes[] =
1160         { 0, GENERIC_READ, GENERIC_WRITE, GENERIC_READ|GENERIC_WRITE,
1161           DELETE, GENERIC_READ|DELETE, GENERIC_WRITE|DELETE, GENERIC_READ|GENERIC_WRITE|DELETE };
1162     static const DWORD sharing_modes[] =
1163         { 0, FILE_SHARE_READ,
1164           FILE_SHARE_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
1165           FILE_SHARE_DELETE, FILE_SHARE_READ|FILE_SHARE_DELETE,
1166           FILE_SHARE_WRITE|FILE_SHARE_DELETE, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE };
1167     int a1, s1, a2, s2;
1168     int ret;
1169     HANDLE h, h2;
1170     BOOL is_win9x = FALSE;
1171
1172     /* make sure the file exists */
1173     h = CreateFileA( filename, GENERIC_READ|GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0 );
1174     if (h == INVALID_HANDLE_VALUE)
1175     {
1176         ok(0, "couldn't create file \"%s\" (err=%d)\n", filename, GetLastError());
1177         return;
1178     }
1179     is_win9x = GetFileAttributesW(filenameW) == INVALID_FILE_ATTRIBUTES;
1180     CloseHandle( h );
1181
1182     for (a1 = 0; a1 < sizeof(access_modes)/sizeof(access_modes[0]); a1++)
1183     {
1184         for (s1 = 0; s1 < sizeof(sharing_modes)/sizeof(sharing_modes[0]); s1++)
1185         {
1186             /* Win9x doesn't support FILE_SHARE_DELETE */
1187             if (is_win9x && (sharing_modes[s1] & FILE_SHARE_DELETE))
1188                 continue;
1189
1190             SetLastError(0xdeadbeef);
1191             h = CreateFileA( filename, access_modes[a1], sharing_modes[s1],
1192                              NULL, OPEN_EXISTING, 0, 0 );
1193             if (h == INVALID_HANDLE_VALUE)
1194             {
1195                 ok(0,"couldn't create file \"%s\" (err=%d)\n",filename,GetLastError());
1196                 return;
1197             }
1198             for (a2 = 0; a2 < sizeof(access_modes)/sizeof(access_modes[0]); a2++)
1199             {
1200                 for (s2 = 0; s2 < sizeof(sharing_modes)/sizeof(sharing_modes[0]); s2++)
1201                 {
1202                     /* Win9x doesn't support FILE_SHARE_DELETE */
1203                     if (is_win9x && (sharing_modes[s2] & FILE_SHARE_DELETE))
1204                         continue;
1205
1206                     SetLastError(0xdeadbeef);
1207                     h2 = CreateFileA( filename, access_modes[a2], sharing_modes[s2],
1208                                       NULL, OPEN_EXISTING, 0, 0 );
1209
1210                     if (is_sharing_compatible( access_modes[a1], sharing_modes[s1],
1211                                                access_modes[a2], sharing_modes[s2], is_win9x ))
1212                     {
1213                         ret = GetLastError();
1214
1215                         ok( h2 != INVALID_HANDLE_VALUE,
1216                             "open failed for modes %x/%x/%x/%x\n",
1217                             access_modes[a1], sharing_modes[s1],
1218                             access_modes[a2], sharing_modes[s2] );
1219                         ok( ret == 0xdeadbeef /* Win9x */ ||
1220                             ret == 0, /* XP */
1221                              "wrong error code %d\n", ret );
1222
1223                         CloseHandle( h2 );
1224                     }
1225                     else
1226                     {
1227                         ret = GetLastError();
1228
1229                         ok( h2 == INVALID_HANDLE_VALUE,
1230                             "open succeeded for modes %x/%x/%x/%x\n",
1231                             access_modes[a1], sharing_modes[s1],
1232                             access_modes[a2], sharing_modes[s2] );
1233                          ok( ret == ERROR_SHARING_VIOLATION,
1234                              "wrong error code %d\n", ret );
1235                     }
1236                 }
1237             }
1238             CloseHandle( h );
1239         }
1240     }
1241
1242     SetLastError(0xdeadbeef);
1243     h = CreateFileA( filename, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, 0, 0 );
1244     ok( h != INVALID_HANDLE_VALUE, "CreateFileA error %d\n", GetLastError() );
1245
1246     SetLastError(0xdeadbeef);
1247     h2 = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
1248     ok( h2 == INVALID_HANDLE_VALUE, "CreateFileA should fail\n");
1249     ok( GetLastError() == ERROR_SHARING_VIOLATION, "wrong error code %d\n", GetLastError() );
1250
1251     h2 = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0 );
1252     ok( h2 != INVALID_HANDLE_VALUE, "CreateFileA error %d\n", GetLastError() );
1253
1254     CloseHandle(h);
1255     CloseHandle(h2);
1256
1257     DeleteFileA( filename );
1258 }
1259
1260 static char get_windows_drive(void)
1261 {
1262     char windowsdir[MAX_PATH];
1263     GetWindowsDirectory(windowsdir, sizeof(windowsdir));
1264     return windowsdir[0];
1265 }
1266
1267 static void test_FindFirstFileA(void)
1268 {
1269     HANDLE handle;
1270     WIN32_FIND_DATAA data;
1271     int err;
1272     char buffer[5] = "C:\\";
1273     char buffer2[100];
1274
1275     /* try FindFirstFileA on "C:\" */
1276     buffer[0] = get_windows_drive();
1277     
1278     SetLastError( 0xdeadbeaf );
1279     handle = FindFirstFileA(buffer, &data);
1280     err = GetLastError();
1281     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on root directory should fail\n" );
1282     ok ( err == ERROR_FILE_NOT_FOUND, "Bad Error number %d\n", err );
1283
1284     /* try FindFirstFileA on "C:\*" */
1285     strcpy(buffer2, buffer);
1286     strcat(buffer2, "*");
1287     handle = FindFirstFileA(buffer2, &data);
1288     ok ( handle != INVALID_HANDLE_VALUE, "FindFirstFile on %s should succeed\n", buffer2 );
1289     ok ( strcmp( data.cFileName, "." ) && strcmp( data.cFileName, ".." ),
1290          "FindFirstFile shouldn't return '%s' in drive root\n", data.cFileName );
1291     if (FindNextFileA( handle, &data ))
1292         ok ( strcmp( data.cFileName, "." ) && strcmp( data.cFileName, ".." ),
1293              "FindNextFile shouldn't return '%s' in drive root\n", data.cFileName );
1294     ok ( FindClose(handle) == TRUE, "Failed to close handle %s\n", buffer2 );
1295
1296     /* try FindFirstFileA on windows dir */
1297     GetWindowsDirectory( buffer2, sizeof(buffer2) );
1298     strcat(buffer2, "\\*");
1299     handle = FindFirstFileA(buffer2, &data);
1300     ok( handle != INVALID_HANDLE_VALUE, "FindFirstFile on %s should succeed\n", buffer2 );
1301     ok( !strcmp( data.cFileName, "." ), "FindFirstFile should return '.' first\n" );
1302     ok( FindNextFileA( handle, &data ), "FindNextFile failed\n" );
1303     ok( !strcmp( data.cFileName, ".." ), "FindNextFile should return '..' as second entry\n" );
1304     while (FindNextFileA( handle, &data ))
1305         ok ( strcmp( data.cFileName, "." ) && strcmp( data.cFileName, ".." ),
1306              "FindNextFile shouldn't return '%s'\n", data.cFileName );
1307     ok ( FindClose(handle) == TRUE, "Failed to close handle %s\n", buffer2 );
1308
1309     /* try FindFirstFileA on "C:\foo\" */
1310     SetLastError( 0xdeadbeaf );
1311     strcpy(buffer2, buffer);
1312     strcat(buffer2, "foo\\");
1313     handle = FindFirstFileA(buffer2, &data);
1314     err = GetLastError();
1315     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
1316     todo_wine {
1317         ok ( err == ERROR_PATH_NOT_FOUND, "Bad Error number %d\n", err );
1318     }
1319
1320     /* try FindFirstFileA on "C:\foo\bar.txt" */
1321     SetLastError( 0xdeadbeaf );
1322     strcpy(buffer2, buffer);
1323     strcat(buffer2, "foo\\bar.txt");
1324     handle = FindFirstFileA(buffer2, &data);
1325     err = GetLastError();
1326     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
1327     ok ( err == ERROR_PATH_NOT_FOUND, "Bad Error number %d\n", err );
1328
1329     /* try FindFirstFileA on "C:\foo\*.*" */
1330     SetLastError( 0xdeadbeaf );
1331     strcpy(buffer2, buffer);
1332     strcat(buffer2, "foo\\*.*");
1333     handle = FindFirstFileA(buffer2, &data);
1334     err = GetLastError();
1335     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
1336     ok ( err == ERROR_PATH_NOT_FOUND, "Bad Error number %d\n", err );
1337
1338     /* try FindFirstFileA on "foo\bar.txt" */
1339     SetLastError( 0xdeadbeaf );
1340     strcpy(buffer2, "foo\\bar.txt");
1341     handle = FindFirstFileA(buffer2, &data);
1342     err = GetLastError();
1343     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
1344     ok ( err == ERROR_PATH_NOT_FOUND, "Bad Error number %d\n", err );
1345
1346     /* try FindFirstFileA on "c:\nul" */
1347     SetLastError( 0xdeadbeaf );
1348     strcpy(buffer2, buffer);
1349     strcat(buffer2, "nul");
1350     handle = FindFirstFileA(buffer2, &data);
1351     err = GetLastError();
1352     ok( handle != INVALID_HANDLE_VALUE, "FindFirstFile on %s failed\n", buffer2 );
1353     ok( 0 == lstrcmpiA(data.cFileName, "nul"), "wrong name %s\n", data.cFileName );
1354     ok( 0 == data.nFileSizeHigh, "wrong size %d\n", data.nFileSizeHigh );
1355     ok( 0 == data.nFileSizeLow, "wrong size %d\n", data.nFileSizeLow );
1356     ok( FILE_ATTRIBUTE_ARCHIVE == data.dwFileAttributes, "wrong attributes %x\n", data.dwFileAttributes );
1357     SetLastError( 0xdeadbeaf );
1358     ok( !FindNextFileA( handle, &data ), "FindNextFileA succeeded\n" );
1359     ok( GetLastError() == ERROR_NO_MORE_FILES, "bad error %d\n", GetLastError() );
1360     ok( FindClose( handle ), "failed to close handle\n" );
1361
1362     /* try FindFirstFileA on "lpt1" */
1363     SetLastError( 0xdeadbeaf );
1364     strcpy(buffer2, "lpt1");
1365     handle = FindFirstFileA(buffer2, &data);
1366     err = GetLastError();
1367     ok( handle != INVALID_HANDLE_VALUE, "FindFirstFile on %s failed\n", buffer2 );
1368     ok( 0 == lstrcmpiA(data.cFileName, "lpt1"), "wrong name %s\n", data.cFileName );
1369     ok( 0 == data.nFileSizeHigh, "wrong size %d\n", data.nFileSizeHigh );
1370     ok( 0 == data.nFileSizeLow, "wrong size %d\n", data.nFileSizeLow );
1371     ok( FILE_ATTRIBUTE_ARCHIVE == data.dwFileAttributes, "wrong attributes %x\n", data.dwFileAttributes );
1372     SetLastError( 0xdeadbeaf );
1373     ok( !FindNextFileA( handle, &data ), "FindNextFileA succeeded\n" );
1374     ok( GetLastError() == ERROR_NO_MORE_FILES, "bad error %d\n", GetLastError() );
1375     ok( FindClose( handle ), "failed to close handle\n" );
1376
1377     /* try FindFirstFileA on "c:\nul\*" */
1378     SetLastError( 0xdeadbeaf );
1379     strcpy(buffer2, buffer);
1380     strcat(buffer2, "nul\\*");
1381     handle = FindFirstFileA(buffer2, &data);
1382     err = GetLastError();
1383     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
1384     ok ( err == ERROR_PATH_NOT_FOUND, "Bad Error number %d\n", err );
1385
1386     /* try FindFirstFileA on "c:\nul*" */
1387     SetLastError( 0xdeadbeaf );
1388     strcpy(buffer2, buffer);
1389     strcat(buffer2, "nul*");
1390     handle = FindFirstFileA(buffer2, &data);
1391     err = GetLastError();
1392     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
1393     ok ( err == ERROR_FILE_NOT_FOUND, "Bad Error number %d\n", err );
1394
1395     /* try FindFirstFileA on "c:\foo\bar\nul" */
1396     SetLastError( 0xdeadbeaf );
1397     strcpy(buffer2, buffer);
1398     strcat(buffer2, "foo\\bar\\nul");
1399     handle = FindFirstFileA(buffer2, &data);
1400     err = GetLastError();
1401     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
1402     ok ( err == ERROR_PATH_NOT_FOUND, "Bad Error number %d\n", err );
1403
1404     /* try FindFirstFileA on "c:\foo\nul\bar" */
1405     SetLastError( 0xdeadbeaf );
1406     strcpy(buffer2, buffer);
1407     strcat(buffer2, "foo\\nul\\bar");
1408     handle = FindFirstFileA(buffer2, &data);
1409     err = GetLastError();
1410     ok ( handle == INVALID_HANDLE_VALUE, "FindFirstFile on %s should Fail\n", buffer2 );
1411     ok ( err == ERROR_PATH_NOT_FOUND, "Bad Error number %d\n", err );
1412 }
1413
1414 static void test_FindNextFileA(void)
1415 {
1416     HANDLE handle;
1417     WIN32_FIND_DATAA search_results;
1418     int err;
1419     char buffer[5] = "C:\\*";
1420
1421     buffer[0] = get_windows_drive();
1422     handle = FindFirstFileA(buffer,&search_results);
1423     ok ( handle != INVALID_HANDLE_VALUE, "FindFirstFile on C:\\* should succeed\n" );
1424     while (FindNextFile(handle, &search_results))
1425     {
1426         /* get to the end of the files */
1427     }
1428     ok ( FindClose(handle) == TRUE, "Failed to close handle\n");
1429     err = GetLastError();
1430     ok ( err == ERROR_NO_MORE_FILES, "GetLastError should return ERROR_NO_MORE_FILES\n");
1431 }
1432
1433 static void test_FindFirstFileExA(void)
1434 {
1435     WIN32_FIND_DATAA search_results;
1436     HANDLE handle;
1437
1438     if (!pFindFirstFileExA)
1439     {
1440         skip("FindFirstFileExA() is missing\n");
1441         return;
1442     }
1443
1444     CreateDirectoryA("test-dir", NULL);
1445     _lclose(_lcreat("test-dir\\file1", 0));
1446     _lclose(_lcreat("test-dir\\file2", 0));
1447     CreateDirectoryA("test-dir\\dir1", NULL);
1448     /* FindExLimitToDirectories is ignored */
1449     SetLastError(0xdeadbeef);
1450     handle = pFindFirstFileExA("test-dir\\*", FindExInfoStandard, &search_results, FindExSearchLimitToDirectories, NULL, 0);
1451     if (handle == INVALID_HANDLE_VALUE && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
1452     {
1453         skip("FindFirstFileExA is not implemented\n");
1454         goto cleanup;
1455     }
1456     ok(handle != INVALID_HANDLE_VALUE, "FindFirstFile failed (err=%u)\n", GetLastError());
1457     ok(strcmp(search_results.cFileName, ".") == 0, "First entry should be '.', is %s\n", search_results.cFileName);
1458
1459 #define CHECK_NAME(fn) (strcmp((fn), "file1") == 0 || strcmp((fn), "file2") == 0 || strcmp((fn), "dir1") == 0)
1460
1461     ok(FindNextFile(handle, &search_results), "Fetching second file failed\n");
1462     ok(strcmp(search_results.cFileName, "..") == 0, "Second entry should be '..' is %s\n", search_results.cFileName);
1463
1464     ok(FindNextFile(handle, &search_results), "Fetching third file failed\n");
1465     ok(CHECK_NAME(search_results.cFileName), "Invalid third entry - %s\n", search_results.cFileName);
1466
1467     ok(FindNextFile(handle, &search_results), "Fetching fourth file failed\n");
1468     ok(CHECK_NAME(search_results.cFileName), "Invalid fourth entry - %s\n", search_results.cFileName);
1469
1470     ok(FindNextFile(handle, &search_results), "Fetching fifth file failed\n");
1471     ok(CHECK_NAME(search_results.cFileName), "Invalid fifth entry - %s\n", search_results.cFileName);
1472
1473 #undef CHECK_NAME
1474
1475     ok(FindNextFile(handle, &search_results) == FALSE, "Fetching sixth file should failed\n");
1476
1477 cleanup:
1478     DeleteFileA("test-dir\\file1");
1479     DeleteFileA("test-dir\\file2");
1480     RemoveDirectoryA("test-dir\\dir1");
1481     RemoveDirectoryA("test-dir");
1482 }
1483
1484 static int test_Mapfile_createtemp(HANDLE *handle)
1485 {
1486     SetFileAttributesA(filename,FILE_ATTRIBUTE_NORMAL);
1487     DeleteFile(filename);
1488     *handle = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, 0,
1489                          CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1490     if (*handle != INVALID_HANDLE_VALUE) {
1491
1492         return 1;
1493     }
1494
1495     return 0;
1496 }
1497
1498 static void test_MapFile(void)
1499 {
1500     HANDLE handle;
1501     HANDLE hmap;
1502
1503     ok(test_Mapfile_createtemp(&handle), "Couldn't create test file.\n");
1504
1505     hmap = CreateFileMapping( handle, NULL, PAGE_READWRITE, 0, 0x1000, "named_file_map" );
1506     ok( hmap != NULL, "mapping should work, I named it!\n" );
1507
1508     ok( CloseHandle( hmap ), "can't close mapping handle\n");
1509
1510     /* We have to close file before we try new stuff with mapping again.
1511        Else we would always succeed on XP or block descriptors on 95. */
1512     hmap = CreateFileMapping( handle, NULL, PAGE_READWRITE, 0, 0, NULL );
1513     ok( hmap != NULL, "We should still be able to map!\n" );
1514     ok( CloseHandle( hmap ), "can't close mapping handle\n");
1515     ok( CloseHandle( handle ), "can't close file handle\n");
1516     handle = NULL;
1517
1518     ok(test_Mapfile_createtemp(&handle), "Couldn't create test file.\n");
1519
1520     hmap = CreateFileMapping( handle, NULL, PAGE_READWRITE, 0, 0, NULL );
1521     ok( hmap == NULL, "mapped zero size file\n");
1522     ok( GetLastError() == ERROR_FILE_INVALID, "not ERROR_FILE_INVALID\n");
1523
1524     hmap = CreateFileMapping( handle, NULL, PAGE_READWRITE, 0x80000000, 0, NULL );
1525     ok( hmap == NULL, "mapping should fail\n");
1526     /* GetLastError() varies between win9x and WinNT and also depends on the filesystem */
1527
1528     hmap = CreateFileMapping( handle, NULL, PAGE_READWRITE, 0x80000000, 0x10000, NULL );
1529     ok( hmap == NULL, "mapping should fail\n");
1530     /* GetLastError() varies between win9x and WinNT and also depends on the filesystem */
1531
1532     /* On XP you can now map again, on Win 95 you cannot. */
1533
1534     ok( CloseHandle( handle ), "can't close file handle\n");
1535     ok( DeleteFileA( filename ), "DeleteFile failed after map\n" );
1536 }
1537
1538 static void test_GetFileType(void)
1539 {
1540     DWORD type;
1541     HANDLE h = CreateFileA( filename, GENERIC_READ|GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0 );
1542     ok( h != INVALID_HANDLE_VALUE, "open %s failed\n", filename );
1543     type = GetFileType(h);
1544     ok( type == FILE_TYPE_DISK, "expected type disk got %d\n", type );
1545     CloseHandle( h );
1546     h = CreateFileA( "nul", GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0 );
1547     ok( h != INVALID_HANDLE_VALUE, "open nul failed\n" );
1548     type = GetFileType(h);
1549     ok( type == FILE_TYPE_CHAR, "expected type char for nul got %d\n", type );
1550     CloseHandle( h );
1551     DeleteFileA( filename );
1552 }
1553
1554 static int completion_count;
1555
1556 static void CALLBACK FileIOComplete(DWORD dwError, DWORD dwBytes, LPOVERLAPPED ovl)
1557 {
1558 /*      printf("(%ld, %ld, %p { %ld, %ld, %ld, %ld, %p })\n", dwError, dwBytes, ovl, ovl->Internal, ovl->InternalHigh, ovl->Offset, ovl->OffsetHigh, ovl->hEvent);*/
1559         ReleaseSemaphore(ovl->hEvent, 1, NULL);
1560         completion_count++;
1561 }
1562
1563 static void test_async_file_errors(void)
1564 {
1565     char szFile[MAX_PATH];
1566     HANDLE hSem = CreateSemaphoreW(NULL, 1, 1, NULL);
1567     HANDLE hFile;
1568     LPVOID lpBuffer = HeapAlloc(GetProcessHeap(), 0, 4096);
1569     OVERLAPPED ovl;
1570     S(U(ovl)).Offset = 0;
1571     S(U(ovl)).OffsetHigh = 0;
1572     ovl.hEvent = hSem;
1573     completion_count = 0;
1574     szFile[0] = '\0';
1575     GetWindowsDirectoryA(szFile, sizeof(szFile)/sizeof(szFile[0])-1-strlen("\\win.ini"));
1576     strcat(szFile, "\\win.ini");
1577     hFile = CreateFileA(szFile, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_ALWAYS, FILE_FLAG_OVERLAPPED, NULL);
1578     ok(hFile != NULL, "CreateFileA(%s ...) failed\n", szFile);
1579     while (TRUE)
1580     {
1581         BOOL res;
1582         while (WaitForSingleObjectEx(hSem, INFINITE, TRUE) == WAIT_IO_COMPLETION)
1583             ;
1584         res = ReadFileEx(hFile, lpBuffer, 4096, &ovl, FileIOComplete);
1585         /*printf("Offset = %ld, result = %s\n", ovl.Offset, res ? "TRUE" : "FALSE");*/
1586         if (!res)
1587             break;
1588         S(U(ovl)).Offset += 4096;
1589         /* i/o completion routine only called if ReadFileEx returned success.
1590          * we only care about violations of this rule so undo what should have
1591          * been done */
1592         completion_count--;
1593     }
1594     ok(completion_count == 0, "completion routine should only be called when ReadFileEx succeeds (this rule was violated %d times)\n", completion_count);
1595     /*printf("Error = %ld\n", GetLastError());*/
1596 }
1597
1598 static void test_read_write(void)
1599 {
1600     DWORD bytes, ret;
1601     HANDLE hFile;
1602     char temp_path[MAX_PATH];
1603     char filename[MAX_PATH];
1604     static const char prefix[] = "pfx";
1605
1606     ret = GetTempPathA(MAX_PATH, temp_path);
1607     ok(ret != 0, "GetTempPathA error %d\n", GetLastError());
1608     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
1609
1610     ret = GetTempFileNameA(temp_path, prefix, 0, filename);
1611     ok(ret != 0, "GetTempFileNameA error %d\n", GetLastError());
1612
1613     hFile = CreateFileA(filename, GENERIC_READ | GENERIC_WRITE, 0, NULL,
1614                         CREATE_ALWAYS, FILE_FLAG_RANDOM_ACCESS, 0);
1615     ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA: error %d\n", GetLastError());
1616
1617     SetLastError(12345678);
1618     bytes = 12345678;
1619     ret = WriteFile(hFile, NULL, 0, &bytes, NULL);
1620     ok(ret && GetLastError() == 12345678,
1621         "ret = %d, error %d\n", ret, GetLastError());
1622     ok(!bytes, "bytes = %d\n", bytes);
1623
1624     SetLastError(12345678);
1625     bytes = 12345678;
1626     ret = WriteFile(hFile, NULL, 10, &bytes, NULL);
1627     ok((!ret && GetLastError() == ERROR_INVALID_USER_BUFFER) || /* Win2k */
1628         (ret && GetLastError() == 12345678), /* Win9x */
1629         "ret = %d, error %d\n", ret, GetLastError());
1630     ok(!bytes || /* Win2k */
1631         bytes == 10, /* Win9x */
1632         "bytes = %d\n", bytes);
1633
1634     /* make sure the file contains data */
1635     WriteFile(hFile, "this is the test data", 21, &bytes, NULL);
1636     SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
1637
1638     SetLastError(12345678);
1639     bytes = 12345678;
1640     ret = ReadFile(hFile, NULL, 0, &bytes, NULL);
1641     ok(ret && GetLastError() == 12345678,
1642         "ret = %d, error %d\n", ret, GetLastError());
1643     ok(!bytes, "bytes = %d\n", bytes);
1644
1645     SetLastError(12345678);
1646     bytes = 12345678;
1647     ret = ReadFile(hFile, NULL, 10, &bytes, NULL);
1648     ok(!ret && (GetLastError() == ERROR_NOACCESS || /* Win2k */
1649                 GetLastError() == ERROR_INVALID_PARAMETER), /* Win9x */
1650         "ret = %d, error %d\n", ret, GetLastError());
1651     ok(!bytes, "bytes = %d\n", bytes);
1652
1653     ret = CloseHandle(hFile);
1654     ok( ret, "CloseHandle: error %d\n", GetLastError());
1655     ret = DeleteFileA(filename);
1656     ok( ret, "DeleteFileA: error %d\n", GetLastError());
1657 }
1658
1659 static void test_OpenFile(void)
1660 {
1661     HFILE hFile;
1662     OFSTRUCT ofs;
1663     BOOL ret;
1664     DWORD retval;
1665     
1666     static const char *file = "\\regsvr32.exe";
1667     static const char *foo = ".\\foo-bar-foo.baz";
1668     static const char *foo_too_long = ".\\foo-bar-foo.baz+++++++++++++++"
1669         "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
1670         "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
1671         "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
1672         "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
1673         "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1674     static const char *backslash = "\\";
1675     char buff[MAX_PATH];
1676     char buff_long[4*MAX_PATH];
1677     char filled_0xA5[OFS_MAXPATHNAME];
1678     UINT length;
1679     
1680     /* Check for existing file */
1681     length = GetSystemDirectoryA(buff, MAX_PATH);
1682
1683     if (length + lstrlen(file) < MAX_PATH)
1684     {
1685         lstrcatA(buff, file);
1686         memset(&ofs, 0xA5, sizeof(ofs));
1687         SetLastError(0xfaceabee);
1688
1689         hFile = OpenFile(buff, &ofs, OF_EXIST);
1690         ok( hFile == TRUE, "%s not found : %d\n", buff, GetLastError() );
1691         ok( GetLastError() == 0xfaceabee || GetLastError() == ERROR_SUCCESS, 
1692             "GetLastError() returns %d\n", GetLastError() );
1693         ok( ofs.cBytes == sizeof(ofs), "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
1694         ok( ofs.nErrCode == ERROR_SUCCESS, "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
1695         ok( lstrcmpiA(ofs.szPathName, buff) == 0,
1696             "OpenFile returned '%s', but was expected to return '%s' or string filled with 0xA5\n",
1697             ofs.szPathName, buff );
1698     }
1699
1700     memset(&filled_0xA5, 0xA5, OFS_MAXPATHNAME);
1701     length = GetCurrentDirectoryA(MAX_PATH, buff);
1702
1703     /* Check for nonexistent file */
1704     if (length + lstrlenA(foo + 1) < MAX_PATH)
1705     {
1706         lstrcatA(buff, foo + 1); /* Avoid '.' during concatenation */
1707         memset(&ofs, 0xA5, sizeof(ofs));
1708         SetLastError(0xfaceabee);
1709
1710         hFile = OpenFile(foo, &ofs, OF_EXIST);
1711         ok( hFile == HFILE_ERROR, "hFile != HFILE_ERROR : %d\n", GetLastError());
1712         ok( GetLastError() == ERROR_FILE_NOT_FOUND, "GetLastError() returns %d\n", GetLastError() );
1713         todo_wine
1714         ok( ofs.cBytes == 0xA5, "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
1715         ok( ofs.nErrCode == ERROR_FILE_NOT_FOUND, "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
1716         ok( lstrcmpiA(ofs.szPathName, buff) == 0 || strncmp(ofs.szPathName, filled_0xA5, OFS_MAXPATHNAME) == 0,
1717             "OpenFile returned '%s', but was expected to return '%s' or string filled with 0xA5\n", 
1718             ofs.szPathName, buff );
1719     }
1720
1721     length = GetCurrentDirectoryA(MAX_PATH, buff_long);
1722     length += lstrlenA(foo_too_long + 1);
1723
1724     /* Check for nonexistent file with too long filename */ 
1725     if (length >= OFS_MAXPATHNAME && length < sizeof(buff_long)) 
1726     {
1727         lstrcatA(buff_long, foo_too_long + 1); /* Avoid '.' during concatenation */
1728         memset(&ofs, 0xA5, sizeof(ofs));
1729         SetLastError(0xfaceabee);
1730
1731         hFile = OpenFile(foo_too_long, &ofs, OF_EXIST);
1732         ok( hFile == HFILE_ERROR, "hFile != HFILE_ERROR : %d\n", GetLastError());
1733         ok( GetLastError() == ERROR_INVALID_DATA || GetLastError() == ERROR_FILENAME_EXCED_RANGE, 
1734             "GetLastError() returns %d\n", GetLastError() );
1735         todo_wine
1736         ok( ofs.cBytes == 0xA5, "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
1737         ok( ofs.nErrCode == ERROR_INVALID_DATA || ofs.nErrCode == ERROR_FILENAME_EXCED_RANGE,
1738             "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
1739         ok( strncmp(ofs.szPathName, filled_0xA5, OFS_MAXPATHNAME) == 0, 
1740             "OpenFile returned '%s', but was expected to return string filled with 0xA5\n", 
1741             ofs.szPathName );
1742     }
1743
1744     length = GetCurrentDirectoryA(MAX_PATH, buff);
1745     length += lstrlenA(backslash);
1746     length += lstrlenA(filename);
1747
1748     if (length >= MAX_PATH) 
1749     {
1750         trace("Buffer too small, requested length = %d, but MAX_PATH = %d.  Skipping test.\n", length, MAX_PATH);
1751         return;
1752     }
1753     lstrcatA(buff, backslash);
1754     lstrcatA(buff, filename);
1755
1756     memset(&ofs, 0xA5, sizeof(ofs));
1757     SetLastError(0xfaceabee);
1758     /* Create an empty file */
1759     hFile = OpenFile(filename, &ofs, OF_CREATE);
1760     ok( hFile != HFILE_ERROR, "OpenFile failed to create nonexistent file\n" );
1761     ok( GetLastError() == 0xfaceabee || GetLastError() == ERROR_SUCCESS, 
1762         "GetLastError() returns %d\n", GetLastError() );
1763     ok( ofs.cBytes == sizeof(OFSTRUCT), "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
1764     ok( ofs.nErrCode == ERROR_SUCCESS, "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
1765     ret = CloseHandle((HANDLE)hFile);
1766     ok( ret == TRUE, "CloseHandle() returns %d\n", ret );
1767     retval = GetFileAttributesA(filename);
1768     ok( retval != INVALID_FILE_ATTRIBUTES, "GetFileAttributesA: error %d\n", GetLastError() );
1769
1770     memset(&ofs, 0xA5, sizeof(ofs));
1771     SetLastError(0xfaceabee);
1772     /* Check various opening options: */
1773     /* for reading only, */
1774     hFile = OpenFile(filename, &ofs, OF_READ);
1775     ok( hFile != HFILE_ERROR, "OpenFile failed on read\n" );
1776     ok( GetLastError() == 0xfaceabee || GetLastError() == ERROR_SUCCESS, 
1777         "GetLastError() returns %d\n", GetLastError() );
1778     ok( ofs.cBytes == sizeof(OFSTRUCT), "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
1779     ok( ofs.nErrCode == ERROR_SUCCESS, "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
1780     ok( lstrcmpiA(ofs.szPathName, buff) == 0,
1781         "OpenFile returned '%s', but was expected to return '%s'\n", ofs.szPathName, buff );
1782     ret = CloseHandle((HANDLE)hFile);
1783     ok( ret == TRUE, "CloseHandle() returns %d\n", ret );
1784
1785     memset(&ofs, 0xA5, sizeof(ofs));
1786     SetLastError(0xfaceabee);
1787     /* for writing only, */
1788     hFile = OpenFile(filename, &ofs, OF_WRITE);
1789     ok( hFile != HFILE_ERROR, "OpenFile failed on write\n" );
1790     ok( GetLastError() == 0xfaceabee || GetLastError() == ERROR_SUCCESS, 
1791         "GetLastError() returns %d\n", GetLastError() );
1792     ok( ofs.cBytes == sizeof(OFSTRUCT), "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
1793     ok( ofs.nErrCode == ERROR_SUCCESS, "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
1794     ok( lstrcmpiA(ofs.szPathName, buff) == 0,
1795         "OpenFile returned '%s', but was expected to return '%s'\n", ofs.szPathName, buff );
1796     ret = CloseHandle((HANDLE)hFile);
1797     ok( ret == TRUE, "CloseHandle() returns %d\n", ret );
1798
1799     memset(&ofs, 0xA5, sizeof(ofs));
1800     SetLastError(0xfaceabee);
1801     /* for reading and writing, */
1802     hFile = OpenFile(filename, &ofs, OF_READWRITE);
1803     ok( hFile != HFILE_ERROR, "OpenFile failed on read/write\n" );
1804     ok( GetLastError() == 0xfaceabee || GetLastError() == ERROR_SUCCESS, 
1805         "GetLastError() returns %d\n", GetLastError() );
1806     ok( ofs.cBytes == sizeof(OFSTRUCT), "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
1807     ok( ofs.nErrCode == ERROR_SUCCESS, "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
1808     ok( lstrcmpiA(ofs.szPathName, buff) == 0,
1809         "OpenFile returned '%s', but was expected to return '%s'\n", ofs.szPathName, buff );
1810     ret = CloseHandle((HANDLE)hFile);
1811     ok( ret == TRUE, "CloseHandle() returns %d\n", ret );
1812
1813     memset(&ofs, 0xA5, sizeof(ofs));
1814     SetLastError(0xfaceabee);
1815     /* for checking file presence. */
1816     hFile = OpenFile(filename, &ofs, OF_EXIST);
1817     ok( hFile == 1, "OpenFile failed on finding our created file\n" );
1818     ok( GetLastError() == 0xfaceabee || GetLastError() == ERROR_SUCCESS, 
1819         "GetLastError() returns %d\n", GetLastError() );
1820     ok( ofs.cBytes == sizeof(OFSTRUCT), "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
1821     ok( ofs.nErrCode == ERROR_SUCCESS, "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
1822     ok( lstrcmpiA(ofs.szPathName, buff) == 0,
1823         "OpenFile returned '%s', but was expected to return '%s'\n", ofs.szPathName, buff );
1824
1825     memset(&ofs, 0xA5, sizeof(ofs));
1826     SetLastError(0xfaceabee);
1827     /* Delete the file and make sure it doesn't exist anymore */
1828     hFile = OpenFile(filename, &ofs, OF_DELETE);
1829     ok( hFile == 1, "OpenFile failed on delete (%d)\n", hFile );
1830     ok( GetLastError() == 0xfaceabee || GetLastError() == ERROR_SUCCESS, 
1831         "GetLastError() returns %d\n", GetLastError() );
1832     ok( ofs.cBytes == sizeof(OFSTRUCT), "OpenFile set ofs.cBytes to %d\n", ofs.cBytes );
1833     ok( ofs.nErrCode == ERROR_SUCCESS, "OpenFile set ofs.nErrCode to %d\n", ofs.nErrCode );
1834     ok( lstrcmpiA(ofs.szPathName, buff) == 0,
1835         "OpenFile returned '%s', but was expected to return '%s'\n", ofs.szPathName, buff );
1836
1837     retval = GetFileAttributesA(filename);
1838     ok( retval == INVALID_FILE_ATTRIBUTES, "GetFileAttributesA succeeded on deleted file\n" );
1839 }
1840
1841 static void test_overlapped(void)
1842 {
1843     OVERLAPPED ov;
1844     DWORD r, result;
1845
1846     /* GetOverlappedResult crashes if the 2nd or 3rd param are NULL */
1847
1848     memset( &ov, 0,  sizeof ov );
1849     result = 1;
1850     r = GetOverlappedResult(0, &ov, &result, 0);
1851     ok( r == TRUE, "should return true\n");
1852     ok( result == 0, "wrong result %u\n", result );
1853
1854     result = 0;
1855     ov.Internal = 0;
1856     ov.InternalHigh = 0xabcd;
1857     r = GetOverlappedResult(0, &ov, &result, 0);
1858     ok( r == TRUE, "should return true\n");
1859     ok( result == 0xabcd, "wrong result %u\n", result );
1860
1861     SetLastError( 0xb00 );
1862     result = 0;
1863     ov.Internal = STATUS_INVALID_HANDLE;
1864     ov.InternalHigh = 0xabcd;
1865     r = GetOverlappedResult(0, &ov, &result, 0);
1866     ok( GetLastError() == ERROR_INVALID_HANDLE, "wrong error %u\n", GetLastError() );
1867     ok( r == FALSE, "should return false\n");
1868     ok( result == 0xabcd, "wrong result %u\n", result );
1869
1870     SetLastError( 0xb00 );
1871     result = 0;
1872     ov.Internal = STATUS_PENDING;
1873     ov.InternalHigh = 0xabcd;
1874     r = GetOverlappedResult(0, &ov, &result, 0);
1875     ok( GetLastError() == ERROR_IO_INCOMPLETE, "wrong error %u\n", GetLastError() );
1876     ok( r == FALSE, "should return false\n");
1877     ok( result == 0, "wrong result %u\n", result );
1878
1879     SetLastError( 0xb00 );
1880     ov.hEvent = CreateEvent( NULL, 1, 1, NULL );
1881     ov.Internal = STATUS_PENDING;
1882     ov.InternalHigh = 0xabcd;
1883     r = GetOverlappedResult(0, &ov, &result, 0);
1884     ok( GetLastError() == ERROR_IO_INCOMPLETE, "wrong error %u\n", GetLastError() );
1885     ok( r == FALSE, "should return false\n");
1886
1887     ResetEvent( ov.hEvent );
1888
1889     SetLastError( 0xb00 );
1890     ov.Internal = STATUS_PENDING;
1891     ov.InternalHigh = 0;
1892     r = GetOverlappedResult(0, &ov, &result, 0);
1893     ok( GetLastError() == ERROR_IO_INCOMPLETE, "wrong error %u\n", GetLastError() );
1894     ok( r == FALSE, "should return false\n");
1895
1896     r = CloseHandle( ov.hEvent );
1897     ok( r == TRUE, "close handle failed\n");
1898 }
1899
1900 static void test_RemoveDirectory(void)
1901 {
1902     int rc;
1903     char directory[] = "removeme";
1904
1905     rc = CreateDirectory(directory, NULL);
1906     ok( rc, "Createdirectory failed, gle=%d\n", GetLastError() );
1907
1908     rc = SetCurrentDirectory(directory);
1909     ok( rc, "SetCurrentDirectory failed, gle=%d\n", GetLastError() );
1910
1911     rc = RemoveDirectory(".");
1912     todo_wine {
1913     ok( !rc, "RemoveDirectory unexpectedly worked\n" );
1914     }
1915
1916     rc = SetCurrentDirectory("..");
1917     ok( rc, "SetCurrentDirectory failed, gle=%d\n", GetLastError() );
1918
1919     rc = RemoveDirectory(directory);
1920     todo_wine {
1921     ok( rc, "RemoveDirectory failed, gle=%d\n", GetLastError() );
1922     }
1923 }
1924
1925 static void test_ReplaceFileA(void)
1926 {
1927     char replaced[MAX_PATH], replacement[MAX_PATH], backup[MAX_PATH];
1928     HANDLE hReplacedFile, hReplacementFile, hBackupFile;
1929     static const char replacedData[] = "file-to-replace";
1930     static const char replacementData[] = "new-file";
1931     static const char backupData[] = "backup-file";
1932     FILETIME ftReplaced, ftReplacement, ftBackup;
1933     static const char prefix[] = "pfx";
1934     char temp_path[MAX_PATH];
1935     DWORD ret;
1936     BOOL retok;
1937
1938     if (!pReplaceFileA)
1939     {
1940         skip("ReplaceFileA() is missing\n");
1941         return;
1942     }
1943
1944     ret = GetTempPathA(MAX_PATH, temp_path);
1945     ok(ret != 0, "GetTempPathA error %d\n", GetLastError());
1946     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
1947
1948     ret = GetTempFileNameA(temp_path, prefix, 0, replaced);
1949     ok(ret != 0, "GetTempFileNameA error (replaced) %d\n", GetLastError());
1950
1951     ret = GetTempFileNameA(temp_path, prefix, 0, replacement);
1952     ok(ret != 0, "GetTempFileNameA error (replacement) %d\n", GetLastError());
1953
1954     ret = GetTempFileNameA(temp_path, prefix, 0, backup);
1955     ok(ret != 0, "GetTempFileNameA error (backup) %d\n", GetLastError());
1956
1957     /* place predictable data in the file to be replaced */
1958     hReplacedFile = CreateFileA(replaced, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0 );
1959     ok(hReplacedFile != INVALID_HANDLE_VALUE,
1960         "failed to open replaced file\n");
1961     retok = WriteFile(hReplacedFile, replacedData, sizeof(replacedData), &ret, NULL );
1962     ok( retok && ret == sizeof(replacedData),
1963        "WriteFile error (replaced) %d\n", GetLastError());
1964     ok(GetFileSize(hReplacedFile, NULL) == sizeof(replacedData),
1965         "replaced file has wrong size\n");
1966     /* place predictable data in the file to be the replacement */
1967     hReplacementFile = CreateFileA(replacement, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0 );
1968     ok(hReplacementFile != INVALID_HANDLE_VALUE,
1969         "failed to open replacement file\n");
1970     retok = WriteFile(hReplacementFile, replacementData, sizeof(replacementData), &ret, NULL );
1971     ok( retok && ret == sizeof(replacementData),
1972        "WriteFile error (replacement) %d\n", GetLastError());
1973     ok(GetFileSize(hReplacementFile, NULL) == sizeof(replacementData),
1974         "replacement file has wrong size\n");
1975     /* place predictable data in the backup file (to be over-written) */
1976     hBackupFile = CreateFileA(backup, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0 );
1977     ok(hBackupFile != INVALID_HANDLE_VALUE,
1978         "failed to open backup file\n");
1979     retok = WriteFile(hBackupFile, backupData, sizeof(backupData), &ret, NULL );
1980     ok( retok && ret == sizeof(backupData),
1981        "WriteFile error (replacement) %d\n", GetLastError());
1982     ok(GetFileSize(hBackupFile, NULL) == sizeof(backupData),
1983         "backup file has wrong size\n");
1984     /* change the filetime on the "replaced" file to ensure that it changes */
1985     ret = GetFileTime(hReplacedFile, NULL, NULL, &ftReplaced);
1986     ok( ret, "GetFileTime error (replaced) %d\n", GetLastError());
1987     ftReplaced.dwLowDateTime -= 600000000; /* 60 second */
1988     ret = SetFileTime(hReplacedFile, NULL, NULL, &ftReplaced);
1989     ok( ret, "SetFileTime error (replaced) %d\n", GetLastError());
1990     GetFileTime(hReplacedFile, NULL, NULL, &ftReplaced);  /* get the actual time back */
1991     CloseHandle(hReplacedFile);
1992     /* change the filetime on the backup to ensure that it changes */
1993     ret = GetFileTime(hBackupFile, NULL, NULL, &ftBackup);
1994     ok( ret, "GetFileTime error (backup) %d\n", GetLastError());
1995     ftBackup.dwLowDateTime -= 1200000000; /* 120 second */
1996     ret = SetFileTime(hBackupFile, NULL, NULL, &ftBackup);
1997     ok( ret, "SetFileTime error (backup) %d\n", GetLastError());
1998     GetFileTime(hBackupFile, NULL, NULL, &ftBackup);  /* get the actual time back */
1999     CloseHandle(hBackupFile);
2000     /* get the filetime on the replacement file to perform checks */
2001     ret = GetFileTime(hReplacementFile, NULL, NULL, &ftReplacement);
2002     ok( ret, "GetFileTime error (replacement) %d\n", GetLastError());
2003     CloseHandle(hReplacementFile);
2004
2005     /* perform replacement w/ backup
2006      * TODO: flags are not implemented
2007      */
2008     SetLastError(0xdeadbeef);
2009     ret = pReplaceFileA(replaced, replacement, backup, 0, 0, 0);
2010     ok(ret, "ReplaceFileA: unexpected error %d\n", GetLastError());
2011     /* make sure that the backup has the size of the old "replaced" file */
2012     hBackupFile = CreateFileA(backup, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
2013     ok(hBackupFile != INVALID_HANDLE_VALUE,
2014         "failed to open backup file\n");
2015     ret = GetFileSize(hBackupFile, NULL);
2016     ok(ret == sizeof(replacedData),
2017         "backup file has wrong size %d\n", ret);
2018     /* make sure that the "replaced" file has the size of the replacement file */
2019     hReplacedFile = CreateFileA(replaced, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
2020     ok(hReplacedFile != INVALID_HANDLE_VALUE,
2021         "failed to open replaced file\n");
2022     ret = GetFileSize(hReplacedFile, NULL);
2023     ok(ret == sizeof(replacementData),
2024         "replaced file has wrong size %d\n", ret);
2025     /* make sure that the replacement file no-longer exists */
2026     hReplacementFile = CreateFileA(replacement, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
2027     ok(hReplacementFile == INVALID_HANDLE_VALUE,
2028        "unexpected error, replacement file should not exist %d\n", GetLastError());
2029     /* make sure that the backup has the old "replaced" filetime */
2030     ret = GetFileTime(hBackupFile, NULL, NULL, &ftBackup);
2031     ok( ret, "GetFileTime error (backup %d\n", GetLastError());
2032     ok(CompareFileTime(&ftBackup, &ftReplaced) == 0,
2033         "backup file has wrong filetime\n");
2034     CloseHandle(hBackupFile);
2035     /* make sure that the "replaced" has the old replacement filetime */
2036     ret = GetFileTime(hReplacedFile, NULL, NULL, &ftReplaced);
2037     ok( ret, "GetFileTime error (backup %d\n", GetLastError());
2038     ok(CompareFileTime(&ftReplaced, &ftReplacement) == 0,
2039         "replaced file has wrong filetime\n");
2040     CloseHandle(hReplacedFile);
2041
2042     /* re-create replacement file for pass w/o backup (blank) */
2043     ret = GetTempFileNameA(temp_path, prefix, 0, replacement);
2044     ok(ret != 0, "GetTempFileNameA error (replacement) %d\n", GetLastError());
2045     /* perform replacement w/o backup
2046      * TODO: flags are not implemented
2047      */
2048     SetLastError(0xdeadbeef);
2049     ret = pReplaceFileA(replaced, replacement, NULL, 0, 0, 0);
2050     ok(ret, "ReplaceFileA: unexpected error %d\n", GetLastError());
2051
2052     /* re-create replacement file for pass w/ backup (backup-file not existing) */
2053     ret = GetTempFileNameA(temp_path, prefix, 0, replacement);
2054     ok(ret != 0, "GetTempFileNameA error (replacement) %d\n", GetLastError());
2055     ret = DeleteFileA(backup);
2056     ok(ret, "DeleteFileA: error (backup) %d\n", GetLastError());
2057     /* perform replacement w/ backup (no pre-existing backup)
2058      * TODO: flags are not implemented
2059      */
2060     SetLastError(0xdeadbeef);
2061     ret = pReplaceFileA(replaced, replacement, backup, 0, 0, 0);
2062     ok(ret, "ReplaceFileA: unexpected error %d\n", GetLastError());
2063
2064     /* re-create replacement file for pass w/ no permissions to "replaced" */
2065     ret = GetTempFileNameA(temp_path, prefix, 0, replacement);
2066     ok(ret != 0, "GetTempFileNameA error (replacement) %d\n", GetLastError());
2067     ret = SetFileAttributesA(replaced, FILE_ATTRIBUTE_READONLY);
2068     ok(ret, "SetFileAttributesA: error setting to read only %d\n", GetLastError());
2069     /* perform replacement w/ backup (no permission to "replaced")
2070      * TODO: flags are not implemented
2071      */
2072     SetLastError(0xdeadbeef);
2073     ret = pReplaceFileA(replaced, replacement, backup, 0, 0, 0);
2074     ok(ret != ERROR_UNABLE_TO_REMOVE_REPLACED, "ReplaceFileA: unexpected error %d\n", GetLastError());
2075     /* make sure that the replacement file still exists */
2076     hReplacementFile = CreateFileA(replacement, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
2077     ok(hReplacementFile != INVALID_HANDLE_VALUE ||
2078        broken(GetLastError() == ERROR_FILE_NOT_FOUND), /* win2k */
2079        "unexpected error, replacement file should still exist %d\n", GetLastError());
2080     CloseHandle(hReplacementFile);
2081     ret = SetFileAttributesA(replaced, FILE_ATTRIBUTE_NORMAL);
2082     ok(ret, "SetFileAttributesA: error setting to normal %d\n", GetLastError());
2083
2084     /* replacement file still exists, make pass w/o "replaced" */
2085     ret = DeleteFileA(replaced);
2086     ok(ret, "DeleteFileA: error (replaced) %d\n", GetLastError());
2087     /* perform replacement w/ backup (no pre-existing backup or "replaced")
2088      * TODO: flags are not implemented
2089      */
2090     SetLastError(0xdeadbeef);
2091     ret = pReplaceFileA(replaced, replacement, backup, 0, 0, 0);
2092     ok(!ret && GetLastError() == ERROR_FILE_NOT_FOUND,
2093                         "ReplaceFileA: unexpected error %d\n", GetLastError());
2094
2095     /* perform replacement w/o existing "replacement" file
2096      * TODO: flags are not implemented
2097      */
2098     SetLastError(0xdeadbeef);
2099     ret = pReplaceFileA(replaced, replacement, NULL, 0, 0, 0);
2100     ok(!ret && GetLastError() == ERROR_FILE_NOT_FOUND,
2101         "ReplaceFileA: unexpected error %d\n", GetLastError());
2102
2103     /*
2104      * if the first round (w/ backup) worked then as long as there is no
2105      * failure then there is no need to check this round (w/ backup is the
2106      * more complete case)
2107      */
2108
2109     /* delete temporary files, replacement and replaced are already deleted */
2110     ret = DeleteFileA(backup);
2111     ok(ret ||
2112        broken(GetLastError() == ERROR_ACCESS_DENIED), /* win2k */
2113        "DeleteFileA: error (backup) %d\n", GetLastError());
2114 }
2115
2116 /*
2117  * ReplaceFileW is a simpler case of ReplaceFileA, there is no
2118  * need to be as thorough.
2119  */
2120 static void test_ReplaceFileW(void)
2121 {
2122     WCHAR replaced[MAX_PATH], replacement[MAX_PATH], backup[MAX_PATH];
2123     static const WCHAR prefix[] = {'p','f','x',0};
2124     WCHAR temp_path[MAX_PATH];
2125     DWORD ret;
2126
2127     if (!pReplaceFileW)
2128     {
2129         skip("ReplaceFileW() is missing\n");
2130         return;
2131     }
2132
2133     ret = GetTempPathW(MAX_PATH, temp_path);
2134     if (ret==0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2135         return;
2136     ok(ret != 0, "GetTempPathW error %d\n", GetLastError());
2137     ok(ret < MAX_PATH, "temp path should fit into MAX_PATH\n");
2138
2139     ret = GetTempFileNameW(temp_path, prefix, 0, replaced);
2140     ok(ret != 0, "GetTempFileNameW error (replaced) %d\n", GetLastError());
2141
2142     ret = GetTempFileNameW(temp_path, prefix, 0, replacement);
2143     ok(ret != 0, "GetTempFileNameW error (replacement) %d\n", GetLastError());
2144
2145     ret = GetTempFileNameW(temp_path, prefix, 0, backup);
2146     ok(ret != 0, "GetTempFileNameW error (backup) %d\n", GetLastError());
2147
2148     ret = pReplaceFileW(replaced, replacement, backup, 0, 0, 0);
2149     ok(ret, "ReplaceFileW: error %d\n", GetLastError());
2150
2151     ret = GetTempFileNameW(temp_path, prefix, 0, replacement);
2152     ok(ret != 0, "GetTempFileNameW error (replacement) %d\n", GetLastError());
2153     ret = pReplaceFileW(replaced, replacement, NULL, 0, 0, 0);
2154     ok(ret, "ReplaceFileW: error %d\n", GetLastError());
2155
2156     ret = GetTempFileNameW(temp_path, prefix, 0, replacement);
2157     ok(ret != 0, "GetTempFileNameW error (replacement) %d\n", GetLastError());
2158     ret = DeleteFileW(backup);
2159     ok(ret, "DeleteFileW: error (backup) %d\n", GetLastError());
2160     ret = pReplaceFileW(replaced, replacement, backup, 0, 0, 0);
2161     ok(ret, "ReplaceFileW: error %d\n", GetLastError());
2162
2163     ret = GetTempFileNameW(temp_path, prefix, 0, replacement);
2164     ok(ret != 0, "GetTempFileNameW error (replacement) %d\n", GetLastError());
2165     ret = SetFileAttributesW(replaced, FILE_ATTRIBUTE_READONLY);
2166     ok(ret, "SetFileAttributesW: error setting to read only %d\n", GetLastError());
2167
2168     ret = pReplaceFileW(replaced, replacement, backup, 0, 0, 0);
2169     ok(ret != ERROR_UNABLE_TO_REMOVE_REPLACED,
2170         "ReplaceFileW: unexpected error %d\n", GetLastError());
2171     ret = SetFileAttributesW(replaced, FILE_ATTRIBUTE_NORMAL);
2172     ok(ret, "SetFileAttributesW: error setting to normal %d\n", GetLastError());
2173
2174     ret = DeleteFileW(replaced);
2175     ok(ret, "DeleteFileW: error (replaced) %d\n", GetLastError());
2176     ret = pReplaceFileW(replaced, replacement, backup, 0, 0, 0);
2177     ok(!ret, "ReplaceFileW: error %d\n", GetLastError());
2178
2179     ret = pReplaceFileW(replaced, replacement, NULL, 0, 0, 0);
2180     ok(!ret && GetLastError() == ERROR_FILE_NOT_FOUND,
2181         "ReplaceFileW: unexpected error %d\n", GetLastError());
2182
2183     ret = DeleteFileW(backup);
2184     ok(ret ||
2185        broken(GetLastError() == ERROR_ACCESS_DENIED), /* win2k */
2186        "DeleteFileW: error (backup) %d\n", GetLastError());
2187 }
2188
2189 START_TEST(file)
2190 {
2191     InitFunctionPointers();
2192
2193     test__hread(  );
2194     test__hwrite(  );
2195     test__lclose(  );
2196     test__lcreat(  );
2197     test__llseek(  );
2198     test__llopen(  );
2199     test__lread(  );
2200     test__lwrite(  );
2201     test_GetTempFileNameA();
2202     test_CopyFileA();
2203     test_CopyFileW();
2204     test_CreateFileA();
2205     test_CreateFileW();
2206     test_DeleteFileA();
2207     test_DeleteFileW();
2208     test_MoveFileA();
2209     test_MoveFileW();
2210     test_FindFirstFileA();
2211     test_FindNextFileA();
2212     test_FindFirstFileExA();
2213     test_LockFile();
2214     test_file_sharing();
2215     test_offset_in_overlapped_structure();
2216     test_MapFile();
2217     test_GetFileType();
2218     test_async_file_errors();
2219     test_read_write();
2220     test_OpenFile();
2221     test_overlapped();
2222     test_RemoveDirectory();
2223     test_ReplaceFileA();
2224     test_ReplaceFileW();
2225 }