[release-branch.go1.24] 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>
(cherry picked from commit a704d39b29)
Reviewed-on: https://go-review.googlesource.com/c/go/+/648135
TryBot-Bypass: Michael Knyszek <mknyszek@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
This commit is contained in:
Michael Anthony Knyszek 2025-02-07 23:22:50 +00:00 committed by Michael Knyszek
parent b7b4c60585
commit 6d399e9da6
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. // - 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. // On these platforms, a Root references a directory name, not a file descriptor.
type Root struct { type Root struct {
root root root *root
} }
const ( const (

View File

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

View File

@ -48,11 +48,11 @@ func newRoot(fd int, name string) (*Root, error) {
syscall.CloseOnExec(fd) syscall.CloseOnExec(fd)
} }
r := &Root{root{ r := &Root{&root{
fd: fd, fd: fd,
name: name, name: name,
}} }}
runtime.SetFinalizer(&r.root, (*root).Close) runtime.SetFinalizer(r.root, (*root).Close)
return r, nil 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")} return nil, &PathError{Op: "open", Path: name, Err: errors.New("not a directory")}
} }
r := &Root{root{ r := &Root{&root{
fd: fd, fd: fd,
name: name, name: name,
}} }}
runtime.SetFinalizer(&r.root, (*root).Close) runtime.SetFinalizer(r.root, (*root).Close)
return r, nil return r, nil
} }