summaryrefslogtreecommitdiff
path: root/tools/slang-test/os.cpp
blob: a938a71e71703a6c9569b07e322fd5026213871f (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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
// os.cpp
#include "os.h"

#include <stdio.h>
#include <stdlib.h>

using namespace Slang;

// Platform-specific code follows

#ifdef _WIN32

#include <Windows.h>

static bool advance(OSFindFilesResult& result)
{
    return FindNextFileW(result.findHandle_, &result.fileData_) != 0;
}

static bool adjustToValidResult(OSFindFilesResult& result)
{
    for (;;)
    {
        if ((result.fileData_.dwFileAttributes & result.requiredMask_) != result.requiredMask_)
            goto skip;

        if ((result.fileData_.dwFileAttributes & result.disallowedMask_) != 0)
            goto skip;

        if (wcscmp(result.fileData_.cFileName, L".") == 0)
            goto skip;

        if (wcscmp(result.fileData_.cFileName, L"..") == 0)
            goto skip;

        result.filePath_ = result.directoryPath_ + String::fromWString(result.fileData_.cFileName);
        if (result.fileData_.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            result.filePath_ = result.filePath_ + "/";

        return true;

    skip:
        if (!advance(result))
            return false;
    }
}


bool OSFindFilesResult::findNextFile()
{
    if (!advance(*this)) return false;
    return adjustToValidResult(*this);
}

OSFindFilesResult osFindFilesInDirectoryMatchingPattern(
    Slang::String directoryPath,
    Slang::String pattern)
{
    // TODO: add separator to end of directory path if needed

    String searchPath = directoryPath + pattern;

    OSFindFilesResult result;
    HANDLE findHandle = FindFirstFileW(
        searchPath.toWString(),
        &result.fileData_);

    result.directoryPath_ = directoryPath;
    result.findHandle_ = findHandle;
    result.requiredMask_ = 0;
    result.disallowedMask_ = FILE_ATTRIBUTE_DIRECTORY;

    if (findHandle == INVALID_HANDLE_VALUE)
    {
        result.findHandle_ = NULL;
        result.error_ = kOSError_FileNotFound;
        return result;
    }

    result.error_ = kOSError_None;
    if (!adjustToValidResult(result))
    {
        result.findHandle_ = NULL;
    }
    return result;
}

OSFindFilesResult osFindFilesInDirectory(
    Slang::String directoryPath)
{
    return osFindFilesInDirectoryMatchingPattern(directoryPath, "*");
}

OSFindFilesResult osFindChildDirectories(
    Slang::String directoryPath)
{
    // TODO: add separator to end of directory path if needed

    String searchPath = directoryPath + "*";

    OSFindFilesResult result;
    HANDLE findHandle = FindFirstFileW(
        searchPath.toWString(),
        &result.fileData_);

    result.directoryPath_ = directoryPath;
    result.findHandle_ = findHandle;
    result.requiredMask_ = FILE_ATTRIBUTE_DIRECTORY;
    result.disallowedMask_ = 0;

    if (findHandle == INVALID_HANDLE_VALUE)
    {
        result.findHandle_ = NULL;
        result.error_ = kOSError_FileNotFound;
        return result;
    }

    result.error_ = kOSError_None;
    if (!adjustToValidResult(result))
    {
        result.findHandle_ = NULL;
    }
    return result;
}

// OSProcessSpawner

struct OSProcessSpawner_ReaderThreadInfo
{
    HANDLE	file;
    String	output;
};

static DWORD WINAPI osReaderThreadProc(LPVOID threadParam)
{
    OSProcessSpawner_ReaderThreadInfo* info = (OSProcessSpawner_ReaderThreadInfo*)threadParam;
    HANDLE file = info->file;

    static const int kChunkSize = 1024;
    char buffer[kChunkSize];

    StringBuilder outputBuilder;

    // We need to re-write the output to deal with line
    // endings, so we check for paired '\r' and '\n'
    // characters, which may span chunks.
    int prevChar = -1;

    for (;;)
    {
        DWORD bytesRead = 0;
        BOOL readResult = ReadFile(file, buffer, kChunkSize, &bytesRead, nullptr);

        if (!readResult || GetLastError() == ERROR_BROKEN_PIPE)
        {
            break;
        }

        // walk the buffer and rewrite to eliminate '\r' '\n' pairs
        char* readCursor = buffer;
        char const* end = buffer + bytesRead;
        char* writeCursor = buffer;

        while (readCursor != end)
        {
            int p = prevChar;
            int c = *readCursor++;
            prevChar = c;
            switch (c)
            {
            case '\r': case '\n':
                // swallow input if '\r' and '\n' appear in sequence
                if ((p ^ c) == ('\r' ^ '\n'))
                {
                    // but don't swallow the next byte
                    prevChar = -1;
                    continue;
                }
                // always replace '\r' with '\n'
                c = '\n';
                break;

            default:
                break;
            }

            *writeCursor++ = (char)c;
        }
        bytesRead = (DWORD)(writeCursor - buffer);

        // Note: Current "core" implementation gives no way to know
        // the length of the buffer, so we ultimately have
        // to just assume null termination...
        outputBuilder.Append(buffer, bytesRead);
    }

    info->output = outputBuilder.ProduceString();

    return 0;
}

void OSProcessSpawner::pushExecutableName(
    Slang::String executableName)
{
    executableName_ = executableName;
    commandLine_.Append(executableName);
    isExecutablePath_ = false;
}

void OSProcessSpawner::pushExecutablePath(
    Slang::String executablePath)
{
    executableName_ = executablePath;
    commandLine_.Append(executablePath);
    isExecutablePath_ = true;
}

void OSProcessSpawner::pushArgument(
    Slang::String argument)
{
    // TODO(tfoley): handle cases where arguments need some escaping
    commandLine_.Append(" ");
    commandLine_.Append(argument);

    argumentList_.add(argument);
}

Slang::String OSProcessSpawner::getCommandLine()
{
    return commandLine_;
}

OSError OSProcessSpawner::spawnAndWaitForCompletion()
{
    SECURITY_ATTRIBUTES securityAttributes;
    securityAttributes.nLength = sizeof(securityAttributes);
    securityAttributes.lpSecurityDescriptor = nullptr;
    securityAttributes.bInheritHandle = true;

    // create stdout pipe for child process
    HANDLE childStdOutReadTmp = nullptr;
    HANDLE childStdOutWrite = nullptr;
    if (!CreatePipe(&childStdOutReadTmp, &childStdOutWrite, &securityAttributes, 0))
    {
        return kOSError_OperationFailed;
    }

    // create stderr pipe for child process
    HANDLE childStdErrReadTmp = nullptr;
    HANDLE childStdErrWrite = nullptr;
    if (!CreatePipe(&childStdErrReadTmp, &childStdErrWrite, &securityAttributes, 0))
    {
        return kOSError_OperationFailed;
    }

    // create stdin pipe for child process
    HANDLE childStdInRead = nullptr;
    HANDLE childStdInWriteTmp = nullptr;
    if (!CreatePipe(&childStdInRead, &childStdInWriteTmp, &securityAttributes, 0))
    {
        return kOSError_OperationFailed;
    }

    HANDLE currentProcess = GetCurrentProcess();

    // create a non-inheritable duplicate of the stdout reader
    HANDLE childStdOutRead = nullptr;
    if (!DuplicateHandle(
        currentProcess, childStdOutReadTmp,
        currentProcess, &childStdOutRead,
        0, FALSE, DUPLICATE_SAME_ACCESS))
    {
        return kOSError_OperationFailed;
    }
    if (!CloseHandle(childStdOutReadTmp))
    {
        return kOSError_OperationFailed;
    }

    // create a non-inheritable duplicate of the stderr reader
    HANDLE childStdErrRead = nullptr;
    if (!DuplicateHandle(
        currentProcess, childStdErrReadTmp,
        currentProcess, &childStdErrRead,
        0, FALSE, DUPLICATE_SAME_ACCESS))
    {
        return kOSError_OperationFailed;
    }
    if (!CloseHandle(childStdErrReadTmp))
    {
        return kOSError_OperationFailed;
    }

    // create a non-inheritable duplicate of the stdin writer
    HANDLE childStdInWrite = nullptr;
    if (!DuplicateHandle(
        currentProcess, childStdInWriteTmp,
        currentProcess, &childStdInWrite,
        0, FALSE, DUPLICATE_SAME_ACCESS))
    {
        return kOSError_OperationFailed;
    }
    if (!CloseHandle(childStdInWriteTmp))
    {
        return kOSError_OperationFailed;
    }

    // Now we can actually get around to starting a process
    PROCESS_INFORMATION processInfo;
    ZeroMemory(&processInfo, sizeof(processInfo));

    // TODO: switch to proper wide-character versions of these...
    STARTUPINFOW startupInfo;
    ZeroMemory(&startupInfo, sizeof(startupInfo));
    startupInfo.cb = sizeof(startupInfo);
    startupInfo.hStdError = childStdErrWrite;
    startupInfo.hStdOutput = childStdOutWrite;
    startupInfo.hStdInput = childStdInRead;
    startupInfo.dwFlags = STARTF_USESTDHANDLES;

    // `CreateProcess` requires write access to this, for some reason...
    BOOL success = CreateProcessW(
        isExecutablePath_ ? executableName_.toWString().begin() : nullptr,
        (LPWSTR)commandLine_.ToString().toWString().begin(),
        nullptr,
        nullptr,
        true,
        CREATE_NO_WINDOW,
        nullptr, // TODO: allow specifying environment variables?
        nullptr,
        &startupInfo,
        &processInfo);
    if (!success)
    {
        return kOSError_OperationFailed;
    }

    // close handles we are now done with
    CloseHandle(processInfo.hThread);
    CloseHandle(childStdOutWrite);
    CloseHandle(childStdErrWrite);
    CloseHandle(childStdInRead);

    // Create a thread to read from the child's stdout.
    OSProcessSpawner_ReaderThreadInfo stdOutThreadInfo;
    stdOutThreadInfo.file = childStdOutRead;
    HANDLE stdOutThread = CreateThread(nullptr, 0, &osReaderThreadProc, (LPVOID)&stdOutThreadInfo, 0, nullptr);

    // Create a thread to read from the child's stderr.
    OSProcessSpawner_ReaderThreadInfo stdErrThreadInfo;
    stdErrThreadInfo.file = childStdErrRead;
    HANDLE stdErrThread = CreateThread(nullptr, 0, &osReaderThreadProc, (LPVOID)&stdErrThreadInfo, 0, nullptr);

    // wait for the process to exit
    // TODO: set a timeout as a safety measure...
    WaitForSingleObject(processInfo.hProcess, INFINITE);

    // get exit code for process
    DWORD childExitCode = 0;
    if (!GetExitCodeProcess(processInfo.hProcess, &childExitCode))
    {
        return kOSError_OperationFailed;
    }

    // wait for the reader threads
    WaitForSingleObject(stdOutThread, INFINITE);
    WaitForSingleObject(stdErrThread, INFINITE);

    CloseHandle(processInfo.hProcess);
    CloseHandle(childStdOutRead);
    CloseHandle(childStdErrRead);
    CloseHandle(childStdInWrite);

    standardOutput_ = stdOutThreadInfo.output;
    standardError_ = stdErrThreadInfo.output;
    resultCode_ = childExitCode;

    return kOSError_None;
}

char const* osGetExecutableSuffix()
{
    return ".exe";
}

#else

static bool advance(OSFindFilesResult& result)
{
    result.entry_ = readdir(result.directory_);
    return result.entry_ != NULL;
}

static bool checkValidResult(OSFindFilesResult& result)
{
//    fprintf(stderr, "checkValidResullt(%s)\n", result.entry_->d_name);

    if (strcmp(result.entry_->d_name, ".") == 0)
        return false;

    if (strcmp(result.entry_->d_name, "..") == 0)
        return false;

    String path = result.directoryPath_
        + String(result.entry_->d_name);

//    fprintf(stderr, "stat(%s)\n", path.getBuffer());
    struct stat fileInfo;
    if(stat(path.getBuffer(), &fileInfo) != 0)
        return false;

    if(S_ISDIR(fileInfo.st_mode))
        path = path + "/";


    result.filePath_ = path;
    return true;    
}

static bool adjustToValidResult(OSFindFilesResult& result)
{
    for (;;)
    {
        if(checkValidResult(result))
            return true;

        if (!advance(result))
            return false;
    }
}


bool OSFindFilesResult::findNextFile()
{
//    fprintf(stderr, "OSFindFilesResult::findNextFile()\n");
    if (!advance(*this)) return false;
    return adjustToValidResult(*this);
}

OSFindFilesResult osFindFilesInDirectory(
    Slang::String directoryPath)
{
    OSFindFilesResult result;

//    fprintf(stderr, "osFindFilesInDirectory(%s)\n", directoryPath.getBuffer());

    result.directory_ = opendir(directoryPath.getBuffer());
    if(!result.directory_)
    {
        result.entry_ = NULL;
        return result;
    }

    result.directoryPath_ = directoryPath;
    result.findNextFile();
    return result;
}

OSFindFilesResult osFindChildDirectories(
    Slang::String directoryPath)
{
    OSFindFilesResult result;

    result.directory_ = opendir(directoryPath.getBuffer());
    if(!result.directory_)
    {
        result.entry_ = NULL;
        return result;
    }

    // TODO: Set attributes to ignore everything but directories

    result.directoryPath_ = directoryPath;
    result.findNextFile();
    return result;
}

// OSProcessSpawner

void OSProcessSpawner::pushExecutableName(
    Slang::String executableName)
{
    executableName_ = executableName;
    arguments_.add(executableName);
    isExecutablePath_ = false;
}

void OSProcessSpawner::pushExecutablePath(
    Slang::String executablePath)
{
    executableName_ = executablePath;
    arguments_.add(executablePath);
    isExecutablePath_ = true;
}

void OSProcessSpawner::pushArgument(
    Slang::String argument)
{
    arguments_.add(argument);
    argumentList_.add(argument);
}

Slang::String OSProcessSpawner::getCommandLine()
{
    Slang::UInt argCount = arguments_.getCount();

    Slang::StringBuilder sb;
    for(Slang::UInt ii = 0; ii < argCount;  ++ii)
    {
        if(ii != 0) sb << " ";
        sb << arguments_[ii];
    }
    return sb.ProduceString();
}

OSError OSProcessSpawner::spawnAndWaitForCompletion()
{
    List<char const*> argPtrs;
    for(auto arg : arguments_)
    {
        argPtrs.add(arg.getBuffer());
    }
    argPtrs.add(NULL);

    int stdoutPipe[2];
    int stderrPipe[2];

    if(pipe(stdoutPipe) == -1)
        return kOSError_OperationFailed;

    if(pipe(stderrPipe) == -1)
        return kOSError_OperationFailed;

    pid_t childProcessID = fork();
    if (childProcessID == -1)
        return kOSError_OperationFailed;

    if(childProcessID == 0)
    {
        // We are the child process.

        dup2(stdoutPipe[1], STDOUT_FILENO);
        dup2(stderrPipe[1], STDERR_FILENO);

        close(stdoutPipe[0]);
        close(stdoutPipe[1]);

        close(stderrPipe[0]);
        close(stderrPipe[1]);

        execvp(
            argPtrs[0],
            (char* const*) &argPtrs[0]);

        // If we get here, then `exec` failed
        fprintf(stderr, "error: `exec` failed\n");
        exit(1);
    }
    else
    {
        // We are the parent process

        close(stdoutPipe[1]);
        close(stderrPipe[1]);

        int stdoutFD = stdoutPipe[0];
        int stderrFD = stderrPipe[0];

        pollfd pollInfos[2];
        nfds_t pollInfoCount = 2;

        pollInfos[0].fd = stdoutFD;
        pollInfos[0].events = POLLIN;
        pollInfos[0].revents = 0;
        pollInfos[1].fd = stderrFD;
        pollInfos[1].events = POLLIN;
        pollInfos[1].revents = 0;

        int remainingCount =  2;
        int iterations = 0;
        while(remainingCount)
        {
            // Safeguard against infinite loop:
            iterations++;
            if (iterations > 10000)
            {
                fprintf(stderr, "poll(): %d iterations\n", iterations);
                return kOSError_OperationFailed;
            }

            // Set a timeout of ten seconds;
            // we really shouldn't wait too long...
            int pollTimeout = 10000;
            int pollResult = poll(pollInfos, pollInfoCount, pollTimeout);
            if (pollResult <= 0)
            {
                // If there was a signal that got in
                // the way, then retry...
                if(pollResult == -1 && errno == EINTR)
                    continue;

                // timeout or error...
                return kOSError_OperationFailed;
            }

            enum { kBufferSize = 1024 };
            char buffer[kBufferSize];

            if(pollInfos[0].revents)
            {
                auto count = read(stdoutFD, buffer, kBufferSize);
                if (count <= 0)
                {
                    // end-of-file
                    close(stdoutFD);
                    pollInfos[0].fd = -1;
                    remainingCount--;
                }

                standardOutput_.append(
                    buffer, buffer + count);
            }

            if(pollInfos[1].revents)
            {
                auto count = read(stderrFD, buffer, kBufferSize);
                if (count <= 0)
                {
                    // end-of-file
                    close(stderrFD);
                    pollInfos[1].fd = -1;
                    remainingCount--;
                }

                standardError_.append(
                    buffer, buffer + count);
            }
        }

        int childStatus = 0;
        iterations = 0;
        for(;;)
        {
            // Safeguard against infinite loop:
            iterations++;
            if (iterations > 10000)
            {
                fprintf(stderr, "waitpid(): %d iterations\n", iterations);
                return kOSError_OperationFailed;
            }


            pid_t terminatedProcessID = waitpid(
                childProcessID,
                &childStatus,
                0);
            if (terminatedProcessID == -1)
            {
                return kOSError_OperationFailed;
            }

            if(terminatedProcessID == childProcessID)
            {
                if(WIFEXITED(childStatus))
                {
                    resultCode_ = (int)(int8_t)WEXITSTATUS(childStatus);
                }
                else
                {
                    resultCode_ = 1;
                }

                return kOSError_None;
            }
        }

    }

    return kOSError_OperationFailed;
}

char const* osGetExecutableSuffix()
{
    return "";
}

#endif