summaryrefslogtreecommitdiff
path: root/src/kmk/kmkbuiltin/mscfakes.c
blob: 7d040ff81761880371fe38c1acaf30b5201737bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
/* $Id: mscfakes.c 2484 2011-07-21 19:01:08Z bird $ */
/** @file
 * Fake Unix stuff for MSC.
 */

/*
 * Copyright (c) 2005-2010 knut st. osmundsen <bird-kBuild-spamx@anduin.net>
 *
 * This file is part of kBuild.
 *
 * kBuild is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * kBuild is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with kBuild.  If not, see <http://www.gnu.org/licenses/>
 *
 */

/*******************************************************************************
*   Header Files                                                               *
*******************************************************************************/
#include "config.h"
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "err.h"
#include "mscfakes.h"

#define timeval windows_timeval
#include <Windows.h>
#undef timeval


/**
 * Makes corrections to a directory path that ends with a trailing slash.
 *
 * @returns temporary buffer to free.
 * @param   ppszPath    The path pointer. This is updated when necessary.
 * @param   pfMustBeDir This is set if it must be a directory, otherwise it's cleared.
 */
static char *
msc_fix_path(const char **ppszPath, int *pfMustBeDir)
{
    const char *pszPath = *ppszPath;
    const char *psz;
    char *pszNew;
    *pfMustBeDir = 0;

    /*
     * Skip any compusory trailing slashes
     */
    if (pszPath[0] == '/' || pszPath[0] == '\\')
    {
        if (   (pszPath[1] == '/' || pszPath[1] == '\\')
            &&  pszPath[2] != '/'
            &&  pszPath[2] != '\\')
            /* unc */
            pszPath += 2;
        else
            /* root slash(es) */
            pszPath++;
    }
    else if (   isalpha(pszPath[0])
             && pszPath[1] == ':')
    {
        if (pszPath[2] == '/' || pszPath[2] == '\\')
            /* drive w/ slash */
            pszPath += 3;
        else
            /* drive relative path. */
            pszPath += 2;
    }
    /* else: relative path, no skipping necessary. */

    /*
     * Any trailing slashes to drop off?
     */
    psz = strchr(pszPath, '\0');
    if (pszPath <= psz)
        return NULL;
    if (   psz[-1] != '/'
        || psz[-1] != '\\')
        return NULL;

    /* figure how many, make a copy and strip them off. */
    while (     psz > pszPath
           &&   (   psz[-1] == '/'
                 || psz[-1] == '\\'))
        psz--;
    pszNew = strdup(pszPath);
    pszNew[psz - pszPath] = '\0';

    *pfMustBeDir = 1;
    *ppszPath = pszNew; /* use this one */
    return pszNew;
}


