author
int64
658
755k
date
stringlengths
19
19
timezone
int64
-46,800
43.2k
hash
stringlengths
40
40
message
stringlengths
5
490
mods
list
language
stringclasses
20 values
license
stringclasses
3 values
repo
stringlengths
5
68
original_message
stringlengths
12
491
259,884
15.09.2020 19:47:49
25,200
c053c4bb03819a9b9bb4d485000789cb653cd9c7
Fix GitHub issue template. runsc -v doesn't work. It should be runsc -version
[ { "change_type": "MODIFY", "old_path": ".github/ISSUE_TEMPLATE/bug_report.md", "new_path": ".github/ISSUE_TEMPLATE/bug_report.md", "diff": "@@ -23,7 +23,7 @@ reproduced with software that is publicly available.\nPlease include the following details of your environment:\n-* `runsc -v`\n+* `runsc -version`\n* `docker version` or `docker info` (if available)\n* `kubectl version` and `kubectl get nodes` (if using Kubernetes)\n* `uname -a`\n" } ]
Go
Apache License 2.0
google/gvisor
Fix GitHub issue template. runsc -v doesn't work. It should be runsc -version PiperOrigin-RevId: 331911035
259,990
15.09.2020 20:50:07
25,200
b8dc9a889f3d945bcd0f02f8ca34eb2e579e8b0e
Use container ID as cgroup name if not provided Useful when you want to run multiple containers with the same config. And runc does that too.
[ { "change_type": "MODIFY", "old_path": "runsc/container/container.go", "new_path": "runsc/container/container.go", "diff": "@@ -311,6 +311,10 @@ func New(conf *boot.Config, args Args) (*Container, error) {\nif isRoot(args.Spec) {\nlog.Debugf(\"Creating new sandbox for container %q\", args.ID)\n+ if args.Spec.Linux != nil && args.Spec.Linux.CgroupsPath == \"\" {\n+ args.Spec.Linux.CgroupsPath = \"/\" + args.ID\n+ }\n+\n// Create and join cgroup before processes are created to ensure they are\n// part of the cgroup from the start (and all their children processes).\ncg, err := cgroup.New(args.Spec)\n" } ]
Go
Apache License 2.0
google/gvisor
Use container ID as cgroup name if not provided Useful when you want to run multiple containers with the same config. And runc does that too.
259,992
16.09.2020 07:45:28
25,200
326a1dbb73addeaf8e51af55b8a9de95638b4017
Refactor removed default test dimension ptrace was always selected as a dimension before, but not anymore. Some tests were specifying "overlay" expecting that to be in addition to the default.
[ { "change_type": "MODIFY", "old_path": "runsc/container/container_test.go", "new_path": "runsc/container/container_test.go", "diff": "@@ -293,22 +293,20 @@ var (\nfunc configs(t *testing.T, opts ...configOption) map[string]*config.Config {\n// Always load the default config.\ncs := make(map[string]*config.Config)\n+ testutil.TestConfig(t)\nfor _, o := range opts {\n+ c := testutil.TestConfig(t)\nswitch o {\ncase overlay:\n- c := testutil.TestConfig(t)\nc.Overlay = true\ncs[\"overlay\"] = c\ncase ptrace:\n- c := testutil.TestConfig(t)\nc.Platform = platforms.Ptrace\ncs[\"ptrace\"] = c\ncase kvm:\n- c := testutil.TestConfig(t)\nc.Platform = platforms.KVM\ncs[\"kvm\"] = c\ncase nonExclusiveFS:\n- c := testutil.TestConfig(t)\nc.FileAccess = config.FileAccessShared\ncs[\"non-exclusive\"] = c\ndefault:\n@@ -513,7 +511,7 @@ func TestExePath(t *testing.T) {\nt.Fatalf(\"error making directory: %v\", err)\n}\n- for name, conf := range configsWithVFS2(t, overlay) {\n+ for name, conf := range configsWithVFS2(t, all...) {\nt.Run(name, func(t *testing.T) {\nfor _, test := range []struct {\npath string\n@@ -838,7 +836,7 @@ func TestExecProcList(t *testing.T) {\n// TestKillPid verifies that we can signal individual exec'd processes.\nfunc TestKillPid(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, overlay) {\n+ for name, conf := range configsWithVFS2(t, all...) {\nt.Run(name, func(t *testing.T) {\napp, err := testutil.FindFile(\"test/cmd/test_app/test_app\")\nif err != nil {\n@@ -1471,7 +1469,7 @@ func TestRunNonRoot(t *testing.T) {\n// TestMountNewDir checks that runsc will create destination directory if it\n// doesn't exit.\nfunc TestMountNewDir(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, overlay) {\n+ for name, conf := range configsWithVFS2(t, all...) {\nt.Run(name, func(t *testing.T) {\nroot, err := ioutil.TempDir(testutil.TmpDir(), \"root\")\nif err != nil {\n@@ -2038,7 +2036,7 @@ func doDestroyStartingTest(t *testing.T, vfs2 bool) {\n}\nfunc TestCreateWorkingDir(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, overlay) {\n+ for name, conf := range configsWithVFS2(t, all...) {\nt.Run(name, func(t *testing.T) {\ntmpDir, err := ioutil.TempDir(testutil.TmpDir(), \"cwd-create\")\nif err != nil {\n@@ -2153,7 +2151,7 @@ func TestMountPropagation(t *testing.T) {\n}\nfunc TestMountSymlink(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, overlay) {\n+ for name, conf := range configsWithVFS2(t, all...) {\nt.Run(name, func(t *testing.T) {\ndir, err := ioutil.TempDir(testutil.TmpDir(), \"mount-symlink\")\nif err != nil {\n" } ]
Go
Apache License 2.0
google/gvisor
Refactor removed default test dimension ptrace was always selected as a dimension before, but not anymore. Some tests were specifying "overlay" expecting that to be in addition to the default. PiperOrigin-RevId: 332004111
259,983
14.08.2020 10:17:08
25,200
d928d3c00a66a29933eee9671e3558cd8163337f
Add function generating array of iovec with different FUSE structs This commit adds a function in the newly created fuse_util library, which accepts a variable number of arguments and data structures. Fixes
[ { "change_type": "MODIFY", "old_path": "test/fuse/linux/BUILD", "new_path": "test/fuse/linux/BUILD", "diff": "@@ -12,6 +12,7 @@ cc_binary(\ndeps = [\ngtest,\n\":fuse_base\",\n+ \"//test/util:fuse_util\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n],\n@@ -24,6 +25,7 @@ cc_library(\nhdrs = [\"fuse_base.h\"],\ndeps = [\ngtest,\n+ \"//test/util:fuse_util\",\n\"//test/util:posix_error\",\n\"//test/util:temp_path\",\n\"//test/util:test_util\",\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/fuse_base.cc", "new_path": "test/fuse/linux/fuse_base.cc", "diff": "#include \"absl/strings/str_format.h\"\n#include \"gtest/gtest.h\"\n+#include \"test/util/fuse_util.h\"\n#include \"test/util/posix_error.h\"\n#include \"test/util/temp_path.h\"\n#include \"test/util/test_util.h\"\n@@ -137,7 +138,6 @@ PosixError FuseTest::ServerConsumeFuseInit() {\nRETURN_ERROR_IF_SYSCALL_FAIL(\nRetryEINTR(read)(dev_fd_, buf.data(), buf.size()));\n- struct iovec iov_out[2];\nstruct fuse_out_header out_header = {\n.len = sizeof(struct fuse_out_header) + sizeof(struct fuse_init_out),\n.error = 0,\n@@ -148,12 +148,10 @@ PosixError FuseTest::ServerConsumeFuseInit() {\nstruct fuse_init_out out_payload = {\n.major = 7,\n};\n- iov_out[0].iov_len = sizeof(out_header);\n- iov_out[0].iov_base = &out_header;\n- iov_out[1].iov_len = sizeof(out_payload);\n- iov_out[1].iov_base = &out_payload;\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload);\n- RETURN_ERROR_IF_SYSCALL_FAIL(RetryEINTR(writev)(dev_fd_, iov_out, 2));\n+ RETURN_ERROR_IF_SYSCALL_FAIL(\n+ RetryEINTR(writev)(dev_fd_, iov_out.data(), iov_out.size()));\nreturn NoError();\n}\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/stat_test.cc", "new_path": "test/fuse/linux/stat_test.cc", "diff": "#include \"gtest/gtest.h\"\n#include \"test/fuse/linux/fuse_base.h\"\n+#include \"test/util/fuse_util.h\"\n#include \"test/util/test_util.h\"\nnamespace gvisor {\n@@ -43,16 +44,10 @@ class StatTest : public FuseTest {\nTEST_F(StatTest, StatNormal) {\n// Set up fixture.\n- std::vector<struct iovec> iov_in(2);\n- std::vector<struct iovec> iov_out(2);\nmode_t expected_mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;\nstruct timespec atime = {.tv_sec = 1595436289, .tv_nsec = 134150844};\nstruct timespec mtime = {.tv_sec = 1595436290, .tv_nsec = 134150845};\nstruct timespec ctime = {.tv_sec = 1595436291, .tv_nsec = 134150846};\n- struct fuse_out_header out_header = {\n- .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_attr_out),\n- .error = 0,\n- };\nstruct fuse_attr attr = {\n.ino = 1,\n.size = 512,\n@@ -70,14 +65,13 @@ TEST_F(StatTest, StatNormal) {\n.rdev = 12,\n.blksize = 4096,\n};\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_attr_out),\n+ };\nstruct fuse_attr_out out_payload = {\n.attr = attr,\n};\n- iov_out[0].iov_len = sizeof(out_header);\n- iov_out[0].iov_base = &out_header;\n- iov_out[1].iov_len = sizeof(out_payload);\n- iov_out[1].iov_base = &out_payload;\n-\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload);\nSetServerResponse(FUSE_GETATTR, iov_out);\n// Do integration test.\n@@ -104,10 +98,7 @@ TEST_F(StatTest, StatNormal) {\n// Check FUSE request.\nstruct fuse_in_header in_header;\nstruct fuse_getattr_in in_payload;\n- iov_in[0].iov_len = sizeof(in_header);\n- iov_in[0].iov_base = &in_header;\n- iov_in[1].iov_len = sizeof(in_payload);\n- iov_in[1].iov_base = &in_payload;\n+ auto iov_in = FuseGenerateIovecs(in_header, in_payload);\nGetServerActualRequest(iov_in);\nEXPECT_EQ(in_header.opcode, FUSE_GETATTR);\n@@ -117,14 +108,11 @@ TEST_F(StatTest, StatNormal) {\nTEST_F(StatTest, StatNotFound) {\n// Set up fixture.\n- std::vector<struct iovec> iov_in(2);\n- std::vector<struct iovec> iov_out(1);\nstruct fuse_out_header out_header = {\n.len = sizeof(struct fuse_out_header),\n.error = -ENOENT,\n};\n- iov_out[0].iov_len = sizeof(out_header);\n- iov_out[0].iov_base = &out_header;\n+ auto iov_out = FuseGenerateIovecs(out_header);\nSetServerResponse(FUSE_GETATTR, iov_out);\n// Do integration test.\n@@ -135,10 +123,7 @@ TEST_F(StatTest, StatNotFound) {\n// Check FUSE request.\nstruct fuse_in_header in_header;\nstruct fuse_getattr_in in_payload;\n- iov_in[0].iov_len = sizeof(in_header);\n- iov_in[0].iov_base = &in_header;\n- iov_in[1].iov_len = sizeof(in_payload);\n- iov_in[1].iov_base = &in_payload;\n+ auto iov_in = FuseGenerateIovecs(in_header, in_payload);\nGetServerActualRequest(iov_in);\nEXPECT_EQ(in_header.opcode, FUSE_GETATTR);\n" }, { "change_type": "MODIFY", "old_path": "test/util/BUILD", "new_path": "test/util/BUILD", "diff": "@@ -45,6 +45,12 @@ cc_library(\n],\n)\n+cc_library(\n+ name = \"fuse_util\",\n+ testonly = 1,\n+ hdrs = [\"fuse_util.h\"],\n+)\n+\ncc_library(\nname = \"proc_util\",\ntestonly = 1,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/util/fuse_util.h", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#ifndef GVISOR_TEST_UTIL_FUSE_UTIL_H_\n+#define GVISOR_TEST_UTIL_FUSE_UTIL_H_\n+\n+#include <sys/uio.h>\n+\n+#include <string>\n+#include <vector>\n+\n+namespace gvisor {\n+namespace testing {\n+\n+// The fundamental generation function with a single argument. If passed by\n+// std::string or std::vector<char>, it will call specialized versions as\n+// implemented below.\n+template <typename T>\n+std::vector<struct iovec> FuseGenerateIovecs(T &first) {\n+ return {(struct iovec){.iov_base = &first, .iov_len = sizeof(first)}};\n+}\n+\n+// If an argument is of type std::string, it must be used in read-only scenario.\n+// Because we are setting up iovec, which contains the original address of a\n+// data structure, we have to drop const qualification. Usually used with\n+// variable-length payload data.\n+template <typename T = std::string>\n+std::vector<struct iovec> FuseGenerateIovecs(std::string &first) {\n+ // Pad one byte for null-terminate c-string.\n+ return {(struct iovec){.iov_base = const_cast<char *>(first.c_str()),\n+ .iov_len = first.size() + 1}};\n+}\n+\n+// If an argument is of type std::vector<char>, it must be used in write-only\n+// scenario and the size of the variable must be greater than or equal to the\n+// size of the expected data. Usually used with variable-length payload data.\n+template <typename T = std::vector<char>>\n+std::vector<struct iovec> FuseGenerateIovecs(std::vector<char> &first) {\n+ return {(struct iovec){.iov_base = first.data(), .iov_len = first.size()}};\n+}\n+\n+// A helper function to set up an array of iovec struct for testing purpose.\n+// Use variadic class template to generalize different numbers and different\n+// types of FUSE structs.\n+template <typename T, typename... Types>\n+std::vector<struct iovec> FuseGenerateIovecs(T &first, Types &...args) {\n+ auto first_iovec = FuseGenerateIovecs(first);\n+ auto iovecs = FuseGenerateIovecs(args...);\n+ first_iovec.insert(std::end(first_iovec), std::begin(iovecs),\n+ std::end(iovecs));\n+ return first_iovec;\n+}\n+\n+} // namespace testing\n+} // namespace gvisor\n+#endif // GVISOR_TEST_UTIL_FUSE_UTIL_H_\n" } ]
Go
Apache License 2.0
google/gvisor
Add function generating array of iovec with different FUSE structs This commit adds a function in the newly created fuse_util library, which accepts a variable number of arguments and data structures. Fixes #3609
259,853
13.08.2020 22:23:40
0
d6ee3ae6d797b7f66092971f395ef63f8a430c78
Implement FUSE_LOOKUP Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/fuse.go", "new_path": "pkg/abi/linux/fuse.go", "diff": "package linux\n+import \"gvisor.dev/gvisor/tools/go_marshal/marshal\"\n+\n// +marshal\ntype FUSEOpcode uint32\n// +marshal\ntype FUSEOpID uint64\n+// FUSE_ROOT_ID is the id of root inode.\n+const FUSE_ROOT_ID = 1\n+\n// Opcodes for FUSE operations. Analogous to the opcodes in include/linux/fuse.h.\nconst (\nFUSE_LOOKUP FUSEOpcode = 1\n@@ -301,3 +306,54 @@ type FUSEGetAttrOut struct {\n// Attr contains the metadata returned from the FUSE server\nAttr FUSEAttr\n}\n+\n+// FUSEEntryOut is the reply sent by the daemon to the kernel\n+// for FUSE_MKNOD, FUSE_MKDIR, FUSE_SYMLINK, FUSE_LINK and\n+// FUSE_LOOKUP.\n+//\n+// +marshal\n+type FUSEEntryOut struct {\n+ // NodeID is the ID for current inode.\n+ NodeID uint64\n+\n+ // Generation is the generation number of inode.\n+ // Used to identify an inode that have different ID at different time.\n+ Generation uint64\n+\n+ // EntryValid indicates timeout for an entry.\n+ EntryValid uint64\n+\n+ // AttrValid indicates timeout for an entry's attributes.\n+ AttrValid uint64\n+\n+ // EntryValidNsec indicates timeout for an entry in nanosecond.\n+ EntryValidNSec uint32\n+\n+ // AttrValidNsec indicates timeout for an entry's attributes in nanosecond.\n+ AttrValidNSec uint32\n+\n+ // Attr contains the attributes of an entry.\n+ Attr FUSEAttr\n+}\n+\n+// FUSELookupIn is the request sent by the kernel to the daemon\n+// to look up a file name.\n+//\n+// Dynamically-sized objects cannot be marshalled.\n+type FUSELookupIn struct {\n+ marshal.StubMarshallable\n+\n+ // Name is a file name to be looked up.\n+ Name string\n+}\n+\n+// MarshalUnsafe serializes r.name to the dst buffer.\n+func (r *FUSELookupIn) MarshalUnsafe(buf []byte) {\n+ copy(buf, []byte(r.Name))\n+}\n+\n+// SizeBytes is the size of the memory representation of FUSELookupIn.\n+// 1 extra byte for null-terminated string.\n+func (r *FUSELookupIn) SizeBytes() int {\n+ return len(r.Name) + 1\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "new_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "diff": "@@ -26,6 +26,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n+ \"gvisor.dev/gvisor/tools/go_marshal/marshal\"\n)\n// Name is the default filesystem name.\n@@ -165,7 +166,7 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\n}\n// root is the fusefs root directory.\n- root := fs.newInode(creds, fsopts.rootMode)\n+ root := fs.newRootInode(creds, fsopts.rootMode)\nreturn fs.VFSFilesystem(), root.VFSDentry(), nil\n}\n@@ -205,14 +206,28 @@ type inode struct {\nkernfs.InodeNotSymlink\nkernfs.OrderedChildren\n+ NodeID uint64\n+ dentry kernfs.Dentry\nlocks vfs.FileLocks\n- dentry kernfs.Dentry\n+ // the owning filesystem. fs is immutable.\n+ fs *filesystem\n}\n-func (fs *filesystem) newInode(creds *auth.Credentials, mode linux.FileMode) *kernfs.Dentry {\n- i := &inode{}\n- i.InodeAttrs.Init(creds, linux.UNNAMED_MAJOR, fs.devMinor, fs.NextIno(), linux.ModeDirectory|0755)\n+func (fs *filesystem) newRootInode(creds *auth.Credentials, mode linux.FileMode) *kernfs.Dentry {\n+ i := &inode{fs: fs}\n+ i.InodeAttrs.Init(creds, linux.UNNAMED_MAJOR, fs.devMinor, 1, linux.ModeDirectory|0755)\n+ i.OrderedChildren.Init(kernfs.OrderedChildrenOptions{})\n+ i.dentry.Init(i)\n+ i.NodeID = 1\n+\n+ return &i.dentry\n+}\n+\n+func (fs *filesystem) newInode(nodeID uint64, attr linux.FUSEAttr) *kernfs.Dentry {\n+ i := &inode{fs: fs, NodeID: nodeID}\n+ creds := auth.Credentials{EffectiveKGID: auth.KGID(attr.UID), EffectiveKUID: auth.KUID(attr.UID)}\n+ i.InodeAttrs.Init(&creds, linux.UNNAMED_MAJOR, fs.devMinor, fs.NextIno(), linux.FileMode(attr.Mode))\ni.OrderedChildren.Init(kernfs.OrderedChildrenOptions{})\ni.EnableLeakCheck()\ni.dentry.Init(i)\n@@ -231,6 +246,57 @@ func (i *inode) Open(ctx context.Context, rp *vfs.ResolvingPath, vfsd *vfs.Dentr\nreturn fd.VFSFileDescription(), nil\n}\n+// Lookup implements kernfs.Inode.Lookup.\n+func (i *inode) Lookup(ctx context.Context, name string) (*vfs.Dentry, error) {\n+ in := linux.FUSELookupIn{Name: name}\n+ return i.newEntry(ctx, name, 0, linux.FUSE_LOOKUP, &in)\n+}\n+\n+// IterDirents implements Inode.IterDirents.\n+func (inode) IterDirents(ctx context.Context, callback vfs.IterDirentsCallback, offset, relOffset int64) (int64, error) {\n+ return offset, nil\n+}\n+\n+// Valid implements Inode.Valid.\n+func (inode) Valid(ctx context.Context) bool {\n+ return true\n+}\n+\n+// newEntry calls FUSE server for entry creation and allocates corresponding entry according to response.\n+// Shared by FUSE_MKNOD, FUSE_MKDIR, FUSE_SYMLINK, FUSE_LINK and FUSE_LOOKUP.\n+func (i *inode) newEntry(ctx context.Context, name string, fileType linux.FileMode, opcode linux.FUSEOpcode, payload marshal.Marshallable) (*vfs.Dentry, error) {\n+ kernelTask := kernel.TaskFromContext(ctx)\n+ if kernelTask == nil {\n+ log.Warningf(\"fusefs.Inode.newEntry: couldn't get kernel task from context\", i.NodeID)\n+ return nil, syserror.EINVAL\n+ }\n+ req, err := i.fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), i.NodeID, opcode, payload)\n+ if err != nil {\n+ return nil, err\n+ }\n+ res, err := i.fs.conn.Call(kernelTask, req)\n+ if err != nil {\n+ return nil, err\n+ }\n+ if err := res.Error(); err != nil {\n+ return nil, err\n+ }\n+ out := linux.FUSEEntryOut{}\n+ if err := res.UnmarshalPayload(&out); err != nil {\n+ return nil, err\n+ }\n+ if opcode != linux.FUSE_LOOKUP && ((out.Attr.Mode&linux.S_IFMT)^uint32(fileType) != 0 || out.NodeID == 0 || out.NodeID == linux.FUSE_ROOT_ID) {\n+ return nil, syserror.EIO\n+ }\n+ child := i.fs.newInode(out.NodeID, out.Attr)\n+ if opcode == linux.FUSE_LOOKUP {\n+ i.dentry.InsertChildLocked(name, child)\n+ } else {\n+ i.dentry.InsertChild(name, child)\n+ }\n+ return child.VFSDentry(), nil\n+}\n+\n// statFromFUSEAttr makes attributes from linux.FUSEAttr to linux.Statx. The\n// opts.Sync attribute is ignored since the synchronization is handled by the\n// FUSE server.\n@@ -299,7 +365,7 @@ func (i *inode) Stat(ctx context.Context, fs *vfs.Filesystem, opts vfs.StatOptio\n// finally be translated into vfs.FilesystemImpl.StatAt() (see\n// pkg/sentry/syscalls/linux/vfs2/stat.go), resulting in the same flow\n// as stat(2). Thus GetAttrFlags and Fh variable will never be used in VFS2.\n- req, err := conn.NewRequest(creds, uint32(task.ThreadID()), i.Ino(), linux.FUSE_GETATTR, &in)\n+ req, err := conn.NewRequest(creds, uint32(task.ThreadID()), i.NodeID, linux.FUSE_GETATTR, &in)\nif err != nil {\nreturn linux.Statx{}, err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "diff": "@@ -140,7 +140,7 @@ func (fs *Filesystem) revalidateChildLocked(ctx context.Context, vfsObj *vfs.Vir\n}\n// Reference on childVFSD dropped by a corresponding Valid.\nchild = childVFSD.Impl().(*Dentry)\n- parent.insertChildLocked(name, child)\n+ parent.InsertChildLocked(name, child)\n}\nreturn child, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/kernfs.go", "new_path": "pkg/sentry/fsimpl/kernfs/kernfs.go", "diff": "@@ -246,15 +246,15 @@ func (d *Dentry) OnZeroWatches(context.Context) {}\n// Precondition: d must represent a directory inode.\nfunc (d *Dentry) InsertChild(name string, child *Dentry) {\nd.dirMu.Lock()\n- d.insertChildLocked(name, child)\n+ d.InsertChildLocked(name, child)\nd.dirMu.Unlock()\n}\n-// insertChildLocked is equivalent to InsertChild, with additional\n+// InsertChildLocked is equivalent to InsertChild, with additional\n// preconditions.\n//\n// Precondition: d.dirMu must be locked.\n-func (d *Dentry) insertChildLocked(name string, child *Dentry) {\n+func (d *Dentry) InsertChildLocked(name string, child *Dentry) {\nif !d.isDir() {\npanic(fmt.Sprintf(\"InsertChild called on non-directory Dentry: %+v.\", d))\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Implement FUSE_LOOKUP Fixes #3231 Co-authored-by: Boyuan He <[email protected]>
259,984
18.08.2020 01:46:39
0
32044f94e9dfbb88c17d07b235b8ed5b07d2ff18
Implement FUSE_OPEN/OPENDIR Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/fuse.go", "new_path": "pkg/abi/linux/fuse.go", "diff": "@@ -357,3 +357,41 @@ func (r *FUSELookupIn) MarshalUnsafe(buf []byte) {\nfunc (r *FUSELookupIn) SizeBytes() int {\nreturn len(r.Name) + 1\n}\n+\n+// MAX_NON_LFS indicates the maximum offset without large file support.\n+const MAX_NON_LFS = ((1 << 31) - 1)\n+\n+// flags returned by OPEN request.\n+const (\n+ // FOPEN_DIRECT_IO indicates bypassing page cache for this opened file.\n+ FOPEN_DIRECT_IO = 1 << 0\n+ // FOPEN_KEEP_CACHE avoids invalidate of data cache on open.\n+ FOPEN_KEEP_CACHE = 1 << 1\n+ // FOPEN_NONSEEKABLE indicates the file cannot be seeked.\n+ FOPEN_NONSEEKABLE = 1 << 2\n+)\n+\n+// FUSEOpenIn is the request sent by the kernel to the daemon,\n+// to negotiate flags and get file handle.\n+//\n+// +marshal\n+type FUSEOpenIn struct {\n+ // Flags of this open request.\n+ Flags uint32\n+\n+ _ uint32\n+}\n+\n+// FUSEOpenOut is the reply sent by the daemon to the kernel\n+// for FUSEOpenIn.\n+//\n+// +marshal\n+type FUSEOpenOut struct {\n+ // Fh is the file handler for opened file.\n+ Fh uint64\n+\n+ // OpenFlag for the opened file.\n+ OpenFlag uint32\n+\n+ _ uint32\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/BUILD", "new_path": "pkg/sentry/fsimpl/fuse/BUILD", "diff": "@@ -31,6 +31,7 @@ go_library(\nsrcs = [\n\"connection.go\",\n\"dev.go\",\n+ \"file.go\",\n\"fusefs.go\",\n\"init.go\",\n\"inode_refs.go\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/connection.go", "new_path": "pkg/sentry/fsimpl/fuse/connection.go", "diff": "@@ -78,8 +78,13 @@ type Response struct {\ntype connection struct {\nfd *DeviceFD\n+ // mu protect access to struct memebers.\n+ mu sync.Mutex\n+\n+ // attributeVersion is the version of connection's attributes.\n+ attributeVersion uint64\n+\n// The following FUSE_INIT flags are currently unsupported by this implementation:\n- // - FUSE_ATOMIC_O_TRUNC: requires open(..., O_TRUNC)\n// - FUSE_EXPORT_SUPPORT\n// - FUSE_HANDLE_KILLPRIV\n// - FUSE_POSIX_LOCKS: requires POSIX locks\n@@ -113,6 +118,11 @@ type connection struct {\n// TODO(gvisor.dev/issue/3185): abort all queued requests.\naborted bool\n+ // atomicOTrunc is true when FUSE does not send a separate SETATTR request\n+ // before open with O_TRUNC flag.\n+ // Negotiated and only set in INIT.\n+ atomicOTrunc bool\n+\n// connInitError if FUSE_INIT encountered error (major version mismatch).\n// Only set in INIT.\nconnInitError bool\n@@ -189,6 +199,10 @@ type connection struct {\n// dontMask if filestestem does not apply umask to creation modes.\n// Negotiated in INIT.\ndontMask bool\n+\n+ // noOpen if FUSE server doesn't support open operation.\n+ // This flag only influence performance, not correctness of the program.\n+ noOpen bool\n}\n// newFUSEConnection creates a FUSE connection to fd.\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fsimpl/fuse/file.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package fuse\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n+)\n+\n+// fileDescription implements vfs.FileDescriptionImpl for fuse.\n+type fileDescription struct {\n+ vfsfd vfs.FileDescription\n+ vfs.FileDescriptionDefaultImpl\n+ vfs.DentryMetadataFileDescriptionImpl\n+ vfs.NoLockFD\n+\n+ // the file handle used in userspace.\n+ Fh uint64\n+\n+ // Nonseekable is indicate cannot perform seek on a file.\n+ Nonseekable bool\n+\n+ // DirectIO suggest fuse to use direct io operation.\n+ DirectIO bool\n+\n+ // OpenFlag is the flag returned by open.\n+ OpenFlag uint32\n+}\n+\n+func (fd *fileDescription) dentry() *kernfs.Dentry {\n+ return fd.vfsfd.Dentry().Impl().(*kernfs.Dentry)\n+}\n+\n+func (fd *fileDescription) inode() *inode {\n+ return fd.dentry().Inode().(*inode)\n+}\n+\n+func (fd *fileDescription) filesystem() *vfs.Filesystem {\n+ return fd.vfsfd.VirtualDentry().Mount().Filesystem()\n+}\n+\n+// Release implements vfs.FileDescriptionImpl.Release.\n+func (fd *fileDescription) Release(ctx context.Context) {}\n+\n+// PRead implements vfs.FileDescriptionImpl.PRead.\n+func (fd *fileDescription) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts vfs.ReadOptions) (int64, error) {\n+ return 0, nil\n+}\n+\n+// Read implements vfs.FileDescriptionImpl.Read.\n+func (fd *fileDescription) Read(ctx context.Context, dst usermem.IOSequence, opts vfs.ReadOptions) (int64, error) {\n+ return 0, nil\n+}\n+\n+// PWrite implements vfs.FileDescriptionImpl.PWrite.\n+func (fd *fileDescription) PWrite(ctx context.Context, src usermem.IOSequence, offset int64, opts vfs.WriteOptions) (int64, error) {\n+ return 0, nil\n+}\n+\n+// Write implements vfs.FileDescriptionImpl.Write.\n+func (fd *fileDescription) Write(ctx context.Context, src usermem.IOSequence, opts vfs.WriteOptions) (int64, error) {\n+ return 0, nil\n+}\n+\n+// Seek implements vfs.FileDescriptionImpl.Seek.\n+func (fd *fileDescription) Seek(ctx context.Context, offset int64, whence int32) (int64, error) {\n+ return 0, nil\n+}\n+\n+// Stat implements FileDescriptionImpl.Stat.\n+// Stat implements vfs.FileDescriptionImpl.Stat.\n+func (fd *fileDescription) Stat(ctx context.Context, opts vfs.StatOptions) (linux.Statx, error) {\n+ fs := fd.filesystem()\n+ inode := fd.inode()\n+ return inode.Stat(ctx, fs, opts)\n+}\n+\n+// SetStat implements FileDescriptionImpl.SetStat.\n+func (fd *fileDescription) SetStat(ctx context.Context, opts vfs.SetStatOptions) error {\n+ return nil\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "new_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "diff": "@@ -17,6 +17,7 @@ package fuse\nimport (\n\"strconv\"\n+ \"sync/atomic\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n@@ -212,6 +213,18 @@ type inode struct {\n// the owning filesystem. fs is immutable.\nfs *filesystem\n+\n+ // size of the file.\n+ size uint64\n+\n+ // attributeVersion is the version of inode's attributes.\n+ attributeVersion uint64\n+\n+ // attributeTime is the remaining vaild time of attributes.\n+ attributeTime uint64\n+\n+ // version of the inode.\n+ version uint64\n}\nfunc (fs *filesystem) newRootInode(creds *auth.Credentials, mode linux.FileMode) *kernfs.Dentry {\n@@ -237,13 +250,87 @@ func (fs *filesystem) newInode(nodeID uint64, attr linux.FUSEAttr) *kernfs.Dentr\n// Open implements kernfs.Inode.Open.\nfunc (i *inode) Open(ctx context.Context, rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n- fd, err := kernfs.NewGenericDirectoryFD(rp.Mount(), vfsd, &i.OrderedChildren, &i.locks, &opts, kernfs.GenericDirectoryFDOptions{\n- SeekEnd: kernfs.SeekEndStaticEntries,\n- })\n+ isDir := i.InodeAttrs.Mode().IsDir()\n+ // return error if specified to open directory but inode is not a directory.\n+ if !isDir && opts.Mode.IsDir() {\n+ return nil, syserror.ENOTDIR\n+ }\n+ if opts.Flags&linux.O_LARGEFILE == 0 && atomic.LoadUint64(&i.size) > linux.MAX_NON_LFS {\n+ return nil, syserror.EOVERFLOW\n+ }\n+\n+ // FOPEN_KEEP_CACHE is the defualt flag for noOpen.\n+ fd := fileDescription{OpenFlag: linux.FOPEN_KEEP_CACHE}\n+ // Only send open request when FUSE server support open or is opening a directory.\n+ if !i.fs.conn.noOpen || isDir {\n+ kernelTask := kernel.TaskFromContext(ctx)\n+ if kernelTask == nil {\n+ log.Warningf(\"fusefs.Inode.Open: couldn't get kernel task from context\")\n+ return nil, syserror.EINVAL\n+ }\n+\n+ var opcode linux.FUSEOpcode\n+ if isDir {\n+ opcode = linux.FUSE_OPENDIR\n+ } else {\n+ opcode = linux.FUSE_OPEN\n+ }\n+ in := linux.FUSEOpenIn{Flags: opts.Flags & ^uint32(linux.O_CREAT|linux.O_EXCL|linux.O_NOCTTY)}\n+ if !i.fs.conn.atomicOTrunc {\n+ in.Flags &= ^uint32(linux.O_TRUNC)\n+ }\n+ req, err := i.fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), i.NodeID, opcode, &in)\n+ if err != nil {\n+ return nil, err\n+ }\n+\n+ res, err := i.fs.conn.Call(kernelTask, req)\nif err != nil {\nreturn nil, err\n}\n- return fd.VFSFileDescription(), nil\n+ if err := res.Error(); err == syserror.ENOSYS && !isDir {\n+ i.fs.conn.noOpen = true\n+ } else if err != nil {\n+ return nil, err\n+ } else {\n+ out := linux.FUSEOpenOut{}\n+ if err := res.UnmarshalPayload(&out); err != nil {\n+ return nil, err\n+ }\n+ fd.OpenFlag = out.OpenFlag\n+ fd.Fh = out.Fh\n+ }\n+ }\n+\n+ if isDir {\n+ fd.OpenFlag &= ^uint32(linux.FOPEN_DIRECT_IO)\n+ }\n+\n+ // TODO(gvisor.dev/issue/3234): invalidate mmap after implemented it for FUSE Inode\n+ fd.DirectIO = fd.OpenFlag&linux.FOPEN_DIRECT_IO != 0\n+ fdOptions := &vfs.FileDescriptionOptions{}\n+ if fd.OpenFlag&linux.FOPEN_NONSEEKABLE != 0 {\n+ fdOptions.DenyPRead = true\n+ fdOptions.DenyPWrite = true\n+ fd.Nonseekable = true\n+ }\n+\n+ // If we don't send SETATTR before open (which is indicated by atomicOTrunc)\n+ // and O_TRUNC is set, update the inode's version number and clean existing data\n+ // by setting the file size to 0.\n+ if i.fs.conn.atomicOTrunc && opts.Flags&linux.O_TRUNC != 0 {\n+ i.fs.conn.mu.Lock()\n+ i.fs.conn.attributeVersion++\n+ i.attributeVersion = i.fs.conn.attributeVersion\n+ atomic.StoreUint64(&i.size, 0)\n+ i.fs.conn.mu.Unlock()\n+ i.attributeTime = 0\n+ }\n+\n+ if err := fd.vfsfd.Init(&fd, opts.Flags, rp.Mount(), vfsd, fdOptions); err != nil {\n+ return nil, err\n+ }\n+ return &fd.vfsfd, nil\n}\n// Lookup implements kernfs.Inode.Lookup.\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/BUILD", "new_path": "test/fuse/BUILD", "diff": "@@ -6,3 +6,8 @@ syscall_test(\nfuse = \"True\",\ntest = \"//test/fuse/linux:stat_test\",\n)\n+\n+syscall_test(\n+ fuse = \"True\",\n+ test = \"//test/fuse/linux:open_test\",\n+)\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/BUILD", "new_path": "test/fuse/linux/BUILD", "diff": "@@ -18,6 +18,19 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"open_test\",\n+ testonly = 1,\n+ srcs = [\"open_test.cc\"],\n+ deps = [\n+ gtest,\n+ \":fuse_base\",\n+ \"//test/util:fuse_util\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n+\ncc_library(\nname = \"fuse_base\",\ntestonly = 1,\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/fuse_base.cc", "new_path": "test/fuse/linux/fuse_base.cc", "diff": "@@ -117,6 +117,16 @@ uint32_t FuseTest::GetServerTotalReceivedBytes() {\nstatic_cast<uint32_t>(FuseTestCmd::kGetTotalReceivedBytes));\n}\n+// Sends the `kSkipRequest` command to the FUSE server, which would skip\n+// current stored request data.\n+void FuseTest::SkipServerActualRequest() {\n+ uint32_t cmd = static_cast<uint32_t>(FuseTestCmd::kSkipRequest);\n+ EXPECT_THAT(RetryEINTR(write)(sock_[0], &cmd, sizeof(cmd)),\n+ SyscallSucceedsWithValue(sizeof(cmd)));\n+\n+ WaitServerComplete();\n+}\n+\n// Sends the `kSetInodeLookup` command, expected mode, and the path of the\n// inode to create under the mount point.\nvoid FuseTest::SetServerInodeLookup(const std::string& path, mode_t mode) {\n@@ -284,6 +294,9 @@ void FuseTest::ServerHandleCommand() {\ncase FuseTestCmd::kGetNumUnsentResponses:\nServerSendData(static_cast<uint32_t>(responses_.RemainingBlocks()));\nbreak;\n+ case FuseTestCmd::kSkipRequest:\n+ ServerSkipReceivedRequest();\n+ break;\ndefault:\nFAIL() << \"Unknown FuseTestCmd \" << cmd;\nbreak;\n@@ -314,32 +327,7 @@ void FuseTest::ServerReceiveInodeLookup() {\n.len = out_len,\n.error = 0,\n};\n- struct fuse_entry_out out_payload = {\n- .nodeid = nodeid_,\n- .generation = 0,\n- .entry_valid = 0,\n- .attr_valid = 0,\n- .entry_valid_nsec = 0,\n- .attr_valid_nsec = 0,\n- .attr =\n- (struct fuse_attr){\n- .ino = nodeid_,\n- .size = 512,\n- .blocks = 4,\n- .atime = 0,\n- .mtime = 0,\n- .ctime = 0,\n- .atimensec = 0,\n- .mtimensec = 0,\n- .ctimensec = 0,\n- .mode = mode,\n- .nlink = 2,\n- .uid = 1234,\n- .gid = 4321,\n- .rdev = 12,\n- .blksize = 4096,\n- },\n- };\n+ struct fuse_entry_out out_payload = DefaultEntryOut(mode, nodeid_);\n// Since this is only used in test, nodeid_ is simply increased by 1 to\n// comply with the unqiueness of different path.\n++nodeid_;\n@@ -363,6 +351,15 @@ void FuseTest::ServerSendReceivedRequest() {\nSyscallSucceedsWithValue(mem_block.len));\n}\n+// Skip the request pointed by current cursor.\n+void FuseTest::ServerSkipReceivedRequest() {\n+ if (requests_.End()) {\n+ FAIL() << \"No more received request.\";\n+ return;\n+ }\n+ requests_.Next();\n+}\n+\n// Handles FUSE request. Reads request from /dev/fuse, checks if it has the\n// same opcode as expected, and responds with the saved fake FUSE response.\n// The FUSE request is copied to the serial buffer and can be retrieved one-\n@@ -390,6 +387,7 @@ void FuseTest::ServerProcessFuseRequest() {\nrequests_.AddMemBlock(in_header->opcode, buf.data(), len);\n+ if (in_header->opcode == FUSE_RELEASE) return;\n// Check if there is a corresponding response.\nif (responses_.End()) {\nGTEST_NONFATAL_FAILURE_(\"No more FUSE response is expected\");\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/fuse_base.h", "new_path": "test/fuse/linux/fuse_base.h", "diff": "@@ -42,6 +42,7 @@ enum class FuseTestCmd {\nkGetNumUnconsumedRequests,\nkGetNumUnsentResponses,\nkGetTotalReceivedBytes,\n+ kSkipRequest,\n};\n// Holds the information of a memory block in a serial buffer.\n@@ -158,6 +159,10 @@ class FuseTest : public ::testing::Test {\n// bytes from /dev/fuse.\nuint32_t GetServerTotalReceivedBytes();\n+ // Called by the testing thread to ask the FUSE server to skip stored\n+ // request data.\n+ void SkipServerActualRequest();\n+\nprotected:\nTempPath mount_point_;\n@@ -211,6 +216,10 @@ class FuseTest : public ::testing::Test {\n// Sends a uint32_t data via socket.\ninline void ServerSendData(uint32_t data);\n+ // The FUSE server side's corresponding code of `SkipServerActualRequest()`.\n+ // Handles `kSkipRequest` command. Skip the request pointed by current cursor.\n+ void ServerSkipReceivedRequest();\n+\n// Handles FUSE request sent to /dev/fuse by its saved responses.\nvoid ServerProcessFuseRequest();\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/fuse/linux/open_test.cc", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <errno.h>\n+#include <fcntl.h>\n+#include <linux/fuse.h>\n+#include <sys/stat.h>\n+#include <sys/statfs.h>\n+#include <sys/types.h>\n+#include <unistd.h>\n+\n+#include <string>\n+\n+#include \"gtest/gtest.h\"\n+#include \"test/fuse/linux/fuse_base.h\"\n+#include \"test/util/fuse_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+class OpenTest : public FuseTest {\n+ protected:\n+ const std::string test_file_ = \"test_file\";\n+ const mode_t regular_file_ = S_IFREG | S_IRWXU | S_IRWXG | S_IRWXO;\n+\n+ struct fuse_open_out out_payload_ = {\n+ .fh = 1,\n+ .open_flags = O_RDWR,\n+ };\n+};\n+\n+TEST_F(OpenTest, RegularFile) {\n+ const std::string test_file_path =\n+ JoinPath(mount_point_.path().c_str(), test_file_);\n+ SetServerInodeLookup(test_file_, regular_file_);\n+\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_open_out),\n+ };\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload_);\n+ SetServerResponse(FUSE_OPEN, iov_out);\n+ FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(test_file_path.c_str(), O_RDWR));\n+\n+ struct fuse_in_header in_header;\n+ struct fuse_open_in in_payload;\n+ auto iov_in = FuseGenerateIovecs(in_header, in_payload);\n+ GetServerActualRequest(iov_in);\n+\n+ EXPECT_EQ(in_header.len, sizeof(in_header) + sizeof(in_payload));\n+ EXPECT_EQ(in_header.opcode, FUSE_OPEN);\n+ EXPECT_EQ(in_payload.flags, O_RDWR);\n+ EXPECT_THAT(fcntl(fd.get(), F_GETFL), SyscallSucceedsWithValue(O_RDWR));\n+}\n+\n+TEST_F(OpenTest, SetNoOpen) {\n+ const std::string test_file_path =\n+ JoinPath(mount_point_.path().c_str(), test_file_);\n+ SetServerInodeLookup(test_file_, regular_file_);\n+\n+ // ENOSYS indicates open is not implemented.\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_open_out),\n+ .error = -ENOSYS,\n+ };\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload_);\n+ SetServerResponse(FUSE_OPEN, iov_out);\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(test_file_path.c_str(), O_RDWR));\n+ SkipServerActualRequest();\n+\n+ // check open doesn't send new request.\n+ uint32_t recieved_before = GetServerTotalReceivedBytes();\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(test_file_path.c_str(), O_RDWR));\n+ EXPECT_EQ(GetServerTotalReceivedBytes(), recieved_before);\n+}\n+\n+TEST_F(OpenTest, OpenFail) {\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_open_out),\n+ .error = -ENOENT,\n+ };\n+\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload_);\n+ SetServerResponse(FUSE_OPENDIR, iov_out);\n+ ASSERT_THAT(open(mount_point_.path().c_str(), O_RDWR),\n+ SyscallFailsWithErrno(ENOENT));\n+\n+ struct fuse_in_header in_header;\n+ struct fuse_open_in in_payload;\n+ auto iov_in = FuseGenerateIovecs(in_header, in_payload);\n+ GetServerActualRequest(iov_in);\n+\n+ EXPECT_EQ(in_header.len, sizeof(in_header) + sizeof(in_payload));\n+ EXPECT_EQ(in_header.opcode, FUSE_OPENDIR);\n+ EXPECT_EQ(in_payload.flags, O_RDWR);\n+}\n+\n+TEST_F(OpenTest, DirectoryFlagOnRegularFile) {\n+ const std::string test_file_path =\n+ JoinPath(mount_point_.path().c_str(), test_file_);\n+\n+ SetServerInodeLookup(test_file_, regular_file_);\n+ ASSERT_THAT(open(test_file_path.c_str(), O_RDWR | O_DIRECTORY),\n+ SyscallFailsWithErrno(ENOTDIR));\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n" }, { "change_type": "MODIFY", "old_path": "test/util/BUILD", "new_path": "test/util/BUILD", "diff": "@@ -48,6 +48,7 @@ cc_library(\ncc_library(\nname = \"fuse_util\",\ntestonly = 1,\n+ srcs = [\"fuse_util.cc\"],\nhdrs = [\"fuse_util.h\"],\n)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/util/fuse_util.cc", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include \"test/util/fuse_util.h\"\n+\n+#include <sys/stat.h>\n+#include <sys/types.h>\n+\n+#include <string>\n+\n+namespace gvisor {\n+namespace testing {\n+\n+// Create response body with specified mode and nodeID.\n+fuse_entry_out DefaultEntryOut(mode_t mode, uint64_t node_id) {\n+ const int time_sec = 1595436289;\n+ const int time_nsec = 134150844;\n+ struct fuse_entry_out default_entry_out = {\n+ .nodeid = node_id,\n+ .generation = 0,\n+ .entry_valid = time_sec,\n+ .attr_valid = time_sec,\n+ .entry_valid_nsec = time_nsec,\n+ .attr_valid_nsec = time_nsec,\n+ .attr =\n+ (struct fuse_attr){\n+ .ino = node_id,\n+ .size = 512,\n+ .blocks = 4,\n+ .atime = time_sec,\n+ .mtime = time_sec,\n+ .ctime = time_sec,\n+ .atimensec = time_nsec,\n+ .mtimensec = time_nsec,\n+ .ctimensec = time_nsec,\n+ .mode = mode,\n+ .nlink = 2,\n+ .uid = 1234,\n+ .gid = 4321,\n+ .rdev = 12,\n+ .blksize = 4096,\n+ },\n+ };\n+ return default_entry_out;\n+};\n+\n+} // namespace testing\n+} // namespace gvisor\n" }, { "change_type": "MODIFY", "old_path": "test/util/fuse_util.h", "new_path": "test/util/fuse_util.h", "diff": "#ifndef GVISOR_TEST_UTIL_FUSE_UTIL_H_\n#define GVISOR_TEST_UTIL_FUSE_UTIL_H_\n+#include <linux/fuse.h>\n#include <sys/uio.h>\n#include <string>\n@@ -62,6 +63,9 @@ std::vector<struct iovec> FuseGenerateIovecs(T &first, Types &...args) {\nreturn first_iovec;\n}\n+// Return a fuse_entry_out FUSE server response body.\n+fuse_entry_out DefaultEntryOut(mode_t mode, uint64_t nodeId);\n+\n} // namespace testing\n} // namespace gvisor\n#endif // GVISOR_TEST_UTIL_FUSE_UTIL_H_\n" } ]
Go
Apache License 2.0
google/gvisor
Implement FUSE_OPEN/OPENDIR Fixes #3174
259,984
18.08.2020 20:59:28
0
947088e10a15b5236f2af3206f67f27245ef2770
Implement FUSE_RELEASE/RELEASEDIR Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/fuse.go", "new_path": "pkg/abi/linux/fuse.go", "diff": "@@ -395,3 +395,21 @@ type FUSEOpenOut struct {\n_ uint32\n}\n+\n+// FUSEReleaseIn is the request sent by the kernel to the daemon\n+// when there is no more reference to a file.\n+//\n+// +marshal\n+type FUSEReleaseIn struct {\n+ // Fh is the file handler for the file to be released.\n+ Fh uint64\n+\n+ // Flags of the file.\n+ Flags uint32\n+\n+ // ReleaseFlags of this release request.\n+ ReleaseFlags uint32\n+\n+ // LockOwner is the id of the lock owner if there is one.\n+ LockOwner uint64\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/dev.go", "new_path": "pkg/sentry/fsimpl/fuse/dev.go", "diff": "@@ -168,6 +168,9 @@ func (fd *DeviceFD) readLocked(ctx context.Context, dst usermem.IOSequence, opts\n// We're done with this request.\nfd.queue.Remove(req)\n+ if req.hdr.Opcode == linux.FUSE_RELEASE {\n+ fd.numActiveRequests -= 1\n+ }\n// Restart the read as this request was invalid.\nlog.Warningf(\"fuse.DeviceFD.Read: request found was too large. Restarting read.\")\n@@ -184,6 +187,9 @@ func (fd *DeviceFD) readLocked(ctx context.Context, dst usermem.IOSequence, opts\nif readCursor >= req.hdr.Len {\n// Fully done with this req, remove it from the queue.\nfd.queue.Remove(req)\n+ if req.hdr.Opcode == linux.FUSE_RELEASE {\n+ fd.numActiveRequests -= 1\n+ }\nbreak\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/file.go", "new_path": "pkg/sentry/fsimpl/fuse/file.go", "diff": "@@ -18,6 +18,8 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n@@ -54,8 +56,34 @@ func (fd *fileDescription) filesystem() *vfs.Filesystem {\nreturn fd.vfsfd.VirtualDentry().Mount().Filesystem()\n}\n+func (fd *fileDescription) statusFlags() uint32 {\n+ return fd.vfsfd.StatusFlags()\n+}\n+\n// Release implements vfs.FileDescriptionImpl.Release.\n-func (fd *fileDescription) Release(ctx context.Context) {}\n+func (fd *fileDescription) Release(ctx context.Context) {\n+ // no need to release if FUSE server doesn't implement Open.\n+ conn := fd.inode().fs.conn\n+ if conn.noOpen {\n+ return\n+ }\n+\n+ in := linux.FUSEReleaseIn{\n+ Fh: fd.Fh,\n+ Flags: fd.statusFlags(),\n+ }\n+ // TODO(gvisor.dev/issue/3245): add logic when we support file lock owner.\n+ var opcode linux.FUSEOpcode\n+ if fd.inode().Mode().IsDir() {\n+ opcode = linux.FUSE_RELEASEDIR\n+ } else {\n+ opcode = linux.FUSE_RELEASE\n+ }\n+ kernelTask := kernel.TaskFromContext(ctx)\n+ // ignoring errors and FUSE server reply is analogous to Linux's behavior.\n+ req, _ := conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), fd.inode().NodeID, opcode, &in)\n+ conn.CallAsync(kernelTask, req)\n+}\n// PRead implements vfs.FileDescriptionImpl.PRead.\nfunc (fd *fileDescription) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts vfs.ReadOptions) (int64, error) {\n@@ -82,7 +110,6 @@ func (fd *fileDescription) Seek(ctx context.Context, offset int64, whence int32)\nreturn 0, nil\n}\n-// Stat implements FileDescriptionImpl.Stat.\n// Stat implements vfs.FileDescriptionImpl.Stat.\nfunc (fd *fileDescription) Stat(ctx context.Context, opts vfs.StatOptions) (linux.Statx, error) {\nfs := fd.filesystem()\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/BUILD", "new_path": "test/fuse/BUILD", "diff": "@@ -11,3 +11,8 @@ syscall_test(\nfuse = \"True\",\ntest = \"//test/fuse/linux:open_test\",\n)\n+\n+syscall_test(\n+ fuse = \"True\",\n+ test = \"//test/fuse/linux:release_test\",\n+)\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/BUILD", "new_path": "test/fuse/linux/BUILD", "diff": "@@ -31,6 +31,19 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"release_test\",\n+ testonly = 1,\n+ srcs = [\"release_test.cc\"],\n+ deps = [\n+ gtest,\n+ \":fuse_base\",\n+ \"//test/util:fuse_util\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n+\ncc_library(\nname = \"fuse_base\",\ntestonly = 1,\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/fuse_base.cc", "new_path": "test/fuse/linux/fuse_base.cc", "diff": "@@ -387,7 +387,8 @@ void FuseTest::ServerProcessFuseRequest() {\nrequests_.AddMemBlock(in_header->opcode, buf.data(), len);\n- if (in_header->opcode == FUSE_RELEASE) return;\n+ if (in_header->opcode == FUSE_RELEASE || in_header->opcode == FUSE_RELEASEDIR)\n+ return;\n// Check if there is a corresponding response.\nif (responses_.End()) {\nGTEST_NONFATAL_FAILURE_(\"No more FUSE response is expected\");\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/fuse_base.h", "new_path": "test/fuse/linux/fuse_base.h", "diff": "@@ -166,13 +166,13 @@ class FuseTest : public ::testing::Test {\nprotected:\nTempPath mount_point_;\n+ // Unmounts the mountpoint of the FUSE server.\n+ void UnmountFuse();\n+\nprivate:\n// Opens /dev/fuse and inherit the file descriptor for the FUSE server.\nvoid MountFuse();\n- // Unmounts the mountpoint of the FUSE server.\n- void UnmountFuse();\n-\n// Creates a socketpair for communication and forks FUSE server.\nvoid SetUpFuseServer();\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/open_test.cc", "new_path": "test/fuse/linux/open_test.cc", "diff": "@@ -33,6 +33,10 @@ namespace testing {\nnamespace {\nclass OpenTest : public FuseTest {\n+ // OpenTest doesn't care the release request when close a fd,\n+ // so doesn't check leftover requests when tearing down.\n+ void TearDown() { UnmountFuse(); }\n+\nprotected:\nconst std::string test_file_ = \"test_file\";\nconst mode_t regular_file_ = S_IFREG | S_IRWXU | S_IRWXG | S_IRWXO;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/fuse/linux/release_test.cc", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <errno.h>\n+#include <fcntl.h>\n+#include <linux/fuse.h>\n+#include <sys/mount.h>\n+#include <sys/stat.h>\n+#include <sys/statfs.h>\n+#include <sys/types.h>\n+#include <unistd.h>\n+\n+#include <string>\n+#include <vector>\n+\n+#include \"gtest/gtest.h\"\n+#include \"test/fuse/linux/fuse_base.h\"\n+#include \"test/util/fuse_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+class ReleaseTest : public FuseTest {\n+ protected:\n+ const std::string test_file_ = \"test_file\";\n+};\n+\n+TEST_F(ReleaseTest, RegularFile) {\n+ const std::string test_file_path =\n+ JoinPath(mount_point_.path().c_str(), test_file_);\n+ SetServerInodeLookup(test_file_, S_IFREG | S_IRWXU | S_IRWXG | S_IRWXO);\n+\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_open_out),\n+ };\n+ struct fuse_open_out out_payload = {\n+ .fh = 1,\n+ .open_flags = O_RDWR,\n+ };\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload);\n+ SetServerResponse(FUSE_OPEN, iov_out);\n+ FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(test_file_path, O_RDWR));\n+ SkipServerActualRequest();\n+ ASSERT_THAT(close(fd.release()), SyscallSucceeds());\n+\n+ struct fuse_in_header in_header;\n+ struct fuse_release_in in_payload;\n+ auto iov_in = FuseGenerateIovecs(in_header, in_payload);\n+ GetServerActualRequest(iov_in);\n+\n+ EXPECT_EQ(in_header.len, sizeof(in_header) + sizeof(in_payload));\n+ EXPECT_EQ(in_header.opcode, FUSE_RELEASE);\n+ EXPECT_EQ(in_payload.flags, O_RDWR);\n+ EXPECT_EQ(in_payload.fh, 1);\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Implement FUSE_RELEASE/RELEASEDIR Fixes #3314
259,984
18.08.2020 21:51:06
0
b53e10f391929e4ad9345a823a0cf33bcfedf413
Implement FUSE_MKNOD Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/fuse.go", "new_path": "pkg/abi/linux/fuse.go", "diff": "@@ -413,3 +413,46 @@ type FUSEReleaseIn struct {\n// LockOwner is the id of the lock owner if there is one.\nLockOwner uint64\n}\n+\n+// FUSEMknodMeta contains all the static fields of FUSEMknodIn,\n+// which is used for FUSE_MKNOD.\n+//\n+// +marshal\n+type FUSEMknodMeta struct {\n+ // Mode of the inode to create.\n+ Mode uint32\n+\n+ // Rdev encodes device major and minor information.\n+ Rdev uint32\n+\n+ // Umask is the current file mode creation mask.\n+ Umask uint32\n+\n+ _ uint32\n+}\n+\n+// FUSEMknodIn contains all the arguments sent by the kernel\n+// to the daemon, to create a new file node.\n+//\n+// Dynamically-sized objects cannot be marshalled.\n+type FUSEMknodIn struct {\n+ marshal.StubMarshallable\n+\n+ // MknodMeta contains mode, rdev and umash field for FUSE_MKNODS.\n+ MknodMeta FUSEMknodMeta\n+\n+ // Name is the name of the node to create.\n+ Name string\n+}\n+\n+// MarshalUnsafe serializes r.MknodMeta and r.Name to the dst buffer.\n+func (r *FUSEMknodIn) MarshalUnsafe(buf []byte) {\n+ r.MknodMeta.MarshalUnsafe(buf[:r.MknodMeta.SizeBytes()])\n+ copy(buf[r.MknodMeta.SizeBytes():], r.Name)\n+}\n+\n+// SizeBytes is the size of the memory representation of FUSEMknodIn.\n+// 1 extra byte for null-terminated string.\n+func (r *FUSEMknodIn) SizeBytes() int {\n+ return r.MknodMeta.SizeBytes() + len(r.Name) + 1\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "new_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "diff": "@@ -349,6 +349,19 @@ func (inode) Valid(ctx context.Context) bool {\nreturn true\n}\n+// NewNode implements kernfs.Inode.NewNode.\n+func (i *inode) NewNode(ctx context.Context, name string, opts vfs.MknodOptions) (*vfs.Dentry, error) {\n+ in := linux.FUSEMknodIn{\n+ MknodMeta: linux.FUSEMknodMeta{\n+ Mode: uint32(opts.Mode),\n+ Rdev: linux.MakeDeviceID(uint16(opts.DevMajor), opts.DevMinor),\n+ Umask: uint32(kernel.TaskFromContext(ctx).FSContext().Umask()),\n+ },\n+ Name: name,\n+ }\n+ return i.newEntry(ctx, name, opts.Mode.FileType(), linux.FUSE_MKNOD, &in)\n+}\n+\n// newEntry calls FUSE server for entry creation and allocates corresponding entry according to response.\n// Shared by FUSE_MKNOD, FUSE_MKDIR, FUSE_SYMLINK, FUSE_LINK and FUSE_LOOKUP.\nfunc (i *inode) newEntry(ctx context.Context, name string, fileType linux.FileMode, opcode linux.FUSEOpcode, payload marshal.Marshallable) (*vfs.Dentry, error) {\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/BUILD", "new_path": "test/fuse/BUILD", "diff": "@@ -16,3 +16,8 @@ syscall_test(\nfuse = \"True\",\ntest = \"//test/fuse/linux:release_test\",\n)\n+\n+syscall_test(\n+ fuse = \"True\",\n+ test = \"//test/fuse/linux:mknod_test\",\n+)\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/BUILD", "new_path": "test/fuse/linux/BUILD", "diff": "@@ -44,6 +44,20 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"mknod_test\",\n+ testonly = 1,\n+ srcs = [\"mknod_test.cc\"],\n+ deps = [\n+ gtest,\n+ \":fuse_base\",\n+ \"//test/util:fuse_util\",\n+ \"//test/util:temp_umask\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n+\ncc_library(\nname = \"fuse_base\",\ntestonly = 1,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/fuse/linux/mknod_test.cc", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <errno.h>\n+#include <fcntl.h>\n+#include <linux/fuse.h>\n+#include <sys/stat.h>\n+#include <sys/statfs.h>\n+#include <sys/types.h>\n+#include <unistd.h>\n+\n+#include <string>\n+#include <vector>\n+\n+#include \"gtest/gtest.h\"\n+#include \"test/fuse/linux/fuse_base.h\"\n+#include \"test/util/fuse_util.h\"\n+#include \"test/util/temp_umask.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+class MknodTest : public FuseTest {\n+ protected:\n+ const std::string test_file_ = \"test_file\";\n+ const mode_t perms_ = S_IRWXU | S_IRWXG | S_IRWXO;\n+};\n+\n+TEST_F(MknodTest, RegularFile) {\n+ const std::string test_file_path =\n+ JoinPath(mount_point_.path().c_str(), test_file_);\n+ const mode_t new_umask = 0077;\n+\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_entry_out),\n+ };\n+ struct fuse_entry_out out_payload = DefaultEntryOut(S_IFREG | perms_, 5);\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload);\n+ SetServerResponse(FUSE_MKNOD, iov_out);\n+ TempUmask mask(new_umask);\n+ ASSERT_THAT(mknod(test_file_path.c_str(), perms_, 0), SyscallSucceeds());\n+\n+ struct fuse_in_header in_header;\n+ struct fuse_mknod_in in_payload;\n+ std::vector<char> actual_file(test_file_.length() + 1);\n+ auto iov_in = FuseGenerateIovecs(in_header, in_payload, actual_file);\n+ GetServerActualRequest(iov_in);\n+\n+ EXPECT_EQ(in_header.len,\n+ sizeof(in_header) + sizeof(in_payload) + test_file_.length() + 1);\n+ EXPECT_EQ(in_header.opcode, FUSE_MKNOD);\n+ EXPECT_EQ(in_payload.mode & 0777, perms_ & ~new_umask);\n+ EXPECT_EQ(in_payload.umask, new_umask);\n+ EXPECT_EQ(in_payload.rdev, 0);\n+ EXPECT_EQ(std::string(actual_file.data()), test_file_);\n+}\n+\n+TEST_F(MknodTest, FileTypeError) {\n+ const std::string test_file_path =\n+ JoinPath(mount_point_.path().c_str(), test_file_);\n+\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_entry_out),\n+ };\n+ // server return directory instead of regular file should cause an error.\n+ struct fuse_entry_out out_payload = DefaultEntryOut(S_IFDIR | perms_, 5);\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload);\n+ SetServerResponse(FUSE_MKNOD, iov_out);\n+ ASSERT_THAT(mknod(test_file_path.c_str(), perms_, 0),\n+ SyscallFailsWithErrno(EIO));\n+ SkipServerActualRequest();\n+}\n+\n+TEST_F(MknodTest, NodeIDError) {\n+ const std::string test_file_path =\n+ JoinPath(mount_point_.path().c_str(), test_file_);\n+\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_entry_out),\n+ };\n+ struct fuse_entry_out out_payload =\n+ DefaultEntryOut(S_IFREG | perms_, FUSE_ROOT_ID);\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload);\n+ SetServerResponse(FUSE_MKNOD, iov_out);\n+ ASSERT_THAT(mknod(test_file_path.c_str(), perms_, 0),\n+ SyscallFailsWithErrno(EIO));\n+ SkipServerActualRequest();\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Implement FUSE_MKNOD Fixes #3492
259,984
18.08.2020 23:09:34
0
b50c03b5715905ebd82b1006c1bb2e2d4eb9334d
Implement FUSE_SYMLINK Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/fuse.go", "new_path": "pkg/abi/linux/fuse.go", "diff": "@@ -456,3 +456,30 @@ func (r *FUSEMknodIn) MarshalUnsafe(buf []byte) {\nfunc (r *FUSEMknodIn) SizeBytes() int {\nreturn r.MknodMeta.SizeBytes() + len(r.Name) + 1\n}\n+\n+// FUSESymLinkIn is the request sent by the kernel to the daemon,\n+// to create a symbolic link.\n+//\n+// Dynamically-sized objects cannot be marshalled.\n+type FUSESymLinkIn struct {\n+ marshal.StubMarshallable\n+\n+ // Name of symlink to create.\n+ Name string\n+\n+ // Target of the symlink.\n+ Target string\n+}\n+\n+// MarshalUnsafe serializes r.Name and r.Target to the dst buffer.\n+// Left null-termination at end of r.Name and r.Target.\n+func (r *FUSESymLinkIn) MarshalUnsafe(buf []byte) {\n+ copy(buf, r.Name)\n+ copy(buf[len(r.Name)+1:], r.Target)\n+}\n+\n+// SizeBytes is the size of the memory representation of FUSESymLinkIn.\n+// 2 extra bytes for null-terminated string.\n+func (r *FUSESymLinkIn) SizeBytes() int {\n+ return len(r.Name) + len(r.Target) + 2\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "new_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "diff": "@@ -362,6 +362,15 @@ func (i *inode) NewNode(ctx context.Context, name string, opts vfs.MknodOptions)\nreturn i.newEntry(ctx, name, opts.Mode.FileType(), linux.FUSE_MKNOD, &in)\n}\n+// NewSymlink implements kernfs.Inode.NewSymlink.\n+func (i *inode) NewSymlink(ctx context.Context, name, target string) (*vfs.Dentry, error) {\n+ in := linux.FUSESymLinkIn{\n+ Name: name,\n+ Target: target,\n+ }\n+ return i.newEntry(ctx, name, linux.S_IFLNK, linux.FUSE_SYMLINK, &in)\n+}\n+\n// newEntry calls FUSE server for entry creation and allocates corresponding entry according to response.\n// Shared by FUSE_MKNOD, FUSE_MKDIR, FUSE_SYMLINK, FUSE_LINK and FUSE_LOOKUP.\nfunc (i *inode) newEntry(ctx context.Context, name string, fileType linux.FileMode, opcode linux.FUSEOpcode, payload marshal.Marshallable) (*vfs.Dentry, error) {\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/BUILD", "new_path": "test/fuse/BUILD", "diff": "@@ -21,3 +21,8 @@ syscall_test(\nfuse = \"True\",\ntest = \"//test/fuse/linux:mknod_test\",\n)\n+\n+syscall_test(\n+ fuse = \"True\",\n+ test = \"//test/fuse/linux:symlink_test\",\n+)\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/BUILD", "new_path": "test/fuse/linux/BUILD", "diff": "@@ -58,6 +58,19 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"symlink_test\",\n+ testonly = 1,\n+ srcs = [\"symlink_test.cc\"],\n+ deps = [\n+ gtest,\n+ \":fuse_base\",\n+ \"//test/util:fuse_util\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n+\ncc_library(\nname = \"fuse_base\",\ntestonly = 1,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/fuse/linux/symlink_test.cc", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <errno.h>\n+#include <fcntl.h>\n+#include <linux/fuse.h>\n+#include <sys/stat.h>\n+#include <sys/statfs.h>\n+#include <sys/types.h>\n+#include <unistd.h>\n+\n+#include <string>\n+#include <vector>\n+\n+#include \"gtest/gtest.h\"\n+#include \"test/fuse/linux/fuse_base.h\"\n+#include \"test/util/fuse_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+class SymlinkTest : public FuseTest {\n+ protected:\n+ const std::string target_file_ = \"target_file_\";\n+ const std::string symlink_ = \"symlink_\";\n+ const mode_t perms_ = S_IRWXU | S_IRWXG | S_IRWXO;\n+};\n+\n+TEST_F(SymlinkTest, CreateSymLink) {\n+ const std::string symlink_path =\n+ JoinPath(mount_point_.path().c_str(), symlink_);\n+\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_entry_out),\n+ };\n+ struct fuse_entry_out out_payload = DefaultEntryOut(S_IFLNK | perms_, 5);\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload);\n+ SetServerResponse(FUSE_SYMLINK, iov_out);\n+ ASSERT_THAT(symlink(target_file_.c_str(), symlink_path.c_str()),\n+ SyscallSucceeds());\n+\n+ struct fuse_in_header in_header;\n+ std::vector<char> actual_target_file(target_file_.length() + 1);\n+ std::vector<char> actual_symlink(symlink_.length() + 1);\n+ auto iov_in =\n+ FuseGenerateIovecs(in_header, actual_symlink, actual_target_file);\n+ GetServerActualRequest(iov_in);\n+\n+ EXPECT_EQ(in_header.len,\n+ sizeof(in_header) + symlink_.length() + target_file_.length() + 2);\n+ EXPECT_EQ(in_header.opcode, FUSE_SYMLINK);\n+ EXPECT_EQ(std::string(actual_target_file.data()), target_file_);\n+ EXPECT_EQ(std::string(actual_symlink.data()), symlink_);\n+}\n+\n+TEST_F(SymlinkTest, FileTypeError) {\n+ const std::string symlink_path =\n+ JoinPath(mount_point_.path().c_str(), symlink_);\n+\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_entry_out),\n+ };\n+ struct fuse_entry_out out_payload = DefaultEntryOut(S_IFREG | perms_, 5);\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload);\n+ SetServerResponse(FUSE_SYMLINK, iov_out);\n+ ASSERT_THAT(symlink(target_file_.c_str(), symlink_path.c_str()),\n+ SyscallFailsWithErrno(EIO));\n+ SkipServerActualRequest();\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Implement FUSE_SYMLINK Fixes #3452
259,984
18.08.2020 23:50:22
0
733d013f979a2107fd866ff3c05249c3e8ba5102
Implement FUSE_READLINK Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/fuse.go", "new_path": "pkg/abi/linux/fuse.go", "diff": "@@ -483,3 +483,14 @@ func (r *FUSESymLinkIn) MarshalUnsafe(buf []byte) {\nfunc (r *FUSESymLinkIn) SizeBytes() int {\nreturn len(r.Name) + len(r.Target) + 2\n}\n+\n+// FUSEEmptyIn is used by operations without request body.\n+type FUSEEmptyIn struct{ marshal.StubMarshallable }\n+\n+// MarshalUnsafe do nothing for marshal.\n+func (r *FUSEEmptyIn) MarshalUnsafe(buf []byte) {}\n+\n+// SizeBytes is 0 for empty request.\n+func (r *FUSEEmptyIn) SizeBytes() int {\n+ return 0\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "new_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "diff": "@@ -225,6 +225,9 @@ type inode struct {\n// version of the inode.\nversion uint64\n+\n+ // link is result of following a symbolic link.\n+ link string\n}\nfunc (fs *filesystem) newRootInode(creds *auth.Credentials, mode linux.FileMode) *kernfs.Dentry {\n@@ -406,6 +409,33 @@ func (i *inode) newEntry(ctx context.Context, name string, fileType linux.FileMo\nreturn child.VFSDentry(), nil\n}\n+// Readlink implements kernfs.Inode.Readlink.\n+func (i *inode) Readlink(ctx context.Context, mnt *vfs.Mount) (string, error) {\n+ if i.Mode().FileType()&linux.S_IFLNK == 0 {\n+ return \"\", syserror.EINVAL\n+ }\n+ if i.link == \"\" {\n+ kernelTask := kernel.TaskFromContext(ctx)\n+ if kernelTask == nil {\n+ log.Warningf(\"fusefs.Inode.Readlink: couldn't get kernel task from context\")\n+ return \"\", syserror.EINVAL\n+ }\n+ req, err := i.fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), i.NodeID, linux.FUSE_READLINK, &linux.FUSEEmptyIn{})\n+ if err != nil {\n+ return \"\", err\n+ }\n+ res, err := i.fs.conn.Call(kernelTask, req)\n+ if err != nil {\n+ return \"\", err\n+ }\n+ i.link = string(res.data[res.hdr.SizeBytes():])\n+ if !mnt.Options().ReadOnly {\n+ i.attributeTime = 0\n+ }\n+ }\n+ return i.link, nil\n+}\n+\n// statFromFUSEAttr makes attributes from linux.FUSEAttr to linux.Statx. The\n// opts.Sync attribute is ignored since the synchronization is handled by the\n// FUSE server.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "diff": "@@ -548,7 +548,7 @@ func (fs *Filesystem) ReadlinkAt(ctx context.Context, rp *vfs.ResolvingPath) (st\nif !d.Impl().(*Dentry).isSymlink() {\nreturn \"\", syserror.EINVAL\n}\n- return inode.Readlink(ctx)\n+ return inode.Readlink(ctx, rp.Mount())\n}\n// RenameAt implements vfs.FilesystemImpl.RenameAt.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go", "new_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go", "diff": "@@ -172,7 +172,7 @@ func (InodeNoDynamicLookup) Valid(ctx context.Context) bool {\ntype InodeNotSymlink struct{}\n// Readlink implements Inode.Readlink.\n-func (InodeNotSymlink) Readlink(context.Context) (string, error) {\n+func (InodeNotSymlink) Readlink(context.Context, *vfs.Mount) (string, error) {\nreturn \"\", syserror.EINVAL\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/kernfs.go", "new_path": "pkg/sentry/fsimpl/kernfs/kernfs.go", "diff": "@@ -437,7 +437,7 @@ type inodeDynamicLookup interface {\ntype inodeSymlink interface {\n// Readlink returns the target of a symbolic link. If an inode is not a\n// symlink, the implementation should return EINVAL.\n- Readlink(ctx context.Context) (string, error)\n+ Readlink(ctx context.Context, mnt *vfs.Mount) (string, error)\n// Getlink returns the target of a symbolic link, as used by path\n// resolution:\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/symlink.go", "new_path": "pkg/sentry/fsimpl/kernfs/symlink.go", "diff": "@@ -52,7 +52,7 @@ func (s *StaticSymlink) Init(creds *auth.Credentials, devMajor uint32, devMinor\n}\n// Readlink implements Inode.\n-func (s *StaticSymlink) Readlink(_ context.Context) (string, error) {\n+func (s *StaticSymlink) Readlink(_ context.Context, _ *vfs.Mount) (string, error) {\nreturn s.target, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/task_fds.go", "new_path": "pkg/sentry/fsimpl/proc/task_fds.go", "diff": "@@ -214,7 +214,7 @@ func (fs *filesystem) newFDSymlink(task *kernel.Task, fd int32, ino uint64) *ker\nreturn d\n}\n-func (s *fdSymlink) Readlink(ctx context.Context) (string, error) {\n+func (s *fdSymlink) Readlink(ctx context.Context, _ *vfs.Mount) (string, error) {\nfile, _ := getTaskFD(s.task, s.fd)\nif file == nil {\nreturn \"\", syserror.ENOENT\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/task_files.go", "new_path": "pkg/sentry/fsimpl/proc/task_files.go", "diff": "@@ -668,7 +668,7 @@ func (fs *filesystem) newExeSymlink(task *kernel.Task, ino uint64) *kernfs.Dentr\n}\n// Readlink implements kernfs.Inode.\n-func (s *exeSymlink) Readlink(ctx context.Context) (string, error) {\n+func (s *exeSymlink) Readlink(ctx context.Context, _ *vfs.Mount) (string, error) {\nif !kernel.ContextCanTrace(ctx, s.task, false) {\nreturn \"\", syserror.EACCES\n}\n@@ -808,11 +808,11 @@ func (fs *filesystem) newNamespaceSymlink(task *kernel.Task, ino uint64, ns stri\n}\n// Readlink implements Inode.\n-func (s *namespaceSymlink) Readlink(ctx context.Context) (string, error) {\n+func (s *namespaceSymlink) Readlink(ctx context.Context, mnt *vfs.Mount) (string, error) {\nif err := checkTaskState(s.task); err != nil {\nreturn \"\", err\n}\n- return s.StaticSymlink.Readlink(ctx)\n+ return s.StaticSymlink.Readlink(ctx, mnt)\n}\n// Getlink implements Inode.Getlink.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks_files.go", "new_path": "pkg/sentry/fsimpl/proc/tasks_files.go", "diff": "@@ -51,7 +51,7 @@ func (fs *filesystem) newSelfSymlink(creds *auth.Credentials, ino uint64, pidns\nreturn d\n}\n-func (s *selfSymlink) Readlink(ctx context.Context) (string, error) {\n+func (s *selfSymlink) Readlink(ctx context.Context, _ *vfs.Mount) (string, error) {\nt := kernel.TaskFromContext(ctx)\nif t == nil {\n// Who is reading this link?\n@@ -64,8 +64,8 @@ func (s *selfSymlink) Readlink(ctx context.Context) (string, error) {\nreturn strconv.FormatUint(uint64(tgid), 10), nil\n}\n-func (s *selfSymlink) Getlink(ctx context.Context, _ *vfs.Mount) (vfs.VirtualDentry, string, error) {\n- target, err := s.Readlink(ctx)\n+func (s *selfSymlink) Getlink(ctx context.Context, mnt *vfs.Mount) (vfs.VirtualDentry, string, error) {\n+ target, err := s.Readlink(ctx, mnt)\nreturn vfs.VirtualDentry{}, target, err\n}\n@@ -94,7 +94,7 @@ func (fs *filesystem) newThreadSelfSymlink(creds *auth.Credentials, ino uint64,\nreturn d\n}\n-func (s *threadSelfSymlink) Readlink(ctx context.Context) (string, error) {\n+func (s *threadSelfSymlink) Readlink(ctx context.Context, _ *vfs.Mount) (string, error) {\nt := kernel.TaskFromContext(ctx)\nif t == nil {\n// Who is reading this link?\n@@ -108,8 +108,8 @@ func (s *threadSelfSymlink) Readlink(ctx context.Context) (string, error) {\nreturn fmt.Sprintf(\"%d/task/%d\", tgid, tid), nil\n}\n-func (s *threadSelfSymlink) Getlink(ctx context.Context, _ *vfs.Mount) (vfs.VirtualDentry, string, error) {\n- target, err := s.Readlink(ctx)\n+func (s *threadSelfSymlink) Getlink(ctx context.Context, mnt *vfs.Mount) (vfs.VirtualDentry, string, error) {\n+ target, err := s.Readlink(ctx, mnt)\nreturn vfs.VirtualDentry{}, target, err\n}\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/BUILD", "new_path": "test/fuse/BUILD", "diff": "@@ -26,3 +26,8 @@ syscall_test(\nfuse = \"True\",\ntest = \"//test/fuse/linux:symlink_test\",\n)\n+\n+syscall_test(\n+ fuse = \"True\",\n+ test = \"//test/fuse/linux:readlink_test\",\n+)\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/BUILD", "new_path": "test/fuse/linux/BUILD", "diff": "@@ -71,6 +71,19 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"readlink_test\",\n+ testonly = 1,\n+ srcs = [\"readlink_test.cc\"],\n+ deps = [\n+ gtest,\n+ \":fuse_base\",\n+ \"//test/util:fuse_util\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n+\ncc_library(\nname = \"fuse_base\",\ntestonly = 1,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/fuse/linux/readlink_test.cc", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <errno.h>\n+#include <fcntl.h>\n+#include <linux/fuse.h>\n+#include <sys/stat.h>\n+#include <sys/statfs.h>\n+#include <sys/types.h>\n+#include <unistd.h>\n+\n+#include <string>\n+#include <vector>\n+\n+#include \"gtest/gtest.h\"\n+#include \"test/fuse/linux/fuse_base.h\"\n+#include \"test/util/fuse_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+class ReadlinkTest : public FuseTest {\n+ protected:\n+ const std::string test_file_ = \"test_file_\";\n+ const mode_t perms_ = S_IRWXU | S_IRWXG | S_IRWXO;\n+};\n+\n+TEST_F(ReadlinkTest, ReadSymLink) {\n+ const std::string symlink_path =\n+ JoinPath(mount_point_.path().c_str(), test_file_);\n+ SetServerInodeLookup(test_file_, S_IFLNK | perms_);\n+\n+ struct fuse_out_header out_header = {\n+ .len = static_cast<uint32_t>(sizeof(struct fuse_out_header)) +\n+ static_cast<uint32_t>(test_file_.length()) + 1,\n+ };\n+ std::string link = test_file_;\n+ auto iov_out = FuseGenerateIovecs(out_header, link);\n+ SetServerResponse(FUSE_READLINK, iov_out);\n+ const std::string actual_link =\n+ ASSERT_NO_ERRNO_AND_VALUE(ReadLink(symlink_path));\n+\n+ struct fuse_in_header in_header;\n+ auto iov_in = FuseGenerateIovecs(in_header);\n+ GetServerActualRequest(iov_in);\n+\n+ EXPECT_EQ(in_header.len, sizeof(in_header));\n+ EXPECT_EQ(in_header.opcode, FUSE_READLINK);\n+ EXPECT_EQ(0, memcmp(actual_link.c_str(), link.data(), link.size()));\n+\n+ // next readlink should have link cached, so shouldn't have new request to\n+ // server.\n+ uint32_t recieved_before = GetServerTotalReceivedBytes();\n+ ASSERT_NO_ERRNO(ReadLink(symlink_path));\n+ EXPECT_EQ(GetServerTotalReceivedBytes(), recieved_before);\n+}\n+\n+TEST_F(ReadlinkTest, NotSymlink) {\n+ const std::string test_file_path =\n+ JoinPath(mount_point_.path().c_str(), test_file_);\n+ SetServerInodeLookup(test_file_, S_IFREG | perms_);\n+\n+ std::vector<char> buf(PATH_MAX + 1);\n+ ASSERT_THAT(readlink(test_file_path.c_str(), buf.data(), PATH_MAX),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Implement FUSE_READLINK Fixes #3316
259,984
18.08.2020 22:45:47
0
4d26c9929de31cdfe3551d4b8be90a07f98fed55
Implement FUSE_MKDIR Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/fuse.go", "new_path": "pkg/abi/linux/fuse.go", "diff": "@@ -494,3 +494,41 @@ func (r *FUSEEmptyIn) MarshalUnsafe(buf []byte) {}\nfunc (r *FUSEEmptyIn) SizeBytes() int {\nreturn 0\n}\n+\n+// FUSEMkdirMeta contains all the static fields of FUSEMkdirIn,\n+// which is used for FUSE_MKDIR.\n+//\n+// +marshal\n+type FUSEMkdirMeta struct {\n+ // Mode of the directory of create.\n+ Mode uint32\n+\n+ // Umask is the user file creation mask.\n+ Umask uint32\n+}\n+\n+// FUSEMkdirIn contains all the arguments sent by the kernel\n+// to the daemon, to create a new directory.\n+//\n+// Dynamically-sized objects cannot be marshalled.\n+type FUSEMkdirIn struct {\n+ marshal.StubMarshallable\n+\n+ // MkdirMeta contains Mode and Umask of the directory to create.\n+ MkdirMeta FUSEMkdirMeta\n+\n+ // Name of the directory to create.\n+ Name string\n+}\n+\n+// MarshalUnsafe serializes r.MkdirMeta and r.Name to the dst buffer.\n+func (r *FUSEMkdirIn) MarshalUnsafe(buf []byte) {\n+ r.MkdirMeta.MarshalUnsafe(buf[:r.MkdirMeta.SizeBytes()])\n+ copy(buf[r.MkdirMeta.SizeBytes():], r.Name)\n+}\n+\n+// SizeBytes is the size of the memory representation of FUSEMkdirIn.\n+// 1 extra byte for null-terminated Name string.\n+func (r *FUSEMkdirIn) SizeBytes() int {\n+ return r.MkdirMeta.SizeBytes() + len(r.Name) + 1\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/BUILD", "new_path": "pkg/sentry/fsimpl/fuse/BUILD", "diff": "@@ -31,6 +31,7 @@ go_library(\nsrcs = [\n\"connection.go\",\n\"dev.go\",\n+ \"directory.go\",\n\"file.go\",\n\"fusefs.go\",\n\"init.go\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fsimpl/fuse/directory.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package fuse\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n+)\n+\n+type directoryFD struct {\n+ fileDescription\n+}\n+\n+// Allocate implements directoryFD.Allocate.\n+func (directoryFD) Allocate(ctx context.Context, mode, offset, length uint64) error {\n+ return syserror.EISDIR\n+}\n+\n+// PRead implements FileDescriptionImpl.PRead.\n+func (directoryFD) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts vfs.ReadOptions) (int64, error) {\n+ return 0, syserror.EISDIR\n+}\n+\n+// Read implements FileDescriptionImpl.Read.\n+func (directoryFD) Read(ctx context.Context, dst usermem.IOSequence, opts vfs.ReadOptions) (int64, error) {\n+ return 0, syserror.EISDIR\n+}\n+\n+// PWrite implements FileDescriptionImpl.PWrite.\n+func (directoryFD) PWrite(ctx context.Context, src usermem.IOSequence, offset int64, opts vfs.WriteOptions) (int64, error) {\n+ return 0, syserror.EISDIR\n+}\n+\n+// Write implements FileDescriptionImpl.Write.\n+func (directoryFD) Write(ctx context.Context, src usermem.IOSequence, opts vfs.WriteOptions) (int64, error) {\n+ return 0, syserror.EISDIR\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "new_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "diff": "@@ -262,8 +262,17 @@ func (i *inode) Open(ctx context.Context, rp *vfs.ResolvingPath, vfsd *vfs.Dentr\nreturn nil, syserror.EOVERFLOW\n}\n+ var fd *fileDescription\n+ var fdImpl vfs.FileDescriptionImpl\n+ if isDir {\n+ directoryFD := &directoryFD{}\n+ fd = &(directoryFD.fileDescription)\n+ fdImpl = directoryFD\n+ } else {\n// FOPEN_KEEP_CACHE is the defualt flag for noOpen.\n- fd := fileDescription{OpenFlag: linux.FOPEN_KEEP_CACHE}\n+ fd = &fileDescription{OpenFlag: linux.FOPEN_KEEP_CACHE}\n+ fdImpl = fd\n+ }\n// Only send open request when FUSE server support open or is opening a directory.\nif !i.fs.conn.noOpen || isDir {\nkernelTask := kernel.TaskFromContext(ctx)\n@@ -330,7 +339,7 @@ func (i *inode) Open(ctx context.Context, rp *vfs.ResolvingPath, vfsd *vfs.Dentr\ni.attributeTime = 0\n}\n- if err := fd.vfsfd.Init(&fd, opts.Flags, rp.Mount(), vfsd, fdOptions); err != nil {\n+ if err := fd.vfsfd.Init(fdImpl, opts.Flags, rp.Mount(), vfsd, fdOptions); err != nil {\nreturn nil, err\n}\nreturn &fd.vfsfd, nil\n@@ -374,6 +383,18 @@ func (i *inode) NewSymlink(ctx context.Context, name, target string) (*vfs.Dentr\nreturn i.newEntry(ctx, name, linux.S_IFLNK, linux.FUSE_SYMLINK, &in)\n}\n+// NewDir implements kernfs.Inode.NewDir.\n+func (i *inode) NewDir(ctx context.Context, name string, opts vfs.MkdirOptions) (*vfs.Dentry, error) {\n+ in := linux.FUSEMkdirIn{\n+ MkdirMeta: linux.FUSEMkdirMeta{\n+ Mode: uint32(opts.Mode),\n+ Umask: uint32(kernel.TaskFromContext(ctx).FSContext().Umask()),\n+ },\n+ Name: name,\n+ }\n+ return i.newEntry(ctx, name, linux.S_IFDIR, linux.FUSE_MKDIR, &in)\n+}\n+\n// newEntry calls FUSE server for entry creation and allocates corresponding entry according to response.\n// Shared by FUSE_MKNOD, FUSE_MKDIR, FUSE_SYMLINK, FUSE_LINK and FUSE_LOOKUP.\nfunc (i *inode) newEntry(ctx context.Context, name string, fileType linux.FileMode, opcode linux.FUSEOpcode, payload marshal.Marshallable) (*vfs.Dentry, error) {\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/BUILD", "new_path": "test/fuse/BUILD", "diff": "@@ -31,3 +31,8 @@ syscall_test(\nfuse = \"True\",\ntest = \"//test/fuse/linux:readlink_test\",\n)\n+\n+syscall_test(\n+ fuse = \"True\",\n+ test = \"//test/fuse/linux:mkdir_test\",\n+)\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/BUILD", "new_path": "test/fuse/linux/BUILD", "diff": "@@ -84,6 +84,20 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"mkdir_test\",\n+ testonly = 1,\n+ srcs = [\"mkdir_test.cc\"],\n+ deps = [\n+ gtest,\n+ \":fuse_base\",\n+ \"//test/util:fuse_util\",\n+ \"//test/util:temp_umask\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n+\ncc_library(\nname = \"fuse_base\",\ntestonly = 1,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/fuse/linux/mkdir_test.cc", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <errno.h>\n+#include <fcntl.h>\n+#include <linux/fuse.h>\n+#include <sys/stat.h>\n+#include <sys/statfs.h>\n+#include <sys/types.h>\n+#include <unistd.h>\n+\n+#include <string>\n+#include <vector>\n+\n+#include \"gtest/gtest.h\"\n+#include \"test/fuse/linux/fuse_base.h\"\n+#include \"test/util/fuse_util.h\"\n+#include \"test/util/temp_umask.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+class MkdirTest : public FuseTest {\n+ protected:\n+ const std::string test_dir_ = \"test_dir\";\n+ const mode_t perms_ = S_IRWXU | S_IRWXG | S_IRWXO;\n+};\n+\n+TEST_F(MkdirTest, CreateDir) {\n+ const std::string test_dir_path_ =\n+ JoinPath(mount_point_.path().c_str(), test_dir_);\n+ const mode_t new_umask = 0077;\n+\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_entry_out),\n+ };\n+ struct fuse_entry_out out_payload = DefaultEntryOut(S_IFDIR | perms_, 5);\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload);\n+ SetServerResponse(FUSE_MKDIR, iov_out);\n+ TempUmask mask(new_umask);\n+ ASSERT_THAT(mkdir(test_dir_path_.c_str(), 0777), SyscallSucceeds());\n+\n+ struct fuse_in_header in_header;\n+ struct fuse_mkdir_in in_payload;\n+ std::vector<char> actual_dir(test_dir_.length() + 1);\n+ auto iov_in = FuseGenerateIovecs(in_header, in_payload, actual_dir);\n+ GetServerActualRequest(iov_in);\n+\n+ EXPECT_EQ(in_header.len,\n+ sizeof(in_header) + sizeof(in_payload) + test_dir_.length() + 1);\n+ EXPECT_EQ(in_header.opcode, FUSE_MKDIR);\n+ EXPECT_EQ(in_payload.mode & 0777, perms_ & ~new_umask);\n+ EXPECT_EQ(in_payload.umask, new_umask);\n+ EXPECT_EQ(std::string(actual_dir.data()), test_dir_);\n+}\n+\n+TEST_F(MkdirTest, FileTypeError) {\n+ const std::string test_dir_path_ =\n+ JoinPath(mount_point_.path().c_str(), test_dir_);\n+\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_entry_out),\n+ };\n+ struct fuse_entry_out out_payload = DefaultEntryOut(S_IFREG | perms_, 5);\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload);\n+ SetServerResponse(FUSE_MKDIR, iov_out);\n+ ASSERT_THAT(mkdir(test_dir_path_.c_str(), 0777), SyscallFailsWithErrno(EIO));\n+ SkipServerActualRequest();\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Implement FUSE_MKDIR Fixes #3392
260,022
11.08.2020 12:13:01
14,400
bc07df88878f47a496f8b364b286bf0b11c0e76f
Implement FUSE_RMDIR Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/fuse.go", "new_path": "pkg/abi/linux/fuse.go", "diff": "@@ -569,3 +569,29 @@ func (r *FUSEMkdirIn) MarshalUnsafe(buf []byte) {\nfunc (r *FUSEMkdirIn) SizeBytes() int {\nreturn r.MkdirMeta.SizeBytes() + len(r.Name) + 1\n}\n+\n+// FUSERmDirIn is the request sent by the kernel to the daemon\n+// when trying to remove a directory.\n+//\n+// Dynamically-sized objects cannot be marshalled.\n+type FUSERmDirIn struct {\n+ marshal.StubMarshallable\n+\n+ // Name is a directory name to be looked up.\n+ Name string\n+}\n+\n+// MarshalUnsafe serializes r.name to the dst buffer.\n+func (r *FUSERmDirIn) MarshalUnsafe(buf []byte) {\n+ copy(buf, r.Name)\n+}\n+\n+// SizeBytes is the size of the memory representation of FUSERmDirIn.\n+func (r *FUSERmDirIn) SizeBytes() int {\n+ return len(r.Name) + 1\n+}\n+\n+// UnmarshalUnsafe deserializes r.name from the src buffer.\n+func (r *FUSERmDirIn) UnmarshalUnsafe(src []byte) {\n+ r.Name = string(src)\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "new_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "diff": "@@ -426,6 +426,33 @@ func (i *inode) NewDir(ctx context.Context, name string, opts vfs.MkdirOptions)\nreturn i.newEntry(ctx, name, linux.S_IFDIR, linux.FUSE_MKDIR, &in)\n}\n+// RmDir implements kernfs.Inode.RmDir.\n+func (i *inode) RmDir(ctx context.Context, name string, child *vfs.Dentry) error {\n+ fusefs := i.fs\n+ task, creds := kernel.TaskFromContext(ctx), auth.CredentialsFromContext(ctx)\n+\n+ in := linux.FUSERmDirIn{Name: name}\n+ req, err := fusefs.conn.NewRequest(creds, uint32(task.ThreadID()), i.NodeID, linux.FUSE_RMDIR, &in)\n+ if err != nil {\n+ return err\n+ }\n+\n+ res, err := i.fs.conn.Call(task, req)\n+ if err != nil {\n+ return err\n+ }\n+ if err := res.Error(); err != nil {\n+ return err\n+ }\n+\n+ // TODO(Before merging): When creating new nodes, should we add nodes to the ordered children?\n+ // If so we'll probably need to call this. We will also need to add them with the writable flag when\n+ // appropriate.\n+ // return i.OrderedChildren.RmDir(ctx, name, child)\n+\n+ return nil\n+}\n+\n// newEntry calls FUSE server for entry creation and allocates corresponding entry according to response.\n// Shared by FUSE_MKNOD, FUSE_MKDIR, FUSE_SYMLINK, FUSE_LINK and FUSE_LOOKUP.\nfunc (i *inode) newEntry(ctx context.Context, name string, fileType linux.FileMode, opcode linux.FUSEOpcode, payload marshal.Marshallable) (*vfs.Dentry, error) {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "diff": "@@ -657,6 +657,10 @@ func (fs *Filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\nfunc (fs *Filesystem) RmdirAt(ctx context.Context, rp *vfs.ResolvingPath) error {\nfs.mu.Lock()\ndefer fs.mu.Unlock()\n+\n+ // Store the name before walkExistingLocked as rp will be advanced past the\n+ // name in the following call.\n+ name := rp.Component()\nvfsd, inode, err := fs.walkExistingLocked(ctx, rp)\nfs.processDeferredDecRefsLocked(ctx)\nif err != nil {\n@@ -686,7 +690,8 @@ func (fs *Filesystem) RmdirAt(ctx context.Context, rp *vfs.ResolvingPath) error\nif err := virtfs.PrepareDeleteDentry(mntns, vfsd); err != nil {\nreturn err\n}\n- if err := parentDentry.inode.RmDir(ctx, rp.Component(), vfsd); err != nil {\n+\n+ if err := parentDentry.inode.RmDir(ctx, name, vfsd); err != nil {\nvirtfs.AbortDeleteDentry(vfsd)\nreturn err\n}\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/BUILD", "new_path": "test/fuse/BUILD", "diff": "@@ -41,3 +41,9 @@ syscall_test(\nfuse = \"True\",\ntest = \"//test/fuse/linux:read_test\",\n)\n+\n+syscall_test(\n+ test = \"//test/fuse/linux:rmdir_test\",\n+ vfs2 = \"True\",\n+ fuse = \"True\",\n+)\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/BUILD", "new_path": "test/fuse/linux/BUILD", "diff": "@@ -98,6 +98,20 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"rmdir_test\",\n+ testonly = 1,\n+ srcs = [\"rmdir_test.cc\"],\n+ deps = [\n+ gtest,\n+ \":fuse_base\",\n+ \"//test/util:fs_util\",\n+ \"//test/util:fuse_util\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n+\ncc_library(\nname = \"fuse_base\",\ntestonly = 1,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/fuse/linux/rmdir_test.cc", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <errno.h>\n+#include <fcntl.h>\n+#include <linux/fuse.h>\n+#include <sys/stat.h>\n+#include <sys/statfs.h>\n+#include <sys/types.h>\n+#include <sys/uio.h>\n+#include <unistd.h>\n+\n+#include <string>\n+#include <vector>\n+\n+#include \"gtest/gtest.h\"\n+#include \"test/fuse/linux/fuse_base.h\"\n+#include \"test/util/fs_util.h\"\n+#include \"test/util/fuse_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+class RmDirTest : public FuseTest {\n+ protected:\n+ const std::string test_dir_name_ = \"test_dir\";\n+ const mode_t test_dir_mode_ = S_IFDIR | S_IRWXU | S_IRWXG | S_IRWXO;\n+};\n+\n+TEST_F(RmDirTest, NormalRmDir) {\n+ const std::string test_dir_path_ =\n+ JoinPath(mount_point_.path().c_str(), test_dir_name_);\n+\n+ SetServerInodeLookup(test_dir_name_, test_dir_mode_);\n+\n+ // RmDir code.\n+ struct fuse_out_header rmdir_header = {\n+ .len = sizeof(struct fuse_out_header),\n+ };\n+\n+ auto iov_out = FuseGenerateIovecs(rmdir_header);\n+ SetServerResponse(FUSE_RMDIR, iov_out);\n+\n+ ASSERT_THAT(rmdir(test_dir_path_.c_str()), SyscallSucceeds());\n+\n+ struct fuse_in_header in_header;\n+ std::vector<char> actual_dirname(test_dir_name_.length() + 1);\n+ auto iov_in = FuseGenerateIovecs(in_header, actual_dirname);\n+ GetServerActualRequest(iov_in);\n+\n+ EXPECT_EQ(in_header.len, sizeof(in_header) + test_dir_name_.length() + 1);\n+ EXPECT_EQ(in_header.opcode, FUSE_RMDIR);\n+ EXPECT_EQ(std::string(actual_dirname.data()), test_dir_name_);\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Implement FUSE_RMDIR Fixes #3587 Co-authored-by: Craig Chi <[email protected]>
260,022
27.07.2020 14:42:31
14,400
4a5857d644ae0e62090bbbed86852dceca79395c
fuse: Implement IterDirents for directory file description Fixes This change adds support for IterDirents. You can now use `ls` in the FUSE sandbox.
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/fuse.go", "new_path": "pkg/abi/linux/fuse.go", "diff": "package linux\n-import \"gvisor.dev/gvisor/tools/go_marshal/marshal\"\n+import (\n+ \"gvisor.dev/gvisor/tools/go_marshal/marshal\"\n+ \"gvisor.dev/gvisor/tools/go_marshal/primitive\"\n+)\n// +marshal\ntype FUSEOpcode uint32\n@@ -595,3 +598,123 @@ func (r *FUSERmDirIn) SizeBytes() int {\nfunc (r *FUSERmDirIn) UnmarshalUnsafe(src []byte) {\nr.Name = string(src)\n}\n+\n+// FUSEDirents is a list of Dirents received from the FUSE daemon server.\n+// It is used for FUSE_READDIR.\n+//\n+// Dynamically-sized objects cannot be marshalled.\n+type FUSEDirents struct {\n+ marshal.StubMarshallable\n+\n+ Dirents []*FUSEDirent\n+}\n+\n+// FUSEDirent is a Dirent received from the FUSE daemon server.\n+// It is used for FUSE_READDIR.\n+//\n+// Dynamically-sized objects cannot be marshalled.\n+type FUSEDirent struct {\n+ marshal.StubMarshallable\n+\n+ // Meta contains all the static fields of FUSEDirent.\n+ Meta FUSEDirentMeta\n+\n+ // Name is the filename of the dirent.\n+ Name string\n+}\n+\n+// FUSEDirentMeta contains all the static fields of FUSEDirent.\n+// It is used for FUSE_READDIR.\n+//\n+// +marshal\n+type FUSEDirentMeta struct {\n+ // Inode of the dirent.\n+ Ino uint64\n+\n+ // Offset of the dirent.\n+ Off uint64\n+\n+ // NameLen is the length of the dirent name.\n+ NameLen uint32\n+\n+ // Type of the dirent.\n+ Type uint32\n+}\n+\n+// MarshalUnsafe serializes FUSEDirents to the dst buffer.\n+func (r *FUSEDirents) MarshalUnsafe(dst []byte) {\n+ for _, dirent := range r.Dirents {\n+ dirent.MarshalUnsafe(dst)\n+ dst = dst[dirent.SizeBytes():]\n+ }\n+}\n+\n+// SizeBytes is the size of the memory representation of FUSEDirents.\n+func (r *FUSEDirents) SizeBytes() int {\n+ var sizeBytes int\n+ for _, dirent := range r.Dirents {\n+ sizeBytes += dirent.SizeBytes()\n+ }\n+\n+ return sizeBytes\n+}\n+\n+// UnmarshalUnsafe deserializes FUSEDirents from the src buffer.\n+func (r *FUSEDirents) UnmarshalUnsafe(src []byte) {\n+ for {\n+ if len(src) <= (*FUSEDirentMeta)(nil).SizeBytes() {\n+ break\n+ }\n+\n+ // Its unclear how many dirents there are in src. Each dirent is dynamically\n+ // sized and so we can't make assumptions about how many dirents we can allocate.\n+ if r.Dirents == nil {\n+ r.Dirents = make([]*FUSEDirent, 0)\n+ }\n+\n+ // We have to allocate a struct for each dirent - there must be a better way\n+ // to do this. Linux allocates 1 page to store all the dirents and then\n+ // simply reads them from the page.\n+ var dirent FUSEDirent\n+ dirent.UnmarshalUnsafe(src)\n+ r.Dirents = append(r.Dirents, &dirent)\n+\n+ src = src[dirent.SizeBytes():]\n+ }\n+}\n+\n+// MarshalUnsafe serializes FUSEDirent to the dst buffer.\n+func (r *FUSEDirent) MarshalUnsafe(dst []byte) {\n+ r.Meta.MarshalUnsafe(dst)\n+ dst = dst[r.Meta.SizeBytes():]\n+\n+ name := primitive.ByteSlice(r.Name)\n+ name.MarshalUnsafe(dst)\n+}\n+\n+// SizeBytes is the size of the memory representation of FUSEDirent.\n+func (r *FUSEDirent) SizeBytes() int {\n+ dataSize := r.Meta.SizeBytes() + len(r.Name)\n+\n+ // Each Dirent must be padded such that its size is a multiple\n+ // of FUSE_DIRENT_ALIGN. Similar to the fuse dirent alignment\n+ // in linux/fuse.h.\n+ return (dataSize + (FUSE_DIRENT_ALIGN - 1)) & ^(FUSE_DIRENT_ALIGN - 1)\n+}\n+\n+// UnmarshalUnsafe deserializes FUSEDirent from the src buffer.\n+func (r *FUSEDirent) UnmarshalUnsafe(src []byte) {\n+ r.Meta.UnmarshalUnsafe(src)\n+ src = src[r.Meta.SizeBytes():]\n+\n+ if r.Meta.NameLen > FUSE_NAME_MAX {\n+ // The name is too long and therefore invalid. We don't\n+ // need to unmarshal the name since it'll be thrown away.\n+ return\n+ }\n+\n+ buf := make([]byte, r.Meta.NameLen)\n+ name := primitive.ByteSlice(buf)\n+ name.UnmarshalUnsafe(src[:r.Meta.NameLen])\n+ r.Name = string(name)\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/connection.go", "new_path": "pkg/sentry/fsimpl/fuse/connection.go", "diff": "@@ -21,6 +21,8 @@ import (\n\"sync/atomic\"\n\"syscall\"\n+ \"gvisor.dev/gvisor/tools/go_marshal/marshal\"\n+\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/log\"\n@@ -352,6 +354,12 @@ func (r *Response) UnmarshalPayload(m marshal.Marshallable) error {\nreturn fmt.Errorf(\"payload too small. Minimum data lenth required: %d, but got data length %d\", wantDataLen, haveDataLen)\n}\n+ // The response data is empty unless there is some payload. And so, doesn't\n+ // need to be unmarshalled.\n+ if r.data == nil {\n+ return nil\n+ }\n+\nm.UnmarshalUnsafe(r.data[hdrLen:])\nreturn nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/directory.go", "new_path": "pkg/sentry/fsimpl/fuse/directory.go", "diff": "package fuse\nimport (\n+ \"sync/atomic\"\n+\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n@@ -49,3 +54,52 @@ func (directoryFD) PWrite(ctx context.Context, src usermem.IOSequence, offset in\nfunc (directoryFD) Write(ctx context.Context, src usermem.IOSequence, opts vfs.WriteOptions) (int64, error) {\nreturn 0, syserror.EISDIR\n}\n+\n+// IterDirents implements FileDescriptionImpl.IterDirents.\n+func (dir *directoryFD) IterDirents(ctx context.Context, callback vfs.IterDirentsCallback) error {\n+ fusefs := dir.inode().fs\n+ task, creds := kernel.TaskFromContext(ctx), auth.CredentialsFromContext(ctx)\n+\n+ in := linux.FUSEReadIn{\n+ Fh: dir.Fh,\n+ Offset: uint64(atomic.LoadInt64(&dir.off)),\n+ Size: linux.FUSE_PAGE_SIZE,\n+ Flags: dir.statusFlags(),\n+ }\n+\n+ /// TODO(gVisor.dev/issue/3404): Support FUSE_READDIRPLUS.\n+ req, err := fusefs.conn.NewRequest(creds, uint32(task.ThreadID()), dir.inode().NodeID, linux.FUSE_READDIR, &in)\n+ if err != nil {\n+ return err\n+ }\n+\n+ res, err := fusefs.conn.Call(task, req)\n+ if err != nil {\n+ return err\n+ }\n+ if err := res.Error(); err != nil {\n+ return err\n+ }\n+\n+ var out linux.FUSEDirents\n+ if err := res.UnmarshalPayload(&out); err != nil {\n+ return err\n+ }\n+\n+ for _, fuseDirent := range out.Dirents {\n+ nextOff := int64(fuseDirent.Meta.Off) + 1\n+ dirent := vfs.Dirent{\n+ Name: fuseDirent.Name,\n+ Type: uint8(fuseDirent.Meta.Type),\n+ Ino: fuseDirent.Meta.Ino,\n+ NextOff: nextOff,\n+ }\n+\n+ if err := callback.Handle(dirent); err != nil {\n+ return err\n+ }\n+ atomic.StoreInt64(&dir.off, nextOff)\n+ }\n+\n+ return nil\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/file.go", "new_path": "pkg/sentry/fsimpl/fuse/file.go", "diff": "@@ -42,6 +42,9 @@ type fileDescription struct {\n// OpenFlag is the flag returned by open.\nOpenFlag uint32\n+\n+ // off is the file offset.\n+ off int64\n}\nfunc (fd *fileDescription) dentry() *kernfs.Dentry {\n@@ -119,5 +122,6 @@ func (fd *fileDescription) Stat(ctx context.Context, opts vfs.StatOptions) (linu\n// SetStat implements FileDescriptionImpl.SetStat.\nfunc (fd *fileDescription) SetStat(ctx context.Context, opts vfs.SetStatOptions) error {\n- return nil\n+ creds := auth.CredentialsFromContext(ctx)\n+ return fd.inode().SetStat(ctx, fd.inode().fs.VFSFilesystem(), creds, opts)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/kernfs.go", "new_path": "pkg/sentry/fsimpl/kernfs/kernfs.go", "diff": "@@ -425,7 +425,7 @@ type inodeDynamicLookup interface {\nValid(ctx context.Context) bool\n// IterDirents is used to iterate over dynamically created entries. It invokes\n- // cb on each entry in the directory represented by the FileDescription.\n+ // cb on each entry in the directory represented by the Inode.\n// 'offset' is the offset for the entire IterDirents call, which may include\n// results from the caller (e.g. \".\" and \"..\"). 'relOffset' is the offset\n// inside the entries returned by this IterDirents invocation. In other words,\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description_impl_util.go", "new_path": "pkg/sentry/vfs/file_description_impl_util.go", "diff": "@@ -107,7 +107,7 @@ func (FileDescriptionDefaultImpl) Write(ctx context.Context, src usermem.IOSeque\n// file_operations::iterate == file_operations::iterate_shared == NULL in\n// Linux.\nfunc (FileDescriptionDefaultImpl) IterDirents(ctx context.Context, cb IterDirentsCallback) error {\n- return syserror.ENOTDIR\n+ return syserror.ENOSYS\n}\n// Seek implements FileDescriptionImpl.Seek analogously to\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/BUILD", "new_path": "test/fuse/BUILD", "diff": "@@ -43,7 +43,11 @@ syscall_test(\n)\nsyscall_test(\n+ fuse = \"True\",\ntest = \"//test/fuse/linux:rmdir_test\",\n- vfs2 = \"True\",\n+)\n+\n+syscall_test(\nfuse = \"True\",\n+ test = \"//test/fuse/linux:readdir_test\",\n)\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/BUILD", "new_path": "test/fuse/linux/BUILD", "diff": "@@ -112,6 +112,20 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"readdir_test\",\n+ testonly = 1,\n+ srcs = [\"readdir_test.cc\"],\n+ deps = [\n+ gtest,\n+ \":fuse_base\",\n+ \"//test/util:fs_util\",\n+ \"//test/util:fuse_util\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n+\ncc_library(\nname = \"fuse_base\",\ntestonly = 1,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/fuse/linux/readdir_test.cc", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <errno.h>\n+#include <fcntl.h>\n+#include <linux/fuse.h>\n+#include <sys/stat.h>\n+#include <sys/statfs.h>\n+#include <sys/types.h>\n+#include <unistd.h>\n+\n+#include <string>\n+\n+#include \"gtest/gtest.h\"\n+#include \"test/fuse/linux/fuse_base.h\"\n+#include \"test/util/fuse_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+#define FUSE_NAME_OFFSET offsetof(struct fuse_dirent, name)\n+#define FUSE_DIRENT_ALIGN(x) \\\n+ (((x) + sizeof(uint64_t) - 1) & ~(sizeof(uint64_t) - 1))\n+#define FUSE_DIRENT_SIZE(d) FUSE_DIRENT_ALIGN(FUSE_NAME_OFFSET + (d)->namelen)\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+class ReaddirTest : public FuseTest {\n+ public:\n+ void fill_fuse_dirent(char *buf, const char *name) {\n+ size_t namelen = strlen(name);\n+ size_t entlen = FUSE_NAME_OFFSET + namelen;\n+ size_t entlen_padded = FUSE_DIRENT_ALIGN(entlen);\n+ struct fuse_dirent *dirent;\n+\n+ dirent = reinterpret_cast<struct fuse_dirent *>(buf);\n+ dirent->namelen = namelen;\n+ memcpy(dirent->name, name, namelen);\n+ memset(dirent->name + namelen, 0, entlen_padded - entlen);\n+ }\n+\n+ protected:\n+ const std::string test_dir_name_ = \"test_dir\";\n+};\n+\n+TEST_F(ReaddirTest, SingleEntry) {\n+ const std::string test_dir_path =\n+ JoinPath(mount_point_.path().c_str(), test_dir_name_);\n+\n+ // We need to make sure the test dir is a directory that can be found.\n+ mode_t expected_mode =\n+ S_IFDIR | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;\n+ struct fuse_attr dir_attr = {\n+ .ino = 1,\n+ .size = 512,\n+ .blocks = 4,\n+ .mode = expected_mode,\n+ .blksize = 4096,\n+ };\n+ struct fuse_out_header stat_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_attr_out),\n+ };\n+\n+ struct fuse_attr_out stat_payload = {\n+ .attr_valid_nsec = 2,\n+ .attr = dir_attr,\n+ };\n+\n+ // We need to make sure the test dir is a directory that can be found.\n+ struct fuse_out_header lookup_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_entry_out),\n+ };\n+ struct fuse_entry_out lookup_payload = {\n+ .nodeid = 1,\n+ .entry_valid = true,\n+ .attr_valid = true,\n+ .attr = dir_attr,\n+ };\n+\n+ struct fuse_out_header open_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_open_out),\n+ };\n+ struct fuse_open_out open_payload = {\n+ .fh = 1,\n+ };\n+ auto iov_out = FuseGenerateIovecs(lookup_header, lookup_payload);\n+ SetServerResponse(FUSE_LOOKUP, iov_out);\n+\n+ iov_out = FuseGenerateIovecs(open_header, open_payload);\n+ SetServerResponse(FUSE_OPENDIR, iov_out);\n+\n+ iov_out = FuseGenerateIovecs(stat_header, stat_payload);\n+ SetServerResponse(FUSE_GETATTR, iov_out);\n+\n+ DIR *dir = opendir(test_dir_path.c_str());\n+\n+ // The opendir command makes three syscalls. Lookup the dir file, stat it and\n+ // open.\n+ // We don't need to inspect those headers in this test.\n+ SkipServerActualRequest(); // LOOKUP.\n+ SkipServerActualRequest(); // GETATTR.\n+ SkipServerActualRequest(); // OPENDIR.\n+\n+ // Readdir test code.\n+ std::string dot = \".\";\n+ std::string dot_dot = \"..\";\n+ std::string test_file = \"testFile\";\n+\n+ // Figure out how many dirents to send over and allocate them appropriately.\n+ // Each dirent has a dynamic name and a static metadata part. The dirent size\n+ // is aligned to being a multiple of 8.\n+ size_t dot_file_dirent_size =\n+ FUSE_DIRENT_ALIGN(dot.length() + FUSE_NAME_OFFSET);\n+ size_t dot_dot_file_dirent_size =\n+ FUSE_DIRENT_ALIGN(dot_dot.length() + FUSE_NAME_OFFSET);\n+ size_t test_file_dirent_size =\n+ FUSE_DIRENT_ALIGN(test_file.length() + FUSE_NAME_OFFSET);\n+\n+ // Create an appropriately sized payload.\n+ size_t readdir_payload_size =\n+ test_file_dirent_size + dot_file_dirent_size + dot_dot_file_dirent_size;\n+ char readdir_payload[readdir_payload_size];\n+\n+ fill_fuse_dirent(readdir_payload, dot.c_str());\n+ fill_fuse_dirent(readdir_payload + dot_file_dirent_size, dot_dot.c_str());\n+ fill_fuse_dirent(\n+ readdir_payload + dot_file_dirent_size + dot_dot_file_dirent_size,\n+ test_file.c_str());\n+\n+ std::vector<char> readdir_payload_vec(readdir_payload,\n+ readdir_payload + readdir_payload_size);\n+ struct fuse_out_header readdir_header = {\n+ .len = uint32_t(sizeof(struct fuse_out_header) + sizeof(readdir_payload)),\n+ };\n+ struct fuse_out_header readdir_header_break = {\n+ .len = uint32_t(sizeof(struct fuse_out_header)),\n+ };\n+\n+ iov_out = FuseGenerateIovecs(readdir_header, readdir_payload_vec);\n+ SetServerResponse(FUSE_READDIR, iov_out);\n+\n+ iov_out = FuseGenerateIovecs(readdir_header_break);\n+ SetServerResponse(FUSE_READDIR, iov_out);\n+\n+ struct dirent *entry;\n+ entry = readdir(dir);\n+ EXPECT_EQ(std::string(entry->d_name), dot);\n+\n+ entry = readdir(dir);\n+ EXPECT_EQ(std::string(entry->d_name), dot_dot);\n+\n+ entry = readdir(dir);\n+ EXPECT_EQ(std::string(entry->d_name), test_file);\n+\n+ entry = readdir(dir);\n+ EXPECT_TRUE((entry == NULL));\n+\n+ SkipServerActualRequest(); // READDIR.\n+ SkipServerActualRequest(); // READDIR with no data.\n+\n+ // Clean up.\n+ closedir(dir);\n+\n+ struct fuse_in_header in_header;\n+ struct fuse_release_in in_payload;\n+\n+ auto iov_in = FuseGenerateIovecs(in_header, in_payload);\n+ GetServerActualRequest(iov_in);\n+ EXPECT_EQ(in_header.len, sizeof(in_header) + sizeof(in_payload));\n+ EXPECT_EQ(in_header.opcode, FUSE_RELEASEDIR);\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n\\ No newline at end of file\n" } ]
Go
Apache License 2.0
google/gvisor
fuse: Implement IterDirents for directory file description Fixes #3255. This change adds support for IterDirents. You can now use `ls` in the FUSE sandbox. Co-authored-by: Craig Chi <[email protected]>
260,022
19.08.2020 20:11:59
14,400
d51ddcefdc46a1007f7345bfa2f7006bb820b157
fuse: use safe go_marshal API for FUSE Until is resolved, this change is needed to ensure we're not corrupting memory anywhere.
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/fuse.go", "new_path": "pkg/abi/linux/fuse.go", "diff": "@@ -359,7 +359,12 @@ type FUSELookupIn struct {\n// MarshalUnsafe serializes r.name to the dst buffer.\nfunc (r *FUSELookupIn) MarshalUnsafe(buf []byte) {\n- copy(buf, []byte(r.Name))\n+ copy(buf, r.Name)\n+}\n+\n+// MarshalBytes serializes r.name to the dst buffer.\n+func (r *FUSELookupIn) MarshalBytes(buf []byte) {\n+ copy(buf, r.Name)\n}\n// SizeBytes is the size of the memory representation of FUSELookupIn.\n@@ -491,6 +496,12 @@ func (r *FUSEMknodIn) MarshalUnsafe(buf []byte) {\ncopy(buf[r.MknodMeta.SizeBytes():], r.Name)\n}\n+// MarshalBytes serializes r.MknodMeta and r.Name to the dst buffer.\n+func (r *FUSEMknodIn) MarshalBytes(buf []byte) {\n+ r.MknodMeta.MarshalBytes(buf[:r.MknodMeta.SizeBytes()])\n+ copy(buf[r.MknodMeta.SizeBytes():], r.Name)\n+}\n+\n// SizeBytes is the size of the memory representation of FUSEMknodIn.\n// 1 extra byte for null-terminated string.\nfunc (r *FUSEMknodIn) SizeBytes() int {\n@@ -518,6 +529,13 @@ func (r *FUSESymLinkIn) MarshalUnsafe(buf []byte) {\ncopy(buf[len(r.Name)+1:], r.Target)\n}\n+// MarshalBytes serializes r.Name and r.Target to the dst buffer.\n+// Left null-termination at end of r.Name and r.Target.\n+func (r *FUSESymLinkIn) MarshalBytes(buf []byte) {\n+ copy(buf, r.Name)\n+ copy(buf[len(r.Name)+1:], r.Target)\n+}\n+\n// SizeBytes is the size of the memory representation of FUSESymLinkIn.\n// 2 extra bytes for null-terminated string.\nfunc (r *FUSESymLinkIn) SizeBytes() int {\n@@ -530,6 +548,9 @@ type FUSEEmptyIn struct{ marshal.StubMarshallable }\n// MarshalUnsafe do nothing for marshal.\nfunc (r *FUSEEmptyIn) MarshalUnsafe(buf []byte) {}\n+// MarshalBytes do nothing for marshal.\n+func (r *FUSEEmptyIn) MarshalBytes(buf []byte) {}\n+\n// SizeBytes is 0 for empty request.\nfunc (r *FUSEEmptyIn) SizeBytes() int {\nreturn 0\n@@ -567,6 +588,12 @@ func (r *FUSEMkdirIn) MarshalUnsafe(buf []byte) {\ncopy(buf[r.MkdirMeta.SizeBytes():], r.Name)\n}\n+// MarshalBytes serializes r.MkdirMeta and r.Name to the dst buffer.\n+func (r *FUSEMkdirIn) MarshalBytes(buf []byte) {\n+ r.MkdirMeta.MarshalBytes(buf[:r.MkdirMeta.SizeBytes()])\n+ copy(buf[r.MkdirMeta.SizeBytes():], r.Name)\n+}\n+\n// SizeBytes is the size of the memory representation of FUSEMkdirIn.\n// 1 extra byte for null-terminated Name string.\nfunc (r *FUSEMkdirIn) SizeBytes() int {\n@@ -589,6 +616,11 @@ func (r *FUSERmDirIn) MarshalUnsafe(buf []byte) {\ncopy(buf, r.Name)\n}\n+// MarshalBytes serializes r.name to the dst buffer.\n+func (r *FUSERmDirIn) MarshalBytes(buf []byte) {\n+ copy(buf, r.Name)\n+}\n+\n// SizeBytes is the size of the memory representation of FUSERmDirIn.\nfunc (r *FUSERmDirIn) SizeBytes() int {\nreturn len(r.Name) + 1\n@@ -599,6 +631,11 @@ func (r *FUSERmDirIn) UnmarshalUnsafe(src []byte) {\nr.Name = string(src)\n}\n+// UnmarshalBytes deserializes r.name from the src buffer.\n+func (r *FUSERmDirIn) UnmarshalBytes(src []byte) {\n+ r.Name = string(src)\n+}\n+\n// FUSEDirents is a list of Dirents received from the FUSE daemon server.\n// It is used for FUSE_READDIR.\n//\n@@ -649,6 +686,14 @@ func (r *FUSEDirents) MarshalUnsafe(dst []byte) {\n}\n}\n+// MarshalBytes serializes FUSEDirents to the dst buffer.\n+func (r *FUSEDirents) MarshalBytes(dst []byte) {\n+ for _, dirent := range r.Dirents {\n+ dirent.MarshalBytes(dst)\n+ dst = dst[dirent.SizeBytes():]\n+ }\n+}\n+\n// SizeBytes is the size of the memory representation of FUSEDirents.\nfunc (r *FUSEDirents) SizeBytes() int {\nvar sizeBytes int\n@@ -683,6 +728,30 @@ func (r *FUSEDirents) UnmarshalUnsafe(src []byte) {\n}\n}\n+// UnmarshalBytes deserializes FUSEDirents from the src buffer.\n+func (r *FUSEDirents) UnmarshalBytes(src []byte) {\n+ for {\n+ if len(src) <= (*FUSEDirentMeta)(nil).SizeBytes() {\n+ break\n+ }\n+\n+ // Its unclear how many dirents there are in src. Each dirent is dynamically\n+ // sized and so we can't make assumptions about how many dirents we can allocate.\n+ if r.Dirents == nil {\n+ r.Dirents = make([]*FUSEDirent, 0)\n+ }\n+\n+ // We have to allocate a struct for each dirent - there must be a better way\n+ // to do this. Linux allocates 1 page to store all the dirents and then\n+ // simply reads them from the page.\n+ var dirent FUSEDirent\n+ dirent.UnmarshalBytes(src)\n+ r.Dirents = append(r.Dirents, &dirent)\n+\n+ src = src[dirent.SizeBytes():]\n+ }\n+}\n+\n// MarshalUnsafe serializes FUSEDirent to the dst buffer.\nfunc (r *FUSEDirent) MarshalUnsafe(dst []byte) {\nr.Meta.MarshalUnsafe(dst)\n@@ -692,6 +761,15 @@ func (r *FUSEDirent) MarshalUnsafe(dst []byte) {\nname.MarshalUnsafe(dst)\n}\n+// MarshalBytes serializes FUSEDirent to the dst buffer.\n+func (r *FUSEDirent) MarshalBytes(dst []byte) {\n+ r.Meta.MarshalBytes(dst)\n+ dst = dst[r.Meta.SizeBytes():]\n+\n+ name := primitive.ByteSlice(r.Name)\n+ name.MarshalBytes(dst)\n+}\n+\n// SizeBytes is the size of the memory representation of FUSEDirent.\nfunc (r *FUSEDirent) SizeBytes() int {\ndataSize := r.Meta.SizeBytes() + len(r.Name)\n@@ -718,3 +796,20 @@ func (r *FUSEDirent) UnmarshalUnsafe(src []byte) {\nname.UnmarshalUnsafe(src[:r.Meta.NameLen])\nr.Name = string(name)\n}\n+\n+// UnmarshalBytes deserializes FUSEDirent from the src buffer.\n+func (r *FUSEDirent) UnmarshalBytes(src []byte) {\n+ r.Meta.UnmarshalBytes(src)\n+ src = src[r.Meta.SizeBytes():]\n+\n+ if r.Meta.NameLen > FUSE_NAME_MAX {\n+ // The name is too long and therefore invalid. We don't\n+ // need to unmarshal the name since it'll be thrown away.\n+ return\n+ }\n+\n+ buf := make([]byte, r.Meta.NameLen)\n+ name := primitive.ByteSlice(buf)\n+ name.UnmarshalBytes(src[:r.Meta.NameLen])\n+ r.Name = string(name)\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/marshal/marshal_impl_util.go", "new_path": "pkg/marshal/marshal_impl_util.go", "diff": "@@ -44,7 +44,7 @@ func (StubMarshallable) MarshalBytes(dst []byte) {\n// UnmarshalBytes implements Marshallable.UnmarshalBytes.\nfunc (StubMarshallable) UnmarshalBytes(src []byte) {\n- panic(\"Please implement your own UnMarshalBytes function\")\n+ panic(\"Please implement your own UnmarshalBytes function\")\n}\n// Packed implements Marshallable.Packed.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/connection.go", "new_path": "pkg/sentry/fsimpl/fuse/connection.go", "diff": "@@ -271,8 +271,10 @@ func (conn *connection) NewRequest(creds *auth.Credentials, pid uint32, ino uint\n}\nbuf := make([]byte, hdr.Len)\n- hdr.MarshalUnsafe(buf[:hdrLen])\n- payload.MarshalUnsafe(buf[hdrLen:])\n+\n+ // TODO(gVisor.dev/3698): Use the unsafe version once go_marshal is safe to use again.\n+ hdr.MarshalBytes(buf[:hdrLen])\n+ payload.MarshalBytes(buf[hdrLen:])\nreturn &Request{\nid: hdr.Unique,\n@@ -360,7 +362,8 @@ func (r *Response) UnmarshalPayload(m marshal.Marshallable) error {\nreturn nil\n}\n- m.UnmarshalUnsafe(r.data[hdrLen:])\n+ // TODO(gVisor.dev/3698): Use the unsafe version once go_marshal is safe to use again.\n+ m.UnmarshalBytes(r.data[hdrLen:])\nreturn nil\n}\n" } ]
Go
Apache License 2.0
google/gvisor
fuse: use safe go_marshal API for FUSE Until #3698 is resolved, this change is needed to ensure we're not corrupting memory anywhere.
259,983
19.08.2020 22:12:15
25,200
21cac9dd042f3446258387378a743b8a7cd76443
Fix FUSE_READDIR offset issue According to readdir(3), the offset attribute in struct dirent is the offset to the next dirent instead of the offset of itself. Send the successive FUSE_READDIR requests with the offset retrieved from the last entry. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/directory.go", "new_path": "pkg/sentry/fsimpl/fuse/directory.go", "diff": "@@ -87,7 +87,7 @@ func (dir *directoryFD) IterDirents(ctx context.Context, callback vfs.IterDirent\n}\nfor _, fuseDirent := range out.Dirents {\n- nextOff := int64(fuseDirent.Meta.Off) + 1\n+ nextOff := int64(fuseDirent.Meta.Off)\ndirent := vfs.Dirent{\nName: fuseDirent.Name,\nType: uint8(fuseDirent.Meta.Type),\n" } ]
Go
Apache License 2.0
google/gvisor
Fix FUSE_READDIR offset issue According to readdir(3), the offset attribute in struct dirent is the offset to the next dirent instead of the offset of itself. Send the successive FUSE_READDIR requests with the offset retrieved from the last entry. Updates #3255
259,983
20.08.2020 10:40:41
25,200
983e30c01616b40348735f894d42bbad204f6b99
Implementing inode.Getlink kernfs uses inode.Getlink to resolve symlink when look up paths. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "new_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "diff": "@@ -488,6 +488,12 @@ func (i *inode) newEntry(ctx context.Context, name string, fileType linux.FileMo\nreturn child.VFSDentry(), nil\n}\n+// Getlink implements Inode.Getlink.\n+func (i *inode) Getlink(ctx context.Context, mnt *vfs.Mount) (vfs.VirtualDentry, string, error) {\n+ path, err := i.Readlink(ctx, mnt)\n+ return vfs.VirtualDentry{}, path, err\n+}\n+\n// Readlink implements kernfs.Inode.Readlink.\nfunc (i *inode) Readlink(ctx context.Context, mnt *vfs.Mount) (string, error) {\nif i.Mode().FileType()&linux.S_IFLNK == 0 {\n" } ]
Go
Apache License 2.0
google/gvisor
Implementing inode.Getlink kernfs uses inode.Getlink to resolve symlink when look up paths. Updates #3452
259,983
20.08.2020 12:31:52
25,200
449986264f9277c4c6174fc82294fc6644923e8b
Support multiple FUSE kernel versions of FUSE_INIT response struct The fuse_init_out struct changes in different FUSE kernel versions. A FUSE server may implement older versions of fuse_init_out, but they share common attributes from the beginning. Implement variable-length marshallable interface to support older versions of ABI. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/fuse.go", "new_path": "pkg/abi/linux/fuse.go", "diff": "package linux\nimport (\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n\"gvisor.dev/gvisor/tools/go_marshal/marshal\"\n\"gvisor.dev/gvisor/tools/go_marshal/primitive\"\n)\n@@ -262,6 +263,63 @@ type FUSEInitOut struct {\n_ [8]uint32\n}\n+// FUSEInitRes is a variable-length wrapper of FUSEInitOut. The FUSE server may\n+// implement older version of FUSE protocol, which contains a FUSEInitOut with\n+// less attributes.\n+//\n+// Dynamically-sized objects cannot be marshalled.\n+type FUSEInitRes struct {\n+ marshal.StubMarshallable\n+\n+ // InitOut contains the response from the FUSE server.\n+ InitOut FUSEInitOut\n+\n+ // Len is the total length of bytes of the response.\n+ Len uint32\n+}\n+\n+// UnMarshalBytes deserializes src to the InitOut attribute in a FUSEInitRes.\n+func (r *FUSEInitRes) UnmarshalBytes(src []byte) {\n+ out := &r.InitOut\n+\n+ // Introduced before FUSE kernel version 7.13.\n+ out.Major = uint32(usermem.ByteOrder.Uint32(src[:4]))\n+ src = src[4:]\n+ out.Minor = uint32(usermem.ByteOrder.Uint32(src[:4]))\n+ src = src[4:]\n+ out.MaxReadahead = uint32(usermem.ByteOrder.Uint32(src[:4]))\n+ src = src[4:]\n+ out.Flags = uint32(usermem.ByteOrder.Uint32(src[:4]))\n+ src = src[4:]\n+ out.MaxBackground = uint16(usermem.ByteOrder.Uint16(src[:2]))\n+ src = src[2:]\n+ out.CongestionThreshold = uint16(usermem.ByteOrder.Uint16(src[:2]))\n+ src = src[2:]\n+ out.MaxWrite = uint32(usermem.ByteOrder.Uint32(src[:4]))\n+ src = src[4:]\n+\n+ // Introduced in FUSE kernel version 7.23.\n+ if len(src) >= 4 {\n+ out.TimeGran = uint32(usermem.ByteOrder.Uint32(src[:4]))\n+ src = src[4:]\n+ }\n+ // Introduced in FUSE kernel version 7.28.\n+ if len(src) >= 2 {\n+ out.MaxPages = uint16(usermem.ByteOrder.Uint16(src[:2]))\n+ src = src[2:]\n+ }\n+ // Introduced in FUSE kernel version 7.31.\n+ if len(src) >= 2 {\n+ out.MapAlignment = uint16(usermem.ByteOrder.Uint16(src[:2]))\n+ src = src[2:]\n+ }\n+}\n+\n+// SizeBytes is the size of the payload of the FUSE_INIT response.\n+func (r *FUSEInitRes) SizeBytes() int {\n+ return int(r.Len)\n+}\n+\n// FUSEGetAttrIn is the request sent by the kernel to the daemon,\n// to get the attribute of a inode.\n//\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/connection.go", "new_path": "pkg/sentry/fsimpl/fuse/connection.go", "diff": "@@ -346,6 +346,11 @@ func (r *Response) Error() error {\nreturn error(sysErrNo)\n}\n+// DataLen returns the size of the response without the header.\n+func (r *Response) DataLen() uint32 {\n+ return r.hdr.Len - uint32(r.hdr.SizeBytes())\n+}\n+\n// UnmarshalPayload unmarshals the response data into m.\nfunc (r *Response) UnmarshalPayload(m marshal.Marshallable) error {\nhdrLen := r.hdr.SizeBytes()\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/init.go", "new_path": "pkg/sentry/fsimpl/fuse/init.go", "diff": "@@ -76,12 +76,12 @@ func (conn *connection) InitRecv(res *Response, hasSysAdminCap bool) error {\nreturn err\n}\n- var out linux.FUSEInitOut\n- if err := res.UnmarshalPayload(&out); err != nil {\n+ initRes := linux.FUSEInitRes{Len: res.DataLen()}\n+ if err := res.UnmarshalPayload(&initRes); err != nil {\nreturn err\n}\n- return conn.initProcessReply(&out, hasSysAdminCap)\n+ return conn.initProcessReply(&initRes.InitOut, hasSysAdminCap)\n}\n// Process the FUSE_INIT reply from the FUSE server.\n" } ]
Go
Apache License 2.0
google/gvisor
Support multiple FUSE kernel versions of FUSE_INIT response struct The fuse_init_out struct changes in different FUSE kernel versions. A FUSE server may implement older versions of fuse_init_out, but they share common attributes from the beginning. Implement variable-length marshallable interface to support older versions of ABI. Fixes #3707
259,983
02.09.2020 13:30:56
25,200
1d8029022e8ca45e177e36405506d42874f125e9
fuse: remove unused marshalling functions This commit removes unused marshalling functions in linux abi package and moves self-defined FUSEInitRes wrapper to fuse package. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/fuse.go", "new_path": "pkg/abi/linux/fuse.go", "diff": "package linux\nimport (\n- \"gvisor.dev/gvisor/pkg/usermem\"\n\"gvisor.dev/gvisor/tools/go_marshal/marshal\"\n\"gvisor.dev/gvisor/tools/go_marshal/primitive\"\n)\n@@ -263,63 +262,6 @@ type FUSEInitOut struct {\n_ [8]uint32\n}\n-// FUSEInitRes is a variable-length wrapper of FUSEInitOut. The FUSE server may\n-// implement older version of FUSE protocol, which contains a FUSEInitOut with\n-// less attributes.\n-//\n-// Dynamically-sized objects cannot be marshalled.\n-type FUSEInitRes struct {\n- marshal.StubMarshallable\n-\n- // InitOut contains the response from the FUSE server.\n- InitOut FUSEInitOut\n-\n- // Len is the total length of bytes of the response.\n- Len uint32\n-}\n-\n-// UnMarshalBytes deserializes src to the InitOut attribute in a FUSEInitRes.\n-func (r *FUSEInitRes) UnmarshalBytes(src []byte) {\n- out := &r.InitOut\n-\n- // Introduced before FUSE kernel version 7.13.\n- out.Major = uint32(usermem.ByteOrder.Uint32(src[:4]))\n- src = src[4:]\n- out.Minor = uint32(usermem.ByteOrder.Uint32(src[:4]))\n- src = src[4:]\n- out.MaxReadahead = uint32(usermem.ByteOrder.Uint32(src[:4]))\n- src = src[4:]\n- out.Flags = uint32(usermem.ByteOrder.Uint32(src[:4]))\n- src = src[4:]\n- out.MaxBackground = uint16(usermem.ByteOrder.Uint16(src[:2]))\n- src = src[2:]\n- out.CongestionThreshold = uint16(usermem.ByteOrder.Uint16(src[:2]))\n- src = src[2:]\n- out.MaxWrite = uint32(usermem.ByteOrder.Uint32(src[:4]))\n- src = src[4:]\n-\n- // Introduced in FUSE kernel version 7.23.\n- if len(src) >= 4 {\n- out.TimeGran = uint32(usermem.ByteOrder.Uint32(src[:4]))\n- src = src[4:]\n- }\n- // Introduced in FUSE kernel version 7.28.\n- if len(src) >= 2 {\n- out.MaxPages = uint16(usermem.ByteOrder.Uint16(src[:2]))\n- src = src[2:]\n- }\n- // Introduced in FUSE kernel version 7.31.\n- if len(src) >= 2 {\n- out.MapAlignment = uint16(usermem.ByteOrder.Uint16(src[:2]))\n- src = src[2:]\n- }\n-}\n-\n-// SizeBytes is the size of the payload of the FUSE_INIT response.\n-func (r *FUSEInitRes) SizeBytes() int {\n- return int(r.Len)\n-}\n-\n// FUSEGetAttrIn is the request sent by the kernel to the daemon,\n// to get the attribute of a inode.\n//\n@@ -415,11 +357,6 @@ type FUSELookupIn struct {\nName string\n}\n-// MarshalUnsafe serializes r.name to the dst buffer.\n-func (r *FUSELookupIn) MarshalUnsafe(buf []byte) {\n- copy(buf, r.Name)\n-}\n-\n// MarshalBytes serializes r.name to the dst buffer.\nfunc (r *FUSELookupIn) MarshalBytes(buf []byte) {\ncopy(buf, r.Name)\n@@ -548,12 +485,6 @@ type FUSEMknodIn struct {\nName string\n}\n-// MarshalUnsafe serializes r.MknodMeta and r.Name to the dst buffer.\n-func (r *FUSEMknodIn) MarshalUnsafe(buf []byte) {\n- r.MknodMeta.MarshalUnsafe(buf[:r.MknodMeta.SizeBytes()])\n- copy(buf[r.MknodMeta.SizeBytes():], r.Name)\n-}\n-\n// MarshalBytes serializes r.MknodMeta and r.Name to the dst buffer.\nfunc (r *FUSEMknodIn) MarshalBytes(buf []byte) {\nr.MknodMeta.MarshalBytes(buf[:r.MknodMeta.SizeBytes()])\n@@ -580,13 +511,6 @@ type FUSESymLinkIn struct {\nTarget string\n}\n-// MarshalUnsafe serializes r.Name and r.Target to the dst buffer.\n-// Left null-termination at end of r.Name and r.Target.\n-func (r *FUSESymLinkIn) MarshalUnsafe(buf []byte) {\n- copy(buf, r.Name)\n- copy(buf[len(r.Name)+1:], r.Target)\n-}\n-\n// MarshalBytes serializes r.Name and r.Target to the dst buffer.\n// Left null-termination at end of r.Name and r.Target.\nfunc (r *FUSESymLinkIn) MarshalBytes(buf []byte) {\n@@ -603,9 +527,6 @@ func (r *FUSESymLinkIn) SizeBytes() int {\n// FUSEEmptyIn is used by operations without request body.\ntype FUSEEmptyIn struct{ marshal.StubMarshallable }\n-// MarshalUnsafe do nothing for marshal.\n-func (r *FUSEEmptyIn) MarshalUnsafe(buf []byte) {}\n-\n// MarshalBytes do nothing for marshal.\nfunc (r *FUSEEmptyIn) MarshalBytes(buf []byte) {}\n@@ -640,12 +561,6 @@ type FUSEMkdirIn struct {\nName string\n}\n-// MarshalUnsafe serializes r.MkdirMeta and r.Name to the dst buffer.\n-func (r *FUSEMkdirIn) MarshalUnsafe(buf []byte) {\n- r.MkdirMeta.MarshalUnsafe(buf[:r.MkdirMeta.SizeBytes()])\n- copy(buf[r.MkdirMeta.SizeBytes():], r.Name)\n-}\n-\n// MarshalBytes serializes r.MkdirMeta and r.Name to the dst buffer.\nfunc (r *FUSEMkdirIn) MarshalBytes(buf []byte) {\nr.MkdirMeta.MarshalBytes(buf[:r.MkdirMeta.SizeBytes()])\n@@ -669,11 +584,6 @@ type FUSERmDirIn struct {\nName string\n}\n-// MarshalUnsafe serializes r.name to the dst buffer.\n-func (r *FUSERmDirIn) MarshalUnsafe(buf []byte) {\n- copy(buf, r.Name)\n-}\n-\n// MarshalBytes serializes r.name to the dst buffer.\nfunc (r *FUSERmDirIn) MarshalBytes(buf []byte) {\ncopy(buf, r.Name)\n@@ -684,16 +594,6 @@ func (r *FUSERmDirIn) SizeBytes() int {\nreturn len(r.Name) + 1\n}\n-// UnmarshalUnsafe deserializes r.name from the src buffer.\n-func (r *FUSERmDirIn) UnmarshalUnsafe(src []byte) {\n- r.Name = string(src)\n-}\n-\n-// UnmarshalBytes deserializes r.name from the src buffer.\n-func (r *FUSERmDirIn) UnmarshalBytes(src []byte) {\n- r.Name = string(src)\n-}\n-\n// FUSEDirents is a list of Dirents received from the FUSE daemon server.\n// It is used for FUSE_READDIR.\n//\n@@ -736,22 +636,6 @@ type FUSEDirentMeta struct {\nType uint32\n}\n-// MarshalUnsafe serializes FUSEDirents to the dst buffer.\n-func (r *FUSEDirents) MarshalUnsafe(dst []byte) {\n- for _, dirent := range r.Dirents {\n- dirent.MarshalUnsafe(dst)\n- dst = dst[dirent.SizeBytes():]\n- }\n-}\n-\n-// MarshalBytes serializes FUSEDirents to the dst buffer.\n-func (r *FUSEDirents) MarshalBytes(dst []byte) {\n- for _, dirent := range r.Dirents {\n- dirent.MarshalBytes(dst)\n- dst = dst[dirent.SizeBytes():]\n- }\n-}\n-\n// SizeBytes is the size of the memory representation of FUSEDirents.\nfunc (r *FUSEDirents) SizeBytes() int {\nvar sizeBytes int\n@@ -762,30 +646,6 @@ func (r *FUSEDirents) SizeBytes() int {\nreturn sizeBytes\n}\n-// UnmarshalUnsafe deserializes FUSEDirents from the src buffer.\n-func (r *FUSEDirents) UnmarshalUnsafe(src []byte) {\n- for {\n- if len(src) <= (*FUSEDirentMeta)(nil).SizeBytes() {\n- break\n- }\n-\n- // Its unclear how many dirents there are in src. Each dirent is dynamically\n- // sized and so we can't make assumptions about how many dirents we can allocate.\n- if r.Dirents == nil {\n- r.Dirents = make([]*FUSEDirent, 0)\n- }\n-\n- // We have to allocate a struct for each dirent - there must be a better way\n- // to do this. Linux allocates 1 page to store all the dirents and then\n- // simply reads them from the page.\n- var dirent FUSEDirent\n- dirent.UnmarshalUnsafe(src)\n- r.Dirents = append(r.Dirents, &dirent)\n-\n- src = src[dirent.SizeBytes():]\n- }\n-}\n-\n// UnmarshalBytes deserializes FUSEDirents from the src buffer.\nfunc (r *FUSEDirents) UnmarshalBytes(src []byte) {\nfor {\n@@ -810,24 +670,6 @@ func (r *FUSEDirents) UnmarshalBytes(src []byte) {\n}\n}\n-// MarshalUnsafe serializes FUSEDirent to the dst buffer.\n-func (r *FUSEDirent) MarshalUnsafe(dst []byte) {\n- r.Meta.MarshalUnsafe(dst)\n- dst = dst[r.Meta.SizeBytes():]\n-\n- name := primitive.ByteSlice(r.Name)\n- name.MarshalUnsafe(dst)\n-}\n-\n-// MarshalBytes serializes FUSEDirent to the dst buffer.\n-func (r *FUSEDirent) MarshalBytes(dst []byte) {\n- r.Meta.MarshalBytes(dst)\n- dst = dst[r.Meta.SizeBytes():]\n-\n- name := primitive.ByteSlice(r.Name)\n- name.MarshalBytes(dst)\n-}\n-\n// SizeBytes is the size of the memory representation of FUSEDirent.\nfunc (r *FUSEDirent) SizeBytes() int {\ndataSize := r.Meta.SizeBytes() + len(r.Name)\n@@ -838,23 +680,6 @@ func (r *FUSEDirent) SizeBytes() int {\nreturn (dataSize + (FUSE_DIRENT_ALIGN - 1)) & ^(FUSE_DIRENT_ALIGN - 1)\n}\n-// UnmarshalUnsafe deserializes FUSEDirent from the src buffer.\n-func (r *FUSEDirent) UnmarshalUnsafe(src []byte) {\n- r.Meta.UnmarshalUnsafe(src)\n- src = src[r.Meta.SizeBytes():]\n-\n- if r.Meta.NameLen > FUSE_NAME_MAX {\n- // The name is too long and therefore invalid. We don't\n- // need to unmarshal the name since it'll be thrown away.\n- return\n- }\n-\n- buf := make([]byte, r.Meta.NameLen)\n- name := primitive.ByteSlice(buf)\n- name.UnmarshalUnsafe(src[:r.Meta.NameLen])\n- r.Name = string(name)\n-}\n-\n// UnmarshalBytes deserializes FUSEDirent from the src buffer.\nfunc (r *FUSEDirent) UnmarshalBytes(src []byte) {\nr.Meta.UnmarshalBytes(src)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/BUILD", "new_path": "pkg/sentry/fsimpl/fuse/BUILD", "diff": "@@ -40,6 +40,7 @@ go_library(\n\"register.go\",\n\"regular_file.go\",\n\"request_list.go\",\n+ \"request_response.go\",\n],\nvisibility = [\"//pkg/sentry:internal\"],\ndeps = [\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/init.go", "new_path": "pkg/sentry/fsimpl/fuse/init.go", "diff": "@@ -76,12 +76,12 @@ func (conn *connection) InitRecv(res *Response, hasSysAdminCap bool) error {\nreturn err\n}\n- initRes := linux.FUSEInitRes{Len: res.DataLen()}\n+ initRes := fuseInitRes{initLen: res.DataLen()}\nif err := res.UnmarshalPayload(&initRes); err != nil {\nreturn err\n}\n- return conn.initProcessReply(&initRes.InitOut, hasSysAdminCap)\n+ return conn.initProcessReply(&initRes.initOut, hasSysAdminCap)\n}\n// Process the FUSE_INIT reply from the FUSE server.\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fsimpl/fuse/request_response.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package fuse\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n+ \"gvisor.dev/gvisor/tools/go_marshal/marshal\"\n+)\n+\n+// fuseInitRes is a variable-length wrapper of linux.FUSEInitOut. The FUSE\n+// server may implement an older version of FUSE protocol, which contains a\n+// linux.FUSEInitOut with less attributes.\n+//\n+// Dynamically-sized objects cannot be marshalled.\n+type fuseInitRes struct {\n+ marshal.StubMarshallable\n+\n+ // initOut contains the response from the FUSE server.\n+ initOut linux.FUSEInitOut\n+\n+ // initLen is the total length of bytes of the response.\n+ initLen uint32\n+}\n+\n+// UnmarshalBytes deserializes src to the initOut attribute in a fuseInitRes.\n+func (r *fuseInitRes) UnmarshalBytes(src []byte) {\n+ out := &r.initOut\n+\n+ // Introduced before FUSE kernel version 7.13.\n+ out.Major = uint32(usermem.ByteOrder.Uint32(src[:4]))\n+ src = src[4:]\n+ out.Minor = uint32(usermem.ByteOrder.Uint32(src[:4]))\n+ src = src[4:]\n+ out.MaxReadahead = uint32(usermem.ByteOrder.Uint32(src[:4]))\n+ src = src[4:]\n+ out.Flags = uint32(usermem.ByteOrder.Uint32(src[:4]))\n+ src = src[4:]\n+ out.MaxBackground = uint16(usermem.ByteOrder.Uint16(src[:2]))\n+ src = src[2:]\n+ out.CongestionThreshold = uint16(usermem.ByteOrder.Uint16(src[:2]))\n+ src = src[2:]\n+ out.MaxWrite = uint32(usermem.ByteOrder.Uint32(src[:4]))\n+ src = src[4:]\n+\n+ // Introduced in FUSE kernel version 7.23.\n+ if len(src) >= 4 {\n+ out.TimeGran = uint32(usermem.ByteOrder.Uint32(src[:4]))\n+ src = src[4:]\n+ }\n+ // Introduced in FUSE kernel version 7.28.\n+ if len(src) >= 2 {\n+ out.MaxPages = uint16(usermem.ByteOrder.Uint16(src[:2]))\n+ src = src[2:]\n+ }\n+ // Introduced in FUSE kernel version 7.31.\n+ if len(src) >= 2 {\n+ out.MapAlignment = uint16(usermem.ByteOrder.Uint16(src[:2]))\n+ src = src[2:]\n+ }\n+}\n+\n+// SizeBytes is the size of the payload of the FUSE_INIT response.\n+func (r *fuseInitRes) SizeBytes() int {\n+ return int(r.initLen)\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
fuse: remove unused marshalling functions This commit removes unused marshalling functions in linux abi package and moves self-defined FUSEInitRes wrapper to fuse package. Updates #3707
259,913
02.09.2020 13:50:31
25,200
e91c026672b9022d5554e20202648d322da0fe1d
Downgrade FUSE minor version support and clarify comments
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/fuse.go", "new_path": "pkg/abi/linux/fuse.go", "diff": "@@ -151,6 +151,7 @@ type FUSEWriteIn struct {\n}\n// FUSE_INIT flags, consistent with the ones in include/uapi/linux/fuse.h.\n+// Our taget version is 7.23 but we have few implemented in advance.\nconst (\nFUSE_ASYNC_READ = 1 << 0\nFUSE_POSIX_LOCKS = 1 << 1\n@@ -170,15 +171,7 @@ const (\nFUSE_ASYNC_DIO = 1 << 15\nFUSE_WRITEBACK_CACHE = 1 << 16\nFUSE_NO_OPEN_SUPPORT = 1 << 17\n- FUSE_PARALLEL_DIROPS = 1 << 18\n- FUSE_HANDLE_KILLPRIV = 1 << 19\n- FUSE_POSIX_ACL = 1 << 20\n- FUSE_ABORT_ERROR = 1 << 21\n- FUSE_MAX_PAGES = 1 << 22\n- FUSE_CACHE_SYMLINKS = 1 << 23\n- FUSE_NO_OPENDIR_SUPPORT = 1 << 24\n- FUSE_EXPLICIT_INVAL_DATA = 1 << 25\n- FUSE_MAP_ALIGNMENT = 1 << 26\n+ FUSE_MAX_PAGES = 1 << 22 // From FUSE 7.28\n)\n// currently supported FUSE protocol version numbers.\n@@ -214,7 +207,7 @@ type FUSEInitIn struct {\n}\n// FUSEInitOut is the reply sent by the daemon to the kernel\n-// for FUSEInitIn.\n+// for FUSEInitIn. We target FUSE 7.23; this struct supports 7.28.\n//\n// +marshal\ntype FUSEInitOut struct {\n@@ -255,9 +248,7 @@ type FUSEInitOut struct {\n// if the value from daemon is too large.\nMaxPages uint16\n- // MapAlignment is an unknown field and not used by this package at this moment.\n- // Use as a placeholder to be consistent with the FUSE protocol.\n- MapAlignment uint16\n+ _ uint16\n_ [8]uint32\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/connection.go", "new_path": "pkg/sentry/fsimpl/fuse/connection.go", "diff": "@@ -86,16 +86,22 @@ type connection struct {\n// attributeVersion is the version of connection's attributes.\nattributeVersion uint64\n+ // We target FUSE 7.23.\n// The following FUSE_INIT flags are currently unsupported by this implementation:\n// - FUSE_EXPORT_SUPPORT\n- // - FUSE_HANDLE_KILLPRIV\n// - FUSE_POSIX_LOCKS: requires POSIX locks\n// - FUSE_FLOCK_LOCKS: requires POSIX locks\n// - FUSE_AUTO_INVAL_DATA: requires page caching eviction\n- // - FUSE_EXPLICIT_INVAL_DATA: requires page caching eviction\n// - FUSE_DO_READDIRPLUS/FUSE_READDIRPLUS_AUTO: requires FUSE_READDIRPLUS implementation\n// - FUSE_ASYNC_DIO\n- // - FUSE_POSIX_ACL: affects defaultPermissions, posixACL, xattr handler\n+ // - FUSE_PARALLEL_DIROPS (7.25)\n+ // - FUSE_HANDLE_KILLPRIV (7.26)\n+ // - FUSE_POSIX_ACL: affects defaultPermissions, posixACL, xattr handler (7.26)\n+ // - FUSE_ABORT_ERROR (7.27)\n+ // - FUSE_CACHE_SYMLINKS (7.28)\n+ // - FUSE_NO_OPENDIR_SUPPORT (7.29)\n+ // - FUSE_EXPLICIT_INVAL_DATA: requires page caching eviction (7.30)\n+ // - FUSE_MAP_ALIGNMENT (7.31)\n// initialized after receiving FUSE_INIT reply.\n// Until it's set, suspend sending FUSE requests.\n@@ -182,19 +188,11 @@ type connection struct {\n// Negotiated and only set in INIT.\nasyncRead bool\n- // abortErr is true if kernel need to return an unique read error after abort.\n- // Negotiated and only set in INIT.\n- abortErr bool\n-\n// writebackCache is true for write-back cache policy,\n// false for write-through policy.\n// Negotiated and only set in INIT.\nwritebackCache bool\n- // cacheSymlinks if filesystem needs to cache READLINK responses in page cache.\n- // Negotiated and only set in INIT.\n- cacheSymlinks bool\n-\n// bigWrites if doing multi-page cached writes.\n// Negotiated and only set in INIT.\nbigWrites bool\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/init.go", "new_path": "pkg/sentry/fsimpl/fuse/init.go", "diff": "@@ -132,8 +132,6 @@ func (conn *connection) initProcessReply(out *linux.FUSEInitOut, hasSysAdminCap\nconn.bigWrites = out.Flags&linux.FUSE_BIG_WRITES != 0\nconn.dontMask = out.Flags&linux.FUSE_DONT_MASK != 0\nconn.writebackCache = out.Flags&linux.FUSE_WRITEBACK_CACHE != 0\n- conn.cacheSymlinks = out.Flags&linux.FUSE_CACHE_SYMLINKS != 0\n- conn.abortErr = out.Flags&linux.FUSE_ABORT_ERROR != 0\n// TODO(gvisor.dev/issue/3195): figure out how to use TimeGran (0 < TimeGran <= fuseMaxTimeGranNs).\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/request_response.go", "new_path": "pkg/sentry/fsimpl/fuse/request_response.go", "diff": "@@ -65,11 +65,6 @@ func (r *fuseInitRes) UnmarshalBytes(src []byte) {\nout.MaxPages = uint16(usermem.ByteOrder.Uint16(src[:2]))\nsrc = src[2:]\n}\n- // Introduced in FUSE kernel version 7.31.\n- if len(src) >= 2 {\n- out.MapAlignment = uint16(usermem.ByteOrder.Uint16(src[:2]))\n- src = src[2:]\n- }\n}\n// SizeBytes is the size of the payload of the FUSE_INIT response.\n" } ]
Go
Apache License 2.0
google/gvisor
Downgrade FUSE minor version support and clarify comments
259,913
02.09.2020 13:55:08
25,200
7ed4e46a717ece014a962e4b9cacff1ff4c461f1
FUSE device: clean up readLocked This change removes the unnecessary loop and avoids the recursive call. It also fixes minor bugs in this function.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/dev.go", "new_path": "pkg/sentry/fsimpl/fuse/dev.go", "diff": "@@ -19,7 +19,6 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n- \"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n@@ -143,16 +142,20 @@ func (fd *DeviceFD) Read(ctx context.Context, dst usermem.IOSequence, opts vfs.R\n}\n// readLocked implements the reading of the fuse device while locked with DeviceFD.mu.\n+//\n+// Preconditions: dst is large enough for any reasonable request.\nfunc (fd *DeviceFD) readLocked(ctx context.Context, dst usermem.IOSequence, opts vfs.ReadOptions) (int64, error) {\n- if fd.queue.Empty() {\n- return 0, syserror.ErrWouldBlock\n+ var req *Request\n+\n+ // Find the first valid request.\n+ // For the normal case this loop only execute once.\n+ for !fd.queue.Empty() {\n+ req = fd.queue.Front()\n+\n+ if int64(req.hdr.Len) <= dst.NumBytes() {\n+ break\n}\n- var readCursor uint32\n- var bytesRead int64\n- for {\n- req := fd.queue.Front()\n- if dst.NumBytes() < int64(req.hdr.Len) {\n// The request is too large. Cannot process it. All requests must be smaller than the\n// negotiated size as specified by Connection.MaxWrite set as part of the FUSE_INIT\n// handshake.\n@@ -168,33 +171,33 @@ func (fd *DeviceFD) readLocked(ctx context.Context, dst usermem.IOSequence, opts\n// We're done with this request.\nfd.queue.Remove(req)\n- if req.hdr.Opcode == linux.FUSE_RELEASE {\n- fd.numActiveRequests -= 1\n+ req = nil\n}\n- // Restart the read as this request was invalid.\n- log.Warningf(\"fuse.DeviceFD.Read: request found was too large. Restarting read.\")\n- return fd.readLocked(ctx, dst, opts)\n+ if req == nil {\n+ return 0, syserror.ErrWouldBlock\n}\n- n, err := dst.CopyOut(ctx, req.data[readCursor:])\n+ // We already checked the size: dst must be able to fit the whole request.\n+ // Now we write the marshalled header, the payload,\n+ // and the potential additional payload\n+ // to the user memory IOSequence.\n+\n+ n, err := dst.CopyOut(ctx, req.data)\nif err != nil {\nreturn 0, err\n}\n- readCursor += uint32(n)\n- bytesRead += int64(n)\n+ if n != len(req.data) {\n+ return 0, syserror.EIO\n+ }\n- if readCursor >= req.hdr.Len {\n// Fully done with this req, remove it from the queue.\nfd.queue.Remove(req)\nif req.hdr.Opcode == linux.FUSE_RELEASE {\nfd.numActiveRequests -= 1\n}\n- break\n- }\n- }\n- return bytesRead, nil\n+ return int64(n), nil\n}\n// PWrite implements vfs.FileDescriptionImpl.PWrite.\n" } ]
Go
Apache License 2.0
google/gvisor
FUSE device: clean up readLocked This change removes the unnecessary loop and avoids the recursive call. It also fixes minor bugs in this function.
259,983
03.09.2020 14:06:59
25,200
18f1e1c91b05059c333197a2a6198716c12508e7
Implement FUSE_CREATE FUSE_CREATE is called when issuing creat(2) or open(2) with O_CREAT. It creates a new file on the FUSE filesystem. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/fuse.go", "new_path": "pkg/abi/linux/fuse.go", "diff": "@@ -445,6 +445,48 @@ type FUSEReleaseIn struct {\nLockOwner uint64\n}\n+// FUSECreateMeta contains all the static fields of FUSECreateIn,\n+// which is used for FUSE_CREATE.\n+//\n+// +marshal\n+type FUSECreateMeta struct {\n+ // Flags of the creating file.\n+ Flags uint32\n+\n+ // Mode is the mode of the creating file.\n+ Mode uint32\n+\n+ // Umask is the current file mode creation mask.\n+ Umask uint32\n+ _ uint32\n+}\n+\n+// FUSECreateIn contains all the arguments sent by the kernel to the daemon, to\n+// atomically create and open a new regular file.\n+//\n+// Dynamically-sized objects cannot be marshalled.\n+type FUSECreateIn struct {\n+ marshal.StubMarshallable\n+\n+ // CreateMeta contains mode, rdev and umash field for FUSE_MKNODS.\n+ CreateMeta FUSECreateMeta\n+\n+ // Name is the name of the node to create.\n+ Name string\n+}\n+\n+// MarshalBytes serializes r.CreateMeta and r.Name to the dst buffer.\n+func (r *FUSECreateIn) MarshalBytes(buf []byte) {\n+ r.CreateMeta.MarshalBytes(buf[:r.CreateMeta.SizeBytes()])\n+ copy(buf[r.CreateMeta.SizeBytes():], r.Name)\n+}\n+\n+// SizeBytes is the size of the memory representation of FUSECreateIn.\n+// 1 extra byte for null-terminated string.\n+func (r *FUSECreateIn) SizeBytes() int {\n+ return r.CreateMeta.SizeBytes() + len(r.Name) + 1\n+}\n+\n// FUSEMknodMeta contains all the static fields of FUSEMknodIn,\n// which is used for FUSE_MKNOD.\n//\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "new_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "diff": "@@ -392,6 +392,24 @@ func (inode) Valid(ctx context.Context) bool {\nreturn true\n}\n+// NewFile implements kernfs.Inode.NewFile.\n+func (i *inode) NewFile(ctx context.Context, name string, opts vfs.OpenOptions) (*vfs.Dentry, error) {\n+ kernelTask := kernel.TaskFromContext(ctx)\n+ if kernelTask == nil {\n+ log.Warningf(\"fusefs.Inode.NewFile: couldn't get kernel task from context\", i.NodeID)\n+ return nil, syserror.EINVAL\n+ }\n+ in := linux.FUSECreateIn{\n+ CreateMeta: linux.FUSECreateMeta{\n+ Flags: opts.Flags,\n+ Mode: uint32(opts.Mode) | linux.S_IFREG,\n+ Umask: uint32(kernelTask.FSContext().Umask()),\n+ },\n+ Name: name,\n+ }\n+ return i.newEntry(ctx, name, linux.S_IFREG, linux.FUSE_CREATE, &in)\n+}\n+\n// NewNode implements kernfs.Inode.NewNode.\nfunc (i *inode) NewNode(ctx context.Context, name string, opts vfs.MknodOptions) (*vfs.Dentry, error) {\nin := linux.FUSEMknodIn{\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/BUILD", "new_path": "test/fuse/BUILD", "diff": "@@ -52,6 +52,10 @@ syscall_test(\ntest = \"//test/fuse/linux:readdir_test\",\n)\n+syscall_test(\n+ fuse = \"True\",\n+ test = \"//test/fuse/linux:create_test\",\n+)\nsyscall_test(\nsize = \"large\",\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/BUILD", "new_path": "test/fuse/linux/BUILD", "diff": "@@ -153,3 +153,18 @@ cc_binary(\n\"//test/util:test_util\",\n],\n)\n+\n+cc_binary(\n+ name = \"create_test\",\n+ testonly = 1,\n+ srcs = [\"create_test.cc\"],\n+ deps = [\n+ gtest,\n+ \":fuse_base\",\n+ \"//test/util:fs_util\",\n+ \"//test/util:fuse_util\",\n+ \"//test/util:temp_umask\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/fuse/linux/create_test.cc", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <errno.h>\n+#include <fcntl.h>\n+#include <linux/fuse.h>\n+#include <sys/stat.h>\n+#include <sys/statfs.h>\n+#include <sys/types.h>\n+#include <unistd.h>\n+\n+#include <string>\n+\n+#include \"gtest/gtest.h\"\n+#include \"test/fuse/linux/fuse_base.h\"\n+#include \"test/util/fs_util.h\"\n+#include \"test/util/fuse_util.h\"\n+#include \"test/util/temp_umask.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+class CreateTest : public FuseTest {\n+ protected:\n+ const std::string test_file_name_ = \"test_file\";\n+ const mode_t mode = S_IFREG | S_IRWXU | S_IRWXG | S_IRWXO;\n+};\n+\n+TEST_F(CreateTest, CreateFile) {\n+ const std::string test_file_path =\n+ JoinPath(mount_point_.path().c_str(), test_file_name_);\n+\n+ // Ensure the file doesn't exist.\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header),\n+ .error = -ENOENT,\n+ };\n+ auto iov_out = FuseGenerateIovecs(out_header);\n+ SetServerResponse(FUSE_LOOKUP, iov_out);\n+\n+ // creat(2) is equal to open(2) with open_flags O_CREAT | O_WRONLY | O_TRUNC.\n+ const mode_t new_mask = S_IWGRP | S_IWOTH;\n+ const int open_flags = O_CREAT | O_WRONLY | O_TRUNC;\n+ out_header.error = 0;\n+ out_header.len = sizeof(struct fuse_out_header) +\n+ sizeof(struct fuse_entry_out) + sizeof(struct fuse_open_out);\n+ struct fuse_entry_out entry_payload = DefaultEntryOut(mode & ~new_mask, 2);\n+ struct fuse_open_out out_payload = {\n+ .fh = 1,\n+ .open_flags = open_flags,\n+ };\n+ iov_out = FuseGenerateIovecs(out_header, entry_payload, out_payload);\n+ SetServerResponse(FUSE_CREATE, iov_out);\n+\n+ // kernfs generates a successive FUSE_OPEN after the file is created. Linux's\n+ // fuse kernel module will not send this FUSE_OPEN after creat(2).\n+ out_header.len =\n+ sizeof(struct fuse_out_header) + sizeof(struct fuse_open_out);\n+ iov_out = FuseGenerateIovecs(out_header, out_payload);\n+ SetServerResponse(FUSE_OPEN, iov_out);\n+\n+ int fd;\n+ TempUmask mask(new_mask);\n+ EXPECT_THAT(fd = creat(test_file_path.c_str(), mode), SyscallSucceeds());\n+ EXPECT_THAT(fcntl(fd, F_GETFL),\n+ SyscallSucceedsWithValue(open_flags & O_ACCMODE));\n+\n+ struct fuse_in_header in_header;\n+ struct fuse_create_in in_payload;\n+ std::vector<char> name(test_file_name_.size() + 1);\n+ auto iov_in = FuseGenerateIovecs(in_header, in_payload, name);\n+\n+ // Skip the request of FUSE_LOOKUP.\n+ SkipServerActualRequest();\n+\n+ // Get the first FUSE_CREATE.\n+ GetServerActualRequest(iov_in);\n+ EXPECT_EQ(in_header.len, sizeof(in_header) + sizeof(in_payload) +\n+ test_file_name_.size() + 1);\n+ EXPECT_EQ(in_header.opcode, FUSE_CREATE);\n+ EXPECT_EQ(in_payload.flags, open_flags);\n+ EXPECT_EQ(in_payload.mode, mode & ~new_mask);\n+ EXPECT_EQ(in_payload.umask, new_mask);\n+ EXPECT_EQ(std::string(name.data()), test_file_name_);\n+\n+ // Get the successive FUSE_OPEN.\n+ struct fuse_open_in in_payload_open;\n+ iov_in = FuseGenerateIovecs(in_header, in_payload_open);\n+ GetServerActualRequest(iov_in);\n+ EXPECT_EQ(in_header.len, sizeof(in_header) + sizeof(in_payload_open));\n+ EXPECT_EQ(in_header.opcode, FUSE_OPEN);\n+ EXPECT_EQ(in_payload_open.flags, open_flags & O_ACCMODE);\n+\n+ EXPECT_THAT(close(fd), SyscallSucceeds());\n+ // Skip the FUSE_RELEASE.\n+ SkipServerActualRequest();\n+}\n+\n+TEST_F(CreateTest, CreateFileAlreadyExists) {\n+ const std::string test_file_path =\n+ JoinPath(mount_point_.path().c_str(), test_file_name_);\n+\n+ const int open_flags = O_CREAT | O_EXCL;\n+\n+ SetServerInodeLookup(test_file_name_);\n+\n+ EXPECT_THAT(open(test_file_path.c_str(), mode, open_flags),\n+ SyscallFailsWithErrno(EEXIST));\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Implement FUSE_CREATE FUSE_CREATE is called when issuing creat(2) or open(2) with O_CREAT. It creates a new file on the FUSE filesystem. Fixes #3825
259,913
01.09.2020 01:49:57
0
98faed55e682cf34bb713c37b063a7d1da5e8352
Implement FUSE_WRITE This commit adds basic write(2) support for FUSE.
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/fuse.go", "new_path": "pkg/abi/linux/fuse.go", "diff": "@@ -124,32 +124,6 @@ type FUSEHeaderOut struct {\nUnique FUSEOpID\n}\n-// FUSEWriteIn is the header written by a daemon when it makes a\n-// write request to the FUSE filesystem.\n-//\n-// +marshal\n-type FUSEWriteIn struct {\n- // Fh specifies the file handle that is being written to.\n- Fh uint64\n-\n- // Offset is the offset of the write.\n- Offset uint64\n-\n- // Size is the size of data being written.\n- Size uint32\n-\n- // WriteFlags is the flags used during the write.\n- WriteFlags uint32\n-\n- // LockOwner is the ID of the lock owner.\n- LockOwner uint64\n-\n- // Flags is the flags for the request.\n- Flags uint32\n-\n- _ uint32\n-}\n-\n// FUSE_INIT flags, consistent with the ones in include/uapi/linux/fuse.h.\n// Our taget version is 7.23 but we have few implemented in advance.\nconst (\n@@ -427,6 +401,47 @@ type FUSEReadIn struct {\n_ uint32\n}\n+// FUSEWriteIn is the first part of the payload of the\n+// request sent by the kernel to the daemon\n+// for FUSE_WRITE (struct for FUSE version >= 7.9).\n+//\n+// The second part of the payload is the\n+// binary bytes of the data to be written.\n+//\n+// +marshal\n+type FUSEWriteIn struct {\n+ // Fh is the file handle in userspace.\n+ Fh uint64\n+\n+ // Offset is the write offset.\n+ Offset uint64\n+\n+ // Size is the number of bytes to write.\n+ Size uint32\n+\n+ // ReadFlags for this FUSE_WRITE request.\n+ WriteFlags uint32\n+\n+ // LockOwner is the id of the lock owner if there is one.\n+ LockOwner uint64\n+\n+ // Flags for the underlying file.\n+ Flags uint32\n+\n+ _ uint32\n+}\n+\n+// FUSEWriteOut is the payload of the reply sent by the daemon to the kernel\n+// for a FUSE_WRITE request.\n+//\n+// +marshal\n+type FUSEWriteOut struct {\n+ // Size is the number of bytes written.\n+ Size uint32\n+\n+ _ uint32\n+}\n+\n// FUSEReleaseIn is the request sent by the kernel to the daemon\n// when there is no more reference to a file.\n//\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/connection.go", "new_path": "pkg/sentry/fsimpl/fuse/connection.go", "diff": "@@ -64,6 +64,10 @@ type Request struct {\nid linux.FUSEOpID\nhdr *linux.FUSEHeaderIn\ndata []byte\n+\n+ // payload for this request: extra bytes to write after\n+ // the data slice. Used by FUSE_WRITE.\n+ payload []byte\n}\n// Response represents an actual response from the server, including the\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/dev.go", "new_path": "pkg/sentry/fsimpl/fuse/dev.go", "diff": "@@ -152,7 +152,7 @@ func (fd *DeviceFD) readLocked(ctx context.Context, dst usermem.IOSequence, opts\nfor !fd.queue.Empty() {\nreq = fd.queue.Front()\n- if int64(req.hdr.Len) <= dst.NumBytes() {\n+ if int64(req.hdr.Len)+int64(len(req.payload)) <= dst.NumBytes() {\nbreak\n}\n@@ -191,6 +191,17 @@ func (fd *DeviceFD) readLocked(ctx context.Context, dst usermem.IOSequence, opts\nreturn 0, syserror.EIO\n}\n+ if req.hdr.Opcode == linux.FUSE_WRITE {\n+ written, err := dst.DropFirst(n).CopyOut(ctx, req.payload)\n+ if err != nil {\n+ return 0, err\n+ }\n+ if written != len(req.payload) {\n+ return 0, syserror.EIO\n+ }\n+ n += int(written)\n+ }\n+\n// Fully done with this req, remove it from the queue.\nfd.queue.Remove(req)\nif req.hdr.Opcode == linux.FUSE_RELEASE {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "new_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "diff": "@@ -18,6 +18,7 @@ package fuse\nimport (\n\"math\"\n\"strconv\"\n+ \"sync\"\n\"sync/atomic\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n@@ -228,13 +229,18 @@ type inode struct {\nkernfs.InodeNotSymlink\nkernfs.OrderedChildren\n- NodeID uint64\ndentry kernfs.Dentry\n- locks vfs.FileLocks\n// the owning filesystem. fs is immutable.\nfs *filesystem\n+ // metaDataMu protects the metadata of this inode.\n+ metadataMu sync.Mutex\n+\n+ NodeID uint64\n+\n+ locks vfs.FileLocks\n+\n// size of the file.\nsize uint64\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/read_write.go", "new_path": "pkg/sentry/fsimpl/fuse/read_write.go", "diff": "@@ -150,3 +150,93 @@ func (fs *filesystem) ReadCallback(ctx context.Context, fd *regularFileFD, off u\nfs.conn.mu.Unlock()\n}\n}\n+\n+// Write sends FUSE_WRITE requests and return the bytes\n+// written according to the response.\n+//\n+// Preconditions: len(data) == size.\n+func (fs *filesystem) Write(ctx context.Context, fd *regularFileFD, off uint64, size uint32, data []byte) (uint32, error) {\n+ t := kernel.TaskFromContext(ctx)\n+ if t == nil {\n+ log.Warningf(\"fusefs.Read: couldn't get kernel task from context\")\n+ return 0, syserror.EINVAL\n+ }\n+\n+ // One request cannnot exceed either maxWrite or maxPages.\n+ maxWrite := uint32(fs.conn.maxPages) << usermem.PageShift\n+ if maxWrite > fs.conn.maxWrite {\n+ maxWrite = fs.conn.maxWrite\n+ }\n+\n+ // Reuse the same struct for unmarshalling to avoid unnecessary memory allocation.\n+ in := linux.FUSEWriteIn{\n+ Fh: fd.Fh,\n+ // TODO(gvisor.dev/issue/3245): file lock\n+ LockOwner: 0,\n+ // TODO(gvisor.dev/issue/3245): |= linux.FUSE_READ_LOCKOWNER\n+ // TODO(gvisor.dev/issue/3237): |= linux.FUSE_WRITE_CACHE (not added yet)\n+ WriteFlags: 0,\n+ Flags: fd.statusFlags(),\n+ }\n+\n+ var written uint32\n+\n+ // This loop is intended for fragmented write where the bytes to write is\n+ // larger than either the maxWrite or maxPages or when bigWrites is false.\n+ // Unless a small value for max_write is explicitly used, this loop\n+ // is expected to execute only once for the majority of the writes.\n+ for written < size {\n+ toWrite := size - written\n+\n+ // Limit the write size to one page.\n+ // Note that the bigWrites flag is obsolete,\n+ // latest libfuse always sets it on.\n+ if !fs.conn.bigWrites && toWrite > usermem.PageSize {\n+ toWrite = usermem.PageSize\n+ }\n+\n+ // Limit the write size to maxWrite.\n+ if toWrite > maxWrite {\n+ toWrite = maxWrite\n+ }\n+\n+ in.Offset = off + uint64(written)\n+ in.Size = toWrite\n+\n+ req, err := fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(t.ThreadID()), fd.inode().NodeID, linux.FUSE_WRITE, &in)\n+ if err != nil {\n+ return 0, err\n+ }\n+\n+ req.payload = data[written : written+toWrite]\n+\n+ // TODO(gvisor.dev/issue/3247): support async write.\n+\n+ res, err := fs.conn.Call(t, req)\n+ if err != nil {\n+ return 0, err\n+ }\n+ if err := res.Error(); err != nil {\n+ return 0, err\n+ }\n+\n+ out := linux.FUSEWriteOut{}\n+ if err := res.UnmarshalPayload(&out); err != nil {\n+ return 0, err\n+ }\n+\n+ // Write more than requested? EIO.\n+ if out.Size > toWrite {\n+ return 0, syserror.EIO\n+ }\n+\n+ written += out.Size\n+\n+ // Break if short write. Not necessarily an error.\n+ if out.Size != toWrite {\n+ break\n+ }\n+ }\n+\n+ return written, nil\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/regular_file.go", "new_path": "pkg/sentry/fsimpl/fuse/regular_file.go", "diff": "@@ -123,3 +123,108 @@ func (fd *regularFileFD) Read(ctx context.Context, dst usermem.IOSequence, opts\nfd.offMu.Unlock()\nreturn n, err\n}\n+\n+// PWrite implements vfs.FileDescriptionImpl.PWrite.\n+func (fd *regularFileFD) PWrite(ctx context.Context, src usermem.IOSequence, offset int64, opts vfs.WriteOptions) (int64, error) {\n+ n, _, err := fd.pwrite(ctx, src, offset, opts)\n+ return n, err\n+}\n+\n+// Write implements vfs.FileDescriptionImpl.Write.\n+func (fd *regularFileFD) Write(ctx context.Context, src usermem.IOSequence, opts vfs.WriteOptions) (int64, error) {\n+ fd.offMu.Lock()\n+ n, off, err := fd.pwrite(ctx, src, fd.off, opts)\n+ fd.off = off\n+ fd.offMu.Unlock()\n+ return n, err\n+}\n+\n+// pwrite returns the number of bytes written, final offset and error. The\n+// final offset should be ignored by PWrite.\n+func (fd *regularFileFD) pwrite(ctx context.Context, src usermem.IOSequence, offset int64, opts vfs.WriteOptions) (written, finalOff int64, err error) {\n+ if offset < 0 {\n+ return 0, offset, syserror.EINVAL\n+ }\n+\n+ // Check that flags are supported.\n+ //\n+ // TODO(gvisor.dev/issue/2601): Support select preadv2 flags.\n+ if opts.Flags&^linux.RWF_HIPRI != 0 {\n+ return 0, offset, syserror.EOPNOTSUPP\n+ }\n+\n+ inode := fd.inode()\n+ inode.metadataMu.Lock()\n+ defer inode.metadataMu.Unlock()\n+\n+ // If the file is opened with O_APPEND, update offset to file size.\n+ // Note: since our Open() implements the interface of kernfs,\n+ // and kernfs currently does not support O_APPEND, this will never\n+ // be true before we switch out from kernfs.\n+ if fd.vfsfd.StatusFlags()&linux.O_APPEND != 0 {\n+ // Locking inode.metadataMu is sufficient for reading size\n+ offset = int64(inode.size)\n+ }\n+\n+ srclen := src.NumBytes()\n+\n+ if srclen > math.MaxUint32 {\n+ // FUSE only supports uint32 for size.\n+ // Overflow.\n+ return 0, offset, syserror.EINVAL\n+ }\n+ if end := offset + srclen; end < offset {\n+ // Overflow.\n+ return 0, offset, syserror.EINVAL\n+ }\n+\n+ srclen, err = vfs.CheckLimit(ctx, offset, srclen)\n+ if err != nil {\n+ return 0, offset, err\n+ }\n+\n+ if srclen == 0 {\n+ // Return before causing any side effects.\n+ return 0, offset, nil\n+ }\n+\n+ src = src.TakeFirst64(srclen)\n+\n+ // TODO(gvisor.dev/issue/3237): Add cache support:\n+ // buffer cache. Ideally we write from src to our buffer cache first.\n+ // The slice passed to fs.Write() should be a slice from buffer cache.\n+ data := make([]byte, srclen)\n+ // Reason for making a copy here: connection.Call() blocks on kerneltask,\n+ // which in turn acquires mm.activeMu lock. Functions like CopyInTo() will\n+ // attemp to acquire the mm.activeMu lock as well -> deadlock.\n+ // We must finish reading from the userspace memory before\n+ // t.Block() deactivates it.\n+ cp, err := src.CopyIn(ctx, data)\n+ if err != nil {\n+ return 0, offset, err\n+ }\n+ if int64(cp) != srclen {\n+ return 0, offset, syserror.EIO\n+ }\n+\n+ n, err := fd.inode().fs.Write(ctx, fd, uint64(offset), uint32(srclen), data)\n+ if err != nil {\n+ return 0, offset, err\n+ }\n+\n+ if n == 0 {\n+ // We have checked srclen != 0 previously.\n+ // If err == nil, then it's a short write and we return EIO.\n+ return 0, offset, syserror.EIO\n+ }\n+\n+ written = int64(n)\n+ finalOff = offset + written\n+\n+ if finalOff > int64(inode.size) {\n+ atomic.StoreUint64(&inode.size, uint64(finalOff))\n+ atomic.AddUint64(&inode.fs.conn.attributeVersion, 1)\n+ }\n+\n+ return\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/BUILD", "new_path": "test/fuse/BUILD", "diff": "@@ -42,6 +42,11 @@ syscall_test(\ntest = \"//test/fuse/linux:read_test\",\n)\n+syscall_test(\n+ fuse = \"True\",\n+ test = \"//test/fuse/linux:write_test\",\n+)\n+\nsyscall_test(\nfuse = \"True\",\ntest = \"//test/fuse/linux:rmdir_test\",\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/BUILD", "new_path": "test/fuse/linux/BUILD", "diff": "@@ -154,6 +154,19 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"write_test\",\n+ testonly = 1,\n+ srcs = [\"write_test.cc\"],\n+ deps = [\n+ gtest,\n+ \":fuse_base\",\n+ \"//test/util:fuse_util\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n+\ncc_binary(\nname = \"create_test\",\ntestonly = 1,\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/fuse_base.cc", "new_path": "test/fuse/linux/fuse_base.cc", "diff": "@@ -164,7 +164,8 @@ void FuseTest::UnmountFuse() {\n}\n// Consumes the first FUSE request and returns the corresponding PosixError.\n-PosixError FuseTest::ServerConsumeFuseInit() {\n+PosixError FuseTest::ServerConsumeFuseInit(\n+ const struct fuse_init_out* out_payload) {\nstd::vector<char> buf(FUSE_MIN_READ_BUFFER);\nRETURN_ERROR_IF_SYSCALL_FAIL(\nRetryEINTR(read)(dev_fd_, buf.data(), buf.size()));\n@@ -176,10 +177,8 @@ PosixError FuseTest::ServerConsumeFuseInit() {\n};\n// Returns a fake fuse_init_out with 7.0 version to avoid ECONNREFUSED\n// error in the initialization of FUSE connection.\n- struct fuse_init_out out_payload = {\n- .major = 7,\n- };\n- auto iov_out = FuseGenerateIovecs(out_header, out_payload);\n+ auto iov_out = FuseGenerateIovecs(\n+ out_header, *const_cast<struct fuse_init_out*>(out_payload));\nRETURN_ERROR_IF_SYSCALL_FAIL(\nRetryEINTR(writev)(dev_fd_, iov_out.data(), iov_out.size()));\n@@ -244,7 +243,7 @@ void FuseTest::ServerFuseLoop() {\n// becomes testing thread and the child thread becomes the FUSE server running\n// in background. These 2 threads are connected via socketpair. sock_[0] is\n// opened in testing thread and sock_[1] is opened in the FUSE server.\n-void FuseTest::SetUpFuseServer() {\n+void FuseTest::SetUpFuseServer(const struct fuse_init_out* payload) {\nASSERT_THAT(socketpair(AF_UNIX, SOCK_STREAM, 0, sock_), SyscallSucceeds());\nswitch (fork()) {\n@@ -261,7 +260,7 @@ void FuseTest::SetUpFuseServer() {\n// Begin child thread, i.e. the FUSE server.\nASSERT_THAT(close(sock_[0]), SyscallSucceeds());\n- ServerCompleteWith(ServerConsumeFuseInit().ok());\n+ ServerCompleteWith(ServerConsumeFuseInit(payload).ok());\nServerFuseLoop();\n_exit(0);\n}\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/fuse_base.h", "new_path": "test/fuse/linux/fuse_base.h", "diff": "@@ -33,6 +33,8 @@ namespace testing {\nconstexpr char kMountOpts[] = \"rootmode=755,user_id=0,group_id=0\";\n+constexpr struct fuse_init_out kDefaultFUSEInitOutPayload = {.major = 7};\n+\n// Internal commands used to communicate between testing thread and the FUSE\n// server. See test/fuse/README.md for further detail.\nenum class FuseTestCmd {\n@@ -171,7 +173,8 @@ class FuseTest : public ::testing::Test {\nvoid MountFuse(const char* mountOpts = kMountOpts);\n// Creates a socketpair for communication and forks FUSE server.\n- void SetUpFuseServer();\n+ void SetUpFuseServer(\n+ const struct fuse_init_out* payload = &kDefaultFUSEInitOutPayload);\n// Unmounts the mountpoint of the FUSE server.\nvoid UnmountFuse();\n@@ -194,7 +197,7 @@ class FuseTest : public ::testing::Test {\n// Consumes the first FUSE request when mounting FUSE. Replies with a\n// response with empty payload.\n- PosixError ServerConsumeFuseInit();\n+ PosixError ServerConsumeFuseInit(const struct fuse_init_out* payload);\n// A command switch that dispatch different FuseTestCmd to its handler.\nvoid ServerHandleCommand();\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/fuse/linux/write_test.cc", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <errno.h>\n+#include <fcntl.h>\n+#include <linux/fuse.h>\n+#include <sys/stat.h>\n+#include <sys/statfs.h>\n+#include <sys/types.h>\n+#include <unistd.h>\n+\n+#include <string>\n+#include <vector>\n+\n+#include \"gtest/gtest.h\"\n+#include \"test/fuse/linux/fuse_base.h\"\n+#include \"test/util/fuse_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+class WriteTest : public FuseTest {\n+ void SetUp() override {\n+ FuseTest::SetUp();\n+ test_file_path_ = JoinPath(mount_point_.path().c_str(), test_file_);\n+ }\n+\n+ // TearDown overrides the parent's function\n+ // to skip checking the unconsumed release request at the end.\n+ void TearDown() override { UnmountFuse(); }\n+\n+ protected:\n+ const std::string test_file_ = \"test_file\";\n+ const mode_t test_file_mode_ = S_IFREG | S_IRWXU | S_IRWXG | S_IRWXO;\n+ const uint64_t test_fh_ = 1;\n+ const uint32_t open_flag_ = O_RDWR;\n+\n+ std::string test_file_path_;\n+\n+ PosixErrorOr<FileDescriptor> OpenTestFile(const std::string &path,\n+ uint64_t size = 512) {\n+ SetServerInodeLookup(test_file_, test_file_mode_, size);\n+\n+ struct fuse_out_header out_header_open = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_open_out),\n+ };\n+ struct fuse_open_out out_payload_open = {\n+ .fh = test_fh_,\n+ .open_flags = open_flag_,\n+ };\n+ auto iov_out_open = FuseGenerateIovecs(out_header_open, out_payload_open);\n+ SetServerResponse(FUSE_OPEN, iov_out_open);\n+\n+ auto res = Open(path.c_str(), open_flag_);\n+ if (res.ok()) {\n+ SkipServerActualRequest();\n+ }\n+ return res;\n+ }\n+};\n+\n+class WriteTestSmallMaxWrite : public WriteTest {\n+ void SetUp() override {\n+ MountFuse();\n+ SetUpFuseServer(&fuse_init_payload);\n+ test_file_path_ = JoinPath(mount_point_.path().c_str(), test_file_);\n+ }\n+\n+ protected:\n+ const static uint32_t max_write_ = 4096;\n+ constexpr static struct fuse_init_out fuse_init_payload = {\n+ .major = 7,\n+ .max_write = max_write_,\n+ };\n+\n+ const uint32_t size_fragment = max_write_;\n+};\n+\n+TEST_F(WriteTest, WriteNormal) {\n+ auto fd = ASSERT_NO_ERRNO_AND_VALUE(OpenTestFile(test_file_path_));\n+\n+ // Prepare for the write.\n+ const int n_write = 10;\n+ struct fuse_out_header out_header_write = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_write_out),\n+ };\n+ struct fuse_write_out out_payload_write = {\n+ .size = n_write,\n+ };\n+ auto iov_out_write = FuseGenerateIovecs(out_header_write, out_payload_write);\n+ SetServerResponse(FUSE_WRITE, iov_out_write);\n+\n+ // Issue the write.\n+ std::vector<char> buf(n_write);\n+ RandomizeBuffer(buf.data(), buf.size());\n+ EXPECT_THAT(write(fd.get(), buf.data(), n_write),\n+ SyscallSucceedsWithValue(n_write));\n+\n+ // Check the write request.\n+ struct fuse_in_header in_header_write;\n+ struct fuse_write_in in_payload_write;\n+ std::vector<char> payload_buf(n_write);\n+ auto iov_in_write =\n+ FuseGenerateIovecs(in_header_write, in_payload_write, payload_buf);\n+ GetServerActualRequest(iov_in_write);\n+\n+ EXPECT_EQ(in_payload_write.fh, test_fh_);\n+ EXPECT_EQ(in_header_write.len,\n+ sizeof(in_header_write) + sizeof(in_payload_write));\n+ EXPECT_EQ(in_header_write.opcode, FUSE_WRITE);\n+ EXPECT_EQ(in_payload_write.offset, 0);\n+ EXPECT_EQ(in_payload_write.size, n_write);\n+ EXPECT_EQ(buf, payload_buf);\n+}\n+\n+TEST_F(WriteTest, WriteShort) {\n+ auto fd = ASSERT_NO_ERRNO_AND_VALUE(OpenTestFile(test_file_path_));\n+\n+ // Prepare for the write.\n+ const int n_write = 10, n_written = 5;\n+ struct fuse_out_header out_header_write = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_write_out),\n+ };\n+ struct fuse_write_out out_payload_write = {\n+ .size = n_written,\n+ };\n+ auto iov_out_write = FuseGenerateIovecs(out_header_write, out_payload_write);\n+ SetServerResponse(FUSE_WRITE, iov_out_write);\n+\n+ // Issue the write.\n+ std::vector<char> buf(n_write);\n+ RandomizeBuffer(buf.data(), buf.size());\n+ EXPECT_THAT(write(fd.get(), buf.data(), n_write),\n+ SyscallSucceedsWithValue(n_written));\n+\n+ // Check the write request.\n+ struct fuse_in_header in_header_write;\n+ struct fuse_write_in in_payload_write;\n+ std::vector<char> payload_buf(n_write);\n+ auto iov_in_write =\n+ FuseGenerateIovecs(in_header_write, in_payload_write, payload_buf);\n+ GetServerActualRequest(iov_in_write);\n+\n+ EXPECT_EQ(in_payload_write.fh, test_fh_);\n+ EXPECT_EQ(in_header_write.len,\n+ sizeof(in_header_write) + sizeof(in_payload_write));\n+ EXPECT_EQ(in_header_write.opcode, FUSE_WRITE);\n+ EXPECT_EQ(in_payload_write.offset, 0);\n+ EXPECT_EQ(in_payload_write.size, n_write);\n+ EXPECT_EQ(buf, payload_buf);\n+}\n+\n+TEST_F(WriteTest, WriteShortZero) {\n+ auto fd = ASSERT_NO_ERRNO_AND_VALUE(OpenTestFile(test_file_path_));\n+\n+ // Prepare for the write.\n+ const int n_write = 10;\n+ struct fuse_out_header out_header_write = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_write_out),\n+ };\n+ struct fuse_write_out out_payload_write = {\n+ .size = 0,\n+ };\n+ auto iov_out_write = FuseGenerateIovecs(out_header_write, out_payload_write);\n+ SetServerResponse(FUSE_WRITE, iov_out_write);\n+\n+ // Issue the write.\n+ std::vector<char> buf(n_write);\n+ RandomizeBuffer(buf.data(), buf.size());\n+ EXPECT_THAT(write(fd.get(), buf.data(), n_write), SyscallFailsWithErrno(EIO));\n+\n+ // Check the write request.\n+ struct fuse_in_header in_header_write;\n+ struct fuse_write_in in_payload_write;\n+ std::vector<char> payload_buf(n_write);\n+ auto iov_in_write =\n+ FuseGenerateIovecs(in_header_write, in_payload_write, payload_buf);\n+ GetServerActualRequest(iov_in_write);\n+\n+ EXPECT_EQ(in_payload_write.fh, test_fh_);\n+ EXPECT_EQ(in_header_write.len,\n+ sizeof(in_header_write) + sizeof(in_payload_write));\n+ EXPECT_EQ(in_header_write.opcode, FUSE_WRITE);\n+ EXPECT_EQ(in_payload_write.offset, 0);\n+ EXPECT_EQ(in_payload_write.size, n_write);\n+ EXPECT_EQ(buf, payload_buf);\n+}\n+\n+TEST_F(WriteTest, WriteZero) {\n+ auto fd = ASSERT_NO_ERRNO_AND_VALUE(OpenTestFile(test_file_path_));\n+\n+ // Issue the write.\n+ std::vector<char> buf(0);\n+ EXPECT_THAT(write(fd.get(), buf.data(), 0), SyscallSucceedsWithValue(0));\n+}\n+\n+TEST_F(WriteTest, PWrite) {\n+ const int file_size = 512;\n+ auto fd = ASSERT_NO_ERRNO_AND_VALUE(OpenTestFile(test_file_path_, file_size));\n+\n+ // Prepare for the write.\n+ const int n_write = 10;\n+ struct fuse_out_header out_header_write = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_write_out),\n+ };\n+ struct fuse_write_out out_payload_write = {\n+ .size = n_write,\n+ };\n+ auto iov_out_write = FuseGenerateIovecs(out_header_write, out_payload_write);\n+ SetServerResponse(FUSE_WRITE, iov_out_write);\n+\n+ // Issue the write.\n+ std::vector<char> buf(n_write);\n+ RandomizeBuffer(buf.data(), buf.size());\n+ const int offset_write = file_size >> 1;\n+ EXPECT_THAT(pwrite(fd.get(), buf.data(), n_write, offset_write),\n+ SyscallSucceedsWithValue(n_write));\n+\n+ // Check the write request.\n+ struct fuse_in_header in_header_write;\n+ struct fuse_write_in in_payload_write;\n+ std::vector<char> payload_buf(n_write);\n+ auto iov_in_write =\n+ FuseGenerateIovecs(in_header_write, in_payload_write, payload_buf);\n+ GetServerActualRequest(iov_in_write);\n+\n+ EXPECT_EQ(in_payload_write.fh, test_fh_);\n+ EXPECT_EQ(in_header_write.len,\n+ sizeof(in_header_write) + sizeof(in_payload_write));\n+ EXPECT_EQ(in_header_write.opcode, FUSE_WRITE);\n+ EXPECT_EQ(in_payload_write.offset, offset_write);\n+ EXPECT_EQ(in_payload_write.size, n_write);\n+ EXPECT_EQ(buf, payload_buf);\n+}\n+\n+TEST_F(WriteTestSmallMaxWrite, WriteSmallMaxWrie) {\n+ const int n_fragment = 10;\n+ const int n_write = size_fragment * n_fragment;\n+\n+ auto fd = ASSERT_NO_ERRNO_AND_VALUE(OpenTestFile(test_file_path_, n_write));\n+\n+ // Prepare for the write.\n+ struct fuse_out_header out_header_write = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_write_out),\n+ };\n+ struct fuse_write_out out_payload_write = {\n+ .size = size_fragment,\n+ };\n+ auto iov_out_write = FuseGenerateIovecs(out_header_write, out_payload_write);\n+\n+ for (int i = 0; i < n_fragment; ++i) {\n+ SetServerResponse(FUSE_WRITE, iov_out_write);\n+ }\n+\n+ // Issue the write.\n+ std::vector<char> buf(n_write);\n+ RandomizeBuffer(buf.data(), buf.size());\n+ EXPECT_THAT(write(fd.get(), buf.data(), n_write),\n+ SyscallSucceedsWithValue(n_write));\n+\n+ ASSERT_EQ(GetServerNumUnsentResponses(), 0);\n+ ASSERT_EQ(GetServerNumUnconsumedRequests(), n_fragment);\n+\n+ // Check the write request.\n+ struct fuse_in_header in_header_write;\n+ struct fuse_write_in in_payload_write;\n+ std::vector<char> payload_buf(size_fragment);\n+ auto iov_in_write =\n+ FuseGenerateIovecs(in_header_write, in_payload_write, payload_buf);\n+\n+ for (int i = 0; i < n_fragment; ++i) {\n+ GetServerActualRequest(iov_in_write);\n+\n+ EXPECT_EQ(in_payload_write.fh, test_fh_);\n+ EXPECT_EQ(in_header_write.len,\n+ sizeof(in_header_write) + sizeof(in_payload_write));\n+ EXPECT_EQ(in_header_write.opcode, FUSE_WRITE);\n+ EXPECT_EQ(in_payload_write.offset, i * size_fragment);\n+ EXPECT_EQ(in_payload_write.size, size_fragment);\n+\n+ auto it = buf.begin() + i * size_fragment;\n+ EXPECT_EQ(std::vector<char>(it, it + size_fragment), payload_buf);\n+ }\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n\\ No newline at end of file\n" } ]
Go
Apache License 2.0
google/gvisor
Implement FUSE_WRITE This commit adds basic write(2) support for FUSE.
259,983
28.08.2020 11:25:19
25,200
e63abd82ddfbaeb35c1dfc7c553db3d78207b037
Add default attr in fuse_util fuse_util provides utilities for fuse testing. Add a function to return a stub fuse_attr struct with specified mode and nodeid.
[ { "change_type": "MODIFY", "old_path": "test/fuse/linux/stat_test.cc", "new_path": "test/fuse/linux/stat_test.cc", "diff": "@@ -45,26 +45,7 @@ class StatTest : public FuseTest {\nTEST_F(StatTest, StatNormal) {\n// Set up fixture.\nmode_t expected_mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;\n- struct timespec atime = {.tv_sec = 1595436289, .tv_nsec = 134150844};\n- struct timespec mtime = {.tv_sec = 1595436290, .tv_nsec = 134150845};\n- struct timespec ctime = {.tv_sec = 1595436291, .tv_nsec = 134150846};\n- struct fuse_attr attr = {\n- .ino = 1,\n- .size = 512,\n- .blocks = 4,\n- .atime = static_cast<uint64_t>(atime.tv_sec),\n- .mtime = static_cast<uint64_t>(mtime.tv_sec),\n- .ctime = static_cast<uint64_t>(ctime.tv_sec),\n- .atimensec = static_cast<uint32_t>(atime.tv_nsec),\n- .mtimensec = static_cast<uint32_t>(mtime.tv_nsec),\n- .ctimensec = static_cast<uint32_t>(ctime.tv_nsec),\n- .mode = expected_mode,\n- .nlink = 2,\n- .uid = 1234,\n- .gid = 4321,\n- .rdev = 12,\n- .blksize = 4096,\n- };\n+ struct fuse_attr attr = DefaultFuseAttr(expected_mode, 1);\nstruct fuse_out_header out_header = {\n.len = sizeof(struct fuse_out_header) + sizeof(struct fuse_attr_out),\n};\n@@ -89,9 +70,12 @@ TEST_F(StatTest, StatNormal) {\n.st_size = static_cast<off_t>(attr.size),\n.st_blksize = attr.blksize,\n.st_blocks = static_cast<blkcnt_t>(attr.blocks),\n- .st_atim = atime,\n- .st_mtim = mtime,\n- .st_ctim = ctime,\n+ .st_atim = (struct timespec){.tv_sec = static_cast<int>(attr.atime),\n+ .tv_nsec = attr.atimensec},\n+ .st_mtim = (struct timespec){.tv_sec = static_cast<int>(attr.mtime),\n+ .tv_nsec = attr.mtimensec},\n+ .st_ctim = (struct timespec){.tv_sec = static_cast<int>(attr.ctime),\n+ .tv_nsec = attr.ctimensec},\n};\nEXPECT_TRUE(StatsAreEqual(stat_buf, expected_stat));\n" }, { "change_type": "MODIFY", "old_path": "test/util/fuse_util.cc", "new_path": "test/util/fuse_util.cc", "diff": "namespace gvisor {\nnamespace testing {\n-// Create response body with specified mode and nodeID.\n-fuse_entry_out DefaultEntryOut(mode_t mode, uint64_t node_id) {\n+// Create a default FuseAttr struct with specified mode and inode.\n+fuse_attr DefaultFuseAttr(mode_t mode, uint64_t inode) {\nconst int time_sec = 1595436289;\nconst int time_nsec = 134150844;\n- struct fuse_entry_out default_entry_out = {\n- .nodeid = node_id,\n- .generation = 0,\n- .entry_valid = time_sec,\n- .attr_valid = time_sec,\n- .entry_valid_nsec = time_nsec,\n- .attr_valid_nsec = time_nsec,\n- .attr =\n- (struct fuse_attr){\n- .ino = node_id,\n+ return (struct fuse_attr){\n+ .ino = inode,\n.size = 512,\n.blocks = 4,\n.atime = time_sec,\n@@ -50,7 +42,19 @@ fuse_entry_out DefaultEntryOut(mode_t mode, uint64_t node_id) {\n.gid = 4321,\n.rdev = 12,\n.blksize = 4096,\n- },\n+ };\n+}\n+\n+// Create response body with specified mode and nodeID.\n+fuse_entry_out DefaultEntryOut(mode_t mode, uint64_t node_id) {\n+ struct fuse_entry_out default_entry_out = {\n+ .nodeid = node_id,\n+ .generation = 0,\n+ .entry_valid = 0,\n+ .attr_valid = 0,\n+ .entry_valid_nsec = 0,\n+ .attr_valid_nsec = 0,\n+ .attr = DefaultFuseAttr(mode, node_id),\n};\nreturn default_entry_out;\n};\n" }, { "change_type": "MODIFY", "old_path": "test/util/fuse_util.h", "new_path": "test/util/fuse_util.h", "diff": "@@ -63,6 +63,9 @@ std::vector<struct iovec> FuseGenerateIovecs(T &first, Types &...args) {\nreturn first_iovec;\n}\n+// Create a fuse_attr filled with the specified mode and inode.\n+fuse_attr DefaultFuseAttr(mode_t mode, uint64_t inode);\n+\n// Return a fuse_entry_out FUSE server response body.\nfuse_entry_out DefaultEntryOut(mode_t mode, uint64_t nodeId);\n" } ]
Go
Apache License 2.0
google/gvisor
Add default attr in fuse_util fuse_util provides utilities for fuse testing. Add a function to return a stub fuse_attr struct with specified mode and nodeid.
259,983
08.09.2020 14:32:02
25,200
1146ab6bac7c4d34a9b78a6c318db3dae8150b4d
Add fuse_fd_util library to include common fuse fd test functions
[ { "change_type": "MODIFY", "old_path": "test/fuse/linux/BUILD", "new_path": "test/fuse/linux/BUILD", "diff": "@@ -141,6 +141,21 @@ cc_library(\n],\n)\n+cc_library(\n+ name = \"fuse_fd_util\",\n+ testonly = 1,\n+ srcs = [\"fuse_fd_util.cc\"],\n+ hdrs = [\"fuse_fd_util.h\"],\n+ deps = [\n+ gtest,\n+ \":fuse_base\",\n+ \"//test/util:cleanup\",\n+ \"//test/util:file_descriptor\",\n+ \"//test/util:fuse_util\",\n+ \"//test/util:posix_error\",\n+ ],\n+)\n+\ncc_binary(\nname = \"read_test\",\ntestonly = 1,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/fuse/linux/fuse_fd_util.cc", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include \"test/fuse/linux/fuse_fd_util.h\"\n+\n+#include <fcntl.h>\n+#include <linux/fuse.h>\n+#include <sys/stat.h>\n+#include <sys/types.h>\n+#include <sys/uio.h>\n+\n+#include <string>\n+#include <vector>\n+\n+#include \"test/util/cleanup.h\"\n+#include \"test/util/file_descriptor.h\"\n+#include \"test/util/fuse_util.h\"\n+#include \"test/util/posix_error.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+PosixErrorOr<FileDescriptor> FuseFdTest::OpenPath(const std::string &path,\n+ uint32_t flags, uint64_t fh) {\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_open_out),\n+ };\n+ struct fuse_open_out out_payload = {\n+ .fh = fh,\n+ .open_flags = flags,\n+ };\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload);\n+ SetServerResponse(FUSE_OPEN, iov_out);\n+\n+ auto res = Open(path.c_str(), flags);\n+ if (res.ok()) {\n+ SkipServerActualRequest();\n+ }\n+ return res;\n+}\n+\n+Cleanup FuseFdTest::CloseFD(FileDescriptor &fd) {\n+ return Cleanup([&] {\n+ close(fd.release());\n+ SkipServerActualRequest();\n+ });\n+}\n+\n+} // namespace testing\n+} // namespace gvisor\n+\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/fuse/linux/fuse_fd_util.h", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#ifndef GVISOR_TEST_FUSE_FUSE_FD_UTIL_H_\n+#define GVISOR_TEST_FUSE_FUSE_FD_UTIL_H_\n+\n+#include <fcntl.h>\n+#include <sys/stat.h>\n+#include <sys/types.h>\n+\n+#include <string>\n+\n+#include \"test/fuse/linux/fuse_base.h\"\n+#include \"test/util/cleanup.h\"\n+#include \"test/util/file_descriptor.h\"\n+#include \"test/util/posix_error.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+class FuseFdTest : public FuseTest {\n+ public:\n+ // Sets the FUSE server to respond to a FUSE_OPEN with corresponding flags and\n+ // fh. Then does a real file system open on the absolute path to get an fd.\n+ PosixErrorOr<FileDescriptor> OpenPath(const std::string &path,\n+ uint32_t flags = O_RDONLY,\n+ uint64_t fh = 1);\n+\n+ // Returns a cleanup object that closes the fd when it is destroyed. After\n+ // the close is done, tells the FUSE server to skip this FUSE_RELEASE.\n+ Cleanup CloseFD(FileDescriptor &fd);\n+};\n+\n+} // namespace testing\n+} // namespace gvisor\n+\n+#endif // GVISOR_TEST_FUSE_FUSE_FD_UTIL_H_\n" } ]
Go
Apache License 2.0
google/gvisor
Add fuse_fd_util library to include common fuse fd test functions
259,983
09.09.2020 09:16:09
25,200
4181e8c97482a3c787c2b508e6d75a21323ba515
Add fh support for revise attr and fstat(2) test According to Linux 4.4's FUSE behavior, the flags and fh attributes in FUSE_GETATTR are only used in read, write, and lseek. fstat(2) doesn't use them either. Add tests to ensure the requests sent from FUSE module are consistent with Linux's. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/fuse.go", "new_path": "pkg/abi/linux/fuse.go", "diff": "@@ -227,6 +227,11 @@ type FUSEInitOut struct {\n_ [8]uint32\n}\n+// FUSE_GETATTR_FH is currently the only flag of FUSEGetAttrIn.GetAttrFlags.\n+// If it is set, the file handle (FUSEGetAttrIn.Fh) is used to indicate the\n+// object instead of the node id attribute in the request header.\n+const FUSE_GETATTR_FH = (1 << 0)\n+\n// FUSEGetAttrIn is the request sent by the kernel to the daemon,\n// to get the attribute of a inode.\n//\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "new_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "diff": "@@ -609,9 +609,9 @@ func statFromFUSEAttr(attr linux.FUSEAttr, mask, devMinor uint32) linux.Statx {\n}\n// getAttr gets the attribute of this inode by issuing a FUSE_GETATTR request\n-// or read from local cache.\n-// It updates the corresponding attributes if necessary.\n-func (i *inode) getAttr(ctx context.Context, fs *vfs.Filesystem, opts vfs.StatOptions) (linux.FUSEAttr, error) {\n+// or read from local cache. It updates the corresponding attributes if\n+// necessary.\n+func (i *inode) getAttr(ctx context.Context, fs *vfs.Filesystem, opts vfs.StatOptions, flags uint32, fh uint64) (linux.FUSEAttr, error) {\nattributeVersion := atomic.LoadUint64(&i.fs.conn.attributeVersion)\n// TODO(gvisor.dev/issue/3679): send the request only if\n@@ -631,11 +631,10 @@ func (i *inode) getAttr(ctx context.Context, fs *vfs.Filesystem, opts vfs.StatOp\ncreds := auth.CredentialsFromContext(ctx)\n- var in linux.FUSEGetAttrIn\n- // We don't set any attribute in the request, because in VFS2 fstat(2) will\n- // finally be translated into vfs.FilesystemImpl.StatAt() (see\n- // pkg/sentry/syscalls/linux/vfs2/stat.go), resulting in the same flow\n- // as stat(2). Thus GetAttrFlags and Fh variable will never be used in VFS2.\n+ in := linux.FUSEGetAttrIn{\n+ GetAttrFlags: flags,\n+ Fh: fh,\n+ }\nreq, err := i.fs.conn.NewRequest(creds, uint32(task.ThreadID()), i.NodeID, linux.FUSE_GETATTR, &in)\nif err != nil {\nreturn linux.FUSEAttr{}, err\n@@ -676,17 +675,17 @@ func (i *inode) getAttr(ctx context.Context, fs *vfs.Filesystem, opts vfs.StatOp\n// reviseAttr attempts to update the attributes for internal purposes\n// by calling getAttr with a pre-specified mask.\n// Used by read, write, lseek.\n-func (i *inode) reviseAttr(ctx context.Context) error {\n+func (i *inode) reviseAttr(ctx context.Context, flags uint32, fh uint64) error {\n// Never need atime for internal purposes.\n_, err := i.getAttr(ctx, i.fs.VFSFilesystem(), vfs.StatOptions{\nMask: linux.STATX_BASIC_STATS &^ linux.STATX_ATIME,\n- })\n+ }, flags, fh)\nreturn err\n}\n// Stat implements kernfs.Inode.Stat.\nfunc (i *inode) Stat(ctx context.Context, fs *vfs.Filesystem, opts vfs.StatOptions) (linux.Statx, error) {\n- attr, err := i.getAttr(ctx, fs, opts)\n+ attr, err := i.getAttr(ctx, fs, opts, 0, 0)\nif err != nil {\nreturn linux.Statx{}, err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/regular_file.go", "new_path": "pkg/sentry/fsimpl/fuse/regular_file.go", "diff": "@@ -65,7 +65,7 @@ func (fd *regularFileFD) PRead(ctx context.Context, dst usermem.IOSequence, offs\n// Reading beyond EOF, update file size if outdated.\nif uint64(offset+size) > atomic.LoadUint64(&inode.size) {\n- if err := inode.reviseAttr(ctx); err != nil {\n+ if err := inode.reviseAttr(ctx, linux.FUSE_GETATTR_FH, fd.Fh); err != nil {\nreturn 0, err\n}\n// If the offset after update is still too large, return error.\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/BUILD", "new_path": "test/fuse/linux/BUILD", "diff": "@@ -11,7 +11,9 @@ cc_binary(\nsrcs = [\"stat_test.cc\"],\ndeps = [\ngtest,\n- \":fuse_base\",\n+ \":fuse_fd_util\",\n+ \"//test/util:cleanup\",\n+ \"//test/util:fs_util\",\n\"//test/util:fuse_util\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/stat_test.cc", "new_path": "test/fuse/linux/stat_test.cc", "diff": "#include <sys/stat.h>\n#include <sys/statfs.h>\n#include <sys/types.h>\n+#include <sys/uio.h>\n#include <unistd.h>\n#include <vector>\n#include \"gtest/gtest.h\"\n-#include \"test/fuse/linux/fuse_base.h\"\n+#include \"test/fuse/linux/fuse_fd_util.h\"\n+#include \"test/util/cleanup.h\"\n+#include \"test/util/fs_util.h\"\n#include \"test/util/fuse_util.h\"\n#include \"test/util/test_util.h\"\n@@ -32,19 +35,30 @@ namespace testing {\nnamespace {\n-class StatTest : public FuseTest {\n+class StatTest : public FuseFdTest {\npublic:\n+ void SetUp() override {\n+ FuseFdTest::SetUp();\n+ test_file_path_ = JoinPath(mount_point_.path(), test_file_);\n+ }\n+\n+ protected:\nbool StatsAreEqual(struct stat expected, struct stat actual) {\n- // device number will be dynamically allocated by kernel, we cannot know\n- // in advance\n+ // Device number will be dynamically allocated by kernel, we cannot know in\n+ // advance.\nactual.st_dev = expected.st_dev;\nreturn memcmp(&expected, &actual, sizeof(struct stat)) == 0;\n}\n+\n+ const std::string test_file_ = \"testfile\";\n+ const mode_t expected_mode = S_IFREG | S_IRUSR | S_IWUSR;\n+ const uint64_t fh = 23;\n+\n+ std::string test_file_path_;\n};\nTEST_F(StatTest, StatNormal) {\n// Set up fixture.\n- mode_t expected_mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;\nstruct fuse_attr attr = DefaultFuseAttr(expected_mode, 1);\nstruct fuse_out_header out_header = {\n.len = sizeof(struct fuse_out_header) + sizeof(struct fuse_attr_out),\n@@ -55,7 +69,7 @@ TEST_F(StatTest, StatNormal) {\nauto iov_out = FuseGenerateIovecs(out_header, out_payload);\nSetServerResponse(FUSE_GETATTR, iov_out);\n- // Do integration test.\n+ // Make syscall.\nstruct stat stat_buf;\nEXPECT_THAT(stat(mount_point_.path().c_str(), &stat_buf), SyscallSucceeds());\n@@ -99,7 +113,7 @@ TEST_F(StatTest, StatNotFound) {\nauto iov_out = FuseGenerateIovecs(out_header);\nSetServerResponse(FUSE_GETATTR, iov_out);\n- // Do integration test.\n+ // Make syscall.\nstruct stat stat_buf;\nEXPECT_THAT(stat(mount_point_.path().c_str(), &stat_buf),\nSyscallFailsWithErrno(ENOENT));\n@@ -115,6 +129,90 @@ TEST_F(StatTest, StatNotFound) {\nEXPECT_EQ(in_payload.fh, 0);\n}\n+TEST_F(StatTest, FstatNormal) {\n+ // Set up fixture.\n+ SetServerInodeLookup(test_file_);\n+ auto fd = ASSERT_NO_ERRNO_AND_VALUE(OpenPath(test_file_path_, O_RDONLY, fh));\n+ auto close_fd = CloseFD(fd);\n+\n+ struct fuse_attr attr = DefaultFuseAttr(expected_mode, 2);\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_attr_out),\n+ };\n+ struct fuse_attr_out out_payload = {\n+ .attr = attr,\n+ };\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload);\n+ SetServerResponse(FUSE_GETATTR, iov_out);\n+\n+ // Make syscall.\n+ struct stat stat_buf;\n+ EXPECT_THAT(fstat(fd.get(), &stat_buf), SyscallSucceeds());\n+\n+ // Check filesystem operation result.\n+ struct stat expected_stat = {\n+ .st_ino = attr.ino,\n+ .st_nlink = attr.nlink,\n+ .st_mode = expected_mode,\n+ .st_uid = attr.uid,\n+ .st_gid = attr.gid,\n+ .st_rdev = attr.rdev,\n+ .st_size = static_cast<off_t>(attr.size),\n+ .st_blksize = attr.blksize,\n+ .st_blocks = static_cast<blkcnt_t>(attr.blocks),\n+ .st_atim = (struct timespec){.tv_sec = static_cast<int>(attr.atime),\n+ .tv_nsec = attr.atimensec},\n+ .st_mtim = (struct timespec){.tv_sec = static_cast<int>(attr.mtime),\n+ .tv_nsec = attr.mtimensec},\n+ .st_ctim = (struct timespec){.tv_sec = static_cast<int>(attr.ctime),\n+ .tv_nsec = attr.ctimensec},\n+ };\n+ EXPECT_TRUE(StatsAreEqual(stat_buf, expected_stat));\n+\n+ // Check FUSE request.\n+ struct fuse_in_header in_header;\n+ struct fuse_getattr_in in_payload;\n+ auto iov_in = FuseGenerateIovecs(in_header, in_payload);\n+\n+ GetServerActualRequest(iov_in);\n+ EXPECT_EQ(in_header.opcode, FUSE_GETATTR);\n+ EXPECT_EQ(in_payload.getattr_flags, 0);\n+ EXPECT_EQ(in_payload.fh, 0);\n+}\n+\n+TEST_F(StatTest, StatByFileHandle) {\n+ // Set up fixture.\n+ SetServerInodeLookup(test_file_, expected_mode, 0);\n+ auto fd = ASSERT_NO_ERRNO_AND_VALUE(OpenPath(test_file_path_, O_RDONLY, fh));\n+ auto close_fd = CloseFD(fd);\n+\n+ struct fuse_attr attr = DefaultFuseAttr(expected_mode, 2, 0);\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_attr_out),\n+ };\n+ struct fuse_attr_out out_payload = {\n+ .attr = attr,\n+ };\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload);\n+ SetServerResponse(FUSE_GETATTR, iov_out);\n+\n+ // Make syscall.\n+ std::vector<char> buf(1);\n+ // Since this is an empty file, it won't issue FUSE_READ. But a FUSE_GETATTR\n+ // will be issued before read completes.\n+ EXPECT_THAT(read(fd.get(), buf.data(), buf.size()), SyscallSucceeds());\n+\n+ // Check FUSE request.\n+ struct fuse_in_header in_header;\n+ struct fuse_getattr_in in_payload;\n+ auto iov_in = FuseGenerateIovecs(in_header, in_payload);\n+\n+ GetServerActualRequest(iov_in);\n+ EXPECT_EQ(in_header.opcode, FUSE_GETATTR);\n+ EXPECT_EQ(in_payload.getattr_flags, FUSE_GETATTR_FH);\n+ EXPECT_EQ(in_payload.fh, fh);\n+}\n+\n} // namespace\n} // namespace testing\n" }, { "change_type": "MODIFY", "old_path": "test/util/fuse_util.cc", "new_path": "test/util/fuse_util.cc", "diff": "namespace gvisor {\nnamespace testing {\n-// Create a default FuseAttr struct with specified mode and inode.\n-fuse_attr DefaultFuseAttr(mode_t mode, uint64_t inode) {\n+// Create a default FuseAttr struct with specified mode, inode, and size.\n+fuse_attr DefaultFuseAttr(mode_t mode, uint64_t inode, uint64_t size) {\nconst int time_sec = 1595436289;\nconst int time_nsec = 134150844;\nreturn (struct fuse_attr){\n.ino = inode,\n- .size = 512,\n+ .size = size,\n.blocks = 4,\n.atime = time_sec,\n.mtime = time_sec,\n@@ -45,8 +45,8 @@ fuse_attr DefaultFuseAttr(mode_t mode, uint64_t inode) {\n};\n}\n-// Create response body with specified mode and nodeID.\n-fuse_entry_out DefaultEntryOut(mode_t mode, uint64_t node_id) {\n+// Create response body with specified mode, nodeID, and size.\n+fuse_entry_out DefaultEntryOut(mode_t mode, uint64_t node_id, uint64_t size) {\nstruct fuse_entry_out default_entry_out = {\n.nodeid = node_id,\n.generation = 0,\n@@ -54,7 +54,7 @@ fuse_entry_out DefaultEntryOut(mode_t mode, uint64_t node_id) {\n.attr_valid = 0,\n.entry_valid_nsec = 0,\n.attr_valid_nsec = 0,\n- .attr = DefaultFuseAttr(mode, node_id),\n+ .attr = DefaultFuseAttr(mode, node_id, size),\n};\nreturn default_entry_out;\n};\n" }, { "change_type": "MODIFY", "old_path": "test/util/fuse_util.h", "new_path": "test/util/fuse_util.h", "diff": "@@ -64,10 +64,11 @@ std::vector<struct iovec> FuseGenerateIovecs(T &first, Types &...args) {\n}\n// Create a fuse_attr filled with the specified mode and inode.\n-fuse_attr DefaultFuseAttr(mode_t mode, uint64_t inode);\n+fuse_attr DefaultFuseAttr(mode_t mode, uint64_t inode, uint64_t size = 512);\n// Return a fuse_entry_out FUSE server response body.\n-fuse_entry_out DefaultEntryOut(mode_t mode, uint64_t nodeId);\n+fuse_entry_out DefaultEntryOut(mode_t mode, uint64_t node_id,\n+ uint64_t size = 512);\n} // namespace testing\n} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Add fh support for revise attr and fstat(2) test According to Linux 4.4's FUSE behavior, the flags and fh attributes in FUSE_GETATTR are only used in read, write, and lseek. fstat(2) doesn't use them either. Add tests to ensure the requests sent from FUSE module are consistent with Linux's. Updates #3655
259,983
09.09.2020 10:44:09
25,200
bf8efe8cdf4b6af50ec89cda37342cf51c8b50b4
Implement FUSE_SETATTR This commit implements FUSE_SETATTR command. When a system call modifies the metadata of a regular file or a folder by chown(2), chmod(2), truncate(2), utime(2), or utimes(2), they should be translated to corresponding FUSE_SETATTR command and sent to the FUSE server. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/fuse.go", "new_path": "pkg/abi/linux/fuse.go", "diff": "@@ -749,3 +749,70 @@ func (r *FUSEDirent) UnmarshalBytes(src []byte) {\nname.UnmarshalBytes(src[:r.Meta.NameLen])\nr.Name = string(name)\n}\n+\n+// FATTR_* consts are the attribute flags defined in include/uapi/linux/fuse.h.\n+// These should be or-ed together for setattr to know what has been changed.\n+const (\n+ FATTR_MODE = (1 << 0)\n+ FATTR_UID = (1 << 1)\n+ FATTR_GID = (1 << 2)\n+ FATTR_SIZE = (1 << 3)\n+ FATTR_ATIME = (1 << 4)\n+ FATTR_MTIME = (1 << 5)\n+ FATTR_FH = (1 << 6)\n+ FATTR_ATIME_NOW = (1 << 7)\n+ FATTR_MTIME_NOW = (1 << 8)\n+ FATTR_LOCKOWNER = (1 << 9)\n+ FATTR_CTIME = (1 << 10)\n+)\n+\n+// FUSESetAttrIn is the request sent by the kernel to the daemon,\n+// to set the attribute(s) of a file.\n+//\n+// +marshal\n+type FUSESetAttrIn struct {\n+ // Valid indicates which attributes are modified by this request.\n+ Valid uint32\n+\n+ _ uint32\n+\n+ // Fh is used to identify the file if FATTR_FH is set in Valid.\n+ Fh uint64\n+\n+ // Size is the size that the request wants to change to.\n+ Size uint64\n+\n+ // LockOwner is the owner of the lock that the request wants to change to.\n+ LockOwner uint64\n+\n+ // Atime is the access time that the request wants to change to.\n+ Atime uint64\n+\n+ // Mtime is the modification time that the request wants to change to.\n+ Mtime uint64\n+\n+ // Ctime is the status change time that the request wants to change to.\n+ Ctime uint64\n+\n+ // AtimeNsec is the nano second part of Atime.\n+ AtimeNsec uint32\n+\n+ // MtimeNsec is the nano second part of Mtime.\n+ MtimeNsec uint32\n+\n+ // CtimeNsec is the nano second part of Ctime.\n+ CtimeNsec uint32\n+\n+ // Mode is the file mode that the request wants to change to.\n+ Mode uint32\n+\n+ _ uint32\n+\n+ // UID is the user ID of the owner that the request wants to change to.\n+ UID uint32\n+\n+ // GID is the group ID of the owner that the request wants to change to.\n+ GID uint32\n+\n+ _ uint32\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/file.go", "new_path": "pkg/sentry/fsimpl/fuse/file.go", "diff": "@@ -123,5 +123,5 @@ func (fd *fileDescription) Stat(ctx context.Context, opts vfs.StatOptions) (linu\n// SetStat implements FileDescriptionImpl.SetStat.\nfunc (fd *fileDescription) SetStat(ctx context.Context, opts vfs.SetStatOptions) error {\ncreds := auth.CredentialsFromContext(ctx)\n- return fd.inode().SetStat(ctx, fd.inode().fs.VFSFilesystem(), creds, opts)\n+ return fd.inode().setAttr(ctx, fd.inode().fs.VFSFilesystem(), creds, opts, true, fd.Fh)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "new_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "diff": "@@ -660,7 +660,7 @@ func (i *inode) getAttr(ctx context.Context, fs *vfs.Filesystem, opts vfs.StatOp\n}\n// Set the metadata of kernfs.InodeAttrs.\n- if err := i.SetStat(ctx, fs, creds, vfs.SetStatOptions{\n+ if err := i.SetInodeStat(ctx, fs, creds, vfs.SetStatOptions{\nStat: statFromFUSEAttr(out.Attr, linux.STATX_ALL, i.fs.devMinor),\n}); err != nil {\nreturn linux.FUSEAttr{}, err\n@@ -703,3 +703,84 @@ func (i *inode) StatFS(ctx context.Context, fs *vfs.Filesystem) (linux.Statfs, e\n// TODO(gvisor.dev/issues/3413): Complete the implementation of statfs.\nreturn vfs.GenericStatFS(linux.FUSE_SUPER_MAGIC), nil\n}\n+\n+// fattrMaskFromStats converts vfs.SetStatOptions.Stat.Mask to linux stats mask\n+// aligned with the attribute mask defined in include/linux/fs.h.\n+func fattrMaskFromStats(mask uint32) uint32 {\n+ var fuseAttrMask uint32\n+ maskMap := map[uint32]uint32{\n+ linux.STATX_MODE: linux.FATTR_MODE,\n+ linux.STATX_UID: linux.FATTR_UID,\n+ linux.STATX_GID: linux.FATTR_GID,\n+ linux.STATX_SIZE: linux.FATTR_SIZE,\n+ linux.STATX_ATIME: linux.FATTR_ATIME,\n+ linux.STATX_MTIME: linux.FATTR_MTIME,\n+ linux.STATX_CTIME: linux.FATTR_CTIME,\n+ }\n+ for statxMask, fattrMask := range maskMap {\n+ if mask&statxMask != 0 {\n+ fuseAttrMask |= fattrMask\n+ }\n+ }\n+ return fuseAttrMask\n+}\n+\n+// SetStat implements kernfs.Inode.SetStat.\n+func (i *inode) SetStat(ctx context.Context, fs *vfs.Filesystem, creds *auth.Credentials, opts vfs.SetStatOptions) error {\n+ return i.setAttr(ctx, fs, creds, opts, false, 0)\n+}\n+\n+func (i *inode) setAttr(ctx context.Context, fs *vfs.Filesystem, creds *auth.Credentials, opts vfs.SetStatOptions, useFh bool, fh uint64) error {\n+ conn := i.fs.conn\n+ task := kernel.TaskFromContext(ctx)\n+ if task == nil {\n+ log.Warningf(\"couldn't get kernel task from context\")\n+ return syserror.EINVAL\n+ }\n+\n+ // We should retain the original file type when assigning new mode.\n+ fileType := uint16(i.Mode()) & linux.S_IFMT\n+ fattrMask := fattrMaskFromStats(opts.Stat.Mask)\n+ if useFh {\n+ fattrMask |= linux.FATTR_FH\n+ }\n+ in := linux.FUSESetAttrIn{\n+ Valid: fattrMask,\n+ Fh: fh,\n+ Size: opts.Stat.Size,\n+ Atime: uint64(opts.Stat.Atime.Sec),\n+ Mtime: uint64(opts.Stat.Mtime.Sec),\n+ Ctime: uint64(opts.Stat.Ctime.Sec),\n+ AtimeNsec: opts.Stat.Atime.Nsec,\n+ MtimeNsec: opts.Stat.Mtime.Nsec,\n+ CtimeNsec: opts.Stat.Ctime.Nsec,\n+ Mode: uint32(fileType | opts.Stat.Mode),\n+ UID: opts.Stat.UID,\n+ GID: opts.Stat.GID,\n+ }\n+ req, err := conn.NewRequest(creds, uint32(task.ThreadID()), i.NodeID, linux.FUSE_SETATTR, &in)\n+ if err != nil {\n+ return err\n+ }\n+\n+ res, err := conn.Call(task, req)\n+ if err != nil {\n+ return err\n+ }\n+ if err := res.Error(); err != nil {\n+ return err\n+ }\n+ out := linux.FUSEGetAttrOut{}\n+ if err := res.UnmarshalPayload(&out); err != nil {\n+ return err\n+ }\n+\n+ // Set the metadata of kernfs.InodeAttrs.\n+ if err := i.SetInodeStat(ctx, fs, creds, vfs.SetStatOptions{\n+ Stat: statFromFUSEAttr(out.Attr, linux.STATX_ALL, i.fs.devMinor),\n+ }); err != nil {\n+ return err\n+ }\n+\n+ return nil\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go", "new_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go", "diff": "@@ -256,6 +256,13 @@ func (a *InodeAttrs) Stat(context.Context, *vfs.Filesystem, vfs.StatOptions) (li\n// SetStat implements Inode.SetStat.\nfunc (a *InodeAttrs) SetStat(ctx context.Context, fs *vfs.Filesystem, creds *auth.Credentials, opts vfs.SetStatOptions) error {\n+ return a.SetInodeStat(ctx, fs, creds, opts)\n+}\n+\n+// SetInodeStat sets the corresponding attributes from opts to InodeAttrs.\n+// This function can be used by other kernfs-based filesystem implementation to\n+// sets the unexported attributes into kernfs.InodeAttrs.\n+func (a *InodeAttrs) SetInodeStat(ctx context.Context, fs *vfs.Filesystem, creds *auth.Credentials, opts vfs.SetStatOptions) error {\nif opts.Stat.Mask == 0 {\nreturn nil\n}\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/BUILD", "new_path": "test/fuse/BUILD", "diff": "@@ -62,6 +62,11 @@ syscall_test(\ntest = \"//test/fuse/linux:create_test\",\n)\n+syscall_test(\n+ fuse = \"True\",\n+ test = \"//test/fuse/linux:setstat_test\",\n+)\n+\nsyscall_test(\nsize = \"large\",\nadd_overlay = True,\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/BUILD", "new_path": "test/fuse/linux/BUILD", "diff": "@@ -100,6 +100,22 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"setstat_test\",\n+ testonly = 1,\n+ srcs = [\"setstat_test.cc\"],\n+ deps = [\n+ gtest,\n+ \":fuse_fd_util\",\n+ \"//test/util:cleanup\",\n+ \"//test/util:fs_util\",\n+ \"//test/util:fuse_util\",\n+ \"//test/util:temp_umask\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n+\ncc_binary(\nname = \"rmdir_test\",\ntestonly = 1,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/fuse/linux/setstat_test.cc", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <errno.h>\n+#include <fcntl.h>\n+#include <linux/fuse.h>\n+#include <sys/stat.h>\n+#include <sys/statfs.h>\n+#include <sys/types.h>\n+#include <sys/uio.h>\n+#include <unistd.h>\n+#include <utime.h>\n+\n+#include <string>\n+#include <vector>\n+\n+#include \"gtest/gtest.h\"\n+#include \"test/fuse/linux/fuse_fd_util.h\"\n+#include \"test/util/cleanup.h\"\n+#include \"test/util/fs_util.h\"\n+#include \"test/util/fuse_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+class SetStatTest : public FuseFdTest {\n+ public:\n+ void SetUp() override {\n+ FuseFdTest::SetUp();\n+ test_dir_path_ = JoinPath(mount_point_.path(), test_dir_);\n+ test_file_path_ = JoinPath(mount_point_.path(), test_file_);\n+ }\n+\n+ protected:\n+ const uint64_t fh = 23;\n+ const std::string test_dir_ = \"testdir\";\n+ const std::string test_file_ = \"testfile\";\n+ const mode_t test_dir_mode_ = S_IFDIR | S_IRUSR | S_IWUSR | S_IXUSR;\n+ const mode_t test_file_mode_ = S_IFREG | S_IRUSR | S_IWUSR | S_IXUSR;\n+\n+ std::string test_dir_path_;\n+ std::string test_file_path_;\n+};\n+\n+TEST_F(SetStatTest, ChmodDir) {\n+ // Set up fixture.\n+ SetServerInodeLookup(test_dir_, test_dir_mode_);\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_attr_out),\n+ .error = 0,\n+ };\n+ mode_t set_mode = S_IRGRP | S_IWGRP | S_IXGRP;\n+ struct fuse_attr_out out_payload = {\n+ .attr = DefaultFuseAttr(set_mode, 2),\n+ };\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload);\n+ SetServerResponse(FUSE_SETATTR, iov_out);\n+\n+ // Make syscall.\n+ EXPECT_THAT(chmod(test_dir_path_.c_str(), set_mode), SyscallSucceeds());\n+\n+ // Check FUSE request.\n+ struct fuse_in_header in_header;\n+ struct fuse_setattr_in in_payload;\n+ auto iov_in = FuseGenerateIovecs(in_header, in_payload);\n+\n+ GetServerActualRequest(iov_in);\n+ EXPECT_EQ(in_header.len, sizeof(in_header) + sizeof(in_payload));\n+ EXPECT_EQ(in_header.opcode, FUSE_SETATTR);\n+ EXPECT_EQ(in_header.uid, 0);\n+ EXPECT_EQ(in_header.gid, 0);\n+ EXPECT_EQ(in_payload.valid, FATTR_MODE);\n+ EXPECT_EQ(in_payload.mode, S_IFDIR | set_mode);\n+}\n+\n+TEST_F(SetStatTest, ChownDir) {\n+ // Set up fixture.\n+ SetServerInodeLookup(test_dir_, test_dir_mode_);\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_attr_out),\n+ .error = 0,\n+ };\n+ struct fuse_attr_out out_payload = {\n+ .attr = DefaultFuseAttr(test_dir_mode_, 2),\n+ };\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload);\n+ SetServerResponse(FUSE_SETATTR, iov_out);\n+\n+ // Make syscall.\n+ EXPECT_THAT(chown(test_dir_path_.c_str(), 1025, 1025), SyscallSucceeds());\n+\n+ // Check FUSE request.\n+ struct fuse_in_header in_header;\n+ struct fuse_setattr_in in_payload;\n+ auto iov_in = FuseGenerateIovecs(in_header, in_payload);\n+\n+ GetServerActualRequest(iov_in);\n+ EXPECT_EQ(in_header.len, sizeof(in_header) + sizeof(in_payload));\n+ EXPECT_EQ(in_header.opcode, FUSE_SETATTR);\n+ EXPECT_EQ(in_header.uid, 0);\n+ EXPECT_EQ(in_header.gid, 0);\n+ EXPECT_EQ(in_payload.valid, FATTR_UID | FATTR_GID);\n+ EXPECT_EQ(in_payload.uid, 1025);\n+ EXPECT_EQ(in_payload.gid, 1025);\n+}\n+\n+TEST_F(SetStatTest, TruncateFile) {\n+ // Set up fixture.\n+ SetServerInodeLookup(test_file_, test_file_mode_);\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_attr_out),\n+ .error = 0,\n+ };\n+ struct fuse_attr_out out_payload = {\n+ .attr = DefaultFuseAttr(S_IFREG | S_IRUSR | S_IWUSR, 2),\n+ };\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload);\n+ SetServerResponse(FUSE_SETATTR, iov_out);\n+\n+ // Make syscall.\n+ EXPECT_THAT(truncate(test_file_path_.c_str(), 321), SyscallSucceeds());\n+\n+ // Check FUSE request.\n+ struct fuse_in_header in_header;\n+ struct fuse_setattr_in in_payload;\n+ auto iov_in = FuseGenerateIovecs(in_header, in_payload);\n+\n+ GetServerActualRequest(iov_in);\n+ EXPECT_EQ(in_header.len, sizeof(in_header) + sizeof(in_payload));\n+ EXPECT_EQ(in_header.opcode, FUSE_SETATTR);\n+ EXPECT_EQ(in_header.uid, 0);\n+ EXPECT_EQ(in_header.gid, 0);\n+ EXPECT_EQ(in_payload.valid, FATTR_SIZE);\n+ EXPECT_EQ(in_payload.size, 321);\n+}\n+\n+TEST_F(SetStatTest, UtimeFile) {\n+ // Set up fixture.\n+ SetServerInodeLookup(test_file_, test_file_mode_);\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_attr_out),\n+ .error = 0,\n+ };\n+ struct fuse_attr_out out_payload = {\n+ .attr = DefaultFuseAttr(S_IFREG | S_IRUSR | S_IWUSR, 2),\n+ };\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload);\n+ SetServerResponse(FUSE_SETATTR, iov_out);\n+\n+ // Make syscall.\n+ time_t expected_atime = 1597159766, expected_mtime = 1597159765;\n+ struct utimbuf times = {\n+ .actime = expected_atime,\n+ .modtime = expected_mtime,\n+ };\n+ EXPECT_THAT(utime(test_file_path_.c_str(), &times), SyscallSucceeds());\n+\n+ // Check FUSE request.\n+ struct fuse_in_header in_header;\n+ struct fuse_setattr_in in_payload;\n+ auto iov_in = FuseGenerateIovecs(in_header, in_payload);\n+\n+ GetServerActualRequest(iov_in);\n+ EXPECT_EQ(in_header.len, sizeof(in_header) + sizeof(in_payload));\n+ EXPECT_EQ(in_header.opcode, FUSE_SETATTR);\n+ EXPECT_EQ(in_header.uid, 0);\n+ EXPECT_EQ(in_header.gid, 0);\n+ EXPECT_EQ(in_payload.valid, FATTR_ATIME | FATTR_MTIME);\n+ EXPECT_EQ(in_payload.atime, expected_atime);\n+ EXPECT_EQ(in_payload.mtime, expected_mtime);\n+}\n+\n+TEST_F(SetStatTest, UtimesFile) {\n+ // Set up fixture.\n+ SetServerInodeLookup(test_file_, test_file_mode_);\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_attr_out),\n+ .error = 0,\n+ };\n+ struct fuse_attr_out out_payload = {\n+ .attr = DefaultFuseAttr(test_file_mode_, 2),\n+ };\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload);\n+ SetServerResponse(FUSE_SETATTR, iov_out);\n+\n+ // Make syscall.\n+ struct timeval expected_times[2] = {\n+ {\n+ .tv_sec = 1597159766,\n+ .tv_usec = 234945,\n+ },\n+ {\n+ .tv_sec = 1597159765,\n+ .tv_usec = 232341,\n+ },\n+ };\n+ EXPECT_THAT(utimes(test_file_path_.c_str(), expected_times),\n+ SyscallSucceeds());\n+\n+ // Check FUSE request.\n+ struct fuse_in_header in_header;\n+ struct fuse_setattr_in in_payload;\n+ auto iov_in = FuseGenerateIovecs(in_header, in_payload);\n+\n+ GetServerActualRequest(iov_in);\n+ EXPECT_EQ(in_header.len, sizeof(in_header) + sizeof(in_payload));\n+ EXPECT_EQ(in_header.opcode, FUSE_SETATTR);\n+ EXPECT_EQ(in_header.uid, 0);\n+ EXPECT_EQ(in_header.gid, 0);\n+ EXPECT_EQ(in_payload.valid, FATTR_ATIME | FATTR_MTIME);\n+ EXPECT_EQ(in_payload.atime, expected_times[0].tv_sec);\n+ EXPECT_EQ(in_payload.atimensec, expected_times[0].tv_usec * 1000);\n+ EXPECT_EQ(in_payload.mtime, expected_times[1].tv_sec);\n+ EXPECT_EQ(in_payload.mtimensec, expected_times[1].tv_usec * 1000);\n+}\n+\n+TEST_F(SetStatTest, FtruncateFile) {\n+ // Set up fixture.\n+ SetServerInodeLookup(test_file_, test_file_mode_);\n+ auto fd = ASSERT_NO_ERRNO_AND_VALUE(OpenPath(test_file_path_, O_RDWR, fh));\n+ auto close_fd = CloseFD(fd);\n+\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_attr_out),\n+ .error = 0,\n+ };\n+ struct fuse_attr_out out_payload = {\n+ .attr = DefaultFuseAttr(test_file_mode_, 2),\n+ };\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload);\n+ SetServerResponse(FUSE_SETATTR, iov_out);\n+\n+ // Make syscall.\n+ EXPECT_THAT(ftruncate(fd.get(), 321), SyscallSucceeds());\n+\n+ // Check FUSE request.\n+ struct fuse_in_header in_header;\n+ struct fuse_setattr_in in_payload;\n+ auto iov_in = FuseGenerateIovecs(in_header, in_payload);\n+\n+ GetServerActualRequest(iov_in);\n+ EXPECT_EQ(in_header.len, sizeof(in_header) + sizeof(in_payload));\n+ EXPECT_EQ(in_header.opcode, FUSE_SETATTR);\n+ EXPECT_EQ(in_header.uid, 0);\n+ EXPECT_EQ(in_header.gid, 0);\n+ EXPECT_EQ(in_payload.valid, FATTR_SIZE | FATTR_FH);\n+ EXPECT_EQ(in_payload.fh, fh);\n+ EXPECT_EQ(in_payload.size, 321);\n+}\n+\n+TEST_F(SetStatTest, FchmodFile) {\n+ // Set up fixture.\n+ SetServerInodeLookup(test_file_, test_file_mode_);\n+ auto fd = ASSERT_NO_ERRNO_AND_VALUE(OpenPath(test_file_path_, O_RDWR, fh));\n+ auto close_fd = CloseFD(fd);\n+\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_attr_out),\n+ .error = 0,\n+ };\n+ mode_t set_mode = S_IROTH | S_IWOTH | S_IXOTH;\n+ struct fuse_attr_out out_payload = {\n+ .attr = DefaultFuseAttr(set_mode, 2),\n+ };\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload);\n+ SetServerResponse(FUSE_SETATTR, iov_out);\n+\n+ // Make syscall.\n+ EXPECT_THAT(fchmod(fd.get(), set_mode), SyscallSucceeds());\n+\n+ // Check FUSE request.\n+ struct fuse_in_header in_header;\n+ struct fuse_setattr_in in_payload;\n+ auto iov_in = FuseGenerateIovecs(in_header, in_payload);\n+\n+ GetServerActualRequest(iov_in);\n+ EXPECT_EQ(in_header.len, sizeof(in_header) + sizeof(in_payload));\n+ EXPECT_EQ(in_header.opcode, FUSE_SETATTR);\n+ EXPECT_EQ(in_header.uid, 0);\n+ EXPECT_EQ(in_header.gid, 0);\n+ EXPECT_EQ(in_payload.valid, FATTR_MODE | FATTR_FH);\n+ EXPECT_EQ(in_payload.fh, fh);\n+ EXPECT_EQ(in_payload.mode, S_IFREG | set_mode);\n+}\n+\n+TEST_F(SetStatTest, FchownFile) {\n+ // Set up fixture.\n+ SetServerInodeLookup(test_file_, test_file_mode_);\n+ auto fd = ASSERT_NO_ERRNO_AND_VALUE(OpenPath(test_file_path_, O_RDWR, fh));\n+ auto close_fd = CloseFD(fd);\n+\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header) + sizeof(struct fuse_attr_out),\n+ .error = 0,\n+ };\n+ struct fuse_attr_out out_payload = {\n+ .attr = DefaultFuseAttr(S_IFREG | S_IRUSR | S_IWUSR | S_IXUSR, 2),\n+ };\n+ auto iov_out = FuseGenerateIovecs(out_header, out_payload);\n+ SetServerResponse(FUSE_SETATTR, iov_out);\n+\n+ // Make syscall.\n+ EXPECT_THAT(fchown(fd.get(), 1025, 1025), SyscallSucceeds());\n+\n+ // Check FUSE request.\n+ struct fuse_in_header in_header;\n+ struct fuse_setattr_in in_payload;\n+ auto iov_in = FuseGenerateIovecs(in_header, in_payload);\n+\n+ GetServerActualRequest(iov_in);\n+ EXPECT_EQ(in_header.len, sizeof(in_header) + sizeof(in_payload));\n+ EXPECT_EQ(in_header.opcode, FUSE_SETATTR);\n+ EXPECT_EQ(in_header.uid, 0);\n+ EXPECT_EQ(in_header.gid, 0);\n+ EXPECT_EQ(in_payload.valid, FATTR_UID | FATTR_GID | FATTR_FH);\n+ EXPECT_EQ(in_payload.fh, fh);\n+ EXPECT_EQ(in_payload.uid, 1025);\n+ EXPECT_EQ(in_payload.gid, 1025);\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Implement FUSE_SETATTR This commit implements FUSE_SETATTR command. When a system call modifies the metadata of a regular file or a folder by chown(2), chmod(2), truncate(2), utime(2), or utimes(2), they should be translated to corresponding FUSE_SETATTR command and sent to the FUSE server. Fixes #3332
259,983
09.09.2020 13:10:56
25,200
2fbbe3b76864bc5b42f05d84166008b25e599bdb
Add comments for exported attributes
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/fuse.go", "new_path": "pkg/abi/linux/fuse.go", "diff": "@@ -252,21 +252,51 @@ type FUSEGetAttrIn struct {\n//\n// +marshal\ntype FUSEAttr struct {\n+ // Ino is the inode number of this file.\nIno uint64\n+\n+ // Size is the size of this file.\nSize uint64\n+\n+ // Blocks is the number of the 512B blocks allocated by this file.\nBlocks uint64\n+\n+ // Atime is the time of last access.\nAtime uint64\n+\n+ // Mtime is the time of last modification.\nMtime uint64\n+\n+ // Ctime is the time of last status change.\nCtime uint64\n+\n+ // AtimeNsec is the nano second part of Atime.\nAtimeNsec uint32\n+\n+ // MtimeNsec is the nano second part of Mtime.\nMtimeNsec uint32\n+\n+ // CtimeNsec is the nano second part of Ctime.\nCtimeNsec uint32\n+\n+ // Mode contains the file type and mode.\nMode uint32\n+\n+ // Nlink is the number of the hard links.\nNlink uint32\n+\n+ // UID is user ID of the owner.\nUID uint32\n+\n+ // GID is group ID of the owner.\nGID uint32\n+\n+ // Rdev is the device ID if this is a special file.\nRdev uint32\n+\n+ // BlkSize is the block size for filesystem I/O.\nBlkSize uint32\n+\n_ uint32\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add comments for exported attributes
259,913
03.09.2020 19:16:17
0
826a685a95bec32286688035922a56faf622e87e
Improve FUSE async/noreply call logic This change adds bookkeeping variables for the FUSE request. With them, old insecure confusing code we used to process async requests is replaced by new clear compiling ones. Future code can take advantage of them to have better control of each requests.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/connection.go", "new_path": "pkg/sentry/fsimpl/fuse/connection.go", "diff": "package fuse\nimport (\n- \"errors\"\n\"sync\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n@@ -201,42 +200,40 @@ func newFUSEConnection(_ context.Context, fd *vfs.FileDescription, opts *filesys\n}, nil\n}\n-// Call makes a request to the server and blocks the invoking task until a\n-// server responds with a response. Task should never be nil.\n-// Requests will not be sent before the connection is initialized.\n-// For async tasks, use CallAsync().\n-func (conn *connection) Call(t *kernel.Task, r *Request) (*Response, error) {\n- // Block requests sent before connection is initalized.\n- if !conn.Initialized() {\n- if err := t.Block(conn.initializedChan); err != nil {\n- return nil, err\n- }\n- }\n-\n- return conn.call(t, r)\n+// CallAsync makes an async (aka background) request.\n+// It's a simple wrapper around Call().\n+func (conn *connection) CallAsync(t *kernel.Task, r *Request) error {\n+ r.async = true\n+ _, err := conn.Call(t, r)\n+ return err\n}\n-// CallAsync makes an async (aka background) request.\n-// Those requests either do not expect a response (e.g. release) or\n-// the response should be handled by others (e.g. init).\n-// Return immediately unless the connection is blocked (before initialization).\n-// Async call example: init, release, forget, aio, interrupt.\n+// Call makes a request to the server.\n+// Block before the connection is initialized.\n// When the Request is FUSE_INIT, it will not be blocked before initialization.\n-func (conn *connection) CallAsync(t *kernel.Task, r *Request) error {\n+// Task should never be nil.\n+//\n+// For a sync request, it blocks the invoking task until\n+// a server responds with a response.\n+//\n+// For an async request (that do not expect a response immediately),\n+// it returns directly unless being blocked either before initialization\n+// or when there are too many async requests ongoing.\n+//\n+// Example for async request:\n+// init, readahead, write, async read/write, fuse_notify_reply,\n+// non-sync release, interrupt, forget.\n+//\n+// The forget request does not have a reply,\n+// as documented in include/uapi/linux/fuse.h:FUSE_FORGET.\n+func (conn *connection) Call(t *kernel.Task, r *Request) (*Response, error) {\n// Block requests sent before connection is initalized.\nif !conn.Initialized() && r.hdr.Opcode != linux.FUSE_INIT {\nif err := t.Block(conn.initializedChan); err != nil {\n- return err\n- }\n+ return nil, err\n}\n-\n- // This should be the only place that invokes call() with a nil task.\n- _, err := conn.call(nil, r)\n- return err\n}\n-// call makes a call without blocking checks.\n-func (conn *connection) call(t *kernel.Task, r *Request) (*Response, error) {\nif !conn.connected {\nreturn nil, syserror.ENOTCONN\n}\n@@ -271,11 +268,6 @@ func (conn *connection) callFuture(t *kernel.Task, r *Request) (*futureResponse,\n// if there are always too many ongoing requests all the time. The\n// supported maxActiveRequests setting should be really high to avoid this.\nfor conn.fd.numActiveRequests == conn.fd.fs.opts.maxActiveRequests {\n- if t == nil {\n- // Since there is no task that is waiting. We must error out.\n- return nil, errors.New(\"FUSE request queue full\")\n- }\n-\nlog.Infof(\"Blocking request %v from being queued. Too many active requests: %v\",\nr.id, conn.fd.numActiveRequests)\nconn.fd.mu.Unlock()\n@@ -292,8 +284,8 @@ func (conn *connection) callFuture(t *kernel.Task, r *Request) (*futureResponse,\n// callFutureLocked makes a request to the server and returns a future response.\nfunc (conn *connection) callFutureLocked(t *kernel.Task, r *Request) (*futureResponse, error) {\nconn.fd.queue.PushBack(r)\n- conn.fd.numActiveRequests += 1\n- fut := newFutureResponse(r.hdr.Opcode)\n+ conn.fd.numActiveRequests++\n+ fut := newFutureResponse(r)\nconn.fd.completions[r.id] = fut\n// Signal the readers that there is something to read.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/dev.go", "new_path": "pkg/sentry/fsimpl/fuse/dev.go", "diff": "@@ -367,22 +367,20 @@ func (fd *DeviceFD) Seek(ctx context.Context, offset int64, whence int32) (int64\n// sendResponse sends a response to the waiting task (if any).\nfunc (fd *DeviceFD) sendResponse(ctx context.Context, fut *futureResponse) error {\n- // See if the running task need to perform some action before returning.\n- // Since we just finished writing the future, we can be sure that\n- // getResponse generates a populated response.\n- if err := fd.noReceiverAction(ctx, fut.getResponse()); err != nil {\n- return err\n- }\n+ // Signal the task waiting on a response if any.\n+ defer close(fut.ch)\n// Signal that the queue is no longer full.\nselect {\ncase fd.fullQueueCh <- struct{}{}:\ndefault:\n}\n- fd.numActiveRequests -= 1\n+ fd.numActiveRequests--\n+\n+ if fut.async {\n+ return fd.asyncCallBack(ctx, fut.getResponse())\n+ }\n- // Signal the task waiting on a response.\n- close(fut.ch)\nreturn nil\n}\n@@ -404,23 +402,18 @@ func (fd *DeviceFD) sendError(ctx context.Context, errno int32, req *Request) er\ndelete(fd.completions, respHdr.Unique)\nfut.hdr = &respHdr\n- if err := fd.sendResponse(ctx, fut); err != nil {\n- return err\n- }\n-\n- return nil\n+ return fd.sendResponse(ctx, fut)\n}\n-// noReceiverAction has the calling kernel.Task do some action if its known that no\n-// receiver is going to be waiting on the future channel. This is to be used by:\n-// FUSE_INIT.\n-func (fd *DeviceFD) noReceiverAction(ctx context.Context, r *Response) error {\n+// asyncCallBack executes pre-defined callback function for async requests.\n+// Currently used by: FUSE_INIT.\n+func (fd *DeviceFD) asyncCallBack(ctx context.Context, r *Response) error {\nswitch r.opcode {\ncase linux.FUSE_INIT:\ncreds := auth.CredentialsFromContext(ctx)\nrootUserNs := kernel.KernelFromContext(ctx).RootUserNamespace()\nreturn fd.fs.conn.InitRecv(r, creds.HasCapabilityIn(linux.CAP_SYS_ADMIN, rootUserNs))\n- // TODO(gvisor.dev/issue/3247): support async read: correctly process the response using information from r.options.\n+ // TODO(gvisor.dev/issue/3247): support async read: correctly process the response.\n}\nreturn nil\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/request_response.go", "new_path": "pkg/sentry/fsimpl/fuse/request_response.go", "diff": "@@ -19,7 +19,6 @@ import (\n\"syscall\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n- \"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n@@ -96,6 +95,12 @@ type Request struct {\n// payload for this request: extra bytes to write after\n// the data slice. Used by FUSE_WRITE.\npayload []byte\n+\n+ // If this request is async.\n+ async bool\n+ // If we don't care its response.\n+ // Manually set by the caller.\n+ noReply bool\n}\n// NewRequest creates a new request that can be sent to the FUSE server.\n@@ -138,24 +143,25 @@ type futureResponse struct {\nch chan struct{}\nhdr *linux.FUSEHeaderOut\ndata []byte\n+\n+ // If this request is async.\n+ async bool\n}\n// newFutureResponse creates a future response to a FUSE request.\n-func newFutureResponse(opcode linux.FUSEOpcode) *futureResponse {\n+func newFutureResponse(req *Request) *futureResponse {\nreturn &futureResponse{\n- opcode: opcode,\n+ opcode: req.hdr.Opcode,\nch: make(chan struct{}),\n+ async: req.async,\n}\n}\n// resolve blocks the task until the server responds to its corresponding request,\n// then returns a resolved response.\nfunc (f *futureResponse) resolve(t *kernel.Task) (*Response, error) {\n- // If there is no Task associated with this request - then we don't try to resolve\n- // the response. Instead, the task writing the response (proxy to the server) will\n- // process the response on our behalf.\n- if t == nil {\n- log.Infof(\"fuse.Response.resolve: Not waiting on a response from server.\")\n+ // Return directly for async requests.\n+ if f.async {\nreturn nil, nil\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Improve FUSE async/noreply call logic This change adds bookkeeping variables for the FUSE request. With them, old insecure confusing code we used to process async requests is replaced by new clear compiling ones. Future code can take advantage of them to have better control of each requests.
259,913
03.09.2020 19:22:24
0
4edc56d3e99b161f2f3311bc22a51012bf0a90ee
Fix FUSE_RELEASE protocol reply processing This commit fixes the potential unexpected errors of original handling of FUSE_RELEASE responses while keep the same behavior (ignoring any reply).
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/dev.go", "new_path": "pkg/sentry/fsimpl/fuse/dev.go", "diff": "@@ -204,8 +204,11 @@ func (fd *DeviceFD) readLocked(ctx context.Context, dst usermem.IOSequence, opts\n// Fully done with this req, remove it from the queue.\nfd.queue.Remove(req)\n- if req.hdr.Opcode == linux.FUSE_RELEASE {\n+\n+ // Remove noReply ones from map of requests expecting a reply.\n+ if req.noReply {\nfd.numActiveRequests -= 1\n+ delete(fd.completions, req.hdr.Unique)\n}\nreturn int64(n), nil\n@@ -296,6 +299,10 @@ func (fd *DeviceFD) writeLocked(ctx context.Context, src usermem.IOSequence, opt\nfut, ok := fd.completions[hdr.Unique]\nif !ok {\n+ if fut.hdr.Unique == linux.FUSE_RELEASE {\n+ // Currently we simply discard the reply for FUSE_RELEASE.\n+ return n + src.NumBytes(), nil\n+ }\n// Server sent us a response for a request we never sent?\nreturn 0, syserror.EINVAL\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/file.go", "new_path": "pkg/sentry/fsimpl/fuse/file.go", "diff": "@@ -84,7 +84,12 @@ func (fd *fileDescription) Release(ctx context.Context) {\n}\nkernelTask := kernel.TaskFromContext(ctx)\n// ignoring errors and FUSE server reply is analogous to Linux's behavior.\n- req, _ := conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), fd.inode().NodeID, opcode, &in)\n+ req, err := conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), fd.inode().NodeID, opcode, &in)\n+ if err != nil {\n+ // No way to invoke Call() with an errored request.\n+ return\n+ }\n+ req.noReply = true\nconn.CallAsync(kernelTask, req)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix FUSE_RELEASE protocol reply processing This commit fixes the potential unexpected errors of original handling of FUSE_RELEASE responses while keep the same behavior (ignoring any reply).
259,913
09.09.2020 16:22:33
25,200
d459bb3372384a4d16fe0d9791847285449dc184
Add FUSE umount support This change implements Release for the FUSE filesystem and expected behaviors of the FUSE devices. It includes several checks for aborted connection in the path for making a request and a function to abort all the ongoing FUSE requests in order.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/BUILD", "new_path": "pkg/sentry/fsimpl/fuse/BUILD", "diff": "@@ -66,7 +66,11 @@ go_library(\ngo_test(\nname = \"fuse_test\",\nsize = \"small\",\n- srcs = [\"dev_test.go\"],\n+ srcs = [\n+ \"connection_test.go\",\n+ \"dev_test.go\",\n+ \"utils_test.go\",\n+ ],\nlibrary = \":fuse\",\ndeps = [\n\"//pkg/abi/linux\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/connection.go", "new_path": "pkg/sentry/fsimpl/fuse/connection.go", "diff": "@@ -180,7 +180,6 @@ func newFUSEConnection(_ context.Context, fd *vfs.FileDescription, opts *filesys\n// Mark the device as ready so it can be used. /dev/fuse can only be used if the FD was used to\n// mount a FUSE filesystem.\nfuseFD := fd.Impl().(*DeviceFD)\n- fuseFD.mounted = true\n// Create the writeBuf for the header to be stored in.\nhdrLen := uint32((*linux.FUSEHeaderOut)(nil).SizeBytes())\n@@ -283,6 +282,16 @@ func (conn *connection) callFuture(t *kernel.Task, r *Request) (*futureResponse,\n// callFutureLocked makes a request to the server and returns a future response.\nfunc (conn *connection) callFutureLocked(t *kernel.Task, r *Request) (*futureResponse, error) {\n+ // Check connected again holding conn.mu.\n+ conn.mu.Lock()\n+ if !conn.connected {\n+ conn.mu.Unlock()\n+ // we checked connected before,\n+ // this must be due to aborted connection.\n+ return nil, syserror.ECONNABORTED\n+ }\n+ conn.mu.Unlock()\n+\nconn.fd.queue.PushBack(r)\nconn.fd.numActiveRequests++\nfut := newFutureResponse(r)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/connection_control.go", "new_path": "pkg/sentry/fsimpl/fuse/connection_control.go", "diff": "@@ -16,8 +16,10 @@ package fuse\nimport (\n\"sync/atomic\"\n+ \"syscall\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n)\n@@ -181,3 +183,63 @@ func (conn *connection) initProcessReply(out *linux.FUSEInitOut, hasSysAdminCap\nreturn nil\n}\n+\n+// Abort this FUSE connection.\n+// It tries to acquire conn.fd.mu, conn.lock, conn.bgLock in order.\n+// All possible requests waiting or blocking will be aborted.\n+func (conn *connection) Abort(ctx context.Context) {\n+ conn.fd.mu.Lock()\n+ conn.mu.Lock()\n+ conn.asyncMu.Lock()\n+\n+ if !conn.connected {\n+ conn.asyncMu.Unlock()\n+ conn.mu.Unlock()\n+ conn.fd.mu.Unlock()\n+ return\n+ }\n+\n+ conn.connected = false\n+\n+ // Empty the `fd.queue` that holds the requests\n+ // not yet read by the FUSE daemon yet.\n+ // These are a subset of the requests in `fuse.completion` map.\n+ for !conn.fd.queue.Empty() {\n+ req := conn.fd.queue.Front()\n+ conn.fd.queue.Remove(req)\n+ }\n+\n+ var terminate []linux.FUSEOpID\n+\n+ // 2. Collect the requests have not been sent to FUSE daemon,\n+ // or have not received a reply.\n+ for unique := range conn.fd.completions {\n+ terminate = append(terminate, unique)\n+ }\n+\n+ // Release all locks to avoid deadlock.\n+ conn.asyncMu.Unlock()\n+ conn.mu.Unlock()\n+ conn.fd.mu.Unlock()\n+\n+ // 1. The requets blocked before initialization.\n+ // Will reach call() `connected` check and return.\n+ if !conn.Initialized() {\n+ conn.SetInitialized()\n+ }\n+\n+ // 2. Terminate the requests collected above.\n+ // Set ECONNABORTED error.\n+ // sendError() will remove them from `fd.completion` map.\n+ // Will enter the path of a normally received error.\n+ for _, toTerminate := range terminate {\n+ conn.fd.sendError(ctx, -int32(syscall.ECONNABORTED), toTerminate)\n+ }\n+\n+ // 3. The requests not yet written to FUSE device.\n+ // Early terminate.\n+ // Will reach callFutureLocked() `connected` check and return.\n+ close(conn.fd.fullQueueCh)\n+\n+ // TODO(gvisor.dev/issue/3528): Forget all pending forget reqs.\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fsimpl/fuse/connection_test.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package fuse\n+\n+import (\n+ \"math/rand\"\n+ \"syscall\"\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+)\n+\n+// TestConnectionInitBlock tests if initialization\n+// correctly blocks and unblocks the connection.\n+// Since it's unfeasible to test kernelTask.Block() in unit test,\n+// the code in Call() are not tested here.\n+func TestConnectionInitBlock(t *testing.T) {\n+ s := setup(t)\n+ defer s.Destroy()\n+\n+ k := kernel.KernelFromContext(s.Ctx)\n+\n+ conn, _, err := newTestConnection(s, k, maxActiveRequestsDefault)\n+ if err != nil {\n+ t.Fatalf(\"newTestConnection: %v\", err)\n+ }\n+\n+ select {\n+ case <-conn.initializedChan:\n+ t.Fatalf(\"initializedChan should be blocking before SetInitialized\")\n+ default:\n+ }\n+\n+ conn.SetInitialized()\n+\n+ select {\n+ case <-conn.initializedChan:\n+ default:\n+ t.Fatalf(\"initializedChan should not be blocking after SetInitialized\")\n+ }\n+}\n+\n+func TestConnectionAbort(t *testing.T) {\n+ s := setup(t)\n+ defer s.Destroy()\n+\n+ k := kernel.KernelFromContext(s.Ctx)\n+ creds := auth.CredentialsFromContext(s.Ctx)\n+ task := kernel.TaskFromContext(s.Ctx)\n+\n+ const maxActiveRequest uint64 = 10\n+\n+ conn, _, err := newTestConnection(s, k, maxActiveRequest)\n+ if err != nil {\n+ t.Fatalf(\"newTestConnection: %v\", err)\n+ }\n+\n+ testObj := &testPayload{\n+ data: rand.Uint32(),\n+ }\n+\n+ var futNormal []*futureResponse\n+\n+ for i := 0; i < 2*int(maxActiveRequest); i++ {\n+ req, err := conn.NewRequest(creds, uint32(i), uint64(i), 0, testObj)\n+ if err != nil {\n+ t.Fatalf(\"NewRequest creation failed: %v\", err)\n+ }\n+ if i < int(maxActiveRequest) {\n+ // Issue the requests that will not be blocked due to maxActiveRequest.\n+ fut, err := conn.callFutureLocked(task, req)\n+ if err != nil {\n+ t.Fatalf(\"callFutureLocked failed: %v\", err)\n+ }\n+ futNormal = append(futNormal, fut)\n+ } else {\n+ go func(t *testing.T) {\n+ // The requests beyond maxActiveRequest will be blocked and receive expected errors.\n+ _, err := conn.callFutureLocked(task, req)\n+ if err != syserror.ECONNABORTED && err != syserror.ENOTCONN {\n+ t.Fatalf(\"Incorrect error code received for blocked callFutureLocked() on aborted connection\")\n+ }\n+ }(t)\n+ }\n+ }\n+\n+ conn.Abort(s.Ctx)\n+\n+ // Abort should unblock the initialization channel.\n+ select {\n+ case <-conn.initializedChan:\n+ default:\n+ t.Fatalf(\"initializedChan should not be blocking after SetInitialized\")\n+ }\n+\n+ // Abort will return ECONNABORTED error to unblocked requests.\n+ for _, fut := range futNormal {\n+ if fut.getResponse().hdr.Error != -int32(syscall.ECONNABORTED) {\n+ t.Fatalf(\"Incorrect error code received for aborted connection\")\n+ }\n+ }\n+\n+ // After abort, Call() should return directly with ENOTCONN.\n+ req, err := conn.NewRequest(creds, 0, 0, 0, testObj)\n+ if err != nil {\n+ t.Fatalf(\"NewRequest creation failed: %v\", err)\n+ }\n+ _, err = conn.Call(task, req)\n+ if err != syserror.ENOTCONN {\n+ t.Fatalf(\"Incorrect error code received for Call() after connection aborted\")\n+ }\n+\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/dev.go", "new_path": "pkg/sentry/fsimpl/fuse/dev.go", "diff": "@@ -55,9 +55,6 @@ type DeviceFD struct {\nvfs.DentryMetadataFileDescriptionImpl\nvfs.NoLockFD\n- // mounted specifies whether a FUSE filesystem was mounted using the DeviceFD.\n- mounted bool\n-\n// nextOpID is used to create new requests.\nnextOpID linux.FUSEOpID\n@@ -99,13 +96,15 @@ type DeviceFD struct {\n// Release implements vfs.FileDescriptionImpl.Release.\nfunc (fd *DeviceFD) Release(context.Context) {\n+ if fd.fs != nil {\nfd.fs.conn.connected = false\n}\n+}\n// PRead implements vfs.FileDescriptionImpl.PRead.\nfunc (fd *DeviceFD) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts vfs.ReadOptions) (int64, error) {\n// Operations on /dev/fuse don't make sense until a FUSE filesystem is mounted.\n- if !fd.mounted {\n+ if fd.fs == nil {\nreturn 0, syserror.EPERM\n}\n@@ -115,10 +114,16 @@ func (fd *DeviceFD) PRead(ctx context.Context, dst usermem.IOSequence, offset in\n// Read implements vfs.FileDescriptionImpl.Read.\nfunc (fd *DeviceFD) Read(ctx context.Context, dst usermem.IOSequence, opts vfs.ReadOptions) (int64, error) {\n// Operations on /dev/fuse don't make sense until a FUSE filesystem is mounted.\n- if !fd.mounted {\n+ if fd.fs == nil {\nreturn 0, syserror.EPERM\n}\n+ // Return ENODEV if the filesystem is umounted.\n+ if fd.fs.umounted {\n+ // TODO(gvisor.dev/issue/3525): return ECONNABORTED if aborted via fuse control fs.\n+ return 0, syserror.ENODEV\n+ }\n+\n// We require that any Read done on this filesystem have a sane minimum\n// read buffer. It must have the capacity for the fixed parts of any request\n// header (Linux uses the request header and the FUSEWriteIn header for this\n@@ -165,7 +170,7 @@ func (fd *DeviceFD) readLocked(ctx context.Context, dst usermem.IOSequence, opts\n}\n// Return the error to the calling task.\n- if err := fd.sendError(ctx, errno, req); err != nil {\n+ if err := fd.sendError(ctx, errno, req.hdr.Unique); err != nil {\nreturn 0, err\n}\n@@ -217,7 +222,7 @@ func (fd *DeviceFD) readLocked(ctx context.Context, dst usermem.IOSequence, opts\n// PWrite implements vfs.FileDescriptionImpl.PWrite.\nfunc (fd *DeviceFD) PWrite(ctx context.Context, src usermem.IOSequence, offset int64, opts vfs.WriteOptions) (int64, error) {\n// Operations on /dev/fuse don't make sense until a FUSE filesystem is mounted.\n- if !fd.mounted {\n+ if fd.fs == nil {\nreturn 0, syserror.EPERM\n}\n@@ -234,10 +239,15 @@ func (fd *DeviceFD) Write(ctx context.Context, src usermem.IOSequence, opts vfs.\n// writeLocked implements writing to the fuse device while locked with DeviceFD.mu.\nfunc (fd *DeviceFD) writeLocked(ctx context.Context, src usermem.IOSequence, opts vfs.WriteOptions) (int64, error) {\n// Operations on /dev/fuse don't make sense until a FUSE filesystem is mounted.\n- if !fd.mounted {\n+ if fd.fs == nil {\nreturn 0, syserror.EPERM\n}\n+ // Return ENODEV if the filesystem is umounted.\n+ if fd.fs.umounted {\n+ return 0, syserror.ENODEV\n+ }\n+\nvar cn, n int64\nhdrLen := uint32((*linux.FUSEHeaderOut)(nil).SizeBytes())\n@@ -303,7 +313,8 @@ func (fd *DeviceFD) writeLocked(ctx context.Context, src usermem.IOSequence, opt\n// Currently we simply discard the reply for FUSE_RELEASE.\nreturn n + src.NumBytes(), nil\n}\n- // Server sent us a response for a request we never sent?\n+ // Server sent us a response for a request we never sent,\n+ // or for which we already received a reply (e.g. aborted), an unlikely event.\nreturn 0, syserror.EINVAL\n}\n@@ -343,7 +354,14 @@ func (fd *DeviceFD) Readiness(mask waiter.EventMask) waiter.EventMask {\n// locked with DeviceFD.mu.\nfunc (fd *DeviceFD) readinessLocked(mask waiter.EventMask) waiter.EventMask {\nvar ready waiter.EventMask\n- ready |= waiter.EventOut // FD is always writable\n+\n+ if fd.fs.umounted {\n+ ready |= waiter.EventErr\n+ return ready & mask\n+ }\n+\n+ // FD is always writable.\n+ ready |= waiter.EventOut\nif !fd.queue.Empty() {\n// Have reqs available, FD is readable.\nready |= waiter.EventIn\n@@ -365,7 +383,7 @@ func (fd *DeviceFD) EventUnregister(e *waiter.Entry) {\n// Seek implements vfs.FileDescriptionImpl.Seek.\nfunc (fd *DeviceFD) Seek(ctx context.Context, offset int64, whence int32) (int64, error) {\n// Operations on /dev/fuse don't make sense until a FUSE filesystem is mounted.\n- if !fd.mounted {\n+ if fd.fs == nil {\nreturn 0, syserror.EPERM\n}\n@@ -391,19 +409,20 @@ func (fd *DeviceFD) sendResponse(ctx context.Context, fut *futureResponse) error\nreturn nil\n}\n-// sendError sends an error response to the waiting task (if any).\n-func (fd *DeviceFD) sendError(ctx context.Context, errno int32, req *Request) error {\n+// sendError sends an error response to the waiting task (if any) by calling sendResponse().\n+func (fd *DeviceFD) sendError(ctx context.Context, errno int32, unique linux.FUSEOpID) error {\n// Return the error to the calling task.\noutHdrLen := uint32((*linux.FUSEHeaderOut)(nil).SizeBytes())\nrespHdr := linux.FUSEHeaderOut{\nLen: outHdrLen,\nError: errno,\n- Unique: req.hdr.Unique,\n+ Unique: unique,\n}\nfut, ok := fd.completions[respHdr.Unique]\nif !ok {\n- // Server sent us a response for a request we never sent?\n+ // A response for a request we never sent,\n+ // or for which we already received a reply (e.g. aborted).\nreturn syserror.EINVAL\n}\ndelete(fd.completions, respHdr.Unique)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/dev_test.go", "new_path": "pkg/sentry/fsimpl/fuse/dev_test.go", "diff": "@@ -35,10 +35,6 @@ import (\n// will simply echo the payload back with the appropriate headers.\nconst echoTestOpcode linux.FUSEOpcode = 1000\n-type testPayload struct {\n- data uint32\n-}\n-\n// TestFUSECommunication tests that the communication layer between the Sentry and the\n// FUSE server daemon works as expected.\nfunc TestFUSECommunication(t *testing.T) {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "new_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "diff": "@@ -29,6 +29,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n+ \"gvisor.dev/gvisor/pkg/waiter\"\n\"gvisor.dev/gvisor/tools/go_marshal/marshal\"\n)\n@@ -82,6 +83,9 @@ type filesystem struct {\n// opts is the options the fusefs is initialized with.\nopts *filesystemOptions\n+\n+ // umounted is true if filesystem.Release() has been called.\n+ umounted bool\n}\n// Name implements vfs.FilesystemType.Name.\n@@ -221,6 +225,14 @@ func newFUSEFilesystem(ctx context.Context, devMinor uint32, opts *filesystemOpt\n// Release implements vfs.FilesystemImpl.Release.\nfunc (fs *filesystem) Release(ctx context.Context) {\n+ fs.umounted = true\n+ fs.conn.Abort(ctx)\n+\n+ fs.conn.fd.mu.Lock()\n+ // Notify all the waiters on this fd.\n+ fs.conn.fd.waitQueue.Notify(waiter.EventIn)\n+ fs.conn.fd.mu.Unlock()\n+\nfs.Filesystem.VFSFilesystem().VirtualFilesystem().PutAnonBlockDevMinor(fs.devMinor)\nfs.Filesystem.Release(ctx)\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fsimpl/fuse/utils_test.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package fuse\n+\n+import (\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/testutil\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n+ \"gvisor.dev/gvisor/tools/go_marshal/marshal\"\n+)\n+\n+func setup(t *testing.T) *testutil.System {\n+ k, err := testutil.Boot()\n+ if err != nil {\n+ t.Fatalf(\"Error creating kernel: %v\", err)\n+ }\n+\n+ ctx := k.SupervisorContext()\n+ creds := auth.CredentialsFromContext(ctx)\n+\n+ k.VFS().MustRegisterFilesystemType(Name, &FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ AllowUserList: true,\n+ AllowUserMount: true,\n+ })\n+\n+ mntns, err := k.VFS().NewMountNamespace(ctx, creds, \"\", \"tmpfs\", &vfs.GetFilesystemOptions{})\n+ if err != nil {\n+ t.Fatalf(\"NewMountNamespace(): %v\", err)\n+ }\n+\n+ return testutil.NewSystem(ctx, t, k.VFS(), mntns)\n+}\n+\n+// newTestConnection creates a fuse connection that the sentry can communicate with\n+// and the FD for the server to communicate with.\n+func newTestConnection(system *testutil.System, k *kernel.Kernel, maxActiveRequests uint64) (*connection, *vfs.FileDescription, error) {\n+ vfsObj := &vfs.VirtualFilesystem{}\n+ fuseDev := &DeviceFD{}\n+\n+ if err := vfsObj.Init(system.Ctx); err != nil {\n+ return nil, nil, err\n+ }\n+\n+ vd := vfsObj.NewAnonVirtualDentry(\"genCountFD\")\n+ defer vd.DecRef(system.Ctx)\n+ if err := fuseDev.vfsfd.Init(fuseDev, linux.O_RDWR|linux.O_CREAT, vd.Mount(), vd.Dentry(), &vfs.FileDescriptionOptions{}); err != nil {\n+ return nil, nil, err\n+ }\n+\n+ fsopts := filesystemOptions{\n+ maxActiveRequests: maxActiveRequests,\n+ }\n+ fs, err := newFUSEFilesystem(system.Ctx, 0, &fsopts, &fuseDev.vfsfd)\n+ if err != nil {\n+ return nil, nil, err\n+ }\n+\n+ return fs.conn, &fuseDev.vfsfd, nil\n+}\n+\n+type testPayload struct {\n+ marshal.StubMarshallable\n+ data uint32\n+}\n+\n+// SizeBytes implements marshal.Marshallable.SizeBytes.\n+func (t *testPayload) SizeBytes() int {\n+ return 4\n+}\n+\n+// MarshalBytes implements marshal.Marshallable.MarshalBytes.\n+func (t *testPayload) MarshalBytes(dst []byte) {\n+ usermem.ByteOrder.PutUint32(dst[:4], t.data)\n+}\n+\n+// UnmarshalBytes implements marshal.Marshallable.UnmarshalBytes.\n+func (t *testPayload) UnmarshalBytes(src []byte) {\n+ *t = testPayload{data: usermem.ByteOrder.Uint32(src[:4])}\n+}\n+\n+// Packed implements marshal.Marshallable.Packed.\n+func (t *testPayload) Packed() bool {\n+ return true\n+}\n+\n+// MarshalUnsafe implements marshal.Marshallable.MarshalUnsafe.\n+func (t *testPayload) MarshalUnsafe(dst []byte) {\n+ t.MarshalBytes(dst)\n+}\n+\n+// UnmarshalUnsafe implements marshal.Marshallable.UnmarshalUnsafe.\n+func (t *testPayload) UnmarshalUnsafe(src []byte) {\n+ t.UnmarshalBytes(src)\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/syserror/syserror.go", "new_path": "pkg/syserror/syserror.go", "diff": "@@ -33,6 +33,7 @@ var (\nEBADFD = error(syscall.EBADFD)\nEBUSY = error(syscall.EBUSY)\nECHILD = error(syscall.ECHILD)\n+ ECONNABORTED = error(syscall.ECONNABORTED)\nECONNREFUSED = error(syscall.ECONNREFUSED)\nECONNRESET = error(syscall.ECONNRESET)\nEDEADLK = error(syscall.EDEADLK)\n" } ]
Go
Apache License 2.0
google/gvisor
Add FUSE umount support This change implements Release for the FUSE filesystem and expected behaviors of the FUSE devices. It includes several checks for aborted connection in the path for making a request and a function to abort all the ongoing FUSE requests in order.
259,983
09.09.2020 16:44:35
25,200
70cfea23776189575807f6aae28769bdfaa1e3fb
Fix comments of TODO issues.
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/fuse.go", "new_path": "pkg/abi/linux/fuse.go", "diff": "@@ -663,7 +663,7 @@ func (r *FUSEMkdirIn) SizeBytes() int {\ntype FUSERmDirIn struct {\nmarshal.StubMarshallable\n- // Name is a directory name to be looked up.\n+ // Name is a directory name to be removed.\nName string\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/request_response.go", "new_path": "pkg/sentry/fsimpl/fuse/request_response.go", "diff": "@@ -122,7 +122,7 @@ func (conn *connection) NewRequest(creds *auth.Credentials, pid uint32, ino uint\nbuf := make([]byte, hdr.Len)\n- // TODO(gVisor.dev/3698): Use the unsafe version once go_marshal is safe to use again.\n+ // TODO(gVisor.dev/issue/3698): Use the unsafe version once go_marshal is safe to use again.\nhdr.MarshalBytes(buf[:hdrLen])\npayload.MarshalBytes(buf[hdrLen:])\n@@ -223,7 +223,7 @@ func (r *Response) UnmarshalPayload(m marshal.Marshallable) error {\nreturn nil\n}\n- // TODO(gVisor.dev/3698): Use the unsafe version once go_marshal is safe to use again.\n+ // TODO(gVisor.dev/issue/3698): Use the unsafe version once go_marshal is safe to use again.\nm.UnmarshalBytes(r.data[hdrLen:])\nreturn nil\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix comments of TODO issues.
259,984
09.09.2020 17:13:18
25,200
2051260e8286b25ab39f3c1cb4614005236cbcc6
Implement FUSE_UNLINK Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/fuse.go", "new_path": "pkg/abi/linux/fuse.go", "diff": "@@ -846,3 +846,26 @@ type FUSESetAttrIn struct {\n_ uint32\n}\n+\n+// FUSEUnlinkIn is the request sent by the kernel to the daemon\n+// when trying to unlink a node.\n+//\n+// Dynamically-sized objects cannot be marshalled.\n+type FUSEUnlinkIn struct {\n+ marshal.StubMarshallable\n+\n+ // Name of the node to unlink.\n+ Name string\n+}\n+\n+// MarshalBytes serializes r.name to the dst buffer, which should\n+// have size len(r.Name) + 1 and last byte set to 0.\n+func (r *FUSEUnlinkIn) MarshalBytes(buf []byte) {\n+ copy(buf, r.Name)\n+}\n+\n+// SizeBytes is the size of the memory representation of FUSEUnlinkIn.\n+// 1 extra byte for null-terminated Name string.\n+func (r *FUSEUnlinkIn) SizeBytes() int {\n+ return len(r.Name) + 1\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "new_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "diff": "@@ -455,6 +455,29 @@ func (i *inode) NewSymlink(ctx context.Context, name, target string) (*vfs.Dentr\nreturn i.newEntry(ctx, name, linux.S_IFLNK, linux.FUSE_SYMLINK, &in)\n}\n+// Unlink implements kernfs.Inode.Unlink.\n+func (i *inode) Unlink(ctx context.Context, name string, child *vfs.Dentry) error {\n+ kernelTask := kernel.TaskFromContext(ctx)\n+ if kernelTask == nil {\n+ log.Warningf(\"fusefs.Inode.newEntry: couldn't get kernel task from context\", i.NodeID)\n+ return syserror.EINVAL\n+ }\n+ in := linux.FUSEUnlinkIn{Name: name}\n+ req, err := i.fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), i.NodeID, linux.FUSE_UNLINK, &in)\n+ if err != nil {\n+ return err\n+ }\n+ res, err := i.fs.conn.Call(kernelTask, req)\n+ if err != nil {\n+ return err\n+ }\n+ // only return error, discard res.\n+ if err := res.Error(); err != nil {\n+ return err\n+ }\n+ return i.dentry.RemoveChildLocked(name, child)\n+}\n+\n// NewDir implements kernfs.Inode.NewDir.\nfunc (i *inode) NewDir(ctx context.Context, name string, opts vfs.MkdirOptions) (*vfs.Dentry, error) {\nin := linux.FUSEMkdirIn{\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "diff": "@@ -770,6 +770,10 @@ func (fs *Filesystem) SymlinkAt(ctx context.Context, rp *vfs.ResolvingPath, targ\nfunc (fs *Filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error {\nfs.mu.Lock()\ndefer fs.mu.Unlock()\n+\n+ // Store the name before walkExistingLocked as rp will be advanced past the\n+ // name in the following call.\n+ name := rp.Component()\nvfsd, _, err := fs.walkExistingLocked(ctx, rp)\nfs.processDeferredDecRefsLocked(ctx)\nif err != nil {\n@@ -795,7 +799,7 @@ func (fs *Filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\nif err := virtfs.PrepareDeleteDentry(mntns, vfsd); err != nil {\nreturn err\n}\n- if err := parentDentry.inode.Unlink(ctx, rp.Component(), vfsd); err != nil {\n+ if err := parentDentry.inode.Unlink(ctx, name, vfsd); err != nil {\nvirtfs.AbortDeleteDentry(vfsd)\nreturn err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/kernfs.go", "new_path": "pkg/sentry/fsimpl/kernfs/kernfs.go", "diff": "@@ -60,6 +60,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/sync\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n)\n// Filesystem mostly implements vfs.FilesystemImpl for a generic in-memory\n@@ -267,6 +268,36 @@ func (d *Dentry) InsertChildLocked(name string, child *Dentry) {\nd.children[name] = child\n}\n+// RemoveChild removes child from the vfs dentry cache. This does not update the\n+// directory inode or modify the inode to be unlinked. So calling this on its own\n+// isn't sufficient to remove a child from a directory.\n+//\n+// Precondition: d must represent a directory inode.\n+func (d *Dentry) RemoveChild(name string, child *vfs.Dentry) error {\n+ d.dirMu.Lock()\n+ defer d.dirMu.Unlock()\n+ return d.RemoveChildLocked(name, child)\n+}\n+\n+// RemoveChildLocked is equivalent to RemoveChild, with additional\n+// preconditions.\n+//\n+// Precondition: d.dirMu must be locked.\n+func (d *Dentry) RemoveChildLocked(name string, child *vfs.Dentry) error {\n+ if !d.isDir() {\n+ panic(fmt.Sprintf(\"RemoveChild called on non-directory Dentry: %+v.\", d))\n+ }\n+ c, ok := d.children[name]\n+ if !ok {\n+ return syserror.ENOENT\n+ }\n+ if &c.vfsd != child {\n+ panic(fmt.Sprintf(\"Dentry hashed into inode doesn't match what vfs thinks! Child: %+v, vfs: %+v\", c, child))\n+ }\n+ delete(d.children, name)\n+ return nil\n+}\n+\n// Inode returns the dentry's inode.\nfunc (d *Dentry) Inode() Inode {\nreturn d.inode\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/BUILD", "new_path": "test/fuse/BUILD", "diff": "@@ -62,6 +62,11 @@ syscall_test(\ntest = \"//test/fuse/linux:create_test\",\n)\n+syscall_test(\n+ fuse = \"True\",\n+ test = \"//test/fuse/linux:unlink_test\",\n+)\n+\nsyscall_test(\nfuse = \"True\",\ntest = \"//test/fuse/linux:setstat_test\",\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/BUILD", "new_path": "test/fuse/linux/BUILD", "diff": "@@ -214,3 +214,17 @@ cc_binary(\n\"//test/util:test_util\",\n],\n)\n+\n+cc_binary(\n+ name = \"unlink_test\",\n+ testonly = 1,\n+ srcs = [\"unlink_test.cc\"],\n+ deps = [\n+ gtest,\n+ \":fuse_base\",\n+ \"//test/util:fuse_util\",\n+ \"//test/util:temp_umask\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/fuse/linux/unlink_test.cc", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <errno.h>\n+#include <fcntl.h>\n+#include <linux/fuse.h>\n+#include <sys/mount.h>\n+#include <sys/stat.h>\n+#include <sys/statfs.h>\n+#include <sys/types.h>\n+#include <unistd.h>\n+\n+#include <string>\n+#include <vector>\n+\n+#include \"gtest/gtest.h\"\n+#include \"test/fuse/linux/fuse_base.h\"\n+#include \"test/util/fuse_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+class UnlinkTest : public FuseTest {\n+ protected:\n+ const std::string test_file_ = \"test_file\";\n+};\n+\n+TEST_F(UnlinkTest, RegularFile) {\n+ const std::string test_file_path =\n+ JoinPath(mount_point_.path().c_str(), test_file_);\n+ SetServerInodeLookup(test_file_, S_IFREG | S_IRWXU | S_IRWXG | S_IRWXO);\n+\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header),\n+ };\n+ auto iov_out = FuseGenerateIovecs(out_header);\n+ SetServerResponse(FUSE_UNLINK, iov_out);\n+\n+ ASSERT_THAT(unlink(test_file_path.c_str()), SyscallSucceeds());\n+ struct fuse_in_header in_header;\n+ std::vector<char> unlinked_file(test_file_.length() + 1);\n+ auto iov_in = FuseGenerateIovecs(in_header, unlinked_file);\n+ GetServerActualRequest(iov_in);\n+\n+ EXPECT_EQ(in_header.len, sizeof(in_header) + test_file_.length() + 1);\n+ EXPECT_EQ(in_header.opcode, FUSE_UNLINK);\n+ EXPECT_EQ(std::string(unlinked_file.data()), test_file_);\n+}\n+\n+TEST_F(UnlinkTest, NoFile) {\n+ const std::string test_file_path =\n+ JoinPath(mount_point_.path().c_str(), test_file_);\n+ SetServerInodeLookup(test_file_, S_IFREG | S_IRWXU | S_IRWXG | S_IRWXO);\n+\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header),\n+ .error = -ENOENT,\n+ };\n+ auto iov_out = FuseGenerateIovecs(out_header);\n+ SetServerResponse(FUSE_UNLINK, iov_out);\n+\n+ ASSERT_THAT(unlink(test_file_path.c_str()), SyscallFailsWithErrno(ENOENT));\n+ SkipServerActualRequest();\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Implement FUSE_UNLINK Fixes #3696
259,983
09.09.2020 16:30:25
25,200
dd103527298375edd3e14600ac762c9a3103ac37
Unexport fusefs.inode.nodeID
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/connection.go", "new_path": "pkg/sentry/fsimpl/fuse/connection.go", "diff": "@@ -47,7 +47,7 @@ const (\ntype connection struct {\nfd *DeviceFD\n- // mu protect access to struct memebers.\n+ // mu protects access to struct memebers.\nmu sync.Mutex\n// attributeVersion is the version of connection's attributes.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/directory.go", "new_path": "pkg/sentry/fsimpl/fuse/directory.go", "diff": "@@ -67,8 +67,8 @@ func (dir *directoryFD) IterDirents(ctx context.Context, callback vfs.IterDirent\nFlags: dir.statusFlags(),\n}\n- /// TODO(gVisor.dev/issue/3404): Support FUSE_READDIRPLUS.\n- req, err := fusefs.conn.NewRequest(creds, uint32(task.ThreadID()), dir.inode().NodeID, linux.FUSE_READDIR, &in)\n+ // TODO(gVisor.dev/issue/3404): Support FUSE_READDIRPLUS.\n+ req, err := fusefs.conn.NewRequest(creds, uint32(task.ThreadID()), dir.inode().nodeID, linux.FUSE_READDIR, &in)\nif err != nil {\nreturn err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/file.go", "new_path": "pkg/sentry/fsimpl/fuse/file.go", "diff": "@@ -84,7 +84,7 @@ func (fd *fileDescription) Release(ctx context.Context) {\n}\nkernelTask := kernel.TaskFromContext(ctx)\n// ignoring errors and FUSE server reply is analogous to Linux's behavior.\n- req, err := conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), fd.inode().NodeID, opcode, &in)\n+ req, err := conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), fd.inode().nodeID, opcode, &in)\nif err != nil {\n// No way to invoke Call() with an errored request.\nreturn\n@@ -125,8 +125,9 @@ func (fd *fileDescription) Stat(ctx context.Context, opts vfs.StatOptions) (linu\nreturn inode.Stat(ctx, fs, opts)\n}\n-// SetStat implements FileDescriptionImpl.SetStat.\n+// SetStat implements vfs.FileDescriptionImpl.SetStat.\nfunc (fd *fileDescription) SetStat(ctx context.Context, opts vfs.SetStatOptions) error {\n+ fs := fd.filesystem()\ncreds := auth.CredentialsFromContext(ctx)\n- return fd.inode().setAttr(ctx, fd.inode().fs.VFSFilesystem(), creds, opts, true, fd.Fh)\n+ return fd.inode().setAttr(ctx, fs, creds, opts, true, fd.Fh)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "new_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "diff": "@@ -254,7 +254,7 @@ type inode struct {\n// metaDataMu protects the metadata of this inode.\nmetadataMu sync.Mutex\n- NodeID uint64\n+ nodeID uint64\nlocks vfs.FileLocks\n@@ -279,13 +279,13 @@ func (fs *filesystem) newRootInode(creds *auth.Credentials, mode linux.FileMode)\ni.InodeAttrs.Init(creds, linux.UNNAMED_MAJOR, fs.devMinor, 1, linux.ModeDirectory|0755)\ni.OrderedChildren.Init(kernfs.OrderedChildrenOptions{})\ni.dentry.Init(i)\n- i.NodeID = 1\n+ i.nodeID = 1\nreturn &i.dentry\n}\nfunc (fs *filesystem) newInode(nodeID uint64, attr linux.FUSEAttr) *kernfs.Dentry {\n- i := &inode{fs: fs, NodeID: nodeID}\n+ i := &inode{fs: fs, nodeID: nodeID}\ncreds := auth.Credentials{EffectiveKGID: auth.KGID(attr.UID), EffectiveKUID: auth.KUID(attr.UID)}\ni.InodeAttrs.Init(&creds, linux.UNNAMED_MAJOR, fs.devMinor, fs.NextIno(), linux.FileMode(attr.Mode))\natomic.StoreUint64(&i.size, attr.Size)\n@@ -342,7 +342,7 @@ func (i *inode) Open(ctx context.Context, rp *vfs.ResolvingPath, vfsd *vfs.Dentr\nin.Flags &= ^uint32(linux.O_TRUNC)\n}\n- req, err := i.fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), i.NodeID, opcode, &in)\n+ req, err := i.fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), i.nodeID, opcode, &in)\nif err != nil {\nreturn nil, err\n}\n@@ -405,13 +405,13 @@ func (i *inode) Lookup(ctx context.Context, name string) (*vfs.Dentry, error) {\nreturn i.newEntry(ctx, name, 0, linux.FUSE_LOOKUP, &in)\n}\n-// IterDirents implements Inode.IterDirents.\n-func (inode) IterDirents(ctx context.Context, callback vfs.IterDirentsCallback, offset, relOffset int64) (int64, error) {\n+// IterDirents implements kernfs.Inode.IterDirents.\n+func (*inode) IterDirents(ctx context.Context, callback vfs.IterDirentsCallback, offset, relOffset int64) (int64, error) {\nreturn offset, nil\n}\n-// Valid implements Inode.Valid.\n-func (inode) Valid(ctx context.Context) bool {\n+// Valid implements kernfs.Inode.Valid.\n+func (*inode) Valid(ctx context.Context) bool {\nreturn true\n}\n@@ -419,7 +419,7 @@ func (inode) Valid(ctx context.Context) bool {\nfunc (i *inode) NewFile(ctx context.Context, name string, opts vfs.OpenOptions) (*vfs.Dentry, error) {\nkernelTask := kernel.TaskFromContext(ctx)\nif kernelTask == nil {\n- log.Warningf(\"fusefs.Inode.NewFile: couldn't get kernel task from context\", i.NodeID)\n+ log.Warningf(\"fusefs.Inode.NewFile: couldn't get kernel task from context\", i.nodeID)\nreturn nil, syserror.EINVAL\n}\nin := linux.FUSECreateIn{\n@@ -459,11 +459,11 @@ func (i *inode) NewSymlink(ctx context.Context, name, target string) (*vfs.Dentr\nfunc (i *inode) Unlink(ctx context.Context, name string, child *vfs.Dentry) error {\nkernelTask := kernel.TaskFromContext(ctx)\nif kernelTask == nil {\n- log.Warningf(\"fusefs.Inode.newEntry: couldn't get kernel task from context\", i.NodeID)\n+ log.Warningf(\"fusefs.Inode.newEntry: couldn't get kernel task from context\", i.nodeID)\nreturn syserror.EINVAL\n}\nin := linux.FUSEUnlinkIn{Name: name}\n- req, err := i.fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), i.NodeID, linux.FUSE_UNLINK, &in)\n+ req, err := i.fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), i.nodeID, linux.FUSE_UNLINK, &in)\nif err != nil {\nreturn err\n}\n@@ -496,7 +496,7 @@ func (i *inode) RmDir(ctx context.Context, name string, child *vfs.Dentry) error\ntask, creds := kernel.TaskFromContext(ctx), auth.CredentialsFromContext(ctx)\nin := linux.FUSERmDirIn{Name: name}\n- req, err := fusefs.conn.NewRequest(creds, uint32(task.ThreadID()), i.NodeID, linux.FUSE_RMDIR, &in)\n+ req, err := fusefs.conn.NewRequest(creds, uint32(task.ThreadID()), i.nodeID, linux.FUSE_RMDIR, &in)\nif err != nil {\nreturn err\n}\n@@ -522,10 +522,10 @@ func (i *inode) RmDir(ctx context.Context, name string, child *vfs.Dentry) error\nfunc (i *inode) newEntry(ctx context.Context, name string, fileType linux.FileMode, opcode linux.FUSEOpcode, payload marshal.Marshallable) (*vfs.Dentry, error) {\nkernelTask := kernel.TaskFromContext(ctx)\nif kernelTask == nil {\n- log.Warningf(\"fusefs.Inode.newEntry: couldn't get kernel task from context\", i.NodeID)\n+ log.Warningf(\"fusefs.Inode.newEntry: couldn't get kernel task from context\", i.nodeID)\nreturn nil, syserror.EINVAL\n}\n- req, err := i.fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), i.NodeID, opcode, payload)\n+ req, err := i.fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), i.nodeID, opcode, payload)\nif err != nil {\nreturn nil, err\n}\n@@ -552,7 +552,7 @@ func (i *inode) newEntry(ctx context.Context, name string, fileType linux.FileMo\nreturn child.VFSDentry(), nil\n}\n-// Getlink implements Inode.Getlink.\n+// Getlink implements kernfs.Inode.Getlink.\nfunc (i *inode) Getlink(ctx context.Context, mnt *vfs.Mount) (vfs.VirtualDentry, string, error) {\npath, err := i.Readlink(ctx, mnt)\nreturn vfs.VirtualDentry{}, path, err\n@@ -563,13 +563,13 @@ func (i *inode) Readlink(ctx context.Context, mnt *vfs.Mount) (string, error) {\nif i.Mode().FileType()&linux.S_IFLNK == 0 {\nreturn \"\", syserror.EINVAL\n}\n- if i.link == \"\" {\n+ if len(i.link) == 0 {\nkernelTask := kernel.TaskFromContext(ctx)\nif kernelTask == nil {\nlog.Warningf(\"fusefs.Inode.Readlink: couldn't get kernel task from context\")\nreturn \"\", syserror.EINVAL\n}\n- req, err := i.fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), i.NodeID, linux.FUSE_READLINK, &linux.FUSEEmptyIn{})\n+ req, err := i.fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(kernelTask.ThreadID()), i.nodeID, linux.FUSE_READLINK, &linux.FUSEEmptyIn{})\nif err != nil {\nreturn \"\", err\n}\n@@ -675,7 +675,7 @@ func (i *inode) getAttr(ctx context.Context, fs *vfs.Filesystem, opts vfs.StatOp\nGetAttrFlags: flags,\nFh: fh,\n}\n- req, err := i.fs.conn.NewRequest(creds, uint32(task.ThreadID()), i.NodeID, linux.FUSE_GETATTR, &in)\n+ req, err := i.fs.conn.NewRequest(creds, uint32(task.ThreadID()), i.nodeID, linux.FUSE_GETATTR, &in)\nif err != nil {\nreturn linux.FUSEAttr{}, err\n}\n@@ -798,7 +798,7 @@ func (i *inode) setAttr(ctx context.Context, fs *vfs.Filesystem, creds *auth.Cre\nUID: opts.Stat.UID,\nGID: opts.Stat.GID,\n}\n- req, err := conn.NewRequest(creds, uint32(task.ThreadID()), i.NodeID, linux.FUSE_SETATTR, &in)\n+ req, err := conn.NewRequest(creds, uint32(task.ThreadID()), i.nodeID, linux.FUSE_SETATTR, &in)\nif err != nil {\nreturn err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/read_write.go", "new_path": "pkg/sentry/fsimpl/fuse/read_write.go", "diff": "@@ -79,7 +79,7 @@ func (fs *filesystem) ReadInPages(ctx context.Context, fd *regularFileFD, off ui\nin.Offset = off + (uint64(pagesRead) << usermem.PageShift)\nin.Size = pagesCanRead << usermem.PageShift\n- req, err := fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(t.ThreadID()), fd.inode().NodeID, linux.FUSE_READ, &in)\n+ req, err := fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(t.ThreadID()), fd.inode().nodeID, linux.FUSE_READ, &in)\nif err != nil {\nreturn nil, 0, err\n}\n@@ -203,7 +203,7 @@ func (fs *filesystem) Write(ctx context.Context, fd *regularFileFD, off uint64,\nin.Offset = off + uint64(written)\nin.Size = toWrite\n- req, err := fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(t.ThreadID()), fd.inode().NodeID, linux.FUSE_WRITE, &in)\n+ req, err := fs.conn.NewRequest(auth.CredentialsFromContext(ctx), uint32(t.ThreadID()), fd.inode().nodeID, linux.FUSE_WRITE, &in)\nif err != nil {\nreturn 0, err\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Unexport fusefs.inode.nodeID
260,004
16.09.2020 12:19:06
25,200
87c5c0ad2568215675391f6fb7fe335bcae06173
Receive broadcast packets on interested endpoints When a broadcast packet is received by the stack, the packet should be delivered to each endpoint that may be interested in the packet. This includes all any address and specified broadcast address listeners. Test: integration_test.TestReuseAddrAndBroadcast
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/transport_demuxer.go", "new_path": "pkg/tcpip/stack/transport_demuxer.go", "diff": "@@ -165,7 +165,7 @@ func (epsByNIC *endpointsByNIC) handlePacket(r *Route, id TransportEndpointID, p\n// If this is a broadcast or multicast datagram, deliver the datagram to all\n// endpoints bound to the right device.\n- if isMulticastOrBroadcast(id.LocalAddress) {\n+ if isInboundMulticastOrBroadcast(r) {\nmpep.handlePacketAll(r, id, pkt)\nepsByNIC.mu.RUnlock() // Don't use defer for performance reasons.\nreturn\n@@ -526,7 +526,7 @@ func (d *transportDemuxer) deliverPacket(r *Route, protocol tcpip.TransportProto\n// If the packet is a UDP broadcast or multicast, then find all matching\n// transport endpoints.\n- if protocol == header.UDPProtocolNumber && isMulticastOrBroadcast(id.LocalAddress) {\n+ if protocol == header.UDPProtocolNumber && isInboundMulticastOrBroadcast(r) {\neps.mu.RLock()\ndestEPs := eps.findAllEndpointsLocked(id)\neps.mu.RUnlock()\n@@ -546,7 +546,7 @@ func (d *transportDemuxer) deliverPacket(r *Route, protocol tcpip.TransportProto\n// If the packet is a TCP packet with a non-unicast source or destination\n// address, then do nothing further and instruct the caller to do the same.\n- if protocol == header.TCPProtocolNumber && (!isUnicast(r.LocalAddress) || !isUnicast(r.RemoteAddress)) {\n+ if protocol == header.TCPProtocolNumber && (!isInboundUnicast(r) || !isOutboundUnicast(r)) {\n// TCP can only be used to communicate between a single source and a\n// single destination; the addresses must be unicast.\nr.Stats().TCP.InvalidSegmentsReceived.Increment()\n@@ -677,10 +677,14 @@ func (d *transportDemuxer) unregisterRawEndpoint(netProto tcpip.NetworkProtocolN\neps.mu.Unlock()\n}\n-func isMulticastOrBroadcast(addr tcpip.Address) bool {\n- return addr == header.IPv4Broadcast || header.IsV4MulticastAddress(addr) || header.IsV6MulticastAddress(addr)\n+func isInboundMulticastOrBroadcast(r *Route) bool {\n+ return r.IsInboundBroadcast() || header.IsV4MulticastAddress(r.LocalAddress) || header.IsV6MulticastAddress(r.LocalAddress)\n}\n-func isUnicast(addr tcpip.Address) bool {\n- return addr != header.IPv4Any && addr != header.IPv6Any && !isMulticastOrBroadcast(addr)\n+func isInboundUnicast(r *Route) bool {\n+ return r.LocalAddress != header.IPv4Any && r.LocalAddress != header.IPv6Any && !isInboundMulticastOrBroadcast(r)\n+}\n+\n+func isOutboundUnicast(r *Route) bool {\n+ return r.RemoteAddress != header.IPv4Any && r.RemoteAddress != header.IPv6Any && !r.IsOutboundBroadcast() && !header.IsV4MulticastAddress(r.RemoteAddress) && !header.IsV6MulticastAddress(r.RemoteAddress)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tests/integration/multicast_broadcast_test.go", "new_path": "pkg/tcpip/tests/integration/multicast_broadcast_test.go", "diff": "@@ -23,6 +23,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/channel\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/link/loopback\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv4\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv6\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n@@ -436,3 +437,122 @@ func TestIncomingMulticastAndBroadcast(t *testing.T) {\n})\n}\n}\n+\n+// TestReuseAddrAndBroadcast makes sure broadcast packets are received by all\n+// interested endpoints.\n+func TestReuseAddrAndBroadcast(t *testing.T) {\n+ const (\n+ nicID = 1\n+ localPort = 9000\n+ loopbackBroadcast = tcpip.Address(\"\\x7f\\xff\\xff\\xff\")\n+ )\n+\n+ data := tcpip.SlicePayload([]byte{1, 2, 3, 4})\n+\n+ tests := []struct {\n+ name string\n+ broadcastAddr tcpip.Address\n+ }{\n+ {\n+ name: \"Subnet directed broadcast\",\n+ broadcastAddr: loopbackBroadcast,\n+ },\n+ {\n+ name: \"IPv4 broadcast\",\n+ broadcastAddr: header.IPv4Broadcast,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocol{ipv4.NewProtocol(), ipv6.NewProtocol()},\n+ TransportProtocols: []stack.TransportProtocol{udp.NewProtocol()},\n+ })\n+ if err := s.CreateNIC(nicID, loopback.New()); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", nicID, err)\n+ }\n+ protoAddr := tcpip.ProtocolAddress{\n+ Protocol: header.IPv4ProtocolNumber,\n+ AddressWithPrefix: tcpip.AddressWithPrefix{\n+ Address: \"\\x7f\\x00\\x00\\x01\",\n+ PrefixLen: 8,\n+ },\n+ }\n+ if err := s.AddProtocolAddress(nicID, protoAddr); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %+v): %s\", nicID, protoAddr, err)\n+ }\n+\n+ s.SetRouteTable([]tcpip.Route{\n+ tcpip.Route{\n+ // We use the empty subnet instead of just the loopback subnet so we\n+ // also have a route to the IPv4 Broadcast address.\n+ Destination: header.IPv4EmptySubnet,\n+ NIC: nicID,\n+ },\n+ })\n+\n+ // We create endpoints that bind to both the wildcard address and the\n+ // broadcast address to make sure both of these types of \"broadcast\n+ // interested\" endpoints receive broadcast packets.\n+ wq := waiter.Queue{}\n+ var eps []tcpip.Endpoint\n+ for _, bindWildcard := range []bool{false, true} {\n+ // Create multiple endpoints for each type of \"broadcast interested\"\n+ // endpoint so we can test that all endpoints receive the broadcast\n+ // packet.\n+ for i := 0; i < 2; i++ {\n+ ep, err := s.NewEndpoint(udp.ProtocolNumber, ipv4.ProtocolNumber, &wq)\n+ if err != nil {\n+ t.Fatalf(\"(eps[%d]) NewEndpoint(%d, %d, _): %s\", len(eps), udp.ProtocolNumber, ipv4.ProtocolNumber, err)\n+ }\n+ defer ep.Close()\n+\n+ if err := ep.SetSockOptBool(tcpip.ReuseAddressOption, true); err != nil {\n+ t.Fatalf(\"eps[%d].SetSockOptBool(tcpip.ReuseAddressOption, true): %s\", len(eps), err)\n+ }\n+\n+ if err := ep.SetSockOptBool(tcpip.BroadcastOption, true); err != nil {\n+ t.Fatalf(\"eps[%d].SetSockOptBool(tcpip.BroadcastOption, true): %s\", len(eps), err)\n+ }\n+\n+ bindAddr := tcpip.FullAddress{Port: localPort}\n+ if bindWildcard {\n+ if err := ep.Bind(bindAddr); err != nil {\n+ t.Fatalf(\"eps[%d].Bind(%+v): %s\", len(eps), bindAddr, err)\n+ }\n+ } else {\n+ bindAddr.Addr = test.broadcastAddr\n+ if err := ep.Bind(bindAddr); err != nil {\n+ t.Fatalf(\"eps[%d].Bind(%+v): %s\", len(eps), bindAddr, err)\n+ }\n+ }\n+\n+ eps = append(eps, ep)\n+ }\n+ }\n+\n+ for i, wep := range eps {\n+ writeOpts := tcpip.WriteOptions{\n+ To: &tcpip.FullAddress{\n+ Addr: test.broadcastAddr,\n+ Port: localPort,\n+ },\n+ }\n+ if n, _, err := wep.Write(data, writeOpts); err != nil {\n+ t.Fatalf(\"eps[%d].Write(_, _): %s\", i, err)\n+ } else if want := int64(len(data)); n != want {\n+ t.Fatalf(\"got eps[%d].Write(_, _) = (%d, nil, nil), want = (%d, nil, nil)\", i, n, want)\n+ }\n+\n+ for j, rep := range eps {\n+ if gotPayload, _, err := rep.Read(nil); err != nil {\n+ t.Errorf(\"(eps[%d] write) eps[%d].Read(nil): %s\", i, j, err)\n+ } else if diff := cmp.Diff(buffer.View(data), gotPayload); diff != \"\" {\n+ t.Errorf(\"(eps[%d] write) got UDP payload from eps[%d] mismatch (-want +got):\\n%s\", i, j, diff)\n+ }\n+ }\n+ }\n+ })\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/tcp_test.go", "new_path": "pkg/tcpip/transport/tcp/tcp_test.go", "diff": "@@ -5214,6 +5214,8 @@ func TestListenBacklogFull(t *testing.T) {\nfunc TestListenNoAcceptNonUnicastV4(t *testing.T) {\nmulticastAddr := tcpip.Address(\"\\xe0\\x00\\x01\\x02\")\notherMulticastAddr := tcpip.Address(\"\\xe0\\x00\\x01\\x03\")\n+ subnet := context.StackAddrWithPrefix.Subnet()\n+ subnetBroadcastAddr := subnet.Broadcast()\ntests := []struct {\nname string\n@@ -5221,53 +5223,59 @@ func TestListenNoAcceptNonUnicastV4(t *testing.T) {\ndstAddr tcpip.Address\n}{\n{\n- \"SourceUnspecified\",\n- header.IPv4Any,\n- context.StackAddr,\n+ name: \"SourceUnspecified\",\n+ srcAddr: header.IPv4Any,\n+ dstAddr: context.StackAddr,\n},\n{\n- \"SourceBroadcast\",\n- header.IPv4Broadcast,\n- context.StackAddr,\n+ name: \"SourceBroadcast\",\n+ srcAddr: header.IPv4Broadcast,\n+ dstAddr: context.StackAddr,\n},\n{\n- \"SourceOurMulticast\",\n- multicastAddr,\n- context.StackAddr,\n+ name: \"SourceOurMulticast\",\n+ srcAddr: multicastAddr,\n+ dstAddr: context.StackAddr,\n},\n{\n- \"SourceOtherMulticast\",\n- otherMulticastAddr,\n- context.StackAddr,\n+ name: \"SourceOtherMulticast\",\n+ srcAddr: otherMulticastAddr,\n+ dstAddr: context.StackAddr,\n},\n{\n- \"DestUnspecified\",\n- context.TestAddr,\n- header.IPv4Any,\n+ name: \"DestUnspecified\",\n+ srcAddr: context.TestAddr,\n+ dstAddr: header.IPv4Any,\n},\n{\n- \"DestBroadcast\",\n- context.TestAddr,\n- header.IPv4Broadcast,\n+ name: \"DestBroadcast\",\n+ srcAddr: context.TestAddr,\n+ dstAddr: header.IPv4Broadcast,\n},\n{\n- \"DestOurMulticast\",\n- context.TestAddr,\n- multicastAddr,\n+ name: \"DestOurMulticast\",\n+ srcAddr: context.TestAddr,\n+ dstAddr: multicastAddr,\n},\n{\n- \"DestOtherMulticast\",\n- context.TestAddr,\n- otherMulticastAddr,\n+ name: \"DestOtherMulticast\",\n+ srcAddr: context.TestAddr,\n+ dstAddr: otherMulticastAddr,\n+ },\n+ {\n+ name: \"SrcSubnetBroadcast\",\n+ srcAddr: subnetBroadcastAddr,\n+ dstAddr: context.StackAddr,\n+ },\n+ {\n+ name: \"DestSubnetBroadcast\",\n+ srcAddr: context.TestAddr,\n+ dstAddr: subnetBroadcastAddr,\n},\n}\nfor _, test := range tests {\n- test := test // capture range variable\n-\nt.Run(test.name, func(t *testing.T) {\n- t.Parallel()\n-\nc := context.New(t, defaultMTU)\ndefer c.Cleanup()\n@@ -5367,11 +5375,7 @@ func TestListenNoAcceptNonUnicastV6(t *testing.T) {\n}\nfor _, test := range tests {\n- test := test // capture range variable\n-\nt.Run(test.name, func(t *testing.T) {\n- t.Parallel()\n-\nc := context.New(t, defaultMTU)\ndefer c.Cleanup()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/testing/context/context.go", "new_path": "pkg/tcpip/transport/tcp/testing/context/context.go", "diff": "@@ -53,11 +53,11 @@ const (\nTestPort = 4096\n// StackV6Addr is the IPv6 address assigned to the stack.\n- StackV6Addr = \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\"\n+ StackV6Addr = \"\\x0a\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\"\n// TestV6Addr is the source address for packets sent to the stack via\n// the link layer endpoint.\n- TestV6Addr = \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\"\n+ TestV6Addr = \"\\x0a\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\"\n// StackV4MappedAddr is StackAddr as a mapped v6 address.\nStackV4MappedAddr = \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xff\\xff\" + StackAddr\n@@ -73,6 +73,18 @@ const (\ntestInitialSequenceNumber = 789\n)\n+// StackAddrWithPrefix is StackAddr with its associated prefix length.\n+var StackAddrWithPrefix = tcpip.AddressWithPrefix{\n+ Address: StackAddr,\n+ PrefixLen: 24,\n+}\n+\n+// StackV6AddrWithPrefix is StackV6Addr with its associated prefix length.\n+var StackV6AddrWithPrefix = tcpip.AddressWithPrefix{\n+ Address: StackV6Addr,\n+ PrefixLen: header.IIDOffsetInIPv6Address * 8,\n+}\n+\n// Headers is used to represent the TCP header fields when building a\n// new packet.\ntype Headers struct {\n@@ -184,12 +196,20 @@ func New(t *testing.T, mtu uint32) *Context {\nt.Fatalf(\"CreateNICWithOptions(_, _, %+v) failed: %v\", opts2, err)\n}\n- if err := s.AddAddress(1, ipv4.ProtocolNumber, StackAddr); err != nil {\n- t.Fatalf(\"AddAddress failed: %v\", err)\n+ v4ProtocolAddr := tcpip.ProtocolAddress{\n+ Protocol: ipv4.ProtocolNumber,\n+ AddressWithPrefix: StackAddrWithPrefix,\n+ }\n+ if err := s.AddProtocolAddress(1, v4ProtocolAddr); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(1, %#v): %s\", v4ProtocolAddr, err)\n}\n- if err := s.AddAddress(1, ipv6.ProtocolNumber, StackV6Addr); err != nil {\n- t.Fatalf(\"AddAddress failed: %v\", err)\n+ v6ProtocolAddr := tcpip.ProtocolAddress{\n+ Protocol: ipv6.ProtocolNumber,\n+ AddressWithPrefix: StackV6AddrWithPrefix,\n+ }\n+ if err := s.AddProtocolAddress(1, v6ProtocolAddr); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(1, %#v): %s\", v6ProtocolAddr, err)\n}\ns.SetRouteTable([]tcpip.Route{\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -2430,6 +2430,7 @@ cc_library(\n\":socket_netlink_route_util\",\n\":socket_test_util\",\n\"//test/util:capability_util\",\n+ \"//test/util:cleanup\",\ngtest,\n],\nalwayslink = 1,\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_ipv4_udp_unbound_netlink.cc", "new_path": "test/syscalls/linux/socket_ipv4_udp_unbound_netlink.cc", "diff": "#include \"test/syscalls/linux/socket_ipv4_udp_unbound_netlink.h\"\n#include <arpa/inet.h>\n+#include <poll.h>\n#include \"gtest/gtest.h\"\n#include \"test/syscalls/linux/socket_netlink_route_util.h\"\n#include \"test/util/capability_util.h\"\n+#include \"test/util/cleanup.h\"\nnamespace gvisor {\nnamespace testing {\n@@ -33,9 +35,23 @@ TEST_P(IPv4UDPUnboundSocketNetlinkTest, JoinSubnet) {\n// Add an IP address to the loopback interface.\nLink loopback_link = ASSERT_NO_ERRNO_AND_VALUE(LoopbackLink());\nstruct in_addr addr;\n- EXPECT_EQ(1, inet_pton(AF_INET, \"192.0.2.1\", &addr));\n- EXPECT_NO_ERRNO(LinkAddLocalAddr(loopback_link.index, AF_INET,\n+ ASSERT_EQ(1, inet_pton(AF_INET, \"192.0.2.1\", &addr));\n+ ASSERT_NO_ERRNO(LinkAddLocalAddr(loopback_link.index, AF_INET,\n/*prefixlen=*/24, &addr, sizeof(addr)));\n+ Cleanup defer_addr_removal = Cleanup(\n+ [loopback_link = std::move(loopback_link), addr = std::move(addr)] {\n+ if (IsRunningOnGvisor()) {\n+ // TODO(gvisor.dev/issue/3921): Remove this once deleting addresses\n+ // via netlink is supported.\n+ EXPECT_THAT(LinkDelLocalAddr(loopback_link.index, AF_INET,\n+ /*prefixlen=*/24, &addr, sizeof(addr)),\n+ PosixErrorIs(EOPNOTSUPP, ::testing::_));\n+ } else {\n+ EXPECT_NO_ERRNO(LinkDelLocalAddr(loopback_link.index, AF_INET,\n+ /*prefixlen=*/24, &addr,\n+ sizeof(addr)));\n+ }\n+ });\nauto snd_sock = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\nauto rcv_sock = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n@@ -45,10 +61,10 @@ TEST_P(IPv4UDPUnboundSocketNetlinkTest, JoinSubnet) {\nTestAddress sender_addr(\"V4NotAssignd1\");\nsender_addr.addr.ss_family = AF_INET;\nsender_addr.addr_len = sizeof(sockaddr_in);\n- EXPECT_EQ(1, inet_pton(AF_INET, \"192.0.2.2\",\n+ ASSERT_EQ(1, inet_pton(AF_INET, \"192.0.2.2\",\n&(reinterpret_cast<sockaddr_in*>(&sender_addr.addr)\n->sin_addr.s_addr)));\n- EXPECT_THAT(\n+ ASSERT_THAT(\nbind(snd_sock->get(), reinterpret_cast<sockaddr*>(&sender_addr.addr),\nsender_addr.addr_len),\nSyscallSucceeds());\n@@ -58,10 +74,10 @@ TEST_P(IPv4UDPUnboundSocketNetlinkTest, JoinSubnet) {\nTestAddress receiver_addr(\"V4NotAssigned2\");\nreceiver_addr.addr.ss_family = AF_INET;\nreceiver_addr.addr_len = sizeof(sockaddr_in);\n- EXPECT_EQ(1, inet_pton(AF_INET, \"192.0.2.254\",\n+ ASSERT_EQ(1, inet_pton(AF_INET, \"192.0.2.254\",\n&(reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)\n->sin_addr.s_addr)));\n- EXPECT_THAT(\n+ ASSERT_THAT(\nbind(rcv_sock->get(), reinterpret_cast<sockaddr*>(&receiver_addr.addr),\nreceiver_addr.addr_len),\nSyscallSucceeds());\n@@ -70,10 +86,10 @@ TEST_P(IPv4UDPUnboundSocketNetlinkTest, JoinSubnet) {\nreinterpret_cast<sockaddr*>(&receiver_addr.addr),\n&receiver_addr_len),\nSyscallSucceeds());\n- EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);\n+ ASSERT_EQ(receiver_addr_len, receiver_addr.addr_len);\nchar send_buf[kSendBufSize];\nRandomizeBuffer(send_buf, kSendBufSize);\n- EXPECT_THAT(\n+ ASSERT_THAT(\nRetryEINTR(sendto)(snd_sock->get(), send_buf, kSendBufSize, 0,\nreinterpret_cast<sockaddr*>(&receiver_addr.addr),\nreceiver_addr.addr_len),\n@@ -83,7 +99,126 @@ TEST_P(IPv4UDPUnboundSocketNetlinkTest, JoinSubnet) {\nchar recv_buf[kSendBufSize] = {};\nASSERT_THAT(RetryEINTR(recv)(rcv_sock->get(), recv_buf, kSendBufSize, 0),\nSyscallSucceedsWithValue(kSendBufSize));\n- EXPECT_EQ(0, memcmp(send_buf, recv_buf, kSendBufSize));\n+ ASSERT_EQ(0, memcmp(send_buf, recv_buf, kSendBufSize));\n+}\n+\n+// Tests that broadcast packets are delivered to all interested sockets\n+// (wildcard and broadcast address specified sockets).\n+//\n+// Note, we cannot test the IPv4 Broadcast (255.255.255.255) because we do\n+// not have a route to it.\n+TEST_P(IPv4UDPUnboundSocketNetlinkTest, ReuseAddrSubnetDirectedBroadcast) {\n+ constexpr uint16_t kPort = 9876;\n+ // Wait up to 20 seconds for the data.\n+ constexpr int kPollTimeoutMs = 20000;\n+ // Number of sockets per socket type.\n+ constexpr int kNumSocketsPerType = 2;\n+\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_ADMIN)));\n+\n+ // Add an IP address to the loopback interface.\n+ Link loopback_link = ASSERT_NO_ERRNO_AND_VALUE(LoopbackLink());\n+ struct in_addr addr;\n+ ASSERT_EQ(1, inet_pton(AF_INET, \"192.0.2.1\", &addr));\n+ ASSERT_NO_ERRNO(LinkAddLocalAddr(loopback_link.index, AF_INET,\n+ 24 /* prefixlen */, &addr, sizeof(addr)));\n+ Cleanup defer_addr_removal = Cleanup(\n+ [loopback_link = std::move(loopback_link), addr = std::move(addr)] {\n+ if (IsRunningOnGvisor()) {\n+ // TODO(gvisor.dev/issue/3921): Remove this once deleting addresses\n+ // via netlink is supported.\n+ EXPECT_THAT(LinkDelLocalAddr(loopback_link.index, AF_INET,\n+ /*prefixlen=*/24, &addr, sizeof(addr)),\n+ PosixErrorIs(EOPNOTSUPP, ::testing::_));\n+ } else {\n+ EXPECT_NO_ERRNO(LinkDelLocalAddr(loopback_link.index, AF_INET,\n+ /*prefixlen=*/24, &addr,\n+ sizeof(addr)));\n+ }\n+ });\n+\n+ TestAddress broadcast_address(\"SubnetBroadcastAddress\");\n+ broadcast_address.addr.ss_family = AF_INET;\n+ broadcast_address.addr_len = sizeof(sockaddr_in);\n+ auto broadcast_address_in =\n+ reinterpret_cast<sockaddr_in*>(&broadcast_address.addr);\n+ ASSERT_EQ(1, inet_pton(AF_INET, \"192.0.2.255\",\n+ &broadcast_address_in->sin_addr.s_addr));\n+ broadcast_address_in->sin_port = htons(kPort);\n+\n+ TestAddress any_address = V4Any();\n+ reinterpret_cast<sockaddr_in*>(&any_address.addr)->sin_port = htons(kPort);\n+\n+ // We create sockets bound to both the wildcard address and the broadcast\n+ // address to make sure both of these types of \"broadcast interested\" sockets\n+ // receive broadcast packets.\n+ std::vector<std::unique_ptr<FileDescriptor>> socks;\n+ for (bool bind_wildcard : {false, true}) {\n+ // Create multiple sockets for each type of \"broadcast interested\"\n+ // socket so we can test that all sockets receive the broadcast packet.\n+ for (int i = 0; i < kNumSocketsPerType; i++) {\n+ auto sock = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n+ auto idx = socks.size();\n+\n+ ASSERT_THAT(setsockopt(sock->get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,\n+ sizeof(kSockOptOn)),\n+ SyscallSucceedsWithValue(0))\n+ << \"socks[\" << idx << \"]\";\n+\n+ ASSERT_THAT(setsockopt(sock->get(), SOL_SOCKET, SO_BROADCAST, &kSockOptOn,\n+ sizeof(kSockOptOn)),\n+ SyscallSucceedsWithValue(0))\n+ << \"socks[\" << idx << \"]\";\n+\n+ if (bind_wildcard) {\n+ ASSERT_THAT(\n+ bind(sock->get(), reinterpret_cast<sockaddr*>(&any_address.addr),\n+ any_address.addr_len),\n+ SyscallSucceeds())\n+ << \"socks[\" << idx << \"]\";\n+ } else {\n+ ASSERT_THAT(bind(sock->get(),\n+ reinterpret_cast<sockaddr*>(&broadcast_address.addr),\n+ broadcast_address.addr_len),\n+ SyscallSucceeds())\n+ << \"socks[\" << idx << \"]\";\n+ }\n+\n+ socks.push_back(std::move(sock));\n+ }\n+ }\n+\n+ char send_buf[kSendBufSize];\n+ RandomizeBuffer(send_buf, kSendBufSize);\n+\n+ // Broadcasts from each socket should be received by every socket (including\n+ // the sending socket).\n+ for (int w = 0; w < socks.size(); w++) {\n+ auto& w_sock = socks[w];\n+ ASSERT_THAT(\n+ RetryEINTR(sendto)(w_sock->get(), send_buf, kSendBufSize, 0,\n+ reinterpret_cast<sockaddr*>(&broadcast_address.addr),\n+ broadcast_address.addr_len),\n+ SyscallSucceedsWithValue(kSendBufSize))\n+ << \"write socks[\" << w << \"]\";\n+\n+ // Check that we received the packet on all sockets.\n+ for (int r = 0; r < socks.size(); r++) {\n+ auto& r_sock = socks[r];\n+\n+ struct pollfd poll_fd = {r_sock->get(), POLLIN, 0};\n+ EXPECT_THAT(RetryEINTR(poll)(&poll_fd, 1, kPollTimeoutMs),\n+ SyscallSucceedsWithValue(1))\n+ << \"write socks[\" << w << \"] & read socks[\" << r << \"]\";\n+\n+ char recv_buf[kSendBufSize] = {};\n+ EXPECT_THAT(RetryEINTR(recv)(r_sock->get(), recv_buf, kSendBufSize, 0),\n+ SyscallSucceedsWithValue(kSendBufSize))\n+ << \"write socks[\" << w << \"] & read socks[\" << r << \"]\";\n+ EXPECT_EQ(0, memcmp(send_buf, recv_buf, kSendBufSize))\n+ << \"write socks[\" << w << \"] & read socks[\" << r << \"]\";\n+ }\n+ }\n}\n} // namespace testing\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_netlink_route_util.cc", "new_path": "test/syscalls/linux/socket_netlink_route_util.cc", "diff": "@@ -26,6 +26,62 @@ namespace {\nconstexpr uint32_t kSeq = 12345;\n+// Types of address modifications that may be performed on an interface.\n+enum class LinkAddrModification {\n+ kAdd,\n+ kDelete,\n+};\n+\n+// Populates |hdr| with appripriate values for the modification type.\n+PosixError PopulateNlmsghdr(LinkAddrModification modification,\n+ struct nlmsghdr* hdr) {\n+ switch (modification) {\n+ case LinkAddrModification::kAdd:\n+ hdr->nlmsg_type = RTM_NEWADDR;\n+ hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;\n+ return NoError();\n+ case LinkAddrModification::kDelete:\n+ hdr->nlmsg_type = RTM_DELADDR;\n+ hdr->nlmsg_flags = NLM_F_REQUEST;\n+ return NoError();\n+ }\n+\n+ return PosixError(EINVAL);\n+}\n+\n+// Adds or removes the specified address from the specified interface.\n+PosixError LinkModifyLocalAddr(int index, int family, int prefixlen,\n+ const void* addr, int addrlen,\n+ LinkAddrModification modification) {\n+ ASSIGN_OR_RETURN_ERRNO(FileDescriptor fd, NetlinkBoundSocket(NETLINK_ROUTE));\n+\n+ struct request {\n+ struct nlmsghdr hdr;\n+ struct ifaddrmsg ifaddr;\n+ char attrbuf[512];\n+ };\n+\n+ struct request req = {};\n+ PosixError err = PopulateNlmsghdr(modification, &req.hdr);\n+ if (!err.ok()) {\n+ return err;\n+ }\n+ req.hdr.nlmsg_len = NLMSG_LENGTH(sizeof(req.ifaddr));\n+ req.hdr.nlmsg_seq = kSeq;\n+ req.ifaddr.ifa_index = index;\n+ req.ifaddr.ifa_family = family;\n+ req.ifaddr.ifa_prefixlen = prefixlen;\n+\n+ struct rtattr* rta = reinterpret_cast<struct rtattr*>(\n+ reinterpret_cast<int8_t*>(&req) + NLMSG_ALIGN(req.hdr.nlmsg_len));\n+ rta->rta_type = IFA_LOCAL;\n+ rta->rta_len = RTA_LENGTH(addrlen);\n+ req.hdr.nlmsg_len = NLMSG_ALIGN(req.hdr.nlmsg_len) + RTA_LENGTH(addrlen);\n+ memcpy(RTA_DATA(rta), addr, addrlen);\n+\n+ return NetlinkRequestAckOrError(fd, kSeq, &req, req.hdr.nlmsg_len);\n+}\n+\n} // namespace\nPosixError DumpLinks(\n@@ -84,31 +140,14 @@ PosixErrorOr<Link> LoopbackLink() {\nPosixError LinkAddLocalAddr(int index, int family, int prefixlen,\nconst void* addr, int addrlen) {\n- ASSIGN_OR_RETURN_ERRNO(FileDescriptor fd, NetlinkBoundSocket(NETLINK_ROUTE));\n-\n- struct request {\n- struct nlmsghdr hdr;\n- struct ifaddrmsg ifaddr;\n- char attrbuf[512];\n- };\n-\n- struct request req = {};\n- req.hdr.nlmsg_len = NLMSG_LENGTH(sizeof(req.ifaddr));\n- req.hdr.nlmsg_type = RTM_NEWADDR;\n- req.hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;\n- req.hdr.nlmsg_seq = kSeq;\n- req.ifaddr.ifa_index = index;\n- req.ifaddr.ifa_family = family;\n- req.ifaddr.ifa_prefixlen = prefixlen;\n-\n- struct rtattr* rta = reinterpret_cast<struct rtattr*>(\n- reinterpret_cast<int8_t*>(&req) + NLMSG_ALIGN(req.hdr.nlmsg_len));\n- rta->rta_type = IFA_LOCAL;\n- rta->rta_len = RTA_LENGTH(addrlen);\n- req.hdr.nlmsg_len = NLMSG_ALIGN(req.hdr.nlmsg_len) + RTA_LENGTH(addrlen);\n- memcpy(RTA_DATA(rta), addr, addrlen);\n+ return LinkModifyLocalAddr(index, family, prefixlen, addr, addrlen,\n+ LinkAddrModification::kAdd);\n+}\n- return NetlinkRequestAckOrError(fd, kSeq, &req, req.hdr.nlmsg_len);\n+PosixError LinkDelLocalAddr(int index, int family, int prefixlen,\n+ const void* addr, int addrlen) {\n+ return LinkModifyLocalAddr(index, family, prefixlen, addr, addrlen,\n+ LinkAddrModification::kDelete);\n}\nPosixError LinkChangeFlags(int index, unsigned int flags, unsigned int change) {\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_netlink_route_util.h", "new_path": "test/syscalls/linux/socket_netlink_route_util.h", "diff": "@@ -43,6 +43,10 @@ PosixErrorOr<Link> LoopbackLink();\nPosixError LinkAddLocalAddr(int index, int family, int prefixlen,\nconst void* addr, int addrlen);\n+// LinkDelLocalAddr removes IFA_LOCAL attribute on the interface.\n+PosixError LinkDelLocalAddr(int index, int family, int prefixlen,\n+ const void* addr, int addrlen);\n+\n// LinkChangeFlags changes interface flags. E.g. IFF_UP.\nPosixError LinkChangeFlags(int index, unsigned int flags, unsigned int change);\n" } ]
Go
Apache License 2.0
google/gvisor
Receive broadcast packets on interested endpoints When a broadcast packet is received by the stack, the packet should be delivered to each endpoint that may be interested in the packet. This includes all any address and specified broadcast address listeners. Test: integration_test.TestReuseAddrAndBroadcast PiperOrigin-RevId: 332060652
259,913
14.09.2020 21:30:51
0
093b0ab6c57d83407704e31005c5c446cf51a5f1
Fix FUSE go unit test merge conflict mistake
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/dev_test.go", "new_path": "pkg/sentry/fsimpl/fuse/dev_test.go", "diff": "@@ -16,12 +16,10 @@ package fuse\nimport (\n\"fmt\"\n- \"io\"\n\"math/rand\"\n\"testing\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n- \"gvisor.dev/gvisor/pkg/marshal\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/testutil\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n@@ -323,102 +321,3 @@ func fuseServerRun(t *testing.T, s *testutil.System, k *kernel.Kernel, fd *vfs.F\n}\n}\n}\n-\n-func setup(t *testing.T) *testutil.System {\n- k, err := testutil.Boot()\n- if err != nil {\n- t.Fatalf(\"Error creating kernel: %v\", err)\n- }\n-\n- ctx := k.SupervisorContext()\n- creds := auth.CredentialsFromContext(ctx)\n-\n- k.VFS().MustRegisterFilesystemType(Name, &FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n- AllowUserList: true,\n- AllowUserMount: true,\n- })\n-\n- mntns, err := k.VFS().NewMountNamespace(ctx, creds, \"\", \"tmpfs\", &vfs.MountOptions{})\n- if err != nil {\n- t.Fatalf(\"NewMountNamespace(): %v\", err)\n- }\n-\n- return testutil.NewSystem(ctx, t, k.VFS(), mntns)\n-}\n-\n-// newTestConnection creates a fuse connection that the sentry can communicate with\n-// and the FD for the server to communicate with.\n-func newTestConnection(system *testutil.System, k *kernel.Kernel, maxActiveRequests uint64) (*connection, *vfs.FileDescription, error) {\n- vfsObj := &vfs.VirtualFilesystem{}\n- fuseDev := &DeviceFD{}\n-\n- if err := vfsObj.Init(system.Ctx); err != nil {\n- return nil, nil, err\n- }\n-\n- vd := vfsObj.NewAnonVirtualDentry(\"genCountFD\")\n- defer vd.DecRef(system.Ctx)\n- if err := fuseDev.vfsfd.Init(fuseDev, linux.O_RDWR|linux.O_CREAT, vd.Mount(), vd.Dentry(), &vfs.FileDescriptionOptions{}); err != nil {\n- return nil, nil, err\n- }\n-\n- fsopts := filesystemOptions{\n- maxActiveRequests: maxActiveRequests,\n- }\n- fs, err := newFUSEFilesystem(system.Ctx, 0, &fsopts, &fuseDev.vfsfd)\n- if err != nil {\n- return nil, nil, err\n- }\n-\n- return fs.conn, &fuseDev.vfsfd, nil\n-}\n-\n-// SizeBytes implements marshal.Marshallable.SizeBytes.\n-func (t *testPayload) SizeBytes() int {\n- return 4\n-}\n-\n-// MarshalBytes implements marshal.Marshallable.MarshalBytes.\n-func (t *testPayload) MarshalBytes(dst []byte) {\n- usermem.ByteOrder.PutUint32(dst[:4], t.data)\n-}\n-\n-// UnmarshalBytes implements marshal.Marshallable.UnmarshalBytes.\n-func (t *testPayload) UnmarshalBytes(src []byte) {\n- *t = testPayload{data: usermem.ByteOrder.Uint32(src[:4])}\n-}\n-\n-// Packed implements marshal.Marshallable.Packed.\n-func (t *testPayload) Packed() bool {\n- return true\n-}\n-\n-// MarshalUnsafe implements marshal.Marshallable.MarshalUnsafe.\n-func (t *testPayload) MarshalUnsafe(dst []byte) {\n- t.MarshalBytes(dst)\n-}\n-\n-// UnmarshalUnsafe implements marshal.Marshallable.UnmarshalUnsafe.\n-func (t *testPayload) UnmarshalUnsafe(src []byte) {\n- t.UnmarshalBytes(src)\n-}\n-\n-// CopyOutN implements marshal.Marshallable.CopyOutN.\n-func (t *testPayload) CopyOutN(cc marshal.CopyContext, addr usermem.Addr, limit int) (int, error) {\n- panic(\"not implemented\")\n-}\n-\n-// CopyOut implements marshal.Marshallable.CopyOut.\n-func (t *testPayload) CopyOut(cc marshal.CopyContext, addr usermem.Addr) (int, error) {\n- panic(\"not implemented\")\n-}\n-\n-// CopyIn implements marshal.Marshallable.CopyIn.\n-func (t *testPayload) CopyIn(cc marshal.CopyContext, addr usermem.Addr) (int, error) {\n- panic(\"not implemented\")\n-}\n-\n-// WriteTo implements io.WriterTo.WriteTo.\n-func (t *testPayload) WriteTo(w io.Writer) (int64, error) {\n- panic(\"not implemented\")\n-}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/utils_test.go", "new_path": "pkg/sentry/fsimpl/fuse/utils_test.go", "diff": "package fuse\nimport (\n+ \"io\"\n\"testing\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n@@ -109,3 +110,23 @@ func (t *testPayload) MarshalUnsafe(dst []byte) {\nfunc (t *testPayload) UnmarshalUnsafe(src []byte) {\nt.UnmarshalBytes(src)\n}\n+\n+// CopyOutN implements marshal.Marshallable.CopyOutN.\n+func (t *testPayload) CopyOutN(task marshal.CopyContext, addr usermem.Addr, limit int) (int, error) {\n+ panic(\"not implemented\")\n+}\n+\n+// CopyOut implements marshal.Marshallable.CopyOut.\n+func (t *testPayload) CopyOut(task marshal.CopyContext, addr usermem.Addr) (int, error) {\n+ panic(\"not implemented\")\n+}\n+\n+// CopyIn implements marshal.Marshallable.CopyIn.\n+func (t *testPayload) CopyIn(task marshal.CopyContext, addr usermem.Addr) (int, error) {\n+ panic(\"not implemented\")\n+}\n+\n+// WriteTo implements io.WriterTo.WriteTo.\n+func (t *testPayload) WriteTo(w io.Writer) (int64, error) {\n+ panic(\"not implemented\")\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix FUSE go unit test merge conflict mistake
259,913
14.09.2020 21:54:18
0
113928754c26ea3d4d7d387bae459ce447774d30
Fix FUSE unit test after vfs interface change
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/utils_test.go", "new_path": "pkg/sentry/fsimpl/fuse/utils_test.go", "diff": "@@ -41,7 +41,7 @@ func setup(t *testing.T) *testutil.System {\nAllowUserMount: true,\n})\n- mntns, err := k.VFS().NewMountNamespace(ctx, creds, \"\", \"tmpfs\", &vfs.GetFilesystemOptions{})\n+ mntns, err := k.VFS().NewMountNamespace(ctx, creds, \"\", \"tmpfs\", &vfs.MountOptions{})\nif err != nil {\nt.Fatalf(\"NewMountNamespace(): %v\", err)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix FUSE unit test after vfs interface change
259,853
15.09.2020 13:31:40
25,200
92a020c798fe237fb7038f3da71f24c5a88bb744
fuse: fix a compile time error readdir_test.cc:134:24: error: variable length arrays are a C99 feature [-Werror,-Wvla-extension] char readdir_payload[readdir_payload_size];
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description_impl_util.go", "new_path": "pkg/sentry/vfs/file_description_impl_util.go", "diff": "@@ -107,7 +107,7 @@ func (FileDescriptionDefaultImpl) Write(ctx context.Context, src usermem.IOSeque\n// file_operations::iterate == file_operations::iterate_shared == NULL in\n// Linux.\nfunc (FileDescriptionDefaultImpl) IterDirents(ctx context.Context, cb IterDirentsCallback) error {\n- return syserror.ENOSYS\n+ return syserror.ENOTDIR\n}\n// Seek implements FileDescriptionImpl.Seek analogously to\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/readdir_test.cc", "new_path": "test/fuse/linux/readdir_test.cc", "diff": "@@ -131,7 +131,8 @@ TEST_F(ReaddirTest, SingleEntry) {\n// Create an appropriately sized payload.\nsize_t readdir_payload_size =\ntest_file_dirent_size + dot_file_dirent_size + dot_dot_file_dirent_size;\n- char readdir_payload[readdir_payload_size];\n+ std::vector<char> readdir_payload_vec(readdir_payload_size);\n+ char *readdir_payload = readdir_payload_vec.data();\nfill_fuse_dirent(readdir_payload, dot.c_str());\nfill_fuse_dirent(readdir_payload + dot_file_dirent_size, dot_dot.c_str());\n@@ -139,10 +140,8 @@ TEST_F(ReaddirTest, SingleEntry) {\nreaddir_payload + dot_file_dirent_size + dot_dot_file_dirent_size,\ntest_file.c_str());\n- std::vector<char> readdir_payload_vec(readdir_payload,\n- readdir_payload + readdir_payload_size);\nstruct fuse_out_header readdir_header = {\n- .len = uint32_t(sizeof(struct fuse_out_header) + sizeof(readdir_payload)),\n+ .len = uint32_t(sizeof(struct fuse_out_header) + readdir_payload_size),\n};\nstruct fuse_out_header readdir_header_break = {\n.len = uint32_t(sizeof(struct fuse_out_header)),\n" } ]
Go
Apache License 2.0
google/gvisor
fuse: fix a compile time error readdir_test.cc:134:24: error: variable length arrays are a C99 feature [-Werror,-Wvla-extension] char readdir_payload[readdir_payload_size];
259,853
15.09.2020 13:51:18
25,200
3ea925a423ed2c195498fac63b200b8a1a302f4c
fuse: don't pass lock by value copylocks: directory.go:34:7: Allocate passes lock by value: fuse/fuse.directoryFD contains fuse/fuse.fileDescription contains pkg/sentry/vfs/vfs.FileDescription contains pkg/sync/sync.Mutex
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/directory.go", "new_path": "pkg/sentry/fsimpl/fuse/directory.go", "diff": "@@ -31,27 +31,27 @@ type directoryFD struct {\n}\n// Allocate implements directoryFD.Allocate.\n-func (directoryFD) Allocate(ctx context.Context, mode, offset, length uint64) error {\n+func (*directoryFD) Allocate(ctx context.Context, mode, offset, length uint64) error {\nreturn syserror.EISDIR\n}\n// PRead implements FileDescriptionImpl.PRead.\n-func (directoryFD) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts vfs.ReadOptions) (int64, error) {\n+func (*directoryFD) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts vfs.ReadOptions) (int64, error) {\nreturn 0, syserror.EISDIR\n}\n// Read implements FileDescriptionImpl.Read.\n-func (directoryFD) Read(ctx context.Context, dst usermem.IOSequence, opts vfs.ReadOptions) (int64, error) {\n+func (*directoryFD) Read(ctx context.Context, dst usermem.IOSequence, opts vfs.ReadOptions) (int64, error) {\nreturn 0, syserror.EISDIR\n}\n// PWrite implements FileDescriptionImpl.PWrite.\n-func (directoryFD) PWrite(ctx context.Context, src usermem.IOSequence, offset int64, opts vfs.WriteOptions) (int64, error) {\n+func (*directoryFD) PWrite(ctx context.Context, src usermem.IOSequence, offset int64, opts vfs.WriteOptions) (int64, error) {\nreturn 0, syserror.EISDIR\n}\n// Write implements FileDescriptionImpl.Write.\n-func (directoryFD) Write(ctx context.Context, src usermem.IOSequence, opts vfs.WriteOptions) (int64, error) {\n+func (*directoryFD) Write(ctx context.Context, src usermem.IOSequence, opts vfs.WriteOptions) (int64, error) {\nreturn 0, syserror.EISDIR\n}\n" } ]
Go
Apache License 2.0
google/gvisor
fuse: don't pass lock by value copylocks: directory.go:34:7: Allocate passes lock by value: fuse/fuse.directoryFD contains fuse/fuse.fileDescription contains pkg/sentry/vfs/vfs.FileDescription contains pkg/sync/sync.Mutex
259,913
14.09.2020 23:16:56
0
96fb1e60c355b330eaf42db3a14a828befe73db9
Fix FUSE connection control lock ordering and race in unit test
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/connection_control.go", "new_path": "pkg/sentry/fsimpl/fuse/connection_control.go", "diff": "@@ -95,6 +95,8 @@ func (conn *connection) InitSend(creds *auth.Credentials, pid uint32) error {\n}\n// InitRecv receives a FUSE_INIT reply and process it.\n+//\n+// Preconditions: conn.asyncMu must not be held if minor verion is newer than 13.\nfunc (conn *connection) InitRecv(res *Response, hasSysAdminCap bool) error {\nif err := res.Error(); err != nil {\nreturn err\n@@ -189,6 +191,8 @@ func (conn *connection) initProcessReply(out *linux.FUSEInitOut, hasSysAdminCap\n// All possible requests waiting or blocking will be aborted.\nfunc (conn *connection) Abort(ctx context.Context) {\nconn.fd.mu.Lock()\n+ defer conn.fd.mu.Unlock()\n+\nconn.mu.Lock()\nconn.asyncMu.Lock()\n@@ -217,10 +221,9 @@ func (conn *connection) Abort(ctx context.Context) {\nterminate = append(terminate, unique)\n}\n- // Release all locks to avoid deadlock.\n+ // Release locks to avoid deadlock.\nconn.asyncMu.Unlock()\nconn.mu.Unlock()\n- conn.fd.mu.Unlock()\n// 1. The requets blocked before initialization.\n// Will reach call() `connected` check and return.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/connection_test.go", "new_path": "pkg/sentry/fsimpl/fuse/connection_test.go", "diff": "@@ -62,9 +62,9 @@ func TestConnectionAbort(t *testing.T) {\ncreds := auth.CredentialsFromContext(s.Ctx)\ntask := kernel.TaskFromContext(s.Ctx)\n- const maxActiveRequest uint64 = 10\n+ const numRequests uint64 = 256\n- conn, _, err := newTestConnection(s, k, maxActiveRequest)\n+ conn, _, err := newTestConnection(s, k, numRequests)\nif err != nil {\nt.Fatalf(\"newTestConnection: %v\", err)\n}\n@@ -75,32 +75,22 @@ func TestConnectionAbort(t *testing.T) {\nvar futNormal []*futureResponse\n- for i := 0; i < 2*int(maxActiveRequest); i++ {\n+ for i := 0; i < int(numRequests); i++ {\nreq, err := conn.NewRequest(creds, uint32(i), uint64(i), 0, testObj)\nif err != nil {\nt.Fatalf(\"NewRequest creation failed: %v\", err)\n}\n- if i < int(maxActiveRequest) {\n- // Issue the requests that will not be blocked due to maxActiveRequest.\nfut, err := conn.callFutureLocked(task, req)\nif err != nil {\nt.Fatalf(\"callFutureLocked failed: %v\", err)\n}\nfutNormal = append(futNormal, fut)\n- } else {\n- go func(t *testing.T) {\n- // The requests beyond maxActiveRequest will be blocked and receive expected errors.\n- _, err := conn.callFutureLocked(task, req)\n- if err != syserror.ECONNABORTED && err != syserror.ENOTCONN {\n- t.Fatalf(\"Incorrect error code received for blocked callFutureLocked() on aborted connection\")\n- }\n- }(t)\n- }\n}\nconn.Abort(s.Ctx)\n// Abort should unblock the initialization channel.\n+ // Note: no test requests are actually blocked on `conn.initializedChan`.\nselect {\ncase <-conn.initializedChan:\ndefault:\n@@ -110,7 +100,7 @@ func TestConnectionAbort(t *testing.T) {\n// Abort will return ECONNABORTED error to unblocked requests.\nfor _, fut := range futNormal {\nif fut.getResponse().hdr.Error != -int32(syscall.ECONNABORTED) {\n- t.Fatalf(\"Incorrect error code received for aborted connection\")\n+ t.Fatalf(\"Incorrect error code received for aborted connection: %v\", fut.getResponse().hdr.Error)\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/dev.go", "new_path": "pkg/sentry/fsimpl/fuse/dev.go", "diff": "@@ -391,6 +391,8 @@ func (fd *DeviceFD) Seek(ctx context.Context, offset int64, whence int32) (int64\n}\n// sendResponse sends a response to the waiting task (if any).\n+//\n+// Preconditions: fd.mu must be held.\nfunc (fd *DeviceFD) sendResponse(ctx context.Context, fut *futureResponse) error {\n// Signal the task waiting on a response if any.\ndefer close(fut.ch)\n@@ -410,6 +412,8 @@ func (fd *DeviceFD) sendResponse(ctx context.Context, fut *futureResponse) error\n}\n// sendError sends an error response to the waiting task (if any) by calling sendResponse().\n+//\n+// Preconditions: fd.mu must be held.\nfunc (fd *DeviceFD) sendError(ctx context.Context, errno int32, unique linux.FUSEOpID) error {\n// Return the error to the calling task.\noutHdrLen := uint32((*linux.FUSEHeaderOut)(nil).SizeBytes())\n" } ]
Go
Apache License 2.0
google/gvisor
Fix FUSE connection control lock ordering and race in unit test
259,853
15.09.2020 14:25:31
25,200
99fca1bf9af0c3fb851bd4c6bf7d16d9c9e44458
test/fuse: clean up
[ { "change_type": "MODIFY", "old_path": "test/util/fuse_util.cc", "new_path": "test/util/fuse_util.cc", "diff": "@@ -57,7 +57,7 @@ fuse_entry_out DefaultEntryOut(mode_t mode, uint64_t node_id, uint64_t size) {\n.attr = DefaultFuseAttr(mode, node_id, size),\n};\nreturn default_entry_out;\n-};\n+}\n} // namespace testing\n} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
test/fuse: clean up
259,913
16.09.2020 01:34:28
0
26879c32b8b48b6c066f1a5ba2c787e7061dabae
FUSE readdir test fix ino initialization
[ { "change_type": "MODIFY", "old_path": "test/fuse/linux/readdir_test.cc", "new_path": "test/fuse/linux/readdir_test.cc", "diff": "@@ -41,13 +41,14 @@ namespace {\nclass ReaddirTest : public FuseTest {\npublic:\n- void fill_fuse_dirent(char *buf, const char *name) {\n+ void fill_fuse_dirent(char *buf, const char *name, uint64_t ino) {\nsize_t namelen = strlen(name);\nsize_t entlen = FUSE_NAME_OFFSET + namelen;\nsize_t entlen_padded = FUSE_DIRENT_ALIGN(entlen);\nstruct fuse_dirent *dirent;\ndirent = reinterpret_cast<struct fuse_dirent *>(buf);\n+ dirent->ino = ino;\ndirent->namelen = namelen;\nmemcpy(dirent->name, name, namelen);\nmemset(dirent->name + namelen, 0, entlen_padded - entlen);\n@@ -61,11 +62,12 @@ TEST_F(ReaddirTest, SingleEntry) {\nconst std::string test_dir_path =\nJoinPath(mount_point_.path().c_str(), test_dir_name_);\n+ const uint64_t ino_dir = 1024;\n// We need to make sure the test dir is a directory that can be found.\nmode_t expected_mode =\nS_IFDIR | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;\nstruct fuse_attr dir_attr = {\n- .ino = 1,\n+ .ino = ino_dir,\n.size = 512,\n.blocks = 4,\n.mode = expected_mode,\n@@ -124,11 +126,12 @@ TEST_F(ReaddirTest, SingleEntry) {\nstd::vector<char> readdir_payload_vec(readdir_payload_size);\nchar *readdir_payload = readdir_payload_vec.data();\n- fill_fuse_dirent(readdir_payload, dot.c_str());\n- fill_fuse_dirent(readdir_payload + dot_file_dirent_size, dot_dot.c_str());\n+ // Use fake ino for other directories.\n+ fill_fuse_dirent(readdir_payload, dot.c_str(), ino_dir-2);\n+ fill_fuse_dirent(readdir_payload + dot_file_dirent_size, dot_dot.c_str(), ino_dir-1);\nfill_fuse_dirent(\nreaddir_payload + dot_file_dirent_size + dot_dot_file_dirent_size,\n- test_file.c_str());\n+ test_file.c_str(), ino_dir);\nstruct fuse_out_header readdir_header = {\n.len = uint32_t(sizeof(struct fuse_out_header) + readdir_payload_size),\n" } ]
Go
Apache License 2.0
google/gvisor
FUSE readdir test fix ino initialization
259,913
16.09.2020 17:39:55
0
70cf503b4c3653df8253438a8873a5d3ebb688e3
fuse: fix FUSE_RELEASE reply handling fix
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/connection.go", "new_path": "pkg/sentry/fsimpl/fuse/connection.go", "diff": "@@ -110,7 +110,7 @@ type connection struct {\n//\n// We call the \"background\" requests in unix term as async requests.\n// The \"async requests\" in unix term is our async requests that expect a reply,\n- // i.e. `!requestOptions.noReply`\n+ // i.e. `!request.noReply`\n// asyncMu protects the async request fields.\nasyncMu sync.Mutex\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/dev.go", "new_path": "pkg/sentry/fsimpl/fuse/dev.go", "diff": "@@ -309,10 +309,6 @@ func (fd *DeviceFD) writeLocked(ctx context.Context, src usermem.IOSequence, opt\nfut, ok := fd.completions[hdr.Unique]\nif !ok {\n- if fut.hdr.Unique == linux.FUSE_RELEASE {\n- // Currently we simply discard the reply for FUSE_RELEASE.\n- return n + src.NumBytes(), nil\n- }\n// Server sent us a response for a request we never sent,\n// or for which we already received a reply (e.g. aborted), an unlikely event.\nreturn 0, syserror.EINVAL\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/file.go", "new_path": "pkg/sentry/fsimpl/fuse/file.go", "diff": "@@ -89,7 +89,7 @@ func (fd *fileDescription) Release(ctx context.Context) {\n// No way to invoke Call() with an errored request.\nreturn\n}\n- req.noReply = true\n+ // The reply will be ignored since no callback is defined in asyncCallBack().\nconn.CallAsync(kernelTask, req)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
fuse: fix FUSE_RELEASE reply handling fix #3963
259,913
16.09.2020 17:44:06
0
c4c302a27e5811ce04bb904686e657c9ed830a44
fuse: fix data race in fusefs Release() fix
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/connection_control.go", "new_path": "pkg/sentry/fsimpl/fuse/connection_control.go", "diff": "@@ -189,10 +189,9 @@ func (conn *connection) initProcessReply(out *linux.FUSEInitOut, hasSysAdminCap\n// Abort this FUSE connection.\n// It tries to acquire conn.fd.mu, conn.lock, conn.bgLock in order.\n// All possible requests waiting or blocking will be aborted.\n+//\n+// Preconditions: conn.fd.mu is locked.\nfunc (conn *connection) Abort(ctx context.Context) {\n- conn.fd.mu.Lock()\n- defer conn.fd.mu.Unlock()\n-\nconn.mu.Lock()\nconn.asyncMu.Lock()\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "new_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "diff": "@@ -225,12 +225,13 @@ func newFUSEFilesystem(ctx context.Context, devMinor uint32, opts *filesystemOpt\n// Release implements vfs.FilesystemImpl.Release.\nfunc (fs *filesystem) Release(ctx context.Context) {\n+ fs.conn.fd.mu.Lock()\n+\nfs.umounted = true\nfs.conn.Abort(ctx)\n-\n- fs.conn.fd.mu.Lock()\n// Notify all the waiters on this fd.\nfs.conn.fd.waitQueue.Notify(waiter.EventIn)\n+\nfs.conn.fd.mu.Unlock()\nfs.Filesystem.VFSFilesystem().VirtualFilesystem().PutAnonBlockDevMinor(fs.devMinor)\n" } ]
Go
Apache License 2.0
google/gvisor
fuse: fix data race in fusefs Release() fix #3956
259,907
16.09.2020 13:46:32
25,200
0356c7ef32dfcc05b1f5e7f242a022883a9ba816
[runtime tests] Add documentation. Added a README describing what these tests are, how they work and how to run them locally. Also reorganized the exclude files into a directory.
[ { "change_type": "MODIFY", "old_path": "test/runtimes/BUILD", "new_path": "test/runtimes/BUILD", "diff": "@@ -5,7 +5,7 @@ package(licenses = [\"notice\"])\nruntime_test(\nname = \"go1.12\",\n- exclude_file = \"exclude_go1.12.csv\",\n+ exclude_file = \"exclude/go1.12.csv\",\nlang = \"go\",\nshard_count = 8,\n)\n@@ -13,28 +13,28 @@ runtime_test(\nruntime_test(\nname = \"java11\",\nbatch = 100,\n- exclude_file = \"exclude_java11.csv\",\n+ exclude_file = \"exclude/java11.csv\",\nlang = \"java\",\nshard_count = 16,\n)\nruntime_test(\nname = \"nodejs12.4.0\",\n- exclude_file = \"exclude_nodejs12.4.0.csv\",\n+ exclude_file = \"exclude/nodejs12.4.0.csv\",\nlang = \"nodejs\",\nshard_count = 8,\n)\nruntime_test(\nname = \"php7.3.6\",\n- exclude_file = \"exclude_php7.3.6.csv\",\n+ exclude_file = \"exclude/php7.3.6.csv\",\nlang = \"php\",\nshard_count = 8,\n)\nruntime_test(\nname = \"python3.7.3\",\n- exclude_file = \"exclude_python3.7.3.csv\",\n+ exclude_file = \"exclude/python3.7.3.csv\",\nlang = \"python\",\nshard_count = 8,\n)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/runtimes/README.md", "diff": "+# gVisor Runtime Tests\n+\n+App Engine uses gvisor to sandbox application containers. The runtime tests aim\n+to test `runsc` compatibility with these\n+[standard runtimes](https://cloud.google.com/appengine/docs/standard/runtimes).\n+The test itself runs the language-defined tests inside the sandboxed standard\n+runtime container.\n+\n+Note: [Ruby runtime](https://cloud.google.com/appengine/docs/standard/ruby) is\n+currently in beta mode and so we do not run tests for it yet.\n+\n+### Testing Locally\n+\n+To run runtime tests individually from a given runtime, use the following table.\n+\n+Language | Version | Download Image | Run Test(s)\n+-------- | ------- | ------------------------------------------- | -----------\n+Go | 1.12 | `make -C images load-runtimes_go1.12` | If the test name ends with `.go`, it is an on-disk test: <br> `docker run --runtime=runsc -it gvisor.dev/images/runtimes/go1.12 ( cd /usr/local/go/test ; go run run.go -v -- <TEST_NAME>... )` <br> Otherwise it is a tool test: <br> `docker run --runtime=runsc -it gvisor.dev/images/runtimes/go1.12 go tool dist test -v -no-rebuild ^TEST1$\\|^TEST2$...`\n+Java | 11 | `make -C images load-runtimes_java11` | `docker run --runtime=runsc -it gvisor.dev/images/runtimes/java11 jtreg -agentvm -dir:/root/test/jdk -noreport -timeoutFactor:20 -verbose:summary <TEST_NAME>...`\n+NodeJS | 12.4.0 | `make -C images load-runtimes_nodejs12.4.0` | `docker run --runtime=runsc -it gvisor.dev/images/runtimes/nodejs12.4.0 python tools/test.py --timeout=180 <TEST_NAME>...`\n+Php | 7.3.6 | `make -C images load-runtimes_php7.3.6` | `docker run --runtime=runsc -it gvisor.dev/images/runtimes/php7.3.6 make test \"TESTS=<TEST_NAME>...\"`\n+Python | 3.7.3 | `make -C images load-runtimes_python3.7.3` | `docker run --runtime=runsc -it gvisor.dev/images/runtimes/python3.7.3 ./python -m test <TEST_NAME>...`\n+\n+To run an entire runtime test locally, use the following table.\n+\n+Note: java runtime test take 1+ hours with 16 cores.\n+\n+Language | Version | Running the test suite\n+-------- | ------- | ----------------------------------------\n+Go | 1.12 | `make go1.12-runtime-tests{_vfs2}`\n+Java | 11 | `make java11-runtime-tests{_vfs2}`\n+NodeJS | 12.4.0 | `make nodejs12.4.0-runtime-tests{_vfs2}`\n+Php | 7.3.6 | `make php7.3.6-runtime-tests{_vfs2}`\n+Python | 3.7.3 | `make python3.7.3-runtime-tests{_vfs2}`\n+\n+#### Clean Up\n+\n+Sometimes when runtime tests fail or when the testing container itself crashes\n+unexpectedly, the containers are not removed or sometimes do not even exit. This\n+can cause some docker commands like `docker system prune` to hang forever.\n+\n+Here are some helpful commands (should be executed in order):\n+\n+```bash\n+docker ps -a # Lists all docker processes; useful when investigating hanging containers.\n+docker kill $(docker ps -a -q) # Kills all running containers.\n+docker rm $(docker ps -a -q) # Removes all exited containers.\n+docker system prune # Remove unused data.\n+```\n+\n+### Testing Infrastructure\n+\n+There are 3 components to this tests infrastructure:\n+\n+- [`runner`](runner) - This is the test entrypoint. This is the binary is\n+ invoked by `bazel test`. The runner spawns the target runtime container\n+ using `runsc` and then copies over the `proctor` binary into the container.\n+- [`proctor`](proctor) - This binary acts as our agent inside the container\n+ which communicates with the runner and actually executes tests.\n+- [`exclude`](exclude) - Holds a CSV file for each language runtime containing\n+ the full path of tests that should be excluded from running along with a\n+ reason for exclusion.\n" }, { "change_type": "RENAME", "old_path": "test/runtimes/exclude_go1.12.csv", "new_path": "test/runtimes/exclude/go1.12.csv", "diff": "" }, { "change_type": "RENAME", "old_path": "test/runtimes/exclude_java11.csv", "new_path": "test/runtimes/exclude/java11.csv", "diff": "" }, { "change_type": "RENAME", "old_path": "test/runtimes/exclude_nodejs12.4.0.csv", "new_path": "test/runtimes/exclude/nodejs12.4.0.csv", "diff": "" }, { "change_type": "RENAME", "old_path": "test/runtimes/exclude_php7.3.6.csv", "new_path": "test/runtimes/exclude/php7.3.6.csv", "diff": "" }, { "change_type": "RENAME", "old_path": "test/runtimes/exclude_python3.7.3.csv", "new_path": "test/runtimes/exclude/python3.7.3.csv", "diff": "" } ]
Go
Apache License 2.0
google/gvisor
[runtime tests] Add documentation. Added a README describing what these tests are, how they work and how to run them locally. Also reorganized the exclude files into a directory. PiperOrigin-RevId: 332079697
260,003
16.09.2020 14:10:58
25,200
666397c5c82ee18a776491919312d19cfe6d4a07
Gracefully translate unknown errno. Neither POSIX.1 nor Linux defines an upperbound for errno.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/rawfile/BUILD", "new_path": "pkg/tcpip/link/rawfile/BUILD", "diff": "-load(\"//tools:defs.bzl\", \"go_library\")\n+load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\npackage(licenses = [\"notice\"])\n@@ -18,3 +18,14 @@ go_library(\n\"@org_golang_x_sys//unix:go_default_library\",\n],\n)\n+\n+go_test(\n+ name = \"rawfile_test\",\n+ srcs = [\n+ \"errors_test.go\",\n+ ],\n+ library = \"rawfile\",\n+ deps = [\n+ \"//pkg/tcpip\",\n+ ],\n+)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/rawfile/errors.go", "new_path": "pkg/tcpip/link/rawfile/errors.go", "diff": "@@ -31,11 +31,13 @@ var translations [maxErrno]*tcpip.Error\n// *tcpip.Error.\n//\n// Valid, but unrecognized errnos will be translated to\n-// tcpip.ErrInvalidEndpointState (EINVAL). Panics on invalid errnos.\n+// tcpip.ErrInvalidEndpointState (EINVAL).\nfunc TranslateErrno(e syscall.Errno) *tcpip.Error {\n+ if e > 0 && e < syscall.Errno(len(translations)) {\nif err := translations[e]; err != nil {\nreturn err\n}\n+ }\nreturn tcpip.ErrInvalidEndpointState\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/tcpip/link/rawfile/errors_test.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// +build linux\n+\n+package rawfile\n+\n+import (\n+ \"syscall\"\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+)\n+\n+func TestTranslateErrno(t *testing.T) {\n+ for _, test := range []struct {\n+ errno syscall.Errno\n+ translated *tcpip.Error\n+ }{\n+ {\n+ errno: syscall.Errno(0),\n+ translated: tcpip.ErrInvalidEndpointState,\n+ },\n+ {\n+ errno: syscall.Errno(maxErrno),\n+ translated: tcpip.ErrInvalidEndpointState,\n+ },\n+ {\n+ errno: syscall.Errno(514),\n+ translated: tcpip.ErrInvalidEndpointState,\n+ },\n+ {\n+ errno: syscall.EEXIST,\n+ translated: tcpip.ErrDuplicateAddress,\n+ },\n+ } {\n+ got := TranslateErrno(test.errno)\n+ if got != test.translated {\n+ t.Errorf(\"TranslateErrno(%q) = %q, want %q\", test.errno, got, test.translated)\n+ }\n+ }\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Gracefully translate unknown errno. Neither POSIX.1 nor Linux defines an upperbound for errno. PiperOrigin-RevId: 332085017
260,001
16.09.2020 14:43:37
25,200
3749e70a693007b706fb06529ab95d910a251ba6
Implement PRead for verity fs PRead is implemented by read from the underlying file in blocks, and verify each block. The verified contents are saved into the output buffer.
[ { "change_type": "MODIFY", "old_path": "pkg/merkletree/merkletree.go", "new_path": "pkg/merkletree/merkletree.go", "diff": "@@ -225,9 +225,9 @@ func Generate(data io.ReadSeeker, dataSize int64, treeReader io.ReadSeeker, tree\n// Verify will modify the cursor for data, but always restores it to its\n// original position upon exit. The cursor for tree is modified and not\n// restored.\n-func Verify(w io.Writer, data, tree io.ReadSeeker, dataSize int64, readOffset int64, readSize int64, expectedRoot []byte, dataAndTreeInSameFile bool) error {\n+func Verify(w io.Writer, data, tree io.ReadSeeker, dataSize int64, readOffset int64, readSize int64, expectedRoot []byte, dataAndTreeInSameFile bool) (int64, error) {\nif readSize <= 0 {\n- return fmt.Errorf(\"Unexpected read size: %d\", readSize)\n+ return 0, fmt.Errorf(\"Unexpected read size: %d\", readSize)\n}\nlayout := InitLayout(int64(dataSize), dataAndTreeInSameFile)\n@@ -240,29 +240,30 @@ func Verify(w io.Writer, data, tree io.ReadSeeker, dataSize int64, readOffset in\n// finishes.\norigOffset, err := data.Seek(0, io.SeekCurrent)\nif err != nil {\n- return fmt.Errorf(\"Find current data offset failed: %v\", err)\n+ return 0, fmt.Errorf(\"Find current data offset failed: %v\", err)\n}\ndefer data.Seek(origOffset, io.SeekStart)\n// Move to the first block that contains target data.\nif _, err := data.Seek(firstDataBlock*layout.blockSize, io.SeekStart); err != nil {\n- return fmt.Errorf(\"Seek to datablock start failed: %v\", err)\n+ return 0, fmt.Errorf(\"Seek to datablock start failed: %v\", err)\n}\nbuf := make([]byte, layout.blockSize)\nvar readErr error\n- bytesRead := 0\n+ total := int64(0)\nfor i := firstDataBlock; i <= lastDataBlock; i++ {\n// Read a block that includes all or part of target range in\n// input data.\n- bytesRead, readErr = data.Read(buf)\n+ bytesRead, err := data.Read(buf)\n+ readErr = err\n// If at the end of input data and all previous blocks are\n// verified, return the verified input data and EOF.\nif readErr == io.EOF && bytesRead == 0 {\nbreak\n}\nif readErr != nil && readErr != io.EOF {\n- return fmt.Errorf(\"Read from data failed: %v\", err)\n+ return 0, fmt.Errorf(\"Read from data failed: %v\", err)\n}\n// If this is the end of file, zero the remaining bytes in buf,\n// otherwise they are still from the previous block.\n@@ -274,7 +275,7 @@ func Verify(w io.Writer, data, tree io.ReadSeeker, dataSize int64, readOffset in\n}\n}\nif err := verifyBlock(tree, layout, buf, i, expectedRoot); err != nil {\n- return err\n+ return 0, err\n}\n// startOff is the beginning of the read range within the\n// current data block. Note that for all blocks other than the\n@@ -298,10 +299,14 @@ func Verify(w io.Writer, data, tree io.ReadSeeker, dataSize int64, readOffset in\nif endOff > int64(bytesRead) {\nendOff = int64(bytesRead)\n}\n- w.Write(buf[startOff:endOff])\n+ n, err := w.Write(buf[startOff:endOff])\n+ if err != nil {\n+ return total, err\n+ }\n+ total += int64(n)\n}\n- return readErr\n+ return total, readErr\n}\n// verifyBlock verifies a block against tree. index is the number of block in\n" }, { "change_type": "MODIFY", "old_path": "pkg/merkletree/merkletree_test.go", "new_path": "pkg/merkletree/merkletree_test.go", "diff": "@@ -67,17 +67,17 @@ func TestLayout(t *testing.T) {\nt.Run(fmt.Sprintf(\"%d\", tc.dataSize), func(t *testing.T) {\nl := InitLayout(tc.dataSize, tc.dataAndTreeInSameFile)\nif l.blockSize != int64(usermem.PageSize) {\n- t.Errorf(\"got blockSize %d, want %d\", l.blockSize, usermem.PageSize)\n+ t.Errorf(\"Got blockSize %d, want %d\", l.blockSize, usermem.PageSize)\n}\nif l.digestSize != sha256DigestSize {\n- t.Errorf(\"got digestSize %d, want %d\", l.digestSize, sha256DigestSize)\n+ t.Errorf(\"Got digestSize %d, want %d\", l.digestSize, sha256DigestSize)\n}\nif l.numLevels() != len(tc.expectedLevelOffset) {\n- t.Errorf(\"got levels %d, want %d\", l.numLevels(), len(tc.expectedLevelOffset))\n+ t.Errorf(\"Got levels %d, want %d\", l.numLevels(), len(tc.expectedLevelOffset))\n}\nfor i := 0; i < l.numLevels() && i < len(tc.expectedLevelOffset); i++ {\nif l.levelOffset[i] != tc.expectedLevelOffset[i] {\n- t.Errorf(\"got levelStart[%d] %d, want %d\", i, l.levelOffset[i], tc.expectedLevelOffset[i])\n+ t.Errorf(\"Got levelStart[%d] %d, want %d\", i, l.levelOffset[i], tc.expectedLevelOffset[i])\n}\n}\n})\n@@ -169,11 +169,11 @@ func TestGenerate(t *testing.T) {\n}, int64(len(tc.data)), &tree, &tree, dataAndTreeInSameFile)\n}\nif err != nil {\n- t.Fatalf(\"got err: %v, want nil\", err)\n+ t.Fatalf(\"Got err: %v, want nil\", err)\n}\nif !bytes.Equal(root, tc.expectedRoot) {\n- t.Errorf(\"got root: %v, want %v\", root, tc.expectedRoot)\n+ t.Errorf(\"Got root: %v, want %v\", root, tc.expectedRoot)\n}\n}\n})\n@@ -334,14 +334,21 @@ func TestVerify(t *testing.T) {\nvar buf bytes.Buffer\ndata[tc.modifyByte] ^= 1\nif tc.shouldSucceed {\n- if err := Verify(&buf, bytes.NewReader(data), &tree, tc.dataSize, tc.verifyStart, tc.verifySize, root, dataAndTreeInSameFile); err != nil && err != io.EOF {\n+ n, err := Verify(&buf, bytes.NewReader(data), &tree, tc.dataSize, tc.verifyStart, tc.verifySize, root, dataAndTreeInSameFile)\n+ if err != nil && err != io.EOF {\nt.Errorf(\"Verification failed when expected to succeed: %v\", err)\n}\n- if int64(buf.Len()) != tc.verifySize || !bytes.Equal(data[tc.verifyStart:tc.verifyStart+tc.verifySize], buf.Bytes()) {\n- t.Errorf(\"Incorrect output from Verify\")\n+ if n != tc.verifySize {\n+ t.Errorf(\"Got Verify output size %d, want %d\", n, tc.verifySize)\n+ }\n+ if int64(buf.Len()) != tc.verifySize {\n+ t.Errorf(\"Got Verify output buf size %d, want %d,\", buf.Len(), tc.verifySize)\n+ }\n+ if !bytes.Equal(data[tc.verifyStart:tc.verifyStart+tc.verifySize], buf.Bytes()) {\n+ t.Errorf(\"Incorrect output buf from Verify\")\n}\n} else {\n- if err := Verify(&buf, bytes.NewReader(data), &tree, tc.dataSize, tc.verifyStart, tc.verifySize, root, dataAndTreeInSameFile); err == nil {\n+ if _, err := Verify(&buf, bytes.NewReader(data), &tree, tc.dataSize, tc.verifyStart, tc.verifySize, root, dataAndTreeInSameFile); err == nil {\nt.Errorf(\"Verification succeeded when expected to fail\")\n}\n}\n@@ -382,14 +389,21 @@ func TestVerifyRandom(t *testing.T) {\nvar buf bytes.Buffer\n// Checks that the random portion of data from the original data is\n// verified successfully.\n- if err := Verify(&buf, bytes.NewReader(data), &tree, dataSize, start, size, root, dataAndTreeInSameFile); err != nil && err != io.EOF {\n+ n, err := Verify(&buf, bytes.NewReader(data), &tree, dataSize, start, size, root, dataAndTreeInSameFile)\n+ if err != nil && err != io.EOF {\nt.Errorf(\"Verification failed for correct data: %v\", err)\n}\nif size > dataSize-start {\nsize = dataSize - start\n}\n- if int64(buf.Len()) != size || !bytes.Equal(data[start:start+size], buf.Bytes()) {\n- t.Errorf(\"Incorrect output from Verify\")\n+ if n != size {\n+ t.Errorf(\"Got Verify output size %d, want %d\", n, size)\n+ }\n+ if int64(buf.Len()) != size {\n+ t.Errorf(\"Got Verify output buf size %d, want %d\", buf.Len(), size)\n+ }\n+ if !bytes.Equal(data[start:start+size], buf.Bytes()) {\n+ t.Errorf(\"Incorrect output buf from Verify\")\n}\nbuf.Reset()\n@@ -397,7 +411,7 @@ func TestVerifyRandom(t *testing.T) {\nrandBytePos := rand.Int63n(size)\ndata[start+randBytePos] ^= 1\n- if err := Verify(&buf, bytes.NewReader(data), &tree, dataSize, start, size, root, dataAndTreeInSameFile); err == nil {\n+ if _, err := Verify(&buf, bytes.NewReader(data), &tree, dataSize, start, size, root, dataAndTreeInSameFile); err == nil {\nt.Errorf(\"Verification succeeded for modified data\")\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/verity/filesystem.go", "new_path": "pkg/sentry/fsimpl/verity/filesystem.go", "diff": "@@ -192,10 +192,7 @@ func (fs *filesystem) verifyChild(ctx context.Context, parent *dentry, child *de\n// contains the expected xattrs. If the file or the xattr does not\n// exist, it indicates unexpected modifications to the file system.\nif err == syserror.ENOENT || err == syserror.ENODATA {\n- if noCrashOnVerificationFailure {\n- return nil, err\n- }\n- panic(fmt.Sprintf(\"Failed to get xattr %s for %s: %v\", merkleOffsetInParentXattr, childPath, err))\n+ return nil, alertIntegrityViolation(err, fmt.Sprintf(\"Failed to get xattr %s for %s: %v\", merkleOffsetInParentXattr, childPath, err))\n}\nif err != nil {\nreturn nil, err\n@@ -204,10 +201,7 @@ func (fs *filesystem) verifyChild(ctx context.Context, parent *dentry, child *de\n// unexpected modifications to the file system.\noffset, err := strconv.Atoi(off)\nif err != nil {\n- if noCrashOnVerificationFailure {\n- return nil, syserror.EINVAL\n- }\n- panic(fmt.Sprintf(\"Failed to convert xattr %s for %s to int: %v\", merkleOffsetInParentXattr, childPath, err))\n+ return nil, alertIntegrityViolation(err, fmt.Sprintf(\"Failed to convert xattr %s for %s to int: %v\", merkleOffsetInParentXattr, childPath, err))\n}\n// Open parent Merkle tree file to read and verify child's root hash.\n@@ -221,10 +215,7 @@ func (fs *filesystem) verifyChild(ctx context.Context, parent *dentry, child *de\n// The parent Merkle tree file should have been created. If it's\n// missing, it indicates an unexpected modification to the file system.\nif err == syserror.ENOENT {\n- if noCrashOnVerificationFailure {\n- return nil, err\n- }\n- panic(fmt.Sprintf(\"Failed to open parent Merkle file for %s: %v\", childPath, err))\n+ return nil, alertIntegrityViolation(err, fmt.Sprintf(\"Failed to open parent Merkle file for %s: %v\", childPath, err))\n}\nif err != nil {\nreturn nil, err\n@@ -242,10 +233,7 @@ func (fs *filesystem) verifyChild(ctx context.Context, parent *dentry, child *de\n// contains the expected xattrs. If the file or the xattr does not\n// exist, it indicates unexpected modifications to the file system.\nif err == syserror.ENOENT || err == syserror.ENODATA {\n- if noCrashOnVerificationFailure {\n- return nil, err\n- }\n- panic(fmt.Sprintf(\"Failed to get xattr %s for %s: %v\", merkleSizeXattr, childPath, err))\n+ return nil, alertIntegrityViolation(err, fmt.Sprintf(\"Failed to get xattr %s for %s: %v\", merkleSizeXattr, childPath, err))\n}\nif err != nil {\nreturn nil, err\n@@ -255,10 +243,7 @@ func (fs *filesystem) verifyChild(ctx context.Context, parent *dentry, child *de\n// unexpected modifications to the file system.\nparentSize, err := strconv.Atoi(dataSize)\nif err != nil {\n- if noCrashOnVerificationFailure {\n- return nil, syserror.EINVAL\n- }\n- panic(fmt.Sprintf(\"Failed to convert xattr %s for %s to int: %v\", merkleSizeXattr, childPath, err))\n+ return nil, alertIntegrityViolation(syserror.EINVAL, fmt.Sprintf(\"Failed to convert xattr %s for %s to int: %v\", merkleSizeXattr, childPath, err))\n}\nfdReader := vfs.FileReadWriteSeeker{\n@@ -270,11 +255,8 @@ func (fs *filesystem) verifyChild(ctx context.Context, parent *dentry, child *de\n// contain the root hash of the children in the parent Merkle tree when\n// Verify returns with success.\nvar buf bytes.Buffer\n- if err := merkletree.Verify(&buf, &fdReader, &fdReader, int64(parentSize), int64(offset), int64(merkletree.DigestSize()), parent.rootHash, true /* dataAndTreeInSameFile */); err != nil && err != io.EOF {\n- if noCrashOnVerificationFailure {\n- return nil, syserror.EIO\n- }\n- panic(fmt.Sprintf(\"Verification for %s failed: %v\", childPath, err))\n+ if _, err := merkletree.Verify(&buf, &fdReader, &fdReader, int64(parentSize), int64(offset), int64(merkletree.DigestSize()), parent.rootHash, true /* dataAndTreeInSameFile */); err != nil && err != io.EOF {\n+ return nil, alertIntegrityViolation(syserror.EIO, fmt.Sprintf(\"Verification for %s failed: %v\", childPath, err))\n}\n// Cache child root hash when it's verified the first time.\n@@ -370,10 +352,7 @@ func (fs *filesystem) lookupAndVerifyLocked(ctx context.Context, parent *dentry,\n// corresponding Merkle tree is found. This indicates an\n// unexpected modification to the file system that\n// removed/renamed the child.\n- if noCrashOnVerificationFailure {\n- return nil, childErr\n- }\n- panic(fmt.Sprintf(\"Target file %s is expected but missing\", parentPath+\"/\"+name))\n+ return nil, alertIntegrityViolation(childErr, fmt.Sprintf(\"Target file %s is expected but missing\", parentPath+\"/\"+name))\n} else if childErr == nil && childMerkleErr == syserror.ENOENT {\n// If in allowRuntimeEnable mode, and the Merkle tree file is\n// not created yet, we create an empty Merkle tree file, so that\n@@ -409,10 +388,7 @@ func (fs *filesystem) lookupAndVerifyLocked(ctx context.Context, parent *dentry,\n// If runtime enable is not allowed. This indicates an\n// unexpected modification to the file system that\n// removed/renamed the Merkle tree file.\n- if noCrashOnVerificationFailure {\n- return nil, childMerkleErr\n- }\n- panic(fmt.Sprintf(\"Expected Merkle file for target %s but none found\", parentPath+\"/\"+name))\n+ return nil, alertIntegrityViolation(childMerkleErr, fmt.Sprintf(\"Expected Merkle file for target %s but none found\", parentPath+\"/\"+name))\n}\n} else if childErr == syserror.ENOENT && childMerkleErr == syserror.ENOENT {\n// Both the child and the corresponding Merkle tree are missing.\n@@ -421,7 +397,7 @@ func (fs *filesystem) lookupAndVerifyLocked(ctx context.Context, parent *dentry,\n// TODO(b/167752508): Investigate possible ways to differentiate\n// cases that both files are deleted from cases that they never\n// exist in the file system.\n- panic(fmt.Sprintf(\"Failed to find file %s\", parentPath+\"/\"+name))\n+ return nil, alertIntegrityViolation(childErr, fmt.Sprintf(\"Failed to find file %s\", parentPath+\"/\"+name))\n}\nmask := uint32(linux.STATX_TYPE | linux.STATX_MODE | linux.STATX_UID | linux.STATX_GID)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/verity/verity.go", "new_path": "pkg/sentry/fsimpl/verity/verity.go", "diff": "package verity\nimport (\n+ \"fmt\"\n\"strconv\"\n\"sync/atomic\"\n@@ -29,7 +30,6 @@ import (\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/marshal/primitive\"\n-\n\"gvisor.dev/gvisor/pkg/merkletree\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\nfslock \"gvisor.dev/gvisor/pkg/sentry/fs/lock\"\n@@ -135,6 +135,16 @@ func (FilesystemType) Name() string {\nreturn Name\n}\n+// alertIntegrityViolation alerts a violation of integrity, which usually means\n+// unexpected modification to the file system is detected. In\n+// noCrashOnVerificationFailure mode, it returns an error, otherwise it panic.\n+func alertIntegrityViolation(err error, msg string) error {\n+ if noCrashOnVerificationFailure {\n+ return err\n+ }\n+ panic(msg)\n+}\n+\n// GetFilesystem implements vfs.FilesystemType.GetFilesystem.\nfunc (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.VirtualFilesystem, creds *auth.Credentials, source string, opts vfs.GetFilesystemOptions) (*vfs.Filesystem, *vfs.Dentry, error) {\niopts, ok := opts.InternalData.(InternalFilesystemOptions)\n@@ -204,15 +214,12 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nreturn nil, nil, err\n}\n} else if err != nil {\n- // Failed to get dentry for the root Merkle file. This indicates\n- // an attack that removed/renamed the root Merkle file, or it's\n- // never generated.\n- if noCrashOnVerificationFailure {\n+ // Failed to get dentry for the root Merkle file. This\n+ // indicates an unexpected modification that removed/renamed\n+ // the root Merkle file, or it's never generated.\nfs.vfsfs.DecRef(ctx)\nd.DecRef(ctx)\n- return nil, nil, err\n- }\n- panic(\"Failed to find root Merkle file\")\n+ return nil, nil, alertIntegrityViolation(err, \"Failed to find root Merkle file\")\n}\nd.lowerMerkleVD = lowerMerkleVD\n@@ -618,6 +625,54 @@ func (fd *fileDescription) Ioctl(ctx context.Context, uio usermem.IO, args arch.\n}\n}\n+// PRead implements vfs.FileDescriptionImpl.PRead.\n+func (fd *fileDescription) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts vfs.ReadOptions) (int64, error) {\n+ // No need to verify if the file is not enabled yet in\n+ // allowRuntimeEnable mode.\n+ if fd.d.fs.allowRuntimeEnable && len(fd.d.rootHash) == 0 {\n+ return fd.lowerFD.PRead(ctx, dst, offset, opts)\n+ }\n+\n+ // dataSize is the size of the whole file.\n+ dataSize, err := fd.merkleReader.GetXattr(ctx, &vfs.GetXattrOptions{\n+ Name: merkleSizeXattr,\n+ Size: sizeOfInt32,\n+ })\n+\n+ // The Merkle tree file for the child should have been created and\n+ // contains the expected xattrs. If the xattr does not exist, it\n+ // indicates unexpected modifications to the file system.\n+ if err == syserror.ENODATA {\n+ return 0, alertIntegrityViolation(err, fmt.Sprintf(\"Failed to get xattr %s: %v\", merkleSizeXattr, err))\n+ }\n+ if err != nil {\n+ return 0, err\n+ }\n+\n+ // The dataSize xattr should be an integer. If it's not, it indicates\n+ // unexpected modifications to the file system.\n+ size, err := strconv.Atoi(dataSize)\n+ if err != nil {\n+ return 0, alertIntegrityViolation(err, fmt.Sprintf(\"Failed to convert xattr %s to int: %v\", merkleSizeXattr, err))\n+ }\n+\n+ dataReader := vfs.FileReadWriteSeeker{\n+ FD: fd.lowerFD,\n+ Ctx: ctx,\n+ }\n+\n+ merkleReader := vfs.FileReadWriteSeeker{\n+ FD: fd.merkleReader,\n+ Ctx: ctx,\n+ }\n+\n+ n, err := merkletree.Verify(dst.Writer(ctx), &dataReader, &merkleReader, int64(size), offset, dst.NumBytes(), fd.d.rootHash, false /* dataAndTreeInSameFile */)\n+ if err != nil {\n+ return 0, alertIntegrityViolation(syserror.EINVAL, fmt.Sprintf(\"Verification failed: %v\", err))\n+ }\n+ return n, err\n+}\n+\n// LockPOSIX implements vfs.FileDescriptionImpl.LockPOSIX.\nfunc (fd *fileDescription) LockPOSIX(ctx context.Context, uid fslock.UniqueID, t fslock.LockType, start, length uint64, whence int16, block fslock.Blocker) error {\nreturn fd.Locks().LockPOSIX(ctx, &fd.vfsfd, uid, t, start, length, whence, block)\n" } ]
Go
Apache License 2.0
google/gvisor
Implement PRead for verity fs PRead is implemented by read from the underlying file in blocks, and verify each block. The verified contents are saved into the output buffer. PiperOrigin-RevId: 332092267
260,001
16.09.2020 16:41:32
25,200
286830855552efb223afa500fbcfa532f33121c5
Implement OpenAt() for verity fs OpenAt() for verity fs is implemented by opening both the target file or directory and the corresponding Merkle tree file in the underlying file system. Generally they are only open for read. In allowRuntimeEnable mode, the Merkle tree file is also open for write.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/verity/filesystem.go", "new_path": "pkg/sentry/fsimpl/verity/filesystem.go", "diff": "@@ -19,6 +19,7 @@ import (\n\"fmt\"\n\"io\"\n\"strconv\"\n+ \"strings\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n@@ -556,8 +557,181 @@ func (fs *filesystem) MknodAt(ctx context.Context, rp *vfs.ResolvingPath, opts v\n// OpenAt implements vfs.FilesystemImpl.OpenAt.\nfunc (fs *filesystem) OpenAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n- //TODO(b/159261227): Implement OpenAt.\n- return nil, nil\n+ // Verity fs is read-only.\n+ if opts.Flags&(linux.O_WRONLY|linux.O_CREAT) != 0 {\n+ return nil, syserror.EROFS\n+ }\n+\n+ var ds *[]*dentry\n+ fs.renameMu.RLock()\n+ defer fs.renameMuRUnlockAndCheckDrop(ctx, &ds)\n+\n+ start := rp.Start().Impl().(*dentry)\n+ if rp.Done() {\n+ return start.openLocked(ctx, rp, &opts)\n+ }\n+\n+afterTrailingSymlink:\n+ parent, err := fs.walkParentDirLocked(ctx, rp, start, &ds)\n+ if err != nil {\n+ return nil, err\n+ }\n+\n+ // Check for search permission in the parent directory.\n+ if err := parent.checkPermissions(rp.Credentials(), vfs.MayExec); err != nil {\n+ return nil, err\n+ }\n+\n+ // Open existing child or follow symlink.\n+ parent.dirMu.Lock()\n+ child, err := fs.stepLocked(ctx, rp, parent, false /*mayFollowSymlinks*/, &ds)\n+ parent.dirMu.Unlock()\n+ if err != nil {\n+ return nil, err\n+ }\n+ if child.isSymlink() && rp.ShouldFollowSymlink() {\n+ target, err := child.readlink(ctx)\n+ if err != nil {\n+ return nil, err\n+ }\n+ if err := rp.HandleSymlink(target); err != nil {\n+ return nil, err\n+ }\n+ start = parent\n+ goto afterTrailingSymlink\n+ }\n+ return child.openLocked(ctx, rp, &opts)\n+}\n+\n+// Preconditions: fs.renameMu must be locked.\n+func (d *dentry) openLocked(ctx context.Context, rp *vfs.ResolvingPath, opts *vfs.OpenOptions) (*vfs.FileDescription, error) {\n+ // Users should not open the Merkle tree files. Those are for verity fs\n+ // use only.\n+ if strings.Contains(d.name, merklePrefix) {\n+ return nil, syserror.EPERM\n+ }\n+ ats := vfs.AccessTypesForOpenFlags(opts)\n+ if err := d.checkPermissions(rp.Credentials(), ats); err != nil {\n+ return nil, err\n+ }\n+\n+ // Verity fs is read-only.\n+ if ats&vfs.MayWrite != 0 {\n+ return nil, syserror.EROFS\n+ }\n+\n+ // Get the path to the target file. This is only used to provide path\n+ // information in failure case.\n+ path, err := d.fs.vfsfs.VirtualFilesystem().PathnameWithDeleted(ctx, d.fs.rootDentry.lowerVD, d.lowerVD)\n+ if err != nil {\n+ return nil, err\n+ }\n+\n+ // Open the file in the underlying file system.\n+ lowerFD, err := rp.VirtualFilesystem().OpenAt(ctx, d.fs.creds, &vfs.PathOperation{\n+ Root: d.lowerVD,\n+ Start: d.lowerVD,\n+ }, opts)\n+\n+ // The file should exist, as we succeeded in finding its dentry. If it's\n+ // missing, it indicates an unexpected modification to the file system.\n+ if err != nil {\n+ if err == syserror.ENOENT {\n+ return nil, alertIntegrityViolation(err, fmt.Sprintf(\"File %s expected but not found\", path))\n+ }\n+ return nil, err\n+ }\n+\n+ // lowerFD needs to be cleaned up if any error occurs. IncRef will be\n+ // called if a verity FD is successfully created.\n+ defer lowerFD.DecRef(ctx)\n+\n+ // Open the Merkle tree file corresponding to the current file/directory\n+ // to be used later for verifying Read/Walk.\n+ merkleReader, err := rp.VirtualFilesystem().OpenAt(ctx, d.fs.creds, &vfs.PathOperation{\n+ Root: d.lowerMerkleVD,\n+ Start: d.lowerMerkleVD,\n+ }, &vfs.OpenOptions{\n+ Flags: linux.O_RDONLY,\n+ })\n+\n+ // The Merkle tree file should exist, as we succeeded in finding its\n+ // dentry. If it's missing, it indicates an unexpected modification to\n+ // the file system.\n+ if err != nil {\n+ if err == syserror.ENOENT {\n+ return nil, alertIntegrityViolation(err, fmt.Sprintf(\"Merkle file for %s expected but not found\", path))\n+ }\n+ return nil, err\n+ }\n+\n+ // merkleReader needs to be cleaned up if any error occurs. IncRef will\n+ // be called if a verity FD is successfully created.\n+ defer merkleReader.DecRef(ctx)\n+\n+ lowerFlags := lowerFD.StatusFlags()\n+ lowerFDOpts := lowerFD.Options()\n+ var merkleWriter *vfs.FileDescription\n+ var parentMerkleWriter *vfs.FileDescription\n+\n+ // Only open the Merkle tree files for write if in allowRuntimeEnable\n+ // mode.\n+ if d.fs.allowRuntimeEnable {\n+ merkleWriter, err = rp.VirtualFilesystem().OpenAt(ctx, d.fs.creds, &vfs.PathOperation{\n+ Root: d.lowerMerkleVD,\n+ Start: d.lowerMerkleVD,\n+ }, &vfs.OpenOptions{\n+ Flags: linux.O_WRONLY | linux.O_APPEND,\n+ })\n+ if err != nil {\n+ if err == syserror.ENOENT {\n+ return nil, alertIntegrityViolation(err, fmt.Sprintf(\"Merkle file for %s expected but not found\", path))\n+ }\n+ return nil, err\n+ }\n+ // merkleWriter is cleaned up if any error occurs. IncRef will\n+ // be called if a verity FD is created successfully.\n+ defer merkleWriter.DecRef(ctx)\n+\n+ parentMerkleWriter, err = rp.VirtualFilesystem().OpenAt(ctx, d.fs.creds, &vfs.PathOperation{\n+ Root: d.parent.lowerMerkleVD,\n+ Start: d.parent.lowerMerkleVD,\n+ }, &vfs.OpenOptions{\n+ Flags: linux.O_WRONLY | linux.O_APPEND,\n+ })\n+ if err != nil {\n+ if err == syserror.ENOENT {\n+ parentPath, _ := d.fs.vfsfs.VirtualFilesystem().PathnameWithDeleted(ctx, d.fs.rootDentry.lowerVD, d.parent.lowerVD)\n+ return nil, alertIntegrityViolation(err, fmt.Sprintf(\"Merkle file for %s expected but not found\", parentPath))\n+ }\n+ return nil, err\n+ }\n+ // parentMerkleWriter is cleaned up if any error occurs. IncRef\n+ // will be called if a verity FD is created successfully.\n+ defer parentMerkleWriter.DecRef(ctx)\n+ }\n+\n+ fd := &fileDescription{\n+ d: d,\n+ lowerFD: lowerFD,\n+ merkleReader: merkleReader,\n+ merkleWriter: merkleWriter,\n+ parentMerkleWriter: parentMerkleWriter,\n+ isDir: d.isDir(),\n+ }\n+\n+ if err := fd.vfsfd.Init(fd, lowerFlags, rp.Mount(), &d.vfsd, &lowerFDOpts); err != nil {\n+ return nil, err\n+ }\n+ lowerFD.IncRef()\n+ merkleReader.IncRef()\n+ if merkleWriter != nil {\n+ merkleWriter.IncRef()\n+ }\n+ if parentMerkleWriter != nil {\n+ parentMerkleWriter.IncRef()\n+ }\n+ return &fd.vfsfd, err\n}\n// ReadlinkAt implements vfs.FilesystemImpl.ReadlinkAt.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/verity/verity.go", "new_path": "pkg/sentry/fsimpl/verity/verity.go", "diff": "@@ -557,7 +557,7 @@ func (fd *fileDescription) enableVerity(ctx context.Context, uio usermem.IO, arg\ndefer verityMu.Unlock()\nif fd.lowerFD == nil || fd.merkleReader == nil || fd.merkleWriter == nil || fd.parentMerkleWriter == nil {\n- panic(\"Unexpected verity fd: missing expected underlying fds\")\n+ return 0, alertIntegrityViolation(syserror.EIO, \"Unexpected verity fd: missing expected underlying fds\")\n}\nrootHash, dataSize, err := fd.generateMerkle(ctx)\n" } ]
Go
Apache License 2.0
google/gvisor
Implement OpenAt() for verity fs OpenAt() for verity fs is implemented by opening both the target file or directory and the corresponding Merkle tree file in the underlying file system. Generally they are only open for read. In allowRuntimeEnable mode, the Merkle tree file is also open for write. PiperOrigin-RevId: 332116423
259,992
17.09.2020 01:07:55
25,200
a11061d78a58ed75b10606d1a770b035ed944b66
Add VFS2 overlay support in runsc All tests under runsc are passing with overlay enabled. Updates
[ { "change_type": "MODIFY", "old_path": "runsc/boot/BUILD", "new_path": "runsc/boot/BUILD", "diff": "@@ -27,6 +27,7 @@ go_library(\n\"//pkg/abi\",\n\"//pkg/abi/linux\",\n\"//pkg/bpf\",\n+ \"//pkg/cleanup\",\n\"//pkg/context\",\n\"//pkg/control/server\",\n\"//pkg/cpuid\",\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/vfs.go", "new_path": "runsc/boot/vfs.go", "diff": "@@ -21,6 +21,7 @@ import (\nspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/cleanup\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/log\"\n@@ -168,26 +169,30 @@ func (c *containerMounter) mountAll(conf *config.Config, procArgs *kernel.Create\n}\nrootProcArgs.MountNamespaceVFS2 = mns\n- // Mount submounts.\n- if err := c.mountSubmountsVFS2(rootCtx, conf, mns, rootCreds); err != nil {\n- return nil, fmt.Errorf(\"mounting submounts vfs2: %w\", err)\n- }\n-\n- if c.root.Readonly || conf.Overlay {\n- // Switch to ReadOnly after all submounts were setup.\nroot := mns.Root()\ndefer root.DecRef(rootCtx)\n+ if root.Mount().ReadOnly() {\n+ // Switch to ReadWrite while we setup submounts.\n+ if err := c.k.VFS().SetMountReadOnly(root.Mount(), false); err != nil {\n+ return nil, fmt.Errorf(`failed to set mount at \"/\" readwrite: %w`, err)\n+ }\n+ // Restore back to ReadOnly at the end.\n+ defer func() {\nif err := c.k.VFS().SetMountReadOnly(root.Mount(), true); err != nil {\n- return nil, fmt.Errorf(`failed to set mount at \"/\" readonly: %v`, err)\n+ panic(fmt.Sprintf(`failed to restore mount at \"/\" back to readonly: %v`, err))\n}\n+ }()\n+ }\n+\n+ // Mount submounts.\n+ if err := c.mountSubmountsVFS2(rootCtx, conf, mns, rootCreds); err != nil {\n+ return nil, fmt.Errorf(\"mounting submounts vfs2: %w\", err)\n}\nreturn mns, nil\n}\n// createMountNamespaceVFS2 creates the container's root mount and namespace.\n-// The mount is created ReadWrite to allow mount point for submounts to be\n-// created. ** The caller is responsible to switch to ReadOnly if needed **\nfunc (c *containerMounter) createMountNamespaceVFS2(ctx context.Context, conf *config.Config, creds *auth.Credentials) (*vfs.MountNamespace, error) {\nfd := c.fds.remove()\ndata := p9MountData(fd, conf.FileAccess, true /* vfs2 */)\n@@ -201,21 +206,71 @@ func (c *containerMounter) createMountNamespaceVFS2(ctx context.Context, conf *c\nlog.Infof(\"Mounting root over 9P, ioFD: %d\", fd)\nopts := &vfs.MountOptions{\n- // Always mount as ReadWrite to allow other mounts on top of it. It'll be\n- // made ReadOnly in the caller (if needed).\n- ReadOnly: false,\n+ ReadOnly: c.root.Readonly,\nGetFilesystemOptions: vfs.GetFilesystemOptions{\nData: strings.Join(data, \",\"),\n},\nInternalMount: true,\n}\n- mns, err := c.k.VFS().NewMountNamespace(ctx, creds, \"\", gofer.Name, opts)\n+\n+ fsName := gofer.Name\n+ if conf.Overlay && !c.root.Readonly {\n+ log.Infof(\"Adding overlay on top of root\")\n+ var err error\n+ var cleanup func()\n+ opts, cleanup, err = c.configureOverlay(ctx, creds, opts, fsName)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"mounting root with overlay: %w\", err)\n+ }\n+ defer cleanup()\n+ fsName = overlay.Name\n+ }\n+\n+ mns, err := c.k.VFS().NewMountNamespace(ctx, creds, \"\", fsName, opts)\nif err != nil {\nreturn nil, fmt.Errorf(\"setting up mount namespace: %w\", err)\n}\nreturn mns, nil\n}\n+// configureOverlay mounts the lower layer using \"lowerOpts\", mounts the upper\n+// layer using tmpfs, and return overlay mount options. \"cleanup\" must be called\n+// after the options have been used to mount the overlay, to release refs on\n+// lower and upper mounts.\n+func (c *containerMounter) configureOverlay(ctx context.Context, creds *auth.Credentials, lowerOpts *vfs.MountOptions, lowerFSName string) (*vfs.MountOptions, func(), error) {\n+ // First copy options from lower layer to upper layer and overlay. Clear\n+ // filesystem specific options.\n+ upperOpts := *lowerOpts\n+ upperOpts.GetFilesystemOptions = vfs.GetFilesystemOptions{}\n+\n+ overlayOpts := *lowerOpts\n+ overlayOpts.GetFilesystemOptions = vfs.GetFilesystemOptions{}\n+\n+ // Next mount upper and lower. Upper is a tmpfs mount to keep all\n+ // modifications inside the sandbox.\n+ upper, err := c.k.VFS().MountDisconnected(ctx, creds, \"\" /* source */, tmpfs.Name, &upperOpts)\n+ if err != nil {\n+ return nil, nil, fmt.Errorf(\"failed to create upper layer for overlay, opts: %+v: %v\", upperOpts, err)\n+ }\n+ cu := cleanup.Make(func() { upper.DecRef(ctx) })\n+ defer cu.Clean()\n+\n+ // All writes go to the upper layer, be paranoid and make lower readonly.\n+ lowerOpts.ReadOnly = true\n+ lower, err := c.k.VFS().MountDisconnected(ctx, creds, \"\" /* source */, lowerFSName, lowerOpts)\n+ if err != nil {\n+ return nil, nil, err\n+ }\n+ cu.Add(func() { lower.DecRef(ctx) })\n+\n+ // Configure overlay with both layers.\n+ overlayOpts.GetFilesystemOptions.InternalData = overlay.FilesystemOptions{\n+ UpperRoot: vfs.MakeVirtualDentry(upper, upper.Root()),\n+ LowerRoots: []vfs.VirtualDentry{vfs.MakeVirtualDentry(lower, lower.Root())},\n+ }\n+ return &overlayOpts, cu.Release(), nil\n+}\n+\nfunc (c *containerMounter) mountSubmountsVFS2(ctx context.Context, conf *config.Config, mns *vfs.MountNamespace, creds *auth.Credentials) error {\nmounts, err := c.prepareMountsVFS2()\nif err != nil {\n@@ -245,7 +300,7 @@ func (c *containerMounter) mountSubmountsVFS2(ctx context.Context, conf *config.\nif mnt != nil && mnt.ReadOnly() {\n// Switch to ReadWrite while we setup submounts.\nif err := c.k.VFS().SetMountReadOnly(mnt, false); err != nil {\n- return fmt.Errorf(\"failed to set mount at %q readwrite: %v\", submount.Destination, err)\n+ return fmt.Errorf(\"failed to set mount at %q readwrite: %w\", submount.Destination, err)\n}\n// Restore back to ReadOnly at the end.\ndefer func() {\n@@ -297,14 +352,7 @@ func (c *containerMounter) prepareMountsVFS2() ([]mountAndFD, error) {\n}\nfunc (c *containerMounter) mountSubmountVFS2(ctx context.Context, conf *config.Config, mns *vfs.MountNamespace, creds *auth.Credentials, submount *mountAndFD) (*vfs.Mount, error) {\n- root := mns.Root()\n- defer root.DecRef(ctx)\n- target := &vfs.PathOperation{\n- Root: root,\n- Start: root,\n- Path: fspath.Parse(submount.Destination),\n- }\n- fsName, opts, err := c.getMountNameAndOptionsVFS2(conf, submount)\n+ fsName, opts, useOverlay, err := c.getMountNameAndOptionsVFS2(conf, submount)\nif err != nil {\nreturn nil, fmt.Errorf(\"mountOptions failed: %w\", err)\n}\n@@ -313,8 +361,27 @@ func (c *containerMounter) mountSubmountVFS2(ctx context.Context, conf *config.C\nreturn nil, nil\n}\n- if err := c.k.VFS().MakeSyntheticMountpoint(ctx, submount.Destination, root, creds); err != nil {\n- return nil, err\n+ if err := c.makeMountPoint(ctx, creds, mns, submount.Destination); err != nil {\n+ return nil, fmt.Errorf(\"creating mount point %q: %w\", submount.Destination, err)\n+ }\n+\n+ if useOverlay {\n+ log.Infof(\"Adding overlay on top of mount %q\", submount.Destination)\n+ var cleanup func()\n+ opts, cleanup, err = c.configureOverlay(ctx, creds, opts, fsName)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"mounting volume with overlay at %q: %w\", submount.Destination, err)\n+ }\n+ defer cleanup()\n+ fsName = overlay.Name\n+ }\n+\n+ root := mns.Root()\n+ defer root.DecRef(ctx)\n+ target := &vfs.PathOperation{\n+ Root: root,\n+ Start: root,\n+ Path: fspath.Parse(submount.Destination),\n}\nmnt, err := c.k.VFS().MountAt(ctx, creds, \"\", target, fsName, opts)\nif err != nil {\n@@ -326,8 +393,9 @@ func (c *containerMounter) mountSubmountVFS2(ctx context.Context, conf *config.C\n// getMountNameAndOptionsVFS2 retrieves the fsName, opts, and useOverlay values\n// used for mounts.\n-func (c *containerMounter) getMountNameAndOptionsVFS2(conf *config.Config, m *mountAndFD) (string, *vfs.MountOptions, error) {\n+func (c *containerMounter) getMountNameAndOptionsVFS2(conf *config.Config, m *mountAndFD) (string, *vfs.MountOptions, bool, error) {\nfsName := m.Type\n+ useOverlay := false\nvar data []string\n// Find filesystem name and FS specific data field.\n@@ -342,7 +410,7 @@ func (c *containerMounter) getMountNameAndOptionsVFS2(conf *config.Config, m *mo\nvar err error\ndata, err = parseAndFilterOptions(m.Options, tmpfsAllowedData...)\nif err != nil {\n- return \"\", nil, err\n+ return \"\", nil, false, err\n}\ncase bind:\n@@ -350,13 +418,16 @@ func (c *containerMounter) getMountNameAndOptionsVFS2(conf *config.Config, m *mo\nif m.fd == 0 {\n// Check that an FD was provided to fails fast. Technically FD=0 is valid,\n// but unlikely to be correct in this context.\n- return \"\", nil, fmt.Errorf(\"9P mount requires a connection FD\")\n+ return \"\", nil, false, fmt.Errorf(\"9P mount requires a connection FD\")\n}\ndata = p9MountData(m.fd, c.getMountAccessType(m.Mount), true /* vfs2 */)\n+ // If configured, add overlay to all writable mounts.\n+ useOverlay = conf.Overlay && !mountFlags(m.Options).ReadOnly\n+\ndefault:\nlog.Warningf(\"ignoring unknown filesystem type %q\", m.Type)\n- return \"\", nil, nil\n+ return \"\", nil, false, nil\n}\nopts := &vfs.MountOptions{\n@@ -381,11 +452,7 @@ func (c *containerMounter) getMountNameAndOptionsVFS2(conf *config.Config, m *mo\n}\n}\n- if conf.Overlay {\n- // All writes go to upper, be paranoid and make lower readonly.\n- opts.ReadOnly = true\n- }\n- return fsName, opts, nil\n+ return fsName, opts, useOverlay, nil\n}\n// mountTmpVFS2 mounts an internal tmpfs at '/tmp' if it's safe to do so.\n@@ -488,13 +555,25 @@ func (c *containerMounter) mountSharedMasterVFS2(ctx context.Context, conf *conf\n// Map mount type to filesystem name, and parse out the options that we are\n// capable of dealing with.\nmntFD := &mountAndFD{Mount: hint.mount}\n- fsName, opts, err := c.getMountNameAndOptionsVFS2(conf, mntFD)\n+ fsName, opts, useOverlay, err := c.getMountNameAndOptionsVFS2(conf, mntFD)\nif err != nil {\nreturn nil, err\n}\nif len(fsName) == 0 {\nreturn nil, fmt.Errorf(\"mount type not supported %q\", hint.mount.Type)\n}\n+\n+ if useOverlay {\n+ log.Infof(\"Adding overlay on top of shared mount %q\", mntFD.Destination)\n+ var cleanup func()\n+ opts, cleanup, err = c.configureOverlay(ctx, creds, opts, fsName)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"mounting shared volume with overlay at %q: %w\", mntFD.Destination, err)\n+ }\n+ defer cleanup()\n+ fsName = overlay.Name\n+ }\n+\nreturn c.k.VFS().MountDisconnected(ctx, creds, \"\", fsName, opts)\n}\n@@ -505,7 +584,9 @@ func (c *containerMounter) mountSharedSubmountVFS2(ctx context.Context, conf *co\nreturn nil, err\n}\n- _, opts, err := c.getMountNameAndOptionsVFS2(conf, &mountAndFD{Mount: mount})\n+ // Ignore data and useOverlay because these were already applied to\n+ // the master mount.\n+ _, opts, _, err := c.getMountNameAndOptionsVFS2(conf, &mountAndFD{Mount: mount})\nif err != nil {\nreturn nil, err\n}\n@@ -517,18 +598,39 @@ func (c *containerMounter) mountSharedSubmountVFS2(ctx context.Context, conf *co\nroot := mns.Root()\ndefer root.DecRef(ctx)\n- if err := c.k.VFS().MakeSyntheticMountpoint(ctx, mount.Destination, root, creds); err != nil {\n- return nil, err\n- }\n-\ntarget := &vfs.PathOperation{\nRoot: root,\nStart: root,\nPath: fspath.Parse(mount.Destination),\n}\n+\n+ if err := c.makeMountPoint(ctx, creds, mns, mount.Destination); err != nil {\n+ return nil, fmt.Errorf(\"creating mount point %q: %w\", mount.Destination, err)\n+ }\n+\nif err := c.k.VFS().ConnectMountAt(ctx, creds, newMnt, target); err != nil {\nreturn nil, err\n}\nlog.Infof(\"Mounted %q type shared bind to %q\", mount.Destination, source.name)\nreturn newMnt, nil\n}\n+\n+func (c *containerMounter) makeMountPoint(ctx context.Context, creds *auth.Credentials, mns *vfs.MountNamespace, dest string) error {\n+ root := mns.Root()\n+ defer root.DecRef(ctx)\n+ target := &vfs.PathOperation{\n+ Root: root,\n+ Start: root,\n+ Path: fspath.Parse(dest),\n+ }\n+ // First check if mount point exists. When overlay is enabled, gofer doesn't\n+ // allow changes to the FS, making MakeSytheticMountpoint() ineffective\n+ // because MkdirAt fails with EROFS even if file exists.\n+ vd, err := c.k.VFS().GetDentryAt(ctx, creds, target, &vfs.GetDentryOptions{})\n+ if err == nil {\n+ // File exists, we're done.\n+ vd.DecRef(ctx)\n+ return nil\n+ }\n+ return c.k.VFS().MakeSyntheticMountpoint(ctx, dest, root, creds)\n+}\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/container_test.go", "new_path": "runsc/container/container_test.go", "diff": "@@ -317,22 +317,12 @@ func configs(t *testing.T, opts ...configOption) map[string]*config.Config {\n}\nfunc configsWithVFS2(t *testing.T, opts ...configOption) map[string]*config.Config {\n- vfs1 := configs(t, opts...)\n-\n- var optsVFS2 []configOption\n- for _, opt := range opts {\n- // TODO(gvisor.dev/issue/1487): Enable overlay tests.\n- if opt != overlay {\n- optsVFS2 = append(optsVFS2, opt)\n- }\n- }\n-\n- for key, value := range configs(t, optsVFS2...) {\n+ all := configs(t, opts...)\n+ for key, value := range configs(t, opts...) {\nvalue.VFS2 = true\n- vfs1[key+\"VFS2\"] = value\n+ all[key+\"VFS2\"] = value\n}\n-\n- return vfs1\n+ return all\n}\n// TestLifecycle tests the basic Create/Start/Signal/Destroy container lifecycle.\n" } ]
Go
Apache License 2.0
google/gvisor
Add VFS2 overlay support in runsc All tests under runsc are passing with overlay enabled. Updates #1487, #1199 PiperOrigin-RevId: 332181267
259,885
17.09.2020 11:50:54
25,200
51a2fe8eb4f045383e67093e3f3fa0b5fac8e9ac
Disable nodejs12.4 test async-hooks/test-statwatcher.
[ { "change_type": "MODIFY", "old_path": "test/runtimes/exclude/nodejs12.4.0.csv", "new_path": "test/runtimes/exclude/nodejs12.4.0.csv", "diff": "test name,bug id,comment\n+async-hooks/test-statwatcher.js,https://github.com/nodejs/node/issues/21425,Check for fix inclusion in nodejs releases after 2020-03-29\nbenchmark/test-benchmark-fs.js,,\nbenchmark/test-benchmark-napi.js,,\ndoctool/test-make-doc.js,b/68848110,Expected to fail.\n" } ]
Go
Apache License 2.0
google/gvisor
Disable nodejs12.4 test async-hooks/test-statwatcher. PiperOrigin-RevId: 332281912
259,885
17.09.2020 11:50:59
25,200
f0b1bd434eb00a0f13cbbc141078a95ba0bc15a4
Deflake vdso_clock_gettime test.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/vdso_clock_gettime.cc", "new_path": "test/syscalls/linux/vdso_clock_gettime.cc", "diff": "@@ -38,8 +38,6 @@ std::string PrintClockId(::testing::TestParamInfo<clockid_t> info) {\nswitch (info.param) {\ncase CLOCK_MONOTONIC:\nreturn \"CLOCK_MONOTONIC\";\n- case CLOCK_REALTIME:\n- return \"CLOCK_REALTIME\";\ncase CLOCK_BOOTTIME:\nreturn \"CLOCK_BOOTTIME\";\ndefault:\n@@ -47,59 +45,31 @@ std::string PrintClockId(::testing::TestParamInfo<clockid_t> info) {\n}\n}\n-class CorrectVDSOClockTest : public ::testing::TestWithParam<clockid_t> {};\n+class MonotonicVDSOClockTest : public ::testing::TestWithParam<clockid_t> {};\n-TEST_P(CorrectVDSOClockTest, IsCorrect) {\n+TEST_P(MonotonicVDSOClockTest, IsCorrect) {\n+ // Check that when we alternate readings from the clock_gettime syscall and\n+ // the VDSO's implementation, we observe the combined sequence as being\n+ // monotonic.\nstruct timespec tvdso, tsys;\nabsl::Time vdso_time, sys_time;\n- uint64_t total_calls = 0;\n-\n- // It is expected that 82.5% of clock_gettime calls will be less than 100us\n- // skewed from the system time.\n- // Unfortunately this is not only influenced by the VDSO clock skew, but also\n- // by arbitrary scheduling delays and the like. The test is therefore\n- // regularly disabled.\n- std::map<absl::Duration, std::tuple<double, uint64_t, uint64_t>> confidence =\n- {\n- {absl::Microseconds(100), std::make_tuple(0.825, 0, 0)},\n- {absl::Microseconds(250), std::make_tuple(0.94, 0, 0)},\n- {absl::Milliseconds(1), std::make_tuple(0.999, 0, 0)},\n- };\n-\n- absl::Time start = absl::Now();\n- while (absl::Now() < start + absl::Seconds(30)) {\n- EXPECT_THAT(clock_gettime(GetParam(), &tvdso), SyscallSucceeds());\n- EXPECT_THAT(syscall(__NR_clock_gettime, GetParam(), &tsys),\n+ ASSERT_THAT(syscall(__NR_clock_gettime, GetParam(), &tsys),\nSyscallSucceeds());\n-\n+ sys_time = absl::TimeFromTimespec(tsys);\n+ auto end = absl::Now() + absl::Seconds(10);\n+ while (absl::Now() < end) {\n+ ASSERT_THAT(clock_gettime(GetParam(), &tvdso), SyscallSucceeds());\nvdso_time = absl::TimeFromTimespec(tvdso);\n-\n- for (auto const& conf : confidence) {\n- std::get<1>(confidence[conf.first]) +=\n- (sys_time - vdso_time) < conf.first;\n- }\n-\n+ EXPECT_LE(sys_time, vdso_time);\n+ ASSERT_THAT(syscall(__NR_clock_gettime, GetParam(), &tsys),\n+ SyscallSucceeds());\nsys_time = absl::TimeFromTimespec(tsys);\n-\n- for (auto const& conf : confidence) {\n- std::get<2>(confidence[conf.first]) +=\n- (vdso_time - sys_time) < conf.first;\n- }\n-\n- ++total_calls;\n- }\n-\n- for (auto const& conf : confidence) {\n- EXPECT_GE(std::get<1>(conf.second) / static_cast<double>(total_calls),\n- std::get<0>(conf.second));\n- EXPECT_GE(std::get<2>(conf.second) / static_cast<double>(total_calls),\n- std::get<0>(conf.second));\n+ EXPECT_LE(vdso_time, sys_time);\n}\n}\n-INSTANTIATE_TEST_SUITE_P(ClockGettime, CorrectVDSOClockTest,\n- ::testing::Values(CLOCK_MONOTONIC, CLOCK_REALTIME,\n- CLOCK_BOOTTIME),\n+INSTANTIATE_TEST_SUITE_P(ClockGettime, MonotonicVDSOClockTest,\n+ ::testing::Values(CLOCK_MONOTONIC, CLOCK_BOOTTIME),\nPrintClockId);\n} // namespace\n" } ]
Go
Apache License 2.0
google/gvisor
Deflake vdso_clock_gettime test. PiperOrigin-RevId: 332281930
259,992
17.09.2020 11:55:54
25,200
da07e38f7c986dca568466beea8a0b7db60f09db
Remove option to panic gofer Gofer panics are suppressed by p9 server and an error is returned to the caller, making it effectively the same as returning EROFS.
[ { "change_type": "MODIFY", "old_path": "runsc/cmd/gofer.go", "new_path": "runsc/cmd/gofer.go", "diff": "@@ -62,7 +62,6 @@ type Gofer struct {\napplyCaps bool\nsetUpRoot bool\n- panicOnWrite bool\nspecFD int\nmountsFD int\n}\n@@ -87,7 +86,6 @@ func (g *Gofer) SetFlags(f *flag.FlagSet) {\nf.StringVar(&g.bundleDir, \"bundle\", \"\", \"path to the root of the bundle directory, defaults to the current directory\")\nf.Var(&g.ioFDs, \"io-fds\", \"list of FDs to connect 9P servers. They must follow this order: root first, then mounts as defined in the spec\")\nf.BoolVar(&g.applyCaps, \"apply-caps\", true, \"if true, apply capabilities to restrict what the Gofer process can do\")\n- f.BoolVar(&g.panicOnWrite, \"panic-on-write\", false, \"if true, panics on attempts to write to RO mounts. RW mounts are unnaffected\")\nf.BoolVar(&g.setUpRoot, \"setup-root\", true, \"if true, set up an empty root for the process\")\nf.IntVar(&g.specFD, \"spec-fd\", -1, \"required fd with the container spec\")\nf.IntVar(&g.mountsFD, \"mounts-fd\", -1, \"mountsFD is the file descriptor to write list of mounts after they have been resolved (direct paths, no symlinks).\")\n@@ -169,7 +167,6 @@ func (g *Gofer) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\nats := make([]p9.Attacher, 0, len(spec.Mounts)+1)\nap, err := fsgofer.NewAttachPoint(\"/\", fsgofer.Config{\nROMount: spec.Root.Readonly || conf.Overlay,\n- PanicOnWrite: g.panicOnWrite,\n})\nif err != nil {\nFatalf(\"creating attach point: %v\", err)\n@@ -182,7 +179,6 @@ func (g *Gofer) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\nif specutils.Is9PMount(m) {\ncfg := fsgofer.Config{\nROMount: isReadonlyMount(m.Options) || conf.Overlay,\n- PanicOnWrite: g.panicOnWrite,\nHostUDS: conf.FSGoferHostUDS,\n}\nap, err := fsgofer.NewAttachPoint(m.Destination, cfg)\n@@ -316,6 +312,7 @@ func setupRootFS(spec *specs.Spec, conf *config.Config) error {\nif err != nil {\nreturn fmt.Errorf(\"resolving symlinks to %q: %v\", spec.Process.Cwd, err)\n}\n+ log.Infof(\"Create working directory %q if needed\", spec.Process.Cwd)\nif err := os.MkdirAll(dst, 0755); err != nil {\nreturn fmt.Errorf(\"creating working directory %q: %v\", spec.Process.Cwd, err)\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/container.go", "new_path": "runsc/container/container.go", "diff": "@@ -902,9 +902,6 @@ func (c *Container) createGoferProcess(spec *specs.Spec, conf *config.Config, bu\n}\nargs = append(args, \"gofer\", \"--bundle\", bundleDir)\n- if conf.Overlay {\n- args = append(args, \"--panic-on-write=true\")\n- }\n// Open the spec file to donate to the sandbox.\nspecFile, err := specutils.OpenSpec(bundleDir)\n" }, { "change_type": "MODIFY", "old_path": "runsc/fsgofer/fsgofer.go", "new_path": "runsc/fsgofer/fsgofer.go", "diff": "@@ -1181,9 +1181,6 @@ func extractErrno(err error) unix.Errno {\nfunc (l *localFile) checkROMount() error {\nif conf := l.attachPoint.conf; conf.ROMount {\n- if conf.PanicOnWrite {\n- panic(\"attempt to write to RO mount\")\n- }\nreturn unix.EROFS\n}\nreturn nil\n" }, { "change_type": "MODIFY", "old_path": "runsc/fsgofer/fsgofer_test.go", "new_path": "runsc/fsgofer/fsgofer_test.go", "diff": "@@ -553,29 +553,6 @@ func TestROMountChecks(t *testing.T) {\n})\n}\n-func TestROMountPanics(t *testing.T) {\n- conf := Config{ROMount: true, PanicOnWrite: true}\n- uid := p9.UID(os.Getuid())\n- gid := p9.GID(os.Getgid())\n-\n- runCustom(t, allTypes, []Config{conf}, func(t *testing.T, s state) {\n- if s.fileType != unix.S_IFLNK {\n- assertPanic(t, func() { s.file.Open(p9.WriteOnly) })\n- }\n- assertPanic(t, func() { s.file.Create(\"some_file\", p9.ReadWrite, 0777, uid, gid) })\n- assertPanic(t, func() { s.file.Mkdir(\"some_dir\", 0777, uid, gid) })\n- assertPanic(t, func() { s.file.RenameAt(\"some_file\", s.file, \"other_file\") })\n- assertPanic(t, func() { s.file.Symlink(\"some_place\", \"some_symlink\", uid, gid) })\n- assertPanic(t, func() { s.file.UnlinkAt(\"some_file\", 0) })\n- assertPanic(t, func() { s.file.Link(s.file, \"some_link\") })\n- assertPanic(t, func() { s.file.Mknod(\"some-nod\", 0777, 1, 2, uid, gid) })\n-\n- valid := p9.SetAttrMask{Size: true}\n- attr := p9.SetAttr{Size: 0}\n- assertPanic(t, func() { s.file.SetAttr(valid, attr) })\n- })\n-}\n-\nfunc TestWalkNotFound(t *testing.T) {\nrunCustom(t, []uint32{unix.S_IFDIR}, allConfs, func(t *testing.T, s state) {\nif _, _, err := s.file.Walk([]string{\"nobody-here\"}); err != unix.ENOENT {\n" } ]
Go
Apache License 2.0
google/gvisor
Remove option to panic gofer Gofer panics are suppressed by p9 server and an error is returned to the caller, making it effectively the same as returning EROFS. PiperOrigin-RevId: 332282959
259,907
17.09.2020 12:08:46
25,200
d796b100ecfe529e350575655b972400c52390d7
Provide testing container with docker config file. This is needed by test/e2e/integration_test:TestCheckpointRestore to check for filesystem versioning.
[ { "change_type": "MODIFY", "old_path": "tools/bazel.mk", "new_path": "tools/bazel.mk", "diff": "@@ -31,6 +31,7 @@ DOCKER_PRIVILEGED ?= --privileged\nBAZEL_CACHE := $(shell readlink -m ~/.cache/bazel/)\nGCLOUD_CONFIG := $(shell readlink -m ~/.config/gcloud/)\nDOCKER_SOCKET := /var/run/docker.sock\n+DOCKER_CONFIG := /etc/docker/daemon.json\n# Bazel flags.\nBAZEL := bazel $(STARTUP_OPTIONS)\n@@ -56,6 +57,9 @@ endif\n# Add docker passthrough options.\nifneq ($(DOCKER_PRIVILEGED),)\nFULL_DOCKER_RUN_OPTIONS += -v \"$(DOCKER_SOCKET):$(DOCKER_SOCKET)\"\n+# TODO(gvisor.dev/issue/1624): Remove docker config volume. This is required\n+# temporarily for checking VFS1 vs VFS2 by some tests.\n+FULL_DOCKER_RUN_OPTIONS += -v \"$(DOCKER_CONFIG):$(DOCKER_CONFIG)\"\nFULL_DOCKER_RUN_OPTIONS += $(DOCKER_PRIVILEGED)\nFULL_DOCKER_EXEC_OPTIONS += $(DOCKER_PRIVILEGED)\nDOCKER_GROUP := $(shell stat -c '%g' $(DOCKER_SOCKET))\n" } ]
Go
Apache License 2.0
google/gvisor
Provide testing container with docker config file. This is needed by test/e2e/integration_test:TestCheckpointRestore to check for filesystem versioning. PiperOrigin-RevId: 332285566
259,913
16.09.2020 22:46:33
0
15f50c8da63486ac0f24cbb6c2891b66a8081c05
Fix kernfs unlinkat and rmdirat incorrect resolved path name
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "diff": "@@ -658,9 +658,6 @@ func (fs *Filesystem) RmdirAt(ctx context.Context, rp *vfs.ResolvingPath) error\nfs.mu.Lock()\ndefer fs.mu.Unlock()\n- // Store the name before walkExistingLocked as rp will be advanced past the\n- // name in the following call.\n- name := rp.Component()\nvfsd, inode, err := fs.walkExistingLocked(ctx, rp)\nfs.processDeferredDecRefsLocked(ctx)\nif err != nil {\n@@ -691,7 +688,7 @@ func (fs *Filesystem) RmdirAt(ctx context.Context, rp *vfs.ResolvingPath) error\nreturn err\n}\n- if err := parentDentry.inode.RmDir(ctx, name, vfsd); err != nil {\n+ if err := parentDentry.inode.RmDir(ctx, d.name, vfsd); err != nil {\nvirtfs.AbortDeleteDentry(vfsd)\nreturn err\n}\n@@ -771,9 +768,6 @@ func (fs *Filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\nfs.mu.Lock()\ndefer fs.mu.Unlock()\n- // Store the name before walkExistingLocked as rp will be advanced past the\n- // name in the following call.\n- name := rp.Component()\nvfsd, _, err := fs.walkExistingLocked(ctx, rp)\nfs.processDeferredDecRefsLocked(ctx)\nif err != nil {\n@@ -799,7 +793,7 @@ func (fs *Filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\nif err := virtfs.PrepareDeleteDentry(mntns, vfsd); err != nil {\nreturn err\n}\n- if err := parentDentry.inode.Unlink(ctx, name, vfsd); err != nil {\n+ if err := parentDentry.inode.Unlink(ctx, d.name, vfsd); err != nil {\nvirtfs.AbortDeleteDentry(vfsd)\nreturn err\n}\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/rmdir_test.cc", "new_path": "test/fuse/linux/rmdir_test.cc", "diff": "@@ -38,6 +38,7 @@ namespace {\nclass RmDirTest : public FuseTest {\nprotected:\nconst std::string test_dir_name_ = \"test_dir\";\n+ const std::string test_subdir_ = \"test_subdir\";\nconst mode_t test_dir_mode_ = S_IFDIR | S_IRWXU | S_IRWXG | S_IRWXO;\n};\n@@ -67,6 +68,32 @@ TEST_F(RmDirTest, NormalRmDir) {\nEXPECT_EQ(std::string(actual_dirname.data()), test_dir_name_);\n}\n+TEST_F(RmDirTest, NormalRmDirSubdir) {\n+ SetServerInodeLookup(test_subdir_, S_IFDIR | S_IRWXU | S_IRWXG | S_IRWXO);\n+ const std::string test_dir_path_ =\n+ JoinPath(mount_point_.path().c_str(), test_subdir_, test_dir_name_);\n+ SetServerInodeLookup(test_dir_name_, test_dir_mode_);\n+\n+ // RmDir code.\n+ struct fuse_out_header rmdir_header = {\n+ .len = sizeof(struct fuse_out_header),\n+ };\n+\n+ auto iov_out = FuseGenerateIovecs(rmdir_header);\n+ SetServerResponse(FUSE_RMDIR, iov_out);\n+\n+ ASSERT_THAT(rmdir(test_dir_path_.c_str()), SyscallSucceeds());\n+\n+ struct fuse_in_header in_header;\n+ std::vector<char> actual_dirname(test_dir_name_.length() + 1);\n+ auto iov_in = FuseGenerateIovecs(in_header, actual_dirname);\n+ GetServerActualRequest(iov_in);\n+\n+ EXPECT_EQ(in_header.len, sizeof(in_header) + test_dir_name_.length() + 1);\n+ EXPECT_EQ(in_header.opcode, FUSE_RMDIR);\n+ EXPECT_EQ(std::string(actual_dirname.data()), test_dir_name_);\n+}\n+\n} // namespace\n} // namespace testing\n" }, { "change_type": "MODIFY", "old_path": "test/fuse/linux/unlink_test.cc", "new_path": "test/fuse/linux/unlink_test.cc", "diff": "@@ -37,6 +37,7 @@ namespace {\nclass UnlinkTest : public FuseTest {\nprotected:\nconst std::string test_file_ = \"test_file\";\n+ const std::string test_subdir_ = \"test_subdir\";\n};\nTEST_F(UnlinkTest, RegularFile) {\n@@ -61,6 +62,29 @@ TEST_F(UnlinkTest, RegularFile) {\nEXPECT_EQ(std::string(unlinked_file.data()), test_file_);\n}\n+TEST_F(UnlinkTest, RegularFileSubDir) {\n+ SetServerInodeLookup(test_subdir_, S_IFDIR | S_IRWXU | S_IRWXG | S_IRWXO);\n+ const std::string test_file_path =\n+ JoinPath(mount_point_.path().c_str(), test_subdir_, test_file_);\n+ SetServerInodeLookup(test_file_, S_IFREG | S_IRWXU | S_IRWXG | S_IRWXO);\n+\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header),\n+ };\n+ auto iov_out = FuseGenerateIovecs(out_header);\n+ SetServerResponse(FUSE_UNLINK, iov_out);\n+\n+ ASSERT_THAT(unlink(test_file_path.c_str()), SyscallSucceeds());\n+ struct fuse_in_header in_header;\n+ std::vector<char> unlinked_file(test_file_.length() + 1);\n+ auto iov_in = FuseGenerateIovecs(in_header, unlinked_file);\n+ GetServerActualRequest(iov_in);\n+\n+ EXPECT_EQ(in_header.len, sizeof(in_header) + test_file_.length() + 1);\n+ EXPECT_EQ(in_header.opcode, FUSE_UNLINK);\n+ EXPECT_EQ(std::string(unlinked_file.data()), test_file_);\n+}\n+\nTEST_F(UnlinkTest, NoFile) {\nconst std::string test_file_path =\nJoinPath(mount_point_.path().c_str(), test_file_);\n" } ]
Go
Apache License 2.0
google/gvisor
Fix kernfs unlinkat and rmdirat incorrect resolved path name
259,962
17.09.2020 15:14:01
25,200
a4db85fff210f0f4f2164f0d620c6cfdc288e26c
Return ENOPROTOOPT for all SOL_PACKET options. This is required to make tcpdump work. tcpdump falls back to not using things like PACKET_RX_RING if setsockopt returns ENOPROTOOPT. This used to be the case before Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -1768,10 +1768,16 @@ func SetSockOpt(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, level int\ncase linux.SOL_IP:\nreturn setSockOptIP(t, s, ep, name, optVal)\n+ case linux.SOL_PACKET:\n+ // gVisor doesn't support any SOL_PACKET options just return not\n+ // supported. Returning nil here will result in tcpdump thinking AF_PACKET\n+ // features are supported and proceed to use them and break.\n+ t.Kernel().EmitUnimplementedEvent(t)\n+ return syserr.ErrProtocolNotAvailable\n+\ncase linux.SOL_UDP,\nlinux.SOL_ICMPV6,\n- linux.SOL_RAW,\n- linux.SOL_PACKET:\n+ linux.SOL_RAW:\nt.Kernel().EmitUnimplementedEvent(t)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Return ENOPROTOOPT for all SOL_PACKET options. This is required to make tcpdump work. tcpdump falls back to not using things like PACKET_RX_RING if setsockopt returns ENOPROTOOPT. This used to be the case before https://github.com/google/gvisor/commit/6f8fb7e0db2790ff1f5ba835780c03fe245e437f. Fixes #3981 PiperOrigin-RevId: 332326517
259,860
17.09.2020 15:36:40
25,200
319d1b8ba0604e7bc029f98ae0e9b09badd5abad
Complete vfs2 implementation of fallocate. This change includes overlay, special regular gofer files, and hostfs. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/filesystem.go", "new_path": "pkg/sentry/fsimpl/gofer/filesystem.go", "diff": "@@ -1026,7 +1026,7 @@ func (d *dentry) open(ctx context.Context, rp *vfs.ResolvingPath, opts *vfs.Open\n// step is required even if !d.cachedMetadataAuthoritative() because\n// d.mappings has to be updated.\n// d.metadataMu has already been acquired if trunc == true.\n- d.updateFileSizeLocked(0)\n+ d.updateSizeLocked(0)\nif d.cachedMetadataAuthoritative() {\nd.touchCMtimeLocked()\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/gofer.go", "new_path": "pkg/sentry/fsimpl/gofer/gofer.go", "diff": "@@ -833,7 +833,7 @@ func (d *dentry) updateFromP9AttrsLocked(mask p9.AttrMask, attr *p9.Attr) {\natomic.StoreUint32(&d.nlink, uint32(attr.NLink))\n}\nif mask.Size {\n- d.updateFileSizeLocked(attr.Size)\n+ d.updateSizeLocked(attr.Size)\n}\n}\n@@ -987,7 +987,7 @@ func (d *dentry) setStat(ctx context.Context, creds *auth.Credentials, opts *vfs\n// d.size should be kept up to date, and privatized\n// copy-on-write mappings of truncated pages need to be\n// invalidated, even if InteropModeShared is in effect.\n- d.updateFileSizeLocked(stat.Size)\n+ d.updateSizeLocked(stat.Size)\n}\n}\nif d.fs.opts.interop == InteropModeShared {\n@@ -1024,8 +1024,31 @@ func (d *dentry) setStat(ctx context.Context, creds *auth.Credentials, opts *vfs\nreturn nil\n}\n+// doAllocate performs an allocate operation on d. Note that d.metadataMu will\n+// be held when allocate is called.\n+func (d *dentry) doAllocate(ctx context.Context, offset, length uint64, allocate func() error) error {\n+ d.metadataMu.Lock()\n+ defer d.metadataMu.Unlock()\n+\n+ // Allocating a smaller size is a noop.\n+ size := offset + length\n+ if d.cachedMetadataAuthoritative() && size <= d.size {\n+ return nil\n+ }\n+\n+ err := allocate()\n+ if err != nil {\n+ return err\n+ }\n+ d.updateSizeLocked(size)\n+ if d.cachedMetadataAuthoritative() {\n+ d.touchCMtimeLocked()\n+ }\n+ return nil\n+}\n+\n// Preconditions: d.metadataMu must be locked.\n-func (d *dentry) updateFileSizeLocked(newSize uint64) {\n+func (d *dentry) updateSizeLocked(newSize uint64) {\nd.dataMu.Lock()\noldSize := d.size\natomic.StoreUint64(&d.size, newSize)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/regular_file.go", "new_path": "pkg/sentry/fsimpl/gofer/regular_file.go", "diff": "@@ -79,28 +79,11 @@ func (fd *regularFileFD) OnClose(ctx context.Context) error {\n// Allocate implements vfs.FileDescriptionImpl.Allocate.\nfunc (fd *regularFileFD) Allocate(ctx context.Context, mode, offset, length uint64) error {\nd := fd.dentry()\n- d.metadataMu.Lock()\n- defer d.metadataMu.Unlock()\n-\n- // Allocating a smaller size is a noop.\n- size := offset + length\n- if d.cachedMetadataAuthoritative() && size <= d.size {\n- return nil\n- }\n-\n+ return d.doAllocate(ctx, offset, length, func() error {\nd.handleMu.RLock()\n- err := d.writeFile.allocate(ctx, p9.ToAllocateMode(mode), offset, length)\n- d.handleMu.RUnlock()\n- if err != nil {\n- return err\n- }\n- d.dataMu.Lock()\n- atomic.StoreUint64(&d.size, size)\n- d.dataMu.Unlock()\n- if d.cachedMetadataAuthoritative() {\n- d.touchCMtimeLocked()\n- }\n- return nil\n+ defer d.handleMu.RUnlock()\n+ return d.writeFile.allocate(ctx, p9.ToAllocateMode(mode), offset, length)\n+ })\n}\n// PRead implements vfs.FileDescriptionImpl.PRead.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/special_file.go", "new_path": "pkg/sentry/fsimpl/gofer/special_file.go", "diff": "@@ -22,6 +22,7 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/fdnotifier\"\n+ \"gvisor.dev/gvisor/pkg/p9\"\n\"gvisor.dev/gvisor/pkg/safemem\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n@@ -135,6 +136,16 @@ func (fd *specialFileFD) EventUnregister(e *waiter.Entry) {\nfd.fileDescription.EventUnregister(e)\n}\n+func (fd *specialFileFD) Allocate(ctx context.Context, mode, offset, length uint64) error {\n+ if fd.isRegularFile {\n+ d := fd.dentry()\n+ return d.doAllocate(ctx, offset, length, func() error {\n+ return fd.handle.file.allocate(ctx, p9.ToAllocateMode(mode), offset, length)\n+ })\n+ }\n+ return fd.FileDescriptionDefaultImpl.Allocate(ctx, mode, offset, length)\n+}\n+\n// PRead implements vfs.FileDescriptionImpl.PRead.\nfunc (fd *specialFileFD) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts vfs.ReadOptions) (int64, error) {\nif fd.seekable && offset < 0 {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/host/host.go", "new_path": "pkg/sentry/fsimpl/host/host.go", "diff": "@@ -560,12 +560,7 @@ func (f *fileDescription) Release(context.Context) {\n// Allocate implements vfs.FileDescriptionImpl.\nfunc (f *fileDescription) Allocate(ctx context.Context, mode, offset, length uint64) error {\n- if !f.inode.seekable {\n- return syserror.ESPIPE\n- }\n-\n- // TODO(gvisor.dev/issue/3589): Implement Allocate for non-pipe hostfds.\n- return syserror.EOPNOTSUPP\n+ return unix.Fallocate(f.inode.hostFD, uint32(mode), int64(offset), int64(length))\n}\n// PRead implements FileDescriptionImpl.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/overlay/non_directory.go", "new_path": "pkg/sentry/fsimpl/overlay/non_directory.go", "diff": "@@ -147,6 +147,16 @@ func (fd *nonDirectoryFD) Stat(ctx context.Context, opts vfs.StatOptions) (linux\nreturn stat, nil\n}\n+// Allocate implements vfs.FileDescriptionImpl.Allocate.\n+func (fd *nonDirectoryFD) Allocate(ctx context.Context, mode, offset, length uint64) error {\n+ wrappedFD, err := fd.getCurrentFD(ctx)\n+ if err != nil {\n+ return err\n+ }\n+ defer wrappedFD.DecRef(ctx)\n+ return wrappedFD.Allocate(ctx, mode, offset, length)\n+}\n+\n// SetStat implements vfs.FileDescriptionImpl.SetStat.\nfunc (fd *nonDirectoryFD) SetStat(ctx context.Context, opts vfs.SetStatOptions) error {\nd := fd.dentry()\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/pipe/vfs.go", "new_path": "pkg/sentry/kernel/pipe/vfs.go", "diff": "@@ -67,6 +67,11 @@ func (vp *VFSPipe) ReaderWriterPair(mnt *vfs.Mount, vfsd *vfs.Dentry, statusFlag\nreturn vp.newFD(mnt, vfsd, linux.O_RDONLY|statusFlags, locks), vp.newFD(mnt, vfsd, linux.O_WRONLY|statusFlags, locks)\n}\n+// Allocate implements vfs.FileDescriptionImpl.Allocate.\n+func (*VFSPipe) Allocate(context.Context, uint64, uint64, uint64) error {\n+ return syserror.ESPIPE\n+}\n+\n// Open opens the pipe represented by vp.\nfunc (vp *VFSPipe) Open(ctx context.Context, mnt *vfs.Mount, vfsd *vfs.Dentry, statusFlags uint32, locks *vfs.FileLocks) (*vfs.FileDescription, error) {\nvp.mu.Lock()\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/hostinet/socket_vfs2.go", "new_path": "pkg/sentry/socket/hostinet/socket_vfs2.go", "diff": "@@ -97,11 +97,6 @@ func (s *socketVFS2) Ioctl(ctx context.Context, uio usermem.IO, args arch.Syscal\nreturn ioctl(ctx, s.fd, uio, args)\n}\n-// Allocate implements vfs.FileDescriptionImpl.Allocate.\n-func (s *socketVFS2) Allocate(ctx context.Context, mode, offset, length uint64) error {\n- return syserror.ENODEV\n-}\n-\n// PRead implements vfs.FileDescriptionImpl.PRead.\nfunc (s *socketVFS2) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts vfs.ReadOptions) (int64, error) {\nreturn 0, syserror.ESPIPE\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description.go", "new_path": "pkg/sentry/vfs/file_description.go", "diff": "@@ -326,6 +326,9 @@ type FileDescriptionImpl interface {\n// Allocate grows the file to offset + length bytes.\n// Only mode == 0 is supported currently.\n//\n+ // Allocate should return EISDIR on directories, ESPIPE on pipes, and ENODEV on\n+ // other files where it is not supported.\n+ //\n// Preconditions: The FileDescription was opened for writing.\nAllocate(ctx context.Context, mode, offset, length uint64) error\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description_impl_util.go", "new_path": "pkg/sentry/vfs/file_description_impl_util.go", "diff": "@@ -57,7 +57,11 @@ func (FileDescriptionDefaultImpl) StatFS(ctx context.Context) (linux.Statfs, err\n}\n// Allocate implements FileDescriptionImpl.Allocate analogously to\n-// fallocate called on regular file, directory or FIFO in Linux.\n+// fallocate called on an invalid type of file in Linux.\n+//\n+// Note that directories can rely on this implementation even though they\n+// should technically return EISDIR. Allocate should never be called for a\n+// directory, because it requires a writable fd.\nfunc (FileDescriptionDefaultImpl) Allocate(ctx context.Context, mode, offset, length uint64) error {\nreturn syserror.ENODEV\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/fallocate.cc", "new_path": "test/syscalls/linux/fallocate.cc", "diff": "@@ -179,6 +179,12 @@ TEST_F(AllocateTest, FallocateOtherFDs) {\nauto sock0 = FileDescriptor(socks[0]);\nauto sock1 = FileDescriptor(socks[1]);\nEXPECT_THAT(fallocate(sock0.get(), 0, 0, 10), SyscallFailsWithErrno(ENODEV));\n+\n+ int pipefds[2];\n+ ASSERT_THAT(pipe(pipefds), SyscallSucceeds());\n+ EXPECT_THAT(fallocate(pipefds[1], 0, 0, 10), SyscallFailsWithErrno(ESPIPE));\n+ close(pipefds[0]);\n+ close(pipefds[1]);\n}\n} // namespace\n" } ]
Go
Apache License 2.0
google/gvisor
Complete vfs2 implementation of fallocate. This change includes overlay, special regular gofer files, and hostfs. Fixes #3589. PiperOrigin-RevId: 332330860
260,001
17.09.2020 16:27:01
25,200
f1f844daabdacf46f6237ddf0a90c370dbe2348a
Set mode when creating Merkle tree file
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/verity/filesystem.go", "new_path": "pkg/sentry/fsimpl/verity/filesystem.go", "diff": "@@ -372,6 +372,7 @@ func (fs *filesystem) lookupAndVerifyLocked(ctx context.Context, parent *dentry,\nPath: fspath.Parse(childMerkleFilename),\n}, &vfs.OpenOptions{\nFlags: linux.O_RDWR | linux.O_CREAT,\n+ Mode: 0644,\n})\nif err != nil {\nreturn nil, err\n" } ]
Go
Apache License 2.0
google/gvisor
Set mode when creating Merkle tree file PiperOrigin-RevId: 332340342
260,001
17.09.2020 17:42:58
25,200
1e8beb5f1d925ed0c30a2b810fc2a0bffbd3cf58
Change sizeofInt32 to string size This constant is used to represent int32 stored in file xattrs. The integers are stored as strings there, so the real size should be the string size (number of digits) instead of an int size (4 bytes).
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/verity/filesystem.go", "new_path": "pkg/sentry/fsimpl/verity/filesystem.go", "diff": "@@ -185,8 +185,7 @@ func (fs *filesystem) verifyChild(ctx context.Context, parent *dentry, child *de\nStart: child.lowerMerkleVD,\n}, &vfs.GetXattrOptions{\nName: merkleOffsetInParentXattr,\n- // Offset is a 32 bit integer.\n- Size: sizeOfInt32,\n+ Size: sizeOfStringInt32,\n})\n// The Merkle tree file for the child should have been created and\n@@ -227,7 +226,7 @@ func (fs *filesystem) verifyChild(ctx context.Context, parent *dentry, child *de\n// the size of all its children's root hashes.\ndataSize, err := parentMerkleFD.GetXattr(ctx, &vfs.GetXattrOptions{\nName: merkleSizeXattr,\n- Size: sizeOfInt32,\n+ Size: sizeOfStringInt32,\n})\n// The Merkle tree file for the child should have been created and\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/verity/verity.go", "new_path": "pkg/sentry/fsimpl/verity/verity.go", "diff": "@@ -57,8 +57,9 @@ const merkleOffsetInParentXattr = \"user.merkle.offset\"\n// whole file. For a directory, it's the size of all its children's root hashes.\nconst merkleSizeXattr = \"user.merkle.size\"\n-// sizeOfInt32 is the size in bytes for a 32 bit integer in extended attributes.\n-const sizeOfInt32 = 4\n+// sizeOfStringInt32 is the size for a 32 bit integer stored as string in\n+// extended attributes. The maximum value of a 32 bit integer is 10 digits.\n+const sizeOfStringInt32 = 10\n// noCrashOnVerificationFailure indicates whether the sandbox should panic\n// whenever verification fails. If true, an error is returned instead of\n@@ -636,7 +637,7 @@ func (fd *fileDescription) PRead(ctx context.Context, dst usermem.IOSequence, of\n// dataSize is the size of the whole file.\ndataSize, err := fd.merkleReader.GetXattr(ctx, &vfs.GetXattrOptions{\nName: merkleSizeXattr,\n- Size: sizeOfInt32,\n+ Size: sizeOfStringInt32,\n})\n// The Merkle tree file for the child should have been created and\n" } ]
Go
Apache License 2.0
google/gvisor
Change sizeofInt32 to string size This constant is used to represent int32 stored in file xattrs. The integers are stored as strings there, so the real size should be the string size (number of digits) instead of an int size (4 bytes). PiperOrigin-RevId: 332353217
259,907
17.09.2020 18:25:20
25,200
c0b74be54c336f53ff3596acad2c57330a63c6b1
Fix root tests target in Makefile.
[ { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "@@ -129,10 +129,9 @@ tests: unit-tests\n@$(call submake,test TARGETS=\"test/syscalls/...\")\n.PHONY: tests\n-\nintegration-tests: ## Run all standard integration tests.\nintegration-tests: docker-tests overlay-tests hostnet-tests swgso-tests\n-integration-tests: do-tests kvm-tests root-tests containerd-tests\n+integration-tests: do-tests kvm-tests containerd-test-1.3.4\n.PHONY: integration-tests\nnetwork-tests: ## Run all networking integration tests.\n@@ -186,6 +185,7 @@ swgso-tests: load-basic-images\n@$(call submake,install-test-runtime RUNTIME=\"swgso\" ARGS=\"--software-gso=true --gso=false\")\n@$(call submake,test-runtime RUNTIME=\"swgso\" TARGETS=\"$(INTEGRATION_TARGETS)\")\n.PHONY: swgso-tests\n+\nhostnet-tests: load-basic-images\n@$(call submake,install-test-runtime RUNTIME=\"hostnet\" ARGS=\"--network=host\")\n@$(call submake,test-runtime RUNTIME=\"hostnet\" OPTIONS=\"--test_arg=-checkpoint=false\" TARGETS=\"$(INTEGRATION_TARGETS)\")\n@@ -217,16 +217,12 @@ packetimpact-tests: load-packetimpact\n@$(call submake,test-runtime OPTIONS=\"--jobs=HOST_CPUS*3 --local_test_jobs=HOST_CPUS*3\" RUNTIME=\"packetimpact\" TARGETS=\"$(shell $(MAKE) query TARGETS='attr(tags, packetimpact, tests(//...))')\")\n.PHONY: packetimpact-tests\n-root-tests: load-basic-images\n- @$(call submake,install-test-runtime)\n- @$(call submake,sudo TARGETS=\"//test/root:root_test\" ARGS=\"-test.v\")\n-.PHONY: root-tests\n-\n# Specific containerd version tests.\n-containerd-test-%: load-basic_alpine load-basic_python load-basic_busybox load-basic_resolv load-basic_httpd install-test-runtime\n+containerd-test-%: load-basic_alpine load-basic_python load-basic_busybox load-basic_resolv load-basic_httpd load-basic_ubuntu\n+ @$(call submake,install-test-runtime RUNTIME=\"root\")\n@CONTAINERD_VERSION=$* $(MAKE) sudo TARGETS=\"tools/installers:containerd\"\n@$(MAKE) sudo TARGETS=\"tools/installers:shim\"\n- @$(MAKE) sudo TARGETS=\"test/root:root_test\" ARGS=\"-test.v\"\n+ @$(MAKE) sudo TARGETS=\"test/root:root_test\" ARGS=\"--runtime=root -test.v\"\n# Note that we can't run containerd-test-1.1.8 tests here.\n#\n" } ]
Go
Apache License 2.0
google/gvisor
Fix root tests target in Makefile. PiperOrigin-RevId: 332358833
259,896
17.09.2020 19:58:27
25,200
d34bda027309695e3e6fb6f92a5839cd1f21173e
{Set,Get} SO_LINGER on all endpoints. SO_LINGER is a socket level option and should be stored on all endpoints even though it is used to linger only for TCP endpoints.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -1185,7 +1185,7 @@ func getSockOptSocket(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, fam\nvar v tcpip.LingerOption\nvar linger linux.Linger\nif err := ep.GetSockOpt(&v); err != nil {\n- return &linger, nil\n+ return nil, syserr.TranslateNetstackError(err)\n}\nif v.Enabled {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/unix/transport/unix.go", "new_path": "pkg/sentry/socket/unix/transport/unix.go", "diff": "@@ -746,6 +746,9 @@ type baseEndpoint struct {\n// path is not empty if the endpoint has been bound,\n// or may be used if the endpoint is connected.\npath string\n+\n+ // linger is used for SO_LINGER socket option.\n+ linger tcpip.LingerOption\n}\n// EventRegister implements waiter.Waitable.EventRegister.\n@@ -841,8 +844,14 @@ func (e *baseEndpoint) SendMsg(ctx context.Context, data [][]byte, c ControlMess\nreturn n, err\n}\n-// SetSockOpt sets a socket option. Currently not supported.\n-func (e *baseEndpoint) SetSockOpt(tcpip.SettableSocketOption) *tcpip.Error {\n+// SetSockOpt sets a socket option.\n+func (e *baseEndpoint) SetSockOpt(opt tcpip.SettableSocketOption) *tcpip.Error {\n+ switch v := opt.(type) {\n+ case *tcpip.LingerOption:\n+ e.Lock()\n+ e.linger = *v\n+ e.Unlock()\n+ }\nreturn nil\n}\n@@ -945,8 +954,11 @@ func (e *baseEndpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, *tcpip.Error) {\n// GetSockOpt implements tcpip.Endpoint.GetSockOpt.\nfunc (e *baseEndpoint) GetSockOpt(opt tcpip.GettableSocketOption) *tcpip.Error {\n- switch opt.(type) {\n+ switch o := opt.(type) {\ncase *tcpip.LingerOption:\n+ e.Lock()\n+ *o = e.linger\n+ e.Unlock()\nreturn nil\ndefault:\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/icmp/endpoint.go", "new_path": "pkg/tcpip/transport/icmp/endpoint.go", "diff": "@@ -74,6 +74,8 @@ type endpoint struct {\nroute stack.Route `state:\"manual\"`\nttl uint8\nstats tcpip.TransportEndpointStats `state:\"nosave\"`\n+ // linger is used for SO_LINGER socket option.\n+ linger tcpip.LingerOption\n// owner is used to get uid and gid of the packet.\nowner tcpip.PacketOwner\n@@ -344,9 +346,14 @@ func (e *endpoint) Peek([][]byte) (int64, tcpip.ControlMessages, *tcpip.Error) {\n// SetSockOpt sets a socket option.\nfunc (e *endpoint) SetSockOpt(opt tcpip.SettableSocketOption) *tcpip.Error {\n- switch opt.(type) {\n+ switch v := opt.(type) {\ncase *tcpip.SocketDetachFilterOption:\nreturn nil\n+\n+ case *tcpip.LingerOption:\n+ e.mu.Lock()\n+ e.linger = *v\n+ e.mu.Unlock()\n}\nreturn nil\n}\n@@ -415,9 +422,18 @@ func (e *endpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, *tcpip.Error) {\n}\n// GetSockOpt implements tcpip.Endpoint.GetSockOpt.\n-func (*endpoint) GetSockOpt(tcpip.GettableSocketOption) *tcpip.Error {\n+func (e *endpoint) GetSockOpt(opt tcpip.GettableSocketOption) *tcpip.Error {\n+ switch o := opt.(type) {\n+ case *tcpip.LingerOption:\n+ e.mu.Lock()\n+ *o = e.linger\n+ e.mu.Unlock()\n+ return nil\n+\n+ default:\nreturn tcpip.ErrUnknownProtocolOption\n}\n+}\nfunc send4(r *stack.Route, ident uint16, data buffer.View, ttl uint8, owner tcpip.PacketOwner) *tcpip.Error {\nif len(data) < header.ICMPv4MinimumSize {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/packet/endpoint.go", "new_path": "pkg/tcpip/transport/packet/endpoint.go", "diff": "@@ -83,6 +83,8 @@ type endpoint struct {\nstats tcpip.TransportEndpointStats `state:\"nosave\"`\nbound bool\nboundNIC tcpip.NICID\n+ // linger is used for SO_LINGER socket option.\n+ linger tcpip.LingerOption\n// lastErrorMu protects lastError.\nlastErrorMu sync.Mutex `state:\"nosave\"`\n@@ -298,10 +300,16 @@ func (ep *endpoint) Readiness(mask waiter.EventMask) waiter.EventMask {\n// used with SetSockOpt, and this function always returns\n// tcpip.ErrNotSupported.\nfunc (ep *endpoint) SetSockOpt(opt tcpip.SettableSocketOption) *tcpip.Error {\n- switch opt.(type) {\n+ switch v := opt.(type) {\ncase *tcpip.SocketDetachFilterOption:\nreturn nil\n+ case *tcpip.LingerOption:\n+ ep.mu.Lock()\n+ ep.linger = *v\n+ ep.mu.Unlock()\n+ return nil\n+\ndefault:\nreturn tcpip.ErrUnknownProtocolOption\n}\n@@ -366,9 +374,18 @@ func (ep *endpoint) LastError() *tcpip.Error {\n}\n// GetSockOpt implements tcpip.Endpoint.GetSockOpt.\n-func (*endpoint) GetSockOpt(tcpip.GettableSocketOption) *tcpip.Error {\n+func (ep *endpoint) GetSockOpt(opt tcpip.GettableSocketOption) *tcpip.Error {\n+ switch o := opt.(type) {\n+ case *tcpip.LingerOption:\n+ ep.mu.Lock()\n+ *o = ep.linger\n+ ep.mu.Unlock()\n+ return nil\n+\n+ default:\nreturn tcpip.ErrNotSupported\n}\n+}\n// GetSockOptBool implements tcpip.Endpoint.GetSockOptBool.\nfunc (*endpoint) GetSockOptBool(opt tcpip.SockOptBool) (bool, *tcpip.Error) {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/raw/endpoint.go", "new_path": "pkg/tcpip/transport/raw/endpoint.go", "diff": "@@ -84,6 +84,8 @@ type endpoint struct {\n// Connect(), and is valid only when conneted is true.\nroute stack.Route `state:\"manual\"`\nstats tcpip.TransportEndpointStats `state:\"nosave\"`\n+ // linger is used for SO_LINGER socket option.\n+ linger tcpip.LingerOption\n// owner is used to get uid and gid of the packet.\nowner tcpip.PacketOwner\n@@ -511,10 +513,16 @@ func (e *endpoint) Readiness(mask waiter.EventMask) waiter.EventMask {\n// SetSockOpt implements tcpip.Endpoint.SetSockOpt.\nfunc (e *endpoint) SetSockOpt(opt tcpip.SettableSocketOption) *tcpip.Error {\n- switch opt.(type) {\n+ switch v := opt.(type) {\ncase *tcpip.SocketDetachFilterOption:\nreturn nil\n+ case *tcpip.LingerOption:\n+ e.mu.Lock()\n+ e.linger = *v\n+ e.mu.Unlock()\n+ return nil\n+\ndefault:\nreturn tcpip.ErrUnknownProtocolOption\n}\n@@ -577,9 +585,18 @@ func (e *endpoint) SetSockOptInt(opt tcpip.SockOptInt, v int) *tcpip.Error {\n}\n// GetSockOpt implements tcpip.Endpoint.GetSockOpt.\n-func (*endpoint) GetSockOpt(tcpip.GettableSocketOption) *tcpip.Error {\n+func (e *endpoint) GetSockOpt(opt tcpip.GettableSocketOption) *tcpip.Error {\n+ switch o := opt.(type) {\n+ case *tcpip.LingerOption:\n+ e.mu.Lock()\n+ *o = e.linger\n+ e.mu.Unlock()\n+ return nil\n+\n+ default:\nreturn tcpip.ErrUnknownProtocolOption\n}\n+}\n// GetSockOptBool implements tcpip.Endpoint.GetSockOptBool.\nfunc (e *endpoint) GetSockOptBool(opt tcpip.SockOptBool) (bool, *tcpip.Error) {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/endpoint.go", "new_path": "pkg/tcpip/transport/udp/endpoint.go", "diff": "@@ -154,6 +154,9 @@ type endpoint struct {\n// owner is used to get uid and gid of the packet.\nowner tcpip.PacketOwner\n+\n+ // linger is used for SO_LINGER socket option.\n+ linger tcpip.LingerOption\n}\n// +stateify savable\n@@ -810,6 +813,11 @@ func (e *endpoint) SetSockOpt(opt tcpip.SettableSocketOption) *tcpip.Error {\ncase *tcpip.SocketDetachFilterOption:\nreturn nil\n+\n+ case *tcpip.LingerOption:\n+ e.mu.Lock()\n+ e.linger = *v\n+ e.mu.Unlock()\n}\nreturn nil\n}\n@@ -966,6 +974,11 @@ func (e *endpoint) GetSockOpt(opt tcpip.GettableSocketOption) *tcpip.Error {\n*o = tcpip.BindToDeviceOption(e.bindToDevice)\ne.mu.RUnlock()\n+ case *tcpip.LingerOption:\n+ e.mu.RLock()\n+ *o = e.linger\n+ e.mu.RUnlock()\n+\ndefault:\nreturn tcpip.ErrUnknownProtocolOption\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/packet_socket_raw.cc", "new_path": "test/syscalls/linux/packet_socket_raw.cc", "diff": "@@ -643,6 +643,27 @@ TEST_P(RawPacketTest, GetSocketDetachFilter) {\nSyscallFailsWithErrno(ENOPROTOOPT));\n}\n+TEST_P(RawPacketTest, SetAndGetSocketLinger) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+\n+ int level = SOL_SOCKET;\n+ int type = SO_LINGER;\n+\n+ struct linger sl;\n+ sl.l_onoff = 1;\n+ sl.l_linger = 5;\n+ ASSERT_THAT(setsockopt(s_, level, type, &sl, sizeof(sl)),\n+ SyscallSucceedsWithValue(0));\n+\n+ struct linger got_linger = {};\n+ socklen_t length = sizeof(sl);\n+ ASSERT_THAT(getsockopt(s_, level, type, &got_linger, &length),\n+ SyscallSucceedsWithValue(0));\n+\n+ ASSERT_EQ(length, sizeof(got_linger));\n+ EXPECT_EQ(0, memcmp(&sl, &got_linger, length));\n+}\n+\nINSTANTIATE_TEST_SUITE_P(AllInetTests, RawPacketTest,\n::testing::Values(ETH_P_IP, ETH_P_ALL));\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/raw_socket_icmp.cc", "new_path": "test/syscalls/linux/raw_socket_icmp.cc", "diff": "@@ -416,6 +416,28 @@ TEST_F(RawSocketICMPTest, BindConnectSendAndReceive) {\nASSERT_NO_FATAL_FAILURE(ExpectICMPSuccess(icmp));\n}\n+// Set and get SO_LINGER.\n+TEST_F(RawSocketICMPTest, SetAndGetSocketLinger) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+\n+ int level = SOL_SOCKET;\n+ int type = SO_LINGER;\n+\n+ struct linger sl;\n+ sl.l_onoff = 1;\n+ sl.l_linger = 5;\n+ ASSERT_THAT(setsockopt(s_, level, type, &sl, sizeof(sl)),\n+ SyscallSucceedsWithValue(0));\n+\n+ struct linger got_linger = {};\n+ socklen_t length = sizeof(sl);\n+ ASSERT_THAT(getsockopt(s_, level, type, &got_linger, &length),\n+ SyscallSucceedsWithValue(0));\n+\n+ ASSERT_EQ(length, sizeof(got_linger));\n+ EXPECT_EQ(0, memcmp(&sl, &got_linger, length));\n+}\n+\nvoid RawSocketICMPTest::ExpectICMPSuccess(const struct icmphdr& icmp) {\n// We're going to receive both the echo request and reply, but the order is\n// indeterminate.\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_ip_udp_generic.cc", "new_path": "test/syscalls/linux/socket_ip_udp_generic.cc", "diff": "@@ -451,7 +451,7 @@ TEST_P(UDPSocketPairTest, TClassRecvMismatch) {\n}\n// Test the SO_LINGER option can be set/get on udp socket.\n-TEST_P(UDPSocketPairTest, SoLingerFail) {\n+TEST_P(UDPSocketPairTest, SetAndGetSocketLinger) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\nint level = SOL_SOCKET;\nint type = SO_LINGER;\n@@ -469,16 +469,8 @@ TEST_P(UDPSocketPairTest, SoLingerFail) {\nSyscallSucceedsWithValue(0));\nASSERT_EQ(length, sizeof(got_linger));\n- // Linux returns the values which are set in the SetSockOpt for SO_LINGER.\n- // In gVisor, we do not store the linger values for UDP as SO_LINGER for UDP\n- // is a no-op.\n- if (IsRunningOnGvisor()) {\n- struct linger want_linger = {};\n- EXPECT_EQ(0, memcmp(&want_linger, &got_linger, length));\n- } else {\nEXPECT_EQ(0, memcmp(&sl, &got_linger, length));\n}\n-}\n} // namespace testing\n} // namespace gvisor\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_unix_stream.cc", "new_path": "test/syscalls/linux/socket_unix_stream.cc", "diff": "@@ -103,6 +103,24 @@ TEST_P(StreamUnixSocketPairTest, Sendto) {\nSyscallFailsWithErrno(EISCONN));\n}\n+TEST_P(StreamUnixSocketPairTest, SetAndGetSocketLinger) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ struct linger sl = {1, 5};\n+ EXPECT_THAT(\n+ setsockopt(sockets->first_fd(), SOL_SOCKET, SO_LINGER, &sl, sizeof(sl)),\n+ SyscallSucceedsWithValue(0));\n+\n+ struct linger got_linger = {};\n+ socklen_t length = sizeof(sl);\n+ EXPECT_THAT(getsockopt(sockets->first_fd(), SOL_SOCKET, SO_LINGER,\n+ &got_linger, &length),\n+ SyscallSucceedsWithValue(0));\n+\n+ ASSERT_EQ(length, sizeof(got_linger));\n+ EXPECT_EQ(0, memcmp(&got_linger, &sl, length));\n+}\n+\nINSTANTIATE_TEST_SUITE_P(\nAllUnixDomainSockets, StreamUnixSocketPairTest,\n::testing::ValuesIn(IncludeReversals(VecCat<SocketPairKind>(\n" } ]
Go
Apache License 2.0
google/gvisor
{Set,Get} SO_LINGER on all endpoints. SO_LINGER is a socket level option and should be stored on all endpoints even though it is used to linger only for TCP endpoints. PiperOrigin-RevId: 332369252
259,891
17.09.2020 22:48:47
25,200
2fbd31e726c5d7bcdd44f0498e73124807052d59
Test IPv4 WritePackets stats IPv6 tests will be added in another CL along with ip6tables.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4_test.go", "new_path": "pkg/tcpip/network/ipv4/ipv4_test.go", "diff": "@@ -1046,3 +1046,211 @@ func TestReceiveFragments(t *testing.T) {\n})\n}\n}\n+\n+func TestWritePacketsStats(t *testing.T) {\n+ const nPackets = 3\n+ tests := []struct {\n+ name string\n+ setup func(*testing.T, *stack.Stack)\n+ linkEP stack.LinkEndpoint\n+ expectSent int\n+ }{\n+ {\n+ name: \"Accept all\",\n+ // No setup needed, tables accept everything by default.\n+ setup: func(*testing.T, *stack.Stack) {},\n+ linkEP: &limitedEP{nPackets},\n+ expectSent: nPackets,\n+ }, {\n+ name: \"Accept all with error\",\n+ // No setup needed, tables accept everything by default.\n+ setup: func(*testing.T, *stack.Stack) {},\n+ linkEP: &limitedEP{nPackets - 1},\n+ expectSent: nPackets - 1,\n+ }, {\n+ name: \"Drop all\",\n+ setup: func(t *testing.T, stk *stack.Stack) {\n+ // Install Output DROP rule.\n+ t.Helper()\n+ ipt := stk.IPTables()\n+ filter, ok := ipt.GetTable(stack.FilterTable, false /* ipv6 */)\n+ if !ok {\n+ t.Fatalf(\"failed to find filter table\")\n+ }\n+ ruleIdx := filter.BuiltinChains[stack.Output]\n+ filter.Rules[ruleIdx].Target = stack.DropTarget{}\n+ if err := ipt.ReplaceTable(stack.FilterTable, filter, false /* ipv6 */); err != nil {\n+ t.Fatalf(\"failed to replace table: %v\", err)\n+ }\n+ },\n+ linkEP: &limitedEP{nPackets},\n+ expectSent: 0,\n+ }, {\n+ name: \"Drop some\",\n+ setup: func(t *testing.T, stk *stack.Stack) {\n+ // Install Output DROP rule that matches only 1\n+ // of the 3 packets.\n+ t.Helper()\n+ ipt := stk.IPTables()\n+ filter, ok := ipt.GetTable(stack.FilterTable, false /* ipv6 */)\n+ if !ok {\n+ t.Fatalf(\"failed to find filter table\")\n+ }\n+ // We'll match and DROP the last packet.\n+ ruleIdx := filter.BuiltinChains[stack.Output]\n+ filter.Rules[ruleIdx].Target = stack.DropTarget{}\n+ filter.Rules[ruleIdx].Matchers = []stack.Matcher{&limitedMatcher{nPackets - 1}}\n+ // Make sure the next rule is ACCEPT.\n+ filter.Rules[ruleIdx+1].Target = stack.AcceptTarget{}\n+ if err := ipt.ReplaceTable(stack.FilterTable, filter, false /* ipv6 */); err != nil {\n+ t.Fatalf(\"failed to replace table: %v\", err)\n+ }\n+ },\n+ linkEP: &limitedEP{nPackets},\n+ expectSent: nPackets - 1,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ rt := buildRoute(t, nil, test.linkEP)\n+\n+ var pbl stack.PacketBufferList\n+ for i := 0; i < nPackets; i++ {\n+ pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n+ ReserveHeaderBytes: header.UDPMinimumSize + int(rt.MaxHeaderLength()),\n+ Data: buffer.NewView(1).ToVectorisedView(),\n+ })\n+ pkt.TransportHeader().Push(header.UDPMinimumSize)\n+ pbl.PushBack(pkt)\n+ }\n+\n+ test.setup(t, rt.Stack())\n+\n+ nWritten, err := rt.WritePackets(nil, pbl, stack.NetworkHeaderParams{})\n+ if err != nil {\n+ t.Fatal(err)\n+ }\n+\n+ got := int(rt.Stats().IP.PacketsSent.Value())\n+ if got != test.expectSent {\n+ t.Errorf(\"sent %d packets, but expected to send %d\", got, test.expectSent)\n+ }\n+ if got != nWritten {\n+ t.Errorf(\"sent %d packets, WritePackets returned %d\", got, nWritten)\n+ }\n+ })\n+ }\n+}\n+\n+func buildRoute(t *testing.T, packetCollectorErrors []*tcpip.Error, linkEP stack.LinkEndpoint) stack.Route {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocol{ipv4.NewProtocol()},\n+ })\n+ s.CreateNIC(1, linkEP)\n+ const (\n+ src = \"\\x10\\x00\\x00\\x01\"\n+ dst = \"\\x10\\x00\\x00\\x02\"\n+ )\n+ s.AddAddress(1, ipv4.ProtocolNumber, src)\n+ {\n+ subnet, err := tcpip.NewSubnet(dst, tcpip.AddressMask(header.IPv4Broadcast))\n+ if err != nil {\n+ t.Fatal(err)\n+ }\n+ s.SetRouteTable([]tcpip.Route{{\n+ Destination: subnet,\n+ NIC: 1,\n+ }})\n+ }\n+ rt, err := s.FindRoute(0, src, dst, ipv4.ProtocolNumber, false /* multicastLoop */)\n+ if err != nil {\n+ t.Fatalf(\"s.FindRoute got %v, want %v\", err, nil)\n+ }\n+ return rt\n+}\n+\n+// limitedEP is a link endpoint that writes up to a certain number of packets\n+// before returning errors.\n+type limitedEP struct {\n+ limit int\n+}\n+\n+// MTU implements LinkEndpoint.MTU.\n+func (*limitedEP) MTU() uint32 { return 0 }\n+\n+// Capabilities implements LinkEndpoint.Capabilities.\n+func (*limitedEP) Capabilities() stack.LinkEndpointCapabilities { return 0 }\n+\n+// MaxHeaderLength implements LinkEndpoint.MaxHeaderLength.\n+func (*limitedEP) MaxHeaderLength() uint16 { return 0 }\n+\n+// LinkAddress implements LinkEndpoint.LinkAddress.\n+func (*limitedEP) LinkAddress() tcpip.LinkAddress { return \"\" }\n+\n+// WritePacket implements LinkEndpoint.WritePacket.\n+func (ep *limitedEP) WritePacket(*stack.Route, *stack.GSO, tcpip.NetworkProtocolNumber, *stack.PacketBuffer) *tcpip.Error {\n+ if ep.limit == 0 {\n+ return tcpip.ErrInvalidEndpointState\n+ }\n+ ep.limit--\n+ return nil\n+}\n+\n+// WritePackets implements LinkEndpoint.WritePackets.\n+func (ep *limitedEP) WritePackets(_ *stack.Route, _ *stack.GSO, pkts stack.PacketBufferList, _ tcpip.NetworkProtocolNumber) (int, *tcpip.Error) {\n+ if ep.limit == 0 {\n+ return 0, tcpip.ErrInvalidEndpointState\n+ }\n+ nWritten := ep.limit\n+ if nWritten > pkts.Len() {\n+ nWritten = pkts.Len()\n+ }\n+ ep.limit -= nWritten\n+ return nWritten, nil\n+}\n+\n+// WriteRawPacket implements LinkEndpoint.WriteRawPacket.\n+func (ep *limitedEP) WriteRawPacket(_ buffer.VectorisedView) *tcpip.Error {\n+ if ep.limit == 0 {\n+ return tcpip.ErrInvalidEndpointState\n+ }\n+ ep.limit--\n+ return nil\n+}\n+\n+// Attach implements LinkEndpoint.Attach.\n+func (*limitedEP) Attach(_ stack.NetworkDispatcher) {}\n+\n+// IsAttached implements LinkEndpoint.IsAttached.\n+func (*limitedEP) IsAttached() bool { return false }\n+\n+// Wait implements LinkEndpoint.Wait.\n+func (*limitedEP) Wait() {}\n+\n+// ARPHardwareType implements LinkEndpoint.ARPHardwareType.\n+func (*limitedEP) ARPHardwareType() header.ARPHardwareType { return header.ARPHardwareEther }\n+\n+// AddHeader implements LinkEndpoint.AddHeader.\n+func (*limitedEP) AddHeader(_, _ tcpip.LinkAddress, _ tcpip.NetworkProtocolNumber, _ *stack.PacketBuffer) {\n+}\n+\n+// limitedMatcher is an iptables matcher that matches after a certain number of\n+// packets are checked against it.\n+type limitedMatcher struct {\n+ limit int\n+}\n+\n+// Name implements Matcher.Name.\n+func (*limitedMatcher) Name() string {\n+ return \"limitedMatcher\"\n+}\n+\n+// Match implements Matcher.Match.\n+func (lm *limitedMatcher) Match(stack.Hook, *stack.PacketBuffer, string) (bool, bool) {\n+ if lm.limit == 0 {\n+ return true, false\n+ }\n+ lm.limit--\n+ return false, false\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Test IPv4 WritePackets stats IPv6 tests will be added in another CL along with ip6tables. PiperOrigin-RevId: 332389102
259,985
17.09.2020 23:35:43
25,200
07d832dbb539e0bcca74800d09d0ea607d8173a3
fuse.DeviceFD needs to hold a reference on the associated filesystem. This fixes a use-after-free in fuse.DeviceFD.Release.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/dev.go", "new_path": "pkg/sentry/fsimpl/fuse/dev.go", "diff": "@@ -95,9 +95,14 @@ type DeviceFD struct {\n}\n// Release implements vfs.FileDescriptionImpl.Release.\n-func (fd *DeviceFD) Release(context.Context) {\n+func (fd *DeviceFD) Release(ctx context.Context) {\nif fd.fs != nil {\n+ fd.fs.conn.mu.Lock()\nfd.fs.conn.connected = false\n+ fd.fs.conn.mu.Unlock()\n+\n+ fd.fs.VFSFilesystem().DecRef(ctx)\n+ fd.fs = nil\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "new_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "diff": "@@ -218,6 +218,7 @@ func newFUSEFilesystem(ctx context.Context, devMinor uint32, opts *filesystemOpt\nconn: conn,\n}\n+ fs.VFSFilesystem().IncRef()\nfuseFD.fs = fs\nreturn fs, nil\n" } ]
Go
Apache License 2.0
google/gvisor
fuse.DeviceFD needs to hold a reference on the associated filesystem. This fixes a use-after-free in fuse.DeviceFD.Release. PiperOrigin-RevId: 332394146
260,004
18.09.2020 00:46:26
25,200
360006d894247ba78771d1244d5b849dabe3ce5a
Use common parsing utilities when sniffing Extract parsing utilities so they can be used by the sniffer. Fixes
[ { "change_type": "ADD", "old_path": null, "new_path": "pkg/tcpip/header/parse/BUILD", "diff": "+load(\"//tools:defs.bzl\", \"go_library\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_library(\n+ name = \"parse\",\n+ srcs = [\"parse.go\"],\n+ visibility = [\"//visibility:public\"],\n+ deps = [\n+ \"//pkg/tcpip\",\n+ \"//pkg/tcpip/buffer\",\n+ \"//pkg/tcpip/header\",\n+ \"//pkg/tcpip/stack\",\n+ ],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/tcpip/header/parse/parse.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// Package parse provides utilities to parse packets.\n+package parse\n+\n+import (\n+ \"fmt\"\n+\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/stack\"\n+)\n+\n+// ARP populates pkt's network header with an ARP header found in\n+// pkt.Data.\n+//\n+// Returns true if the header was successfully parsed.\n+func ARP(pkt *stack.PacketBuffer) bool {\n+ _, ok := pkt.NetworkHeader().Consume(header.ARPSize)\n+ if ok {\n+ pkt.NetworkProtocolNumber = header.ARPProtocolNumber\n+ }\n+ return ok\n+}\n+\n+// IPv4 parses an IPv4 packet found in pkt.Data and populates pkt's network\n+// header with the IPv4 header.\n+//\n+// Returns true if the header was successfully parsed.\n+func IPv4(pkt *stack.PacketBuffer) bool {\n+ hdr, ok := pkt.Data.PullUp(header.IPv4MinimumSize)\n+ if !ok {\n+ return false\n+ }\n+ ipHdr := header.IPv4(hdr)\n+\n+ // Header may have options, determine the true header length.\n+ headerLen := int(ipHdr.HeaderLength())\n+ if headerLen < header.IPv4MinimumSize {\n+ // TODO(gvisor.dev/issue/2404): Per RFC 791, IHL needs to be at least 5 in\n+ // order for the packet to be valid. Figure out if we want to reject this\n+ // case.\n+ headerLen = header.IPv4MinimumSize\n+ }\n+ hdr, ok = pkt.NetworkHeader().Consume(headerLen)\n+ if !ok {\n+ return false\n+ }\n+ ipHdr = header.IPv4(hdr)\n+\n+ pkt.NetworkProtocolNumber = header.IPv4ProtocolNumber\n+ pkt.Data.CapLength(int(ipHdr.TotalLength()) - len(hdr))\n+ return true\n+}\n+\n+// IPv6 parses an IPv6 packet found in pkt.Data and populates pkt's network\n+// header with the IPv6 header.\n+func IPv6(pkt *stack.PacketBuffer) (proto tcpip.TransportProtocolNumber, fragID uint32, fragOffset uint16, fragMore bool, ok bool) {\n+ hdr, ok := pkt.Data.PullUp(header.IPv6MinimumSize)\n+ if !ok {\n+ return 0, 0, 0, false, false\n+ }\n+ ipHdr := header.IPv6(hdr)\n+\n+ // dataClone consists of:\n+ // - Any IPv6 header bytes after the first 40 (i.e. extensions).\n+ // - The transport header, if present.\n+ // - Any other payload data.\n+ views := [8]buffer.View{}\n+ dataClone := pkt.Data.Clone(views[:])\n+ dataClone.TrimFront(header.IPv6MinimumSize)\n+ it := header.MakeIPv6PayloadIterator(header.IPv6ExtensionHeaderIdentifier(ipHdr.NextHeader()), dataClone)\n+\n+ // Iterate over the IPv6 extensions to find their length.\n+ var nextHdr tcpip.TransportProtocolNumber\n+ var extensionsSize int\n+\n+traverseExtensions:\n+ for {\n+ extHdr, done, err := it.Next()\n+ if err != nil {\n+ break\n+ }\n+\n+ // If we exhaust the extension list, the entire packet is the IPv6 header\n+ // and (possibly) extensions.\n+ if done {\n+ extensionsSize = dataClone.Size()\n+ break\n+ }\n+\n+ switch extHdr := extHdr.(type) {\n+ case header.IPv6FragmentExtHdr:\n+ if fragID == 0 && fragOffset == 0 && !fragMore {\n+ fragID = extHdr.ID()\n+ fragOffset = extHdr.FragmentOffset()\n+ fragMore = extHdr.More()\n+ }\n+\n+ case header.IPv6RawPayloadHeader:\n+ // We've found the payload after any extensions.\n+ extensionsSize = dataClone.Size() - extHdr.Buf.Size()\n+ nextHdr = tcpip.TransportProtocolNumber(extHdr.Identifier)\n+ break traverseExtensions\n+\n+ default:\n+ // Any other extension is a no-op, keep looping until we find the payload.\n+ }\n+ }\n+\n+ // Put the IPv6 header with extensions in pkt.NetworkHeader().\n+ hdr, ok = pkt.NetworkHeader().Consume(header.IPv6MinimumSize + extensionsSize)\n+ if !ok {\n+ panic(fmt.Sprintf(\"pkt.Data should have at least %d bytes, but only has %d.\", header.IPv6MinimumSize+extensionsSize, pkt.Data.Size()))\n+ }\n+ ipHdr = header.IPv6(hdr)\n+ pkt.Data.CapLength(int(ipHdr.PayloadLength()))\n+ pkt.NetworkProtocolNumber = header.IPv6ProtocolNumber\n+\n+ return nextHdr, fragID, fragOffset, fragMore, true\n+}\n+\n+// UDP parses a UDP packet found in pkt.Data and populates pkt's transport\n+// header with the UDP header.\n+//\n+// Returns true if the header was successfully parsed.\n+func UDP(pkt *stack.PacketBuffer) bool {\n+ _, ok := pkt.TransportHeader().Consume(header.UDPMinimumSize)\n+ return ok\n+}\n+\n+// TCP parses a TCP packet found in pkt.Data and populates pkt's transport\n+// header with the TCP header.\n+//\n+// Returns true if the header was successfully parsed.\n+func TCP(pkt *stack.PacketBuffer) bool {\n+ // TCP header is variable length, peek at it first.\n+ hdrLen := header.TCPMinimumSize\n+ hdr, ok := pkt.Data.PullUp(hdrLen)\n+ if !ok {\n+ return false\n+ }\n+\n+ // If the header has options, pull those up as well.\n+ if offset := int(header.TCP(hdr).DataOffset()); offset > header.TCPMinimumSize && offset <= pkt.Data.Size() {\n+ // TODO(gvisor.dev/issue/2404): Figure out whether to reject this kind of\n+ // packets.\n+ hdrLen = offset\n+ }\n+\n+ _, ok = pkt.TransportHeader().Consume(hdrLen)\n+ return ok\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/sniffer/BUILD", "new_path": "pkg/tcpip/link/sniffer/BUILD", "diff": "@@ -14,6 +14,7 @@ go_library(\n\"//pkg/tcpip\",\n\"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/header\",\n+ \"//pkg/tcpip/header/parse\",\n\"//pkg/tcpip/link/nested\",\n\"//pkg/tcpip/stack\",\n],\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/sniffer/sniffer.go", "new_path": "pkg/tcpip/link/sniffer/sniffer.go", "diff": "@@ -31,6 +31,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header/parse\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/nested\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n)\n@@ -195,49 +196,52 @@ func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, pkt *stack.P\nvar transProto uint8\nsrc := tcpip.Address(\"unknown\")\ndst := tcpip.Address(\"unknown\")\n- id := 0\n- size := uint16(0)\n+ var size uint16\n+ var id uint32\nvar fragmentOffset uint16\nvar moreFragments bool\n- // Examine the packet using a new VV. Backing storage must not be written.\n- vv := buffer.NewVectorisedView(pkt.Size(), pkt.Views())\n-\n+ // Clone the packet buffer to not modify the original.\n+ //\n+ // We don't clone the original packet buffer so that the new packet buffer\n+ // does not have any of its headers set.\n+ pkt = stack.NewPacketBuffer(stack.PacketBufferOptions{Data: buffer.NewVectorisedView(pkt.Size(), pkt.Views())})\nswitch protocol {\ncase header.IPv4ProtocolNumber:\n- hdr, ok := vv.PullUp(header.IPv4MinimumSize)\n- if !ok {\n+ if ok := parse.IPv4(pkt); !ok {\nreturn\n}\n- ipv4 := header.IPv4(hdr)\n+\n+ ipv4 := header.IPv4(pkt.NetworkHeader().View())\nfragmentOffset = ipv4.FragmentOffset()\nmoreFragments = ipv4.Flags()&header.IPv4FlagMoreFragments == header.IPv4FlagMoreFragments\nsrc = ipv4.SourceAddress()\ndst = ipv4.DestinationAddress()\ntransProto = ipv4.Protocol()\nsize = ipv4.TotalLength() - uint16(ipv4.HeaderLength())\n- vv.TrimFront(int(ipv4.HeaderLength()))\n- id = int(ipv4.ID())\n+ id = uint32(ipv4.ID())\ncase header.IPv6ProtocolNumber:\n- hdr, ok := vv.PullUp(header.IPv6MinimumSize)\n+ proto, fragID, fragOffset, fragMore, ok := parse.IPv6(pkt)\nif !ok {\nreturn\n}\n- ipv6 := header.IPv6(hdr)\n+\n+ ipv6 := header.IPv6(pkt.NetworkHeader().View())\nsrc = ipv6.SourceAddress()\ndst = ipv6.DestinationAddress()\n- transProto = ipv6.NextHeader()\n+ transProto = uint8(proto)\nsize = ipv6.PayloadLength()\n- vv.TrimFront(header.IPv6MinimumSize)\n+ id = fragID\n+ moreFragments = fragMore\n+ fragmentOffset = fragOffset\ncase header.ARPProtocolNumber:\n- hdr, ok := vv.PullUp(header.ARPSize)\n- if !ok {\n+ if parse.ARP(pkt) {\nreturn\n}\n- vv.TrimFront(header.ARPSize)\n- arp := header.ARP(hdr)\n+\n+ arp := header.ARP(pkt.NetworkHeader().View())\nlog.Infof(\n\"%s arp %s (%s) -> %s (%s) valid:%t\",\nprefix,\n@@ -259,7 +263,7 @@ func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, pkt *stack.P\nswitch tcpip.TransportProtocolNumber(transProto) {\ncase header.ICMPv4ProtocolNumber:\ntransName = \"icmp\"\n- hdr, ok := vv.PullUp(header.ICMPv4MinimumSize)\n+ hdr, ok := pkt.Data.PullUp(header.ICMPv4MinimumSize)\nif !ok {\nbreak\n}\n@@ -296,7 +300,7 @@ func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, pkt *stack.P\ncase header.ICMPv6ProtocolNumber:\ntransName = \"icmp\"\n- hdr, ok := vv.PullUp(header.ICMPv6MinimumSize)\n+ hdr, ok := pkt.Data.PullUp(header.ICMPv6MinimumSize)\nif !ok {\nbreak\n}\n@@ -331,11 +335,11 @@ func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, pkt *stack.P\ncase header.UDPProtocolNumber:\ntransName = \"udp\"\n- hdr, ok := vv.PullUp(header.UDPMinimumSize)\n- if !ok {\n+ if ok := parse.UDP(pkt); !ok {\nbreak\n}\n- udp := header.UDP(hdr)\n+\n+ udp := header.UDP(pkt.TransportHeader().View())\nif fragmentOffset == 0 {\nsrcPort = udp.SourcePort()\ndstPort = udp.DestinationPort()\n@@ -345,19 +349,19 @@ func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, pkt *stack.P\ncase header.TCPProtocolNumber:\ntransName = \"tcp\"\n- hdr, ok := vv.PullUp(header.TCPMinimumSize)\n- if !ok {\n+ if ok := parse.TCP(pkt); !ok {\nbreak\n}\n- tcp := header.TCP(hdr)\n+\n+ tcp := header.TCP(pkt.TransportHeader().View())\nif fragmentOffset == 0 {\noffset := int(tcp.DataOffset())\nif offset < header.TCPMinimumSize {\ndetails += fmt.Sprintf(\"invalid packet: tcp data offset too small %d\", offset)\nbreak\n}\n- if offset > vv.Size() && !moreFragments {\n- details += fmt.Sprintf(\"invalid packet: tcp data offset %d larger than packet buffer length %d\", offset, vv.Size())\n+ if size := pkt.Data.Size() + len(tcp); offset > size && !moreFragments {\n+ details += fmt.Sprintf(\"invalid packet: tcp data offset %d larger than tcp packet length %d\", offset, size)\nbreak\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/arp/BUILD", "new_path": "pkg/tcpip/network/arp/BUILD", "diff": "@@ -10,6 +10,7 @@ go_library(\n\"//pkg/tcpip\",\n\"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/header\",\n+ \"//pkg/tcpip/header/parse\",\n\"//pkg/tcpip/stack\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/arp/arp.go", "new_path": "pkg/tcpip/network/arp/arp.go", "diff": "@@ -29,6 +29,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header/parse\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n)\n@@ -234,11 +235,7 @@ func (*protocol) Wait() {}\n// Parse implements stack.NetworkProtocol.Parse.\nfunc (*protocol) Parse(pkt *stack.PacketBuffer) (proto tcpip.TransportProtocolNumber, hasTransportHdr bool, ok bool) {\n- _, ok = pkt.NetworkHeader().Consume(header.ARPSize)\n- if !ok {\n- return 0, false, false\n- }\n- return 0, false, true\n+ return 0, false, parse.ARP(pkt)\n}\n// NewProtocol returns an ARP network protocol.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/BUILD", "new_path": "pkg/tcpip/network/ipv4/BUILD", "diff": "@@ -13,6 +13,7 @@ go_library(\n\"//pkg/tcpip\",\n\"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/header\",\n+ \"//pkg/tcpip/header/parse\",\n\"//pkg/tcpip/network/fragmentation\",\n\"//pkg/tcpip/network/hash\",\n\"//pkg/tcpip/stack\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4.go", "new_path": "pkg/tcpip/network/ipv4/ipv4.go", "diff": "@@ -26,6 +26,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header/parse\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/fragmentation\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/hash\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n@@ -529,37 +530,14 @@ func (*protocol) Close() {}\n// Wait implements stack.TransportProtocol.Wait.\nfunc (*protocol) Wait() {}\n-// Parse implements stack.TransportProtocol.Parse.\n+// Parse implements stack.NetworkProtocol.Parse.\nfunc (*protocol) Parse(pkt *stack.PacketBuffer) (proto tcpip.TransportProtocolNumber, hasTransportHdr bool, ok bool) {\n- hdr, ok := pkt.Data.PullUp(header.IPv4MinimumSize)\n- if !ok {\n+ if ok := parse.IPv4(pkt); !ok {\nreturn 0, false, false\n}\n- ipHdr := header.IPv4(hdr)\n- // Header may have options, determine the true header length.\n- headerLen := int(ipHdr.HeaderLength())\n- if headerLen < header.IPv4MinimumSize {\n- // TODO(gvisor.dev/issue/2404): Per RFC 791, IHL needs to be at least 5 in\n- // order for the packet to be valid. Figure out if we want to reject this\n- // case.\n- headerLen = header.IPv4MinimumSize\n- }\n- hdr, ok = pkt.NetworkHeader().Consume(headerLen)\n- if !ok {\n- return 0, false, false\n- }\n- ipHdr = header.IPv4(hdr)\n-\n- // If this is a fragment, don't bother parsing the transport header.\n- parseTransportHeader := true\n- if ipHdr.More() || ipHdr.FragmentOffset() != 0 {\n- parseTransportHeader = false\n- }\n-\n- pkt.NetworkProtocolNumber = header.IPv4ProtocolNumber\n- pkt.Data.CapLength(int(ipHdr.TotalLength()) - len(hdr))\n- return ipHdr.TransportProtocol(), parseTransportHeader, true\n+ ipHdr := header.IPv4(pkt.NetworkHeader().View())\n+ return ipHdr.TransportProtocol(), !ipHdr.More() && ipHdr.FragmentOffset() == 0, true\n}\n// calculateMTU calculates the network-layer payload MTU based on the link-layer\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/BUILD", "new_path": "pkg/tcpip/network/ipv6/BUILD", "diff": "@@ -13,6 +13,7 @@ go_library(\n\"//pkg/tcpip\",\n\"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/header\",\n+ \"//pkg/tcpip/header/parse\",\n\"//pkg/tcpip/network/fragmentation\",\n\"//pkg/tcpip/stack\",\n],\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6.go", "new_path": "pkg/tcpip/network/ipv6/ipv6.go", "diff": "@@ -27,6 +27,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header/parse\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/fragmentation\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n)\n@@ -574,75 +575,14 @@ func (*protocol) Close() {}\n// Wait implements stack.TransportProtocol.Wait.\nfunc (*protocol) Wait() {}\n-// Parse implements stack.TransportProtocol.Parse.\n+// Parse implements stack.NetworkProtocol.Parse.\nfunc (*protocol) Parse(pkt *stack.PacketBuffer) (proto tcpip.TransportProtocolNumber, hasTransportHdr bool, ok bool) {\n- hdr, ok := pkt.Data.PullUp(header.IPv6MinimumSize)\n+ proto, _, fragOffset, fragMore, ok := parse.IPv6(pkt)\nif !ok {\nreturn 0, false, false\n}\n- ipHdr := header.IPv6(hdr)\n- // dataClone consists of:\n- // - Any IPv6 header bytes after the first 40 (i.e. extensions).\n- // - The transport header, if present.\n- // - Any other payload data.\n- views := [8]buffer.View{}\n- dataClone := pkt.Data.Clone(views[:])\n- dataClone.TrimFront(header.IPv6MinimumSize)\n- it := header.MakeIPv6PayloadIterator(header.IPv6ExtensionHeaderIdentifier(ipHdr.NextHeader()), dataClone)\n-\n- // Iterate over the IPv6 extensions to find their length.\n- //\n- // Parsing occurs again in HandlePacket because we don't track the\n- // extensions in PacketBuffer. Unfortunately, that means HandlePacket\n- // has to do the parsing work again.\n- var nextHdr tcpip.TransportProtocolNumber\n- foundNext := true\n- extensionsSize := 0\n-traverseExtensions:\n- for extHdr, done, err := it.Next(); ; extHdr, done, err = it.Next() {\n- if err != nil {\n- break\n- }\n- // If we exhaust the extension list, the entire packet is the IPv6 header\n- // and (possibly) extensions.\n- if done {\n- extensionsSize = dataClone.Size()\n- foundNext = false\n- break\n- }\n-\n- switch extHdr := extHdr.(type) {\n- case header.IPv6FragmentExtHdr:\n- // If this is an atomic fragment, we don't have to treat it specially.\n- if !extHdr.More() && extHdr.FragmentOffset() == 0 {\n- continue\n- }\n- // This is a non-atomic fragment and has to be re-assembled before we can\n- // examine the payload for a transport header.\n- foundNext = false\n-\n- case header.IPv6RawPayloadHeader:\n- // We've found the payload after any extensions.\n- extensionsSize = dataClone.Size() - extHdr.Buf.Size()\n- nextHdr = tcpip.TransportProtocolNumber(extHdr.Identifier)\n- break traverseExtensions\n-\n- default:\n- // Any other extension is a no-op, keep looping until we find the payload.\n- }\n- }\n-\n- // Put the IPv6 header with extensions in pkt.NetworkHeader().\n- hdr, ok = pkt.NetworkHeader().Consume(header.IPv6MinimumSize + extensionsSize)\n- if !ok {\n- panic(fmt.Sprintf(\"pkt.Data should have at least %d bytes, but only has %d.\", header.IPv6MinimumSize+extensionsSize, pkt.Data.Size()))\n- }\n- ipHdr = header.IPv6(hdr)\n- pkt.Data.CapLength(int(ipHdr.PayloadLength()))\n- pkt.NetworkProtocolNumber = header.IPv6ProtocolNumber\n-\n- return nextHdr, foundNext, true\n+ return proto, !fragMore && fragOffset == 0, true\n}\n// calculateMTU calculates the network-layer payload MTU based on the link-layer\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/BUILD", "new_path": "pkg/tcpip/transport/tcp/BUILD", "diff": "@@ -69,6 +69,7 @@ go_library(\n\"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/hash/jenkins\",\n\"//pkg/tcpip/header\",\n+ \"//pkg/tcpip/header/parse\",\n\"//pkg/tcpip/ports\",\n\"//pkg/tcpip/seqnum\",\n\"//pkg/tcpip/stack\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/protocol.go", "new_path": "pkg/tcpip/transport/tcp/protocol.go", "diff": "@@ -29,6 +29,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header/parse\"\n\"gvisor.dev/gvisor/pkg/tcpip/seqnum\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/raw\"\n@@ -506,22 +507,7 @@ func (p *protocol) SynRcvdCounter() *synRcvdCounter {\n// Parse implements stack.TransportProtocol.Parse.\nfunc (*protocol) Parse(pkt *stack.PacketBuffer) bool {\n- // TCP header is variable length, peek at it first.\n- hdrLen := header.TCPMinimumSize\n- hdr, ok := pkt.Data.PullUp(hdrLen)\n- if !ok {\n- return false\n- }\n-\n- // If the header has options, pull those up as well.\n- if offset := int(header.TCP(hdr).DataOffset()); offset > header.TCPMinimumSize && offset <= pkt.Data.Size() {\n- // TODO(gvisor.dev/issue/2404): Figure out whether to reject this kind of\n- // packets.\n- hdrLen = offset\n- }\n-\n- _, ok = pkt.TransportHeader().Consume(hdrLen)\n- return ok\n+ return parse.TCP(pkt)\n}\n// NewProtocol returns a TCP transport protocol.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/BUILD", "new_path": "pkg/tcpip/transport/udp/BUILD", "diff": "@@ -32,6 +32,7 @@ go_library(\n\"//pkg/tcpip\",\n\"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/header\",\n+ \"//pkg/tcpip/header/parse\",\n\"//pkg/tcpip/ports\",\n\"//pkg/tcpip/stack\",\n\"//pkg/tcpip/transport/raw\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/protocol.go", "new_path": "pkg/tcpip/transport/udp/protocol.go", "diff": "@@ -24,6 +24,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header/parse\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/raw\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n@@ -219,8 +220,7 @@ func (*protocol) Wait() {}\n// Parse implements stack.TransportProtocol.Parse.\nfunc (*protocol) Parse(pkt *stack.PacketBuffer) bool {\n- _, ok := pkt.TransportHeader().Consume(header.UDPMinimumSize)\n- return ok\n+ return parse.UDP(pkt)\n}\n// NewProtocol returns a UDP transport protocol.\n" } ]
Go
Apache License 2.0
google/gvisor
Use common parsing utilities when sniffing Extract parsing utilities so they can be used by the sniffer. Fixes #3930 PiperOrigin-RevId: 332401880
259,881
18.09.2020 09:54:00
25,200
313e1988c4609c74ada99c1a5e9ecde56c313125
Drop ARCH_GET_FS Go does not call arch_prctl(ARCH_GET_FS), nor am I sure it ever did. Drop the filter.
[ { "change_type": "MODIFY", "old_path": "runsc/boot/filter/config_amd64.go", "new_path": "runsc/boot/filter/config_amd64.go", "diff": "@@ -25,7 +25,6 @@ import (\nfunc init() {\nallowedSyscalls[syscall.SYS_ARCH_PRCTL] = append(allowedSyscalls[syscall.SYS_ARCH_PRCTL],\n- seccomp.Rule{seccomp.EqualTo(linux.ARCH_GET_FS)},\nseccomp.Rule{seccomp.EqualTo(linux.ARCH_SET_FS)},\n)\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/fsgofer/filter/config_amd64.go", "new_path": "runsc/fsgofer/filter/config_amd64.go", "diff": "@@ -25,7 +25,6 @@ import (\nfunc init() {\nallowedSyscalls[syscall.SYS_ARCH_PRCTL] = []seccomp.Rule{\n- {seccomp.EqualTo(linux.ARCH_GET_FS)},\n{seccomp.EqualTo(linux.ARCH_SET_FS)},\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Drop ARCH_GET_FS Go does not call arch_prctl(ARCH_GET_FS), nor am I sure it ever did. Drop the filter. PiperOrigin-RevId: 332470532
259,992
18.09.2020 10:25:52
25,200
93fd164fa24e1f70e4c69fc2edfb0d4961a6683b
Add "Containing a Real Vulnerability" blog post
[ { "change_type": "MODIFY", "old_path": "images/jekyll/build.sh", "new_path": "images/jekyll/build.sh", "diff": "@@ -18,4 +18,5 @@ set -euxo pipefail\n# Generate the syntax highlighting css file.\n/usr/gem/bin/rougify style github >/input/_sass/syntax.css\n-/usr/gem/bin/jekyll build -t -s /input -d /output\n+# Build website including pages irrespective of date.\n+/usr/gem/bin/jekyll build --future -t -s /input -d /output\n" }, { "change_type": "MODIFY", "old_path": "website/_config.yml", "new_path": "website/_config.yml", "diff": "@@ -34,3 +34,6 @@ authors:\nigudger:\nname: Ian Gudger\nemail: [email protected]\n+ fvoznika:\n+ name: Fabricio Voznika\n+ email: [email protected]\n" }, { "change_type": "ADD", "old_path": "website/assets/images/2020-09-18-containing-a-real-vulnerability-figure1.png", "new_path": "website/assets/images/2020-09-18-containing-a-real-vulnerability-figure1.png", "diff": "Binary files /dev/null and b/website/assets/images/2020-09-18-containing-a-real-vulnerability-figure1.png differ\n" }, { "change_type": "MODIFY", "old_path": "website/blog/2019-11-18-security-basics.md", "new_path": "website/blog/2019-11-18-security-basics.md", "diff": "@@ -279,8 +279,10 @@ weaknesses of each gVisor component.\nWe will also use it to introduce Google's Vulnerability Reward Program[^14], and\nother ways the community can contribute to help make gVisor safe, fast and\nstable.\n+<br>\n+<br>\n-## Notes\n+--------------------------------------------------------------------------------\n[^1]: [https://en.wikipedia.org/wiki/Secure_by_design](https://en.wikipedia.org/wiki/Secure_by_design)\n[^2]: [https://gvisor.dev/docs/architecture_guide](https://gvisor.dev/docs/architecture_guide/)\n" }, { "change_type": "MODIFY", "old_path": "website/blog/BUILD", "new_path": "website/blog/BUILD", "diff": "@@ -28,6 +28,16 @@ doc(\npermalink = \"/blog/2020/04/02/gvisor-networking-security/\",\n)\n+doc(\n+ name = \"containing_a_real_vulnerability\",\n+ src = \"2020-09-18-containing-a-real-vulnerability.md\",\n+ authors = [\n+ \"fvoznika\",\n+ ],\n+ layout = \"post\",\n+ permalink = \"/blog/2020/09/18/containing-a-real-vulnerability/\",\n+)\n+\ndocs(\nname = \"posts\",\ndeps = [\n" } ]
Go
Apache License 2.0
google/gvisor
Add "Containing a Real Vulnerability" blog post PiperOrigin-RevId: 332477119
260,023
18.09.2020 10:47:52
25,200
fcf8d7c6ddac1146cf0d48f833c982cbfb0991e5
Enqueue TCP sends arriving in SYN_SENT state. TCP needs to enqueue any send requests arriving when the connection is in SYN_SENT state. The data should be sent out soon after completion of the connection handshake. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint.go", "new_path": "pkg/tcpip/transport/tcp/endpoint.go", "diff": "@@ -1317,14 +1317,17 @@ func (e *endpoint) readLocked() (buffer.View, *tcpip.Error) {\n// indicating the reason why it's not writable.\n// Caller must hold e.mu and e.sndBufMu\nfunc (e *endpoint) isEndpointWritableLocked() (int, *tcpip.Error) {\n- // The endpoint cannot be written to if it's not connected.\n- if !e.EndpointState().connected() {\n- switch e.EndpointState() {\n- case StateError:\n+ switch s := e.EndpointState(); {\n+ case s == StateError:\nreturn 0, e.HardError\n- default:\n+ case !s.connecting() && !s.connected():\nreturn 0, tcpip.ErrClosedForSend\n- }\n+ case s.connecting():\n+ // As per RFC793, page 56, a send request arriving when in connecting\n+ // state, can be queued to be completed after the state becomes\n+ // connected. Return an error code for the caller of endpoint Write to\n+ // try again, until the connection handshake is complete.\n+ return 0, tcpip.ErrWouldBlock\n}\n// Check if the connection has already been closed for sends.\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/BUILD", "new_path": "test/packetimpact/tests/BUILD", "diff": "@@ -271,6 +271,16 @@ packetimpact_go_test(\n],\n)\n+packetimpact_go_test(\n+ name = \"tcp_queue_send_in_syn_sent\",\n+ srcs = [\"tcp_queue_send_in_syn_sent_test.go\"],\n+ deps = [\n+ \"//pkg/tcpip/header\",\n+ \"//test/packetimpact/testbench\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n+ ],\n+)\n+\npacketimpact_go_test(\nname = \"icmpv6_param_problem\",\nsrcs = [\"icmpv6_param_problem_test.go\"],\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/packetimpact/tests/tcp_queue_send_in_syn_sent_test.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package tcp_queue_send_in_syn_sent_test\n+\n+import (\n+ \"context\"\n+ \"errors\"\n+ \"flag\"\n+ \"net\"\n+ \"sync\"\n+ \"syscall\"\n+ \"testing\"\n+ \"time\"\n+\n+ \"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/test/packetimpact/testbench\"\n+)\n+\n+func init() {\n+ testbench.RegisterFlags(flag.CommandLine)\n+}\n+\n+// TestQueueSendInSynSent tests send behavior when the TCP state\n+// is SYN-SENT.\n+// It tests for 2 variants when in SYN_SENT state and:\n+// (1) DUT blocks on send and complete handshake\n+// (2) DUT blocks on send and receive a TCP RST.\n+func TestQueueSendInSynSent(t *testing.T) {\n+ for _, tt := range []struct {\n+ description string\n+ reset bool\n+ }{\n+ {description: \"Complete handshake\", reset: false},\n+ {description: \"Send RST\", reset: true},\n+ } {\n+ t.Run(tt.description, func(t *testing.T) {\n+ dut := testbench.NewDUT(t)\n+ defer dut.TearDown()\n+\n+ socket, remotePort := dut.CreateBoundSocket(t, unix.SOCK_STREAM, unix.IPPROTO_TCP, net.ParseIP(testbench.RemoteIPv4))\n+ conn := testbench.NewTCPIPv4(t, testbench.TCP{DstPort: &remotePort}, testbench.TCP{SrcPort: &remotePort})\n+ defer conn.Close(t)\n+\n+ sampleData := []byte(\"Sample Data\")\n+ samplePayload := &testbench.Payload{Bytes: sampleData}\n+ dut.SetNonBlocking(t, socket, true)\n+ if _, err := dut.ConnectWithErrno(context.Background(), t, socket, conn.LocalAddr(t)); !errors.Is(err, syscall.EINPROGRESS) {\n+ t.Fatalf(\"failed to bring DUT to SYN-SENT, got: %s, want EINPROGRESS\", err)\n+ }\n+ if _, err := conn.Expect(t, testbench.TCP{Flags: testbench.Uint8(header.TCPFlagSyn)}, time.Second); err != nil {\n+ t.Fatalf(\"expected a SYN from DUT, but got none: %s\", err)\n+ }\n+ if _, err := dut.SendWithErrno(context.Background(), t, socket, sampleData, 0); err != syscall.Errno(unix.EWOULDBLOCK) {\n+ t.Fatalf(\"expected error %s, got %s\", syscall.Errno(unix.EWOULDBLOCK), err)\n+ }\n+\n+ // Test blocking write.\n+ dut.SetNonBlocking(t, socket, false)\n+\n+ var wg sync.WaitGroup\n+ defer wg.Wait()\n+ wg.Add(1)\n+ var block sync.WaitGroup\n+ block.Add(1)\n+ go func() {\n+ defer wg.Done()\n+ ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)\n+ defer cancel()\n+\n+ block.Done()\n+ // Issue SEND call in SYN-SENT, this should be queued for\n+ // process until the connection is established.\n+ n, err := dut.SendWithErrno(ctx, t, socket, sampleData, 0)\n+ if tt.reset {\n+ if err != syscall.Errno(unix.ECONNREFUSED) {\n+ t.Errorf(\"expected error %s, got %s\", syscall.Errno(unix.ECONNREFUSED), err)\n+ }\n+ if n != -1 {\n+ t.Errorf(\"expected return value %d, got %d\", -1, n)\n+ }\n+ return\n+ }\n+ if n != int32(len(sampleData)) {\n+ t.Errorf(\"failed to send on DUT: %s\", err)\n+ }\n+ }()\n+\n+ // Wait for the goroutine to be scheduled and before it\n+ // blocks on endpoint send.\n+ block.Wait()\n+ // The following sleep is used to prevent the connection\n+ // from being established before we are blocked on send.\n+ time.Sleep(100 * time.Millisecond)\n+\n+ if tt.reset {\n+ conn.Send(t, testbench.TCP{Flags: testbench.Uint8(header.TCPFlagRst | header.TCPFlagAck)})\n+ return\n+ }\n+\n+ // Bring the connection to Established.\n+ conn.Send(t, testbench.TCP{Flags: testbench.Uint8(header.TCPFlagSyn | header.TCPFlagAck)})\n+\n+ // Expect the data from the DUT's enqueued send request.\n+ //\n+ // On Linux, this can be piggybacked with the ACK completing the\n+ // handshake. On gVisor, getting such a piggyback is a bit more\n+ // complicated because the actual data enqueuing occurs in the\n+ // callers of endpoint Write.\n+ if _, err := conn.ExpectData(t, &testbench.TCP{Flags: testbench.Uint8(header.TCPFlagPsh | header.TCPFlagAck)}, samplePayload, time.Second); err != nil {\n+ t.Fatalf(\"expected payload was not received: %s\", err)\n+ }\n+\n+ // Send sample payload and expect an ACK to ensure connection is still ESTABLISHED.\n+ conn.Send(t, testbench.TCP{Flags: testbench.Uint8(header.TCPFlagPsh | header.TCPFlagAck)}, &testbench.Payload{Bytes: sampleData})\n+ if _, err := conn.Expect(t, testbench.TCP{Flags: testbench.Uint8(header.TCPFlagAck)}, time.Second); err != nil {\n+ t.Fatalf(\"expected an ACK from DUT, but got none: %s\", err)\n+ }\n+ })\n+ }\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Enqueue TCP sends arriving in SYN_SENT state. TCP needs to enqueue any send requests arriving when the connection is in SYN_SENT state. The data should be sent out soon after completion of the connection handshake. Fixes #3995 PiperOrigin-RevId: 332482041
259,891
18.09.2020 11:06:53
25,200
bd69afdcd1c9303602aadce9e59aecff3eb7b9c8
Count packets dropped by iptables in IPStats
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -158,6 +158,9 @@ var Metrics = tcpip.Stats{\nOutgoingPacketErrors: mustCreateMetric(\"/netstack/ip/outgoing_packet_errors\", \"Total number of IP packets which failed to write to a link-layer endpoint.\"),\nMalformedPacketsReceived: mustCreateMetric(\"/netstack/ip/malformed_packets_received\", \"Total number of IP packets which failed IP header validation checks.\"),\nMalformedFragmentsReceived: mustCreateMetric(\"/netstack/ip/malformed_fragments_received\", \"Total number of IP fragments which failed IP fragment validation checks.\"),\n+ IPTablesPreroutingDropped: mustCreateMetric(\"/netstack/ip/iptables/prerouting_dropped\", \"Total number of IP packets dropped in the Prerouting chain.\"),\n+ IPTablesInputDropped: mustCreateMetric(\"/netstack/ip/iptables/input_dropped\", \"Total number of IP packets dropped in the Input chain.\"),\n+ IPTablesOutputDropped: mustCreateMetric(\"/netstack/ip/iptables/output_dropped\", \"Total number of IP packets dropped in the Output chain.\"),\n},\nTCP: tcpip.TCPStats{\nActiveConnectionOpenings: mustCreateMetric(\"/netstack/tcp/active_connection_openings\", \"Number of connections opened successfully via Connect.\"),\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4.go", "new_path": "pkg/tcpip/network/ipv4/ipv4.go", "diff": "@@ -236,6 +236,7 @@ func (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, params stack.Netw\nipt := e.stack.IPTables()\nif ok := ipt.Check(stack.Output, pkt, gso, r, \"\", nicName); !ok {\n// iptables is telling us to drop the packet.\n+ r.Stats().IP.IPTablesOutputDropped.Increment()\nreturn nil\n}\n@@ -300,6 +301,7 @@ func (e *endpoint) WritePackets(r *stack.Route, gso *stack.GSO, pkts stack.Packe\nr.Stats().IP.PacketsSent.IncrementBy(uint64(n))\nreturn n, err\n}\n+ r.Stats().IP.IPTablesOutputDropped.IncrementBy(uint64(len(dropped)))\n// Slow path as we are dropping some packets in the batch degrade to\n// emitting one packet at a time.\n@@ -321,12 +323,15 @@ func (e *endpoint) WritePackets(r *stack.Route, gso *stack.GSO, pkts stack.Packe\n}\nif err := e.linkEP.WritePacket(r, gso, ProtocolNumber, pkt); err != nil {\nr.Stats().IP.PacketsSent.IncrementBy(uint64(n))\n- return n, err\n+ // Dropped packets aren't errors, so include them in\n+ // the return value.\n+ return n + len(dropped), err\n}\nn++\n}\nr.Stats().IP.PacketsSent.IncrementBy(uint64(n))\n- return n, nil\n+ // Dropped packets aren't errors, so include them in the return value.\n+ return n + len(dropped), nil\n}\n// WriteHeaderIncludedPacket writes a packet already containing a network\n@@ -395,6 +400,7 @@ func (e *endpoint) HandlePacket(r *stack.Route, pkt *stack.PacketBuffer) {\nipt := e.stack.IPTables()\nif ok := ipt.Check(stack.Input, pkt, nil, nil, \"\", \"\"); !ok {\n// iptables is telling us to drop the packet.\n+ r.Stats().IP.IPTablesInputDropped.Increment()\nreturn\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4_test.go", "new_path": "pkg/tcpip/network/ipv4/ipv4_test.go", "diff": "@@ -1047,26 +1047,32 @@ func TestReceiveFragments(t *testing.T) {\n}\n}\n-func TestWritePacketsStats(t *testing.T) {\n+func TestWriteStats(t *testing.T) {\nconst nPackets = 3\ntests := []struct {\nname string\nsetup func(*testing.T, *stack.Stack)\n- linkEP stack.LinkEndpoint\n+ linkEP func() stack.LinkEndpoint\nexpectSent int\n+ expectDropped int\n+ expectWritten int\n}{\n{\nname: \"Accept all\",\n// No setup needed, tables accept everything by default.\nsetup: func(*testing.T, *stack.Stack) {},\n- linkEP: &limitedEP{nPackets},\n+ linkEP: func() stack.LinkEndpoint { return &limitedEP{nPackets} },\nexpectSent: nPackets,\n+ expectDropped: 0,\n+ expectWritten: nPackets,\n}, {\nname: \"Accept all with error\",\n// No setup needed, tables accept everything by default.\nsetup: func(*testing.T, *stack.Stack) {},\n- linkEP: &limitedEP{nPackets - 1},\n+ linkEP: func() stack.LinkEndpoint { return &limitedEP{nPackets - 1} },\nexpectSent: nPackets - 1,\n+ expectDropped: 0,\n+ expectWritten: nPackets - 1,\n}, {\nname: \"Drop all\",\nsetup: func(t *testing.T, stk *stack.Stack) {\n@@ -1083,8 +1089,10 @@ func TestWritePacketsStats(t *testing.T) {\nt.Fatalf(\"failed to replace table: %v\", err)\n}\n},\n- linkEP: &limitedEP{nPackets},\n+ linkEP: func() stack.LinkEndpoint { return &limitedEP{nPackets} },\nexpectSent: 0,\n+ expectDropped: nPackets,\n+ expectWritten: nPackets,\n}, {\nname: \"Drop some\",\nsetup: func(t *testing.T, stk *stack.Stack) {\n@@ -1106,38 +1114,68 @@ func TestWritePacketsStats(t *testing.T) {\nt.Fatalf(\"failed to replace table: %v\", err)\n}\n},\n- linkEP: &limitedEP{nPackets},\n+ linkEP: func() stack.LinkEndpoint { return &limitedEP{nPackets} },\nexpectSent: nPackets - 1,\n+ expectDropped: 1,\n+ expectWritten: nPackets,\n},\n}\n+ // Parameterize the tests to run with both WritePacket and WritePackets.\n+ writers := []struct {\n+ name string\n+ writePackets func(*stack.Route, stack.PacketBufferList) (int, *tcpip.Error)\n+ }{\n+ {\n+ name: \"WritePacket\",\n+ writePackets: func(rt *stack.Route, pkts stack.PacketBufferList) (int, *tcpip.Error) {\n+ nWritten := 0\n+ for pkt := pkts.Front(); pkt != nil; pkt = pkt.Next() {\n+ if err := rt.WritePacket(nil, stack.NetworkHeaderParams{}, pkt); err != nil {\n+ return nWritten, err\n+ }\n+ nWritten++\n+ }\n+ return nWritten, nil\n+ },\n+ }, {\n+ name: \"WritePackets\",\n+ writePackets: func(rt *stack.Route, pkts stack.PacketBufferList) (int, *tcpip.Error) {\n+ return rt.WritePackets(nil, pkts, stack.NetworkHeaderParams{})\n+ },\n+ },\n+ }\n+\n+ for _, writer := range writers {\n+ t.Run(writer.name, func(t *testing.T) {\nfor _, test := range tests {\nt.Run(test.name, func(t *testing.T) {\n- rt := buildRoute(t, nil, test.linkEP)\n+ rt := buildRoute(t, nil, test.linkEP())\n- var pbl stack.PacketBufferList\n+ var pkts stack.PacketBufferList\nfor i := 0; i < nPackets; i++ {\npkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\nReserveHeaderBytes: header.UDPMinimumSize + int(rt.MaxHeaderLength()),\n- Data: buffer.NewView(1).ToVectorisedView(),\n+ Data: buffer.NewView(0).ToVectorisedView(),\n})\npkt.TransportHeader().Push(header.UDPMinimumSize)\n- pbl.PushBack(pkt)\n+ pkts.PushBack(pkt)\n}\ntest.setup(t, rt.Stack())\n- nWritten, err := rt.WritePackets(nil, pbl, stack.NetworkHeaderParams{})\n- if err != nil {\n- t.Fatal(err)\n- }\n+ nWritten, _ := writer.writePackets(&rt, pkts)\n- got := int(rt.Stats().IP.PacketsSent.Value())\n- if got != test.expectSent {\n+ if got := int(rt.Stats().IP.PacketsSent.Value()); got != test.expectSent {\nt.Errorf(\"sent %d packets, but expected to send %d\", got, test.expectSent)\n}\n- if got != nWritten {\n- t.Errorf(\"sent %d packets, WritePackets returned %d\", got, nWritten)\n+ if got := int(rt.Stats().IP.IPTablesOutputDropped.Value()); got != test.expectDropped {\n+ t.Errorf(\"dropped %d packets, but expected to drop %d\", got, test.expectDropped)\n+ }\n+ if nWritten != test.expectWritten {\n+ t.Errorf(\"wrote %d packets, but expected WritePackets to return %d\", nWritten, test.expectWritten)\n+ }\n+ })\n}\n})\n}\n@@ -1177,7 +1215,10 @@ type limitedEP struct {\n}\n// MTU implements LinkEndpoint.MTU.\n-func (*limitedEP) MTU() uint32 { return 0 }\n+func (*limitedEP) MTU() uint32 {\n+ // Give an MTU that won't cause fragmentation for IPv4+UDP.\n+ return header.IPv4MinimumSize + header.UDPMinimumSize\n+}\n// Capabilities implements LinkEndpoint.Capabilities.\nfunc (*limitedEP) Capabilities() stack.LinkEndpointCapabilities { return 0 }\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6.go", "new_path": "pkg/tcpip/network/ipv6/ipv6.go", "diff": "@@ -114,6 +114,7 @@ func (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, params stack.Netw\nipt := e.stack.IPTables()\nif ok := ipt.Check(stack.Output, pkt, gso, r, \"\", nicName); !ok {\n// iptables is telling us to drop the packet.\n+ r.Stats().IP.IPTablesOutputDropped.Increment()\nreturn nil\n}\n@@ -147,8 +148,11 @@ func (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, params stack.Netw\nreturn nil\n}\n+ if err := e.linkEP.WritePacket(r, gso, ProtocolNumber, pkt); err != nil {\n+ return err\n+ }\nr.Stats().IP.PacketsSent.Increment()\n- return e.linkEP.WritePacket(r, gso, ProtocolNumber, pkt)\n+ return nil\n}\n// WritePackets implements stack.LinkEndpoint.WritePackets.\n@@ -176,6 +180,7 @@ func (e *endpoint) WritePackets(r *stack.Route, gso *stack.GSO, pkts stack.Packe\nr.Stats().IP.PacketsSent.IncrementBy(uint64(n))\nreturn n, err\n}\n+ r.Stats().IP.IPTablesOutputDropped.IncrementBy(uint64(len(dropped)))\n// Slow path as we are dropping some packets in the batch degrade to\n// emitting one packet at a time.\n@@ -197,13 +202,16 @@ func (e *endpoint) WritePackets(r *stack.Route, gso *stack.GSO, pkts stack.Packe\n}\nif err := e.linkEP.WritePacket(r, gso, ProtocolNumber, pkt); err != nil {\nr.Stats().IP.PacketsSent.IncrementBy(uint64(n))\n- return n, err\n+ // Dropped packets aren't errors, so include them in\n+ // the return value.\n+ return n + len(dropped), err\n}\nn++\n}\nr.Stats().IP.PacketsSent.IncrementBy(uint64(n))\n- return n, nil\n+ // Dropped packets aren't errors, so include them in the return value.\n+ return n + len(dropped), nil\n}\n// WriteHeaderIncludedPacker implements stack.NetworkEndpoint. It is not yet\n@@ -237,6 +245,7 @@ func (e *endpoint) HandlePacket(r *stack.Route, pkt *stack.PacketBuffer) {\nipt := e.stack.IPTables()\nif ok := ipt.Check(stack.Input, pkt, nil, nil, \"\", \"\"); !ok {\n// iptables is telling us to drop the packet.\n+ r.Stats().IP.IPTablesInputDropped.Increment()\nreturn\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "new_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "diff": "@@ -1710,26 +1710,32 @@ func TestInvalidIPv6Fragments(t *testing.T) {\n}\n}\n-func TestWritePacketsStats(t *testing.T) {\n+func TestWriteStats(t *testing.T) {\nconst nPackets = 3\ntests := []struct {\nname string\nsetup func(*testing.T, *stack.Stack)\n- linkEP stack.LinkEndpoint\n+ linkEP func() stack.LinkEndpoint\nexpectSent int\n+ expectDropped int\n+ expectWritten int\n}{\n{\nname: \"Accept all\",\n// No setup needed, tables accept everything by default.\nsetup: func(*testing.T, *stack.Stack) {},\n- linkEP: &limitedEP{nPackets},\n+ linkEP: func() stack.LinkEndpoint { return &limitedEP{nPackets} },\nexpectSent: nPackets,\n+ expectDropped: 0,\n+ expectWritten: nPackets,\n}, {\nname: \"Accept all with error\",\n// No setup needed, tables accept everything by default.\nsetup: func(*testing.T, *stack.Stack) {},\n- linkEP: &limitedEP{nPackets - 1},\n+ linkEP: func() stack.LinkEndpoint { return &limitedEP{nPackets - 1} },\nexpectSent: nPackets - 1,\n+ expectDropped: 0,\n+ expectWritten: nPackets - 1,\n}, {\nname: \"Drop all\",\nsetup: func(t *testing.T, stk *stack.Stack) {\n@@ -1746,8 +1752,10 @@ func TestWritePacketsStats(t *testing.T) {\nt.Fatalf(\"failed to replace table: %v\", err)\n}\n},\n- linkEP: &limitedEP{nPackets},\n+ linkEP: func() stack.LinkEndpoint { return &limitedEP{nPackets} },\nexpectSent: 0,\n+ expectDropped: nPackets,\n+ expectWritten: nPackets,\n}, {\nname: \"Drop some\",\nsetup: func(t *testing.T, stk *stack.Stack) {\n@@ -1769,38 +1777,67 @@ func TestWritePacketsStats(t *testing.T) {\nt.Fatalf(\"failed to replace table: %v\", err)\n}\n},\n- linkEP: &limitedEP{nPackets},\n+ linkEP: func() stack.LinkEndpoint { return &limitedEP{nPackets} },\nexpectSent: nPackets - 1,\n+ expectDropped: 1,\n+ expectWritten: nPackets,\n},\n}\n+ writers := []struct {\n+ name string\n+ writePackets func(*stack.Route, stack.PacketBufferList) (int, *tcpip.Error)\n+ }{\n+ {\n+ name: \"WritePacket\",\n+ writePackets: func(rt *stack.Route, pkts stack.PacketBufferList) (int, *tcpip.Error) {\n+ nWritten := 0\n+ for pkt := pkts.Front(); pkt != nil; pkt = pkt.Next() {\n+ if err := rt.WritePacket(nil, stack.NetworkHeaderParams{}, pkt); err != nil {\n+ return nWritten, err\n+ }\n+ nWritten++\n+ }\n+ return nWritten, nil\n+ },\n+ }, {\n+ name: \"WritePackets\",\n+ writePackets: func(rt *stack.Route, pkts stack.PacketBufferList) (int, *tcpip.Error) {\n+ return rt.WritePackets(nil, pkts, stack.NetworkHeaderParams{})\n+ },\n+ },\n+ }\n+\n+ for _, writer := range writers {\n+ t.Run(writer.name, func(t *testing.T) {\nfor _, test := range tests {\nt.Run(test.name, func(t *testing.T) {\n- rt := buildRoute(t, nil, test.linkEP)\n+ rt := buildRoute(t, nil, test.linkEP())\n- var pbl stack.PacketBufferList\n+ var pkts stack.PacketBufferList\nfor i := 0; i < nPackets; i++ {\npkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\nReserveHeaderBytes: header.UDPMinimumSize + int(rt.MaxHeaderLength()),\n- Data: buffer.NewView(1).ToVectorisedView(),\n+ Data: buffer.NewView(0).ToVectorisedView(),\n})\npkt.TransportHeader().Push(header.UDPMinimumSize)\n- pbl.PushBack(pkt)\n+ pkts.PushBack(pkt)\n}\ntest.setup(t, rt.Stack())\n- nWritten, err := rt.WritePackets(nil, pbl, stack.NetworkHeaderParams{})\n- if err != nil {\n- t.Fatal(err)\n- }\n+ nWritten, _ := writer.writePackets(&rt, pkts)\n- got := int(rt.Stats().IP.PacketsSent.Value())\n- if got != test.expectSent {\n+ if got := int(rt.Stats().IP.PacketsSent.Value()); got != test.expectSent {\nt.Errorf(\"sent %d packets, but expected to send %d\", got, test.expectSent)\n}\n- if got != nWritten {\n- t.Errorf(\"sent %d packets, WritePackets returned %d\", got, nWritten)\n+ if got := int(rt.Stats().IP.IPTablesOutputDropped.Value()); got != test.expectDropped {\n+ t.Errorf(\"dropped %d packets, but expected to drop %d\", got, test.expectDropped)\n+ }\n+ if nWritten != test.expectWritten {\n+ t.Errorf(\"wrote %d packets, but expected WritePackets to return %d\", nWritten, test.expectWritten)\n+ }\n+ })\n}\n})\n}\n@@ -1840,7 +1877,9 @@ type limitedEP struct {\n}\n// MTU implements LinkEndpoint.MTU.\n-func (*limitedEP) MTU() uint32 { return 0 }\n+func (*limitedEP) MTU() uint32 {\n+ return header.IPv6MinimumMTU\n+}\n// Capabilities implements LinkEndpoint.Capabilities.\nfunc (*limitedEP) Capabilities() stack.LinkEndpointCapabilities { return 0 }\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/iptables.go", "new_path": "pkg/tcpip/stack/iptables.go", "diff": "@@ -289,8 +289,6 @@ const (\n// which address and nicName can be gathered. Currently, address is only\n// needed for prerouting and nicName is only needed for output.\n//\n-// TODO(gvisor.dev/issue/170): Dropped packets should be counted.\n-//\n// Precondition: pkt.NetworkHeader is set.\nfunc (it *IPTables) Check(hook Hook, pkt *PacketBuffer, gso *GSO, r *Route, preroutingAddr tcpip.Address, nicName string) bool {\nif pkt.NetworkProtocolNumber != header.IPv4ProtocolNumber && pkt.NetworkProtocolNumber != header.IPv6ProtocolNumber {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -1289,6 +1289,7 @@ func (n *NIC) DeliverNetworkPacket(remote, local tcpip.LinkAddress, protocol tcp\naddress := n.primaryAddress(protocol)\nif ok := ipt.Check(Prerouting, pkt, nil, nil, address.Address, \"\"); !ok {\n// iptables is telling us to drop the packet.\n+ n.stack.stats.IP.IPTablesPreroutingDropped.Increment()\nreturn\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -1474,6 +1474,18 @@ type IPStats struct {\n// MalformedFragmentsReceived is the total number of IP Fragments that were\n// dropped due to the fragment failing validation checks.\nMalformedFragmentsReceived *StatCounter\n+\n+ // IPTablesPreroutingDropped is the total number of IP packets dropped\n+ // in the Prerouting chain.\n+ IPTablesPreroutingDropped *StatCounter\n+\n+ // IPTablesInputDropped is the total number of IP packets dropped in\n+ // the Input chain.\n+ IPTablesInputDropped *StatCounter\n+\n+ // IPTablesOutputDropped is the total number of IP packets dropped in\n+ // the Output chain.\n+ IPTablesOutputDropped *StatCounter\n}\n// TCPStats collects TCP-specific stats.\n" } ]
Go
Apache License 2.0
google/gvisor
Count packets dropped by iptables in IPStats PiperOrigin-RevId: 332486383
259,992
18.09.2020 11:19:04
25,200
ddf37cb19f373ae47836db97349013081cc857b4
Reduce the number of steps to get started with gVisor Streamline instruction for the common case.
[ { "change_type": "MODIFY", "old_path": "g3doc/user_guide/FAQ.md", "new_path": "g3doc/user_guide/FAQ.md", "diff": "@@ -74,11 +74,10 @@ directories.\n### I'm getting an error like: `panic: unable to attach: operation not permitted` or `fork/exec /proc/self/exe: invalid argument: unknown` {#runsc-perms}\n-Make sure that permissions and the owner is correct on the `runsc` binary.\n+Make sure that permissions is correct on the `runsc` binary.\n```bash\n-sudo chown root:root /usr/local/bin/runsc\n-sudo chmod 0755 /usr/local/bin/runsc\n+sudo chmod a+rx /usr/local/bin/runsc\n```\n### I'm getting an error like `mount submount \"/etc/hostname\": creating mount with source \".../hostname\": input/output error: unknown.` {#memlock}\n" }, { "change_type": "MODIFY", "old_path": "g3doc/user_guide/install.md", "new_path": "g3doc/user_guide/install.md", "diff": "> Note: gVisor supports only x86\\_64 and requires Linux 4.14.77+\n> ([older Linux](./networking.md#gso)).\n+## Install latest release {#install-latest}\n+\n+To download and install the latest release manually follow these steps:\n+\n+```bash\n+(\n+ set -e\n+ URL=https://storage.googleapis.com/gvisor/releases/release/latest\n+ wget ${URL}/runsc ${URL}/runsc.sha512\n+ sha512sum -c runsc.sha512\n+ rm -f runsc.sha512\n+ sudo mv runsc /usr/local/bin\n+ sudo chmod a+rx /usr/local/bin/runsc\n+)\n+```\n+\n+To install gVisor with Docker, run the following commands:\n+\n+```bash\n+/usr/local/bin/runsc install\n+sudo systemctl restart docker\n+docker run --rm --runtime=runsc hello-world\n+```\n+\n+For more details about using gVisor with Docker, see\n+[Docker Quick Start](./quick_start/docker.md)\n+\n+Note: It is important to copy `runsc` to a location that is readable and\n+executable to all users, since `runsc` executes itself as user `nobody` to avoid\n+unnecessary privileges. The `/usr/local/bin` directory is a good place to put\n+the `runsc` binary.\n+\n+## Install from an `apt` repository\n+\n+First, appropriate dependencies must be installed to allow `apt` to install\n+packages via https:\n+\n+```bash\n+sudo apt-get update && \\\n+sudo apt-get install -y \\\n+ apt-transport-https \\\n+ ca-certificates \\\n+ curl \\\n+ gnupg-agent \\\n+ software-properties-common\n+```\n+\n+Next, the configure the key used to sign archives and the repository:\n+\n+```bash\n+curl -fsSL https://gvisor.dev/archive.key | sudo apt-key add -\n+sudo add-apt-repository \"deb https://storage.googleapis.com/gvisor/releases release main\"\n+```\n+\n+Now the runsc package can be installed:\n+\n+```bash\n+sudo apt-get update && sudo apt-get install -y runsc\n+```\n+\n+If you have Docker installed, it will be automatically configured.\n+\n## Versions\nThe `runsc` binaries and repositories are available in multiple versions and\n@@ -21,12 +83,16 @@ Binaries are available for every commit on the `master` branch, and are\navailable at the following URL:\n`https://storage.googleapis.com/gvisor/releases/master/latest/runsc`\n+`https://storage.googleapis.com/gvisor/releases/master/latest/runsc.sha512`\n-Checksums for the release binary are at:\n+You can use this link with the steps described in\n+[Install latest release](#install-latest).\n-`https://storage.googleapis.com/gvisor/releases/master/latest/runsc.sha512`\n+For `apt` installation, use the `master` to configure the repository:\n-For `apt` installation, use the `master` as the `${DIST}` below.\n+```bash\n+sudo add-apt-repository \"deb https://storage.googleapis.com/gvisor/releases master main\"\n+```\n### Nightly\n@@ -34,18 +100,22 @@ Nightly releases are built most nights from the master branch, and are available\nat the following URL:\n`https://storage.googleapis.com/gvisor/releases/nightly/latest/runsc`\n-\n-Checksums for the release binary are at:\n-\n`https://storage.googleapis.com/gvisor/releases/nightly/latest/runsc.sha512`\n+You can use this link with the steps described in\n+[Install latest release](#install-latest).\n+\nSpecific nightly releases can be found at:\n`https://storage.googleapis.com/gvisor/releases/nightly/${yyyy-mm-dd}/runsc`\nNote that a release may not be available for every day.\n-For `apt` installation, use the `nightly` as the `${DIST}` below.\n+For `apt` installation, use the `nightly` to configure the repository:\n+\n+```bash\n+sudo add-apt-repository \"deb https://storage.googleapis.com/gvisor/releases nightly main\"\n+```\n### Latest release\n@@ -53,105 +123,47 @@ The latest official release is available at the following URL:\n`https://storage.googleapis.com/gvisor/releases/release/latest`\n-For `apt` installation, use the `release` as the `${DIST}` below.\n-\n-### Specific release\n-\n-A given release release is available at the following URL:\n-\n-`https://storage.googleapis.com/gvisor/releases/release/${yyyymmdd}`\n-\n-See the [releases][releases] page for information about specific releases.\n-\n-For `apt` installation of a specific release, which may include point updates,\n-use the date of the release, e.g. `${yyyymmdd}`, as the `${DIST}` below.\n-\n-> Note: only newer releases may be available as `apt` repositories.\n-\n-### Point release\n-\n-A given point release is available at the following URL:\n-\n-`https://storage.googleapis.com/gvisor/releases/release/${yyyymmdd}.${rc}`\n-\n-Note that `apt` installation of a specific point release is not supported.\n-\n-## Install from an `apt` repository\n+You can use this link with the steps described in\n+[Install latest release](#install-latest).\n-First, appropriate dependencies must be installed to allow `apt` to install\n-packages via https:\n+For `apt` installation, use the `release` to configure the repository:\n```bash\n-sudo apt-get update && \\\n-sudo apt-get install -y \\\n- apt-transport-https \\\n- ca-certificates \\\n- curl \\\n- gnupg-agent \\\n- software-properties-common\n+sudo add-apt-repository \"deb https://storage.googleapis.com/gvisor/releases release main\"\n```\n-Next, the key used to sign archives should be added to your `apt` keychain:\n-\n-```bash\n-curl -fsSL https://gvisor.dev/archive.key | sudo apt-key add -\n-```\n+### Specific release\n-Based on the release type, you will need to substitute `${DIST}` below, using\n-one of:\n+A given release release is available at the following URL:\n-* `master`: For HEAD.\n-* `nightly`: For nightly releases.\n-* `release`: For the latest release.\n-* `${yyyymmdd}`: For a specific releases (see above).\n+`https://storage.googleapis.com/gvisor/releases/release/${yyyymmdd}`\n-The repository for the release you wish to install should be added:\n+You can use this link with the steps described in\n+[Install latest release](#install-latest).\n-```bash\n-sudo add-apt-repository \"deb https://storage.googleapis.com/gvisor/releases ${DIST} main\"\n-```\n+See the [releases](https://github.com/google/gvisor/releases) page for\n+information about specific releases.\n-For example, to install the latest official release, you can use:\n+For `apt` installation of a specific release, which may include point updates,\n+use the date of the release for repository, e.g. `${yyyymmdd}`.\n```bash\n-sudo add-apt-repository \"deb https://storage.googleapis.com/gvisor/releases release main\"\n+sudo add-apt-repository \"deb https://storage.googleapis.com/gvisor/releases yyyymmdd main\"\n```\n-Now the runsc package can be installed:\n-\n-```bash\n-sudo apt-get update && sudo apt-get install -y runsc\n-```\n+> Note: only newer releases may be available as `apt` repositories.\n-If you have Docker installed, it will be automatically configured.\n+### Point release\n-## Install directly\n+A given point release is available at the following URL:\n-The binary URLs provided above can be used to install directly. For example, the\n-latest nightly binary can be downloaded, validated, and placed in an appropriate\n-location by running:\n+`https://storage.googleapis.com/gvisor/releases/release/${yyyymmdd}.${rc}`\n-```bash\n-(\n- set -e\n- URL=https://storage.googleapis.com/gvisor/releases/nightly/latest\n- wget ${URL}/runsc\n- wget ${URL}/runsc.sha512\n- sha512sum -c runsc.sha512\n- rm -f runsc.sha512\n- sudo mv runsc /usr/local/bin\n- sudo chown root:root /usr/local/bin/runsc\n- sudo chmod 0755 /usr/local/bin/runsc\n-)\n-```\n+You can use this link with the steps described in\n+[Install latest release](#install-latest).\n-**It is important to copy this binary to a location that is accessible to all\n-users, and ensure it is executable by all users**, since `runsc` executes itself\n-as user `nobody` to avoid unnecessary privileges. The `/usr/local/bin` directory\n-is a good place to put the `runsc` binary.\n+Note that `apt` installation of a specific point release is not supported.\nAfter installation, try out `runsc` by following the\n[Docker Quick Start](./quick_start/docker.md) or\n[OCI Quick Start](./quick_start/oci.md).\n-\n-[releases]: https://github.com/google/gvisor/releases\n" }, { "change_type": "MODIFY", "old_path": "g3doc/user_guide/quick_start/docker.md", "new_path": "g3doc/user_guide/quick_start/docker.md", "diff": "@@ -22,18 +22,6 @@ named \"runsc\" by default.\nsudo runsc install\n```\n-You may also wish to install a runtime entry for debugging. The `runsc install`\n-command can accept options that will be passed to the runtime when it is invoked\n-by Docker.\n-\n-```bash\n-sudo runsc install --runtime runsc-debug -- \\\n- --debug \\\n- --debug-log=/tmp/runsc-debug.log \\\n- --strace \\\n- --log-packets\n-```\n-\nYou must restart the Docker daemon after installing the runtime. Typically this\nis done via `systemd`:\n@@ -85,6 +73,21 @@ $ docker run --runtime=runsc -it ubuntu dmesg\nNote that this is easily replicated by an attacker so applications should never\nuse `dmesg` to verify the runtime in a security sensitive context.\n+## Options\n+\n+You may also wish to install a runtime entry with different options. The `runsc\n+install` command can accept flags that will be passed to the runtime when it is\n+invoked by Docker. For example, to install a runtime with debugging enabled, run\n+the following:\n+\n+```bash\n+sudo runsc install --runtime runsc-debug -- \\\n+ --debug \\\n+ --debug-log=/tmp/runsc-debug.log \\\n+ --strace \\\n+ --log-packets\n+```\n+\nNext, look at the different options available for gVisor: [platform][platforms],\n[network][networking], [filesystem][filesystem].\n" }, { "change_type": "MODIFY", "old_path": "website/index.md", "new_path": "website/index.md", "diff": "<div class=\"col-md-6\">\n<p>gVisor is an <b>application kernel</b> for <b>containers</b> that provides efficient defense-in-depth anywhere.</p>\n<p style=\"margin-top: 20px;\">\n- <a class=\"btn\" href=\"/docs/user_guide/quick_start/docker/\">Quick start&nbsp;<i class=\"fas fa-arrow-alt-circle-right ml-2\"></i></a>\n+ <a class=\"btn\" href=\"/docs/user_guide/install/\">Get started&nbsp;<i class=\"fas fa-arrow-alt-circle-right ml-2\"></i></a>\n<a class=\"btn\" href=\"/docs/\">Learn More&nbsp;<i class=\"fas fa-arrow-alt-circle-right ml-2\"></i></a>\n</p>\n</div>\n" } ]
Go
Apache License 2.0
google/gvisor
Reduce the number of steps to get started with gVisor Streamline instruction for the common case. PiperOrigin-RevId: 332488910
259,891
18.09.2020 12:19:02
25,200
f911b43f05f88807a1e36adc6ab3b7c8cf8ec2ee
Remove SKIP_IF for now-supported features. Updates
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/ip6tables.cc", "new_path": "test/syscalls/linux/ip6tables.cc", "diff": "@@ -87,8 +87,6 @@ TEST(IP6TablesBasic, GetEntriesErrorPrecedence) {\n// empty when running in native, but we can test that gVisor has the same\n// initial state that a newly-booted Linux machine would have.\nTEST(IP6TablesTest, InitialInfo) {\n- // TODO(gvisor.dev/issue/3549): Enable for ip6tables.\n- SKIP_IF(true);\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\nFileDescriptor sock =\n@@ -132,8 +130,6 @@ TEST(IP6TablesTest, InitialInfo) {\n// are empty when running in native, but we can test that gVisor has the same\n// initial state that a newly-booted Linux machine would have.\nTEST(IP6TablesTest, InitialEntries) {\n- // TODO(gvisor.dev/issue/3549): Enable for ip6tables.\n- SKIP_IF(true);\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\nFileDescriptor sock =\n" } ]
Go
Apache License 2.0
google/gvisor
Remove SKIP_IF for now-supported features. Updates #3549. PiperOrigin-RevId: 332501660
259,913
17.09.2020 23:27:16
0
9a06a1a1603f549808f842b658e5d13a0934916d
fuse: update design doc with I/O implementation
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/g3doc/fuse.md", "new_path": "pkg/sentry/fs/g3doc/fuse.md", "diff": "@@ -79,7 +79,7 @@ ops can be implemented in parallel.\n- Implement `/dev/fuse` - a character device used to establish an FD for\ncommunication between the sentry and the server daemon.\n-- Implement basic FUSE ops like `FUSE_INIT`, `FUSE_DESTROY`.\n+- Implement basic FUSE ops like `FUSE_INIT`.\n#### Read-only mount with basic file operations\n@@ -141,6 +141,58 @@ ops can be implemented in parallel.\n- a channel that the kernel task will be blocked on when the fd is not\navailable.\n+#### Basic I/O Implementation\n+\n+Currently we have implemented basic functionalities of read and write\n+for our FUSE. We describe the design and ways to improve it here:\n+\n+##### Basic FUSE Read\n+\n+The vfs2 expects implementations of `vfs.FileDescriptionImpl.Read()` and\n+`vfs.FileDescriptionImpl.PRead()`. When a syscall is made, it will eventually\n+reach our implementation of those interface functions located at\n+`pkg/sentry/fsimpl/fuse/regular_file.go` for regular files.\n+\n+After validation checks of the input, sentry sends `FUSE_READ` requests\n+to the FUSE daemon. The FUSE daemon returns data after the `fuse_out_header`\n+as the responses. For the first version, we create a copy in kernel memory\n+of those data. They are represented as a byte slice in the marshalled\n+struct. This happens as a common process for all the FUSE responses at this\n+moment at `pkg/sentry/fsimpl/fuse/dev.go:writeLocked()`. We then directly\n+copy from this intermediate buffer to the input buffer\n+provided by the read syscall.\n+\n+There is an extra requirement for FUSE: When mounting the FUSE fs,\n+the mounter or the FUSE daemon can specify a `max_read` or a `max_pages`\n+parameter. They are the upperbound of the bytes to read in each\n+`FUSE_READ` request. We implemented the code to handle the fragmented reads.\n+\n+To improve the performance: ideally we should have buffer cache to copy\n+those data from the responses of FUSE daemon into, as is also the\n+design of several other existing file system implementations for\n+sentry, instead of a single-use temporary buffer. Directly mapping\n+the memory of one process to another could also boost the performance,\n+but to keep them isolated, we did not choose to do so.\n+\n+##### Basic FUSE Write\n+\n+The vfs2 invokes implementations of `vfs.FileDescriptionImpl.Write()`\n+and `vfs.FileDescriptionImpl.PWrite()` on the regular file descriptor\n+of FUSE when a user makes write(2) and pwrite(2) syscall.\n+\n+For valid writes, sentry sends the bytes to write after a `FUSE_WRITE`\n+header (can be regarded as a request with 2 payloads) to the FUSE daemon.\n+For the first version, we allocate a buffer inside kernel memory to store\n+the bytes from the user, and copy directly from that buffer to the memory\n+of FUSE daemon. This happens at `pkg/sentry/fsimpl/fuse/dev.go:readLocked()`\n+\n+The parameters `max_write` and `max_pages` restrict the number of bytes in one\n+`FUSE_WRITE`. There are code handling fragmented writes in current\n+implementation.\n+\n+To have better performance: the extra copy created to store the bytes to write\n+can be replaced by the buffer cache as well.\n+\n# Appendix\n## FUSE Protocol\n" } ]
Go
Apache License 2.0
google/gvisor
fuse: update design doc with I/O implementation
259,885
18.09.2020 13:23:41
25,200
ca4ecf481d617edfae22a5735a657d60186392e1
Use a tmpfs file for shared anonymous and /dev/zero mmap on VFS2. This is more consistent with Linux (see comment on MM.NewSharedAnonMappable()). We don't do the same thing on VFS1 for reasons documented by the updated comment.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/devices/memdev/BUILD", "new_path": "pkg/sentry/devices/memdev/BUILD", "diff": "@@ -18,9 +18,10 @@ go_library(\n\"//pkg/rand\",\n\"//pkg/safemem\",\n\"//pkg/sentry/fsimpl/devtmpfs\",\n+ \"//pkg/sentry/fsimpl/tmpfs\",\n+ \"//pkg/sentry/kernel\",\n+ \"//pkg/sentry/kernel/auth\",\n\"//pkg/sentry/memmap\",\n- \"//pkg/sentry/mm\",\n- \"//pkg/sentry/pgalloc\",\n\"//pkg/sentry/vfs\",\n\"//pkg/syserror\",\n\"//pkg/usermem\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/devices/memdev/zero.go", "new_path": "pkg/sentry/devices/memdev/zero.go", "diff": "@@ -16,9 +16,10 @@ package memdev\nimport (\n\"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/tmpfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/memmap\"\n- \"gvisor.dev/gvisor/pkg/sentry/mm\"\n- \"gvisor.dev/gvisor/pkg/sentry/pgalloc\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n@@ -79,11 +80,22 @@ func (fd *zeroFD) Seek(ctx context.Context, offset int64, whence int32) (int64,\n// ConfigureMMap implements vfs.FileDescriptionImpl.ConfigureMMap.\nfunc (fd *zeroFD) ConfigureMMap(ctx context.Context, opts *memmap.MMapOpts) error {\n- m, err := mm.NewSharedAnonMappable(opts.Length, pgalloc.MemoryFileProviderFromContext(ctx))\n+ if opts.Private || !opts.MaxPerms.Write {\n+ // This mapping will never permit writing to the \"underlying file\" (in\n+ // Linux terms, it isn't VM_SHARED), so implement it as an anonymous\n+ // mapping, but back it with fd; this is what Linux does, and is\n+ // actually application-visible because the resulting VMA will show up\n+ // in /proc/[pid]/maps with fd.vfsfd.VirtualDentry()'s path rather than\n+ // \"/dev/zero (deleted)\".\n+ opts.Offset = 0\n+ opts.MappingIdentity = &fd.vfsfd\n+ opts.MappingIdentity.IncRef()\n+ return nil\n+ }\n+ tmpfsFD, err := tmpfs.NewZeroFile(ctx, auth.CredentialsFromContext(ctx), kernel.KernelFromContext(ctx).ShmMount(), opts.Length)\nif err != nil {\nreturn err\n}\n- opts.MappingIdentity = m\n- opts.Mappable = m\n- return nil\n+ defer tmpfsFD.DecRef(ctx)\n+ return tmpfsFD.ConfigureMMap(ctx, opts)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "diff": "@@ -865,8 +865,16 @@ func (fs *filesystem) PrependPath(ctx context.Context, vfsroot, vd vfs.VirtualDe\n}\nif d.parent == nil {\nif d.name != \"\" {\n- // This must be an anonymous memfd file.\n+ // This file must have been created by\n+ // newUnlinkedRegularFileDescription(). In Linux,\n+ // mm/shmem.c:__shmem_file_setup() =>\n+ // fs/file_table.c:alloc_file_pseudo() sets the created\n+ // dentry's dentry_operations to anon_ops, for which d_dname ==\n+ // simple_dname. fs/d_path.c:simple_dname() defines the\n+ // dentry's pathname to be its name, prefixed with \"/\" and\n+ // suffixed with \" (deleted)\".\nb.PrependComponent(\"/\" + d.name)\n+ b.AppendString(\" (deleted)\")\nreturn vfs.PrependPathSyntheticError{}\n}\nreturn vfs.PrependPathAtNonMountRootError{}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go", "new_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go", "diff": "@@ -42,6 +42,10 @@ type regularFile struct {\n// memFile is a platform.File used to allocate pages to this regularFile.\nmemFile *pgalloc.MemoryFile\n+ // memoryUsageKind is the memory accounting category under which pages backing\n+ // this regularFile's contents are accounted.\n+ memoryUsageKind usage.MemoryKind\n+\n// mapsMu protects mappings.\nmapsMu sync.Mutex `state:\"nosave\"`\n@@ -87,6 +91,7 @@ type regularFile struct {\nfunc (fs *filesystem) newRegularFile(kuid auth.KUID, kgid auth.KGID, mode linux.FileMode) *inode {\nfile := &regularFile{\nmemFile: fs.memFile,\n+ memoryUsageKind: usage.Tmpfs,\nseals: linux.F_SEAL_SEAL,\n}\nfile.inode.init(file, fs, kuid, kgid, linux.S_IFREG|mode)\n@@ -94,6 +99,66 @@ func (fs *filesystem) newRegularFile(kuid auth.KUID, kgid auth.KGID, mode linux.\nreturn &file.inode\n}\n+// newUnlinkedRegularFileDescription creates a regular file on the tmpfs\n+// filesystem represented by mount and returns an FD representing that file.\n+// The new file is not reachable by path traversal from any other file.\n+//\n+// newUnlinkedRegularFileDescription is analogous to Linux's\n+// mm/shmem.c:__shmem_file_setup().\n+//\n+// Preconditions: mount must be a tmpfs mount.\n+func newUnlinkedRegularFileDescription(ctx context.Context, creds *auth.Credentials, mount *vfs.Mount, name string) (*regularFileFD, error) {\n+ fs, ok := mount.Filesystem().Impl().(*filesystem)\n+ if !ok {\n+ panic(\"tmpfs.newUnlinkedRegularFileDescription() called with non-tmpfs mount\")\n+ }\n+\n+ inode := fs.newRegularFile(creds.EffectiveKUID, creds.EffectiveKGID, 0777)\n+ d := fs.newDentry(inode)\n+ defer d.DecRef(ctx)\n+ d.name = name\n+\n+ fd := &regularFileFD{}\n+ fd.Init(&inode.locks)\n+ flags := uint32(linux.O_RDWR)\n+ if err := fd.vfsfd.Init(fd, flags, mount, &d.vfsd, &vfs.FileDescriptionOptions{}); err != nil {\n+ return nil, err\n+ }\n+ return fd, nil\n+}\n+\n+// NewZeroFile creates a new regular file and file description as for\n+// mmap(MAP_SHARED | MAP_ANONYMOUS). The file has the given size and is\n+// initially (implicitly) filled with zeroes.\n+//\n+// Preconditions: mount must be a tmpfs mount.\n+func NewZeroFile(ctx context.Context, creds *auth.Credentials, mount *vfs.Mount, size uint64) (*vfs.FileDescription, error) {\n+ // Compare mm/shmem.c:shmem_zero_setup().\n+ fd, err := newUnlinkedRegularFileDescription(ctx, creds, mount, \"dev/zero\")\n+ if err != nil {\n+ return nil, err\n+ }\n+ rf := fd.inode().impl.(*regularFile)\n+ rf.memoryUsageKind = usage.Anonymous\n+ rf.size = size\n+ return &fd.vfsfd, err\n+}\n+\n+// NewMemfd creates a new regular file and file description as for\n+// memfd_create.\n+//\n+// Preconditions: mount must be a tmpfs mount.\n+func NewMemfd(ctx context.Context, creds *auth.Credentials, mount *vfs.Mount, allowSeals bool, name string) (*vfs.FileDescription, error) {\n+ fd, err := newUnlinkedRegularFileDescription(ctx, creds, mount, name)\n+ if err != nil {\n+ return nil, err\n+ }\n+ if allowSeals {\n+ fd.inode().impl.(*regularFile).seals = 0\n+ }\n+ return &fd.vfsfd, nil\n+}\n+\n// truncate grows or shrinks the file to the given size. It returns true if the\n// file size was updated.\nfunc (rf *regularFile) truncate(newSize uint64) (bool, error) {\n@@ -226,7 +291,7 @@ func (rf *regularFile) Translate(ctx context.Context, required, optional memmap.\noptional.End = pgend\n}\n- cerr := rf.data.Fill(ctx, required, optional, rf.memFile, usage.Tmpfs, func(_ context.Context, dsts safemem.BlockSeq, _ uint64) (uint64, error) {\n+ cerr := rf.data.Fill(ctx, required, optional, rf.memFile, rf.memoryUsageKind, func(_ context.Context, dsts safemem.BlockSeq, _ uint64) (uint64, error) {\n// Newly-allocated pages are zeroed, so we don't need to do anything.\nreturn dsts.NumBytes(), nil\n})\n@@ -575,7 +640,7 @@ func (rw *regularFileReadWriter) WriteFromBlocks(srcs safemem.BlockSeq) (uint64,\ncase gap.Ok():\n// Allocate memory for the write.\ngapMR := gap.Range().Intersect(pgMR)\n- fr, err := rw.file.memFile.Allocate(gapMR.Length(), usage.Tmpfs)\n+ fr, err := rw.file.memFile.Allocate(gapMR.Length(), rw.file.memoryUsageKind)\nif err != nil {\nretErr = err\ngoto exitLoop\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go", "new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go", "diff": "@@ -746,37 +746,6 @@ func (fd *fileDescription) RemoveXattr(ctx context.Context, name string) error {\nreturn nil\n}\n-// NewMemfd creates a new tmpfs regular file and file description that can back\n-// an anonymous fd created by memfd_create.\n-func NewMemfd(ctx context.Context, creds *auth.Credentials, mount *vfs.Mount, allowSeals bool, name string) (*vfs.FileDescription, error) {\n- fs, ok := mount.Filesystem().Impl().(*filesystem)\n- if !ok {\n- panic(\"NewMemfd() called with non-tmpfs mount\")\n- }\n-\n- // Per Linux, mm/shmem.c:__shmem_file_setup(), memfd inodes are set up with\n- // S_IRWXUGO.\n- inode := fs.newRegularFile(creds.EffectiveKUID, creds.EffectiveKGID, 0777)\n- rf := inode.impl.(*regularFile)\n- if allowSeals {\n- rf.seals = 0\n- }\n-\n- d := fs.newDentry(inode)\n- defer d.DecRef(ctx)\n- d.name = name\n-\n- // Per Linux, mm/shmem.c:__shmem_file_setup(), memfd files are set up with\n- // FMODE_READ | FMODE_WRITE.\n- var fd regularFileFD\n- fd.Init(&inode.locks)\n- flags := uint32(linux.O_RDWR)\n- if err := fd.vfsfd.Init(&fd, flags, mount, &d.vfsd, &vfs.FileDescriptionOptions{}); err != nil {\n- return nil, err\n- }\n- return &fd.vfsfd, nil\n-}\n-\n// LockPOSIX implements vfs.FileDescriptionImpl.LockPOSIX.\nfunc (fd *fileDescription) LockPOSIX(ctx context.Context, uid fslock.UniqueID, t fslock.LockType, start, length uint64, whence int16, block fslock.Blocker) error {\nreturn fd.Locks().LockPOSIX(ctx, &fd.vfsfd, uid, t, start, length, whence, block)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/mm/mm.go", "new_path": "pkg/sentry/mm/mm.go", "diff": "@@ -242,7 +242,7 @@ type MemoryManager struct {\n// +stateify savable\ntype vma struct {\n// mappable is the virtual memory object mapped by this vma. If mappable is\n- // nil, the vma represents a private anonymous mapping.\n+ // nil, the vma represents an anonymous mapping.\nmappable memmap.Mappable\n// off is the offset into mappable at which this vma begins. If mappable is\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/mm/mm_test.go", "new_path": "pkg/sentry/mm/mm_test.go", "diff": "@@ -52,6 +52,7 @@ func TestUsageASUpdates(t *testing.T) {\naddr, err := mm.MMap(ctx, memmap.MMapOpts{\nLength: 2 * usermem.PageSize,\n+ Private: true,\n})\nif err != nil {\nt.Fatalf(\"MMap got err %v want nil\", err)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/mm/special_mappable.go", "new_path": "pkg/sentry/mm/special_mappable.go", "diff": "@@ -136,9 +136,12 @@ func (m *SpecialMappable) Length() uint64 {\n// NewSharedAnonMappable returns a SpecialMappable that implements the\n// semantics of mmap(MAP_SHARED|MAP_ANONYMOUS) and mappings of /dev/zero.\n//\n-// TODO(jamieliu): The use of SpecialMappable is a lazy code reuse hack. Linux\n-// uses an ephemeral file created by mm/shmem.c:shmem_zero_setup(); we should\n-// do the same to get non-zero device and inode IDs.\n+// TODO(gvisor.dev/issue/1624): Linux uses an ephemeral file created by\n+// mm/shmem.c:shmem_zero_setup(), and VFS2 does something analogous. VFS1 uses\n+// a SpecialMappable instead, incorrectly getting device and inode IDs of zero\n+// and causing memory for shared anonymous mappings to be allocated up-front\n+// instead of on first touch; this is to avoid exacerbating the fs.MountSource\n+// leak (b/143656263). Delete this function along with VFS1.\nfunc NewSharedAnonMappable(length uint64, mfp pgalloc.MemoryFileProvider) (*SpecialMappable, error) {\nif length == 0 {\nreturn nil, syserror.EINVAL\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/mm/syscalls.go", "new_path": "pkg/sentry/mm/syscalls.go", "diff": "@@ -24,7 +24,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel/futex\"\n\"gvisor.dev/gvisor/pkg/sentry/limits\"\n\"gvisor.dev/gvisor/pkg/sentry/memmap\"\n- \"gvisor.dev/gvisor/pkg/sentry/pgalloc\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n@@ -93,18 +92,6 @@ func (mm *MemoryManager) MMap(ctx context.Context, opts memmap.MMapOpts) (userme\n}\n} else {\nopts.Offset = 0\n- if !opts.Private {\n- if opts.MappingIdentity != nil {\n- return 0, syserror.EINVAL\n- }\n- m, err := NewSharedAnonMappable(opts.Length, pgalloc.MemoryFileProviderFromContext(ctx))\n- if err != nil {\n- return 0, err\n- }\n- defer m.DecRef(ctx)\n- opts.MappingIdentity = m\n- opts.Mappable = m\n- }\n}\nif opts.Addr.RoundDown() != opts.Addr {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_mmap.go", "new_path": "pkg/sentry/syscalls/linux/sys_mmap.go", "diff": "@@ -100,6 +100,15 @@ func Mmap(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallC\nif err := file.ConfigureMMap(t, &opts); err != nil {\nreturn 0, nil, err\n}\n+ } else if shared {\n+ // Back shared anonymous mappings with a special mappable.\n+ opts.Offset = 0\n+ m, err := mm.NewSharedAnonMappable(opts.Length, t.Kernel())\n+ if err != nil {\n+ return 0, nil, err\n+ }\n+ opts.MappingIdentity = m // transfers ownership of m to opts\n+ opts.Mappable = m\n}\nrv, err := t.MemoryManager().MMap(t, opts)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/mmap.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/mmap.go", "diff": "@@ -17,6 +17,7 @@ package vfs2\nimport (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/tmpfs\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/memmap\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n@@ -82,6 +83,17 @@ func Mmap(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallC\nopts.MaxPerms.Write = false\n}\n+ if err := file.ConfigureMMap(t, &opts); err != nil {\n+ return 0, nil, err\n+ }\n+ } else if shared {\n+ // Back shared anonymous mappings with an anonymous tmpfs file.\n+ opts.Offset = 0\n+ file, err := tmpfs.NewZeroFile(t, t.Credentials(), t.Kernel().ShmMount(), opts.Length)\n+ if err != nil {\n+ return 0, nil, err\n+ }\n+ defer file.DecRef(t)\nif err := file.ConfigureMMap(t, &opts); err != nil {\nreturn 0, nil, err\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -1673,6 +1673,7 @@ cc_binary(\ngtest,\n\"//test/util:memory_util\",\n\"//test/util:posix_error\",\n+ \"//test/util:proc_util\",\n\"//test/util:temp_path\",\n\"//test/util:test_util\",\n\"//test/util:thread_util\",\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/proc.cc", "new_path": "test/syscalls/linux/proc.cc", "diff": "#include \"test/util/fs_util.h\"\n#include \"test/util/memory_util.h\"\n#include \"test/util/posix_error.h\"\n+#include \"test/util/proc_util.h\"\n#include \"test/util/temp_path.h\"\n#include \"test/util/test_util.h\"\n#include \"test/util/thread_util.h\"\n@@ -672,6 +673,23 @@ TEST(ProcSelfMaps, Mprotect) {\n3 * kPageSize, PROT_READ)));\n}\n+TEST(ProcSelfMaps, SharedAnon) {\n+ const Mapping m = ASSERT_NO_ERRNO_AND_VALUE(\n+ MmapAnon(kPageSize, PROT_READ, MAP_SHARED | MAP_ANONYMOUS));\n+\n+ const auto proc_self_maps =\n+ ASSERT_NO_ERRNO_AND_VALUE(GetContents(\"/proc/self/maps\"));\n+ for (const auto& line : absl::StrSplit(proc_self_maps, '\\n')) {\n+ const auto entry = ASSERT_NO_ERRNO_AND_VALUE(ParseProcMapsLine(line));\n+ if (entry.start <= m.addr() && m.addr() < entry.end) {\n+ // cf. proc(5), \"/proc/[pid]/map_files/\"\n+ EXPECT_EQ(entry.filename, \"/dev/zero (deleted)\");\n+ return;\n+ }\n+ }\n+ FAIL() << \"no maps entry containing mapping at \" << m.ptr();\n+}\n+\nTEST(ProcSelfFd, OpenFd) {\nint pipe_fds[2];\nASSERT_THAT(pipe2(pipe_fds, O_CLOEXEC), SyscallSucceeds());\n" } ]
Go
Apache License 2.0
google/gvisor
Use a tmpfs file for shared anonymous and /dev/zero mmap on VFS2. This is more consistent with Linux (see comment on MM.NewSharedAnonMappable()). We don't do the same thing on VFS1 for reasons documented by the updated comment. PiperOrigin-RevId: 332514849
259,885
18.09.2020 15:27:29
25,200
c23e39f419f2dbdb67920fed1828399a5ac2479b
Implement fsimpl/overlay.filesystem.RenameAt. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/filesystem.go", "new_path": "pkg/sentry/fsimpl/gofer/filesystem.go", "diff": "@@ -1311,6 +1311,9 @@ func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\nif !renamed.isDir() {\nreturn syserror.EISDIR\n}\n+ if genericIsAncestorDentry(replaced, renamed) {\n+ return syserror.ENOTEMPTY\n+ }\n} else {\nif rp.MustBeDir() || renamed.isDir() {\nreturn syserror.ENOTDIR\n@@ -1361,14 +1364,15 @@ func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\n// with reference counts and queue oldParent for checkCachingLocked if the\n// parent isn't actually changing.\nif oldParent != newParent {\n+ oldParent.decRefLocked()\nds = appendDentry(ds, oldParent)\nnewParent.IncRef()\nif renamed.isSynthetic() {\noldParent.syntheticChildren--\nnewParent.syntheticChildren++\n}\n- }\nrenamed.parent = newParent\n+ }\nrenamed.name = newName\nif newParent.children == nil {\nnewParent.children = make(map[string]*dentry)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/overlay/copy_up.go", "new_path": "pkg/sentry/fsimpl/overlay/copy_up.go", "diff": "@@ -92,7 +92,7 @@ func (d *dentry) copyUpLocked(ctx context.Context) error {\nerr = vfsObj.UnlinkAt(ctx, d.fs.creds, &newpop)\n}\nif err != nil {\n- ctx.Warningf(\"Unrecoverable overlayfs inconsistency: failed to delete upper layer file after copy-up error: %v\", err)\n+ panic(fmt.Sprintf(\"unrecoverable overlayfs inconsistency: failed to delete upper layer file after copy-up error: %v\", err))\n}\nif d.upperVD.Ok() {\nd.upperVD.DecRef(ctx)\n@@ -362,7 +362,7 @@ func (d *dentry) copyXattrsLocked(ctx context.Context) error {\n// There are no guarantees as to the contents of lowerXattrs.\nreturn nil\n}\n- ctx.Warningf(\"failed to copy up xattrs because ListXattrAt failed: %v\", err)\n+ ctx.Infof(\"failed to copy up xattrs because ListXattrAt failed: %v\", err)\nreturn err\n}\n@@ -374,14 +374,48 @@ func (d *dentry) copyXattrsLocked(ctx context.Context) error {\nvalue, err := vfsObj.GetXattrAt(ctx, d.fs.creds, lowerPop, &vfs.GetXattrOptions{Name: name, Size: 0})\nif err != nil {\n- ctx.Warningf(\"failed to copy up xattrs because GetXattrAt failed: %v\", err)\n+ ctx.Infof(\"failed to copy up xattrs because GetXattrAt failed: %v\", err)\nreturn err\n}\nif err := vfsObj.SetXattrAt(ctx, d.fs.creds, upperPop, &vfs.SetXattrOptions{Name: name, Value: value}); err != nil {\n- ctx.Warningf(\"failed to copy up xattrs because SetXattrAt failed: %v\", err)\n+ ctx.Infof(\"failed to copy up xattrs because SetXattrAt failed: %v\", err)\nreturn err\n}\n}\nreturn nil\n}\n+\n+// copyUpDescendantsLocked ensures that all descendants of d are copied up.\n+//\n+// Preconditions:\n+// * filesystem.renameMu must be locked.\n+// * d.dirMu must be locked.\n+// * d.isDir().\n+func (d *dentry) copyUpDescendantsLocked(ctx context.Context, ds **[]*dentry) error {\n+ dirents, err := d.getDirentsLocked(ctx)\n+ if err != nil {\n+ return err\n+ }\n+ for _, dirent := range dirents {\n+ if dirent.Name == \".\" || dirent.Name == \"..\" {\n+ continue\n+ }\n+ child, err := d.fs.getChildLocked(ctx, d, dirent.Name, ds)\n+ if err != nil {\n+ return err\n+ }\n+ if err := child.copyUpLocked(ctx); err != nil {\n+ return err\n+ }\n+ if child.isDir() {\n+ child.dirMu.Lock()\n+ err := child.copyUpDescendantsLocked(ctx, ds)\n+ child.dirMu.Unlock()\n+ if err != nil {\n+ return err\n+ }\n+ }\n+ }\n+ return nil\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/overlay/directory.go", "new_path": "pkg/sentry/fsimpl/overlay/directory.go", "diff": "@@ -143,7 +143,14 @@ func (d *dentry) getDirents(ctx context.Context) ([]vfs.Dirent, error) {\ndefer d.fs.renameMu.RUnlock()\nd.dirMu.Lock()\ndefer d.dirMu.Unlock()\n+ return d.getDirentsLocked(ctx)\n+}\n+// Preconditions:\n+// * filesystem.renameMu must be locked.\n+// * d.dirMu must be locked.\n+// * d.isDir().\n+func (d *dentry) getDirentsLocked(ctx context.Context) ([]vfs.Dirent, error) {\nif d.dirents != nil {\nreturn d.dirents, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/overlay/filesystem.go", "new_path": "pkg/sentry/fsimpl/overlay/filesystem.go", "diff": "package overlay\nimport (\n+ \"fmt\"\n\"strings\"\n\"sync/atomic\"\n@@ -512,7 +513,7 @@ func (fs *filesystem) createWhiteout(ctx context.Context, vfsObj *vfs.VirtualFil\nfunc (fs *filesystem) cleanupRecreateWhiteout(ctx context.Context, vfsObj *vfs.VirtualFilesystem, pop *vfs.PathOperation) {\nif err := fs.createWhiteout(ctx, vfsObj, pop); err != nil {\n- ctx.Warningf(\"Unrecoverable overlayfs inconsistency: failed to recreate whiteout after failed file creation: %v\", err)\n+ panic(fmt.Sprintf(\"unrecoverable overlayfs inconsistency: failed to recreate whiteout after failed file creation: %v\", err))\n}\n}\n@@ -624,7 +625,7 @@ func (fs *filesystem) LinkAt(ctx context.Context, rp *vfs.ResolvingPath, vd vfs.\n},\n}); err != nil {\nif cleanupErr := vfsObj.UnlinkAt(ctx, fs.creds, &newpop); cleanupErr != nil {\n- ctx.Warningf(\"Unrecoverable overlayfs inconsistency: failed to delete upper layer file after LinkAt metadata update failure: %v\", cleanupErr)\n+ panic(fmt.Sprintf(\"unrecoverable overlayfs inconsistency: failed to delete upper layer file after LinkAt metadata update failure: %v\", cleanupErr))\n} else if haveUpperWhiteout {\nfs.cleanupRecreateWhiteout(ctx, vfsObj, &newpop)\n}\n@@ -663,7 +664,7 @@ func (fs *filesystem) MkdirAt(ctx context.Context, rp *vfs.ResolvingPath, opts v\n},\n}); err != nil {\nif cleanupErr := vfsObj.RmdirAt(ctx, fs.creds, &pop); cleanupErr != nil {\n- ctx.Warningf(\"Unrecoverable overlayfs inconsistency: failed to delete upper layer directory after MkdirAt metadata update failure: %v\", cleanupErr)\n+ panic(fmt.Sprintf(\"unrecoverable overlayfs inconsistency: failed to delete upper layer directory after MkdirAt metadata update failure: %v\", cleanupErr))\n} else if haveUpperWhiteout {\nfs.cleanupRecreateWhiteout(ctx, vfsObj, &pop)\n}\n@@ -678,7 +679,7 @@ func (fs *filesystem) MkdirAt(ctx context.Context, rp *vfs.ResolvingPath, opts v\nValue: \"y\",\n}); err != nil {\nif cleanupErr := vfsObj.RmdirAt(ctx, fs.creds, &pop); cleanupErr != nil {\n- ctx.Warningf(\"Unrecoverable overlayfs inconsistency: failed to delete upper layer directory after MkdirAt set-opaque failure: %v\", cleanupErr)\n+ panic(fmt.Sprintf(\"unrecoverable overlayfs inconsistency: failed to delete upper layer directory after MkdirAt set-opaque failure: %v\", cleanupErr))\n} else {\nfs.cleanupRecreateWhiteout(ctx, vfsObj, &pop)\n}\n@@ -722,7 +723,7 @@ func (fs *filesystem) MknodAt(ctx context.Context, rp *vfs.ResolvingPath, opts v\n},\n}); err != nil {\nif cleanupErr := vfsObj.UnlinkAt(ctx, fs.creds, &pop); cleanupErr != nil {\n- ctx.Warningf(\"Unrecoverable overlayfs inconsistency: failed to delete upper layer file after MknodAt metadata update failure: %v\", cleanupErr)\n+ panic(fmt.Sprintf(\"unrecoverable overlayfs inconsistency: failed to delete upper layer file after MknodAt metadata update failure: %v\", cleanupErr))\n} else if haveUpperWhiteout {\nfs.cleanupRecreateWhiteout(ctx, vfsObj, &pop)\n}\n@@ -942,7 +943,7 @@ func (fs *filesystem) createAndOpenLocked(ctx context.Context, rp *vfs.Resolving\n},\n}); err != nil {\nif cleanupErr := vfsObj.UnlinkAt(ctx, fs.creds, &pop); cleanupErr != nil {\n- ctx.Warningf(\"Unrecoverable overlayfs inconsistency: failed to delete upper layer file after OpenAt(O_CREAT) metadata update failure: %v\", cleanupErr)\n+ panic(fmt.Sprintf(\"unrecoverable overlayfs inconsistency: failed to delete upper layer file after OpenAt(O_CREAT) metadata update failure: %v\", cleanupErr))\n} else if haveUpperWhiteout {\nfs.cleanupRecreateWhiteout(ctx, vfsObj, &pop)\n}\n@@ -953,7 +954,7 @@ func (fs *filesystem) createAndOpenLocked(ctx context.Context, rp *vfs.Resolving\nchild, err := fs.getChildLocked(ctx, parent, childName, ds)\nif err != nil {\nif cleanupErr := vfsObj.UnlinkAt(ctx, fs.creds, &pop); cleanupErr != nil {\n- ctx.Warningf(\"Unrecoverable overlayfs inconsistency: failed to delete upper layer file after OpenAt(O_CREAT) dentry lookup failure: %v\", cleanupErr)\n+ panic(fmt.Sprintf(\"unrecoverable overlayfs inconsistency: failed to delete upper layer file after OpenAt(O_CREAT) dentry lookup failure: %v\", cleanupErr))\n} else if haveUpperWhiteout {\nfs.cleanupRecreateWhiteout(ctx, vfsObj, &pop)\n}\n@@ -1019,9 +1020,223 @@ func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\n}\ndefer mnt.EndWrite()\n- // FIXME(gvisor.dev/issue/1199): Actually implement rename.\n- _ = newParent\n- return syserror.EXDEV\n+ oldParent := oldParentVD.Dentry().Impl().(*dentry)\n+ creds := rp.Credentials()\n+ if err := oldParent.checkPermissions(creds, vfs.MayWrite|vfs.MayExec); err != nil {\n+ return err\n+ }\n+ // We need a dentry representing the renamed file since, if it's a\n+ // directory, we need to check for write permission on it.\n+ oldParent.dirMu.Lock()\n+ defer oldParent.dirMu.Unlock()\n+ renamed, err := fs.getChildLocked(ctx, oldParent, oldName, &ds)\n+ if err != nil {\n+ return err\n+ }\n+ if err := vfs.CheckDeleteSticky(creds, linux.FileMode(atomic.LoadUint32(&oldParent.mode)), auth.KUID(atomic.LoadUint32(&renamed.uid))); err != nil {\n+ return err\n+ }\n+ if renamed.isDir() {\n+ if renamed == newParent || genericIsAncestorDentry(renamed, newParent) {\n+ return syserror.EINVAL\n+ }\n+ if oldParent != newParent {\n+ if err := renamed.checkPermissions(creds, vfs.MayWrite); err != nil {\n+ return err\n+ }\n+ }\n+ } else {\n+ if opts.MustBeDir || rp.MustBeDir() {\n+ return syserror.ENOTDIR\n+ }\n+ }\n+\n+ if oldParent != newParent {\n+ if err := newParent.checkPermissions(creds, vfs.MayWrite|vfs.MayExec); err != nil {\n+ return err\n+ }\n+ newParent.dirMu.Lock()\n+ defer newParent.dirMu.Unlock()\n+ }\n+ if newParent.vfsd.IsDead() {\n+ return syserror.ENOENT\n+ }\n+ replacedLayer, err := fs.lookupLayerLocked(ctx, newParent, newName)\n+ if err != nil {\n+ return err\n+ }\n+ var (\n+ replaced *dentry\n+ replacedVFSD *vfs.Dentry\n+ whiteouts map[string]bool\n+ )\n+ if replacedLayer.existsInOverlay() {\n+ replaced, err = fs.getChildLocked(ctx, newParent, newName, &ds)\n+ if err != nil {\n+ return err\n+ }\n+ replacedVFSD = &replaced.vfsd\n+ if replaced.isDir() {\n+ if !renamed.isDir() {\n+ return syserror.EISDIR\n+ }\n+ if genericIsAncestorDentry(replaced, renamed) {\n+ return syserror.ENOTEMPTY\n+ }\n+ replaced.dirMu.Lock()\n+ defer replaced.dirMu.Unlock()\n+ whiteouts, err = replaced.collectWhiteoutsForRmdirLocked(ctx)\n+ if err != nil {\n+ return err\n+ }\n+ } else {\n+ if rp.MustBeDir() || renamed.isDir() {\n+ return syserror.ENOTDIR\n+ }\n+ }\n+ }\n+\n+ if oldParent == newParent && oldName == newName {\n+ return nil\n+ }\n+\n+ // renamed and oldParent need to be copied-up before they're renamed on the\n+ // upper layer.\n+ if err := renamed.copyUpLocked(ctx); err != nil {\n+ return err\n+ }\n+ // If renamed is a directory, all of its descendants need to be copied-up\n+ // before they're renamed on the upper layer.\n+ if renamed.isDir() {\n+ if err := renamed.copyUpDescendantsLocked(ctx, &ds); err != nil {\n+ return err\n+ }\n+ }\n+ // newParent must be copied-up before it can contain renamed on the upper\n+ // layer.\n+ if err := newParent.copyUpLocked(ctx); err != nil {\n+ return err\n+ }\n+ // If replaced exists, it doesn't need to be copied-up, but we do need to\n+ // serialize with copy-up. Holding renameMu for writing should be\n+ // sufficient, but out of an abundance of caution...\n+ if replaced != nil {\n+ replaced.copyMu.RLock()\n+ defer replaced.copyMu.RUnlock()\n+ }\n+\n+ vfsObj := rp.VirtualFilesystem()\n+ mntns := vfs.MountNamespaceFromContext(ctx)\n+ defer mntns.DecRef(ctx)\n+ if err := vfsObj.PrepareRenameDentry(mntns, &renamed.vfsd, replacedVFSD); err != nil {\n+ return err\n+ }\n+\n+ newpop := vfs.PathOperation{\n+ Root: newParent.upperVD,\n+ Start: newParent.upperVD,\n+ Path: fspath.Parse(newName),\n+ }\n+\n+ needRecreateWhiteouts := false\n+ cleanupRecreateWhiteouts := func() {\n+ if !needRecreateWhiteouts {\n+ return\n+ }\n+ for whiteoutName, whiteoutUpper := range whiteouts {\n+ if !whiteoutUpper {\n+ continue\n+ }\n+ if err := fs.createWhiteout(ctx, vfsObj, &vfs.PathOperation{\n+ Root: replaced.upperVD,\n+ Start: replaced.upperVD,\n+ Path: fspath.Parse(whiteoutName),\n+ }); err != nil && err != syserror.EEXIST {\n+ panic(fmt.Sprintf(\"unrecoverable overlayfs inconsistency: failed to recreate deleted whiteout after RenameAt failure: %v\", err))\n+ }\n+ }\n+ }\n+ if renamed.isDir() {\n+ if replacedLayer == lookupLayerUpper {\n+ // Remove whiteouts from the directory being replaced.\n+ needRecreateWhiteouts = true\n+ for whiteoutName, whiteoutUpper := range whiteouts {\n+ if !whiteoutUpper {\n+ continue\n+ }\n+ if err := vfsObj.UnlinkAt(ctx, fs.creds, &vfs.PathOperation{\n+ Root: replaced.upperVD,\n+ Start: replaced.upperVD,\n+ Path: fspath.Parse(whiteoutName),\n+ }); err != nil {\n+ cleanupRecreateWhiteouts()\n+ vfsObj.AbortRenameDentry(&renamed.vfsd, replacedVFSD)\n+ return err\n+ }\n+ }\n+ } else if replacedLayer == lookupLayerUpperWhiteout {\n+ // We need to explicitly remove the whiteout since otherwise rename\n+ // on the upper layer will fail with ENOTDIR.\n+ if err := vfsObj.UnlinkAt(ctx, fs.creds, &newpop); err != nil {\n+ vfsObj.AbortRenameDentry(&renamed.vfsd, replacedVFSD)\n+ return err\n+ }\n+ }\n+ }\n+\n+ // Essentially no gVisor filesystem supports RENAME_WHITEOUT, so just do a\n+ // regular rename and create the whiteout at the origin manually. Unlike\n+ // RENAME_WHITEOUT, this isn't atomic with respect to other users of the\n+ // upper filesystem, but this is already the case for virtually all other\n+ // overlay filesystem operations too.\n+ oldpop := vfs.PathOperation{\n+ Root: oldParent.upperVD,\n+ Start: oldParent.upperVD,\n+ Path: fspath.Parse(oldName),\n+ }\n+ if err := vfsObj.RenameAt(ctx, creds, &oldpop, &newpop, &opts); err != nil {\n+ cleanupRecreateWhiteouts()\n+ vfsObj.AbortRenameDentry(&renamed.vfsd, replacedVFSD)\n+ return err\n+ }\n+\n+ // Below this point, the renamed dentry is now at newpop, and anything we\n+ // replaced is gone forever. Commit the rename, update the overlay\n+ // filesystem tree, and abandon attempts to recover from errors.\n+ vfsObj.CommitRenameReplaceDentry(ctx, &renamed.vfsd, replacedVFSD)\n+ delete(oldParent.children, oldName)\n+ if replaced != nil {\n+ ds = appendDentry(ds, replaced)\n+ }\n+ if oldParent != newParent {\n+ newParent.dirents = nil\n+ // This can't drop the last reference on oldParent because one is held\n+ // by oldParentVD, so lock recursion is impossible.\n+ oldParent.DecRef(ctx)\n+ ds = appendDentry(ds, oldParent)\n+ newParent.IncRef()\n+ renamed.parent = newParent\n+ }\n+ renamed.name = newName\n+ if newParent.children == nil {\n+ newParent.children = make(map[string]*dentry)\n+ }\n+ newParent.children[newName] = renamed\n+ oldParent.dirents = nil\n+\n+ if err := fs.createWhiteout(ctx, vfsObj, &oldpop); err != nil {\n+ panic(fmt.Sprintf(\"unrecoverable overlayfs inconsistency: failed to create whiteout at origin after RenameAt: %v\", err))\n+ }\n+ if renamed.isDir() {\n+ if err := vfsObj.SetXattrAt(ctx, fs.creds, &newpop, &vfs.SetXattrOptions{\n+ Name: _OVL_XATTR_OPAQUE,\n+ Value: \"y\",\n+ }); err != nil {\n+ panic(fmt.Sprintf(\"unrecoverable overlayfs inconsistency: failed to make renamed directory opaque: %v\", err))\n+ }\n+ }\n+\n+ return nil\n}\n// RmdirAt implements vfs.FilesystemImpl.RmdirAt.\n@@ -1100,7 +1315,7 @@ func (fs *filesystem) RmdirAt(ctx context.Context, rp *vfs.ResolvingPath) error\nStart: child.upperVD,\nPath: fspath.Parse(whiteoutName),\n}); err != nil && err != syserror.EEXIST {\n- ctx.Warningf(\"Unrecoverable overlayfs inconsistency: failed to recreate deleted whiteout after RmdirAt failure: %v\", err)\n+ panic(fmt.Sprintf(\"unrecoverable overlayfs inconsistency: failed to recreate deleted whiteout after RmdirAt failure: %v\", err))\n}\n}\n}\n@@ -1130,9 +1345,7 @@ func (fs *filesystem) RmdirAt(ctx context.Context, rp *vfs.ResolvingPath) error\n// Don't attempt to recover from this: the original directory is\n// already gone, so any dentries representing it are invalid, and\n// creating a new directory won't undo that.\n- ctx.Warningf(\"Unrecoverable overlayfs inconsistency: failed to create whiteout during RmdirAt: %v\", err)\n- vfsObj.AbortDeleteDentry(&child.vfsd)\n- return err\n+ panic(fmt.Sprintf(\"unrecoverable overlayfs inconsistency: failed to create whiteout during RmdirAt: %v\", err))\n}\nvfsObj.CommitDeleteDentry(ctx, &child.vfsd)\n@@ -1246,7 +1459,7 @@ func (fs *filesystem) SymlinkAt(ctx context.Context, rp *vfs.ResolvingPath, targ\n},\n}); err != nil {\nif cleanupErr := vfsObj.UnlinkAt(ctx, fs.creds, &pop); cleanupErr != nil {\n- ctx.Warningf(\"Unrecoverable overlayfs inconsistency: failed to delete upper layer file after SymlinkAt metadata update failure: %v\", cleanupErr)\n+ panic(fmt.Sprintf(\"unrecoverable overlayfs inconsistency: failed to delete upper layer file after SymlinkAt metadata update failure: %v\", cleanupErr))\n} else if haveUpperWhiteout {\nfs.cleanupRecreateWhiteout(ctx, vfsObj, &pop)\n}\n@@ -1339,11 +1552,7 @@ func (fs *filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\n}\n}\nif err := fs.createWhiteout(ctx, vfsObj, &pop); err != nil {\n- ctx.Warningf(\"Unrecoverable overlayfs inconsistency: failed to create whiteout during UnlinkAt: %v\", err)\n- if child != nil {\n- vfsObj.AbortDeleteDentry(&child.vfsd)\n- }\n- return err\n+ panic(fmt.Sprintf(\"unrecoverable overlayfs inconsistency: failed to create whiteout during UnlinkAt: %v\", err))\n}\nif child != nil {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/overlay/overlay.go", "new_path": "pkg/sentry/fsimpl/overlay/overlay.go", "diff": "@@ -111,16 +111,16 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nfsoptsRaw := opts.InternalData\nfsopts, haveFSOpts := fsoptsRaw.(FilesystemOptions)\nif fsoptsRaw != nil && !haveFSOpts {\n- ctx.Warningf(\"overlay.FilesystemType.GetFilesystem: GetFilesystemOptions.InternalData has type %T, wanted overlay.FilesystemOptions or nil\", fsoptsRaw)\n+ ctx.Infof(\"overlay.FilesystemType.GetFilesystem: GetFilesystemOptions.InternalData has type %T, wanted overlay.FilesystemOptions or nil\", fsoptsRaw)\nreturn nil, nil, syserror.EINVAL\n}\nif haveFSOpts {\nif len(fsopts.LowerRoots) == 0 {\n- ctx.Warningf(\"overlay.FilesystemType.GetFilesystem: LowerRoots must be non-empty\")\n+ ctx.Infof(\"overlay.FilesystemType.GetFilesystem: LowerRoots must be non-empty\")\nreturn nil, nil, syserror.EINVAL\n}\nif len(fsopts.LowerRoots) < 2 && !fsopts.UpperRoot.Ok() {\n- ctx.Warningf(\"overlay.FilesystemType.GetFilesystem: at least two LowerRoots are required when UpperRoot is unspecified\")\n+ ctx.Infof(\"overlay.FilesystemType.GetFilesystem: at least two LowerRoots are required when UpperRoot is unspecified\")\nreturn nil, nil, syserror.EINVAL\n}\n// We don't enforce a maximum number of lower layers when not\n@@ -137,7 +137,7 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\ndelete(mopts, \"workdir\")\nupperPath := fspath.Parse(upperPathname)\nif !upperPath.Absolute {\n- ctx.Warningf(\"overlay.FilesystemType.GetFilesystem: upperdir %q must be absolute\", upperPathname)\n+ ctx.Infof(\"overlay.FilesystemType.GetFilesystem: upperdir %q must be absolute\", upperPathname)\nreturn nil, nil, syserror.EINVAL\n}\nupperRoot, err := vfsObj.GetDentryAt(ctx, creds, &vfs.PathOperation{\n@@ -149,13 +149,13 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nCheckSearchable: true,\n})\nif err != nil {\n- ctx.Warningf(\"overlay.FilesystemType.GetFilesystem: failed to resolve upperdir %q: %v\", upperPathname, err)\n+ ctx.Infof(\"overlay.FilesystemType.GetFilesystem: failed to resolve upperdir %q: %v\", upperPathname, err)\nreturn nil, nil, err\n}\ndefer upperRoot.DecRef(ctx)\nprivateUpperRoot, err := clonePrivateMount(vfsObj, upperRoot, false /* forceReadOnly */)\nif err != nil {\n- ctx.Warningf(\"overlay.FilesystemType.GetFilesystem: failed to make private bind mount of upperdir %q: %v\", upperPathname, err)\n+ ctx.Infof(\"overlay.FilesystemType.GetFilesystem: failed to make private bind mount of upperdir %q: %v\", upperPathname, err)\nreturn nil, nil, err\n}\ndefer privateUpperRoot.DecRef(ctx)\n@@ -163,24 +163,24 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\n}\nlowerPathnamesStr, ok := mopts[\"lowerdir\"]\nif !ok {\n- ctx.Warningf(\"overlay.FilesystemType.GetFilesystem: missing required option lowerdir\")\n+ ctx.Infof(\"overlay.FilesystemType.GetFilesystem: missing required option lowerdir\")\nreturn nil, nil, syserror.EINVAL\n}\ndelete(mopts, \"lowerdir\")\nlowerPathnames := strings.Split(lowerPathnamesStr, \":\")\nconst maxLowerLayers = 500 // Linux: fs/overlay/super.c:OVL_MAX_STACK\nif len(lowerPathnames) < 2 && !fsopts.UpperRoot.Ok() {\n- ctx.Warningf(\"overlay.FilesystemType.GetFilesystem: at least two lowerdirs are required when upperdir is unspecified\")\n+ ctx.Infof(\"overlay.FilesystemType.GetFilesystem: at least two lowerdirs are required when upperdir is unspecified\")\nreturn nil, nil, syserror.EINVAL\n}\nif len(lowerPathnames) > maxLowerLayers {\n- ctx.Warningf(\"overlay.FilesystemType.GetFilesystem: %d lowerdirs specified, maximum %d\", len(lowerPathnames), maxLowerLayers)\n+ ctx.Infof(\"overlay.FilesystemType.GetFilesystem: %d lowerdirs specified, maximum %d\", len(lowerPathnames), maxLowerLayers)\nreturn nil, nil, syserror.EINVAL\n}\nfor _, lowerPathname := range lowerPathnames {\nlowerPath := fspath.Parse(lowerPathname)\nif !lowerPath.Absolute {\n- ctx.Warningf(\"overlay.FilesystemType.GetFilesystem: lowerdir %q must be absolute\", lowerPathname)\n+ ctx.Infof(\"overlay.FilesystemType.GetFilesystem: lowerdir %q must be absolute\", lowerPathname)\nreturn nil, nil, syserror.EINVAL\n}\nlowerRoot, err := vfsObj.GetDentryAt(ctx, creds, &vfs.PathOperation{\n@@ -192,13 +192,13 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nCheckSearchable: true,\n})\nif err != nil {\n- ctx.Warningf(\"overlay.FilesystemType.GetFilesystem: failed to resolve lowerdir %q: %v\", lowerPathname, err)\n+ ctx.Infof(\"overlay.FilesystemType.GetFilesystem: failed to resolve lowerdir %q: %v\", lowerPathname, err)\nreturn nil, nil, err\n}\ndefer lowerRoot.DecRef(ctx)\nprivateLowerRoot, err := clonePrivateMount(vfsObj, lowerRoot, true /* forceReadOnly */)\nif err != nil {\n- ctx.Warningf(\"overlay.FilesystemType.GetFilesystem: failed to make private bind mount of lowerdir %q: %v\", lowerPathname, err)\n+ ctx.Infof(\"overlay.FilesystemType.GetFilesystem: failed to make private bind mount of lowerdir %q: %v\", lowerPathname, err)\nreturn nil, nil, err\n}\ndefer privateLowerRoot.DecRef(ctx)\n@@ -206,7 +206,7 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\n}\n}\nif len(mopts) != 0 {\n- ctx.Warningf(\"overlay.FilesystemType.GetFilesystem: unused options: %v\", mopts)\n+ ctx.Infof(\"overlay.FilesystemType.GetFilesystem: unused options: %v\", mopts)\nreturn nil, nil, syserror.EINVAL\n}\n@@ -279,7 +279,7 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nreturn nil, nil, syserror.EREMOTE\n}\nif isWhiteout(&rootStat) {\n- ctx.Warningf(\"overlay.FilesystemType.GetFilesystem: filesystem root is a whiteout\")\n+ ctx.Infof(\"overlay.FilesystemType.GetFilesystem: filesystem root is a whiteout\")\nroot.destroyLocked(ctx)\nfs.vfsfs.DecRef(ctx)\nreturn nil, nil, syserror.EINVAL\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/rename.cc", "new_path": "test/syscalls/linux/rename.cc", "diff": "@@ -170,6 +170,9 @@ TEST(RenameTest, FileOverwritesFile) {\n}\nTEST(RenameTest, DirectoryOverwritesDirectoryLinkCount) {\n+ // Directory link counts are synthetic on overlay filesystems.\n+ SKIP_IF(ASSERT_NO_ERRNO_AND_VALUE(IsOverlayfs(GetAbsoluteTestTmpdir())));\n+\nauto parent1 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\nEXPECT_THAT(Links(parent1.path()), IsPosixErrorOkAndHolds(2));\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/stat.cc", "new_path": "test/syscalls/linux/stat.cc", "diff": "@@ -346,7 +346,10 @@ TEST_F(StatTest, StatDoesntChangeAfterRename) {\nEXPECT_EQ(st_old.st_nlink, st_new.st_nlink);\nEXPECT_EQ(st_old.st_dev, st_new.st_dev);\n+ // Overlay filesystems may synthesize directory inode numbers on the fly.\n+ if (!ASSERT_NO_ERRNO_AND_VALUE(IsOverlayfs(GetAbsoluteTestTmpdir()))) {\nEXPECT_EQ(st_old.st_ino, st_new.st_ino);\n+ }\nEXPECT_EQ(st_old.st_mode, st_new.st_mode);\nEXPECT_EQ(st_old.st_uid, st_new.st_uid);\nEXPECT_EQ(st_old.st_gid, st_new.st_gid);\n" } ]
Go
Apache License 2.0
google/gvisor
Implement fsimpl/overlay.filesystem.RenameAt. Updates #1199 PiperOrigin-RevId: 332539197
259,885
18.09.2020 20:51:56
25,200
916751039cca927a0e64b4e6f776d2d4732cf8d8
Disable vdso_clock_gettime on KVM. Unfortunately, I think TSC misalignment means that we can't really expect any consistent correspondence between a TSC-based VDSO and the sentry's view of time on the KVM platform.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/vdso_clock_gettime.cc", "new_path": "test/syscalls/linux/vdso_clock_gettime.cc", "diff": "@@ -48,6 +48,11 @@ std::string PrintClockId(::testing::TestParamInfo<clockid_t> info) {\nclass MonotonicVDSOClockTest : public ::testing::TestWithParam<clockid_t> {};\nTEST_P(MonotonicVDSOClockTest, IsCorrect) {\n+ // The VDSO implementation of clock_gettime() uses the TSC. On KVM, sentry and\n+ // application TSCs can be very desynchronized; see\n+ // sentry/platform/kvm/kvm.vCPU.setSystemTime().\n+ SKIP_IF(GvisorPlatform() == Platform::kKVM);\n+\n// Check that when we alternate readings from the clock_gettime syscall and\n// the VDSO's implementation, we observe the combined sequence as being\n// monotonic.\n" } ]
Go
Apache License 2.0
google/gvisor
Disable vdso_clock_gettime on KVM. Unfortunately, I think TSC misalignment means that we can't really expect any consistent correspondence between a TSC-based VDSO and the sentry's view of time on the KVM platform. PiperOrigin-RevId: 332576147
259,975
21.09.2020 10:03:32
25,200
5ce58829515b7534a2a01210e1a18f1b200727e4
Fix flakes in UdpSocketTest `recv` calls with MSG_DONTWAIT can fail with EAGAIN randomly in tests. Fix this by calling `select` on sockets with a timeout prior to attempting a `recv`.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_test_util.cc", "new_path": "test/syscalls/linux/socket_test_util.cc", "diff": "@@ -753,6 +753,19 @@ PosixErrorOr<int> SendMsg(int sock, msghdr* msg, char buf[], int buf_size) {\nreturn ret;\n}\n+PosixErrorOr<int> RecvMsgTimeout(int sock, char buf[], int buf_size,\n+ int timeout) {\n+ fd_set rfd;\n+ struct timeval to = {.tv_sec = timeout, .tv_usec = 0};\n+ FD_ZERO(&rfd);\n+ FD_SET(sock, &rfd);\n+\n+ int ret;\n+ RETURN_ERROR_IF_SYSCALL_FAIL(ret = select(1, &rfd, NULL, NULL, &to));\n+ RETURN_ERROR_IF_SYSCALL_FAIL(ret = recv(sock, buf, buf_size, MSG_DONTWAIT));\n+ return ret;\n+}\n+\nvoid RecvNoData(int sock) {\nchar data = 0;\nstruct iovec iov;\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_test_util.h", "new_path": "test/syscalls/linux/socket_test_util.h", "diff": "@@ -467,6 +467,10 @@ PosixError FreeAvailablePort(int port);\n// SendMsg converts a buffer to an iovec and adds it to msg before sending it.\nPosixErrorOr<int> SendMsg(int sock, msghdr* msg, char buf[], int buf_size);\n+// RecvMsgTimeout calls select on sock with timeout and then calls recv on sock.\n+PosixErrorOr<int> RecvMsgTimeout(int sock, char buf[], int buf_size,\n+ int timeout);\n+\n// RecvNoData checks that no data is receivable on sock.\nvoid RecvNoData(int sock);\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/udp_socket.cc", "new_path": "test/syscalls/linux/udp_socket.cc", "diff": "#include <arpa/inet.h>\n#include <fcntl.h>\n+\n+#include <ctime>\n+\n#ifdef __linux__\n#include <linux/errqueue.h>\n#include <linux/filter.h>\n@@ -834,8 +837,9 @@ TEST_P(UdpSocketTest, ReceiveBeforeConnect) {\n// Receive the data. It works because it was sent before the connect.\nchar received[sizeof(buf)];\n- EXPECT_THAT(recv(bind_.get(), received, sizeof(received), 0),\n- SyscallSucceedsWithValue(sizeof(received)));\n+ EXPECT_THAT(\n+ RecvMsgTimeout(bind_.get(), received, sizeof(received), 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(sizeof(received)));\nEXPECT_EQ(memcmp(buf, received, sizeof(buf)), 0);\n// Send again. This time it should not be received.\n@@ -924,7 +928,9 @@ TEST_P(UdpSocketTest, ReadShutdownNonblockPendingData) {\nSyscallSucceedsWithValue(1));\n// We should get the data even though read has been shutdown.\n- EXPECT_THAT(recv(bind_.get(), received, 2, 0), SyscallSucceedsWithValue(2));\n+ EXPECT_THAT(\n+ RecvMsgTimeout(bind_.get(), received, 2 /*buf_size*/, 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(2));\n// Because we read less than the entire packet length, since it's a packet\n// based socket any subsequent reads should return EWOULDBLOCK.\n@@ -1692,9 +1698,9 @@ TEST_P(UdpSocketTest, RecvBufLimitsEmptyRcvBuf) {\nsendto(sock_.get(), buf.data(), buf.size(), 0, bind_addr_, addrlen_),\nSyscallSucceedsWithValue(buf.size()));\nstd::vector<char> received(buf.size());\n- EXPECT_THAT(\n- recv(bind_.get(), received.data(), received.size(), MSG_DONTWAIT),\n- SyscallSucceedsWithValue(received.size()));\n+ EXPECT_THAT(RecvMsgTimeout(bind_.get(), received.data(), received.size(),\n+ 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(received.size()));\n}\n{\n@@ -1708,9 +1714,9 @@ TEST_P(UdpSocketTest, RecvBufLimitsEmptyRcvBuf) {\nSyscallSucceedsWithValue(buf.size()));\nstd::vector<char> received(buf.size());\n- EXPECT_THAT(\n- recv(bind_.get(), received.data(), received.size(), MSG_DONTWAIT),\n- SyscallSucceedsWithValue(received.size()));\n+ ASSERT_THAT(RecvMsgTimeout(bind_.get(), received.data(), received.size(),\n+ 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(received.size()));\n}\n}\n@@ -1779,9 +1785,9 @@ TEST_P(UdpSocketTest, RecvBufLimits) {\nfor (int i = 0; i < sent - 1; i++) {\n// Receive the data.\nstd::vector<char> received(buf.size());\n- EXPECT_THAT(\n- recv(bind_.get(), received.data(), received.size(), MSG_DONTWAIT),\n- SyscallSucceedsWithValue(received.size()));\n+ EXPECT_THAT(RecvMsgTimeout(bind_.get(), received.data(), received.size(),\n+ 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(received.size()));\nEXPECT_EQ(memcmp(buf.data(), received.data(), buf.size()), 0);\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix flakes in UdpSocketTest `recv` calls with MSG_DONTWAIT can fail with EAGAIN randomly in tests. Fix this by calling `select` on sockets with a timeout prior to attempting a `recv`. PiperOrigin-RevId: 332873735
259,907
21.09.2020 10:25:41
25,200
e09d78f016ecbada5784324925b3c6b18041a2ec
Port fuse tests to Makefile.
[ { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "@@ -121,8 +121,13 @@ smoke-tests: ## Runs a simple smoke test after build runsc.\n@$(call submake,run DOCKER_PRIVILEGED=\"\" ARGS=\"--alsologtostderr --network none --debug --TESTONLY-unsafe-nonroot=true --rootless do true\")\n.PHONY: smoke-tests\n+fuse-tests:\n+ @$(call submake,test OPTIONS=\"--test_tag_filters fuse\" TARGETS=\"test/fuse/...\")\n+.PHONY: fuse-tests\n+\nunit-tests: ## Local package unit tests in pkg/..., runsc/, tools/.., etc.\n@$(call submake,test TARGETS=\"pkg/... runsc/... tools/...\")\n+.PHONY: unit-tests\ntests: ## Runs all unit tests and syscall tests.\ntests: unit-tests\n" }, { "change_type": "DELETE", "old_path": "scripts/fuse_tests.sh", "new_path": null, "diff": "-#!/bin/bash\n-\n-# Copyright 2020 The gVisor Authors.\n-#\n-# Licensed under the Apache License, Version 2.0 (the \"License\");\n-# you may not use this file except in compliance with the License.\n-# You may obtain a copy of the License at\n-#\n-# http://www.apache.org/licenses/LICENSE-2.0\n-#\n-# Unless required by applicable law or agreed to in writing, software\n-# distributed under the License is distributed on an \"AS IS\" BASIS,\n-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-# See the License for the specific language governing permissions and\n-# limitations under the License.\n-\n-source $(dirname $0)/common.sh\n-\n-# Run all vfs2_fuse system call tests.\n-test --test_tag_filters=fuse //test/fuse/...\n" } ]
Go
Apache License 2.0
google/gvisor
Port fuse tests to Makefile. PiperOrigin-RevId: 332878900
259,860
21.09.2020 12:29:00
25,200
d72022373f8ab2ca60ec1494858a3cb3e2be9040
Add ftruncate test for writeable fd but no write permissions.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/truncate.cc", "new_path": "test/syscalls/linux/truncate.cc", "diff": "@@ -196,6 +196,26 @@ TEST(TruncateTest, FtruncateNonWriteable) {\nEXPECT_THAT(ftruncate(fd.get(), 0), SyscallFailsWithErrno(EINVAL));\n}\n+// ftruncate(2) should succeed as long as the file descriptor is writeable,\n+// regardless of whether the file permissions allow writing.\n+TEST(TruncateTest, FtruncateWithoutWritePermission_NoRandomSave) {\n+ // Drop capabilities that allow us to override file permissions.\n+ ASSERT_NO_ERRNO(SetCapability(CAP_DAC_OVERRIDE, false));\n+\n+ // The only time we can open a file with flags forbidden by its permissions\n+ // is when we are creating the file. We cannot re-open with the same flags,\n+ // so we cannot restore an fd obtained from such an operation.\n+ const DisableSave ds;\n+ auto path = NewTempAbsPath();\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(path, O_RDWR | O_CREAT, 0444));\n+\n+ // In goferfs, ftruncate may be converted to a remote truncate operation that\n+ // unavoidably requires write permission.\n+ SKIP_IF(IsRunningOnGvisor() && !ASSERT_NO_ERRNO_AND_VALUE(IsTmpfs(path)));\n+ ASSERT_THAT(ftruncate(fd.get(), 100), SyscallSucceeds());\n+}\n+\nTEST(TruncateTest, TruncateNonExist) {\nEXPECT_THAT(truncate(\"/foo/bar\", 0), SyscallFailsWithErrno(ENOENT));\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add ftruncate test for writeable fd but no write permissions. PiperOrigin-RevId: 332907453
259,975
21.09.2020 12:44:26
25,200
a129204cf508b170a62c93ed7148453f346b32e4
Fix proc_net_test_native for native tests. "DefaultValueEqZero" is only valid if the test is in a sandbox. Our CI VMs often have "/proc/sys/net/ipv4/ip_forward" set to 1.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/proc_net.cc", "new_path": "test/syscalls/linux/proc_net.cc", "diff": "@@ -522,6 +522,9 @@ TEST(ProcSysNetIpv4IpForward, Exists) {\n}\nTEST(ProcSysNetIpv4IpForward, DefaultValueEqZero) {\n+ // Test is only valid in sandbox. Not hermetic in native tests\n+ // running on a arbitrary machine.\n+ SKIP_IF(!IsRunningOnGvisor());\nauto const fd = ASSERT_NO_ERRNO_AND_VALUE(Open(kIpForward, O_RDONLY));\nchar buf = 101;\n" } ]
Go
Apache License 2.0
google/gvisor
Fix proc_net_test_native for native tests. "DefaultValueEqZero" is only valid if the test is in a sandbox. Our CI VMs often have "/proc/sys/net/ipv4/ip_forward" set to 1. PiperOrigin-RevId: 332910859
259,860
21.09.2020 14:46:51
25,200
10dcefbc77815314d56e45f01b8c9986a2c56778
Use kernfs.Dentry for kernfs.Lookup. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/devpts/devpts.go", "new_path": "pkg/sentry/fsimpl/devpts/devpts.go", "diff": "@@ -198,7 +198,7 @@ func (i *rootInode) Open(ctx context.Context, rp *vfs.ResolvingPath, vfsd *vfs.D\n}\n// Lookup implements kernfs.Inode.Lookup.\n-func (i *rootInode) Lookup(ctx context.Context, name string) (*vfs.Dentry, error) {\n+func (i *rootInode) Lookup(ctx context.Context, name string) (*kernfs.Dentry, error) {\nidx, err := strconv.ParseUint(name, 10, 32)\nif err != nil {\nreturn nil, syserror.ENOENT\n@@ -207,7 +207,7 @@ func (i *rootInode) Lookup(ctx context.Context, name string) (*vfs.Dentry, error\ndefer i.mu.Unlock()\nif si, ok := i.replicas[uint32(idx)]; ok {\nsi.dentry.IncRef()\n- return si.dentry.VFSDentry(), nil\n+ return &si.dentry, nil\n}\nreturn nil, syserror.ENOENT\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "new_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "diff": "@@ -402,7 +402,7 @@ func (i *inode) Open(ctx context.Context, rp *vfs.ResolvingPath, vfsd *vfs.Dentr\n}\n// Lookup implements kernfs.Inode.Lookup.\n-func (i *inode) Lookup(ctx context.Context, name string) (*vfs.Dentry, error) {\n+func (i *inode) Lookup(ctx context.Context, name string) (*kernfs.Dentry, error) {\nin := linux.FUSELookupIn{Name: name}\nreturn i.newEntry(ctx, name, 0, linux.FUSE_LOOKUP, &in)\n}\n@@ -432,7 +432,11 @@ func (i *inode) NewFile(ctx context.Context, name string, opts vfs.OpenOptions)\n},\nName: name,\n}\n- return i.newEntry(ctx, name, linux.S_IFREG, linux.FUSE_CREATE, &in)\n+ d, err := i.newEntry(ctx, name, linux.S_IFREG, linux.FUSE_CREATE, &in)\n+ if err != nil {\n+ return nil, err\n+ }\n+ return d.VFSDentry(), nil\n}\n// NewNode implements kernfs.Inode.NewNode.\n@@ -445,7 +449,11 @@ func (i *inode) NewNode(ctx context.Context, name string, opts vfs.MknodOptions)\n},\nName: name,\n}\n- return i.newEntry(ctx, name, opts.Mode.FileType(), linux.FUSE_MKNOD, &in)\n+ d, err := i.newEntry(ctx, name, opts.Mode.FileType(), linux.FUSE_MKNOD, &in)\n+ if err != nil {\n+ return nil, err\n+ }\n+ return d.VFSDentry(), nil\n}\n// NewSymlink implements kernfs.Inode.NewSymlink.\n@@ -454,7 +462,11 @@ func (i *inode) NewSymlink(ctx context.Context, name, target string) (*vfs.Dentr\nName: name,\nTarget: target,\n}\n- return i.newEntry(ctx, name, linux.S_IFLNK, linux.FUSE_SYMLINK, &in)\n+ d, err := i.newEntry(ctx, name, linux.S_IFLNK, linux.FUSE_SYMLINK, &in)\n+ if err != nil {\n+ return nil, err\n+ }\n+ return d.VFSDentry(), nil\n}\n// Unlink implements kernfs.Inode.Unlink.\n@@ -489,7 +501,11 @@ func (i *inode) NewDir(ctx context.Context, name string, opts vfs.MkdirOptions)\n},\nName: name,\n}\n- return i.newEntry(ctx, name, linux.S_IFDIR, linux.FUSE_MKDIR, &in)\n+ d, err := i.newEntry(ctx, name, linux.S_IFDIR, linux.FUSE_MKDIR, &in)\n+ if err != nil {\n+ return nil, err\n+ }\n+ return d.VFSDentry(), nil\n}\n// RmDir implements kernfs.Inode.RmDir.\n@@ -521,7 +537,7 @@ func (i *inode) RmDir(ctx context.Context, name string, child *vfs.Dentry) error\n// newEntry calls FUSE server for entry creation and allocates corresponding entry according to response.\n// Shared by FUSE_MKNOD, FUSE_MKDIR, FUSE_SYMLINK, FUSE_LINK and FUSE_LOOKUP.\n-func (i *inode) newEntry(ctx context.Context, name string, fileType linux.FileMode, opcode linux.FUSEOpcode, payload marshal.Marshallable) (*vfs.Dentry, error) {\n+func (i *inode) newEntry(ctx context.Context, name string, fileType linux.FileMode, opcode linux.FUSEOpcode, payload marshal.Marshallable) (*kernfs.Dentry, error) {\nkernelTask := kernel.TaskFromContext(ctx)\nif kernelTask == nil {\nlog.Warningf(\"fusefs.Inode.newEntry: couldn't get kernel task from context\", i.nodeID)\n@@ -551,7 +567,7 @@ func (i *inode) newEntry(ctx context.Context, name string, fileType linux.FileMo\n} else {\ni.dentry.InsertChild(name, child)\n}\n- return child.VFSDentry(), nil\n+ return child, nil\n}\n// Getlink implements kernfs.Inode.Getlink.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "diff": "@@ -127,20 +127,15 @@ func (fs *Filesystem) revalidateChildLocked(ctx context.Context, vfsObj *vfs.Vir\n}\n}\nif child == nil {\n- // Dentry isn't cached; it either doesn't exist or failed\n- // revalidation. Attempt to resolve it via Lookup.\n- //\n- // FIXME(gvisor.dev/issue/1193): Inode.Lookup() should return\n- // *(kernfs.)Dentry, not *vfs.Dentry, since (kernfs.)Filesystem assumes\n- // that all dentries in the filesystem are (kernfs.)Dentry and performs\n- // vfs.DentryImpl casts accordingly.\n- childVFSD, err := parent.inode.Lookup(ctx, name)\n+ // Dentry isn't cached; it either doesn't exist or failed revalidation.\n+ // Attempt to resolve it via Lookup.\n+ c, err := parent.inode.Lookup(ctx, name)\nif err != nil {\nreturn nil, err\n}\n// Reference on childVFSD dropped by a corresponding Valid.\n- child = childVFSD.Impl().(*Dentry)\n- parent.InsertChildLocked(name, child)\n+ parent.InsertChildLocked(name, c)\n+ child = c\n}\nreturn child, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go", "new_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go", "diff": "@@ -130,7 +130,7 @@ func (InodeNotDirectory) Rename(context.Context, string, string, *vfs.Dentry, *v\n}\n// Lookup implements Inode.Lookup.\n-func (InodeNotDirectory) Lookup(ctx context.Context, name string) (*vfs.Dentry, error) {\n+func (InodeNotDirectory) Lookup(ctx context.Context, name string) (*Dentry, error) {\npanic(\"Lookup called on non-directory inode\")\n}\n@@ -152,7 +152,7 @@ func (InodeNotDirectory) Valid(context.Context) bool {\ntype InodeNoDynamicLookup struct{}\n// Lookup implements Inode.Lookup.\n-func (InodeNoDynamicLookup) Lookup(ctx context.Context, name string) (*vfs.Dentry, error) {\n+func (InodeNoDynamicLookup) Lookup(ctx context.Context, name string) (*Dentry, error) {\nreturn nil, syserror.ENOENT\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/kernfs.go", "new_path": "pkg/sentry/fsimpl/kernfs/kernfs.go", "diff": "@@ -449,7 +449,7 @@ type inodeDynamicLookup interface {\n//\n// Lookup returns the child with an extra reference and the caller owns this\n// reference.\n- Lookup(ctx context.Context, name string) (*vfs.Dentry, error)\n+ Lookup(ctx context.Context, name string) (*Dentry, error)\n// Valid should return true if this inode is still valid, or needs to\n// be resolved again by a call to Lookup.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/subtasks.go", "new_path": "pkg/sentry/fsimpl/proc/subtasks.go", "diff": "@@ -69,7 +69,7 @@ func (fs *filesystem) newSubtasks(task *kernel.Task, pidns *kernel.PIDNamespace,\n}\n// Lookup implements kernfs.inodeDynamicLookup.Lookup.\n-func (i *subtasksInode) Lookup(ctx context.Context, name string) (*vfs.Dentry, error) {\n+func (i *subtasksInode) Lookup(ctx context.Context, name string) (*kernfs.Dentry, error) {\ntid, err := strconv.ParseUint(name, 10, 32)\nif err != nil {\nreturn nil, syserror.ENOENT\n@@ -82,9 +82,7 @@ func (i *subtasksInode) Lookup(ctx context.Context, name string) (*vfs.Dentry, e\nif subTask.ThreadGroup() != i.task.ThreadGroup() {\nreturn nil, syserror.ENOENT\n}\n-\n- subTaskDentry := i.fs.newTaskInode(subTask, i.pidns, false, i.cgroupControllers)\n- return subTaskDentry.VFSDentry(), nil\n+ return i.fs.newTaskInode(subTask, i.pidns, false, i.cgroupControllers), nil\n}\n// IterDirents implements kernfs.inodeDynamicLookup.IterDirents.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/task_fds.go", "new_path": "pkg/sentry/fsimpl/proc/task_fds.go", "diff": "@@ -136,7 +136,7 @@ func (fs *filesystem) newFDDirInode(task *kernel.Task) *kernfs.Dentry {\n}\n// Lookup implements kernfs.inodeDynamicLookup.Lookup.\n-func (i *fdDirInode) Lookup(ctx context.Context, name string) (*vfs.Dentry, error) {\n+func (i *fdDirInode) Lookup(ctx context.Context, name string) (*kernfs.Dentry, error) {\nfdInt, err := strconv.ParseInt(name, 10, 32)\nif err != nil {\nreturn nil, syserror.ENOENT\n@@ -145,8 +145,7 @@ func (i *fdDirInode) Lookup(ctx context.Context, name string) (*vfs.Dentry, erro\nif !taskFDExists(ctx, i.task, fd) {\nreturn nil, syserror.ENOENT\n}\n- taskDentry := i.fs.newFDSymlink(i.task, fd, i.fs.NextIno())\n- return taskDentry.VFSDentry(), nil\n+ return i.fs.newFDSymlink(i.task, fd, i.fs.NextIno()), nil\n}\n// Open implements kernfs.Inode.Open.\n@@ -270,7 +269,7 @@ func (fs *filesystem) newFDInfoDirInode(task *kernel.Task) *kernfs.Dentry {\n}\n// Lookup implements kernfs.inodeDynamicLookup.Lookup.\n-func (i *fdInfoDirInode) Lookup(ctx context.Context, name string) (*vfs.Dentry, error) {\n+func (i *fdInfoDirInode) Lookup(ctx context.Context, name string) (*kernfs.Dentry, error) {\nfdInt, err := strconv.ParseInt(name, 10, 32)\nif err != nil {\nreturn nil, syserror.ENOENT\n@@ -283,8 +282,7 @@ func (i *fdInfoDirInode) Lookup(ctx context.Context, name string) (*vfs.Dentry,\ntask: i.task,\nfd: fd,\n}\n- dentry := i.fs.newTaskOwnedFile(i.task, i.fs.NextIno(), 0444, data)\n- return dentry.VFSDentry(), nil\n+ return i.fs.newTaskOwnedFile(i.task, i.fs.NextIno(), 0444, data), nil\n}\n// Open implements kernfs.Inode.Open.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks.go", "new_path": "pkg/sentry/fsimpl/proc/tasks.go", "diff": "@@ -52,8 +52,8 @@ type tasksInode struct {\n// '/proc/self' and '/proc/thread-self' have custom directory offsets in\n// Linux. So handle them outside of OrderedChildren.\n- selfSymlink *vfs.Dentry\n- threadSelfSymlink *vfs.Dentry\n+ selfSymlink *kernfs.Dentry\n+ threadSelfSymlink *kernfs.Dentry\n// cgroupControllers is a map of controller name to directory in the\n// cgroup hierarchy. These controllers are immutable and will be listed\n@@ -81,8 +81,8 @@ func (fs *filesystem) newTasksInode(k *kernel.Kernel, pidns *kernel.PIDNamespace\ninode := &tasksInode{\npidns: pidns,\nfs: fs,\n- selfSymlink: fs.newSelfSymlink(root, fs.NextIno(), pidns).VFSDentry(),\n- threadSelfSymlink: fs.newThreadSelfSymlink(root, fs.NextIno(), pidns).VFSDentry(),\n+ selfSymlink: fs.newSelfSymlink(root, fs.NextIno(), pidns),\n+ threadSelfSymlink: fs.newThreadSelfSymlink(root, fs.NextIno(), pidns),\ncgroupControllers: cgroupControllers,\n}\ninode.InodeAttrs.Init(root, linux.UNNAMED_MAJOR, fs.devMinor, fs.NextIno(), linux.ModeDirectory|0555)\n@@ -99,7 +99,7 @@ func (fs *filesystem) newTasksInode(k *kernel.Kernel, pidns *kernel.PIDNamespace\n}\n// Lookup implements kernfs.inodeDynamicLookup.Lookup.\n-func (i *tasksInode) Lookup(ctx context.Context, name string) (*vfs.Dentry, error) {\n+func (i *tasksInode) Lookup(ctx context.Context, name string) (*kernfs.Dentry, error) {\n// Try to lookup a corresponding task.\ntid, err := strconv.ParseUint(name, 10, 64)\nif err != nil {\n@@ -118,8 +118,7 @@ func (i *tasksInode) Lookup(ctx context.Context, name string) (*vfs.Dentry, erro\nreturn nil, syserror.ENOENT\n}\n- taskDentry := i.fs.newTaskInode(task, i.pidns, true, i.cgroupControllers)\n- return taskDentry.VFSDentry(), nil\n+ return i.fs.newTaskInode(task, i.pidns, true, i.cgroupControllers), nil\n}\n// IterDirents implements kernfs.inodeDynamicLookup.IterDirents.\n" } ]
Go
Apache License 2.0
google/gvisor
Use kernfs.Dentry for kernfs.Lookup. Updates #1193. PiperOrigin-RevId: 332939026
259,975
21.09.2020 15:04:13
25,200
06dbd5b7bcd8ff16d73c38bdeac4677698385a65
Fix socket_ipv4_udp_unbound_test_native in opensource. Calls to recv sometimes fail with EAGAIN, so call select beforehand.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -2413,6 +2413,7 @@ cc_library(\n\":socket_test_util\",\n\"@com_google_absl//absl/memory\",\ngtest,\n+ \"//test/util:posix_error\",\n\"//test/util:test_util\",\n],\nalwayslink = 1,\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_ipv4_udp_unbound.cc", "new_path": "test/syscalls/linux/socket_ipv4_udp_unbound.cc", "diff": "#include \"absl/memory/memory.h\"\n#include \"test/syscalls/linux/ip_socket_test_util.h\"\n#include \"test/syscalls/linux/socket_test_util.h\"\n+#include \"test/util/posix_error.h\"\n#include \"test/util/test_util.h\"\nnamespace gvisor {\n@@ -73,9 +74,9 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackNoGroup) {\n// Check that we did not receive the multicast packet.\nchar recv_buf[sizeof(send_buf)] = {};\n- EXPECT_THAT(RetryEINTR(recv)(socket2->get(), recv_buf, sizeof(recv_buf),\n- MSG_DONTWAIT),\n- SyscallFailsWithErrno(EAGAIN));\n+ EXPECT_THAT(\n+ RecvMsgTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ PosixErrorIs(EAGAIN, ::testing::_));\n}\n// Check that not setting a default send interface prevents multicast packets\n@@ -207,8 +208,9 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackAddr) {\n// Check that we received the multicast packet.\nchar recv_buf[sizeof(send_buf)] = {};\n- ASSERT_THAT(RetryEINTR(recv)(socket2->get(), recv_buf, sizeof(recv_buf), 0),\n- SyscallSucceedsWithValue(sizeof(recv_buf)));\n+ ASSERT_THAT(\n+ RecvMsgTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(sizeof(recv_buf)));\nEXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n}\n@@ -262,8 +264,9 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackNic) {\n// Check that we received the multicast packet.\nchar recv_buf[sizeof(send_buf)] = {};\n- ASSERT_THAT(RetryEINTR(recv)(socket2->get(), recv_buf, sizeof(recv_buf), 0),\n- SyscallSucceedsWithValue(sizeof(recv_buf)));\n+ ASSERT_THAT(\n+ RecvMsgTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(sizeof(recv_buf)));\nEXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n}\n@@ -317,8 +320,9 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfAddr) {\n// Check that we received the multicast packet.\nchar recv_buf[sizeof(send_buf)] = {};\n- ASSERT_THAT(RetryEINTR(recv)(socket2->get(), recv_buf, sizeof(recv_buf), 0),\n- SyscallSucceedsWithValue(sizeof(recv_buf)));\n+ ASSERT_THAT(\n+ RecvMsgTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(sizeof(recv_buf)));\nEXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n}\n@@ -372,8 +376,9 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfNic) {\n// Check that we received the multicast packet.\nchar recv_buf[sizeof(send_buf)] = {};\n- ASSERT_THAT(RetryEINTR(recv)(socket2->get(), recv_buf, sizeof(recv_buf), 0),\n- SyscallSucceedsWithValue(sizeof(recv_buf)));\n+ ASSERT_THAT(\n+ RecvMsgTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(sizeof(recv_buf)));\nEXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n}\n@@ -431,8 +436,9 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfAddrConnect) {\n// Check that we received the multicast packet.\nchar recv_buf[sizeof(send_buf)] = {};\n- ASSERT_THAT(RetryEINTR(recv)(socket2->get(), recv_buf, sizeof(recv_buf), 0),\n- SyscallSucceedsWithValue(sizeof(recv_buf)));\n+ ASSERT_THAT(\n+ RecvMsgTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(sizeof(recv_buf)));\nEXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n}\n@@ -490,8 +496,9 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfNicConnect) {\n// Check that we received the multicast packet.\nchar recv_buf[sizeof(send_buf)] = {};\n- ASSERT_THAT(RetryEINTR(recv)(socket2->get(), recv_buf, sizeof(recv_buf), 0),\n- SyscallSucceedsWithValue(sizeof(recv_buf)));\n+ ASSERT_THAT(\n+ RecvMsgTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(sizeof(recv_buf)));\nEXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n}\n@@ -545,8 +552,9 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfAddrSelf) {\n// Check that we received the multicast packet.\nchar recv_buf[sizeof(send_buf)] = {};\n- ASSERT_THAT(RetryEINTR(recv)(socket1->get(), recv_buf, sizeof(recv_buf), 0),\n- SyscallSucceedsWithValue(sizeof(recv_buf)));\n+ ASSERT_THAT(\n+ RecvMsgTimeout(socket1->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(sizeof(recv_buf)));\nEXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n}\n@@ -600,8 +608,9 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfNicSelf) {\n// Check that we received the multicast packet.\nchar recv_buf[sizeof(send_buf)] = {};\n- ASSERT_THAT(RetryEINTR(recv)(socket1->get(), recv_buf, sizeof(recv_buf), 0),\n- SyscallSucceedsWithValue(sizeof(recv_buf)));\n+ ASSERT_THAT(\n+ RecvMsgTimeout(socket1->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(sizeof(recv_buf)));\nEXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n}\n@@ -659,9 +668,9 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfAddrSelfConnect) {\n// Check that we did not receive the multicast packet.\nchar recv_buf[sizeof(send_buf)] = {};\n- EXPECT_THAT(RetryEINTR(recv)(socket1->get(), recv_buf, sizeof(recv_buf),\n- MSG_DONTWAIT),\n- SyscallFailsWithErrno(EAGAIN));\n+ EXPECT_THAT(\n+ RecvMsgTimeout(socket1->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ PosixErrorIs(EAGAIN, ::testing::_));\n}\n// Check that multicast works when the default send interface is configured by\n@@ -717,9 +726,9 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfNicSelfConnect) {\n// Check that we did not receive the multicast packet.\nchar recv_buf[sizeof(send_buf)] = {};\n- EXPECT_THAT(RetryEINTR(recv)(socket1->get(), recv_buf, sizeof(recv_buf),\n- MSG_DONTWAIT),\n- SyscallFailsWithErrno(EAGAIN));\n+ EXPECT_THAT(\n+ RecvMsgTimeout(socket1->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ PosixErrorIs(EAGAIN, ::testing::_));\n}\n// Check that multicast works when the default send interface is configured by\n@@ -775,8 +784,9 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfAddrSelfNoLoop) {\n// Check that we received the multicast packet.\nchar recv_buf[sizeof(send_buf)] = {};\n- ASSERT_THAT(RetryEINTR(recv)(socket1->get(), recv_buf, sizeof(recv_buf), 0),\n- SyscallSucceedsWithValue(sizeof(recv_buf)));\n+ ASSERT_THAT(\n+ RecvMsgTimeout(socket1->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(sizeof(recv_buf)));\nEXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n}\n@@ -834,8 +844,9 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfNicSelfNoLoop) {\n// Check that we received the multicast packet.\nchar recv_buf[sizeof(send_buf)] = {};\n- ASSERT_THAT(RetryEINTR(recv)(socket1->get(), recv_buf, sizeof(recv_buf), 0),\n- SyscallSucceedsWithValue(sizeof(recv_buf)));\n+ ASSERT_THAT(\n+ RecvMsgTimeout(socket1->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(sizeof(recv_buf)));\nEXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n}\n@@ -907,9 +918,9 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastDropAddr) {\n// Check that we did not receive the multicast packet.\nchar recv_buf[sizeof(send_buf)] = {};\n- EXPECT_THAT(RetryEINTR(recv)(socket2->get(), recv_buf, sizeof(recv_buf),\n- MSG_DONTWAIT),\n- SyscallFailsWithErrno(EAGAIN));\n+ EXPECT_THAT(\n+ RecvMsgTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ PosixErrorIs(EAGAIN, ::testing::_));\n}\n// Check that dropping a group membership prevents multicast packets from being\n@@ -965,9 +976,9 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastDropNic) {\n// Check that we did not receive the multicast packet.\nchar recv_buf[sizeof(send_buf)] = {};\n- EXPECT_THAT(RetryEINTR(recv)(socket2->get(), recv_buf, sizeof(recv_buf),\n- MSG_DONTWAIT),\n- SyscallFailsWithErrno(EAGAIN));\n+ EXPECT_THAT(\n+ RecvMsgTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ PosixErrorIs(EAGAIN, ::testing::_));\n}\nTEST_P(IPv4UDPUnboundSocketTest, IpMulticastIfZero) {\n@@ -1319,9 +1330,9 @@ TEST_P(IPv4UDPUnboundSocketTest, TestMcastReceptionOnTwoSockets) {\n// Check that we received the multicast packet on both sockets.\nfor (auto& sockets : socket_pairs) {\nchar recv_buf[sizeof(send_buf)] = {};\n- ASSERT_THAT(\n- RetryEINTR(recv)(sockets->second_fd(), recv_buf, sizeof(recv_buf), 0),\n- SyscallSucceedsWithValue(sizeof(recv_buf)));\n+ ASSERT_THAT(RecvMsgTimeout(sockets->second_fd(), recv_buf,\n+ sizeof(recv_buf), 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(sizeof(recv_buf)));\nEXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n}\n}\n@@ -1398,9 +1409,9 @@ TEST_P(IPv4UDPUnboundSocketTest, TestMcastReceptionWhenDroppingMemberships) {\n// Check that we received the multicast packet on both sockets.\nfor (auto& sockets : socket_pairs) {\nchar recv_buf[sizeof(send_buf)] = {};\n- ASSERT_THAT(\n- RetryEINTR(recv)(sockets->second_fd(), recv_buf, sizeof(recv_buf), 0),\n- SyscallSucceedsWithValue(sizeof(recv_buf)));\n+ ASSERT_THAT(RecvMsgTimeout(sockets->second_fd(), recv_buf,\n+ sizeof(recv_buf), 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(sizeof(recv_buf)));\nEXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n}\n}\n@@ -1421,9 +1432,9 @@ TEST_P(IPv4UDPUnboundSocketTest, TestMcastReceptionWhenDroppingMemberships) {\nchar recv_buf[sizeof(send_buf)] = {};\nfor (auto& sockets : socket_pairs) {\n- ASSERT_THAT(RetryEINTR(recv)(sockets->second_fd(), recv_buf,\n- sizeof(recv_buf), MSG_DONTWAIT),\n- SyscallFailsWithErrno(EAGAIN));\n+ ASSERT_THAT(RecvMsgTimeout(sockets->second_fd(), recv_buf,\n+ sizeof(recv_buf), 1 /*timeout*/),\n+ PosixErrorIs(EAGAIN, ::testing::_));\n}\n}\n}\n@@ -1474,9 +1485,9 @@ TEST_P(IPv4UDPUnboundSocketTest, TestBindToMcastThenJoinThenReceive) {\n// Check that we received the multicast packet.\nchar recv_buf[sizeof(send_buf)] = {};\n- ASSERT_THAT(RetryEINTR(recv)(socket2->get(), recv_buf, sizeof(recv_buf),\n- MSG_DONTWAIT),\n- SyscallSucceedsWithValue(sizeof(recv_buf)));\n+ ASSERT_THAT(\n+ RecvMsgTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(sizeof(recv_buf)));\nEXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n}\n@@ -1518,9 +1529,9 @@ TEST_P(IPv4UDPUnboundSocketTest, TestBindToMcastThenNoJoinThenNoReceive) {\n// Check that we don't receive the multicast packet.\nchar recv_buf[sizeof(send_buf)] = {};\n- ASSERT_THAT(RetryEINTR(recv)(socket2->get(), recv_buf, sizeof(recv_buf),\n- MSG_DONTWAIT),\n- SyscallFailsWithErrno(EAGAIN));\n+ ASSERT_THAT(\n+ RecvMsgTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ PosixErrorIs(EAGAIN, ::testing::_));\n}\n// Check that a socket can bind to a multicast address and still send out\n@@ -1568,9 +1579,9 @@ TEST_P(IPv4UDPUnboundSocketTest, TestBindToMcastThenSend) {\n// Check that we received the packet.\nchar recv_buf[sizeof(send_buf)] = {};\n- ASSERT_THAT(RetryEINTR(recv)(socket2->get(), recv_buf, sizeof(recv_buf),\n- MSG_DONTWAIT),\n- SyscallSucceedsWithValue(sizeof(recv_buf)));\n+ ASSERT_THAT(\n+ RecvMsgTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(sizeof(recv_buf)));\nEXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n}\n@@ -1615,9 +1626,9 @@ TEST_P(IPv4UDPUnboundSocketTest, TestBindToBcastThenReceive) {\n// Check that we received the multicast packet.\nchar recv_buf[sizeof(send_buf)] = {};\n- ASSERT_THAT(RetryEINTR(recv)(socket2->get(), recv_buf, sizeof(recv_buf),\n- MSG_DONTWAIT),\n- SyscallSucceedsWithValue(sizeof(recv_buf)));\n+ ASSERT_THAT(\n+ RecvMsgTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(sizeof(recv_buf)));\nEXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n}\n@@ -1666,9 +1677,9 @@ TEST_P(IPv4UDPUnboundSocketTest, TestBindToBcastThenSend) {\n// Check that we received the packet.\nchar recv_buf[sizeof(send_buf)] = {};\n- ASSERT_THAT(RetryEINTR(recv)(socket2->get(), recv_buf, sizeof(recv_buf),\n- MSG_DONTWAIT),\n- SyscallSucceedsWithValue(sizeof(recv_buf)));\n+ ASSERT_THAT(\n+ RecvMsgTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(sizeof(recv_buf)));\nEXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n}\n@@ -1726,17 +1737,17 @@ TEST_P(IPv4UDPUnboundSocketTest, ReuseAddrDistribution_NoRandomSave) {\n// of the other sockets to have received it, but we will check that later.\nchar recv_buf[sizeof(send_buf)] = {};\nEXPECT_THAT(\n- RetryEINTR(recv)(last->get(), recv_buf, sizeof(recv_buf), MSG_DONTWAIT),\n- SyscallSucceedsWithValue(sizeof(send_buf)));\n+ RecvMsgTimeout(last->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(sizeof(send_buf)));\nEXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));\n}\n// Verify that no other messages were received.\nfor (auto& socket : sockets) {\nchar recv_buf[kMessageSize] = {};\n- EXPECT_THAT(RetryEINTR(recv)(socket->get(), recv_buf, sizeof(recv_buf),\n- MSG_DONTWAIT),\n- SyscallFailsWithErrno(EAGAIN));\n+ EXPECT_THAT(RecvMsgTimeout(socket->get(), recv_buf, sizeof(recv_buf),\n+ 1 /*timeout*/),\n+ PosixErrorIs(EAGAIN, ::testing::_));\n}\n}\n@@ -2113,12 +2124,12 @@ TEST_P(IPv4UDPUnboundSocketTest, ReuseAddrReusePortDistribution) {\n// balancing (REUSEPORT) instead of the most recently bound socket\n// (REUSEADDR).\nchar recv_buf[kMessageSize] = {};\n- EXPECT_THAT(RetryEINTR(recv)(receiver1->get(), recv_buf, sizeof(recv_buf),\n- MSG_DONTWAIT),\n- SyscallSucceedsWithValue(kMessageSize));\n- EXPECT_THAT(RetryEINTR(recv)(receiver2->get(), recv_buf, sizeof(recv_buf),\n- MSG_DONTWAIT),\n- SyscallSucceedsWithValue(kMessageSize));\n+ EXPECT_THAT(RecvMsgTimeout(receiver1->get(), recv_buf, sizeof(recv_buf),\n+ 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(kMessageSize));\n+ EXPECT_THAT(RecvMsgTimeout(receiver2->get(), recv_buf, sizeof(recv_buf),\n+ 1 /*timeout*/),\n+ IsPosixErrorOkAndHolds(kMessageSize));\n}\n// Test that socket will receive packet info control message.\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_test_util.cc", "new_path": "test/syscalls/linux/socket_test_util.cc", "diff": "@@ -762,7 +762,8 @@ PosixErrorOr<int> RecvMsgTimeout(int sock, char buf[], int buf_size,\nint ret;\nRETURN_ERROR_IF_SYSCALL_FAIL(ret = select(1, &rfd, NULL, NULL, &to));\n- RETURN_ERROR_IF_SYSCALL_FAIL(ret = recv(sock, buf, buf_size, MSG_DONTWAIT));\n+ RETURN_ERROR_IF_SYSCALL_FAIL(\n+ ret = RetryEINTR(recv)(sock, buf, buf_size, MSG_DONTWAIT));\nreturn ret;\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix socket_ipv4_udp_unbound_test_native in opensource. Calls to recv sometimes fail with EAGAIN, so call select beforehand. PiperOrigin-RevId: 332943156
260,004
21.09.2020 16:32:41
25,200
059d90b9f1c52e6aed259ba7ac4847de297273c6
Receive ACK when deleting address in syscall tests
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_netlink_route_util.cc", "new_path": "test/syscalls/linux/socket_netlink_route_util.cc", "diff": "@@ -42,7 +42,7 @@ PosixError PopulateNlmsghdr(LinkAddrModification modification,\nreturn NoError();\ncase LinkAddrModification::kDelete:\nhdr->nlmsg_type = RTM_DELADDR;\n- hdr->nlmsg_flags = NLM_F_REQUEST;\n+ hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;\nreturn NoError();\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Receive ACK when deleting address in syscall tests PiperOrigin-RevId: 332961666
259,860
21.09.2020 23:42:47
25,200
742e58b873dbb8d3c14b2e40f212df90ec837671
Allow partial writes for gofer.specialFileFD. Originally, we avoided partial writes in case it caused us to write a partial packet to a socket-backed specialFileFD. However, this check causes splicing from a pipe to specialFileFD to fail if we hit EOF on the pipe.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/special_file.go", "new_path": "pkg/sentry/fsimpl/gofer/special_file.go", "diff": "@@ -246,11 +246,12 @@ func (fd *specialFileFD) pwrite(ctx context.Context, src usermem.IOSequence, off\nd.touchCMtime()\n}\nbuf := make([]byte, src.NumBytes())\n- // Don't do partial writes if we get a partial read from src.\n- if _, err := src.CopyIn(ctx, buf); err != nil {\n- return 0, offset, err\n+ copied, copyErr := src.CopyIn(ctx, buf)\n+ if copied == 0 && copyErr != nil {\n+ // Only return the error if we didn't get any data.\n+ return 0, offset, copyErr\n}\n- n, err := fd.handle.writeFromBlocksAt(ctx, safemem.BlockSeqOf(safemem.BlockFromSafeSlice(buf)), uint64(offset))\n+ n, err := fd.handle.writeFromBlocksAt(ctx, safemem.BlockSeqOf(safemem.BlockFromSafeSlice(buf[:copied])), uint64(offset))\nif err == syserror.EAGAIN {\nerr = syserror.ErrWouldBlock\n}\n@@ -267,8 +268,11 @@ func (fd *specialFileFD) pwrite(ctx context.Context, src usermem.IOSequence, off\natomic.StoreUint64(&d.size, uint64(offset))\n}\n}\n+ if err != nil {\nreturn int64(n), offset, err\n}\n+ return int64(n), offset, copyErr\n+}\n// Write implements vfs.FileDescriptionImpl.Write.\nfunc (fd *specialFileFD) Write(ctx context.Context, src usermem.IOSequence, opts vfs.WriteOptions) (int64, error) {\n" } ]
Go
Apache License 2.0
google/gvisor
Allow partial writes for gofer.specialFileFD. Originally, we avoided partial writes in case it caused us to write a partial packet to a socket-backed specialFileFD. However, this check causes splicing from a pipe to specialFileFD to fail if we hit EOF on the pipe. PiperOrigin-RevId: 333016216
260,021
22.09.2020 15:52:41
-28,800
a38f1d145797b307afc34985533f3b9208eacc7d
arm64: set SCTLR_UCI bit in SCTLR_EL1 some application such as openjdk will excute DC CVAU at el0, if SCTLR_UCI is not set, it will trap to EL1 which will cause panic.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ring0/entry_arm64.s", "new_path": "pkg/sentry/platform/ring0/entry_arm64.s", "diff": "#define SCTLR_C 1 << 2\n#define SCTLR_I 1 << 12\n#define SCTLR_UCT 1 << 15\n+#define SCTLR_UCI 1 << 26\n-#define SCTLR_EL1_DEFAULT (SCTLR_M | SCTLR_C | SCTLR_I | SCTLR_UCT)\n+#define SCTLR_EL1_DEFAULT (SCTLR_M | SCTLR_C | SCTLR_I | SCTLR_UCT | SCTLR_UCI)\n// cntkctl_el1: counter-timer kernel control register el1.\n#define CNTKCTL_EL0PCTEN 1 << 0\n" } ]
Go
Apache License 2.0
google/gvisor
arm64: set SCTLR_UCI bit in SCTLR_EL1 some application such as openjdk will excute DC CVAU at el0, if SCTLR_UCI is not set, it will trap to EL1 which will cause panic. Signed-off-by: Min Le <[email protected]>
259,881
22.09.2020 08:38:53
25,200
f134f873fc75f941405de7d0e046852a38795bec
Force clone parent_tidptr and child_tidptr to zero Neither CLONE_PARENT_SETTID nor CLONE_CHILD_SETTID are used, so these arguments will always be NULL.
[ { "change_type": "MODIFY", "old_path": "runsc/boot/filter/config.go", "new_path": "runsc/boot/filter/config.go", "diff": "@@ -27,17 +27,6 @@ import (\n// allowedSyscalls is the set of syscalls executed by the Sentry to the host OS.\nvar allowedSyscalls = seccomp.SyscallRules{\nsyscall.SYS_CLOCK_GETTIME: {},\n- syscall.SYS_CLONE: []seccomp.Rule{\n- {\n- seccomp.EqualTo(\n- syscall.CLONE_VM |\n- syscall.CLONE_FS |\n- syscall.CLONE_FILES |\n- syscall.CLONE_SIGHAND |\n- syscall.CLONE_SYSVSEM |\n- syscall.CLONE_THREAD),\n- },\n- },\nsyscall.SYS_CLOSE: {},\nsyscall.SYS_DUP: {},\nsyscall.SYS_DUP3: []seccomp.Rule{\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/filter/config_amd64.go", "new_path": "runsc/boot/filter/config_amd64.go", "diff": "@@ -24,7 +24,25 @@ import (\n)\nfunc init() {\n- allowedSyscalls[syscall.SYS_ARCH_PRCTL] = append(allowedSyscalls[syscall.SYS_ARCH_PRCTL],\n- seccomp.Rule{seccomp.EqualTo(linux.ARCH_SET_FS)},\n- )\n+ allowedSyscalls[syscall.SYS_ARCH_PRCTL] = []seccomp.Rule{\n+ {seccomp.EqualTo(linux.ARCH_SET_FS)},\n+ }\n+\n+ allowedSyscalls[syscall.SYS_CLONE] = []seccomp.Rule{\n+ // parent_tidptr and child_tidptr are always 0 because neither\n+ // CLONE_PARENT_SETTID nor CLONE_CHILD_SETTID are used.\n+ {\n+ seccomp.EqualTo(\n+ syscall.CLONE_VM |\n+ syscall.CLONE_FS |\n+ syscall.CLONE_FILES |\n+ syscall.CLONE_SIGHAND |\n+ syscall.CLONE_SYSVSEM |\n+ syscall.CLONE_THREAD),\n+ seccomp.MatchAny{}, // newsp\n+ seccomp.EqualTo(0), // parent_tidptr\n+ seccomp.EqualTo(0), // child_tidptr\n+ seccomp.MatchAny{}, // tls\n+ },\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/filter/config_arm64.go", "new_path": "runsc/boot/filter/config_arm64.go", "diff": "package filter\n-// Reserve for future customization.\n+import (\n+ \"syscall\"\n+\n+ \"gvisor.dev/gvisor/pkg/seccomp\"\n+)\n+\nfunc init() {\n+ allowedSyscalls[syscall.SYS_CLONE] = []seccomp.Rule{\n+ // parent_tidptr and child_tidptr are always 0 because neither\n+ // CLONE_PARENT_SETTID nor CLONE_CHILD_SETTID are used.\n+ {\n+ seccomp.EqualTo(\n+ syscall.CLONE_VM |\n+ syscall.CLONE_FS |\n+ syscall.CLONE_FILES |\n+ syscall.CLONE_SIGHAND |\n+ syscall.CLONE_SYSVSEM |\n+ syscall.CLONE_THREAD),\n+ seccomp.MatchAny{}, // newsp\n+ // These arguments are left uninitialized by the Go\n+ // runtime, so they may be anything (and are unused by\n+ // the host).\n+ seccomp.MatchAny{}, // parent_tidptr\n+ seccomp.MatchAny{}, // tls\n+ seccomp.MatchAny{}, // child_tidptr\n+ },\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/fsgofer/filter/config.go", "new_path": "runsc/fsgofer/filter/config.go", "diff": "@@ -27,17 +27,6 @@ import (\nvar allowedSyscalls = seccomp.SyscallRules{\nsyscall.SYS_ACCEPT: {},\nsyscall.SYS_CLOCK_GETTIME: {},\n- syscall.SYS_CLONE: []seccomp.Rule{\n- {\n- seccomp.EqualTo(\n- syscall.CLONE_VM |\n- syscall.CLONE_FS |\n- syscall.CLONE_FILES |\n- syscall.CLONE_SIGHAND |\n- syscall.CLONE_SYSVSEM |\n- syscall.CLONE_THREAD),\n- },\n- },\nsyscall.SYS_CLOSE: {},\nsyscall.SYS_DUP: {},\nsyscall.SYS_EPOLL_CTL: {},\n" }, { "change_type": "MODIFY", "old_path": "runsc/fsgofer/filter/config_amd64.go", "new_path": "runsc/fsgofer/filter/config_amd64.go", "diff": "@@ -28,5 +28,23 @@ func init() {\n{seccomp.EqualTo(linux.ARCH_SET_FS)},\n}\n+ allowedSyscalls[syscall.SYS_CLONE] = []seccomp.Rule{\n+ // parent_tidptr and child_tidptr are always 0 because neither\n+ // CLONE_PARENT_SETTID nor CLONE_CHILD_SETTID are used.\n+ {\n+ seccomp.EqualTo(\n+ syscall.CLONE_VM |\n+ syscall.CLONE_FS |\n+ syscall.CLONE_FILES |\n+ syscall.CLONE_SIGHAND |\n+ syscall.CLONE_SYSVSEM |\n+ syscall.CLONE_THREAD),\n+ seccomp.MatchAny{}, // newsp\n+ seccomp.EqualTo(0), // parent_tidptr\n+ seccomp.EqualTo(0), // child_tidptr\n+ seccomp.MatchAny{}, // tls\n+ },\n+ }\n+\nallowedSyscalls[syscall.SYS_NEWFSTATAT] = []seccomp.Rule{}\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/fsgofer/filter/config_arm64.go", "new_path": "runsc/fsgofer/filter/config_arm64.go", "diff": "@@ -23,5 +23,26 @@ import (\n)\nfunc init() {\n+ allowedSyscalls[syscall.SYS_CLONE] = []seccomp.Rule{\n+ // parent_tidptr and child_tidptr are always 0 because neither\n+ // CLONE_PARENT_SETTID nor CLONE_CHILD_SETTID are used.\n+ {\n+ seccomp.EqualTo(\n+ syscall.CLONE_VM |\n+ syscall.CLONE_FS |\n+ syscall.CLONE_FILES |\n+ syscall.CLONE_SIGHAND |\n+ syscall.CLONE_SYSVSEM |\n+ syscall.CLONE_THREAD),\n+ seccomp.MatchAny{}, // newsp\n+ // These arguments are left uninitialized by the Go\n+ // runtime, so they may be anything (and are unused by\n+ // the host).\n+ seccomp.MatchAny{}, // parent_tidptr\n+ seccomp.MatchAny{}, // tls\n+ seccomp.MatchAny{}, // child_tidptr\n+ },\n+ }\n+\nallowedSyscalls[syscall.SYS_FSTATAT] = []seccomp.Rule{}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Force clone parent_tidptr and child_tidptr to zero Neither CLONE_PARENT_SETTID nor CLONE_CHILD_SETTID are used, so these arguments will always be NULL. PiperOrigin-RevId: 333085326
259,881
22.09.2020 09:56:06
25,200
13a9a622e13ccdda76ed02d3de99b565212f6b2f
Allow CLONE_SETTLS for Go 1.16 switches the Go runtime (on amd64) from using arch_prctl(ARCH_SET_FS) to CLONE_SETTLS to set the TLS.
[ { "change_type": "MODIFY", "old_path": "runsc/boot/filter/config_amd64.go", "new_path": "runsc/boot/filter/config_amd64.go", "diff": "@@ -25,6 +25,7 @@ import (\nfunc init() {\nallowedSyscalls[syscall.SYS_ARCH_PRCTL] = []seccomp.Rule{\n+ // TODO(b/168828518): No longer used in Go 1.16+.\n{seccomp.EqualTo(linux.ARCH_SET_FS)},\n}\n@@ -32,6 +33,21 @@ func init() {\n// parent_tidptr and child_tidptr are always 0 because neither\n// CLONE_PARENT_SETTID nor CLONE_CHILD_SETTID are used.\n{\n+ seccomp.EqualTo(\n+ syscall.CLONE_VM |\n+ syscall.CLONE_FS |\n+ syscall.CLONE_FILES |\n+ syscall.CLONE_SETTLS |\n+ syscall.CLONE_SIGHAND |\n+ syscall.CLONE_SYSVSEM |\n+ syscall.CLONE_THREAD),\n+ seccomp.MatchAny{}, // newsp\n+ seccomp.EqualTo(0), // parent_tidptr\n+ seccomp.EqualTo(0), // child_tidptr\n+ seccomp.MatchAny{}, // tls\n+ },\n+ {\n+ // TODO(b/168828518): No longer used in Go 1.16+ (on amd64).\nseccomp.EqualTo(\nsyscall.CLONE_VM |\nsyscall.CLONE_FS |\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/filter/config_arm64.go", "new_path": "runsc/boot/filter/config_arm64.go", "diff": "@@ -24,8 +24,6 @@ import (\nfunc init() {\nallowedSyscalls[syscall.SYS_CLONE] = []seccomp.Rule{\n- // parent_tidptr and child_tidptr are always 0 because neither\n- // CLONE_PARENT_SETTID nor CLONE_CHILD_SETTID are used.\n{\nseccomp.EqualTo(\nsyscall.CLONE_VM |\n" }, { "change_type": "MODIFY", "old_path": "runsc/fsgofer/filter/config_amd64.go", "new_path": "runsc/fsgofer/filter/config_amd64.go", "diff": "@@ -25,6 +25,7 @@ import (\nfunc init() {\nallowedSyscalls[syscall.SYS_ARCH_PRCTL] = []seccomp.Rule{\n+ // TODO(b/168828518): No longer used in Go 1.16+.\n{seccomp.EqualTo(linux.ARCH_SET_FS)},\n}\n@@ -32,6 +33,21 @@ func init() {\n// parent_tidptr and child_tidptr are always 0 because neither\n// CLONE_PARENT_SETTID nor CLONE_CHILD_SETTID are used.\n{\n+ seccomp.EqualTo(\n+ syscall.CLONE_VM |\n+ syscall.CLONE_FS |\n+ syscall.CLONE_FILES |\n+ syscall.CLONE_SETTLS |\n+ syscall.CLONE_SIGHAND |\n+ syscall.CLONE_SYSVSEM |\n+ syscall.CLONE_THREAD),\n+ seccomp.MatchAny{}, // newsp\n+ seccomp.EqualTo(0), // parent_tidptr\n+ seccomp.EqualTo(0), // child_tidptr\n+ seccomp.MatchAny{}, // tls\n+ },\n+ {\n+ // TODO(b/168828518): No longer used in Go 1.16+ (on amd64).\nseccomp.EqualTo(\nsyscall.CLONE_VM |\nsyscall.CLONE_FS |\n" } ]
Go
Apache License 2.0
google/gvisor
Allow CLONE_SETTLS for Go 1.16 https://go.googlesource.com/go/+/0941fc3 switches the Go runtime (on amd64) from using arch_prctl(ARCH_SET_FS) to CLONE_SETTLS to set the TLS. PiperOrigin-RevId: 333100550
259,964
22.09.2020 12:43:28
25,200
6e5ea605f4ca9fb8c29adc9510edc980f844ddfc
Move stack.fakeClock into a separate package
[ { "change_type": "ADD", "old_path": null, "new_path": "pkg/tcpip/faketime/BUILD", "diff": "+load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_library(\n+ name = \"faketime\",\n+ srcs = [\"faketime.go\"],\n+ visibility = [\"//visibility:public\"],\n+ deps = [\n+ \"//pkg/tcpip\",\n+ \"@com_github_dpjacques_clockwork//:go_default_library\",\n+ ],\n+)\n+\n+go_test(\n+ name = \"faketime_test\",\n+ size = \"small\",\n+ srcs = [\n+ \"faketime_test.go\",\n+ ],\n+ deps = [\n+ \"//pkg/tcpip/faketime\",\n+ ],\n+)\n" }, { "change_type": "RENAME", "old_path": "pkg/tcpip/stack/fake_time_test.go", "new_path": "pkg/tcpip/faketime/faketime.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-package stack\n+// Package faketime provides a fake clock that implements tcpip.Clock interface.\n+package faketime\nimport (\n\"container/heap\"\n@@ -23,7 +24,9 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip\"\n)\n-type fakeClock struct {\n+// ManualClock implements tcpip.Clock and only advances manually with Advance\n+// method.\n+type ManualClock struct {\nclock clockwork.FakeClock\n// mu protects the fields below.\n@@ -39,34 +42,35 @@ type fakeClock struct {\nwaitGroups map[time.Time]*sync.WaitGroup\n}\n-func newFakeClock() *fakeClock {\n- return &fakeClock{\n+// NewManualClock creates a new ManualClock instance.\n+func NewManualClock() *ManualClock {\n+ return &ManualClock{\nclock: clockwork.NewFakeClock(),\ntimes: &timeHeap{},\nwaitGroups: make(map[time.Time]*sync.WaitGroup),\n}\n}\n-var _ tcpip.Clock = (*fakeClock)(nil)\n+var _ tcpip.Clock = (*ManualClock)(nil)\n// NowNanoseconds implements tcpip.Clock.NowNanoseconds.\n-func (fc *fakeClock) NowNanoseconds() int64 {\n- return fc.clock.Now().UnixNano()\n+func (mc *ManualClock) NowNanoseconds() int64 {\n+ return mc.clock.Now().UnixNano()\n}\n// NowMonotonic implements tcpip.Clock.NowMonotonic.\n-func (fc *fakeClock) NowMonotonic() int64 {\n- return fc.NowNanoseconds()\n+func (mc *ManualClock) NowMonotonic() int64 {\n+ return mc.NowNanoseconds()\n}\n// AfterFunc implements tcpip.Clock.AfterFunc.\n-func (fc *fakeClock) AfterFunc(d time.Duration, f func()) tcpip.Timer {\n- until := fc.clock.Now().Add(d)\n- wg := fc.addWait(until)\n- return &fakeTimer{\n- clock: fc,\n+func (mc *ManualClock) AfterFunc(d time.Duration, f func()) tcpip.Timer {\n+ until := mc.clock.Now().Add(d)\n+ wg := mc.addWait(until)\n+ return &manualTimer{\n+ clock: mc,\nuntil: until,\n- timer: fc.clock.AfterFunc(d, func() {\n+ timer: mc.clock.AfterFunc(d, func() {\ndefer wg.Done()\nf()\n}),\n@@ -75,110 +79,113 @@ func (fc *fakeClock) AfterFunc(d time.Duration, f func()) tcpip.Timer {\n// addWait adds an additional wait to the WaitGroup for parallel execution of\n// all work scheduled for t. Returns a reference to the WaitGroup modified.\n-func (fc *fakeClock) addWait(t time.Time) *sync.WaitGroup {\n- fc.mu.RLock()\n- wg, ok := fc.waitGroups[t]\n- fc.mu.RUnlock()\n+func (mc *ManualClock) addWait(t time.Time) *sync.WaitGroup {\n+ mc.mu.RLock()\n+ wg, ok := mc.waitGroups[t]\n+ mc.mu.RUnlock()\nif ok {\nwg.Add(1)\nreturn wg\n}\n- fc.mu.Lock()\n- heap.Push(fc.times, t)\n- fc.mu.Unlock()\n+ mc.mu.Lock()\n+ heap.Push(mc.times, t)\n+ mc.mu.Unlock()\nwg = &sync.WaitGroup{}\nwg.Add(1)\n- fc.mu.Lock()\n- fc.waitGroups[t] = wg\n- fc.mu.Unlock()\n+ mc.mu.Lock()\n+ mc.waitGroups[t] = wg\n+ mc.mu.Unlock()\nreturn wg\n}\n// removeWait removes a wait from the WaitGroup for parallel execution of all\n// work scheduled for t.\n-func (fc *fakeClock) removeWait(t time.Time) {\n- fc.mu.RLock()\n- defer fc.mu.RUnlock()\n+func (mc *ManualClock) removeWait(t time.Time) {\n+ mc.mu.RLock()\n+ defer mc.mu.RUnlock()\n- wg := fc.waitGroups[t]\n+ wg := mc.waitGroups[t]\nwg.Done()\n}\n-// advance executes all work that have been scheduled to execute within d from\n-// the current fake time. Blocks until all work has completed execution.\n-func (fc *fakeClock) advance(d time.Duration) {\n+// Advance executes all work that have been scheduled to execute within d from\n+// the current time. Blocks until all work has completed execution.\n+func (mc *ManualClock) Advance(d time.Duration) {\n// Block until all the work is done\n- until := fc.clock.Now().Add(d)\n+ until := mc.clock.Now().Add(d)\nfor {\n- fc.mu.Lock()\n- if fc.times.Len() == 0 {\n- fc.mu.Unlock()\n- return\n+ mc.mu.Lock()\n+ if mc.times.Len() == 0 {\n+ mc.mu.Unlock()\n+ break\n}\n- t := heap.Pop(fc.times).(time.Time)\n+ t := heap.Pop(mc.times).(time.Time)\nif t.After(until) {\n// No work to do\n- heap.Push(fc.times, t)\n- fc.mu.Unlock()\n- return\n+ heap.Push(mc.times, t)\n+ mc.mu.Unlock()\n+ break\n}\n- fc.mu.Unlock()\n+ mc.mu.Unlock()\n- diff := t.Sub(fc.clock.Now())\n- fc.clock.Advance(diff)\n+ diff := t.Sub(mc.clock.Now())\n+ mc.clock.Advance(diff)\n- fc.mu.RLock()\n- wg := fc.waitGroups[t]\n- fc.mu.RUnlock()\n+ mc.mu.RLock()\n+ wg := mc.waitGroups[t]\n+ mc.mu.RUnlock()\nwg.Wait()\n- fc.mu.Lock()\n- delete(fc.waitGroups, t)\n- fc.mu.Unlock()\n+ mc.mu.Lock()\n+ delete(mc.waitGroups, t)\n+ mc.mu.Unlock()\n+ }\n+ if now := mc.clock.Now(); until.After(now) {\n+ mc.clock.Advance(until.Sub(now))\n}\n}\n-type fakeTimer struct {\n- clock *fakeClock\n+type manualTimer struct {\n+ clock *ManualClock\ntimer clockwork.Timer\nmu sync.RWMutex\nuntil time.Time\n}\n-var _ tcpip.Timer = (*fakeTimer)(nil)\n+var _ tcpip.Timer = (*manualTimer)(nil)\n// Reset implements tcpip.Timer.Reset.\n-func (ft *fakeTimer) Reset(d time.Duration) {\n- if !ft.timer.Reset(d) {\n+func (t *manualTimer) Reset(d time.Duration) {\n+ if !t.timer.Reset(d) {\nreturn\n}\n- ft.mu.Lock()\n- defer ft.mu.Unlock()\n+ t.mu.Lock()\n+ defer t.mu.Unlock()\n- ft.clock.removeWait(ft.until)\n- ft.until = ft.clock.clock.Now().Add(d)\n- ft.clock.addWait(ft.until)\n+ t.clock.removeWait(t.until)\n+ t.until = t.clock.clock.Now().Add(d)\n+ t.clock.addWait(t.until)\n}\n// Stop implements tcpip.Timer.Stop.\n-func (ft *fakeTimer) Stop() bool {\n- if !ft.timer.Stop() {\n+func (t *manualTimer) Stop() bool {\n+ if !t.timer.Stop() {\nreturn false\n}\n- ft.mu.RLock()\n- defer ft.mu.RUnlock()\n+ t.mu.RLock()\n+ defer t.mu.RUnlock()\n- ft.clock.removeWait(ft.until)\n+ t.clock.removeWait(t.until)\nreturn true\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/tcpip/faketime/faketime_test.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package faketime_test\n+\n+import (\n+ \"testing\"\n+ \"time\"\n+\n+ \"gvisor.dev/gvisor/pkg/tcpip/faketime\"\n+)\n+\n+func TestManualClockAdvance(t *testing.T) {\n+ const timeout = time.Millisecond\n+ clock := faketime.NewManualClock()\n+ start := clock.NowMonotonic()\n+ clock.Advance(timeout)\n+ if got, want := time.Duration(clock.NowMonotonic()-start)*time.Nanosecond, timeout; got != want {\n+ t.Errorf(\"got = %d, want = %d\", got, want)\n+ }\n+}\n+\n+func TestManualClockAfterFunc(t *testing.T) {\n+ const (\n+ timeout1 = time.Millisecond // timeout for counter1\n+ timeout2 = 2 * time.Millisecond // timeout for counter2\n+ )\n+ tests := []struct {\n+ name string\n+ advance time.Duration\n+ wantCounter1 int\n+ wantCounter2 int\n+ }{\n+ {\n+ name: \"before timeout1\",\n+ advance: timeout1 - 1,\n+ wantCounter1: 0,\n+ wantCounter2: 0,\n+ },\n+ {\n+ name: \"timeout1\",\n+ advance: timeout1,\n+ wantCounter1: 1,\n+ wantCounter2: 0,\n+ },\n+ {\n+ name: \"timeout2\",\n+ advance: timeout2,\n+ wantCounter1: 1,\n+ wantCounter2: 1,\n+ },\n+ {\n+ name: \"after timeout2\",\n+ advance: timeout2 + 1,\n+ wantCounter1: 1,\n+ wantCounter2: 1,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ clock := faketime.NewManualClock()\n+ counter1 := 0\n+ counter2 := 0\n+ clock.AfterFunc(timeout1, func() {\n+ counter1++\n+ })\n+ clock.AfterFunc(timeout2, func() {\n+ counter2++\n+ })\n+ start := clock.NowMonotonic()\n+ clock.Advance(test.advance)\n+ if got, want := counter1, test.wantCounter1; got != want {\n+ t.Errorf(\"got counter1 = %d, want = %d\", got, want)\n+ }\n+ if got, want := counter2, test.wantCounter2; got != want {\n+ t.Errorf(\"got counter2 = %d, want = %d\", got, want)\n+ }\n+ if got, want := time.Duration(clock.NowMonotonic()-start)*time.Nanosecond, test.advance; got != want {\n+ t.Errorf(\"got elapsed = %d, want = %d\", got, want)\n+ }\n+ })\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/BUILD", "new_path": "pkg/tcpip/stack/BUILD", "diff": "@@ -138,7 +138,6 @@ go_test(\nname = \"stack_test\",\nsize = \"small\",\nsrcs = [\n- \"fake_time_test.go\",\n\"forwarder_test.go\",\n\"linkaddrcache_test.go\",\n\"neighbor_cache_test.go\",\n@@ -152,8 +151,8 @@ go_test(\n\"//pkg/sync\",\n\"//pkg/tcpip\",\n\"//pkg/tcpip/buffer\",\n+ \"//pkg/tcpip/faketime\",\n\"//pkg/tcpip/header\",\n- \"@com_github_dpjacques_clockwork//:go_default_library\",\n\"@com_github_google_go_cmp//cmp:go_default_library\",\n\"@com_github_google_go_cmp//cmp/cmpopts:go_default_library\",\n],\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_cache_test.go", "new_path": "pkg/tcpip/stack/neighbor_cache_test.go", "diff": "@@ -30,6 +30,7 @@ import (\n\"github.com/google/go-cmp/cmp/cmpopts\"\n\"gvisor.dev/gvisor/pkg/sleep\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/faketime\"\n)\nconst (\n@@ -239,7 +240,7 @@ type entryEvent struct {\nfunc TestNeighborCacheGetConfig(t *testing.T) {\nnudDisp := testNUDDispatcher{}\nc := DefaultNUDConfigurations()\n- clock := newFakeClock()\n+ clock := faketime.NewManualClock()\nneigh := newTestNeighborCache(&nudDisp, c, clock)\nif got, want := neigh.config(), c; got != want {\n@@ -257,7 +258,7 @@ func TestNeighborCacheGetConfig(t *testing.T) {\nfunc TestNeighborCacheSetConfig(t *testing.T) {\nnudDisp := testNUDDispatcher{}\nc := DefaultNUDConfigurations()\n- clock := newFakeClock()\n+ clock := faketime.NewManualClock()\nneigh := newTestNeighborCache(&nudDisp, c, clock)\nc.MinRandomFactor = 1\n@@ -279,7 +280,7 @@ func TestNeighborCacheSetConfig(t *testing.T) {\nfunc TestNeighborCacheEntry(t *testing.T) {\nc := DefaultNUDConfigurations()\nnudDisp := testNUDDispatcher{}\n- clock := newFakeClock()\n+ clock := faketime.NewManualClock()\nneigh := newTestNeighborCache(&nudDisp, c, clock)\nstore := newTestEntryStore()\nlinkRes := &testNeighborResolver{\n@@ -298,7 +299,7 @@ func TestNeighborCacheEntry(t *testing.T) {\nt.Errorf(\"got neigh.entry(%s, %s, _, nil) = %v, want = %s\", entry.Addr, entry.LocalAddr, err, tcpip.ErrWouldBlock)\n}\n- clock.advance(typicalLatency)\n+ clock.Advance(typicalLatency)\nwantEvents := []testEntryEventInfo{\n{\n@@ -339,7 +340,7 @@ func TestNeighborCacheRemoveEntry(t *testing.T) {\nconfig := DefaultNUDConfigurations()\nnudDisp := testNUDDispatcher{}\n- clock := newFakeClock()\n+ clock := faketime.NewManualClock()\nneigh := newTestNeighborCache(&nudDisp, config, clock)\nstore := newTestEntryStore()\nlinkRes := &testNeighborResolver{\n@@ -358,7 +359,7 @@ func TestNeighborCacheRemoveEntry(t *testing.T) {\nt.Errorf(\"got neigh.entry(%s, %s, _, nil) = %v, want = %s\", entry.Addr, entry.LocalAddr, err, tcpip.ErrWouldBlock)\n}\n- clock.advance(typicalLatency)\n+ clock.Advance(typicalLatency)\nwantEvents := []testEntryEventInfo{\n{\n@@ -409,7 +410,7 @@ func TestNeighborCacheRemoveEntry(t *testing.T) {\n}\ntype testContext struct {\n- clock *fakeClock\n+ clock *faketime.ManualClock\nneigh *neighborCache\nstore *testEntryStore\nlinkRes *testNeighborResolver\n@@ -418,7 +419,7 @@ type testContext struct {\nfunc newTestContext(c NUDConfigurations) testContext {\nnudDisp := &testNUDDispatcher{}\n- clock := newFakeClock()\n+ clock := faketime.NewManualClock()\nneigh := newTestNeighborCache(nudDisp, c, clock)\nstore := newTestEntryStore()\nlinkRes := &testNeighborResolver{\n@@ -454,7 +455,7 @@ func (c *testContext) overflowCache(opts overflowOptions) error {\nif _, _, err := c.neigh.entry(entry.Addr, entry.LocalAddr, c.linkRes, nil); err != tcpip.ErrWouldBlock {\nreturn fmt.Errorf(\"got c.neigh.entry(%s, %s, _, nil) = %v, want = %s\", entry.Addr, entry.LocalAddr, err, tcpip.ErrWouldBlock)\n}\n- c.clock.advance(c.neigh.config().RetransmitTimer)\n+ c.clock.Advance(c.neigh.config().RetransmitTimer)\nvar wantEvents []testEntryEventInfo\n@@ -567,7 +568,7 @@ func TestNeighborCacheRemoveEntryThenOverflow(t *testing.T) {\nif err != tcpip.ErrWouldBlock {\nt.Errorf(\"got c.neigh.entry(%s, %s, _, nil) = %v, want = %s\", entry.Addr, entry.LocalAddr, err, tcpip.ErrWouldBlock)\n}\n- c.clock.advance(c.neigh.config().RetransmitTimer)\n+ c.clock.Advance(c.neigh.config().RetransmitTimer)\nwantEvents := []testEntryEventInfo{\n{\nEventType: entryTestAdded,\n@@ -803,7 +804,7 @@ func TestNeighborCacheOverwriteWithStaticEntryThenOverflow(t *testing.T) {\nif err != tcpip.ErrWouldBlock {\nt.Errorf(\"got c.neigh.entry(%s, %s, _, nil) = %v, want = %s\", entry.Addr, entry.LocalAddr, err, tcpip.ErrWouldBlock)\n}\n- c.clock.advance(typicalLatency)\n+ c.clock.Advance(typicalLatency)\nwantEvents := []testEntryEventInfo{\n{\nEventType: entryTestAdded,\n@@ -876,7 +877,7 @@ func TestNeighborCacheNotifiesWaker(t *testing.T) {\nconfig := DefaultNUDConfigurations()\nnudDisp := testNUDDispatcher{}\n- clock := newFakeClock()\n+ clock := faketime.NewManualClock()\nneigh := newTestNeighborCache(&nudDisp, config, clock)\nstore := newTestEntryStore()\nlinkRes := &testNeighborResolver{\n@@ -902,7 +903,7 @@ func TestNeighborCacheNotifiesWaker(t *testing.T) {\nif doneCh == nil {\nt.Fatalf(\"expected done channel from neigh.entry(%s, %s, _, _)\", entry.Addr, entry.LocalAddr)\n}\n- clock.advance(typicalLatency)\n+ clock.Advance(typicalLatency)\nselect {\ncase <-doneCh:\n@@ -944,7 +945,7 @@ func TestNeighborCacheRemoveWaker(t *testing.T) {\nconfig := DefaultNUDConfigurations()\nnudDisp := testNUDDispatcher{}\n- clock := newFakeClock()\n+ clock := faketime.NewManualClock()\nneigh := newTestNeighborCache(&nudDisp, config, clock)\nstore := newTestEntryStore()\nlinkRes := &testNeighborResolver{\n@@ -974,7 +975,7 @@ func TestNeighborCacheRemoveWaker(t *testing.T) {\n// Remove the waker before the neighbor cache has the opportunity to send a\n// notification.\nneigh.removeWaker(entry.Addr, &w)\n- clock.advance(typicalLatency)\n+ clock.Advance(typicalLatency)\nselect {\ncase <-doneCh:\n@@ -1073,7 +1074,7 @@ func TestNeighborCacheClear(t *testing.T) {\nconfig := DefaultNUDConfigurations()\nnudDisp := testNUDDispatcher{}\n- clock := newFakeClock()\n+ clock := faketime.NewManualClock()\nneigh := newTestNeighborCache(&nudDisp, config, clock)\nstore := newTestEntryStore()\nlinkRes := &testNeighborResolver{\n@@ -1092,7 +1093,7 @@ func TestNeighborCacheClear(t *testing.T) {\nif err != tcpip.ErrWouldBlock {\nt.Errorf(\"got neigh.entry(%s, %s, _, nil) = %v, want = %s\", entry.Addr, entry.LocalAddr, err, tcpip.ErrWouldBlock)\n}\n- clock.advance(typicalLatency)\n+ clock.Advance(typicalLatency)\nwantEvents := []testEntryEventInfo{\n{\n@@ -1188,7 +1189,7 @@ func TestNeighborCacheClearThenOverflow(t *testing.T) {\nif err != tcpip.ErrWouldBlock {\nt.Errorf(\"got c.neigh.entry(%s, %s, _, nil) = %v, want = %s\", entry.Addr, entry.LocalAddr, err, tcpip.ErrWouldBlock)\n}\n- c.clock.advance(typicalLatency)\n+ c.clock.Advance(typicalLatency)\nwantEvents := []testEntryEventInfo{\n{\nEventType: entryTestAdded,\n@@ -1249,7 +1250,7 @@ func TestNeighborCacheKeepFrequentlyUsed(t *testing.T) {\nconfig.MaxRandomFactor = 1\nnudDisp := testNUDDispatcher{}\n- clock := newFakeClock()\n+ clock := faketime.NewManualClock()\nneigh := newTestNeighborCache(&nudDisp, config, clock)\nstore := newTestEntryStore()\nlinkRes := &testNeighborResolver{\n@@ -1277,7 +1278,7 @@ func TestNeighborCacheKeepFrequentlyUsed(t *testing.T) {\nif err != tcpip.ErrWouldBlock {\nt.Errorf(\"got neigh.entry(%s, %s, _, nil) = %v, want = %s\", entry.Addr, entry.LocalAddr, err, tcpip.ErrWouldBlock)\n}\n- clock.advance(typicalLatency)\n+ clock.Advance(typicalLatency)\nselect {\ncase <-doneCh:\ndefault:\n@@ -1325,7 +1326,7 @@ func TestNeighborCacheKeepFrequentlyUsed(t *testing.T) {\nif err != tcpip.ErrWouldBlock {\nt.Errorf(\"got neigh.entry(%s, %s, _, nil) = %v, want = %s\", entry.Addr, entry.LocalAddr, err, tcpip.ErrWouldBlock)\n}\n- clock.advance(typicalLatency)\n+ clock.Advance(typicalLatency)\nselect {\ncase <-doneCh:\ndefault:\n@@ -1412,7 +1413,7 @@ func TestNeighborCacheConcurrent(t *testing.T) {\nconfig := DefaultNUDConfigurations()\nnudDisp := testNUDDispatcher{}\n- clock := newFakeClock()\n+ clock := faketime.NewManualClock()\nneigh := newTestNeighborCache(&nudDisp, config, clock)\nstore := newTestEntryStore()\nlinkRes := &testNeighborResolver{\n@@ -1440,7 +1441,7 @@ func TestNeighborCacheConcurrent(t *testing.T) {\nwg.Wait()\n// Process all the requests for a single entry concurrently\n- clock.advance(typicalLatency)\n+ clock.Advance(typicalLatency)\n}\n// All goroutines add in the same order and add more values than can fit in\n@@ -1472,7 +1473,7 @@ func TestNeighborCacheReplace(t *testing.T) {\nconfig := DefaultNUDConfigurations()\nnudDisp := testNUDDispatcher{}\n- clock := newFakeClock()\n+ clock := faketime.NewManualClock()\nneigh := newTestNeighborCache(&nudDisp, config, clock)\nstore := newTestEntryStore()\nlinkRes := &testNeighborResolver{\n@@ -1491,7 +1492,7 @@ func TestNeighborCacheReplace(t *testing.T) {\nif err != tcpip.ErrWouldBlock {\nt.Fatalf(\"got neigh.entry(%s, %s, _, nil) = %v, want = %s\", entry.Addr, entry.LocalAddr, err, tcpip.ErrWouldBlock)\n}\n- clock.advance(typicalLatency)\n+ clock.Advance(typicalLatency)\nselect {\ncase <-doneCh:\ndefault:\n@@ -1541,7 +1542,7 @@ func TestNeighborCacheReplace(t *testing.T) {\nif err != tcpip.ErrWouldBlock {\nt.Fatalf(\"got neigh.entry(%s, %s, _, nil) = %v, want = %s\", entry.Addr, entry.LocalAddr, err, tcpip.ErrWouldBlock)\n}\n- clock.advance(config.DelayFirstProbeTime + typicalLatency)\n+ clock.Advance(config.DelayFirstProbeTime + typicalLatency)\nselect {\ncase <-doneCh:\ndefault:\n@@ -1552,7 +1553,7 @@ func TestNeighborCacheReplace(t *testing.T) {\n// Verify the entry's new link address\n{\ne, _, err := neigh.entry(entry.Addr, entry.LocalAddr, linkRes, nil)\n- clock.advance(typicalLatency)\n+ clock.Advance(typicalLatency)\nif err != nil {\nt.Errorf(\"unexpected error from neigh.entry(%s, %s, _, nil): %s\", entry.Addr, entry.LocalAddr, err)\n}\n@@ -1572,7 +1573,7 @@ func TestNeighborCacheResolutionFailed(t *testing.T) {\nconfig := DefaultNUDConfigurations()\nnudDisp := testNUDDispatcher{}\n- clock := newFakeClock()\n+ clock := faketime.NewManualClock()\nneigh := newTestNeighborCache(&nudDisp, config, clock)\nstore := newTestEntryStore()\n@@ -1595,7 +1596,7 @@ func TestNeighborCacheResolutionFailed(t *testing.T) {\nif _, _, err := neigh.entry(entry.Addr, entry.LocalAddr, linkRes, nil); err != tcpip.ErrWouldBlock {\nt.Fatalf(\"got neigh.entry(%s, %s, _, nil) = %v, want = %s\", entry.Addr, entry.LocalAddr, err, tcpip.ErrWouldBlock)\n}\n- clock.advance(typicalLatency)\n+ clock.Advance(typicalLatency)\ngot, _, err := neigh.entry(entry.Addr, entry.LocalAddr, linkRes, nil)\nif err != nil {\nt.Fatalf(\"unexpected error from neigh.entry(%s, %s, _, nil): %s\", entry.Addr, entry.LocalAddr, err)\n@@ -1618,7 +1619,7 @@ func TestNeighborCacheResolutionFailed(t *testing.T) {\nt.Fatalf(\"got neigh.entry(%s, %s, _, nil) = %v, want = %s\", entry.Addr, entry.LocalAddr, err, tcpip.ErrWouldBlock)\n}\nwaitFor := config.DelayFirstProbeTime + typicalLatency*time.Duration(config.MaxMulticastProbes)\n- clock.advance(waitFor)\n+ clock.Advance(waitFor)\nif _, _, err := neigh.entry(entry.Addr, entry.LocalAddr, linkRes, nil); err != tcpip.ErrNoLinkAddress {\nt.Fatalf(\"got neigh.entry(%s, %s, _, nil) = %v, want = %s\", entry.Addr, entry.LocalAddr, err, tcpip.ErrNoLinkAddress)\n}\n@@ -1636,7 +1637,7 @@ func TestNeighborCacheResolutionTimeout(t *testing.T) {\nconfig := DefaultNUDConfigurations()\nconfig.RetransmitTimer = time.Millisecond // small enough to cause timeout\n- clock := newFakeClock()\n+ clock := faketime.NewManualClock()\nneigh := newTestNeighborCache(nil, config, clock)\nstore := newTestEntryStore()\nlinkRes := &testNeighborResolver{\n@@ -1654,7 +1655,7 @@ func TestNeighborCacheResolutionTimeout(t *testing.T) {\nt.Fatalf(\"got neigh.entry(%s, %s, _, nil) = %v, want = %s\", entry.Addr, entry.LocalAddr, err, tcpip.ErrWouldBlock)\n}\nwaitFor := config.RetransmitTimer * time.Duration(config.MaxMulticastProbes)\n- clock.advance(waitFor)\n+ clock.Advance(waitFor)\nif _, _, err := neigh.entry(entry.Addr, entry.LocalAddr, linkRes, nil); err != tcpip.ErrNoLinkAddress {\nt.Fatalf(\"got neigh.entry(%s, %s, _, nil) = %v, want = %s\", entry.Addr, entry.LocalAddr, err, tcpip.ErrNoLinkAddress)\n}\n@@ -1664,7 +1665,7 @@ func TestNeighborCacheResolutionTimeout(t *testing.T) {\n// resolved immediately and don't send resolution requests.\nfunc TestNeighborCacheStaticResolution(t *testing.T) {\nconfig := DefaultNUDConfigurations()\n- clock := newFakeClock()\n+ clock := faketime.NewManualClock()\nneigh := newTestNeighborCache(nil, config, clock)\nstore := newTestEntryStore()\nlinkRes := &testNeighborResolver{\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_entry_test.go", "new_path": "pkg/tcpip/stack/neighbor_entry_test.go", "diff": "@@ -27,6 +27,7 @@ import (\n\"github.com/google/go-cmp/cmp/cmpopts\"\n\"gvisor.dev/gvisor/pkg/sleep\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/faketime\"\n)\nconst (\n@@ -221,8 +222,8 @@ func (r *entryTestLinkResolver) LinkAddressProtocol() tcpip.NetworkProtocolNumbe\nreturn entryTestNetNumber\n}\n-func entryTestSetup(c NUDConfigurations) (*neighborEntry, *testNUDDispatcher, *entryTestLinkResolver, *fakeClock) {\n- clock := newFakeClock()\n+func entryTestSetup(c NUDConfigurations) (*neighborEntry, *testNUDDispatcher, *entryTestLinkResolver, *faketime.ManualClock) {\n+ clock := faketime.NewManualClock()\ndisp := testNUDDispatcher{}\nnic := NIC{\nid: entryTestNICID,\n@@ -267,7 +268,7 @@ func TestEntryInitiallyUnknown(t *testing.T) {\n}\ne.mu.Unlock()\n- clock.advance(c.RetransmitTimer)\n+ clock.Advance(c.RetransmitTimer)\n// No probes should have been sent.\nlinkRes.mu.Lock()\n@@ -300,7 +301,7 @@ func TestEntryUnknownToUnknownWhenConfirmationWithUnknownAddress(t *testing.T) {\n}\ne.mu.Unlock()\n- clock.advance(time.Hour)\n+ clock.Advance(time.Hour)\n// No probes should have been sent.\nlinkRes.mu.Lock()\n@@ -410,7 +411,7 @@ func TestEntryIncompleteToIncompleteDoesNotChangeUpdatedAt(t *testing.T) {\nupdatedAt := e.neigh.UpdatedAt\ne.mu.Unlock()\n- clock.advance(c.RetransmitTimer)\n+ clock.Advance(c.RetransmitTimer)\n// UpdatedAt should remain the same during address resolution.\nwantProbes := []entryTestProbeInfo{\n@@ -439,7 +440,7 @@ func TestEntryIncompleteToIncompleteDoesNotChangeUpdatedAt(t *testing.T) {\n}\ne.mu.Unlock()\n- clock.advance(c.RetransmitTimer)\n+ clock.Advance(c.RetransmitTimer)\n// UpdatedAt should change after failing address resolution. Timing out after\n// sending the last probe transitions the entry to Failed.\n@@ -459,7 +460,7 @@ func TestEntryIncompleteToIncompleteDoesNotChangeUpdatedAt(t *testing.T) {\n}\n}\n- clock.advance(c.RetransmitTimer)\n+ clock.Advance(c.RetransmitTimer)\nwantEvents := []testEntryEventInfo{\n{\n@@ -748,7 +749,7 @@ func TestEntryIncompleteToFailed(t *testing.T) {\ne.mu.Unlock()\nwaitFor := c.RetransmitTimer * time.Duration(c.MaxMulticastProbes)\n- clock.advance(waitFor)\n+ clock.Advance(waitFor)\nwantProbes := []entryTestProbeInfo{\n// The Incomplete-to-Incomplete state transition is tested here by\n@@ -983,7 +984,7 @@ func TestEntryReachableToStaleWhenTimeout(t *testing.T) {\nt.Fatalf(\"link address resolver probes mismatch (-got, +want):\\n%s\", diff)\n}\n- clock.advance(c.BaseReachableTime)\n+ clock.Advance(c.BaseReachableTime)\nwantEvents := []testEntryEventInfo{\n{\n@@ -1612,7 +1613,7 @@ func TestEntryDelayToReachableWhenUpperLevelConfirmation(t *testing.T) {\nt.Fatalf(\"link address resolver probes mismatch (-got, +want):\\n%s\", diff)\n}\n- clock.advance(c.BaseReachableTime)\n+ clock.Advance(c.BaseReachableTime)\nwantEvents := []testEntryEventInfo{\n{\n@@ -1706,7 +1707,7 @@ func TestEntryDelayToReachableWhenSolicitedOverrideConfirmation(t *testing.T) {\nt.Fatalf(\"link address resolver probes mismatch (-got, +want):\\n%s\", diff)\n}\n- clock.advance(c.BaseReachableTime)\n+ clock.Advance(c.BaseReachableTime)\nwantEvents := []testEntryEventInfo{\n{\n@@ -1989,7 +1990,7 @@ func TestEntryDelayToProbe(t *testing.T) {\n}\ne.mu.Unlock()\n- clock.advance(c.DelayFirstProbeTime)\n+ clock.Advance(c.DelayFirstProbeTime)\nwantProbes := []entryTestProbeInfo{\n// The first probe is caused by the Unknown-to-Incomplete transition.\n@@ -2069,7 +2070,7 @@ func TestEntryProbeToStaleWhenProbeWithDifferentAddress(t *testing.T) {\ne.handlePacketQueuedLocked()\ne.mu.Unlock()\n- clock.advance(c.DelayFirstProbeTime)\n+ clock.Advance(c.DelayFirstProbeTime)\nwantProbes := []entryTestProbeInfo{\n// The first probe is caused by the Unknown-to-Incomplete transition.\n@@ -2166,7 +2167,7 @@ func TestEntryProbeToStaleWhenConfirmationWithDifferentAddress(t *testing.T) {\ne.handlePacketQueuedLocked()\ne.mu.Unlock()\n- clock.advance(c.DelayFirstProbeTime)\n+ clock.Advance(c.DelayFirstProbeTime)\nwantProbes := []entryTestProbeInfo{\n// The first probe is caused by the Unknown-to-Incomplete transition.\n@@ -2267,7 +2268,7 @@ func TestEntryStaysProbeWhenOverrideConfirmationWithSameAddress(t *testing.T) {\ne.handlePacketQueuedLocked()\ne.mu.Unlock()\n- clock.advance(c.DelayFirstProbeTime)\n+ clock.Advance(c.DelayFirstProbeTime)\nwantProbes := []entryTestProbeInfo{\n// The first probe is caused by the Unknown-to-Incomplete transition.\n@@ -2364,7 +2365,7 @@ func TestEntryUnknownToStaleToProbeToReachable(t *testing.T) {\ne.handlePacketQueuedLocked()\ne.mu.Unlock()\n- clock.advance(c.DelayFirstProbeTime)\n+ clock.Advance(c.DelayFirstProbeTime)\nwantProbes := []entryTestProbeInfo{\n// Probe caused by the Delay-to-Probe transition\n@@ -2398,7 +2399,7 @@ func TestEntryUnknownToStaleToProbeToReachable(t *testing.T) {\n}\ne.mu.Unlock()\n- clock.advance(c.BaseReachableTime)\n+ clock.Advance(c.BaseReachableTime)\nwantEvents := []testEntryEventInfo{\n{\n@@ -2463,7 +2464,7 @@ func TestEntryProbeToReachableWhenSolicitedOverrideConfirmation(t *testing.T) {\ne.handlePacketQueuedLocked()\ne.mu.Unlock()\n- clock.advance(c.DelayFirstProbeTime)\n+ clock.Advance(c.DelayFirstProbeTime)\nwantProbes := []entryTestProbeInfo{\n// The first probe is caused by the Unknown-to-Incomplete transition.\n@@ -2503,7 +2504,7 @@ func TestEntryProbeToReachableWhenSolicitedOverrideConfirmation(t *testing.T) {\n}\ne.mu.Unlock()\n- clock.advance(c.BaseReachableTime)\n+ clock.Advance(c.BaseReachableTime)\nwantEvents := []testEntryEventInfo{\n{\n@@ -2575,7 +2576,7 @@ func TestEntryProbeToReachableWhenSolicitedConfirmationWithSameAddress(t *testin\ne.handlePacketQueuedLocked()\ne.mu.Unlock()\n- clock.advance(c.DelayFirstProbeTime)\n+ clock.Advance(c.DelayFirstProbeTime)\nwantProbes := []entryTestProbeInfo{\n// The first probe is caused by the Unknown-to-Incomplete transition.\n@@ -2612,7 +2613,7 @@ func TestEntryProbeToReachableWhenSolicitedConfirmationWithSameAddress(t *testin\n}\ne.mu.Unlock()\n- clock.advance(c.BaseReachableTime)\n+ clock.Advance(c.BaseReachableTime)\nwantEvents := []testEntryEventInfo{\n{\n@@ -2682,7 +2683,7 @@ func TestEntryProbeToFailed(t *testing.T) {\ne.mu.Unlock()\nwaitFor := c.DelayFirstProbeTime + c.RetransmitTimer*time.Duration(c.MaxUnicastProbes)\n- clock.advance(waitFor)\n+ clock.Advance(waitFor)\nwantProbes := []entryTestProbeInfo{\n// The first probe is caused by the Unknown-to-Incomplete transition.\n@@ -2787,7 +2788,7 @@ func TestEntryFailedGetsDeleted(t *testing.T) {\ne.mu.Unlock()\nwaitFor := c.DelayFirstProbeTime + c.RetransmitTimer*time.Duration(c.MaxUnicastProbes) + c.UnreachableTime\n- clock.advance(waitFor)\n+ clock.Advance(waitFor)\nwantProbes := []entryTestProbeInfo{\n// The first probe is caused by the Unknown-to-Incomplete transition.\n" } ]
Go
Apache License 2.0
google/gvisor
Move stack.fakeClock into a separate package PiperOrigin-RevId: 333138701
259,992
22.09.2020 13:43:02
25,200
778c367171f96c6cfd269cd2363c9f608dd96bcb
Fix panic in `runsc flags` When printing flags, FlagSet.PrintDefaults compares the Zero value to the flag default value. The Zero refs.LeakMode value was panicking in String() because it didn't expect the default to be used Closes
[ { "change_type": "MODIFY", "old_path": "pkg/refs/refcounter.go", "new_path": "pkg/refs/refcounter.go", "diff": "@@ -257,6 +257,8 @@ func (l *LeakMode) Get() interface{} {\n// String implements flag.Value.\nfunc (l *LeakMode) String() string {\nswitch *l {\n+ case UninitializedLeakChecking:\n+ return \"uninitialized\"\ncase NoLeakChecking:\nreturn \"disabled\"\ncase LeaksLogWarning:\n@@ -264,7 +266,7 @@ func (l *LeakMode) String() string {\ncase LeaksLogTraces:\nreturn \"log-traces\"\n}\n- panic(fmt.Sprintf(\"invalid ref leak mode %q\", *l))\n+ panic(fmt.Sprintf(\"invalid ref leak mode %d\", *l))\n}\n// leakMode stores the current mode for the reference leak checker.\n" } ]
Go
Apache License 2.0
google/gvisor
Fix panic in `runsc flags` When printing flags, FlagSet.PrintDefaults compares the Zero value to the flag default value. The Zero refs.LeakMode value was panicking in String() because it didn't expect the default to be used Closes #4023 PiperOrigin-RevId: 333150836
259,951
22.09.2020 15:04:11
25,200
cf3cef1171bdfb41a27d563eb368d4488e0b99f1
Refactor testutil.TestEndpoint and use it instead of limitedEP The new testutil.MockLinkEndpoint implementation is not composed by channel.Channel anymore because none of its features were used.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4_test.go", "new_path": "pkg/tcpip/network/ipv4/ipv4_test.go", "diff": "@@ -17,6 +17,7 @@ package ipv4_test\nimport (\n\"bytes\"\n\"encoding/hex\"\n+ \"math\"\n\"testing\"\n\"github.com/google/go-cmp/cmp\"\n@@ -160,47 +161,6 @@ func compareFragments(t *testing.T, packets []*stack.PacketBuffer, sourcePacketI\n}\n}\n-type testRoute struct {\n- stack.Route\n-\n- linkEP *testutil.TestEndpoint\n-}\n-\n-func buildTestRoute(t *testing.T, ep *channel.Endpoint, packetCollectorErrors []*tcpip.Error) testRoute {\n- // Make the packet and write it.\n- s := stack.New(stack.Options{\n- NetworkProtocols: []stack.NetworkProtocol{ipv4.NewProtocol()},\n- })\n- testEP := testutil.NewTestEndpoint(ep, packetCollectorErrors)\n- s.CreateNIC(1, testEP)\n- const (\n- src = \"\\x10\\x00\\x00\\x01\"\n- dst = \"\\x10\\x00\\x00\\x02\"\n- )\n- s.AddAddress(1, ipv4.ProtocolNumber, src)\n- {\n- subnet, err := tcpip.NewSubnet(dst, tcpip.AddressMask(header.IPv4Broadcast))\n- if err != nil {\n- t.Fatal(err)\n- }\n- s.SetRouteTable([]tcpip.Route{{\n- Destination: subnet,\n- NIC: 1,\n- }})\n- }\n- r, err := s.FindRoute(0, src, dst, ipv4.ProtocolNumber, false /* multicastLoop */)\n- if err != nil {\n- t.Fatalf(\"s.FindRoute got %v, want %v\", err, nil)\n- }\n- t.Cleanup(func() {\n- testEP.Close()\n- })\n- return testRoute{\n- Route: r,\n- linkEP: testEP,\n- }\n-}\n-\nfunc TestFragmentation(t *testing.T) {\nvar manyPayloadViewsSizes [1000]int\nfor i := range manyPayloadViewsSizes {\n@@ -228,7 +188,8 @@ func TestFragmentation(t *testing.T) {\nfor _, ft := range fragTests {\nt.Run(ft.description, func(t *testing.T) {\n- r := buildTestRoute(t, channel.New(0, ft.mtu, \"\"), nil)\n+ ep := testutil.NewMockLinkEndpoint(ft.mtu, nil, math.MaxInt32)\n+ r := buildRoute(t, ep)\npkt := testutil.MakeRandPkt(ft.transportHeaderLength, ft.extraHeaderReserveLength, ft.payloadViewsSizes, header.IPv4ProtocolNumber)\nsource := pkt.Clone()\nerr := r.WritePacket(ft.gso, stack.NetworkHeaderParams{\n@@ -237,16 +198,16 @@ func TestFragmentation(t *testing.T) {\nTOS: stack.DefaultTOS,\n}, pkt)\nif err != nil {\n- t.Errorf(\"err got %v, want %v\", err, nil)\n+ t.Errorf(\"got err = %s, want = nil\", err)\n}\n- if got, want := len(r.linkEP.WrittenPackets), ft.expectedFrags; got != want {\n- t.Errorf(\"len(r.linkEP.WrittenPackets) got %d, want %d\", got, want)\n+ if got := len(ep.WrittenPackets); got != ft.expectedFrags {\n+ t.Errorf(\"got len(ep.WrittenPackets) = %d, want = %d\", got, ft.expectedFrags)\n}\n- if got, want := len(r.linkEP.WrittenPackets), int(r.Stats().IP.PacketsSent.Value()); got != want {\n- t.Errorf(\"no errors yet len(r.linkEP.WrittenPackets) got %d, want %d\", got, want)\n+ if got, want := len(ep.WrittenPackets), int(r.Stats().IP.PacketsSent.Value()); got != want {\n+ t.Errorf(\"no errors yet got len(ep.WrittenPackets) = %d, want = %d\", got, want)\n}\n- compareFragments(t, r.linkEP.WrittenPackets, source, ft.mtu)\n+ compareFragments(t, ep.WrittenPackets, source, ft.mtu)\n})\n}\n}\n@@ -259,35 +220,30 @@ func TestFragmentationErrors(t *testing.T) {\nmtu uint32\ntransportHeaderLength int\npayloadViewsSizes []int\n- packetCollectorErrors []*tcpip.Error\n+ err *tcpip.Error\n+ allowPackets int\n}{\n- {\"NoFrag\", 2000, 0, []int{1000}, []*tcpip.Error{tcpip.ErrAborted}},\n- {\"ErrorOnFirstFrag\", 500, 0, []int{1000}, []*tcpip.Error{tcpip.ErrAborted}},\n- {\"ErrorOnSecondFrag\", 500, 0, []int{1000}, []*tcpip.Error{nil, tcpip.ErrAborted}},\n- {\"ErrorOnFirstFragMTUSmallerThanHeader\", 500, 1000, []int{500}, []*tcpip.Error{tcpip.ErrAborted}},\n+ {\"NoFrag\", 2000, 0, []int{1000}, tcpip.ErrAborted, 0},\n+ {\"ErrorOnFirstFrag\", 500, 0, []int{1000}, tcpip.ErrAborted, 0},\n+ {\"ErrorOnSecondFrag\", 500, 0, []int{1000}, tcpip.ErrAborted, 1},\n+ {\"ErrorOnFirstFragMTUSmallerThanHeader\", 500, 1000, []int{500}, tcpip.ErrAborted, 0},\n}\nfor _, ft := range fragTests {\nt.Run(ft.description, func(t *testing.T) {\n- r := buildTestRoute(t, channel.New(0, ft.mtu, \"\"), ft.packetCollectorErrors)\n+ ep := testutil.NewMockLinkEndpoint(ft.mtu, ft.err, ft.allowPackets)\n+ r := buildRoute(t, ep)\npkt := testutil.MakeRandPkt(ft.transportHeaderLength, header.IPv4MinimumSize, ft.payloadViewsSizes, header.IPv4ProtocolNumber)\nerr := r.WritePacket(&stack.GSO{}, stack.NetworkHeaderParams{\nProtocol: tcp.ProtocolNumber,\nTTL: 42,\nTOS: stack.DefaultTOS,\n}, pkt)\n- for i := 0; i < len(ft.packetCollectorErrors)-1; i++ {\n- if got, want := ft.packetCollectorErrors[i], (*tcpip.Error)(nil); got != want {\n- t.Errorf(\"ft.packetCollectorErrors[%d] got %v, want %v\", i, got, want)\n+ if err != ft.err {\n+ t.Errorf(\"got WritePacket() = %s, want = %s\", err, ft.err)\n}\n- }\n- // We only need to check that last error because all the ones before are\n- // nil.\n- if got, want := err, ft.packetCollectorErrors[len(ft.packetCollectorErrors)-1]; got != want {\n- t.Errorf(\"err got %v, want %v\", got, want)\n- }\n- if got, want := len(r.linkEP.WrittenPackets), int(r.Stats().IP.PacketsSent.Value())+1; err != nil && got != want {\n- t.Errorf(\"after linkEP error len(result) got %d, want %d\", got, want)\n+ if got, want := len(ep.WrittenPackets), int(r.Stats().IP.PacketsSent.Value()); err != nil && got != want {\n+ t.Errorf(\"got len(ep.WrittenPackets) = %d, want = %d\", got, want)\n}\n})\n}\n@@ -1052,7 +1008,7 @@ func TestWriteStats(t *testing.T) {\ntests := []struct {\nname string\nsetup func(*testing.T, *stack.Stack)\n- linkEP func() stack.LinkEndpoint\n+ allowPackets int\nexpectSent int\nexpectDropped int\nexpectWritten int\n@@ -1061,7 +1017,7 @@ func TestWriteStats(t *testing.T) {\nname: \"Accept all\",\n// No setup needed, tables accept everything by default.\nsetup: func(*testing.T, *stack.Stack) {},\n- linkEP: func() stack.LinkEndpoint { return &limitedEP{nPackets} },\n+ allowPackets: math.MaxInt32,\nexpectSent: nPackets,\nexpectDropped: 0,\nexpectWritten: nPackets,\n@@ -1069,7 +1025,7 @@ func TestWriteStats(t *testing.T) {\nname: \"Accept all with error\",\n// No setup needed, tables accept everything by default.\nsetup: func(*testing.T, *stack.Stack) {},\n- linkEP: func() stack.LinkEndpoint { return &limitedEP{nPackets - 1} },\n+ allowPackets: nPackets - 1,\nexpectSent: nPackets - 1,\nexpectDropped: 0,\nexpectWritten: nPackets - 1,\n@@ -1086,10 +1042,10 @@ func TestWriteStats(t *testing.T) {\nruleIdx := filter.BuiltinChains[stack.Output]\nfilter.Rules[ruleIdx].Target = stack.DropTarget{}\nif err := ipt.ReplaceTable(stack.FilterTable, filter, false /* ipv6 */); err != nil {\n- t.Fatalf(\"failed to replace table: %v\", err)\n+ t.Fatalf(\"failed to replace table: %s\", err)\n}\n},\n- linkEP: func() stack.LinkEndpoint { return &limitedEP{nPackets} },\n+ allowPackets: math.MaxInt32,\nexpectSent: 0,\nexpectDropped: nPackets,\nexpectWritten: nPackets,\n@@ -1111,10 +1067,10 @@ func TestWriteStats(t *testing.T) {\n// Make sure the next rule is ACCEPT.\nfilter.Rules[ruleIdx+1].Target = stack.AcceptTarget{}\nif err := ipt.ReplaceTable(stack.FilterTable, filter, false /* ipv6 */); err != nil {\n- t.Fatalf(\"failed to replace table: %v\", err)\n+ t.Fatalf(\"failed to replace table: %s\", err)\n}\n},\n- linkEP: func() stack.LinkEndpoint { return &limitedEP{nPackets} },\n+ allowPackets: math.MaxInt32,\nexpectSent: nPackets - 1,\nexpectDropped: 1,\nexpectWritten: nPackets,\n@@ -1150,7 +1106,8 @@ func TestWriteStats(t *testing.T) {\nt.Run(writer.name, func(t *testing.T) {\nfor _, test := range tests {\nt.Run(test.name, func(t *testing.T) {\n- rt := buildRoute(t, nil, test.linkEP())\n+ ep := testutil.NewMockLinkEndpoint(header.IPv4MinimumSize+header.UDPMinimumSize, tcpip.ErrInvalidEndpointState, test.allowPackets)\n+ rt := buildRoute(t, ep)\nvar pkts stack.PacketBufferList\nfor i := 0; i < nPackets; i++ {\n@@ -1181,101 +1138,37 @@ func TestWriteStats(t *testing.T) {\n}\n}\n-func buildRoute(t *testing.T, packetCollectorErrors []*tcpip.Error, linkEP stack.LinkEndpoint) stack.Route {\n+func buildRoute(t *testing.T, ep stack.LinkEndpoint) stack.Route {\ns := stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocol{ipv4.NewProtocol()},\n})\n- s.CreateNIC(1, linkEP)\n+ if err := s.CreateNIC(1, ep); err != nil {\n+ t.Fatalf(\"CreateNIC(1, _) failed: %s\", err)\n+ }\nconst (\nsrc = \"\\x10\\x00\\x00\\x01\"\ndst = \"\\x10\\x00\\x00\\x02\"\n)\n- s.AddAddress(1, ipv4.ProtocolNumber, src)\n+ if err := s.AddAddress(1, ipv4.ProtocolNumber, src); err != nil {\n+ t.Fatalf(\"AddAddress(1, %d, _) failed: %s\", ipv4.ProtocolNumber, err)\n+ }\n{\nsubnet, err := tcpip.NewSubnet(dst, tcpip.AddressMask(header.IPv4Broadcast))\nif err != nil {\n- t.Fatal(err)\n+ t.Fatalf(\"NewSubnet(_, _) failed: %v\", err)\n}\ns.SetRouteTable([]tcpip.Route{{\nDestination: subnet,\nNIC: 1,\n}})\n}\n- rt, err := s.FindRoute(0, src, dst, ipv4.ProtocolNumber, false /* multicastLoop */)\n+ rt, err := s.FindRoute(1, src, dst, ipv4.ProtocolNumber, false /* multicastLoop */)\nif err != nil {\n- t.Fatalf(\"s.FindRoute got %v, want %v\", err, nil)\n+ t.Fatalf(\"got FindRoute(1, _, _, %d, false) = %s, want = nil\", ipv4.ProtocolNumber, err)\n}\nreturn rt\n}\n-// limitedEP is a link endpoint that writes up to a certain number of packets\n-// before returning errors.\n-type limitedEP struct {\n- limit int\n-}\n-\n-// MTU implements LinkEndpoint.MTU.\n-func (*limitedEP) MTU() uint32 {\n- // Give an MTU that won't cause fragmentation for IPv4+UDP.\n- return header.IPv4MinimumSize + header.UDPMinimumSize\n-}\n-\n-// Capabilities implements LinkEndpoint.Capabilities.\n-func (*limitedEP) Capabilities() stack.LinkEndpointCapabilities { return 0 }\n-\n-// MaxHeaderLength implements LinkEndpoint.MaxHeaderLength.\n-func (*limitedEP) MaxHeaderLength() uint16 { return 0 }\n-\n-// LinkAddress implements LinkEndpoint.LinkAddress.\n-func (*limitedEP) LinkAddress() tcpip.LinkAddress { return \"\" }\n-\n-// WritePacket implements LinkEndpoint.WritePacket.\n-func (ep *limitedEP) WritePacket(*stack.Route, *stack.GSO, tcpip.NetworkProtocolNumber, *stack.PacketBuffer) *tcpip.Error {\n- if ep.limit == 0 {\n- return tcpip.ErrInvalidEndpointState\n- }\n- ep.limit--\n- return nil\n-}\n-\n-// WritePackets implements LinkEndpoint.WritePackets.\n-func (ep *limitedEP) WritePackets(_ *stack.Route, _ *stack.GSO, pkts stack.PacketBufferList, _ tcpip.NetworkProtocolNumber) (int, *tcpip.Error) {\n- if ep.limit == 0 {\n- return 0, tcpip.ErrInvalidEndpointState\n- }\n- nWritten := ep.limit\n- if nWritten > pkts.Len() {\n- nWritten = pkts.Len()\n- }\n- ep.limit -= nWritten\n- return nWritten, nil\n-}\n-\n-// WriteRawPacket implements LinkEndpoint.WriteRawPacket.\n-func (ep *limitedEP) WriteRawPacket(_ buffer.VectorisedView) *tcpip.Error {\n- if ep.limit == 0 {\n- return tcpip.ErrInvalidEndpointState\n- }\n- ep.limit--\n- return nil\n-}\n-\n-// Attach implements LinkEndpoint.Attach.\n-func (*limitedEP) Attach(_ stack.NetworkDispatcher) {}\n-\n-// IsAttached implements LinkEndpoint.IsAttached.\n-func (*limitedEP) IsAttached() bool { return false }\n-\n-// Wait implements LinkEndpoint.Wait.\n-func (*limitedEP) Wait() {}\n-\n-// ARPHardwareType implements LinkEndpoint.ARPHardwareType.\n-func (*limitedEP) ARPHardwareType() header.ARPHardwareType { return header.ARPHardwareEther }\n-\n-// AddHeader implements LinkEndpoint.AddHeader.\n-func (*limitedEP) AddHeader(_, _ tcpip.LinkAddress, _ tcpip.NetworkProtocolNumber, _ *stack.PacketBuffer) {\n-}\n-\n// limitedMatcher is an iptables matcher that matches after a certain number of\n// packets are checked against it.\ntype limitedMatcher struct {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/BUILD", "new_path": "pkg/tcpip/network/ipv6/BUILD", "diff": "@@ -35,6 +35,7 @@ go_test(\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/link/channel\",\n\"//pkg/tcpip/link/sniffer\",\n+ \"//pkg/tcpip/network/testutil\",\n\"//pkg/tcpip/stack\",\n\"//pkg/tcpip/transport/icmp\",\n\"//pkg/tcpip/transport/udp\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "new_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "diff": "@@ -23,6 +23,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/channel\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/network/testutil\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/icmp\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/udp\"\n@@ -1715,7 +1716,7 @@ func TestWriteStats(t *testing.T) {\ntests := []struct {\nname string\nsetup func(*testing.T, *stack.Stack)\n- linkEP func() stack.LinkEndpoint\n+ allowPackets int\nexpectSent int\nexpectDropped int\nexpectWritten int\n@@ -1724,7 +1725,7 @@ func TestWriteStats(t *testing.T) {\nname: \"Accept all\",\n// No setup needed, tables accept everything by default.\nsetup: func(*testing.T, *stack.Stack) {},\n- linkEP: func() stack.LinkEndpoint { return &limitedEP{nPackets} },\n+ allowPackets: math.MaxInt32,\nexpectSent: nPackets,\nexpectDropped: 0,\nexpectWritten: nPackets,\n@@ -1732,7 +1733,7 @@ func TestWriteStats(t *testing.T) {\nname: \"Accept all with error\",\n// No setup needed, tables accept everything by default.\nsetup: func(*testing.T, *stack.Stack) {},\n- linkEP: func() stack.LinkEndpoint { return &limitedEP{nPackets - 1} },\n+ allowPackets: nPackets - 1,\nexpectSent: nPackets - 1,\nexpectDropped: 0,\nexpectWritten: nPackets - 1,\n@@ -1752,7 +1753,7 @@ func TestWriteStats(t *testing.T) {\nt.Fatalf(\"failed to replace table: %v\", err)\n}\n},\n- linkEP: func() stack.LinkEndpoint { return &limitedEP{nPackets} },\n+ allowPackets: math.MaxInt32,\nexpectSent: 0,\nexpectDropped: nPackets,\nexpectWritten: nPackets,\n@@ -1777,7 +1778,7 @@ func TestWriteStats(t *testing.T) {\nt.Fatalf(\"failed to replace table: %v\", err)\n}\n},\n- linkEP: func() stack.LinkEndpoint { return &limitedEP{nPackets} },\n+ allowPackets: math.MaxInt32,\nexpectSent: nPackets - 1,\nexpectDropped: 1,\nexpectWritten: nPackets,\n@@ -1812,7 +1813,8 @@ func TestWriteStats(t *testing.T) {\nt.Run(writer.name, func(t *testing.T) {\nfor _, test := range tests {\nt.Run(test.name, func(t *testing.T) {\n- rt := buildRoute(t, nil, test.linkEP())\n+ ep := testutil.NewMockLinkEndpoint(header.IPv6MinimumMTU, tcpip.ErrInvalidEndpointState, test.allowPackets)\n+ rt := buildRoute(t, ep)\nvar pkts stack.PacketBufferList\nfor i := 0; i < nPackets; i++ {\n@@ -1843,100 +1845,37 @@ func TestWriteStats(t *testing.T) {\n}\n}\n-func buildRoute(t *testing.T, packetCollectorErrors []*tcpip.Error, linkEP stack.LinkEndpoint) stack.Route {\n+func buildRoute(t *testing.T, ep stack.LinkEndpoint) stack.Route {\ns := stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocol{NewProtocol()},\n})\n- s.CreateNIC(1, linkEP)\n+ if err := s.CreateNIC(1, ep); err != nil {\n+ t.Fatalf(\"CreateNIC(1, _) failed: %s\", err)\n+ }\nconst (\nsrc = \"\\xfc\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\"\ndst = \"\\xfc\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\"\n)\n- s.AddAddress(1, ProtocolNumber, src)\n+ if err := s.AddAddress(1, ProtocolNumber, src); err != nil {\n+ t.Fatalf(\"AddAddress(1, %d, _) failed: %s\", ProtocolNumber, err)\n+ }\n{\nsubnet, err := tcpip.NewSubnet(dst, tcpip.AddressMask(\"\\xfc\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\"))\nif err != nil {\n- t.Fatal(err)\n+ t.Fatalf(\"NewSubnet(_, _) failed: %v\", err)\n}\ns.SetRouteTable([]tcpip.Route{{\nDestination: subnet,\nNIC: 1,\n}})\n}\n- rt, err := s.FindRoute(0, src, dst, ProtocolNumber, false /* multicastLoop */)\n+ rt, err := s.FindRoute(1, src, dst, ProtocolNumber, false /* multicastLoop */)\nif err != nil {\n- t.Fatalf(\"s.FindRoute got %v, want %v\", err, nil)\n+ t.Fatalf(\"got FindRoute(1, _, _, %d, false) = %s, want = nil\", ProtocolNumber, err)\n}\nreturn rt\n}\n-// limitedEP is a link endpoint that writes up to a certain number of packets\n-// before returning errors.\n-type limitedEP struct {\n- limit int\n-}\n-\n-// MTU implements LinkEndpoint.MTU.\n-func (*limitedEP) MTU() uint32 {\n- return header.IPv6MinimumMTU\n-}\n-\n-// Capabilities implements LinkEndpoint.Capabilities.\n-func (*limitedEP) Capabilities() stack.LinkEndpointCapabilities { return 0 }\n-\n-// MaxHeaderLength implements LinkEndpoint.MaxHeaderLength.\n-func (*limitedEP) MaxHeaderLength() uint16 { return 0 }\n-\n-// LinkAddress implements LinkEndpoint.LinkAddress.\n-func (*limitedEP) LinkAddress() tcpip.LinkAddress { return \"\" }\n-\n-// WritePacket implements LinkEndpoint.WritePacket.\n-func (ep *limitedEP) WritePacket(*stack.Route, *stack.GSO, tcpip.NetworkProtocolNumber, *stack.PacketBuffer) *tcpip.Error {\n- if ep.limit == 0 {\n- return tcpip.ErrInvalidEndpointState\n- }\n- ep.limit--\n- return nil\n-}\n-\n-// WritePackets implements LinkEndpoint.WritePackets.\n-func (ep *limitedEP) WritePackets(_ *stack.Route, _ *stack.GSO, pkts stack.PacketBufferList, _ tcpip.NetworkProtocolNumber) (int, *tcpip.Error) {\n- if ep.limit == 0 {\n- return 0, tcpip.ErrInvalidEndpointState\n- }\n- nWritten := ep.limit\n- if nWritten > pkts.Len() {\n- nWritten = pkts.Len()\n- }\n- ep.limit -= nWritten\n- return nWritten, nil\n-}\n-\n-// WriteRawPacket implements LinkEndpoint.WriteRawPacket.\n-func (ep *limitedEP) WriteRawPacket(_ buffer.VectorisedView) *tcpip.Error {\n- if ep.limit == 0 {\n- return tcpip.ErrInvalidEndpointState\n- }\n- ep.limit--\n- return nil\n-}\n-\n-// Attach implements LinkEndpoint.Attach.\n-func (*limitedEP) Attach(_ stack.NetworkDispatcher) {}\n-\n-// IsAttached implements LinkEndpoint.IsAttached.\n-func (*limitedEP) IsAttached() bool { return false }\n-\n-// Wait implements LinkEndpoint.Wait.\n-func (*limitedEP) Wait() {}\n-\n-// ARPHardwareType implements LinkEndpoint.ARPHardwareType.\n-func (*limitedEP) ARPHardwareType() header.ARPHardwareType { return header.ARPHardwareEther }\n-\n-// AddHeader implements LinkEndpoint.AddHeader.\n-func (*limitedEP) AddHeader(_, _ tcpip.LinkAddress, _ tcpip.NetworkProtocolNumber, _ *stack.PacketBuffer) {\n-}\n-\n// limitedMatcher is an iptables matcher that matches after a certain number of\n// packets are checked against it.\ntype limitedMatcher struct {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/testutil/BUILD", "new_path": "pkg/tcpip/network/testutil/BUILD", "diff": "@@ -7,11 +7,14 @@ go_library(\nsrcs = [\n\"testutil.go\",\n],\n- visibility = [\"//pkg/tcpip/network/ipv4:__pkg__\"],\n+ visibility = [\n+ \"//pkg/tcpip/network/ipv4:__pkg__\",\n+ \"//pkg/tcpip/network/ipv6:__pkg__\",\n+ ],\ndeps = [\n\"//pkg/tcpip\",\n\"//pkg/tcpip/buffer\",\n- \"//pkg/tcpip/link/channel\",\n+ \"//pkg/tcpip/header\",\n\"//pkg/tcpip/stack\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/testutil/testutil.go", "new_path": "pkg/tcpip/network/testutil/testutil.go", "diff": "@@ -22,48 +22,100 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n- \"gvisor.dev/gvisor/pkg/tcpip/link/channel\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n)\n-// TestEndpoint is an endpoint used for testing, it stores packets written to it\n-// and can mock errors.\n-type TestEndpoint struct {\n- *channel.Endpoint\n-\n- // WrittenPackets is where we store packets written via WritePacket().\n+// MockLinkEndpoint is an endpoint used for testing, it stores packets written\n+// to it and can mock errors.\n+type MockLinkEndpoint struct {\n+ // WrittenPackets is where packets written to the endpoint are stored.\nWrittenPackets []*stack.PacketBuffer\n- packetCollectorErrors []*tcpip.Error\n+ mtu uint32\n+ err *tcpip.Error\n+ allowPackets int\n}\n-// NewTestEndpoint creates a new TestEndpoint endpoint.\n+// NewMockLinkEndpoint creates a new MockLinkEndpoint.\n//\n-// packetCollectorErrors can be used to set error values and each call to\n-// WritePacket will remove the first one from the slice and return it until\n-// the slice is empty - at that point it will return nil every time.\n-func NewTestEndpoint(ep *channel.Endpoint, packetCollectorErrors []*tcpip.Error) *TestEndpoint {\n- return &TestEndpoint{\n- Endpoint: ep,\n- WrittenPackets: make([]*stack.PacketBuffer, 0),\n- packetCollectorErrors: packetCollectorErrors,\n+// err is the error that will be returned once allowPackets packets are written\n+// to the endpoint.\n+func NewMockLinkEndpoint(mtu uint32, err *tcpip.Error, allowPackets int) *MockLinkEndpoint {\n+ return &MockLinkEndpoint{\n+ mtu: mtu,\n+ err: err,\n+ allowPackets: allowPackets,\n+ }\n+}\n+\n+// MTU implements LinkEndpoint.MTU.\n+func (ep *MockLinkEndpoint) MTU() uint32 { return ep.mtu }\n+\n+// Capabilities implements LinkEndpoint.Capabilities.\n+func (*MockLinkEndpoint) Capabilities() stack.LinkEndpointCapabilities { return 0 }\n+\n+// MaxHeaderLength implements LinkEndpoint.MaxHeaderLength.\n+func (*MockLinkEndpoint) MaxHeaderLength() uint16 { return 0 }\n+\n+// LinkAddress implements LinkEndpoint.LinkAddress.\n+func (*MockLinkEndpoint) LinkAddress() tcpip.LinkAddress { return \"\" }\n+\n+// WritePacket implements LinkEndpoint.WritePacket.\n+func (ep *MockLinkEndpoint) WritePacket(_ *stack.Route, _ *stack.GSO, _ tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) *tcpip.Error {\n+ if ep.allowPackets == 0 {\n+ return ep.err\n}\n+ ep.allowPackets--\n+ ep.WrittenPackets = append(ep.WrittenPackets, pkt)\n+ return nil\n}\n-// WritePacket stores outbound packets and may return an error if one was\n-// injected.\n-func (e *TestEndpoint) WritePacket(_ *stack.Route, _ *stack.GSO, _ tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) *tcpip.Error {\n- e.WrittenPackets = append(e.WrittenPackets, pkt)\n+// WritePackets implements LinkEndpoint.WritePackets.\n+func (ep *MockLinkEndpoint) WritePackets(r *stack.Route, gso *stack.GSO, pkts stack.PacketBufferList, protocol tcpip.NetworkProtocolNumber) (int, *tcpip.Error) {\n+ var n int\n+\n+ for pkt := pkts.Front(); pkt != nil; pkt = pkt.Next() {\n+ if err := ep.WritePacket(r, gso, protocol, pkt); err != nil {\n+ return n, err\n+ }\n+ n++\n+ }\n- if len(e.packetCollectorErrors) > 0 {\n- nextError := e.packetCollectorErrors[0]\n- e.packetCollectorErrors = e.packetCollectorErrors[1:]\n- return nextError\n+ return n, nil\n}\n+// WriteRawPacket implements LinkEndpoint.WriteRawPacket.\n+func (ep *MockLinkEndpoint) WriteRawPacket(vv buffer.VectorisedView) *tcpip.Error {\n+ if ep.allowPackets == 0 {\n+ return ep.err\n+ }\n+ ep.allowPackets--\n+\n+ pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n+ Data: vv,\n+ })\n+ ep.WrittenPackets = append(ep.WrittenPackets, pkt)\n+\nreturn nil\n}\n+// Attach implements LinkEndpoint.Attach.\n+func (*MockLinkEndpoint) Attach(stack.NetworkDispatcher) {}\n+\n+// IsAttached implements LinkEndpoint.IsAttached.\n+func (*MockLinkEndpoint) IsAttached() bool { return false }\n+\n+// Wait implements LinkEndpoint.Wait.\n+func (*MockLinkEndpoint) Wait() {}\n+\n+// ARPHardwareType implements LinkEndpoint.ARPHardwareType.\n+func (*MockLinkEndpoint) ARPHardwareType() header.ARPHardwareType { return header.ARPHardwareNone }\n+\n+// AddHeader implements LinkEndpoint.AddHeader.\n+func (*MockLinkEndpoint) AddHeader(_, _ tcpip.LinkAddress, _ tcpip.NetworkProtocolNumber, _ *stack.PacketBuffer) {\n+}\n+\n// MakeRandPkt generates a randomized packet. transportHeaderLength indicates\n// how many random bytes will be copied in the Transport Header.\n// extraHeaderReserveLength indicates how much extra space will be reserved for\n" } ]
Go
Apache License 2.0
google/gvisor
Refactor testutil.TestEndpoint and use it instead of limitedEP The new testutil.MockLinkEndpoint implementation is not composed by channel.Channel anymore because none of its features were used. PiperOrigin-RevId: 333167753
259,860
22.09.2020 22:29:28
25,200
b54dbdfdc6b6cbdb6f45cd2abd9efb1f2f821a20
Handle EOF properly in splice/sendfile. Use HandleIOErrorVFS2 instead of custom error handling.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/pipe/pipe.go", "new_path": "pkg/sentry/kernel/pipe/pipe.go", "diff": "@@ -17,6 +17,7 @@ package pipe\nimport (\n\"fmt\"\n+ \"io\"\n\"sync/atomic\"\n\"syscall\"\n@@ -215,7 +216,7 @@ func (p *Pipe) readLocked(ctx context.Context, ops readOps) (int64, error) {\nif p.view.Size() == 0 {\nif !p.HasWriters() {\n// There are no writers, return EOF.\n- return 0, nil\n+ return 0, io.EOF\n}\nreturn 0, syserror.ErrWouldBlock\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/splice.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/splice.go", "diff": "@@ -23,6 +23,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/pipe\"\n+ slinux \"gvisor.dev/gvisor/pkg/sentry/syscalls/linux\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n@@ -146,11 +147,6 @@ func Splice(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\npanic(\"at least one end of splice must be a pipe\")\n}\n- if n == 0 && err == io.EOF {\n- // We reached the end of the file. Eat the error and exit the loop.\n- err = nil\n- break\n- }\nif n != 0 || err != syserror.ErrWouldBlock || nonBlock {\nbreak\n}\n@@ -171,15 +167,16 @@ func Splice(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\n}\n}\n- if n == 0 {\n- return 0, nil, err\n- }\n-\n+ if n != 0 {\n// On Linux, inotify behavior is not very consistent with splice(2). We try\n// our best to emulate Linux for very basic calls to splice, where for some\n// reason, events are generated for output files, but not input files.\noutFile.Dentry().InotifyWithParent(t, linux.IN_MODIFY, 0, vfs.PathEvent)\n- return uintptr(n), nil, nil\n+ }\n+\n+ // We can only pass a single file to handleIOError, so pick inFile arbitrarily.\n+ // This is used only for debugging purposes.\n+ return uintptr(n), nil, slinux.HandleIOErrorVFS2(t, n != 0, err, syserror.ERESTARTSYS, \"splice\", outFile)\n}\n// Tee implements Linux syscall tee(2).\n@@ -251,11 +248,20 @@ func Tee(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallCo\nbreak\n}\n}\n- if n == 0 {\n- return 0, nil, err\n- }\n+\n+ if n != 0 {\noutFile.Dentry().InotifyWithParent(t, linux.IN_MODIFY, 0, vfs.PathEvent)\n- return uintptr(n), nil, nil\n+\n+ // If a partial write is completed, the error is dropped. Log it here.\n+ if err != nil && err != io.EOF && err != syserror.ErrWouldBlock {\n+ log.Debugf(\"tee completed a partial write with error: %v\", err)\n+ err = nil\n+ }\n+ }\n+\n+ // We can only pass a single file to handleIOError, so pick inFile arbitrarily.\n+ // This is used only for debugging purposes.\n+ return uintptr(n), nil, slinux.HandleIOErrorVFS2(t, n != 0, err, syserror.ERESTARTSYS, \"tee\", inFile)\n}\n// Sendfile implements linux system call sendfile(2).\n@@ -348,11 +354,6 @@ func Sendfile(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\nfor n < count {\nvar spliceN int64\nspliceN, err = outPipeFD.SpliceFromNonPipe(t, inFile, offset, count)\n- if spliceN == 0 && err == io.EOF {\n- // We reached the end of the file. Eat the error and exit the loop.\n- err = nil\n- break\n- }\nif offset != -1 {\noffset += spliceN\n}\n@@ -375,13 +376,6 @@ func Sendfile(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\n} else {\nreadN, err = inFile.Read(t, usermem.BytesIOSequence(buf), vfs.ReadOptions{})\n}\n- if readN == 0 && err != nil {\n- if err == io.EOF {\n- // We reached the end of the file. Eat the error before exiting the loop.\n- err = nil\n- }\n- break\n- }\nn += readN\n// Write all of the bytes that we read. This may need\n@@ -432,13 +426,20 @@ func Sendfile(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\n}\n}\n- if n == 0 {\n- return 0, nil, err\n- }\n-\n+ if n != 0 {\ninFile.Dentry().InotifyWithParent(t, linux.IN_ACCESS, 0, vfs.PathEvent)\noutFile.Dentry().InotifyWithParent(t, linux.IN_MODIFY, 0, vfs.PathEvent)\n- return uintptr(n), nil, nil\n+\n+ if err != nil && err != io.EOF && err != syserror.ErrWouldBlock {\n+ // If a partial write is completed, the error is dropped. Log it here.\n+ log.Debugf(\"sendfile completed a partial write with error: %v\", err)\n+ err = nil\n+ }\n+ }\n+\n+ // We can only pass a single file to handleIOError, so pick inFile arbitrarily.\n+ // This is used only for debugging purposes.\n+ return uintptr(n), nil, slinux.HandleIOErrorVFS2(t, n != 0, err, syserror.ERESTARTSYS, \"sendfile\", inFile)\n}\n// dualWaiter is used to wait on one or both vfs.FileDescriptions. It is not\n" } ]
Go
Apache License 2.0
google/gvisor
Handle EOF properly in splice/sendfile. Use HandleIOErrorVFS2 instead of custom error handling. PiperOrigin-RevId: 333227581
259,898
23.09.2020 16:49:33
25,200
c3c66ea428c8f56ff64e415961035feffef718f3
Clean up flag.* usage in packetimpact's runner.RegisterFlags
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/runner/dut.go", "new_path": "test/packetimpact/runner/dut.go", "diff": "@@ -69,8 +69,8 @@ func RegisterFlags(fs *flag.FlagSet) {\nfs.BoolVar(&native, \"native\", false, \"whether the test should be run natively\")\nfs.StringVar(&testbenchBinary, \"testbench_binary\", \"\", \"path to the testbench binary\")\nfs.BoolVar(&tshark, \"tshark\", false, \"use more verbose tshark in logs instead of tcpdump\")\n- flag.Var(&extraTestArgs, \"extra_test_arg\", \"extra arguments to pass to the testbench\")\n- flag.BoolVar(&expectFailure, \"expect_failure\", false, \"expect that the test will fail when run\")\n+ fs.Var(&extraTestArgs, \"extra_test_arg\", \"extra arguments to pass to the testbench\")\n+ fs.BoolVar(&expectFailure, \"expect_failure\", false, \"expect that the test will fail when run\")\n}\n// CtrlPort is the port that posix_server listens on.\n" } ]
Go
Apache License 2.0
google/gvisor
Clean up flag.* usage in packetimpact's runner.RegisterFlags PiperOrigin-RevId: 333400865
260,001
23.09.2020 17:10:43
25,200
994062ec9ca70110c39d9c004cad62e23d4c7a41
Set verity underlying fs mount as internal
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/verity/verity.go", "new_path": "pkg/sentry/fsimpl/verity/verity.go", "diff": "@@ -159,6 +159,7 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\n// verity, and should not be exposed or connected.\nmopts := &vfs.MountOptions{\nGetFilesystemOptions: iopts.LowerGetFSOptions,\n+ InternalMount: true,\n}\nmnt, err := vfsObj.MountDisconnected(ctx, creds, \"\", iopts.LowerName, mopts)\nif err != nil {\n" } ]
Go
Apache License 2.0
google/gvisor
Set verity underlying fs mount as internal PiperOrigin-RevId: 333404727
260,004
23.09.2020 17:13:32
25,200
e02e7e999a65d4cb7784e67de74fb4ffa556b386
Remove unused field from neighborEntry
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_entry.go", "new_path": "pkg/tcpip/stack/neighbor_entry.go", "diff": "@@ -74,7 +74,6 @@ type neighborEntry struct {\nneighborEntryEntry\nnic *NIC\n- protocol tcpip.NetworkProtocolNumber\n// linkRes provides the functionality to send reachability probes, used in\n// Neighbor Unreachability Detection.\n" } ]
Go
Apache License 2.0
google/gvisor
Remove unused field from neighborEntry PiperOrigin-RevId: 333405169
260,001
23.09.2020 18:03:21
25,200
9c8a6796fd88fbcffad1dd3fa80c301ec425fcbf
Let underlying fs handle LockFD in verity fs
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/verity/verity.go", "new_path": "pkg/sentry/fsimpl/verity/verity.go", "diff": "@@ -677,10 +677,10 @@ func (fd *fileDescription) PRead(ctx context.Context, dst usermem.IOSequence, of\n// LockPOSIX implements vfs.FileDescriptionImpl.LockPOSIX.\nfunc (fd *fileDescription) LockPOSIX(ctx context.Context, uid fslock.UniqueID, t fslock.LockType, start, length uint64, whence int16, block fslock.Blocker) error {\n- return fd.Locks().LockPOSIX(ctx, &fd.vfsfd, uid, t, start, length, whence, block)\n+ return fd.lowerFD.LockPOSIX(ctx, uid, t, start, length, whence, block)\n}\n// UnlockPOSIX implements vfs.FileDescriptionImpl.UnlockPOSIX.\nfunc (fd *fileDescription) UnlockPOSIX(ctx context.Context, uid fslock.UniqueID, start, length uint64, whence int16) error {\n- return fd.Locks().UnlockPOSIX(ctx, &fd.vfsfd, uid, start, length, whence)\n+ return fd.lowerFD.UnlockPOSIX(ctx, uid, start, length, whence)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Let underlying fs handle LockFD in verity fs PiperOrigin-RevId: 333412836
259,907
23.09.2020 18:43:16
25,200
08bbad690764dd55e333cade340d779df93de920
[vfs] kernfs: Enable leak checking consistently. There were some instances where we were not enabling leak checking.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "new_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "diff": "@@ -280,6 +280,7 @@ func (fs *filesystem) newRootInode(creds *auth.Credentials, mode linux.FileMode)\ni := &inode{fs: fs}\ni.InodeAttrs.Init(creds, linux.UNNAMED_MAJOR, fs.devMinor, 1, linux.ModeDirectory|0755)\ni.OrderedChildren.Init(kernfs.OrderedChildrenOptions{})\n+ i.EnableLeakCheck()\ni.dentry.Init(i)\ni.nodeID = 1\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/host/host.go", "new_path": "pkg/sentry/fsimpl/host/host.go", "diff": "@@ -58,7 +58,7 @@ func newInode(fs *filesystem, hostFD int, fileType linux.FileMode, isTTY bool) (\ncanMap: fileType == linux.S_IFREG,\n}\ni.pf.inode = i\n- i.refs.EnableLeakCheck()\n+ i.EnableLeakCheck()\n// Non-seekable files can't be memory mapped, assert this.\nif !i.seekable && i.canMap {\n@@ -193,7 +193,7 @@ type inode struct {\nlocks vfs.FileLocks\n// When the reference count reaches zero, the host fd is closed.\n- refs inodeRefs\n+ inodeRefs\n// hostFD contains the host fd that this file was originally created from,\n// which must be available at time of restore.\n@@ -435,19 +435,9 @@ func (i *inode) SetStat(ctx context.Context, fs *vfs.Filesystem, creds *auth.Cre\nreturn nil\n}\n-// IncRef implements kernfs.Inode.IncRef.\n-func (i *inode) IncRef() {\n- i.refs.IncRef()\n-}\n-\n-// TryIncRef implements kernfs.Inode.TryIncRef.\n-func (i *inode) TryIncRef() bool {\n- return i.refs.TryIncRef()\n-}\n-\n// DecRef implements kernfs.Inode.DecRef.\nfunc (i *inode) DecRef(ctx context.Context) {\n- i.refs.DecRef(func() {\n+ i.inodeRefs.DecRef(func() {\nif i.wouldBlock {\nfdnotifier.RemoveFD(int32(i.hostFD))\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go", "new_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go", "diff": "@@ -574,6 +574,7 @@ var _ Inode = (*StaticDirectory)(nil)\nfunc NewStaticDir(creds *auth.Credentials, devMajor, devMinor uint32, ino uint64, perm linux.FileMode, children map[string]*Dentry, fdOpts GenericDirectoryFDOptions) *Dentry {\ninode := &StaticDirectory{}\ninode.Init(creds, devMajor, devMinor, ino, perm, fdOpts)\n+ inode.EnableLeakCheck()\ndentry := &Dentry{}\ndentry.Init(inode)\n" } ]
Go
Apache License 2.0
google/gvisor
[vfs] kernfs: Enable leak checking consistently. There were some instances where we were not enabling leak checking. PiperOrigin-RevId: 333418571
259,860
23.09.2020 22:40:10
25,200
6410e74a9602ecb92813375f45b953ab813cf313
Add more descriptive comments on mount options.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/filesystem_type.go", "new_path": "pkg/sentry/vfs/filesystem_type.go", "diff": "@@ -56,9 +56,10 @@ type registeredFilesystemType struct {\n// RegisterFilesystemTypeOptions contains options to\n// VirtualFilesystem.RegisterFilesystem().\ntype RegisterFilesystemTypeOptions struct {\n- // If AllowUserMount is true, allow calls to VirtualFilesystem.MountAt()\n- // for which MountOptions.InternalMount == false to use this filesystem\n- // type.\n+ // AllowUserMount determines whether users are allowed to mount a file system\n+ // of this type, i.e. through mount(2). If AllowUserMount is true, allow calls\n+ // to VirtualFilesystem.MountAt() for which MountOptions.InternalMount == false\n+ // to use this filesystem type.\nAllowUserMount bool\n// If AllowUserList is true, make this filesystem type visible in\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/options.go", "new_path": "pkg/sentry/vfs/options.go", "diff": "@@ -103,8 +103,10 @@ type MountOptions struct {\n// GetFilesystemOptions contains options to FilesystemType.GetFilesystem().\nGetFilesystemOptions GetFilesystemOptions\n- // If InternalMount is true, allow the use of filesystem types for which\n- // RegisterFilesystemTypeOptions.AllowUserMount == false.\n+ // InternalMount indicates whether the mount operation is coming from the\n+ // application, i.e. through mount(2). If InternalMount is true, allow the use\n+ // of filesystem types for which RegisterFilesystemTypeOptions.AllowUserMount\n+ // == false.\nInternalMount bool\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add more descriptive comments on mount options. PiperOrigin-RevId: 333447255
259,860
23.09.2020 23:00:27
25,200
03898a087d8858f7a006f3eda649a18b02949d80
Clean up inotify tests. Mostly simplifies SKIP_IF statements and adds some more documentation. Also, mknod is now supported by gofer fs, so remove SKIP_IFs related to this.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/inotify.cc", "new_path": "test/syscalls/linux/inotify.cc", "diff": "@@ -465,7 +465,9 @@ TEST(Inotify, ConcurrentFileDeletionAndWatchRemoval) {\nfor (int i = 0; i < 100; ++i) {\nFileDescriptor file_fd =\nASSERT_NO_ERRNO_AND_VALUE(Open(filename, O_CREAT, S_IRUSR | S_IWUSR));\n- file_fd.reset(); // Close before unlinking (although save is disabled).\n+ // Close before unlinking (although S/R is disabled). Some filesystems\n+ // cannot restore an open fd on an unlinked file.\n+ file_fd.reset();\nEXPECT_THAT(unlink(filename.c_str()), SyscallSucceeds());\n}\n};\n@@ -1256,10 +1258,7 @@ TEST(Inotify, MknodGeneratesCreateEvent) {\nInotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));\nconst TempPath file1(root.path() + \"/file1\");\n- const int rc = mknod(file1.path().c_str(), S_IFREG, 0);\n- // mknod(2) is only supported on tmpfs in the sandbox.\n- SKIP_IF(IsRunningOnGvisor() && rc != 0);\n- ASSERT_THAT(rc, SyscallSucceeds());\n+ ASSERT_THAT(mknod(file1.path().c_str(), S_IFREG, 0), SyscallSucceeds());\nconst std::vector<Event> events =\nASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));\n@@ -1289,6 +1288,10 @@ TEST(Inotify, SymlinkGeneratesCreateEvent) {\n}\nTEST(Inotify, LinkGeneratesAttribAndCreateEvents) {\n+ // Inotify does not work properly with hard links in gofer and overlay fs.\n+ SKIP_IF(IsRunningOnGvisor() &&\n+ !ASSERT_NO_ERRNO_AND_VALUE(IsTmpfs(GetAbsoluteTestTmpdir())));\n+\nconst TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\nconst TempPath file1 =\nASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));\n@@ -1301,11 +1304,8 @@ TEST(Inotify, LinkGeneratesAttribAndCreateEvents) {\nconst int file1_wd = ASSERT_NO_ERRNO_AND_VALUE(\nInotifyAddWatch(fd.get(), file1.path(), IN_ALL_EVENTS));\n- const int rc = link(file1.path().c_str(), link1.path().c_str());\n- // NOTE(b/34861058): link(2) is only supported on tmpfs in the sandbox.\n- SKIP_IF(IsRunningOnGvisor() && rc != 0 &&\n- (errno == EPERM || errno == ENOENT));\n- ASSERT_THAT(rc, SyscallSucceeds());\n+ ASSERT_THAT(link(file1.path().c_str(), link1.path().c_str()),\n+ SyscallSucceeds());\nconst std::vector<Event> events =\nASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));\n@@ -1334,68 +1334,70 @@ TEST(Inotify, UtimesGeneratesAttribEvent) {\n}\nTEST(Inotify, HardlinksReuseSameWatch) {\n+ // Inotify does not work properly with hard links in gofer and overlay fs.\n+ SKIP_IF(IsRunningOnGvisor() &&\n+ !ASSERT_NO_ERRNO_AND_VALUE(IsTmpfs(GetAbsoluteTestTmpdir())));\n+\nconst TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n- TempPath file1 =\n+ TempPath file =\nASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(root.path()));\n- TempPath link1(root.path() + \"/link1\");\n- const int rc = link(file1.path().c_str(), link1.path().c_str());\n- // link(2) is only supported on tmpfs in the sandbox.\n- SKIP_IF(IsRunningOnGvisor() && rc != 0 &&\n- (errno == EPERM || errno == ENOENT));\n- ASSERT_THAT(rc, SyscallSucceeds());\n+\n+ TempPath file2(root.path() + \"/file2\");\n+ ASSERT_THAT(link(file.path().c_str(), file2.path().c_str()),\n+ SyscallSucceeds());\nconst FileDescriptor fd =\nASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));\nconst int root_wd = ASSERT_NO_ERRNO_AND_VALUE(\nInotifyAddWatch(fd.get(), root.path(), IN_ALL_EVENTS));\n- const int file1_wd = ASSERT_NO_ERRNO_AND_VALUE(\n- InotifyAddWatch(fd.get(), file1.path(), IN_ALL_EVENTS));\n- const int link1_wd = ASSERT_NO_ERRNO_AND_VALUE(\n- InotifyAddWatch(fd.get(), link1.path(), IN_ALL_EVENTS));\n+ const int file_wd = ASSERT_NO_ERRNO_AND_VALUE(\n+ InotifyAddWatch(fd.get(), file.path(), IN_ALL_EVENTS));\n+ const int file2_wd = ASSERT_NO_ERRNO_AND_VALUE(\n+ InotifyAddWatch(fd.get(), file2.path(), IN_ALL_EVENTS));\n// The watch descriptors for watches on different links to the same file\n// should be identical.\n- EXPECT_NE(root_wd, file1_wd);\n- EXPECT_EQ(file1_wd, link1_wd);\n+ EXPECT_NE(root_wd, file_wd);\n+ EXPECT_EQ(file_wd, file2_wd);\n- FileDescriptor file1_fd =\n- ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_WRONLY));\n+ FileDescriptor file_fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_WRONLY));\nstd::vector<Event> events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));\nASSERT_THAT(events,\n- AreUnordered({Event(IN_OPEN, root_wd, Basename(file1.path())),\n- Event(IN_OPEN, file1_wd)}));\n+ AreUnordered({Event(IN_OPEN, root_wd, Basename(file.path())),\n+ Event(IN_OPEN, file_wd)}));\n// For the next step, we want to ensure all fds to the file are closed. Do\n// that now and drain the resulting events.\n- file1_fd.reset();\n+ file_fd.reset();\nevents = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));\nASSERT_THAT(\nevents,\n- AreUnordered({Event(IN_CLOSE_WRITE, root_wd, Basename(file1.path())),\n- Event(IN_CLOSE_WRITE, file1_wd)}));\n+ AreUnordered({Event(IN_CLOSE_WRITE, root_wd, Basename(file.path())),\n+ Event(IN_CLOSE_WRITE, file_wd)}));\n// Try removing the link and let's see what events show up. Note that after\n// this, we still have a link to the file so the watch shouldn't be\n// automatically removed.\n- const std::string link1_path = link1.reset();\n+ const std::string file2_path = file2.reset();\nevents = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));\nASSERT_THAT(events,\n- AreUnordered({Event(IN_ATTRIB, link1_wd),\n- Event(IN_DELETE, root_wd, Basename(link1_path))}));\n+ AreUnordered({Event(IN_ATTRIB, file2_wd),\n+ Event(IN_DELETE, root_wd, Basename(file2_path))}));\n// Now remove the other link. Since this is the last link to the file, the\n// watch should be automatically removed.\n- const std::string file1_path = file1.reset();\n+ const std::string file_path = file.reset();\nevents = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(fd.get()));\nASSERT_THAT(\nevents,\n- AreUnordered({Event(IN_ATTRIB, file1_wd), Event(IN_DELETE_SELF, file1_wd),\n- Event(IN_IGNORED, file1_wd),\n- Event(IN_DELETE, root_wd, Basename(file1_path))}));\n+ AreUnordered({Event(IN_ATTRIB, file_wd), Event(IN_DELETE_SELF, file_wd),\n+ Event(IN_IGNORED, file_wd),\n+ Event(IN_DELETE, root_wd, Basename(file_path))}));\n}\n// Calling mkdir within \"parent/child\" should generate an event for child, but\n@@ -1806,17 +1808,17 @@ TEST(Inotify, SpliceOnInotifyFD) {\n// Watches on a parent should not be triggered by actions on a hard link to one\n// of its children that has a different parent.\nTEST(Inotify, LinkOnOtherParent) {\n+ // Inotify does not work properly with hard links in gofer and overlay fs.\n+ SKIP_IF(IsRunningOnGvisor() &&\n+ !ASSERT_NO_ERRNO_AND_VALUE(IsTmpfs(GetAbsoluteTestTmpdir())));\n+\nconst TempPath dir1 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\nconst TempPath dir2 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\nconst TempPath file =\nASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(dir1.path()));\nstd::string link_path = NewTempAbsPathInDir(dir2.path());\n- const int rc = link(file.path().c_str(), link_path.c_str());\n- // NOTE(b/34861058): link(2) is only supported on tmpfs in the sandbox.\n- SKIP_IF(IsRunningOnGvisor() && rc != 0 &&\n- (errno == EPERM || errno == ENOENT));\n- ASSERT_THAT(rc, SyscallSucceeds());\n+ ASSERT_THAT(link(file.path().c_str(), link_path.c_str()), SyscallSucceeds());\nconst FileDescriptor inotify_fd =\nASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));\n@@ -1825,13 +1827,18 @@ TEST(Inotify, LinkOnOtherParent) {\n// Perform various actions on the link outside of dir1, which should trigger\n// no inotify events.\n- const FileDescriptor fd =\n+ FileDescriptor fd =\nASSERT_NO_ERRNO_AND_VALUE(Open(link_path.c_str(), O_RDWR));\nint val = 0;\nASSERT_THAT(write(fd.get(), &val, sizeof(val)), SyscallSucceeds());\nASSERT_THAT(read(fd.get(), &val, sizeof(val)), SyscallSucceeds());\nASSERT_THAT(ftruncate(fd.get(), 12345), SyscallSucceeds());\n+\n+ // Close before unlinking; some filesystems cannot restore an open fd on an\n+ // unlinked file.\n+ fd.reset();\nASSERT_THAT(unlink(link_path.c_str()), SyscallSucceeds());\n+\nconst std::vector<Event> events =\nASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));\nEXPECT_THAT(events, Are({}));\n@@ -2055,21 +2062,21 @@ TEST(Inotify, ExcludeUnlinkDirectory_NoRandomSave) {\n// We need to disable S/R because there are filesystems where we cannot re-open\n// fds to an unlinked file across S/R, e.g. gofer-backed filesytems.\nTEST(Inotify, ExcludeUnlinkMultipleChildren_NoRandomSave) {\n- const DisableSave ds;\n+ // Inotify does not work properly with hard links in gofer and overlay fs.\n+ SKIP_IF(IsRunningOnGvisor() &&\n+ !ASSERT_NO_ERRNO_AND_VALUE(IsTmpfs(GetAbsoluteTestTmpdir())));\n// TODO(gvisor.dev/issue/1624): This test fails on VFS1.\nSKIP_IF(IsRunningWithVFS1());\n+ const DisableSave ds;\n+\nconst TempPath dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\nconst TempPath file =\nASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(dir.path()));\nstd::string path1 = file.path();\nstd::string path2 = NewTempAbsPathInDir(dir.path());\n+ ASSERT_THAT(link(path1.c_str(), path2.c_str()), SyscallSucceeds());\n- const int rc = link(path1.c_str(), path2.c_str());\n- // NOTE(b/34861058): link(2) is only supported on tmpfs in the sandbox.\n- SKIP_IF(IsRunningOnGvisor() && rc != 0 &&\n- (errno == EPERM || errno == ENOENT));\n- ASSERT_THAT(rc, SyscallSucceeds());\nconst FileDescriptor fd1 =\nASSERT_NO_ERRNO_AND_VALUE(Open(path1.c_str(), O_RDWR));\nconst FileDescriptor fd2 =\n@@ -2101,6 +2108,15 @@ TEST(Inotify, ExcludeUnlinkMultipleChildren_NoRandomSave) {\n// We need to disable S/R because there are filesystems where we cannot re-open\n// fds to an unlinked file across S/R, e.g. gofer-backed filesytems.\nTEST(Inotify, ExcludeUnlinkInodeEvents_NoRandomSave) {\n+ // TODO(gvisor.dev/issue/1624): Fails on VFS1.\n+ SKIP_IF(IsRunningWithVFS1());\n+\n+ // NOTE(gvisor.dev/issue/3654): In the gofer filesystem, we do not allow\n+ // setting attributes through an fd if the file at the open path has been\n+ // deleted.\n+ SKIP_IF(IsRunningOnGvisor() &&\n+ !ASSERT_NO_ERRNO_AND_VALUE(IsTmpfs(GetAbsoluteTestTmpdir())));\n+\nconst DisableSave ds;\nconst TempPath dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n@@ -2110,18 +2126,6 @@ TEST(Inotify, ExcludeUnlinkInodeEvents_NoRandomSave) {\nconst FileDescriptor fd =\nASSERT_NO_ERRNO_AND_VALUE(Open(file.path().c_str(), O_RDWR));\n- // NOTE(b/157163751): Create another link before unlinking. This is needed for\n- // the gofer filesystem in gVisor, where open fds will not work once the link\n- // count hits zero. In VFS2, we end up skipping the gofer test anyway, because\n- // hard links are not supported for gofer fs.\n- if (IsRunningOnGvisor()) {\n- std::string link_path = NewTempAbsPath();\n- const int rc = link(file.path().c_str(), link_path.c_str());\n- // NOTE(b/34861058): link(2) is only supported on tmpfs in the sandbox.\n- SKIP_IF(rc != 0 && (errno == EPERM || errno == ENOENT));\n- ASSERT_THAT(rc, SyscallSucceeds());\n- }\n-\nconst FileDescriptor inotify_fd =\nASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));\nconst int dir_wd = ASSERT_NO_ERRNO_AND_VALUE(InotifyAddWatch(\n" } ]
Go
Apache License 2.0
google/gvisor
Clean up inotify tests. Mostly simplifies SKIP_IF statements and adds some more documentation. Also, mknod is now supported by gofer fs, so remove SKIP_IFs related to this. PiperOrigin-RevId: 333449932
259,905
24.09.2020 14:16:12
-28,800
332e1716fc93e3f2ffe6961d3c296503d2079bc8
Rename kernel.SocketEntry to kernel.SocketRecord SocketEntry can be confusing with the template types as the 'Entry' is usually used as a suffix for list element types, e.g. socketEntry in the same package. Suggested by Dean (@dean-deng).
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/BUILD", "new_path": "pkg/sentry/kernel/BUILD", "diff": "@@ -69,8 +69,8 @@ go_template_instance(\nprefix = \"socket\",\ntemplate = \"//pkg/ilist:generic_list\",\ntypes = {\n- \"Element\": \"*SocketEntry\",\n- \"Linker\": \"*SocketEntry\",\n+ \"Element\": \"*SocketRecord\",\n+ \"Linker\": \"*SocketRecord\",\n},\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/kernel.go", "new_path": "pkg/sentry/kernel/kernel.go", "diff": "@@ -224,9 +224,9 @@ type Kernel struct {\n// extMu.\nsockets socketList\n- // nextSocketEntry is the next entry number to use in sockets. Protected\n+ // nextSocketRecord is the next entry number to use in sockets. Protected\n// by extMu.\n- nextSocketEntry uint64\n+ nextSocketRecord uint64\n// deviceRegistry is used to save/restore device.SimpleDevices.\ndeviceRegistry struct{} `state:\".(*device.Registry)\"`\n@@ -1509,11 +1509,11 @@ func (k *Kernel) SupervisorContext() context.Context {\n}\n}\n-// SocketEntry represents a socket recorded in Kernel.sockets. It implements\n+// SocketRecord represents a socket recorded in Kernel.sockets. It implements\n// refs.WeakRefUser for sockets stored in the socket table.\n//\n// +stateify savable\n-type SocketEntry struct {\n+type SocketRecord struct {\nsocketEntry\nk *Kernel\nSock *refs.WeakRef\n@@ -1522,7 +1522,7 @@ type SocketEntry struct {\n}\n// WeakRefGone implements refs.WeakRefUser.WeakRefGone.\n-func (s *SocketEntry) WeakRefGone(context.Context) {\n+func (s *SocketRecord) WeakRefGone(context.Context) {\ns.k.extMu.Lock()\ns.k.sockets.Remove(s)\ns.k.extMu.Unlock()\n@@ -1533,9 +1533,9 @@ func (s *SocketEntry) WeakRefGone(context.Context) {\n// Precondition: Caller must hold a reference to sock.\nfunc (k *Kernel) RecordSocket(sock *fs.File) {\nk.extMu.Lock()\n- id := k.nextSocketEntry\n- k.nextSocketEntry++\n- s := &SocketEntry{k: k, ID: id}\n+ id := k.nextSocketRecord\n+ k.nextSocketRecord++\n+ s := &SocketRecord{k: k, ID: id}\ns.Sock = refs.NewWeakRef(sock, s)\nk.sockets.PushBack(s)\nk.extMu.Unlock()\n@@ -1550,9 +1550,9 @@ func (k *Kernel) RecordSocket(sock *fs.File) {\n// vfs.FileDescription, because we do not support weak refs on VFS2 files.\nfunc (k *Kernel) RecordSocketVFS2(sock *vfs.FileDescription) {\nk.extMu.Lock()\n- id := k.nextSocketEntry\n- k.nextSocketEntry++\n- s := &SocketEntry{\n+ id := k.nextSocketRecord\n+ k.nextSocketRecord++\n+ s := &SocketRecord{\nk: k,\nID: id,\nSockVFS2: sock,\n@@ -1563,11 +1563,11 @@ func (k *Kernel) RecordSocketVFS2(sock *vfs.FileDescription) {\n// ListSockets returns a snapshot of all sockets.\n//\n-// Callers of ListSockets() in VFS2 should use SocketEntry.SockVFS2.TryIncRef()\n+// Callers of ListSockets() in VFS2 should use SocketRecord.SockVFS2.TryIncRef()\n// to get a reference on a socket in the table.\n-func (k *Kernel) ListSockets() []*SocketEntry {\n+func (k *Kernel) ListSockets() []*SocketRecord {\nk.extMu.Lock()\n- var socks []*SocketEntry\n+ var socks []*SocketRecord\nfor s := k.sockets.Front(); s != nil; s = s.Next() {\nsocks = append(socks, s)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Rename kernel.SocketEntry to kernel.SocketRecord SocketEntry can be confusing with the template types as the 'Entry' is usually used as a suffix for list element types, e.g. socketEntry in the same package. Suggested by Dean (@dean-deng). Signed-off-by: Tiwei Bie <[email protected]>
259,905
24.09.2020 14:16:12
-28,800
71f8cab91b2005c9e3ab904e3a2cba99cb031230
Fix socket record leak in VFS2 VFS2 socket record is not removed from the system-wide socket table when the socket is released, which will lead to a memory leak. This patch fixes this issue. Fixes:
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/BUILD", "new_path": "pkg/sentry/kernel/BUILD", "diff": "@@ -69,8 +69,8 @@ go_template_instance(\nprefix = \"socket\",\ntemplate = \"//pkg/ilist:generic_list\",\ntypes = {\n- \"Element\": \"*SocketRecord\",\n- \"Linker\": \"*SocketRecord\",\n+ \"Element\": \"*SocketRecordVFS1\",\n+ \"Linker\": \"*SocketRecordVFS1\",\n},\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/kernel.go", "new_path": "pkg/sentry/kernel/kernel.go", "diff": "@@ -220,10 +220,15 @@ type Kernel struct {\n// danglingEndpoints is used to save / restore tcpip.DanglingEndpoints.\ndanglingEndpoints struct{} `state:\".([]tcpip.Endpoint)\"`\n- // sockets is the list of all network sockets the system. Protected by\n- // extMu.\n+ // sockets is the list of all network sockets in the system.\n+ // Protected by extMu.\n+ // TODO(gvisor.dev/issue/1624): Only used by VFS1.\nsockets socketList\n+ // socketsVFS2 records all network sockets in the system. Protected by\n+ // extMu.\n+ socketsVFS2 map[*vfs.FileDescription]*SocketRecord\n+\n// nextSocketRecord is the next entry number to use in sockets. Protected\n// by extMu.\nnextSocketRecord uint64\n@@ -414,6 +419,8 @@ func (k *Kernel) Init(args InitKernelArgs) error {\nreturn fmt.Errorf(\"failed to create sockfs mount: %v\", err)\n}\nk.socketMount = socketMount\n+\n+ k.socketsVFS2 = make(map[*vfs.FileDescription]*SocketRecord)\n}\nreturn nil\n@@ -1509,20 +1516,27 @@ func (k *Kernel) SupervisorContext() context.Context {\n}\n}\n-// SocketRecord represents a socket recorded in Kernel.sockets. It implements\n-// refs.WeakRefUser for sockets stored in the socket table.\n+// SocketRecord represents a socket recorded in Kernel.socketsVFS2.\n//\n// +stateify savable\ntype SocketRecord struct {\n- socketEntry\nk *Kernel\n- Sock *refs.WeakRef\n- SockVFS2 *vfs.FileDescription\n+ Sock *refs.WeakRef // TODO(gvisor.dev/issue/1624): Only used by VFS1.\n+ SockVFS2 *vfs.FileDescription // Only used by VFS2.\nID uint64 // Socket table entry number.\n}\n+// SocketRecordVFS1 represents a socket recorded in Kernel.sockets. It implements\n+// refs.WeakRefUser for sockets stored in the socket table.\n+//\n+// +stateify savable\n+type SocketRecordVFS1 struct {\n+ socketEntry\n+ SocketRecord\n+}\n+\n// WeakRefGone implements refs.WeakRefUser.WeakRefGone.\n-func (s *SocketRecord) WeakRefGone(context.Context) {\n+func (s *SocketRecordVFS1) WeakRefGone(context.Context) {\ns.k.extMu.Lock()\ns.k.sockets.Remove(s)\ns.k.extMu.Unlock()\n@@ -1535,7 +1549,12 @@ func (k *Kernel) RecordSocket(sock *fs.File) {\nk.extMu.Lock()\nid := k.nextSocketRecord\nk.nextSocketRecord++\n- s := &SocketRecord{k: k, ID: id}\n+ s := &SocketRecordVFS1{\n+ SocketRecord: SocketRecord{\n+ k: k,\n+ ID: id,\n+ },\n+ }\ns.Sock = refs.NewWeakRef(sock, s)\nk.sockets.PushBack(s)\nk.extMu.Unlock()\n@@ -1547,9 +1566,12 @@ func (k *Kernel) RecordSocket(sock *fs.File) {\n// Precondition: Caller must hold a reference to sock.\n//\n// Note that the socket table will not hold a reference on the\n-// vfs.FileDescription, because we do not support weak refs on VFS2 files.\n+// vfs.FileDescription.\nfunc (k *Kernel) RecordSocketVFS2(sock *vfs.FileDescription) {\nk.extMu.Lock()\n+ if _, ok := k.socketsVFS2[sock]; ok {\n+ panic(fmt.Sprintf(\"Socket %p added twice\", sock))\n+ }\nid := k.nextSocketRecord\nk.nextSocketRecord++\ns := &SocketRecord{\n@@ -1557,7 +1579,14 @@ func (k *Kernel) RecordSocketVFS2(sock *vfs.FileDescription) {\nID: id,\nSockVFS2: sock,\n}\n- k.sockets.PushBack(s)\n+ k.socketsVFS2[sock] = s\n+ k.extMu.Unlock()\n+}\n+\n+// DeleteSocketVFS2 removes a VFS2 socket from the system-wide socket table.\n+func (k *Kernel) DeleteSocketVFS2(sock *vfs.FileDescription) {\n+ k.extMu.Lock()\n+ delete(k.socketsVFS2, sock)\nk.extMu.Unlock()\n}\n@@ -1568,9 +1597,15 @@ func (k *Kernel) RecordSocketVFS2(sock *vfs.FileDescription) {\nfunc (k *Kernel) ListSockets() []*SocketRecord {\nk.extMu.Lock()\nvar socks []*SocketRecord\n- for s := k.sockets.Front(); s != nil; s = s.Next() {\n+ if VFS2Enabled {\n+ for _, s := range k.socketsVFS2 {\nsocks = append(socks, s)\n}\n+ } else {\n+ for s := k.sockets.Front(); s != nil; s = s.Next() {\n+ socks = append(socks, &s.SocketRecord)\n+ }\n+ }\nk.extMu.Unlock()\nreturn socks\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/hostinet/socket_vfs2.go", "new_path": "pkg/sentry/socket/hostinet/socket_vfs2.go", "diff": "@@ -77,6 +77,13 @@ func newVFS2Socket(t *kernel.Task, family int, stype linux.SockType, protocol in\nreturn vfsfd, nil\n}\n+// Release implements vfs.FileDescriptionImpl.Release.\n+func (s *socketVFS2) Release(ctx context.Context) {\n+ t := kernel.TaskFromContext(ctx)\n+ t.Kernel().DeleteSocketVFS2(&s.vfsfd)\n+ s.socketOpsCommon.Release(ctx)\n+}\n+\n// Readiness implements waiter.Waitable.Readiness.\nfunc (s *socketVFS2) Readiness(mask waiter.EventMask) waiter.EventMask {\nreturn s.socketOpsCommon.Readiness(mask)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netlink/socket_vfs2.go", "new_path": "pkg/sentry/socket/netlink/socket_vfs2.go", "diff": "@@ -82,6 +82,13 @@ func NewVFS2(t *kernel.Task, skType linux.SockType, protocol Protocol) (*SocketV\nreturn fd, nil\n}\n+// Release implements vfs.FileDescriptionImpl.Release.\n+func (s *SocketVFS2) Release(ctx context.Context) {\n+ t := kernel.TaskFromContext(ctx)\n+ t.Kernel().DeleteSocketVFS2(&s.vfsfd)\n+ s.socketOpsCommon.Release(ctx)\n+}\n+\n// Readiness implements waiter.Waitable.Readiness.\nfunc (s *SocketVFS2) Readiness(mask waiter.EventMask) waiter.EventMask {\nreturn s.socketOpsCommon.Readiness(mask)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack_vfs2.go", "new_path": "pkg/sentry/socket/netstack/netstack_vfs2.go", "diff": "@@ -79,6 +79,13 @@ func NewVFS2(t *kernel.Task, family int, skType linux.SockType, protocol int, qu\nreturn vfsfd, nil\n}\n+// Release implements vfs.FileDescriptionImpl.Release.\n+func (s *SocketVFS2) Release(ctx context.Context) {\n+ t := kernel.TaskFromContext(ctx)\n+ t.Kernel().DeleteSocketVFS2(&s.vfsfd)\n+ s.socketOpsCommon.Release(ctx)\n+}\n+\n// Readiness implements waiter.Waitable.Readiness.\nfunc (s *SocketVFS2) Readiness(mask waiter.EventMask) waiter.EventMask {\nreturn s.socketOpsCommon.Readiness(mask)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/unix/BUILD", "new_path": "pkg/sentry/socket/unix/BUILD", "diff": "@@ -7,10 +7,21 @@ go_template_instance(\nname = \"socket_refs\",\nout = \"socket_refs.go\",\npackage = \"unix\",\n- prefix = \"socketOpsCommon\",\n+ prefix = \"socketOperations\",\ntemplate = \"//pkg/refs_vfs2:refs_template\",\ntypes = {\n- \"T\": \"socketOpsCommon\",\n+ \"T\": \"SocketOperations\",\n+ },\n+)\n+\n+go_template_instance(\n+ name = \"socket_vfs2_refs\",\n+ out = \"socket_vfs2_refs.go\",\n+ package = \"unix\",\n+ prefix = \"socketVFS2\",\n+ template = \"//pkg/refs_vfs2:refs_template\",\n+ types = {\n+ \"T\": \"SocketVFS2\",\n},\n)\n@@ -20,6 +31,7 @@ go_library(\n\"device.go\",\n\"io.go\",\n\"socket_refs.go\",\n+ \"socket_vfs2_refs.go\",\n\"unix.go\",\n\"unix_vfs2.go\",\n],\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/unix/unix.go", "new_path": "pkg/sentry/socket/unix/unix.go", "diff": "@@ -55,6 +55,7 @@ type SocketOperations struct {\nfsutil.FileNoopFlush `state:\"nosave\"`\nfsutil.FileUseInodeUnstableAttr `state:\"nosave\"`\n+ socketOperationsRefs\nsocketOpsCommon\n}\n@@ -84,11 +85,27 @@ func NewWithDirent(ctx context.Context, d *fs.Dirent, ep transport.Endpoint, sty\nreturn fs.NewFile(ctx, d, flags, &s)\n}\n+// DecRef implements RefCounter.DecRef.\n+func (s *SocketOperations) DecRef(ctx context.Context) {\n+ s.socketOperationsRefs.DecRef(func() {\n+ s.ep.Close(ctx)\n+ if s.abstractNamespace != nil {\n+ s.abstractNamespace.Remove(s.abstractName, s)\n+ }\n+ })\n+}\n+\n+// Release implemements fs.FileOperations.Release.\n+func (s *SocketOperations) Release(ctx context.Context) {\n+ // Release only decrements a reference on s because s may be referenced in\n+ // the abstract socket namespace.\n+ s.DecRef(ctx)\n+}\n+\n// socketOpsCommon contains the socket operations common to VFS1 and VFS2.\n//\n// +stateify savable\ntype socketOpsCommon struct {\n- socketOpsCommonRefs\nsocket.SendReceiveTimeout\nep transport.Endpoint\n@@ -101,23 +118,6 @@ type socketOpsCommon struct {\nabstractNamespace *kernel.AbstractSocketNamespace\n}\n-// DecRef implements RefCounter.DecRef.\n-func (s *socketOpsCommon) DecRef(ctx context.Context) {\n- s.socketOpsCommonRefs.DecRef(func() {\n- s.ep.Close(ctx)\n- if s.abstractNamespace != nil {\n- s.abstractNamespace.Remove(s.abstractName, s)\n- }\n- })\n-}\n-\n-// Release implemements fs.FileOperations.Release.\n-func (s *socketOpsCommon) Release(ctx context.Context) {\n- // Release only decrements a reference on s because s may be referenced in\n- // the abstract socket namespace.\n- s.DecRef(ctx)\n-}\n-\nfunc (s *socketOpsCommon) isPacket() bool {\nswitch s.stype {\ncase linux.SOCK_DGRAM, linux.SOCK_SEQPACKET:\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/unix/unix_vfs2.go", "new_path": "pkg/sentry/socket/unix/unix_vfs2.go", "diff": "@@ -43,6 +43,7 @@ type SocketVFS2 struct {\nvfs.DentryMetadataFileDescriptionImpl\nvfs.LockFD\n+ socketVFS2Refs\nsocketOpsCommon\n}\n@@ -88,6 +89,25 @@ func NewFileDescription(ep transport.Endpoint, stype linux.SockType, flags uint3\nreturn vfsfd, nil\n}\n+// DecRef implements RefCounter.DecRef.\n+func (s *SocketVFS2) DecRef(ctx context.Context) {\n+ s.socketVFS2Refs.DecRef(func() {\n+ t := kernel.TaskFromContext(ctx)\n+ t.Kernel().DeleteSocketVFS2(&s.vfsfd)\n+ s.ep.Close(ctx)\n+ if s.abstractNamespace != nil {\n+ s.abstractNamespace.Remove(s.abstractName, s)\n+ }\n+ })\n+}\n+\n+// Release implements vfs.FileDescriptionImpl.Release.\n+func (s *SocketVFS2) Release(ctx context.Context) {\n+ // Release only decrements a reference on s because s may be referenced in\n+ // the abstract socket namespace.\n+ s.DecRef(ctx)\n+}\n+\n// GetSockOpt implements the linux syscall getsockopt(2) for sockets backed by\n// a transport.Endpoint.\nfunc (s *SocketVFS2) GetSockOpt(t *kernel.Task, level, name int, outPtr usermem.Addr, outLen int) (marshal.Marshallable, *syserr.Error) {\n" } ]
Go
Apache License 2.0
google/gvisor
Fix socket record leak in VFS2 VFS2 socket record is not removed from the system-wide socket table when the socket is released, which will lead to a memory leak. This patch fixes this issue. Fixes: #3874 Signed-off-by: Tiwei Bie <[email protected]>
259,853
23.09.2020 23:32:46
25,200
3838e83a9844f1ebeafab50e33df588480986927
fuse: don't call dentry.InsertChild It is called from the kernfs code (OpenAt and revalidateChildLocked()). For RemoveChildLocked, it is opposed. We need to call it from fuse.RmDir and fuse.Unlink.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "new_path": "pkg/sentry/fsimpl/fuse/fusefs.go", "diff": "@@ -528,12 +528,7 @@ func (i *inode) RmDir(ctx context.Context, name string, child *vfs.Dentry) error\nreturn err\n}\n- // TODO(Before merging): When creating new nodes, should we add nodes to the ordered children?\n- // If so we'll probably need to call this. We will also need to add them with the writable flag when\n- // appropriate.\n- // return i.OrderedChildren.RmDir(ctx, name, child)\n-\n- return nil\n+ return i.dentry.RemoveChildLocked(name, child)\n}\n// newEntry calls FUSE server for entry creation and allocates corresponding entry according to response.\n@@ -563,11 +558,6 @@ func (i *inode) newEntry(ctx context.Context, name string, fileType linux.FileMo\nreturn nil, syserror.EIO\n}\nchild := i.fs.newInode(out.NodeID, out.Attr)\n- if opcode == linux.FUSE_LOOKUP {\n- i.dentry.InsertChildLocked(name, child)\n- } else {\n- i.dentry.InsertChild(name, child)\n- }\nreturn child, nil\n}\n" } ]
Go
Apache License 2.0
google/gvisor
fuse: don't call dentry.InsertChild It is called from the kernfs code (OpenAt and revalidateChildLocked()). For RemoveChildLocked, it is opposed. We need to call it from fuse.RmDir and fuse.Unlink. PiperOrigin-RevId: 333453218
259,853
24.09.2020 00:47:01
25,200
0a232a5e8c846406f2fcc985d2223c8021bbef8c
test/syscall/mknod: Don't use a hard-coded file name
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/mknod.cc", "new_path": "test/syscalls/linux/mknod.cc", "diff": "@@ -105,11 +105,13 @@ TEST(MknodTest, UnimplementedTypesReturnError) {\n}\nTEST(MknodTest, Socket) {\n+ SKIP_IF(IsRunningOnGvisor() && IsRunningWithVFS1());\n+\nASSERT_THAT(chdir(GetAbsoluteTestTmpdir().c_str()), SyscallSucceeds());\n- SKIP_IF(IsRunningOnGvisor() && IsRunningWithVFS1());\n+ auto filename = NewTempRelPath();\n- ASSERT_THAT(mknod(\"./file0\", S_IFSOCK | S_IRUSR | S_IWUSR, 0),\n+ ASSERT_THAT(mknod(filename.c_str(), S_IFSOCK | S_IRUSR | S_IWUSR, 0),\nSyscallSucceeds());\nint sk;\n@@ -117,9 +119,10 @@ TEST(MknodTest, Socket) {\nFileDescriptor fd(sk);\nstruct sockaddr_un addr = {.sun_family = AF_UNIX};\n- absl::SNPrintF(addr.sun_path, sizeof(addr.sun_path), \"./file0\");\n+ absl::SNPrintF(addr.sun_path, sizeof(addr.sun_path), \"%s\", filename.c_str());\nASSERT_THAT(connect(sk, (struct sockaddr *)&addr, sizeof(addr)),\nSyscallFailsWithErrno(ECONNREFUSED));\n+ ASSERT_THAT(unlink(filename.c_str()), SyscallSucceeds());\n}\nTEST(MknodTest, Fifo) {\n" } ]
Go
Apache License 2.0
google/gvisor
test/syscall/mknod: Don't use a hard-coded file name PiperOrigin-RevId: 333461380
259,975
24.09.2020 10:29:59
25,200
c3fc69022afdbc1085c9b122a084168afa25cb80
Fix Nginx Startup and Size Benchmarks. Changes in Nginx Benchmarks in network_tests also affect Startup/Size Nginx Benchmarks. Make sure the commands line up.
[ { "change_type": "MODIFY", "old_path": "images/benchmarks/nginx/Dockerfile", "new_path": "images/benchmarks/nginx/Dockerfile", "diff": "@@ -9,3 +9,4 @@ RUN mkdir -p /local && \\\nRUN touch /local/index.html\nCOPY ./nginx.conf /etc/nginx/nginx.conf\n+COPY ./nginx_gofer.conf /etc/nginx/nginx_gofer.conf\n" }, { "change_type": "ADD", "old_path": null, "new_path": "images/benchmarks/nginx/nginx_gofer.conf", "diff": "+user nginx;\n+worker_processes 1;\n+daemon off;\n+\n+error_log /var/log/nginx/error.log warn;\n+pid /var/run/nginx.pid;\n+\n+events {\n+ worker_connections 1024;\n+}\n+\n+\n+http {\n+ server {\n+ location / {\n+ root /local;\n+ }\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/base/size_test.go", "new_path": "test/benchmarks/base/size_test.go", "diff": "@@ -105,6 +105,7 @@ func BenchmarkSizeNginx(b *testing.B) {\nmachine: machine,\nport: port,\nrunOpts: runOpts,\n+ cmd: []string{\"nginx\", \"-c\", \"/etc/nginx/nginx_gofer.conf\"},\n})\ndefer cleanUpContainers(ctx, servers)\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/base/startup_test.go", "new_path": "test/benchmarks/base/startup_test.go", "diff": "@@ -64,6 +64,7 @@ func BenchmarkStartupNginx(b *testing.B) {\nmachine: machine,\nrunOpts: runOpts,\nport: 80,\n+ cmd: []string{\"nginx\", \"-c\", \"/etc/nginx/nginx_gofer.conf\"},\n})\n}\n@@ -123,8 +124,6 @@ func redisInstance(ctx context.Context, b *testing.B, machine harness.Machine) (\n// runServerWorkload runs a server workload defined by 'runOpts' and 'cmd'.\n// 'clientMachine' is used to connect to the server on 'serverMachine'.\nfunc runServerWorkload(ctx context.Context, b *testing.B, args serverArgs) {\n- b.Helper()\n-\nb.ResetTimer()\nfor i := 0; i < b.N; i++ {\nif err := func() error {\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/network/nginx_test.go", "new_path": "test/benchmarks/network/nginx_test.go", "diff": "@@ -36,50 +36,63 @@ var nginxDocs = map[string]string{\nfunc BenchmarkNginxConcurrency(b *testing.B) {\nconcurrency := []int{1, 25, 100, 1000}\nfor _, c := range concurrency {\n- b.Run(fmt.Sprintf(\"%d\", c), func(b *testing.B) {\n+ for _, tmpfs := range []bool{true, false} {\n+ fs := \"Gofer\"\n+ if tmpfs {\n+ fs = \"Tmpfs\"\n+ }\n+ name := fmt.Sprintf(\"%d_%s\", c, fs)\n+ b.Run(name, func(b *testing.B) {\nhey := &tools.Hey{\nRequests: c * b.N,\nConcurrency: c,\nDoc: nginxDocs[\"10kb\"], // see Dockerfile '//images/benchmarks/nginx' and httpd_test.\n}\n- runNginx(b, hey, false /* reverse */)\n+ runNginx(b, hey, false /* reverse */, tmpfs /* tmpfs */)\n})\n}\n+\n+ }\n}\n// BenchmarkNginxDocSize iterates over different sized payloads, testing how\n// well the runtime handles sending different payload sizes.\nfunc BenchmarkNginxDocSize(b *testing.B) {\n- benchmarkHttpdDocSize(b, false /* reverse */)\n+ benchmarkNginxDocSize(b, false /* reverse */, true /* tmpfs */)\n+ benchmarkNginxDocSize(b, false /* reverse */, false /* tmpfs */)\n}\n// BenchmarkReverseNginxDocSize iterates over different sized payloads, testing\n// how well the runtime handles receiving different payload sizes.\nfunc BenchmarkReverseNginxDocSize(b *testing.B) {\n- benchmarkHttpdDocSize(b, true /* reverse */)\n+ benchmarkNginxDocSize(b, true /* reverse */, true /* tmpfs */)\n}\n// benchmarkNginxDocSize iterates through all doc sizes, running subbenchmarks\n// for each size.\n-func benchmarkNginxDocSize(b *testing.B, reverse bool) {\n- b.Helper()\n+func benchmarkNginxDocSize(b *testing.B, reverse, tmpfs bool) {\nfor name, filename := range nginxDocs {\nconcurrency := []int{1, 25, 50, 100, 1000}\nfor _, c := range concurrency {\n- b.Run(fmt.Sprintf(\"%s_%d\", name, c), func(b *testing.B) {\n+ fs := \"Gofer\"\n+ if tmpfs {\n+ fs = \"Tmpfs\"\n+ }\n+ benchName := fmt.Sprintf(\"%s_%d_%s\", name, c, fs)\n+ b.Run(benchName, func(b *testing.B) {\nhey := &tools.Hey{\nRequests: c * b.N,\nConcurrency: c,\nDoc: filename,\n}\n- runNginx(b, hey, reverse)\n+ runNginx(b, hey, reverse, tmpfs)\n})\n}\n}\n}\n// runNginx configures the static serving methods to run httpd.\n-func runNginx(b *testing.B, hey *tools.Hey, reverse bool) {\n+func runNginx(b *testing.B, hey *tools.Hey, reverse, tmpfs bool) {\n// nginx runs on port 80.\nport := 80\nnginxRunOpts := dockerutil.RunOpts{\n@@ -87,7 +100,11 @@ func runNginx(b *testing.B, hey *tools.Hey, reverse bool) {\nPorts: []int{port},\n}\n+ nginxCmd := []string{\"nginx\", \"-c\", \"/etc/nginx/nginx_gofer.conf\"}\n+ if tmpfs {\n+ nginxCmd = []string{\"sh\", \"-c\", \"mkdir -p /tmp/html && cp -a /local/* /tmp/html && nginx -c /etc/nginx/nginx.conf\"}\n+ }\n+\n// Command copies nginxDocs to tmpfs serving directory and runs nginx.\n- nginxCmd := []string{\"sh\", \"-c\", \"mkdir -p /tmp/html && cp -a /local/* /tmp/html && nginx\"}\nrunStaticServer(b, nginxRunOpts, nginxCmd, port, hey, reverse)\n}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/network/static_server.go", "new_path": "test/benchmarks/network/static_server.go", "diff": "@@ -25,7 +25,6 @@ import (\n// runStaticServer runs static serving workloads (httpd, nginx).\nfunc runStaticServer(b *testing.B, serverOpts dockerutil.RunOpts, serverCmd []string, port int, hey *tools.Hey, reverse bool) {\n- b.Helper()\nctx := context.Background()\n// Get two machines: a client and server.\n" } ]
Go
Apache License 2.0
google/gvisor
Fix Nginx Startup and Size Benchmarks. Changes in Nginx Benchmarks in network_tests also affect Startup/Size Nginx Benchmarks. Make sure the commands line up. PiperOrigin-RevId: 333543697
259,907
24.09.2020 13:44:25
25,200
832d91b8058c3c716c648701cf93095dd3157541
[vfs] kernfs: Do not hold reference on the inode when opening FD. The FD should hold a reference on the dentry they were opened on which in turn holds a reference on the inode it points to.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/devpts/master.go", "new_path": "pkg/sentry/fsimpl/devpts/master.go", "diff": "@@ -58,14 +58,12 @@ func (mi *masterInode) Open(ctx context.Context, rp *vfs.ResolvingPath, d *kernf\nreturn nil, err\n}\n- mi.IncRef()\nfd := &masterFileDescription{\ninode: mi,\nt: t,\n}\nfd.LockFD.Init(&mi.locks)\nif err := fd.vfsfd.Init(fd, opts.Flags, rp.Mount(), d.VFSDentry(), &vfs.FileDescriptionOptions{}); err != nil {\n- mi.DecRef(ctx)\nreturn nil, err\n}\nreturn &fd.vfsfd, nil\n@@ -106,7 +104,6 @@ var _ vfs.FileDescriptionImpl = (*masterFileDescription)(nil)\n// Release implements vfs.FileDescriptionImpl.Release.\nfunc (mfd *masterFileDescription) Release(ctx context.Context) {\nmfd.inode.root.masterClose(mfd.t)\n- mfd.inode.DecRef(ctx)\n}\n// EventRegister implements waiter.Waitable.EventRegister.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/devpts/replica.go", "new_path": "pkg/sentry/fsimpl/devpts/replica.go", "diff": "@@ -54,14 +54,12 @@ type replicaInode struct {\nvar _ kernfs.Inode = (*replicaInode)(nil)\n// Open implements kernfs.Inode.Open.\n-func (si *replicaInode) Open(ctx context.Context, rp *vfs.ResolvingPath, d *kernfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n- si.IncRef()\n+func (ri *replicaInode) Open(ctx context.Context, rp *vfs.ResolvingPath, d *kernfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\nfd := &replicaFileDescription{\n- inode: si,\n+ inode: ri,\n}\n- fd.LockFD.Init(&si.locks)\n+ fd.LockFD.Init(&ri.locks)\nif err := fd.vfsfd.Init(fd, opts.Flags, rp.Mount(), d.VFSDentry(), &vfs.FileDescriptionOptions{}); err != nil {\n- si.DecRef(ctx)\nreturn nil, err\n}\nreturn &fd.vfsfd, nil\n@@ -69,32 +67,32 @@ func (si *replicaInode) Open(ctx context.Context, rp *vfs.ResolvingPath, d *kern\n}\n// Valid implements kernfs.Inode.Valid.\n-func (si *replicaInode) Valid(context.Context) bool {\n+func (ri *replicaInode) Valid(context.Context) bool {\n// Return valid if the replica still exists.\n- si.root.mu.Lock()\n- defer si.root.mu.Unlock()\n- _, ok := si.root.replicas[si.t.n]\n+ ri.root.mu.Lock()\n+ defer ri.root.mu.Unlock()\n+ _, ok := ri.root.replicas[ri.t.n]\nreturn ok\n}\n// Stat implements kernfs.Inode.Stat.\n-func (si *replicaInode) Stat(ctx context.Context, vfsfs *vfs.Filesystem, opts vfs.StatOptions) (linux.Statx, error) {\n- statx, err := si.InodeAttrs.Stat(ctx, vfsfs, opts)\n+func (ri *replicaInode) Stat(ctx context.Context, vfsfs *vfs.Filesystem, opts vfs.StatOptions) (linux.Statx, error) {\n+ statx, err := ri.InodeAttrs.Stat(ctx, vfsfs, opts)\nif err != nil {\nreturn linux.Statx{}, err\n}\nstatx.Blksize = 1024\nstatx.RdevMajor = linux.UNIX98_PTY_REPLICA_MAJOR\n- statx.RdevMinor = si.t.n\n+ statx.RdevMinor = ri.t.n\nreturn statx, nil\n}\n// SetStat implements kernfs.Inode.SetStat\n-func (si *replicaInode) SetStat(ctx context.Context, vfsfs *vfs.Filesystem, creds *auth.Credentials, opts vfs.SetStatOptions) error {\n+func (ri *replicaInode) SetStat(ctx context.Context, vfsfs *vfs.Filesystem, creds *auth.Credentials, opts vfs.SetStatOptions) error {\nif opts.Stat.Mask&linux.STATX_SIZE != 0 {\nreturn syserror.EINVAL\n}\n- return si.InodeAttrs.SetStat(ctx, vfsfs, creds, opts)\n+ return ri.InodeAttrs.SetStat(ctx, vfsfs, creds, opts)\n}\n// +stateify savable\n@@ -109,37 +107,35 @@ type replicaFileDescription struct {\nvar _ vfs.FileDescriptionImpl = (*replicaFileDescription)(nil)\n// Release implements fs.FileOperations.Release.\n-func (sfd *replicaFileDescription) Release(ctx context.Context) {\n- sfd.inode.DecRef(ctx)\n-}\n+func (rfd *replicaFileDescription) Release(ctx context.Context) {}\n// EventRegister implements waiter.Waitable.EventRegister.\n-func (sfd *replicaFileDescription) EventRegister(e *waiter.Entry, mask waiter.EventMask) {\n- sfd.inode.t.ld.replicaWaiter.EventRegister(e, mask)\n+func (rfd *replicaFileDescription) EventRegister(e *waiter.Entry, mask waiter.EventMask) {\n+ rfd.inode.t.ld.replicaWaiter.EventRegister(e, mask)\n}\n// EventUnregister implements waiter.Waitable.EventUnregister.\n-func (sfd *replicaFileDescription) EventUnregister(e *waiter.Entry) {\n- sfd.inode.t.ld.replicaWaiter.EventUnregister(e)\n+func (rfd *replicaFileDescription) EventUnregister(e *waiter.Entry) {\n+ rfd.inode.t.ld.replicaWaiter.EventUnregister(e)\n}\n// Readiness implements waiter.Waitable.Readiness.\n-func (sfd *replicaFileDescription) Readiness(mask waiter.EventMask) waiter.EventMask {\n- return sfd.inode.t.ld.replicaReadiness()\n+func (rfd *replicaFileDescription) Readiness(mask waiter.EventMask) waiter.EventMask {\n+ return rfd.inode.t.ld.replicaReadiness()\n}\n// Read implements vfs.FileDescriptionImpl.Read.\n-func (sfd *replicaFileDescription) Read(ctx context.Context, dst usermem.IOSequence, _ vfs.ReadOptions) (int64, error) {\n- return sfd.inode.t.ld.inputQueueRead(ctx, dst)\n+func (rfd *replicaFileDescription) Read(ctx context.Context, dst usermem.IOSequence, _ vfs.ReadOptions) (int64, error) {\n+ return rfd.inode.t.ld.inputQueueRead(ctx, dst)\n}\n// Write implements vfs.FileDescriptionImpl.Write.\n-func (sfd *replicaFileDescription) Write(ctx context.Context, src usermem.IOSequence, _ vfs.WriteOptions) (int64, error) {\n- return sfd.inode.t.ld.outputQueueWrite(ctx, src)\n+func (rfd *replicaFileDescription) Write(ctx context.Context, src usermem.IOSequence, _ vfs.WriteOptions) (int64, error) {\n+ return rfd.inode.t.ld.outputQueueWrite(ctx, src)\n}\n// Ioctl implements vfs.FileDescriptionImpl.Ioctl.\n-func (sfd *replicaFileDescription) Ioctl(ctx context.Context, io usermem.IO, args arch.SyscallArguments) (uintptr, error) {\n+func (rfd *replicaFileDescription) Ioctl(ctx context.Context, io usermem.IO, args arch.SyscallArguments) (uintptr, error) {\nt := kernel.TaskFromContext(ctx)\nif t == nil {\n// ioctl(2) may only be called from a task goroutine.\n@@ -149,35 +145,35 @@ func (sfd *replicaFileDescription) Ioctl(ctx context.Context, io usermem.IO, arg\nswitch cmd := args[1].Uint(); cmd {\ncase linux.FIONREAD: // linux.FIONREAD == linux.TIOCINQ\n// Get the number of bytes in the input queue read buffer.\n- return 0, sfd.inode.t.ld.inputQueueReadSize(t, io, args)\n+ return 0, rfd.inode.t.ld.inputQueueReadSize(t, io, args)\ncase linux.TCGETS:\n- return sfd.inode.t.ld.getTermios(t, args)\n+ return rfd.inode.t.ld.getTermios(t, args)\ncase linux.TCSETS:\n- return sfd.inode.t.ld.setTermios(t, args)\n+ return rfd.inode.t.ld.setTermios(t, args)\ncase linux.TCSETSW:\n// TODO(b/29356795): This should drain the output queue first.\n- return sfd.inode.t.ld.setTermios(t, args)\n+ return rfd.inode.t.ld.setTermios(t, args)\ncase linux.TIOCGPTN:\n- nP := primitive.Uint32(sfd.inode.t.n)\n+ nP := primitive.Uint32(rfd.inode.t.n)\n_, err := nP.CopyOut(t, args[2].Pointer())\nreturn 0, err\ncase linux.TIOCGWINSZ:\n- return 0, sfd.inode.t.ld.windowSize(t, args)\n+ return 0, rfd.inode.t.ld.windowSize(t, args)\ncase linux.TIOCSWINSZ:\n- return 0, sfd.inode.t.ld.setWindowSize(t, args)\n+ return 0, rfd.inode.t.ld.setWindowSize(t, args)\ncase linux.TIOCSCTTY:\n// Make the given terminal the controlling terminal of the\n// calling process.\n- return 0, sfd.inode.t.setControllingTTY(ctx, args, false /* isMaster */)\n+ return 0, rfd.inode.t.setControllingTTY(ctx, args, false /* isMaster */)\ncase linux.TIOCNOTTY:\n// Release this process's controlling terminal.\n- return 0, sfd.inode.t.releaseControllingTTY(ctx, args, false /* isMaster */)\n+ return 0, rfd.inode.t.releaseControllingTTY(ctx, args, false /* isMaster */)\ncase linux.TIOCGPGRP:\n// Get the foreground process group.\n- return sfd.inode.t.foregroundProcessGroup(ctx, args, false /* isMaster */)\n+ return rfd.inode.t.foregroundProcessGroup(ctx, args, false /* isMaster */)\ncase linux.TIOCSPGRP:\n// Set the foreground process group.\n- return sfd.inode.t.setForegroundProcessGroup(ctx, args, false /* isMaster */)\n+ return rfd.inode.t.setForegroundProcessGroup(ctx, args, false /* isMaster */)\ndefault:\nmaybeEmitUnimplementedEvent(ctx, cmd)\nreturn 0, syserror.ENOTTY\n@@ -185,24 +181,24 @@ func (sfd *replicaFileDescription) Ioctl(ctx context.Context, io usermem.IO, arg\n}\n// SetStat implements vfs.FileDescriptionImpl.SetStat.\n-func (sfd *replicaFileDescription) SetStat(ctx context.Context, opts vfs.SetStatOptions) error {\n+func (rfd *replicaFileDescription) SetStat(ctx context.Context, opts vfs.SetStatOptions) error {\ncreds := auth.CredentialsFromContext(ctx)\n- fs := sfd.vfsfd.VirtualDentry().Mount().Filesystem()\n- return sfd.inode.SetStat(ctx, fs, creds, opts)\n+ fs := rfd.vfsfd.VirtualDentry().Mount().Filesystem()\n+ return rfd.inode.SetStat(ctx, fs, creds, opts)\n}\n// Stat implements vfs.FileDescriptionImpl.Stat.\n-func (sfd *replicaFileDescription) Stat(ctx context.Context, opts vfs.StatOptions) (linux.Statx, error) {\n- fs := sfd.vfsfd.VirtualDentry().Mount().Filesystem()\n- return sfd.inode.Stat(ctx, fs, opts)\n+func (rfd *replicaFileDescription) Stat(ctx context.Context, opts vfs.StatOptions) (linux.Statx, error) {\n+ fs := rfd.vfsfd.VirtualDentry().Mount().Filesystem()\n+ return rfd.inode.Stat(ctx, fs, opts)\n}\n// LockPOSIX implements vfs.FileDescriptionImpl.LockPOSIX.\n-func (sfd *replicaFileDescription) LockPOSIX(ctx context.Context, uid fslock.UniqueID, t fslock.LockType, start, length uint64, whence int16, block fslock.Blocker) error {\n- return sfd.Locks().LockPOSIX(ctx, &sfd.vfsfd, uid, t, start, length, whence, block)\n+func (rfd *replicaFileDescription) LockPOSIX(ctx context.Context, uid fslock.UniqueID, t fslock.LockType, start, length uint64, whence int16, block fslock.Blocker) error {\n+ return rfd.Locks().LockPOSIX(ctx, &rfd.vfsfd, uid, t, start, length, whence, block)\n}\n// UnlockPOSIX implements vfs.FileDescriptionImpl.UnlockPOSIX.\n-func (sfd *replicaFileDescription) UnlockPOSIX(ctx context.Context, uid fslock.UniqueID, start, length uint64, whence int16) error {\n- return sfd.Locks().UnlockPOSIX(ctx, &sfd.vfsfd, uid, start, length, whence)\n+func (rfd *replicaFileDescription) UnlockPOSIX(ctx context.Context, uid fslock.UniqueID, start, length uint64, whence int16) error {\n+ return rfd.Locks().UnlockPOSIX(ctx, &rfd.vfsfd, uid, start, length, whence)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "diff": "@@ -132,7 +132,8 @@ func (fs *Filesystem) revalidateChildLocked(ctx context.Context, vfsObj *vfs.Vir\nif err != nil {\nreturn nil, err\n}\n- // Reference on childVFSD dropped by a corresponding Valid.\n+ // Reference on c (provided by Lookup) will be dropped when the dentry\n+ // fails validation.\nparent.InsertChildLocked(name, c)\nchild = c\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/kernfs.go", "new_path": "pkg/sentry/fsimpl/kernfs/kernfs.go", "diff": "@@ -350,7 +350,7 @@ type Inode interface {\n// Open creates a file description for the filesystem object represented by\n// this inode. The returned file description should hold a reference on the\n- // inode for its lifetime.\n+ // dentry for its lifetime.\n//\n// Precondition: rp.Done(). vfsd.Impl() must be the kernfs Dentry containing\n// the inode on which Open() is being called.\n" } ]
Go
Apache License 2.0
google/gvisor
[vfs] kernfs: Do not hold reference on the inode when opening FD. The FD should hold a reference on the dentry they were opened on which in turn holds a reference on the inode it points to. PiperOrigin-RevId: 333589223