summaryrefslogtreecommitdiffhomepage
path: root/src/builtin.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/builtin.c')
-rw-r--r--src/builtin.c34
1 files changed, 24 insertions, 10 deletions
diff --git a/src/builtin.c b/src/builtin.c
index 5cca7f8..887d7ce 100644
--- a/src/builtin.c
+++ b/src/builtin.c
@@ -793,22 +793,36 @@ static int b_cd(int argc, char **argv) {
* @param argc Argument count.
* @param argv Arguments.
* @param status Where the `cd` status goes.
- * @return false if the current directory could not be saved, in which case
- * the caller must use a forked subshell instead.
*/
-bool builtin_cd_isolated(int argc, char **argv, int *status) {
+void builtin_cd_isolated(int argc, char **argv, int *status) {
int cwd = open(".", O_RDONLY);
- if (cwd < 0)
- return false;
+ char path[PATH_MAX];
+ bool have_path = getcwd(path, sizeof path) != nullptr;
char *saved = xstrdup(get_curdir());
bool had_pwd = var_get("PWD") != nullptr;
bool had_oldpwd = var_get("OLDPWD") != nullptr;
char *pwd = had_pwd ? xstrdup(var_get("PWD")) : nullptr;
char *oldpwd = had_oldpwd ? xstrdup(var_get("OLDPWD")) : nullptr;
- *status = b_cd(argc, argv);
- if (fchdir(cwd) < 0)
- chdir(saved);
- close(cwd);
+ jmploc jl;
+ jmploc *prev = exc_handler;
+ int result;
+
+ if (setjmp(jl.buf) == 0) {
+ exc_handler = &jl;
+ result = b_cd(argc, argv);
+ } else {
+ /* b_cd raised; the directory may still have moved. */
+ result = exitstatus ? exitstatus : 2;
+ }
+ exc_handler = prev;
+
+ bool restored = cwd >= 0 && fchdir(cwd) == 0;
+ if (cwd >= 0)
+ close(cwd);
+ if (!restored)
+ restored = chdir(saved) == 0;
+ if (!restored && have_path)
+ (void)chdir(path);
if (had_pwd)
var_set("PWD", pwd, V_EXPORT);
else
@@ -821,7 +835,7 @@ bool builtin_cd_isolated(int argc, char **argv, int *status) {
curdir = saved;
free(pwd);
free(oldpwd);
- return true;
+ *status = result;
}
/**