static int
msc_set_errno(DWORD dwErr)
{
    switch (dwErr)
    {
        default:
        case ERROR_INVALID_FUNCTION:        errno = EINVAL; break;
        case ERROR_FILE_NOT_FOUND:          errno = ENOENT; break;
        case ERROR_PATH_NOT_FOUND:          errno = ENOENT; break;
        case ERROR_TOO_MANY_OPEN_FILES:     errno = EMFILE; break;
        case ERROR_ACCESS_DENIED:           errno = EACCES; break;
        case ERROR_INVALID_HANDLE:          errno = EBADF; break;
        case ERROR_ARENA_TRASHED:           errno = ENOMEM; break;
        case ERROR_NOT_ENOUGH_MEMORY:       errno = ENOMEM; break;
        case ERROR_INVALID_BLOCK:           errno = ENOMEM; break;
        case ERROR_BAD_ENVIRONMENT:         errno = E2BIG; break;
        case ERROR_BAD_FORMAT:              errno = ENOEXEC; break;
        case ERROR_INVALID_ACCESS:          errno = EINVAL; break;
        case ERROR_INVALID_DATA:            errno = EINVAL; break;
        case ERROR_INVALID_DRIVE:           errno = ENOENT; break;
        case ERROR_CURRENT_DIRECTORY:       errno = EACCES; break;
        case ERROR_NOT_SAME_DEVICE:         errno = EXDEV; break;
        case ERROR_NO_MORE_FILES:           errno = ENOENT; break;
        case ERROR_LOCK_VIOLATION:          errno = EACCES; break;
        case ERROR_BAD_NETPATH:             errno = ENOENT; break;
        case ERROR_NETWORK_ACCESS_DENIED:   errno = EACCES; break;
        case ERROR_BAD_NET_NAME:            errno = ENOENT; break;
        case ERROR_FILE_EXISTS:             errno = EEXIST; break;
        case ERROR_CANNOT_MAKE:             errno = EACCES; break;
        case ERROR_FAIL_I24:                errno = EACCES; break;
        case ERROR_INVALID_PARAMETER:       errno = EINVAL; break;
        case ERROR_NO_PROC_SLOTS:           errno = EAGAIN; break;
        case ERROR_DRIVE_LOCKED:            errno = EACCES; break;
        case ERROR_BROKEN_PIPE:             errno = EPIPE; break;
        case ERROR_DISK_FULL:               errno = ENOSPC; break;
        case ERROR_INVALID_TARGET_HANDLE:   errno = EBADF; break;
        case ERROR_WAIT_NO_CHILDREN:        errno = ECHILD; break;
        case ERROR_CHILD_NOT_COMPLETE:      errno = ECHILD; break;
        case ERROR_DIRECT_ACCESS_HANDLE:    errno = EBADF; break;
        case ERROR_NEGATIVE_SEEK:           errno = EINVAL; break;
        case ERROR_SEEK_ON_DEVICE:          errno = EACCES; break;
        case ERROR_DIR_NOT_EMPTY:           errno = ENOTEMPTY; break;
        case ERROR_NOT_LOCKED:              errno = EACCES; break;
        case ERROR_BAD_PATHNAME:            errno = ENOENT; break;
        case ERROR_MAX_THRDS_REACHED:       errno = EAGAIN; break;
        case ERROR_LOCK_FAILED:             errno = EACCES; break;
        case ERROR_ALREADY_EXISTS:          errno = EEXIST; break;
        case ERROR_FILENAME_EXCED_RANGE:    errno = ENOENT; break;
        case ERROR_NESTING_NOT_ALLOWED:     errno = EAGAIN; break;
#ifdef EMLINK
        case ERROR_TOO_MANY_LINKS:          errno = EMLINK; break;
#endif
    }

    return -1;
}

char *dirname(char *path)
{
    /** @todo later */
    return path;
}


int lchmod(const char *pszPath, mode_t mode)
{
    int rc = 0;
    int fMustBeDir;
    char *pszPathFree = msc_fix_path(&pszPath, &fMustBeDir);

    /*
     * Get the current attributes
     */
    DWORD fAttr = GetFileAttributes(pszPath);
    if (fAttr == INVALID_FILE_ATTRIBUTES)
        rc = msc_set_errno(GetLastError());
    else if (fMustBeDir & !(fAttr & FILE_ATTRIBUTE_DIRECTORY))
    {
        errno = ENOTDIR;
        rc = -1;
    }
    else
    {
        /*
         * Modify the attributes and try set them.
         */
        if (mode & _S_IWRITE)
            fAttr &= ~FILE_ATTRIBUTE_READONLY;
        else
            fAttr |= FILE_ATTRIBUTE_READONLY;
        if (!SetFileAttributes(pszPath, fAttr))
            rc = msc_set_errno(GetLastError());
    }

    if (pszPathFree)
    {
        int saved_errno = errno;
        free(pszPathFree);
        errno = saved_errno;
    }
    return rc;
}


int msc_chmod(const char *pszPath, mode_t mode)
{
    int rc = 0;
    int fMustBeDir;
    char *pszPathFree = msc_fix_path(&pszPath, &fMustBeDir);

    /*
     * Get the current attributes.
     */
    DWORD fAttr = GetFileAttributes(pszPath);
    if (fAttr == INVALID_FILE_ATTRIBUTES)
        rc = msc_set_errno(GetLastError());
    else if (fMustBeDir & !(fAttr & FILE_ATTRIBUTE_DIRECTORY))
    {
        errno = ENOTDIR;
        rc = -1;
    }
    else if (fAttr & FILE_ATTRIBUTE_REPARSE_POINT)
    {
        errno = ENOSYS; /** @todo resolve symbolic link / rewrite to NtSetInformationFile. */
        rc = -1;
    }
    else
    {
        /*
         * Modify the attributes and try set them.
         */
        if (mode & _S_IWRITE)
            fAttr &= ~FILE_ATTRIBUTE_READONLY;
        else
            fAttr |= FILE_ATTRIBUTE_READONLY;
        if (!SetFileAttributes(pszPath, fAttr))
            rc = msc_set_errno(GetLastError());
    }

    if (pszPathFree)
    {
        int saved_errno = errno;
        free(pszPathFree);
        errno = saved_errno;
    }
    return rc;
}


