os: hide SetFinalizer from users of Root

Currently Root embeds a root and calls SetFinalizer on &r.root. This
sets the finalizer on the outer root, which is visible to users of
os.Root, and thus they can mutate the finalizer attached to it.

This change modifies Root to not embed its inner root, but rather to
refer to it by pointer. This allows us to set the finalizer on this
independent inner object, preventing users of os.Root from changing the
finalizer. This follows the same pattern as os.File's finalizer.

Fixes #71617.

Change-Id: Ibd199bab1b3c877d5e12ef380fd4647b4e10221f
Reviewed-on: https://go-review.googlesource.com/c/go/+/647876
Auto-Submit: Michael Knyszek <mknyszek@google.com>
Reviewed-by: Damien Neil <dneil@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
This commit is contained in:
Michael Anthony Knyszek 2025-02-07 23:22:50 +00:00 committed by Gopher Robot
parent 47d0b0f2bf
commit a704d39b29
4 changed files with 6 additions and 6 deletions

View file

@ -60,7 +60,7 @@ func OpenInRoot(dir, name string) (*File, error) {
// - When GOOS=plan9 or GOOS=js, Root does not track directories across renames.
// On these platforms, a Root references a directory name, not a file descriptor.
type Root struct {
root root
root *root
}
const (

View file

@ -49,7 +49,7 @@ func newRoot(name string) (*Root, error) {
if !fi.IsDir() {
return nil, errors.New("not a directory")
}
return &Root{root{name: name}}, nil
return &Root{&root{name: name}}, nil
}
func (r *root) Close() error {

View file

@ -48,11 +48,11 @@ func newRoot(fd int, name string) (*Root, error) {
syscall.CloseOnExec(fd)
}
r := &Root{root{
r := &Root{&root{
fd: fd,
name: name,
}}
runtime.SetFinalizer(&r.root, (*root).Close)
runtime.SetFinalizer(r.root, (*root).Close)
return r, nil
}

View file

@ -105,11 +105,11 @@ func newRoot(fd syscall.Handle, name string) (*Root, error) {
return nil, &PathError{Op: "open", Path: name, Err: errors.New("not a directory")}
}
r := &Root{root{
r := &Root{&root{
fd: fd,
name: name,
}}
runtime.SetFinalizer(&r.root, (*root).Close)
runtime.SetFinalizer(r.root, (*root).Close)
return r, nil
}