fix 32-bit Windows fio (overflow in getusage and gettimeofday)
[fio.git] / os / windows / posix.c
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>
10 #include <stdlib.h>
11 #include <unistd.h>
12 #include <dirent.h>
13 #include <pthread.h>
14 #include <semaphore.h>
15 #include <sys/shm.h>
16 #include <sys/mman.h>
17 #include <sys/uio.h>
18 #include <sys/resource.h>
19 #include <sys/poll.h>
20
21 #include "../os-windows.h"
22
23 extern unsigned long mtime_since_now(struct timeval *);
24 extern void fio_gettime(struct timeval *, void *);
25
26 long sysconf(int name)
27 {
28         long long val = -1;
29         DWORD len;
30         SYSTEM_LOGICAL_PROCESSOR_INFORMATION processorInfo;
31         SYSTEM_INFO sysInfo;
32         MEMORYSTATUSEX status;
33
34         switch (name)
35         {
36         case _SC_NPROCESSORS_ONLN:
37                 len = sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
38                 GetLogicalProcessorInformation(&processorInfo, &len);
39                 val = len / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
40                 break;
41
42         case _SC_PAGESIZE:
43                 GetSystemInfo(&sysInfo);
44                 val = sysInfo.dwPageSize;
45                 break;
46
47         case _SC_PHYS_PAGES:
48                 status.dwLength = sizeof(status);
49                 GlobalMemoryStatusEx(&status);
50                 val = status.ullTotalPhys;
51                 break;
52         default:
53                 log_err("sysconf(%d) is not implemented\n", name);
54                 break;
55         }
56
57         return val;
58 }
59
60 char *dl_error = NULL;
61
62 int dlclose(void *handle)
63 {
64         return !FreeLibrary((HMODULE)handle);
65 }
66
67 void *dlopen(const char *file, int mode)
68 {
69         HMODULE hMod;
70
71         hMod = LoadLibrary(file);
72         if (hMod == INVALID_HANDLE_VALUE)
73                 dl_error = (char*)"LoadLibrary failed";
74         else
75                 dl_error = NULL;
76
77         return hMod;
78 }
79
80 void *dlsym(void *handle, const char *name)
81 {
82         FARPROC fnPtr;
83
84         fnPtr = GetProcAddress((HMODULE)handle, name);
85         if (fnPtr == NULL)
86                 dl_error = (char*)"GetProcAddress failed";
87         else
88                 dl_error = NULL;
89
90         return fnPtr;
91 }
92
93 char *dlerror(void)
94 {
95         return dl_error;
96 }
97
98 int gettimeofday(struct timeval *restrict tp, void *restrict tzp)
99 {
100         FILETIME fileTime;
101         unsigned long long unix_time, windows_time;
102         const unsigned long long MILLISECONDS_BETWEEN_1601_AND_1970 = 11644473600000;
103
104         /* Ignore the timezone parameter */
105         (void)tzp;
106
107         /*
108          * Windows time is stored as the number 100 ns intervals since January 1 1601.
109          * Conversion details from http://www.informit.com/articles/article.aspx?p=102236&seqNum=3
110          * Its precision is 100 ns but accuracy is only one clock tick, or normally around 15 ms.
111          */
112         GetSystemTimeAsFileTime(&fileTime);
113         windows_time = ((unsigned long long)fileTime.dwHighDateTime << 32) + fileTime.dwLowDateTime;
114         /* Divide by 10,000 to convert to ms and subtract the time between 1601 and 1970 */
115         unix_time = (((windows_time)/10000) - MILLISECONDS_BETWEEN_1601_AND_1970);
116         /* unix_time is now the number of milliseconds since 1970 (the Unix epoch) */
117         tp->tv_sec = unix_time / 1000;
118         tp->tv_usec = (unix_time % 1000) * 1000;
119         return 0;
120 }
121
122 void syslog(int priority, const char *message, ... /* argument */)
123 {
124         log_err("%s is not implemented\n", __func__);
125 }
126
127 int sigaction(int sig, const struct sigaction *act,
128                 struct sigaction *oact)
129 {
130         int rc = 0;
131         void (*prev_handler)(int);
132
133         prev_handler = signal(sig, act->sa_handler);
134         if (oact != NULL)
135                 oact->sa_handler = prev_handler;
136
137         if (prev_handler == SIG_ERR)
138                 rc = -1;
139
140         return rc;
141 }
142
143 int lstat(const char * path, struct stat * buf)
144 {
145         return stat(path, buf);
146 }
147
148 void *mmap(void *addr, size_t len, int prot, int flags,
149                 int fildes, off_t off)
150 {
151         DWORD vaProt = 0;
152         void* allocAddr = NULL;
153
154         if (prot & PROT_NONE)
155                 vaProt |= PAGE_NOACCESS;
156
157         if ((prot & PROT_READ) && !(prot & PROT_WRITE))
158                 vaProt |= PAGE_READONLY;
159
160         if (prot & PROT_WRITE)
161                 vaProt |= PAGE_READWRITE;
162
163         if ((flags & MAP_ANON) | (flags & MAP_ANONYMOUS))
164         {
165                 allocAddr = VirtualAlloc(addr, len, MEM_COMMIT, vaProt);
166         }
167
168         return allocAddr;
169 }
170
171 int munmap(void *addr, size_t len)
172 {
173         return !VirtualFree(addr, 0, MEM_RELEASE);
174 }
175
176 int fork(void)
177 {
178         log_err("%s is not implemented\n", __func__);
179         errno = ENOSYS;
180         return (-1);
181 }
182
183 pid_t setsid(void)
184 {
185         log_err("%s is not implemented\n", __func__);
186         errno = ENOSYS;
187         return (-1);
188 }
189
190 void openlog(const char *ident, int logopt, int facility)
191 {
192         log_err("%s is not implemented\n", __func__);
193 }
194
195 void closelog(void)
196 {
197         log_err("%s is not implemented\n", __func__);
198 }
199
200 int kill(pid_t pid, int sig)
201 {
202         errno = ESRCH;
203         return (-1);
204 }
205
206 /*
207  * This is assumed to be used only by the network code,
208  * and so doesn't try and handle any of the other cases
209  */
210 int fcntl(int fildes, int cmd, ...)
211 {
212         /*
213          * non-blocking mode doesn't work the same as in BSD sockets,
214          * so ignore it.
215          */
216 #if 0
217         va_list ap;
218         int val, opt, status;
219
220         if (cmd == F_GETFL)
221                 return 0;
222         else if (cmd != F_SETFL) {
223                 errno = EINVAL;
224                 return (-1);
225         }
226
227         va_start(ap, 1);
228
229         opt = va_arg(ap, int);
230         if (opt & O_NONBLOCK)
231                 val = 1;
232         else
233                 val = 0;
234
235         status = ioctlsocket((SOCKET)fildes, opt, &val);
236
237         if (status == SOCKET_ERROR) {
238                 errno = EINVAL;
239                 val = -1;
240         }
241
242         va_end(ap);
243
244         return val;
245 #endif
246 return 0;
247 }
248
249 /*
250  * Get the value of a local clock source.
251  * This implementation supports 2 clocks: CLOCK_MONOTONIC provides high-accuracy
252  * relative time, while CLOCK_REALTIME provides a low-accuracy wall time.
253  */
254 int clock_gettime(clockid_t clock_id, struct timespec *tp)
255 {
256         int rc = 0;
257
258         if (clock_id == CLOCK_MONOTONIC)
259         {
260                 static LARGE_INTEGER freq = {{0,0}};
261                 LARGE_INTEGER counts;
262
263                 QueryPerformanceCounter(&counts);
264                 if (freq.QuadPart == 0)
265                         QueryPerformanceFrequency(&freq);
266
267                 tp->tv_sec = counts.QuadPart / freq.QuadPart;
268                 /* Get the difference between the number of ns stored
269                  * in 'tv_sec' and that stored in 'counts' */
270                 unsigned long long t = tp->tv_sec * freq.QuadPart;
271                 t = counts.QuadPart - t;
272                 /* 't' now contains the number of cycles since the last second.
273                  * We want the number of nanoseconds, so multiply out by 1,000,000,000
274                  * and then divide by the frequency. */
275                 t *= 1000000000;
276                 tp->tv_nsec = t / freq.QuadPart;
277         }
278         else if (clock_id == CLOCK_REALTIME)
279         {
280                 /* clock_gettime(CLOCK_REALTIME,...) is just an alias for gettimeofday with a
281                  * higher-precision field. */
282                 struct timeval tv;
283                 gettimeofday(&tv, NULL);
284                 tp->tv_sec = tv.tv_sec;
285                 tp->tv_nsec = tv.tv_usec * 1000;
286         } else {
287                 errno = EINVAL;
288                 rc = -1;
289         }
290
291         return rc;
292 }
293
294 int mlock(const void * addr, size_t len)
295 {
296         return !VirtualLock((LPVOID)addr, len);
297 }
298
299 int munlock(const void * addr, size_t len)
300 {
301         return !VirtualUnlock((LPVOID)addr, len);
302 }
303
304 pid_t waitpid(pid_t pid, int *stat_loc, int options)
305 {
306         log_err("%s is not implemented\n", __func__);
307         errno = ENOSYS;
308         return -1;
309 }
310
311 int usleep(useconds_t useconds)
312 {
313         Sleep(useconds / 1000);
314         return 0;
315 }
316
317 char *basename(char *path)
318 {
319         static char name[MAX_PATH];
320         int i;
321
322         if (path == NULL || strlen(path) == 0)
323                 return (char*)".";
324
325         i = strlen(path) - 1;
326
327         while (name[i] != '\\' && name[i] != '/' && i >= 0)
328                 i--;
329
330         strcpy(name, path + i);
331
332         return name;
333 }
334
335 int posix_fallocate(int fd, off_t offset, off_t len)
336 {
337         const int BUFFER_SIZE = 64*1024*1024;
338         int rc = 0;
339         char *buf;
340         unsigned int write_len;
341         unsigned int bytes_written;
342         off_t bytes_remaining = len;
343
344         if (len == 0 || offset < 0)
345                 return EINVAL;
346
347         buf = malloc(BUFFER_SIZE);
348
349         if (buf == NULL)
350                 return ENOMEM;
351
352         memset(buf, 0, BUFFER_SIZE);
353
354         if (lseek(fd, offset, SEEK_SET) == -1)
355                 return errno;
356
357         while (bytes_remaining > 0) {
358                 if (bytes_remaining < BUFFER_SIZE)
359                         write_len = (unsigned int)bytes_remaining;
360                 else
361                         write_len = BUFFER_SIZE;
362
363                 bytes_written = _write(fd, buf, write_len);
364                 if (bytes_written == -1) {
365                         rc = errno;
366                         break;
367                 }
368
369                 bytes_remaining -= bytes_written;
370         }
371
372         free(buf);
373         return rc;
374 }
375
376 int ftruncate(int fildes, off_t length)
377 {
378         BOOL bSuccess;
379         int old_pos = tell(fildes);
380         lseek(fildes, length, SEEK_SET);
381         HANDLE hFile = (HANDLE)_get_osfhandle(fildes);
382         bSuccess = SetEndOfFile(hFile);
383         lseek(fildes, old_pos, SEEK_SET);
384         return !bSuccess;
385 }
386
387 int fsync(int fildes)
388 {
389         HANDLE hFile = (HANDLE)_get_osfhandle(fildes);
390         return !FlushFileBuffers(hFile);
391 }
392
393 int nFileMappings = 0;
394 HANDLE fileMappings[1024];
395
396 int shmget(key_t key, size_t size, int shmflg)
397 {
398         int mapid = -1;
399         uint32_t size_low = size & 0xFFFFFFFF;
400         uint32_t size_high = ((uint64_t)size) >> 32;
401         HANDLE hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, (PAGE_EXECUTE_READWRITE | SEC_RESERVE), size_high, size_low, NULL);
402         if (hMapping != NULL) {
403                 fileMappings[nFileMappings] = hMapping;
404                 mapid = nFileMappings;
405                 nFileMappings++;
406         } else {
407                 errno = ENOSYS;
408         }
409
410         return mapid;
411 }
412
413 void *shmat(int shmid, const void *shmaddr, int shmflg)
414 {
415         void* mapAddr;
416         MEMORY_BASIC_INFORMATION memInfo;
417         mapAddr = MapViewOfFile(fileMappings[shmid], FILE_MAP_ALL_ACCESS, 0, 0, 0);
418         VirtualQuery(mapAddr, &memInfo, sizeof(memInfo));
419         mapAddr = VirtualAlloc(mapAddr, memInfo.RegionSize, MEM_COMMIT, PAGE_READWRITE);
420         return mapAddr;
421 }
422
423 int shmdt(const void *shmaddr)
424 {
425         return !UnmapViewOfFile(shmaddr);
426 }
427
428 int shmctl(int shmid, int cmd, struct shmid_ds *buf)
429 {
430         if (cmd == IPC_RMID) {
431                 fileMappings[shmid] = INVALID_HANDLE_VALUE;
432                 return 0;
433         } else {
434                 log_err("%s is not implemented\n", __func__);
435         }
436         return (-1);
437 }
438
439 int setuid(uid_t uid)
440 {
441         log_err("%s is not implemented\n", __func__);
442         errno = ENOSYS;
443         return (-1);
444 }
445
446 int setgid(gid_t gid)
447 {
448         log_err("%s is not implemented\n", __func__);
449         errno = ENOSYS;
450         return (-1);
451 }
452
453 int nice(int incr)
454 {
455         if (incr != 0) {
456                 errno = EINVAL;
457                 return -1;
458         }
459
460         return 0;
461 }
462
463 int getrusage(int who, struct rusage *r_usage)
464 {
465         const unsigned long long SECONDS_BETWEEN_1601_AND_1970 = 11644473600;
466         FILETIME cTime, eTime, kTime, uTime;
467         time_t time;
468
469         memset(r_usage, 0, sizeof(*r_usage));
470
471         HANDLE hProcess = GetCurrentProcess();
472         GetProcessTimes(hProcess, &cTime, &eTime, &kTime, &uTime);
473         time = ((unsigned long long)uTime.dwHighDateTime << 32) + uTime.dwLowDateTime;
474         /* Divide by 10,000,000 to get the number of seconds and move the epoch from
475          * 1601 to 1970 */
476         time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
477         r_usage->ru_utime.tv_sec = time;
478         /* getrusage() doesn't care about anything other than seconds, so set tv_usec to 0 */
479         r_usage->ru_utime.tv_usec = 0;
480         time = ((unsigned long long)kTime.dwHighDateTime << 32) + kTime.dwLowDateTime;
481         /* Divide by 10,000,000 to get the number of seconds and move the epoch from
482          * 1601 to 1970 */
483         time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
484         r_usage->ru_stime.tv_sec = time;
485         r_usage->ru_stime.tv_usec = 0;
486         return 0;
487 }
488
489 int posix_madvise(void *addr, size_t len, int advice)
490 {
491         log_err("%s is not implemented\n", __func__);
492         return ENOSYS;
493 }
494
495 /* Windows doesn't support advice for memory pages. Just ignore it. */
496 int msync(void *addr, size_t len, int flags)
497 {
498         log_err("%s is not implemented\n", __func__);
499         errno = ENOSYS;
500         return -1;
501 }
502
503 int fdatasync(int fildes)
504 {
505         return fsync(fildes);
506 }
507
508 ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
509                 off_t offset)
510 {
511         long pos = tell(fildes);
512         ssize_t len = write(fildes, buf, nbyte);
513         lseek(fildes, pos, SEEK_SET);
514         return len;
515 }
516
517 ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset)
518 {
519         long pos = tell(fildes);
520         ssize_t len = read(fildes, buf, nbyte);
521         lseek(fildes, pos, SEEK_SET);
522         return len;
523 }
524
525 ssize_t readv(int fildes, const struct iovec *iov, int iovcnt)
526 {
527         log_err("%s is not implemented\n", __func__);
528         errno = ENOSYS;
529         return (-1);
530 }
531
532 ssize_t writev(int fildes, const struct iovec *iov, int iovcnt)
533 {
534         log_err("%s is not implemented\n", __func__);
535         errno = ENOSYS;
536         return (-1);
537 }
538
539 long long strtoll(const char *restrict str, char **restrict endptr,
540                 int base)
541 {
542         return _strtoi64(str, endptr, base);
543 }
544
545 char *strsep(char **stringp, const char *delim)
546 {
547         char *orig = *stringp;
548         BOOL gotMatch = FALSE;
549         int i = 0;
550         int j = 0;
551
552         if (*stringp == NULL)
553                 return NULL;
554
555         while ((*stringp)[i] != '\0') {
556                 j = 0;
557                 while (delim[j] != '\0') {
558                         if ((*stringp)[i] == delim[j]) {
559                                 gotMatch = TRUE;
560                                 (*stringp)[i] = '\0';
561                                 *stringp = *stringp + i + 1;
562                                 break;
563                         }
564                         j++;
565                 }
566                 if (gotMatch)
567                         break;
568
569                 i++;
570         }
571
572         if (!gotMatch)
573                 *stringp = NULL;
574
575         return orig;
576 }
577
578 int poll(struct pollfd fds[], nfds_t nfds, int timeout)
579 {
580         struct timeval tv;
581         struct timeval *to = NULL;
582         fd_set readfds, writefds, exceptfds;
583         int i;
584         int rc;
585
586         if (timeout != -1)
587                 to = &tv;
588
589         to->tv_sec = timeout / 1000;
590         to->tv_usec = (timeout % 1000) * 1000;
591
592         FD_ZERO(&readfds);
593         FD_ZERO(&writefds);
594         FD_ZERO(&exceptfds);
595
596         for (i = 0; i < nfds; i++)
597         {
598                 if (fds[i].fd < 0) {
599                         fds[i].revents = 0;
600                         continue;
601                 }
602
603                 if (fds[i].events & POLLIN)
604                         FD_SET(fds[i].fd, &readfds);
605
606                 if (fds[i].events & POLLOUT)
607                         FD_SET(fds[i].fd, &writefds);
608
609                 FD_SET(fds[i].fd, &exceptfds);
610         }
611
612         rc = select(nfds, &readfds, &writefds, &exceptfds, to);
613
614         if (rc != SOCKET_ERROR) {
615                 for (i = 0; i < nfds; i++)
616                 {
617                         if (fds[i].fd < 0) {
618                                 continue;
619                         }
620
621                         if ((fds[i].events & POLLIN) && FD_ISSET(fds[i].fd, &readfds))
622                                 fds[i].revents |= POLLIN;
623
624                         if ((fds[i].events & POLLOUT) && FD_ISSET(fds[i].fd, &writefds))
625                                 fds[i].revents |= POLLOUT;
626
627                         if (FD_ISSET(fds[i].fd, &exceptfds))
628                                 fds[i].revents |= POLLHUP;
629                 }
630         }
631
632         return rc;
633 }
634
635 int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
636 {
637         struct timeval tv;
638         DWORD ms_remaining;
639         DWORD ms_total = (rqtp->tv_sec * 1000) + (rqtp->tv_nsec / 1000000.0);
640
641         if (ms_total == 0)
642                 ms_total = 1;
643
644         ms_remaining = ms_total;
645
646         /* Since Sleep() can sleep for less than the requested time, add a loop to
647            ensure we only return after the requested length of time has elapsed */
648         do {
649                 fio_gettime(&tv, NULL);
650                 Sleep(ms_remaining);
651                 ms_remaining = ms_total - mtime_since_now(&tv);
652         } while (ms_remaining > 0 && ms_remaining < ms_total);
653
654         /* this implementation will never sleep for less than the requested time */
655         if (rmtp != NULL) {
656                 rmtp->tv_sec = 0;
657                 rmtp->tv_nsec = 0;
658         }
659
660         return 0;
661 }
662
663 DIR *opendir(const char *dirname)
664 {
665         log_err("%s is not implemented\n", __func__);
666         errno = ENOSYS;
667         return NULL;
668 }
669
670 int closedir(DIR *dirp)
671 {
672         log_err("%s is not implemented\n", __func__);
673         errno = ENOSYS;
674         return -1;
675 }
676
677 struct dirent *readdir(DIR *dirp)
678 {
679         log_err("%s is not implemented\n", __func__);
680         errno = ENOSYS;
681         return NULL;
682 }
683
684 uid_t geteuid(void)
685 {
686         log_err("%s is not implemented\n", __func__);
687         errno = ENOSYS;
688         return -1;
689 }
690
691 int inet_aton(char *addr)
692 {
693         log_err("%s is not implemented\n", __func__);
694         errno = ENOSYS;
695         return 0;
696 }
697
698 const char* inet_ntop(int af, const void *restrict src,
699                 char *restrict dst, socklen_t size)
700 {
701         INT status = SOCKET_ERROR;
702         WSADATA wsd;
703         char *ret = NULL;
704
705         if (af != AF_INET && af != AF_INET6) {
706                 errno = EAFNOSUPPORT;
707                 return NULL;
708         }
709
710         WSAStartup(MAKEWORD(2,2), &wsd);
711
712         if (af == AF_INET) {
713                 struct sockaddr_in si;
714                 DWORD len = size;
715                 memset(&si, 0, sizeof(si));
716                 si.sin_family = af;
717                 memcpy(&si.sin_addr, src, sizeof(si.sin_addr));
718                 status = WSAAddressToString((struct sockaddr*)&si, sizeof(si), NULL, dst, &len);
719         } else if (af == AF_INET6) {
720                 struct sockaddr_in6 si6;
721                 DWORD len = size;
722                 memset(&si6, 0, sizeof(si6));
723                 si6.sin6_family = af;
724                 memcpy(&si6.sin6_addr, src, sizeof(si6.sin6_addr));
725                 status = WSAAddressToString((struct sockaddr*)&si6, sizeof(si6), NULL, dst, &len);
726         }
727
728         if (status != SOCKET_ERROR)
729                 ret = dst;
730         else
731                 errno = ENOSPC;
732
733         WSACleanup();
734         return ret;
735 }
736
737 int inet_pton(int af, const char *restrict src, void *restrict dst)
738 {
739         INT status = SOCKET_ERROR;
740         WSADATA wsd;
741         int ret = 1;
742
743         if (af != AF_INET && af != AF_INET6) {
744                 errno = EAFNOSUPPORT;
745                 return -1;
746         }
747
748         WSAStartup(MAKEWORD(2,2), &wsd);
749
750         if (af == AF_INET) {
751                 struct sockaddr_in si;
752                 INT len = sizeof(si);
753                 memset(&si, 0, sizeof(si));
754                 si.sin_family = af;
755                 status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si, &len);
756                 if (status != SOCKET_ERROR)
757                         memcpy(dst, &si.sin_addr, sizeof(si.sin_addr));
758         } else if (af == AF_INET6) {
759                 struct sockaddr_in6 si6;
760                 INT len = sizeof(si6);
761                 memset(&si6, 0, sizeof(si6));
762                 si6.sin6_family = af;
763                 status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si6, &len);
764                 if (status != SOCKET_ERROR)
765                         memcpy(dst, &si6.sin6_addr, sizeof(si6.sin6_addr));
766         }
767
768         if (status == SOCKET_ERROR) {
769                 errno = ENOSPC;
770                 ret = 0;
771         }
772
773         WSACleanup();
774
775         return ret;
776 }