typedef BOOL (WINAPI *PFNCREATEHARDLINKA)(LPCSTR, LPCSTR, LPSECURITY_ATTRIBUTES);
int link(const char *pszDst, const char *pszLink)
{
    static PFNCREATEHARDLINKA   s_pfnCreateHardLinkA = NULL;
    static int                  s_fTried = FALSE;

    /* The API was introduced in Windows 2000, so resolve it dynamically. */
    if (!s_pfnCreateHardLinkA)
    {
        if (!s_fTried)
        {
            HMODULE hmod = LoadLibrary("KERNEL32.DLL");
            if (hmod)
                *(FARPROC *)&s_pfnCreateHardLinkA = GetProcAddress(hmod, "CreateHardLinkA");
            s_fTried = TRUE;
        }
        if (!s_pfnCreateHardLinkA)
        {
            errno = ENOSYS;
            return -1;
        }
    }

    if (s_pfnCreateHardLinkA(pszLink, pszDst, NULL))
        return 0;
    return msc_set_errno(GetLastError());
}


int mkdir_msc(const char *path, mode_t mode)
{
    int rc = (mkdir)(path);
    if (rc)
    {
        size_t len = strlen(path);
        if (len > 0 && (path[len - 1] == '/' || path[len - 1] == '\\'))
        {
            char *str = strdup(path);
            while (len > 0 && (str[len - 1] == '/' || str[len - 1] == '\\'))
                str[--len] = '\0';
            rc = (mkdir)(str);
            free(str);
        }
    }
    return rc;
}

int rmdir_msc(const char *path)
{
    int rc = (rmdir)(path);
    if (rc)
    {
        size_t len = strlen(path);
        if (len > 0 && (path[len - 1] == '/' || path[len - 1] == '\\'))
        {
            char *str = strdup(path);
            while (len > 0 && (str[len - 1] == '/' || str[len - 1] == '\\'))
                str[--len] = '\0';
            rc = (rmdir)(str);
            free(str);
        }
    }
    return rc;
}


static int doname(char *pszX, char *pszEnd)
{
    static char s_szChars[] = "Xabcdefghijklmnopqrstuwvxyz1234567890";
    int rc = 0;
    do
    {
        char ch;

        pszEnd++;
        ch = *(strchr(s_szChars, *pszEnd) + 1);
        if (ch)
        {
            *pszEnd = ch;
            return 0;
        }
        *pszEnd = 'a';
    } while (pszEnd != pszX);
    return 1;
}


int mkstemp(char *temp)
{
    char *pszX = strchr(temp, 'X');
    char *pszEnd = strchr(pszX, '\0');
    int cTries = 1000;
    while (--cTries > 0)
    {
        int fd;
        if (doname(pszX, pszEnd))
            return -1;
        fd = open(temp, _O_EXCL | _O_CREAT | _O_BINARY | _O_RDWR, 0777);
        if (fd >= 0)
            return fd;
    }
    return -1;
}


/** Unix to DOS. */
static char *fix_slashes(char *psz)
{
    char *pszRet = psz;
    for (; *psz; psz++)
        if (*psz == '/')
            *psz = '\\';
    return pszRet;
}


/** Calcs the SYMBOLIC_LINK_FLAG_DIRECTORY flag for CreatesymbolcLink.  */
static DWORD is_directory(const char *pszPath, const char *pszRelativeTo)
{
    size_t cchPath = strlen(pszPath);
    struct stat st;
    if (cchPath > 0 && pszPath[cchPath - 1] == '\\' || pszPath[cchPath - 1] == '/')
        return 1; /* SYMBOLIC_LINK_FLAG_DIRECTORY */

    if (stat(pszPath, &st))
    {
        size_t cchRelativeTo = strlen(pszRelativeTo);
        char *psz = malloc(cchPath + cchRelativeTo + 4);
        memcpy(psz, pszRelativeTo, cchRelativeTo);
        memcpy(psz + cchRelativeTo, "\\", 1);
        memcpy(psz + cchRelativeTo + 1, pszPath, cchPath + 1);
        if (stat(pszPath, &st))
            st.st_mode = _S_IFREG;
        free(psz);
    }

    return (st.st_mode & _S_IFMT) == _S_IFDIR ? 1 : 0;
}


