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