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.
7 #include <netinet/in.h>
16 #include <semaphore.h>
20 #include <sys/resource.h>
25 #include "../os-windows.h"
26 #include "../../lib/hweight.h"
28 extern unsigned long mtime_since_now(struct timespec *);
29 extern void fio_gettime(struct timespec *, void *);
31 int win_to_posix_error(DWORD winerr)
36 case ERROR_FILE_NOT_FOUND:
38 case ERROR_PATH_NOT_FOUND:
40 case ERROR_ACCESS_DENIED:
42 case ERROR_INVALID_HANDLE:
44 case ERROR_NOT_ENOUGH_MEMORY:
46 case ERROR_INVALID_DATA:
48 case ERROR_OUTOFMEMORY:
50 case ERROR_INVALID_DRIVE:
52 case ERROR_NOT_SAME_DEVICE:
54 case ERROR_WRITE_PROTECT:
60 case ERROR_SHARING_VIOLATION:
62 case ERROR_LOCK_VIOLATION:
64 case ERROR_SHARING_BUFFER_EXCEEDED:
66 case ERROR_HANDLE_DISK_FULL:
68 case ERROR_NOT_SUPPORTED:
70 case ERROR_FILE_EXISTS:
72 case ERROR_CANNOT_MAKE:
74 case ERROR_INVALID_PARAMETER:
76 case ERROR_NO_PROC_SLOTS:
78 case ERROR_BROKEN_PIPE:
80 case ERROR_OPEN_FAILED:
82 case ERROR_NO_MORE_SEARCH_HANDLES:
84 case ERROR_CALL_NOT_IMPLEMENTED:
86 case ERROR_INVALID_NAME:
88 case ERROR_WAIT_NO_CHILDREN:
90 case ERROR_CHILD_NOT_COMPLETE:
92 case ERROR_DIR_NOT_EMPTY:
94 case ERROR_SIGNAL_REFUSED:
96 case ERROR_BAD_PATHNAME:
98 case ERROR_SIGNAL_PENDING:
100 case ERROR_MAX_THRDS_REACHED:
104 case ERROR_ALREADY_EXISTS:
106 case ERROR_NO_SIGNAL_SENT:
108 case ERROR_FILENAME_EXCED_RANGE:
110 case ERROR_META_EXPANSION_TOO_LONG:
112 case ERROR_INVALID_SIGNAL_NUMBER:
114 case ERROR_THREAD_1_INACTIVE:
118 case ERROR_PIPE_BUSY:
122 case ERROR_MORE_DATA:
124 case ERROR_DIRECTORY:
126 case ERROR_PIPE_CONNECTED:
130 case ERROR_PROCESS_ABORTED:
132 case ERROR_BAD_DEVICE:
134 case ERROR_BAD_USERNAME:
136 case ERROR_OPEN_FILES:
138 case ERROR_ACTIVE_CONNECTIONS:
140 case ERROR_DEVICE_IN_USE:
142 case ERROR_INVALID_AT_INTERRUPT_TIME:
144 case ERROR_IO_DEVICE:
146 case ERROR_NOT_OWNER:
148 case ERROR_END_OF_MEDIA:
150 case ERROR_EOM_OVERFLOW:
152 case ERROR_BEGINNING_OF_MEDIA:
154 case ERROR_SETMARK_DETECTED:
156 case ERROR_NO_DATA_DETECTED:
158 case ERROR_POSSIBLE_DEADLOCK:
162 case ERROR_NEGATIVE_SEEK:
164 case ERROR_DISK_FULL:
168 case ERROR_FILE_INVALID:
171 log_err("fio: windows error %lu not handled\n", winerr);
178 int GetNumLogicalProcessors(void)
180 SYSTEM_LOGICAL_PROCESSOR_INFORMATION *processor_info = NULL;
182 DWORD num_processors = 0;
186 while (!GetLogicalProcessorInformation(processor_info, &len)) {
187 error = GetLastError();
188 if (error == ERROR_INSUFFICIENT_BUFFER)
189 processor_info = malloc(len);
191 log_err("Error: GetLogicalProcessorInformation failed: %lu\n",
196 if (processor_info == NULL) {
197 log_err("Error: failed to allocate memory for GetLogicalProcessorInformation");
202 for (i = 0; i < len / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); i++) {
203 if (processor_info[i].Relationship == RelationProcessorCore)
204 num_processors += hweight64(processor_info[i].ProcessorMask);
207 free(processor_info);
208 return num_processors;
211 long sysconf(int name)
216 MEMORYSTATUSEX status;
219 case _SC_NPROCESSORS_CONF:
221 * Using GetMaximumProcessorCount introduces a problem in
222 * gettime.c because Windows does not have
223 * fio_get_thread_affinity. Log sample (see #1479):
225 * CPU mask contains processor beyond last active processor index (2)
226 * clock setaffinity failed: No error
228 val = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
230 log_err("sysconf(_SC_NPROCESSORS_CONF) failed\n");
235 GetSystemInfo(&sysInfo);
236 val = sysInfo.dwPageSize;
240 status.dwLength = sizeof(status);
241 val2 = sysconf(_SC_PAGESIZE);
242 if (GlobalMemoryStatusEx(&status) && val2 != -1)
243 val = status.ullTotalPhys / val2;
245 log_err("sysconf(_SC_PHYS_PAGES) failed\n");
248 log_err("sysconf(%d) is not implemented\n", name);
255 char *dl_error = NULL;
257 int dlclose(void *handle)
259 return !FreeLibrary((HMODULE)handle);
262 void *dlopen(const char *file, int mode)
266 hMod = LoadLibrary(file);
267 if (hMod == INVALID_HANDLE_VALUE)
268 dl_error = (char*)"LoadLibrary failed";
275 void *dlsym(void *handle, const char *name)
279 fnPtr = GetProcAddress((HMODULE)handle, name);
281 dl_error = (char*)"GetProcAddress failed";
293 /* Copied from http://blogs.msdn.com/b/joshpoley/archive/2007/12/19/date-time-formats-and-conversions.aspx */
294 void Time_tToSystemTime(time_t dosTime, SYSTEMTIME *systemTime)
298 SYSTEMTIME tempSystemTime;
300 jan1970 = Int32x32To64(dosTime, 10000000) + 116444736000000000;
301 utcFT.dwLowDateTime = (DWORD)jan1970;
302 utcFT.dwHighDateTime = jan1970 >> 32;
304 FileTimeToSystemTime((FILETIME*)&utcFT, &tempSystemTime);
305 SystemTimeToTzSpecificLocalTime(NULL, &tempSystemTime, systemTime);
308 char *ctime_r(const time_t *t, char *buf)
311 const char * const dayOfWeek[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
312 const char * const monthOfYear[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
314 Time_tToSystemTime(*t, &systime);
317 * We don't know how long `buf` is, but assume it's rounded up from
318 * the minimum of 25 to 32
320 snprintf(buf, 32, "%s %s %d %02d:%02d:%02d %04d\n",
321 dayOfWeek[systime.wDayOfWeek % 7],
322 monthOfYear[(systime.wMonth - 1) % 12],
323 systime.wDay, systime.wHour, systime.wMinute,
324 systime.wSecond, systime.wYear);
328 int gettimeofday(struct timeval *restrict tp, void *restrict tzp)
331 uint64_t unix_time, windows_time;
332 const uint64_t MILLISECONDS_BETWEEN_1601_AND_1970 = 11644473600000;
334 /* Ignore the timezone parameter */
338 * Windows time is stored as the number 100 ns intervals since January 1 1601.
339 * Conversion details from http://www.informit.com/articles/article.aspx?p=102236&seqNum=3
340 * Its precision is 100 ns but accuracy is only one clock tick, or normally around 15 ms.
342 GetSystemTimeAsFileTime(&fileTime);
343 windows_time = ((uint64_t)fileTime.dwHighDateTime << 32) + fileTime.dwLowDateTime;
344 /* Divide by 10,000 to convert to ms and subtract the time between 1601 and 1970 */
345 unix_time = (((windows_time)/10000) - MILLISECONDS_BETWEEN_1601_AND_1970);
346 /* unix_time is now the number of milliseconds since 1970 (the Unix epoch) */
347 tp->tv_sec = unix_time / 1000;
348 tp->tv_usec = (unix_time % 1000) * 1000;
352 int sigaction(int sig, const struct sigaction *act, struct sigaction *oact)
355 void (*prev_handler)(int);
357 prev_handler = signal(sig, act->sa_handler);
359 oact->sa_handler = prev_handler;
361 if (prev_handler == SIG_ERR)
367 int lstat(const char *path, struct stat *buf)
369 return stat(path, buf);
372 void *mmap(void *addr, size_t len, int prot, int flags, int fildes, off_t off)
379 void* allocAddr = NULL;
381 if (prot & PROT_NONE)
382 vaProt |= PAGE_NOACCESS;
384 if ((prot & PROT_READ) && !(prot & PROT_WRITE)) {
385 vaProt |= PAGE_READONLY;
386 mapAccess = FILE_MAP_READ;
389 if (prot & PROT_WRITE) {
390 vaProt |= PAGE_READWRITE;
391 mapAccess |= FILE_MAP_WRITE;
394 lenlow = len & 0xFFFF;
396 /* If the low DWORD is zero and the high DWORD is non-zero, `CreateFileMapping`
397 will return ERROR_INVALID_PARAMETER. To avoid this, set both to zero. */
401 if (flags & MAP_ANON || flags & MAP_ANONYMOUS) {
402 allocAddr = VirtualAlloc(addr, len, MEM_COMMIT, vaProt);
403 if (allocAddr == NULL)
404 errno = win_to_posix_error(GetLastError());
406 hMap = CreateFileMapping((HANDLE)_get_osfhandle(fildes), NULL,
407 vaProt, lenhigh, lenlow, NULL);
410 allocAddr = MapViewOfFile(hMap, mapAccess, off >> 16,
412 if (hMap == NULL || allocAddr == NULL)
413 errno = win_to_posix_error(GetLastError());
420 int munmap(void *addr, size_t len)
424 /* We may have allocated the memory with either MapViewOfFile or
425 VirtualAlloc. Therefore, try calling UnmapViewOfFile first, and if that
426 fails, call VirtualFree. */
427 success = UnmapViewOfFile(addr);
430 success = VirtualFree(addr, 0, MEM_RELEASE);
435 int msync(void *addr, size_t len, int flags)
437 return !FlushViewOfFile(addr, len);
442 log_err("%s is not implemented\n", __func__);
449 log_err("%s is not implemented\n", __func__);
454 static HANDLE log_file = INVALID_HANDLE_VALUE;
456 void openlog(const char *ident, int logopt, int facility)
458 if (log_file != INVALID_HANDLE_VALUE)
461 log_file = CreateFileA("syslog.txt", GENERIC_WRITE,
462 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
463 OPEN_ALWAYS, 0, NULL);
468 CloseHandle(log_file);
469 log_file = INVALID_HANDLE_VALUE;
472 void syslog(int priority, const char *message, ... /* argument */)
479 if (log_file == INVALID_HANDLE_VALUE) {
480 log_file = CreateFileA("syslog.txt", GENERIC_WRITE,
481 FILE_SHARE_READ | FILE_SHARE_WRITE,
482 NULL, OPEN_ALWAYS, 0, NULL);
485 if (log_file == INVALID_HANDLE_VALUE) {
486 log_err("syslog: failed to open log file\n");
490 va_start(v, message);
491 len = _vscprintf(message, v);
492 output = malloc(len + sizeof(char));
493 vsprintf(output, message, v);
494 WriteFile(log_file, output, len, &bytes_written, NULL);
499 int kill(pid_t pid, int sig)
506 * This is assumed to be used only by the network code,
507 * and so doesn't try and handle any of the other cases
509 int fcntl(int fildes, int cmd, ...)
512 * non-blocking mode doesn't work the same as in BSD sockets,
517 int val, opt, status;
521 else if (cmd != F_SETFL) {
528 opt = va_arg(ap, int);
529 if (opt & O_NONBLOCK)
534 status = ioctlsocket((SOCKET)fildes, opt, &val);
536 if (status == SOCKET_ERROR) {
548 #ifndef CLOCK_MONOTONIC_RAW
549 #define CLOCK_MONOTONIC_RAW 4
553 * Get the value of a local clock source.
554 * This implementation supports 3 clocks: CLOCK_MONOTONIC/CLOCK_MONOTONIC_RAW
555 * provide high-accuracy relative time, while CLOCK_REALTIME provides a
556 * low-accuracy wall time.
558 int clock_gettime(clockid_t clock_id, struct timespec *tp)
562 if (clock_id == CLOCK_MONOTONIC || clock_id == CLOCK_MONOTONIC_RAW) {
563 static LARGE_INTEGER freq = {{0,0}};
564 LARGE_INTEGER counts;
567 QueryPerformanceCounter(&counts);
568 if (freq.QuadPart == 0)
569 QueryPerformanceFrequency(&freq);
571 tp->tv_sec = counts.QuadPart / freq.QuadPart;
572 /* Get the difference between the number of ns stored
573 * in 'tv_sec' and that stored in 'counts' */
574 t = tp->tv_sec * freq.QuadPart;
575 t = counts.QuadPart - t;
576 /* 't' now contains the number of cycles since the last second.
577 * We want the number of nanoseconds, so multiply out by 1,000,000,000
578 * and then divide by the frequency. */
580 tp->tv_nsec = t / freq.QuadPart;
581 } else if (clock_id == CLOCK_REALTIME) {
582 /* clock_gettime(CLOCK_REALTIME,...) is just an alias for gettimeofday with a
583 * higher-precision field. */
585 gettimeofday(&tv, NULL);
586 tp->tv_sec = tv.tv_sec;
587 tp->tv_nsec = tv.tv_usec * 1000;
596 int mlock(const void * addr, size_t len)
600 HANDLE process = GetCurrentProcess();
602 success = GetProcessWorkingSetSize(process, &min, &max);
604 errno = win_to_posix_error(GetLastError());
610 success = SetProcessWorkingSetSize(process, min, max);
612 errno = win_to_posix_error(GetLastError());
616 success = VirtualLock((LPVOID)addr, len);
618 errno = win_to_posix_error(GetLastError());
625 int munlock(const void * addr, size_t len)
627 BOOL success = VirtualUnlock((LPVOID)addr, len);
630 errno = win_to_posix_error(GetLastError());
637 pid_t waitpid(pid_t pid, int *stat_loc, int options)
639 log_err("%s is not implemented\n", __func__);
644 int usleep(useconds_t useconds)
646 Sleep(useconds / 1000);
650 char *basename(char *path)
652 static char name[MAX_PATH];
655 if (path == NULL || strlen(path) == 0)
658 i = strlen(path) - 1;
660 while (path[i] != '\\' && path[i] != '/' && i >= 0)
663 name[MAX_PATH - 1] = '\0';
664 strncpy(name, path + i + 1, MAX_PATH - 1);
669 int fsync(int fildes)
671 HANDLE hFile = (HANDLE)_get_osfhandle(fildes);
672 if (!FlushFileBuffers(hFile)) {
673 errno = win_to_posix_error(GetLastError());
680 int nFileMappings = 0;
681 HANDLE fileMappings[1024];
683 int shmget(key_t key, size_t size, int shmflg)
686 uint32_t size_low = size & 0xFFFFFFFF;
687 uint32_t size_high = ((uint64_t)size) >> 32;
690 hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL,
691 PAGE_EXECUTE_READWRITE | SEC_RESERVE,
692 size_high, size_low, NULL);
693 if (hMapping != NULL) {
694 fileMappings[nFileMappings] = hMapping;
695 mapid = nFileMappings;
703 void *shmat(int shmid, const void *shmaddr, int shmflg)
706 MEMORY_BASIC_INFORMATION memInfo;
708 mapAddr = MapViewOfFile(fileMappings[shmid], FILE_MAP_ALL_ACCESS, 0, 0, 0);
709 if (mapAddr == NULL) {
710 errno = win_to_posix_error(GetLastError());
714 if (VirtualQuery(mapAddr, &memInfo, sizeof(memInfo)) == 0) {
715 errno = win_to_posix_error(GetLastError());
719 mapAddr = VirtualAlloc(mapAddr, memInfo.RegionSize, MEM_COMMIT, PAGE_READWRITE);
720 if (mapAddr == NULL) {
721 errno = win_to_posix_error(GetLastError());
728 int shmdt(const void *shmaddr)
730 if (!UnmapViewOfFile(shmaddr)) {
731 errno = win_to_posix_error(GetLastError());
738 int shmctl(int shmid, int cmd, struct shmid_ds *buf)
740 if (cmd == IPC_RMID) {
741 fileMappings[shmid] = INVALID_HANDLE_VALUE;
745 log_err("%s is not implemented\n", __func__);
750 int setuid(uid_t uid)
752 log_err("%s is not implemented\n", __func__);
757 int setgid(gid_t gid)
759 log_err("%s is not implemented\n", __func__);
766 DWORD prioclass = NORMAL_PRIORITY_CLASS;
769 prioclass = HIGH_PRIORITY_CLASS;
771 prioclass = ABOVE_NORMAL_PRIORITY_CLASS;
773 prioclass = IDLE_PRIORITY_CLASS;
775 prioclass = BELOW_NORMAL_PRIORITY_CLASS;
777 if (!SetPriorityClass(GetCurrentProcess(), prioclass))
778 log_err("fio: SetPriorityClass failed\n");
783 int getrusage(int who, struct rusage *r_usage)
785 const uint64_t SECONDS_BETWEEN_1601_AND_1970 = 11644473600;
786 FILETIME cTime, eTime, kTime, uTime;
790 memset(r_usage, 0, sizeof(*r_usage));
792 if (who == RUSAGE_SELF) {
793 h = GetCurrentProcess();
794 GetProcessTimes(h, &cTime, &eTime, &kTime, &uTime);
795 } else if (who == RUSAGE_THREAD) {
796 h = GetCurrentThread();
797 GetThreadTimes(h, &cTime, &eTime, &kTime, &uTime);
799 log_err("fio: getrusage %d is not implemented\n", who);
803 time = ((uint64_t)uTime.dwHighDateTime << 32) + uTime.dwLowDateTime;
804 /* Divide by 10,000,000 to get the number of seconds and move the epoch from
806 time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
807 r_usage->ru_utime.tv_sec = time;
808 /* getrusage() doesn't care about anything other than seconds, so set tv_usec to 0 */
809 r_usage->ru_utime.tv_usec = 0;
810 time = ((uint64_t)kTime.dwHighDateTime << 32) + kTime.dwLowDateTime;
811 /* Divide by 10,000,000 to get the number of seconds and move the epoch from
813 time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
814 r_usage->ru_stime.tv_sec = time;
815 r_usage->ru_stime.tv_usec = 0;
819 int posix_madvise(void *addr, size_t len, int advice)
824 int fdatasync(int fildes)
826 return fsync(fildes);
829 ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
832 int64_t pos = _telli64(fildes);
833 ssize_t len = _write(fildes, buf, nbyte);
835 _lseeki64(fildes, pos, SEEK_SET);
839 ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset)
841 int64_t pos = _telli64(fildes);
842 ssize_t len = read(fildes, buf, nbyte);
844 _lseeki64(fildes, pos, SEEK_SET);
848 ssize_t readv(int fildes, const struct iovec *iov, int iovcnt)
850 log_err("%s is not implemented\n", __func__);
855 ssize_t writev(int fildes, const struct iovec *iov, int iovcnt)
858 DWORD bytes_written = 0;
860 for (i = 0; i < iovcnt; i++) {
863 len = send((SOCKET)fildes, iov[i].iov_base, iov[i].iov_len, 0);
864 if (len == SOCKET_ERROR) {
865 DWORD err = GetLastError();
866 errno = win_to_posix_error(err);
870 bytes_written += len;
873 return bytes_written;
877 long long strtoll(const char *restrict str, char **restrict endptr, int base)
879 return _strtoi64(str, endptr, base);
883 int poll(struct pollfd fds[], nfds_t nfds, int timeout)
886 struct timeval *to = NULL;
887 fd_set readfds, writefds, exceptfds;
893 to->tv_sec = timeout / 1000;
894 to->tv_usec = (timeout % 1000) * 1000;
901 for (i = 0; i < nfds; i++) {
902 if (fds[i].fd == INVALID_SOCKET) {
907 if (fds[i].events & POLLIN)
908 FD_SET(fds[i].fd, &readfds);
910 if (fds[i].events & POLLOUT)
911 FD_SET(fds[i].fd, &writefds);
913 FD_SET(fds[i].fd, &exceptfds);
915 rc = select(nfds, &readfds, &writefds, &exceptfds, to);
917 if (rc != SOCKET_ERROR) {
918 for (i = 0; i < nfds; i++) {
919 if (fds[i].fd == INVALID_SOCKET)
922 if ((fds[i].events & POLLIN) && FD_ISSET(fds[i].fd, &readfds))
923 fds[i].revents |= POLLIN;
925 if ((fds[i].events & POLLOUT) && FD_ISSET(fds[i].fd, &writefds))
926 fds[i].revents |= POLLOUT;
928 if (FD_ISSET(fds[i].fd, &exceptfds))
929 fds[i].revents |= POLLHUP;
935 int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
939 DWORD ms_total = (rqtp->tv_sec * 1000) + (rqtp->tv_nsec / 1000000.0);
944 ms_remaining = ms_total;
946 /* Since Sleep() can sleep for less than the requested time, add a loop to
947 ensure we only return after the requested length of time has elapsed */
949 fio_gettime(&tv, NULL);
951 ms_remaining = ms_total - mtime_since_now(&tv);
952 } while (ms_remaining > 0 && ms_remaining < ms_total);
954 /* this implementation will never sleep for less than the requested time */
963 DIR *opendir(const char *dirname)
965 struct dirent_ctx *dc = NULL;
968 /* See if we can open it. If not, we'll return an error here */
969 file = CreateFileA(dirname, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
970 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
971 if (file != INVALID_HANDLE_VALUE) {
973 dc = malloc(sizeof(struct dirent_ctx));
974 snprintf(dc->dirname, sizeof(dc->dirname), "%s", dirname);
975 dc->find_handle = INVALID_HANDLE_VALUE;
977 DWORD error = GetLastError();
978 if (error == ERROR_FILE_NOT_FOUND)
981 else if (error == ERROR_PATH_NOT_FOUND)
983 else if (error == ERROR_TOO_MANY_OPEN_FILES)
985 else if (error == ERROR_ACCESS_DENIED)
994 int closedir(DIR *dirp)
996 if (dirp != NULL && dirp->find_handle != INVALID_HANDLE_VALUE)
997 FindClose(dirp->find_handle);
1003 struct dirent *readdir(DIR *dirp)
1005 static struct dirent de;
1006 WIN32_FIND_DATA find_data;
1011 if (dirp->find_handle == INVALID_HANDLE_VALUE) {
1012 char search_pattern[MAX_PATH];
1014 snprintf(search_pattern, sizeof(search_pattern), "%s\\*",
1016 dirp->find_handle = FindFirstFileA(search_pattern, &find_data);
1017 if (dirp->find_handle == INVALID_HANDLE_VALUE)
1020 if (!FindNextFile(dirp->find_handle, &find_data))
1024 snprintf(de.d_name, sizeof(de.d_name), find_data.cFileName);
1032 log_err("%s is not implemented\n", __func__);
1037 in_addr_t inet_network(const char *cp)
1040 in_addr_t nbo = inet_addr(cp);
1041 hbo = ((nbo & 0xFF) << 24) + ((nbo & 0xFF00) << 8) + ((nbo & 0xFF0000) >> 8) + ((nbo & 0xFF000000) >> 24);
1045 static HANDLE create_named_pipe(char *pipe_name, int wait_connect_time)
1049 hpipe = CreateNamedPipe (
1052 PIPE_WAIT | PIPE_TYPE_BYTE,
1053 1, 0, 0, wait_connect_time, NULL);
1055 if (hpipe == INVALID_HANDLE_VALUE) {
1056 log_err("ConnectNamedPipe failed (%lu).\n", GetLastError());
1057 return INVALID_HANDLE_VALUE;
1060 if (!ConnectNamedPipe(hpipe, NULL)) {
1061 log_err("ConnectNamedPipe failed (%lu).\n", GetLastError());
1063 return INVALID_HANDLE_VALUE;
1069 static BOOL windows_create_process(PROCESS_INFORMATION *pi, const char *args, HANDLE *hjob)
1071 LPSTR this_cmd_line = GetCommandLine();
1072 LPSTR new_process_cmd_line = malloc((strlen(this_cmd_line)+strlen(args)) * sizeof(char *));
1073 STARTUPINFO si = {0};
1076 strcpy(new_process_cmd_line, this_cmd_line);
1077 strcat(new_process_cmd_line, args);
1080 memset(pi, 0, sizeof(*pi));
1082 if ((hjob != NULL) && (*hjob != INVALID_HANDLE_VALUE))
1083 flags = CREATE_SUSPENDED | CREATE_BREAKAWAY_FROM_JOB;
1085 flags |= CREATE_NEW_CONSOLE;
1087 if( !CreateProcess( NULL,
1088 new_process_cmd_line,
1089 NULL, /* Process handle not inherited */
1090 NULL, /* Thread handle not inherited */
1091 TRUE, /* no handle inheritance */
1093 NULL, /* Use parent's environment block */
1094 NULL, /* Use parent's starting directory */
1099 log_err("CreateProcess failed (%lu).\n", GetLastError() );
1100 free(new_process_cmd_line);
1103 if ((hjob != NULL) && (*hjob != INVALID_HANDLE_VALUE)) {
1104 BOOL ret = AssignProcessToJobObject(*hjob, pi->hProcess);
1106 log_err("AssignProcessToJobObject failed (%lu).\n", GetLastError() );
1110 ResumeThread(pi->hThread);
1113 free(new_process_cmd_line);
1117 HANDLE windows_create_job(void)
1119 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 };
1121 HANDLE hjob = CreateJobObject(NULL, NULL);
1123 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
1124 success = SetInformationJobObject(hjob, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli));
1125 if ( success == 0 ) {
1126 log_err( "SetInformationJobObject failed: error %lu\n", GetLastError() );
1127 return INVALID_HANDLE_VALUE;
1132 /* wait for a child process to either exit or connect to a child */
1133 static bool monitor_process_till_connect(PROCESS_INFORMATION *pi, HANDLE *hpipe)
1135 bool connected = FALSE;
1136 bool process_alive = TRUE;
1137 char buffer[32] = {0};
1142 GetExitCodeProcess(pi->hProcess, &exit_code);
1143 if (exit_code != STILL_ACTIVE) {
1144 dprint(FD_PROCESS, "process %u exited %d\n", GetProcessId(pi->hProcess), exit_code);
1148 memset(buffer, 0, sizeof(buffer));
1149 ReadFile(*hpipe, &buffer, sizeof(buffer) - 1, &bytes_read, NULL);
1150 if (bytes_read && strstr(buffer, "connected")) {
1151 dprint(FD_PROCESS, "process %u connected to client\n", GetProcessId(pi->hProcess));
1155 } while (process_alive && !connected);
1159 /*create a process with --server-internal to emulate fork() */
1160 HANDLE windows_handle_connection(HANDLE hjob, int sk)
1162 char pipe_name[64] = "\\\\.\\pipe\\fiointernal-";
1163 char args[128] = " --server-internal=";
1164 PROCESS_INFORMATION pi;
1165 HANDLE hpipe = INVALID_HANDLE_VALUE;
1166 WSAPROTOCOL_INFO protocol_info;
1169 sprintf(pipe_name+strlen(pipe_name), "%d", GetCurrentProcessId());
1170 sprintf(args+strlen(args), "%s", pipe_name);
1172 if (windows_create_process(&pi, args, &hjob) != 0)
1173 return INVALID_HANDLE_VALUE;
1177 /* duplicate socket and write the protocol_info to pipe so child can
1178 * duplicate the communication socket */
1179 if (WSADuplicateSocket(sk, GetProcessId(pi.hProcess), &protocol_info)) {
1180 log_err("WSADuplicateSocket failed (%lu).\n", GetLastError());
1181 ret = INVALID_HANDLE_VALUE;
1185 /* make a pipe with a unique name based upon processid */
1186 hpipe = create_named_pipe(pipe_name, 1000);
1187 if (hpipe == INVALID_HANDLE_VALUE) {
1188 ret = INVALID_HANDLE_VALUE;
1192 if (!WriteFile(hpipe, &protocol_info, sizeof(protocol_info), NULL, NULL)) {
1193 log_err("WriteFile failed (%lu).\n", GetLastError());
1194 ret = INVALID_HANDLE_VALUE;
1198 dprint(FD_PROCESS, "process %d created child process %u\n", GetCurrentProcessId(), GetProcessId(pi.hProcess));
1200 /* monitor the process until it either exits or connects. This level
1201 * doesnt care which of those occurs because the result is that it
1202 * needs to loop around and create another child process to monitor */
1203 if (!monitor_process_till_connect(&pi, &hpipe))
1204 ret = INVALID_HANDLE_VALUE;
1207 /* close the handles and pipes because this thread is done monitoring them */
1208 if (ret == INVALID_HANDLE_VALUE)
1209 CloseHandle(pi.hProcess);
1210 CloseHandle(pi.hThread);
1211 DisconnectNamedPipe(hpipe);