Update Windows code to fix build breakage
[fio.git] / os / windows / posix.c
CommitLineData
9277ec14
BC
1/* This file contains functions which implement those POSIX and Linux functions
2 * that MinGW and Microsoft don't provide. The implementations contain just enough
3 * functionality to support fio.
4 */
5
6#include <arpa/inet.h>
7#include <netinet/in.h>
8#include <windows.h>
9#include <stddef.h>
ad9c0fbc 10#include <string.h>
9277ec14
BC
11#include <stdlib.h>
12#include <unistd.h>
13#include <dirent.h>
14#include <pthread.h>
f16b7405 15#include <time.h>
9277ec14
BC
16#include <semaphore.h>
17#include <sys/shm.h>
18#include <sys/mman.h>
19#include <sys/uio.h>
20#include <sys/resource.h>
21#include <sys/poll.h>
22
23#include "../os-windows.h"
671b0600 24#include "../../lib/hweight.h"
9277ec14 25
21c75387
BC
26extern unsigned long mtime_since_now(struct timeval *);
27extern void fio_gettime(struct timeval *, void *);
28
ad9c0fbc
BC
29/* These aren't defined in the MinGW headers */
30HRESULT WINAPI StringCchCopyA(
31 char *pszDest,
32 size_t cchDest,
33 const char *pszSrc);
34
35HRESULT WINAPI StringCchPrintfA(
36 char *pszDest,
37 size_t cchDest,
38 const char *pszFormat,
39 ...);
40
41int vsprintf_s(
42 char *buffer,
43 size_t numberOfElements,
44 const char *format,
45 va_list argptr);
46
10a6b3c6
BC
47int win_to_posix_error(DWORD winerr)
48{
49 switch (winerr)
50 {
51 case ERROR_FILE_NOT_FOUND: return ENOENT;
52 case ERROR_PATH_NOT_FOUND: return ENOENT;
53 case ERROR_ACCESS_DENIED: return EACCES;
54 case ERROR_INVALID_HANDLE: return EBADF;
55 case ERROR_NOT_ENOUGH_MEMORY: return ENOMEM;
56 case ERROR_INVALID_DATA: return EINVAL;
57 case ERROR_OUTOFMEMORY: return ENOMEM;
58 case ERROR_INVALID_DRIVE: return ENODEV;
59 case ERROR_NOT_SAME_DEVICE: return EXDEV;
60 case ERROR_WRITE_PROTECT: return EROFS;
61 case ERROR_BAD_UNIT: return ENODEV;
62 case ERROR_SHARING_VIOLATION: return EACCES;
63 case ERROR_LOCK_VIOLATION: return EACCES;
64 case ERROR_SHARING_BUFFER_EXCEEDED: return ENOLCK;
65 case ERROR_HANDLE_DISK_FULL: return ENOSPC;
66 case ERROR_NOT_SUPPORTED: return ENOSYS;
67 case ERROR_FILE_EXISTS: return EEXIST;
68 case ERROR_CANNOT_MAKE: return EPERM;
69 case ERROR_INVALID_PARAMETER: return EINVAL;
70 case ERROR_NO_PROC_SLOTS: return EAGAIN;
71 case ERROR_BROKEN_PIPE: return EPIPE;
72 case ERROR_OPEN_FAILED: return EIO;
73 case ERROR_NO_MORE_SEARCH_HANDLES: return ENFILE;
74 case ERROR_CALL_NOT_IMPLEMENTED: return ENOSYS;
75 case ERROR_INVALID_NAME: return ENOENT;
76 case ERROR_WAIT_NO_CHILDREN: return ECHILD;
77 case ERROR_CHILD_NOT_COMPLETE: return EBUSY;
78 case ERROR_DIR_NOT_EMPTY: return ENOTEMPTY;
79 case ERROR_SIGNAL_REFUSED: return EIO;
80 case ERROR_BAD_PATHNAME: return ENOENT;
81 case ERROR_SIGNAL_PENDING: return EBUSY;
82 case ERROR_MAX_THRDS_REACHED: return EAGAIN;
83 case ERROR_BUSY: return EBUSY;
84 case ERROR_ALREADY_EXISTS: return EEXIST;
85 case ERROR_NO_SIGNAL_SENT: return EIO;
86 case ERROR_FILENAME_EXCED_RANGE: return EINVAL;
87 case ERROR_META_EXPANSION_TOO_LONG: return EINVAL;
88 case ERROR_INVALID_SIGNAL_NUMBER: return EINVAL;
89 case ERROR_THREAD_1_INACTIVE: return EINVAL;
90 case ERROR_BAD_PIPE: return EINVAL;
91 case ERROR_PIPE_BUSY: return EBUSY;
92 case ERROR_NO_DATA: return EPIPE;
93 case ERROR_MORE_DATA: return EAGAIN;
94 case ERROR_DIRECTORY: return ENOTDIR;
95 case ERROR_PIPE_CONNECTED: return EBUSY;
96 case ERROR_NO_TOKEN: return EINVAL;
97 case ERROR_PROCESS_ABORTED: return EFAULT;
98 case ERROR_BAD_DEVICE: return ENODEV;
99 case ERROR_BAD_USERNAME: return EINVAL;
100 case ERROR_OPEN_FILES: return EAGAIN;
101 case ERROR_ACTIVE_CONNECTIONS: return EAGAIN;
102 case ERROR_DEVICE_IN_USE: return EAGAIN;
103 case ERROR_INVALID_AT_INTERRUPT_TIME: return EINTR;
104 case ERROR_IO_DEVICE: return EIO;
105 case ERROR_NOT_OWNER: return EPERM;
106 case ERROR_END_OF_MEDIA: return ENOSPC;
107 case ERROR_EOM_OVERFLOW: return ENOSPC;
108 case ERROR_BEGINNING_OF_MEDIA: return ESPIPE;
109 case ERROR_SETMARK_DETECTED: return ESPIPE;
110 case ERROR_NO_DATA_DETECTED: return ENOSPC;
111 case ERROR_POSSIBLE_DEADLOCK: return EDEADLOCK;
112 case ERROR_CRC: return EIO;
113 case ERROR_NEGATIVE_SEEK: return EINVAL;
114 case ERROR_DISK_FULL: return ENOSPC;
115 case ERROR_NOACCESS: return EFAULT;
116 case ERROR_FILE_INVALID: return ENXIO;
117 }
118
119 return winerr;
120}
121
671b0600
BC
122int GetNumLogicalProcessors(void)
123{
124 SYSTEM_LOGICAL_PROCESSOR_INFORMATION *processor_info = NULL;
125 DWORD len = 0;
126 DWORD num_processors = 0;
127 DWORD error = 0;
128 DWORD i;
129
130 while (!GetLogicalProcessorInformation(processor_info, &len)) {
131 error = GetLastError();
132 if (error == ERROR_INSUFFICIENT_BUFFER)
133 processor_info = malloc(len);
134 else {
135 log_err("Error: GetLogicalProcessorInformation failed: %d\n", error);
136 return -1;
137 }
138
139 if (processor_info == NULL) {
140 log_err("Error: failed to allocate memory for GetLogicalProcessorInformation");
141 return -1;
142 }
143 }
144
145 for (i = 0; i < len / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); i++)
146 {
147 if (processor_info[i].Relationship == RelationProcessorCore)
4ee47af0 148 num_processors += hweight64(processor_info[i].ProcessorMask);
671b0600
BC
149 }
150
151 free(processor_info);
152 return num_processors;
153}
154
9277ec14
BC
155long sysconf(int name)
156{
671b0600 157 long val = -1;
01d26955 158 long val2 = -1;
9277ec14
BC
159 SYSTEM_INFO sysInfo;
160 MEMORYSTATUSEX status;
161
162 switch (name)
163 {
164 case _SC_NPROCESSORS_ONLN:
671b0600
BC
165 val = GetNumLogicalProcessors();
166 if (val == -1)
01d26955 167 log_err("sysconf(_SC_NPROCESSORS_ONLN) failed\n");
671b0600 168
9277ec14
BC
169 break;
170
171 case _SC_PAGESIZE:
172 GetSystemInfo(&sysInfo);
173 val = sysInfo.dwPageSize;
174 break;
175
176 case _SC_PHYS_PAGES:
177 status.dwLength = sizeof(status);
01d26955
BC
178 val2 = sysconf(_SC_PAGESIZE);
179 if (GlobalMemoryStatusEx(&status) && val2 != -1)
180 val = status.ullTotalPhys / val2;
181 else
182 log_err("sysconf(_SC_PHYS_PAGES) failed\n");
9277ec14
BC
183 break;
184 default:
185 log_err("sysconf(%d) is not implemented\n", name);
186 break;
187 }
188
189 return val;
190}
191
192char *dl_error = NULL;
193
194int dlclose(void *handle)
195{
196 return !FreeLibrary((HMODULE)handle);
197}
198
199void *dlopen(const char *file, int mode)
200{
201 HMODULE hMod;
202
203 hMod = LoadLibrary(file);
204 if (hMod == INVALID_HANDLE_VALUE)
205 dl_error = (char*)"LoadLibrary failed";
206 else
207 dl_error = NULL;
208
209 return hMod;
210}
211
212void *dlsym(void *handle, const char *name)
213{
214 FARPROC fnPtr;
215
216 fnPtr = GetProcAddress((HMODULE)handle, name);
217 if (fnPtr == NULL)
218 dl_error = (char*)"GetProcAddress failed";
219 else
220 dl_error = NULL;
221
222 return fnPtr;
223}
224
225char *dlerror(void)
226{
227 return dl_error;
228}
229
230int gettimeofday(struct timeval *restrict tp, void *restrict tzp)
231{
232 FILETIME fileTime;
9576f613
BC
233 uint64_t unix_time, windows_time;
234 const uint64_t MILLISECONDS_BETWEEN_1601_AND_1970 = 11644473600000;
9277ec14 235
fc0b830f 236 /* Ignore the timezone parameter */
9277ec14
BC
237 (void)tzp;
238
239 /*
240 * Windows time is stored as the number 100 ns intervals since January 1 1601.
241 * Conversion details from http://www.informit.com/articles/article.aspx?p=102236&seqNum=3
242 * Its precision is 100 ns but accuracy is only one clock tick, or normally around 15 ms.
243 */
244 GetSystemTimeAsFileTime(&fileTime);
9576f613 245 windows_time = ((uint64_t)fileTime.dwHighDateTime << 32) + fileTime.dwLowDateTime;
9277ec14
BC
246 /* Divide by 10,000 to convert to ms and subtract the time between 1601 and 1970 */
247 unix_time = (((windows_time)/10000) - MILLISECONDS_BETWEEN_1601_AND_1970);
248 /* unix_time is now the number of milliseconds since 1970 (the Unix epoch) */
249 tp->tv_sec = unix_time / 1000;
250 tp->tv_usec = (unix_time % 1000) * 1000;
251 return 0;
252}
253
9277ec14
BC
254int sigaction(int sig, const struct sigaction *act,
255 struct sigaction *oact)
256{
e5b8f91c
BC
257 int rc = 0;
258 void (*prev_handler)(int);
259
260 prev_handler = signal(sig, act->sa_handler);
261 if (oact != NULL)
262 oact->sa_handler = prev_handler;
263
264 if (prev_handler == SIG_ERR)
265 rc = -1;
266
267 return rc;
9277ec14
BC
268}
269
270int lstat(const char * path, struct stat * buf)
271{
272 return stat(path, buf);
273}
274
275void *mmap(void *addr, size_t len, int prot, int flags,
276 int fildes, off_t off)
277{
278 DWORD vaProt = 0;
279 void* allocAddr = NULL;
280
281 if (prot & PROT_NONE)
282 vaProt |= PAGE_NOACCESS;
283
284 if ((prot & PROT_READ) && !(prot & PROT_WRITE))
285 vaProt |= PAGE_READONLY;
286
287 if (prot & PROT_WRITE)
288 vaProt |= PAGE_READWRITE;
289
290 if ((flags & MAP_ANON) | (flags & MAP_ANONYMOUS))
291 {
292 allocAddr = VirtualAlloc(addr, len, MEM_COMMIT, vaProt);
10a6b3c6
BC
293 if (allocAddr == NULL)
294 errno = win_to_posix_error(GetLastError());
9277ec14
BC
295 }
296
297 return allocAddr;
298}
299
300int munmap(void *addr, size_t len)
301{
10a6b3c6
BC
302 if (!VirtualFree(addr, 0, MEM_RELEASE)) {
303 errno = win_to_posix_error(GetLastError());
304 return -1;
305 }
306
307 return 0;
9277ec14
BC
308}
309
310int fork(void)
311{
312 log_err("%s is not implemented\n", __func__);
313 errno = ENOSYS;
10a6b3c6 314 return -1;
9277ec14
BC
315}
316
317pid_t setsid(void)
318{
319 log_err("%s is not implemented\n", __func__);
320 errno = ENOSYS;
10a6b3c6 321 return -1;
9277ec14
BC
322}
323
ad9c0fbc
BC
324static HANDLE log_file = INVALID_HANDLE_VALUE;
325
9277ec14
BC
326void openlog(const char *ident, int logopt, int facility)
327{
ad9c0fbc
BC
328 if (log_file == INVALID_HANDLE_VALUE)
329 log_file = CreateFileA("syslog.txt", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
9277ec14
BC
330}
331
332void closelog(void)
333{
ad9c0fbc
BC
334 CloseHandle(log_file);
335 log_file = INVALID_HANDLE_VALUE;
336}
337
338void syslog(int priority, const char *message, ... /* argument */)
339{
340 va_list v;
341 int len;
342 char *output;
343 DWORD bytes_written;
344
345 if (log_file == INVALID_HANDLE_VALUE) {
346 log_file = CreateFileA("syslog.txt", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
347 }
348
349 if (log_file == INVALID_HANDLE_VALUE) {
350 log_err("syslog: failed to open log file\n");
351 return;
352 }
353
354 va_start(v, message);
355 len = _vscprintf(message, v);
356 output = malloc(len + sizeof(char));
98dc2db5 357 vsprintf(output, message, v);
ad9c0fbc
BC
358 WriteFile(log_file, output, len, &bytes_written, NULL);
359 va_end(v);
98dc2db5 360 free(output);
9277ec14
BC
361}
362
363int kill(pid_t pid, int sig)
364{
365 errno = ESRCH;
10a6b3c6 366 return -1;
9277ec14
BC
367}
368
fc0b830f
BC
369/*
370 * This is assumed to be used only by the network code,
371 * and so doesn't try and handle any of the other cases
372 */
9277ec14
BC
373int fcntl(int fildes, int cmd, ...)
374{
fc0b830f
BC
375 /*
376 * non-blocking mode doesn't work the same as in BSD sockets,
377 * so ignore it.
378 */
9277ec14
BC
379#if 0
380 va_list ap;
381 int val, opt, status;
382
383 if (cmd == F_GETFL)
384 return 0;
385 else if (cmd != F_SETFL) {
386 errno = EINVAL;
10a6b3c6 387 return -1;
9277ec14
BC
388 }
389
390 va_start(ap, 1);
391
392 opt = va_arg(ap, int);
393 if (opt & O_NONBLOCK)
394 val = 1;
395 else
396 val = 0;
397
398 status = ioctlsocket((SOCKET)fildes, opt, &val);
399
400 if (status == SOCKET_ERROR) {
401 errno = EINVAL;
402 val = -1;
403 }
404
405 va_end(ap);
406
407 return val;
408#endif
409return 0;
410}
411
412/*
413 * Get the value of a local clock source.
414 * This implementation supports 2 clocks: CLOCK_MONOTONIC provides high-accuracy
415 * relative time, while CLOCK_REALTIME provides a low-accuracy wall time.
416 */
417int clock_gettime(clockid_t clock_id, struct timespec *tp)
418{
419 int rc = 0;
420
421 if (clock_id == CLOCK_MONOTONIC)
422 {
423 static LARGE_INTEGER freq = {{0,0}};
424 LARGE_INTEGER counts;
5aa23eb8 425 uint64_t t;
9277ec14
BC
426
427 QueryPerformanceCounter(&counts);
428 if (freq.QuadPart == 0)
429 QueryPerformanceFrequency(&freq);
430
431 tp->tv_sec = counts.QuadPart / freq.QuadPart;
432 /* Get the difference between the number of ns stored
433 * in 'tv_sec' and that stored in 'counts' */
5aa23eb8 434 t = tp->tv_sec * freq.QuadPart;
9277ec14
BC
435 t = counts.QuadPart - t;
436 /* 't' now contains the number of cycles since the last second.
437 * We want the number of nanoseconds, so multiply out by 1,000,000,000
438 * and then divide by the frequency. */
439 t *= 1000000000;
440 tp->tv_nsec = t / freq.QuadPart;
441 }
442 else if (clock_id == CLOCK_REALTIME)
443 {
444 /* clock_gettime(CLOCK_REALTIME,...) is just an alias for gettimeofday with a
445 * higher-precision field. */
446 struct timeval tv;
447 gettimeofday(&tv, NULL);
448 tp->tv_sec = tv.tv_sec;
449 tp->tv_nsec = tv.tv_usec * 1000;
450 } else {
451 errno = EINVAL;
452 rc = -1;
453 }
454
455 return rc;
456}
457
458int mlock(const void * addr, size_t len)
459{
10a6b3c6
BC
460 SIZE_T min, max;
461 BOOL success;
462 HANDLE process = GetCurrentProcess();
463
464 success = GetProcessWorkingSetSize(process, &min, &max);
465 if (!success) {
466 errno = win_to_posix_error(GetLastError());
467 return -1;
468 }
469
470 min += len;
471 max += len;
472 success = SetProcessWorkingSetSize(process, min, max);
473 if (!success) {
474 errno = win_to_posix_error(GetLastError());
475 return -1;
476 }
477
478 success = VirtualLock((LPVOID)addr, len);
479 if (!success) {
480 errno = win_to_posix_error(GetLastError());
481 return -1;
482 }
483
484 return 0;
9277ec14
BC
485}
486
487int munlock(const void * addr, size_t len)
488{
10a6b3c6
BC
489 BOOL success = VirtualUnlock((LPVOID)addr, len);
490 if (!success) {
491 errno = win_to_posix_error(GetLastError());
492 return -1;
493 }
494
495 return 0;
9277ec14
BC
496}
497
498pid_t waitpid(pid_t pid, int *stat_loc, int options)
499{
500 log_err("%s is not implemented\n", __func__);
501 errno = ENOSYS;
502 return -1;
503}
504
505int usleep(useconds_t useconds)
506{
507 Sleep(useconds / 1000);
508 return 0;
509}
510
511char *basename(char *path)
512{
513 static char name[MAX_PATH];
514 int i;
515
516 if (path == NULL || strlen(path) == 0)
517 return (char*)".";
518
519 i = strlen(path) - 1;
520
9576f613 521 while (path[i] != '\\' && path[i] != '/' && i >= 0)
9277ec14
BC
522 i--;
523
9576f613 524 strncpy(name, path + i + 1, MAX_PATH);
9277ec14
BC
525
526 return name;
527}
528
9277ec14
BC
529int fsync(int fildes)
530{
531 HANDLE hFile = (HANDLE)_get_osfhandle(fildes);
10a6b3c6
BC
532 if (!FlushFileBuffers(hFile)) {
533 errno = win_to_posix_error(GetLastError());
534 return -1;
535 }
536
537 return 0;
9277ec14
BC
538}
539
540int nFileMappings = 0;
541HANDLE fileMappings[1024];
542
543int shmget(key_t key, size_t size, int shmflg)
544{
545 int mapid = -1;
d3987946
BC
546 uint32_t size_low = size & 0xFFFFFFFF;
547 uint32_t size_high = ((uint64_t)size) >> 32;
548 HANDLE hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, (PAGE_EXECUTE_READWRITE | SEC_RESERVE), size_high, size_low, NULL);
9277ec14
BC
549 if (hMapping != NULL) {
550 fileMappings[nFileMappings] = hMapping;
551 mapid = nFileMappings;
552 nFileMappings++;
553 } else {
554 errno = ENOSYS;
555 }
556
557 return mapid;
558}
559
560void *shmat(int shmid, const void *shmaddr, int shmflg)
561{
562 void* mapAddr;
563 MEMORY_BASIC_INFORMATION memInfo;
564 mapAddr = MapViewOfFile(fileMappings[shmid], FILE_MAP_ALL_ACCESS, 0, 0, 0);
10a6b3c6
BC
565 if (mapAddr == NULL) {
566 errno = win_to_posix_error(GetLastError());
567 return (void*)-1;
568 }
569
570 if (VirtualQuery(mapAddr, &memInfo, sizeof(memInfo)) == 0) {
571 errno = win_to_posix_error(GetLastError());
572 return (void*)-1;
573 }
574
9277ec14 575 mapAddr = VirtualAlloc(mapAddr, memInfo.RegionSize, MEM_COMMIT, PAGE_READWRITE);
10a6b3c6
BC
576 if (mapAddr == NULL) {
577 errno = win_to_posix_error(GetLastError());
578 return (void*)-1;
579 }
580
9277ec14
BC
581 return mapAddr;
582}
583
584int shmdt(const void *shmaddr)
585{
10a6b3c6
BC
586 if (!UnmapViewOfFile(shmaddr)) {
587 errno = win_to_posix_error(GetLastError());
588 return -1;
589 }
590
591 return 0;
9277ec14
BC
592}
593
594int shmctl(int shmid, int cmd, struct shmid_ds *buf)
595{
596 if (cmd == IPC_RMID) {
597 fileMappings[shmid] = INVALID_HANDLE_VALUE;
598 return 0;
599 } else {
600 log_err("%s is not implemented\n", __func__);
601 }
10a6b3c6
BC
602 errno = ENOSYS;
603 return -1;
9277ec14
BC
604}
605
606int setuid(uid_t uid)
607{
608 log_err("%s is not implemented\n", __func__);
609 errno = ENOSYS;
10a6b3c6 610 return -1;
9277ec14
BC
611}
612
613int setgid(gid_t gid)
614{
615 log_err("%s is not implemented\n", __func__);
616 errno = ENOSYS;
10a6b3c6 617 return -1;
9277ec14
BC
618}
619
620int nice(int incr)
621{
622 if (incr != 0) {
623 errno = EINVAL;
624 return -1;
625 }
626
627 return 0;
628}
629
630int getrusage(int who, struct rusage *r_usage)
631{
9576f613 632 const uint64_t SECONDS_BETWEEN_1601_AND_1970 = 11644473600;
9277ec14
BC
633 FILETIME cTime, eTime, kTime, uTime;
634 time_t time;
7732a09b 635 HANDLE h;
9277ec14
BC
636
637 memset(r_usage, 0, sizeof(*r_usage));
638
7732a09b
HL
639 if (who == RUSAGE_SELF) {
640 h = GetCurrentProcess();
641 GetProcessTimes(h, &cTime, &eTime, &kTime, &uTime);
642 } else if (who == RUSAGE_THREAD) {
643 h = GetCurrentThread();
644 GetThreadTimes(h, &cTime, &eTime, &kTime, &uTime);
645 } else {
646 log_err("fio: getrusage %d is not implemented\n", who);
647 return -1;
648 }
649
9576f613 650 time = ((uint64_t)uTime.dwHighDateTime << 32) + uTime.dwLowDateTime;
9277ec14
BC
651 /* Divide by 10,000,000 to get the number of seconds and move the epoch from
652 * 1601 to 1970 */
653 time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
654 r_usage->ru_utime.tv_sec = time;
655 /* getrusage() doesn't care about anything other than seconds, so set tv_usec to 0 */
656 r_usage->ru_utime.tv_usec = 0;
9576f613 657 time = ((uint64_t)kTime.dwHighDateTime << 32) + kTime.dwLowDateTime;
9277ec14
BC
658 /* Divide by 10,000,000 to get the number of seconds and move the epoch from
659 * 1601 to 1970 */
660 time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
661 r_usage->ru_stime.tv_sec = time;
662 r_usage->ru_stime.tv_usec = 0;
663 return 0;
664}
665
666int posix_madvise(void *addr, size_t len, int advice)
667{
668 log_err("%s is not implemented\n", __func__);
669 return ENOSYS;
670}
671
fc0b830f 672/* Windows doesn't support advice for memory pages. Just ignore it. */
9277ec14
BC
673int msync(void *addr, size_t len, int flags)
674{
9277ec14
BC
675 errno = ENOSYS;
676 return -1;
677}
678
679int fdatasync(int fildes)
680{
681 return fsync(fildes);
682}
683
684ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
685 off_t offset)
686{
9576f613
BC
687 int64_t pos = _telli64(fildes);
688 ssize_t len = _write(fildes, buf, nbyte);
689 _lseeki64(fildes, pos, SEEK_SET);
9277ec14
BC
690 return len;
691}
692
693ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset)
694{
9576f613 695 int64_t pos = _telli64(fildes);
9277ec14 696 ssize_t len = read(fildes, buf, nbyte);
9576f613 697 _lseeki64(fildes, pos, SEEK_SET);
9277ec14
BC
698 return len;
699}
700
701ssize_t readv(int fildes, const struct iovec *iov, int iovcnt)
702{
703 log_err("%s is not implemented\n", __func__);
704 errno = ENOSYS;
10a6b3c6 705 return -1;
9277ec14
BC
706}
707
708ssize_t writev(int fildes, const struct iovec *iov, int iovcnt)
709{
710 log_err("%s is not implemented\n", __func__);
711 errno = ENOSYS;
10a6b3c6 712 return -1;
9277ec14
BC
713}
714
715long long strtoll(const char *restrict str, char **restrict endptr,
716 int base)
717{
718 return _strtoi64(str, endptr, base);
719}
720
9277ec14
BC
721int poll(struct pollfd fds[], nfds_t nfds, int timeout)
722{
723 struct timeval tv;
724 struct timeval *to = NULL;
725 fd_set readfds, writefds, exceptfds;
726 int i;
727 int rc;
728
3f457bea 729 if (timeout != -1) {
f9a58c2a 730 to = &tv;
3f457bea
BC
731 to->tv_sec = timeout / 1000;
732 to->tv_usec = (timeout % 1000) * 1000;
733 }
9277ec14
BC
734
735 FD_ZERO(&readfds);
736 FD_ZERO(&writefds);
737 FD_ZERO(&exceptfds);
738
739 for (i = 0; i < nfds; i++)
740 {
741 if (fds[i].fd < 0) {
742 fds[i].revents = 0;
743 continue;
744 }
745
746 if (fds[i].events & POLLIN)
747 FD_SET(fds[i].fd, &readfds);
748
749 if (fds[i].events & POLLOUT)
750 FD_SET(fds[i].fd, &writefds);
751
f9a58c2a 752 FD_SET(fds[i].fd, &exceptfds);
9277ec14
BC
753 }
754
755 rc = select(nfds, &readfds, &writefds, &exceptfds, to);
756
757 if (rc != SOCKET_ERROR) {
758 for (i = 0; i < nfds; i++)
759 {
760 if (fds[i].fd < 0) {
761 continue;
762 }
763
764 if ((fds[i].events & POLLIN) && FD_ISSET(fds[i].fd, &readfds))
765 fds[i].revents |= POLLIN;
766
767 if ((fds[i].events & POLLOUT) && FD_ISSET(fds[i].fd, &writefds))
768 fds[i].revents |= POLLOUT;
769
770 if (FD_ISSET(fds[i].fd, &exceptfds))
771 fds[i].revents |= POLLHUP;
772 }
773 }
774
775 return rc;
776}
777
778int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
779{
21c75387
BC
780 struct timeval tv;
781 DWORD ms_remaining;
782 DWORD ms_total = (rqtp->tv_sec * 1000) + (rqtp->tv_nsec / 1000000.0);
783
784 if (ms_total == 0)
785 ms_total = 1;
786
787 ms_remaining = ms_total;
788
789 /* Since Sleep() can sleep for less than the requested time, add a loop to
790 ensure we only return after the requested length of time has elapsed */
791 do {
792 fio_gettime(&tv, NULL);
793 Sleep(ms_remaining);
794 ms_remaining = ms_total - mtime_since_now(&tv);
795 } while (ms_remaining > 0 && ms_remaining < ms_total);
796
797 /* this implementation will never sleep for less than the requested time */
798 if (rmtp != NULL) {
799 rmtp->tv_sec = 0;
800 rmtp->tv_nsec = 0;
801 }
802
803 return 0;
9277ec14
BC
804}
805
806DIR *opendir(const char *dirname)
807{
01d26955
BC
808 struct dirent_ctx *dc = NULL;
809
810 /* See if we can open it. If not, we'll return an error here */
811 HANDLE file = CreateFileA(dirname, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
812 if (file != INVALID_HANDLE_VALUE) {
813 CloseHandle(file);
814 dc = (struct dirent_ctx*)malloc(sizeof(struct dirent_ctx));
815 StringCchCopyA(dc->dirname, MAX_PATH, dirname);
816 dc->find_handle = INVALID_HANDLE_VALUE;
817 } else {
818 DWORD error = GetLastError();
819 if (error == ERROR_FILE_NOT_FOUND)
820 errno = ENOENT;
821
822 else if (error == ERROR_PATH_NOT_FOUND)
823 errno = ENOTDIR;
824 else if (error == ERROR_TOO_MANY_OPEN_FILES)
825 errno = ENFILE;
826 else if (error == ERROR_ACCESS_DENIED)
827 errno = EACCES;
828 else
829 errno = error;
830 }
831
832 return dc;
9277ec14
BC
833}
834
835int closedir(DIR *dirp)
836{
01d26955
BC
837 if (dirp != NULL && dirp->find_handle != INVALID_HANDLE_VALUE)
838 FindClose(dirp->find_handle);
ad9c0fbc 839
01d26955
BC
840 free(dirp);
841 return 0;
9277ec14
BC
842}
843
844struct dirent *readdir(DIR *dirp)
845{
ad9c0fbc
BC
846 static struct dirent de;
847 WIN32_FIND_DATA find_data;
848
849 if (dirp == NULL)
850 return NULL;
851
852 if (dirp->find_handle == INVALID_HANDLE_VALUE) {
853 char search_pattern[MAX_PATH];
854 StringCchPrintfA(search_pattern, MAX_PATH, "%s\\*", dirp->dirname);
855 dirp->find_handle = FindFirstFileA(search_pattern, &find_data);
856 if (dirp->find_handle == INVALID_HANDLE_VALUE)
857 return NULL;
858 } else {
859 if (!FindNextFile(dirp->find_handle, &find_data))
860 return NULL;
861 }
862
863 StringCchCopyA(de.d_name, MAX_PATH, find_data.cFileName);
864 de.d_ino = 0;
865
866 return &de;
9277ec14
BC
867}
868
869uid_t geteuid(void)
870{
871 log_err("%s is not implemented\n", __func__);
872 errno = ENOSYS;
873 return -1;
874}
875
f16b7405
BC
876in_addr_t inet_network(const char *cp)
877{
878 in_addr_t hbo;
879 in_addr_t nbo = inet_addr(cp);
880 hbo = ((nbo & 0xFF) << 24) + ((nbo & 0xFF00) << 8) + ((nbo & 0xFF0000) >> 8) + ((nbo & 0xFF000000) >> 24);
881 return hbo;
882}
883
9277ec14
BC
884const char* inet_ntop(int af, const void *restrict src,
885 char *restrict dst, socklen_t size)
886{
887 INT status = SOCKET_ERROR;
888 WSADATA wsd;
889 char *ret = NULL;
890
891 if (af != AF_INET && af != AF_INET6) {
892 errno = EAFNOSUPPORT;
893 return NULL;
894 }
895
896 WSAStartup(MAKEWORD(2,2), &wsd);
897
898 if (af == AF_INET) {
899 struct sockaddr_in si;
900 DWORD len = size;
901 memset(&si, 0, sizeof(si));
902 si.sin_family = af;
903 memcpy(&si.sin_addr, src, sizeof(si.sin_addr));
904 status = WSAAddressToString((struct sockaddr*)&si, sizeof(si), NULL, dst, &len);
905 } else if (af == AF_INET6) {
906 struct sockaddr_in6 si6;
907 DWORD len = size;
908 memset(&si6, 0, sizeof(si6));
909 si6.sin6_family = af;
910 memcpy(&si6.sin6_addr, src, sizeof(si6.sin6_addr));
911 status = WSAAddressToString((struct sockaddr*)&si6, sizeof(si6), NULL, dst, &len);
912 }
913
914 if (status != SOCKET_ERROR)
915 ret = dst;
916 else
917 errno = ENOSPC;
918
919 WSACleanup();
3f457bea 920
9277ec14
BC
921 return ret;
922}
923
924int inet_pton(int af, const char *restrict src, void *restrict dst)
925{
926 INT status = SOCKET_ERROR;
927 WSADATA wsd;
928 int ret = 1;
929
930 if (af != AF_INET && af != AF_INET6) {
931 errno = EAFNOSUPPORT;
932 return -1;
933 }
934
935 WSAStartup(MAKEWORD(2,2), &wsd);
936
937 if (af == AF_INET) {
938 struct sockaddr_in si;
939 INT len = sizeof(si);
940 memset(&si, 0, sizeof(si));
941 si.sin_family = af;
942 status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si, &len);
943 if (status != SOCKET_ERROR)
944 memcpy(dst, &si.sin_addr, sizeof(si.sin_addr));
945 } else if (af == AF_INET6) {
946 struct sockaddr_in6 si6;
947 INT len = sizeof(si6);
948 memset(&si6, 0, sizeof(si6));
949 si6.sin6_family = af;
950 status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si6, &len);
951 if (status != SOCKET_ERROR)
952 memcpy(dst, &si6.sin6_addr, sizeof(si6.sin6_addr));
953 }
954
955 if (status == SOCKET_ERROR) {
956 errno = ENOSPC;
957 ret = 0;
958 }
959
960 WSACleanup();
961
962 return ret;
963}