summaryrefslogtreecommitdiffstats
path: root/src/kash/shfork-win.c
blob: 7ca0d56298273e77d6e8529d3db8e968ace1fe11 (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
/*******************************************************************************
*   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 pid_t shfork_do_it(shinstance *psh);
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);
extern void init_syntax(void);


/**
 * 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(NULL);
        g_stack_limit = stack = (char *)sh_malloc(NULL, SHFORK_STACK_SIZE);
        g_stack_base = stack += SHFORK_STACK_SIZE;
        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");
    kHlpAssert((uintptr_t)stack_ptr < (uintptr_t)g_stack_base);
    kHlpAssert((uintptr_t)stack_ptr > (uintptr_t)g_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;
}

/**
 * Do the fork.
 * @returns same as fork().
 * @param   psh             The shell that's forking.
 */
int shfork_do(shinstance *psh)
{
    /* save globals */
    void *pheap_head = shheap_get_head();
    pid_t pid = shfork_do_it(psh);
    if (pid == 0)
    {
        /* reinit stuff, only the heap is copied! */
        shthread_set_shell(psh);
        shheap_init(pheap_head);
        setlocale(LC_ALL, "");
        init_syntax();
        sh_init_globals();
    }
    return pid;
}

/**
 * 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;

    kHlpAssert((uintptr_t)stack_ptr < (uintptr_t)g_stack_base);
    kHlpAssert((uintptr_t)stack_ptr > (uintptr_t)g_stack_limit);

    /*
     * 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';
        TRACE2((NULL, "shfork_body: szCmdLine=%s\n", szCmdLine));

        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 = STARTF_USESTDHANDLES;;
        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, NULL);
                    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;
}