int symlink(const char *pszDst, const char *pszLink)
{
    static BOOLEAN (WINAPI *s_pfnCreateSymbolicLinkA)(LPCSTR, LPCSTR, DWORD) = 0;
    static BOOL s_fTried = FALSE;

    if (!s_fTried)
    {
        HMODULE hmod = LoadLibrary("KERNEL32.DLL");
        if (hmod)
            *(FARPROC *)&s_pfnCreateSymbolicLinkA = GetProcAddress(hmod, "CreateSymbolicLinkA");
        s_fTried = TRUE;
    }

    if (s_pfnCreateSymbolicLinkA)
    {
        char *pszDstCopy = fix_slashes(strdup(pszDst));
        char *pszLinkCopy = fix_slashes(strdup(pszLink));
        BOOLEAN fRc = s_pfnCreateSymbolicLinkA(pszLinkCopy, pszDstCopy,
                                               is_directory(pszDstCopy, pszLinkCopy));
        DWORD err = GetLastError();
        free(pszDstCopy);
        free(pszLinkCopy);
        if (fRc)
            return 0;
        switch (err)
        {
            case ERROR_NOT_SUPPORTED:       errno = ENOSYS; break;
            case ERROR_ALREADY_EXISTS:
            case ERROR_FILE_EXISTS:         errno = EEXIST; break;
            case ERROR_DIRECTORY:           errno = ENOTDIR; break;
            case ERROR_ACCESS_DENIED:
            case ERROR_PRIVILEGE_NOT_HELD:  errno = EPERM; break;
            default:                        errno = EINVAL; break;
        }
        return -1;
    }

    errno = ENOSYS;
    err(1, "symlink() is not implemented on windows!");
    return -1;
}


#if _MSC_VER < 1400
int snprintf(char *buf, size_t size, const char *fmt, ...)
{
    int cch;
    va_list args;
    va_start(args, fmt);
    cch = vsprintf(buf, fmt, args);
    va_end(args);
    return cch;
}
#endif


int utimes(const char *pszPath, const struct timeval *paTimes)
{
    /** @todo implement me! */
    return 0;
}


int writev(int fd, const struct iovec *vector, int count)
{
    int size = 0;
    int i;
    for (i = 0; i < count; i++)
    {
        int cb = (int)write(fd, vector[i].iov_base, (int)vector[i].iov_len);
        if (cb < 0)
            return -1;
        size += cb;
    }
    return size;
}


intmax_t strtoimax(const char *nptr, char **endptr, int base)
{
    return strtol(nptr, endptr, base); /** @todo fix this. */
}


uintmax_t strtoumax(const char *nptr, char **endptr, int base)
{
    return strtoul(nptr, endptr, base); /** @todo fix this. */
}


int asprintf(char **strp, const char *fmt, ...)
{
    int rc;
    va_list va;
    va_start(va, fmt);
    rc = vasprintf(strp, fmt, va);
    va_end(va);
    return rc;
}


int vasprintf(char **strp, const char *fmt, va_list va)
{
    int rc;
    char *psz;
    size_t cb = 1024;

    *strp = NULL;
    for (;;)
    {
        va_list va2;

        psz = malloc(cb);
        if (!psz)
            return -1;

#ifdef va_copy
        va_copy(va2, va);
        rc = snprintf(psz, cb, fmt, va2);
        va_end(vaCopy);
#else
        va2 = va;
        rc = snprintf(psz, cb, fmt, va2);
#endif
        if (rc < 0 || (size_t)rc < cb)
            break;
        cb *= 2;
        free(psz);
    }

    *strp = psz;
    return rc;
}


#undef stat
/*
 * Workaround for directory names with trailing slashes.
 * Added by bird reasons stated.
 */
int
my_other_stat(const char *path, struct stat *st)
{
    int rc = stat(path, st);
    if (    rc != 0
        &&  errno == ENOENT
        &&  *path != '\0')
    {
        char *slash = strchr(path, '\0') - 1;
        if (*slash == '/' || *slash == '\\')
        {
            size_t len_path = slash - path + 1;
            char *tmp = alloca(len_path + 4);
            memcpy(tmp, path, len_path);
            tmp[len_path] = '.';
            tmp[len_path + 1] = '\0';
            errno = 0;
            rc = stat(tmp, st);
            if (    rc == 0
                &&  !S_ISDIR(st->st_mode))
            {
                errno = ENOTDIR;
                rc = -1;
            }
        }
    }
    return rc;
}