Resolve argv[0] based on path search in ape-m1

This commit is contained in:
Justine Tunney 2023-06-16 16:58:30 -07:00
parent 1353db7d3f
commit 7bc20bff3e
No known key found for this signature in database
GPG key ID: BE714B4575D6E328
2 changed files with 23 additions and 11 deletions

View file

@ -687,6 +687,24 @@ int main(int argc, char **argv, char **envp) {
argv = (char **)((sp += 1) + 1);
}
// search for executable
if (!(exe = Commandv(&M->ps, prog, GetEnv(envp, "PATH")))) {
Pexit(prog, 0, "not found (maybe chmod +x)");
} else if ((fd = openat(AT_FDCWD, exe, O_RDONLY)) < 0) {
Pexit(exe, -1, "open");
} else if ((rc = read(fd, M->ehdr.buf, sizeof(M->ehdr.buf))) < 0) {
Pexit(exe, -1, "read");
} else if (rc != sizeof(M->ehdr.buf)) {
Pexit(exe, 0, "too small");
}
// resolve argv[0] to reflect path search
if (argc > 0 && *prog != '/' && *exe == '/' && !StrCmp(prog, argv[0])) {
tp -= (n = StrLen(exe) + 1);
MemMove(tp, exe, n);
argv[0] = tp;
}
// squeeze and align the argument block
ip = (long *)(((long)tp - AUXV_BYTES) & -sizeof(long));
ip -= (n = bp - sp);
@ -699,17 +717,6 @@ int main(int argc, char **argv, char **envp) {
MemMove(M->rando, rando, sizeof(M->rando));
MemSet(rando, 0, sizeof(rando));
// search for executable
if (!(exe = Commandv(&M->ps, prog, GetEnv(envp, "PATH")))) {
Pexit(prog, 0, "not found (maybe chmod +x)");
} else if ((fd = openat(AT_FDCWD, exe, O_RDONLY)) < 0) {
Pexit(exe, -1, "open");
} else if ((rc = read(fd, M->ehdr.buf, sizeof(M->ehdr.buf))) < 0) {
Pexit(exe, -1, "read");
} else if (rc != sizeof(M->ehdr.buf)) {
Pexit(exe, 0, "too small");
}
#if TROUBLESHOOT
for (i = 0; i < argc; ++i) {
Emit("argv = ");

View file

@ -123,6 +123,11 @@ static inline void GetProgramExecutableNameImpl(char *p, char *e) {
return;
}
}
// otherwise give up and just copy argv[0] into it
if (!*p && __argv[0] && strlen(__argv[0]) < e - p) {
strcpy(p, __argv[0]);
}
}
/**