summaryrefslogtreecommitdiff
path: root/src/kash/shfork-win.c
blob: ce6df7b8936563c271d9d50ebc1d7fa5667cb8b6 (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


/*******************************************************************************
*   Header Files                                                               *
*******************************************************************************/
#include <string.h>
#include <locale.h>
#include "shinstance.h"
#include <Windows.h>

/*******************************************************************************
*   Defined Constants And Macros                                               *
*******************************************************************************/
/** The stack size. This is also defined in shforkA-win.asm. */
#define SHFORK_STACK_SIZE (1*1024*1024)


/*******************************************************************************
*   Global Variables                                                           *
*******************************************************************************/
static void *g_stack_base = 0;
static void *g_stack_limit = 0;


/*******************************************************************************
*   Internal Functions                                                         *
*******************************************************************************/
static void *shfork_string_to_ptr(const char *str, const char *argv0, const char *what);

/* in shforkA-win.asm: */
extern void shfork_resume(void *cur, void *base, void *limit);

/* called by shforkA-win.asm: */
void *shfork_maybe_forked(int argc, char **argv, char **envp);
extern int shfork_body(shinstance *psh, void *stack_ptr);


/***
 * Called by shforkA-win.asm to check whether we're a forked child
 * process or not.
 *
 * In the former case we will resume execution at the fork resume
 * point. In the latter we'll allocate a new stack of the forkable
 * heap and return it to the caller so real_main() in main.c can be
 * invoked on it.
 *
 * @returns Stack or not at all.
 * @param   argc    Argument count.
 * @param   argv    Argument vector.
 * @param   envp    Environment vector.
 */
void *shfork_maybe_forked(int argc, char **argv, char **envp)
{
    void *stack_ptr;

    /*
     * Are we actually forking?
     */
    if (    argc != 8
        ||  strcmp(argv[1], "--!forked!--")
        ||  strcmp(argv[2], "--stack-address")
        ||  strcmp(argv[4], "--stack-base")
        ||  strcmp(argv[6], "--stack-limit"))
    {
        char *stack;
        shheap_init();
        stack = (char *)sh_malloc(NULL, SHFORK_STACK_SIZE) + SHFORK_STACK_SIZE;
        g_stack_base = stack + SHFORK_STACK_SIZE;
        g_stack_limit = stack;
        return stack;
    }

    /*
     * Do any init that needs to be done before resuming the
     * fork() call.
     */
    setlocale(LC_ALL, "");

    /*
     * Convert the stack addresses.
     */
    stack_ptr     = shfork_string_to_ptr(argv[3], argv[0], "--stack-address");
    g_stack_base  = shfork_string_to_ptr(argv[5], argv[0], "--stack-base");
    g_stack_limit = shfork_string_to_ptr(argv[7], argv[0], "--stack-limit");

    /*
     * Switch stack and jump to the fork resume point.
     */
    shfork_resume(stack_ptr, g_stack_base, g_stack_limit);
    /* (won't get here) */
    return NULL;
}

/***
 * Converts a string into a pointer.
 *
 * @returns Pointer.
 * @param   argv0   The program name in case of error.
 * @param   str     The string to convert.
 */
static void *shfork_string_to_ptr(const char *str, const char *argv0, const char *what)
{
    const char *start = str;
    intptr_t ptr = 0;
    if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
        str += 2;
    while (*str)
    {
        unsigned digit;
        switch (*str)
        {
            case '0':            digit =   0; break;
            case '1':            digit =   1; break;
            case '2':            digit =   2; break;
            case '3':            digit =   3; break;
            case '4':            digit =   4; break;
            case '5':            digit =   5; break;
            case '6':            digit =   6; break;
            case '7':            digit =   7; break;
            case '8':            digit =   8; break;
            case '9':            digit =   9; break;
            case 'a': case 'A':  digit = 0xa; break;
            case 'b': case 'B':  digit = 0xb; break;
            case 'c': case 'C':  digit = 0xc; break;
            case 'd': case 'D':  digit = 0xd; break;
            case 'e': case 'E':  digit = 0xe; break;
            case 'f': case 'F':  digit = 0xf; break;
            default:
                fprintf(stderr, "%s: fatal error: Invalid %s '%s'\n", argv0, what, start);
                exit(2);
        }
        ptr <<= 4;
        ptr |= digit;
        str++;
    }
    return (void *)ptr;
}

/***
 * Create the child process making sure it inherits all our handles,
 * copy of the forkable heap and kick it off.
 *
 * Called by shfork_do_it() in shforkA-win.asm.
 *
 * @returns child pid on success, -1 and errno on failure.
 * @param   psh             The shell that's forking.
 * @param   stack_ptr       The stack address at which the guest is suppost to resume.
 */
int shfork_body(shinstance *psh, void *stack_ptr)
{
    PROCESS_INFORMATION ProcInfo;
    STARTUPINFO StrtInfo;
    intptr_t hndls[3];
    char szExeName[1024];
    char szCmdLine[1024+256];
    DWORD cch;
    int rc = 0;

    /*
     * Mark all handles inheritable and get the three standard handles.
     */
    shfile_fork_win(&psh->fdtab, 1 /* set */, &hndls[0]);

    /*
     * Create the process.
     */
    cch = GetModuleFileName(GetModuleHandle(NULL), szExeName, sizeof(szExeName));
    if (cch > 0)
    {
#if 0 /* quoting the program name doesn't seems to be working :/ */
        szCmdLine[0] = '"';
        memcpy(&szCmdLine[1], szExeName, cch);
        szCmdLine[++cch] = '"';
#else
        memcpy(&szCmdLine[0], szExeName, cch);
#endif
        cch += sprintf(&szCmdLine[cch], " --!forked!-- --stack-address %p --stack-base %p --stack-limit %p",
                       stack_ptr, g_stack_base, g_stack_limit);
        szCmdLine[cch+1] = '\0';

        memset(&StrtInfo, '\0', sizeof(StrtInfo)); /* just in case. */
        StrtInfo.cb = sizeof(StrtInfo);
        StrtInfo.lpReserved = NULL;
        StrtInfo.lpDesktop = NULL;
        StrtInfo.lpTitle = NULL;
        StrtInfo.dwX = 0;
        StrtInfo.dwY = 0;
        StrtInfo.dwXSize = 0;
        StrtInfo.dwYSize = 0;
        StrtInfo.dwXCountChars = 0;
        StrtInfo.dwYCountChars = 0;
        StrtInfo.dwFillAttribute = 0;
        StrtInfo.dwFlags = 0;
        StrtInfo.wShowWindow = 0;
        StrtInfo.cbReserved2 = 0;
        StrtInfo.lpReserved2 = NULL;
        StrtInfo.hStdInput  = (HANDLE)hndls[0];
        StrtInfo.hStdOutput = (HANDLE)hndls[1];
        StrtInfo.hStdError  = (HANDLE)hndls[2];
        if (CreateProcess(szExeName,
                          szCmdLine,
                          NULL,         /* pProcessAttributes */
                          NULL,         /* pThreadAttributes */
                          TRUE,         /* bInheritHandles */
                          CREATE_SUSPENDED,
                          NULL,         /* pEnvironment */
                          NULL,         /* pCurrentDirectory */
                          &StrtInfo,
                          &ProcInfo))
        {
            /*
             * Copy the memory to the child.
             */
            rc = shheap_fork_copy_to_child(ProcInfo.hProcess);
            if (!rc)
            {
                if (ResumeThread(ProcInfo.hThread) != (DWORD)-1)
                {
                    rc = sh_add_child(psh, ProcInfo.dwProcessId, ProcInfo.hProcess);
                    if (!rc)
                        rc = (int)ProcInfo.dwProcessId;
                }
                else
                {
                    DWORD dwErr = GetLastError();
                    fprintf(stderr, "shfork: ResumeThread() -> %d\n", dwErr);
                    errno = EINVAL;
                    rc = -1;
                }
            }
            if (rc == -1)
            {
                TerminateProcess(ProcInfo.hProcess, 127);
                /* needed?: ResumeThread(ProcInfo.hThread); */
                CloseHandle(ProcInfo.hProcess);
            }
            CloseHandle(ProcInfo.hThread);
        }
        else
        {
            DWORD dwErr = GetLastError();
            fprintf(stderr, "shfork: CreateProcess(%s) -> %d\n", szExeName, dwErr);
            errno = EINVAL;
            rc = -1;
        }
    }
    else
    {
        DWORD dwErr = GetLastError();
        fprintf(stderr, "shfork: GetModuleFileName() -> %d\n", dwErr);
        errno = EINVAL;
        rc = -1;
    }

    /*
     * Restore the handle inherit property.
     */
    shfile_fork_win(&psh->fdtab, 0 /* restore */, NULL);

    return rc;
}