source: trunk/src/kmk/kmkbuiltin/mscfakes.c@ 2757

Last change on this file since 2757 was 2756, checked in by bird, 10 years ago

2nd attempt at the ENOSPC problem on windows.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 18.4 KB
Line 
1/* $Id: mscfakes.c 2756 2015-01-28 12:39:20Z bird $ */
2/** @file
3 * Fake Unix stuff for MSC.
4 */
5
6/*
7 * Copyright (c) 2005-2015 knut st. osmundsen <bird-kBuild-spamx@anduin.net>
8 *
9 * This file is part of kBuild.
10 *
11 * kBuild is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * kBuild is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with kBuild. If not, see <http://www.gnu.org/licenses/>
23 *
24 */
25
26/*******************************************************************************
27* Header Files *
28*******************************************************************************/
29#include "config.h"
30#include <assert.h>
31#include <stdarg.h>
32#include <stdio.h>
33#include <stdlib.h>
34#include <string.h>
35#include <errno.h>
36#include <io.h>
37#include <fcntl.h>
38#include <sys/stat.h>
39#include "err.h"
40#include "mscfakes.h"
41
42#define timeval windows_timeval
43#include <Windows.h>
44#undef timeval
45
46/*******************************************************************************
47* Internal Functions *
48*******************************************************************************/
49static BOOL isPipeFd(int fd);
50
51
52/**
53 * Makes corrections to a directory path that ends with a trailing slash.
54 *
55 * @returns temporary buffer to free.
56 * @param ppszPath The path pointer. This is updated when necessary.
57 * @param pfMustBeDir This is set if it must be a directory, otherwise it's cleared.
58 */
59static char *
60msc_fix_path(const char **ppszPath, int *pfMustBeDir)
61{
62 const char *pszPath = *ppszPath;
63 const char *psz;
64 char *pszNew;
65 *pfMustBeDir = 0;
66
67 /*
68 * Skip any compusory trailing slashes
69 */
70 if (pszPath[0] == '/' || pszPath[0] == '\\')
71 {
72 if ( (pszPath[1] == '/' || pszPath[1] == '\\')
73 && pszPath[2] != '/'
74 && pszPath[2] != '\\')
75 /* unc */
76 pszPath += 2;
77 else
78 /* root slash(es) */
79 pszPath++;
80 }
81 else if ( isalpha(pszPath[0])
82 && pszPath[1] == ':')
83 {
84 if (pszPath[2] == '/' || pszPath[2] == '\\')
85 /* drive w/ slash */
86 pszPath += 3;
87 else
88 /* drive relative path. */
89 pszPath += 2;
90 }
91 /* else: relative path, no skipping necessary. */
92
93 /*
94 * Any trailing slashes to drop off?
95 */
96 psz = strchr(pszPath, '\0');
97 if (pszPath <= psz)
98 return NULL;
99 if ( psz[-1] != '/'
100 || psz[-1] != '\\')
101 return NULL;
102
103 /* figure how many, make a copy and strip them off. */
104 while ( psz > pszPath
105 && ( psz[-1] == '/'
106 || psz[-1] == '\\'))
107 psz--;
108 pszNew = strdup(pszPath);
109 pszNew[psz - pszPath] = '\0';
110
111 *pfMustBeDir = 1;
112 *ppszPath = pszNew; /* use this one */
113 return pszNew;
114}
115
116
117int
118birdSetErrno(unsigned dwErr)
119{
120 switch (dwErr)
121 {
122 default:
123 case ERROR_INVALID_FUNCTION: errno = EINVAL; break;
124 case ERROR_FILE_NOT_FOUND: errno = ENOENT; break;
125 case ERROR_PATH_NOT_FOUND: errno = ENOENT; break;
126 case ERROR_TOO_MANY_OPEN_FILES: errno = EMFILE; break;
127 case ERROR_ACCESS_DENIED: errno = EACCES; break;
128 case ERROR_INVALID_HANDLE: errno = EBADF; break;
129 case ERROR_ARENA_TRASHED: errno = ENOMEM; break;
130 case ERROR_NOT_ENOUGH_MEMORY: errno = ENOMEM; break;
131 case ERROR_INVALID_BLOCK: errno = ENOMEM; break;
132 case ERROR_BAD_ENVIRONMENT: errno = E2BIG; break;
133 case ERROR_BAD_FORMAT: errno = ENOEXEC; break;
134 case ERROR_INVALID_ACCESS: errno = EINVAL; break;
135 case ERROR_INVALID_DATA: errno = EINVAL; break;
136 case ERROR_INVALID_DRIVE: errno = ENOENT; break;
137 case ERROR_CURRENT_DIRECTORY: errno = EACCES; break;
138 case ERROR_NOT_SAME_DEVICE: errno = EXDEV; break;
139 case ERROR_NO_MORE_FILES: errno = ENOENT; break;
140 case ERROR_LOCK_VIOLATION: errno = EACCES; break;
141 case ERROR_BAD_NETPATH: errno = ENOENT; break;
142 case ERROR_NETWORK_ACCESS_DENIED: errno = EACCES; break;
143 case ERROR_BAD_NET_NAME: errno = ENOENT; break;
144 case ERROR_FILE_EXISTS: errno = EEXIST; break;
145 case ERROR_CANNOT_MAKE: errno = EACCES; break;
146 case ERROR_FAIL_I24: errno = EACCES; break;
147 case ERROR_INVALID_PARAMETER: errno = EINVAL; break;
148 case ERROR_NO_PROC_SLOTS: errno = EAGAIN; break;
149 case ERROR_DRIVE_LOCKED: errno = EACCES; break;
150 case ERROR_BROKEN_PIPE: errno = EPIPE; break;
151 case ERROR_DISK_FULL: errno = ENOSPC; break;
152 case ERROR_INVALID_TARGET_HANDLE: errno = EBADF; break;
153 case ERROR_WAIT_NO_CHILDREN: errno = ECHILD; break;
154 case ERROR_CHILD_NOT_COMPLETE: errno = ECHILD; break;
155 case ERROR_DIRECT_ACCESS_HANDLE: errno = EBADF; break;
156 case ERROR_NEGATIVE_SEEK: errno = EINVAL; break;
157 case ERROR_SEEK_ON_DEVICE: errno = EACCES; break;
158 case ERROR_DIR_NOT_EMPTY: errno = ENOTEMPTY; break;
159 case ERROR_NOT_LOCKED: errno = EACCES; break;
160 case ERROR_BAD_PATHNAME: errno = ENOENT; break;
161 case ERROR_MAX_THRDS_REACHED: errno = EAGAIN; break;
162 case ERROR_LOCK_FAILED: errno = EACCES; break;
163 case ERROR_ALREADY_EXISTS: errno = EEXIST; break;
164 case ERROR_FILENAME_EXCED_RANGE: errno = ENOENT; break;
165 case ERROR_NESTING_NOT_ALLOWED: errno = EAGAIN; break;
166#ifdef EMLINK
167 case ERROR_TOO_MANY_LINKS: errno = EMLINK; break;
168#endif
169 }
170
171 return -1;
172}
173
174char *dirname(char *path)
175{
176 /** @todo later */
177 return path;
178}
179
180
181int lchmod(const char *pszPath, mode_t mode)
182{
183 int rc = 0;
184 int fMustBeDir;
185 char *pszPathFree = msc_fix_path(&pszPath, &fMustBeDir);
186
187 /*
188 * Get the current attributes
189 */
190 DWORD fAttr = GetFileAttributes(pszPath);
191 if (fAttr == INVALID_FILE_ATTRIBUTES)
192 rc = birdSetErrno(GetLastError());
193 else if (fMustBeDir & !(fAttr & FILE_ATTRIBUTE_DIRECTORY))
194 {
195 errno = ENOTDIR;
196 rc = -1;
197 }
198 else
199 {
200 /*
201 * Modify the attributes and try set them.
202 */
203 if (mode & _S_IWRITE)
204 fAttr &= ~FILE_ATTRIBUTE_READONLY;
205 else
206 fAttr |= FILE_ATTRIBUTE_READONLY;
207 if (!SetFileAttributes(pszPath, fAttr))
208 rc = birdSetErrno(GetLastError());
209 }
210
211 if (pszPathFree)
212 {
213 int saved_errno = errno;
214 free(pszPathFree);
215 errno = saved_errno;
216 }
217 return rc;
218}
219
220
221int msc_chmod(const char *pszPath, mode_t mode)
222{
223 int rc = 0;
224 int fMustBeDir;
225 char *pszPathFree = msc_fix_path(&pszPath, &fMustBeDir);
226
227 /*
228 * Get the current attributes.
229 */
230 DWORD fAttr = GetFileAttributes(pszPath);
231 if (fAttr == INVALID_FILE_ATTRIBUTES)
232 rc = birdSetErrno(GetLastError());
233 else if (fMustBeDir & !(fAttr & FILE_ATTRIBUTE_DIRECTORY))
234 {
235 errno = ENOTDIR;
236 rc = -1;
237 }
238 else if (fAttr & FILE_ATTRIBUTE_REPARSE_POINT)
239 {
240 errno = ENOSYS; /** @todo resolve symbolic link / rewrite to NtSetInformationFile. */
241 rc = -1;
242 }
243 else
244 {
245 /*
246 * Modify the attributes and try set them.
247 */
248 if (mode & _S_IWRITE)
249 fAttr &= ~FILE_ATTRIBUTE_READONLY;
250 else
251 fAttr |= FILE_ATTRIBUTE_READONLY;
252 if (!SetFileAttributes(pszPath, fAttr))
253 rc = birdSetErrno(GetLastError());
254 }
255
256 if (pszPathFree)
257 {
258 int saved_errno = errno;
259 free(pszPathFree);
260 errno = saved_errno;
261 }
262 return rc;
263}
264
265
266typedef BOOL (WINAPI *PFNCREATEHARDLINKA)(LPCSTR, LPCSTR, LPSECURITY_ATTRIBUTES);
267int link(const char *pszDst, const char *pszLink)
268{
269 static PFNCREATEHARDLINKA s_pfnCreateHardLinkA = NULL;
270 static int s_fTried = FALSE;
271
272 /* The API was introduced in Windows 2000, so resolve it dynamically. */
273 if (!s_pfnCreateHardLinkA)
274 {
275 if (!s_fTried)
276 {
277 HMODULE hmod = LoadLibrary("KERNEL32.DLL");
278 if (hmod)
279 *(FARPROC *)&s_pfnCreateHardLinkA = GetProcAddress(hmod, "CreateHardLinkA");
280 s_fTried = TRUE;
281 }
282 if (!s_pfnCreateHardLinkA)
283 {
284 errno = ENOSYS;
285 return -1;
286 }
287 }
288
289 if (s_pfnCreateHardLinkA(pszLink, pszDst, NULL))
290 return 0;
291 return birdSetErrno(GetLastError());
292}
293
294
295int mkdir_msc(const char *path, mode_t mode)
296{
297 int rc = (mkdir)(path);
298 if (rc)
299 {
300 size_t len = strlen(path);
301 if (len > 0 && (path[len - 1] == '/' || path[len - 1] == '\\'))
302 {
303 char *str = strdup(path);
304 while (len > 0 && (str[len - 1] == '/' || str[len - 1] == '\\'))
305 str[--len] = '\0';
306 rc = (mkdir)(str);
307 free(str);
308 }
309 }
310 return rc;
311}
312
313int rmdir_msc(const char *path)
314{
315 int rc = (rmdir)(path);
316 if (rc)
317 {
318 size_t len = strlen(path);
319 if (len > 0 && (path[len - 1] == '/' || path[len - 1] == '\\'))
320 {
321 char *str = strdup(path);
322 while (len > 0 && (str[len - 1] == '/' || str[len - 1] == '\\'))
323 str[--len] = '\0';
324 rc = (rmdir)(str);
325 free(str);
326 }
327 }
328 return rc;
329}
330
331
332static int doname(char *pszX, char *pszEnd)
333{
334 static char s_szChars[] = "Xabcdefghijklmnopqrstuwvxyz1234567890";
335 int rc = 0;
336 do
337 {
338 char ch;
339
340 pszEnd++;
341 ch = *(strchr(s_szChars, *pszEnd) + 1);
342 if (ch)
343 {
344 *pszEnd = ch;
345 return 0;
346 }
347 *pszEnd = 'a';
348 } while (pszEnd != pszX);
349 return 1;
350}
351
352
353int mkstemp(char *temp)
354{
355 char *pszX = strchr(temp, 'X');
356 char *pszEnd = strchr(pszX, '\0');
357 int cTries = 1000;
358 while (--cTries > 0)
359 {
360 int fd;
361 if (doname(pszX, pszEnd))
362 return -1;
363 fd = open(temp, _O_EXCL | _O_CREAT | _O_BINARY | _O_RDWR, 0777);
364 if (fd >= 0)
365 return fd;
366 }
367 return -1;
368}
369
370
371/** Unix to DOS. */
372static char *fix_slashes(char *psz)
373{
374 char *pszRet = psz;
375 for (; *psz; psz++)
376 if (*psz == '/')
377 *psz = '\\';
378 return pszRet;
379}
380
381
382/** Calcs the SYMBOLIC_LINK_FLAG_DIRECTORY flag for CreatesymbolcLink. */
383static DWORD is_directory(const char *pszPath, const char *pszRelativeTo)
384{
385 size_t cchPath = strlen(pszPath);
386 struct stat st;
387 if (cchPath > 0 && pszPath[cchPath - 1] == '\\' || pszPath[cchPath - 1] == '/')
388 return 1; /* SYMBOLIC_LINK_FLAG_DIRECTORY */
389
390 if (stat(pszPath, &st))
391 {
392 size_t cchRelativeTo = strlen(pszRelativeTo);
393 char *psz = malloc(cchPath + cchRelativeTo + 4);
394 memcpy(psz, pszRelativeTo, cchRelativeTo);
395 memcpy(psz + cchRelativeTo, "\\", 1);
396 memcpy(psz + cchRelativeTo + 1, pszPath, cchPath + 1);
397 if (stat(pszPath, &st))
398 st.st_mode = _S_IFREG;
399 free(psz);
400 }
401
402 return (st.st_mode & _S_IFMT) == _S_IFDIR ? 1 : 0;
403}
404
405
406int symlink(const char *pszDst, const char *pszLink)
407{
408 static BOOLEAN (WINAPI *s_pfnCreateSymbolicLinkA)(LPCSTR, LPCSTR, DWORD) = 0;
409 static BOOL s_fTried = FALSE;
410
411 if (!s_fTried)
412 {
413 HMODULE hmod = LoadLibrary("KERNEL32.DLL");
414 if (hmod)
415 *(FARPROC *)&s_pfnCreateSymbolicLinkA = GetProcAddress(hmod, "CreateSymbolicLinkA");
416 s_fTried = TRUE;
417 }
418
419 if (s_pfnCreateSymbolicLinkA)
420 {
421 char *pszDstCopy = fix_slashes(strdup(pszDst));
422 char *pszLinkCopy = fix_slashes(strdup(pszLink));
423 BOOLEAN fRc = s_pfnCreateSymbolicLinkA(pszLinkCopy, pszDstCopy,
424 is_directory(pszDstCopy, pszLinkCopy));
425 DWORD err = GetLastError();
426 free(pszDstCopy);
427 free(pszLinkCopy);
428 if (fRc)
429 return 0;
430 switch (err)
431 {
432 case ERROR_NOT_SUPPORTED: errno = ENOSYS; break;
433 case ERROR_ALREADY_EXISTS:
434 case ERROR_FILE_EXISTS: errno = EEXIST; break;
435 case ERROR_DIRECTORY: errno = ENOTDIR; break;
436 case ERROR_ACCESS_DENIED:
437 case ERROR_PRIVILEGE_NOT_HELD: errno = EPERM; break;
438 default: errno = EINVAL; break;
439 }
440 return -1;
441 }
442
443 errno = ENOSYS;
444 err(1, "symlink() is not implemented on windows!");
445 return -1;
446}
447
448
449#if _MSC_VER < 1400
450int snprintf(char *buf, size_t size, const char *fmt, ...)
451{
452 int cch;
453 va_list args;
454 va_start(args, fmt);
455 cch = vsprintf(buf, fmt, args);
456 va_end(args);
457 return cch;
458}
459#endif
460
461
462int utimes(const char *pszPath, const struct timeval *paTimes)
463{
464 /** @todo implement me! */
465 return 0;
466}
467
468
469int writev(int fd, const struct iovec *vector, int count)
470{
471 int size = 0;
472 int i;
473 for (i = 0; i < count; i++)
474 {
475 int cb = write(fd, vector[i].iov_base, (int)vector[i].iov_len);
476 if (cb < 0)
477 {
478 /* ENOSPC on pipe kludge. */
479 char *pbCur;
480 size_t cbLeft;
481 int cbLimit;
482 int cSinceLastSuccess;
483 int iErr = errno;
484
485 if (errno != ENOSPC)
486 return -1;
487 if ((int)vector[i].iov_len == 0)
488 continue;
489 if (!isPipeFd(fd))
490 {
491 errno = ENOSPC;
492 return -1;
493 }
494
495 /* Likely a full pipe buffer, try write smaller amounts and do some
496 sleeping inbetween each unsuccessful one. */
497 pbCur = vector[i].iov_base;
498 cbLeft = vector[i].iov_len;
499 cbLimit = cbLeft / 4;
500 if (cbLimit < 4)
501 cbLimit = 4;
502 else if (cbLimit > 512)
503 cbLimit = 512;
504 cSinceLastSuccess = 0;
505
506 while (cbLeft > 0)
507 {
508 int cbAttempt = cbLeft > cbLimit ? (int)cbLimit : (int)cbLeft;
509 cb = write(fd, pbCur, cbAttempt);
510 if (cb > 0)
511 {
512 assert(cb <= cbAttempt);
513 pbCur += cb;
514 cbLeft -= cb;
515 size += cb;
516 if (cbLimit < 32)
517 cbLimit = 32;
518 cSinceLastSuccess = 0;
519 }
520 else if (errno != ENOSPC)
521 return -1;
522 else
523 {
524 /* Delay for about 30 seconds, then just give up. */
525 cSinceLastSuccess++;
526 if (cSinceLastSuccess > 1860)
527 return -1;
528 if (cSinceLastSuccess <= 2)
529 Sleep(0);
530 else if (cSinceLastSuccess <= 66)
531 {
532 if (cbLimit >= 8)
533 cbLimit /= 2; /* Just in case the pipe buffer is very very small. */
534 Sleep(1);
535 }
536 else
537 Sleep(16);
538 }
539 }
540 cb = 0;
541 }
542 size += cb;
543 }
544 return size;
545}
546
547
548intmax_t strtoimax(const char *nptr, char **endptr, int base)
549{
550 if (*nptr != '-')
551 return _strtoui64(nptr, endptr, base);
552 return -(intmax_t)_strtoui64(nptr + 1, endptr, base);
553}
554
555
556uintmax_t strtoumax(const char *nptr, char **endptr, int base)
557{
558 return _strtoui64(nptr, endptr, base);
559}
560
561
562int asprintf(char **strp, const char *fmt, ...)
563{
564 int rc;
565 va_list va;
566 va_start(va, fmt);
567 rc = vasprintf(strp, fmt, va);
568 va_end(va);
569 return rc;
570}
571
572
573int vasprintf(char **strp, const char *fmt, va_list va)
574{
575 int rc;
576 char *psz;
577 size_t cb = 1024;
578
579 *strp = NULL;
580 for (;;)
581 {
582 va_list va2;
583
584 psz = malloc(cb);
585 if (!psz)
586 return -1;
587
588#ifdef va_copy
589 va_copy(va2, va);
590 rc = snprintf(psz, cb, fmt, va2);
591 va_end(vaCopy);
592#else
593 va2 = va;
594 rc = snprintf(psz, cb, fmt, va2);
595#endif
596 if (rc < 0 || (size_t)rc < cb)
597 break;
598 cb *= 2;
599 free(psz);
600 }
601
602 *strp = psz;
603 return rc;
604}
605
606
607/**
608 * Checks if the given file descriptor is a pipe or not.
609 *
610 * @returns TRUE if pipe, FALSE if not.
611 * @param fd The libc file descriptor number.
612 */
613static BOOL isPipeFd(int fd)
614{
615 /* Is pipe? */
616 HANDLE hFile = (HANDLE)_get_osfhandle(fd);
617 if (hFile != INVALID_HANDLE_VALUE)
618 {
619 DWORD fType = GetFileType(hFile);
620 fType &= ~FILE_TYPE_REMOTE;
621 if (fType == FILE_TYPE_PIPE)
622 return TRUE;
623 }
624 return FALSE;
625}
626
627
628
629/**
630 * This is a kludge to make pipe handles blocking.
631 *
632 * @returns TRUE if it's now blocking, FALSE if not a pipe or we failed to fix
633 * the blocking mode.
634 * @param fd The libc file descriptor number.
635 */
636static BOOL makePipeBlocking(int fd)
637{
638 if (isPipeFd(fd))
639 {
640 /* Try fix it. */
641 HANDLE hFile = (HANDLE)_get_osfhandle(fd);
642 DWORD fState = 0;
643 if (GetNamedPipeHandleState(hFile, &fState, NULL, NULL, NULL, NULL, 0))
644 {
645 fState &= ~PIPE_NOWAIT;
646 fState |= PIPE_WAIT;
647 if (SetNamedPipeHandleState(hFile, &fState, NULL, NULL))
648 return TRUE;
649 }
650 }
651 return FALSE;
652}
653
654
655/**
656 * Initializes the msc fake stuff.
657 * @returns 0 on success (non-zero would indicate failure, see rterr.h).
658 */
659int mscfake_init(void)
660{
661 /*
662 * Kludge against _write returning ENOSPC on non-blocking pipes.
663 */
664 makePipeBlocking(STDOUT_FILENO);
665 makePipeBlocking(STDERR_FILENO);
666
667 return 0;
668}
669
670/*
671 * Do this before main is called.
672 */
673#pragma section(".CRT$XIA", read)
674#pragma section(".CRT$XIU", read)
675#pragma section(".CRT$XIZ", read)
676typedef int (__cdecl *PFNCRTINIT)(void);
677static __declspec(allocate(".CRT$XIU")) PFNCRTINIT g_MscFakeInitVectorEntry = mscfake_init;
678
Note: See TracBrowser for help on using the repository browser.