commit d4ce7f18b993640e671c31892122426ce685835f
parent 9499528b65fa47723e8392cf8c320ff6cdd96723
Author: sin <sin@2f30.org>
Date: Fri, 23 Mar 2018 11:52:58 +0000
Add -i to clear environment before exec
Diffstat:
M | Makefile | | | 4 | +++- |
A | arg.h | | | 50 | ++++++++++++++++++++++++++++++++++++++++++++++++++ |
M | pexec.c | | | 27 | +++++++++++++++------------ |
3 files changed, 68 insertions(+), 13 deletions(-)
diff --git a/Makefile b/Makefile
@@ -3,10 +3,12 @@ PREFIX = /usr/local
SRC = pexec.c
OBJ = pexec.o
BIN = pexec
-DISTFILES = $(SRC) Makefile
+DISTFILES = $(SRC) Makefile arg.h
all: $(BIN)
+pexec.o: arg.h
+
clean:
rm -f $(OBJ) $(BIN) $(BIN)-$(VERSION).tar.gz
diff --git a/arg.h b/arg.h
@@ -0,0 +1,50 @@
+/*
+ * Copy me if you can.
+ * by 20h
+ */
+
+#ifndef ARG_H__
+#define ARG_H__
+
+extern char *argv0;
+
+/* use main(int argc, char *argv[]) */
+#define ARGBEGIN for (argv0 = *argv, argv++, argc--;\
+ argv[0] && argv[0][0] == '-'\
+ && argv[0][1];\
+ argc--, argv++) {\
+ char argc_;\
+ char **argv_;\
+ int brk_;\
+ if (argv[0][1] == '-' && argv[0][2] == '\0') {\
+ argv++;\
+ argc--;\
+ break;\
+ }\
+ int i_;\
+ for (i_ = 1, brk_ = 0, argv_ = argv;\
+ argv[0][i_] && !brk_;\
+ i_++) {\
+ if (argv_ != argv)\
+ break;\
+ argc_ = argv[0][i_];\
+ switch (argc_)
+
+#define ARGEND }\
+ }
+
+#define ARGC() argc_
+
+#define EARGF(x) ((argv[0][i_+1] == '\0' && argv[1] == NULL)?\
+ ((x), abort(), (char *)0) :\
+ (brk_ = 1, (argv[0][i_+1] != '\0')?\
+ (&argv[0][i_+1]) :\
+ (argc--, argv++, argv[0])))
+
+#define ARGF() ((argv[0][i_+1] == '\0' && argv[1] == NULL)?\
+ (char *)0 :\
+ (brk_ = 1, (argv[0][i_+1] != '\0')?\
+ (&argv[0][i_+1]) :\
+ (argc--, argv++, argv[0])))
+
+#endif
diff --git a/pexec.c b/pexec.c
@@ -27,6 +27,9 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
+#include "arg.h"
+
+char *argv0;
static int
memfd_create(const char *name, unsigned int flags)
@@ -75,27 +78,27 @@ xwrite(int fd, const void *buf, size_t nbytes)
}
static void
-pexec(int fd, int argc, char *argv[], char *envp[])
-{
- if (fexecve(fd, argv, envp) < 0)
- err(1, "fexecve");
-}
-
-static void
usage(void)
{
- fprintf(stderr, "usage: pexec argv[0] [argv[1]...]\n");
+ fprintf(stderr, "usage: pexec [-i] argv[0] [argv[1]...]\n");
exit(1);
}
int
main(int argc, char *argv[])
{
+ char *envp[] = { NULL };
char buf[BUFSIZ];
ssize_t n;
- int fd;
+ int fd, iflag = 0;
- if (argc < 2)
+ ARGBEGIN {
+ case 'i':
+ iflag = 1;
+ break;
+ } ARGEND
+
+ if (argc == 0)
usage();
fd = memfd_create("exec", 0);
@@ -105,8 +108,8 @@ main(int argc, char *argv[])
while ((n = xread(STDIN_FILENO, buf, BUFSIZ)) > 0)
xwrite(fd, buf, n);
- argc--, argv++;
extern char **environ;
- pexec(fd, argc, argv, environ);
+ if (fexecve(fd, argv, iflag ? envp : environ) < 0)
+ err(1, "fexecve");
/* unreachable */
}