Subject: Re: [PATCH] Make locked paths absolute when current directory is changed

From: Junio C Hamano <[email-masked]>
Date: Fri, 18 Jul 2014 10:47:02 -0700

Nguyễn Thái Ngọc Duy  <[email-masked]> writes:

> Locked paths are saved in a linked list so that if something wrong
> happens, *.lock are removed. This works fine if we keep cwd the same,
> which is true 99% of time except:
>
>  - update-index and read-tree hold the lock on $GIT_DIR/index really
>    early, then later on may call setup_work_tree() to move cwd.
>
>  - Suppose a lock is being held (e.g. by "git add") then somewhere
>    down the line, somebody calls real_path (e.g. "link_alt_odb_entry"),
>    which temporarily moves cwd away and back.
>
> During that time when cwd is moved (either permanently or temporarily)
> and we decide to die(), attempts to remove relative *.lock will fail,
> and the next operation will complain that some files are still locked.
>
> Avoid this case by turning relative paths to absolute when chdir() is
> called (or soon to be called, in setup_git_directory_gently case).

The rationale makes sense.

> +extern void make_locked_paths_absolute(void);
> +static inline int chdir_safe(const char *path)
> +{
> +	make_locked_paths_absolute();
> +	return chdir(path);
> +}

Clever ;-).  Instead of making paths absolute when you receive
requests to lock them, you lazily turn the ones relative to cwd()
absolute just before they are about to become invalid/problematic
because the program wants to chdir.

> diff --git a/lockfile.c b/lockfile.c
> index 8fbcb6a..a70d107 100644
> --- a/lockfile.c
> +++ b/lockfile.c
> @@ -280,3 +280,19 @@ void rollback_lock_file(struct lock_file *lk)
>  	}
>  	lk->filename[0] = 0;
>  }
> +
> +void make_locked_paths_absolute(void)
> +{
> +	struct lock_file *lk;
> +	const char *abspath;
> +	for (lk = lock_file_list; lk != NULL; lk = lk->next) {
> +		if (!lk->filename[0] || lk->filename[0] == '/')
> +			continue;

Do we have to worry about Windows?

> +		abspath = absolute_path(lk->filename);
> +		if (strlen(abspath) >= sizeof(lk->filename))
> +			warning("locked path %s is relative when current directory "
> +				"is changed", lk->filename);

Shouldn't this be a die() or an error return (which will kill the
caller anyway)?

> @@ -636,6 +636,7 @@ static const char *setup_git_directory_gently_1(int *nongit_ok)
>  		die_errno("Unable to read current working directory");
>  	offset = len = strlen(cwd);
>  
> +	make_locked_paths_absolute();

Just being curious, but this early in the start-up sequence, what
files do we have locks on?