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