VirtualBox

source: kBuild/trunk/src/kmk/kmkbuiltin/mscfakes.c@ 2759

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

More generic ENOSPC workaround for windows.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 19.7 KB
Line 
1/* $Id: mscfakes.c 2759 2015-01-28 16:14:00Z bird $ */
2/** @file
3 * Fake Unix stuff for MSC.
4 */
5
6/*
7 * Copyright (c) 2005-2015 knut st. osmundsen <[email protected]>
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
469/* We override the libc write function (in our modules only, unfortunately) so
470 we can kludge our way around a ENOSPC problem observed on build servers
471 capturing STDOUT and STDERR via pipes. Apparently this may happen when the
472 pipe buffer is full, even with the mscfake_init hack in place.
473
474 XXX: Probably need to hook into fwrite as well. */
475ssize_t msc_write(int fd, const void *pvSrc, size_t cbSrc)
476{
477 ssize_t cbRet;
478 if (cbSrc < UINT_MAX / 4)
479 {
480#ifndef MSC_WRITE_TEST
481 cbRet = _write(fd, pvSrc, (unsigned int)cbSrc);
482#else
483 cbRet = -1; errno = ENOSPC;
484#endif
485 if (cbRet < 0)
486 {
487 /* ENOSPC on pipe kludge. */
488 int cbLimit;
489 int cSinceLastSuccess;
490
491 if (cbSrc == 0)
492 return 0;
493 if (errno != ENOSPC)
494 return -1;
495#ifndef MSC_WRITE_TEST
496 if (!isPipeFd(fd))
497 {
498 errno = ENOSPC;
499 return -1;
500 }
501#endif
502
503 /* Likely a full pipe buffer, try write smaller amounts and do some
504 sleeping inbetween each unsuccessful one. */
505 cbLimit = cbSrc / 4;
506 if (cbLimit < 4)
507 cbLimit = 4;
508 else if (cbLimit > 512)
509 cbLimit = 512;
510 cSinceLastSuccess = 0;
511 cbRet = 0;
512#ifdef MSC_WRITE_TEST
513 cbLimit = 4;
514#endif
515
516 while (cbSrc > 0)
517 {
518 unsigned int cbAttempt = cbSrc > cbLimit ? (int)cbLimit : (int)cbSrc;
519 ssize_t cbActual = _write(fd, pvSrc, cbAttempt);
520 if (cbActual > 0)
521 {
522 assert(cbActual <= (ssize_t)cbAttempt);
523 pvSrc = (char *)pvSrc + cbActual;
524 cbSrc -= cbActual;
525 cbRet += cbActual;
526#ifndef MSC_WRITE_TEST
527 if (cbLimit < 32)
528 cbLimit = 32;
529#endif
530 cSinceLastSuccess = 0;
531 }
532 else if (errno != ENOSPC)
533 return -1;
534 else
535 {
536 /* Delay for about 30 seconds, then just give up. */
537 cSinceLastSuccess++;
538 if (cSinceLastSuccess > 1860)
539 return -1;
540 if (cSinceLastSuccess <= 2)
541 Sleep(0);
542 else if (cSinceLastSuccess <= 66)
543 {
544 if (cbLimit >= 8)
545 cbLimit /= 2; /* Just in case the pipe buffer is very very small. */
546 Sleep(1);
547 }
548 else
549 Sleep(16);
550 }
551 }
552 }
553 }
554 else
555 {
556 /*
557 * Type limit exceeded. Split the job up.
558 */
559 cbRet = 0;
560 while (cbSrc > 0)
561 {
562 size_t cbToWrite = cbSrc > UINT_MAX / 4 ? UINT_MAX / 4 : cbSrc;
563 ssize_t cbWritten = msc_write(fd, pvSrc, cbToWrite);
564 if (cbWritten > 0)
565 {
566 pvSrc = (char *)pvSrc + (size_t)cbWritten;
567 cbSrc -= (size_t)cbWritten;
568 cbRet += (size_t)cbWritten;
569 }
570 else if (cbWritten == 0 || cbRet > 0)
571 break;
572 else
573 return -1;
574 }
575 }
576 return cbRet;
577}
578
579ssize_t writev(int fd, const struct iovec *vector, int count)
580{
581 int size = 0;
582 int i;
583 for (i = 0; i < count; i++)
584 {
585 int cb = msc_write(fd, vector[i].iov_base, (int)vector[i].iov_len);
586 if (cb < 0)
587 return cb;
588 size += cb;
589 }
590 return size;
591}
592
593
594intmax_t strtoimax(const char *nptr, char **endptr, int base)
595{
596 if (*nptr != '-')
597 return _strtoui64(nptr, endptr, base);
598 return -(intmax_t)_strtoui64(nptr + 1, endptr, base);
599}
600
601
602uintmax_t strtoumax(const char *nptr, char **endptr, int base)
603{
604 return _strtoui64(nptr, endptr, base);
605}
606
607
608int asprintf(char **strp, const char *fmt, ...)
609{
610 int rc;
611 va_list va;
612 va_start(va, fmt);
613 rc = vasprintf(strp, fmt, va);
614 va_end(va);
615 return rc;
616}
617
618
619int vasprintf(char **strp, const char *fmt, va_list va)
620{
621 int rc;
622 char *psz;
623 size_t cb = 1024;
624
625 *strp = NULL;
626 for (;;)
627 {
628 va_list va2;
629
630 psz = malloc(cb);
631 if (!psz)
632 return -1;
633
634#ifdef va_copy
635 va_copy(va2, va);
636 rc = snprintf(psz, cb, fmt, va2);
637 va_end(vaCopy);
638#else
639 va2 = va;
640 rc = snprintf(psz, cb, fmt, va2);
641#endif
642 if (rc < 0 || (size_t)rc < cb)
643 break;
644 cb *= 2;
645 free(psz);
646 }
647
648 *strp = psz;
649 return rc;
650}
651
652
653/**
654 * Checks if the given file descriptor is a pipe or not.
655 *
656 * @returns TRUE if pipe, FALSE if not.
657 * @param fd The libc file descriptor number.
658 */
659static BOOL isPipeFd(int fd)
660{
661 /* Is pipe? */
662 HANDLE hFile = (HANDLE)_get_osfhandle(fd);
663 if (hFile != INVALID_HANDLE_VALUE)
664 {
665 DWORD fType = GetFileType(hFile);
666 fType &= ~FILE_TYPE_REMOTE;
667 if (fType == FILE_TYPE_PIPE)
668 return TRUE;
669 }
670 return FALSE;
671}
672
673
674/**
675 * This is a kludge to make pipe handles blocking.
676 *
677 * @returns TRUE if it's now blocking, FALSE if not a pipe or we failed to fix
678 * the blocking mode.
679 * @param fd The libc file descriptor number.
680 */
681static BOOL makePipeBlocking(int fd)
682{
683 if (isPipeFd(fd))
684 {
685 /* Try fix it. */
686 HANDLE hFile = (HANDLE)_get_osfhandle(fd);
687 DWORD fState = 0;
688 if (GetNamedPipeHandleState(hFile, &fState, NULL, NULL, NULL, NULL, 0))
689 {
690 fState &= ~PIPE_NOWAIT;
691 fState |= PIPE_WAIT;
692 if (SetNamedPipeHandleState(hFile, &fState, NULL, NULL))
693 return TRUE;
694 }
695 }
696 return FALSE;
697}
698
699
700/**
701 * Initializes the msc fake stuff.
702 * @returns 0 on success (non-zero would indicate failure, see rterr.h).
703 */
704int mscfake_init(void)
705{
706 /*
707 * Kludge against _write returning ENOSPC on non-blocking pipes.
708 */
709 makePipeBlocking(STDOUT_FILENO);
710 makePipeBlocking(STDERR_FILENO);
711
712 return 0;
713}
714
715/*
716 * Do this before main is called.
717 */
718#pragma section(".CRT$XIA", read)
719#pragma section(".CRT$XIU", read)
720#pragma section(".CRT$XIZ", read)
721typedef int (__cdecl *PFNCRTINIT)(void);
722static __declspec(allocate(".CRT$XIU")) PFNCRTINIT g_MscFakeInitVectorEntry = mscfake_init;
723
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette