1/* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements.  See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License.  You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <kernel/OS.h>
18#include <stdlib.h>
19#include <unistd.h>
20#include <stdio.h>
21
22struct pipefd {
23	int in;
24	int out;
25	int err;
26};
27
28int main(int argc, char *argv[]) {
29/* we expect the following...
30 *
31 * argv[0] = this stub
32 * argv[1] = directory to run in...
33 * argv[2] = progname to execute
34 * rest of arguments to be passed to program
35 */
36	char *progname = argv[2];
37	char *directory = argv[1];
38	struct pipefd *pfd;
39	thread_id sender;
40	void *buffer;
41	char ** newargs;
42	int i = 0;
43
44	newargs = (char**)malloc(sizeof(char*) * (argc - 1));
45
46	buffer = (void*)malloc(sizeof(struct pipefd));
47	/* this will block until we get the data */
48	receive_data(&sender, buffer, sizeof(struct pipefd));
49	pfd = (struct pipefd*)buffer;
50
51	if (pfd->in > STDERR_FILENO) {
52		if (dup2(pfd->in, STDIN_FILENO) != STDIN_FILENO) return (-1);
53	    close (pfd->in);
54	}
55	if (pfd->out > STDERR_FILENO) {
56		if (dup2(pfd->out, STDOUT_FILENO) != STDOUT_FILENO) return (-1);
57	    close (pfd->out);
58	}
59	if (pfd->err > STDERR_FILENO) {
60		if (dup2(pfd->err, STDERR_FILENO) != STDERR_FILENO) return (-1);
61	    close (pfd->err);
62	}
63
64	for	(i=3;i<=argc;i++){
65	    newargs[i-3] = argv[i];
66	}
67
68	/* tell the caller we're OK to start */
69	send_data(sender,1,NULL,0);
70
71	if (directory != NULL)
72		chdir(directory);
73	execve (progname, newargs, environ);
74
75	return (-1);
76}
77