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