aboutsummaryrefslogtreecommitdiff
path: root/src/Exec.cpp
blob: 12e373d2aec64e3e5bdd0fcc8c37589b7335cfd5 (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
#include "../include/Exec.hpp"
#include "../include/env.hpp"

#if OS_FAMILY == OS_FAMILY_POSIX
#include <sys/wait.h>
#include <unistd.h>
#endif

using namespace std;

const int BUFSIZE = 4096;

// TODO: Redirect stderr to 
namespace sibs
{
#if OS_FAMILY == OS_FAMILY_POSIX
    Result<ExecResult> exec(const std::vector<FileString> &args, bool print_instead_of_pipe)
    {
        char buffer[BUFSIZE];
        std::string execStdout;

        if(args.empty())
            return Result<ExecResult>::Err("exec requires at least one argument (the program name)");

        std::vector<const char*> exec_args;
        for(const FileString &arg : args) {
            exec_args.push_back(arg.c_str());
        }
        exec_args.push_back(nullptr);

        int fd[2];
        if(!print_instead_of_pipe && pipe(fd) == -1)
            return Result<ExecResult>::Err(strerror(errno));

        pid_t pid = fork();
        if(pid == -1) {
            if(!print_instead_of_pipe) {
                close(fd[0]);
                close(fd[1]);
            }
            return Result<ExecResult>::Err("Failed to exec " + args[0] + " (failed to fork)");
        } else if(pid == 0) { // child
            if(!print_instead_of_pipe) {
                dup2(fd[1], STDOUT_FILENO);
                close(fd[0]);
                close(fd[1]);
            }
            execvp(exec_args[0], (char* const*)exec_args.data());
            perror("execvp");
            _exit(127);
        } else { // parent
            if(!print_instead_of_pipe)
                close(fd[1]);
        }

        if(!print_instead_of_pipe) {
            for(;;) {
                ssize_t bytes_read = read(fd[0], buffer, sizeof(buffer));
                if(bytes_read == 0) {
                    break;
                } else if(bytes_read == -1) {
                    std::string err_msg = "Failed to read from pipe to program " + args[0] + ", error: " + strerror(errno);
                    kill(pid, SIGTERM);
                    close(fd[0]);
                    return Result<ExecResult>::Err(err_msg);
                }

                execStdout.append(buffer, bytes_read);
            }
        }

        int status = 0;
        if(waitpid(pid, &status, 0) == -1) {
            std::string err_msg = std::string("waitpid failed, error: ") + strerror(errno);
            if(!print_instead_of_pipe)
                close(fd[0]);
            return Result<ExecResult>::Err(err_msg);
        }
        if(!print_instead_of_pipe)
            close(fd[0]);

        if(WIFEXITED(status))
        {
            int returned = WEXITSTATUS(status);
            ExecResult execResult;
            execResult.execStdout = move(execStdout);
            execResult.exitCode = returned;
            return Result<ExecResult>::Ok(execResult);
        }
        else if(WIFSIGNALED(status))
        {
            int signum = WSTOPSIG(status);
            string errMsg = "Exited due to receiving signal ";
            errMsg += to_string(signum);
            return Result<ExecResult>::Err(errMsg);
        }
        else if(WIFSTOPPED(status))
        {
            int signum = WSTOPSIG(status);
            string errMsg = "Stopped due to receiving signal ";
            errMsg += to_string(signum);
            return Result<ExecResult>::Err(errMsg);
        }
        else
        {
            string errMsg = "exec unexpected error on waitpid: ";
            errMsg += to_string(status);
            return Result<ExecResult>::Err(errMsg);
        }
    }

#else
    static FileString escape_arg(const FileString &arg) {
        FileString escaped = TINYDIR_STRING("\"");
        for(_tinydir_char_t c : arg) {
            if(c == '"') {
                escaped += TINYDIR_STRING("\"\"");
            } else {
                escaped += c;
            }
        }
        escaped += TINYDIR_STRING("\"");
        return escaped;
    }
    
    static FileString command_list_to_command_string(const std::vector<FileString> &args) {
        FileString cmd;
        for(size_t i = 0; i < args.size(); ++i) {
            if(i > 0)
                cmd += TINYDIR_STRING(" ");
            cmd += escape_arg(args[i]);
        }
        return cmd;
    }

    // Currently stdout is read in text mode so \n is replaced with \r\n, should we read in binary mode instead?
    Result<ExecResult> exec(const std::vector<FileString> &args, bool print_instead_of_pipe)
    {
        FileString cmdNonConst = command_list_to_command_string(args);
        std::string execStdout;

        SECURITY_ATTRIBUTES saAttr;
        saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
        saAttr.bInheritHandle = TRUE;
        saAttr.lpSecurityDescriptor = nullptr;

        HANDLE childReadHandle = nullptr;
        HANDLE childStdoutHandle = nullptr;

        if(!print_instead_of_pipe) {
            if (!CreatePipe(&childReadHandle, &childStdoutHandle, &saAttr, 0))
            {
                string errMsg = "exec unexpected error: ";
                errMsg += toUtf8(getLastErrorAsString());
                return Result<ExecResult>::Err(errMsg);
            }

            if (!SetHandleInformation(childReadHandle, HANDLE_FLAG_INHERIT, 0))
                goto cleanupAndExit;
        }

        PROCESS_INFORMATION piProcInfo;
        ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));

        STARTUPINFO siStartInfo;
        ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
        siStartInfo.cb = sizeof(STARTUPINFO);
        siStartInfo.hStdError = nullptr;
        siStartInfo.hStdOutput = print_instead_of_pipe ? nullptr : childStdoutHandle;
        siStartInfo.hStdInput = nullptr;
        siStartInfo.dwFlags |= STARTF_USESTDHANDLES;

        DWORD exitCode;

        if (!CreateProcessW(nullptr, (LPWSTR)cmdNonConst.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &siStartInfo, &piProcInfo))
            goto cleanupAndExit;

        if(!print_instead_of_pipe) {
            CloseHandle(childStdoutHandle);
            childStdoutHandle = nullptr;

            DWORD bytesRead;
            CHAR buffer[BUFSIZE];
            while (true)
            {
                BOOL bSuccess = ReadFile(childReadHandle, buffer, BUFSIZE, &bytesRead, nullptr);
                if (!bSuccess || bytesRead == 0)
                    break;

                execStdout.append(buffer, bytesRead);
                if (print)
                    printf("%.*s", bytesRead, buffer);
            }
        }

        WaitForSingleObject(piProcInfo.hProcess, INFINITE);
        GetExitCodeProcess(piProcInfo.hProcess, &exitCode);
        CloseHandle(piProcInfo.hProcess);
        CloseHandle(piProcInfo.hThread);

        {
            ExecResult execResult;
            execResult.execStdout = move(execStdout);
            execResult.exitCode = exitCode;
            CloseHandle(childReadHandle);
            return Result<ExecResult>::Ok(execResult);
        }

    cleanupAndExit:
        string errMsg = "exec unexpected error: ";
        errMsg += toUtf8(getLastErrorAsString());
        if(childReadHandle)
            CloseHandle(childReadHandle);
        if(childStdoutHandle)
            CloseHandle(childStdoutHandle);
        return Result<ExecResult>::Err(errMsg);
    }
#endif
}