about summary refs log tree commit diff
path: root/src/rt/rust_run_program.cpp
blob: 7b73586e9c855fb38dd19aa3c86a2e7cc57cb3b5 (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
#include "rust_internal.h"

#if defined(__WIN32__)

#include <process.h>
#include <io.h>

extern "C" CDECL int
rust_run_program(void* task, const char* argv[],
                 int in_fd, int out_fd, int err_fd) {
    STARTUPINFO si;
    ZeroMemory(&si, sizeof(STARTUPINFO));
    si.cb = sizeof(STARTUPINFO);
    si.dwFlags = STARTF_USESTDHANDLES;
    si.hStdInput = (HANDLE)_get_osfhandle(in_fd ? in_fd : 0);
    si.hStdOutput = (HANDLE)_get_osfhandle(out_fd ? out_fd : 1);
    si.hStdError = (HANDLE)_get_osfhandle(err_fd ? err_fd : 2);

    size_t cmd_len = 0;
    for (const char** arg = argv; *arg; arg++) {
        cmd_len += strlen(*arg);
        cmd_len++; // Space or \0
    }
    char* cmd = (char*)malloc(cmd_len);
    char* pos = cmd;
    for (const char** arg = argv; *arg; arg++) {
        strcpy(pos, *arg);
        pos += strlen(*arg);
        if (*(arg+1)) *(pos++) = ' ';
    }

    PROCESS_INFORMATION pi;
    BOOL created = CreateProcess(NULL, cmd, NULL, NULL, TRUE,
                                 0, NULL, NULL, &si, &pi);
    free(cmd);

    if (!created) return -1;
    return (int)pi.hProcess;
}

extern "C" CDECL int
rust_process_wait(void* task, int proc) {
    DWORD status;
    while (true) {
        if (GetExitCodeProcess((HANDLE)proc, &status) &&
            status != STILL_ACTIVE)
            return (int)status;
        WaitForSingleObject((HANDLE)proc, INFINITE);
    }
}

#elif defined(__GNUC__)

#include <sys/file.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <termios.h>

extern "C" CDECL int
rust_run_program(rust_task* task, char* argv[],
                 int in_fd, int out_fd, int err_fd) {
    int pid = fork();
    if (pid != 0) return pid;

    sigset_t sset;
    sigemptyset(&sset);
    sigprocmask(SIG_SETMASK, &sset, NULL);

    if (in_fd) dup2(in_fd, 0);
    if (out_fd) dup2(out_fd, 1);
    if (err_fd) dup2(err_fd, 2);
    /* Close all other fds. */
    for (int fd = getdtablesize() - 1; fd >= 3; fd--) close(fd);
    execvp(argv[0], argv);
    exit(1);
}

extern "C" CDECL int
rust_process_wait(void* task, int proc) {
    // FIXME: stub; exists to placate linker.
    return 0;
}

#else
#error "Platform not supported."
#endif

//
// Local Variables:
// mode: C++
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C .. 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
//