-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathdtwin.c
4074 lines (3702 loc) · 120 KB
/
dtwin.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/****************************************************************************
* *
* COPYRIGHT (c) 2006 - 2021 *
* This Software Provided *
* By *
* Robin's Nest Software Inc. *
* *
* Permission to use, copy, modify, distribute and sell this software and *
* its documentation for any purpose and without fee is hereby granted, *
* provided that the above copyright notice appear in all copies and that *
* both that copyright notice and this permission notice appear in the *
* supporting documentation, and that the name of the author not be used *
* in advertising or publicity pertaining to distribution of the software *
* without specific, written prior permission. *
* *
* THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, *
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN *
* NO EVENT SHALL HE BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL *
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR *
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS *
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF *
* THIS SOFTWARE. *
* *
****************************************************************************/
/*
* Module: dtwin.c
* Author: Robin T. Miller
*
* Description:
* This module contains *unix OS specific functions.
*
* Modification History:
*
* June 5th, 2020 by Robin T. Miller
* Update os_pread_file() to detecting overlapped I/O, then wait for
* accordingly for it to finish. When async I/O is enable, and read after
* write is enabled, currently reads are done synchonously. While this
* defeats the purpose of async I/O, we don't wish these reads to fail!
*
* May 5th, 2020 by Robin T. Miller
* Include the high resolution gettimeofday() as highresolutiontime(),
* which will be used where more accurate timing is desired, such as history
* entries. The Unix eqivalent gettimeofday() is only accurate to 10-15ms,
* but is preferred (by some) in block tags (btags) for Epoch write times.
* Note: Robin often creates large history with timing for tracing I/O's.
*
* April 6th, 2015 by Robin T. Miller
* In os_rename_file(), do not delete the newpath unless the oldpath
* exists. Depending on the test, we can delete files that should remain,
* plus this behavior is closer to POSIX rename() semantics (I believe).
*
* February 7th, 2015 by Robin T. Miller
* Fixed bug in POSIX flag mapping, O_RDONLY was setting the wrong
* access (Read and Write), which failed on a read-only file! The author
* forgot that O_RDONLY is defined with a value of 0, so cannot be checked!
*
* January 2012 by Robin T. Miller
* pthread* API's should not report errors, but simply return the
* error to the caller, so these changes have been made. The caller needs
* to use OS specific functions to handle *nix vs. Windows error reporting.
*
* Note: dt has its' own open/close/seek functions, so these may go!
* Still need to evaluate the AIO functions. and maybe cleanup more
* error handling, and probably remove unused API's.
*/
#include "dt.h"
#include "dtwin.h"
#include <stdio.h>
#include <signal.h>
#include <winbase.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/timeb.h>
#include <io.h>
//#define WINDOWS_XP 1
#define Thread __declspec(thread)
/*
* Local Storage:
*/
/*
* Forward References:
*/
char *dt_get_volume_path_name(dinfo_t *dip, char *path);
void map_posix_flags(dinfo_t *dip, char *name, int posix_flags,
DWORD *DesiredAccess, DWORD *CreationDisposition,
DWORD *FlagsAndAttributes, DWORD *ShareMode);
/*
* Fake pthread implementation using Windows threads. Windows threads
* are generally a superset of pthreads, so there is no lost functionality.
*
* Note: Lots of Windows documentation/links added by Robin, who does not
* do sufficient Windows programming to feel confident in his theads knowledge.
*/
int
pthread_attr_init(pthread_attr_t *attr)
{
return( PTHREAD_NORMAL_EXIT );
}
int
pthread_attr_setscope(pthread_attr_t *attr, unsigned type)
{
return( PTHREAD_NORMAL_EXIT );
}
int
pthread_attr_setdetachstate(pthread_attr_t *attr, int type)
{
return( PTHREAD_NORMAL_EXIT );
}
/*
* Reference:
* http://msdn.microsoft.com/en-us/library/windows/desktop/ms682453(v=vs.85).aspx
*
* Remarks:
* The number of threads a process can create is limited by the available virtual
* memory. By default, every thread has one megabyte of stack space. Therefore,
* you can create at most 2,048 threads. If you reduce the default stack size, you
* can create more threads. However, your application will have better performance
* if you create one thread per processor and build queues of requests for which
* the application maintains the context information. A thread would process all
* requests in a queue before processing requests in the next queue.
*/
int
pthread_attr_getstacksize(const pthread_attr_t *attr, size_t *stacksize)
{
*stacksize = MBYTE_SIZE;
return( PTHREAD_NORMAL_EXIT );
}
int
pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize)
{
return( PTHREAD_NORMAL_EXIT );
}
int
pthread_mutexattr_init(pthread_mutexattr_t *attr)
{
return( PTHREAD_NORMAL_EXIT );
}
int
pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
{
return( PTHREAD_NORMAL_EXIT );
}
int
pthread_mutexattr_gettype(pthread_mutexattr_t *attr, int *type)
{
return( PTHREAD_NORMAL_EXIT );
}
int
pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
{
return( PTHREAD_NORMAL_EXIT );
}
/*
* Windows Notes from:
* http://msdn.microsoft.com/en-us/library/windows/desktop/ms682659(v=vs.85).aspx
* A thread in an executable that is linked to the static C run-time library
* (CRT) should use _beginthread and _endthread for thread management rather
* than CreateThread and ExitThread. Failure to do so results in small memory
* leaks when the thread calls ExitThread. Another work around is to link the
* executable to the CRT in a DLL instead of the static CRT.
* Note that this memory leak only occurs from a DLL if the DLL is linked to
* the static CRT *and* a thread calls the DisableThreadLibraryCalls function.
* Otherwise, it is safe to call CreateThread and ExitThread from a thread in
* a DLL that links to the static CRT.
*
* Robin's Note: September 2012
* Since we are NOT calling DisableThreadLibraryCalls(), I'm assuming we
* do not need to worry about using these alternate thread create/exit API's!
* Note: The code has left, but not enabled since _MT changes to _MTx.
* Update: Reenabling _MT method for threads, otherwise hangs occur!
* Note: The hangs occur while waiting for the parent thread to exit.
*
* A different warning...
* If you are going to call C run-time routines from a program built
* with Libcmt.lib, you must start your threads with the _beginthread
* or _beginthreadex function. Do not use the Win32 functions ExitThread
* and CreateThread. Using SuspendThread can lead to a deadlock when more
* than one thread is blocked waiting for the suspended thread to complete
* its access to a C run-time data structure.
* URL: http://msdn.microsoft.com/en-us/library/7t9ha0zh(VS.80).aspx
*
* Note: My testing proved this to be true, but hangs occurred regardless
* of using these alternate thread API's with thread suspend/resume!
*
* Outputs:
* tid for Windows is actually the Thread handle, NOT the thread ID!
*/
int
pthread_create(pthread_t *tid, pthread_attr_t *attr,
void *(*func)(void *), void *arg)
{
DWORD dwTid;
#if defined(_MT)
/*
* uintptr_t _beginthreadex(
* void *security,
* unsigned stack_size,
* unsigned ( *start_address )( void * ),
* void *arglist,
* unsigned initflag,
* unsigned *thrdaddr );
*/
#define myTHREAD_START_ROUTINE unsigned int (__stdcall *)(void *)
*tid = (pthread_t *)_beginthreadex(NULL, 0, (myTHREAD_START_ROUTINE)func, arg, 0, &dwTid);
#else /* !defined(_MT) */
/*
* Use CreateThread so we have a real thread handle
* to synchronize on
* HANDLE WINAPI CreateThread(
* _In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
* _In_ SIZE_T dwStackSize,
* _In_ LPTHREAD_START_ROUTINE lpStartAddress,
* _In_opt_ LPVOID lpParameter,
* _In_ DWORD dwCreationFlags,
* _Out_opt_ LPDWORD lpThreadId
* );
*/
*tid = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)func, arg, 0, &dwTid);
#endif /* defined(_MT) */
if (*tid == NULL) {
return (int)GetLastError();
} else {
return PTHREAD_NORMAL_EXIT;
}
}
void
pthread_exit(void *status)
{
#if defined(_MT)
/*
* void _endthreadex(unsigned retval);
*/
_endthreadex( (unsigned)status );
#else /* !defined(_MT) */
ExitThread( (DWORD)status );
#endif /* defined(_MT) */
}
int
pthread_join(pthread_t thread, void **exit_value)
{
HANDLE handle = (HANDLE)thread;
DWORD status = PTHREAD_NORMAL_EXIT;
DWORD thread_status = PTHREAD_NORMAL_EXIT;
DWORD wait_status;
if (GetCurrentThread() == thread) {
return -1;
}
wait_status = WaitForSingleObject(handle, INFINITE);
if (wait_status == WAIT_FAILED) {
status = GetLastError();
} else if (GetExitCodeThread(handle, &thread_status) == False) {
status = GetLastError();
}
if (CloseHandle(handle) == False) {
status = GetLastError();
}
if (exit_value) {
*(int *)exit_value = (int)thread_status;
}
return((int)status);
}
int
pthread_detach(pthread_t thread)
{
if (CloseHandle((HANDLE)thread) == False) {
return (int)GetLastError();
} else {
return PTHREAD_NORMAL_EXIT;
}
}
/*
* Reference: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686717(v=vs.85).aspx
*
* TerminateThread is used to cause a thread to exit. When this occurs, the target thread
* has no chance to execute any user-mode code. DLLs attached to the thread are not notified
* that the thread is terminating. The system frees the thread's initial stack.
*
* Windows Server 2003 and Windows XP: The target thread's initial stack is not freed, causing
* a resource leak.
*
* TerminateThread is a dangerous function that should only be used in the most extreme cases.
* You should call TerminateThread only if you know exactly what the target thread is doing,
* and you control all of the code that the target thread could possibly be running at the
* time of the termination. For example, TerminateThread can result in the following problems:
*
* If the target thread owns a critical section, the critical section will not be released.
* If the target thread is allocating memory from the heap, the heap lock will not be released.
* If the target thread is executing certain kernel32 calls when it is terminated, the kernel32
* state for the thread's process could be inconsistent.
* If the target thread is manipulating the global state of a shared DLL, the state of the DLL
* could be destroyed, affecting other users of the DLL.
*/
int
pthread_cancel(pthread_t thread)
{
if (TerminateThread((HANDLE)thread, ERROR_SUCCESS) == False) {
return (int)GetLastError();
} else {
return PTHREAD_NORMAL_EXIT;
}
}
void
pthread_kill(pthread_t thread, int sig)
{
if (sig == SIGKILL) {
(void)TerminateThread((HANDLE)thread, sig);
}
return;
}
int
pthread_mutex_init(pthread_mutex_t *lock, void *attr)
{
/*
* HANDLE WINAPI CreateMutex(
* _In_opt_ LPSECURITY_ATTRIBUTES lpMutexAttributes,
* _In_ BOOL bInitialOwner,
* _In_opt_ LPCTSTR lpName
* );
*/
*lock = CreateMutex(NULL, False, NULL);
if (*lock == NULL) {
return (int)GetLastError();
} else {
return(PTHREAD_NORMAL_EXIT);
}
}
int
pthread_mutex_destroy(pthread_mutex_t *mutex)
{
if (CloseHandle(*mutex) == False) {
return (int)GetLastError();
} else {
return( PTHREAD_NORMAL_EXIT );
}
}
/*
* the diff b/w this and mutex_lock is that this one returns
* if any thread including itself has the mutex object locked
* (man pthread_mutex_trylock on Solaris)
*/
int
pthread_mutex_trylock(pthread_mutex_t *lock)
{
DWORD result = WaitForSingleObject(*lock, INFINITE);
/* TODO - errors and return values? */
return( PTHREAD_NORMAL_EXIT );
}
int
pthread_mutex_lock(pthread_mutex_t *lock)
{
DWORD result = WaitForSingleObject(*lock, INFINITE);
switch (result) {
case WAIT_ABANDONED:
case WAIT_TIMEOUT:
break;
case WAIT_FAILED:
return (int)GetLastError();
}
return( PTHREAD_NORMAL_EXIT );
}
int
pthread_mutex_unlock(pthread_mutex_t *lock)
{
/*
* BOOL WINAPI ReleaseMutex( _In_ HANDLE hMutex );
*
* Note: The caller *must* be the owner (thread) of the lock!
*/
if (ReleaseMutex(*lock) == False) {
return (int)GetLastError();
} else {
return(PTHREAD_NORMAL_EXIT);
}
}
int
pthread_cond_init(pthread_cond_t * cv, const void *dummy)
{
/*
* I'm not sure the broadcast thang works - untested
* I had to tweak this to use SetEvent when signalling
* the SIGNAL event
*/
/* Create an auto-reset event */
cv->events_[SIGNAL] = CreateEvent(NULL, /* no security */
False, /* auto-reset event */
False, /* non-signaled initially */
NULL); /* unnamed */
/* Create a manual-reset event. */
cv->events_[BROADCAST] = CreateEvent(NULL, /* no security */
True, /* manual-reset */
False, /* non-signaled initially */
NULL); /* unnamed */
/* TODO - error handling */
return( PTHREAD_NORMAL_EXIT );
}
/* Note: This should return pthread_t, but cannot due to type mismatch! */
os_tid_t
pthread_self(void)
{
/* DWORD WINAPI GetCurrentThreadId(void); */
return( (os_tid_t)GetCurrentThreadId() );
}
/* Release the lock and wait for the other lock
* in one move.
*
* N.B.
* This isn't strictly pthread_cond_wait, but it works
* for this program without any race conditions.
*
*/
int
pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *lock)
{
DWORD dwRes = 0;
int ret = 0;
dwRes = SignalObjectAndWait(*lock, cv->events_[SIGNAL], INFINITE, True);
switch (dwRes) {
case WAIT_ABANDONED:
//printf("SignalObjectAndWait - Wait Abandoned \n");
return -1;
/* MSDN says this is one of the ret values, but I get compile errors */
//case WAIT_OBJECT_O:
// printf("SignalObjectAndWait thinks object is signalled\n");
// break;
case WAIT_TIMEOUT:
//printf("SignalObjectAndWait timed out\n");
break;
case 0xFFFFFFFF:
//os_perror(NULL, "SignalObjectAndWait failed");
return -1;
}
/* reacquire the lock */
WaitForSingleObject(*lock, INFINITE);
return ret;
}
/*
* Try to release one waiting thread.
*/
int
pthread_cond_signal(pthread_cond_t *cv)
{
if (!SetEvent (cv->events_[SIGNAL])) {
return (int)GetLastError();
} else {
return( PTHREAD_NORMAL_EXIT );
}
}
/*
* Try to release all waiting threads.
*/
int
pthread_cond_broadcast(pthread_cond_t *cv)
{
if (!PulseEvent (cv->events_[BROADCAST])) {
return (int)GetLastError();
} else {
return(PTHREAD_NORMAL_EXIT);
}
}
void
map_posix_flags(dinfo_t *dip, char *file, int posix_flags,
DWORD *DesiredAccess, DWORD *CreationDisposition,
DWORD *FlagsAndAttributes, DWORD *ShareMode)
{
*DesiredAccess = 0;
*CreationDisposition = 0;
*FlagsAndAttributes = 0;
*ShareMode = 0;
/*
* FILE_SHARE_DELETE = 0x00000004
* Enables subsequent open operations on a file or device to request
* delete access. Otherwise, other processes cannot open the file or device
* if they request delete access. If this flag is not specified, but the
* file or device has been opened for delete access, the function fails.
* Note: Delete access allows both delete and rename operations.
*/
if (posix_flags & O_EXCL) {
/*
* Value 0 - Prevents other processes from opening a file or device
* if they request delete, read, or write access.
*/
*ShareMode = 0;
} else {
*ShareMode = (FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE);
}
/*
* We map Unix style flags to the Windows equivalent (as best we can).
*
* Note: Changed FILE_READ_DATA/FILE_WRITE_DATA to GENERIC methods, to
* match what dt has always used and most other tools. Only cruisio and
* sio/nassio use the FILE*DATA method. dwim, crud, & netmist use GENERIC.
* At this point, I see no harm in switching, but add this note nonetheless!
*
* References: (Amazing what one can do on Windows!)
* http://msdn.microsoft.com/en-us/library/windows/desktop/aa365432(v=vs.85).aspx
* http://msdn.microsoft.com/en-us/library/windows/desktop/aa379607(v=vs.85).aspx
* http://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
*
*/
if (posix_flags & O_WRONLY) {
*DesiredAccess = GENERIC_WRITE;
} else if (posix_flags & O_RDWR) {
*DesiredAccess = (GENERIC_READ | GENERIC_WRITE);
} else { /* Assume O_RDONLY, which has a value of 0! */
*DesiredAccess = GENERIC_READ;
}
if (posix_flags & O_APPEND) {
*DesiredAccess |= FILE_APPEND_DATA;
}
if (posix_flags & O_CREAT) {
/*
* Note: This logic is required to match Unix create file behavior!
*/
if (posix_flags & O_EXCL) {
/*
* CREATE_NEW = 1 - Creates a new file, only if it does not already exist.
* If the specified file exists, the function fails and the last-error
* code is set to ERROR_FILE_EXISTS (80). If the specified file does not
* exist and is a valid path to a writable location, a new file is created.
*/
*CreationDisposition = CREATE_NEW;
#if 0
} else if (os_file_exists(file) == False) {
/*
* CREATE_ALWAYS = 2 - Creates a new file, always.
* If the specified file exists and is writable, the function overwrites the
* file, the function succeeds, and last-error code is set to ERROR_ALREADY_EXISTS (183).
* If the specified file does not exist and is a valid path, a new file is created,
* the function succeeds, and the last-error code is set to zero.
* Note: The overwrite sets the file length to 0, effectively truncating!
*/
*CreationDisposition = CREATE_ALWAYS;
#endif /* 0 */
} else {
/*
* OPEN_ALWAYS = 4 - Opens a file, always.
* If the specified file exists, the function succeeds and the last-error
* code is set to ERROR_ALREADY_EXISTS (183).
* If the specified file does not exist and is a valid path to a writable
* location, the function creates a file and the last-error code is set to zero.
*/
*CreationDisposition = OPEN_ALWAYS;
}
} else if (posix_flags & O_TRUNC) {
hbool_t exists;
/*
* TRUNCATE_EXISTING = 5
* Opens a file and truncates it so that its size is zero bytes, only
* if it exists. If the specified file does not exist, the function fails
* and the last-error code is set to ERROR_FILE_NOT_FOUND (2).
* The calling process must open the file with the GENERIC_WRITE bit set
* as part of the dwDesiredAccess parameter.
*/
if (dip) {
exists = dt_file_exists(dip, file);
} else {
exists = os_file_exists(file);
}
if (exists == True) {
*CreationDisposition = TRUNCATE_EXISTING;
} else {
*CreationDisposition = OPEN_ALWAYS;
}
} else {
/*
* OPEN_EXISTING = 3 - Opens a file or device, only if it exists.
* If the specified file or device does not exist, the function
* fails and the last-error code is set to ERROR_FILE_NOT_FOUND (2).
*/
*CreationDisposition = OPEN_EXISTING;
}
/*
* Who would have thought?
* https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
* To open a directory using CreateFile, specify the FILE_FLAG_BACKUP_SEMANTICS
* flag as part of dwFlagsAndAttributes. You must set this flag to obtain a handle
* to a directory. A directory handle can be passed to some functions instead of a
* file handle. Otherwise, ERROR_ACCESS_DENIED (5) is returned!
*/
if ( os_isdir(file) == True ) {
*FlagsAndAttributes |= FILE_FLAG_BACKUP_SEMANTICS;
}
if (posix_flags & (O_SYNC|O_DSYNC)) {
*FlagsAndAttributes |= FILE_FLAG_WRITE_THROUGH;
}
if (posix_flags & O_DIRECT) {
*FlagsAndAttributes |= (FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH);
}
if (posix_flags & O_RDONLY) {
*FlagsAndAttributes |= FILE_ATTRIBUTE_READONLY;
}
if (posix_flags & O_RANDOM) {
*FlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
} else if (posix_flags & O_SEQUENTIAL) {
*FlagsAndAttributes |= FILE_FLAG_SEQUENTIAL_SCAN;
}
if (posix_flags & O_ASYNC) {
*FlagsAndAttributes |= FILE_FLAG_OVERLAPPED;
}
/* Note: cruisio/sio also add FILE_FLAG_BACKUP_SEMANTICS. */
/* The best I can tell, this bypasses certain security! */
if (*FlagsAndAttributes == 0) {
*FlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
}
return;
}
/*
* dt_open_file() - Open a file with retries.
*
* Inputs:
* dip = The device information pointer.
* file = File name to check for existance.
* flags = The file open flags.
* perm = The file permissions.
* isDiskFull = Pointer to disk full flag.
* isDirectory = Pointer to directory flag.
* errors = The error control flag.
* retries = The retries control flag.
*
* Return Value:
* Returns the file handle (NoFd on failures).
*/
HANDLE
dt_open_file(dinfo_t *dip, char *file, int flags, int perm,
hbool_t *isDiskFull, hbool_t *isDirectory,
hbool_t errors, hbool_t retrys)
{
DWORD DesiredAccess;
DWORD CreationDisposition;
DWORD FlagsAndAttributes;
DWORD ShareMode;
HANDLE handle = NoFd;
int rc = SUCCESS;
if (isDiskFull) *isDiskFull = False;
if (isDirectory) *isDirectory = False;
map_posix_flags(dip, file, flags, &DesiredAccess, &CreationDisposition, &FlagsAndAttributes, &ShareMode);
if (dip->di_debug_flag) {
Printf(dip, "Attempting to open file %s with POSIX open flags %#x...\n", file, flags);
if (dip->di_extended_errors == True) {
ReportOpenInformation(dip, file, OS_OPEN_FILE_OP, DesiredAccess,
CreationDisposition, FlagsAndAttributes, ShareMode, False);
}
}
if (retrys == True) dip->di_retry_count = 0;
do {
ENABLE_NOPROG(dip, OPEN_OP);
handle = CreateFile(file, DesiredAccess, ShareMode,
NULL, CreationDisposition, FlagsAndAttributes, NULL);
DISABLE_NOPROG(dip);
if (handle == NoFd) {
os_error_t error = os_get_error();
INIT_ERROR_INFO(eip, file, OS_OPEN_FILE_OP, OPEN_OP, NULL, 0, (Offset_t)0, (size_t)0,
error, logLevelError, PRT_SYSLOG, RPT_NOXERRORS);
if (isDiskFull) {
*isDiskFull = os_isDiskFull(error);
if (*isDiskFull == True) return(handle);
}
if (isDirectory) {
*isDirectory = os_isADirectory(error);
if (*isDirectory == True) return(handle);
}
if (errors == False) eip->ei_rpt_flags |= RPT_NOERRORS;
if (retrys == False) eip->ei_rpt_flags |= RPT_NORETRYS;
rc = ReportRetryableError(dip, eip, "Failed to open file %s", file);
}
} while ( (handle == NoFd) && (rc == RETRYABLE) );
if ( (handle == NoFd) && (errors == True) ) {
if (dip->di_extended_errors == True) {
ReportOpenInformation(dip, file, OS_OPEN_FILE_OP, DesiredAccess,
CreationDisposition, FlagsAndAttributes, ShareMode, True);
}
} else if ( (dip->di_debug_flag == True) && (handle != NoFd) ) {
Printf(dip, "File %s successfully opened, handle = %d\n", file, handle);
}
return( handle );
}
HANDLE
os_open_file(char *name, int oflags, int perm)
{
HANDLE Handle;
DWORD DesiredAccess;
DWORD CreationDisposition;
DWORD FlagsAndAttributes;
DWORD ShareMode;
map_posix_flags(NULL, name, oflags, &DesiredAccess, &CreationDisposition, &FlagsAndAttributes, &ShareMode);
/*
* http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
*
* HANDLE WINAPI CreateFile(
* _In_ LPCTSTR lpFileName,
* _In_ DWORD dwDesiredAccess,
* _In_ DWORD dwShareMode,
* _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
* _In_ DWORD dwCreationDisposition,
* _In_ DWORD dwFlagsAndAttributes,
* _In_opt_ HANDLE hTemplateFile
*);
*/
Handle = CreateFile(name, DesiredAccess, ShareMode,
NULL, CreationDisposition, FlagsAndAttributes, NULL);
return( Handle );
}
__inline ssize_t
os_read_file(HANDLE handle, void *buffer, size_t size)
{
DWORD bytesRead;
/*
* BOOL WINAPI ReadFile(
* _In_ HANDLE hFile,
* _Out_ LPVOID lpBuffer,
* _In_ DWORD nNumberOfBytesToRead,
* _Out_opt_ LPDWORD lpNumberOfBytesRead,
* _Inout_opt_ LPOVERLAPPED lpOverlapped
* );
*/
if (ReadFile(handle, buffer, (DWORD)size, (LPDWORD)&bytesRead, NULL) == False) {
bytesRead = -1;
}
return( (ssize_t)(int)bytesRead );
}
__inline ssize_t
os_write_file(HANDLE handle, void *buffer, size_t size)
{
DWORD bytesWritten;
/*
* BOOL WINAPI WriteFile(
* _In_ HANDLE hFile,
* _In_ LPCVOID lpBuffer,
* _In_ DWORD nNumberOfBytesToWrite,
* _Out_opt_ LPDWORD lpNumberOfBytesWritten,
* _Inout_opt_ LPOVERLAPPED lpOverlapped
* );
*/
if (WriteFile(handle, buffer, (DWORD)size, (LPDWORD)&bytesWritten, NULL) == False) {
bytesWritten = -1;
}
return( (ssize_t)(int)bytesWritten );
}
/* Unix whence values: SEEK_SET(0), SEEK_CUR(1), SEEK_END(2) */
static int seek_map[] = { FILE_BEGIN, FILE_CURRENT, FILE_END };
/*
* Note that this is a 64-bit seek, Offset_t better be 64 bits
*/
Offset_t
os_seek_file(HANDLE handle, Offset_t offset, int whence)
{
LARGE_INTEGER liDistanceToMove;
LARGE_INTEGER lpNewFilePointer;
/*
* BOOL WINAPI SetFilePointerEx(
* _In_ HANDLE hFile,
* _In_ LARGE_INTEGER liDistanceToMove,
* _Out_opt_ PLARGE_INTEGER lpNewFilePointer,
* _In_ DWORD dwMoveMethod
* );
*/
liDistanceToMove.QuadPart = offset;
if ( SetFilePointerEx(handle, liDistanceToMove, &lpNewFilePointer, seek_map[whence]) == False) {
lpNewFilePointer.QuadPart = -1;
}
return( (Offset_t)(lpNewFilePointer.QuadPart) );
}
ssize_t
os_pread_file(HANDLE handle, void *buffer, size_t size, Offset_t offset)
{
DWORD bytesRead;
OVERLAPPED overlap;
BOOL result;
LARGE_INTEGER li;
li.QuadPart = offset;
overlap.Offset = li.LowPart;
overlap.OffsetHigh = li.HighPart;
overlap.hEvent = NULL;
/*
* BOOL WINAPI ReadFile(
* _In_ HANDLE hFile,
* _Out_ LPVOID lpBuffer,
* _In_ DWORD nNumberOfBytesToRead,
* _Out_opt_ LPDWORD lpNumberOfBytesRead,
* _Inout_opt_ LPOVERLAPPED lpOverlapped
* );
*/
result = ReadFile(handle, buffer, (DWORD)size, (LPDWORD)&bytesRead, &overlap);
if (result == False) {
DWORD error = GetLastError();
if (error == ERROR_IO_PENDING) {
/* WTF? When setting wait parameter True, the wrong bytes read value is returned on disks! */
while ( (result = GetOverlappedResult(handle, &overlap, (LPDWORD)&bytesRead, False)) == False) {
error = GetLastError();
if (error == ERROR_IO_INCOMPLETE) {
Sleep(10);
} else {
break;
}
}
}
if (result == False) {
bytesRead = FAILURE;
}
}
return( (ssize_t)(int)bytesRead );
}
ssize_t
os_pwrite_file(HANDLE handle, void *buffer, size_t size, Offset_t offset)
{
DWORD bytesWrite;
OVERLAPPED overlap;
BOOL result;
LARGE_INTEGER li;
li.QuadPart = offset;
overlap.Offset = li.LowPart;
overlap.OffsetHigh = li.HighPart;
overlap.hEvent = NULL;
/*
* BOOL WINAPI WriteFile(
* _In_ HANDLE hFile,
* _In_ LPCVOID lpBuffer,
* _In_ DWORD nNumberOfBytesToWrite,
* _Out_opt_ LPDWORD lpNumberOfBytesWritten,
* _Inout_opt_ LPOVERLAPPED lpOverlapped
* );
*/
result = WriteFile(handle, buffer, (DWORD)size, (LPDWORD)&bytesWrite, &overlap);
if (result == False) {
bytesWrite = FAILURE;
}
return( (ssize_t)(int)bytesWrite );
}
os_error_t
win32_getuncpath(char *path, char **uncpathp)
{
os_error_t error = NO_ERROR;
if (IsDriveLetter(path) == True) {
char uncpath[PATH_BUFFER_SIZE];
char drive[3];
DWORD uncpathsize = sizeof(uncpath);
strncpy(drive, path, 2); /* Copy the drive letter. */
drive[2] = '\0';
/*
* http://msdn.microsoft.com/en-us/library/windows/desktop/aa385453(v=vs.85).aspx
*
* DWORD WNetGetConnection(
* _In_ LPCTSTR lpLocalName,
* _Out_ LPTSTR lpRemoteName,
* _Inout_ LPDWORD lpnLength
* );
*/
if ((error = WNetGetConnection(drive, uncpath, &uncpathsize)) == NO_ERROR) {
strcat(uncpath, &path[2]); /* Copy everything *after* drive letter. */
*uncpathp = strdup(uncpath);
}
}
return(error);
}
HANDLE
win32_dup(HANDLE handle)
{
HANDLE hDup = (HANDLE)-1;
/* http://msdn.microsoft.com/en-us/library/ms724251(VS.85).aspx */
if ( !DuplicateHandle(GetCurrentProcess(),
handle,
GetCurrentProcess(),
&hDup,
0,
False,
DUPLICATE_SAME_ACCESS) ) {
DWORD dwErr = GetLastError();
errno = EINVAL;
}
return (hDup);
}
/* ============================================================================== */
hbool_t
IsDriveLetter(char *device)
{
/* Check for drive letters "[a-zA-Z]:" */
if ((strlen(device) >= 2) && (device[1] == ':') &&
((device[0] >= 'a') && (device[0] <= 'z') ||
(device[0] >= 'A') && (device[0] <= 'Z'))) {
return(True);
}
return(False);
}
char *
setup_scsi_device(dinfo_t *dip, char *path)
{
char *scsi_device;
scsi_device = Malloc(dip, (DEV_DIR_LEN * 2) );
if (scsi_device == NULL) return(scsi_device);
/* Format: \\.\[A-Z]: */
strcpy(scsi_device, DEV_DIR_PREFIX);
scsi_device[DEV_DIR_LEN] = path[0]; /* The drive letter. */
scsi_device[DEV_DIR_LEN+1] = path[1]; /* The ':' terminator. */
return(scsi_device);
}
hbool_t
FindMountDevice(dinfo_t *dip, char *path, hbool_t debug)
{
hbool_t match = False;
char *sdsf = NULL;
if ( IsDriveLetter(path) ) {
match = True;
sdsf = setup_scsi_device(dip, path);
} else if ( EQL(path, "\\\\", 2) || EQL(path, "//", 2) ) {
; /* Skip UNC paths! */
} else {
char path_dir[PATH_BUFFER_SIZE];
char *path_dirp;
memset(path_dir, '\0', sizeof(path_dir));
path_dirp = getcwd(path_dir, sizeof(path_dir));
if (path_dirp == NULL) return(match);
if ( IsDriveLetter(path_dirp) ) {
match = True;
sdsf = setup_scsi_device(dip, path_dirp);
}
}
if (match == True) {
dip->di_mounted_from_device = strdup(sdsf);
//dip->di_mounted_on_dir = strdup(mounted_path);