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,868 | 23.05.2022 17:46:56 | 25,200 | 6a922404e7832a7ea81373ac3e525b9ac9f9a4bd | Default Docker image: Add kmod package. | [
{
"change_type": "MODIFY",
"old_path": "images/default/Dockerfile",
"new_path": "images/default/Dockerfile",
"diff": "@@ -7,7 +7,7 @@ RUN apt-get update && apt-get install -y curl gnupg2 git \\\nopenjdk-11-jdk-headless zip unzip \\\napt-transport-https ca-certificates gnupg-agent \\\nsoftware-properties-common \\\n- pkg-config libffi-dev patch diffutils libssl-dev iptables\n+ pkg-config libffi-dev patch diffutils libssl-dev iptables kmod\n# Install Docker client for the website build.\nRUN curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -\n"
}
] | Go | Apache License 2.0 | google/gvisor | Default Docker image: Add kmod package.
PiperOrigin-RevId: 450564818 |
259,868 | 23.05.2022 19:09:10 | 25,200 | a6fbca2eec789ed5ca0704eb0816021ead957902 | `yaml_test`: Add argument to allow non-strict YAML decoding. | [
{
"change_type": "MODIFY",
"old_path": "tools/yamltest/defs.bzl",
"new_path": "tools/yamltest/defs.bzl",
"diff": "@@ -6,9 +6,10 @@ def _yaml_test_impl(ctx):\nctx.actions.write(runner, \"\\n\".join([\n\"#!/bin/bash\",\n\"set -euo pipefail\",\n- \"%s -schema=%s -- %s\" % (\n+ \"%s -schema=%s -strict=%s -- %s\" % (\nctx.files._tool[0].short_path,\nctx.files.schema[0].short_path,\n+ \"true\" if ctx.attr.strict else \"false\",\n\" \".join([f.short_path for f in ctx.files.srcs]),\n),\n]), is_executable = True)\n@@ -31,6 +32,11 @@ yaml_test = rule(\nallow_single_file = True,\nmandatory = True,\n),\n+ \"strict\": attr.bool(\n+ doc = \"Whether to use strict mode for YAML decoding.\",\n+ mandatory = False,\n+ default = True,\n+ ),\n\"_tool\": attr.label(\nexecutable = True,\ncfg = \"host\",\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/yamltest/main.go",
"new_path": "tools/yamltest/main.go",
"diff": "@@ -26,6 +26,11 @@ import (\nyaml \"gopkg.in/yaml.v2\"\n)\n+var (\n+ schema = flag.String(\"schema\", \"\", \"path to JSON schema file.\")\n+ strict = flag.Bool(\"strict\", true, \"Whether to enable strict mode for YAML decoding\")\n+)\n+\nfunc fixup(v interface{}) (interface{}, error) {\nswitch x := v.(type) {\ncase map[interface{}]interface{}:\n@@ -65,7 +70,7 @@ func loadFile(filename string) (gojsonschema.JSONLoader, error) {\n}\ndefer f.Close()\ndec := yaml.NewDecoder(f)\n- dec.SetStrict(true)\n+ dec.SetStrict(*strict)\nvar object interface{}\nif err := dec.Decode(&object); err != nil {\nreturn nil, err\n@@ -81,8 +86,6 @@ func loadFile(filename string) (gojsonschema.JSONLoader, error) {\nreturn gojsonschema.NewStringLoader(string(bytes)), nil\n}\n-var schema = flag.String(\"schema\", \"\", \"path to JSON schema file.\")\n-\nfunc main() {\nflag.Parse()\nif *schema == \"\" || len(flag.Args()) == 0 {\n"
}
] | Go | Apache License 2.0 | google/gvisor | `yaml_test`: Add argument to allow non-strict YAML decoding.
PiperOrigin-RevId: 450576605 |
259,985 | 24.05.2022 14:44:11 | 25,200 | edf123719cc4f2d60520ecf33f3de54ae9857d31 | cgroupfs: Implement named hierarchies. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/base.go",
"new_path": "pkg/sentry/fsimpl/cgroupfs/base.go",
"diff": "@@ -203,10 +203,16 @@ func (fs *filesystem) newCgroupInode(ctx context.Context, creds *auth.Credential\nreturn c\n}\n+// HierarchyID implements kernel.CgroupImpl.HierarchyID.\nfunc (c *cgroupInode) HierarchyID() uint32 {\nreturn c.fs.hierarchyID\n}\n+// Name implements kernel.CgroupImpl.Name.\n+func (c *cgroupInode) Name() string {\n+ return c.fs.hierarchyName\n+}\n+\n// Controllers implements kernel.CgroupImpl.Controllers.\nfunc (c *cgroupInode) Controllers() []kernel.CgroupController {\nreturn c.fs.kcontrollers\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/cgroupfs.go",
"new_path": "pkg/sentry/fsimpl/cgroupfs/cgroupfs.go",
"diff": "@@ -149,6 +149,12 @@ type filesystem struct {\n// hierarchyID is immutable after initialization.\nhierarchyID uint32\n+ // hierarchyName is the name for a named hierarchy. May be empty if the\n+ // 'name=' mount option was not used when the hierarchy was created.\n+ //\n+ // Immutable after initialization.\n+ hierarchyName string\n+\n// controllers and kcontrollers are both the list of controllers attached to\n// this cgroupfs. Both lists are the same set of controllers, but typecast\n// to different interfaces for convenience. Both must stay in sync, and are\n@@ -236,11 +242,39 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nwantControllers = allControllers\n}\n- if len(wantControllers) == 0 {\n- // Specifying no controllers implies all controllers.\n+ var name string\n+ var ok bool\n+ if name, ok = mopts[\"name\"]; ok {\n+ delete(mopts, \"name\")\n+ }\n+\n+ var none bool\n+ if _, ok = mopts[\"none\"]; ok {\n+ none = true\n+ delete(mopts, \"none\")\n+ }\n+\n+ if !none && len(wantControllers) == 0 {\n+ // Specifying no controllers implies all controllers, unless \"none\" was\n+ // explicitly requested.\nwantControllers = allControllers\n}\n+ // Some combinations of \"none\", \"all\", \"name=\" and explicit controllers are\n+ // not allowed. See Linux, kernel/cgroup.c:parse_cgroupfs_options().\n+\n+ // All empty hierarchies must have a name.\n+ if len(wantControllers) == 0 && name == \"\" {\n+ ctx.Debugf(\"cgroupfs.FilesystemType.GetFilesystem: empty hierarchy with no name\")\n+ return nil, nil, linuxerr.EINVAL\n+ }\n+\n+ // Can't have \"none\" and some controllers.\n+ if none && len(wantControllers) != 0 {\n+ ctx.Debugf(\"cgroupfs.FilesystemType.GetFilesystem: 'none' specified with controllers: %v\", wantControllers)\n+ return nil, nil, linuxerr.EINVAL\n+ }\n+\nif len(mopts) != 0 {\nctx.Debugf(\"cgroupfs.FilesystemType.GetFilesystem: unknown options: %v\", mopts)\nreturn nil, nil, linuxerr.EINVAL\n@@ -259,7 +293,11 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\n//\n// Note: we're guaranteed to have at least one requested controller, since\n// no explicit controller name implies all controllers.\n- if vfsfs := r.FindHierarchy(wantControllers); vfsfs != nil {\n+ vfsfs, err := r.FindHierarchy(name, wantControllers)\n+ if err != nil {\n+ return nil, nil, err\n+ }\n+ if vfsfs != nil {\nfs := vfsfs.Impl().(*filesystem)\nctx.Debugf(\"cgroupfs.FilesystemType.GetFilesystem: mounting new view to hierarchy %v\", fs.hierarchyID)\nfs.root.IncRef()\n@@ -276,6 +314,7 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\n// the new hierarchy later.\nfs := &filesystem{\ndevMinor: devMinor,\n+ hierarchyName: name,\n}\nfs.MaxCachedDentries = maxCachedDentries\nfs.VFSFilesystem().Init(vfsObj, &fsType, fs)\n@@ -337,7 +376,7 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\n// Register controllers. The registry may be modified concurrently, so if we\n// get an error, we raced with someone else who registered the same\n// controllers first.\n- if err := r.Register(fs.kcontrollers, fs); err != nil {\n+ if err := r.Register(name, fs.kcontrollers, fs); err != nil {\nctx.Infof(\"cgroupfs.FilesystemType.GetFilesystem: failed to register new hierarchy with controllers %v: %v\", wantControllers, err)\nrootD.DecRef(ctx)\nfs.VFSFilesystem().DecRef(ctx)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/cgroup.go",
"new_path": "pkg/sentry/kernel/cgroup.go",
"diff": "@@ -21,6 +21,8 @@ import (\n\"gvisor.dev/gvisor/pkg/atomicbitops\"\n\"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n+ \"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n)\n@@ -101,12 +103,6 @@ func (c *Cgroup) Path() string {\nreturn c.FSLocalPath()\n}\n-// HierarchyID returns the id of the hierarchy that contains this cgroup.\n-func (c *Cgroup) HierarchyID() uint32 {\n- // Note: a cgroup is guaranteed to have at least one controller.\n- return c.Controllers()[0].HierarchyID()\n-}\n-\n// CgroupMigrationContext represents an in-flight cgroup migration for\n// a single task.\ntype CgroupMigrationContext struct {\n@@ -137,6 +133,13 @@ type CgroupImpl interface {\n// Controllers lists the controller associated with this cgroup.\nControllers() []CgroupController\n+ // HierarchyID returns the id of the hierarchy that contains this cgroup.\n+ HierarchyID() uint32\n+\n+ // Name returns the name for this cgroup, if any. If no name was provided\n+ // when the hierarchy was created, returns \"\".\n+ Name() string\n+\n// Enter moves t into this cgroup.\nEnter(t *Task)\n@@ -175,6 +178,7 @@ type CgroupImpl interface {\n// +stateify savable\ntype hierarchy struct {\nid uint32\n+ name string\n// These are a subset of the controllers in CgroupRegistry.controllers,\n// grouped here by hierarchy for conveninent lookup.\ncontrollers map[CgroupControllerType]CgroupController\n@@ -220,21 +224,29 @@ type CgroupRegistry struct {\nmu cgroupMutex `state:\"nosave\"`\n// controllers is the set of currently known cgroup controllers on the\n- // system. Protected by mu.\n+ // system.\n//\n// +checklocks:mu\ncontrollers map[CgroupControllerType]CgroupController\n- // hierarchies is the active set of cgroup hierarchies. Protected by mu.\n+ // hierarchies is the active set of cgroup hierarchies. This contains all\n+ // hierarchies on the system.\n//\n// +checklocks:mu\nhierarchies map[uint32]hierarchy\n+\n+ // hierarchiesByName is a map of named hierarchies. Only named hierarchies\n+ // are tracked on this map.\n+ //\n+ // +checklocks:mu\n+ hierarchiesByName map[string]hierarchy\n}\nfunc newCgroupRegistry() *CgroupRegistry {\nreturn &CgroupRegistry{\ncontrollers: make(map[CgroupControllerType]CgroupController),\nhierarchies: make(map[uint32]hierarchy),\n+ hierarchiesByName: make(map[string]hierarchy),\n}\n}\n@@ -247,13 +259,36 @@ func (r *CgroupRegistry) nextHierarchyID() (uint32, error) {\n}\n// FindHierarchy returns a cgroup filesystem containing exactly the set of\n-// controllers named in names. If no such FS is found, FindHierarchy return\n-// nil. FindHierarchy takes a reference on the returned FS, which is transferred\n-// to the caller.\n-func (r *CgroupRegistry) FindHierarchy(ctypes []CgroupControllerType) *vfs.Filesystem {\n+// controllers named in ctypes, and optionally the name specified in name if it\n+// isn't empty. If no such FS is found, FindHierarchy return nil. FindHierarchy\n+// takes a reference on the returned FS, which is transferred to the caller.\n+func (r *CgroupRegistry) FindHierarchy(name string, ctypes []CgroupControllerType) (*vfs.Filesystem, error) {\nr.mu.Lock()\ndefer r.mu.Unlock()\n+ // If we have a hierarchy name, lookup by name.\n+ if name != \"\" {\n+ h, ok := r.hierarchiesByName[name]\n+ if !ok {\n+ // Name not found.\n+ return nil, nil\n+ }\n+\n+ if h.match(ctypes) {\n+ if !h.fs.TryIncRef() {\n+ // May be racing with filesystem destruction, see below.\n+ r.unregisterLocked(h.id)\n+ return nil, nil\n+ }\n+ return h.fs, nil\n+ }\n+\n+ // Name matched, but controllers didn't. Fail per linux\n+ // kernel/cgroup.c:cgroup_mount().\n+ log.Debugf(\"cgroupfs: Registry lookup for name=%s controllers=%v failed; named matched but controllers didn't (have controllers=%v)\", name, ctypes, h.controllers)\n+ return nil, linuxerr.EBUSY\n+ }\n+\nfor _, h := range r.hierarchies {\nif h.match(ctypes) {\nif !h.fs.TryIncRef() {\n@@ -272,25 +307,25 @@ func (r *CgroupRegistry) FindHierarchy(ctypes []CgroupControllerType) *vfs.Files\n// dying hierarchy now. The eventual unregister by the FS\n// teardown will become a no-op.\nr.unregisterLocked(h.id)\n- return nil\n+ return nil, nil\n}\n- return h.fs\n+ return h.fs, nil\n}\n}\n- return nil\n+ return nil, nil\n}\n// Register registers the provided set of controllers with the registry as a new\n// hierarchy. If any controller is already registered, the function returns an\n// error without modifying the registry. Register sets the hierarchy ID for the\n// filesystem on success.\n-func (r *CgroupRegistry) Register(cs []CgroupController, fs cgroupFS) error {\n+func (r *CgroupRegistry) Register(name string, cs []CgroupController, fs cgroupFS) error {\nr.mu.Lock()\ndefer r.mu.Unlock()\n- if len(cs) == 0 {\n- return fmt.Errorf(\"can't register hierarchy with no controllers\")\n+ if name == \"\" && len(cs) == 0 {\n+ return fmt.Errorf(\"can't register hierarchy with both no controllers and no name\")\n}\nfor _, c := range cs {\n@@ -299,6 +334,10 @@ func (r *CgroupRegistry) Register(cs []CgroupController, fs cgroupFS) error {\n}\n}\n+ if _, ok := r.hierarchiesByName[name]; name != \"\" && ok {\n+ return fmt.Errorf(\"hierarchy named %q already exists\", name)\n+ }\n+\nhid, err := r.nextHierarchyID()\nif err != nil {\nreturn err\n@@ -310,6 +349,7 @@ func (r *CgroupRegistry) Register(cs []CgroupController, fs cgroupFS) error {\nh := hierarchy{\nid: hid,\n+ name: name,\ncontrollers: make(map[CgroupControllerType]CgroupController),\nfs: fs.VFSFilesystem(),\n}\n@@ -319,6 +359,9 @@ func (r *CgroupRegistry) Register(cs []CgroupController, fs cgroupFS) error {\nh.controllers[n] = c\n}\nr.hierarchies[hid] = h\n+ if name != \"\" {\n+ r.hierarchiesByName[name] = h\n+ }\nreturn nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_cgroup.go",
"new_path": "pkg/sentry/kernel/task_cgroup.go",
"diff": "@@ -194,14 +194,22 @@ func (t *Task) GenerateProcTaskCgroup(buf *bytes.Buffer) {\nfor c := range t.cgroups {\nctls := c.Controllers()\nctlNames := make([]string, 0, len(ctls))\n+\n+ // We're guaranteed to have a valid name, a non-empty controller list,\n+ // or both.\n+\n+ // Explicit hierachy name, if any.\n+ if name := c.Name(); name != \"\" {\n+ ctlNames = append(ctlNames, fmt.Sprintf(\"name=%s\", name))\n+ }\n+\n+ // Controllers attached to this hierarchy, if any.\nfor _, ctl := range ctls {\nctlNames = append(ctlNames, string(ctl.Type()))\n}\ncgEntries = append(cgEntries, taskCgroupEntry{\n- // Note: We're guaranteed to have at least one controller, and all\n- // controllers are guaranteed to be on the same hierarchy.\n- hierarchyID: ctls[0].HierarchyID(),\n+ hierarchyID: c.HierarchyID(),\ncontrollers: strings.Join(ctlNames, \",\"),\npath: c.Path(),\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/cgroup.cc",
"new_path": "test/syscalls/linux/cgroup.cc",
"diff": "@@ -585,6 +585,48 @@ TEST(Cgroup, TIDZeroMovesSelf) {\nEXPECT_FALSE(tasks.contains(syscall(SYS_gettid)));\n}\n+TEST(Cgroup, NamedHierarchies) {\n+ SKIP_IF(!CgroupsAvailable());\n+\n+ Mounter m(ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir()));\n+ Cgroup c1 = ASSERT_NO_ERRNO_AND_VALUE(m.MountCgroupfs(\"none,name=h1\"));\n+ Cgroup c2 = ASSERT_NO_ERRNO_AND_VALUE(m.MountCgroupfs(\"name=h2,cpu\"));\n+\n+ // Check that /proc/<pid>/cgroup contains an entry for this task.\n+ absl::flat_hash_map<std::string, PIDCgroupEntry> entries =\n+ ASSERT_NO_ERRNO_AND_VALUE(ProcPIDCgroupEntries(getpid()));\n+ EXPECT_TRUE(entries.contains(\"name=h1\"));\n+ EXPECT_TRUE(entries.contains(\"name=h2,cpu\"));\n+ EXPECT_NO_ERRNO(c1.ContainsCallingProcess());\n+ EXPECT_NO_ERRNO(c2.ContainsCallingProcess());\n+}\n+\n+TEST(Cgroup, NoneExclusiveWithAnyController) {\n+ SKIP_IF(!CgroupsAvailable());\n+\n+ Mounter m(ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir()));\n+ EXPECT_THAT(m.MountCgroupfs(\"none,cpu\"), PosixErrorIs(EINVAL, _));\n+}\n+\n+TEST(Cgroup, EmptyHierarchyMustHaveName) {\n+ SKIP_IF(!CgroupsAvailable());\n+\n+ Mounter m(ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir()));\n+ // This will fail since it is an empty hierarchy with no name.\n+ EXPECT_THAT(m.MountCgroupfs(\"none\"), PosixErrorIs(EINVAL, _));\n+}\n+\n+TEST(Cgroup, NameMatchButControllersDont) {\n+ SKIP_IF(!CgroupsAvailable());\n+\n+ Mounter m(ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir()));\n+ Cgroup c1 = ASSERT_NO_ERRNO_AND_VALUE(m.MountCgroupfs(\"none,name=h1\"));\n+ Cgroup c2 = ASSERT_NO_ERRNO_AND_VALUE(m.MountCgroupfs(\"name=h2,memory\"));\n+\n+ EXPECT_THAT(m.MountCgroupfs(\"name=h1,memory\"), PosixErrorIs(EBUSY, _));\n+ EXPECT_THAT(m.MountCgroupfs(\"name=h2,cpu\"), PosixErrorIs(EBUSY, _));\n+}\n+\nTEST(MemoryCgroup, MemoryUsageInBytes) {\nSKIP_IF(!CgroupsAvailable());\n"
}
] | Go | Apache License 2.0 | google/gvisor | cgroupfs: Implement named hierarchies.
PiperOrigin-RevId: 450773348 |
259,907 | 24.05.2022 15:57:00 | 25,200 | b274736ac7ee604a5ec8b834c6cad0a621bb0e2e | Add support for /prod/[pid]/fd to trace procfs.
On Linux, /proc/[pid]/fd/ entries are symlinks with name
as FD number and target as the file path.
runsc trace procfs will return the FD numbers and their
corresponding file paths for each process.
Updates | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/procfs/dump.go",
"new_path": "runsc/boot/procfs/dump.go",
"diff": "@@ -29,6 +29,14 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n)\n+// FDInfo contains information about an application file descriptor.\n+type FDInfo struct {\n+ // Number is the FD number.\n+ Number int32 `json:\"number,omitempty\"`\n+ // Path is the path of the file that FD represents.\n+ Path string `json:\"path,omitempty\"`\n+}\n+\n// ProcessProcfsDump contains the procfs dump for one process.\ntype ProcessProcfsDump struct {\n// PID is the process ID.\n@@ -41,6 +49,9 @@ type ProcessProcfsDump struct {\nEnv []string `json:\"env,omitempty\"`\n// CWD is the symlink target of /proc/[pid]/cwd.\nCWD string `json:\"cwd,omitempty\"`\n+ // FDs contains the directory entries of /proc/[pid]/fd and also contains the\n+ // symlink target for each FD.\n+ FDs []FDInfo `json:\"fdlist,omitempty\"`\n}\n// getMM returns t's MemoryManager. On success, the MemoryManager's users count\n@@ -102,6 +113,46 @@ func getCWD(ctx context.Context, t *kernel.Task, pid kernel.ThreadID) string {\nreturn name\n}\n+func getFDs(ctx context.Context, t *kernel.Task, pid kernel.ThreadID) []FDInfo {\n+ type fdInfo struct {\n+ fd *vfs.FileDescription\n+ no int32\n+ }\n+ var fds []fdInfo\n+ defer func() {\n+ for _, fd := range fds {\n+ fd.fd.DecRef(ctx)\n+ }\n+ }()\n+\n+ t.WithMuLocked(func(t *kernel.Task) {\n+ if fdTable := t.FDTable(); fdTable != nil {\n+ fdNos := fdTable.GetFDs(ctx)\n+ fds = make([]fdInfo, 0, len(fdNos))\n+ for _, fd := range fdNos {\n+ file, _ := fdTable.GetVFS2(fd)\n+ if file != nil {\n+ fds = append(fds, fdInfo{fd: file, no: fd})\n+ }\n+ }\n+ }\n+ })\n+\n+ root := vfs.RootFromContext(ctx)\n+ defer root.DecRef(ctx)\n+\n+ res := make([]FDInfo, 0, len(fds))\n+ for _, fd := range fds {\n+ path, err := t.Kernel().VFS().PathnameWithDeleted(ctx, root, fd.fd.VirtualDentry())\n+ if err != nil {\n+ log.Warningf(\"PathnameWithDeleted failed to find path for fd %d in PID %s: %v\", fd.no, pid, err)\n+ path = \"\"\n+ }\n+ res = append(res, FDInfo{Number: fd.no, Path: path})\n+ }\n+ return res\n+}\n+\n// Dump returns a procfs dump for process pid. t must be a task in process pid.\nfunc Dump(t *kernel.Task, pid kernel.ThreadID) (ProcessProcfsDump, error) {\nctx := t.AsyncContext()\n@@ -118,5 +169,6 @@ func Dump(t *kernel.Task, pid kernel.ThreadID) (ProcessProcfsDump, error) {\nArgs: getMetadataArray(ctx, pid, mm, proc.Cmdline),\nEnv: getMetadataArray(ctx, pid, mm, proc.Environ),\nCWD: getCWD(ctx, t, pid),\n+ FDs: getFDs(ctx, t, pid),\n}, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/trace_test.go",
"new_path": "runsc/container/trace_test.go",
"diff": "@@ -365,4 +365,18 @@ func TestProcfsDump(t *testing.T) {\nif spec.Process.Cwd != procfsDump[0].CWD {\nt.Errorf(\"expected CWD %q, got %q\", spec.Process.Cwd, procfsDump[0].CWD)\n}\n+\n+ // Expect 3 host FDs for stdout, stdin and stderr.\n+ if len(procfsDump[0].FDs) != 3 {\n+ t.Errorf(\"expected 3 FDs for the sleep process, got %+v\", procfsDump[0].FDs)\n+ } else {\n+ for i, fd := range procfsDump[0].FDs {\n+ if want := int32(i); fd.Number != want {\n+ t.Errorf(\"expected FD number %d, got %d\", want, fd.Number)\n+ }\n+ if wantSubStr := \"host\"; !strings.Contains(fd.Path, wantSubStr) {\n+ t.Errorf(\"expected FD path to contain %q, got %q\", wantSubStr, fd.Path)\n+ }\n+ }\n+ }\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add support for /prod/[pid]/fd to trace procfs.
On Linux, /proc/[pid]/fd/ entries are symlinks with name
as FD number and target as the file path.
runsc trace procfs will return the FD numbers and their
corresponding file paths for each process.
Updates #4805
PiperOrigin-RevId: 450788929 |
259,907 | 24.05.2022 16:40:13 | 25,200 | 0ad98ee0e8426830c79c46787ac9ea0d6c5623ff | Add support for process start time to trace procfs.
Added test for this.
Updates | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/procfs/dump.go",
"new_path": "runsc/boot/procfs/dump.go",
"diff": "@@ -52,6 +52,8 @@ type ProcessProcfsDump struct {\n// FDs contains the directory entries of /proc/[pid]/fd and also contains the\n// symlink target for each FD.\nFDs []FDInfo `json:\"fdlist,omitempty\"`\n+ // StartTime is the process start time in nanoseconds since Unix epoch.\n+ StartTime int64 `json:\"clone_ts,omitempty\"`\n}\n// getMM returns t's MemoryManager. On success, the MemoryManager's users count\n@@ -170,5 +172,6 @@ func Dump(t *kernel.Task, pid kernel.ThreadID) (ProcessProcfsDump, error) {\nEnv: getMetadataArray(ctx, pid, mm, proc.Environ),\nCWD: getCWD(ctx, t, pid),\nFDs: getFDs(ctx, t, pid),\n+ StartTime: t.StartTime().Nanoseconds(),\n}, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/trace_test.go",
"new_path": "runsc/container/trace_test.go",
"diff": "@@ -324,6 +324,7 @@ func TestProcfsDump(t *testing.T) {\nt.Fatalf(\"error starting container: %v\", err)\n}\n+ startTime := time.Now().UnixNano()\nprocfsDump, err := cont.Sandbox.ProcfsDump()\nif err != nil {\nt.Fatalf(\"ProcfsDump() failed: %v\", err)\n@@ -379,4 +380,11 @@ func TestProcfsDump(t *testing.T) {\n}\n}\n}\n+\n+ // Start time should be at most 3 second away from our locally calculated\n+ // start time. Local startTime was calculated after container started, so\n+ // process start time must be earlier than local startTime.\n+ if startTime-procfsDump[0].StartTime > 3*time.Second.Nanoseconds() {\n+ t.Errorf(\"wanted start time to be around %s, but got %s\", time.Unix(0, startTime), time.Unix(0, procfsDump[0].StartTime))\n+ }\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add support for process start time to trace procfs.
Added test for this.
Updates #4805
PiperOrigin-RevId: 450797692 |
259,907 | 24.05.2022 22:45:42 | 25,200 | f7d57e9746192459f6d1e1411bed5ccc32cdfb3c | Add support for /proc/[pid]/root to trace procfs.
Updates | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/procfs/dump.go",
"new_path": "runsc/boot/procfs/dump.go",
"diff": "@@ -37,7 +37,8 @@ type FDInfo struct {\nPath string `json:\"path,omitempty\"`\n}\n-// ProcessProcfsDump contains the procfs dump for one process.\n+// ProcessProcfsDump contains the procfs dump for one process. For more details\n+// on fields that directly correspond to /proc fields, see proc(5).\ntype ProcessProcfsDump struct {\n// PID is the process ID.\nPID int32 `json:\"pid,omitempty\"`\n@@ -54,6 +55,8 @@ type ProcessProcfsDump struct {\nFDs []FDInfo `json:\"fdlist,omitempty\"`\n// StartTime is the process start time in nanoseconds since Unix epoch.\nStartTime int64 `json:\"clone_ts,omitempty\"`\n+ // Root is /proc/[pid]/root.\n+ Root string `json:\"root,omitempty\"`\n}\n// getMM returns t's MemoryManager. On success, the MemoryManager's users count\n@@ -155,6 +158,18 @@ func getFDs(ctx context.Context, t *kernel.Task, pid kernel.ThreadID) []FDInfo {\nreturn res\n}\n+func getRoot(t *kernel.Task, pid kernel.ThreadID) string {\n+ realRoot := t.MountNamespaceVFS2().Root()\n+ root := t.FSContext().RootDirectoryVFS2()\n+ defer root.DecRef(t)\n+ path, err := t.Kernel().VFS().PathnameWithDeleted(t, realRoot, root)\n+ if err != nil {\n+ log.Warningf(\"PathnameWithDeleted failed to find root path for PID %s: %v\", pid, err)\n+ return \"\"\n+ }\n+ return path\n+}\n+\n// Dump returns a procfs dump for process pid. t must be a task in process pid.\nfunc Dump(t *kernel.Task, pid kernel.ThreadID) (ProcessProcfsDump, error) {\nctx := t.AsyncContext()\n@@ -173,5 +188,6 @@ func Dump(t *kernel.Task, pid kernel.ThreadID) (ProcessProcfsDump, error) {\nCWD: getCWD(ctx, t, pid),\nFDs: getFDs(ctx, t, pid),\nStartTime: t.StartTime().Nanoseconds(),\n+ Root: getRoot(t, pid),\n}, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/trace_test.go",
"new_path": "runsc/container/trace_test.go",
"diff": "@@ -387,4 +387,8 @@ func TestProcfsDump(t *testing.T) {\nif startTime-procfsDump[0].StartTime > 3*time.Second.Nanoseconds() {\nt.Errorf(\"wanted start time to be around %s, but got %s\", time.Unix(0, startTime), time.Unix(0, procfsDump[0].StartTime))\n}\n+\n+ if want := \"/\"; procfsDump[0].Root != \"/\" {\n+ t.Errorf(\"expected root to be %q, but got %q\", want, procfsDump[0].Root)\n+ }\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add support for /proc/[pid]/root to trace procfs.
Updates #4805
PiperOrigin-RevId: 450846922 |
259,891 | 25.05.2022 10:38:47 | 25,200 | 0a6e768256203700a484d2b7e42e5a428bfc34b6 | reduce sharedmem server test runtime
The large bulk tests can take 25-45+ seconds. AFAIK we don't need to test such
large values. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/sharedmem/sharedmem_server_test.go",
"new_path": "pkg/tcpip/link/sharedmem/sharedmem_server_test.go",
"diff": "@@ -297,8 +297,6 @@ func TestServerBulkTransfer(t *testing.T) {\n512 << 20, // 512 MiB\n1024 << 20, // 1 GiB\n2048 << 20, // 2 GiB\n- 4096 << 20, // 4 GiB\n- 8192 << 20, // 8 GiB\n}\nfor _, payloadSize := range payloadSizes {\n@@ -353,8 +351,6 @@ func TestClientBulkTransfer(t *testing.T) {\n512 << 20, // 512 MiB\n1024 << 20, // 1 GiB\n2048 << 20, // 2 GiB\n- 4096 << 20, // 4 GiB\n- 8192 << 20, // 8 GiB\n}\nfor _, payloadSize := range payloadSizes {\n"
}
] | Go | Apache License 2.0 | google/gvisor | reduce sharedmem server test runtime
The large bulk tests can take 25-45+ seconds. AFAIK we don't need to test such
large values.
PiperOrigin-RevId: 450959539 |
259,992 | 25.05.2022 11:58:07 | 25,200 | d2743355aea086de1884454ec6d62560bd23730d | Handle negative FDs in syscall points
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/points.go",
"new_path": "pkg/sentry/syscalls/linux/points.go",
"diff": "@@ -35,13 +35,16 @@ func newExitMaybe(info kernel.SyscallInfo) *pb.Exit {\n}\nfunc getFilePath(t *kernel.Task, fd int32) string {\n+ if fd < 0 {\n+ return \"\"\n+ }\nfdt := t.FDTable()\nif fdt == nil {\nreturn \"[err: no FD table]\"\n}\nfile, _ := fdt.GetVFS2(fd)\nif file == nil {\n- return \"[err: requires VFS2]\"\n+ return \"[err: FD not found]\"\n}\ndefer file.DecRef(t)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Handle negative FDs in syscall points
Updates #4805
PiperOrigin-RevId: 450980807 |
259,985 | 25.05.2022 12:05:47 | 25,200 | 2a6fe814c742559f3aac9932b00e219eda6a2158 | cgroupfs: Mark the "cgroup.procs" and "task" files as writable.
We were bypassing permission checks and writing to these files from
tests since all our tests run as the root user. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/base.go",
"new_path": "pkg/sentry/fsimpl/cgroupfs/base.go",
"diff": "@@ -175,8 +175,8 @@ func (fs *filesystem) newCgroupInode(ctx context.Context, creds *auth.Credential\nc.dir.cgi = c\ncontents := make(map[string]kernfs.Inode)\n- contents[\"cgroup.procs\"] = fs.newControllerFile(ctx, creds, &cgroupProcsData{c})\n- contents[\"tasks\"] = fs.newControllerFile(ctx, creds, &tasksData{c})\n+ contents[\"cgroup.procs\"] = fs.newControllerWritableFile(ctx, creds, &cgroupProcsData{c})\n+ contents[\"tasks\"] = fs.newControllerWritableFile(ctx, creds, &tasksData{c})\nif parent != nil {\nfor ty, ctl := range parent.controllers {\n"
}
] | Go | Apache License 2.0 | google/gvisor | cgroupfs: Mark the "cgroup.procs" and "task" files as writable.
We were bypassing permission checks and writing to these files from
tests since all our tests run as the root user.
PiperOrigin-RevId: 450983044 |
259,891 | 25.05.2022 12:22:53 | 25,200 | 2b52af3592780308e5ea43862e06349b02b98111 | netstack: have IncRef() return *PacketBuffer
This makes it clearer where the new ownership is occuring. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/channel/channel.go",
"new_path": "pkg/tcpip/link/channel/channel.go",
"diff": "@@ -84,10 +84,9 @@ func (q *queue) Write(pkt *stack.PacketBuffer) tcpip.Error {\nreturn &tcpip.ErrClosedForSend{}\n}\n- pkt.IncRef()\nwrote := false\nselect {\n- case q.c <- pkt:\n+ case q.c <- pkt.IncRef():\nwrote = true\ndefault:\npkt.DecRef()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/packetsocket/packetsocket_test.go",
"new_path": "pkg/tcpip/link/packetsocket/packetsocket_test.go",
"diff": "@@ -89,7 +89,7 @@ func (t *testNetworkDispatcher) reset() {\nfunc (t *testNetworkDispatcher) DeliverNetworkPacket(protocol tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) {\nnetworkPacket := networkPacketInfo{\n- pkt: pkt,\n+ pkt: pkt.IncRef(),\nprotocol: protocol,\n}\n@@ -97,14 +97,12 @@ func (t *testNetworkDispatcher) DeliverNetworkPacket(protocol tcpip.NetworkProto\nt.t.Fatalf(\"already delivered network packet = %#v; new = %#v\", t.networkPacket, networkPacket)\n}\n- pkt.IncRef()\n-\nt.networkPacket = networkPacket\n}\nfunc (t *testNetworkDispatcher) DeliverLinkPacket(protocol tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer, incoming bool) {\nlinkPacket := linkPacketInfo{\n- pkt: pkt,\n+ pkt: pkt.IncRef(),\nprotocol: protocol,\nincoming: incoming,\n}\n@@ -113,8 +111,6 @@ func (t *testNetworkDispatcher) DeliverLinkPacket(protocol tcpip.NetworkProtocol\nt.t.Fatalf(\"already delivered link packet = %#v; new = %#v\", t.linkPacket, linkPacket)\n}\n- pkt.IncRef()\n-\nt.linkPacket = linkPacket\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/qdisc/fifo/fifo.go",
"new_path": "pkg/tcpip/link/qdisc/fifo/fifo.go",
"diff": "@@ -133,8 +133,7 @@ func (d *discipline) WritePacket(pkt *stack.PacketBuffer) tcpip.Error {\nqd.mu.Lock()\nhaveSpace := qd.queue.hasSpace()\nif haveSpace {\n- pkt.IncRef()\n- qd.queue.pushBack(pkt)\n+ qd.queue.pushBack(pkt.IncRef())\n}\nqd.mu.Unlock()\nif !haveSpace {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/internal/fragmentation/reassembler.go",
"new_path": "pkg/tcpip/network/internal/fragmentation/reassembler.go",
"diff": "@@ -133,9 +133,8 @@ func (r *reassembler) process(first, last uint16, more bool, proto uint8, pkt *s\nlast: last,\nfilled: true,\nfinal: currentHole.final,\n- pkt: pkt,\n+ pkt: pkt.IncRef(),\n}\n- pkt.IncRef()\nr.filled++\n// For IPv6, it is possible to have different Protocol values between\n// fragments of a packet (because, unlike IPv4, the Protocol is not used to\n@@ -149,8 +148,7 @@ func (r *reassembler) process(first, last uint16, more bool, proto uint8, pkt *s\nif r.pkt != nil {\nr.pkt.DecRef()\n}\n- r.pkt = pkt\n- pkt.IncRef()\n+ r.pkt = pkt.IncRef()\nr.proto = proto\n}\nbreak\n@@ -169,8 +167,7 @@ func (r *reassembler) process(first, last uint16, more bool, proto uint8, pkt *s\nreturn r.holes[i].first < r.holes[j].first\n})\n- resPkt := r.holes[0].pkt\n- resPkt.IncRef()\n+ resPkt := r.holes[0].pkt.IncRef()\nfor i := 1; i < len(r.holes); i++ {\nstack.MergeFragment(resPkt, r.holes[i].pkt)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/internal/testutil/testutil.go",
"new_path": "pkg/tcpip/network/internal/testutil/testutil.go",
"diff": "@@ -69,8 +69,7 @@ func (ep *MockLinkEndpoint) WritePackets(pkts stack.PacketBufferList) (int, tcpi\nreturn n, ep.err\n}\nep.allowPackets--\n- pkt.IncRef()\n- ep.WrittenPackets = append(ep.WrittenPackets, pkt)\n+ ep.WrittenPackets = append(ep.WrittenPackets, pkt.IncRef())\nn++\n}\nreturn n, nil\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/packet_buffer.go",
"new_path": "pkg/tcpip/stack/packet_buffer.go",
"diff": "@@ -199,6 +199,12 @@ func NewPacketBuffer(opts PacketBufferOptions) *PacketBuffer {\nreturn pk\n}\n+// IncRef increments the PacketBuffer's refcount.\n+func (pk *PacketBuffer) IncRef() *PacketBuffer {\n+ pk.packetBufferRefs.IncRef()\n+ return pk\n+}\n+\n// DecRef decrements the PacketBuffer's refcount. If the refcount is\n// decremented to zero, the PacketBuffer is returned to the PacketBuffer\n// pool.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/pending_packets.go",
"new_path": "pkg/tcpip/stack/pending_packets.go",
"diff": "@@ -146,9 +146,8 @@ func (f *packetsPendingLinkResolution) enqueue(r *Route, pkt *PacketBuffer) tcpi\npackets, ok := f.mu.packets[ch]\npackets = append(packets, pendingPacket{\nrouteInfo: routeInfo,\n- pkt: pkt,\n+ pkt: pkt.IncRef(),\n})\n- pkt.IncRef()\nif len(packets) > maxPendingPacketsPerResolution {\nf.incrementOutgoingPacketErrors(packets[0].pkt)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/datagram_test.go",
"new_path": "pkg/tcpip/transport/datagram_test.go",
"diff": "@@ -157,8 +157,7 @@ func (e *mockEndpoint) WritePackets(pkts stack.PacketBufferList) (int, tcpip.Err\nlen := pkts.Len()\nfor _, pkt := range pkts.AsSlice() {\n- pkt.IncRef()\n- e.pkts.PushBack(pkt)\n+ e.pkts.PushBack(pkt.IncRef())\n}\nreturn len, nil\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -966,9 +966,8 @@ func (e *endpoint) HandlePacket(id stack.TransportEndpointID, pkt *stack.PacketB\nAddr: id.LocalAddress,\nPort: hdr.DestinationPort(),\n},\n- pkt: pkt,\n+ pkt: pkt.IncRef(),\n}\n- pkt.IncRef()\ne.rcvList.PushBack(packet)\ne.rcvBufSize += pkt.Data().Size()\n"
}
] | Go | Apache License 2.0 | google/gvisor | netstack: have IncRef() return *PacketBuffer
This makes it clearer where the new ownership is occuring.
PiperOrigin-RevId: 450987161 |
259,992 | 25.05.2022 12:28:30 | 25,200 | 1c0fe0e724619871b906ada123692d067a38b253 | Remove VFS1 TTY from runsc
Updates | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader.go",
"new_path": "runsc/boot/loader.go",
"diff": "@@ -39,9 +39,8 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/control\"\n\"gvisor.dev/gvisor/pkg/sentry/fdimport\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n- \"gvisor.dev/gvisor/pkg/sentry/fs/host\"\n\"gvisor.dev/gvisor/pkg/sentry/fs/user\"\n- hostvfs2 \"gvisor.dev/gvisor/pkg/sentry/fsimpl/host\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/host\"\n\"gvisor.dev/gvisor/pkg/sentry/inet\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n@@ -163,10 +162,7 @@ type execProcess struct {\ntg *kernel.ThreadGroup\n// tty will be nil if the process is not attached to a terminal.\n- tty *host.TTYFileOperations\n-\n- // tty will be nil if the process is not attached to a terminal.\n- ttyVFS2 *hostvfs2.TTYFileDescription\n+ tty *host.TTYFileDescription\n// pidnsPath is the pid namespace path in spec\npidnsPath string\n@@ -411,7 +407,7 @@ func New(args Args) (*Loader, error) {\ninfo.spec = args.Spec\n// Set up host mount that will be used for imported fds.\n- hostFilesystem, err := hostvfs2.NewFilesystem(k.VFS())\n+ hostFilesystem, err := host.NewFilesystem(k.VFS())\nif err != nil {\nreturn nil, fmt.Errorf(\"failed to create hostfs filesystem: %w\", err)\n}\n@@ -632,7 +628,7 @@ func (l *Loader) run() error {\ntg *kernel.ThreadGroup\nerr error\n)\n- tg, ep.tty, ep.ttyVFS2, err = l.createContainerProcess(true, l.sandboxID, &l.root)\n+ tg, ep.tty, err = l.createContainerProcess(true, l.sandboxID, &l.root)\nif err != nil {\nreturn err\n}\n@@ -780,7 +776,7 @@ func (l *Loader) startSubcontainer(spec *specs.Spec, conf *config.Config, cid st\ninfo.stdioFDs = stdioFDs\n}\n- ep.tg, ep.tty, ep.ttyVFS2, err = l.createContainerProcess(false, cid, info)\n+ ep.tg, ep.tty, err = l.createContainerProcess(false, cid, info)\nif err != nil {\nreturn err\n}\n@@ -809,12 +805,12 @@ func (l *Loader) startSubcontainer(spec *specs.Spec, conf *config.Config, cid st\nreturn nil\n}\n-func (l *Loader) createContainerProcess(root bool, cid string, info *containerInfo) (*kernel.ThreadGroup, *host.TTYFileOperations, *hostvfs2.TTYFileDescription, error) {\n+func (l *Loader) createContainerProcess(root bool, cid string, info *containerInfo) (*kernel.ThreadGroup, *host.TTYFileDescription, error) {\n// Create the FD map, which will set stdin, stdout, and stderr.\nctx := info.procArgs.NewContext(l.k)\n- fdTable, ttyFile, ttyFileVFS2, err := createFDTable(ctx, info.spec.Process.Terminal, info.stdioFDs, info.spec.Process.User)\n+ fdTable, ttyFile, err := createFDTable(ctx, info.spec.Process.Terminal, info.stdioFDs, info.spec.Process.User)\nif err != nil {\n- return nil, nil, nil, fmt.Errorf(\"importing fds: %w\", err)\n+ return nil, nil, fmt.Errorf(\"importing fds: %w\", err)\n}\n// CreateProcess takes a reference on fdTable if successful. We won't need\n// ours either way.\n@@ -822,41 +818,38 @@ func (l *Loader) createContainerProcess(root bool, cid string, info *containerIn\n// Gofer FDs must be ordered and the first FD is always the rootfs.\nif len(info.goferFDs) < 1 {\n- return nil, nil, nil, fmt.Errorf(\"rootfs gofer FD not found\")\n+ return nil, nil, fmt.Errorf(\"rootfs gofer FD not found\")\n}\nl.startGoferMonitor(cid, int32(info.goferFDs[0].FD()))\nmntr := newContainerMounter(info, l.k, l.mountHints, l.productName)\nif root {\nif err := mntr.processHints(info.conf, info.procArgs.Credentials); err != nil {\n- return nil, nil, nil, err\n+ return nil, nil, err\n}\n}\nif err := setupContainerVFS(ctx, info.conf, mntr, &info.procArgs); err != nil {\n- return nil, nil, nil, err\n+ return nil, nil, err\n}\n// Add the HOME environment variable if it is not already set.\ninfo.procArgs.Envv, err = user.MaybeAddExecUserHomeVFS2(ctx, info.procArgs.MountNamespaceVFS2,\ninfo.procArgs.Credentials.RealKUID, info.procArgs.Envv)\nif err != nil {\n- return nil, nil, nil, err\n+ return nil, nil, err\n}\n// Create and start the new process.\ntg, _, err := l.k.CreateProcess(info.procArgs)\nif err != nil {\n- return nil, nil, nil, fmt.Errorf(\"creating process: %w\", err)\n+ return nil, nil, fmt.Errorf(\"creating process: %w\", err)\n}\n// CreateProcess takes a reference on FDTable if successful.\ninfo.procArgs.FDTable.DecRef(ctx)\n// Set the foreground process group on the TTY to the global init process\n// group, since that is what we are about to start running.\n- switch {\n- case ttyFileVFS2 != nil:\n- ttyFileVFS2.InitForegroundProcessGroup(tg.ProcessGroup())\n- case ttyFile != nil:\n+ if ttyFile != nil {\nttyFile.InitForegroundProcessGroup(tg.ProcessGroup())\n}\n@@ -865,7 +858,7 @@ func (l *Loader) createContainerProcess(root bool, cid string, info *containerIn\nif info.spec.Linux != nil && info.spec.Linux.Seccomp != nil {\nprogram, err := seccomp.BuildProgram(info.spec.Linux.Seccomp)\nif err != nil {\n- return nil, nil, nil, fmt.Errorf(\"building seccomp program: %w\", err)\n+ return nil, nil, fmt.Errorf(\"building seccomp program: %w\", err)\n}\nif log.IsLogging(log.Debug) {\n@@ -876,7 +869,7 @@ func (l *Loader) createContainerProcess(root bool, cid string, info *containerIn\ntask := tg.Leader()\n// NOTE: It seems Flags are ignored by runc so we ignore them too.\nif err := task.AppendSyscallFilter(program, true); err != nil {\n- return nil, nil, nil, fmt.Errorf(\"appending seccomp filters: %w\", err)\n+ return nil, nil, fmt.Errorf(\"appending seccomp filters: %w\", err)\n}\n}\n} else {\n@@ -885,7 +878,7 @@ func (l *Loader) createContainerProcess(root bool, cid string, info *containerIn\n}\n}\n- return tg, ttyFile, ttyFileVFS2, nil\n+ return tg, ttyFile, nil\n}\n// startGoferMonitor runs a goroutine to monitor gofer's health. It polls on\n@@ -1020,7 +1013,7 @@ func (l *Loader) executeAsync(args *control.ExecArgs) (kernel.ThreadID, error) {\n// Start the process.\nproc := control.Proc{Kernel: l.k}\n- newTG, tgid, ttyFile, ttyFileVFS2, err := control.ExecAsync(&proc, args)\n+ newTG, tgid, _, ttyFile, err := control.ExecAsync(&proc, args)\nif err != nil {\nreturn 0, err\n}\n@@ -1029,7 +1022,6 @@ func (l *Loader) executeAsync(args *control.ExecArgs) (kernel.ThreadID, error) {\nl.processes[eid] = &execProcess{\ntg: newTG,\ntty: ttyFile,\n- ttyVFS2: ttyFileVFS2,\n}\nlog.Debugf(\"updated processes: %v\", l.processes)\n@@ -1308,21 +1300,15 @@ func (l *Loader) signalForegrondProcessGroup(cid string, tgid kernel.ThreadID, s\nreturn fmt.Errorf(\"container %q not started\", cid)\n}\n- tty, ttyVFS2, err := l.ttyFromIDLocked(execID{cid: cid, pid: tgid})\n+ tty, err := l.ttyFromIDLocked(execID{cid: cid, pid: tgid})\nl.mu.Unlock()\nif err != nil {\nreturn fmt.Errorf(\"no thread group found: %w\", err)\n}\n-\n- var pg *kernel.ProcessGroup\n- switch {\n- case ttyVFS2 != nil:\n- pg = ttyVFS2.ForegroundProcessGroup()\n- case tty != nil:\n- pg = tty.ForegroundProcessGroup()\n- default:\n+ if tty == nil {\nreturn fmt.Errorf(\"no TTY attached\")\n}\n+ pg := tty.ForegroundProcessGroup()\nif pg == nil {\n// No foreground process group has been set. Signal the\n// original thread group.\n@@ -1385,25 +1371,25 @@ func (l *Loader) tryThreadGroupFromIDLocked(key execID) (*kernel.ThreadGroup, er\n// return nil in case the container has not started yet. Returns error if\n// execution ID is invalid or if the container cannot be found (maybe it has\n// been deleted). Caller must hold 'mu'.\n-func (l *Loader) ttyFromIDLocked(key execID) (*host.TTYFileOperations, *hostvfs2.TTYFileDescription, error) {\n+func (l *Loader) ttyFromIDLocked(key execID) (*host.TTYFileDescription, error) {\nep := l.processes[key]\nif ep == nil {\n- return nil, nil, fmt.Errorf(\"container %q not found\", key.cid)\n+ return nil, fmt.Errorf(\"container %q not found\", key.cid)\n}\n- return ep.tty, ep.ttyVFS2, nil\n+ return ep.tty, nil\n}\n-func createFDTable(ctx context.Context, console bool, stdioFDs []*fd.FD, user specs.User) (*kernel.FDTable, *host.TTYFileOperations, *hostvfs2.TTYFileDescription, error) {\n+func createFDTable(ctx context.Context, console bool, stdioFDs []*fd.FD, user specs.User) (*kernel.FDTable, *host.TTYFileDescription, error) {\nif len(stdioFDs) != 3 {\n- return nil, nil, nil, fmt.Errorf(\"stdioFDs should contain exactly 3 FDs (stdin, stdout, and stderr), but %d FDs received\", len(stdioFDs))\n+ return nil, nil, fmt.Errorf(\"stdioFDs should contain exactly 3 FDs (stdin, stdout, and stderr), but %d FDs received\", len(stdioFDs))\n}\nk := kernel.KernelFromContext(ctx)\nfdTable := k.NewFDTable()\n- ttyFile, ttyFileVFS2, err := fdimport.Import(ctx, fdTable, console, auth.KUID(user.UID), auth.KGID(user.GID), stdioFDs)\n+ _, ttyFile, err := fdimport.Import(ctx, fdTable, console, auth.KUID(user.UID), auth.KGID(user.GID), stdioFDs)\nif err != nil {\nfdTable.DecRef(ctx)\n- return nil, nil, nil, err\n+ return nil, nil, err\n}\n- return fdTable, ttyFile, ttyFileVFS2, nil\n+ return fdTable, ttyFile, nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove VFS1 TTY from runsc
Updates #1624
PiperOrigin-RevId: 450988463 |
259,982 | 25.05.2022 13:31:29 | 25,200 | f84e9a85d1e5716745780537fce0e6c51fa2f1fb | Add Points to some syscalls
Added a raw syscall points to all syscalls. Added schematized syscall
points to the following syscalls:
Chdir
Fchdir
Setgid
Setuid
Setsid
Setresuid
Setresgid | [
{
"change_type": "MODIFY",
"old_path": "examples/seccheck/server.cc",
"new_path": "examples/seccheck/server.cc",
"diff": "@@ -92,6 +92,9 @@ std::vector<Callback> dispatchers = {\nunpackSyscall<::gvisor::syscall::Connect>,\nunpackSyscall<::gvisor::syscall::Execve>,\nunpackSyscall<::gvisor::syscall::Socket>,\n+ unpackSyscall<::gvisor::syscall::Chdir>,\n+ unpackSyscall<::gvisor::syscall::Setid>,\n+ unpackSyscall<::gvisor::syscall::Setresid>,\n};\nvoid unpack(absl::string_view buf) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/metadata_amd64.go",
"new_path": "pkg/sentry/seccheck/metadata_amd64.go",
"diff": "@@ -66,6 +66,19 @@ func init() {\nName: \"envv\",\n},\n})\n+ addSyscallPoint(80, \"chdir\", nil)\n+ addSyscallPoint(81, \"fchdir\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+\n+ addSyscallPoint(105, \"setuid\", nil)\n+ addSyscallPoint(106, \"setgid\", nil)\n+ addSyscallPoint(112, \"setsid\", nil)\n+ addSyscallPoint(117, \"setresuid\", nil)\n+ addSyscallPoint(119, \"setresgid\", nil)\nconst lastSyscallInTable = 441\nfor i := 0; i <= lastSyscallInTable; i++ {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/metadata_arm64.go",
"new_path": "pkg/sentry/seccheck/metadata_arm64.go",
"diff": "@@ -59,6 +59,18 @@ func init() {\nName: \"envv\",\n},\n})\n+ addSyscallPoint(49, \"chdir\", nil)\n+ addSyscallPoint(50, \"fchdir\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(146, \"setuid\", nil)\n+ addSyscallPoint(144, \"setgid\", nil)\n+ addSyscallPoint(157, \"setsid\", nil)\n+ addSyscallPoint(147, \"setresuid\", nil)\n+ addSyscallPoint(149, \"setresgid\", nil)\nconst lastSyscallInTable = 441\nfor i := 0; i <= lastSyscallInTable; i++ {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/points/common.proto",
"new_path": "pkg/sentry/seccheck/points/common.proto",
"diff": "@@ -110,5 +110,8 @@ enum MessageType {\nMESSAGE_SYSCALL_CONNECT = 10;\nMESSAGE_SYSCALL_EXECVE = 11;\nMESSAGE_SYSCALL_SOCKET = 12;\n+ MESSAGE_SYSCALL_CHDIR = 13;\n+ MESSAGE_SYSCALL_SETID = 14;\n+ MESSAGE_SYSCALL_SETRESID = 15;\n}\n// LINT.ThenChange(../../../../examples/seccheck/server.cc)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/points/syscall.proto",
"new_path": "pkg/sentry/seccheck/points/syscall.proto",
"diff": "@@ -92,3 +92,28 @@ message Socket {\nint32 type = 5;\nint32 protocol = 6;\n}\n+\n+message Chdir {\n+ gvisor.common.ContextData context_data = 1;\n+ Exit exit = 2;\n+ uint64 sysno = 3;\n+ int64 fd = 4;\n+ string fd_path = 5;\n+ string pathname = 6;\n+}\n+\n+message Setresid {\n+ gvisor.common.ContextData context_data = 1;\n+ Exit exit = 2;\n+ uint64 sysno = 3;\n+ uint32 rgid = 4;\n+ uint32 egid = 5;\n+ uint32 sgid = 6;\n+}\n+\n+message Setid {\n+ gvisor.common.ContextData context_data = 1;\n+ Exit exit = 2;\n+ uint64 sysno = 3;\n+ uint32 id = 4;\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/linux64.go",
"new_path": "pkg/sentry/syscalls/linux/linux64.go",
"diff": "@@ -132,8 +132,8 @@ var AMD64 = &kernel.SyscallTable{\n77: syscalls.Supported(\"ftruncate\", Ftruncate),\n78: syscalls.Supported(\"getdents\", Getdents),\n79: syscalls.Supported(\"getcwd\", Getcwd),\n- 80: syscalls.Supported(\"chdir\", Chdir),\n- 81: syscalls.Supported(\"fchdir\", Fchdir),\n+ 80: syscalls.SupportedPoint(\"chdir\", Chdir, PointChdir),\n+ 81: syscalls.SupportedPoint(\"fchdir\", Fchdir, PointFchdir),\n82: syscalls.Supported(\"rename\", Rename),\n83: syscalls.Supported(\"mkdir\", Mkdir),\n84: syscalls.Supported(\"rmdir\", Rmdir),\n@@ -157,21 +157,21 @@ var AMD64 = &kernel.SyscallTable{\n102: syscalls.Supported(\"getuid\", Getuid),\n103: syscalls.PartiallySupported(\"syslog\", Syslog, \"Outputs a dummy message for security reasons.\", nil),\n104: syscalls.Supported(\"getgid\", Getgid),\n- 105: syscalls.Supported(\"setuid\", Setuid),\n- 106: syscalls.Supported(\"setgid\", Setgid),\n+ 105: syscalls.SupportedPoint(\"setuid\", Setuid, PointSetuid),\n+ 106: syscalls.SupportedPoint(\"setgid\", Setgid, PointSetgid),\n107: syscalls.Supported(\"geteuid\", Geteuid),\n108: syscalls.Supported(\"getegid\", Getegid),\n109: syscalls.Supported(\"setpgid\", Setpgid),\n110: syscalls.Supported(\"getppid\", Getppid),\n111: syscalls.Supported(\"getpgrp\", Getpgrp),\n- 112: syscalls.Supported(\"setsid\", Setsid),\n+ 112: syscalls.SupportedPoint(\"setsid\", Setsid, PointSetsid),\n113: syscalls.Supported(\"setreuid\", Setreuid),\n114: syscalls.Supported(\"setregid\", Setregid),\n115: syscalls.Supported(\"getgroups\", Getgroups),\n116: syscalls.Supported(\"setgroups\", Setgroups),\n- 117: syscalls.Supported(\"setresuid\", Setresuid),\n+ 117: syscalls.SupportedPoint(\"setresuid\", Setresuid, PointSetresuid),\n118: syscalls.Supported(\"getresuid\", Getresuid),\n- 119: syscalls.Supported(\"setresgid\", Setresgid),\n+ 119: syscalls.SupportedPoint(\"setresgid\", Setresgid, PointSetresgid),\n120: syscalls.Supported(\"getresgid\", Getresgid),\n121: syscalls.Supported(\"getpgid\", Getpgid),\n122: syscalls.ErrorWithEvent(\"setfsuid\", linuxerr.ENOSYS, \"\", []string{\"gvisor.dev/issue/260\"}), // TODO(b/112851702)\n@@ -479,8 +479,8 @@ var ARM64 = &kernel.SyscallTable{\n46: syscalls.Supported(\"ftruncate\", Ftruncate),\n47: syscalls.PartiallySupported(\"fallocate\", Fallocate, \"Not all options are supported.\", nil),\n48: syscalls.Supported(\"faccessat\", Faccessat),\n- 49: syscalls.Supported(\"chdir\", Chdir),\n- 50: syscalls.Supported(\"fchdir\", Fchdir),\n+ 49: syscalls.SupportedPoint(\"chdir\", Chdir, PointChdir),\n+ 50: syscalls.SupportedPoint(\"fchdir\", Fchdir, PointFchdir),\n51: syscalls.Supported(\"chroot\", Chroot),\n52: syscalls.PartiallySupported(\"fchmod\", Fchmod, \"Options S_ISUID and S_ISGID not supported.\", nil),\n53: syscalls.Supported(\"fchmodat\", Fchmodat),\n@@ -574,12 +574,12 @@ var ARM64 = &kernel.SyscallTable{\n141: syscalls.PartiallySupported(\"getpriority\", Getpriority, \"Stub implementation.\", nil),\n142: syscalls.CapError(\"reboot\", linux.CAP_SYS_BOOT, \"\", nil),\n143: syscalls.Supported(\"setregid\", Setregid),\n- 144: syscalls.Supported(\"setgid\", Setgid),\n+ 144: syscalls.SupportedPoint(\"setgid\", Setgid, PointSetgid),\n145: syscalls.Supported(\"setreuid\", Setreuid),\n- 146: syscalls.Supported(\"setuid\", Setuid),\n- 147: syscalls.Supported(\"setresuid\", Setresuid),\n+ 146: syscalls.SupportedPoint(\"setuid\", Setuid, PointSetuid),\n+ 147: syscalls.SupportedPoint(\"setresuid\", Setresuid, PointSetresuid),\n148: syscalls.Supported(\"getresuid\", Getresuid),\n- 149: syscalls.Supported(\"setresgid\", Setresgid),\n+ 149: syscalls.SupportedPoint(\"setresgid\", Setresgid, PointSetresgid),\n150: syscalls.Supported(\"getresgid\", Getresgid),\n151: syscalls.ErrorWithEvent(\"setfsuid\", linuxerr.ENOSYS, \"\", []string{\"gvisor.dev/issue/260\"}), // TODO(b/112851702)\n152: syscalls.ErrorWithEvent(\"setfsgid\", linuxerr.ENOSYS, \"\", []string{\"gvisor.dev/issue/260\"}), // TODO(b/112851702)\n@@ -587,7 +587,7 @@ var ARM64 = &kernel.SyscallTable{\n154: syscalls.Supported(\"setpgid\", Setpgid),\n155: syscalls.Supported(\"getpgid\", Getpgid),\n156: syscalls.Supported(\"getsid\", Getsid),\n- 157: syscalls.Supported(\"setsid\", Setsid),\n+ 157: syscalls.SupportedPoint(\"setsid\", Setsid, PointSetsid),\n158: syscalls.Supported(\"getgroups\", Getgroups),\n159: syscalls.Supported(\"setgroups\", Setgroups),\n160: syscalls.Supported(\"uname\", Uname),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/points.go",
"new_path": "pkg/sentry/syscalls/linux/points.go",
"diff": "@@ -19,6 +19,7 @@ import (\n\"google.golang.org/protobuf/proto\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/hostarch\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/seccheck\"\npb \"gvisor.dev/gvisor/pkg/sentry/seccheck/points/points_go_proto\"\n@@ -264,3 +265,95 @@ func PointExecveat(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.Context\nreturn p, pb.MessageType_MESSAGE_SYSCALL_EXECVE\n}\n+\n+// pointChdirHelper converts chdir(2) and fchdir(2) syscall to proto.\n+func pointChdirHelper(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo, fd int64, path hostarch.Addr) (proto.Message, pb.MessageType) {\n+ p := &pb.Chdir{\n+ ContextData: cxtData,\n+ Sysno: uint64(info.Sysno),\n+ Fd: fd,\n+ }\n+\n+ if path > 0 {\n+ pathname, err := t.CopyInString(path, linux.PATH_MAX)\n+ if err == nil {\n+ p.Pathname = pathname\n+ }\n+ }\n+\n+ if fields.Local.Contains(seccheck.FieldSyscallPath) {\n+ p.FdPath = getFilePath(t, int32(p.Fd))\n+ }\n+\n+ p.Exit = newExitMaybe(info)\n+\n+ return p, pb.MessageType_MESSAGE_SYSCALL_CHDIR\n+}\n+\n+// PointChdir calls pointChdirHelper to convert chdir(2) syscall to proto.\n+func PointChdir(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ path := info.Args[0].Pointer()\n+ return pointChdirHelper(t, fields, cxtData, info, linux.AT_FDCWD, path)\n+}\n+\n+// PointFchdir calls pointChdirHelper to convert fchdir(2) syscall to proto.\n+func PointFchdir(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ fd := int64(info.Args[0].Int())\n+ path := info.Args[1].Pointer()\n+ return pointChdirHelper(t, fields, cxtData, info, fd, path)\n+}\n+\n+// pointSetidHelper converts setuid(2) and setgid(2) syscall to proto.\n+func pointSetidHelper(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo, id uint32) (proto.Message, pb.MessageType) {\n+ p := &pb.Setid{\n+ ContextData: cxtData,\n+ Sysno: uint64(info.Sysno),\n+ Id: id,\n+ }\n+\n+ p.Exit = newExitMaybe(info)\n+\n+ return p, pb.MessageType_MESSAGE_SYSCALL_SETID\n+}\n+\n+// PointSetuid calls pointSetidHelper to convert setuid(2) syscall to proto.\n+func PointSetuid(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ id := uint32(info.Args[0].Uint())\n+ return pointSetidHelper(t, fields, cxtData, info, id)\n+}\n+\n+// PointSetgid calls pointSetidHelper to convert setgid(2) syscall to proto.\n+func PointSetgid(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ id := uint32(info.Args[0].Uint())\n+ return pointSetidHelper(t, fields, cxtData, info, id)\n+}\n+\n+// PointSetsid calls pointSetidHelper to convert setsid(2) syscall to proto.\n+func PointSetsid(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ return pointSetidHelper(t, fields, cxtData, info, 0)\n+}\n+\n+// pointSetresidHelper converts setresuid(2) and setresgid(2) syscall to proto.\n+func pointSetresidHelper(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ p := &pb.Setresid{\n+ ContextData: cxtData,\n+ Sysno: uint64(info.Sysno),\n+ Rgid: uint32(info.Args[0].Uint()),\n+ Egid: uint32(info.Args[1].Uint()),\n+ Sgid: uint32(info.Args[2].Uint()),\n+ }\n+\n+ p.Exit = newExitMaybe(info)\n+\n+ return p, pb.MessageType_MESSAGE_SYSCALL_SETRESID\n+}\n+\n+// PointSetresuid calls pointSetresidHelper to convert setresuid(2) syscall to proto.\n+func PointSetresuid(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ return pointSetresidHelper(t, fields, cxtData, info)\n+}\n+\n+// PointSetresgid calls pointSetresidHelper to convert setresgid(2) syscall to proto.\n+func PointSetresgid(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ return pointSetresidHelper(t, fields, cxtData, info)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/vfs2.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/vfs2.go",
"diff": "@@ -69,8 +69,8 @@ func Override() {\ns.Table[77] = syscalls.Supported(\"ftruncate\", Ftruncate)\ns.Table[78] = syscalls.Supported(\"getdents\", Getdents)\ns.Table[79] = syscalls.Supported(\"getcwd\", Getcwd)\n- s.Table[80] = syscalls.Supported(\"chdir\", Chdir)\n- s.Table[81] = syscalls.Supported(\"fchdir\", Fchdir)\n+ s.Table[80] = syscalls.SupportedPoint(\"chdir\", Chdir, linux.PointChdir)\n+ s.Table[81] = syscalls.SupportedPoint(\"fchdir\", Fchdir, linux.PointFchdir)\ns.Table[82] = syscalls.Supported(\"rename\", Rename)\ns.Table[83] = syscalls.Supported(\"mkdir\", Mkdir)\ns.Table[84] = syscalls.Supported(\"rmdir\", Rmdir)\n@@ -210,8 +210,8 @@ func Override() {\ns.Table[46] = syscalls.Supported(\"ftruncate\", Ftruncate)\ns.Table[47] = syscalls.PartiallySupported(\"fallocate\", Fallocate, \"Not all options are supported.\", nil)\ns.Table[48] = syscalls.Supported(\"faccessat\", Faccessat)\n- s.Table[49] = syscalls.Supported(\"chdir\", Chdir)\n- s.Table[50] = syscalls.Supported(\"fchdir\", Fchdir)\n+ s.Table[49] = syscalls.SupportedPoint(\"chdir\", Chdir, linux.PointChdir)\n+ s.Table[50] = syscalls.SupportedPoint(\"fchdir\", Fchdir, linux.PointFchdir)\ns.Table[51] = syscalls.Supported(\"chroot\", Chroot)\ns.Table[52] = syscalls.Supported(\"fchmod\", Fchmod)\ns.Table[53] = syscalls.Supported(\"fchmodat\", Fchmodat)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add Points to some syscalls
Added a raw syscall points to all syscalls. Added schematized syscall
points to the following syscalls:
- Chdir
- Fchdir
- Setgid
- Setuid
- Setsid
- Setresuid
- Setresgid
PiperOrigin-RevId: 451001973 |
259,992 | 25.05.2022 13:57:21 | 25,200 | 11a9f17b9a6041ce32bf3c4cd0a9bb48a5700432 | Trace points integration test
Updates | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -203,7 +203,7 @@ nogo-tests:\n# For unit tests, we take everything in the root, pkg/... and tools/..., and\n# pull in all directories in runsc except runsc/container.\nunit-tests: ## Local package unit tests in pkg/..., tools/.., etc.\n- @$(call test,--build_tag_filters=-nogo --test_tag_filters=-nogo --test_filter=-//runsc/container/... //:all pkg/... tools/... runsc/... vdso/...)\n+ @$(call test,--build_tag_filters=-nogo --test_tag_filters=-nogo --test_filter=-//runsc/container/... //:all pkg/... tools/... runsc/... vdso/... test/trace/...)\n.PHONY: unit-tests\n# See unit-tests: this includes runsc/container.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/checkers/remote/test/BUILD",
"new_path": "pkg/sentry/seccheck/checkers/remote/test/BUILD",
"diff": "@@ -13,7 +13,6 @@ go_library(\n\"//pkg/sentry/seccheck/checkers/remote/wire\",\n\"//pkg/sentry/seccheck/points:points_go_proto\",\n\"//pkg/sync\",\n- \"//pkg/test/testutil\",\n\"//pkg/unet\",\n\"@org_golang_google_protobuf//proto:go_default_library\",\n\"@org_golang_x_sys//unix:go_default_library\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/checkers/remote/test/server.go",
"new_path": "pkg/sentry/seccheck/checkers/remote/test/server.go",
"diff": "@@ -21,7 +21,6 @@ import (\n\"io/ioutil\"\n\"os\"\n\"path/filepath\"\n- \"time\"\n\"golang.org/x/sys/unix\"\n\"google.golang.org/protobuf/proto\"\n@@ -30,7 +29,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/seccheck/checkers/remote/wire\"\npb \"gvisor.dev/gvisor/pkg/sentry/seccheck/points/points_go_proto\"\n\"gvisor.dev/gvisor/pkg/sync\"\n- \"gvisor.dev/gvisor/pkg/test/testutil\"\n\"gvisor.dev/gvisor/pkg/unet\"\n)\n@@ -40,14 +38,16 @@ type Server struct {\nPath string\nsocket *unet.ServerSocket\n- mu sync.Mutex\n+ cond sync.Cond\n- // +checklocks:mu\n+ // +checklocks:cond.L\nclients []*unet.Socket\n- // +checklocks:mu\n+ // +checklocks:cond.L\npoints []Message\n+ mu sync.Mutex\n+\n// +checklocks:mu\nversion uint32\n}\n@@ -104,6 +104,7 @@ func newServerPath(path string) (*Server, error) {\nPath: path,\nsocket: ss,\nversion: wire.CurrentVersion,\n+ cond: sync.Cond{L: &sync.Mutex{}},\n}\ngo server.run()\ncu.Release()\n@@ -125,9 +126,10 @@ func (s *Server) run() {\n_ = client.Close()\ncontinue\n}\n- s.mu.Lock()\n+ s.cond.L.Lock()\ns.clients = append(s.clients, client)\n- s.mu.Unlock()\n+ s.cond.Broadcast()\n+ s.cond.L.Unlock()\ngo s.handleClient(client)\n}\n}\n@@ -164,14 +166,15 @@ func (s *Server) handshake(client *unet.Socket) error {\nfunc (s *Server) handleClient(client *unet.Socket) {\ndefer func() {\n- s.mu.Lock()\n+ s.cond.L.Lock()\nfor i, c := range s.clients {\nif c == client {\ns.clients = append(s.clients[:i], s.clients[i+1:]...)\nbreak\n}\n}\n- s.mu.Unlock()\n+ s.cond.Broadcast()\n+ s.cond.L.Unlock()\n_ = client.Close()\n}()\n@@ -192,28 +195,33 @@ func (s *Server) handleClient(client *unet.Socket) {\nif read < int(hdr.HeaderSize) {\npanic(fmt.Sprintf(\"message truncated, header size: %d, readL %d\", hdr.HeaderSize, read))\n}\n+\n+ msgSize := read - int(hdr.HeaderSize)\nmsg := Message{\nMsgType: pb.MessageType(hdr.MessageType),\n- Msg: buf[hdr.HeaderSize:read],\n+ Msg: make([]byte, msgSize),\n}\n- s.mu.Lock()\n+ copy(msg.Msg, buf[hdr.HeaderSize:read])\n+\n+ s.cond.L.Lock()\ns.points = append(s.points, msg)\n- s.mu.Unlock()\n+ s.cond.Broadcast()\n+ s.cond.L.Unlock()\n}\n}\n// Count return the number of points it has received.\nfunc (s *Server) Count() int {\n- s.mu.Lock()\n- defer s.mu.Unlock()\n+ s.cond.L.Lock()\n+ defer s.cond.L.Unlock()\nreturn len(s.points)\n}\n// Reset throws aways all points received so far and returns the number of\n// points discarded.\nfunc (s *Server) Reset() int {\n- s.mu.Lock()\n- defer s.mu.Unlock()\n+ s.cond.L.Lock()\n+ defer s.cond.L.Unlock()\ncount := len(s.points)\ns.points = nil\nreturn count\n@@ -221,8 +229,8 @@ func (s *Server) Reset() int {\n// GetPoints returns all points that it has received.\nfunc (s *Server) GetPoints() []Message {\n- s.mu.Lock()\n- defer s.mu.Unlock()\n+ s.cond.L.Lock()\n+ defer s.cond.L.Unlock()\ncpy := make([]Message, len(s.points))\ncopy(cpy, s.points)\nreturn cpy\n@@ -231,23 +239,33 @@ func (s *Server) GetPoints() []Message {\n// Close stops listenning and closes all connections.\nfunc (s *Server) Close() {\n_ = s.socket.Close()\n- s.mu.Lock()\n+ s.cond.L.Lock()\nfor _, client := range s.clients {\n_ = client.Close()\n}\n- s.mu.Unlock()\n+ s.clients = nil\n+ s.cond.Broadcast()\n+ s.cond.L.Unlock()\n_ = os.Remove(s.Path)\n}\n-// WaitForCount waits for the number of points to reach the desired number for\n-// 5 seconds. It fails if not received in time.\n-func (s *Server) WaitForCount(count int) error {\n- return testutil.Poll(func() error {\n- if got := s.Count(); got < count {\n- return fmt.Errorf(\"waiting for points %d to arrive, received %d\", count, got)\n+// WaitForCount waits for the number of points to reach the desired number.\n+func (s *Server) WaitForCount(count int) {\n+ s.cond.L.Lock()\n+ defer s.cond.L.Unlock()\n+ for len(s.points) < count {\n+ s.cond.Wait()\n+ }\n+ return\n+}\n+\n+// WaitForNoClients waits until the number of clients connected reaches 0.\n+func (s *Server) WaitForNoClients() {\n+ s.cond.L.Lock()\n+ defer s.cond.L.Unlock()\n+ for len(s.clients) > 0 {\n+ s.cond.Wait()\n}\n- return nil\n- }, 5*time.Second)\n}\n// SetVersion sets the version to be used in handshake.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/config.go",
"new_path": "pkg/sentry/seccheck/config.go",
"diff": "@@ -97,13 +97,13 @@ func Create(conf *SessionConfig, force bool) error {\nmask, err := setFields(ptConfig.OptionalFields, desc.OptionalFields)\nif err != nil {\n- return err\n+ return fmt.Errorf(\"configuring point %q: %w\", ptConfig.Name, err)\n}\nreq.Fields.Local = mask\nmask, err = setFields(ptConfig.ContextFields, desc.ContextFields)\nif err != nil {\n- return err\n+ return fmt.Errorf(\"configuring point %q: %w\", ptConfig.Name, err)\n}\nreq.Fields.Context = mask\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/trace_test.go",
"new_path": "runsc/container/trace_test.go",
"diff": "@@ -81,9 +81,7 @@ func TestTraceStartup(t *testing.T) {\n}\n// Wait for the point to be received and then check that fields match.\n- if err := server.WaitForCount(1); err != nil {\n- t.Fatalf(\"WaitForCount(1): %v\", err)\n- }\n+ server.WaitForCount(1)\npt := server.GetPoints()[0]\nif want := pb.MessageType_MESSAGE_CONTAINER_START; pt.MsgType != want {\nt.Errorf(\"wrong message type, want: %v, got: %v\", want, pt.MsgType)\n@@ -157,9 +155,7 @@ func TestTraceLifecycle(t *testing.T) {\nif ws, err := execute(conf, cont, \"/bin/true\"); err != nil || ws != 0 {\nt.Fatalf(\"exec: true, ws: %v, err: %v\", ws, err)\n}\n- if err := server.WaitForCount(1); err != nil {\n- t.Fatalf(\"WaitForCount(1): %v\", err)\n- }\n+ server.WaitForCount(1)\npt := server.GetPoints()[0]\nif want := pb.MessageType_MESSAGE_SENTRY_TASK_EXIT; pt.MsgType != want {\nt.Errorf(\"wrong message type, want: %v, got: %v\", want, pt.MsgType)\n@@ -259,9 +255,7 @@ func TestTraceForceCreate(t *testing.T) {\nif ws, err := execute(conf, cont, \"/bin/true\"); err != nil || ws != 0 {\nt.Fatalf(\"exec: true, ws: %v, err: %v\", ws, err)\n}\n- if err := server.WaitForCount(1); err != nil {\n- t.Fatalf(\"WaitForCount(1): %v\", err)\n- }\n+ server.WaitForCount(1)\npt := server.GetPoints()[0]\nif want := pb.MessageType_MESSAGE_SENTRY_EXIT_NOTIFY_PARENT; pt.MsgType != want {\nt.Errorf(\"wrong message type, want: %v, got: %v\", want, pt.MsgType)\n@@ -289,9 +283,7 @@ func TestTraceForceCreate(t *testing.T) {\nif ws, err := execute(conf, cont, \"/bin/true\"); err != nil || ws != 0 {\nt.Fatalf(\"exec: true, ws: %v, err: %v\", ws, err)\n}\n- if err := server.WaitForCount(1); err != nil {\n- t.Fatalf(\"WaitForCount(1): %v\", err)\n- }\n+ server.WaitForCount(1)\npt = server.GetPoints()[0]\nif want := pb.MessageType_MESSAGE_SENTRY_TASK_EXIT; pt.MsgType != want {\nt.Errorf(\"wrong message type, want: %v, got: %v\", want, pt.MsgType)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/trace/BUILD",
"diff": "+load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_test(\n+ name = \"trace_test\",\n+ size = \"small\",\n+ srcs = [\"trace_test.go\"],\n+ data = [\n+ \"//runsc\",\n+ \"//test/trace/workload\",\n+ ],\n+ library = \":trace\",\n+ tags = [\n+ \"local\",\n+ \"manual\",\n+ ],\n+ deps = [\n+ \"//pkg/sentry/seccheck\",\n+ \"//pkg/sentry/seccheck/checkers/remote/test\",\n+ \"//pkg/sentry/seccheck/points:points_go_proto\",\n+ \"//pkg/test/testutil\",\n+ \"//runsc/boot\",\n+ \"@org_golang_google_protobuf//proto:go_default_library\",\n+ ],\n+)\n+\n+go_library(\n+ name = \"trace\",\n+ srcs = [\"trace.go\"],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/trace/trace.go",
"diff": "+// Copyright 2022 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 trace is empty. See trace_test.go for description.\n+package trace\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/trace/trace_test.go",
"diff": "+// Copyright 2022 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 trace provides end-to-end integration tests for `runsc trace`.\n+package trace\n+\n+import (\n+ \"bufio\"\n+ \"bytes\"\n+ \"encoding/json\"\n+ \"fmt\"\n+ \"io/ioutil\"\n+ \"os\"\n+ \"os/exec\"\n+ \"strings\"\n+ \"testing\"\n+ \"time\"\n+\n+ \"google.golang.org/protobuf/proto\"\n+ \"gvisor.dev/gvisor/pkg/sentry/seccheck\"\n+ \"gvisor.dev/gvisor/pkg/sentry/seccheck/checkers/remote/test\"\n+ pb \"gvisor.dev/gvisor/pkg/sentry/seccheck/points/points_go_proto\"\n+ \"gvisor.dev/gvisor/pkg/test/testutil\"\n+ \"gvisor.dev/gvisor/runsc/boot\"\n+)\n+\n+// TestAll enabled all trace points in the system with all optional and context\n+// fields enabled. Then it runs a workload that will trigger those points and\n+// run some basic validation over the points generated.\n+func TestAll(t *testing.T) {\n+ server, err := test.NewServer()\n+ if err != nil {\n+ t.Fatal(err)\n+ }\n+\n+ runsc, err := testutil.FindFile(\"runsc/runsc\")\n+ if err != nil {\n+ t.Fatal(err)\n+ }\n+ cfg, err := buildPodConfig(runsc, server.Path)\n+ if err != nil {\n+ t.Fatal(err)\n+ }\n+\n+ cfgFile, err := ioutil.TempFile(testutil.TmpDir(), \"config\")\n+ if err != nil {\n+ t.Fatalf(\"error creating tmp file: %v\", err)\n+ }\n+ defer cfgFile.Close()\n+ encoder := json.NewEncoder(cfgFile)\n+ if err := encoder.Encode(&cfg); err != nil {\n+ t.Fatalf(\"JSON encode: %v\", err)\n+ }\n+\n+ workload, err := testutil.FindFile(\"test/trace/workload/workload\")\n+ if err != nil {\n+ t.Fatal(err)\n+ }\n+ cmd := exec.Command(\n+ runsc,\n+ \"--debug\", \"--alsologtostderr\", // Debug logging for troubleshooting\n+ \"--rootless\", \"--network=none\", // Disable features that we don't care\n+ \"--pod-init-config\", cfgFile.Name(),\n+ \"do\", workload)\n+ out, err := cmd.CombinedOutput()\n+ if err != nil {\n+ t.Fatalf(\"runsc do: %v\", err)\n+ }\n+ t.Log(string(out))\n+\n+ // Wait until the sandbox disconnects to ensure all points were gathered.\n+ server.WaitForNoClients()\n+ matchPoints(t, server.GetPoints())\n+}\n+\n+func buildPodConfig(runscPath, endpoint string) (*boot.InitConfig, error) {\n+ pts, err := allPoints(runscPath)\n+ if err != nil {\n+ return nil, err\n+ }\n+ return &boot.InitConfig{\n+ TraceSession: seccheck.SessionConfig{\n+ Name: seccheck.DefaultSessionName,\n+ Points: pts,\n+ Sinks: []seccheck.SinkConfig{\n+ {\n+ Name: \"remote\",\n+ Config: map[string]interface{}{\n+ \"endpoint\": endpoint,\n+ },\n+ },\n+ },\n+ },\n+ }, nil\n+}\n+\n+func allPoints(runscPath string) ([]seccheck.PointConfig, error) {\n+ cmd := exec.Command(runscPath, \"trace\", \"metadata\")\n+ out, err := cmd.CombinedOutput()\n+ if err != nil {\n+ return nil, err\n+ }\n+\n+ // The command above produces an output like the following:\n+ // POINTS (907)\n+ // Name: container/start, optional fields: [], context fields: [time|thread_id]\n+ scanner := bufio.NewScanner(bytes.NewReader(out))\n+ if !scanner.Scan() {\n+ return nil, fmt.Errorf(\"%q returned empty\", cmd)\n+ }\n+ if !scanner.Scan() {\n+ return nil, fmt.Errorf(\"%q returned empty\", cmd)\n+ }\n+ var points []seccheck.PointConfig\n+ for line := scanner.Text(); scanner.Scan(); line = scanner.Text() {\n+ elems := strings.Split(line, \",\")\n+ if len(elems) != 3 {\n+ return nil, fmt.Errorf(\"invalid line: %q\", line)\n+ }\n+ name := strings.TrimPrefix(elems[0], \"Name: \")\n+ optFields, err := parseFields(elems[1], \"optional fields: \")\n+ if err != nil {\n+ return nil, err\n+ }\n+ ctxFields, err := parseFields(elems[2], \"context fields: \")\n+ if err != nil {\n+ return nil, err\n+ }\n+ points = append(points, seccheck.PointConfig{\n+ Name: name,\n+ OptionalFields: optFields,\n+ ContextFields: ctxFields,\n+ })\n+ }\n+ if scanner.Err() != nil {\n+ return nil, scanner.Err()\n+ }\n+ return points, nil\n+}\n+\n+func parseFields(elem, prefix string) ([]string, error) {\n+ stripped := strings.TrimPrefix(strings.TrimSpace(elem), prefix)\n+ switch {\n+ case len(stripped) < 2:\n+ return nil, fmt.Errorf(\"invalid %s format: %q\", prefix, elem)\n+ case len(stripped) == 2:\n+ return nil, nil\n+ }\n+ // Remove [] from `stripped`.\n+ clean := stripped[1 : len(stripped)-1]\n+ return strings.Split(clean, \"|\"), nil\n+}\n+\n+func matchPoints(t *testing.T, msgs []test.Message) {\n+ // Register functions that verify each available point.\n+ matchers := map[pb.MessageType]*struct {\n+ checker func(test.Message) error\n+ count int\n+ }{\n+ pb.MessageType_MESSAGE_CONTAINER_START: {checker: checkContainerStart},\n+ pb.MessageType_MESSAGE_SENTRY_TASK_EXIT: {checker: checkSentryTaskExit},\n+ pb.MessageType_MESSAGE_SYSCALL_RAW: {checker: checkSyscallRaw},\n+ pb.MessageType_MESSAGE_SYSCALL_OPEN: {checker: checkSyscallOpen},\n+ pb.MessageType_MESSAGE_SYSCALL_CLOSE: {checker: checkSyscallClose},\n+ pb.MessageType_MESSAGE_SYSCALL_READ: {checker: checkSyscallRead},\n+ }\n+ for _, msg := range msgs {\n+ t.Logf(\"Processing message type %v\", msg.MsgType)\n+ if handler := matchers[msg.MsgType]; handler == nil {\n+ // All points generated should have a corresponding matcher.\n+ t.Errorf(\"No matcher for message type %v\", msg.MsgType)\n+ } else {\n+ handler.count++\n+ if err := handler.checker(msg); err != nil {\n+ t.Errorf(\"message type %v: %v\", msg.MsgType, err)\n+ }\n+ }\n+ }\n+ for msgType, match := range matchers {\n+ t.Logf(\"Processed %d messages for %v\", match.count, msgType)\n+ if match.count == 0 {\n+ // All matchers should be triggered at least once to ensure points are\n+ // firing with the workload.\n+ t.Errorf(\"no point was generated for %v\", msgType)\n+ }\n+ }\n+}\n+\n+func checkContextData(data *pb.ContextData) error {\n+ if data == nil {\n+ return fmt.Errorf(\"ContextData should not be nil\")\n+ }\n+ if !strings.HasPrefix(data.ContainerId, \"runsc-\") {\n+ return fmt.Errorf(\"invalid container ID %q\", data.ContainerId)\n+ }\n+\n+ cutoff := time.Now().Add(-time.Minute)\n+ if data.TimeNs <= int64(cutoff.Nanosecond()) {\n+ return fmt.Errorf(\"time should not be less than %d (%v), got: %d (%v)\", cutoff.Nanosecond(), cutoff, data.TimeNs, time.Unix(0, data.TimeNs))\n+ }\n+ if data.ThreadStartTimeNs <= int64(cutoff.Nanosecond()) {\n+ return fmt.Errorf(\"thread_start_time should not be less than %d (%v), got: %d (%v)\", cutoff.Nanosecond(), cutoff, data.ThreadStartTimeNs, time.Unix(0, data.ThreadStartTimeNs))\n+ }\n+ if data.ThreadStartTimeNs > data.TimeNs {\n+ return fmt.Errorf(\"thread_start_time should not be greater than point time: %d (%v), got: %d (%v)\", data.TimeNs, time.Unix(0, data.TimeNs), data.ThreadStartTimeNs, time.Unix(0, data.ThreadStartTimeNs))\n+ }\n+ if data.ThreadGroupStartTimeNs <= int64(cutoff.Nanosecond()) {\n+ return fmt.Errorf(\"thread_group_start_time should not be less than %d (%v), got: %d (%v)\", cutoff.Nanosecond(), cutoff, data.ThreadGroupStartTimeNs, time.Unix(0, data.ThreadGroupStartTimeNs))\n+ }\n+ if data.ThreadGroupStartTimeNs > data.TimeNs {\n+ return fmt.Errorf(\"thread_group_start_time should not be greater than point time: %d (%v), got: %d (%v)\", data.TimeNs, time.Unix(0, data.TimeNs), data.ThreadGroupStartTimeNs, time.Unix(0, data.ThreadGroupStartTimeNs))\n+ }\n+\n+ if data.ThreadId <= 0 {\n+ return fmt.Errorf(\"invalid thread_id: %v\", data.ThreadId)\n+ }\n+ if data.ThreadGroupId <= 0 {\n+ return fmt.Errorf(\"invalid thread_group_id: %v\", data.ThreadGroupId)\n+ }\n+ if len(data.Cwd) == 0 {\n+ return fmt.Errorf(\"invalid cwd: %v\", data.Cwd)\n+ }\n+ if len(data.ProcessName) == 0 {\n+ return fmt.Errorf(\"invalid process_name: %v\", data.ProcessName)\n+ }\n+ return nil\n+}\n+\n+func checkContainerStart(msg test.Message) error {\n+ p := pb.Start{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ if err := checkContextData(p.ContextData); err != nil {\n+ return err\n+ }\n+ if !strings.HasPrefix(p.Id, \"runsc-\") {\n+ return fmt.Errorf(\"invalid container ID %q\", p.Id)\n+ }\n+ cwd, err := os.Getwd()\n+ if err != nil {\n+ return fmt.Errorf(\"Getwd(): %v\", err)\n+ }\n+ if cwd != p.Cwd {\n+ return fmt.Errorf(\"invalid cwd, want: %q, got: %q\", cwd, p.Cwd)\n+ }\n+ if len(p.Args) == 0 {\n+ return fmt.Errorf(\"empty args\")\n+ }\n+ if len(p.Env) == 0 {\n+ return fmt.Errorf(\"empty env\")\n+ }\n+ for _, e := range p.Env {\n+ if strings.IndexRune(e, '=') == -1 {\n+ return fmt.Errorf(\"malformed env: %q\", e)\n+ }\n+ }\n+ if p.Terminal {\n+ return fmt.Errorf(\"terminal should be off\")\n+ }\n+ return nil\n+}\n+\n+func checkSentryTaskExit(msg test.Message) error {\n+ p := pb.TaskExit{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ if err := checkContextData(p.ContextData); err != nil {\n+ return err\n+ }\n+ return nil\n+}\n+\n+func checkSyscallRaw(msg test.Message) error {\n+ p := pb.Syscall{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ if err := checkContextData(p.ContextData); err != nil {\n+ return err\n+ }\n+ // Sanity check that Sysno is within valid range. If sysno could be larger\n+ // than the value below, update it accordingly.\n+ if p.Sysno > 500 {\n+ return fmt.Errorf(\"invalid syscall number %d\", p.Sysno)\n+ }\n+ return nil\n+}\n+\n+func checkSyscallClose(msg test.Message) error {\n+ p := pb.Close{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ if err := checkContextData(p.ContextData); err != nil {\n+ return err\n+ }\n+ if p.Fd < 0 {\n+ // Although negative FD is possible, it doesn't happen in the test.\n+ return fmt.Errorf(\"closing negative FD: %d\", p.Fd)\n+ }\n+ return nil\n+}\n+\n+func checkSyscallOpen(msg test.Message) error {\n+ p := pb.Open{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ if err := checkContextData(p.ContextData); err != nil {\n+ return err\n+ }\n+ return nil\n+}\n+\n+func checkSyscallRead(msg test.Message) error {\n+ p := pb.Read{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ if err := checkContextData(p.ContextData); err != nil {\n+ return err\n+ }\n+ if p.Fd < 0 {\n+ // Although negative FD is possible, it doesn't happen in the test.\n+ return fmt.Errorf(\"reading negative FD: %d\", p.Fd)\n+ }\n+ return nil\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/trace/workload/BUILD",
"diff": "+load(\"//tools:defs.bzl\", \"cc_binary\")\n+\n+package(licenses = [\"notice\"])\n+\n+cc_binary(\n+ name = \"workload\",\n+ testonly = 1,\n+ srcs = [\n+ \"workload.cc\",\n+ ],\n+ visibility = [\"//test/trace:__pkg__\"],\n+ deps = [\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/trace/workload/workload.cc",
"diff": "+// Copyright 2022 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+// Empty for now. Actual workload will be added as more points are covered.\n+int main(int argc, char** argv) { return 0; }\n"
}
] | Go | Apache License 2.0 | google/gvisor | Trace points integration test
Updates #4805
PiperOrigin-RevId: 451007875 |
259,907 | 25.05.2022 15:27:33 | 25,200 | a3892a07b5a16b6cc0bbc03d723ddfe2d64a8a57 | Add support for prlimit(RLIMIT_NOFILE) to trace procfs.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/limits/limits.go",
"new_path": "pkg/sentry/limits/limits.go",
"diff": "@@ -51,9 +51,9 @@ const Infinity = ^uint64(0)\n// +stateify savable\ntype Limit struct {\n// Cur specifies the current limit.\n- Cur uint64\n+ Cur uint64 `json:\"cur,omitempty\"`\n// Max specifies the maximum settable limit.\n- Max uint64\n+ Max uint64 `json:\"max,omitempty\"`\n}\n// LimitSet represents the Limits that correspond to each LimitType.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/procfs/BUILD",
"new_path": "runsc/boot/procfs/BUILD",
"diff": "@@ -11,6 +11,7 @@ go_library(\n\"//pkg/log\",\n\"//pkg/sentry/fsimpl/proc\",\n\"//pkg/sentry/kernel\",\n+ \"//pkg/sentry/limits\",\n\"//pkg/sentry/mm\",\n\"//pkg/sentry/vfs\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/procfs/dump.go",
"new_path": "runsc/boot/procfs/dump.go",
"diff": "@@ -25,6 +25,7 @@ import (\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/proc\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/limits\"\n\"gvisor.dev/gvisor/pkg/sentry/mm\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n)\n@@ -57,6 +58,9 @@ type ProcessProcfsDump struct {\nStartTime int64 `json:\"clone_ts,omitempty\"`\n// Root is /proc/[pid]/root.\nRoot string `json:\"root,omitempty\"`\n+ // Limits constains resource limits for this process. Currently only\n+ // RLIMIT_NOFILE is supported.\n+ Limits map[string]limits.Limit `json:\"limits,omitempty\"`\n}\n// getMM returns t's MemoryManager. On success, the MemoryManager's users count\n@@ -170,6 +174,13 @@ func getRoot(t *kernel.Task, pid kernel.ThreadID) string {\nreturn path\n}\n+func getFDLimit(ctx context.Context, pid kernel.ThreadID) (limits.Limit, error) {\n+ if limitSet := limits.FromContext(ctx); limitSet != nil {\n+ return limitSet.Get(limits.NumberOfFiles), nil\n+ }\n+ return limits.Limit{}, fmt.Errorf(\"could not find limit set for pid %s\", pid)\n+}\n+\n// Dump returns a procfs dump for process pid. t must be a task in process pid.\nfunc Dump(t *kernel.Task, pid kernel.ThreadID) (ProcessProcfsDump, error) {\nctx := t.AsyncContext()\n@@ -180,6 +191,11 @@ func Dump(t *kernel.Task, pid kernel.ThreadID) (ProcessProcfsDump, error) {\n}\ndefer mm.DecUsers(ctx)\n+ fdLimit, err := getFDLimit(ctx, pid)\n+ if err != nil {\n+ return ProcessProcfsDump{}, err\n+ }\n+\nreturn ProcessProcfsDump{\nPID: int32(pid),\nExe: getExecutablePath(ctx, pid, mm),\n@@ -189,5 +205,8 @@ func Dump(t *kernel.Task, pid kernel.ThreadID) (ProcessProcfsDump, error) {\nFDs: getFDs(ctx, t, pid),\nStartTime: t.StartTime().Nanoseconds(),\nRoot: getRoot(t, pid),\n+ Limits: map[string]limits.Limit{\n+ \"RLIMIT_NOFILE\": fdLimit,\n+ },\n}, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/BUILD",
"new_path": "runsc/container/BUILD",
"diff": "@@ -70,6 +70,7 @@ go_test(\n\"//pkg/sentry/control\",\n\"//pkg/sentry/kernel\",\n\"//pkg/sentry/kernel/auth\",\n+ \"//pkg/sentry/limits\",\n\"//pkg/sentry/platform\",\n\"//pkg/sentry/seccheck\",\n\"//pkg/sentry/seccheck/checkers/remote/test\",\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/trace_test.go",
"new_path": "runsc/container/trace_test.go",
"diff": "@@ -21,7 +21,9 @@ import (\n\"testing\"\n\"time\"\n+ specs \"github.com/opencontainers/runtime-spec/specs-go\"\n\"google.golang.org/protobuf/proto\"\n+ \"gvisor.dev/gvisor/pkg/sentry/limits\"\n\"gvisor.dev/gvisor/pkg/sentry/seccheck\"\n\"gvisor.dev/gvisor/pkg/sentry/seccheck/checkers/remote/test\"\npb \"gvisor.dev/gvisor/pkg/sentry/seccheck/points/points_go_proto\"\n@@ -295,6 +297,13 @@ func TestProcfsDump(t *testing.T) {\ntestEnv := \"GVISOR_IS_GREAT=true\"\nspec.Process.Env = append(spec.Process.Env, testEnv)\nspec.Process.Cwd = \"/\"\n+ fdLimit := limits.Limit{\n+ Cur: 10_000,\n+ Max: 100_000,\n+ }\n+ spec.Process.Rlimits = []specs.POSIXRlimit{\n+ {Type: \"RLIMIT_NOFILE\", Hard: fdLimit.Max, Soft: fdLimit.Cur},\n+ }\n_, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)\nif err != nil {\nt.Fatalf(\"error setting up container: %v\", err)\n@@ -383,4 +392,8 @@ func TestProcfsDump(t *testing.T) {\nif want := \"/\"; procfsDump[0].Root != \"/\" {\nt.Errorf(\"expected root to be %q, but got %q\", want, procfsDump[0].Root)\n}\n+\n+ if got := procfsDump[0].Limits[\"RLIMIT_NOFILE\"]; got != fdLimit {\n+ t.Errorf(\"expected FD limit to be %+v, but got %+v\", fdLimit, got)\n+ }\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add support for prlimit(RLIMIT_NOFILE) to trace procfs.
Updates #4805
PiperOrigin-RevId: 451029238 |
259,966 | 26.05.2022 08:02:48 | 25,200 | 33c687560388eab79133f3cf1f8a69afc8c9d200 | Implement remove multicast route.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4.go",
"diff": "@@ -1521,6 +1521,20 @@ func (p *protocol) AddMulticastRoute(addresses stack.UnicastSourceAndMulticastDe\nreturn nil\n}\n+// RemoveMulticastRoute implements\n+// stack.MulticastForwardingNetworkProtocol.RemoveMulticastRoute.\n+func (p *protocol) RemoveMulticastRoute(addresses stack.UnicastSourceAndMulticastDestination) tcpip.Error {\n+ if err := p.validateUnicastSourceAndMulticastDestination(addresses); err != nil {\n+ return err\n+ }\n+\n+ if removed := p.multicastRouteTable.RemoveInstalledRoute(addresses); !removed {\n+ return &tcpip.ErrNoRoute{}\n+ }\n+\n+ return nil\n+}\n+\nfunc (p *protocol) forwardPendingMulticastPacket(pkt *stack.PacketBuffer, installedRoute *multicast.InstalledRoute) {\ndefer pkt.DecRef()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6.go",
"diff": "@@ -2320,6 +2320,20 @@ func (p *protocol) AddMulticastRoute(addresses stack.UnicastSourceAndMulticastDe\nreturn nil\n}\n+// RemoveMulticastRoute implements\n+// stack.MulticastForwardingNetworkProtocol.RemoveMulticastRoute.\n+func (p *protocol) RemoveMulticastRoute(addresses stack.UnicastSourceAndMulticastDestination) tcpip.Error {\n+ if err := validateUnicastSourceAndMulticastDestination(addresses); err != nil {\n+ return err\n+ }\n+\n+ if removed := p.multicastRouteTable.RemoveInstalledRoute(addresses); !removed {\n+ return &tcpip.ErrNoRoute{}\n+ }\n+\n+ return nil\n+}\n+\nfunc (p *protocol) forwardPendingMulticastPacket(pkt *stack.PacketBuffer, installedRoute *multicast.InstalledRoute) {\ndefer pkt.DecRef()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/registration.go",
"new_path": "pkg/tcpip/stack/registration.go",
"diff": "@@ -802,6 +802,13 @@ type MulticastForwardingNetworkProtocol interface {\n//\n// Returns an error if the addresses or route is invalid.\nAddMulticastRoute(UnicastSourceAndMulticastDestination, MulticastRoute) tcpip.Error\n+\n+ // RemoveMulticastRoute removes the route matching the provided addresses\n+ // from the multicast routing table.\n+ //\n+ // Returns an error if the addresses are invalid or a matching route is not\n+ // found.\n+ RemoveMulticastRoute(UnicastSourceAndMulticastDestination) tcpip.Error\n}\n// NetworkDispatcher contains the methods used by the network stack to deliver\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -564,6 +564,22 @@ func (s *Stack) SetForwardingDefaultAndAllNICs(protocol tcpip.NetworkProtocolNum\nreturn nil\n}\n+// RemoveMulticastRoute removes a multicast route that matches the specified\n+// addresses and protocol.\n+func (s *Stack) RemoveMulticastRoute(protocol tcpip.NetworkProtocolNumber, addresses UnicastSourceAndMulticastDestination) tcpip.Error {\n+ netProto, ok := s.networkProtocols[protocol]\n+ if !ok {\n+ return &tcpip.ErrUnknownProtocol{}\n+ }\n+\n+ forwardingNetProto, ok := netProto.(MulticastForwardingNetworkProtocol)\n+ if !ok {\n+ return &tcpip.ErrNotSupported{}\n+ }\n+\n+ return forwardingNetProto.RemoveMulticastRoute(addresses)\n+}\n+\n// AddMulticastRoute adds a multicast route to be used for the specified\n// addresses and protocol.\nfunc (s *Stack) AddMulticastRoute(protocol tcpip.NetworkProtocolNumber, addresses UnicastSourceAndMulticastDestination, route MulticastRoute) tcpip.Error {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack_test.go",
"new_path": "pkg/tcpip/stack/stack_test.go",
"diff": "@@ -242,6 +242,7 @@ type fakeNetworkProtocol struct {\ndefaultTTL uint8\naddMulticastRouteData addMulticastRouteData\n+ removeMulticastRouteData stack.UnicastSourceAndMulticastDestination\n}\nfunc (*fakeNetworkProtocol) Number() tcpip.NetworkProtocolNumber {\n@@ -313,6 +314,13 @@ func (f *fakeNetworkProtocol) AddMulticastRoute(addresses stack.UnicastSourceAnd\nreturn nil\n}\n+// RemoveMulticastRoute implements\n+// MulticastForwardingNetworkProtocol.RemoveMulticastRoute.\n+func (f *fakeNetworkProtocol) RemoveMulticastRoute(addresses stack.UnicastSourceAndMulticastDestination) tcpip.Error {\n+ f.removeMulticastRouteData = addresses\n+ return nil\n+}\n+\n// Forwarding implements stack.ForwardingNetworkEndpoint.\nfunc (f *fakeNetworkEndpoint) Forwarding() bool {\nf.mu.RLock()\n@@ -4740,6 +4748,58 @@ func TestAddMulticastRoute(t *testing.T) {\n}\n}\n+func TestRemoveMulticastRoute(t *testing.T) {\n+ const nicID = 1\n+ address := testutil.MustParse4(\"192.168.1.1\")\n+ addresses := stack.UnicastSourceAndMulticastDestination{Source: address, Destination: address}\n+\n+ tests := []struct {\n+ name string\n+ netProto tcpip.NetworkProtocolNumber\n+ factory stack.NetworkProtocolFactory\n+ wantErr tcpip.Error\n+ }{\n+ {\n+ name: \"valid\",\n+ netProto: fakeNetNumber,\n+ factory: fakeNetFactory,\n+ wantErr: nil,\n+ },\n+ {\n+ name: \"unknown protocol\",\n+ factory: fakeNetFactory,\n+ netProto: arp.ProtocolNumber,\n+ wantErr: &tcpip.ErrUnknownProtocol{},\n+ },\n+ {\n+ name: \"not supported\",\n+ factory: arp.NewProtocol,\n+ netProto: arp.ProtocolNumber,\n+ wantErr: &tcpip.ErrNotSupported{},\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.NetworkProtocolFactory{test.factory},\n+ })\n+\n+ err := s.RemoveMulticastRoute(test.netProto, addresses)\n+\n+ if !cmp.Equal(err, test.wantErr, cmpopts.EquateErrors()) {\n+ t.Errorf(\"s.RemoveMulticastRoute(%d, %#v) = %s, want %s\", test.netProto, addresses, err, test.wantErr)\n+ }\n+\n+ if test.wantErr == nil {\n+ fakeNet := s.NetworkProtocolInstance(fakeNetNumber).(*fakeNetworkProtocol)\n+ if !cmp.Equal(fakeNet.removeMulticastRouteData, addresses) {\n+ t.Errorf(\"fakeNet.removeMulticastRouteData = %#v, want = %#v\", fakeNet.removeMulticastRouteData, addresses)\n+ }\n+ }\n+ })\n+ }\n+}\n+\nfunc TestNICForwarding(t *testing.T) {\nconst nicID = 1\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/integration/multicast_forward_test.go",
"new_path": "pkg/tcpip/tests/integration/multicast_forward_test.go",
"diff": "@@ -419,6 +419,170 @@ func TestAddMulticastRoute(t *testing.T) {\n}\n}\n+func TestRemoveMulticastRoute(t *testing.T) {\n+ endpointConfigs := map[tcpip.NICID]endpointAddrType{\n+ incomingNICID: incomingEndpointAddr,\n+ outgoingNICID: outgoingEndpointAddr,\n+ otherNICID: otherEndpointAddr,\n+ }\n+\n+ tests := []struct {\n+ name string\n+ srcAddr, dstAddr addrType\n+ wantErr tcpip.Error\n+ }{\n+ {\n+ name: \"success\",\n+ srcAddr: remoteUnicastAddr,\n+ dstAddr: multicastAddr,\n+ wantErr: nil,\n+ },\n+ {\n+ name: \"no matching route\",\n+ srcAddr: remoteUnicastAddr,\n+ dstAddr: otherMulticastAddr,\n+ wantErr: &tcpip.ErrNoRoute{},\n+ },\n+ {\n+ name: \"multicast source\",\n+ srcAddr: multicastAddr,\n+ dstAddr: multicastAddr,\n+ wantErr: &tcpip.ErrBadAddress{},\n+ },\n+ {\n+ name: \"any source\",\n+ srcAddr: anyAddr,\n+ dstAddr: multicastAddr,\n+ wantErr: &tcpip.ErrBadAddress{},\n+ },\n+ {\n+ name: \"link-local unicast source\",\n+ srcAddr: linkLocalUnicastAddr,\n+ dstAddr: multicastAddr,\n+ wantErr: &tcpip.ErrBadAddress{},\n+ },\n+ {\n+ name: \"empty source\",\n+ srcAddr: emptyAddr,\n+ dstAddr: multicastAddr,\n+ wantErr: &tcpip.ErrBadAddress{},\n+ },\n+ {\n+ name: \"unicast destination\",\n+ srcAddr: remoteUnicastAddr,\n+ dstAddr: remoteUnicastAddr,\n+ wantErr: &tcpip.ErrBadAddress{},\n+ },\n+ {\n+ name: \"empty destination\",\n+ srcAddr: remoteUnicastAddr,\n+ dstAddr: emptyAddr,\n+ wantErr: &tcpip.ErrBadAddress{},\n+ },\n+ {\n+ name: \"link-local multicast destination\",\n+ srcAddr: remoteUnicastAddr,\n+ dstAddr: linkLocalMulticastAddr,\n+ wantErr: &tcpip.ErrBadAddress{},\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ for _, protocol := range []tcpip.NetworkProtocolNumber{ipv4.ProtocolNumber, ipv6.ProtocolNumber} {\n+ t.Run(fmt.Sprintf(\"%s %d\", test.name, protocol), func(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},\n+ TransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol},\n+ })\n+ defer s.Close()\n+\n+ endpoints := make(map[tcpip.NICID]*channel.Endpoint)\n+ for nicID, addrType := range endpointConfigs {\n+ ep := channel.New(1, ipv4.MaxTotalSize, \"\")\n+ defer ep.Close()\n+\n+ if err := s.CreateNIC(nicID, ep); err != nil {\n+ t.Fatalf(\"s.CreateNIC(%d, _): %s\", nicID, err)\n+ }\n+ addr := tcpip.ProtocolAddress{\n+ Protocol: protocol,\n+ AddressWithPrefix: getEndpointAddr(protocol, addrType),\n+ }\n+ if err := s.AddProtocolAddress(nicID, addr, stack.AddressProperties{}); err != nil {\n+ t.Fatalf(\"s.AddProtocolAddress(%d, %#v, {}): %s\", nicID, addr, err)\n+ }\n+ s.SetNICMulticastForwarding(nicID, protocol, true /* enabled */)\n+ endpoints[nicID] = ep\n+ }\n+\n+ srcAddr := getAddr(protocol, remoteUnicastAddr)\n+ dstAddr := getAddr(protocol, multicastAddr)\n+\n+ outgoingInterfaces := []stack.MulticastRouteOutgoingInterface{\n+ {ID: outgoingNICID, MinTTL: routeMinTTL},\n+ }\n+\n+ addresses := stack.UnicastSourceAndMulticastDestination{\n+ Source: srcAddr,\n+ Destination: dstAddr,\n+ }\n+\n+ route := stack.MulticastRoute{\n+ ExpectedInputInterface: incomingNICID,\n+ OutgoingInterfaces: outgoingInterfaces,\n+ }\n+\n+ if err := s.AddMulticastRoute(protocol, addresses, route); err != nil {\n+ t.Fatalf(\"got s.AddMulticastRoute(%d, %#v, %#v) = %s, want = nil\", protocol, addresses, route, err)\n+ }\n+\n+ addresses = stack.UnicastSourceAndMulticastDestination{\n+ Source: getAddr(protocol, test.srcAddr),\n+ Destination: getAddr(protocol, test.dstAddr),\n+ }\n+ err := s.RemoveMulticastRoute(protocol, addresses)\n+\n+ if !cmp.Equal(err, test.wantErr, cmpopts.EquateErrors()) {\n+ t.Errorf(\"got s.RemoveMulticastRoute(%d, %#v) = %s, want %s\", protocol, addresses, err, test.wantErr)\n+ }\n+\n+ incomingEp, ok := endpoints[incomingNICID]\n+ if !ok {\n+ t.Fatalf(\"got endpoints[%d] = (_, false), want (_, true)\", incomingNICID)\n+ }\n+\n+ injectPacket(incomingEp, protocol, srcAddr, dstAddr, packetTTL)\n+ p := incomingEp.Read()\n+\n+ if p != nil {\n+ // An ICMP error should never be sent in response to a multicast\n+ // packet.\n+ t.Errorf(\"expected no ICMP packet through incoming NIC, instead found: %#v\", p)\n+ }\n+\n+ outgoingEp, ok := endpoints[outgoingNICID]\n+ if !ok {\n+ t.Fatalf(\"got endpoints[%d] = (_, false), want (_, true)\", outgoingNICID)\n+ }\n+\n+ p = outgoingEp.Read()\n+\n+ // If the route was successfully removed, then the packet should not be\n+ // forwarded.\n+ expectForward := test.wantErr != nil\n+ if (p != nil) != expectForward {\n+ t.Fatalf(\"got outgoingEp.Read() = %#v, want = (_ == nil) = %t\", p, expectForward)\n+ }\n+\n+ if expectForward {\n+ checkEchoRequest(t, protocol, p, srcAddr, dstAddr, packetTTL-1)\n+ p.DecRef()\n+ }\n+ })\n+ }\n+ }\n+}\n+\nfunc TestMulticastForwarding(t *testing.T) {\nendpointConfigs := map[tcpip.NICID]endpointAddrType{\nincomingNICID: incomingEndpointAddr,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement remove multicast route.
Updates #7338.
PiperOrigin-RevId: 451162886 |
259,966 | 26.05.2022 08:56:43 | 25,200 | e9520375517bfb0c868019cad4574254012ad07f | Implement GetMulticastRouteLastUsedTime.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4.go",
"diff": "@@ -1535,6 +1535,22 @@ func (p *protocol) RemoveMulticastRoute(addresses stack.UnicastSourceAndMulticas\nreturn nil\n}\n+// MulticastRouteLastUsedTime implements\n+// stack.MulticastForwardingNetworkProtocol.\n+func (p *protocol) MulticastRouteLastUsedTime(addresses stack.UnicastSourceAndMulticastDestination) (tcpip.MonotonicTime, tcpip.Error) {\n+ if err := p.validateUnicastSourceAndMulticastDestination(addresses); err != nil {\n+ return tcpip.MonotonicTime{}, err\n+ }\n+\n+ timestamp, found := p.multicastRouteTable.GetLastUsedTimestamp(addresses)\n+\n+ if !found {\n+ return tcpip.MonotonicTime{}, &tcpip.ErrNoRoute{}\n+ }\n+\n+ return timestamp, nil\n+}\n+\nfunc (p *protocol) forwardPendingMulticastPacket(pkt *stack.PacketBuffer, installedRoute *multicast.InstalledRoute) {\ndefer pkt.DecRef()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6.go",
"diff": "@@ -2334,6 +2334,22 @@ func (p *protocol) RemoveMulticastRoute(addresses stack.UnicastSourceAndMulticas\nreturn nil\n}\n+// MulticastRouteLastUsedTime implements\n+// stack.MulticastForwardingNetworkProtocol.\n+func (p *protocol) MulticastRouteLastUsedTime(addresses stack.UnicastSourceAndMulticastDestination) (tcpip.MonotonicTime, tcpip.Error) {\n+ if err := validateUnicastSourceAndMulticastDestination(addresses); err != nil {\n+ return tcpip.MonotonicTime{}, err\n+ }\n+\n+ timestamp, found := p.multicastRouteTable.GetLastUsedTimestamp(addresses)\n+\n+ if !found {\n+ return tcpip.MonotonicTime{}, &tcpip.ErrNoRoute{}\n+ }\n+\n+ return timestamp, nil\n+}\n+\nfunc (p *protocol) forwardPendingMulticastPacket(pkt *stack.PacketBuffer, installedRoute *multicast.InstalledRoute) {\ndefer pkt.DecRef()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/registration.go",
"new_path": "pkg/tcpip/stack/registration.go",
"diff": "@@ -809,6 +809,14 @@ type MulticastForwardingNetworkProtocol interface {\n// Returns an error if the addresses are invalid or a matching route is not\n// found.\nRemoveMulticastRoute(UnicastSourceAndMulticastDestination) tcpip.Error\n+\n+ // MulticastRouteLastUsedTime returns a monotonic timestamp that\n+ // represents the last time that the route matching the provided addresses\n+ // was used or updated.\n+ //\n+ // Returns an error if the addresses are invalid or a matching route was not\n+ // found.\n+ MulticastRouteLastUsedTime(UnicastSourceAndMulticastDestination) (tcpip.MonotonicTime, tcpip.Error)\n}\n// NetworkDispatcher contains the methods used by the network stack to deliver\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -564,9 +564,9 @@ func (s *Stack) SetForwardingDefaultAndAllNICs(protocol tcpip.NetworkProtocolNum\nreturn nil\n}\n-// RemoveMulticastRoute removes a multicast route that matches the specified\n+// AddMulticastRoute adds a multicast route to be used for the specified\n// addresses and protocol.\n-func (s *Stack) RemoveMulticastRoute(protocol tcpip.NetworkProtocolNumber, addresses UnicastSourceAndMulticastDestination) tcpip.Error {\n+func (s *Stack) AddMulticastRoute(protocol tcpip.NetworkProtocolNumber, addresses UnicastSourceAndMulticastDestination, route MulticastRoute) tcpip.Error {\nnetProto, ok := s.networkProtocols[protocol]\nif !ok {\nreturn &tcpip.ErrUnknownProtocol{}\n@@ -577,12 +577,12 @@ func (s *Stack) RemoveMulticastRoute(protocol tcpip.NetworkProtocolNumber, addre\nreturn &tcpip.ErrNotSupported{}\n}\n- return forwardingNetProto.RemoveMulticastRoute(addresses)\n+ return forwardingNetProto.AddMulticastRoute(addresses, route)\n}\n-// AddMulticastRoute adds a multicast route to be used for the specified\n+// RemoveMulticastRoute removes a multicast route that matches the specified\n// addresses and protocol.\n-func (s *Stack) AddMulticastRoute(protocol tcpip.NetworkProtocolNumber, addresses UnicastSourceAndMulticastDestination, route MulticastRoute) tcpip.Error {\n+func (s *Stack) RemoveMulticastRoute(protocol tcpip.NetworkProtocolNumber, addresses UnicastSourceAndMulticastDestination) tcpip.Error {\nnetProto, ok := s.networkProtocols[protocol]\nif !ok {\nreturn &tcpip.ErrUnknownProtocol{}\n@@ -593,7 +593,24 @@ func (s *Stack) AddMulticastRoute(protocol tcpip.NetworkProtocolNumber, addresse\nreturn &tcpip.ErrNotSupported{}\n}\n- return forwardingNetProto.AddMulticastRoute(addresses, route)\n+ return forwardingNetProto.RemoveMulticastRoute(addresses)\n+}\n+\n+// MulticastRouteLastUsedTime returns a monotonic timestamp that represents the\n+// last time that the route that matches the provided addresses and protocol\n+// was used or updated.\n+func (s *Stack) MulticastRouteLastUsedTime(protocol tcpip.NetworkProtocolNumber, addresses UnicastSourceAndMulticastDestination) (tcpip.MonotonicTime, tcpip.Error) {\n+ netProto, ok := s.networkProtocols[protocol]\n+ if !ok {\n+ return tcpip.MonotonicTime{}, &tcpip.ErrUnknownProtocol{}\n+ }\n+\n+ forwardingNetProto, ok := netProto.(MulticastForwardingNetworkProtocol)\n+ if !ok {\n+ return tcpip.MonotonicTime{}, &tcpip.ErrNotSupported{}\n+ }\n+\n+ return forwardingNetProto.MulticastRouteLastUsedTime(addresses)\n}\n// SetNICMulticastForwarding enables or disables multicast packet forwarding on\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack_test.go",
"new_path": "pkg/tcpip/stack/stack_test.go",
"diff": "@@ -242,6 +242,7 @@ type fakeNetworkProtocol struct {\ndefaultTTL uint8\naddMulticastRouteData addMulticastRouteData\n+ multicastRouteLastUsedTimeData stack.UnicastSourceAndMulticastDestination\nremoveMulticastRouteData stack.UnicastSourceAndMulticastDestination\n}\n@@ -321,6 +322,13 @@ func (f *fakeNetworkProtocol) RemoveMulticastRoute(addresses stack.UnicastSource\nreturn nil\n}\n+// MulticastRouteLastUsedTime implements\n+// MulticastForwardingNetworkProtocol.MulticastRouteLastUsedTime.\n+func (f *fakeNetworkProtocol) MulticastRouteLastUsedTime(addresses stack.UnicastSourceAndMulticastDestination) (tcpip.MonotonicTime, tcpip.Error) {\n+ f.multicastRouteLastUsedTimeData = addresses\n+ return tcpip.MonotonicTime{}, nil\n+}\n+\n// Forwarding implements stack.ForwardingNetworkEndpoint.\nfunc (f *fakeNetworkEndpoint) Forwarding() bool {\nf.mu.RLock()\n@@ -4800,6 +4808,58 @@ func TestRemoveMulticastRoute(t *testing.T) {\n}\n}\n+func TestMulticastRouteLastUsedTime(t *testing.T) {\n+ address := testutil.MustParse4(\"192.168.1.1\")\n+ addresses := stack.UnicastSourceAndMulticastDestination{Source: address, Destination: address}\n+\n+ tests := []struct {\n+ name string\n+ netProto tcpip.NetworkProtocolNumber\n+ factory stack.NetworkProtocolFactory\n+ wantErr tcpip.Error\n+ }{\n+ {\n+ name: \"valid\",\n+ netProto: fakeNetNumber,\n+ factory: fakeNetFactory,\n+ wantErr: nil,\n+ },\n+ {\n+ name: \"unknown protocol\",\n+ factory: fakeNetFactory,\n+ netProto: arp.ProtocolNumber,\n+ wantErr: &tcpip.ErrUnknownProtocol{},\n+ },\n+ {\n+ name: \"not supported\",\n+ factory: arp.NewProtocol,\n+ netProto: arp.ProtocolNumber,\n+ wantErr: &tcpip.ErrNotSupported{},\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.NetworkProtocolFactory{test.factory},\n+ })\n+\n+ _, err := s.MulticastRouteLastUsedTime(test.netProto, addresses)\n+\n+ if !cmp.Equal(err, test.wantErr, cmpopts.EquateErrors()) {\n+ t.Errorf(\"s.MulticastRouteLastUsedTime(%d, %#v) = %v, want %v\", test.netProto, addresses, err, test.wantErr)\n+ }\n+\n+ if test.wantErr == nil {\n+ fakeNet := s.NetworkProtocolInstance(fakeNetNumber).(*fakeNetworkProtocol)\n+\n+ if !cmp.Equal(fakeNet.multicastRouteLastUsedTimeData, addresses) {\n+ t.Errorf(\"fakeNet.multicastRouteLastUsedTimeData = %#v, want = %#v\", fakeNet.multicastRouteLastUsedTimeData, addresses)\n+ }\n+ }\n+ })\n+ }\n+}\n+\nfunc TestNICForwarding(t *testing.T) {\nconst nicID = 1\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/integration/BUILD",
"new_path": "pkg/tcpip/tests/integration/BUILD",
"diff": "@@ -177,6 +177,7 @@ go_test(\n\"//pkg/refsvfs2\",\n\"//pkg/tcpip\",\n\"//pkg/tcpip/checker\",\n+ \"//pkg/tcpip/faketime\",\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/link/channel\",\n\"//pkg/tcpip/network/ipv4\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/integration/multicast_forward_test.go",
"new_path": "pkg/tcpip/tests/integration/multicast_forward_test.go",
"diff": "@@ -18,6 +18,7 @@ import (\n\"fmt\"\n\"os\"\n\"testing\"\n+ \"time\"\n\"github.com/google/go-cmp/cmp\"\n\"github.com/google/go-cmp/cmp/cmpopts\"\n@@ -25,6 +26,7 @@ import (\n\"gvisor.dev/gvisor/pkg/refsvfs2\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/checker\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/faketime\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/channel\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv4\"\n@@ -419,6 +421,160 @@ func TestAddMulticastRoute(t *testing.T) {\n}\n}\n+func TestMulticastRouteLastUsedTime(t *testing.T) {\n+ endpointConfigs := map[tcpip.NICID]endpointAddrType{\n+ incomingNICID: incomingEndpointAddr,\n+ outgoingNICID: outgoingEndpointAddr,\n+ otherNICID: otherEndpointAddr,\n+ }\n+\n+ tests := []struct {\n+ name string\n+ srcAddr, dstAddr addrType\n+ wantErr tcpip.Error\n+ }{\n+ {\n+ name: \"success\",\n+ srcAddr: remoteUnicastAddr,\n+ dstAddr: multicastAddr,\n+ wantErr: nil,\n+ },\n+ {\n+ name: \"no matching route\",\n+ srcAddr: remoteUnicastAddr,\n+ dstAddr: otherMulticastAddr,\n+ wantErr: &tcpip.ErrNoRoute{},\n+ },\n+ {\n+ name: \"multicast source\",\n+ srcAddr: multicastAddr,\n+ dstAddr: multicastAddr,\n+ wantErr: &tcpip.ErrBadAddress{},\n+ },\n+ {\n+ name: \"any source\",\n+ srcAddr: anyAddr,\n+ dstAddr: multicastAddr,\n+ wantErr: &tcpip.ErrBadAddress{},\n+ },\n+ {\n+ name: \"link-local unicast source\",\n+ srcAddr: linkLocalUnicastAddr,\n+ dstAddr: multicastAddr,\n+ wantErr: &tcpip.ErrBadAddress{},\n+ },\n+ {\n+ name: \"empty source\",\n+ srcAddr: emptyAddr,\n+ dstAddr: multicastAddr,\n+ wantErr: &tcpip.ErrBadAddress{},\n+ },\n+ {\n+ name: \"unicast destination\",\n+ srcAddr: remoteUnicastAddr,\n+ dstAddr: remoteUnicastAddr,\n+ wantErr: &tcpip.ErrBadAddress{},\n+ },\n+ {\n+ name: \"empty destination\",\n+ srcAddr: remoteUnicastAddr,\n+ dstAddr: emptyAddr,\n+ wantErr: &tcpip.ErrBadAddress{},\n+ },\n+ {\n+ name: \"link-local multicast destination\",\n+ srcAddr: remoteUnicastAddr,\n+ dstAddr: linkLocalMulticastAddr,\n+ wantErr: &tcpip.ErrBadAddress{},\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ for _, protocol := range []tcpip.NetworkProtocolNumber{ipv4.ProtocolNumber, ipv6.ProtocolNumber} {\n+ t.Run(fmt.Sprintf(\"%s %d\", test.name, protocol), func(t *testing.T) {\n+ clock := faketime.NewManualClock()\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},\n+ TransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol},\n+ Clock: clock,\n+ })\n+ defer s.Close()\n+\n+ endpoints := make(map[tcpip.NICID]*channel.Endpoint)\n+ for nicID, addrType := range endpointConfigs {\n+ ep := channel.New(1, ipv4.MaxTotalSize, \"\")\n+ defer ep.Close()\n+\n+ if err := s.CreateNIC(nicID, ep); err != nil {\n+ t.Fatalf(\"s.CreateNIC(%d, _): %s\", nicID, err)\n+ }\n+ addr := tcpip.ProtocolAddress{\n+ Protocol: protocol,\n+ AddressWithPrefix: getEndpointAddr(protocol, addrType),\n+ }\n+ if err := s.AddProtocolAddress(nicID, addr, stack.AddressProperties{}); err != nil {\n+ t.Fatalf(\"s.AddProtocolAddress(%d, %#v, {}): %s\", nicID, addr, err)\n+ }\n+ s.SetNICMulticastForwarding(nicID, protocol, true /* enabled */)\n+ endpoints[nicID] = ep\n+ }\n+\n+ srcAddr := getAddr(protocol, remoteUnicastAddr)\n+ dstAddr := getAddr(protocol, multicastAddr)\n+\n+ outgoingInterfaces := []stack.MulticastRouteOutgoingInterface{\n+ {ID: outgoingNICID, MinTTL: routeMinTTL},\n+ }\n+\n+ addresses := stack.UnicastSourceAndMulticastDestination{\n+ Source: srcAddr,\n+ Destination: dstAddr,\n+ }\n+\n+ route := stack.MulticastRoute{\n+ ExpectedInputInterface: incomingNICID,\n+ OutgoingInterfaces: outgoingInterfaces,\n+ }\n+\n+ if err := s.AddMulticastRoute(protocol, addresses, route); err != nil {\n+ t.Fatalf(\"s.AddMulticastRoute(%d, %#v, %#v) = %s, want = nil\", protocol, addresses, route, err)\n+ }\n+\n+ incomingEp, ok := endpoints[incomingNICID]\n+ if !ok {\n+ t.Fatalf(\"Got endpoints[%d] = (_, false), want (_, true)\", incomingNICID)\n+ }\n+\n+ clock.Advance(10 * time.Second)\n+\n+ injectPacket(incomingEp, protocol, srcAddr, dstAddr, packetTTL)\n+ p := incomingEp.Read()\n+\n+ if p != nil {\n+ t.Fatalf(\"Expected no ICMP packet through incoming NIC, instead found: %#v\", p)\n+ }\n+\n+ addresses = stack.UnicastSourceAndMulticastDestination{\n+ Source: getAddr(protocol, test.srcAddr),\n+ Destination: getAddr(protocol, test.dstAddr),\n+ }\n+ timestamp, err := s.MulticastRouteLastUsedTime(protocol, addresses)\n+\n+ if !cmp.Equal(err, test.wantErr, cmpopts.EquateErrors()) {\n+ t.Errorf(\"s.MulticastRouteLastUsedTime(%d, %#v) = (_, %s), want = (_, %s)\", protocol, addresses, err, test.wantErr)\n+ }\n+\n+ if test.wantErr == nil {\n+ wantTimestamp := clock.NowMonotonic()\n+ if diff := cmp.Diff(wantTimestamp, timestamp, cmp.AllowUnexported(tcpip.MonotonicTime{})); diff != \"\" {\n+ t.Errorf(\"s.MulticastRouteLastUsedTime(%d, %#v) timestamp mismatch (-want +got):\\n%s\", protocol, addresses, diff)\n+ }\n+ }\n+ })\n+ }\n+ }\n+}\n+\nfunc TestRemoveMulticastRoute(t *testing.T) {\nendpointConfigs := map[tcpip.NICID]endpointAddrType{\nincomingNICID: incomingEndpointAddr,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement GetMulticastRouteLastUsedTime.
Updates #7338.
PiperOrigin-RevId: 451172827 |
259,891 | 26.05.2022 12:29:26 | 25,200 | 3dfcffdb157bc1888d1f370d3ef64089caed55e8 | remove checkescape from iptables.go
These fail on buildkite arm64 machines. While we figure out the problem, we
should unblock submits. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables.go",
"new_path": "pkg/tcpip/stack/iptables.go",
"diff": "@@ -315,7 +315,7 @@ func (it *IPTables) shouldSkipOrPopulateTables(tables []checkTable, pkt *PacketB\n// This is called in the hot path even when iptables are disabled, so we ensure\n// that it does not allocate. Note that called functions (e.g.\n// getConnAndUpdate) can allocate.\n-// +checkescape\n+// TODO(b/233951539): checkescape fails on arm sometimes. Fix and re-add.\nfunc (it *IPTables) CheckPrerouting(pkt *PacketBuffer, addressEP AddressableEndpoint, inNicName string) bool {\ntables := [...]checkTable{\n{\n@@ -353,7 +353,7 @@ func (it *IPTables) CheckPrerouting(pkt *PacketBuffer, addressEP AddressableEndp\n// This is called in the hot path even when iptables are disabled, so we ensure\n// that it does not allocate. Note that called functions (e.g.\n// getConnAndUpdate) can allocate.\n-// +checkescape\n+// TODO(b/233951539): checkescape fails on arm sometimes. Fix and re-add.\nfunc (it *IPTables) CheckInput(pkt *PacketBuffer, inNicName string) bool {\ntables := [...]checkTable{\n{\n@@ -393,7 +393,7 @@ func (it *IPTables) CheckInput(pkt *PacketBuffer, inNicName string) bool {\n// This is called in the hot path even when iptables are disabled, so we ensure\n// that it does not allocate. Note that called functions (e.g.\n// getConnAndUpdate) can allocate.\n-// +checkescape\n+// TODO(b/233951539): checkescape fails on arm sometimes. Fix and re-add.\nfunc (it *IPTables) CheckForward(pkt *PacketBuffer, inNicName, outNicName string) bool {\ntables := [...]checkTable{\n{\n@@ -425,7 +425,7 @@ func (it *IPTables) CheckForward(pkt *PacketBuffer, inNicName, outNicName string\n// This is called in the hot path even when iptables are disabled, so we ensure\n// that it does not allocate. Note that called functions (e.g.\n// getConnAndUpdate) can allocate.\n-// +checkescape\n+// TODO(b/233951539): checkescape fails on arm sometimes. Fix and re-add.\nfunc (it *IPTables) CheckOutput(pkt *PacketBuffer, r *Route, outNicName string) bool {\ntables := [...]checkTable{\n{\n@@ -467,7 +467,7 @@ func (it *IPTables) CheckOutput(pkt *PacketBuffer, r *Route, outNicName string)\n// This is called in the hot path even when iptables are disabled, so we ensure\n// that it does not allocate. Note that called functions (e.g.\n// getConnAndUpdate) can allocate.\n-// +checkescape\n+// TODO(b/233951539): checkescape fails on arm sometimes. Fix and re-add.\nfunc (it *IPTables) CheckPostrouting(pkt *PacketBuffer, r *Route, addressEP AddressableEndpoint, outNicName string) bool {\ntables := [...]checkTable{\n{\n"
}
] | Go | Apache License 2.0 | google/gvisor | remove checkescape from iptables.go
These fail on buildkite arm64 machines. While we figure out the problem, we
should unblock submits.
PiperOrigin-RevId: 451219197 |
260,004 | 26.05.2022 14:04:28 | 25,200 | 6f5e475674d6c200e4f09f9f0edd1ef15d3fc0e0 | Loop multicast packets from raw sockets | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/BUILD",
"new_path": "pkg/tcpip/transport/BUILD",
"diff": "@@ -30,5 +30,6 @@ go_test(\n\"//pkg/tcpip/transport/raw\",\n\"//pkg/tcpip/transport/udp\",\n\"//pkg/waiter\",\n+ \"@com_github_google_go_cmp//cmp:go_default_library\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/datagram_test.go",
"new_path": "pkg/tcpip/transport/datagram_test.go",
"diff": "@@ -21,6 +21,7 @@ import (\n\"math\"\n\"testing\"\n+ \"github.com/google/go-cmp/cmp\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n@@ -392,6 +393,7 @@ func TestDeviceReturnErrNoBufferSpace(t *testing.T) {\nname string\ncreateEndpoint func(*stack.Stack) (tcpip.Endpoint, error)\n}{\n+ // TODO(https://gvisor.dev/issues/7656): Also test ping sockets.\n{\nname: \"UDP\",\ncreateEndpoint: func(s *stack.Stack) (tcpip.Endpoint, error) {\n@@ -519,3 +521,147 @@ func TestDeviceReturnErrNoBufferSpace(t *testing.T) {\n})\n}\n}\n+\n+func TestMulticastLoop(t *testing.T) {\n+ const (\n+ nicID = 1\n+ port = 12345\n+ )\n+\n+ for _, netProto := range []struct {\n+ name string\n+ num tcpip.NetworkProtocolNumber\n+ localAddr tcpip.AddressWithPrefix\n+ destAddr tcpip.Address\n+ rawSocketHdrLen int\n+ }{\n+ {\n+ name: \"IPv4\",\n+ num: header.IPv4ProtocolNumber,\n+ localAddr: testutil.MustParse4(\"1.2.3.4\").WithPrefix(),\n+ destAddr: header.IPv4AllSystems,\n+ rawSocketHdrLen: header.IPv4MinimumSize,\n+ },\n+ {\n+ name: \"IPv6\",\n+ num: header.IPv6ProtocolNumber,\n+ localAddr: testutil.MustParse6(\"a::1\").WithPrefix(),\n+ destAddr: header.IPv6AllNodesMulticastAddress,\n+ rawSocketHdrLen: 0,\n+ },\n+ } {\n+ t.Run(netProto.name, func(t *testing.T) {\n+ for _, test := range []struct {\n+ name string\n+ createEndpoint func(*stack.Stack, *waiter.Queue) (tcpip.Endpoint, error)\n+ includedHdrBytes int\n+ }{\n+ {\n+ name: \"UDP\",\n+ createEndpoint: func(s *stack.Stack, wq *waiter.Queue) (tcpip.Endpoint, error) {\n+ ep, err := s.NewEndpoint(udp.ProtocolNumber, netProto.num, wq)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"s.NewEndpoint(%d, %d, _) failed: %s\", udp.ProtocolNumber, netProto.num, err)\n+ }\n+ return ep, nil\n+ },\n+ includedHdrBytes: 0,\n+ },\n+ {\n+ name: \"RAW\",\n+ createEndpoint: func(s *stack.Stack, wq *waiter.Queue) (tcpip.Endpoint, error) {\n+ ep, err := s.NewRawEndpoint(udp.ProtocolNumber, netProto.num, wq, true /* associated */)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"s.NewRawEndpoint(%d, %d, _, true) failed: %s\", udp.ProtocolNumber, netProto.num, err)\n+ }\n+ return ep, nil\n+ },\n+ includedHdrBytes: netProto.rawSocketHdrLen,\n+ },\n+ } {\n+ t.Run(test.name, func(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},\n+ TransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol},\n+ RawFactory: &raw.EndpointFactory{},\n+ })\n+ var e mockEndpoint\n+ defer e.releasePackets()\n+ if err := s.CreateNIC(nicID, &e); err != nil {\n+ t.Fatalf(\"s.CreateNIC(%d, _) failed: %s\", nicID, err)\n+ }\n+ var wq waiter.Queue\n+ ep, err := test.createEndpoint(s, &wq)\n+ if err != nil {\n+ t.Fatalf(\"test.createEndpoint(_) failed: %s\", err)\n+ }\n+ defer ep.Close()\n+\n+ addr := tcpip.ProtocolAddress{\n+ Protocol: netProto.num,\n+ AddressWithPrefix: netProto.localAddr,\n+ }\n+ if err := s.AddProtocolAddress(nicID, addr, stack.AddressProperties{}); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %#v, {}): %s\", nicID, addr, err)\n+ }\n+ s.SetRouteTable([]tcpip.Route{\n+ {\n+ Destination: header.IPv4EmptySubnet,\n+ NIC: nicID,\n+ },\n+ {\n+ Destination: header.IPv6EmptySubnet,\n+ NIC: nicID,\n+ },\n+ })\n+\n+ bind := tcpip.FullAddress{Port: port}\n+ if err := ep.Bind(bind); err != nil {\n+ t.Fatalf(\"ep.Bind(%#v): %s\", bind, err)\n+ }\n+\n+ to := tcpip.FullAddress{NIC: nicID, Addr: netProto.destAddr, Port: port}\n+ checkWrite := func(buf []byte, withRead bool) {\n+ t.Helper()\n+\n+ {\n+ var r bytes.Reader\n+ r.Reset(buf[:])\n+ if n, err := ep.Write(&r, tcpip.WriteOptions{To: &to}); err != nil {\n+ t.Fatalf(\"Write(...): %s\", err)\n+ } else if want := int64(len(buf)); n != want {\n+ t.Fatalf(\"got Write(...) = %d, want = %d\", n, want)\n+ }\n+ }\n+\n+ var wantErr tcpip.Error\n+ if !withRead {\n+ wantErr = &tcpip.ErrWouldBlock{}\n+ }\n+\n+ var r bytes.Buffer\n+ if _, err := ep.Read(&r, tcpip.ReadOptions{}); err != wantErr {\n+ t.Fatalf(\"got Read(...) = %s, want = %s\", err, wantErr)\n+ }\n+ if wantErr != nil {\n+ return\n+ }\n+\n+ if diff := cmp.Diff(buf, r.Bytes()[test.includedHdrBytes:]); diff != \"\" {\n+ t.Errorf(\"read data bytes mismatch (-want +got):\\n%s\", diff)\n+ }\n+ }\n+\n+ checkWrite([]byte{1, 2, 3, 4}, true /* withRead */)\n+\n+ ops := ep.SocketOptions()\n+ ops.SetMulticastLoop(false)\n+ checkWrite([]byte{5, 6, 7, 8}, false /* withRead */)\n+\n+ ops.SetMulticastLoop(true)\n+ checkWrite([]byte{9, 10, 11, 12}, true /* withRead */)\n+ })\n+ }\n+ })\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/raw/endpoint.go",
"new_path": "pkg/tcpip/transport/raw/endpoint.go",
"diff": "@@ -131,6 +131,7 @@ func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProt\nipv6ChecksumOffset: ipv6ChecksumOffset,\n}\ne.ops.InitHandler(e, e.stack, tcpip.GetStackSendBufferLimits, tcpip.GetStackReceiveBufferLimits)\n+ e.ops.SetMulticastLoop(true)\ne.ops.SetHeaderIncluded(!associated)\ne.ops.SetSendBufferSize(32*1024, false /* notify */)\ne.ops.SetReceiveBufferSize(32*1024, false /* notify */)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Loop multicast packets from raw sockets
Bug: https://fxbug.dev/101226
PiperOrigin-RevId: 451239264 |
259,907 | 26.05.2022 20:00:05 | 25,200 | 37076bc16f911c0176cd6dd1cf6b35ed59ce9002 | Add support for /proc/[pid]/cgroup to trace procfs.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_cgroup.go",
"new_path": "pkg/sentry/kernel/task_cgroup.go",
"diff": "@@ -177,20 +177,21 @@ func (t *Task) MigrateCgroup(dst Cgroup) error {\nreturn nil\n}\n-// taskCgroupEntry represents a line in /proc/<pid>/cgroup, and is used to\n+// TaskCgroupEntry represents a line in /proc/<pid>/cgroup, and is used to\n// format a cgroup for display.\n-type taskCgroupEntry struct {\n- hierarchyID uint32\n- controllers string\n- path string\n+type TaskCgroupEntry struct {\n+ HierarchyID uint32 `json:\"hierarchy_id,omitempty\"`\n+ Controllers string `json:\"controllers,omitempty\"`\n+ Path string `json:\"path,omitempty\"`\n}\n-// GenerateProcTaskCgroup writes the contents of /proc/<pid>/cgroup for t to buf.\n-func (t *Task) GenerateProcTaskCgroup(buf *bytes.Buffer) {\n+// GetCgroupEntries generates the contents of /proc/<pid>/cgroup as\n+// a TaskCgroupEntry array.\n+func (t *Task) GetCgroupEntries() []TaskCgroupEntry {\nt.mu.Lock()\ndefer t.mu.Unlock()\n- cgEntries := make([]taskCgroupEntry, 0, len(t.cgroups))\n+ cgEntries := make([]TaskCgroupEntry, 0, len(t.cgroups))\nfor c := range t.cgroups {\nctls := c.Controllers()\nctlNames := make([]string, 0, len(ctls))\n@@ -208,16 +209,22 @@ func (t *Task) GenerateProcTaskCgroup(buf *bytes.Buffer) {\nctlNames = append(ctlNames, string(ctl.Type()))\n}\n- cgEntries = append(cgEntries, taskCgroupEntry{\n- hierarchyID: c.HierarchyID(),\n- controllers: strings.Join(ctlNames, \",\"),\n- path: c.Path(),\n+ cgEntries = append(cgEntries, TaskCgroupEntry{\n+ HierarchyID: c.HierarchyID(),\n+ Controllers: strings.Join(ctlNames, \",\"),\n+ Path: c.Path(),\n})\n}\n- sort.Slice(cgEntries, func(i, j int) bool { return cgEntries[i].hierarchyID > cgEntries[j].hierarchyID })\n+ sort.Slice(cgEntries, func(i, j int) bool { return cgEntries[i].HierarchyID > cgEntries[j].HierarchyID })\n+ return cgEntries\n+}\n+\n+// GenerateProcTaskCgroup writes the contents of /proc/<pid>/cgroup for t to buf.\n+func (t *Task) GenerateProcTaskCgroup(buf *bytes.Buffer) {\n+ cgEntries := t.GetCgroupEntries()\nfor _, cgE := range cgEntries {\n- fmt.Fprintf(buf, \"%d:%s:%s\\n\", cgE.hierarchyID, cgE.controllers, cgE.path)\n+ fmt.Fprintf(buf, \"%d:%s:%s\\n\", cgE.HierarchyID, cgE.Controllers, cgE.Path)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/procfs/dump.go",
"new_path": "runsc/boot/procfs/dump.go",
"diff": "@@ -61,6 +61,8 @@ type ProcessProcfsDump struct {\n// Limits constains resource limits for this process. Currently only\n// RLIMIT_NOFILE is supported.\nLimits map[string]limits.Limit `json:\"limits,omitempty\"`\n+ // Cgroup is /proc/[pid]/cgroup split into an array.\n+ Cgroup []kernel.TaskCgroupEntry `json:\"cgroup,omitempty\"`\n}\n// getMM returns t's MemoryManager. On success, the MemoryManager's users count\n@@ -208,5 +210,8 @@ func Dump(t *kernel.Task, pid kernel.ThreadID) (ProcessProcfsDump, error) {\nLimits: map[string]limits.Limit{\n\"RLIMIT_NOFILE\": fdLimit,\n},\n+ // We don't need to worry about fake cgroup controllers as that is not\n+ // supported in runsc.\n+ Cgroup: t.GetCgroupEntries(),\n}, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/trace_test.go",
"new_path": "runsc/container/trace_test.go",
"diff": "@@ -23,6 +23,7 @@ import (\nspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n\"google.golang.org/protobuf/proto\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/limits\"\n\"gvisor.dev/gvisor/pkg/sentry/seccheck\"\n\"gvisor.dev/gvisor/pkg/sentry/seccheck/checkers/remote/test\"\n@@ -304,6 +305,7 @@ func TestProcfsDump(t *testing.T) {\nspec.Process.Rlimits = []specs.POSIXRlimit{\n{Type: \"RLIMIT_NOFILE\", Hard: fdLimit.Max, Soft: fdLimit.Cur},\n}\n+ conf.Cgroupfs = true\n_, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)\nif err != nil {\nt.Fatalf(\"error setting up container: %v\", err)\n@@ -396,4 +398,18 @@ func TestProcfsDump(t *testing.T) {\nif got := procfsDump[0].Limits[\"RLIMIT_NOFILE\"]; got != fdLimit {\nt.Errorf(\"expected FD limit to be %+v, but got %+v\", fdLimit, got)\n}\n+\n+ wantCgroup := []kernel.TaskCgroupEntry{\n+ kernel.TaskCgroupEntry{HierarchyID: 2, Controllers: \"memory\", Path: \"/\"},\n+ kernel.TaskCgroupEntry{HierarchyID: 1, Controllers: \"cpu\", Path: \"/\"},\n+ }\n+ if len(procfsDump[0].Cgroup) != len(wantCgroup) {\n+ t.Errorf(\"expected 2 cgroup controllers, got %+v\", procfsDump[0].Cgroup)\n+ } else {\n+ for i, cgroup := range procfsDump[0].Cgroup {\n+ if cgroup != wantCgroup[i] {\n+ t.Errorf(\"expected %+v, got %+v\", wantCgroup[i], cgroup)\n+ }\n+ }\n+ }\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add support for /proc/[pid]/cgroup to trace procfs.
Updates #4805
PiperOrigin-RevId: 451297968 |
259,907 | 26.05.2022 20:31:04 | 25,200 | 565fbe2151b328d4a5aa1151e8efb28cd9484549 | Add support for /proc/[pid]/status to trace procfs.
Updates | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/procfs/dump.go",
"new_path": "runsc/boot/procfs/dump.go",
"diff": "@@ -38,11 +38,26 @@ type FDInfo struct {\nPath string `json:\"path,omitempty\"`\n}\n+// UIDGID contains information for /proc/[pid]/status/{uid,gid}.\n+type UIDGID struct {\n+ Real uint32 `json:\"real,omitempty\"`\n+ Effective uint32 `json:\"effective,omitempty\"`\n+ Saved uint32 `json:\"saved,omitempty\"`\n+}\n+\n+// Status contains information for /proc/[pid]/status.\n+type Status struct {\n+ Comm string `json:\"comm,omitempty\"`\n+ PID int32 `json:\"pid,omitempty\"`\n+ UID UIDGID `json:\"uid,omitempty\"`\n+ GID UIDGID `json:\"gid,omitempty\"`\n+ VMSize uint64 `json:\"vm_size,omitempty\"`\n+ VMRSS uint64 `json:\"vm_rss,omitempty\"`\n+}\n+\n// ProcessProcfsDump contains the procfs dump for one process. For more details\n// on fields that directly correspond to /proc fields, see proc(5).\ntype ProcessProcfsDump struct {\n- // PID is the process ID.\n- PID int32 `json:\"pid,omitempty\"`\n// Exe is the symlink target of /proc/[pid]/exe.\nExe string `json:\"exe,omitempty\"`\n// Args is /proc/[pid]/cmdline split into an array.\n@@ -63,6 +78,8 @@ type ProcessProcfsDump struct {\nLimits map[string]limits.Limit `json:\"limits,omitempty\"`\n// Cgroup is /proc/[pid]/cgroup split into an array.\nCgroup []kernel.TaskCgroupEntry `json:\"cgroup,omitempty\"`\n+ // Status is /proc/[pid]/status.\n+ Status Status `json:\"status,omitempty\"`\n}\n// getMM returns t's MemoryManager. On success, the MemoryManager's users count\n@@ -183,6 +200,27 @@ func getFDLimit(ctx context.Context, pid kernel.ThreadID) (limits.Limit, error)\nreturn limits.Limit{}, fmt.Errorf(\"could not find limit set for pid %s\", pid)\n}\n+func getStatus(t *kernel.Task, mm *mm.MemoryManager, pid kernel.ThreadID) Status {\n+ creds := t.Credentials()\n+ uns := creds.UserNamespace\n+ return Status{\n+ Comm: t.Name(),\n+ PID: int32(pid),\n+ UID: UIDGID{\n+ Real: uint32(creds.RealKUID.In(uns).OrOverflow()),\n+ Effective: uint32(creds.EffectiveKUID.In(uns).OrOverflow()),\n+ Saved: uint32(creds.SavedKUID.In(uns).OrOverflow()),\n+ },\n+ GID: UIDGID{\n+ Real: uint32(creds.RealKGID.In(uns).OrOverflow()),\n+ Effective: uint32(creds.EffectiveKGID.In(uns).OrOverflow()),\n+ Saved: uint32(creds.SavedKGID.In(uns).OrOverflow()),\n+ },\n+ VMSize: mm.VirtualMemorySize() >> 10,\n+ VMRSS: mm.ResidentSetSize() >> 10,\n+ }\n+}\n+\n// Dump returns a procfs dump for process pid. t must be a task in process pid.\nfunc Dump(t *kernel.Task, pid kernel.ThreadID) (ProcessProcfsDump, error) {\nctx := t.AsyncContext()\n@@ -199,7 +237,6 @@ func Dump(t *kernel.Task, pid kernel.ThreadID) (ProcessProcfsDump, error) {\n}\nreturn ProcessProcfsDump{\n- PID: int32(pid),\nExe: getExecutablePath(ctx, pid, mm),\nArgs: getMetadataArray(ctx, pid, mm, proc.Cmdline),\nEnv: getMetadataArray(ctx, pid, mm, proc.Environ),\n@@ -213,5 +250,6 @@ func Dump(t *kernel.Task, pid kernel.ThreadID) (ProcessProcfsDump, error) {\n// We don't need to worry about fake cgroup controllers as that is not\n// supported in runsc.\nCgroup: t.GetCgroupEntries(),\n+ Status: getStatus(t, mm, pid),\n}, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/trace_test.go",
"new_path": "runsc/container/trace_test.go",
"diff": "@@ -339,8 +339,8 @@ func TestProcfsDump(t *testing.T) {\n}\n// Sleep should be PID 1.\n- if procfsDump[0].PID != 1 {\n- t.Errorf(\"expected sleep process to be pid 1, got %d\", procfsDump[0].PID)\n+ if procfsDump[0].Status.PID != 1 {\n+ t.Errorf(\"expected sleep process to be pid 1, got %d\", procfsDump[0].Status.PID)\n}\n// Check that bin/sleep is part of the executable path.\n@@ -412,4 +412,22 @@ func TestProcfsDump(t *testing.T) {\n}\n}\n}\n+\n+ if wantName := \"sleep\"; procfsDump[0].Status.Comm != wantName {\n+ t.Errorf(\"expected Comm to be %q, but got %q\", wantName, procfsDump[0].Status.Comm)\n+ }\n+\n+ if uid := procfsDump[0].Status.UID; uid.Real != 0 || uid.Effective != 0 || uid.Saved != 0 {\n+ t.Errorf(\"expected UIDs to be 0 (root), got %+v\", uid)\n+ }\n+ if gid := procfsDump[0].Status.GID; gid.Real != 0 || gid.Effective != 0 || gid.Saved != 0 {\n+ t.Errorf(\"expected GIDs to be 0 (root), got %+v\", gid)\n+ }\n+\n+ if procfsDump[0].Status.VMSize == 0 {\n+ t.Errorf(\"expected VMSize to be set\")\n+ }\n+ if procfsDump[0].Status.VMRSS == 0 {\n+ t.Errorf(\"expected VMSize to be set\")\n+ }\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add support for /proc/[pid]/status to trace procfs.
Updates #4805
PiperOrigin-RevId: 451301995 |
259,907 | 26.05.2022 22:22:53 | 25,200 | f1c9664506be4b072bb57b517cc18decaeec7350 | Add support for /proc/[pid]/stat to trace procfs.
Updates | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/controller.go",
"new_path": "runsc/boot/controller.go",
"diff": "@@ -639,7 +639,7 @@ func (cm *containerManager) ProcfsDump(_ *struct{}, out *[]procfs.ProcessProcfsD\n*out = make([]procfs.ProcessProcfsDump, 0, len(cm.l.processes))\nfor _, tg := range pidns.ThreadGroups() {\npid := pidns.IDOfThreadGroup(tg)\n- procDump, err := procfs.Dump(tg.Leader(), pid)\n+ procDump, err := procfs.Dump(tg.Leader(), pid, pidns)\nif err != nil {\nlog.Warningf(\"skipping procfs dump for PID %s: %v\", pid, err)\ncontinue\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/procfs/dump.go",
"new_path": "runsc/boot/procfs/dump.go",
"diff": "@@ -55,6 +55,12 @@ type Status struct {\nVMRSS uint64 `json:\"vm_rss,omitempty\"`\n}\n+// Stat contains information for /proc/[pid]/stat.\n+type Stat struct {\n+ PGID int32 `json:\"pgid,omitempty\"`\n+ SID int32 `json:\"sid,omitempty\"`\n+}\n+\n// ProcessProcfsDump contains the procfs dump for one process. For more details\n// on fields that directly correspond to /proc fields, see proc(5).\ntype ProcessProcfsDump struct {\n@@ -80,6 +86,8 @@ type ProcessProcfsDump struct {\nCgroup []kernel.TaskCgroupEntry `json:\"cgroup,omitempty\"`\n// Status is /proc/[pid]/status.\nStatus Status `json:\"status,omitempty\"`\n+ // Stat is /proc/[pid]/stat.\n+ Stat Stat `json:\"stat,omitempty\"`\n}\n// getMM returns t's MemoryManager. On success, the MemoryManager's users count\n@@ -221,8 +229,15 @@ func getStatus(t *kernel.Task, mm *mm.MemoryManager, pid kernel.ThreadID) Status\n}\n}\n+func getStat(t *kernel.Task, pid kernel.ThreadID, pidns *kernel.PIDNamespace) Stat {\n+ return Stat{\n+ PGID: int32(pidns.IDOfProcessGroup(t.ThreadGroup().ProcessGroup())),\n+ SID: int32(pidns.IDOfSession(t.ThreadGroup().Session())),\n+ }\n+}\n+\n// Dump returns a procfs dump for process pid. t must be a task in process pid.\n-func Dump(t *kernel.Task, pid kernel.ThreadID) (ProcessProcfsDump, error) {\n+func Dump(t *kernel.Task, pid kernel.ThreadID, pidns *kernel.PIDNamespace) (ProcessProcfsDump, error) {\nctx := t.AsyncContext()\nmm := getMM(t)\n@@ -251,5 +266,6 @@ func Dump(t *kernel.Task, pid kernel.ThreadID) (ProcessProcfsDump, error) {\n// supported in runsc.\nCgroup: t.GetCgroupEntries(),\nStatus: getStatus(t, mm, pid),\n+ Stat: getStat(t, pid, pidns),\n}, nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add support for /proc/[pid]/stat to trace procfs.
Updates #4805
PiperOrigin-RevId: 451314545 |
259,907 | 30.05.2022 19:46:54 | 25,200 | c7690e05c1fd863a7f6670078a7a557cba19f58a | Add option to hide application data in strace logs.
This is helpful in disabling printing sensitive application data when strace is
enabled. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/strace/socket.go",
"new_path": "pkg/sentry/strace/socket.go",
"diff": "@@ -462,7 +462,7 @@ func sockOptVal(t *kernel.Task, level, optname uint64, optVal hostarch.Addr, opt\n}\nreturn fmt.Sprintf(\"%#x {value=%v}\", optVal, v)\ndefault:\n- return dump(t, optVal, uint(optLen), maximumBlobSize)\n+ return dump(t, optVal, uint(optLen), maximumBlobSize, true /* content */)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/strace/strace.go",
"new_path": "pkg/sentry/strace/strace.go",
"diff": "@@ -48,6 +48,10 @@ var LogMaximumSize uint = DefaultLogMaximumSize\n// do anything useful with binary text dump of byte array arguments.\nvar EventMaximumSize uint\n+// LogAppDataAllowed is set to true when printing application data in strace\n+// logs is allowed.\n+var LogAppDataAllowed = true\n+\n// ItimerTypes are the possible itimer types.\nvar ItimerTypes = abi.ValueSet{\nlinux.ITIMER_REAL: \"ITIMER_REAL\",\n@@ -108,7 +112,10 @@ func iovecs(t *kernel.Task, addr hostarch.Addr, iovcnt int, printContent bool, m\nreturn fmt.Sprintf(\"%#x %s\", addr, strings.Join(iovs, \", \"))\n}\n-func dump(t *kernel.Task, addr hostarch.Addr, size uint, maximumBlobSize uint) string {\n+func dump(t *kernel.Task, addr hostarch.Addr, size uint, maximumBlobSize uint, printContent bool) string {\n+ if !printContent {\n+ return fmt.Sprintf(\"{base=%#x, len=%d}\", addr, size)\n+ }\norigSize := size\nif size > maximumBlobSize {\nsize = maximumBlobSize\n@@ -415,13 +422,13 @@ func (i *SyscallInfo) pre(t *kernel.Task, args arch.SyscallArguments, maximumBlo\ncase FD:\noutput = append(output, fd(t, args[arg].Int()))\ncase WriteBuffer:\n- output = append(output, dump(t, args[arg].Pointer(), args[arg+1].SizeT(), maximumBlobSize))\n+ output = append(output, dump(t, args[arg].Pointer(), args[arg+1].SizeT(), maximumBlobSize, LogAppDataAllowed /* content */))\ncase WriteIOVec:\n- output = append(output, iovecs(t, args[arg].Pointer(), int(args[arg+1].Int()), true /* content */, uint64(maximumBlobSize)))\n+ output = append(output, iovecs(t, args[arg].Pointer(), int(args[arg+1].Int()), LogAppDataAllowed /* content */, uint64(maximumBlobSize)))\ncase IOVec:\noutput = append(output, iovecs(t, args[arg].Pointer(), int(args[arg+1].Int()), false /* content */, uint64(maximumBlobSize)))\ncase SendMsgHdr:\n- output = append(output, msghdr(t, args[arg].Pointer(), true /* content */, uint64(maximumBlobSize)))\n+ output = append(output, msghdr(t, args[arg].Pointer(), LogAppDataAllowed /* content */, uint64(maximumBlobSize)))\ncase RecvMsgHdr:\noutput = append(output, msghdr(t, args[arg].Pointer(), false /* content */, uint64(maximumBlobSize)))\ncase Path:\n@@ -520,20 +527,20 @@ func (i *SyscallInfo) post(t *kernel.Task, args arch.SyscallArguments, rval uint\n}\nswitch i.format[arg] {\ncase ReadBuffer:\n- output[arg] = dump(t, args[arg].Pointer(), uint(rval), maximumBlobSize)\n+ output[arg] = dump(t, args[arg].Pointer(), uint(rval), maximumBlobSize, LogAppDataAllowed /* content */)\ncase ReadIOVec:\nprintLength := uint64(rval)\nif printLength > uint64(maximumBlobSize) {\nprintLength = uint64(maximumBlobSize)\n}\n- output[arg] = iovecs(t, args[arg].Pointer(), int(args[arg+1].Int()), true /* content */, printLength)\n+ output[arg] = iovecs(t, args[arg].Pointer(), int(args[arg+1].Int()), LogAppDataAllowed /* content */, printLength)\ncase WriteIOVec, IOVec, WriteBuffer:\n// We already have a big blast from write.\noutput[arg] = \"...\"\ncase SendMsgHdr:\noutput[arg] = msghdr(t, args[arg].Pointer(), false /* content */, uint64(maximumBlobSize))\ncase RecvMsgHdr:\n- output[arg] = msghdr(t, args[arg].Pointer(), true /* content */, uint64(maximumBlobSize))\n+ output[arg] = msghdr(t, args[arg].Pointer(), LogAppDataAllowed /* content */, uint64(maximumBlobSize))\ncase PostPath:\noutput[arg] = path(t, args[arg].Pointer())\ncase PipeFDs:\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/strace.go",
"new_path": "runsc/boot/strace.go",
"diff": "@@ -29,6 +29,9 @@ func enableStrace(conf *config.Config) error {\nreturn nil\n}\n+ // For now runsc always allows logging application buffers in strace logs.\n+ strace.LogAppDataAllowed = true\n+\nmax := conf.StraceLogSize\nif max == 0 {\nmax = 1024\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add option to hide application data in strace logs.
This is helpful in disabling printing sensitive application data when strace is
enabled.
PiperOrigin-RevId: 451946198 |
259,966 | 31.05.2022 08:21:46 | 25,200 | ea5c64b6174388a62727ba0d9c4a5eadfe7a3f29 | Emit multicast forwarding events.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4.go",
"diff": "@@ -367,6 +367,18 @@ func (e *endpoint) disableLocked() {\n}\n}\n+// multicastEventDispatcher returns the multicast forwarding event dispatcher.\n+//\n+// Panics if a multicast forwarding event dispatcher does not exist. This\n+// indicates that multicast forwarding is enabled, but no dispatcher was\n+// provided.\n+func (e *endpoint) multicastEventDispatcher() stack.MulticastForwardingEventDispatcher {\n+ if mcastDisp := e.protocol.options.MulticastForwardingDisp; mcastDisp != nil {\n+ return mcastDisp\n+ }\n+ panic(\"e.procotol.options.MulticastForwardingDisp unexpectedly nil\")\n+}\n+\n// DefaultTTL is the default time-to-live value for this endpoint.\nfunc (e *endpoint) DefaultTTL() uint8 {\nreturn e.protocol.DefaultTTL()\n@@ -886,10 +898,18 @@ func (e *endpoint) forwardMulticastPacket(h header.IPv4, pkt *stack.PacketBuffer\nreturn &ip.ErrNoMulticastPendingQueueBufferSpace{}\n}\n- // TODO(https://gvisor.dev/issue/7338): Emit an event for a missing route.\n- if result.GetRouteResultState == multicast.InstalledRouteFound {\n+ switch result.GetRouteResultState {\n+ case multicast.InstalledRouteFound:\n// Attempt to forward the pkt using an existing route.\nreturn e.forwardValidatedMulticastPacket(pkt, result.InstalledRoute)\n+ case multicast.NoRouteFoundAndPendingInserted:\n+ e.multicastEventDispatcher().OnMissingRoute(stack.MulticastPacketContext{\n+ stack.UnicastSourceAndMulticastDestination{h.SourceAddress(), h.DestinationAddress()},\n+ e.nic.ID(),\n+ })\n+ case multicast.PacketQueuedInPendingRoute:\n+ default:\n+ panic(fmt.Sprintf(\"unexpected GetRouteResultState: %s\", result.GetRouteResultState))\n}\nreturn &ip.ErrNoRoute{}\n}\n@@ -937,8 +957,11 @@ func (e *endpoint) forwardValidatedMulticastPacket(pkt *stack.PacketBuffer, inst\n// on the proper interface for forwarding. If not, the datagram is\n// dropped silently.\nif e.nic.ID() != installedRoute.ExpectedInputInterface {\n- // TODO(https://gvisor.dev/issue/7338): Emit an event for an unexpected\n- // input interface.\n+ h := header.IPv4(pkt.NetworkHeader().View())\n+ e.multicastEventDispatcher().OnUnexpectedInputInterface(stack.MulticastPacketContext{\n+ stack.UnicastSourceAndMulticastDestination{h.SourceAddress(), h.DestinationAddress()},\n+ e.nic.ID(),\n+ }, installedRoute.ExpectedInputInterface)\nreturn &ip.ErrUnexpectedMulticastInputInterface{}\n}\n@@ -1749,6 +1772,10 @@ type Options struct {\n// AllowExternalLoopbackTraffic indicates that inbound loopback packets (i.e.\n// martian loopback packets) should be accepted.\nAllowExternalLoopbackTraffic bool\n+\n+ // MulticastForwardingDisp is the multicast forwarding event dispatcher that\n+ // an integrator can provide to receive multicast forwarding events.\n+ MulticastForwardingDisp stack.MulticastForwardingEventDispatcher\n}\n// NewProtocolWithOptions returns an IPv4 network protocol.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/icmp_test.go",
"new_path": "pkg/tcpip/network/ipv6/icmp_test.go",
"diff": "@@ -199,6 +199,15 @@ func handleICMPInIPv6(ep stack.NetworkEndpoint, src, dst tcpip.Address, icmp hea\npkt.DecRef()\n}\n+var _ stack.MulticastForwardingEventDispatcher = (*fakeMulticastEventDispatcher)(nil)\n+\n+type fakeMulticastEventDispatcher struct{}\n+\n+func (m *fakeMulticastEventDispatcher) OnMissingRoute(context stack.MulticastPacketContext) {}\n+\n+func (m *fakeMulticastEventDispatcher) OnUnexpectedInputInterface(context stack.MulticastPacketContext, expectedInputInterface tcpip.NICID) {\n+}\n+\ntype testContext struct {\ns *stack.Stack\nclock *faketime.ManualClock\n@@ -207,7 +216,7 @@ type testContext struct {\nfunc newTestContext() testContext {\nclock := faketime.NewManualClock()\ns := stack.New(stack.Options{\n- NetworkProtocols: []stack.NetworkProtocolFactory{NewProtocol},\n+ NetworkProtocols: []stack.NetworkProtocolFactory{NewProtocolWithOptions(Options{MulticastForwardingDisp: &fakeMulticastEventDispatcher{}})},\nTransportProtocols: []stack.TransportProtocolFactory{icmp.NewProtocol6, udp.NewProtocol},\nClock: clock,\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6.go",
"diff": "@@ -1123,15 +1123,18 @@ func (e *endpoint) forwardMulticastPacket(h header.IPv6, pkt *stack.PacketBuffer\nreturn &ip.ErrNoMulticastPendingQueueBufferSpace{}\n}\n- // TODO(https://gvisor.dev/issue/7338): Emit an event for a missing route.\nswitch result.GetRouteResultState {\ncase multicast.InstalledRouteFound:\n// Attempt to forward the pkt using an existing route.\nreturn e.forwardValidatedMulticastPacket(pkt, result.InstalledRoute)\ncase multicast.NoRouteFoundAndPendingInserted:\n+ e.multicastEventDispatcher().OnMissingRoute(stack.MulticastPacketContext{\n+ stack.UnicastSourceAndMulticastDestination{h.SourceAddress(), h.DestinationAddress()},\n+ e.nic.ID(),\n+ })\ncase multicast.PacketQueuedInPendingRoute:\ndefault:\n- panic(fmt.Sprintf(\"unexpected result.GetRouteResultState: %s\", result.GetRouteResultState))\n+ panic(fmt.Sprintf(\"unexpected GetRouteResultState: %s\", result.GetRouteResultState))\n}\nreturn &ip.ErrNoRoute{}\n}\n@@ -1148,8 +1151,11 @@ func (e *endpoint) forwardValidatedMulticastPacket(pkt *stack.PacketBuffer, inst\n// on the proper interface for forwarding. If not, the datagram is\n// dropped silently.\nif e.nic.ID() != installedRoute.ExpectedInputInterface {\n- // TODO(https://gvisor.dev/issue/7338): Emit an event for an unexpected\n- // input interface.\n+ h := header.IPv6(pkt.NetworkHeader().View())\n+ e.multicastEventDispatcher().OnUnexpectedInputInterface(stack.MulticastPacketContext{\n+ stack.UnicastSourceAndMulticastDestination{h.SourceAddress(), h.DestinationAddress()},\n+ e.nic.ID(),\n+ }, installedRoute.ExpectedInputInterface)\nreturn &ip.ErrUnexpectedMulticastInputInterface{}\n}\n@@ -2264,6 +2270,18 @@ func (p *protocol) DefaultTTL() uint8 {\nreturn uint8(p.defaultTTL.Load())\n}\n+// multicastEventDispatcher returns the multicast forwarding event dispatcher.\n+//\n+// Panics if a multicast forwarding event dispatcher does not exist. This\n+// indicates that multicast forwarding is enabled, but no dispatcher was\n+// provided.\n+func (e *endpoint) multicastEventDispatcher() stack.MulticastForwardingEventDispatcher {\n+ if mcastDisp := e.protocol.options.MulticastForwardingDisp; mcastDisp != nil {\n+ return mcastDisp\n+ }\n+ panic(\"e.procotol.options.MulticastForwardingDisp unexpectedly nil\")\n+}\n+\n// Close implements stack.TransportProtocol.\nfunc (p *protocol) Close() {\np.fragmentation.Release()\n@@ -2528,6 +2546,10 @@ type Options struct {\n// AllowExternalLoopbackTraffic indicates that inbound loopback packets (i.e.\n// martian loopback packets) should be accepted.\nAllowExternalLoopbackTraffic bool\n+\n+ // MulticastForwardingDisp is the multicast forwarding event dispatcher that\n+ // an integrator can provide to receive multicast forwarding events.\n+ MulticastForwardingDisp stack.MulticastForwardingEventDispatcher\n}\n// NewProtocolWithOptions returns an IPv6 network protocol.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/registration.go",
"new_path": "pkg/tcpip/stack/registration.go",
"diff": "@@ -819,6 +819,37 @@ type MulticastForwardingNetworkProtocol interface {\nMulticastRouteLastUsedTime(UnicastSourceAndMulticastDestination) (tcpip.MonotonicTime, tcpip.Error)\n}\n+// MulticastPacketContext is the context in which a multicast packet triggered\n+// a multicast forwarding event.\n+type MulticastPacketContext struct {\n+ // SourceAndDestination contains the unicast source address and the multicast\n+ // destination address found in the relevant multicast packet.\n+ SourceAndDestination UnicastSourceAndMulticastDestination\n+ // InputInterface is the interface on which the relevant multicast packet\n+ // arrived.\n+ InputInterface tcpip.NICID\n+}\n+\n+// MulticastForwardingEventDispatcher is the interface that integrators should\n+// implement to handle multicast routing events.\n+type MulticastForwardingEventDispatcher interface {\n+ // OnMissingRoute is called when an incoming multicast packet does not match\n+ // any installed route.\n+ //\n+ // The packet that triggered this event may be queued so that it can be\n+ // transmitted once a route is installed. Even then, it may still be dropped\n+ // as per the routing table's GC/eviction policy.\n+ OnMissingRoute(MulticastPacketContext)\n+\n+ // OnUnexpectedInputInterface is called when a multicast packet arrives at an\n+ // interface that does not match the installed route's expected input\n+ // interface.\n+ //\n+ // This may be an indication of a routing loop. The packet that triggered\n+ // this event is dropped without being forwarded.\n+ OnUnexpectedInputInterface(context MulticastPacketContext, expectedInputInterface tcpip.NICID)\n+}\n+\n// NetworkDispatcher contains the methods used by the network stack to deliver\n// inbound/outbound packets to the appropriate network/packet(if any) endpoints.\ntype NetworkDispatcher interface {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/integration/multicast_forward_test.go",
"new_path": "pkg/tcpip/tests/integration/multicast_forward_test.go",
"diff": "@@ -68,6 +68,33 @@ const (\notherOutgoingEndpointAddr\n)\n+type onMissingRouteData struct {\n+ context stack.MulticastPacketContext\n+}\n+\n+type onUnexpectedInputInterfaceData struct {\n+ context stack.MulticastPacketContext\n+ expectedInputInterface tcpip.NICID\n+}\n+\n+var _ stack.MulticastForwardingEventDispatcher = (*fakeMulticastEventDispatcher)(nil)\n+\n+type fakeMulticastEventDispatcher struct {\n+ onMissingRouteData *onMissingRouteData\n+ onUnexpectedInputInterfaceData *onUnexpectedInputInterfaceData\n+}\n+\n+func (m *fakeMulticastEventDispatcher) OnMissingRoute(context stack.MulticastPacketContext) {\n+ m.onMissingRouteData = &onMissingRouteData{context}\n+}\n+\n+func (m *fakeMulticastEventDispatcher) OnUnexpectedInputInterface(context stack.MulticastPacketContext, expectedInputInterface tcpip.NICID) {\n+ m.onUnexpectedInputInterfaceData = &onUnexpectedInputInterfaceData{\n+ context,\n+ expectedInputInterface,\n+ }\n+}\n+\nvar (\nv4Addrs = map[addrType]tcpip.Address{\nanyAddr: header.IPv4Any,\n@@ -335,9 +362,12 @@ func TestAddMulticastRoute(t *testing.T) {\nfor _, test := range tests {\nfor _, protocol := range []tcpip.NetworkProtocolNumber{ipv4.ProtocolNumber, ipv6.ProtocolNumber} {\nt.Run(fmt.Sprintf(\"%s %d\", test.name, protocol), func(t *testing.T) {\n+ eventDispatcher := &fakeMulticastEventDispatcher{}\ns := stack.New(stack.Options{\n- NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},\n- TransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol},\n+ NetworkProtocols: []stack.NetworkProtocolFactory{\n+ ipv4.NewProtocolWithOptions(ipv4.Options{MulticastForwardingDisp: eventDispatcher}),\n+ ipv6.NewProtocolWithOptions(ipv6.Options{MulticastForwardingDisp: eventDispatcher}),\n+ },\n})\ndefer s.Close()\n@@ -646,8 +676,12 @@ func TestRemoveMulticastRoute(t *testing.T) {\nfor _, test := range tests {\nfor _, protocol := range []tcpip.NetworkProtocolNumber{ipv4.ProtocolNumber, ipv6.ProtocolNumber} {\nt.Run(fmt.Sprintf(\"%s %d\", test.name, protocol), func(t *testing.T) {\n+ eventDispatcher := &fakeMulticastEventDispatcher{}\ns := stack.New(stack.Options{\n- NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},\n+ NetworkProtocols: []stack.NetworkProtocolFactory{\n+ ipv4.NewProtocolWithOptions(ipv4.Options{MulticastForwardingDisp: eventDispatcher}),\n+ ipv6.NewProtocolWithOptions(ipv6.Options{MulticastForwardingDisp: eventDispatcher}),\n+ },\nTransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol},\n})\ndefer s.Close()\n@@ -763,6 +797,8 @@ func TestMulticastForwarding(t *testing.T) {\nrouteInputInterface tcpip.NICID\ndisableMulticastForwarding bool\nremoveOutputInterface tcpip.NICID\n+ expectMissingRouteEvent bool\n+ expectUnexpectedInputInterfaceEvent bool\njoinMulticastGroup bool\nexpectedForwardingInterfaces []tcpip.NICID\n}{\n@@ -802,6 +838,7 @@ func TestMulticastForwarding(t *testing.T) {\ndstAddr: multicastAddr,\nttl: packetTTL,\nrouteInputInterface: otherNICID,\n+ expectUnexpectedInputInterfaceEvent: true,\nexpectedForwardingInterfaces: []tcpip.NICID{},\n},\n{\n@@ -838,15 +875,27 @@ func TestMulticastForwarding(t *testing.T) {\ndstAddr: otherMulticastAddr,\nttl: packetTTL,\nrouteInputInterface: incomingNICID,\n+ expectMissingRouteEvent: true,\nexpectedForwardingInterfaces: []tcpip.NICID{},\n},\n}\nfor _, test := range tests {\nfor _, protocol := range []tcpip.NetworkProtocolNumber{ipv4.ProtocolNumber, ipv6.ProtocolNumber} {\n+ ipv4EventDispatcher := &fakeMulticastEventDispatcher{}\n+ ipv6EventDispatcher := &fakeMulticastEventDispatcher{}\n+\n+ eventDispatchers := map[tcpip.NetworkProtocolNumber]*fakeMulticastEventDispatcher{\n+ ipv4.ProtocolNumber: ipv4EventDispatcher,\n+ ipv6.ProtocolNumber: ipv6EventDispatcher,\n+ }\n+\nt.Run(fmt.Sprintf(\"%s %d\", test.name, protocol), func(t *testing.T) {\ns := stack.New(stack.Options{\n- NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},\n+ NetworkProtocols: []stack.NetworkProtocolFactory{\n+ ipv4.NewProtocolWithOptions(ipv4.Options{MulticastForwardingDisp: ipv4EventDispatcher}),\n+ ipv6.NewProtocolWithOptions(ipv6.Options{MulticastForwardingDisp: ipv6EventDispatcher}),\n+ },\nTransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol},\n})\ndefer s.Close()\n@@ -974,6 +1023,33 @@ func TestMulticastForwarding(t *testing.T) {\ncheckEchoReply(t, protocol, p, getEndpointAddr(protocol, incomingEpAddrType).Address, srcAddr)\np.DecRef()\n}\n+\n+ eventDispatcher, ok := eventDispatchers[protocol]\n+ if !ok {\n+ t.Fatalf(\"eventDispatchers[%d] = (_, false), want (_, true)\", protocol)\n+ }\n+\n+ wantUnexpectedInputInterfaceEvent := func() *onUnexpectedInputInterfaceData {\n+ if test.expectUnexpectedInputInterfaceEvent {\n+ return &onUnexpectedInputInterfaceData{stack.MulticastPacketContext{stack.UnicastSourceAndMulticastDestination{srcAddr, dstAddr}, incomingNICID}, test.routeInputInterface}\n+ }\n+ return nil\n+ }()\n+\n+ if diff := cmp.Diff(wantUnexpectedInputInterfaceEvent, eventDispatcher.onUnexpectedInputInterfaceData, cmp.AllowUnexported(onUnexpectedInputInterfaceData{})); diff != \"\" {\n+ t.Errorf(\"onUnexpectedInputInterfaceData mismatch (-want +got):\\n%s\", diff)\n+ }\n+\n+ wantMissingRouteEvent := func() *onMissingRouteData {\n+ if test.expectMissingRouteEvent {\n+ return &onMissingRouteData{stack.MulticastPacketContext{stack.UnicastSourceAndMulticastDestination{srcAddr, dstAddr}, incomingNICID}}\n+ }\n+ return nil\n+ }()\n+\n+ if diff := cmp.Diff(wantMissingRouteEvent, eventDispatcher.onMissingRouteData, cmp.AllowUnexported(onMissingRouteData{})); diff != \"\" {\n+ t.Errorf(\"onMissingRouteData mismatch (-want +got):\\n%s\", diff)\n+ }\n})\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Emit multicast forwarding events.
Updates #7338.
PiperOrigin-RevId: 452051657 |
259,891 | 31.05.2022 14:12:48 | 25,200 | f4d6127a5cc311560d74581554d86ffccdbc61f9 | checkescape: address ARM relative offsets
`go tool objdump` produces relative offsets for BL instructions as a number of
instructions rather than a number of bytes. Calculate the byte offset ourselves.
Example passing run on ARM machine:
Filed bug upstream about confusing output here: | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables.go",
"new_path": "pkg/tcpip/stack/iptables.go",
"diff": "@@ -315,7 +315,7 @@ func (it *IPTables) shouldSkipOrPopulateTables(tables []checkTable, pkt *PacketB\n// This is called in the hot path even when iptables are disabled, so we ensure\n// that it does not allocate. Note that called functions (e.g.\n// getConnAndUpdate) can allocate.\n-// TODO(b/233951539): checkescape fails on arm sometimes. Fix and re-add.\n+// +checkescape\nfunc (it *IPTables) CheckPrerouting(pkt *PacketBuffer, addressEP AddressableEndpoint, inNicName string) bool {\ntables := [...]checkTable{\n{\n@@ -353,7 +353,7 @@ func (it *IPTables) CheckPrerouting(pkt *PacketBuffer, addressEP AddressableEndp\n// This is called in the hot path even when iptables are disabled, so we ensure\n// that it does not allocate. Note that called functions (e.g.\n// getConnAndUpdate) can allocate.\n-// TODO(b/233951539): checkescape fails on arm sometimes. Fix and re-add.\n+// +checkescape\nfunc (it *IPTables) CheckInput(pkt *PacketBuffer, inNicName string) bool {\ntables := [...]checkTable{\n{\n@@ -393,7 +393,7 @@ func (it *IPTables) CheckInput(pkt *PacketBuffer, inNicName string) bool {\n// This is called in the hot path even when iptables are disabled, so we ensure\n// that it does not allocate. Note that called functions (e.g.\n// getConnAndUpdate) can allocate.\n-// TODO(b/233951539): checkescape fails on arm sometimes. Fix and re-add.\n+// +checkescape\nfunc (it *IPTables) CheckForward(pkt *PacketBuffer, inNicName, outNicName string) bool {\ntables := [...]checkTable{\n{\n@@ -425,7 +425,7 @@ func (it *IPTables) CheckForward(pkt *PacketBuffer, inNicName, outNicName string\n// This is called in the hot path even when iptables are disabled, so we ensure\n// that it does not allocate. Note that called functions (e.g.\n// getConnAndUpdate) can allocate.\n-// TODO(b/233951539): checkescape fails on arm sometimes. Fix and re-add.\n+// +checkescape\nfunc (it *IPTables) CheckOutput(pkt *PacketBuffer, r *Route, outNicName string) bool {\ntables := [...]checkTable{\n{\n@@ -467,7 +467,7 @@ func (it *IPTables) CheckOutput(pkt *PacketBuffer, r *Route, outNicName string)\n// This is called in the hot path even when iptables are disabled, so we ensure\n// that it does not allocate. Note that called functions (e.g.\n// getConnAndUpdate) can allocate.\n-// TODO(b/233951539): checkescape fails on arm sometimes. Fix and re-add.\n+// +checkescape\nfunc (it *IPTables) CheckPostrouting(pkt *PacketBuffer, r *Route, addressEP AddressableEndpoint, outNicName string) bool {\ntables := [...]checkTable{\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/checkescape/BUILD",
"new_path": "tools/checkescape/BUILD",
"diff": "@@ -4,7 +4,11 @@ package(licenses = [\"notice\"])\ngo_library(\nname = \"checkescape\",\n- srcs = [\"checkescape.go\"],\n+ srcs = [\n+ \"checkescape.go\",\n+ \"checkescape_amd64.go\",\n+ \"checkescape_arm64.go\",\n+ ],\nnogo = False,\nvisibility = [\"//tools/nogo:__subpackages__\"],\ndeps = [\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/checkescape/checkescape.go",
"new_path": "tools/checkescape/checkescape.go",
"diff": "@@ -436,10 +436,11 @@ func loadObjdump(binary io.Reader) (finalResults map[string][]string, finalErr e\n}\n}()\n- // Identify calls by address or name. Note that this is also\n- // constructed dynamically below, as we encounted the addresses.\n- // This is because some of the functions (duffzero) may have\n- // jump targets in the middle of the function itself.\n+ // Identify calls by address or name. Note that the list of allowed addresses\n+ // -- not the list of allowed function names -- is also constructed\n+ // dynamically below, as we encounter the addresses. This is because some of\n+ // the functions (duffzero) may have jump targets in the middle of the\n+ // function itself.\nfuncsAllowed := map[string]struct{}{\n\"runtime.duffzero\": {},\n\"runtime.duffcopy\": {},\n@@ -463,6 +464,8 @@ func loadObjdump(binary io.Reader) (finalResults map[string][]string, finalErr e\n\"runtime.stackcheck\": {},\n\"runtime.settls\": {},\n}\n+ // addrsAllowed lists every address that can be jumped to within the\n+ // funcsAllowed functions.\naddrsAllowed := make(map[string]struct{})\n// Build the map.\n@@ -477,7 +480,8 @@ NextLine:\n}\nfields := strings.Fields(line)\n- // Is this an \"allowed\" function definition?\n+ // Is this an \"allowed\" function definition? If so, record every address of\n+ // the function body.\nif len(fields) >= 2 && fields[0] == \"TEXT\" {\nnextFunc = strings.TrimSuffix(fields[1], \"(SB)\")\nif _, ok := funcsAllowed[nextFunc]; !ok {\n@@ -485,7 +489,8 @@ NextLine:\n}\n}\nif nextFunc != \"\" && len(fields) > 2 {\n- // Save the given address (in hex form, as it appears).\n+ // We're inside an allowed function. Save the given address (in hex form,\n+ // as it appears).\naddrsAllowed[fields[1]] = struct{}{}\n}\n@@ -503,6 +508,10 @@ NextLine:\n}\nsite := fields[0]\ntarget := strings.TrimSuffix(fields[4], \"(SB)\")\n+ target, err := fixOffset(fields, target)\n+ if err != nil {\n+ return nil, err\n+ }\n// Ignore strings containing allowed functions.\nif _, ok := funcsAllowed[target]; ok {\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tools/checkescape/checkescape_amd64.go",
"diff": "+// Copyright 2022 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 checkescape\n+\n+// fixOffset does nothing on amd64.\n+func fixOffset(fields []string, target string) (string, error) {\n+ return target, nil\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tools/checkescape/checkescape_arm64.go",
"diff": "+// Copyright 2022 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 checkescape\n+\n+import (\n+ \"fmt\"\n+ \"strconv\"\n+ \"strings\"\n+)\n+\n+// fixOffset accounts for the output of arm64 `go tool objdump`. Objdump gives\n+// the instruction offset rather than the byte offset. The offset confuses\n+// checkescape, as it looks like the branch is to random memory.\n+//\n+// When appropriate, we re-parse the instruction ourselves and return the\n+// correct offset.\n+func fixOffset(fields []string, target string) (string, error) {\n+ // We're looking for a line that looks something like:\n+ // iptables.go:320 0x211214 97f9b198 CALL -413288(PC)\n+ // In this case, target is passed as -413288(PC). The byte offset of this\n+ // instruction should be -1653152.\n+\n+ // Make sure we're dealing with a PC offset.\n+ if !strings.HasSuffix(target, \"(PC)\") {\n+ return target, nil // Not a relative branch.\n+ }\n+\n+ // Examine the opcode to ensure it's a BL instruction. See the ARM\n+ // documentation here:\n+ // https://developer.arm.com/documentation/ddi0596/2020-12/Base-Instructions/BL--Branch-with-Link-?lang=en\n+ const (\n+ opcodeBits = 0xfc000000\n+ blOpcode = 0x94000000\n+ )\n+ instr64, err := strconv.ParseUint(fields[2], 16, 32)\n+ if err != nil {\n+ return \"\", err\n+ }\n+ instr := uint32(instr64)\n+ if instr&opcodeBits != blOpcode {\n+ return target, nil // Not a BL.\n+ }\n+ // Per documentation, the offset is formed via:\n+ // - Take the lower 26 bits\n+ // - Append 2 zero bits (this is what objdump omits)\n+ // - Sign extend out to 64 bits\n+ offset := int64(int32(instr<<6) >> 4)\n+\n+ // Parse the PC, removing the leading \"0x\".\n+ pc, err := strconv.ParseUint(fields[1][len(\"0x\"):], 16, 64)\n+ if err != nil {\n+ return \"\", err\n+ }\n+ // PC is always the next instruction.\n+ pc += 8\n+ return fmt.Sprintf(\"0x%x\", pc+uint64(offset)), nil\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | checkescape: address ARM relative offsets
`go tool objdump` produces relative offsets for BL instructions as a number of
instructions rather than a number of bytes. Calculate the byte offset ourselves.
Example passing run on ARM machine:
https://buildkite.com/gvisor/pipeline/builds/14732#018106ac-ac8e-4636-9a5a-bde1641b1175
Filed bug upstream about confusing output here:
https://github.com/golang/go/issues/53117
PiperOrigin-RevId: 452137751 |
259,868 | 31.05.2022 15:18:22 | 25,200 | 3ec7b4b614ad2d8f13e481e5f80b79d685002860 | Add Makefile support to mount kernel header files and device files.
Also use `realpath` in place of `readlink` wherever appropriate. | [
{
"change_type": "MODIFY",
"old_path": "tools/bazel.mk",
"new_path": "tools/bazel.mk",
"diff": "## BAZEL_CACHE - The bazel cache directory (default: detected).\n## GCLOUD_CONFIG - The gcloud config directory (detect: detected).\n## DOCKER_SOCKET - The Docker socket (default: detected).\n+## DEVICE_FILE - An optional device file to expose in the container\n+## (default: no device file is exposed).\n##\n## To opt out of these wrappers, set DOCKER_BUILD=false.\nDOCKER_BUILD := true\n@@ -44,7 +46,7 @@ RACE_FLAGS := --@io_bazel_rules_go//go/config:race\n# Bazel container configuration (see below).\nUSER := $(shell whoami)\n-HASH := $(shell readlink -m $(CURDIR) | md5sum | cut -c1-8)\n+HASH := $(shell realpath -m $(CURDIR) | md5sum | cut -c1-8)\nBUILDER_NAME := gvisor-builder-$(HASH)-$(ARCH)\nDOCKER_NAME := gvisor-bazel-$(HASH)-$(ARCH)\nDOCKER_PRIVILEGED := --privileged\n@@ -52,6 +54,7 @@ BAZEL_CACHE := $(HOME)/.cache/bazel/\nGCLOUD_CONFIG := $(HOME)/.config/gcloud/\nDOCKER_SOCKET := /var/run/docker.sock\nDOCKER_CONFIG := /etc/docker\n+DEVICE_FILE ?=\n##\n## Bazel helpers.\n@@ -80,15 +83,28 @@ DOCKER_RUN_OPTIONS += --rm\nDOCKER_RUN_OPTIONS += --user $(UID):$(GID)\nDOCKER_RUN_OPTIONS += --entrypoint \"\"\nDOCKER_RUN_OPTIONS += --init\n-DOCKER_RUN_OPTIONS += -v \"$(shell readlink -m $(BAZEL_CACHE)):$(BAZEL_CACHE)\"\n-DOCKER_RUN_OPTIONS += -v \"$(shell readlink -m $(GCLOUD_CONFIG)):$(GCLOUD_CONFIG)\"\n-DOCKER_RUN_OPTIONS += -v \"/tmp:/tmp\"\n+DOCKER_RUN_OPTIONS += -v \"$(shell realpath -m $(BAZEL_CACHE)):$(BAZEL_CACHE):shared\"\n+DOCKER_RUN_OPTIONS += -v \"$(shell realpath -m $(GCLOUD_CONFIG)):$(GCLOUD_CONFIG)\"\n+DOCKER_RUN_OPTIONS += -v \"/tmp:/tmp:shared\"\nDOCKER_EXEC_OPTIONS := --user $(UID):$(GID)\nDOCKER_EXEC_OPTIONS += --interactive\nifeq (true,$(shell test -t 1 && echo true))\nDOCKER_EXEC_OPTIONS += --tty\nendif\n+# If kernel headers are available, mount them too.\n+ifneq (,$(wildcard /lib/modules))\n+DOCKER_RUN_OPTIONS += -v \"/lib/modules:/lib/modules\"\n+endif\n+KERNEL_HEADERS_DIR := $(shell realpath -m /lib/modules/$(shell uname -r)/build)\n+ifneq (,$(wildcard $(KERNEL_HEADERS_DIR)))\n+DOCKER_RUN_OPTIONS += -v \"$(KERNEL_HEADERS_DIR):$(KERNEL_HEADERS_DIR)\"\n+ifneq ($(shell realpath -m $(KERNEL_HEADERS_DIR)/Makefile),$(KERNEL_HEADERS_DIR)/Makefile)\n+KERNEL_HEADERS_DIR_LINKED := $(dir $(shell realpath -m $(KERNEL_HEADERS_DIR)/Makefile))\n+DOCKER_RUN_OPTIONS += -v \"$(KERNEL_HEADERS_DIR_LINKED):$(KERNEL_HEADERS_DIR_LINKED)\"\n+endif\n+endif\n+\n# Add basic UID/GID options.\n#\n# Note that USERADD_DOCKER and GROUPADD_DOCKER are both defined as \"deferred\"\n@@ -113,6 +129,7 @@ ifneq ($(DOCKER_PRIVILEGED),)\nDOCKER_RUN_OPTIONS += -v \"$(DOCKER_SOCKET):$(DOCKER_SOCKET)\"\nDOCKER_RUN_OPTIONS += -v \"$(DOCKER_CONFIG):$(DOCKER_CONFIG)\"\nDOCKER_RUN_OPTIONS += $(DOCKER_PRIVILEGED)\n+DOCKER_RUN_OPTIONS += --cap-add SYS_MODULE\nDOCKER_EXEC_OPTIONS += $(DOCKER_PRIVILEGED)\nDOCKER_GROUP := $(shell stat -c '%g' $(DOCKER_SOCKET))\nifneq ($(GID),$(DOCKER_GROUP))\n@@ -133,6 +150,13 @@ DOCKER_RUN_OPTIONS += --group-add $(KVM_GROUP)\nendif\nendif\n+# Add other device file, if specified.\n+ifneq ($(DEVICE_FILE),)\n+ifneq (,$(wildcard $(DEVICE_FILE)))\n+DOCKER_RUN_OPTIONS += --device \"$(DEVICE_FILE):$(DEVICE_FILE)\"\n+endif\n+endif\n+\n# Top-level functions.\n#\n# This command runs a bazel server, and the container sticks around\n@@ -187,7 +211,7 @@ build_paths = \\\n(set -euo pipefail; \\\n$(call wrapper,$(BAZEL) build $(BASE_OPTIONS) $(BAZEL_OPTIONS) $(1)) && \\\n$(call wrapper,$(BAZEL) cquery $(BASE_OPTIONS) $(BAZEL_OPTIONS) $(1) --output=starlark --starlark:file=tools/show_paths.bzl) \\\n- | xargs -r -I {} bash -c 'test -e \"{}\" || exit 0; readlink -f \"{}\"' \\\n+ | xargs -r -I {} bash -c 'test -e \"{}\" || exit 0; realpath -m \"{}\"' \\\n| xargs -r -I {} bash -c 'set -euo pipefail; $(2)')\nclean = $(call header,CLEAN) && $(call wrapper,$(BAZEL) clean)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add Makefile support to mount kernel header files and device files.
Also use `realpath` in place of `readlink` wherever appropriate.
PiperOrigin-RevId: 452152372 |
259,868 | 31.05.2022 15:44:05 | 25,200 | 9ab1f6756b6ecea55aca988ff464bbfff454d0d4 | runsc: Add more precise error messages in `{container,sandbox}.go`. | [
{
"change_type": "MODIFY",
"old_path": "runsc/container/container.go",
"new_path": "runsc/container/container.go",
"diff": "@@ -219,7 +219,7 @@ func New(conf *config.Config, args Args) (*Container, error) {\n// Lock the container metadata file to prevent concurrent creations of\n// containers with the same id.\nif err := c.Saver.lockForNew(); err != nil {\n- return nil, err\n+ return nil, fmt.Errorf(\"cannot lock container metadata file: %w\", err)\n}\ndefer c.Saver.unlockOrDie()\n@@ -252,14 +252,14 @@ func New(conf *config.Config, args Args) (*Container, error) {\n// part of the cgroup from the start (and all their children processes).\nparentCgroup, subCgroup, err = c.setupCgroupForRoot(conf, args.Spec)\nif err != nil {\n- return nil, err\n+ return nil, fmt.Errorf(\"cannot set up cgroup for root: %w\", err)\n}\n}\nc.CompatCgroup = cgroup.CgroupJSON{Cgroup: subCgroup}\nif err := runInCgroup(parentCgroup, func() error {\nioFiles, specFile, err := c.createGoferProcess(args.Spec, conf, args.BundleDir, args.Attached)\nif err != nil {\n- return err\n+ return fmt.Errorf(\"cannot create gofer process: %w\", err)\n}\n// Start a new sandbox for this container. Any errors after this point\n@@ -277,7 +277,7 @@ func New(conf *config.Config, args Args) (*Container, error) {\n}\nsand, err := sandbox.New(conf, sandArgs)\nif err != nil {\n- return err\n+ return fmt.Errorf(\"cannot create sandbox: %w\", err)\n}\nc.Sandbox = sand\nreturn nil\n@@ -295,7 +295,7 @@ func New(conf *config.Config, args Args) (*Container, error) {\n}\nsb, err := Load(conf.RootDir, fullID, LoadOpts{Exact: true})\nif err != nil {\n- return nil, err\n+ return nil, fmt.Errorf(\"cannot load sandbox: %w\", err)\n}\nc.Sandbox = sb.Sandbox\n@@ -320,7 +320,7 @@ func New(conf *config.Config, args Args) (*Container, error) {\n}\nif err := c.Sandbox.CreateSubcontainer(conf, c.ID, tty); err != nil {\n- return nil, err\n+ return nil, fmt.Errorf(\"cannot create subcontainer: %w\", err)\n}\n}\nc.changeStatus(Created)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -202,7 +202,7 @@ func New(conf *config.Config, args *Args) (*Sandbox, error) {\n}\nargs.SinkFiles, err = initConf.Setup()\nif err != nil {\n- return nil, err\n+ return nil, fmt.Errorf(\"cannot init config: %w\", err)\n}\n}\n@@ -219,7 +219,7 @@ func New(conf *config.Config, args *Args) (*Sandbox, error) {\n// process exits unexpectedly.\nsandboxSyncFile.Close()\nif err != nil {\n- return nil, err\n+ return nil, fmt.Errorf(\"cannot create sandbox process: %w\", err)\n}\n// Wait until the sandbox has booted.\n@@ -237,7 +237,7 @@ func New(conf *config.Config, args *Args) (*Sandbox, error) {\nreturn nil, fmt.Errorf(\"%v: %v\", err, permsErr)\n}\n}\n- return nil, err\n+ return nil, fmt.Errorf(\"cannot read client sync file: %w\", err)\n}\nc.Release()\n@@ -623,7 +623,7 @@ func (s *Sandbox) createSandboxProcess(conf *config.Config, args *Args, startSyn\nspecFile, err := specutils.OpenSpec(args.BundleDir)\nif err != nil {\n- return err\n+ return fmt.Errorf(\"cannot open spec file in bundle dir %v: %w\", args.BundleDir, err)\n}\ndonations.DonateAndClose(\"spec-fd\", specFile)\n@@ -634,7 +634,7 @@ func (s *Sandbox) createSandboxProcess(conf *config.Config, args *Args, startSyn\ngPlatform, err := platform.Lookup(conf.Platform)\nif err != nil {\n- return err\n+ return fmt.Errorf(\"cannot look up platform: %w\", err)\n}\nif deviceFile, err := gPlatform.OpenDevice(conf.PlatformDevicePath); err != nil {\nreturn fmt.Errorf(\"opening device file for platform %q: %v\", conf.Platform, err)\n"
}
] | Go | Apache License 2.0 | google/gvisor | runsc: Add more precise error messages in `{container,sandbox}.go`.
PiperOrigin-RevId: 452158030 |
259,907 | 31.05.2022 16:43:47 | 25,200 | cad9a8303f2e76afd7ad7bfaba367c08fa3fdb46 | Add ppid to trace procfs output.
Updates | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/procfs/dump.go",
"new_path": "runsc/boot/procfs/dump.go",
"diff": "@@ -49,6 +49,7 @@ type UIDGID struct {\ntype Status struct {\nComm string `json:\"comm,omitempty\"`\nPID int32 `json:\"pid,omitempty\"`\n+ PPID int32 `json:\"ppid,omitempty\"`\nUID UIDGID `json:\"uid,omitempty\"`\nGID UIDGID `json:\"gid,omitempty\"`\nVMSize uint64 `json:\"vm_size,omitempty\"`\n@@ -208,12 +209,17 @@ func getFDLimit(ctx context.Context, pid kernel.ThreadID) (limits.Limit, error)\nreturn limits.Limit{}, fmt.Errorf(\"could not find limit set for pid %s\", pid)\n}\n-func getStatus(t *kernel.Task, mm *mm.MemoryManager, pid kernel.ThreadID) Status {\n+func getStatus(t *kernel.Task, mm *mm.MemoryManager, pid kernel.ThreadID, pidns *kernel.PIDNamespace) Status {\ncreds := t.Credentials()\nuns := creds.UserNamespace\n+ ppid := kernel.ThreadID(0)\n+ if parent := t.Parent(); parent != nil {\n+ ppid = pidns.IDOfThreadGroup(parent.ThreadGroup())\n+ }\nreturn Status{\nComm: t.Name(),\nPID: int32(pid),\n+ PPID: int32(ppid),\nUID: UIDGID{\nReal: uint32(creds.RealKUID.In(uns).OrOverflow()),\nEffective: uint32(creds.EffectiveKUID.In(uns).OrOverflow()),\n@@ -265,7 +271,7 @@ func Dump(t *kernel.Task, pid kernel.ThreadID, pidns *kernel.PIDNamespace) (Proc\n// We don't need to worry about fake cgroup controllers as that is not\n// supported in runsc.\nCgroup: t.GetCgroupEntries(),\n- Status: getStatus(t, mm, pid),\n+ Status: getStatus(t, mm, pid, pidns),\nStat: getStat(t, pid, pidns),\n}, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/trace_test.go",
"new_path": "runsc/container/trace_test.go",
"diff": "@@ -413,6 +413,10 @@ func TestProcfsDump(t *testing.T) {\n}\n}\n+ if wantPPID := int32(0); procfsDump[0].Status.PPID != wantPPID {\n+ t.Errorf(\"expected PPID to be %d, but got %d\", wantPPID, procfsDump[0].Status.PPID)\n+ }\n+\nif wantName := \"sleep\"; procfsDump[0].Status.Comm != wantName {\nt.Errorf(\"expected Comm to be %q, but got %q\", wantName, procfsDump[0].Status.Comm)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add ppid to trace procfs output.
Updates #4805
PiperOrigin-RevId: 452169866 |
259,909 | 31.05.2022 17:14:09 | 25,200 | c24bef7b80aba0831b1a7907737df8ee0bc152bd | Fix racy behavior in tcp Read().
The startRead and commitRead with RcvReadMu is not safe anymore with the
change to Close() that purges the read queue.
This may reduce performance of highly concurrent reads. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/accept.go",
"new_path": "pkg/tcpip/transport/tcp/accept.go",
"diff": "@@ -214,7 +214,10 @@ func (l *listenContext) createConnectingEndpoint(s *segment, rcvdSynOpts header.\n// Bootstrap the auto tuning algorithm. Starting at zero will result in\n// a large step function on the first window adjustment causing the\n// window to grow to a really large value.\n- n.rcvQueueInfo.RcvAutoParams.PrevCopiedBytes = n.initialReceiveWindow()\n+ initWnd := n.initialReceiveWindow()\n+ n.rcvQueueMu.Lock()\n+ n.RcvAutoParams.PrevCopiedBytes = initWnd\n+ n.rcvQueueMu.Unlock()\nreturn n, nil\n}\n@@ -432,9 +435,9 @@ func (a *acceptQueue) isFull() bool {\n//\n// +checklocks:e.mu\nfunc (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) tcpip.Error {\n- e.rcvQueueInfo.rcvQueueMu.Lock()\n- rcvClosed := e.rcvQueueInfo.RcvClosed\n- e.rcvQueueInfo.rcvQueueMu.Unlock()\n+ e.rcvQueueMu.Lock()\n+ rcvClosed := e.RcvClosed\n+ e.rcvQueueMu.Unlock()\nif rcvClosed || s.flags.Contains(header.TCPFlagSyn|header.TCPFlagAck) {\n// If the endpoint is shutdown, reply with reset.\n//\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/connect.go",
"new_path": "pkg/tcpip/transport/tcp/connect.go",
"diff": "@@ -654,13 +654,13 @@ func (h *handshake) transitionToStateEstablishedLocked(s *segment) {\nh.ep.snd.updateRTO(rtt)\n}\n- h.ep.rcvQueueInfo.rcvQueueMu.Lock()\n+ h.ep.rcvQueueMu.Lock()\nh.ep.rcv = newReceiver(h.ep, h.ackNum-1, h.rcvWnd, h.effectiveRcvWndScale())\n// Bootstrap the auto tuning algorithm. Starting at zero will\n// result in a really large receive window after the first auto\n// tuning adjustment.\n- h.ep.rcvQueueInfo.RcvAutoParams.PrevCopiedBytes = int(h.rcvWnd)\n- h.ep.rcvQueueInfo.rcvQueueMu.Unlock()\n+ h.ep.RcvAutoParams.PrevCopiedBytes = int(h.rcvWnd)\n+ h.ep.rcvQueueMu.Unlock()\nh.ep.setEndpointState(StateEstablished)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -293,18 +293,6 @@ func (sq *sndQueueInfo) CloneState(other *stack.TCPSndBufState) {\nother.AutoTuneSndBufDisabled = atomicbitops.FromUint32(sq.AutoTuneSndBufDisabled.RacyLoad())\n}\n-// rcvQueueInfo contains the endpoint's rcvQueue and associated metadata.\n-//\n-// +stateify savable\n-type rcvQueueInfo struct {\n- rcvQueueMu sync.Mutex `state:\"nosave\"`\n- stack.TCPRcvBufState\n-\n- // rcvQueue is the queue for ready-for-delivery segments. This struct's\n- // mutex must be held in order append segments to list.\n- rcvQueue segmentList `state:\"wait\"`\n-}\n-\n// endpoint represents a TCP endpoint. This struct serves as the interface\n// between users of the endpoint and the protocol implementation; it is legal to\n// have concurrent goroutines make calls into the endpoint, they are properly\n@@ -321,7 +309,8 @@ type rcvQueueInfo struct {\n// acquired with e.mu then e.mu must be acquired first.\n//\n// e.acceptMu -> Protects e.acceptQueue.\n-// e.rcvQueueMu -> Protects e.rcvQueue and associated fields.\n+// e.rcvQueueMu -> Protects e.rcvQueue's associated fields but not e.rcvQueue\n+// itself.\n// e.sndQueueMu -> Protects the e.sndQueue and associated fields.\n// e.lastErrorMu -> Protects the lastError field.\n//\n@@ -380,22 +369,10 @@ type endpoint struct {\nlastErrorMu sync.Mutex `state:\"nosave\"`\nlastError tcpip.Error\n- // rcvReadMu synchronizes calls to Read.\n- //\n- // mu and rcvQueueMu are temporarily released during data copying. rcvReadMu\n- // must be held during each read to ensure atomicity, so that multiple reads\n- // do not interleave.\n- //\n- // rcvReadMu should be held before holding mu.\n- rcvReadMu sync.Mutex `state:\"nosave\"`\n+ rcvQueueMu sync.Mutex `state:\"nosave\"`\n- // rcvQueueInfo holds the implementation of the endpoint's receive buffer.\n- // The data within rcvQueueInfo should only be accessed while rcvReadMu, mu,\n- // and rcvQueueMu are held, in that stated order. While processing the segment\n- // range, you can determine a range and then temporarily release mu and\n- // rcvQueueMu, which allows new segments to be appended to the queue while\n- // processing.\n- rcvQueueInfo rcvQueueInfo\n+ // +checklocks:rcvQueueMu\n+ stack.TCPRcvBufState\n// rcvMemUsed tracks the total amount of memory in use by received segments\n// held in rcvQueue, pendingRcvdSegments and the segment queue. This is used to\n@@ -412,6 +389,11 @@ type endpoint struct {\nmu sync.CrossGoroutineMutex `state:\"nosave\"`\nownedByUser atomicbitops.Uint32\n+ // rcvQueue is the queue for ready-for-delivery segments.\n+ //\n+ // +checklocks:mu\n+ rcvQueue segmentList `state:\"wait\"`\n+\n// state must be read/set using the EndpointState()/setEndpointState()\n// methods.\nstate atomicbitops.Uint32 `state:\".(EndpointState)\"`\n@@ -856,7 +838,7 @@ func newEndpoint(s *stack.Stack, protocol *protocol, netProto tcpip.NetworkProto\nvar mrb tcpip.TCPModerateReceiveBufferOption\nif err := s.TransportProtocolOption(ProtocolNumber, &mrb); err == nil {\n- e.rcvQueueInfo.RcvAutoParams.Disabled = !bool(mrb)\n+ e.RcvAutoParams.Disabled = !bool(mrb)\n}\nvar de tcpip.TCPDelayEnabled\n@@ -928,11 +910,11 @@ func (e *endpoint) Readiness(mask waiter.EventMask) waiter.EventMask {\n// Determine if the endpoint is readable if requested.\nif (mask & waiter.ReadableEvents) != 0 {\n- e.rcvQueueInfo.rcvQueueMu.Lock()\n- if e.rcvQueueInfo.RcvBufUsed > 0 || e.rcvQueueInfo.RcvClosed {\n+ e.rcvQueueMu.Lock()\n+ if e.RcvBufUsed > 0 || e.RcvClosed {\nresult |= waiter.ReadableEvents\n}\n- e.rcvQueueInfo.rcvQueueMu.Unlock()\n+ e.rcvQueueMu.Unlock()\n}\n}\n@@ -952,17 +934,17 @@ func (e *endpoint) purgePendingRcvQueue() {\n// +checklocks:e.mu\nfunc (e *endpoint) purgeReadQueue() {\nif e.rcv != nil {\n- e.rcvQueueInfo.rcvQueueMu.Lock()\n- defer e.rcvQueueInfo.rcvQueueMu.Unlock()\n+ e.rcvQueueMu.Lock()\n+ defer e.rcvQueueMu.Unlock()\nfor {\n- s := e.rcvQueueInfo.rcvQueue.Front()\n+ s := e.rcvQueue.Front()\nif s == nil {\nbreak\n}\n- e.rcvQueueInfo.rcvQueue.Remove(s)\n+ e.rcvQueue.Remove(s)\ns.DecRef()\n}\n- e.rcvQueueInfo.RcvBufUsed = 0\n+ e.RcvBufUsed = 0\n}\n}\n@@ -1236,19 +1218,19 @@ func (e *endpoint) ModerateRecvBuf(copied int) {\nsendNonZeroWindowUpdate := false\n- e.rcvQueueInfo.rcvQueueMu.Lock()\n- if e.rcvQueueInfo.RcvAutoParams.Disabled {\n- e.rcvQueueInfo.rcvQueueMu.Unlock()\n+ e.rcvQueueMu.Lock()\n+ if e.RcvAutoParams.Disabled {\n+ e.rcvQueueMu.Unlock()\nreturn\n}\nnow := e.stack.Clock().NowMonotonic()\n- if rtt := e.rcvQueueInfo.RcvAutoParams.RTT; rtt == 0 || now.Sub(e.rcvQueueInfo.RcvAutoParams.MeasureTime) < rtt {\n- e.rcvQueueInfo.RcvAutoParams.CopiedBytes += copied\n- e.rcvQueueInfo.rcvQueueMu.Unlock()\n+ if rtt := e.RcvAutoParams.RTT; rtt == 0 || now.Sub(e.RcvAutoParams.MeasureTime) < rtt {\n+ e.RcvAutoParams.CopiedBytes += copied\n+ e.rcvQueueMu.Unlock()\nreturn\n}\n- prevRTTCopied := e.rcvQueueInfo.RcvAutoParams.CopiedBytes + copied\n- prevCopied := e.rcvQueueInfo.RcvAutoParams.PrevCopiedBytes\n+ prevRTTCopied := e.RcvAutoParams.CopiedBytes + copied\n+ prevCopied := e.RcvAutoParams.PrevCopiedBytes\nrcvWnd := 0\nif prevRTTCopied > prevCopied {\n// The minimal receive window based on what was copied by the app\n@@ -1294,14 +1276,14 @@ func (e *endpoint) ModerateRecvBuf(copied int) {\n// where PrevCopiedBytes > prevRTTCopied the existing buffer is already big\n// enough to handle the current rate and we don't need to do any\n// adjustments.\n- e.rcvQueueInfo.RcvAutoParams.PrevCopiedBytes = prevRTTCopied\n+ e.RcvAutoParams.PrevCopiedBytes = prevRTTCopied\n}\n- e.rcvQueueInfo.RcvAutoParams.MeasureTime = now\n- e.rcvQueueInfo.RcvAutoParams.CopiedBytes = 0\n- e.rcvQueueInfo.rcvQueueMu.Unlock()\n+ e.RcvAutoParams.MeasureTime = now\n+ e.RcvAutoParams.CopiedBytes = 0\n+ e.rcvQueueMu.Unlock()\n- // Send the update after unlocking rcvQueueInfo as sending a segment acquires\n- // e.rcvQueueInfo.rcvQueueMu to calculate the window to be sent.\n+ // Send the update after unlocking rcvQueueMu as sending a segment acquires\n+ // the lock to calculate the window to be sent.\nif e.EndpointState().connected() && sendNonZeroWindowUpdate {\ne.rcv.nonZeroWindow() // +checklocksforce:e.rcv.ep.mu\n}\n@@ -1356,45 +1338,63 @@ func (e *endpoint) UpdateLastError(err tcpip.Error) {\n// Read implements tcpip.Endpoint.Read.\nfunc (e *endpoint) Read(dst io.Writer, opts tcpip.ReadOptions) (tcpip.ReadResult, tcpip.Error) {\n- e.rcvReadMu.Lock()\n- defer e.rcvReadMu.Unlock()\n-\n- // N.B. Here we get a range of segments to be processed. It is safe to not\n- // hold rcvQueueMu when processing, since we hold rcvReadMu to ensure only we\n- // can remove segments from the list through commitRead().\n- first, last, serr := e.startRead()\n- if serr != nil {\n- if _, ok := serr.(*tcpip.ErrClosedForReceive); ok {\n+ e.LockUser()\n+ defer e.UnlockUser()\n+\n+ if err := e.checkReadLocked(); err != nil {\n+ if _, ok := err.(*tcpip.ErrClosedForReceive); ok {\ne.stats.ReadErrors.ReadClosed.Increment()\n}\n- return tcpip.ReadResult{}, serr\n+ return tcpip.ReadResult{}, err\n}\nvar err error\ndone := 0\n- s := first\n+ // N.B. Here we get the first segment to be processed. It is safe to not\n+ // hold rcvQueueMu when processing, since we hold e.mu to ensure we only\n+ // remove segments from the list through Read() and that new segments\n+ // cannot be appended.\n+ s := e.rcvQueue.Front()\nfor s != nil {\nvar n int\nn, err = s.ReadTo(dst, opts.Peek)\n// Book keeping first then error handling.\n-\ndone += n\nif opts.Peek {\n- // For peek, we use the (first, last) range of segment returned from\n- // startRead. We don't consume the receive buffer, so commitRead should\n- // not be called.\n- //\n- // N.B. It is important to use `last` to determine the last segment, since\n- // appending can happen while we process, and will lead to data race.\n- if s == last {\n- break\n- }\ns = s.Next()\n} else {\n- // N.B. commitRead() conveniently returns the next segment to read, after\n- // removing the data/segment that is read.\n- s = e.commitRead(n)\n+ sendNonZeroWindowUpdate := false\n+ memDelta := 0\n+ for {\n+ seg := e.rcvQueue.Front()\n+ if seg == nil || seg.payloadSize() != 0 {\n+ break\n+ }\n+ e.rcvQueue.Remove(seg)\n+ // Memory is only considered released when the whole segment has been\n+ // read.\n+ memDelta += seg.segMemSize()\n+ seg.DecRef()\n+ }\n+ e.rcvQueueMu.Lock()\n+ e.RcvBufUsed -= n\n+ s = e.rcvQueue.Front()\n+\n+ if memDelta > 0 {\n+ // If the window was small before this read and if the read freed up\n+ // enough buffer space, to either fit an aMSS or half a receive buffer\n+ // (whichever smaller), then notify the protocol goroutine to send a\n+ // window update.\n+ if crossed, above := e.windowCrossedACKThresholdLocked(memDelta, int(e.ops.GetReceiveBufferSize())); crossed && above {\n+ sendNonZeroWindowUpdate = true\n+ }\n+ }\n+ e.rcvQueueMu.Unlock()\n+\n+ if e.EndpointState().connected() && sendNonZeroWindowUpdate {\n+ e.rcv.nonZeroWindow() // +checklocksforce:e.rcv.ep.mu\n+ }\n}\nif err != nil {\n@@ -1412,101 +1412,44 @@ func (e *endpoint) Read(dst io.Writer, opts tcpip.ReadOptions) (tcpip.ReadResult\n}, nil\n}\n-// startRead checks that endpoint is in a readable state, and return the\n-// inclusive range of segments that can be read.\n+// checkRead checks that endpoint is in a readable state.\n//\n-// +checklocks:e.rcvReadMu\n-func (e *endpoint) startRead() (first, last *segment, err tcpip.Error) {\n- e.LockUser()\n- defer e.UnlockUser()\n-\n+// +checklocks:e.mu\n+func (e *endpoint) checkReadLocked() tcpip.Error {\n+ e.rcvQueueMu.Lock()\n+ defer e.rcvQueueMu.Unlock()\n// When in SYN-SENT state, let the caller block on the receive.\n// An application can initiate a non-blocking connect and then block\n// on a receive. It can expect to read any data after the handshake\n// is complete. RFC793, section 3.9, p58.\nif e.EndpointState() == StateSynSent {\n- return nil, nil, &tcpip.ErrWouldBlock{}\n+ return &tcpip.ErrWouldBlock{}\n}\n// The endpoint can be read if it's connected, or if it's already closed\n// but has some pending unread data. Also note that a RST being received\n// would cause the state to become StateError so we should allow the\n// reads to proceed before returning a ECONNRESET.\n- e.rcvQueueInfo.rcvQueueMu.Lock()\n- defer e.rcvQueueInfo.rcvQueueMu.Unlock()\n-\n- bufUsed := e.rcvQueueInfo.RcvBufUsed\n+ bufUsed := e.RcvBufUsed\nif s := e.EndpointState(); !s.connected() && s != StateClose && bufUsed == 0 {\nif s == StateError {\nif err := e.hardErrorLocked(); err != nil {\n- return nil, nil, err\n+ return err\n}\n- return nil, nil, &tcpip.ErrClosedForReceive{}\n+ return &tcpip.ErrClosedForReceive{}\n}\ne.stats.ReadErrors.NotConnected.Increment()\n- return nil, nil, &tcpip.ErrNotConnected{}\n- }\n-\n- if e.rcvQueueInfo.RcvBufUsed == 0 {\n- if e.rcvQueueInfo.RcvClosed || !e.EndpointState().connected() {\n- return nil, nil, &tcpip.ErrClosedForReceive{}\n- }\n- return nil, nil, &tcpip.ErrWouldBlock{}\n- }\n-\n- return e.rcvQueueInfo.rcvQueue.Front(), e.rcvQueueInfo.rcvQueue.Back(), nil\n-}\n-\n-// commitRead commits a read of done bytes and returns the next non-empty\n-// segment to read. Data read from the segment must have also been removed from\n-// the segment in order for this method to work correctly.\n-//\n-// It is performance critical to call commitRead frequently when servicing a big\n-// Read request, so TCP can make progress timely. Right now, it is designed to\n-// do this per segment read, hence this method conveniently returns the next\n-// segment to read while holding the lock.\n-//\n-// +checklocks:e.rcvReadMu\n-func (e *endpoint) commitRead(done int) *segment {\n- e.LockUser()\n- defer e.UnlockUser()\n-\n- sendNonZeroWindowUpdate := false\n- e.rcvQueueInfo.rcvQueueMu.Lock()\n- memDelta := 0\n- s := e.rcvQueueInfo.rcvQueue.Front()\n- for s != nil && s.payloadSize() == 0 {\n- e.rcvQueueInfo.rcvQueue.Remove(s)\n- // Memory is only considered released when the whole segment has been\n- // read.\n- memDelta += s.segMemSize()\n- s.DecRef()\n- s = e.rcvQueueInfo.rcvQueue.Front()\n- }\n- // Concurrent calls to Close() and Read() could cause RcvBufUsed to be\n- // negative because Read() unlocks between startRead() and commitRead(). In\n- // this case the read is allowed, but we refrain from subtracting from\n- // RcvBufUsed since it should already be zero.\n- if e.rcvQueueInfo.RcvBufUsed != 0 {\n- e.rcvQueueInfo.RcvBufUsed -= done\n+ return &tcpip.ErrNotConnected{}\n}\n- if memDelta > 0 {\n- // If the window was small before this read and if the read freed up\n- // enough buffer space, to either fit an aMSS or half a receive buffer\n- // (whichever smaller), then notify the protocol goroutine to send a\n- // window update.\n- if crossed, above := e.windowCrossedACKThresholdLocked(memDelta, int(e.ops.GetReceiveBufferSize())); crossed && above {\n- sendNonZeroWindowUpdate = true\n+ if e.RcvBufUsed == 0 {\n+ if e.RcvClosed || !e.EndpointState().connected() {\n+ return &tcpip.ErrClosedForReceive{}\n}\n+ return &tcpip.ErrWouldBlock{}\n}\n- nextSeg := e.rcvQueueInfo.rcvQueue.Front()\n- e.rcvQueueInfo.rcvQueueMu.Unlock()\n- if e.EndpointState().connected() && sendNonZeroWindowUpdate {\n- e.rcv.nonZeroWindow() // +checklocksforce:e.rcv.ep.mu\n- }\n- return nextSeg\n+ return nil\n}\n// isEndpointWritableLocked checks if a given endpoint is writable\n@@ -1652,11 +1595,11 @@ func (e *endpoint) Write(p tcpip.Payloader, opts tcpip.WriteOptions) (int64, tcp\n// selectWindowLocked returns the new window without checking for shrinking or scaling\n// applied.\n// +checklocks:e.mu\n-// +checklocks:e.rcvQueueInfo.rcvQueueMu\n+// +checklocks:e.rcvQueueMu\nfunc (e *endpoint) selectWindowLocked(rcvBufSize int) (wnd seqnum.Size) {\nwndFromAvailable := wndFromSpace(e.receiveBufferAvailableLocked(rcvBufSize))\nmaxWindow := wndFromSpace(rcvBufSize)\n- wndFromUsedBytes := maxWindow - e.rcvQueueInfo.RcvBufUsed\n+ wndFromUsedBytes := maxWindow - e.RcvBufUsed\n// We take the lesser of the wndFromAvailable and wndFromUsedBytes because in\n// cases where we receive a lot of small segments the segment overhead is a\n@@ -1677,9 +1620,9 @@ func (e *endpoint) selectWindowLocked(rcvBufSize int) (wnd seqnum.Size) {\n// selectWindow invokes selectWindowLocked after acquiring e.rcvQueueMu.\n// +checklocks:e.mu\nfunc (e *endpoint) selectWindow() (wnd seqnum.Size) {\n- e.rcvQueueInfo.rcvQueueMu.Lock()\n+ e.rcvQueueMu.Lock()\nwnd = e.selectWindowLocked(int(e.ops.GetReceiveBufferSize()))\n- e.rcvQueueInfo.rcvQueueMu.Unlock()\n+ e.rcvQueueMu.Unlock()\nreturn wnd\n}\n@@ -1698,7 +1641,7 @@ func (e *endpoint) selectWindow() (wnd seqnum.Size) {\n// otherwise.\n//\n// +checklocks:e.mu\n-// +checklocks:e.rcvQueueInfo.rcvQueueMu\n+// +checklocks:e.rcvQueueMu\nfunc (e *endpoint) windowCrossedACKThresholdLocked(deltaBefore int, rcvBufSize int) (crossed bool, above bool) {\nnewAvail := int(e.selectWindowLocked(rcvBufSize))\noldAvail := newAvail - deltaBefore\n@@ -1776,7 +1719,7 @@ func (e *endpoint) OnSetReceiveBufferSize(rcvBufSz, oldSz int64) (newSz int64, p\ne.LockUser()\nsendNonZeroWindowUpdate := false\n- e.rcvQueueInfo.rcvQueueMu.Lock()\n+ e.rcvQueueMu.Lock()\n// Make sure the receive buffer size allows us to send a\n// non-zero window size.\n@@ -1790,7 +1733,7 @@ func (e *endpoint) OnSetReceiveBufferSize(rcvBufSz, oldSz int64) (newSz int64, p\navailBefore := wndFromSpace(e.receiveBufferAvailableLocked(int(oldSz)))\navailAfter := wndFromSpace(e.receiveBufferAvailableLocked(int(rcvBufSz)))\n- e.rcvQueueInfo.RcvAutoParams.Disabled = true\n+ e.RcvAutoParams.Disabled = true\n// Immediately send an ACK to uncork the sender silly window\n// syndrome prevetion, when our available space grows above aMSS\n@@ -1799,7 +1742,7 @@ func (e *endpoint) OnSetReceiveBufferSize(rcvBufSz, oldSz int64) (newSz int64, p\nsendNonZeroWindowUpdate = true\n}\n- e.rcvQueueInfo.rcvQueueMu.Unlock()\n+ e.rcvQueueMu.Unlock()\npostSet = func() {\ne.LockUser()\n@@ -2029,10 +1972,10 @@ func (e *endpoint) readyReceiveSize() (int, tcpip.Error) {\nreturn 0, &tcpip.ErrInvalidEndpointState{}\n}\n- e.rcvQueueInfo.rcvQueueMu.Lock()\n- defer e.rcvQueueInfo.rcvQueueMu.Unlock()\n+ e.rcvQueueMu.Lock()\n+ defer e.rcvQueueMu.Unlock()\n- return e.rcvQueueInfo.RcvBufUsed, nil\n+ return e.RcvBufUsed, nil\n}\n// GetSockOptInt implements tcpip.Endpoint.GetSockOptInt.\n@@ -2506,10 +2449,10 @@ func (e *endpoint) shutdownLocked(flags tcpip.ShutdownFlags) tcpip.Error {\n// Close for read.\nif e.shutdownFlags&tcpip.ShutdownRead != 0 {\n// Mark read side as closed.\n- e.rcvQueueInfo.rcvQueueMu.Lock()\n- e.rcvQueueInfo.RcvClosed = true\n- rcvBufUsed := e.rcvQueueInfo.RcvBufUsed\n- e.rcvQueueInfo.rcvQueueMu.Unlock()\n+ e.rcvQueueMu.Lock()\n+ e.RcvClosed = true\n+ rcvBufUsed := e.RcvBufUsed\n+ e.rcvQueueMu.Unlock()\n// If we're fully closed and we have unread data we need to abort\n// the connection with a RST.\nif e.shutdownFlags&tcpip.ShutdownWrite != 0 && rcvBufUsed > 0 {\n@@ -2560,9 +2503,9 @@ func (e *endpoint) shutdownLocked(flags tcpip.ShutdownFlags) tcpip.Error {\n//\n// By not removing this endpoint from the demuxer mapping, we\n// ensure that any other bind to the same port fails, as on Linux.\n- e.rcvQueueInfo.rcvQueueMu.Lock()\n- e.rcvQueueInfo.RcvClosed = true\n- e.rcvQueueInfo.rcvQueueMu.Unlock()\n+ e.rcvQueueMu.Lock()\n+ e.RcvClosed = true\n+ e.rcvQueueMu.Unlock()\ne.closePendingAcceptableConnectionsLocked()\n// Notify waiters that the endpoint is shutdown.\ne.waiterQueue.Notify(waiter.ReadableEvents | waiter.WritableEvents | waiter.EventHUp | waiter.EventErr)\n@@ -2606,9 +2549,9 @@ func (e *endpoint) listen(backlog int) tcpip.Error {\n}\ne.shutdownFlags = 0\n- e.rcvQueueInfo.rcvQueueMu.Lock()\n- e.rcvQueueInfo.RcvClosed = false\n- e.rcvQueueInfo.rcvQueueMu.Unlock()\n+ e.rcvQueueMu.Lock()\n+ e.RcvClosed = false\n+ e.rcvQueueMu.Unlock()\nreturn nil\n}\n@@ -2668,9 +2611,9 @@ func (e *endpoint) Accept(peerAddr *tcpip.FullAddress) (tcpip.Endpoint, *waiter.\ne.LockUser()\ndefer e.UnlockUser()\n- e.rcvQueueInfo.rcvQueueMu.Lock()\n- rcvClosed := e.rcvQueueInfo.RcvClosed\n- e.rcvQueueInfo.rcvQueueMu.Unlock()\n+ e.rcvQueueMu.Lock()\n+ rcvClosed := e.RcvClosed\n+ e.rcvQueueMu.Unlock()\n// Endpoint must be in listen state before it can accept connections.\nif rcvClosed || e.EndpointState() != StateListen {\nreturn nil, nil, &tcpip.ErrInvalidEndpointState{}\n@@ -2949,22 +2892,24 @@ func (e *endpoint) updateSndBufferUsage(v int) {\n// readyToRead is called by the protocol goroutine when a new segment is ready\n// to be read, or when the connection is closed for receiving (in which case\n// s will be nil).\n+//\n+// +checklocks:e.mu\nfunc (e *endpoint) readyToRead(s *segment) {\n- e.rcvQueueInfo.rcvQueueMu.Lock()\n+ e.rcvQueueMu.Lock()\nif s != nil {\n- e.rcvQueueInfo.RcvBufUsed += s.payloadSize()\n+ e.RcvBufUsed += s.payloadSize()\ns.IncRef()\n- e.rcvQueueInfo.rcvQueue.PushBack(s)\n+ e.rcvQueue.PushBack(s)\n} else {\n- e.rcvQueueInfo.RcvClosed = true\n+ e.RcvClosed = true\n}\n- e.rcvQueueInfo.rcvQueueMu.Unlock()\n+ e.rcvQueueMu.Unlock()\ne.waiterQueue.Notify(waiter.ReadableEvents)\n}\n// receiveBufferAvailableLocked calculates how many bytes are still available\n// in the receive buffer.\n-// +checklocks:e.rcvQueueInfo.rcvQueueMu\n+// +checklocks:e.rcvQueueMu\nfunc (e *endpoint) receiveBufferAvailableLocked(rcvBufSize int) int {\n// We may use more bytes than the buffer size when the receive buffer\n// shrinks.\n@@ -2980,17 +2925,17 @@ func (e *endpoint) receiveBufferAvailableLocked(rcvBufSize int) int {\n// receive buffer based on the actual memory used by all segments held in\n// receive buffer/pending and segment queue.\nfunc (e *endpoint) receiveBufferAvailable() int {\n- e.rcvQueueInfo.rcvQueueMu.Lock()\n+ e.rcvQueueMu.Lock()\navailable := e.receiveBufferAvailableLocked(int(e.ops.GetReceiveBufferSize()))\n- e.rcvQueueInfo.rcvQueueMu.Unlock()\n+ e.rcvQueueMu.Unlock()\nreturn available\n}\n// receiveBufferUsed returns the amount of in-use receive buffer.\nfunc (e *endpoint) receiveBufferUsed() int {\n- e.rcvQueueInfo.rcvQueueMu.Lock()\n- used := e.rcvQueueInfo.RcvBufUsed\n- e.rcvQueueInfo.rcvQueueMu.Unlock()\n+ e.rcvQueueMu.Lock()\n+ used := e.RcvBufUsed\n+ e.rcvQueueMu.Unlock()\nreturn used\n}\n@@ -3024,9 +2969,9 @@ func (e *endpoint) maxReceiveBufferSize() int {\nfunc (e *endpoint) rcvWndScaleForHandshake() int {\nbufSizeForScale := e.ops.GetReceiveBufferSize()\n- e.rcvQueueInfo.rcvQueueMu.Lock()\n- autoTuningDisabled := e.rcvQueueInfo.RcvAutoParams.Disabled\n- e.rcvQueueInfo.rcvQueueMu.Unlock()\n+ e.rcvQueueMu.Lock()\n+ autoTuningDisabled := e.RcvAutoParams.Disabled\n+ e.rcvQueueMu.Unlock()\nif autoTuningDisabled {\nreturn FindWndScale(seqnum.Size(bufSizeForScale))\n}\n@@ -3108,9 +3053,9 @@ func (e *endpoint) completeStateLocked(s *stack.TCPEndpointState) {\ne.sndQueueInfo.sndQueueMu.Unlock()\n// Copy the receive buffer atomically.\n- e.rcvQueueInfo.rcvQueueMu.Lock()\n- s.RcvBufState = e.rcvQueueInfo.TCPRcvBufState\n- e.rcvQueueInfo.rcvQueueMu.Unlock()\n+ e.rcvQueueMu.Lock()\n+ s.RcvBufState = e.TCPRcvBufState\n+ e.rcvQueueMu.Unlock()\n// Copy the endpoint TCP Option state.\ns.SACK.Blocks = make([]header.SACKBlock, e.sack.NumBlocks)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/rcv.go",
"new_path": "pkg/tcpip/transport/tcp/rcv.go",
"diff": "@@ -153,11 +153,11 @@ func (r *receiver) getSendParams() (RcvNxt seqnum.Value, rcvWnd seqnum.Size) {\n// Keep advertising zero receive window up until the new window reaches a\n// threshold.\nif r.rcvWnd == 0 && newWnd != 0 {\n- r.ep.rcvQueueInfo.rcvQueueMu.Lock()\n+ r.ep.rcvQueueMu.Lock()\nif crossed, above := r.ep.windowCrossedACKThresholdLocked(int(newWnd), int(r.ep.ops.GetReceiveBufferSize())); !crossed && !above {\nnewWnd = 0\n}\n- r.ep.rcvQueueInfo.rcvQueueMu.Unlock()\n+ r.ep.rcvQueueMu.Unlock()\n}\n// Stash away the non-scaled receive window as we use it for measuring\n@@ -328,36 +328,36 @@ func (r *receiver) updateRTT() {\n// estimate the round-trip time by observing the time between when a byte\n// is first acknowledged and the receipt of data that is at least one\n// window beyond the sequence number that was acknowledged.\n- r.ep.rcvQueueInfo.rcvQueueMu.Lock()\n- if r.ep.rcvQueueInfo.RcvAutoParams.RTTMeasureTime == (tcpip.MonotonicTime{}) {\n+ r.ep.rcvQueueMu.Lock()\n+ if r.ep.RcvAutoParams.RTTMeasureTime == (tcpip.MonotonicTime{}) {\n// New measurement.\n- r.ep.rcvQueueInfo.RcvAutoParams.RTTMeasureTime = r.ep.stack.Clock().NowMonotonic()\n- r.ep.rcvQueueInfo.RcvAutoParams.RTTMeasureSeqNumber = r.RcvNxt.Add(r.rcvWnd)\n- r.ep.rcvQueueInfo.rcvQueueMu.Unlock()\n+ r.ep.RcvAutoParams.RTTMeasureTime = r.ep.stack.Clock().NowMonotonic()\n+ r.ep.RcvAutoParams.RTTMeasureSeqNumber = r.RcvNxt.Add(r.rcvWnd)\n+ r.ep.rcvQueueMu.Unlock()\nreturn\n}\n- if r.RcvNxt.LessThan(r.ep.rcvQueueInfo.RcvAutoParams.RTTMeasureSeqNumber) {\n- r.ep.rcvQueueInfo.rcvQueueMu.Unlock()\n+ if r.RcvNxt.LessThan(r.ep.RcvAutoParams.RTTMeasureSeqNumber) {\n+ r.ep.rcvQueueMu.Unlock()\nreturn\n}\n- rtt := r.ep.stack.Clock().NowMonotonic().Sub(r.ep.rcvQueueInfo.RcvAutoParams.RTTMeasureTime)\n+ rtt := r.ep.stack.Clock().NowMonotonic().Sub(r.ep.RcvAutoParams.RTTMeasureTime)\n// We only store the minimum observed RTT here as this is only used in\n// absence of a SRTT available from either timestamps or a sender\n// measurement of RTT.\n- if r.ep.rcvQueueInfo.RcvAutoParams.RTT == 0 || rtt < r.ep.rcvQueueInfo.RcvAutoParams.RTT {\n- r.ep.rcvQueueInfo.RcvAutoParams.RTT = rtt\n+ if r.ep.RcvAutoParams.RTT == 0 || rtt < r.ep.RcvAutoParams.RTT {\n+ r.ep.RcvAutoParams.RTT = rtt\n}\n- r.ep.rcvQueueInfo.RcvAutoParams.RTTMeasureTime = r.ep.stack.Clock().NowMonotonic()\n- r.ep.rcvQueueInfo.RcvAutoParams.RTTMeasureSeqNumber = r.RcvNxt.Add(r.rcvWnd)\n- r.ep.rcvQueueInfo.rcvQueueMu.Unlock()\n+ r.ep.RcvAutoParams.RTTMeasureTime = r.ep.stack.Clock().NowMonotonic()\n+ r.ep.RcvAutoParams.RTTMeasureSeqNumber = r.RcvNxt.Add(r.rcvWnd)\n+ r.ep.rcvQueueMu.Unlock()\n}\n// +checklocks:r.ep.mu\n// +checklocksalias:r.ep.snd.ep.mu=r.ep.mu\nfunc (r *receiver) handleRcvdSegmentClosing(s *segment, state EndpointState, closed bool) (drop bool, err tcpip.Error) {\n- r.ep.rcvQueueInfo.rcvQueueMu.Lock()\n- rcvClosed := r.ep.rcvQueueInfo.RcvClosed || r.closed\n- r.ep.rcvQueueInfo.rcvQueueMu.Unlock()\n+ r.ep.rcvQueueMu.Lock()\n+ rcvClosed := r.ep.RcvClosed || r.closed\n+ r.ep.rcvQueueMu.Unlock()\n// If we are in one of the shutdown states then we need to do\n// additional checks before we try and process the segment.\n@@ -487,9 +487,9 @@ func (r *receiver) handleRcvdSegment(s *segment) (drop bool, err tcpip.Error) {\n// segments to arrive allowing pending segments to be processed and\n// delivered to the user.\nif rcvBufSize := r.ep.ops.GetReceiveBufferSize(); rcvBufSize > 0 && (r.PendingBufUsed+int(segLen)) < int(rcvBufSize)>>2 {\n- r.ep.rcvQueueInfo.rcvQueueMu.Lock()\n+ r.ep.rcvQueueMu.Lock()\nr.PendingBufUsed += s.segMemSize()\n- r.ep.rcvQueueInfo.rcvQueueMu.Unlock()\n+ r.ep.rcvQueueMu.Unlock()\ns.IncRef()\nheap.Push(&r.pendingRcvdSegments, s)\nUpdateSACKBlocks(&r.ep.sack, segSeq, segSeq.Add(segLen), r.RcvNxt)\n@@ -523,9 +523,9 @@ func (r *receiver) handleRcvdSegment(s *segment) (drop bool, err tcpip.Error) {\n}\nheap.Pop(&r.pendingRcvdSegments)\n- r.ep.rcvQueueInfo.rcvQueueMu.Lock()\n+ r.ep.rcvQueueMu.Lock()\nr.PendingBufUsed -= s.segMemSize()\n- r.ep.rcvQueueInfo.rcvQueueMu.Unlock()\n+ r.ep.rcvQueueMu.Unlock()\ns.DecRef()\n}\nreturn false, nil\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/segment.go",
"new_path": "pkg/tcpip/transport/tcp/segment.go",
"diff": "@@ -185,6 +185,7 @@ func (s *segment) setOwner(ep *endpoint, qFlags queueFlags) {\nfunc (s *segment) DecRef() {\ns.segmentRefs.DecRef(func() {\ndefer s.pkt.DecRef()\n+ s.pkt = nil\nif s.ep != nil {\nswitch s.qFlags {\ncase recvQ:\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix racy behavior in tcp Read().
The startRead and commitRead with RcvReadMu is not safe anymore with the
change to Close() that purges the read queue.
This may reduce performance of highly concurrent reads.
PiperOrigin-RevId: 452175522 |
259,868 | 31.05.2022 18:45:22 | 25,200 | b43a19fad0e480081cbc09b618c5150ef4dcc2c1 | BuildKite pre-command: Install kernel headers if available, install `kmod`. | [
{
"change_type": "MODIFY",
"old_path": ".buildkite/hooks/pre-command",
"new_path": ".buildkite/hooks/pre-command",
"diff": "+# Download any build-specific configuration that has been uploaded.\n+# This allows top-level steps to override all subsequent steps.\n+buildkite-agent artifact download 'tools/bazeldefs/*' . || true\n+\n# Install packages we need. Docker must be installed and configured,\n# as should Go itself. We just install some extra bits and pieces.\nfunction install_pkgs() {\nexport DEBIAN_FRONTEND=noninteractive\nwhile true; do\n- if sudo -E apt-get update && \\\n- sudo -E apt-get install -y \"$@\"; then\n+ if sudo -E apt-get update && sudo -E apt-get install -y \"$@\"; then\nbreak\nfi\ndone\n}\ninstall_pkgs make linux-libc-dev graphviz jq curl binutils gnupg gnupg-agent \\\ngcc pkg-config apt-transport-https ca-certificates software-properties-common \\\n- rsync\n+ rsync kmod\n# Install headers, only if available.\nif test -n \"$(apt-cache search --names-only \"^linux-headers-$(uname -r)$\")\"; then\ninstall_pkgs \"linux-headers-$(uname -r)\"\n+elif test -n \"$(apt-cache search --names-only \"^linux-gcp-headers-$(uname -r | cut -d- -f1-2)$\")\"; then\n+ install_pkgs \"linux-gcp-headers-$(uname -r | cut -d- -f1-2)\"\nfi\n# Setup for parallelization with PARTITION and TOTAL_PARTITIONS.\n@@ -26,7 +31,8 @@ export TOTAL_PARTITIONS=${BUILDKITE_PARALLEL_JOB_COUNT:-1}\n# Ensure Docker has experimental enabled.\nEXPERIMENTAL=$(sudo docker version --format='{{.Server.Experimental}}')\nif test \"${EXPERIMENTAL}\" != \"true\"; then\n- make sudo TARGETS=//runsc:runsc ARGS=\"install --experimental=true\"\n+ make sudo TARGETS=//runsc:runsc \\\n+ ARGS=\"install --experimental=true -- ${RUNTIME_ARGS:-}\"\nsudo systemctl restart docker\nfi\n"
}
] | Go | Apache License 2.0 | google/gvisor | BuildKite pre-command: Install kernel headers if available, install `kmod`.
PiperOrigin-RevId: 452188918 |
259,868 | 31.05.2022 19:01:53 | 25,200 | a507abead7487757d30ba28d7dc61d24a6bd3419 | Run ARM64 smoke tests after AMD64, in parallel with the other tests.
This means only the AMD64 smoke tests block all other steps, which speeds up
builds as ARM64 agents are more often contended for. | [
{
"change_type": "MODIFY",
"old_path": ".buildkite/pipeline.yaml",
"new_path": ".buildkite/pipeline.yaml",
"diff": "@@ -49,13 +49,12 @@ steps:\ncommand: make smoke-tests\nagents:\narch: \"amd64\"\n+ - wait\n- <<: *common\nlabel: \":fire: Smoke tests (ARM64)\"\ncommand: make smoke-tests\nagents:\narch: \"arm64\"\n-\n- - wait\n- <<: *common\nlabel: \":fire: Smoke race tests\"\ncommand: make smoke-race-tests\n"
}
] | Go | Apache License 2.0 | google/gvisor | Run ARM64 smoke tests after AMD64, in parallel with the other tests.
This means only the AMD64 smoke tests block all other steps, which speeds up
builds as ARM64 agents are more often contended for.
PiperOrigin-RevId: 452190945 |
259,891 | 01.06.2022 13:42:04 | 25,200 | a09c49b908d41ae49d90c5c30ea6c6acea7afc37 | netstack: conntrack skips bad packets
Conntrack, like Linux, now skips bad packets entirely and lets the appropriate
layer deal with them. See net/netfilter/nf_conntrack_core.c:nf_conntrack_in.
This change shares the bad packet detection code between conntrack and TCP/UDP
so that they see the same packets as bad. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/tcp.go",
"new_path": "pkg/tcpip/header/tcp.go",
"diff": "@@ -687,3 +687,23 @@ func Acceptable(segSeq seqnum.Value, segLen seqnum.Size, rcvNxt, rcvAcc seqnum.V\n// as Linux.\nreturn rcvNxt.LessThan(segSeq.Add(segLen)) && segSeq.LessThanEq(rcvAcc)\n}\n+\n+// TCPValid returns true if the pkt has a valid TCP header. It checks whether:\n+// - The data offset is too small.\n+// - The data offset is too large.\n+// - The checksum is invalid.\n+//\n+// TCPValid corresponds to net/netfilter/nf_conntrack_proto_tcp.c:tcp_error.\n+func TCPValid(hdr TCP, payloadChecksum func() uint16, payloadSize uint16, srcAddr, dstAddr tcpip.Address, skipChecksumValidation bool) (csum uint16, csumValid, ok bool) {\n+ if offset := int(hdr.DataOffset()); offset < TCPMinimumSize || offset > len(hdr) {\n+ return\n+ }\n+\n+ if skipChecksumValidation {\n+ csumValid = true\n+ } else {\n+ csum = hdr.Checksum()\n+ csumValid = hdr.IsChecksumValid(srcAddr, dstAddr, payloadChecksum(), payloadSize)\n+ }\n+ return csum, csumValid, true\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/udp.go",
"new_path": "pkg/tcpip/header/udp.go",
"diff": "@@ -159,3 +159,36 @@ func (b UDP) UpdateChecksumPseudoHeaderAddress(old, new tcpip.Address, fullCheck\nb.SetChecksum(xsum)\n}\n+\n+// UDPValid returns true if the pkt has a valid UDP header. It checks whether:\n+// - The length field is too small.\n+// - The length field is too large.\n+// - The checksum is invalid.\n+//\n+// UDPValid corresponds to net/netfilter/nf_conntrack_proto_udp.c:udp_error.\n+func UDPValid(hdr UDP, payloadChecksum func() uint16, payloadSize uint16, netProto tcpip.NetworkProtocolNumber, srcAddr, dstAddr tcpip.Address, skipChecksumValidation bool) (lengthValid, csumValid bool) {\n+ if length := hdr.Length(); length > payloadSize+UDPMinimumSize || length < UDPMinimumSize {\n+ return false, false\n+ }\n+\n+ if skipChecksumValidation {\n+ return true, true\n+ }\n+\n+ // On IPv4, UDP checksum is optional, and a zero value means the transmitter\n+ // omitted the checksum generation, as per RFC 768:\n+ //\n+ // An all zero transmitted checksum value means that the transmitter\n+ // generated no checksum (for debugging or for higher level protocols that\n+ // don't care).\n+ //\n+ // On IPv6, UDP checksum is not optional, as per RFC 2460 Section 8.1:\n+ //\n+ // Unlike IPv4, when UDP packets are originated by an IPv6 node, the UDP\n+ // checksum is not optional.\n+ if netProto == IPv4ProtocolNumber && hdr.Checksum() == 0 {\n+ return true, true\n+ }\n+\n+ return true, hdr.IsChecksumValid(srcAddr, dstAddr, payloadChecksum())\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -511,7 +511,7 @@ func (ct *ConnTrack) init() {\n//\n// If the packet's protocol is trackable, the connection's state is updated to\n// match the contents of the packet.\n-func (ct *ConnTrack) getConnAndUpdate(pkt *PacketBuffer) *tuple {\n+func (ct *ConnTrack) getConnAndUpdate(pkt *PacketBuffer, skipChecksumValidation bool) *tuple {\n// Get or (maybe) create a connection.\nt := func() *tuple {\nvar allowNewConn bool\n@@ -527,6 +527,34 @@ func (ct *ConnTrack) getConnAndUpdate(pkt *PacketBuffer) *tuple {\npanic(fmt.Sprintf(\"unhandled %[1]T = %[1]d\", res))\n}\n+ // Just skip bad packets. They'll be rejected later by the appropriate\n+ // protocol package.\n+ switch pkt.TransportProtocolNumber {\n+ case header.TCPProtocolNumber:\n+ _, csumValid, ok := header.TCPValid(\n+ header.TCP(pkt.TransportHeader().View()),\n+ func() uint16 { return pkt.Data().AsRange().Checksum() },\n+ uint16(pkt.Data().Size()),\n+ tid.srcAddr,\n+ tid.dstAddr,\n+ pkt.RXTransportChecksumValidated || skipChecksumValidation)\n+ if !csumValid || !ok {\n+ return nil\n+ }\n+ case header.UDPProtocolNumber:\n+ lengthValid, csumValid := header.UDPValid(\n+ header.UDP(pkt.TransportHeader().View()),\n+ func() uint16 { return pkt.Data().AsRange().Checksum() },\n+ uint16(pkt.Data().Size()),\n+ pkt.NetworkProtocolNumber,\n+ tid.srcAddr,\n+ tid.dstAddr,\n+ pkt.RXTransportChecksumValidated || skipChecksumValidation)\n+ if !lengthValid || !csumValid {\n+ return nil\n+ }\n+ }\n+\nbktID := ct.bucket(tid)\nct.mu.RLock()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack_test.go",
"new_path": "pkg/tcpip/stack/conntrack_test.go",
"diff": "@@ -44,7 +44,7 @@ func TestReap(t *testing.T) {\n// the connection won't be considered established. Thus the timeout for\n// reaping is unestablishedTimeout.\npkt1 := genTCPPacket(genTCPOpts{})\n- pkt1.tuple = ct.getConnAndUpdate(pkt1)\n+ pkt1.tuple = ct.getConnAndUpdate(pkt1, true /* skipChecksumValidation */)\nif pkt1.tuple.conn.handlePacket(pkt1, Output, &rt) {\nt.Fatal(\"handlePacket() shouldn't perform any NAT\")\n}\n@@ -54,7 +54,7 @@ func TestReap(t *testing.T) {\n// lastUsed, but per #6748 didn't.\nclock.Advance(unestablishedTimeout / 2)\npkt2 := genTCPPacket(genTCPOpts{})\n- pkt2.tuple = ct.getConnAndUpdate(pkt2)\n+ pkt2.tuple = ct.getConnAndUpdate(pkt2, true /* skipChecksumValidation */)\nif pkt2.tuple.conn.handlePacket(pkt2, Output, &rt) {\nt.Fatal(\"handlePacket() shouldn't perform any NAT\")\n}\n@@ -173,7 +173,7 @@ func testWindowScaling(t *testing.T, windowSize uint16, synScale, synAckScale ui\nsrcPort: &originatorPort,\ndstPort: &responderPort,\n})\n- synPkt.tuple = ct.getConnAndUpdate(synPkt)\n+ synPkt.tuple = ct.getConnAndUpdate(synPkt, true /* skipChecksumValidation */)\nif synPkt.tuple.conn.handlePacket(synPkt, Output, &rt) {\nt.Fatal(\"handlePacket() shouldn't perform any NAT\")\n}\n@@ -205,7 +205,7 @@ func testWindowScaling(t *testing.T, windowSize uint16, synScale, synAckScale ui\nsrcPort: &responderPort,\ndstPort: &originatorPort,\n})\n- synAckPkt.tuple = ct.getConnAndUpdate(synAckPkt)\n+ synAckPkt.tuple = ct.getConnAndUpdate(synAckPkt, true /* skipChecksumValidation */)\nif synAckPkt.tuple.conn.handlePacket(synAckPkt, Prerouting, &rt) {\nt.Fatal(\"handlePacket() shouldn't perform any NAT\")\n}\n@@ -236,7 +236,7 @@ func testWindowScaling(t *testing.T, windowSize uint16, synScale, synAckScale ui\nsrcPort: &originatorPort,\ndstPort: &responderPort,\n})\n- ackPkt.tuple = ct.getConnAndUpdate(ackPkt)\n+ ackPkt.tuple = ct.getConnAndUpdate(ackPkt, true /* skipChecksumValidation */)\nif ackPkt.tuple.conn.handlePacket(ackPkt, Output, &rt) {\nt.Fatal(\"handlePacket() shouldn't perform any NAT\")\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables.go",
"new_path": "pkg/tcpip/stack/iptables.go",
"diff": "@@ -332,7 +332,7 @@ func (it *IPTables) CheckPrerouting(pkt *PacketBuffer, addressEP AddressableEndp\nreturn true\n}\n- pkt.tuple = it.connections.getConnAndUpdate(pkt)\n+ pkt.tuple = it.connections.getConnAndUpdate(pkt, false /* skipChecksumValidation */)\nfor _, table := range tables {\nif !table.fn(it, table.table, Prerouting, pkt, nil /* route */, addressEP, inNicName, \"\" /* outNicName */) {\n@@ -446,7 +446,9 @@ func (it *IPTables) CheckOutput(pkt *PacketBuffer, r *Route, outNicName string)\nreturn true\n}\n- pkt.tuple = it.connections.getConnAndUpdate(pkt)\n+ // We don't need to validate the checksum in the Output path: we can assume\n+ // we calculate it correctly, plus checksumming may be deferred due to GSO.\n+ pkt.tuple = it.connections.getConnAndUpdate(pkt, true /* skipChecksumValidation */)\nfor _, table := range tables {\nif !table.fn(it, table.table, Output, pkt, r, nil /* addressEP */, \"\" /* inNicName */, outNicName) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables_test.go",
"new_path": "pkg/tcpip/stack/iptables_test.go",
"diff": "@@ -48,6 +48,7 @@ func v6PacketBufferWithSrcAddr(srcAddr tcpip.Address) *PacketBuffer {\nudp := header.UDP(pkt.TransportHeader().Push(header.UDPMinimumSize))\nudp.SetSourcePort(srcPort)\nudp.SetDestinationPort(dstPort)\n+ udp.SetLength(uint16(len(udp)))\nudp.SetChecksum(0)\nudp.SetChecksum(^udp.CalculateChecksum(header.PseudoHeaderChecksum(\nheader.UDPProtocolNumber,\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/integration/iptables_test.go",
"new_path": "pkg/tcpip/tests/integration/iptables_test.go",
"diff": "@@ -70,6 +70,7 @@ func genStackV6(t *testing.T) (*stack.Stack, *channel.Endpoint) {\nt.Helper()\ns := stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocolFactory{ipv6.NewProtocol},\n+ TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol, udp.NewProtocol},\n})\ne := channel.New(0, header.IPv6MinimumMTU, linkAddr)\nnicOpts := stack.NICOptions{Name: nicName}\n@@ -90,6 +91,7 @@ func genStackV4(t *testing.T) (*stack.Stack, *channel.Endpoint) {\nt.Helper()\ns := stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol},\n+ TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol, udp.NewProtocol},\n})\ne := channel.New(0, header.IPv4MinimumMTU, linkAddr)\nnicOpts := stack.NICOptions{Name: nicName}\n@@ -2036,6 +2038,7 @@ func udpv4Packet(srcAddr, dstAddr tcpip.Address, srcPort, dstPort uint16, dataSi\nudp := header.UDP(hdr.Prepend(udpSize))\nudp.SetSourcePort(srcPort)\nudp.SetDestinationPort(dstPort)\n+ udp.SetLength(uint16(udpSize))\nudp.SetChecksum(0)\nudp.SetChecksum(^udp.CalculateChecksum(header.PseudoHeaderChecksum(\nheader.UDPProtocolNumber,\n@@ -2100,6 +2103,7 @@ func udpv6Packet(srcAddr, dstAddr tcpip.Address, srcPort, dstPort uint16, dataSi\nudp := header.UDP(hdr.Prepend(udpSize))\nudp.SetSourcePort(srcPort)\nudp.SetDestinationPort(dstPort)\n+ udp.SetLength(uint16(udpSize))\nudp.SetChecksum(0)\nudp.SetChecksum(^udp.CalculateChecksum(header.PseudoHeaderChecksum(\nheader.UDPProtocolNumber,\n@@ -3304,3 +3308,191 @@ func TestRejectWith(t *testing.T) {\n})\n}\n}\n+\n+// TestInvalidTransportHeader tests that bad transport headers (with a bad\n+// length/offset field) don't panic.\n+func TestInvalidTransportHeader(t *testing.T) {\n+ tests := []struct {\n+ name string\n+ setupStack func(*testing.T) (*stack.Stack, *channel.Endpoint)\n+ genPacket func(int8) *stack.PacketBuffer\n+ offset int8\n+ }{\n+ {\n+ name: \"TCP4 offset small\",\n+ setupStack: genStackV4,\n+ genPacket: genTCP4,\n+ offset: -1,\n+ },\n+ {\n+ name: \"TCP4 offset large\",\n+ setupStack: genStackV4,\n+ genPacket: genTCP4,\n+ offset: 1,\n+ },\n+ {\n+ name: \"UDP4 offset small\",\n+ setupStack: genStackV4,\n+ genPacket: genUDP4,\n+ offset: -1,\n+ },\n+ {\n+ name: \"UDP4 offset large\",\n+ setupStack: genStackV4,\n+ genPacket: genUDP4,\n+ offset: 1,\n+ },\n+ {\n+ name: \"TCP6 offset small\",\n+ setupStack: genStackV6,\n+ genPacket: genTCP6,\n+ offset: -1,\n+ },\n+ {\n+ name: \"TCP6 offset large\",\n+ setupStack: genStackV6,\n+ genPacket: genTCP6,\n+ offset: 1,\n+ },\n+ {\n+ name: \"UDP6 offset small\",\n+ setupStack: genStackV6,\n+ genPacket: genUDP6,\n+ offset: -1,\n+ },\n+ {\n+ name: \"UDP6 offset large\",\n+ setupStack: genStackV6,\n+ genPacket: genUDP6,\n+ offset: 1,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ s, e := test.setupStack(t)\n+\n+ // Enable iptables and conntrack.\n+ ipt := s.IPTables()\n+ filter := ipt.GetTable(stack.FilterID, false /* ipv6 */)\n+ ipt.ReplaceTable(stack.FilterID, filter, false /* ipv6 */)\n+\n+ // This can panic if conntrack isn't checking lengths.\n+ e.InjectInbound(header.IPv4ProtocolNumber, test.genPacket(test.offset))\n+ })\n+ }\n+}\n+\n+func genTCP4(offset int8) *stack.PacketBuffer {\n+ pktSize := header.IPv4MinimumSize + header.TCPMinimumSize\n+ hdr := prependable.New(pktSize)\n+\n+ tcp := header.TCP(hdr.Prepend(header.TCPMinimumSize))\n+ tcp.Encode(&header.TCPFields{\n+ SeqNum: 0,\n+ AckNum: 0,\n+ DataOffset: header.TCPMinimumSize + uint8(offset)*4, // DataOffset must be a multiple of 4.\n+ Flags: header.TCPFlagSyn,\n+ Checksum: 0,\n+ })\n+\n+ ip := header.IPv4(hdr.Prepend(header.IPv4MinimumSize))\n+ ip.Encode(&header.IPv4Fields{\n+ TOS: 0,\n+ TotalLength: uint16(pktSize),\n+ ID: 1,\n+ Flags: 0,\n+ FragmentOffset: 0,\n+ TTL: 48,\n+ Protocol: uint8(header.TCPProtocolNumber),\n+ SrcAddr: srcAddrV4,\n+ DstAddr: dstAddrV4,\n+ })\n+ ip.SetChecksum(0)\n+ ip.SetChecksum(^ip.CalculateChecksum())\n+\n+ vv := buffer.NewViewFromBytes(hdr.View()).ToVectorisedView()\n+ return stack.NewPacketBuffer(stack.PacketBufferOptions{Data: vv})\n+}\n+\n+func genTCP6(offset int8) *stack.PacketBuffer {\n+ pktSize := header.IPv6MinimumSize + header.TCPMinimumSize\n+ hdr := prependable.New(pktSize)\n+\n+ tcp := header.TCP(hdr.Prepend(header.TCPMinimumSize))\n+ tcp.Encode(&header.TCPFields{\n+ SeqNum: 0,\n+ AckNum: 0,\n+ DataOffset: header.TCPMinimumSize + uint8(offset)*4, // DataOffset must be a multiple of 4.\n+ Flags: header.TCPFlagSyn,\n+ Checksum: 0,\n+ })\n+\n+ ip := header.IPv6(hdr.Prepend(header.IPv6MinimumSize))\n+ ip.Encode(&header.IPv6Fields{\n+ PayloadLength: header.TCPMinimumSize,\n+ TransportProtocol: header.TCPProtocolNumber,\n+ HopLimit: 255,\n+ SrcAddr: srcAddrV6,\n+ DstAddr: dstAddrV6,\n+ })\n+\n+ vv := buffer.NewViewFromBytes(hdr.View()).ToVectorisedView()\n+ return stack.NewPacketBuffer(stack.PacketBufferOptions{Data: vv})\n+}\n+\n+func genUDP4(offset int8) *stack.PacketBuffer {\n+ pktSize := header.IPv4MinimumSize + header.UDPMinimumSize\n+ hdr := prependable.New(pktSize)\n+\n+ udp := header.UDP(hdr.Prepend(header.UDPMinimumSize))\n+ udp.Encode(&header.UDPFields{\n+ SrcPort: 343,\n+ DstPort: 2401,\n+ Length: header.UDPMinimumSize + uint16(offset),\n+ Checksum: 0,\n+ })\n+\n+ ip := header.IPv4(hdr.Prepend(header.IPv4MinimumSize))\n+ ip.Encode(&header.IPv4Fields{\n+ TOS: 0,\n+ TotalLength: uint16(pktSize),\n+ ID: 1,\n+ Flags: 0,\n+ FragmentOffset: 0,\n+ TTL: 48,\n+ Protocol: uint8(header.UDPProtocolNumber),\n+ SrcAddr: srcAddrV4,\n+ DstAddr: dstAddrV4,\n+ })\n+ ip.SetChecksum(0)\n+ ip.SetChecksum(^ip.CalculateChecksum())\n+\n+ vv := buffer.NewViewFromBytes(hdr.View()).ToVectorisedView()\n+ return stack.NewPacketBuffer(stack.PacketBufferOptions{Data: vv})\n+}\n+\n+func genUDP6(offset int8) *stack.PacketBuffer {\n+ pktSize := header.IPv6MinimumSize + header.UDPMinimumSize\n+ hdr := prependable.New(pktSize)\n+\n+ udp := header.UDP(hdr.Prepend(header.UDPMinimumSize))\n+ udp.Encode(&header.UDPFields{\n+ SrcPort: 343,\n+ DstPort: 2401,\n+ Length: header.UDPMinimumSize + uint16(offset),\n+ Checksum: 0,\n+ })\n+\n+ ip := header.IPv6(hdr.Prepend(header.IPv6MinimumSize))\n+ ip.Encode(&header.IPv6Fields{\n+ PayloadLength: header.UDPMinimumSize,\n+ TransportProtocol: header.UDPProtocolNumber,\n+ HopLimit: 255,\n+ SrcAddr: srcAddrV6,\n+ DstAddr: dstAddrV6,\n+ })\n+\n+ vv := buffer.NewViewFromBytes(hdr.View()).ToVectorisedView()\n+ return stack.NewPacketBuffer(stack.PacketBufferOptions{Data: vv})\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/integration/link_resolution_test.go",
"new_path": "pkg/tcpip/tests/integration/link_resolution_test.go",
"diff": "@@ -956,7 +956,7 @@ func TestWritePacketsLinkResolution(t *testing.T) {\nData: buffer.View([]byte{d}).ToVectorisedView(),\n})\npkt.TransportProtocolNumber = udp.ProtocolNumber\n- length := uint16(pkt.Size())\n+ length := uint16(pkt.Data().Size() + header.UDPMinimumSize)\nudpHdr := header.UDP(pkt.TransportHeader().Push(header.UDPMinimumSize))\nudpHdr.Encode(&header.UDPFields{\nSrcPort: 5555,\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/segment.go",
"new_path": "pkg/tcpip/transport/tcp/segment.go",
"diff": "@@ -85,18 +85,17 @@ type segment struct {\n}\nfunc newIncomingSegment(id stack.TransportEndpointID, clock tcpip.Clock, pkt *stack.PacketBuffer) (*segment, error) {\n- // We check that the offset to the data respects the following constraints:\n- // 1. That it's at least the minimum header size; if we don't do this\n- // then part of the header would be delivered to user.\n- // 2. That the header fits within the buffer; if we don't do this, we\n- // would panic when we tried to access data beyond the buffer.\n- if pkt.TransportHeader().View().Size() < header.TCPMinimumSize {\n- return nil, fmt.Errorf(\"packet header smaller than minimum TCP header size: minimum size = %d, got size=%d\", header.TCPMinimumSize, pkt.TransportHeader().View().Size())\n- }\nhdr := header.TCP(pkt.TransportHeader().View())\n- offset := int(hdr.DataOffset())\n- if offset < header.TCPMinimumSize || offset > len(hdr) {\n- return nil, fmt.Errorf(\"header data offset does not respect size constraints: %d < offset < %d, got offset=%d\", header.TCPMinimumSize, len(hdr), offset)\n+ netHdr := pkt.Network()\n+ csum, csumValid, ok := header.TCPValid(\n+ hdr,\n+ func() uint16 { return pkt.Data().AsRange().Checksum() },\n+ uint16(pkt.Data().Size()),\n+ netHdr.SourceAddress(),\n+ netHdr.DestinationAddress(),\n+ pkt.RXTransportChecksumValidated)\n+ if !ok {\n+ return nil, fmt.Errorf(\"header data offset does not respect size constraints: %d < offset < %d, got offset=%d\", header.TCPMinimumSize, len(hdr), hdr.DataOffset())\n}\ns := &segment{\n@@ -110,18 +109,13 @@ func newIncomingSegment(id stack.TransportEndpointID, clock tcpip.Clock, pkt *st\nrcvdTime: clock.NowMonotonic(),\ndataMemSize: pkt.MemSize(),\npkt: pkt,\n+ csumValid: csumValid,\n}\npkt.IncRef()\ns.InitRefs()\n- if s.pkt.RXTransportChecksumValidated {\n- s.csumValid = true\n- } else {\n- s.csum = hdr.Checksum()\n- payloadChecksum := s.pkt.Data().AsRange().Checksum()\n- payloadLength := uint16(s.payloadSize())\n- net := s.pkt.Network()\n- s.csumValid = hdr.IsChecksumValid(net.SourceAddress(), net.DestinationAddress(), payloadChecksum, payloadLength)\n+ if !s.pkt.RXTransportChecksumValidated {\n+ s.csum = csum\n}\nreturn s, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -886,45 +886,28 @@ func (e *endpoint) Readiness(mask waiter.EventMask) waiter.EventMask {\nreturn result\n}\n-// verifyChecksum verifies the checksum unless RX checksum offload is enabled.\n-func verifyChecksum(hdr header.UDP, pkt *stack.PacketBuffer) bool {\n- if pkt.RXTransportChecksumValidated {\n- return true\n- }\n-\n- // On IPv4, UDP checksum is optional, and a zero value means the transmitter\n- // omitted the checksum generation, as per RFC 768:\n- //\n- // An all zero transmitted checksum value means that the transmitter\n- // generated no checksum (for debugging or for higher level protocols that\n- // don't care).\n- //\n- // On IPv6, UDP checksum is not optional, as per RFC 2460 Section 8.1:\n- //\n- // Unlike IPv4, when UDP packets are originated by an IPv6 node, the UDP\n- // checksum is not optional.\n- if pkt.NetworkProtocolNumber == header.IPv4ProtocolNumber && hdr.Checksum() == 0 {\n- return true\n- }\n-\n- netHdr := pkt.Network()\n- payloadChecksum := pkt.Data().AsRange().Checksum()\n- return hdr.IsChecksumValid(netHdr.SourceAddress(), netHdr.DestinationAddress(), payloadChecksum)\n-}\n-\n// HandlePacket is called by the stack when new packets arrive to this transport\n// endpoint.\nfunc (e *endpoint) HandlePacket(id stack.TransportEndpointID, pkt *stack.PacketBuffer) {\n// Get the header then trim it from the view.\nhdr := header.UDP(pkt.TransportHeader().View())\n- if int(hdr.Length()) > pkt.Data().Size()+header.UDPMinimumSize {\n+ netHdr := pkt.Network()\n+ lengthValid, csumValid := header.UDPValid(\n+ hdr,\n+ func() uint16 { return pkt.Data().AsRange().Checksum() },\n+ uint16(pkt.Data().Size()),\n+ pkt.NetworkProtocolNumber,\n+ netHdr.SourceAddress(),\n+ netHdr.DestinationAddress(),\n+ pkt.RXTransportChecksumValidated)\n+ if !lengthValid {\n// Malformed packet.\ne.stack.Stats().UDP.MalformedPacketsReceived.Increment()\ne.stats.ReceiveErrors.MalformedPacketsReceived.Increment()\nreturn\n}\n- if !verifyChecksum(hdr, pkt) {\n+ if !csumValid {\ne.stack.Stats().UDP.ChecksumErrors.Increment()\ne.stats.ReceiveErrors.ChecksumErrors.Increment()\nreturn\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/protocol.go",
"new_path": "pkg/tcpip/transport/udp/protocol.go",
"diff": "@@ -80,12 +80,21 @@ func (*protocol) ParsePorts(v buffer.View) (src, dst uint16, err tcpip.Error) {\n// protocol but don't match any existing endpoint.\nfunc (p *protocol) HandleUnknownDestinationPacket(id stack.TransportEndpointID, pkt *stack.PacketBuffer) stack.UnknownDestinationPacketDisposition {\nhdr := header.UDP(pkt.TransportHeader().View())\n- if int(hdr.Length()) > pkt.Data().Size()+header.UDPMinimumSize {\n+ netHdr := pkt.Network()\n+ lengthValid, csumValid := header.UDPValid(\n+ hdr,\n+ func() uint16 { return pkt.Data().AsRange().Checksum() },\n+ uint16(pkt.Data().Size()),\n+ pkt.NetworkProtocolNumber,\n+ netHdr.SourceAddress(),\n+ netHdr.DestinationAddress(),\n+ pkt.RXTransportChecksumValidated)\n+ if !lengthValid {\np.stack.Stats().UDP.MalformedPacketsReceived.Increment()\nreturn stack.UnknownDestinationPacketMalformed\n}\n- if !verifyChecksum(hdr, pkt) {\n+ if !csumValid {\np.stack.Stats().UDP.ChecksumErrors.Increment()\nreturn stack.UnknownDestinationPacketMalformed\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | netstack: conntrack skips bad packets
Conntrack, like Linux, now skips bad packets entirely and lets the appropriate
layer deal with them. See net/netfilter/nf_conntrack_core.c:nf_conntrack_in.
This change shares the bad packet detection code between conntrack and TCP/UDP
so that they see the same packets as bad.
PiperOrigin-RevId: 452374626 |
259,975 | 01.06.2022 16:25:50 | 25,200 | 9b751b88ed507d4efd1e89ed72cdc857f7d709b1 | [bugs] Refactor seccomp test. | [
{
"change_type": "MODIFY",
"old_path": "pkg/seccomp/seccomp_test.go",
"new_path": "pkg/seccomp/seccomp_test.go",
"diff": "@@ -965,44 +965,49 @@ func TestRandom(t *testing.T) {\n// that it doesn't die when the filter is not triggered.\nfunc TestRealDeal(t *testing.T) {\nfor _, test := range []struct {\n+ name string\ndie bool\nwant string\n}{\n- {die: true, want: \"bad system call\"},\n- {die: false, want: \"Syscall was allowed!!!\"},\n+ {name: \"bad syscall\", die: true, want: \"bad system call\"},\n+ {name: \"allowed syscall\", die: false, want: \"Syscall was allowed!!!\"},\n} {\n+ t.Run(test.name, func(t *testing.T) {\nvictim, err := newVictim()\nif err != nil {\nt.Fatalf(\"unable to get victim: %v\", err)\n}\n- defer os.Remove(victim)\n+ defer func() {\n+ if err := os.Remove(victim); err != nil {\n+ t.Fatalf(\"Unable to remove victim: %v\", err)\n+ }\n+ }()\n+\ndieFlag := fmt.Sprintf(\"-die=%v\", test.die)\ncmd := exec.Command(victim, dieFlag)\n-\nout, err := cmd.CombinedOutput()\nif test.die {\nif err == nil {\n- t.Errorf(\"victim was not killed as expected, output: %s\", out)\n- continue\n+ t.Fatalf(\"Victim was not killed as expected, output: %s\", out)\n}\n// Depending on kernel version, either RET_TRAP or RET_KILL_PROCESS is\n// used. RET_TRAP dumps reason for exit in output, while RET_KILL_PROCESS\n// returns SIGSYS as exit status.\nif !strings.Contains(string(out), test.want) &&\n!strings.Contains(err.Error(), test.want) {\n- t.Errorf(\"Victim error is wrong, got: %v, err: %v, want: %v\", string(out), err, test.want)\n- continue\n+ t.Fatalf(\"Victim error is wrong, got: %v, err: %v, want: %v\", string(out), err, test.want)\n+ }\n+ return\n}\n- } else {\n+ // test.die is false\nif err != nil {\n- t.Errorf(\"victim failed to execute, err: %v\", err)\n- continue\n+ t.Logf(\"out: %s\", string(out))\n+ t.Fatalf(\"Victim failed to execute, err: %v\", err)\n}\nif !strings.Contains(string(out), test.want) {\n- t.Errorf(\"Victim output is wrong, got: %v, want: %v\", string(out), test.want)\n- continue\n- }\n+ t.Fatalf(\"Victim output is wrong, got: %v, want: %v\", string(out), test.want)\n}\n+ })\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/seccomp/seccomp_test_victim.go",
"new_path": "pkg/seccomp/seccomp_test_victim.go",
"diff": "@@ -96,11 +96,11 @@ func main() {\n}\narch_syscalls(syscalls)\n-\n// We choose a syscall that is unlikely to be called by Go runtime,\n// even with race or other instrumentation enabled.\nsyscall := uintptr(unix.SYS_AFS_SYSCALL)\n- syscallArg := uintptr(10)\n+ // This test goes up to 11.\n+ syscallArg := uintptr(11)\ndie := *dieFlag\nif !die {\n@@ -112,11 +112,14 @@ func main() {\n}\nif err := seccomp.Install(syscalls, nil); err != nil {\n- fmt.Printf(\"Failed to install seccomp: %v\", err)\n+ fmt.Printf(\"Failed to install seccomp: %v\\n\", err)\nos.Exit(1)\n}\nfmt.Printf(\"Filters installed\\n\")\n- unix.RawSyscall(syscall, syscallArg, 0, 0)\n+ if _, _, err := unix.RawSyscall(syscall, syscallArg, 0, 0); err != unix.Errno(0) {\n+ fmt.Printf(\"syscall error: %v\\n\", err)\n+ }\n+\nfmt.Printf(\"Syscall was allowed!!!\\n\")\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | [bugs] Refactor seccomp test.
PiperOrigin-RevId: 452409930 |
259,992 | 03.06.2022 09:50:14 | 25,200 | 0968254ce715c0d8e6457558d55cb405a545ad2f | Speed up container_test
TestExePath doesn't need to run on all platforms, but it does need
to run with overlay enabled (it was doing the opposite).
TestExecProcList doesn't need to wait for `sleep 5` to finish
executing. Exec success is tested in TestExec and many other tests
already. | [
{
"change_type": "MODIFY",
"old_path": "runsc/container/container_test.go",
"new_path": "runsc/container/container_test.go",
"diff": "@@ -394,8 +394,6 @@ func run(spec *specs.Spec, conf *config.Config) error {\nvar platforms = flag.String(\"test_platforms\", os.Getenv(\"TEST_PLATFORMS\"), \"Platforms to test with.\")\n// configs generates different configurations to run tests.\n-//\n-// TODO(gvisor.dev/issue/1624): Remove VFS1 dimension.\nfunc configs(t *testing.T, noOverlay bool) map[string]*config.Config {\nvar ps []string\nif *platforms == \"\" {\n@@ -612,7 +610,13 @@ func TestExePath(t *testing.T) {\nt.Fatalf(\"error making directory: %v\", err)\n}\n- for name, conf := range configs(t, false /* noOverlay */) {\n+ configs := map[string]*config.Config{\n+ \"default\": testutil.TestConfig(t),\n+ \"overlay\": testutil.TestConfig(t),\n+ }\n+ configs[\"overlay\"].Overlay = true\n+\n+ for name, conf := range configs {\nt.Run(name, func(t *testing.T) {\nfor _, test := range []struct {\npath string\n@@ -637,38 +641,21 @@ func TestExePath(t *testing.T) {\n{path: filepath.Join(firstPath, \"masked2\"), success: false},\n{path: filepath.Join(secondPath, \"masked2\"), success: true},\n} {\n- t.Run(fmt.Sprintf(\"path=%s,success=%t\", test.path, test.success), func(t *testing.T) {\n+ name := fmt.Sprintf(\"path=%s,success=%t\", test.path, test.success)\n+ t.Run(name, func(t *testing.T) {\nspec := testutil.NewSpecWithArgs(test.path)\nspec.Process.Env = []string{\nfmt.Sprintf(\"PATH=%s:%s:%s\", firstPath, secondPath, os.Getenv(\"PATH\")),\n}\n- _, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)\n- if err != nil {\n- t.Fatalf(\"exec: error setting up container: %v\", err)\n- }\n- defer cleanup()\n-\n- args := Args{\n- ID: testutil.RandomContainerID(),\n- Spec: spec,\n- BundleDir: bundleDir,\n- Attached: true,\n- }\n- ws, err := Run(conf, args)\n-\n+ err := run(spec, conf)\nif test.success {\nif err != nil {\nt.Errorf(\"exec: error running container: %v\", err)\n}\n- if ws.ExitStatus() != 0 {\n- t.Errorf(\"exec: got exit status %v want %v\", ws.ExitStatus(), 0)\n- }\n- } else {\n- if err == nil {\n+ } else if err == nil {\nt.Errorf(\"exec: got: no error, want: error\")\n}\n- }\n})\n}\n})\n@@ -933,16 +920,6 @@ func TestExecProcList(t *testing.T) {\nif err := waitForProcessList(cont, expectedPL); err != nil {\nt.Fatalf(\"error waiting for processes: %v\", err)\n}\n-\n- // Ensure that exec finished without error.\n- select {\n- case <-time.After(10 * time.Second):\n- t.Fatalf(\"container timed out waiting for exec to finish.\")\n- case err := <-ch:\n- if err != nil {\n- t.Errorf(\"container failed to exec %v: %v\", args, err)\n- }\n- }\n})\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Speed up container_test
TestExePath doesn't need to run on all platforms, but it does need
to run with overlay enabled (it was doing the opposite).
TestExecProcList doesn't need to wait for `sleep 5` to finish
executing. Exec success is tested in TestExec and many other tests
already.
PiperOrigin-RevId: 452785343 |
259,992 | 03.06.2022 11:53:41 | 25,200 | d25fe0538ace4a188b4872508149127219c26e83 | Drain all messages before closing socket
Updates | [
{
"change_type": "MODIFY",
"old_path": "examples/seccheck/server.cc",
"new_path": "examples/seccheck/server.cc",
"diff": "@@ -123,6 +123,19 @@ void unpack(absl::string_view buf) {\ncb(proto);\n}\n+bool readAndUnpack(int client) {\n+ std::array<char, maxEventSize> buf;\n+ int bytes = read(client, buf.data(), buf.size());\n+ if (bytes < 0) {\n+ err(1, \"read\");\n+ }\n+ if (bytes == 0) {\n+ return false;\n+ }\n+ unpack(absl::string_view(buf.data(), bytes));\n+ return true;\n+}\n+\nvoid* pollLoop(void* ptr) {\nconst int poll_fd = *reinterpret_cast<int*>(&ptr);\nfor (;;) {\n@@ -138,16 +151,13 @@ void* pollLoop(void* ptr) {\nfor (int i = 0; i < nfds; ++i) {\nif (evts[i].events & EPOLLIN) {\nint client = evts[i].data.fd;\n- std::array<char, maxEventSize> buf;\n- int bytes = read(client, buf.data(), buf.size());\n- if (bytes < 0) {\n- err(1, \"read\");\n- } else if (bytes > 0) {\n- unpack(absl::string_view(buf.data(), bytes));\n- }\n+ readAndUnpack(client);\n}\nif ((evts[i].events & (EPOLLRDHUP | EPOLLHUP)) != 0) {\nint client = evts[i].data.fd;\n+ // Drain any remaining messages before closing the socket.\n+ while (readAndUnpack(client)) {\n+ }\nclose(client);\nprintf(\"Connection closed\\n\");\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Drain all messages before closing socket
Updates #4805
PiperOrigin-RevId: 452812458 |
259,853 | 03.06.2022 13:00:02 | 25,200 | aaaa3429f7851a35e5db8f367eedbd53f8df082d | fs: use lockdep mutexes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/BUILD",
"new_path": "pkg/sentry/fs/BUILD",
"diff": "load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\nload(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\n+load(\"//pkg/sync/locking:locking.bzl\", \"declare_mutex\")\npackage(licenses = [\"notice\"])\n@@ -29,11 +30,14 @@ go_library(\n\"inode_overlay.go\",\n\"inotify.go\",\n\"inotify_event.go\",\n+ \"inotify_event_mutex.go\",\n+ \"inotify_mutex.go\",\n\"inotify_watch.go\",\n\"mock.go\",\n\"mount.go\",\n\"mount_overlay.go\",\n\"mounts.go\",\n+ \"namespace_mutex.go\",\n\"offset.go\",\n\"overlay.go\",\n\"path.go\",\n@@ -68,6 +72,7 @@ go_library(\n\"//pkg/sentry/usage\",\n\"//pkg/state\",\n\"//pkg/sync\",\n+ \"//pkg/sync/locking\",\n\"//pkg/usermem\",\n\"//pkg/waiter\",\n\"@org_golang_x_sys//unix:go_default_library\",\n@@ -98,6 +103,27 @@ go_template_instance(\n},\n)\n+declare_mutex(\n+ name = \"namespace_mutex\",\n+ out = \"namespace_mutex.go\",\n+ package = \"fs\",\n+ prefix = \"namespace\",\n+)\n+\n+declare_mutex(\n+ name = \"inotify_event_mutex\",\n+ out = \"inotify_event_mutex.go\",\n+ package = \"fs\",\n+ prefix = \"inotifyEvent\",\n+)\n+\n+declare_mutex(\n+ name = \"inotify_mutex\",\n+ out = \"inotify_mutex.go\",\n+ package = \"fs\",\n+ prefix = \"inotify\",\n+)\n+\ngo_test(\nname = \"fs_x_test\",\nsize = \"small\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/inotify.go",
"new_path": "pkg/sentry/fs/inotify.go",
"diff": "@@ -25,7 +25,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/memmap\"\n\"gvisor.dev/gvisor/pkg/sentry/uniqueid\"\n- \"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n@@ -50,7 +49,7 @@ type Inotify struct {\n// while queuing events, a watch needs to lock the event queue, and using mu\n// for that would violate lock ordering since at that point the calling\n// goroutine already holds Watch.target.Watches.mu.\n- evMu sync.Mutex `state:\"nosave\"`\n+ evMu inotifyEventMutex `state:\"nosave\"`\n// A list of pending events for this inotify instance. Protected by evMu.\nevents eventList\n@@ -60,7 +59,7 @@ type Inotify struct {\nscratch []byte\n// mu protects the fields below.\n- mu sync.Mutex `state:\"nosave\"`\n+ mu inotifyMutex `state:\"nosave\"`\n// The next watch descriptor number to use for this inotify instance. Note\n// that Linux starts numbering watch descriptors from 1.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/mounts.go",
"new_path": "pkg/sentry/fs/mounts.go",
"diff": "@@ -23,7 +23,6 @@ import (\n\"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n\"gvisor.dev/gvisor/pkg/refs\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n- \"gvisor.dev/gvisor/pkg/sync\"\n)\n// DefaultTraversalLimit provides a sensible default traversal limit that may\n@@ -151,7 +150,7 @@ type MountNamespace struct {\nroot *Dirent\n// mu protects mounts and mountID counter.\n- mu sync.Mutex `state:\"nosave\"`\n+ mu namespaceMutex `state:\"nosave\"`\n// mounts is a map of mounted Dirent -> Mount object. There are three\n// possible cases:\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/BUILD",
"new_path": "pkg/sentry/fsimpl/cgroupfs/BUILD",
"diff": "load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\nload(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\n+load(\"//pkg/sync/locking:locking.bzl\", \"declare_mutex\", \"declare_rwmutex\")\nlicenses([\"notice\"])\n+declare_mutex(\n+ name = \"pids_controller_mutex\",\n+ out = \"pids_controller_mutex.go\",\n+ package = \"cgroupfs\",\n+ prefix = \"pidsController\",\n+)\n+\n+declare_rwmutex(\n+ name = \"task_mutex\",\n+ out = \"task_mutex.go\",\n+ package = \"cgroupfs\",\n+ prefix = \"task\",\n+)\n+\ngo_template_instance(\nname = \"dir_refs\",\nout = \"dir_refs.go\",\n@@ -27,6 +42,8 @@ go_library(\n\"job.go\",\n\"memory.go\",\n\"pids.go\",\n+ \"pids_controller_mutex.go\",\n+ \"task_mutex.go\",\n],\nvisibility = [\"//pkg/sentry:internal\"],\ndeps = [\n@@ -49,6 +66,7 @@ go_library(\n\"//pkg/sentry/usage\",\n\"//pkg/sentry/vfs\",\n\"//pkg/sync\",\n+ \"//pkg/sync/locking\",\n\"//pkg/usermem\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/cgroupfs.go",
"new_path": "pkg/sentry/fsimpl/cgroupfs/cgroupfs.go",
"diff": "@@ -72,7 +72,6 @@ import (\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/sync\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n@@ -173,7 +172,7 @@ type filesystem struct {\n// tasksMu serializes task membership changes across all cgroups within a\n// filesystem.\n- tasksMu sync.RWMutex `state:\"nosave\"`\n+ tasksMu taskRWMutex `state:\"nosave\"`\n}\n// InitializeHierarchyID implements kernel.cgroupFS.InitializeHierarchyID.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/pids.go",
"new_path": "pkg/sentry/fsimpl/cgroupfs/pids.go",
"diff": "@@ -27,7 +27,6 @@ import (\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/sync\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n@@ -61,7 +60,7 @@ type pidsController struct {\nisRoot bool\n// mu protects the fields below.\n- mu sync.Mutex `state:\"nosave\"`\n+ mu pidsControllerMutex `state:\"nosave\"`\n// pendingTotal and pendingPool tracks the charge for processes starting\n// up. During startup, we check if PIDs are available by charging the\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/BUILD",
"new_path": "pkg/sentry/fsimpl/kernfs/BUILD",
"diff": "load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\nload(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\n+load(\"//pkg/sync/locking:locking.bzl\", \"declare_mutex\", \"declare_rwmutex\")\nlicenses([\"notice\"])\n@@ -82,13 +83,29 @@ go_template_instance(\n},\n)\n+declare_rwmutex(\n+ name = \"filesystem_mutex\",\n+ out = \"filesystem_mutex.go\",\n+ package = \"kernfs\",\n+ prefix = \"filesystem\",\n+)\n+\n+declare_mutex(\n+ name = \"deferred_dec_refs_mutex\",\n+ out = \"deferred_dec_refs_mutex.go\",\n+ package = \"kernfs\",\n+ prefix = \"deferredDecRefs\",\n+)\n+\ngo_library(\nname = \"kernfs\",\nsrcs = [\n+ \"deferred_dec_refs_mutex.go\",\n\"dentry_list.go\",\n\"dynamic_bytes_file.go\",\n\"fd_impl_util.go\",\n\"filesystem.go\",\n+ \"filesystem_mutex.go\",\n\"fstree.go\",\n\"inode_impl_util.go\",\n\"kernfs.go\",\n@@ -120,6 +137,7 @@ go_library(\n\"//pkg/sentry/socket/unix/transport\",\n\"//pkg/sentry/vfs\",\n\"//pkg/sync\",\n+ \"//pkg/sync/locking\",\n\"//pkg/usermem\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/kernfs.go",
"new_path": "pkg/sentry/fsimpl/kernfs/kernfs.go",
"diff": "@@ -80,7 +80,7 @@ import (\ntype Filesystem struct {\nvfsfs vfs.Filesystem\n- deferredDecRefsMu sync.Mutex `state:\"nosave\"`\n+ deferredDecRefsMu deferredDecRefsMutex `state:\"nosave\"`\n// deferredDecRefs is a list of dentries waiting to be DecRef()ed. This is\n// used to defer dentry destruction until mu can be acquired for\n@@ -108,7 +108,7 @@ type Filesystem struct {\n// defer fs.mu.RUnlock()\n// ...\n// fs.deferDecRef(dentry)\n- mu sync.RWMutex `state:\"nosave\"`\n+ mu filesystemRWMutex `state:\"nosave\"`\n// nextInoMinusOne is used to to allocate inode numbers on this\n// filesystem. Must be accessed by atomic operations.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/BUILD",
"new_path": "pkg/sentry/vfs/BUILD",
"diff": "load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\nload(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\n+load(\"//pkg/sync/locking:locking.bzl\", \"declare_mutex\")\nlicenses([\"notice\"])\n+declare_mutex(\n+ name = \"virtual_filesystem_mutex\",\n+ out = \"virtual_filesystem_mutex.go\",\n+ package = \"vfs\",\n+ prefix = \"virtualFilesystem\",\n+)\n+\n+declare_mutex(\n+ name = \"inotify_event_mutex\",\n+ out = \"inotify_event_mutex.go\",\n+ package = \"vfs\",\n+ prefix = \"inotifyEvent\",\n+)\n+\n+declare_mutex(\n+ name = \"inotify_mutex\",\n+ out = \"inotify_mutex.go\",\n+ package = \"vfs\",\n+ prefix = \"inotify\",\n+)\n+\n+declare_mutex(\n+ name = \"epoll_instance_mutex\",\n+ out = \"epoll_instance_mutex.go\",\n+ package = \"vfs\",\n+ prefix = \"epollReadyInstance\",\n+)\n+\n+declare_mutex(\n+ name = \"epoll_mutex\",\n+ out = \"epoll_mutex.go\",\n+ package = \"vfs\",\n+ prefix = \"epoll\",\n+)\n+\ngo_template_instance(\nname = \"epoll_interest_list\",\nout = \"epoll_interest_list.go\",\n@@ -69,7 +105,9 @@ go_library(\n\"dentry.go\",\n\"device.go\",\n\"epoll.go\",\n+ \"epoll_instance_mutex.go\",\n\"epoll_interest_list.go\",\n+ \"epoll_mutex.go\",\n\"event_list.go\",\n\"file_description.go\",\n\"file_description_impl_util.go\",\n@@ -79,6 +117,8 @@ go_library(\n\"filesystem_refs.go\",\n\"filesystem_type.go\",\n\"inotify.go\",\n+ \"inotify_event_mutex.go\",\n+ \"inotify_mutex.go\",\n\"lock.go\",\n\"mount.go\",\n\"mount_namespace_refs.go\",\n@@ -90,6 +130,7 @@ go_library(\n\"resolving_path.go\",\n\"save_restore.go\",\n\"vfs.go\",\n+ \"virtual_filesystem_mutex.go\",\n],\nvisibility = [\"//pkg/sentry:internal\"],\ndeps = [\n@@ -117,6 +158,7 @@ go_library(\n\"//pkg/sentry/socket/unix/transport\",\n\"//pkg/sentry/uniqueid\",\n\"//pkg/sync\",\n+ \"//pkg/sync/locking\",\n\"//pkg/usermem\",\n\"//pkg/waiter\",\n\"@org_golang_x_sys//unix:go_default_library\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/epoll.go",
"new_path": "pkg/sentry/vfs/epoll.go",
"diff": "@@ -50,7 +50,7 @@ type EpollInstance struct {\n// readyMu protects ready, readySeq, epollInterest.ready, and\n// epollInterest.epollInterestEntry. ready is analogous to Linux's struct\n// eventpoll::lock.\n- readyMu sync.Mutex `state:\"nosave\"`\n+ readyMu epollReadyInstanceMutex `state:\"nosave\"`\n// ready is the set of file descriptors that may be \"ready\" for I/O. Note\n// that this must be an ordered list, not a map: \"If more than maxevents\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/file_description.go",
"new_path": "pkg/sentry/vfs/file_description.go",
"diff": "@@ -60,7 +60,7 @@ type FileDescription struct {\n// epolls is the set of epollInterests registered for this FileDescription.\n// epolls is protected by epollMu.\n- epollMu sync.Mutex `state:\"nosave\"`\n+ epollMu epollMutex `state:\"nosave\"`\nepolls map[*epollInterest]struct{}\n// vd is the filesystem location at which this FileDescription was opened.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/inotify.go",
"new_path": "pkg/sentry/vfs/inotify.go",
"diff": "@@ -71,7 +71,7 @@ type Inotify struct {\n// evMu *only* protects the events list. We need a separate lock while\n// queuing events: using mu may violate lock ordering, since at that point\n// the calling goroutine may already hold Watches.mu.\n- evMu sync.Mutex `state:\"nosave\"`\n+ evMu inotifyEventMutex `state:\"nosave\"`\n// A list of pending events for this inotify instance. Protected by evMu.\nevents eventList\n@@ -81,7 +81,7 @@ type Inotify struct {\nscratch []byte\n// mu protects the fields below.\n- mu sync.Mutex `state:\"nosave\"`\n+ mu inotifyMutex `state:\"nosave\"`\n// nextWatchMinusOne is used to allocate watch descriptors on this Inotify\n// instance. Note that Linux starts numbering watch descriptors from 1.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/vfs.go",
"new_path": "pkg/sentry/vfs/vfs.go",
"diff": "@@ -60,7 +60,7 @@ type VirtualFilesystem struct {\n// mountMu serializes mount mutations.\n//\n// mountMu is analogous to Linux's namespace_sem.\n- mountMu sync.Mutex `state:\"nosave\"`\n+ mountMu virtualFilesystemMutex `state:\"nosave\"`\n// mounts maps (mount parent, mount point) pairs to mounts. (Since mounts\n// are uniquely namespaced, including mount parent in the key correctly\n"
}
] | Go | Apache License 2.0 | google/gvisor | fs: use lockdep mutexes
PiperOrigin-RevId: 452826155 |
259,907 | 03.06.2022 14:46:16 | 25,200 | 501f43c16f1d3aa4b60e56c445a295af7925cd65 | Deflake TestProcfsDump.
The sleep process in the container may have other open FDs to
SO files. So just check for stdout, stderr, stdin. | [
{
"change_type": "MODIFY",
"old_path": "runsc/container/trace_test.go",
"new_path": "runsc/container/trace_test.go",
"diff": "@@ -370,11 +370,11 @@ func TestProcfsDump(t *testing.T) {\nt.Errorf(\"expected CWD %q, got %q\", spec.Process.Cwd, procfsDump[0].CWD)\n}\n- // Expect 3 host FDs for stdout, stdin and stderr.\n- if len(procfsDump[0].FDs) != 3 {\n- t.Errorf(\"expected 3 FDs for the sleep process, got %+v\", procfsDump[0].FDs)\n+ // Expect at least 3 host FDs for stdout, stdin and stderr.\n+ if len(procfsDump[0].FDs) < 3 {\n+ t.Errorf(\"expected at least 3 FDs for the sleep process, got %+v\", procfsDump[0].FDs)\n} else {\n- for i, fd := range procfsDump[0].FDs {\n+ for i, fd := range procfsDump[0].FDs[:3] {\nif want := int32(i); fd.Number != want {\nt.Errorf(\"expected FD number %d, got %d\", want, fd.Number)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Deflake TestProcfsDump.
The sleep process in the container may have other open FDs to
SO files. So just check for stdout, stderr, stdin.
PiperOrigin-RevId: 452847291 |
259,868 | 03.06.2022 17:01:28 | 25,200 | 4a0ab9caa8400ca682f1940ae9103641ae4381ba | Export `GVISOR_PLATFORM_SUPPORT` environment variable for tests.
This environment variable encodes what capabilities the platform
supports, and is consumed by `platform_util.cc` to determine
which syscall tests are appropriate to run. | [
{
"change_type": "MODIFY",
"old_path": "test/runner/BUILD",
"new_path": "test/runner/BUILD",
"diff": "@@ -27,4 +27,5 @@ bzl_library(\nname = \"defs_bzl\",\nsrcs = [\"defs.bzl\"],\nvisibility = [\"//visibility:private\"],\n+ deps = [\"//tools:defs_bzl\"],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/runner/defs.bzl",
"new_path": "test/runner/defs.bzl",
"diff": "\"\"\"Defines a rule for syscall test targets.\"\"\"\n-load(\"//tools:defs.bzl\", \"default_platform\", \"platforms\")\n+load(\"//tools:defs.bzl\", \"default_platform\", \"platform_capabilities\", \"platforms\")\n+\n+# Maps platform names to a GVISOR_PLATFORM_SUPPORT environment variable consumed by platform_util.cc\n+_platform_support_env_vars = {\n+ platform: \",\".join(sorted([\n+ (\"%s:%s\" % (capability, \"TRUE\" if supported else \"FALSE\"))\n+ for capability, supported in support.items()\n+ ]))\n+ for platform, support in platform_capabilities.items()\n+}\ndef _runner_test_impl(ctx):\n# Generate a runner binary.\n@@ -105,9 +114,19 @@ def _syscall_test(\ncontainer = \"container\" in tags\n+ if platform == \"native\":\n+ # The \"native\" platform supports everything.\n+ platform_support = \",\".join(sorted([\n+ (\"%s:TRUE\" % key)\n+ for key in platform_capabilities[default_platform].keys()\n+ ]))\n+ else:\n+ platform_support = _platform_support_env_vars.get(platform, \"\")\n+\nrunner_args = [\n# Arguments are passed directly to runner binary.\n\"--platform=\" + platform,\n+ \"--platform-support=\" + platform_support,\n\"--network=\" + network,\n\"--use-tmpfs=\" + str(use_tmpfs),\n\"--file-access=\" + file_access,\n"
},
{
"change_type": "MODIFY",
"old_path": "test/runner/main.go",
"new_path": "test/runner/main.go",
"diff": "@@ -43,6 +43,7 @@ var (\ndebug = flag.Bool(\"debug\", false, \"enable debug logs\")\nstrace = flag.Bool(\"strace\", false, \"enable strace logs\")\nplatform = flag.String(\"platform\", \"ptrace\", \"platform to run on\")\n+ platformSupport = flag.String(\"platform-support\", \"\", \"String passed to the test as GVISOR_PLATFORM_SUPPORT environment variable. Used to determine which syscall tests are expected to work with the current platform.\")\nnetwork = flag.String(\"network\", \"none\", \"network stack to run on (sandbox, host, none)\")\nuseTmpfs = flag.Bool(\"use-tmpfs\", false, \"mounts tmpfs for /tmp\")\nfileAccess = flag.String(\"file-access\", \"exclusive\", \"mounts root in exclusive or shared mode\")\n@@ -58,6 +59,11 @@ var (\nleakCheck = flag.Bool(\"leak-check\", false, \"check for reference leaks\")\n)\n+const (\n+ // Environment variable used by platform_util.cc to determine platform capabilities.\n+ platformSupportEnvVar = \"GVISOR_PLATFORM_SUPPORT\"\n+)\n+\n// runTestCaseNative runs the test case directly on the host machine.\nfunc runTestCaseNative(testBin string, tc gtest.TestCase, t *testing.T) {\n// These tests might be running in parallel, so make sure they have a\n@@ -100,6 +106,10 @@ func runTestCaseNative(testBin string, tc gtest.TestCase, t *testing.T) {\nenv = append(env, \"TEST_UDS_ATTACH_TREE=\"+socketDir)\n}\n+ if *platformSupport != \"\" {\n+ env = append(env, fmt.Sprintf(\"%s=%s\", platformSupportEnvVar, *platformSupport))\n+ }\n+\ncmd := exec.Command(testBin, tc.Args()...)\ncmd.Env = env\ncmd.Stdout = os.Stdout\n@@ -399,6 +409,9 @@ func runTestCaseRunsc(testBin string, tc gtest.TestCase, t *testing.T) {\nlisafsVar = \"LISAFS_ENABLED\"\n)\nenv := append(os.Environ(), platformVar+\"=\"+*platform, networkVar+\"=\"+*network)\n+ if *platformSupport != \"\" {\n+ env = append(env, fmt.Sprintf(\"%s=%s\", platformSupportEnvVar, *platformSupport))\n+ }\nif *fuse {\nenv = append(env, fuseVar+\"=TRUE\")\n} else {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/platform_util.cc",
"new_path": "test/util/platform_util.cc",
"diff": "#include \"test/util/platform_util.h\"\n+#include <vector>\n+\n#include \"test/util/test_util.h\"\nnamespace gvisor {\nnamespace testing {\nPlatformSupport PlatformSupport32Bit() {\n- if (GvisorPlatform() == Platform::kPtrace ||\n- GvisorPlatform() == Platform::kKVM) {\n- return PlatformSupport::NotSupported;\n- } else {\n+ const char* support = std::getenv(\"GVISOR_PLATFORM_SUPPORT\");\n+ if (support != nullptr) {\n+ if (std::string(support).find(\"32BIT:TRUE\") != std::string::npos) {\nreturn PlatformSupport::Allowed;\n}\n+ if (std::string(support).find(\"32BIT:FALSE\") != std::string::npos) {\n+ return PlatformSupport::NotSupported;\n+ }\n+ std::cerr << \"GVISOR_PLATFORM_SUPPORT variable does not contain 32BIT \"\n+ \"support information: \"\n+ << support << std::endl;\n+ TEST_CHECK(false);\n+ }\n+ std::cerr << \"GVISOR_PLATFORM_SUPPORT variable undefined\" << std::endl;\n+ TEST_CHECK(false);\n}\nPlatformSupport PlatformSupportAlignmentCheck() {\n+ const char* support = std::getenv(\"GVISOR_PLATFORM_SUPPORT\");\n+ if (support != nullptr) {\n+ if (std::string(support).find(\"ALIGNMENT_CHECK:TRUE\") !=\n+ std::string::npos) {\nreturn PlatformSupport::Allowed;\n}\n+ if (std::string(support).find(\"ALIGNMENT_CHECK:FALSE\") !=\n+ std::string::npos) {\n+ return PlatformSupport::NotSupported;\n+ }\n+ std::cerr\n+ << \"GVISOR_PLATFORM_SUPPORT variable does not contain ALIGNMENT_CHECK \"\n+ \"support information: \"\n+ << support << std::endl;\n+ TEST_CHECK(false);\n+ }\n+ std::cerr << \"GVISOR_PLATFORM_SUPPORT variable undefined\" << std::endl;\n+ TEST_CHECK(false);\n+}\nPlatformSupport PlatformSupportMultiProcess() {\n+ const char* support = std::getenv(\"GVISOR_PLATFORM_SUPPORT\");\n+ if (support != nullptr) {\n+ if (std::string(support).find(\"MULTIPROCESS:TRUE\") != std::string::npos) {\nreturn PlatformSupport::Allowed;\n}\n+ if (std::string(support).find(\"MULTIPROCESS:FALSE\") != std::string::npos) {\n+ return PlatformSupport::NotSupported;\n+ }\n+ std::cerr\n+ << \"GVISOR_PLATFORM_SUPPORT variable does not contain MULTIPROCESS \"\n+ \"support information: \"\n+ << support << std::endl;\n+ TEST_CHECK(false);\n+ }\n+ std::cerr << \"GVISOR_PLATFORM_SUPPORT variable undefined\" << std::endl;\n+ TEST_CHECK(false);\n+}\nPlatformSupport PlatformSupportInt3() {\n- if (GvisorPlatform() == Platform::kKVM) {\n- return PlatformSupport::NotSupported;\n- } else {\n+ const char* support = std::getenv(\"GVISOR_PLATFORM_SUPPORT\");\n+ if (support != nullptr) {\n+ if (std::string(support).find(\"INT3:TRUE\") != std::string::npos) {\nreturn PlatformSupport::Allowed;\n}\n+ if (std::string(support).find(\"INT3:FALSE\") != std::string::npos) {\n+ return PlatformSupport::NotSupported;\n+ }\n+ std::cerr << \"GVISOR_PLATFORM_SUPPORT variable does not contain INT3 \"\n+ \"support information: \"\n+ << support << std::endl;\n+ TEST_CHECK(false);\n+ }\n+ std::cerr << \"GVISOR_PLATFORM_SUPPORT variable undefined\" << std::endl;\n+ TEST_CHECK(false);\n}\n} // namespace testing\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/bazeldefs/platforms.bzl",
"new_path": "tools/bazeldefs/platforms.bzl",
"diff": "@@ -6,4 +6,28 @@ platforms = {\n\"kvm\": [],\n}\n+# Capabilities that platforms may or may not support.\n+# Used by platform_util.cc to determine which syscall tests are appropriate.\n+_CAPABILITY_32BIT = \"32BIT\"\n+_CAPABILITY_ALIGNMENT_CHECK = \"ALIGNMENT_CHECK\"\n+_CAPABILITY_MULTIPROCESS = \"MULTIPROCESS\"\n+_CAPABILITY_INT3 = \"INT3\"\n+\n+# platform_capabilities maps platform names to a dictionary of capabilities mapped to\n+# True (supported) or False (unsupported).\n+platform_capabilities = {\n+ \"ptrace\": {\n+ _CAPABILITY_32BIT: False,\n+ _CAPABILITY_ALIGNMENT_CHECK: True,\n+ _CAPABILITY_MULTIPROCESS: True,\n+ _CAPABILITY_INT3: True,\n+ },\n+ \"kvm\": {\n+ _CAPABILITY_32BIT: False,\n+ _CAPABILITY_ALIGNMENT_CHECK: True,\n+ _CAPABILITY_MULTIPROCESS: True,\n+ _CAPABILITY_INT3: False,\n+ },\n+}\n+\ndefault_platform = \"ptrace\"\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/defs.bzl",
"new_path": "tools/defs.bzl",
"diff": "@@ -12,7 +12,7 @@ load(\"//tools/bazeldefs:defs.bzl\", _BuildSettingInfo = \"BuildSettingInfo\", _amd6\nload(\"//tools/bazeldefs:cc.bzl\", _cc_binary = \"cc_binary\", _cc_flags_supplier = \"cc_flags_supplier\", _cc_grpc_library = \"cc_grpc_library\", _cc_library = \"cc_library\", _cc_proto_library = \"cc_proto_library\", _cc_test = \"cc_test\", _cc_toolchain = \"cc_toolchain\", _gbenchmark = \"gbenchmark\", _gbenchmark_internal = \"gbenchmark_internal\", _grpcpp = \"grpcpp\", _gtest = \"gtest\", _vdso_linker_option = \"vdso_linker_option\")\nload(\"//tools/bazeldefs:go.bzl\", _gazelle = \"gazelle\", _go_binary = \"go_binary\", _go_embed_data = \"go_embed_data\", _go_grpc_and_proto_libraries = \"go_grpc_and_proto_libraries\", _go_library = \"go_library\", _go_path = \"go_path\", _go_proto_library = \"go_proto_library\", _go_rule = \"go_rule\", _go_test = \"go_test\", _gotsan_flag_values = \"gotsan_flag_values\", _gotsan_values = \"gotsan_values\", _select_goarch = \"select_goarch\", _select_goos = \"select_goos\")\nload(\"//tools/bazeldefs:pkg.bzl\", _pkg_deb = \"pkg_deb\", _pkg_tar = \"pkg_tar\")\n-load(\"//tools/bazeldefs:platforms.bzl\", _default_platform = \"default_platform\", _platforms = \"platforms\")\n+load(\"//tools/bazeldefs:platforms.bzl\", _default_platform = \"default_platform\", _platform_capabilities = \"platform_capabilities\", _platforms = \"platforms\")\nload(\"//tools/bazeldefs:tags.bzl\", \"go_suffixes\")\n# Core rules.\n@@ -59,6 +59,7 @@ pkg_tar = _pkg_tar\n# Platform options.\ndefault_platform = _default_platform\nplatforms = _platforms\n+platform_capabilities = _platform_capabilities\ndef _go_add_tags(ctx):\n\"\"\" Adds tags to the given source file. \"\"\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | Export `GVISOR_PLATFORM_SUPPORT` environment variable for tests.
This environment variable encodes what capabilities the platform
supports, and is consumed by `platform_util.cc` to determine
which syscall tests are appropriate to run.
PiperOrigin-RevId: 452870567 |
259,909 | 05.06.2022 19:08:14 | 25,200 | 7dbe1e6670860b7e4e2588c350adabee43bdf05c | Fix connect() not properly setting endpoint state.
If connect does not set the state to Connecting before taking over the binding
of another endpoint in TIME_WAIT, a race can happen where an segment is
processed without the endpoint having a proper state, causing a panic. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -2162,73 +2162,11 @@ func (e *endpoint) Connect(addr tcpip.FullAddress) tcpip.Error {\nreturn err\n}\n-// connect connects the endpoint to its peer.\n+// registerEndpoint registers the endpoint with the provided address.\n+//\n// +checklocks:e.mu\n-func (e *endpoint) connect(addr tcpip.FullAddress, handshake bool) tcpip.Error {\n- connectingAddr := addr.Addr\n-\n- addr, netProto, err := e.checkV4MappedLocked(addr)\n- if err != nil {\n- return err\n- }\n-\n- if e.EndpointState().connected() {\n- // The endpoint is already connected. If caller hasn't been\n- // notified yet, return success.\n- if !e.isConnectNotified {\n- e.isConnectNotified = true\n- return nil\n- }\n- // Otherwise return that it's already connected.\n- return &tcpip.ErrAlreadyConnected{}\n- }\n-\n- nicID := addr.NIC\n- switch e.EndpointState() {\n- case StateBound:\n- // If we're already bound to a NIC but the caller is requesting\n- // that we use a different one now, we cannot proceed.\n- if e.boundNICID == 0 {\n- break\n- }\n-\n- if nicID != 0 && nicID != e.boundNICID {\n- return &tcpip.ErrNoRoute{}\n- }\n-\n- nicID = e.boundNICID\n-\n- case StateInitial:\n- // Nothing to do. We'll eventually fill-in the gaps in the ID (if any)\n- // when we find a route.\n-\n- case StateConnecting, StateSynSent, StateSynRecv:\n- // A connection request has already been issued but hasn't completed\n- // yet.\n- return &tcpip.ErrAlreadyConnecting{}\n-\n- case StateError:\n- if err := e.hardErrorLocked(); err != nil {\n- return err\n- }\n- return &tcpip.ErrConnectionAborted{}\n-\n- default:\n- return &tcpip.ErrInvalidEndpointState{}\n- }\n-\n- // Find a route to the desired destination.\n- r, err := e.stack.FindRoute(nicID, e.TransportEndpointInfo.ID.LocalAddress, addr.Addr, netProto, false /* multicastLoop */)\n- if err != nil {\n- return err\n- }\n- defer r.Release()\n-\n+func (e *endpoint) registerEndpoint(addr tcpip.FullAddress, netProto tcpip.NetworkProtocolNumber, nicID tcpip.NICID) tcpip.Error {\nnetProtos := []tcpip.NetworkProtocolNumber{netProto}\n- e.TransportEndpointInfo.ID.LocalAddress = r.LocalAddress()\n- e.TransportEndpointInfo.ID.RemoteAddress = r.RemoteAddress()\n- e.TransportEndpointInfo.ID.RemotePort = addr.Port\n-\nif e.TransportEndpointInfo.ID.LocalPort != 0 {\n// The endpoint is bound to a port, attempt to register it.\nerr := e.stack.RegisterTransportEndpoint(netProtos, ProtocolNumber, e.TransportEndpointInfo.ID, e, e.boundPortFlags, e.boundBindToDevice)\n@@ -2306,7 +2244,7 @@ func (e *endpoint) connect(addr tcpip.FullAddress, handshake bool) tcpip.Error {\n// done yet) or the reservation was freed between the check above and\n// the FindTransportEndpoint below. But rather than retry the same port\n// we just skip it and move on.\n- transEP := e.stack.FindTransportEndpoint(netProto, ProtocolNumber, transEPID, r.NICID())\n+ transEP := e.stack.FindTransportEndpoint(netProto, ProtocolNumber, transEPID, nicID)\nif transEP == nil {\n// ReservePort failed but there is no registered endpoint with\n// demuxer. Which indicates there is at least some endpoint that has\n@@ -2377,13 +2315,87 @@ func (e *endpoint) connect(addr tcpip.FullAddress, handshake bool) tcpip.Error {\nreturn err\n}\n}\n+ return nil\n+}\n- e.isRegistered = true\n+// connect connects the endpoint to its peer.\n+// +checklocks:e.mu\n+func (e *endpoint) connect(addr tcpip.FullAddress, handshake bool) tcpip.Error {\n+ connectingAddr := addr.Addr\n+\n+ addr, netProto, err := e.checkV4MappedLocked(addr)\n+ if err != nil {\n+ return err\n+ }\n+\n+ if e.EndpointState().connected() {\n+ // The endpoint is already connected. If caller hasn't been\n+ // notified yet, return success.\n+ if !e.isConnectNotified {\n+ e.isConnectNotified = true\n+ return nil\n+ }\n+ // Otherwise return that it's already connected.\n+ return &tcpip.ErrAlreadyConnected{}\n+ }\n+\n+ nicID := addr.NIC\n+ switch e.EndpointState() {\n+ case StateBound:\n+ // If we're already bound to a NIC but the caller is requesting\n+ // that we use a different one now, we cannot proceed.\n+ if e.boundNICID == 0 {\n+ break\n+ }\n+\n+ if nicID != 0 && nicID != e.boundNICID {\n+ return &tcpip.ErrNoRoute{}\n+ }\n+\n+ nicID = e.boundNICID\n+\n+ case StateInitial:\n+ // Nothing to do. We'll eventually fill-in the gaps in the ID (if any)\n+ // when we find a route.\n+\n+ case StateConnecting, StateSynSent, StateSynRecv:\n+ // A connection request has already been issued but hasn't completed\n+ // yet.\n+ return &tcpip.ErrAlreadyConnecting{}\n+\n+ case StateError:\n+ if err := e.hardErrorLocked(); err != nil {\n+ return err\n+ }\n+ return &tcpip.ErrConnectionAborted{}\n+\n+ default:\n+ return &tcpip.ErrInvalidEndpointState{}\n+ }\n+\n+ // Find a route to the desired destination.\n+ r, err := e.stack.FindRoute(nicID, e.TransportEndpointInfo.ID.LocalAddress, addr.Addr, netProto, false /* multicastLoop */)\n+ if err != nil {\n+ return err\n+ }\n+ defer r.Release()\n+\n+ e.TransportEndpointInfo.ID.LocalAddress = r.LocalAddress()\n+ e.TransportEndpointInfo.ID.RemoteAddress = r.RemoteAddress()\n+ e.TransportEndpointInfo.ID.RemotePort = addr.Port\n+\n+ oldState := e.EndpointState()\ne.setEndpointState(StateConnecting)\n+ if err := e.registerEndpoint(addr, netProto, r.NICID()); err != nil {\n+ e.setEndpointState(oldState)\n+ return err\n+ }\n+\n+ e.isRegistered = true\nr.Acquire()\ne.route = r\ne.boundNICID = nicID\n- e.effectiveNetProtos = netProtos\n+ e.effectiveNetProtos = []tcpip.NetworkProtocolNumber{netProto}\ne.connectingAddress = connectingAddr\ne.initGSO()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/test/e2e/tcp_test.go",
"new_path": "pkg/tcpip/transport/tcp/test/e2e/tcp_test.go",
"diff": "@@ -4982,6 +4982,105 @@ func TestReusePort(t *testing.T) {\n}\n}\n+func TestTimeWaitAssassination(t *testing.T) {\n+ var wg sync.WaitGroup\n+ defer wg.Wait()\n+ // We need to run this test lots of times because it triggers a very rare race\n+ // condition in segment processing.\n+ initalTestPort := 1024\n+ testRuns := 25\n+ for port := initalTestPort; port < initalTestPort+testRuns; port++ {\n+ wg.Add(1)\n+ go func(port uint16) {\n+ defer wg.Done()\n+ c := context.New(t, e2e.DefaultMTU)\n+ defer c.Cleanup()\n+\n+ twReuse := tcpip.TCPTimeWaitReuseOption(tcpip.TCPTimeWaitReuseGlobal)\n+ if err := c.Stack().SetTransportProtocolOption(tcp.ProtocolNumber, &twReuse); err != nil {\n+ t.Errorf(\"s.TransportProtocolOption(%v, %v) = %v\", tcp.ProtocolNumber, &twReuse, err)\n+ }\n+\n+ if err := c.Stack().SetPortRange(port, port); err != nil {\n+ t.Errorf(\"got s.SetPortRange(%d, %d) = %s, want = nil\", port, port, err)\n+ }\n+\n+ iss := seqnum.Value(context.TestInitialSequenceNumber)\n+ c.CreateConnected(context.TestInitialSequenceNumber, 30000, -1)\n+ c.EP.Close()\n+\n+ checker.IPv4(t, c.GetPacket(), checker.TCP(\n+ checker.SrcPort(port),\n+ checker.DstPort(context.TestPort),\n+ checker.TCPSeqNum(uint32(c.IRS+1)),\n+ checker.TCPAckNum(uint32(iss)+1),\n+ checker.TCPFlags(header.TCPFlagFin|header.TCPFlagAck)))\n+\n+ finHeaders := &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: port,\n+ Flags: header.TCPFlagAck | header.TCPFlagFin,\n+ SeqNum: iss + 1,\n+ AckNum: c.IRS + 2,\n+ }\n+\n+ c.SendPacket(nil, finHeaders)\n+\n+ // c.EP is in TIME_WAIT. We must allow for a second to pass before the\n+ // new endpoint is allowed to take over the old endpoint's binding.\n+ time.Sleep(time.Second)\n+\n+ seq := iss + 1\n+ ack := c.IRS + 2\n+\n+ var wg sync.WaitGroup\n+ defer wg.Wait()\n+\n+ wg.Add(1)\n+ go func() {\n+ defer wg.Done()\n+ // The new endpoint will take over the binding.\n+ c.Create(-1)\n+ timeout := time.After(5 * time.Second)\n+ connect:\n+ for {\n+ select {\n+ case <-timeout:\n+ break connect\n+ default:\n+ err := c.EP.Connect(tcpip.FullAddress{Addr: context.TestAddr, Port: context.TestPort})\n+ // It can take some extra time for the port to be available.\n+ if _, ok := err.(*tcpip.ErrNoPortAvailable); ok {\n+ continue connect\n+ }\n+ if _, ok := err.(*tcpip.ErrConnectStarted); !ok {\n+ t.Errorf(\"Unexpected return value from Connect: %v\", err)\n+ }\n+ break connect\n+ }\n+ }\n+ }()\n+\n+ // If the new endpoint does not properly transition to connecting before\n+ // taking over the port reservation, sending acks will cause the processor\n+ // to panic 1-5% of the time.\n+ for i := 0; i < 5; i++ {\n+ wg.Add(1)\n+ go func() {\n+ defer wg.Done()\n+ c.SendPacket(nil, &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: port,\n+ Flags: header.TCPFlagAck,\n+ SeqNum: seq,\n+ AckNum: ack,\n+ })\n+ }()\n+ }\n+ }(uint16(port))\n+ }\n+}\n+\nfunc checkRecvBufferSize(t *testing.T, ep tcpip.Endpoint, v int) {\nt.Helper()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix connect() not properly setting endpoint state.
If connect does not set the state to Connecting before taking over the binding
of another endpoint in TIME_WAIT, a race can happen where an segment is
processed without the endpoint having a proper state, causing a panic.
PiperOrigin-RevId: 453109764 |
259,992 | 06.06.2022 16:44:24 | 25,200 | a30c81cd802214ab5f08335e663c228a66e566c5 | Only check for systemd when needed | [
{
"change_type": "MODIFY",
"old_path": "runsc/cgroup/cgroup.go",
"new_path": "runsc/cgroup/cgroup.go",
"diff": "@@ -402,7 +402,7 @@ func new(pid, cgroupsPath string, useSystemd bool) (Cgroup, error) {\nOwn: make(map[string]bool),\n}\n}\n- log.Debugf(\"New cgroup for pid: %s, %+v\", pid, cg)\n+ log.Debugf(\"New cgroup for pid: %s, %T: %+v\", pid, cg, cg)\nreturn cg, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cgroup/systemd.go",
"new_path": "runsc/cgroup/systemd.go",
"diff": "@@ -23,6 +23,7 @@ import (\n\"regexp\"\n\"strconv\"\n\"strings\"\n+ \"sync\"\n\"time\"\nsystemdDbus \"github.com/coreos/go-systemd/v22/dbus\"\n@@ -40,8 +41,6 @@ var (\n// ErrInvalidSlice indicates that the slice name passed via cgroup.Path is\n// invalid.\nErrInvalidSlice = errors.New(\"invalid slice name\")\n-\n- isRunningSystemd = runningSystemd()\n)\n// cgroupSystemd represents a cgroupv2 managed by systemd.\n@@ -59,7 +58,7 @@ type cgroupSystemd struct {\n}\nfunc newCgroupV2Systemd(cgv2 *cgroupV2) (*cgroupSystemd, error) {\n- if !isRunningSystemd {\n+ if !isRunningSystemd() {\nreturn nil, fmt.Errorf(\"systemd not running on host\")\n}\nctx := context.Background()\n@@ -236,9 +235,17 @@ func validSlice(slice string) error {\nreturn nil\n}\n-func runningSystemd() bool {\n+var systemdCheck struct {\n+ once sync.Once\n+ cache bool\n+}\n+\n+func isRunningSystemd() bool {\n+ systemdCheck.once.Do(func() {\nfi, err := os.Lstat(\"/run/systemd/system\")\n- return err == nil && fi.IsDir()\n+ systemdCheck.cache = err == nil && fi.IsDir()\n+ })\n+ return systemdCheck.cache\n}\nfunc systemdVersion(conn *systemdDbus.Conn) (int, error) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Only check for systemd when needed
PiperOrigin-RevId: 453311374 |
259,853 | 07.06.2022 14:08:11 | 25,200 | 2e0ff5d9d0455217fa9c0f1d38a07d44808a3821 | platform/kvm: Disable async preemption while mapping initial virtual regions.
All new mappings are handled from the SIGSYS signal handler and we have to
guarantee that the signal handler doesn't race with the code that handles
initial regions. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine.go",
"new_path": "pkg/sentry/platform/kvm/machine.go",
"diff": "@@ -318,6 +318,10 @@ func newMachine(vm int) (*machine, error) {\n}\n}\n+ // handleBluepillFault takes the slot spinlock and it is called from\n+ // seccompMmapHandler, so here we have to guarantee that mmap is not\n+ // called while we hold the slot spinlock.\n+ disableAsyncPreemption()\napplyVirtualRegions(func(vr virtualRegion) {\nif excludeVirtualRegion(vr) {\nreturn // skip region.\n@@ -331,6 +335,7 @@ func newMachine(vm int) (*machine, error) {\nmapRegion(vr, 0)\n})\n+ enableAsyncPreemption()\n// Initialize architecture state.\nif err := m.initArchState(); err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine_unsafe.go",
"new_path": "pkg/sentry/platform/kvm/machine_unsafe.go",
"diff": "@@ -240,3 +240,23 @@ func seccompMmapHandler(context unsafe.Pointer) {\n}\nseccompMmapHandlerCnt.Add(-1)\n}\n+\n+// disableAsyncPreemption disables asynchronous preemption of go-routines.\n+func disableAsyncPreemption() {\n+ set := linux.MakeSignalSet(linux.SIGURG)\n+ _, _, errno := unix.RawSyscall6(unix.SYS_RT_SIGPROCMASK, linux.SIG_BLOCK,\n+ uintptr(unsafe.Pointer(&set)), 0, linux.SignalSetSize, 0, 0)\n+ if errno != 0 {\n+ panic(fmt.Sprintf(\"sigprocmask failed: %d\", errno))\n+ }\n+}\n+\n+// enableAsyncPreemption enables asynchronous preemption of go-routines.\n+func enableAsyncPreemption() {\n+ set := linux.MakeSignalSet(linux.SIGURG)\n+ _, _, errno := unix.RawSyscall6(unix.SYS_RT_SIGPROCMASK, linux.SIG_UNBLOCK,\n+ uintptr(unsafe.Pointer(&set)), 0, linux.SignalSetSize, 0, 0)\n+ if errno != 0 {\n+ panic(fmt.Sprintf(\"sigprocmask failed: %d\", errno))\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | platform/kvm: Disable async preemption while mapping initial virtual regions.
All new mappings are handled from the SIGSYS signal handler and we have to
guarantee that the signal handler doesn't race with the code that handles
initial regions.
PiperOrigin-RevId: 453521202 |
259,868 | 07.06.2022 16:40:13 | 25,200 | 68ec24098221567237af9b5404e72f0ad7194f47 | Disable tests for platforms tagged with "internal". | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/platforms/BUILD",
"new_path": "runsc/boot/platforms/BUILD",
"diff": "@@ -22,6 +22,7 @@ exempt_go_library(\nlinux = [\n\"//pkg/sentry/platform/%s\" % platform\nfor platform in platforms\n+ if \"internal\" not in platforms[platform]\n],\n),\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/runner/defs.bzl",
"new_path": "test/runner/defs.bzl",
"diff": "@@ -148,6 +148,12 @@ def _syscall_test(\n**kwargs\n)\n+def all_platforms():\n+ \"\"\"All platforms returns a list of all platforms.\"\"\"\n+ available = dict(platforms.items())\n+ available[default_platform] = platforms.get(default_platform, [])\n+ return available.items()\n+\ndef syscall_test(\ntest,\nuse_tmpfs = False,\n@@ -190,7 +196,7 @@ def syscall_test(\n**kwargs\n)\n- for (platform, platform_tags) in platforms.items():\n+ for platform, platform_tags in all_platforms():\n_syscall_test(\ntest = test,\nplatform = platform,\n@@ -221,7 +227,7 @@ def syscall_test(\nplatform = default_platform,\nuse_tmpfs = use_tmpfs,\nadd_uds_tree = add_uds_tree,\n- tags = platforms[default_platform] + tags,\n+ tags = platforms.get(default_platform, []) + tags,\ndebug = debug,\nfuse = fuse,\noverlay = True,\n@@ -234,7 +240,7 @@ def syscall_test(\nuse_tmpfs = use_tmpfs,\nnetwork = \"host\",\nadd_uds_tree = add_uds_tree,\n- tags = platforms[default_platform] + tags,\n+ tags = platforms.get(default_platform, []) + tags,\ndebug = debug,\nfuse = fuse,\n**kwargs\n@@ -246,7 +252,7 @@ def syscall_test(\nplatform = default_platform,\nuse_tmpfs = use_tmpfs,\nadd_uds_tree = add_uds_tree,\n- tags = platforms[default_platform] + tags,\n+ tags = platforms.get(default_platform, []) + tags,\ndebug = debug,\nfile_access = \"shared\",\nfuse = fuse,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Disable tests for platforms tagged with "internal".
PiperOrigin-RevId: 453554360 |
259,868 | 07.06.2022 20:48:51 | 25,200 | 8b5289e723b5174402947fc09a11a66a70d0e945 | BuildKite: Install runsc under a unique runtime name.
Without this, the runtime entry can get overwritten between
runs of different pipelines, potentially with different flags. | [
{
"change_type": "MODIFY",
"old_path": ".buildkite/hooks/pre-command",
"new_path": ".buildkite/hooks/pre-command",
"diff": "@@ -28,13 +28,14 @@ export PARTITION=${BUILDKITE_PARALLEL_JOB:-0}\nPARTITION=$((${PARTITION}+1)) # 1-indexed, but PARALLEL_JOB is 0-indexed.\nexport TOTAL_PARTITIONS=${BUILDKITE_PARALLEL_JOB_COUNT:-1}\n+# Set the system-wide Docker runtime name after the BuildKite branch name.\n+export RUNTIME=\"${BUILDKITE_BRANCH}-${BUILDKITE_BUILD_ID}\"\n+\n# Ensure Docker has experimental enabled.\nEXPERIMENTAL=$(sudo docker version --format='{{.Server.Experimental}}')\n-if test \"${EXPERIMENTAL}\" != \"true\"; then\nmake sudo TARGETS=//runsc:runsc \\\n- ARGS=\"install --experimental=true -- ${RUNTIME_ARGS:-}\"\n+ ARGS=\"install --experimental=true --runtime=${RUNTIME} -- ${RUNTIME_ARGS:-}\"\nsudo systemctl restart docker\n-fi\n# Helper for benchmarks, based on the branch.\nif test \"${BUILDKITE_BRANCH}\" = \"master\"; then\n"
}
] | Go | Apache License 2.0 | google/gvisor | BuildKite: Install runsc under a unique runtime name.
Without this, the runtime entry can get overwritten between
runs of different pipelines, potentially with different flags.
PiperOrigin-RevId: 453589305 |
260,009 | 08.06.2022 09:59:37 | 25,200 | 3290a054c5bd6d53e23c09b8e7041c11e5a2441c | getdents: Test that size parameter is not zero before allocating PMAs.
Trying to allocate PMAs with 0 length leads to panic. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/getdents.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/getdents.go",
"diff": "@@ -36,10 +36,17 @@ func Getdents64(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sy\nreturn getdents(t, args, true /* isGetdents64 */)\n}\n+// DirentStructBytesWithoutName is enough to fit (struct linux_dirent) and\n+// (struct linux_dirent64) without accounting for the name parameter.\n+const DirentStructBytesWithoutName = 8 + 8 + 2 + 1 + 1\n+\nfunc getdents(t *kernel.Task, args arch.SyscallArguments, isGetdents64 bool) (uintptr, *kernel.SyscallControl, error) {\nfd := args[0].Int()\naddr := args[1].Pointer()\nsize := int(args[2].Uint())\n+ if size < DirentStructBytesWithoutName {\n+ return 0, nil, linuxerr.EINVAL\n+ }\nfile := t.GetFileVFS2(fd)\nif file == nil {\n@@ -123,7 +130,7 @@ func (cb *getdentsCallback) Handle(dirent vfs.Dirent) error {\n// unsigned char d_type; /* File type */\n// char d_name[]; /* Filename (null-terminated) */\n// };\n- size := 8 + 8 + 2 + 1 + 1 + len(dirent.Name)\n+ size := DirentStructBytesWithoutName + len(dirent.Name)\nsize = (size + 7) &^ 7 // round up to multiple of 8\nif size > remaining {\n// This is only needed to imitate Linux, since it writes out to the user\n@@ -164,7 +171,7 @@ func (cb *getdentsCallback) Handle(dirent vfs.Dirent) error {\nif cb.t.Arch().Width() != 8 {\npanic(fmt.Sprintf(\"unsupported sizeof(unsigned long): %d\", cb.t.Arch().Width()))\n}\n- size := 8 + 8 + 2 + 1 + 1 + len(dirent.Name)\n+ size := DirentStructBytesWithoutName + len(dirent.Name)\nsize = (size + 7) &^ 7 // round up to multiple of sizeof(long)\nif size > remaining {\nif cb.copied == 0 && cb.userReportedSize >= size {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/getdents.cc",
"new_path": "test/syscalls/linux/getdents.cc",
"diff": "@@ -485,6 +485,17 @@ TYPED_TEST(GetdentsTest, Issue128ProcSeekEnd) {\nSyscallSucceeds());\n}\n+// Tests that getdents() fails when called with a zero-length buffer.\n+TYPED_TEST(GetdentsTest, ZeroLengthOutBuffer) {\n+ auto dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ auto fd = ASSERT_NO_ERRNO_AND_VALUE(Open(dir.path(), O_DIRECTORY));\n+\n+ typename TestFixture::DirentBufferType dirents(0);\n+ ASSERT_THAT(RetryEINTR(syscall)(this->SyscallNum(), fd.get(), dirents.Data(),\n+ dirents.Size()),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\n// Some tests using the glibc readdir interface.\nTEST(ReaddirTest, OpenDir) {\nDIR* dev;\n"
}
] | Go | Apache License 2.0 | google/gvisor | getdents: Test that size parameter is not zero before allocating PMAs.
Trying to allocate PMAs with 0 length leads to panic.
PiperOrigin-RevId: 453704555 |
259,891 | 08.06.2022 15:00:48 | 25,200 | f78c23ffd6758374dfb78759db7a88a38ae8d216 | state: don't print the encoded object twice upon error
Sufficiently junky data can cause printing to take a *long* time. OSS-fuzz times
out entirely [1]. On my desktop it takes ~20s to run that test.
1 | [
{
"change_type": "MODIFY",
"old_path": "pkg/state/decode.go",
"new_path": "pkg/state/decode.go",
"diff": "@@ -639,7 +639,7 @@ func (ds *decodeState) Load(obj reflect.Value) {\nods = nil\nencoded = nil\ndefault:\n- Failf(\"wanted type or object ID, got %#v\", encoded)\n+ Failf(\"wanted type or object ID, got %T\", encoded)\n}\n}\n}); err != nil {\n"
}
] | Go | Apache License 2.0 | google/gvisor | state: don't print the encoded object twice upon error
Sufficiently junky data can cause printing to take a *long* time. OSS-fuzz times
out entirely [1]. On my desktop it takes ~20s to run that test.
1 - https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=45414&q=gvisor&can=2
PiperOrigin-RevId: 453774647 |
259,868 | 08.06.2022 18:00:05 | 25,200 | 75f0c9b05ec592a09d00675afb06c6d40c2da349 | Fix flakiness in `Processes::ExecSwapThreadGroupLeader`.
This closes the write end of the pipe earlier in the main test
body, and avoids allocations after fork+clone when building up
the `execve` array's flags.
There may be more obvious ways to do this, let me know :) | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -4469,6 +4469,7 @@ cc_binary(\n\"//test/util:test_util\",\n\"//test/util:thread_util\",\n\"@com_google_absl//absl/flags:flag\",\n+ \"@com_google_absl//absl/strings\",\n\"@com_google_absl//absl/strings:str_format\",\n\"@com_google_absl//absl/time\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/processes.cc",
"new_path": "test/syscalls/linux/processes.cc",
"diff": "// limitations under the License.\n#include <stdint.h>\n+#include <sys/mman.h>\n#include <sys/syscall.h>\n#include <unistd.h>\n+#include <algorithm>\n+#include <cstring>\n+\n#include \"gtest/gtest.h\"\n#include \"absl/flags/flag.h\"\n#include \"absl/strings/str_format.h\"\n+#include \"absl/strings/string_view.h\"\n#include \"absl/time/clock.h\"\n#include \"absl/time/time.h\"\n#include \"test/util/capability_util.h\"\n@@ -93,7 +98,7 @@ TEST(Processes, SetPGIDOfZombie) {\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN)));\n// Fork a test process in a new PID namespace, because it needs to manipulate\n- // with reparanted processes.\n+ // with reparented processes.\nstruct clone_arg {\n// Reserve some space for clone() to locate arguments and retcode in this\n// place.\n@@ -134,6 +139,7 @@ TEST(Processes, TheadSharesSamePID) {\nclone(WritePIDToPipe, ca.stack_ptr,\nCLONE_THREAD | CLONE_SIGHAND | CLONE_VM | CLONE_FS, pipe_fds),\nSyscallSucceeds());\n+ ASSERT_THAT(close(pipe_fds[1]), SyscallSucceeds());\npid_t pid_from_child;\nTEST_PCHECK(read(pipe_fds[0], &pid_from_child, sizeof(pid_from_child)) ==\nsizeof(pid_from_child));\n@@ -141,7 +147,6 @@ TEST(Processes, TheadSharesSamePID) {\nTEST_PCHECK(read(pipe_fds[0], &buf, sizeof(buf)) ==\n0); // Wait for cloned thread to exit\nASSERT_THAT(close(pipe_fds[0]), SyscallSucceeds());\n- ASSERT_THAT(close(pipe_fds[1]), SyscallSucceeds());\nEXPECT_EQ(test_pid, pid_from_child);\n}\n@@ -162,6 +167,27 @@ struct ExecSwapResult {\npid_t post_exec_tid;\n};\n+// The number of elements in ExecSwapArg.execve_array.\n+constexpr int kExecveArraySize = 7;\n+\n+// The size of the preallocated elements of execve_array that are populated\n+// in ExecSwapPreExec. Should be large enough to hold any flag string.\n+constexpr int kExecveArrayComponentsSize = 256;\n+\n+// ExecSwapArg is passed as argument to ExecSwapPreExec.\n+struct ExecSwapArg {\n+ // The pipe FD to write results to.\n+ int pipe_fd;\n+\n+ // Data from prior to cloning.\n+ pid_t pre_clone_pid;\n+ pid_t pre_clone_tid;\n+\n+ // Pre-allocated array to use in execve, so that we can use it without doing\n+ // allocations in ExecSwapPreExec.\n+ char* execve_array[kExecveArraySize];\n+};\n+\n// ExecSwapPostExec is the third part of the ExecSwapThreadGroupLeader test.\n// It is called after the test has fork()'d, clone()'d, and exec()'d into this.\n// It writes all the PIDs and TIDs from each part of the test to a pipe.\n@@ -196,32 +222,42 @@ int ExecSwapPostExec() {\n// It is called after the test has fork()'d and clone()'d.\n// It calls exec() with flags that cause the test binary to run\n// ExecSwapPostExec.\n-int ExecSwapPreExec(void* arg) {\n- ExecSwapResult* result = reinterpret_cast<ExecSwapResult*>(arg);\n+int ExecSwapPreExec(void* void_arg) {\n+ ExecSwapArg* arg = reinterpret_cast<ExecSwapArg*>(void_arg);\npid_t pid;\nTEST_PCHECK(pid = getpid());\npid_t tid;\nTEST_PCHECK(tid = gettid());\n- ExecveArray const execve_argv = {\n- \"/proc/self/exe\",\n- \"--processes_test_exec_swap\",\n- absl::StrFormat(\"--processes_test_exec_swap_pre_clone_pid=%d\",\n- result->pre_clone_pid),\n- absl::StrFormat(\"--processes_test_exec_swap_pre_clone_tid=%d\",\n- result->pre_clone_tid),\n- absl::StrFormat(\"--processes_test_exec_swap_pre_exec_pid=%d\", pid),\n- absl::StrFormat(\"--processes_test_exec_swap_pre_exec_tid=%d\", tid),\n- absl::StrFormat(\"--processes_test_exec_swap_pipe_fd=%d\", result->pipe_fd),\n- };\n- TEST_PCHECK(execv(\"/proc/self/exe\", execve_argv.get()));\n+ strncpy(arg->execve_array[0], \"/proc/self/exe\", kExecveArrayComponentsSize);\n+ strncpy(arg->execve_array[1], \"--processes_test_exec_swap\",\n+ kExecveArrayComponentsSize);\n+ absl::SNPrintF(arg->execve_array[2], kExecveArrayComponentsSize,\n+ \"--processes_test_exec_swap_pre_clone_pid=%d\",\n+ arg->pre_clone_pid);\n+ absl::SNPrintF(arg->execve_array[3], kExecveArrayComponentsSize,\n+ \"--processes_test_exec_swap_pre_clone_tid=%d\",\n+ arg->pre_clone_tid);\n+ absl::SNPrintF(arg->execve_array[4], kExecveArrayComponentsSize,\n+ \"--processes_test_exec_swap_pre_exec_pid=%d\", pid);\n+ absl::SNPrintF(arg->execve_array[5], kExecveArrayComponentsSize,\n+ \"--processes_test_exec_swap_pre_exec_tid=%d\", tid);\n+ absl::SNPrintF(arg->execve_array[6], kExecveArrayComponentsSize,\n+ \"--processes_test_exec_swap_pipe_fd=%d\", arg->pipe_fd);\n+ std::cerr << \"Test exec'ing:\" << std::endl;\n+ for (int i = 0; i < kExecveArraySize; ++i) {\n+ std::cerr << \" execve_array[\" << i << \"] = \" << arg->execve_array[i]\n+ << std::endl;\n+ }\n+ TEST_PCHECK(execv(\"/proc/self/exe\", arg->execve_array));\n+ std::cerr << \"execve: \" << errno << std::endl;\n_exit(1); // Should be unreachable.\n}\n// ExecSwapPreClone is the first part of the ExecSwapThreadGroupLeader test.\n// It is called after the test has fork()'d.\n// It calls clone() to run ExecSwapPreExec.\n-void ExecSwapPreClone(int* pipe_fds) {\n+void ExecSwapPreClone(ExecSwapArg* exec_swap_arg) {\npid_t pid;\nASSERT_THAT(pid = getpid(), SyscallSucceeds());\npid_t tid;\n@@ -230,14 +266,12 @@ void ExecSwapPreClone(int* pipe_fds) {\nchar stack[4096] __attribute__((aligned(16)));\nchar stack_ptr[0];\n} ca;\n- ExecSwapResult result;\n- result.pipe_fd = pipe_fds[1];\n- result.pre_clone_pid = pid;\n- result.pre_clone_tid = tid;\n+ exec_swap_arg->pre_clone_pid = pid;\n+ exec_swap_arg->pre_clone_tid = tid;\nstd::cerr << \"Test cloning.\" << std::endl;\nASSERT_THAT(\nclone(ExecSwapPreExec, ca.stack_ptr,\n- CLONE_THREAD | CLONE_SIGHAND | CLONE_VM | CLONE_FS, &result),\n+ CLONE_THREAD | CLONE_SIGHAND | CLONE_VM | CLONE_FS, exec_swap_arg),\nSyscallSucceeds());\n// The clone thread will call exec, so just sit around here until it does.\nabsl::SleepFor(absl::Milliseconds(500));\n@@ -255,12 +289,30 @@ TEST(Processes, ExecSwapThreadGroupLeader) {\nASSERT_THAT(test_pid = getpid(), SyscallSucceeds());\npid_t test_tid;\nASSERT_THAT(test_tid = gettid(), SyscallSucceeds());\n+\n+ // Preallocate ExecSwapArg ahead of fork().\n+ // This uses shared memory because we use it after fork()+clone().\n+ ExecSwapArg* exec_swap_arg =\n+ (ExecSwapArg*)mmap(NULL, sizeof(ExecSwapArg), PROT_READ | PROT_WRITE,\n+ MAP_SHARED | MAP_ANONYMOUS, -1, 0);\n+ ASSERT_NE(exec_swap_arg, MAP_FAILED);\n+ exec_swap_arg->pipe_fd = pipe_fds[1];\n+ char* execve_array_component;\n+ for (int i = 0; i < kExecveArraySize; ++i) {\n+ execve_array_component =\n+ (char*)mmap(NULL, kExecveArrayComponentsSize * sizeof(char),\n+ PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);\n+ ASSERT_NE(execve_array_component, MAP_FAILED);\n+ exec_swap_arg->execve_array[i] = execve_array_component;\n+ }\n+\nstd::cerr << \"Test forking.\" << std::endl;\npid_t fork_pid = fork();\nif (fork_pid == 0) {\n- ExecSwapPreClone(pipe_fds);\n+ ExecSwapPreClone(exec_swap_arg);\nASSERT_TRUE(false) << \"Did not get replaced by execed child\";\n}\n+ ASSERT_THAT(close(pipe_fds[1]), SyscallSucceeds());\nstd::cerr << \"Waiting for test results.\" << std::endl;\nExecSwapResult result;\n@@ -279,7 +331,6 @@ TEST(Processes, ExecSwapThreadGroupLeader) {\n<< result.post_exec_tid << std::endl;\nASSERT_THAT(close(pipe_fds[0]), SyscallSucceeds());\n- ASSERT_THAT(close(pipe_fds[1]), SyscallSucceeds());\n// Test starts out as the thread group leader of itself.\nEXPECT_EQ(test_pid, test_tid);\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix flakiness in `Processes::ExecSwapThreadGroupLeader`.
This closes the write end of the pipe earlier in the main test
body, and avoids allocations after fork+clone when building up
the `execve` array's flags.
There may be more obvious ways to do this, let me know :)
PiperOrigin-RevId: 453809395 |
259,853 | 08.06.2022 23:55:21 | 25,200 | c3a7b477f9f08ec04225fe561266a01646ceecc0 | tests: don't use raw threads
We have to use pthreads if we want to use other libc calls. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/processes.cc",
"new_path": "test/syscalls/linux/processes.cc",
"diff": "@@ -116,13 +116,12 @@ TEST(Processes, SetPGIDOfZombie) {\nEXPECT_EQ(status, 0);\n}\n-int WritePIDToPipe(void* arg) {\n- int* pipe_fds = reinterpret_cast<int*>(arg);\n+void WritePIDToPipe(int* pipe_fds) {\npid_t child_pid;\nTEST_PCHECK(child_pid = getpid());\n+ TEST_PCHECK(child_pid != gettid());\nTEST_PCHECK(write(pipe_fds[1], &child_pid, sizeof(child_pid)) ==\nsizeof(child_pid));\n- _exit(0);\n}\nTEST(Processes, TheadSharesSamePID) {\n@@ -131,14 +130,7 @@ TEST(Processes, TheadSharesSamePID) {\npid_t test_pid;\nASSERT_THAT(test_pid = getpid(), SyscallSucceeds());\nEXPECT_NE(test_pid, 0);\n- struct clone_arg {\n- char stack[256] __attribute__((aligned(16)));\n- char stack_ptr[0];\n- } ca;\n- ASSERT_THAT(\n- clone(WritePIDToPipe, ca.stack_ptr,\n- CLONE_THREAD | CLONE_SIGHAND | CLONE_VM | CLONE_FS, pipe_fds),\n- SyscallSucceeds());\n+ ScopedThread([&pipe_fds]() { WritePIDToPipe(pipe_fds); }).Join();\nASSERT_THAT(close(pipe_fds[1]), SyscallSucceeds());\npid_t pid_from_child;\nTEST_PCHECK(read(pipe_fds[0], &pid_from_child, sizeof(pid_from_child)) ==\n"
}
] | Go | Apache License 2.0 | google/gvisor | tests: don't use raw threads
We have to use pthreads if we want to use other libc calls.
PiperOrigin-RevId: 453851326 |
259,868 | 09.06.2022 16:37:07 | 25,200 | cbbcf9344369862c924001bc5e48525e7a4ee854 | Add BuildKite pipeline filegroup. Make platforms_bzl more widely visible. | [
{
"change_type": "MODIFY",
"old_path": "BUILD",
"new_path": "BUILD",
"diff": "@@ -63,6 +63,12 @@ yaml_test(\nschema = \"@github_workflow_schema//file\",\n)\n+filegroup(\n+ name = \"buildkite_pipelines\",\n+ srcs = glob([\".buildkite/*.yaml\"]),\n+ visibility = [\"//:sandbox\"],\n+)\n+\nyaml_test(\nname = \"buildkite_pipelines_test\",\nsrcs = glob([\".buildkite/*.yaml\"]),\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/bazeldefs/BUILD",
"new_path": "tools/bazeldefs/BUILD",
"diff": "@@ -8,7 +8,7 @@ package(\nbzl_library(\nname = \"platforms_bzl\",\nsrcs = [\"platforms.bzl\"],\n- visibility = [\"//visibility:private\"],\n+ visibility = [\"//:sandbox\"],\n)\nbzl_library(\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add BuildKite pipeline filegroup. Make platforms_bzl more widely visible.
PiperOrigin-RevId: 454040412 |
259,868 | 10.06.2022 14:47:03 | 25,200 | 0df51fa5db5415ad487dc9879074ff5aff4427bf | `integration_test`: Ensure Docker has experimental features enabled.
This test relies on `docker checkpoint`, which requires experimental
features to be turned on in Docker. | [
{
"change_type": "MODIFY",
"old_path": "pkg/test/dockerutil/dockerutil.go",
"new_path": "pkg/test/dockerutil/dockerutil.go",
"diff": "@@ -26,6 +26,7 @@ import (\n\"os/exec\"\n\"regexp\"\n\"strconv\"\n+ \"strings\"\n\"time\"\n\"gvisor.dev/gvisor/pkg/test/testutil\"\n@@ -62,6 +63,15 @@ var (\nuseSystemdRgx = regexp.MustCompile(\"\\\\s*(native\\\\.cgroupdriver)\\\\s*=\\\\s*(systemd)\\\\s*\")\n)\n+// PrintDockerConfig prints the whole Docker configuration file to the log.\n+func PrintDockerConfig() {\n+ configBytes, err := ioutil.ReadFile(*config)\n+ if err != nil {\n+ log.Fatalf(\"Cannot read Docker config at %v: %v\", *config, err)\n+ }\n+ log.Printf(\"Docker config (from %v):\\n--------\\n%v\\n--------\\n\", *config, string(configBytes))\n+}\n+\n// EnsureSupportedDockerVersion checks if correct docker is installed.\n//\n// This logs directly to stderr, as it is typically called from a Main wrapper.\n@@ -83,6 +93,19 @@ func EnsureSupportedDockerVersion() {\n}\n}\n+// EnsureDockerExperimentalEnabled ensures that Docker has experimental features enabled.\n+func EnsureDockerExperimentalEnabled() {\n+ cmd := exec.Command(\"docker\", \"version\", \"--format={{.Server.Experimental}}\")\n+ out, err := cmd.CombinedOutput()\n+ if err != nil {\n+ log.Fatalf(\"error running %s: %v\", \"docker version --format='{{.Server.Experimental}}'\", err)\n+ }\n+ if strings.TrimSpace(string(out)) != \"true\" {\n+ PrintDockerConfig()\n+ log.Fatalf(\"Docker is running without experimental features enabled.\")\n+ }\n+}\n+\n// RuntimePath returns the binary path for the current runtime.\nfunc RuntimePath() (string, error) {\nrs, err := runtimeMap()\n"
},
{
"change_type": "MODIFY",
"old_path": "test/e2e/integration_test.go",
"new_path": "test/e2e/integration_test.go",
"diff": "@@ -179,6 +179,7 @@ func TestCheckpointRestore(t *testing.T) {\nif !testutil.IsCheckpointSupported() {\nt.Skip(\"Pause/resume is not supported.\")\n}\n+ dockerutil.EnsureDockerExperimentalEnabled()\nctx := context.Background()\nd := dockerutil.MakeContainer(ctx, t)\n"
}
] | Go | Apache License 2.0 | google/gvisor | `integration_test`: Ensure Docker has experimental features enabled.
This test relies on `docker checkpoint`, which requires experimental
features to be turned on in Docker.
PiperOrigin-RevId: 454246068 |
259,868 | 10.06.2022 15:00:29 | 25,200 | 13fff26c601398cf95e104b29cf32e5fe67af531 | Test runner: Containerize host-networking syscall tests by default. | [
{
"change_type": "MODIFY",
"old_path": "test/runner/defs.bzl",
"new_path": "test/runner/defs.bzl",
"diff": "@@ -71,6 +71,7 @@ def _syscall_test(\nadd_uds_tree = False,\nlisafs = False,\nfuse = False,\n+ container = None,\n**kwargs):\n# Prepend \"runsc\" to non-native platform names.\nfull_platform = platform if platform == \"native\" else \"runsc_\" + platform\n@@ -93,7 +94,7 @@ def _syscall_test(\ntags = []\n# Add the full_platform and file access in a tag to make it easier to run\n- # all the tests on a specific flavor. Use --test_tag_filters=ptrace,file_shared.\n+ # all the tests on a specific flavor. Use --test_tag_filters=runsc_ptrace,file_shared.\ntags = list(tags)\ntags += [full_platform, \"file_\" + file_access]\n@@ -112,7 +113,12 @@ def _syscall_test(\nif platform == \"native\":\ntags.append(\"nogotsan\")\n- container = \"container\" in tags\n+ if container == None:\n+ # Containerize in the following cases:\n+ # - \"container\" is explicitly specified as a tag\n+ # - Running tests natively\n+ # - Running tests with host networking\n+ container = \"container\" in tags or network == \"host\"\nif platform == \"native\":\n# The \"native\" platform supports everything.\n@@ -164,6 +170,7 @@ def syscall_test(\nfuse = False,\nallow_native = True,\ndebug = True,\n+ container = None,\ntags = None,\n**kwargs):\n\"\"\"syscall_test is a macro that will create targets for all platforms.\n@@ -178,6 +185,7 @@ def syscall_test(\nfuse: enable FUSE support.\nallow_native: generate a native test variant.\ndebug: enable debug output.\n+ container: Run the test in a container. If None, determined from other information.\ntags: starting test tags.\n**kwargs: additional test arguments.\n\"\"\"\n@@ -193,6 +201,7 @@ def syscall_test(\nadd_uds_tree = add_uds_tree,\ntags = tags,\ndebug = debug,\n+ container = container,\n**kwargs\n)\n@@ -205,6 +214,7 @@ def syscall_test(\ntags = platform_tags + tags,\nfuse = fuse,\ndebug = debug,\n+ container = container,\n**kwargs\n)\n@@ -218,6 +228,7 @@ def syscall_test(\ntags = platforms[default_platform] + tags + [\"lisafs\"],\ndebug = debug,\nfuse = fuse,\n+ container = container,\nlisafs = True,\n**kwargs\n)\n@@ -230,6 +241,7 @@ def syscall_test(\ntags = platforms.get(default_platform, []) + tags,\ndebug = debug,\nfuse = fuse,\n+ container = container,\noverlay = True,\n**kwargs\n)\n@@ -243,6 +255,7 @@ def syscall_test(\ntags = platforms.get(default_platform, []) + tags,\ndebug = debug,\nfuse = fuse,\n+ container = container,\n**kwargs\n)\nif not use_tmpfs:\n@@ -254,6 +267,7 @@ def syscall_test(\nadd_uds_tree = add_uds_tree,\ntags = platforms.get(default_platform, []) + tags,\ndebug = debug,\n+ container = container,\nfile_access = \"shared\",\nfuse = fuse,\n**kwargs\n"
},
{
"change_type": "MODIFY",
"old_path": "test/runner/main.go",
"new_path": "test/runner/main.go",
"diff": "@@ -50,7 +50,7 @@ var (\noverlay = flag.Bool(\"overlay\", false, \"wrap filesystem mounts with writable tmpfs overlay\")\nfuse = flag.Bool(\"fuse\", false, \"enable FUSE\")\nlisafs = flag.Bool(\"lisafs\", false, \"enable lisafs protocol if vfs2 is also enabled\")\n- container = flag.Bool(\"container\", false, \"run tests in their own namespaces (user ns, network ns, etc), pretending to be root\")\n+ container = flag.Bool(\"container\", false, \"run tests in their own namespaces (user ns, network ns, etc), pretending to be root. Implicitly enabled if network=host, or if using network namespaces\")\nsetupContainerPath = flag.String(\"setup-container\", \"\", \"path to setup_container binary (for use with --container)\")\naddUDSTree = flag.Bool(\"add-uds-tree\", false, \"expose a tree of UDS utilities for use in tests\")\n@@ -64,6 +64,18 @@ const (\nplatformSupportEnvVar = \"GVISOR_PLATFORM_SUPPORT\"\n)\n+// getSetupContainerPath returns the path to the setup_container binary.\n+func getSetupContainerPath() string {\n+ if *setupContainerPath != \"\" {\n+ return *setupContainerPath\n+ }\n+ setupContainer, err := testutil.FindFile(\"test/runner/setup_container/setup_container\")\n+ if err != nil {\n+ fatalf(\"cannot find setup_container: %v\", err)\n+ }\n+ return setupContainer\n+}\n+\n// runTestCaseNative runs the test case directly on the host machine.\nfunc runTestCaseNative(testBin string, tc gtest.TestCase, t *testing.T) {\n// These tests might be running in parallel, so make sure they have a\n@@ -116,33 +128,31 @@ func runTestCaseNative(testBin string, tc gtest.TestCase, t *testing.T) {\ncmd.Stderr = os.Stderr\ncmd.SysProcAttr = &unix.SysProcAttr{}\n- if *container {\n+ if specutils.HasCapabilities(capability.CAP_SYS_ADMIN) {\n+ cmd.SysProcAttr.Cloneflags |= unix.CLONE_NEWUTS\n+ }\n+\n+ if specutils.HasCapabilities(capability.CAP_NET_ADMIN) {\n+ cmd.SysProcAttr.Cloneflags |= unix.CLONE_NEWNET\n+ }\n+\n+ if *container || (cmd.SysProcAttr.Cloneflags&unix.CLONE_NEWNET != 0) {\n// setup_container takes in its target argv as positional arguments.\n- cmd.Path = *setupContainerPath\n+ cmd.Path = getSetupContainerPath()\ncmd.Args = append([]string{cmd.Path}, cmd.Args...)\n- cmd.SysProcAttr = &unix.SysProcAttr{\n- Cloneflags: unix.CLONE_NEWUSER | unix.CLONE_NEWNET | unix.CLONE_NEWIPC | unix.CLONE_NEWUTS,\n+ cmd.SysProcAttr.Cloneflags |= unix.CLONE_NEWUSER | unix.CLONE_NEWNET | unix.CLONE_NEWIPC | unix.CLONE_NEWUTS\n// Set current user/group as root inside the namespace.\n- UidMappings: []syscall.SysProcIDMap{\n+ cmd.SysProcAttr.UidMappings = []syscall.SysProcIDMap{\n{ContainerID: 0, HostID: os.Getuid(), Size: 1},\n- },\n- GidMappings: []syscall.SysProcIDMap{\n+ }\n+ cmd.SysProcAttr.GidMappings = []syscall.SysProcIDMap{\n{ContainerID: 0, HostID: os.Getgid(), Size: 1},\n- },\n- GidMappingsEnableSetgroups: false,\n- Credential: &syscall.Credential{\n+ }\n+ cmd.SysProcAttr.GidMappingsEnableSetgroups = false\n+ cmd.SysProcAttr.Credential = &syscall.Credential{\nUid: 0,\nGid: 0,\n- },\n- }\n}\n-\n- if specutils.HasCapabilities(capability.CAP_SYS_ADMIN) {\n- cmd.SysProcAttr.Cloneflags |= unix.CLONE_NEWUTS\n- }\n-\n- if specutils.HasCapabilities(capability.CAP_NET_ADMIN) {\n- cmd.SysProcAttr.Cloneflags |= unix.CLONE_NEWNET\n}\nif err := cmd.Run(); err != nil {\n@@ -249,6 +259,11 @@ func runRunsc(tc gtest.TestCase, spec *specs.Spec) error {\nGid: 0,\n},\n}\n+ if *container || *network == \"host\" || (cmd.SysProcAttr.Cloneflags&unix.CLONE_NEWNET != 0) {\n+ cmd.SysProcAttr.Cloneflags |= unix.CLONE_NEWNET\n+ cmd.Path = getSetupContainerPath()\n+ cmd.Args = append([]string{cmd.Path}, cmd.Args...)\n+ }\ncmd.Stdout = os.Stdout\ncmd.Stderr = os.Stderr\nsig := make(chan os.Signal, 1)\n@@ -491,13 +506,6 @@ func main() {\npanic(err.Error())\n}\n}\n- if *container && *setupContainerPath == \"\" {\n- setupContainer, err := testutil.FindFile(\"test/runner/setup_container/setup_container\")\n- if err != nil {\n- fatalf(\"cannot find setup_container: %v\", err)\n- }\n- *setupContainerPath = setupContainer\n- }\n// Make sure stdout and stderr are opened with O_APPEND, otherwise logs\n// from outside the sandbox can (and will) stomp on logs from inside\n"
},
{
"change_type": "MODIFY",
"old_path": "test/runner/setup_container/setup_container.cc",
"new_path": "test/runner/setup_container/setup_container.cc",
"diff": "@@ -31,7 +31,7 @@ PosixError SetupContainer() {\nstd::cerr << \"Cannot determine if we have CAP_NET_ADMIN.\" << std::endl;\nreturn have_net_admin.error();\n}\n- if (have_net_admin.ValueOrDie() && !IsRunningOnGvisor()) {\n+ if (have_net_admin.ValueOrDie()) {\nPosixErrorOr<FileDescriptor> sockfd = Socket(AF_INET, SOCK_DGRAM, 0);\nif (!sockfd.ok()) {\nstd::cerr << \"Cannot open socket.\" << std::endl;\n@@ -51,6 +51,11 @@ PosixError SetupContainer() {\nreturn PosixError(errno);\n}\n}\n+ } else {\n+ std::cerr\n+ << \"Capability CAP_NET_ADMIN not granted, so cannot bring up \"\n+ << \"'lo' interface. This may cause host-network-related tests to fail.\"\n+ << std::endl;\n}\nreturn NoError();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -454,7 +454,7 @@ syscall_test(\n)\nsyscall_test(\n- tags = [\"container\"],\n+ container = True,\ntest = \"//test/syscalls/linux:proc_isolated_test\",\n)\n@@ -680,8 +680,8 @@ syscall_test(\nsyscall_test(\nsize = \"large\",\n+ container = True,\nshard_count = most_shards,\n- tags = [\"container\"],\ntest = \"//test/syscalls/linux:socket_inet_loopback_isolated_test\",\n)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Test runner: Containerize host-networking syscall tests by default.
PiperOrigin-RevId: 454248722 |
259,868 | 10.06.2022 15:08:18 | 25,200 | 16a5ced34f90d0e8dd71cf6b6609e81d1d8a37ec | Add `VSYSCALL` capability to platforms definitions.
This can be used to selectively disable tests where vsyscall
functionality is not expected to work on a per-platform basis. | [
{
"change_type": "MODIFY",
"old_path": "test/util/platform_util.cc",
"new_path": "test/util/platform_util.cc",
"diff": "@@ -97,5 +97,23 @@ PlatformSupport PlatformSupportInt3() {\nTEST_CHECK(false);\n}\n+PlatformSupport PlatformSupportVsyscall() {\n+ const char* support = std::getenv(\"GVISOR_PLATFORM_SUPPORT\");\n+ if (support != nullptr) {\n+ if (std::string(support).find(\"VSYSCALL:TRUE\") != std::string::npos) {\n+ return PlatformSupport::Allowed;\n+ }\n+ if (std::string(support).find(\"VSYSCALL:FALSE\") != std::string::npos) {\n+ return PlatformSupport::NotSupported;\n+ }\n+ std::cerr << \"GVISOR_PLATFORM_SUPPORT variable does not contain VSYSCALL \"\n+ \"support information: \"\n+ << support << std::endl;\n+ TEST_CHECK(false);\n+ }\n+ std::cerr << \"GVISOR_PLATFORM_SUPPORT variable undefined\" << std::endl;\n+ TEST_CHECK(false);\n+}\n+\n} // namespace testing\n} // namespace gvisor\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/platform_util.h",
"new_path": "test/util/platform_util.h",
"diff": "@@ -49,8 +49,9 @@ PlatformSupport PlatformSupport32Bit();\nPlatformSupport PlatformSupportAlignmentCheck();\nPlatformSupport PlatformSupportMultiProcess();\nPlatformSupport PlatformSupportInt3();\n+PlatformSupport PlatformSupportVsyscall();\n} // namespace testing\n} // namespace gvisor\n-#endif // GVISOR_TEST_UTIL_PLATFORM_UTL_H_\n+#endif // GVISOR_TEST_UTIL_PLATFORM_UTIL_H_\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/bazeldefs/platforms.bzl",
"new_path": "tools/bazeldefs/platforms.bzl",
"diff": "@@ -12,6 +12,7 @@ _CAPABILITY_32BIT = \"32BIT\"\n_CAPABILITY_ALIGNMENT_CHECK = \"ALIGNMENT_CHECK\"\n_CAPABILITY_MULTIPROCESS = \"MULTIPROCESS\"\n_CAPABILITY_INT3 = \"INT3\"\n+_CAPABILITY_VSYSCALL = \"VSYSCALL\"\n# platform_capabilities maps platform names to a dictionary of capabilities mapped to\n# True (supported) or False (unsupported).\n@@ -21,12 +22,14 @@ platform_capabilities = {\n_CAPABILITY_ALIGNMENT_CHECK: True,\n_CAPABILITY_MULTIPROCESS: True,\n_CAPABILITY_INT3: True,\n+ _CAPABILITY_VSYSCALL: True,\n},\n\"kvm\": {\n_CAPABILITY_32BIT: False,\n_CAPABILITY_ALIGNMENT_CHECK: True,\n_CAPABILITY_MULTIPROCESS: True,\n_CAPABILITY_INT3: False,\n+ _CAPABILITY_VSYSCALL: True,\n},\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add `VSYSCALL` capability to platforms definitions.
This can be used to selectively disable tests where vsyscall
functionality is not expected to work on a per-platform basis.
PiperOrigin-RevId: 454250385 |
259,868 | 10.06.2022 16:05:13 | 25,200 | 6294e603c6856bee9945bdad4f76b54cd633fafd | Disable `RetKillVsyscallCausesDeathBySIGSYS` if `VSYSCALL` isn't supported. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -2241,6 +2241,7 @@ cc_binary(\n\"//test/util:logging\",\n\"//test/util:memory_util\",\n\"//test/util:multiprocess_util\",\n+ \"//test/util:platform_util\",\n\"//test/util:posix_error\",\n\"//test/util:proc_util\",\n\"//test/util:test_util\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/seccomp.cc",
"new_path": "test/syscalls/linux/seccomp.cc",
"diff": "#include \"test/util/logging.h\"\n#include \"test/util/memory_util.h\"\n#include \"test/util/multiprocess_util.h\"\n+#include \"test/util/platform_util.h\"\n#include \"test/util/posix_error.h\"\n#include \"test/util/proc_util.h\"\n#include \"test/util/test_util.h\"\n@@ -216,6 +217,7 @@ time_t vsyscall_time(time_t* t) {\nTEST(SeccompTest, SeccompAppliesToVsyscall) {\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(IsVsyscallEnabled()));\n+ SKIP_IF(PlatformSupportVsyscall() == PlatformSupport::NotSupported);\npid_t const pid = fork();\nif (pid == 0) {\n@@ -246,6 +248,7 @@ TEST(SeccompTest, SeccompAppliesToVsyscall) {\nTEST(SeccompTest, RetKillVsyscallCausesDeathBySIGSYS) {\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(IsVsyscallEnabled()));\n+ SKIP_IF(PlatformSupportVsyscall() == PlatformSupport::NotSupported);\npid_t const pid = fork();\nif (pid == 0) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Disable `RetKillVsyscallCausesDeathBySIGSYS` if `VSYSCALL` isn't supported.
PiperOrigin-RevId: 454260740 |
259,868 | 10.06.2022 16:35:53 | 25,200 | b7c0ac33c9bb06c9b78f8f6555f1399a72a1477a | Add `PRE_BAZEL_INIT` variable to run a command before Bazel server starts.
This is useful for initializing things that the Bazel server container
requires before starting in the first place. | [
{
"change_type": "MODIFY",
"old_path": "tools/bazel.mk",
"new_path": "tools/bazel.mk",
"diff": "## DOCKER_RUN_OPTIONS - Options for the container (default: --privileged, required for tests).\n## DOCKER_NAME - The container name (default: gvisor-bazel-HASH).\n## DOCKER_PRIVILEGED - Docker privileged flags (default: --privileged).\n+## PRE_BAZEL_INIT - If set, run this command with bash outside the Bazel\n+## server container.\n## BAZEL_CACHE - The bazel cache directory (default: detected).\n## GCLOUD_CONFIG - The gcloud config directory (detect: detected).\n## DOCKER_SOCKET - The Docker socket (default: detected).\n@@ -55,6 +57,7 @@ GCLOUD_CONFIG := $(HOME)/.config/gcloud/\nDOCKER_SOCKET := /var/run/docker.sock\nDOCKER_CONFIG := /etc/docker\nDEVICE_FILE ?=\n+PRE_BAZEL_INIT ?=\n##\n## Bazel helpers.\n@@ -152,10 +155,8 @@ endif\n# Add other device file, if specified.\nifneq ($(DEVICE_FILE),)\n-ifneq (,$(wildcard $(DEVICE_FILE)))\nDOCKER_RUN_OPTIONS += --device \"$(DEVICE_FILE):$(DEVICE_FILE)\"\nendif\n-endif\n# Top-level functions.\n#\n@@ -188,6 +189,10 @@ bazel-image: load-default ## Ensures that the local builder exists.\nifneq (true,$(shell $(wrapper echo true)))\nbazel-server: bazel-image ## Ensures that the server exists.\n+ifneq (,$(PRE_BAZEL_INIT))\n+ @$(call header,PRE_BAZEL_INIT)\n+ @bash -euxo pipefail -c \"$(PRE_BAZEL_INIT)\"\n+endif\n@$(call header,DOCKER RUN)\n@docker rm -f $(DOCKER_NAME) 2>/dev/null || true\n@mkdir -p $(BAZEL_CACHE)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add `PRE_BAZEL_INIT` variable to run a command before Bazel server starts.
This is useful for initializing things that the Bazel server container
requires before starting in the first place.
PiperOrigin-RevId: 454265814 |
259,868 | 10.06.2022 17:27:56 | 25,200 | 382499139ef4de6d24bb1058d4fa3c8451fb8293 | BuildKite `pre-command`: Improve log signal-to-noise ratio.
This removes noise from the package installation process (boring and
noisy), and adds logging for the shell commands that run after that
(which are more interesting). | [
{
"change_type": "MODIFY",
"old_path": ".buildkite/hooks/pre-command",
"new_path": ".buildkite/hooks/pre-command",
"diff": "@@ -7,7 +7,7 @@ buildkite-agent artifact download 'tools/bazeldefs/*' . || true\nfunction install_pkgs() {\nexport DEBIAN_FRONTEND=noninteractive\nwhile true; do\n- if sudo -E apt-get update && sudo -E apt-get install -y \"$@\"; then\n+ if sudo -E apt-get update -q && sudo -E apt-get install -qy \"$@\"; then\nbreak\nfi\ndone\n@@ -23,6 +23,8 @@ elif test -n \"$(apt-cache search --names-only \"^linux-gcp-headers-$(uname -r | c\ninstall_pkgs \"linux-gcp-headers-$(uname -r | cut -d- -f1-2)\"\nfi\n+set -x\n+\n# Setup for parallelization with PARTITION and TOTAL_PARTITIONS.\nexport PARTITION=${BUILDKITE_PARALLEL_JOB:-0}\nPARTITION=$((${PARTITION}+1)) # 1-indexed, but PARALLEL_JOB is 0-indexed.\n"
}
] | Go | Apache License 2.0 | google/gvisor | BuildKite `pre-command`: Improve log signal-to-noise ratio.
This removes noise from the package installation process (boring and
noisy), and adds logging for the shell commands that run after that
(which are more interesting).
PiperOrigin-RevId: 454273369 |
259,975 | 13.06.2022 10:48:51 | 25,200 | 0301bb07efabc1b6e441727814fce25cf8a847ca | [bugs] Don't hold root taskset mutex when starting kernel tasks.
Holding the kernel.taskSetRWMutex isn't necessary while calling t.Start() and
doing so can cause a nested locking error. We only need to make sure start is
called on each task once. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/kernel.go",
"new_path": "pkg/sentry/kernel/kernel.go",
"diff": "@@ -1122,11 +1122,18 @@ func (k *Kernel) Start() error {\n// Kernel.SaveTo and need to be resumed. If k was created by NewKernel,\n// this is a no-op.\nk.resumeTimeLocked(k.SupervisorContext())\n- // Start task goroutines.\nk.tasks.mu.RLock()\n- defer k.tasks.mu.RUnlock()\n- for t, tid := range k.tasks.Root.tids {\n- t.Start(tid)\n+ ts := make([]*Task, 0, len(k.tasks.Root.tids))\n+ for t := range k.tasks.Root.tids {\n+ ts = append(ts, t)\n+ }\n+ k.tasks.mu.RUnlock()\n+ // Start task goroutines.\n+ // NOTE(b/235349091): We don't actually need the TaskSet mutex, we just\n+ // need to make sure we only call t.Start() once for each task. Holding the\n+ // mutex for each task start may cause a nested locking error.\n+ for _, t := range ts {\n+ t.Start(t.ThreadID())\n}\nreturn nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | [bugs] Don't hold root taskset mutex when starting kernel tasks.
Holding the kernel.taskSetRWMutex isn't necessary while calling t.Start() and
doing so can cause a nested locking error. We only need to make sure start is
called on each task once.
PiperOrigin-RevId: 454648122 |
259,853 | 13.06.2022 15:02:23 | 25,200 | 5ffcc1f799e31eba3a95d7e2f251ee111656520c | Don't leak network namespaces | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/testutil/kernel.go",
"new_path": "pkg/sentry/fsimpl/testutil/kernel.go",
"diff": "@@ -147,6 +147,7 @@ func CreateTask(ctx context.Context, name string, tc *kernel.ThreadGroup, mntns\nFDTable: k.NewFDTable(),\nUserCounters: k.GetUserCounters(creds.RealKUID),\n}\n+ config.NetworkNamespace.IncRef()\nt, err := k.TaskSet().NewTask(ctx, config)\nif err != nil {\nconfig.ThreadGroup.Release(ctx)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/inet/BUILD",
"new_path": "pkg/sentry/inet/BUILD",
"diff": "@@ -6,6 +6,17 @@ package(\nlicenses = [\"notice\"],\n)\n+go_template_instance(\n+ name = \"namespace_refs\",\n+ out = \"namespace_refs.go\",\n+ package = \"inet\",\n+ prefix = \"namespace\",\n+ template = \"//pkg/refsvfs2:refs_template\",\n+ types = {\n+ \"T\": \"Namespace\",\n+ },\n+)\n+\ngo_template_instance(\nname = \"atomicptr_netns\",\nout = \"atomicptr_netns_unsafe.go\",\n@@ -24,11 +35,14 @@ go_library(\n\"context.go\",\n\"inet.go\",\n\"namespace.go\",\n+ \"namespace_refs.go\",\n\"test_stack.go\",\n],\ndeps = [\n\"//pkg/abi/linux\",\n+ \"//pkg/atomicbitops\",\n\"//pkg/context\",\n+ \"//pkg/refsvfs2\",\n\"//pkg/tcpip\",\n\"//pkg/tcpip/stack\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/inet/inet.go",
"new_path": "pkg/sentry/inet/inet.go",
"diff": "@@ -85,6 +85,9 @@ type Stack interface {\n// Resume restarts the network stack after restore.\nResume()\n+ // Destroy the network stack.\n+ Destroy()\n+\n// RegisteredEndpoints returns all endpoints which are currently registered.\nRegisteredEndpoints() []stack.TransportEndpoint\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/inet/namespace.go",
"new_path": "pkg/sentry/inet/namespace.go",
"diff": "@@ -18,6 +18,8 @@ package inet\n//\n// +stateify savable\ntype Namespace struct {\n+ namespaceRefs\n+\n// stack is the network stack implementation of this network namespace.\nstack Stack `state:\"nosave\"`\n@@ -36,11 +38,13 @@ type Namespace struct {\n// allowing new network namespaces to be created. If creator is nil, no\n// networking will function if the network is namespaced.\nfunc NewRootNamespace(stack Stack, creator NetworkStackCreator) *Namespace {\n- return &Namespace{\n+ n := &Namespace{\nstack: stack,\ncreator: creator,\nisRoot: true,\n}\n+ n.InitRefs()\n+ return n\n}\n// NewNamespace creates a new network namespace from the root.\n@@ -49,9 +53,19 @@ func NewNamespace(root *Namespace) *Namespace {\ncreator: root.creator,\n}\nn.init()\n+ n.InitRefs()\nreturn n\n}\n+// DecRef decrements the Namespace's refcount.\n+func (n *Namespace) DecRef() {\n+ n.namespaceRefs.DecRef(func() {\n+ if s := n.Stack(); s != nil {\n+ s.Destroy()\n+ }\n+ })\n+}\n+\n// Stack returns the network stack of n. Stack may return nil if no network\n// stack is configured.\nfunc (n *Namespace) Stack() Stack {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/inet/test_stack.go",
"new_path": "pkg/sentry/inet/test_stack.go",
"diff": "@@ -50,6 +50,10 @@ func (s *TestStack) Interfaces() map[int32]Interface {\nreturn s.InterfacesMap\n}\n+// Destroy implements Stack.\n+func (s *TestStack) Destroy() {\n+}\n+\n// RemoveInterface implements Stack.\nfunc (s *TestStack) RemoveInterface(idx int32) error {\ndelete(s.InterfacesMap, idx)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/kernel.go",
"new_path": "pkg/sentry/kernel/kernel.go",
"diff": "@@ -1079,6 +1079,7 @@ func (k *Kernel) CreateProcess(args CreateProcessArgs) (*ThreadGroup, ThreadID,\nContainerID: args.ContainerID,\nUserCounters: k.GetUserCounters(args.Credentials.RealKUID),\n}\n+ config.NetworkNamespace.IncRef()\nt, err := k.tasks.NewTask(ctx, config)\nif err != nil {\nreturn nil, 0, err\n@@ -1853,6 +1854,7 @@ func (k *Kernel) Release() {\n}\nk.timekeeper.Destroy()\nk.vdso.Release(ctx)\n+ k.RootNetworkNamespace().DecRef()\n}\n// PopulateNewCgroupHierarchy moves all tasks into a newly created cgroup\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_clone.go",
"new_path": "pkg/sentry/kernel/task_clone.go",
"diff": "@@ -117,7 +117,12 @@ func (t *Task) Clone(args *linux.CloneArgs) (ThreadID, *SyscallControl, error) {\nnetns := t.NetworkNamespace()\nif args.Flags&linux.CLONE_NEWNET != 0 {\nnetns = inet.NewNamespace(netns)\n+ } else {\n+ netns.IncRef()\n}\n+ cu.Add(func() {\n+ netns.DecRef()\n+ })\n// TODO(b/63601033): Implement CLONE_NEWNS.\nmntnsVFS2 := t.mountNamespaceVFS2\n@@ -454,11 +459,13 @@ func (t *Task) Unshare(flags int32) error {\n}\nt.mu.Lock()\n// Can't defer unlock: DecRefs must occur without holding t.mu.\n+ var oldNETNS *inet.Namespace\nif flags&linux.CLONE_NEWNET != 0 {\nif !haveCapSysAdmin {\nt.mu.Unlock()\nreturn linuxerr.EPERM\n}\n+ oldNETNS = t.netns.Load()\nt.netns.Store(inet.NewNamespace(t.netns.Load()))\n}\nif flags&linux.CLONE_NEWUTS != 0 {\n@@ -498,6 +505,9 @@ func (t *Task) Unshare(flags int32) error {\nif oldIPCNS != nil {\noldIPCNS.DecRef(t)\n}\n+ if oldNETNS != nil {\n+ oldNETNS.DecRef()\n+ }\nif oldFDTable != nil {\noldFDTable.DecRef(t)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_exit.go",
"new_path": "pkg/sentry/kernel/task_exit.go",
"diff": "@@ -272,11 +272,13 @@ func (*runExitMain) execute(t *Task) taskRunState {\nmntns := t.mountNamespaceVFS2\nt.mountNamespaceVFS2 = nil\nipcns := t.ipcns\n+ netns := t.NetworkNamespace()\nt.mu.Unlock()\nif mntns != nil {\nmntns.DecRef(t)\n}\nipcns.DecRef(t)\n+ netns.DecRef()\n// If this is the last task to exit from the thread group, release the\n// thread group's resources.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_start.go",
"new_path": "pkg/sentry/kernel/task_start.go",
"diff": "@@ -115,6 +115,7 @@ func (ts *TaskSet) NewTask(ctx context.Context, cfg *TaskConfig) (*Task, error)\ncfg.FSContext.DecRef(ctx)\ncfg.FDTable.DecRef(ctx)\ncfg.IPCNamespace.DecRef(ctx)\n+ cfg.NetworkNamespace.DecRef()\nif cfg.MountNamespaceVFS2 != nil {\ncfg.MountNamespaceVFS2.DecRef(ctx)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/hostinet/stack.go",
"new_path": "pkg/sentry/socket/hostinet/stack.go",
"diff": "@@ -65,6 +65,10 @@ type Stack struct {\nnetSNMPFile *os.File\n}\n+// Destroy implements inet.Stack.Destroy.\n+func (*Stack) Destroy() {\n+}\n+\n// NewStack returns an empty Stack containing no configuration.\nfunc NewStack() *Stack {\nreturn &Stack{\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/stack.go",
"new_path": "pkg/sentry/socket/netstack/stack.go",
"diff": "@@ -37,6 +37,11 @@ type Stack struct {\nStack *stack.Stack `state:\"manual\"`\n}\n+// Destroy implements inet.Stack.Destroy.\n+func (s *Stack) Destroy() {\n+ s.Stack.Close()\n+}\n+\n// SupportsIPv6 implements Stack.SupportsIPv6.\nfunc (s *Stack) SupportsIPv6() bool {\nreturn s.Stack.CheckNetworkProtocol(ipv6.ProtocolNumber)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Don't leak network namespaces
PiperOrigin-RevId: 454707336 |
259,885 | 13.06.2022 18:11:30 | 25,200 | 82498d087ef8fa85ba4537406522a500a7b92a26 | Don't hold MM.activeMu when calling MM.vmaMapsEntryLocked().
Cloned from CL by 'hg patch'. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/debug.go",
"new_path": "pkg/sentry/mm/debug.go",
"diff": "@@ -40,24 +40,22 @@ func (mm *MemoryManager) String() string {\n// DebugString returns a string containing information about mm for debugging.\nfunc (mm *MemoryManager) DebugString(ctx context.Context) string {\n+ var b bytes.Buffer\n+\nmm.mappingMu.RLock()\ndefer mm.mappingMu.RUnlock()\n- mm.activeMu.RLock()\n- defer mm.activeMu.RUnlock()\n- return mm.debugStringLocked(ctx)\n-}\n-\n-// Preconditions: mm.mappingMu and mm.activeMu must be locked.\n-func (mm *MemoryManager) debugStringLocked(ctx context.Context) string {\n- var b bytes.Buffer\nb.WriteString(\"VMAs:\\n\")\nfor vseg := mm.vmas.FirstSegment(); vseg.Ok(); vseg = vseg.NextSegment() {\nb.Write(mm.vmaMapsEntryLocked(ctx, vseg))\n}\n+\n+ mm.activeMu.RLock()\n+ defer mm.activeMu.RUnlock()\nb.WriteString(\"PMAs:\\n\")\nfor pseg := mm.pmas.FirstSegment(); pseg.Ok(); pseg = pseg.NextSegment() {\nb.Write(pseg.debugStringEntryLocked())\n}\n+\nreturn string(b.Bytes())\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Don't hold MM.activeMu when calling MM.vmaMapsEntryLocked().
Cloned from CL 446797388 by 'hg patch'.
PiperOrigin-RevId: 454742145 |
259,891 | 14.06.2022 11:58:26 | 25,200 | 758a425bbc2e40cf789c521024533574ca1770e5 | shrink DataTransferStressTest | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_generic_stress.cc",
"new_path": "test/syscalls/linux/socket_generic_stress.cc",
"diff": "@@ -193,9 +193,6 @@ INSTANTIATE_TEST_SUITE_P(\nusing DataTransferStressTest = SocketPairTest;\nTEST_P(DataTransferStressTest, BigDataTransfer) {\n- // TODO(b/165912341): These are too slow on KVM platform with nested virt.\n- SKIP_IF(GvisorPlatform() == Platform::kKVM);\n-\nconst std::unique_ptr<SocketPair> sockets =\nASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\nint client_fd = sockets->first_fd();\n@@ -218,9 +215,12 @@ TEST_P(DataTransferStressTest, BigDataTransfer) {\nASSERT_THAT(shutdown(server_fd, SHUT_WR), SyscallSucceeds());\n});\n+ // Tests can be prohibitively slow on the KVM platform with nested virt.\n+ const int kShift = GvisorPlatform() == Platform::kKVM ? 10 : 20;\n+\nconst std::string chunk = \"Though this upload be but little, it is fierce.\";\nstd::string big_string;\n- while (big_string.size() < 31 << 20) {\n+ while (big_string.size() < 31 << kShift) {\nbig_string += chunk;\n}\nabsl::string_view data = big_string;\n@@ -236,7 +236,7 @@ TEST_P(DataTransferStressTest, BigDataTransfer) {\n});\nstd::string buf;\n- buf.resize(1 << 20);\n+ buf.resize(1 << kShift);\nwhile (!data.empty()) {\nssize_t n = read(client_fd, buf.data(), buf.size());\nASSERT_GE(n, 0);\n"
}
] | Go | Apache License 2.0 | google/gvisor | shrink DataTransferStressTest
PiperOrigin-RevId: 454921228 |
260,004 | 14.06.2022 12:03:43 | 25,200 | ebadfe7702fe745bf451c5538be72eacfc7f397c | Allow IPv6 only stack to use UDP endpoints
Check if stack supports IPv4 before registering an IPv6 endpoint as
dual-stack. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/datagram_test.go",
"new_path": "pkg/tcpip/transport/datagram_test.go",
"diff": "@@ -1016,7 +1016,7 @@ func TestIPv6PacketInfo(t *testing.T) {\nfor _, test := range tests {\nt.Run(test.name, func(t *testing.T) {\ns := stack.New(stack.Options{\n- NetworkProtocols: []stack.NetworkProtocolFactory{ipv6.NewProtocol, ipv4.NewProtocol},\n+ NetworkProtocols: []stack.NetworkProtocolFactory{ipv6.NewProtocol},\nTransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol},\nRawFactory: &raw.EndpointFactory{},\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -653,7 +653,7 @@ func (e *endpoint) Connect(addr tcpip.FullAddress) tcpip.Error {\n// packets on a different network protocol, so we register both even if\n// v6only is set to false and this is an ipv6 endpoint.\nnetProtos := []tcpip.NetworkProtocolNumber{netProto}\n- if netProto == header.IPv6ProtocolNumber && !e.ops.GetV6Only() {\n+ if netProto == header.IPv6ProtocolNumber && !e.ops.GetV6Only() && e.stack.CheckNetworkProtocol(header.IPv4ProtocolNumber) {\nnetProtos = []tcpip.NetworkProtocolNumber{\nheader.IPv4ProtocolNumber,\nheader.IPv6ProtocolNumber,\n@@ -790,7 +790,7 @@ func (e *endpoint) bindLocked(addr tcpip.FullAddress) tcpip.Error {\n// wildcard (empty) address, and this is an IPv6 endpoint with v6only\n// set to false.\nnetProtos := []tcpip.NetworkProtocolNumber{boundNetProto}\n- if boundNetProto == header.IPv6ProtocolNumber && !e.ops.GetV6Only() && boundAddr == \"\" {\n+ if boundNetProto == header.IPv6ProtocolNumber && !e.ops.GetV6Only() && boundAddr == \"\" && e.stack.CheckNetworkProtocol(header.IPv4ProtocolNumber) {\nnetProtos = []tcpip.NetworkProtocolNumber{\nheader.IPv6ProtocolNumber,\nheader.IPv4ProtocolNumber,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow IPv6 only stack to use UDP endpoints
Check if stack supports IPv4 before registering an IPv6 endpoint as
dual-stack.
PiperOrigin-RevId: 454922614 |
259,853 | 14.06.2022 14:45:20 | 25,200 | 6e662d0262c7827ab6fff7373e563f2c1bab45a1 | buildkite: move "Build everything" upper in the list
It runs for a long time and so it would be good to run it
earlier. | [
{
"change_type": "MODIFY",
"old_path": ".buildkite/pipeline.yaml",
"new_path": ".buildkite/pipeline.yaml",
"diff": "@@ -59,6 +59,13 @@ steps:\nlabel: \":fire: Smoke race tests\"\ncommand: make smoke-race-tests\n+ # Build everything.\n+ - <<: *common\n+ label: \":world_map: Build everything\"\n+ command: \"make build OPTIONS=--build_tag_filters=-nogo TARGETS=//...\"\n+ agents:\n+ arch: \"amd64\"\n+\n# Check that the Go branch builds. This is not technically required, as this build is maintained\n# as a GitHub action in order to preserve this maintaince across forks. However, providing the\n# action here may provide easier debuggability and diagnosis on failure.\n@@ -364,13 +371,6 @@ steps:\narch: \"amd64\"\nos: \"ubuntu\"\n- # Build everything.\n- - <<: *common\n- label: \":world_map: Build everything\"\n- command: \"make build OPTIONS=--build_tag_filters=-nogo TARGETS=//...\"\n- agents:\n- arch: \"amd64\"\n-\n# Run basic benchmarks smoke tests (no upload).\n- <<: *common\nlabel: \":fire: Benchmarks smoke test\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | buildkite: move "Build everything" upper in the list
It runs for a long time and so it would be good to run it
earlier.
PiperOrigin-RevId: 454960320 |
259,891 | 14.06.2022 20:01:58 | 25,200 | c54948f3c1940071f1690651b533e22977481de4 | notify users of common reasons for failing to create a raw socket
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/log/BUILD",
"new_path": "pkg/log/BUILD",
"diff": "@@ -9,6 +9,7 @@ go_library(\n\"json.go\",\n\"json_k8s.go\",\n\"log.go\",\n+ \"rate_limited.go\",\n],\nmarshal = False,\nstateify = False,\n@@ -18,6 +19,7 @@ go_library(\ndeps = [\n\"//pkg/linewriter\",\n\"//pkg/sync\",\n+ \"@org_golang_x_time//rate:go_default_library\",\n],\n)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/log/rate_limited.go",
"diff": "+// Copyright 2022 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 log\n+\n+import (\n+ \"time\"\n+\n+ \"golang.org/x/time/rate\"\n+)\n+\n+type rateLimitedLogger struct {\n+ logger Logger\n+ limit *rate.Limiter\n+}\n+\n+func (rl *rateLimitedLogger) Debugf(format string, v ...interface{}) {\n+ if rl.limit.Allow() {\n+ rl.logger.Debugf(format, v...)\n+ }\n+}\n+\n+func (rl *rateLimitedLogger) Infof(format string, v ...interface{}) {\n+ if rl.limit.Allow() {\n+ rl.logger.Infof(format, v...)\n+ }\n+}\n+\n+func (rl *rateLimitedLogger) Warningf(format string, v ...interface{}) {\n+ if rl.limit.Allow() {\n+ rl.logger.Warningf(format, v...)\n+ }\n+}\n+\n+func (rl *rateLimitedLogger) IsLogging(level Level) bool {\n+ return rl.logger.IsLogging(level)\n+}\n+\n+// BasicRateLimitedLogger returns a Logger that logs to the global logger no\n+// more than once per the provided duration.\n+func BasicRateLimitedLogger(every time.Duration) Logger {\n+ return RateLimitedLogger(Log(), every)\n+}\n+\n+// RateLimitedLogger returns a Logger that logs to the provided logger no more\n+// than once per the provided duration.\n+func RateLimitedLogger(logger Logger, every time.Duration) Logger {\n+ return &rateLimitedLogger{\n+ logger: logger,\n+ limit: rate.NewLimiter(rate.Every(every), 1),\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/provider.go",
"new_path": "pkg/sentry/socket/netstack/provider.go",
"diff": "package netstack\nimport (\n+ \"time\"\n+\n\"golang.org/x/sys/unix\"\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/fs\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n@@ -40,6 +43,8 @@ type provider struct {\nnetProto tcpip.NetworkProtocolNumber\n}\n+var rawMissingLogger = log.BasicRateLimitedLogger(time.Minute)\n+\n// getTransportProtocol figures out transport protocol. Currently only TCP,\n// UDP, and ICMP are supported. The bool return value is true when this socket\n// is associated with a transport protocol. This is only false for SOCK_RAW,\n@@ -66,6 +71,7 @@ func getTransportProtocol(ctx context.Context, stype linux.SockType, protocol in\n// Raw sockets require CAP_NET_RAW.\ncreds := auth.CredentialsFromContext(ctx)\nif !creds.HasCapability(linux.CAP_NET_RAW) {\n+ rawMissingLogger.Infof(\"A process tried to create a raw socket without CAP_NET_RAW. Should the container config enable CAP_NET_RAW?\")\nreturn 0, true, syserr.ErrNotPermitted\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/provider_vfs2.go",
"new_path": "pkg/sentry/socket/netstack/provider_vfs2.go",
"diff": "@@ -86,6 +86,7 @@ func packetSocketVFS2(t *kernel.Task, epStack *Stack, stype linux.SockType, prot\n// Packet sockets require CAP_NET_RAW.\ncreds := auth.CredentialsFromContext(t)\nif !creds.HasCapability(linux.CAP_NET_RAW) {\n+ rawMissingLogger.Infof(\"A process tried to create a raw socket without CAP_NET_RAW. Should the container config enable CAP_NET_RAW?\")\nreturn nil, syserr.ErrNotPermitted\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -30,6 +30,7 @@ import (\n\"golang.org/x/time/rate\"\n\"gvisor.dev/gvisor/pkg/atomicbitops\"\n\"gvisor.dev/gvisor/pkg/buffer\"\n+ \"gvisor.dev/gvisor/pkg/log\"\ncryptorand \"gvisor.dev/gvisor/pkg/rand\"\n\"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n@@ -64,6 +65,8 @@ func (u *uniqueIDGenerator) UniqueID() uint64 {\nreturn ((*atomicbitops.Uint64)(u)).Add(1)\n}\n+var netRawMissingLogger = log.BasicRateLimitedLogger(time.Minute)\n+\n// Stack is a networking stack, with all supported protocols, NICs, and route\n// table.\n//\n@@ -712,6 +715,7 @@ func (s *Stack) NewEndpoint(transport tcpip.TransportProtocolNumber, network tcp\n// of address.\nfunc (s *Stack) NewRawEndpoint(transport tcpip.TransportProtocolNumber, network tcpip.NetworkProtocolNumber, waiterQueue *waiter.Queue, associated bool) (tcpip.Endpoint, tcpip.Error) {\nif s.rawFactory == nil {\n+ netRawMissingLogger.Infof(\"A process tried to create a raw socket, but --net-raw was not specified. Should runsc be run with --net-raw?\")\nreturn nil, &tcpip.ErrNotPermitted{}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | notify users of common reasons for failing to create a raw socket
Fixes #199
PiperOrigin-RevId: 455018292 |
259,858 | 14.06.2022 21:20:35 | 25,200 | 1ff543e17ee355943abfba33be59ad771bb88095 | Handle cross-package global guards.
Updates | [
{
"change_type": "MODIFY",
"old_path": "tools/checklocks/analysis.go",
"new_path": "tools/checklocks/analysis.go",
"diff": "@@ -322,9 +322,17 @@ func (pc *passContext) checkFieldAccess(inst almostInst, structObj ssa.Value, fi\npc.checkGuards(inst, structObj, fieldObj, ls, isWrite)\n}\n+// noReferrers wraps an instruction as an almostInst.\n+type noReferrers struct {\n+ ssa.Instruction\n+}\n+\n+// Referrers implements almostInst.Referrers.\n+func (noReferrers) Referrers() *[]ssa.Instruction { return nil }\n+\n// checkGlobalAccess checks the validity of a global access.\n-func (pc *passContext) checkGlobalAccess(g *ssa.Global, ls *lockState, isWrite bool) {\n- pc.checkGuards(g, g, g.Object(), ls, isWrite)\n+func (pc *passContext) checkGlobalAccess(inst ssa.Instruction, g *ssa.Global, ls *lockState, isWrite bool) {\n+ pc.checkGuards(noReferrers{inst}, g, g.Object(), ls, isWrite)\n}\nfunc (pc *passContext) checkCall(call callCommon, lff *lockFunctionFacts, ls *lockState) {\n@@ -592,7 +600,7 @@ func (pc *passContext) checkInstruction(inst ssa.Instruction, lff *lockFunctionF\ncontinue\n}\n_, isWrite := inst.(*ssa.Store)\n- pc.checkGlobalAccess(g, ls, isWrite)\n+ pc.checkGlobalAccess(inst, g, ls, isWrite)\n}\n// Process the instruction.\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/checklocks/facts.go",
"new_path": "tools/checklocks/facts.go",
"diff": "@@ -167,6 +167,9 @@ type globalGuard struct {\n// ObjectName indicates the object from which resolution should occur.\nObjectName string\n+ // PackageName is the package where the object lives.\n+ PackageName string\n+\n// FieldList is the traversal path from object.\nFieldList fieldList\n}\n@@ -179,7 +182,11 @@ type ssaPackager interface {\n// resolveCommon implements resolution for all cases.\nfunc (g *globalGuard) resolveCommon(pc *passContext, ls *lockState) resolvedValue {\nstate := pc.pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA)\n- v := state.Pkg.Members[g.ObjectName].(ssa.Value)\n+ pkg := state.Pkg\n+ if g.PackageName != \"\" && g.PackageName != state.Pkg.Pkg.Path() {\n+ pkg = state.Pkg.Prog.ImportedPackage(g.PackageName)\n+ }\n+ v := pkg.Members[g.ObjectName].(ssa.Value)\nreturn makeResolvedValue(v, g.FieldList)\n}\n@@ -628,6 +635,7 @@ func (pc *passContext) findGlobalGuard(pos token.Pos, guardName string) (*global\n}\nreturn &globalGuard{\nObjectName: parts[0],\n+ PackageName: pc.pass.Pkg.Path(),\nFieldList: fl,\n}, true\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/checklocks/test/BUILD",
"new_path": "tools/checklocks/test/BUILD",
"diff": "@@ -27,4 +27,5 @@ go_library(\n# control expected failures for analysis.\nmarshal = False,\nstateify = False,\n+ deps = [\"//tools/checklocks/test/crosspkg\"],\n)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tools/checklocks/test/crosspkg/BUILD",
"diff": "+load(\"//tools:defs.bzl\", \"go_library\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_library(\n+ name = \"crosspkg\",\n+ srcs = [\"crosspkg.go\"],\n+ # See next level up.\n+ marshal = False,\n+ stateify = False,\n+ visibility = [\"//tools/checklocks/test:__pkg__\"],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tools/checklocks/test/crosspkg/crosspkg.go",
"diff": "+// Copyright 2022 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 crosspkg is a second package for testing.\n+package crosspkg\n+\n+import (\n+ \"sync\"\n+)\n+\n+var (\n+ // +checklocks:FooMu\n+ Foo int\n+ FooMu sync.Mutex\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/checklocks/test/globals.go",
"new_path": "tools/checklocks/test/globals.go",
"diff": "@@ -16,6 +16,8 @@ package test\nimport (\n\"sync\"\n+\n+ \"gvisor.dev/gvisor/tools/checklocks/test/crosspkg\"\n)\nvar (\n@@ -83,3 +85,13 @@ func testGlobalInvalid() {\notherStruct.guardedField2 = 1 // +checklocksfail\notherStruct.guardedField3 = 1 // +checklocksfail\n}\n+\n+func testCrosspkgGlobalValid() {\n+ crosspkg.FooMu.Lock()\n+ crosspkg.Foo = 1\n+ crosspkg.FooMu.Unlock()\n+}\n+\n+func testCrosspkgGlobalInvalid() {\n+ crosspkg.Foo = 1 // +checklocksfail\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Handle cross-package global guards.
Updates #7721
PiperOrigin-RevId: 455029306 |
259,992 | 15.06.2022 13:37:13 | 25,200 | 6258291815e823034218fc617c3fc70978d7137b | Small fixes to trace points
Don't collect `cwd` when task root is not present anymore, e.g. zombie.
Limit the size allocated for address in `connect(2)`.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/seccheck.go",
"new_path": "pkg/sentry/kernel/seccheck.go",
"diff": "@@ -49,13 +49,15 @@ func LoadSeccheckDataLocked(t *Task, mask seccheck.FieldMask, info *pb.ContextDa\ninfo.ContainerId = t.tg.leader.ContainerID()\n}\nif mask.Contains(seccheck.FieldCtxtCwd) {\n- root := t.FSContext().RootDirectoryVFS2()\n+ if root := t.FSContext().RootDirectoryVFS2(); root.Ok() {\ndefer root.DecRef(t)\n- wd := t.FSContext().WorkingDirectoryVFS2()\n+ if wd := t.FSContext().WorkingDirectoryVFS2(); wd.Ok() {\ndefer wd.DecRef(t)\nvfsObj := root.Mount().Filesystem().VirtualFilesystem()\ninfo.Cwd, _ = vfsObj.PathnameWithDeleted(t, root, wd)\n}\n+ }\n+ }\nif mask.Contains(seccheck.FieldCtxtProcessName) {\ninfo.ProcessName = t.Name()\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/points.go",
"new_path": "pkg/sentry/syscalls/linux/points.go",
"diff": "@@ -191,10 +191,7 @@ func PointConnect(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextD\naddr := info.Args[1].Pointer()\naddrlen := info.Args[2].Uint()\n- if addr > 0 {\n- p.Address = make([]byte, addrlen)\n- _, _ = t.CopyInBytes(addr, p.Address)\n- }\n+ p.Address, _ = CaptureAddress(t, addr, addrlen)\nif fields.Local.Contains(seccheck.FieldSyscallPath) {\np.FdPath = getFilePath(t, int32(p.Fd))\n"
}
] | Go | Apache License 2.0 | google/gvisor | Small fixes to trace points
Don't collect `cwd` when task root is not present anymore, e.g. zombie.
Limit the size allocated for address in `connect(2)`.
Updates #4805
PiperOrigin-RevId: 455208465 |
259,992 | 15.06.2022 16:10:10 | 25,200 | b252543133681c44bccdabf682b3afc447fd4702 | Restrict checkers.remote visibility
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/checkers/remote/remote.go",
"new_path": "pkg/sentry/seccheck/checkers/remote/remote.go",
"diff": "@@ -36,26 +36,26 @@ import (\nfunc init() {\nseccheck.RegisterSink(seccheck.SinkDesc{\nName: \"remote\",\n- Setup: Setup,\n- New: New,\n+ Setup: setupSink,\n+ New: new,\n})\n}\n-// Remote sends a serialized point to a remote process asynchronously over a\n+// remote sends a serialized point to a remote process asynchronously over a\n// SOCK_SEQPACKET Unix-domain socket. Each message corresponds to a single\n// serialized point proto, preceded by a standard header. If the point cannot\n// be sent, e.g. buffer full, the point is dropped on the floor to avoid\n// delaying/hanging indefinitely the application.\n-type Remote struct {\n+type remote struct {\nendpoint *fd.FD\n}\n-var _ seccheck.Checker = (*Remote)(nil)\n+var _ seccheck.Checker = (*remote)(nil)\n-// Setup starts the connection to the remote process and returns a file that\n+// setupSink starts the connection to the remote process and returns a file that\n// can be used to communicate with it. The caller is responsible to close to\n// file.\n-func Setup(config map[string]interface{}) (*os.File, error) {\n+func setupSink(config map[string]interface{}) (*os.File, error) {\naddrOpaque, ok := config[\"endpoint\"]\nif !ok {\nreturn nil, fmt.Errorf(\"endpoint not present in configuration\")\n@@ -119,16 +119,16 @@ func setup(path string) (*os.File, error) {\nreturn f, nil\n}\n-// New creates a new Remote checker.\n-func New(_ map[string]interface{}, endpoint *fd.FD) (seccheck.Checker, error) {\n+// new creates a new Remote checker.\n+func new(_ map[string]interface{}, endpoint *fd.FD) (seccheck.Checker, error) {\nif endpoint == nil {\nreturn nil, fmt.Errorf(\"remote sink requires an endpoint\")\n}\n- return &Remote{endpoint: endpoint}, nil\n+ return &remote{endpoint: endpoint}, nil\n}\n// Stop implements seccheck.Checker.\n-func (r *Remote) Stop() {\n+func (r *remote) Stop() {\nif r.endpoint != nil {\n// It's possible to race with Point firing, but in the worst case they will\n// simply fail to be delivered.\n@@ -136,7 +136,7 @@ func (r *Remote) Stop() {\n}\n}\n-func (r *Remote) write(msg proto.Message, msgType pb.MessageType) {\n+func (r *remote) write(msg proto.Message, msgType pb.MessageType) {\nout, err := proto.Marshal(msg)\nif err != nil {\nlog.Debugf(\"Marshal(%+v): %v\", msg, err)\n@@ -158,43 +158,43 @@ func (r *Remote) write(msg proto.Message, msgType pb.MessageType) {\n}\n// Clone implements seccheck.Checker.\n-func (r *Remote) Clone(_ context.Context, _ seccheck.FieldSet, info *pb.CloneInfo) error {\n+func (r *remote) Clone(_ context.Context, _ seccheck.FieldSet, info *pb.CloneInfo) error {\nr.write(info, pb.MessageType_MESSAGE_SENTRY_CLONE)\nreturn nil\n}\n// Execve implements seccheck.Checker.\n-func (r *Remote) Execve(_ context.Context, _ seccheck.FieldSet, info *pb.ExecveInfo) error {\n+func (r *remote) Execve(_ context.Context, _ seccheck.FieldSet, info *pb.ExecveInfo) error {\nr.write(info, pb.MessageType_MESSAGE_SENTRY_EXEC)\nreturn nil\n}\n// ExitNotifyParent implements seccheck.Checker.\n-func (r *Remote) ExitNotifyParent(_ context.Context, _ seccheck.FieldSet, info *pb.ExitNotifyParentInfo) error {\n+func (r *remote) ExitNotifyParent(_ context.Context, _ seccheck.FieldSet, info *pb.ExitNotifyParentInfo) error {\nr.write(info, pb.MessageType_MESSAGE_SENTRY_EXIT_NOTIFY_PARENT)\nreturn nil\n}\n// TaskExit implements seccheck.Checker.\n-func (r *Remote) TaskExit(_ context.Context, _ seccheck.FieldSet, info *pb.TaskExit) error {\n+func (r *remote) TaskExit(_ context.Context, _ seccheck.FieldSet, info *pb.TaskExit) error {\nr.write(info, pb.MessageType_MESSAGE_SENTRY_TASK_EXIT)\nreturn nil\n}\n// ContainerStart implements seccheck.Checker.\n-func (r *Remote) ContainerStart(_ context.Context, _ seccheck.FieldSet, info *pb.Start) error {\n+func (r *remote) ContainerStart(_ context.Context, _ seccheck.FieldSet, info *pb.Start) error {\nr.write(info, pb.MessageType_MESSAGE_CONTAINER_START)\nreturn nil\n}\n// RawSyscall implements seccheck.Checker.\n-func (r *Remote) RawSyscall(_ context.Context, _ seccheck.FieldSet, info *pb.Syscall) error {\n+func (r *remote) RawSyscall(_ context.Context, _ seccheck.FieldSet, info *pb.Syscall) error {\nr.write(info, pb.MessageType_MESSAGE_SYSCALL_RAW)\nreturn nil\n}\n// Syscall implements seccheck.Checker.\n-func (r *Remote) Syscall(ctx context.Context, fields seccheck.FieldSet, ctxData *pb.ContextData, msgType pb.MessageType, msg proto.Message) error {\n+func (r *remote) Syscall(ctx context.Context, fields seccheck.FieldSet, ctxData *pb.ContextData, msgType pb.MessageType, msg proto.Message) error {\nr.write(msg, msgType)\nreturn nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/checkers/remote/remote_test.go",
"new_path": "pkg/sentry/seccheck/checkers/remote/remote_test.go",
"diff": "@@ -126,7 +126,7 @@ func TestBasic(t *testing.T) {\n}\n_ = endpoint.Close()\n- r, err := New(nil, endpointFD)\n+ r, err := new(nil, endpointFD)\nif err != nil {\nt.Fatalf(\"New(): %v\", err)\n}\n@@ -205,7 +205,7 @@ func TestExample(t *testing.T) {\n}\n_ = endpoint.Close()\n- r, err := New(nil, endpointFD)\n+ r, err := new(nil, endpointFD)\nif err != nil {\nt.Fatalf(\"New(): %v\", err)\n}\n@@ -247,7 +247,7 @@ func BenchmarkSmall(t *testing.B) {\n}\n_ = endpoint.Close()\n- r, err := New(nil, endpointFD)\n+ r, err := new(nil, endpointFD)\nif err != nil {\nt.Fatalf(\"New(): %v\", err)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Restrict checkers.remote visibility
Updates #4805
PiperOrigin-RevId: 455242654 |
259,907 | 15.06.2022 19:04:50 | 25,200 | 8011b8d6d298cb9bbdd3656a6f0d9ba4c5b1f955 | Make anonfs return ENOTDIR for open(O_DIRECTORY) calls.
All anonfs dentries are non-directories. So all FilesystemImpl
methods that would require an anonDentry to be a directory should
return ENOTDIR. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/anonfs.go",
"new_path": "pkg/sentry/vfs/anonfs.go",
"diff": "@@ -100,7 +100,7 @@ func (fs *anonFilesystem) Sync(ctx context.Context) error {\n// AccessAt implements vfs.Filesystem.Impl.AccessAt.\nfunc (fs *anonFilesystem) AccessAt(ctx context.Context, rp *ResolvingPath, creds *auth.Credentials, ats AccessTypes) error {\n- if !rp.Done() {\n+ if !rp.Done() || rp.MustBeDir() {\nreturn linuxerr.ENOTDIR\n}\nreturn GenericCheckPermissions(creds, ats, anonFileMode, anonFileUID, anonFileGID)\n@@ -108,7 +108,7 @@ func (fs *anonFilesystem) AccessAt(ctx context.Context, rp *ResolvingPath, creds\n// GetDentryAt implements FilesystemImpl.GetDentryAt.\nfunc (fs *anonFilesystem) GetDentryAt(ctx context.Context, rp *ResolvingPath, opts GetDentryOptions) (*Dentry, error) {\n- if !rp.Done() {\n+ if !rp.Done() || rp.MustBeDir() {\nreturn nil, linuxerr.ENOTDIR\n}\nif opts.CheckSearchable {\n@@ -153,7 +153,7 @@ func (fs *anonFilesystem) MknodAt(ctx context.Context, rp *ResolvingPath, opts M\n// OpenAt implements FilesystemImpl.OpenAt.\nfunc (fs *anonFilesystem) OpenAt(ctx context.Context, rp *ResolvingPath, opts OpenOptions) (*FileDescription, error) {\n- if !rp.Done() {\n+ if !rp.Done() || rp.MustBeDir() {\nreturn nil, linuxerr.ENOTDIR\n}\nreturn nil, linuxerr.ENODEV\n@@ -161,7 +161,7 @@ func (fs *anonFilesystem) OpenAt(ctx context.Context, rp *ResolvingPath, opts Op\n// ReadlinkAt implements FilesystemImpl.ReadlinkAt.\nfunc (fs *anonFilesystem) ReadlinkAt(ctx context.Context, rp *ResolvingPath) (string, error) {\n- if !rp.Done() {\n+ if !rp.Done() || rp.MustBeDir() {\nreturn \"\", linuxerr.ENOTDIR\n}\nreturn \"\", linuxerr.EINVAL\n@@ -185,7 +185,7 @@ func (fs *anonFilesystem) RmdirAt(ctx context.Context, rp *ResolvingPath) error\n// SetStatAt implements FilesystemImpl.SetStatAt.\nfunc (fs *anonFilesystem) SetStatAt(ctx context.Context, rp *ResolvingPath, opts SetStatOptions) error {\n- if !rp.Done() {\n+ if !rp.Done() || rp.MustBeDir() {\nreturn linuxerr.ENOTDIR\n}\n// Linux actually permits anon_inode_inode's metadata to be set, which is\n@@ -196,7 +196,7 @@ func (fs *anonFilesystem) SetStatAt(ctx context.Context, rp *ResolvingPath, opts\n// StatAt implements FilesystemImpl.StatAt.\nfunc (fs *anonFilesystem) StatAt(ctx context.Context, rp *ResolvingPath, opts StatOptions) (linux.Statx, error) {\n- if !rp.Done() {\n+ if !rp.Done() || rp.MustBeDir() {\nreturn linux.Statx{}, linuxerr.ENOTDIR\n}\n// See fs/anon_inodes.c:anon_inode_init() => fs/libfs.c:alloc_anon_inode().\n@@ -217,7 +217,7 @@ func (fs *anonFilesystem) StatAt(ctx context.Context, rp *ResolvingPath, opts St\n// StatFSAt implements FilesystemImpl.StatFSAt.\nfunc (fs *anonFilesystem) StatFSAt(ctx context.Context, rp *ResolvingPath) (linux.Statfs, error) {\n- if !rp.Done() {\n+ if !rp.Done() || rp.MustBeDir() {\nreturn linux.Statfs{}, linuxerr.ENOTDIR\n}\nreturn linux.Statfs{\n@@ -255,7 +255,7 @@ func (fs *anonFilesystem) BoundEndpointAt(ctx context.Context, rp *ResolvingPath\n// ListXattrAt implements FilesystemImpl.ListXattrAt.\nfunc (fs *anonFilesystem) ListXattrAt(ctx context.Context, rp *ResolvingPath, size uint64) ([]string, error) {\n- if !rp.Done() {\n+ if !rp.Done() || rp.MustBeDir() {\nreturn nil, linuxerr.ENOTDIR\n}\nreturn nil, nil\n@@ -263,7 +263,7 @@ func (fs *anonFilesystem) ListXattrAt(ctx context.Context, rp *ResolvingPath, si\n// GetXattrAt implements FilesystemImpl.GetXattrAt.\nfunc (fs *anonFilesystem) GetXattrAt(ctx context.Context, rp *ResolvingPath, opts GetXattrOptions) (string, error) {\n- if !rp.Done() {\n+ if !rp.Done() || rp.MustBeDir() {\nreturn \"\", linuxerr.ENOTDIR\n}\nreturn \"\", linuxerr.ENOTSUP\n@@ -271,7 +271,7 @@ func (fs *anonFilesystem) GetXattrAt(ctx context.Context, rp *ResolvingPath, opt\n// SetXattrAt implements FilesystemImpl.SetXattrAt.\nfunc (fs *anonFilesystem) SetXattrAt(ctx context.Context, rp *ResolvingPath, opts SetXattrOptions) error {\n- if !rp.Done() {\n+ if !rp.Done() || rp.MustBeDir() {\nreturn linuxerr.ENOTDIR\n}\nreturn linuxerr.EPERM\n@@ -279,7 +279,7 @@ func (fs *anonFilesystem) SetXattrAt(ctx context.Context, rp *ResolvingPath, opt\n// RemoveXattrAt implements FilesystemImpl.RemoveXattrAt.\nfunc (fs *anonFilesystem) RemoveXattrAt(ctx context.Context, rp *ResolvingPath, name string) error {\n- if !rp.Done() {\n+ if !rp.Done() || rp.MustBeDir() {\nreturn linuxerr.ENOTDIR\n}\nreturn linuxerr.EPERM\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/resolving_path.go",
"new_path": "pkg/sentry/vfs/resolving_path.go",
"diff": "@@ -377,7 +377,7 @@ func (rp *ResolvingPath) relpathPrepend(path fspath.Path) {\n// HandleJump is called when the current path component is a \"magic\" link to\n// the given VirtualDentry, like /proc/[pid]/fd/[fd]. If the calling Filesystem\n-// method should continue path traversal, HandleMagicSymlink updates the path\n+// method should continue path traversal, HandleJump updates the path\n// component stream to reflect the magic link target and returns nil. Otherwise\n// it returns a non-nil error.\n//\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -1777,6 +1777,7 @@ cc_binary(\n\"@com_google_absl//absl/synchronization\",\n\"@com_google_absl//absl/time\",\ngtest,\n+ \"//test/util:eventfd_util\",\n\"//test/util:memory_util\",\n\"//test/util:multiprocess_util\",\n\"//test/util:posix_error\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/proc.cc",
"new_path": "test/syscalls/linux/proc.cc",
"diff": "#include \"absl/time/time.h\"\n#include \"test/util/capability_util.h\"\n#include \"test/util/cleanup.h\"\n+#include \"test/util/eventfd_util.h\"\n#include \"test/util/file_descriptor.h\"\n#include \"test/util/fs_util.h\"\n#include \"test/util/memory_util.h\"\n@@ -1669,8 +1670,7 @@ TEST(ProcPidStatusTest, HasBasicFields) {\nstd::vector<gid_t> supplementary_gids;\nint ngids = getgroups(0, nullptr);\nsupplementary_gids.resize(ngids);\n- ASSERT_THAT(getgroups(ngids, supplementary_gids.data()),\n- SyscallSucceeds());\n+ ASSERT_THAT(getgroups(ngids, supplementary_gids.data()), SyscallSucceeds());\nEXPECT_THAT(\nstatus,\n@@ -1678,15 +1678,14 @@ TEST(ProcPidStatusTest, HasBasicFields) {\n::testing::Matcher<std::pair<std::string, std::string>>>{\n// gVisor doesn't support fsuid/gid, and even if it did there is\n// no getfsuid/getfsgid().\n- Pair(\"Uid\", StartsWith(absl::StrFormat(\"%d\\t%d\\t%d\\t\", ruid, euid,\n- suid))),\n- Pair(\"Gid\", StartsWith(absl::StrFormat(\"%d\\t%d\\t%d\\t\", rgid, egid,\n- sgid))),\n+ Pair(\"Uid\",\n+ StartsWith(absl::StrFormat(\"%d\\t%d\\t%d\\t\", ruid, euid, suid))),\n+ Pair(\"Gid\",\n+ StartsWith(absl::StrFormat(\"%d\\t%d\\t%d\\t\", rgid, egid, sgid))),\n// ParseProcStatus strips leading whitespace for each value,\n// so if the Groups line is empty then the trailing space is\n// stripped.\n- Pair(\"Groups\",\n- StartsWith(absl::StrJoin(supplementary_gids, \" \"))),\n+ Pair(\"Groups\", StartsWith(absl::StrJoin(supplementary_gids, \" \"))),\n}));\n});\n}\n@@ -2734,6 +2733,16 @@ TEST(Proc, ResolveSymlinkToProc) {\nEXPECT_EQ(target, JoinPath(\"/proc/\", absl::StrCat(getpid()), \"/cmdline\"));\n}\n+// NOTE(b/236035339): Tests that opening /proc/[pid]/fd/[eventFDNum] with\n+// O_DIRECTORY leads to ENOTDIR.\n+TEST(Proc, RegressionTestB236035339) {\n+ FileDescriptor efd =\n+ ASSERT_NO_ERRNO_AND_VALUE(NewEventFD(0, EFD_NONBLOCK | EFD_CLOEXEC));\n+ const auto path = JoinPath(\"/proc/self/fd/\", absl::StrCat(efd.get()));\n+ EXPECT_THAT(open(path.c_str(), O_RDONLY | O_CLOEXEC | O_DIRECTORY),\n+ SyscallFailsWithErrno(ENOTDIR));\n+}\n+\n} // namespace\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Make anonfs return ENOTDIR for open(O_DIRECTORY) calls.
All anonfs dentries are non-directories. So all FilesystemImpl
methods that would require an anonDentry to be a directory should
return ENOTDIR.
PiperOrigin-RevId: 455271653 |
259,858 | 16.06.2022 08:56:19 | 25,200 | 9dfa65ebdb74f35c3bfbdebf6ee87af6073733c0 | checklocks: make behavior configurable.
Defaults are the same, but certain behaviors can now be disabled to more easily
use the analyzer on its own. Now wrappers, lock inferrence and atomic default
analysis can be disabled. For example:
```
go vet -vettool=$HOME/go/bin/checklocks -wrappers=false -inferred=false -atomic=false ./...
```
Fixes | [
{
"change_type": "MODIFY",
"old_path": "tools/checklocks/analysis.go",
"new_path": "tools/checklocks/analysis.go",
"diff": "@@ -268,6 +268,10 @@ func (pc *passContext) checkGuards(inst almostInst, from ssa.Value, accessObj ty\npc.maybeFail(inst.Pos(), \"non-atomic write of field %s, writes must still be atomic with locks held (locks: %s)\", accessObj.Name(), ls.String())\n}\ncase atomicDisallow:\n+ // If atomic analysis is not enabled, skip.\n+ if !enableAtomic {\n+ break\n+ }\n// Check that this is *not* used atomically.\nif refs := inst.Referrers(); refs != nil {\nfor _, otherInst := range *refs {\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/checklocks/annotations.go",
"new_path": "tools/checklocks/annotations.go",
"diff": "@@ -91,6 +91,9 @@ func (pc *passContext) maybeFail(pos token.Pos, fmtStr string, args ...interface\nif _, ok := pc.exemptions[pc.positionKey(pos)]; ok {\nreturn // Ignored, not counted.\n}\n+ if !enableWrappers && !pos.IsValid() {\n+ return // Ignored, implicit.\n+ }\npc.pass.Reportf(pos, fmtStr, args...)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/checklocks/checklocks.go",
"new_path": "tools/checklocks/checklocks.go",
"diff": "@@ -41,6 +41,18 @@ var Analyzer = &analysis.Analyzer{\n},\n}\n+var (\n+ enableInferred = true\n+ enableAtomic = true\n+ enableWrappers = true\n+)\n+\n+func init() {\n+ Analyzer.Flags.BoolVar(&enableInferred, \"inferred\", true, \"enable inferred locks\")\n+ Analyzer.Flags.BoolVar(&enableAtomic, \"atomic\", true, \"enable atomic checks\")\n+ Analyzer.Flags.BoolVar(&enableWrappers, \"wrappers\", true, \"enable analysis of wrappers\")\n+}\n+\n// objectObservations tracks lock correlations.\ntype objectObservations struct {\ncounts map[types.Object]int\n@@ -187,7 +199,9 @@ func run(pass *analysis.Pass) (interface{}, error) {\n}\n// Check for inferred checklocks annotations.\n+ if enableInferred {\npc.checkInferred()\n+ }\n// Check for expected failures.\npc.checkFailures()\n"
}
] | Go | Apache License 2.0 | google/gvisor | checklocks: make behavior configurable.
Defaults are the same, but certain behaviors can now be disabled to more easily
use the analyzer on its own. Now wrappers, lock inferrence and atomic default
analysis can be disabled. For example:
```
go vet -vettool=$HOME/go/bin/checklocks -wrappers=false -inferred=false -atomic=false ./...
```
Fixes #7721
PiperOrigin-RevId: 455393957 |
259,992 | 16.06.2022 10:02:36 | 25,200 | 5dc4c42f8f91f5b604bef187bb5e507739e04b12 | Add more trace point integration tests
Updates | [
{
"change_type": "MODIFY",
"old_path": "test/trace/BUILD",
"new_path": "test/trace/BUILD",
"diff": "@@ -22,6 +22,7 @@ go_test(\n\"//pkg/test/testutil\",\n\"//test/trace/config\",\n\"@org_golang_google_protobuf//proto:go_default_library\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/trace/trace_test.go",
"new_path": "test/trace/trace_test.go",
"diff": "@@ -23,6 +23,7 @@ import (\n\"testing\"\n\"time\"\n+ \"golang.org/x/sys/unix\"\n\"google.golang.org/protobuf/proto\"\n\"gvisor.dev/gvisor/pkg/sentry/seccheck\"\n\"gvisor.dev/gvisor/pkg/sentry/seccheck/checkers/remote/test\"\n@@ -31,6 +32,8 @@ import (\n\"gvisor.dev/gvisor/test/trace/config\"\n)\n+var cutoffTime time.Time\n+\n// TestAll enabled all trace points in the system with all optional and context\n// fields enabled. Then it runs a workload that will trigger those points and\n// run some basic validation over the points generated.\n@@ -68,6 +71,8 @@ func TestAll(t *testing.T) {\nif err != nil {\nt.Fatal(err)\n}\n+ // No trace point should have a time lesser than this.\n+ cutoffTime = time.Now()\ncmd := exec.Command(\nrunsc,\n\"--debug\", \"--alsologtostderr\", // Debug logging for troubleshooting\n@@ -75,10 +80,10 @@ func TestAll(t *testing.T) {\n\"--pod-init-config\", cfgFile.Name(),\n\"do\", workload)\nout, err := cmd.CombinedOutput()\n+ t.Log(string(out))\nif err != nil {\nt.Fatalf(\"runsc do: %v\", err)\n}\n- t.Log(string(out))\n// Wait until the sandbox disconnects to ensure all points were gathered.\nserver.WaitForNoClients()\n@@ -92,11 +97,17 @@ func matchPoints(t *testing.T, msgs []test.Message) {\ncount int\n}{\npb.MessageType_MESSAGE_CONTAINER_START: {checker: checkContainerStart},\n+ pb.MessageType_MESSAGE_SENTRY_CLONE: {checker: checkSentryClone},\n+ pb.MessageType_MESSAGE_SENTRY_EXEC: {checker: checkSentryExec},\n+ pb.MessageType_MESSAGE_SENTRY_EXIT_NOTIFY_PARENT: {checker: checkSentryExitNotifyParent},\npb.MessageType_MESSAGE_SENTRY_TASK_EXIT: {checker: checkSentryTaskExit},\n- pb.MessageType_MESSAGE_SYSCALL_RAW: {checker: checkSyscallRaw},\n- pb.MessageType_MESSAGE_SYSCALL_OPEN: {checker: checkSyscallOpen},\npb.MessageType_MESSAGE_SYSCALL_CLOSE: {checker: checkSyscallClose},\n+ pb.MessageType_MESSAGE_SYSCALL_CONNECT: {checker: checkSyscallConnect},\n+ pb.MessageType_MESSAGE_SYSCALL_EXECVE: {checker: checkSyscallExecve},\n+ pb.MessageType_MESSAGE_SYSCALL_OPEN: {checker: checkSyscallOpen},\n+ pb.MessageType_MESSAGE_SYSCALL_RAW: {checker: checkSyscallRaw},\npb.MessageType_MESSAGE_SYSCALL_READ: {checker: checkSyscallRead},\n+ pb.MessageType_MESSAGE_SYSCALL_SOCKET: {checker: checkSyscallSocket},\n}\nfor _, msg := range msgs {\nt.Logf(\"Processing message type %v\", msg.MsgType)\n@@ -120,7 +131,22 @@ func matchPoints(t *testing.T, msgs []test.Message) {\n}\n}\n+func checkTimeNs(ns int64) error {\n+ if ns <= int64(cutoffTime.Nanosecond()) {\n+ return fmt.Errorf(\"time should not be less than %d (%v), got: %d (%v)\", cutoffTime.Nanosecond(), cutoffTime, ns, time.Unix(0, ns))\n+ }\n+ return nil\n+}\n+\n+type contextDataOpts struct {\n+ skipCwd bool\n+}\n+\nfunc checkContextData(data *pb.ContextData) error {\n+ return checkContextDataOpts(data, contextDataOpts{})\n+}\n+\n+func checkContextDataOpts(data *pb.ContextData, opts contextDataOpts) error {\nif data == nil {\nreturn fmt.Errorf(\"ContextData should not be nil\")\n}\n@@ -128,18 +154,17 @@ func checkContextData(data *pb.ContextData) error {\nreturn fmt.Errorf(\"invalid container ID %q\", data.ContainerId)\n}\n- cutoff := time.Now().Add(-time.Minute)\n- if data.TimeNs <= int64(cutoff.Nanosecond()) {\n- return fmt.Errorf(\"time should not be less than %d (%v), got: %d (%v)\", cutoff.Nanosecond(), cutoff, data.TimeNs, time.Unix(0, data.TimeNs))\n+ if err := checkTimeNs(data.TimeNs); err != nil {\n+ return err\n}\n- if data.ThreadStartTimeNs <= int64(cutoff.Nanosecond()) {\n- return fmt.Errorf(\"thread_start_time should not be less than %d (%v), got: %d (%v)\", cutoff.Nanosecond(), cutoff, data.ThreadStartTimeNs, time.Unix(0, data.ThreadStartTimeNs))\n+ if err := checkTimeNs(data.ThreadStartTimeNs); err != nil {\n+ return err\n}\nif data.ThreadStartTimeNs > data.TimeNs {\nreturn fmt.Errorf(\"thread_start_time should not be greater than point time: %d (%v), got: %d (%v)\", data.TimeNs, time.Unix(0, data.TimeNs), data.ThreadStartTimeNs, time.Unix(0, data.ThreadStartTimeNs))\n}\n- if data.ThreadGroupStartTimeNs <= int64(cutoff.Nanosecond()) {\n- return fmt.Errorf(\"thread_group_start_time should not be less than %d (%v), got: %d (%v)\", cutoff.Nanosecond(), cutoff, data.ThreadGroupStartTimeNs, time.Unix(0, data.ThreadGroupStartTimeNs))\n+ if err := checkTimeNs(data.ThreadGroupStartTimeNs); err != nil {\n+ return err\n}\nif data.ThreadGroupStartTimeNs > data.TimeNs {\nreturn fmt.Errorf(\"thread_group_start_time should not be greater than point time: %d (%v), got: %d (%v)\", data.TimeNs, time.Unix(0, data.TimeNs), data.ThreadGroupStartTimeNs, time.Unix(0, data.ThreadGroupStartTimeNs))\n@@ -151,7 +176,7 @@ func checkContextData(data *pb.ContextData) error {\nif data.ThreadGroupId <= 0 {\nreturn fmt.Errorf(\"invalid thread_group_id: %v\", data.ThreadGroupId)\n}\n- if len(data.Cwd) == 0 {\n+ if !opts.skipCwd && len(data.Cwd) == 0 {\nreturn fmt.Errorf(\"invalid cwd: %v\", data.Cwd)\n}\nif len(data.ProcessName) == 0 {\n@@ -262,3 +287,149 @@ func checkSyscallRead(msg test.Message) error {\n}\nreturn nil\n}\n+\n+func checkSentryClone(msg test.Message) error {\n+ p := pb.CloneInfo{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ if err := checkContextData(p.ContextData); err != nil {\n+ return err\n+ }\n+ if p.CreatedThreadId < 0 {\n+ return fmt.Errorf(\"invalid TID: %d\", p.CreatedThreadId)\n+ }\n+ if p.CreatedThreadGroupId < 0 {\n+ return fmt.Errorf(\"invalid TGID: %d\", p.CreatedThreadGroupId)\n+ }\n+ if p.CreatedThreadStartTimeNs < 0 {\n+ return fmt.Errorf(\"invalid TID: %d\", p.CreatedThreadId)\n+ }\n+ return checkTimeNs(p.CreatedThreadStartTimeNs)\n+}\n+\n+func checkSentryExec(msg test.Message) error {\n+ p := pb.ExecveInfo{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ if err := checkContextData(p.ContextData); err != nil {\n+ return err\n+ }\n+ if want := \"/bin/true\"; want != p.BinaryPath {\n+ return fmt.Errorf(\"wrong BinaryPath, want: %q, got: %q\", want, p.BinaryPath)\n+ }\n+ if len(p.Argv) == 0 {\n+ return fmt.Errorf(\"empty Argv\")\n+ }\n+ if p.Argv[0] != p.BinaryPath {\n+ return fmt.Errorf(\"wrong Argv[0], want: %q, got: %q\", p.BinaryPath, p.Argv[0])\n+ }\n+ if len(p.Env) == 0 {\n+ return fmt.Errorf(\"empty Env\")\n+ }\n+ if want := \"TEST=123\"; want != p.Env[0] {\n+ return fmt.Errorf(\"wrong Env[0], want: %q, got: %q\", want, p.Env[0])\n+ }\n+ if (p.BinaryMode & 0111) == 0 {\n+ return fmt.Errorf(\"executing non-executable file, mode: %#o (%#x)\", p.BinaryMode, p.BinaryMode)\n+ }\n+ const nobody = 65534\n+ if p.BinaryUid != nobody {\n+ return fmt.Errorf(\"BinaryUid, want: %d, got: %d\", nobody, p.BinaryUid)\n+ }\n+ if p.BinaryGid != nobody {\n+ return fmt.Errorf(\"BinaryGid, want: %d, got: %d\", nobody, p.BinaryGid)\n+ }\n+ return nil\n+}\n+\n+func checkSyscallExecve(msg test.Message) error {\n+ p := pb.Execve{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ if err := checkContextData(p.ContextData); err != nil {\n+ return err\n+ }\n+ if p.Fd < 3 {\n+ return fmt.Errorf(\"execve invalid FD: %d\", p.Fd)\n+ }\n+ if want := \"/\"; want != p.FdPath {\n+ return fmt.Errorf(\"wrong FdPath, want: %q, got: %q\", want, p.FdPath)\n+ }\n+ if want := \"/bin/true\"; want != p.Pathname {\n+ return fmt.Errorf(\"wrong Pathname, want: %q, got: %q\", want, p.Pathname)\n+ }\n+ if len(p.Argv) == 0 {\n+ return fmt.Errorf(\"empty Argv\")\n+ }\n+ if p.Argv[0] != p.Pathname {\n+ return fmt.Errorf(\"wrong Argv[0], want: %q, got: %q\", p.Pathname, p.Argv[0])\n+ }\n+ if len(p.Envv) == 0 {\n+ return fmt.Errorf(\"empty Envv\")\n+ }\n+ if want := \"TEST=123\"; want != p.Envv[0] {\n+ return fmt.Errorf(\"wrong Envv[0], want: %q, got: %q\", want, p.Envv[0])\n+ }\n+ return nil\n+}\n+\n+func checkSentryExitNotifyParent(msg test.Message) error {\n+ p := pb.ExitNotifyParentInfo{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ // cwd is empty because the task has already been destroyed when the point\n+ // fires.\n+ opts := contextDataOpts{skipCwd: true}\n+ if err := checkContextDataOpts(p.ContextData, opts); err != nil {\n+ return err\n+ }\n+ if p.ExitStatus != 0 {\n+ return fmt.Errorf(\"wrong ExitStatus, want: 0, got: %d\", p.ExitStatus)\n+ }\n+ return nil\n+}\n+\n+func checkSyscallConnect(msg test.Message) error {\n+ p := pb.Connect{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ if err := checkContextData(p.ContextData); err != nil {\n+ return err\n+ }\n+ if p.Fd < 3 {\n+ return fmt.Errorf(\"invalid FD: %d\", p.Fd)\n+ }\n+ if want := \"socket:\"; !strings.HasPrefix(p.FdPath, want) {\n+ return fmt.Errorf(\"FdPath should start with %q, got: %q\", want, p.FdPath)\n+ }\n+ if len(p.Address) == 0 {\n+ return fmt.Errorf(\"empty address: %q\", string(p.Address))\n+ }\n+\n+ return nil\n+}\n+\n+func checkSyscallSocket(msg test.Message) error {\n+ p := pb.Socket{}\n+ if err := proto.Unmarshal(msg.Msg, &p); err != nil {\n+ return err\n+ }\n+ if err := checkContextData(p.ContextData); err != nil {\n+ return err\n+ }\n+ if want := unix.AF_UNIX; int32(want) != p.Domain {\n+ return fmt.Errorf(\"wrong Domain, want: %v, got: %v\", want, p.Domain)\n+ }\n+ if want := unix.SOCK_STREAM; int32(want) != p.Type {\n+ return fmt.Errorf(\"wrong Type, want: %v, got: %v\", want, p.Type)\n+ }\n+ if want := int32(0); want != p.Protocol {\n+ return fmt.Errorf(\"wrong Protocol, want: %v, got: %v\", want, p.Protocol)\n+ }\n+ return nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/trace/workload/BUILD",
"new_path": "test/trace/workload/BUILD",
"diff": "@@ -10,5 +10,12 @@ cc_binary(\n],\nvisibility = [\"//test/trace:__pkg__\"],\ndeps = [\n+ \"//test/util:file_descriptor\",\n+ \"//test/util:multiprocess_util\",\n+ \"//test/util:posix_error\",\n+ \"//test/util:test_util\",\n+ \"@com_google_absl//absl/cleanup\",\n+ \"@com_google_absl//absl/strings\",\n+ \"@com_google_absl//absl/time\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/trace/workload/workload.cc",
"new_path": "test/trace/workload/workload.cc",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// Empty for now. Actual workload will be added as more points are covered.\n-int main(int argc, char** argv) { return 0; }\n+#include <err.h>\n+#include <sys/socket.h>\n+#include <sys/types.h>\n+#include <sys/un.h>\n+\n+#include \"absl/cleanup/cleanup.h\"\n+#include \"absl/strings/str_cat.h\"\n+#include \"absl/time/clock.h\"\n+#include \"test/util/file_descriptor.h\"\n+#include \"test/util/multiprocess_util.h\"\n+#include \"test/util/posix_error.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+void runForkExecve() {\n+ auto root_or_error = Open(\"/\", O_RDONLY, 0);\n+ auto& root = root_or_error.ValueOrDie();\n+\n+ pid_t child;\n+ int execve_errno;\n+ ExecveArray argv = {\"/bin/true\"};\n+ ExecveArray envv = {\"TEST=123\"};\n+ auto kill_or_error = ForkAndExecveat(root.get(), \"/bin/true\", argv, envv, 0,\n+ nullptr, &child, &execve_errno);\n+ ASSERT_EQ(0, execve_errno);\n+\n+ // Don't kill child, just wait for gracefully exit.\n+ kill_or_error.ValueOrDie().Release();\n+ RetryEINTR(waitpid)(child, nullptr, 0);\n+}\n+\n+// Creates a simple UDS in the abstract namespace and send one byte from the\n+// client to the server.\n+void runSocket() {\n+ auto path = absl::StrCat(std::string(\"\\0\", 1), \"trace_test.\", getpid(),\n+ absl::GetCurrentTimeNanos());\n+\n+ struct sockaddr_un addr;\n+ addr.sun_family = AF_UNIX;\n+ strncpy(addr.sun_path, path.c_str(), path.size() + 1);\n+\n+ int parent_sock = socket(AF_UNIX, SOCK_STREAM, 0);\n+ if (parent_sock < 0) {\n+ err(1, \"socket\");\n+ }\n+ auto sock_closer = absl::MakeCleanup([parent_sock] { close(parent_sock); });\n+\n+ if (bind(parent_sock, reinterpret_cast<struct sockaddr*>(&addr),\n+ sizeof(addr))) {\n+ err(1, \"bind\");\n+ }\n+ if (listen(parent_sock, 5) < 0) {\n+ err(1, \"listen\");\n+ }\n+\n+ pid_t pid = fork();\n+ if (pid < 0) {\n+ // Fork error.\n+ err(1, \"fork\");\n+\n+ } else if (pid == 0) {\n+ // Child.\n+ close(parent_sock); // ensure it's not mistakely used in child.\n+\n+ int server = socket(AF_UNIX, SOCK_STREAM, 0);\n+ if (server < 0) {\n+ err(1, \"socket\");\n+ }\n+ auto server_closer = absl::MakeCleanup([server] { close(server); });\n+\n+ if (connect(server, reinterpret_cast<struct sockaddr*>(&addr),\n+ sizeof(addr)) < 0) {\n+ err(1, \"connect\");\n+ }\n+\n+ char buf = 'A';\n+ int bytes = write(server, &buf, sizeof(buf));\n+ if (bytes != 1) {\n+ err(1, \"write: %d\", bytes);\n+ }\n+ exit(0);\n+\n+ } else {\n+ // Parent.\n+ int client = RetryEINTR(accept)(parent_sock, nullptr, nullptr);\n+ if (client < 0) {\n+ err(1, \"accept\");\n+ }\n+ auto client_closer = absl::MakeCleanup([client] { close(client); });\n+\n+ char buf;\n+ int bytes = read(client, &buf, sizeof(buf));\n+ if (bytes != 1) {\n+ err(1, \"read: %d\", bytes);\n+ }\n+\n+ // Wait to reap the child.\n+ RetryEINTR(waitpid)(pid, nullptr, 0);\n+ }\n+}\n+\n+} // namespace testing\n+} // namespace gvisor\n+\n+int main(int argc, char** argv) {\n+ ::gvisor::testing::runForkExecve();\n+ ::gvisor::testing::runSocket();\n+\n+ return 0;\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add more trace point integration tests
Updates #4805
PiperOrigin-RevId: 455408137 |
259,868 | 16.06.2022 10:36:04 | 25,200 | 72295623b015b0a73d02af0b39cba7d11b29b177 | `bazel.mk`: Set Docker hostnames for all containers.
This makes it easier to tell where each command is being run than a
random-generated string. | [
{
"change_type": "MODIFY",
"old_path": "tools/bazel.mk",
"new_path": "tools/bazel.mk",
"diff": "## USER - The in-container user.\n## DOCKER_RUN_OPTIONS - Options for the container (default: --privileged, required for tests).\n## DOCKER_NAME - The container name (default: gvisor-bazel-HASH).\n+## DOCKER_HOSTNAME - The container name (default: same as DOCKER_NAME).\n## DOCKER_PRIVILEGED - Docker privileged flags (default: --privileged).\n## PRE_BAZEL_INIT - If set, run this command with bash outside the Bazel\n## server container.\n@@ -50,7 +51,9 @@ RACE_FLAGS := --@io_bazel_rules_go//go/config:race\nUSER := $(shell whoami)\nHASH := $(shell realpath -m $(CURDIR) | md5sum | cut -c1-8)\nBUILDER_NAME := gvisor-builder-$(HASH)-$(ARCH)\n+BUILDER_HOSTNAME := $(BUILDER_NAME)\nDOCKER_NAME := gvisor-bazel-$(HASH)-$(ARCH)\n+DOCKER_HOSTNAME := $(DOCKER_NAME)\nDOCKER_PRIVILEGED := --privileged\nBAZEL_CACHE := $(HOME)/.cache/bazel/\nGCLOUD_CONFIG := $(HOME)/.config/gcloud/\n@@ -182,7 +185,9 @@ bazel-alias: ## Emits an alias that can be used within the shell.\nbazel-image: load-default ## Ensures that the local builder exists.\n@$(call header,DOCKER BUILD)\n@docker rm -f $(BUILDER_NAME) 2>/dev/null || true\n- @docker run --user 0:0 --entrypoint \"\" --name $(BUILDER_NAME) gvisor.dev/images/default \\\n+ @docker run --user 0:0 --entrypoint \"\" \\\n+ --name $(BUILDER_NAME) --hostname $(BUILDER_HOSTNAME) \\\n+ gvisor.dev/images/default \\\nbash -c \"$(GROUPADD_DOCKER) $(USERADD_DOCKER) if test -e /dev/kvm; then chmod a+rw /dev/kvm; fi\" >&2\n@docker commit $(BUILDER_NAME) gvisor.dev/images/builder >&2\n.PHONY: bazel-image\n@@ -197,7 +202,7 @@ endif\n@docker rm -f $(DOCKER_NAME) 2>/dev/null || true\n@mkdir -p $(BAZEL_CACHE)\n@mkdir -p $(GCLOUD_CONFIG)\n- @docker run -d --name $(DOCKER_NAME) \\\n+ @docker run -d --name $(DOCKER_NAME) --hostname $(DOCKER_HOSTNAME) \\\n-v \"$(CURDIR):$(CURDIR)\" \\\n--workdir \"$(CURDIR)\" \\\n$(DOCKER_RUN_OPTIONS) \\\n"
}
] | Go | Apache License 2.0 | google/gvisor | `bazel.mk`: Set Docker hostnames for all containers.
This makes it easier to tell where each command is being run than a
random-generated string.
PiperOrigin-RevId: 455416726 |
259,868 | 16.06.2022 10:43:42 | 25,200 | 1b604ce01053e0acae0138b7e345da50afe2007f | Pass on systemd-related files to Docker containers if present.
This allows control of the Docker container via `systemd` from
within the containers themselves. This is useful for tests that
require restarting Docker, e.g. after installing a new runtime
or enabling Docker's `experimental` mode. | [
{
"change_type": "MODIFY",
"old_path": ".buildkite/hooks/pre-command",
"new_path": ".buildkite/hooks/pre-command",
"diff": "@@ -13,8 +13,8 @@ function install_pkgs() {\ndone\n}\ninstall_pkgs make linux-libc-dev graphviz jq curl binutils gnupg gnupg-agent \\\n- gcc pkg-config apt-transport-https ca-certificates software-properties-common \\\n- rsync kmod\n+ gcc pkg-config apt-transport-https ca-certificates \\\n+ software-properties-common rsync kmod systemd\n# Install headers, only if available.\nif test -n \"$(apt-cache search --names-only \"^linux-headers-$(uname -r)$\")\"; then\n@@ -34,9 +34,20 @@ export TOTAL_PARTITIONS=${BUILDKITE_PARALLEL_JOB_COUNT:-1}\nexport RUNTIME=\"${BUILDKITE_BRANCH}-${BUILDKITE_BUILD_ID}\"\n# Ensure Docker has experimental enabled.\n-EXPERIMENTAL=$(sudo docker version --format='{{.Server.Experimental}}')\n+if [[ -n \"${STAGED_BINARIES:-}\" ]]; then\n+ # Used `runsc` from STAGED_BINARIES instead of building it from scratch.\n+ tmpdir=\"$(mktemp -d)\"\n+ gsutil cat \"$(STAGED_BINARIES)\" | tar -C \"$tmpdir\" -zxvf - runsc\n+ chmod +x \"$tmpdir/runsc\"\n+ \"$tmpdir/runsc\" install --experimental=true --runtime=\"${RUNTIME}\" \\\n+ -- \"${RUNTIME_ARGS:-}\"\n+ rm -rf \"$tmpdir\"\n+else\nmake sudo TARGETS=//runsc:runsc \\\nARGS=\"install --experimental=true --runtime=${RUNTIME} -- ${RUNTIME_ARGS:-}\"\n+fi\n+# WARNING: We may be running in a container when this command executes.\n+# This only makes sense if Docker's `live-restore` feature is enabled.\nsudo systemctl restart docker\n# Helper for benchmarks, based on the branch.\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/bazel.mk",
"new_path": "tools/bazel.mk",
"diff": "@@ -111,6 +111,16 @@ DOCKER_RUN_OPTIONS += -v \"$(KERNEL_HEADERS_DIR_LINKED):$(KERNEL_HEADERS_DIR_LINK\nendif\nendif\n+# Same for systemd-related files and directories. This allows control of systemd\n+# from within the container, which is useful for tests that need to e.g. restart\n+# docker.\n+ifneq (,$(wildcard /run/systemd/system))\n+DOCKER_RUN_OPTIONS += -v \"/run/systemd/system:/run/systemd/system\"\n+endif\n+ifneq (,$(wildcard /var/run/dbus/system_bus_socket))\n+DOCKER_RUN_OPTIONS += -v \"/var/run/dbus/system_bus_socket:/var/run/dbus/system_bus_socket\"\n+endif\n+\n# Add basic UID/GID options.\n#\n# Note that USERADD_DOCKER and GROUPADD_DOCKER are both defined as \"deferred\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | Pass on systemd-related files to Docker containers if present.
This allows control of the Docker container via `systemd` from
within the containers themselves. This is useful for tests that
require restarting Docker, e.g. after installing a new runtime
or enabling Docker's `experimental` mode.
PiperOrigin-RevId: 455418499 |
259,909 | 16.06.2022 13:33:01 | 25,200 | 35227fb84fd0d9a35ece6d43834ce3099d3944fc | Add a panic that prints information about the sender before calling splitSeg.
Calling splitSeg with a negative value panics anyway, we need to know why. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/snd.go",
"new_path": "pkg/tcpip/transport/tcp/snd.go",
"diff": "@@ -859,6 +859,13 @@ func (s *sender) maybeSendSegment(seg *segment, limit int, end seqnum.Value) (se\n}\nif seg.payloadSize() > available {\n+ // A negative value causes splitSeg to panic anyways, so just panic\n+ // earlier to get more information about the cause.\n+ // TOOD(b/236090764): Remove this panic once the cause of negative values\n+ // of \"available\" is understood.\n+ if available < 0 {\n+ panic(fmt.Sprintf(\"got available=%d, want available>=0. limit %d, s.MaxPayloadSize %d, seg.payloadSize() %d, gso.MaxSize %d, gso.MSS %d\", available, limit, s.MaxPayloadSize, seg.payloadSize(), s.ep.gso.MaxSize, s.ep.gso.MSS))\n+ }\ns.splitSeg(seg, available)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add a panic that prints information about the sender before calling splitSeg.
Calling splitSeg with a negative value panics anyway, we need to know why.
PiperOrigin-RevId: 455455562 |
259,985 | 16.06.2022 13:54:09 | 25,200 | d5a04e338eef531108e9f6266e67e09f63ae4155 | cgroupfs: Don't copy in with cgroups locks held.
CopyIn acquires mm.mappingMu, which is ordered before cgroups locks.
Reported-by: | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/pids.go",
"new_path": "pkg/sentry/fsimpl/cgroupfs/pids.go",
"diff": "@@ -268,9 +268,6 @@ func (d *pidsMaxData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n// Write implements vfs.WritableDynamicBytesSource.Write.\nfunc (d *pidsMaxData) Write(ctx context.Context, _ *vfs.FileDescription, src usermem.IOSequence, offset int64) (int64, error) {\n- d.c.mu.Lock()\n- defer d.c.mu.Unlock()\n-\nt := kernel.TaskFromContext(ctx)\nbuf := t.CopyScratchBuffer(hostarch.PageSize)\nncpy, err := src.CopyIn(ctx, buf)\n@@ -278,6 +275,8 @@ func (d *pidsMaxData) Write(ctx context.Context, _ *vfs.FileDescription, src use\nreturn 0, err\n}\nif strings.TrimSpace(string(buf)) == \"max\" {\n+ d.c.mu.Lock()\n+ defer d.c.mu.Unlock()\nd.c.max = pidLimitUnlimited\nreturn int64(ncpy), nil\n}\n@@ -290,6 +289,8 @@ func (d *pidsMaxData) Write(ctx context.Context, _ *vfs.FileDescription, src use\nreturn 0, linuxerr.EINVAL\n}\n+ d.c.mu.Lock()\n+ defer d.c.mu.Unlock()\nd.c.max = val\nreturn int64(n), nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | cgroupfs: Don't copy in with cgroups locks held.
CopyIn acquires mm.mappingMu, which is ordered before cgroups locks.
Reported-by: syzbot+97a5960840a8aeb25e6a@syzkaller.appspotmail.com
PiperOrigin-RevId: 455460140 |
259,853 | 16.06.2022 15:20:40 | 25,200 | 9f7d89e7d96635215f3589c98813e42711f1ce5b | overlay: use lockdep mutexes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/overlay/BUILD",
"new_path": "pkg/sentry/fsimpl/overlay/BUILD",
"diff": "load(\"//tools:defs.bzl\", \"go_library\")\nload(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\n+load(\"//pkg/sync/locking:locking.bzl\", \"declare_mutex\", \"declare_rwmutex\")\nlicenses([\"notice\"])\n+declare_mutex(\n+ name = \"dir_mutex\",\n+ out = \"dir_mutex.go\",\n+ package = \"overlay\",\n+ prefix = \"dir\",\n+)\n+\n+declare_mutex(\n+ name = \"dev_mutex\",\n+ out = \"dev_mutex.go\",\n+ package = \"overlay\",\n+ prefix = \"dev\",\n+)\n+\n+declare_mutex(\n+ name = \"dir_cache_mutex\",\n+ out = \"dir_cache_mutex.go\",\n+ package = \"overlay\",\n+ prefix = \"dirInoCache\",\n+)\n+\n+declare_mutex(\n+ name = \"reg_file_fd_mutex\",\n+ out = \"req_file_fd_mutex.go\",\n+ package = \"overlay\",\n+ prefix = \"regularFileFD\",\n+)\n+\n+declare_mutex(\n+ name = \"dir_fd_mutex\",\n+ out = \"dir_fd_mutex.go\",\n+ package = \"overlay\",\n+ prefix = \"directoryFD\",\n+)\n+\n+declare_rwmutex(\n+ name = \"rename_rwmutex\",\n+ out = \"rename_rwmutex.go\",\n+ package = \"overlay\",\n+ prefix = \"rename\",\n+)\n+\n+declare_rwmutex(\n+ name = \"data_rwmutex\",\n+ out = \"data_rwmutex.go\",\n+ package = \"overlay\",\n+ prefix = \"data\",\n+)\n+\n+declare_mutex(\n+ name = \"maps_mutex\",\n+ out = \"maps_mutex.go\",\n+ package = \"overlay\",\n+ prefix = \"maps\",\n+)\n+\ngo_template_instance(\nname = \"fstree\",\nout = \"fstree.go\",\n@@ -18,11 +75,19 @@ go_library(\nname = \"overlay\",\nsrcs = [\n\"copy_up.go\",\n+ \"data_rwmutex.go\",\n+ \"dev_mutex.go\",\n+ \"dir_cache_mutex\",\n+ \"dir_fd_mutex.go\",\n+ \"dir_mutex.go\",\n\"directory.go\",\n\"filesystem.go\",\n\"fstree.go\",\n+ \"maps_mutex.go\",\n\"overlay.go\",\n\"regular_file.go\",\n+ \"rename_rwmutex.go\",\n+ \"req_file_fd_mutex.go\",\n\"save_restore.go\",\n],\nvisibility = [\"//pkg/sentry:internal\"],\n@@ -43,6 +108,7 @@ go_library(\n\"//pkg/sentry/socket/unix/transport\",\n\"//pkg/sentry/vfs\",\n\"//pkg/sync\",\n+ \"//pkg/sync/locking\",\n\"//pkg/usermem\",\n\"//pkg/waiter\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/overlay/directory.go",
"new_path": "pkg/sentry/fsimpl/overlay/directory.go",
"diff": "@@ -20,7 +20,6 @@ import (\n\"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n\"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n- \"gvisor.dev/gvisor/pkg/sync\"\n)\nfunc (d *dentry) isDir() bool {\n@@ -104,7 +103,7 @@ type directoryFD struct {\nvfs.DirectoryFileDescriptionDefaultImpl\nvfs.DentryMetadataFileDescriptionImpl\n- mu sync.Mutex `state:\"nosave\"`\n+ mu directoryFDMutex `state:\"nosave\"`\noff int64\ndirents []vfs.Dirent\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/overlay/filesystem.go",
"new_path": "pkg/sentry/fsimpl/overlay/filesystem.go",
"diff": "@@ -1117,8 +1117,8 @@ func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\nif err := newParent.checkPermissions(creds, vfs.MayWrite|vfs.MayExec); err != nil {\nreturn err\n}\n- newParent.dirMu.Lock()\n- defer newParent.dirMu.Unlock()\n+ newParent.dirMu.NestedLock()\n+ defer newParent.dirMu.NestedUnlock()\n}\nif newParent.vfsd.IsDead() {\nreturn linuxerr.ENOENT\n@@ -1145,8 +1145,8 @@ func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\nif genericIsAncestorDentry(replaced, renamed) {\nreturn linuxerr.ENOTEMPTY\n}\n- replaced.dirMu.Lock()\n- defer replaced.dirMu.Unlock()\n+ replaced.dirMu.NestedLock()\n+ defer replaced.dirMu.NestedUnlock()\nwhiteouts, err = replaced.collectWhiteoutsForRmdirLocked(ctx)\nif err != nil {\nreturn err\n@@ -1350,8 +1350,8 @@ func (fs *filesystem) RmdirAt(ctx context.Context, rp *vfs.ResolvingPath) error\nif err := parent.mayDelete(rp.Credentials(), child); err != nil {\nreturn err\n}\n- child.dirMu.Lock()\n- defer child.dirMu.Unlock()\n+ child.dirMu.NestedLock()\n+ defer child.dirMu.NestedUnlock()\nwhiteouts, err := child.collectWhiteoutsForRmdirLocked(ctx)\nif err != nil {\nreturn err\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/overlay/overlay.go",
"new_path": "pkg/sentry/fsimpl/overlay/overlay.go",
"diff": "@@ -108,18 +108,18 @@ type filesystem struct {\n// distinguishable because they will diverge after copy-up; this isn't true\n// for non-directory files already on the upper layer.) lowerDevMinors is\n// protected by devMu.\n- devMu sync.Mutex `state:\"nosave\"`\n+ devMu devMutex `state:\"nosave\"`\nlowerDevMinors map[layerDevNumber]uint32\n// renameMu synchronizes renaming with non-renaming operations in order to\n// ensure consistent lock ordering between dentry.dirMu in different\n// dentries.\n- renameMu sync.RWMutex `state:\"nosave\"`\n+ renameMu renameRWMutex `state:\"nosave\"`\n// dirInoCache caches overlay-private directory inode numbers by mapped\n// topmost device numbers and inode number. dirInoCache is protected by\n// dirInoCacheMu.\n- dirInoCacheMu sync.Mutex `state:\"nosave\"`\n+ dirInoCacheMu dirInoCacheMutex `state:\"nosave\"`\ndirInoCache map[layerDevNoAndIno]uint64\n// lastDirIno is the last inode number assigned to a directory. lastDirIno\n@@ -452,7 +452,7 @@ type dentry struct {\n// and dirents (if not nil) is a cache of dirents as returned by\n// directoryFDs representing this directory. children is protected by\n// dirMu.\n- dirMu sync.Mutex `state:\"nosave\"`\n+ dirMu dirMutex `state:\"nosave\"`\nchildren map[string]*dentry\ndirents []vfs.Dirent\n@@ -499,9 +499,9 @@ type dentry struct {\n//\n// - isMappable is non-zero iff wrappedMappable is non-nil. isMappable is\n// accessed using atomic memory operations.\n- mapsMu sync.Mutex `state:\"nosave\"`\n+ mapsMu mapsMutex `state:\"nosave\"`\nlowerMappings memmap.MappingSet\n- dataMu sync.RWMutex `state:\"nosave\"`\n+ dataMu dataRWMutex `state:\"nosave\"`\nwrappedMappable memmap.Mappable\nisMappable atomicbitops.Uint32\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/overlay/regular_file.go",
"new_path": "pkg/sentry/fsimpl/overlay/regular_file.go",
"diff": "@@ -24,7 +24,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/memmap\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n- \"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n@@ -54,7 +53,7 @@ type regularFileFD struct {\n// fileDescription.dentry().upperVD. cachedFlags is the last known value of\n// cachedFD.StatusFlags(). copiedUp, cachedFD, and cachedFlags are\n// protected by mu.\n- mu sync.Mutex `state:\"nosave\"`\n+ mu regularFileFDMutex `state:\"nosave\"`\ncopiedUp bool\ncachedFD *vfs.FileDescription\ncachedFlags uint32\n"
}
] | Go | Apache License 2.0 | google/gvisor | overlay: use lockdep mutexes
PiperOrigin-RevId: 455478722 |
259,941 | 17.06.2022 04:55:20 | -19,080 | 66a847a0c24874d9527355ce6c2bf8d1c5d32965 | m. refactor eliminate a redundant variable | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/endpoint.go",
"new_path": "pkg/tcpip/link/fdbased/endpoint.go",
"diff": "@@ -555,17 +555,15 @@ func (e *endpoint) writePacket(pkt *stack.PacketBuffer) tcpip.Error {\nfunc (e *endpoint) sendBatch(batchFDInfo fdInfo, pkts []*stack.PacketBuffer) (int, tcpip.Error) {\n// Degrade to writePacket if underlying fd is not a socket.\nif !batchFDInfo.isSocket {\n- written := 0\n- for i := 0; i < len(pkts); i++ {\n- if err := e.writePacket(pkts[i]); err != nil {\n- if written > 0 {\n- return written, nil\n- }\n- return 0, err\n+ var written int\n+ var err error\n+ for written < len(pkts) {\n+ if err = e.writePacket(pkts[written]); err != nil {\n+ break\n}\n- written = i\n+ written++\n}\n- return written, nil\n+ return written, err\n}\n// Send a batch of packets through batchFD.\n"
}
] | Go | Apache License 2.0 | google/gvisor | m. refactor eliminate a redundant variable |
259,907 | 20.06.2022 18:38:53 | 25,200 | 9dfac31f0a577b0b9746b73594ecda5a7e328904 | Add O_DIRECTORY support to openat(O_PATH) in VFS2.
VFS2 earlier was ignoring the effect of O_DIRECTORY with O_PATH. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/opath.go",
"new_path": "pkg/sentry/vfs/opath.go",
"diff": "@@ -137,3 +137,32 @@ func (fd *opathFD) StatFS(ctx context.Context) (linux.Statfs, error) {\nrp.Release(ctx)\nreturn statfs, err\n}\n+\n+func (vfs *VirtualFilesystem) openOPathFD(ctx context.Context, creds *auth.Credentials, pop *PathOperation, flags uint32) (*FileDescription, error) {\n+ vd, err := vfs.GetDentryAt(ctx, creds, pop, &GetDentryOptions{})\n+ if err != nil {\n+ return nil, err\n+ }\n+ defer vd.DecRef(ctx)\n+\n+ if flags&linux.O_DIRECTORY != 0 {\n+ stat, err := vfs.StatAt(ctx, creds, &PathOperation{\n+ Root: vd,\n+ Start: vd,\n+ }, &StatOptions{\n+ Mask: linux.STATX_MODE,\n+ })\n+ if err != nil {\n+ return nil, err\n+ }\n+ if stat.Mode&linux.S_IFDIR == 0 {\n+ return nil, linuxerr.ENOTDIR\n+ }\n+ }\n+\n+ fd := &opathFD{}\n+ if err := fd.vfsfd.Init(fd, flags, vd.Mount(), vd.Dentry(), &FileDescriptionOptions{}); err != nil {\n+ return nil, err\n+ }\n+ return &fd.vfsfd, err\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/vfs.go",
"new_path": "pkg/sentry/vfs/vfs.go",
"diff": "@@ -417,22 +417,13 @@ func (vfs *VirtualFilesystem) OpenAt(ctx context.Context, creds *auth.Credential\nif opts.Flags&linux.O_NOFOLLOW != 0 {\npop.FollowFinalSymlink = false\n}\n+ if opts.Flags&linux.O_PATH != 0 {\n+ return vfs.openOPathFD(ctx, creds, pop, opts.Flags)\n+ }\nrp := vfs.getResolvingPath(creds, pop)\nif opts.Flags&linux.O_DIRECTORY != 0 {\nrp.mustBeDir = true\n}\n- if opts.Flags&linux.O_PATH != 0 {\n- vd, err := vfs.GetDentryAt(ctx, creds, pop, &GetDentryOptions{})\n- if err != nil {\n- return nil, err\n- }\n- fd := &opathFD{}\n- if err := fd.vfsfd.Init(fd, opts.Flags, vd.Mount(), vd.Dentry(), &FileDescriptionOptions{}); err != nil {\n- return nil, err\n- }\n- vd.DecRef(ctx)\n- return &fd.vfsfd, err\n- }\nfor {\nfd, err := rp.mount.fs.impl.OpenAt(ctx, rp, *opts)\nif err == nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/open.cc",
"new_path": "test/syscalls/linux/open.cc",
"diff": "@@ -523,6 +523,14 @@ TEST_F(OpenTest, OpenWithOpath) {\nASSERT_NO_ERRNO(Open(path, O_PATH));\n}\n+// NOTE(b/236445327): Regression test. Opening a non-directory with O_PATH and\n+// O_DIRECTORY should fail with ENOTDIR.\n+TEST_F(OpenTest, OPathWithODirectory) {\n+ auto newFile = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n+ EXPECT_THAT(open(newFile.path().c_str(), O_RDONLY | O_DIRECTORY | O_PATH),\n+ SyscallFailsWithErrno(ENOTDIR));\n+}\n+\n} // namespace\n} // namespace testing\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add O_DIRECTORY support to openat(O_PATH) in VFS2.
VFS2 earlier was ignoring the effect of O_DIRECTORY with O_PATH.
PiperOrigin-RevId: 456147699 |
259,992 | 21.06.2022 09:54:32 | 25,200 | 5deab709e7e8c1a98396bf09aabba73b88924c97 | Add mode to procfs dump
Updates | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/procfs/BUILD",
"new_path": "runsc/boot/procfs/BUILD",
"diff": "@@ -7,6 +7,7 @@ go_library(\nsrcs = [\"dump.go\"],\nvisibility = [\"//runsc:__subpackages__\"],\ndeps = [\n+ \"//pkg/abi/linux\",\n\"//pkg/context\",\n\"//pkg/log\",\n\"//pkg/sentry/fsimpl/proc\",\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/procfs/dump.go",
"new_path": "runsc/boot/procfs/dump.go",
"diff": "@@ -21,6 +21,7 @@ import (\n\"fmt\"\n\"strings\"\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/fsimpl/proc\"\n@@ -36,6 +37,8 @@ type FDInfo struct {\nNumber int32 `json:\"number,omitempty\"`\n// Path is the path of the file that FD represents.\nPath string `json:\"path,omitempty\"`\n+ // Mode is the file mode.\n+ Mode uint16 `json:\"mode,omitempty\"`\n}\n// UIDGID contains information for /proc/[pid]/status/{uid,gid}.\n@@ -185,7 +188,13 @@ func getFDs(ctx context.Context, t *kernel.Task, pid kernel.ThreadID) []FDInfo {\nlog.Warningf(\"PathnameWithDeleted failed to find path for fd %d in PID %s: %v\", fd.no, pid, err)\npath = \"\"\n}\n- res = append(res, FDInfo{Number: fd.no, Path: path})\n+ mode := uint16(0)\n+ if statx, err := fd.fd.Stat(ctx, vfs.StatOptions{Mask: linux.STATX_MODE}); err != nil {\n+ log.Warningf(\"Stat(STATX_MODE) failed for fd %d in PID %s: %v\", fd.no, pid, err)\n+ } else {\n+ mode = statx.Mode\n+ }\n+ res = append(res, FDInfo{Number: fd.no, Path: path, Mode: mode})\n}\nreturn res\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/trace_test.go",
"new_path": "runsc/container/trace_test.go",
"diff": "@@ -22,6 +22,7 @@ import (\n\"time\"\nspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n+ \"golang.org/x/sys/unix\"\n\"google.golang.org/protobuf/proto\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/limits\"\n@@ -374,12 +375,16 @@ func TestProcfsDump(t *testing.T) {\nif len(procfsDump[0].FDs) < 3 {\nt.Errorf(\"expected at least 3 FDs for the sleep process, got %+v\", procfsDump[0].FDs)\n} else {\n+ modes := []uint16{unix.S_IFCHR, unix.S_IFIFO, unix.S_IFREG}\nfor i, fd := range procfsDump[0].FDs[:3] {\nif want := int32(i); fd.Number != want {\nt.Errorf(\"expected FD number %d, got %d\", want, fd.Number)\n}\nif wantSubStr := \"host\"; !strings.Contains(fd.Path, wantSubStr) {\n- t.Errorf(\"expected FD path to contain %q, got %q\", wantSubStr, fd.Path)\n+ t.Errorf(\"expected FD %d path to contain %q, got %q\", fd.Number, wantSubStr, fd.Path)\n+ }\n+ if want, got := modes[i], fd.Mode&unix.S_IFMT; uint16(want) != got {\n+ t.Errorf(\"wrong mode FD %d, want: %#o, got: %#o\", fd.Number, want, got)\n}\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add mode to procfs dump
Updates #4805
PiperOrigin-RevId: 456284312 |
259,992 | 21.06.2022 13:20:23 | 25,200 | ed38782b23dce6396c77be0868397bc696484396 | Remove omitempty for fields than can be 0
Some fields can have a legitimate value of 0 and that was
causing the field to be omitted from the output, giving the
impression that it hasn't been set.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_cgroup.go",
"new_path": "pkg/sentry/kernel/task_cgroup.go",
"diff": "@@ -180,7 +180,7 @@ func (t *Task) MigrateCgroup(dst Cgroup) error {\n// TaskCgroupEntry represents a line in /proc/<pid>/cgroup, and is used to\n// format a cgroup for display.\ntype TaskCgroupEntry struct {\n- HierarchyID uint32 `json:\"hierarchy_id,omitempty\"`\n+ HierarchyID uint32 `json:\"hierarchy_id\"`\nControllers string `json:\"controllers,omitempty\"`\nPath string `json:\"path,omitempty\"`\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/procfs/dump.go",
"new_path": "runsc/boot/procfs/dump.go",
"diff": "@@ -34,25 +34,25 @@ import (\n// FDInfo contains information about an application file descriptor.\ntype FDInfo struct {\n// Number is the FD number.\n- Number int32 `json:\"number,omitempty\"`\n+ Number int32 `json:\"number\"`\n// Path is the path of the file that FD represents.\nPath string `json:\"path,omitempty\"`\n// Mode is the file mode.\n- Mode uint16 `json:\"mode,omitempty\"`\n+ Mode uint16 `json:\"mode\"`\n}\n// UIDGID contains information for /proc/[pid]/status/{uid,gid}.\ntype UIDGID struct {\n- Real uint32 `json:\"real,omitempty\"`\n- Effective uint32 `json:\"effective,omitempty\"`\n- Saved uint32 `json:\"saved,omitempty\"`\n+ Real uint32 `json:\"real\"`\n+ Effective uint32 `json:\"effective\"`\n+ Saved uint32 `json:\"saved\"`\n}\n// Status contains information for /proc/[pid]/status.\ntype Status struct {\nComm string `json:\"comm,omitempty\"`\n- PID int32 `json:\"pid,omitempty\"`\n- PPID int32 `json:\"ppid,omitempty\"`\n+ PID int32 `json:\"pid\"`\n+ PPID int32 `json:\"ppid\"`\nUID UIDGID `json:\"uid,omitempty\"`\nGID UIDGID `json:\"gid,omitempty\"`\nVMSize uint64 `json:\"vm_size,omitempty\"`\n@@ -61,8 +61,8 @@ type Status struct {\n// Stat contains information for /proc/[pid]/stat.\ntype Stat struct {\n- PGID int32 `json:\"pgid,omitempty\"`\n- SID int32 `json:\"sid,omitempty\"`\n+ PGID int32 `json:\"pgid\"`\n+ SID int32 `json:\"sid\"`\n}\n// ProcessProcfsDump contains the procfs dump for one process. For more details\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove omitempty for fields than can be 0
Some fields can have a legitimate value of 0 and that was
causing the field to be omitted from the output, giving the
impression that it hasn't been set.
Updates #4805
PiperOrigin-RevId: 456335515 |
259,907 | 22.06.2022 10:17:32 | 25,200 | dadb72341a65b1f03691b46a099c0fc9b99d474e | Fix remaining comments to adhere to gofmt. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/task_files.go",
"new_path": "pkg/sentry/fsimpl/proc/task_files.go",
"diff": "@@ -226,6 +226,7 @@ func GetMetadata(ctx context.Context, mm *mm.MemoryManager, buf *bytes.Buffer, t\n}\n// metadataData implements vfs.DynamicBytesSource for proc metadata fields like:\n+//\n// - /proc/[pid]/cmdline\n// - /proc/[pid]/environ\n//\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/tracereplay/save.go",
"new_path": "tools/tracereplay/save.go",
"diff": "@@ -58,8 +58,7 @@ func (s *Save) Start() error {\n// of messages. Both JSON and messages are prefixed by an uint64 with their\n// size.\n//\n-// Ex:\n-// signature <size>Config JSON [<size>message]*\n+// Ex: signature <size>Config JSON [<size>message]*\nfunc (s *Save) NewClient() (server.MessageHandler, error) {\nseq := s.clientCount.Add(1)\nfilename := filepath.Join(s.dir, fmt.Sprintf(\"%s%04d\", s.prefix, seq))\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix remaining comments to adhere to gofmt.
PiperOrigin-RevId: 456544446 |
259,868 | 22.06.2022 17:06:28 | 25,200 | 164ca68bcd5ff3065a8f79353a99a479fd066bc2 | gVisor BuildKite `pre-command`: Clean Docker `RUNTIME` to not contain slashes.
Slashes in Docker runtime names break Docker. | [
{
"change_type": "MODIFY",
"old_path": ".buildkite/hooks/pre-command",
"new_path": ".buildkite/hooks/pre-command",
"diff": "@@ -31,7 +31,10 @@ PARTITION=$((${PARTITION}+1)) # 1-indexed, but PARALLEL_JOB is 0-indexed.\nexport TOTAL_PARTITIONS=${BUILDKITE_PARALLEL_JOB_COUNT:-1}\n# Set the system-wide Docker runtime name after the BuildKite branch name.\n-export RUNTIME=\"${BUILDKITE_BRANCH}-${BUILDKITE_BUILD_ID}\"\n+# Remove any slashes and other characters that are not supported in Docker\n+# runtime names. The runtime name must be a single valid path component.\n+export RUNTIME=\"buildkite_runtime_${BUILDKITE_BRANCH}-${BUILDKITE_BUILD_ID}\"\n+export RUNTIME=\"$(echo \"$RUNTIME\" | sed -r 's~[^-_a-z0-9]+~_~g')\"\n# Ensure Docker has experimental enabled.\nif [[ -n \"${STAGED_BINARIES:-}\" ]]; then\n"
}
] | Go | Apache License 2.0 | google/gvisor | gVisor BuildKite `pre-command`: Clean Docker `RUNTIME` to not contain slashes.
Slashes in Docker runtime names break Docker.
PiperOrigin-RevId: 456642822 |
259,868 | 23.06.2022 12:31:07 | 25,200 | 55776eca5f7bc13e22bc1e32cb5dfaa3bd822592 | integration_test: Make `TestTmpMountWithSize` error message less confusing.
If I understand correctly, this test expects the second write to fail, but
if it succeeds, the error message it shows suggests that it should have
failed.
This CL rewords this message to reflect that.
#codehealth | [
{
"change_type": "MODIFY",
"old_path": "test/e2e/integration_test.go",
"new_path": "test/e2e/integration_test.go",
"diff": "@@ -944,7 +944,7 @@ func TestTmpMountWithSize(t *testing.T) {\n}\nechoOutput, err := d.Exec(ctx, dockerutil.ExecOpts{}, \"/bin/sh\", \"-c\", \"echo world > /tmp/foo/test2.txt\")\nif err == nil {\n- t.Fatalf(\"docker exec size check failed: %v\", err)\n+ t.Fatalf(\"docker exec size check unexpectedly succeeded (output: %v)\", echoOutput)\n}\nwantErr := \"No space left on device\"\nif !strings.Contains(echoOutput, wantErr) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | integration_test: Make `TestTmpMountWithSize` error message less confusing.
If I understand correctly, this test expects the second write to fail, but
if it succeeds, the error message it shows suggests that it should have
failed.
This CL rewords this message to reflect that.
#codehealth
PiperOrigin-RevId: 456835892 |
259,907 | 23.06.2022 13:31:44 | 25,200 | c1111baf6cc0d9ad845be8e8de240e836ada5ffa | Allow strace logs for symlinkat(2) to print FD.
Helps with debugging issues that involve symlinkat(2). FD also
prints the path file that the FD backs which is helpful. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/strace/linux64_amd64.go",
"new_path": "pkg/sentry/strace/linux64_amd64.go",
"diff": "@@ -291,7 +291,7 @@ var linuxAMD64 = SyscallMap{\n263: makeSyscallInfo(\"unlinkat\", FD, Path, Hex),\n264: makeSyscallInfo(\"renameat\", FD, Path, Hex, Path),\n265: makeSyscallInfo(\"linkat\", FD, Path, Hex, Path, Hex),\n- 266: makeSyscallInfo(\"symlinkat\", Path, Hex, Path),\n+ 266: makeSyscallInfo(\"symlinkat\", Path, FD, Path),\n267: makeSyscallInfo(\"readlinkat\", FD, Path, ReadBuffer, Hex),\n268: makeSyscallInfo(\"fchmodat\", FD, Path, Mode),\n269: makeSyscallInfo(\"faccessat\", FD, Path, Oct, Hex),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/strace/linux64_arm64.go",
"new_path": "pkg/sentry/strace/linux64_arm64.go",
"diff": "@@ -61,7 +61,7 @@ var linuxARM64 = SyscallMap{\n33: makeSyscallInfo(\"mknodat\", FD, Path, Mode, Hex),\n34: makeSyscallInfo(\"mkdirat\", FD, Path, Hex),\n35: makeSyscallInfo(\"unlinkat\", FD, Path, Hex),\n- 36: makeSyscallInfo(\"symlinkat\", Path, Hex, Path),\n+ 36: makeSyscallInfo(\"symlinkat\", Path, FD, Path),\n37: makeSyscallInfo(\"linkat\", FD, Path, Hex, Path, Hex),\n38: makeSyscallInfo(\"renameat\", FD, Path, Hex, Path),\n39: makeSyscallInfo(\"umount2\", Path, Hex),\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow strace logs for symlinkat(2) to print FD.
Helps with debugging issues that involve symlinkat(2). FD also
prints the path file that the FD backs which is helpful.
PiperOrigin-RevId: 456849268 |
259,868 | 23.06.2022 16:21:38 | 25,200 | cf533616cb27a03bd75522d35a12eb0ab2e3abe9 | BuildKite pre-command: Use alternate way to reload Docker when available. | [
{
"change_type": "MODIFY",
"old_path": ".buildkite/hooks/pre-command",
"new_path": ".buildkite/hooks/pre-command",
"diff": "@@ -36,7 +36,15 @@ export TOTAL_PARTITIONS=${BUILDKITE_PARALLEL_JOB_COUNT:-1}\nexport RUNTIME=\"buildkite_runtime_${BUILDKITE_BRANCH}-${BUILDKITE_BUILD_ID}\"\nexport RUNTIME=\"$(echo \"$RUNTIME\" | sed -r 's~[^-_a-z0-9]+~_~g')\"\n-# Ensure Docker has experimental enabled.\n+# If running in a container, set the reload command appropriately.\n+if [[ -x /tmp/buildkite-reload-host-docker/reload ]]; then\n+ export DOCKER_RELOAD_COMMAND='/tmp/buildkite-reload-host-docker/reload'\n+else\n+ export DOCKER_RELOAD_COMMAND='sudo systemctl reload docker'\n+fi\n+\n+# Ensure Docker has experimental enabled, install runtimes.\n+HAD_EXPERIMENTAL=\"$(docker version --format='{{.Server.Experimental}}')\"\nif [[ -n \"${STAGED_BINARIES:-}\" ]]; then\n# Used `runsc` from STAGED_BINARIES instead of building it from scratch.\ntmpdir=\"$(mktemp -d)\"\n@@ -49,9 +57,16 @@ else\nmake sudo TARGETS=//runsc:runsc \\\nARGS=\"install --experimental=true --runtime=${RUNTIME} -- ${RUNTIME_ARGS:-}\"\nfi\n+if [[ \"$HAD_EXPERIMENTAL\" == false ]]; then\n# WARNING: We may be running in a container when this command executes.\n# This only makes sense if Docker's `live-restore` feature is enabled.\nsudo systemctl restart docker\n+else\n+ # If experimental-ness was already enabled, we don't need to restart, as the\n+ # only thing we modified is the list of runtimes, which can be reloaded with\n+ # just a SIGHUP.\n+ bash -c \"$DOCKER_RELOAD_COMMAND\"\n+fi\n# Helper for benchmarks, based on the branch.\nif test \"${BUILDKITE_BRANCH}\" = \"master\"; then\n"
},
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -102,7 +102,8 @@ endif\n## RUNTIME_ARGS - Arguments passed to the runtime when installed.\n## STAGED_BINARIES - A tarball of staged binaries. If this is set, then binaries\n## will be installed from this staged bundle instead of built.\n-##\n+## DOCKER_RELOAD_COMMAND - The command to run to reload Docker. (default: sudo systemctl reload docker).\n+\nifeq (,$(BRANCH_NAME))\nRUNTIME := runsc\nRUNTIME_DIR := $(shell dirname $(shell mktemp -u))/$(RUNTIME)\n@@ -114,6 +115,7 @@ RUNTIME_BIN := $(RUNTIME_DIR)/runsc\nRUNTIME_LOG_DIR := $(RUNTIME_DIR)/logs\nRUNTIME_LOGS := $(RUNTIME_LOG_DIR)/runsc.log.%TEST%.%TIMESTAMP%.%COMMAND%\nRUNTIME_ARGS ?=\n+DOCKER_RELOAD_COMMAND ?= sudo systemctl reload docker\nifeq ($(shell stat -f -c \"%T\" /sys/fs/cgroup 2>/dev/null),cgroup2fs)\nCGROUPV2 := true\n@@ -138,7 +140,8 @@ configure_noreload = \\\nsudo $(RUNTIME_BIN) install --experimental=true --runtime=\"$(1)\" -- $(RUNTIME_ARGS) --debug-log \"$(RUNTIME_LOGS)\" $(2) && \\\nsudo rm -rf \"$(RUNTIME_LOG_DIR)\" && mkdir -p \"$(RUNTIME_LOG_DIR)\"\nreload_docker = \\\n- sudo systemctl reload docker && \\\n+ $(call header,DOCKER RELOAD); \\\n+ bash -xc \"$(DOCKER_RELOAD_COMMAND)\" && \\\nif test -f /etc/docker/daemon.json; then \\\nsudo chmod 0755 /etc/docker && \\\nsudo chmod 0644 /etc/docker/daemon.json; \\\n"
}
] | Go | Apache License 2.0 | google/gvisor | BuildKite pre-command: Use alternate way to reload Docker when available.
PiperOrigin-RevId: 456884864 |
259,868 | 23.06.2022 17:12:20 | 25,200 | bd90c6b241ce53d31173c9689a8c37f44ae85216 | Makefile: Set `RUNTIME_DIR` actually work the way it is documented.
Prior to this, setting `RUNTIME_DIR` had no effect, as the Makefile always
clobbered it. | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -94,7 +94,7 @@ endif\n## These targets faciliate local development by automatically\n## installing and configuring a runtime. Several variables may\n## be used here to tweak the installation:\n-## RUNTIME - The name of the installed runtime (default: branch).\n+## RUNTIME - The name of the installed runtime (default: $BRANCH_NAME).\n## RUNTIME_DIR - Where the runtime will be installed (default: temporary directory with the $RUNTIME).\n## RUNTIME_BIN - The runtime binary (default: $RUNTIME_DIR/runsc).\n## RUNTIME_LOG_DIR - The logs directory (default: $RUNTIME_DIR/logs).\n@@ -106,11 +106,10 @@ endif\nifeq (,$(BRANCH_NAME))\nRUNTIME := runsc\n-RUNTIME_DIR := $(shell dirname $(shell mktemp -u))/$(RUNTIME)\nelse\nRUNTIME := $(BRANCH_NAME)\n-RUNTIME_DIR := $(shell dirname $(shell mktemp -u))/$(RUNTIME)\nendif\n+RUNTIME_DIR ?= $(shell dirname $(shell mktemp -u))/$(RUNTIME)\nRUNTIME_BIN := $(RUNTIME_DIR)/runsc\nRUNTIME_LOG_DIR := $(RUNTIME_DIR)/logs\nRUNTIME_LOGS := $(RUNTIME_LOG_DIR)/runsc.log.%TEST%.%TIMESTAMP%.%COMMAND%\n"
}
] | Go | Apache License 2.0 | google/gvisor | Makefile: Set `RUNTIME_DIR` actually work the way it is documented.
Prior to this, setting `RUNTIME_DIR` had no effect, as the Makefile always
clobbered it.
PiperOrigin-RevId: 456893921 |
259,868 | 23.06.2022 17:46:34 | 25,200 | ffabadf0108addafd94f3429b3998a84d89b6c58 | BuildKite: Install runtime using `STAGED_BINARIES`, clean it up properly.
Prior to this, `STAGED_BINARIES` was executed as a command
(`$(STAGED_BINARIES)`), which didn't work. This change fixes this, and adds
cleanup of the runtime directory in `post-command`. | [
{
"change_type": "MODIFY",
"old_path": ".buildkite/hooks/post-command",
"new_path": ".buildkite/hooks/post-command",
"diff": "+set -x\n+\n# Clear any downloaded credentials.\nrm -f repo.key\n@@ -71,3 +73,18 @@ for container in $(docker ps -q); do\ndocker container kill \"${container}\"\nfi\ndone\n+\n+set -euo pipefail\n+\n+# Remove all Docker runtimes that may be installed.\n+if grep -qE runtimes /etc/docker/daemon.json; then\n+ cat /etc/docker/daemon.json | jq 'del(.runtimes) + {runtimes: {}}' \\\n+ | sudo tee /etc/docker/daemon.json.tmp\n+ sudo mv /etc/docker/daemon.json.tmp /etc/docker/daemon.json\n+ bash -c \"$DOCKER_RELOAD_COMMAND\"\n+fi\n+\n+# Cleanup temporary directory where STAGED_BINARIES may have been extracted.\n+if [[ -n \"${BUILDKITE_STAGED_BINARIES_DIRECTORY:-}\" ]]; then\n+ rm -rf \"$BUILDKITE_STAGED_BINARIES_DIRECTORY\" || true\n+fi\n"
},
{
"change_type": "MODIFY",
"old_path": ".buildkite/hooks/pre-command",
"new_path": ".buildkite/hooks/pre-command",
"diff": "+set -euo pipefail\n+\n# Download any build-specific configuration that has been uploaded.\n# This allows top-level steps to override all subsequent steps.\nbuildkite-agent artifact download 'tools/bazeldefs/*' . || true\n@@ -47,12 +49,13 @@ fi\nHAD_EXPERIMENTAL=\"$(docker version --format='{{.Server.Experimental}}')\"\nif [[ -n \"${STAGED_BINARIES:-}\" ]]; then\n# Used `runsc` from STAGED_BINARIES instead of building it from scratch.\n- tmpdir=\"$(mktemp -d)\"\n- gsutil cat \"$(STAGED_BINARIES)\" | tar -C \"$tmpdir\" -zxvf - runsc\n- chmod +x \"$tmpdir/runsc\"\n- \"$tmpdir/runsc\" install --experimental=true --runtime=\"${RUNTIME}\" \\\n+ export BUILDKITE_STAGED_BINARIES_DIRECTORY=\"$(mktemp -d)\"\n+ gsutil cat \"$STAGED_BINARIES\" \\\n+ | tar -C \"$BUILDKITE_STAGED_BINARIES_DIRECTORY\" -zxvf - runsc\n+ chmod +x \"$BUILDKITE_STAGED_BINARIES_DIRECTORY/runsc\"\n+ sudo \"$BUILDKITE_STAGED_BINARIES_DIRECTORY/runsc\" install \\\n+ --experimental=true --runtime=\"${RUNTIME}\" \\\n-- \"${RUNTIME_ARGS:-}\"\n- rm -rf \"$tmpdir\"\nelse\nmake sudo TARGETS=//runsc:runsc \\\nARGS=\"install --experimental=true --runtime=${RUNTIME} -- ${RUNTIME_ARGS:-}\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | BuildKite: Install runtime using `STAGED_BINARIES`, clean it up properly.
Prior to this, `STAGED_BINARIES` was executed as a command
(`$(STAGED_BINARIES)`), which didn't work. This change fixes this, and adds
cleanup of the runtime directory in `post-command`.
PiperOrigin-RevId: 456900530 |
259,909 | 24.06.2022 13:46:42 | 25,200 | efdc289a96e5bae0b5a28d705b86a711f8458d04 | Add nil receiver and io methods to bufferv2.
Allowing for nil receivers in read-like operations lets views be treated
more like slices, which is easier for the programmer generally.
io methods are useful for copy operations to avoid unnecessary allocations. | [
{
"change_type": "MODIFY",
"old_path": "pkg/bufferv2/buffer.go",
"new_path": "pkg/bufferv2/buffer.go",
"diff": "@@ -294,13 +294,13 @@ func (b *Buffer) prependOwned(v *View) {\n}\n// PullUp makes the specified range contiguous and returns the backing memory.\n-func (b *Buffer) PullUp(offset, length int) (*View, bool) {\n+func (b *Buffer) PullUp(offset, length int) (View, bool) {\nif length == 0 {\n- return nil, true\n+ return View{}, true\n}\ntgt := Range{begin: offset, end: offset + length}\nif tgt.Intersect(Range{end: int(b.size)}).Len() != length {\n- return nil, false\n+ return View{}, false\n}\ncurr := Range{}\n@@ -312,12 +312,13 @@ func (b *Buffer) PullUp(offset, length int) (*View, bool) {\nif x := curr.Intersect(tgt); x.Len() == tgt.Len() {\n// buf covers the whole requested target range.\nsub := x.Offset(-curr.begin)\n- new := viewPool.Get().(*View)\n- new.read = sub.begin\n- new.write = sub.end\n// Don't increment the reference count of the underlying chunk. Views\n// returned by PullUp are explicitly unowned and read only\n- new.chunk = v.chunk\n+ new := View{\n+ read: v.read + sub.begin,\n+ write: v.read + sub.end,\n+ chunk: v.chunk,\n+ }\nreturn new, true\n} else if x.Len() > 0 {\n// buf is pointing at the starting buffer we want to merge.\n@@ -357,10 +358,11 @@ func (b *Buffer) PullUp(offset, length int) (*View, bool) {\nb.removeView(v)\nr := tgt.Offset(-curr.begin)\n- pulled := viewPool.Get().(*View)\n- pulled.read = r.begin\n- pulled.write = r.end\n- pulled.chunk = merged.chunk\n+ pulled := View{\n+ read: r.begin,\n+ write: r.end,\n+ chunk: merged.chunk,\n+ }\nreturn pulled, true\n}\n@@ -418,11 +420,11 @@ func (b *Buffer) Apply(fn func(*View)) {\n// outside of b is ignored.\nfunc (b *Buffer) SubApply(offset, length int, fn func(*View)) {\nfor v := b.data.Front(); length > 0 && v != nil; v = v.Next() {\n- d := v.Clone()\n- if offset >= d.Size() {\n- offset -= d.Size()\n+ if offset >= v.Size() {\n+ offset -= v.Size()\ncontinue\n}\n+ d := v.Clone()\nif offset > 0 {\nd.TrimFront(offset)\noffset = 0\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/bufferv2/buffer_test.go",
"new_path": "pkg/bufferv2/buffer_test.go",
"diff": "@@ -612,7 +612,7 @@ func TestBufferPullUp(t *testing.T) {\ngot, gotOk := b.PullUp(tc.offset, tc.length)\nwant, wantOk := []byte(tc.output), !tc.failed\n- if gotOk == wantOk && got == nil && len(want) == 0 {\n+ if gotOk == wantOk && got.Size() == 0 && len(want) == 0 {\nreturn\n}\nif gotOk != wantOk || !bytes.Equal(got.AsSlice(), want) {\n@@ -630,6 +630,25 @@ func TestBufferPullUp(t *testing.T) {\n}\n}\n+func TestPullUpModifiedViews(t *testing.T) {\n+ var b Buffer\n+ defer b.Release()\n+ for _, s := range []string{\"abcdef\", \"123456\", \"ghijkl\"} {\n+ v := NewViewWithData([]byte(s))\n+ v.TrimFront(3)\n+ b.appendOwned(v)\n+ }\n+\n+ v, ok := b.PullUp(3, 3)\n+ if !ok {\n+ t.Errorf(\"PullUp failed: want ok=true, got ok=false\")\n+ }\n+ want := []byte(\"456\")\n+ if !bytes.Equal(v.AsSlice(), want) {\n+ t.Errorf(\"PullUp failed: want %v, got %v\", want, v.AsSlice())\n+ }\n+}\n+\nfunc TestBufferClone(t *testing.T) {\nconst (\noriginalSize = 90\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/bufferv2/view.go",
"new_path": "pkg/bufferv2/view.go",
"diff": "@@ -21,6 +21,10 @@ import (\n\"gvisor.dev/gvisor/pkg/sync\"\n)\n+// ReadSize is the default amount that a View's size is increased by when an\n+// io.Reader has more data than a View can hold during calls to ReadFrom.\n+const ReadSize = 512\n+\nvar viewPool = sync.Pool{\nNew: func() interface{} {\nreturn &View{}\n@@ -42,8 +46,6 @@ var viewPool = sync.Pool{\n// must use Write/WriteAt/CopyIn to modify the underlying View. This preserves\n// the safety guarantees of copy-on-write.\ntype View struct {\n- sync.NoCopy\n-\nviewEntry\nread int\nwrite int\n@@ -84,6 +86,9 @@ func NewViewWithData(data []byte) *View {\n// The caller must own the View to call Clone. It is not safe to call Clone\n// on a borrowed or shared View because it can race with other View methods.\nfunc (v *View) Clone() *View {\n+ if v == nil {\n+ panic(\"cannot clone a nil view\")\n+ }\nv.chunk.IncRef()\nnewV := viewPool.Get().(*View)\nnewV.chunk = v.chunk\n@@ -94,6 +99,9 @@ func (v *View) Clone() *View {\n// Release releases the chunk held by v and returns v to the pool.\nfunc (v *View) Release() {\n+ if v == nil {\n+ panic(\"cannot release a nil view\")\n+ }\nv.chunk.DecRef()\n*v = View{}\nviewPool.Put(v)\n@@ -112,16 +120,25 @@ func (v *View) Full() bool {\n// Capacity returns the total size of this view's chunk.\nfunc (v *View) Capacity() int {\n+ if v == nil {\n+ return 0\n+ }\nreturn len(v.chunk.data)\n}\n// Size returns the size of data written to the view.\nfunc (v *View) Size() int {\n+ if v == nil {\n+ return 0\n+ }\nreturn v.write - v.read\n}\n// TrimFront advances the read index by the given amount.\nfunc (v *View) TrimFront(n int) {\n+ if v.read+n > v.write {\n+ panic(\"cannot trim past the end of a view\")\n+ }\nv.read += n\n}\n@@ -135,6 +152,9 @@ func (v *View) AsSlice() []byte {\n// AvailableSize returns the number of bytes available for writing.\nfunc (v *View) AvailableSize() int {\n+ if v == nil {\n+ return 0\n+ }\nreturn len(v.chunk.data) - v.write\n}\n@@ -153,6 +173,26 @@ func (v *View) Read(p []byte) (int, error) {\nreturn n, nil\n}\n+// WriteTo writes data to w until the view is empty or an error occurs. The\n+// return value n is the number of bytes written.\n+//\n+// WriteTo implements the io.WriterTo interface.\n+func (v *View) WriteTo(w io.Writer) (n int64, err error) {\n+ if v.Size() > 0 {\n+ sz := v.Size()\n+ m, e := w.Write(v.AsSlice())\n+ v.TrimFront(m)\n+ n = int64(m)\n+ if e != nil {\n+ return n, e\n+ }\n+ if m != sz {\n+ return n, io.ErrShortWrite\n+ }\n+ }\n+ return n, nil\n+}\n+\n// ReadAt reads data to the p starting at offset.\n//\n// Implements the io.ReaderAt interface.\n@@ -170,24 +210,62 @@ func (v *View) ReadAt(p []byte, off int) (int, error) {\n//\n// Implements the io.Writer interface.\nfunc (v *View) Write(p []byte) (int, error) {\n- if v.sharesChunk() {\n+ if v == nil {\n+ panic(\"cannot write to a nil view\")\n+ }\n+ if v.AvailableSize() < len(p) {\n+ v.growCap(len(p) - v.AvailableSize())\n+ } else if v.sharesChunk() {\ndefer v.chunk.DecRef()\nv.chunk = v.chunk.Clone()\n}\nn := copy(v.chunk.data[v.write:], p)\nv.write += n\nif n < len(p) {\n- return n, fmt.Errorf(\"could not finish write: want len(p) <= v.AvailableSize(), got len(p)=%d, v.AvailableSize()=%d\", len(p), v.AvailableSize())\n+ return n, io.ErrShortWrite\n}\nreturn n, nil\n}\n+// ReadFrom reads data from r until EOF and appends it to the buffer, growing\n+// the buffer as needed. The return value n is the number of bytes read. Any\n+// error except io.EOF encountered during the read is also returned.\n+//\n+// ReadFrom implements the io.ReaderFrom interface.\n+func (v *View) ReadFrom(r io.Reader) (n int64, err error) {\n+ if v == nil {\n+ panic(\"cannot write to a nil view\")\n+ }\n+ if v.sharesChunk() {\n+ defer v.chunk.DecRef()\n+ v.chunk = v.chunk.Clone()\n+ }\n+ for {\n+ if v.AvailableSize() == 0 {\n+ v.growCap(ReadSize)\n+ }\n+ m, e := r.Read(v.availableSlice())\n+ v.write += m\n+ n += int64(m)\n+\n+ if e == io.EOF {\n+ return n, nil\n+ }\n+ if e != nil {\n+ return n, e\n+ }\n+ }\n+}\n+\n// WriteAt writes data to the views's chunk starting at start. If the\n// view's chunk has a reference count greater than 1, the chunk is copied first\n// and then written to.\n//\n// Implements the io.WriterAt interface.\nfunc (v *View) WriteAt(p []byte, off int) (int, error) {\n+ if v == nil {\n+ panic(\"cannot write to a nil view\")\n+ }\nif off < 0 || off > v.Size() {\nreturn 0, fmt.Errorf(\"write offset out of bounds: want 0 < off < %d, got off=%d\", v.Size(), off)\n}\n@@ -197,22 +275,43 @@ func (v *View) WriteAt(p []byte, off int) (int, error) {\n}\nn := copy(v.AsSlice()[off:], p)\nif n < len(p) {\n- return n, fmt.Errorf(\"could not finish write: want off + len(p) < v.Capacity(), got off=%d, len(p)=%d ,v.Size() = %d\", off, len(p), v.Size())\n+ return n, io.ErrShortWrite\n}\nreturn n, nil\n}\n-// Grow advances the write index by the given amount.\n+// Grow increases the size of the view. If the new size is greater than the\n+// view's current capacity, Grow will reallocate the view with an increased\n+// capacity.\nfunc (v *View) Grow(n int) {\n- if n+v.write > v.Capacity() {\n- panic(\"cannot grow view past capacity\")\n+ if v == nil {\n+ panic(\"cannot grow a nil view\")\n+ }\n+ if v.write+n > v.Capacity() {\n+ v.growCap(n)\n}\nv.write += n\n}\n+// growCap increases the capacity of the view by at least n.\n+func (v *View) growCap(n int) {\n+ if v == nil {\n+ panic(\"cannot grow a nil view\")\n+ }\n+ defer v.chunk.DecRef()\n+ old := v.AsSlice()\n+ v.chunk = newChunk(v.Capacity() + n)\n+ copy(v.chunk.data, old)\n+ v.read = 0\n+ v.write = len(old)\n+}\n+\n// CapLength caps the length of the view's read slice to n. If n > v.Size(),\n// the function is a no-op.\nfunc (v *View) CapLength(n int) {\n+ if v == nil {\n+ panic(\"cannot resize a nil view\")\n+ }\nif n < 0 {\npanic(\"n must be >= 0\")\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/bufferv2/view_test.go",
"new_path": "pkg/bufferv2/view_test.go",
"diff": "package buffer\nimport (\n+ \"bytes\"\n\"math/rand\"\n\"testing\"\n@@ -80,7 +81,7 @@ func TestWrite(t *testing.T) {\nfor _, tc := range []struct {\nname string\nview *View\n- initData []byte\n+ initSize int\nwriteSize int\n}{\n{\n@@ -91,45 +92,41 @@ func TestWrite(t *testing.T) {\n{\nname: \"full view\",\nview: NewView(100),\n- initData: make([]byte, 100),\n+ initSize: 100,\nwriteSize: 50,\n},\n{\nname: \"full write to partially full view\",\nview: NewView(100),\n- initData: make([]byte, 20),\n+ initSize: 20,\nwriteSize: 50,\n},\n{\nname: \"partial write to partially full view\",\nview: NewView(100),\n- initData: make([]byte, 80),\n+ initSize: 80,\nwriteSize: 50,\n},\n} {\nt.Run(tc.name, func(t *testing.T) {\n- tc.view.Write(tc.initData)\n+ tc.view.Grow(tc.initSize)\ndefer tc.view.Release()\n- origWriteSize := tc.view.AvailableSize()\n-\n- var orig []byte\n- orig = append(orig, tc.view.AsSlice()...)\n+ orig := append([]byte(nil), tc.view.AsSlice()...)\ntoWrite := make([]byte, tc.writeSize)\nrand.Read(toWrite)\n- n, _ := tc.view.Write(toWrite)\n-\n- if n > origWriteSize {\n- t.Errorf(\"got tc.view.Write() = %d, want <=%d\", n, origWriteSize)\n+ n, err := tc.view.Write(toWrite)\n+ if err != nil {\n+ t.Errorf(\"Write failed: %s\", err)\n}\n- if tc.writeSize > origWriteSize {\n- toWrite = toWrite[:origWriteSize]\n+ if n != tc.writeSize {\n+ t.Errorf(\"got n=%d, want %d\", n, tc.writeSize)\n}\n- if tc.view.AvailableSize() != tc.view.Capacity()-(len(toWrite)+len(orig)) {\n- t.Errorf(\"got tc.view.WriteSize() = %d, want %d\", tc.view.AvailableSize(), tc.view.Capacity()-(len(toWrite)+len(orig)))\n+ if tc.view.Size() != len(orig)+tc.writeSize {\n+ t.Errorf(\"got Size()=%d, want %d\", tc.view.Size(), len(orig)+tc.writeSize)\n}\nif !cmp.Equal(tc.view.AsSlice(), append(orig, toWrite...)) {\n- t.Errorf(\"got tc.view.ReadSlice() = %d, want %d\", tc.view.AsSlice(), toWrite)\n+ t.Errorf(\"got tc.view.AsSlice() = %d, want %d\", tc.view.AsSlice(), toWrite)\n}\n})\n}\n@@ -172,3 +169,61 @@ func TestWriteAt(t *testing.T) {\nt.Errorf(\"got v.AsSlice()[:off] = %v, want %v\", v.AsSlice()[:off], orig.AsSlice()[:off])\n}\n}\n+\n+func TestWriteTo(t *testing.T) {\n+ writeToSize := 100\n+ v := NewViewSize(writeToSize)\n+ defer v.Release()\n+\n+ w := bytes.NewBuffer(make([]byte, 100))\n+\n+ n, err := v.WriteTo(w)\n+ if err != nil {\n+ t.Errorf(\"WriteTo failed: %s\", err)\n+ }\n+ if n != int64(writeToSize) {\n+ t.Errorf(\"got n=%d, want 100\", n)\n+ }\n+ if v.Size() != 0 {\n+ t.Errorf(\"got v.Size()=%d, want 0\", v.Size())\n+ }\n+}\n+\n+func TestReadFrom(t *testing.T) {\n+ for _, tc := range []struct {\n+ name string\n+ data []byte\n+ view *View\n+ }{\n+ {\n+ name: \"basic\",\n+ data: []byte{1, 2, 3},\n+ view: NewView(10),\n+ },\n+ {\n+ name: \"requires grow\",\n+ data: []byte{4, 5, 6},\n+ view: NewViewSize(63),\n+ },\n+ } {\n+ defer tc.view.Release()\n+ clone := tc.view.Clone()\n+ defer clone.Release()\n+ r := bytes.NewReader(tc.data)\n+\n+ n, err := tc.view.ReadFrom(r)\n+\n+ if err != nil {\n+ t.Errorf(\"v.ReadFrom failed: %s\", err)\n+ }\n+ if int(n) != len(tc.data) {\n+ t.Errorf(\"v.ReadFrom failed: want n=%d, got %d\", len(tc.data), n)\n+ }\n+ if tc.view.Size() == clone.Size() {\n+ t.Errorf(\"expected clone.Size() != v.Size(), got match\")\n+ }\n+ if !bytes.Equal(tc.view.AsSlice(), append(clone.AsSlice(), tc.data...)) {\n+ t.Errorf(\"v.ReadFrom failed: want %v, got %v\", tc.data, tc.view.AsSlice())\n+ }\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add nil receiver and io methods to bufferv2.
Allowing for nil receivers in read-like operations lets views be treated
more like slices, which is easier for the programmer generally.
io methods are useful for copy operations to avoid unnecessary allocations.
PiperOrigin-RevId: 457086370 |
259,909 | 27.06.2022 15:50:38 | 25,200 | 953d8d129b894a5886e9761cee2361b12d8e88e0 | Create configuration flags to control buffer pooling. | [
{
"change_type": "MODIFY",
"old_path": "pkg/bufferv2/BUILD",
"new_path": "pkg/bufferv2/BUILD",
"diff": "@@ -6,7 +6,7 @@ package(licenses = [\"notice\"])\ngo_template_instance(\nname = \"chunk_refs\",\nout = \"chunk_refs.go\",\n- package = \"buffer\",\n+ package = \"bufferv2\",\nprefix = \"chunk\",\ntemplate = \"//pkg/refsvfs2:refs_template\",\ntypes = {\n@@ -17,7 +17,7 @@ go_template_instance(\ngo_template_instance(\nname = \"view_list\",\nout = \"view_list.go\",\n- package = \"buffer\",\n+ package = \"bufferv2\",\nprefix = \"view\",\ntemplate = \"//pkg/ilist:generic_list\",\ntypes = {\n@@ -27,7 +27,7 @@ go_template_instance(\n)\ngo_library(\n- name = \"buffer\",\n+ name = \"bufferv2\",\nsrcs = [\n\"buffer.go\",\n\"buffer_state.go\",\n@@ -51,13 +51,12 @@ go_library(\n)\ngo_test(\n- name = \"buffer_test\",\n- size = \"small\",\n+ name = \"bufferv2_test\",\nsrcs = [\n\"buffer_test.go\",\n\"view_test.go\",\n],\n- library = \":buffer\",\n+ library = \":bufferv2\",\ndeps = [\n\"//pkg/state\",\n\"@com_github_google_go_cmp//cmp:go_default_library\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/bufferv2/buffer.go",
"new_path": "pkg/bufferv2/buffer.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// Package buffer provides the implementation of a non-contiguous buffer.\n-//\n-// A buffer is an flexible buffer, supporting the safecopy operations natively\n-// as well as the ability to grow via either prepend or append, as well as shrink.\n-package buffer\n+// Package bufferv2 provides the implementation of a non-contiguous buffer that\n+// is reference counted, pooled, and copy-on-write. It allows O(1) append,\n+// and prepend operations.\n+package bufferv2\nimport (\n\"fmt\"\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/bufferv2/buffer_state.go",
"new_path": "pkg/bufferv2/buffer_state.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-package buffer\n+package bufferv2\n// saveBuf is invoked by stateify.\nfunc (b *Buffer) saveData() []byte {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/bufferv2/buffer_test.go",
"new_path": "pkg/bufferv2/buffer_test.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-package buffer\n+package bufferv2\nimport (\n\"bytes\"\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/bufferv2/chunk.go",
"new_path": "pkg/bufferv2/chunk.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-package buffer\n+package bufferv2\nimport (\n\"fmt\"\n@@ -21,6 +21,12 @@ import (\n\"gvisor.dev/gvisor/pkg/sync\"\n)\n+// PoolingEnabled is set to true when pooling is enabled. Added as a\n+// global to allow easy access.\n+//\n+// TODO(b/236996271): Remove once buffer pooling experiment complete.\n+var PoolingEnabled = true\n+\nconst (\n// This is log2(baseChunkSize). This number is used to calculate which pool\n// to use for a payload size by right shifting the payload size by this\n@@ -78,7 +84,7 @@ type chunk struct {\nfunc newChunk(size int) *chunk {\nvar c *chunk\n- if size > maxChunkSize {\n+ if !PoolingEnabled || size > maxChunkSize {\nc = &chunk{\ndata: make([]byte, size),\n}\n@@ -94,7 +100,7 @@ func newChunk(size int) *chunk {\n}\nfunc (c *chunk) destroy() {\n- if len(c.data) > maxChunkSize {\n+ if !PoolingEnabled || len(c.data) > maxChunkSize {\nc.data = nil\nreturn\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/bufferv2/view.go",
"new_path": "pkg/bufferv2/view.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-package buffer\n+package bufferv2\nimport (\n\"fmt\"\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/bufferv2/view_test.go",
"new_path": "pkg/bufferv2/view_test.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-package buffer\n+package bufferv2\nimport (\n\"bytes\"\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/bufferv2/view_unsafe.go",
"new_path": "pkg/bufferv2/view_unsafe.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-package buffer\n+package bufferv2\nimport (\n\"reflect\"\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/BUILD",
"new_path": "runsc/boot/BUILD",
"diff": "@@ -29,6 +29,7 @@ go_library(\n\"//pkg/abi\",\n\"//pkg/abi/linux\",\n\"//pkg/bpf\",\n+ \"//pkg/bufferv2\",\n\"//pkg/cleanup\",\n\"//pkg/context\",\n\"//pkg/control/server\",\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader.go",
"new_path": "runsc/boot/loader.go",
"diff": "@@ -27,6 +27,7 @@ import (\n\"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/bpf\"\n+ \"gvisor.dev/gvisor/pkg/bufferv2\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/coverage\"\n\"gvisor.dev/gvisor/pkg/cpuid\"\n@@ -251,6 +252,7 @@ func New(args Args) (*Loader, error) {\nkernel.VFS2Enabled = true\nkernel.FUSEEnabled = args.Conf.FUSE\nkernel.LISAFSEnabled = args.Conf.Lisafs\n+ bufferv2.PoolingEnabled = args.Conf.BufferPooling\nvfs2.Override()\n// Make host FDs stable between invocations. Host FDs must map to the exact\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/config/config.go",
"new_path": "runsc/config/config.go",
"diff": "@@ -226,6 +226,9 @@ type Config struct {\n// take during pod creation.\nPodInitConfig string `flag:\"pod-init-config\"`\n+ // Use pools to manage buffer memory instead of heap.\n+ BufferPooling bool `flag:\"buffer-pooling\"`\n+\n// TestOnlyAllowRunAsCurrentUserWithoutChroot should only be used in\n// tests. It allows runsc to start the sandbox process as the current\n// user, and without chrooting the sandbox process. This can be\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/config/flags.go",
"new_path": "runsc/config/flags.go",
"diff": "@@ -94,6 +94,7 @@ func RegisterFlags(flagSet *flag.FlagSet) {\nflagSet.Bool(\"rx-checksum-offload\", true, \"enable RX checksum offload.\")\nflagSet.Var(queueingDisciplinePtr(QDiscFIFO), \"qdisc\", \"specifies which queueing discipline to apply by default to the non loopback nics used by the sandbox.\")\nflagSet.Int(\"num-network-channels\", 1, \"number of underlying channels(FDs) to use for network link endpoints.\")\n+ flagSet.Bool(\"buffer-pooling\", true, \"enable allocation of buffers from a shared pool instead of the heap.\")\n// Test flags, not to be used outside tests, ever.\nflagSet.Bool(\"TESTONLY-unsafe-nonroot\", false, \"TEST ONLY; do not ever use! This skips many security measures that isolate the host from the sandbox.\")\n"
}
] | Go | Apache License 2.0 | google/gvisor | Create configuration flags to control buffer pooling.
PiperOrigin-RevId: 457584626 |
259,891 | 27.06.2022 16:38:08 | 25,200 | 94126dd4aa4db6954884681ec1ef6a3483f578b2 | Limit the number of open files per sandbox
Fixes | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -266,8 +266,11 @@ INTEGRATION_TARGETS := //test/image:image_test //test/e2e:integration_test\ndocker-tests: load-basic $(RUNTIME_BIN)\n@$(call install_runtime,$(RUNTIME),) # Clear flags.\n+ # Used by TestRlimitNoFile.\n+ @$(call install_runtime,$(RUNTIME)-fdlimit,--fdlimit=2000)\n@$(call test_runtime,$(RUNTIME),$(INTEGRATION_TARGETS))\n@$(call install_runtime,$(RUNTIME), --lisafs) # Run again with lisafs.\n+ @$(call install_runtime,$(RUNTIME)-fdlimit,--lisafs --fdlimit=2000)\n@$(call test_runtime,$(RUNTIME),$(INTEGRATION_TARGETS))\n.PHONY: docker-tests\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/test/dockerutil/container.go",
"new_path": "pkg/test/dockerutil/container.go",
"diff": "@@ -128,6 +128,12 @@ func MakeContainer(ctx context.Context, logger testutil.Logger) *Container {\nreturn makeContainer(ctx, logger, *runtime)\n}\n+// MakeContainerWithRuntime is like MakeContainer, but allows for a runtime\n+// to be specified by suffix.\n+func MakeContainerWithRuntime(ctx context.Context, logger testutil.Logger, suffix string) *Container {\n+ return makeContainer(ctx, logger, *runtime+suffix)\n+}\n+\n// MakeNativeContainer constructs a suitable Container object.\n//\n// The runtime used will be the system default.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/boot.go",
"new_path": "runsc/cmd/boot.go",
"diff": "@@ -252,6 +252,23 @@ func (b *Boot) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\npanic(\"unreachable\")\n}\n+ // At this point we won't re-execute, so it's safe to limit via rlimits. Any\n+ // limit >= 0 works. If the limit is lower than the current number of open\n+ // files, then Setrlimit will succeed, and the next open will fail.\n+ if conf.FDLimit > -1 {\n+ rlimit := unix.Rlimit{\n+ Cur: uint64(conf.FDLimit),\n+ Max: uint64(conf.FDLimit),\n+ }\n+ switch err := unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit); err {\n+ case nil:\n+ case unix.EPERM:\n+ log.Warningf(\"FD limit %d is higher than the current hard limit or system-wide maximum\", conf.FDLimit)\n+ default:\n+ util.Fatalf(\"Failed to set RLIMIT_NOFILE: %v\", err)\n+ }\n+ }\n+\n// Read resolved mount list and replace the original one from the spec.\nmountsFile := os.NewFile(uintptr(b.mountsFD), \"mounts file\")\ncleanMounts, err := specutils.ReadMounts(mountsFile)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/gofer.go",
"new_path": "runsc/cmd/gofer.go",
"diff": "@@ -127,6 +127,23 @@ func (g *Gofer) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\npanic(\"unreachable\")\n}\n+ // At this point we won't re-execute, so it's safe to limit via rlimits. Any\n+ // limit >= 0 works. If the limit is lower than the current number of open\n+ // files, then Setrlimit will succeed, and the next open will fail.\n+ if conf.FDLimit > -1 {\n+ rlimit := unix.Rlimit{\n+ Cur: uint64(conf.FDLimit),\n+ Max: uint64(conf.FDLimit),\n+ }\n+ switch err := unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit); err {\n+ case nil:\n+ case unix.EPERM:\n+ log.Warningf(\"FD limit %d is higher than the current hard limit or system-wide maximum\", conf.FDLimit)\n+ default:\n+ util.Fatalf(\"Failed to set RLIMIT_NOFILE: %v\", err)\n+ }\n+ }\n+\n// Find what path is going to be served by this gofer.\nroot := spec.Root.Path\nif !conf.TestOnlyAllowRunAsCurrentUserWithoutChroot {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/config/config.go",
"new_path": "runsc/config/config.go",
"diff": "@@ -229,6 +229,11 @@ type Config struct {\n// Use pools to manage buffer memory instead of heap.\nBufferPooling bool `flag:\"buffer-pooling\"`\n+ // FDLimit specifies a limit on the number of host file descriptors that can\n+ // be open simultaneously by the sentry and gofer. It applies separately to\n+ // each.\n+ FDLimit int `flag:\"fdlimit\"`\n+\n// TestOnlyAllowRunAsCurrentUserWithoutChroot should only be used in\n// tests. It allows runsc to start the sandbox process as the current\n// user, and without chrooting the sandbox process. This can be\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/config/flags.go",
"new_path": "runsc/config/flags.go",
"diff": "@@ -84,6 +84,7 @@ func RegisterFlags(flagSet *flag.FlagSet) {\nflagSet.Bool(\"lisafs\", false, \"Enables lisafs protocol instead of 9P.\")\nflagSet.Bool(\"cgroupfs\", false, \"Automatically mount cgroupfs.\")\nflagSet.Bool(\"ignore-cgroups\", false, \"don't configure cgroups.\")\n+ flagSet.Int(\"fdlimit\", -1, \"Specifies a limit on the number of host file descriptors that can be open. Applies separately to the sentry and gofer. Note: each file in the sandbox holds more than one host FD open.\")\n// Flags that control sandbox runtime behavior: network related.\nflagSet.Var(networkTypePtr(NetworkSandbox), \"network\", \"specifies which network to use: sandbox (default), host, none. Using network inside the sandbox is more secure because it's isolated from the host network.\")\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -568,6 +568,7 @@ func (s *Sandbox) createSandboxProcess(conf *config.Config, args *Args, startSyn\n}\n}\n+ // Relay all the config flags to the sandbox process.\ncmd := exec.Command(specutils.ExePath, conf.ToFlags()...)\ncmd.SysProcAttr = &unix.SysProcAttr{\n// Detach from this session, otherwise cmd will get SIGHUP and SIGCONT\n"
},
{
"change_type": "MODIFY",
"old_path": "test/e2e/integration_test.go",
"new_path": "test/e2e/integration_test.go",
"diff": "@@ -997,3 +997,36 @@ func TestNonSearchableWorkingDirectory(t *testing.T) {\nt.Errorf(\"ls error message not found, want: %q, got: %q\", wantErrorMsg, got)\n}\n}\n+\n+func TestRlimitNoFile(t *testing.T) {\n+ ctx := context.Background()\n+ d := dockerutil.MakeContainerWithRuntime(ctx, t, \"-fdlimit\")\n+ defer d.CleanUp(ctx)\n+\n+ // We have to create a directory with a bunch of files.\n+ const nfiles = 5000\n+ tmpDir := testutil.TmpDir()\n+ for i := 0; i < nfiles; i++ {\n+ if _, err := ioutil.TempFile(tmpDir, \"tmp\"); err != nil {\n+ t.Fatalf(\"TempFile(): %v\", err)\n+ }\n+ }\n+\n+ // Run the container. Open a bunch of files simutaneously and sleep a bit\n+ // to give time for everything to start. We should hit the FD limit and\n+ // fail rather than waiting the full sleep duration.\n+ cmd := `for file in /tmp/foo/*; do (cat > \"${file}\") & done && sleep 60`\n+ got, err := d.Run(ctx, dockerutil.RunOpts{\n+ Image: \"basic/ubuntu\",\n+ Mounts: []mount.Mount{\n+ {\n+ Type: mount.TypeBind,\n+ Source: tmpDir,\n+ Target: \"/tmp/foo\",\n+ },\n+ },\n+ }, \"bash\", \"-c\", cmd)\n+ if err == nil {\n+ t.Fatalf(\"docker run didn't fail: %s\", got)\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Limit the number of open files per sandbox
Fixes #6547.
PiperOrigin-RevId: 457594490 |
259,868 | 27.06.2022 18:12:36 | 25,200 | 7cba29ca3bf12f15b505d1b1b5bdda6e87cd5ca0 | gVisor Makefile: Add `--cgroupns=host` only when supported by Docker.
Docker doesn't support the `--cgroupns` option until API version 1.41.
This change prevents the addition of the `--cgroupns=host` option
(which is only necessary for `cgroup_test` to pass, not necessary
for any build) unless Docker supports it. | [
{
"change_type": "MODIFY",
"old_path": "tools/bazel.mk",
"new_path": "tools/bazel.mk",
"diff": "@@ -161,6 +161,21 @@ ifneq ($(DEVICE_FILE),)\nDOCKER_RUN_OPTIONS += --device \"$(DEVICE_FILE):$(DEVICE_FILE)\"\nendif\n+# Check if Docker API version supports cgroupns (supported in >=1.41).\n+# If not, don't include it in options.\n+ifeq ($(DOCKER_BUILD),true)\n+DOCKER_API_VERSION := $(shell docker version --format='{{.Server.APIVersion}}')\n+ifeq ($(shell echo $(DOCKER_API_VERSION) | tr '.' '\\n' | wc -l),2)\n+ifeq ($(shell test $(shell echo $(DOCKER_API_VERSION) | cut -d. -f1) -gt 1 && echo true),true)\n+DOCKER_RUN_OPTIONS += --cgroupns=host\n+else # If API version 1, check second version component.\n+ifeq ($(shell test $(shell echo $(DOCKER_API_VERSION) | cut -d. -f2) -ge 41 && echo true),true)\n+DOCKER_RUN_OPTIONS += --cgroupns=host\n+endif\n+endif\n+endif\n+endif\n+\n# Top-level functions.\n#\n# This command runs a bazel server, and the container sticks around\n@@ -205,7 +220,7 @@ endif\n@docker run -d --name $(DOCKER_NAME) --hostname $(DOCKER_HOSTNAME) \\\n-v \"$(CURDIR):$(CURDIR)\" \\\n--workdir \"$(CURDIR)\" \\\n- --pid=host --cgroupns=host \\\n+ --pid=host \\\n$(DOCKER_RUN_OPTIONS) \\\ngvisor.dev/images/builder \\\nbash -c \"set -x; tail -f --pid=\\$$($(BAZEL) info server_pid) /dev/null\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | gVisor Makefile: Add `--cgroupns=host` only when supported by Docker.
Docker doesn't support the `--cgroupns` option until API version 1.41.
This change prevents the addition of the `--cgroupns=host` option
(which is only necessary for `cgroup_test` to pass, not necessary
for any build) unless Docker supports it.
PiperOrigin-RevId: 457612257 |
259,891 | 28.06.2022 10:54:36 | 25,200 | 7b50d94cc8b2063ed8b16c0de99d009bf181bb12 | factor out gofer dirent cache
This will enable simpler tuning of cache size in child CL. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"new_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"diff": "@@ -1918,7 +1918,6 @@ func (fs *filesystem) MountOptions() string {\n{moptDfltGID, fs.opts.dfltgid},\n{moptMsize, fs.opts.msize},\n{moptVersion, fs.opts.version},\n- {moptDentryCacheLimit, fs.opts.maxCachedDentries},\n}\nswitch fs.opts.interop {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"diff": "// regularFileFD/directoryFD.mu\n// filesystem.renameMu\n// dentry.cachingMu\n-// filesystem.cacheMu\n+// dentryCache.mu\n// dentry.dirMu\n// filesystem.syncMu\n// dentry.metadataMu\n@@ -81,7 +81,6 @@ const (\nmoptDfltGID = \"dfltgid\"\nmoptMsize = \"msize\"\nmoptVersion = \"version\"\n- moptDentryCacheLimit = \"dentry_cache_limit\"\nmoptCache = \"cache\"\nmoptForcePageCache = \"force_page_cache\"\nmoptLimitHostFDTranslation = \"limit_host_fd_translation\"\n@@ -97,6 +96,21 @@ const (\ncacheRemoteRevalidating = \"remote_revalidating\"\n)\n+const defaultMaxCachedDentries = 1000\n+\n+// +stateify savable\n+type dentryCache struct {\n+ // mu protects the below fields.\n+ mu sync.Mutex `state:\"nosave\"`\n+ // dentries contains all dentries with 0 references. Due to race conditions,\n+ // it may also contain dentries with non-zero references.\n+ dentries dentryList\n+ // dentriesLen is the number of dentries in dentries.\n+ dentriesLen uint64\n+ // maxCachedDentries is the maximum number of cachable dentries.\n+ maxCachedDentries uint64\n+}\n+\n// Valid values for \"trans\" mount option.\nconst transportModeFD = \"fd\"\n@@ -147,13 +161,7 @@ type filesystem struct {\n// it is reachable from its parent).\nrenameMu sync.RWMutex `state:\"nosave\"`\n- // cachedDentries contains all dentries with 0 references. (Due to race\n- // conditions, it may also contain dentries with non-zero references.)\n- // cachedDentriesLen is the number of dentries in cachedDentries. These fields\n- // are protected by cacheMu.\n- cacheMu sync.Mutex `state:\"nosave\"`\n- cachedDentries dentryList\n- cachedDentriesLen uint64\n+ dentryCache *dentryCache\n// syncableDentries contains all non-synthetic dentries. specialFileFDs\n// contains all open specialFileFDs. These fields are protected by syncMu.\n@@ -197,9 +205,6 @@ type filesystemOptions struct {\nmsize uint32\nversion string\n- // maxCachedDentries is the maximum size of filesystem.cachedDentries.\n- maxCachedDentries uint64\n-\n// If forcePageCache is true, host FDs may not be used for application\n// memory mappings even if available; instead, the client must perform its\n// own caching of regular file pages. This is primarily useful for testing.\n@@ -423,18 +428,6 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nfsopts.version = version\n}\n- // Parse the dentry cache limit.\n- fsopts.maxCachedDentries = 1000\n- if str, ok := mopts[moptDentryCacheLimit]; ok {\n- delete(mopts, moptDentryCacheLimit)\n- maxCachedDentries, err := strconv.ParseUint(str, 10, 64)\n- if err != nil {\n- ctx.Warningf(\"gofer.FilesystemType.GetFilesystem: invalid dentry cache limit: %s=%s\", moptDentryCacheLimit, str)\n- return nil, nil, linuxerr.EINVAL\n- }\n- fsopts.maxCachedDentries = maxCachedDentries\n- }\n-\n// Handle simple flags.\nif _, ok := mopts[moptForcePageCache]; ok {\ndelete(mopts, moptForcePageCache)\n@@ -488,6 +481,7 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nspecialFileFDs: make(map[*specialFileFD]struct{}),\ninoByQIDPath: make(map[uint64]uint64),\ninoByKey: make(map[inoKey]uint64),\n+ dentryCache: &dentryCache{maxCachedDentries: defaultMaxCachedDentries},\n}\nfs.vfsfs.Init(vfsObj, &fstype, fs)\n@@ -824,7 +818,7 @@ type dentry struct {\ncachingMu sync.Mutex `state:\"nosave\"`\n// If cached is true, dentryEntry links dentry into\n- // filesystem.cachedDentries. cached and dentryEntry are protected by\n+ // filesystem.dentryCache.dentries. cached and dentryEntry are protected by\n// cachingMu.\ncached bool\ndentryEntry\n@@ -1811,11 +1805,12 @@ func (d *dentry) checkCachingLocked(ctx context.Context, renameMuWriteLocked boo\nreturn\n}\nif refs > 0 {\n- // fs.cachedDentries is permitted to contain dentries with non-zero refs,\n- // which are skipped by fs.evictCachedDentryLocked() upon reaching the end\n- // of the LRU. But it is still beneficial to remove d from the cache as we\n- // are already holding d.cachingMu. Keeping a cleaner cache also reduces\n- // the number of evictions (which is expensive as it acquires fs.renameMu).\n+ // fs.dentryCache.dentries is permitted to contain dentries with non-zero\n+ // refs, which are skipped by fs.evictCachedDentryLocked() upon reaching\n+ // the end of the LRU. But it is still beneficial to remove d from the\n+ // cache as we are already holding d.cachingMu. Keeping a cleaner cache\n+ // also reduces the number of evictions (which is expensive as it acquires\n+ // fs.renameMu).\nd.removeFromCacheLocked()\nd.cachingMu.Unlock()\nreturn\n@@ -1872,22 +1867,22 @@ func (d *dentry) checkCachingLocked(ctx context.Context, renameMuWriteLocked boo\nreturn\n}\n- d.fs.cacheMu.Lock()\n+ d.fs.dentryCache.mu.Lock()\n// If d is already cached, just move it to the front of the LRU.\nif d.cached {\n- d.fs.cachedDentries.Remove(d)\n- d.fs.cachedDentries.PushFront(d)\n- d.fs.cacheMu.Unlock()\n+ d.fs.dentryCache.dentries.Remove(d)\n+ d.fs.dentryCache.dentries.PushFront(d)\n+ d.fs.dentryCache.mu.Unlock()\nd.cachingMu.Unlock()\nreturn\n}\n// Cache the dentry, then evict the least recently used cached dentry if\n// the cache becomes over-full.\n- d.fs.cachedDentries.PushFront(d)\n- d.fs.cachedDentriesLen++\n+ d.fs.dentryCache.dentries.PushFront(d)\n+ d.fs.dentryCache.dentriesLen++\nd.cached = true\n- shouldEvict := d.fs.cachedDentriesLen > d.fs.opts.maxCachedDentries\n- d.fs.cacheMu.Unlock()\n+ shouldEvict := d.fs.dentryCache.dentriesLen > d.fs.dentryCache.maxCachedDentries\n+ d.fs.dentryCache.mu.Unlock()\nd.cachingMu.Unlock()\nif shouldEvict {\n@@ -1904,10 +1899,10 @@ func (d *dentry) checkCachingLocked(ctx context.Context, renameMuWriteLocked boo\n// Preconditions: d.cachingMu must be locked.\nfunc (d *dentry) removeFromCacheLocked() {\nif d.cached {\n- d.fs.cacheMu.Lock()\n- d.fs.cachedDentries.Remove(d)\n- d.fs.cachedDentriesLen--\n- d.fs.cacheMu.Unlock()\n+ d.fs.dentryCache.mu.Lock()\n+ d.fs.dentryCache.dentries.Remove(d)\n+ d.fs.dentryCache.dentriesLen--\n+ d.fs.dentryCache.mu.Unlock()\nd.cached = false\n}\n}\n@@ -1916,7 +1911,7 @@ func (d *dentry) removeFromCacheLocked() {\n// unlocked.\n// +checklocks:fs.renameMu\nfunc (fs *filesystem) evictAllCachedDentriesLocked(ctx context.Context) {\n- for fs.cachedDentriesLen != 0 {\n+ for fs.dentryCache.dentriesLen != 0 {\nfs.evictCachedDentryLocked(ctx)\n}\n}\n@@ -1926,42 +1921,69 @@ func (fs *filesystem) evictAllCachedDentriesLocked(ctx context.Context) {\n//\n// +checklocks:fs.renameMu\nfunc (fs *filesystem) evictCachedDentryLocked(ctx context.Context) {\n- fs.cacheMu.Lock()\n- victim := fs.cachedDentries.Back()\n- fs.cacheMu.Unlock()\n+ fs.dentryCache.mu.Lock()\n+ victim := fs.dentryCache.dentries.Back()\n+ fs.dentryCache.mu.Unlock()\nif victim == nil {\n- // fs.cachedDentries may have become empty between when it was checked and\n- // when we locked fs.cacheMu.\n+ // fs.dentryCache.dentries may have become empty between when it was\n+ // checked and when we locked fs.dentryCache.mu.\nreturn\n}\n- victim.cachingMu.Lock()\n- victim.removeFromCacheLocked()\n- // victim.refs or victim.watches.Size() may have become non-zero from an\n- // earlier path resolution since it was inserted into fs.cachedDentries.\n- if victim.refs.Load() != 0 || victim.watches.Size() != 0 {\n- victim.cachingMu.Unlock()\n+ if victim.fs == fs {\n+ victim.evictLocked(ctx) // +checklocksforce: owned as precondition, victim.fs == fs\nreturn\n}\n- if victim.parent != nil {\n- victim.parent.dirMu.Lock()\n- if !victim.vfsd.IsDead() {\n- // Note that victim can't be a mount point (in any mount\n- // namespace), since VFS holds references on mount points.\n- fs.vfsfs.VirtualFilesystem().InvalidateDentry(ctx, &victim.vfsd)\n- delete(victim.parent.children, victim.name)\n+\n+ // The dentry cache is shared between all gofer filesystems and the victim is\n+ // from another filesystem. Have that filesystem do the work. We unlock\n+ // fs.renameMu to prevent deadlock: two filesystems could otherwise wait on\n+ // each others' renameMu.\n+ fs.renameMu.Unlock()\n+ defer fs.renameMu.Lock()\n+ victim.evict(ctx)\n+}\n+\n+// Preconditions:\n+// - d.fs.renameMu must not be locked for writing.\n+func (d *dentry) evict(ctx context.Context) {\n+ d.fs.renameMu.Lock()\n+ defer d.fs.renameMu.Unlock()\n+ d.evictLocked(ctx)\n+}\n+\n+// Preconditions:\n+// - d.fs.renameMu must be locked for writing; it may be temporarily unlocked.\n+//\n+// +checklocks:d.fs.renameMu\n+func (d *dentry) evictLocked(ctx context.Context) {\n+ d.cachingMu.Lock()\n+ d.removeFromCacheLocked()\n+ // d.refs or d.watches.Size() may have become non-zero from an earlier path\n+ // resolution since it was inserted into fs.dentryCache.dentries.\n+ if d.refs.Load() != 0 || d.watches.Size() != 0 {\n+ d.cachingMu.Unlock()\n+ return\n+ }\n+ if d.parent != nil {\n+ d.parent.dirMu.Lock()\n+ if !d.vfsd.IsDead() {\n+ // Note that d can't be a mount point (in any mount namespace), since VFS\n+ // holds references on mount points.\n+ d.fs.vfsfs.VirtualFilesystem().InvalidateDentry(ctx, &d.vfsd)\n+ delete(d.parent.children, d.name)\n// We're only deleting the dentry, not the file it\n// represents, so we don't need to update\n- // victimParent.dirents etc.\n+ // victim parent.dirents etc.\n}\n- victim.parent.dirMu.Unlock()\n+ d.parent.dirMu.Unlock()\n}\n- // Safe to unlock cachingMu now that victim.vfsd.IsDead(). Henceforth any\n- // concurrent caching attempts on victim will attempt to destroy it and so\n- // will try to acquire fs.renameMu (which we have already acquired). Hence,\n+ // Safe to unlock cachingMu now that d.vfsd.IsDead(). Henceforth any\n+ // concurrent caching attempts on d will attempt to destroy it and so will\n+ // try to acquire fs.renameMu (which we have already acquiredd). Hence,\n// fs.renameMu will synchronize the destroy attempts.\n- victim.cachingMu.Unlock()\n- victim.destroyLocked(ctx) // +checklocksforce: owned as precondition, victim.fs == fs.\n+ d.cachingMu.Unlock()\n+ d.destroyLocked(ctx) // +checklocksforce: owned as precondition.\n}\n// destroyLocked destroys the dentry.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer_test.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer_test.go",
"diff": "@@ -26,13 +26,11 @@ func TestDestroyIdempotent(t *testing.T) {\nctx := contexttest.Context(t)\nfs := filesystem{\nmfp: pgalloc.MemoryFileProviderFromContext(ctx),\n- opts: filesystemOptions{\n- // Test relies on no dentry being held in the cache.\n- maxCachedDentries: 0,\n- },\nsyncableDentries: make(map[*dentry]struct{}),\ninoByQIDPath: make(map[uint64]uint64),\ninoByKey: make(map[inoKey]uint64),\n+ // Test relies on no dentry being held in the cache.\n+ dentryCache: &dentryCache{maxCachedDentries: 0},\n}\nattr := &p9.Attr{\n"
},
{
"change_type": "MODIFY",
"old_path": "test/e2e/integration_test.go",
"new_path": "test/e2e/integration_test.go",
"diff": "@@ -1003,7 +1003,7 @@ func TestRlimitNoFile(t *testing.T) {\nd := dockerutil.MakeContainerWithRuntime(ctx, t, \"-fdlimit\")\ndefer d.CleanUp(ctx)\n- // We have to create a directory with a bunch of files.\n+ // Create a directory with a bunch of files.\nconst nfiles = 5000\ntmpDir := testutil.TmpDir()\nfor i := 0; i < nfiles; i++ {\n"
}
] | Go | Apache License 2.0 | google/gvisor | factor out gofer dirent cache
This will enable simpler tuning of cache size in child CL.
PiperOrigin-RevId: 457771698 |
259,891 | 28.06.2022 18:55:27 | 25,200 | 2b97d38657de0e04a4a50473c4b704f9b5765a41 | make gofer directory cache size configurable
Passing --dcache=N causes all gofer mounts to use a global dirent cache of size
N. | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -268,10 +268,12 @@ docker-tests: load-basic $(RUNTIME_BIN)\n@$(call install_runtime,$(RUNTIME),) # Clear flags.\n# Used by TestRlimitNoFile.\n@$(call install_runtime,$(RUNTIME)-fdlimit,--fdlimit=2000)\n- @$(call test_runtime,$(RUNTIME),$(INTEGRATION_TARGETS))\n+ @$(call install_runtime,$(RUNTIME)-dcache,--fdlimit=2000 --dcache=100)\n+ @$(call test_runtime,$(RUNTIME),$(INTEGRATION_TARGETS) //test/e2e:integration_runtime_test)\n@$(call install_runtime,$(RUNTIME), --lisafs) # Run again with lisafs.\n@$(call install_runtime,$(RUNTIME)-fdlimit,--lisafs --fdlimit=2000)\n- @$(call test_runtime,$(RUNTIME),$(INTEGRATION_TARGETS))\n+ @$(call install_runtime,$(RUNTIME)-dcache,--lisafs --fdlimit=2000 --dcache=100)\n+ @$(call test_runtime,$(RUNTIME),$(INTEGRATION_TARGETS) //test/e2e:integration_runtime_test)\n.PHONY: docker-tests\noverlay-tests: load-basic $(RUNTIME_BIN)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"diff": "@@ -111,6 +111,16 @@ type dentryCache struct {\nmaxCachedDentries uint64\n}\n+// SetDentryCacheSize sets the size of the global gofer dentry cache.\n+func SetDentryCacheSize(size int) {\n+ globalDentryCache.mu.Lock()\n+ defer globalDentryCache.mu.Unlock()\n+ globalDentryCache.maxCachedDentries = uint64(size)\n+}\n+\n+// globalDentryCache is a global cache of dentries across all gofers.\n+var globalDentryCache dentryCache\n+\n// Valid values for \"trans\" mount option.\nconst transportModeFD = \"fd\"\n@@ -481,8 +491,17 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nspecialFileFDs: make(map[*specialFileFD]struct{}),\ninoByQIDPath: make(map[uint64]uint64),\ninoByKey: make(map[inoKey]uint64),\n- dentryCache: &dentryCache{maxCachedDentries: defaultMaxCachedDentries},\n}\n+\n+ // Did the user configure a global dentry cache?\n+ globalDentryCache.mu.Lock()\n+ if globalDentryCache.maxCachedDentries >= 1 {\n+ fs.dentryCache = &globalDentryCache\n+ } else {\n+ fs.dentryCache = &dentryCache{maxCachedDentries: defaultMaxCachedDentries}\n+ }\n+ globalDentryCache.mu.Unlock()\n+\nfs.vfsfs.Init(vfsObj, &fstype, fs)\nif err := fs.initClientAndRoot(ctx); err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/vfs.go",
"new_path": "runsc/boot/vfs.go",
"diff": "@@ -409,6 +409,9 @@ func (c *containerMounter) createMountNamespace(ctx context.Context, conf *confi\n// Options field). So assume root is always on top of overlayfs.\ndata = append(data, \"overlayfs_stale_read\")\n+ // Configure the gofer dentry cache size.\n+ gofer.SetDentryCacheSize(conf.DCache)\n+\nlog.Infof(\"Mounting root over 9P, ioFD: %d\", fd)\nopts := &vfs.MountOptions{\nReadOnly: c.root.Readonly,\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/config/config.go",
"new_path": "runsc/config/config.go",
"diff": "@@ -234,6 +234,10 @@ type Config struct {\n// each.\nFDLimit int `flag:\"fdlimit\"`\n+ // DCache sets the global dirent cache size. If zero, per-mount caches are\n+ // used.\n+ DCache int `flag:\"dcache\"`\n+\n// TestOnlyAllowRunAsCurrentUserWithoutChroot should only be used in\n// tests. It allows runsc to start the sandbox process as the current\n// user, and without chrooting the sandbox process. This can be\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/config/flags.go",
"new_path": "runsc/config/flags.go",
"diff": "@@ -85,6 +85,7 @@ func RegisterFlags(flagSet *flag.FlagSet) {\nflagSet.Bool(\"cgroupfs\", false, \"Automatically mount cgroupfs.\")\nflagSet.Bool(\"ignore-cgroups\", false, \"don't configure cgroups.\")\nflagSet.Int(\"fdlimit\", -1, \"Specifies a limit on the number of host file descriptors that can be open. Applies separately to the sentry and gofer. Note: each file in the sandbox holds more than one host FD open.\")\n+ flagSet.Int(\"dcache\", 0, \"Set the global gofer direct cache size. This acts as a coarse-grained control on the number of host FDs simultaneously open by the sentry. If zero, per-mount caches are used.\")\n// Flags that control sandbox runtime behavior: network related.\nflagSet.Var(networkTypePtr(NetworkSandbox), \"network\", \"specifies which network to use: sandbox (default), host, none. Using network inside the sandbox is more secure because it's isolated from the host network.\")\n"
},
{
"change_type": "MODIFY",
"old_path": "test/e2e/BUILD",
"new_path": "test/e2e/BUILD",
"diff": "@@ -26,6 +26,26 @@ go_test(\n],\n)\n+go_test(\n+ name = \"integration_runtime_test\",\n+ size = \"large\",\n+ srcs = [\n+ \"integration_runtime_test.go\",\n+ ],\n+ library = \":integration\",\n+ tags = [\n+ # Requires docker and runsc to be configured before the test runs.\n+ \"local\",\n+ \"manual\",\n+ ],\n+ visibility = [\"//:sandbox\"],\n+ deps = [\n+ \"//pkg/test/dockerutil\",\n+ \"//pkg/test/testutil\",\n+ \"@com_github_docker_docker//api/types/mount:go_default_library\",\n+ ],\n+)\n+\ngo_library(\nname = \"integration\",\nsrcs = [\"integration.go\"],\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/e2e/integration_runtime_test.go",
"diff": "+// Copyright 2018 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 integration provides end-to-end integration tests for runsc.\n+//\n+// Each test calls docker commands to start up a container, and tests that it is\n+// behaving properly, with various runsc commands. The container is killed and\n+// deleted at the end.\n+//\n+// Setup instruction in test/README.md.\n+package integration\n+\n+import (\n+ \"context\"\n+ \"flag\"\n+ \"io/ioutil\"\n+ \"os\"\n+ \"strings\"\n+ \"testing\"\n+ \"time\"\n+\n+ \"github.com/docker/docker/api/types/mount\"\n+ \"gvisor.dev/gvisor/pkg/test/dockerutil\"\n+ \"gvisor.dev/gvisor/pkg/test/testutil\"\n+)\n+\n+const (\n+ // defaultWait is the default wait time used for tests.\n+ defaultWait = time.Minute\n+\n+ memInfoCmd = \"cat /proc/meminfo | grep MemTotal: | awk '{print $2}'\"\n+)\n+\n+func TestMain(m *testing.M) {\n+ dockerutil.EnsureSupportedDockerVersion()\n+ flag.Parse()\n+ os.Exit(m.Run())\n+}\n+\n+func TestRlimitNoFile(t *testing.T) {\n+ ctx := context.Background()\n+ d := dockerutil.MakeContainerWithRuntime(ctx, t, \"-fdlimit\")\n+ defer d.CleanUp(ctx)\n+\n+ // Create a directory with a bunch of files.\n+ const nfiles = 5000\n+ tmpDir := testutil.TmpDir()\n+ for i := 0; i < nfiles; i++ {\n+ if _, err := ioutil.TempFile(tmpDir, \"tmp\"); err != nil {\n+ t.Fatalf(\"TempFile(): %v\", err)\n+ }\n+ }\n+\n+ // Run the container. Open a bunch of files simutaneously and sleep a bit\n+ // to give time for everything to start. We should hit the FD limit and\n+ // fail rather than waiting the full sleep duration.\n+ cmd := `for file in /tmp/foo/*; do (cat > \"${file}\") & done && sleep 60`\n+ got, err := d.Run(ctx, dockerutil.RunOpts{\n+ Image: \"basic/ubuntu\",\n+ Mounts: []mount.Mount{\n+ {\n+ Type: mount.TypeBind,\n+ Source: tmpDir,\n+ Target: \"/tmp/foo\",\n+ },\n+ },\n+ }, \"bash\", \"-c\", cmd)\n+ if err == nil {\n+ t.Fatalf(\"docker run didn't fail: %s\", got)\n+ } else if strings.Contains(err.Error(), \"Unknown runtime specified\") {\n+ t.Fatalf(\"docker failed because -fdlimit runtime was not installed\")\n+ }\n+}\n+\n+func TestDentryCacheLimit(t *testing.T) {\n+ ctx := context.Background()\n+ d := dockerutil.MakeContainerWithRuntime(ctx, t, \"-dcache\")\n+ defer d.CleanUp(ctx)\n+\n+ // Create a directory with a bunch of files.\n+ const nfiles = 5000\n+ tmpDir := testutil.TmpDir()\n+ for i := 0; i < nfiles; i++ {\n+ if _, err := ioutil.TempFile(tmpDir, \"tmp\"); err != nil {\n+ t.Fatalf(\"TempFile(): %v\", err)\n+ }\n+ }\n+\n+ // Run the container. Open a bunch of files simutaneously and sleep a bit\n+ // to give time for everything to start. We shouldn't hit the FD limit\n+ // because the dentry cache is small.\n+ cmd := `for file in /tmp/foo/*; do (cat > \"${file}\") & done && sleep 10`\n+ got, err := d.Run(ctx, dockerutil.RunOpts{\n+ Image: \"basic/ubuntu\",\n+ Mounts: []mount.Mount{\n+ {\n+ Type: mount.TypeBind,\n+ Source: tmpDir,\n+ Target: \"/tmp/foo\",\n+ },\n+ },\n+ }, \"bash\", \"-c\", cmd)\n+ if err != nil {\n+ t.Fatalf(\"docker failed: %v, %s\", err, got)\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/e2e/integration_test.go",
"new_path": "test/e2e/integration_test.go",
"diff": "@@ -997,36 +997,3 @@ func TestNonSearchableWorkingDirectory(t *testing.T) {\nt.Errorf(\"ls error message not found, want: %q, got: %q\", wantErrorMsg, got)\n}\n}\n-\n-func TestRlimitNoFile(t *testing.T) {\n- ctx := context.Background()\n- d := dockerutil.MakeContainerWithRuntime(ctx, t, \"-fdlimit\")\n- defer d.CleanUp(ctx)\n-\n- // Create a directory with a bunch of files.\n- const nfiles = 5000\n- tmpDir := testutil.TmpDir()\n- for i := 0; i < nfiles; i++ {\n- if _, err := ioutil.TempFile(tmpDir, \"tmp\"); err != nil {\n- t.Fatalf(\"TempFile(): %v\", err)\n- }\n- }\n-\n- // Run the container. Open a bunch of files simutaneously and sleep a bit\n- // to give time for everything to start. We should hit the FD limit and\n- // fail rather than waiting the full sleep duration.\n- cmd := `for file in /tmp/foo/*; do (cat > \"${file}\") & done && sleep 60`\n- got, err := d.Run(ctx, dockerutil.RunOpts{\n- Image: \"basic/ubuntu\",\n- Mounts: []mount.Mount{\n- {\n- Type: mount.TypeBind,\n- Source: tmpDir,\n- Target: \"/tmp/foo\",\n- },\n- },\n- }, \"bash\", \"-c\", cmd)\n- if err == nil {\n- t.Fatalf(\"docker run didn't fail: %s\", got)\n- }\n-}\n"
}
] | Go | Apache License 2.0 | google/gvisor | make gofer directory cache size configurable
Passing --dcache=N causes all gofer mounts to use a global dirent cache of size
N.
PiperOrigin-RevId: 457867503 |
259,907 | 29.06.2022 22:38:08 | 25,200 | 0c3abacb1c8cf11b914eb6be46dacaff0a993ebf | Limit the lisafs buffer that are printed with strace.
Otherwise, in case case read request asks for a lot of bytes but
response contains fewer bytes, we end up printing a lot of
garbage. | [
{
"change_type": "MODIFY",
"old_path": "pkg/lisafs/message.go",
"new_path": "pkg/lisafs/message.go",
"diff": "@@ -880,7 +880,8 @@ func (r *PReadResp) CheckedUnmarshal(src []byte) ([]byte, bool) {\n// We expect the client to have already allocated r.Buf. r.Buf probably\n// (optimally) points to usermem. Directly copy into that.\n- return srcRemain[copy(r.Buf[:r.NumBytes], srcRemain[:r.NumBytes]):], true\n+ r.Buf = r.Buf[:r.NumBytes]\n+ return srcRemain[copy(r.Buf, srcRemain[:r.NumBytes]):], true\n}\n// PWriteReq is used to pwrite(2) on an FD.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Limit the lisafs buffer that are printed with strace.
Otherwise, in case case read request asks for a lot of bytes but
response contains fewer bytes, we end up printing a lot of
garbage.
PiperOrigin-RevId: 458140547 |
259,891 | 30.06.2022 11:55:27 | 25,200 | 1eb2c3659db2088a6e71aecebff1b3810471980b | rename GSO: hardware->host and software->gVisor
API names such as flags and Makefile targets are unchanged so as not to break
users. | [
{
"change_type": "MODIFY",
"old_path": ".buildkite/pipeline.yaml",
"new_path": ".buildkite/pipeline.yaml",
"diff": "@@ -209,7 +209,7 @@ steps:\narch: \"amd64\"\nos: \"ubuntu\"\n- <<: *common\n- label: \":satellite: SWGSO tests\"\n+ label: \":satellite: gVisor GSO tests\"\ncommand: make swgso-tests\nagents:\narch: \"amd64\"\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/endpoint.go",
"new_path": "pkg/tcpip/link/fdbased/endpoint.go",
"diff": "@@ -192,8 +192,8 @@ type Options struct {\n// disabled.\nGSOMaxSize uint32\n- // SoftwareGSOEnabled indicates whether software GSO is enabled or not.\n- SoftwareGSOEnabled bool\n+ // GvisorGSOEnabled indicates whether Gvisor GSO is enabled or not.\n+ GvisorGSOEnabled bool\n// PacketDispatchMode specifies the type of inbound dispatcher to be\n// used for this endpoint.\n@@ -295,10 +295,10 @@ func New(opts *Options) (stack.LinkEndpoint, error) {\ne.fds = append(e.fds, fdInfo{fd: fd, isSocket: isSocket})\nif isSocket {\nif opts.GSOMaxSize != 0 {\n- if opts.SoftwareGSOEnabled {\n- e.gsoKind = stack.SWGSOSupported\n+ if opts.GvisorGSOEnabled {\n+ e.gsoKind = stack.GvisorGSOSupported\n} else {\n- e.gsoKind = stack.HWGSOSupported\n+ e.gsoKind = stack.HostGSOSupported\n}\ne.gsoMaxSize = opts.GSOMaxSize\n}\n@@ -506,7 +506,7 @@ func (e *endpoint) writePacket(pkt *stack.PacketBuffer) tcpip.Error {\nfdInfo := e.fds[pkt.Hash%uint32(len(e.fds))]\nfd := fdInfo.fd\nvar vnetHdrBuf []byte\n- if e.gsoKind == stack.HWGSOSupported {\n+ if e.gsoKind == stack.HostGSOSupported {\nvnetHdr := virtioNetHdr{}\nif pkt.GSOOptions.Type != stack.GSONone {\nvnetHdr.hdrLen = uint16(pkt.HeaderSize())\n@@ -577,7 +577,7 @@ func (e *endpoint) sendBatch(batchFDInfo fdInfo, pkts []*stack.PacketBuffer) (in\nsyscallHeaderBytes := uintptr(0)\nfor _, pkt := range batch {\nvar vnetHdrBuf []byte\n- if e.gsoKind == stack.HWGSOSupported {\n+ if e.gsoKind == stack.HostGSOSupported {\nvnetHdr := virtioNetHdr{}\nif pkt.GSOOptions.Type != stack.GSONone {\nvnetHdr.hdrLen = uint16(pkt.HeaderSize())\n@@ -670,7 +670,7 @@ func (e *endpoint) sendBatch(batchFDInfo fdInfo, pkts []*stack.PacketBuffer) (in\n// - pkt.NetworkProtocolNumber\nfunc (e *endpoint) WritePackets(pkts stack.PacketBufferList) (int, tcpip.Error) {\n// Preallocate to avoid repeated reallocation as we append to batch.\n- // batchSz is 47 because when SWGSO is in use then a single 65KB TCP\n+ // batchSz is 47 because when GvisorGSO is in use then a single 65KB TCP\n// segment can get split into 46 segments of 1420 bytes and a single 216\n// byte segment.\nconst batchSz = 47\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/packet_dispatchers.go",
"new_path": "pkg/tcpip/link/fdbased/packet_dispatchers.go",
"diff": "@@ -184,7 +184,7 @@ func newReadVDispatcher(fd int, e *endpoint) (linkDispatcher, error) {\nfd: fd,\ne: e,\n}\n- skipsVnetHdr := d.e.gsoKind == stack.HWGSOSupported\n+ skipsVnetHdr := d.e.gsoKind == stack.HostGSOSupported\nd.buf = newIovecBuffer(BufConfig, skipsVnetHdr)\nreturn d, nil\n}\n@@ -269,7 +269,7 @@ func newRecvMMsgDispatcher(fd int, e *endpoint) (linkDispatcher, error) {\nbufs: make([]*iovecBuffer, MaxMsgsPerRecv),\nmsgHdrs: make([]rawfile.MMsgHdr, MaxMsgsPerRecv),\n}\n- skipsVnetHdr := d.e.gsoKind == stack.HWGSOSupported\n+ skipsVnetHdr := d.e.gsoKind == stack.HostGSOSupported\nfor i := range d.bufs {\nd.bufs[i] = newIovecBuffer(BufConfig, skipsVnetHdr)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/registration.go",
"new_path": "pkg/tcpip/stack/registration.go",
"diff": "@@ -1168,9 +1168,9 @@ const (\nGSOTCPv4\nGSOTCPv6\n- // GSOSW is used for software GSO segments which have to be sent by\n+ // GSOGvisor is used for gVisor GSO segments which have to be sent by\n// endpoint.WritePackets.\n- GSOSW\n+ GSOGvisor\n)\n// GSO contains generic segmentation offload properties.\n@@ -1193,20 +1193,22 @@ type GSO struct {\nMaxSize uint32\n}\n-// SupportedGSO returns the type of segmentation offloading supported.\n+// SupportedGSO is the type of segmentation offloading supported.\ntype SupportedGSO int\nconst (\n// GSONotSupported indicates that segmentation offloading is not supported.\nGSONotSupported SupportedGSO = iota\n- // HWGSOSupported indicates that segmentation offloading may be performed by\n- // the hardware.\n- HWGSOSupported\n+ // HostGSOSupported indicates that segmentation offloading may be performed\n+ // by the host. This is typically true when netstack is attached to a host\n+ // AF_PACKET socket, and not true when attached to a unix socket or other\n+ // non-networking data layer.\n+ HostGSOSupported\n- // SWGSOSupported indicates that segmentation offloading may be performed in\n- // software.\n- SWGSOSupported\n+ // GvisorGSOSupported indicates that segmentation offloading may be performed\n+ // in gVisor.\n+ GvisorGSOSupported\n)\n// GSOEndpoint provides access to GSO properties.\n@@ -1218,6 +1220,6 @@ type GSOEndpoint interface {\nSupportedGSO() SupportedGSO\n}\n-// SoftwareGSOMaxSize is a maximum allowed size of a software GSO segment.\n+// GvisorGSOMaxSize is a maximum allowed size of a software GSO segment.\n// This isn't a hard limit, because it is never set into packet headers.\n-const SoftwareGSOMaxSize = 1 << 16\n+const GvisorGSOMaxSize = 1 << 16\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/route.go",
"new_path": "pkg/tcpip/stack/route.go",
"diff": "@@ -302,18 +302,18 @@ func (r *Route) RequiresTXTransportChecksum() bool {\nreturn r.outgoingNIC.NetworkLinkEndpoint.Capabilities()&CapabilityTXChecksumOffload == 0\n}\n-// HasSoftwareGSOCapability returns true if the route supports software GSO.\n-func (r *Route) HasSoftwareGSOCapability() bool {\n+// HasGvisorGSOCapability returns true if the route supports gVisor GSO.\n+func (r *Route) HasGvisorGSOCapability() bool {\nif gso, ok := r.outgoingNIC.NetworkLinkEndpoint.(GSOEndpoint); ok {\n- return gso.SupportedGSO() == SWGSOSupported\n+ return gso.SupportedGSO() == GvisorGSOSupported\n}\nreturn false\n}\n-// HasHardwareGSOCapability returns true if the route supports hardware GSO.\n-func (r *Route) HasHardwareGSOCapability() bool {\n+// HasHostGSOCapability returns true if the route supports host GSO.\n+func (r *Route) HasHostGSOCapability() bool {\nif gso, ok := r.outgoingNIC.NetworkLinkEndpoint.(GSOEndpoint); ok {\n- return gso.SupportedGSO() == HWGSOSupported\n+ return gso.SupportedGSO() == HostGSOSupported\n}\nreturn false\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/connect.go",
"new_path": "pkg/tcpip/transport/tcp/connect.go",
"diff": "@@ -900,7 +900,7 @@ func sendTCP(r *stack.Route, tf tcpFields, pkt *stack.PacketBuffer, gso stack.GS\ntf.rcvWnd = math.MaxUint16\n}\n- if r.Loop()&stack.PacketLoop == 0 && gso.Type == stack.GSOSW && int(gso.MSS) < pkt.Data().Size() {\n+ if r.Loop()&stack.PacketLoop == 0 && gso.Type == stack.GSOGvisor && int(gso.MSS) < pkt.Data().Size() {\nreturn sendTCPBatch(r, tf, pkt, gso, owner)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -3088,7 +3088,7 @@ func (e *endpoint) completeStateLocked(s *stack.TCPEndpointState) {\ns.Sender.SpuriousRecovery = e.snd.spuriousRecovery\n}\n-func (e *endpoint) initHardwareGSO() {\n+func (e *endpoint) initHostGSO() {\nswitch e.route.NetProto() {\ncase header.IPv4ProtocolNumber:\ne.gso.Type = stack.GSOTCPv4\n@@ -3105,12 +3105,12 @@ func (e *endpoint) initHardwareGSO() {\n}\nfunc (e *endpoint) initGSO() {\n- if e.route.HasHardwareGSOCapability() {\n- e.initHardwareGSO()\n- } else if e.route.HasSoftwareGSOCapability() {\n+ if e.route.HasHostGSOCapability() {\n+ e.initHostGSO()\n+ } else if e.route.HasGvisorGSOCapability() {\ne.gso = stack.GSO{\nMaxSize: e.route.GSOMaxSize(),\n- Type: stack.GSOSW,\n+ Type: stack.GSOGvisor,\nNeedsCsum: false,\n}\n}\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": "@@ -1268,7 +1268,7 @@ func (c *Context) SACKEnabled() bool {\n// SetGSOEnabled enables or disables generic segmentation offload.\nfunc (c *Context) SetGSOEnabled(enable bool) {\nif enable {\n- c.linkEP.SupportedGSOKind = stack.HWGSOSupported\n+ c.linkEP.SupportedGSOKind = stack.HostGSOSupported\n} else {\nc.linkEP.SupportedGSOKind = stack.GSONotSupported\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/network.go",
"new_path": "runsc/boot/network.go",
"diff": "@@ -91,7 +91,7 @@ type FDBasedLink struct {\nAddresses []IPWithPrefix\nRoutes []Route\nGSOMaxSize uint32\n- SoftwareGSOEnabled bool\n+ GvisorGSOEnabled bool\nTXChecksumOffload bool\nRXChecksumOffload bool\nLinkAddress net.HardwareAddr\n@@ -221,7 +221,7 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\nAddress: mac,\nPacketDispatchMode: fdbased.RecvMMsg,\nGSOMaxSize: link.GSOMaxSize,\n- SoftwareGSOEnabled: link.SoftwareGSOEnabled,\n+ GvisorGSOEnabled: link.GvisorGSOEnabled,\nTXChecksumOffload: link.TXChecksumOffload,\nRXChecksumOffload: link.RXChecksumOffload,\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/config/config.go",
"new_path": "runsc/config/config.go",
"diff": "@@ -88,11 +88,12 @@ type Config struct {\n// AllowPacketEndpointWrite enables write operations on packet endpoints.\nAllowPacketEndpointWrite bool `flag:\"TESTONLY-allow-packet-endpoint-write\"`\n- // HardwareGSO indicates that hardware segmentation offload is enabled.\n- HardwareGSO bool `flag:\"gso\"`\n+ // HostGSO indicates that host segmentation offload is enabled.\n+ HostGSO bool `flag:\"gso\"`\n- // SoftwareGSO indicates that software segmentation offload is enabled.\n- SoftwareGSO bool `flag:\"software-gso\"`\n+ // GvisorGSO indicates that gVisor segmentation offload is enabled. The flag\n+ // retains its old name of \"software\" GSO for API consistency.\n+ GvisorGSO bool `flag:\"software-gso\"`\n// TXChecksumOffload indicates that TX Checksum Offload is enabled.\nTXChecksumOffload bool `flag:\"tx-checksum-offload\"`\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/config/flags.go",
"new_path": "runsc/config/flags.go",
"diff": "@@ -90,8 +90,8 @@ func RegisterFlags(flagSet *flag.FlagSet) {\n// Flags that control sandbox runtime behavior: network related.\nflagSet.Var(networkTypePtr(NetworkSandbox), \"network\", \"specifies which network to use: sandbox (default), host, none. Using network inside the sandbox is more secure because it's isolated from the host network.\")\nflagSet.Bool(\"net-raw\", false, \"enable raw sockets. When false, raw sockets are disabled by removing CAP_NET_RAW from containers (`runsc exec` will still be able to utilize raw sockets). Raw sockets allow malicious containers to craft packets and potentially attack the network.\")\n- flagSet.Bool(\"gso\", true, \"enable hardware segmentation offload if it is supported by a network device.\")\n- flagSet.Bool(\"software-gso\", true, \"enable software segmentation offload when hardware offload can't be enabled.\")\n+ flagSet.Bool(\"gso\", true, \"enable host segmentation offload if it is supported by a network device.\")\n+ flagSet.Bool(\"software-gso\", true, \"enable gVisor segmentation offload when host offload can't be enabled.\")\nflagSet.Bool(\"tx-checksum-offload\", false, \"enable TX checksum offload.\")\nflagSet.Bool(\"rx-checksum-offload\", true, \"enable RX checksum offload.\")\nflagSet.Var(queueingDisciplinePtr(QDiscFIFO), \"qdisc\", \"specifies which queueing discipline to apply by default to the non loopback nics used by the sandbox.\")\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/network.go",
"new_path": "runsc/sandbox/network.go",
"diff": "@@ -63,7 +63,7 @@ func setupNetwork(conn *urpc.Client, pid int, conf *config.Config) error {\n// Build the path to the net namespace of the sandbox process.\n// This is what we will copy.\nnsPath := filepath.Join(\"/proc\", strconv.Itoa(pid), \"ns/net\")\n- if err := createInterfacesAndRoutesFromNS(conn, nsPath, conf.HardwareGSO, conf.SoftwareGSO, conf.TXChecksumOffload, conf.RXChecksumOffload, conf.NumNetworkChannels, conf.QDisc); err != nil {\n+ if err := createInterfacesAndRoutesFromNS(conn, nsPath, conf.HostGSO, conf.GvisorGSO, conf.TXChecksumOffload, conf.RXChecksumOffload, conf.NumNetworkChannels, conf.QDisc); err != nil {\nreturn fmt.Errorf(\"creating interfaces from net namespace %q: %v\", nsPath, err)\n}\ncase config.NetworkHost:\n@@ -116,7 +116,7 @@ func isRootNS() (bool, error) {\n// createInterfacesAndRoutesFromNS scrapes the interface and routes from the\n// net namespace with the given path, creates them in the sandbox, and removes\n// them from the host.\n-func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, hardwareGSO bool, softwareGSO bool, txChecksumOffload bool, rxChecksumOffload bool, numNetworkChannels int, qDisc config.QueueingDiscipline) error {\n+func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, hostGSO bool, gvisorGSO bool, txChecksumOffload bool, rxChecksumOffload bool, numNetworkChannels int, qDisc config.QueueingDiscipline) error {\n// Join the network namespace that we will be copying.\nrestore, err := joinNetNS(nsPath)\nif err != nil {\n@@ -235,7 +235,7 @@ func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, hardwareG\n// Create the socket for the device.\nfor i := 0; i < link.NumChannels; i++ {\nlog.Debugf(\"Creating Channel %d\", i)\n- socketEntry, err := createSocket(iface, ifaceLink, hardwareGSO)\n+ socketEntry, err := createSocket(iface, ifaceLink, hostGSO)\nif err != nil {\nreturn fmt.Errorf(\"failed to createSocket for %s : %w\", iface.Name, err)\n}\n@@ -250,10 +250,10 @@ func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, hardwareG\nargs.FilePayload.Files = append(args.FilePayload.Files, socketEntry.deviceFile)\n}\n- if link.GSOMaxSize == 0 && softwareGSO {\n- // Hardware GSO is disabled. Let's enable software GSO.\n- link.GSOMaxSize = stack.SoftwareGSOMaxSize\n- link.SoftwareGSOEnabled = true\n+ if link.GSOMaxSize == 0 && gvisorGSO {\n+ // Host GSO is disabled. Let's enable gVisor GSO.\n+ link.GSOMaxSize = stack.GvisorGSOMaxSize\n+ link.GvisorGSOEnabled = true\n}\n// Collect the addresses for the interface, enable forwarding,\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/tcp/tcp_proxy.go",
"new_path": "test/benchmarks/tcp/tcp_proxy.go",
"diff": "@@ -59,7 +59,7 @@ var (\nmoderateRecvBuf = flag.Bool(\"moderate_recv_buf\", false, \"enable TCP Receive Buffer Auto-tuning\")\ncubic = flag.Bool(\"cubic\", false, \"enable use of CUBIC congestion control for netstack\")\ngso = flag.Int(\"gso\", 0, \"GSO maximum size\")\n- swgso = flag.Bool(\"swgso\", false, \"software-level GSO\")\n+ swgso = flag.Bool(\"swgso\", false, \"gVisor-level GSO\")\nclientTCPProbeFile = flag.String(\"client_tcp_probe_file\", \"\", \"if specified, installs a tcp probe to dump endpoint state to the specified file.\")\nserverTCPProbeFile = flag.String(\"server_tcp_probe_file\", \"\", \"if specified, installs a tcp probe to dump endpoint state to the specified file.\")\ncpuprofile = flag.String(\"cpuprofile\", \"\", \"write cpu profile to the specified file.\")\n@@ -200,7 +200,7 @@ func newNetstackImpl(mode string) (impl, error) {\nRXChecksumOffload: true,\nPacketDispatchMode: fdbased.RecvMMsg,\nGSOMaxSize: uint32(*gso),\n- SoftwareGSOEnabled: *swgso,\n+ GvisorGSOEnabled: *swgso,\n})\nif err != nil {\nreturn nil, fmt.Errorf(\"failed to create FD endpoint: %v\", err)\n"
}
] | Go | Apache License 2.0 | google/gvisor | rename GSO: hardware->host and software->gVisor
API names such as flags and Makefile targets are unchanged so as not to break
users.
PiperOrigin-RevId: 458279776 |
259,941 | 01.07.2022 01:44:38 | -19,080 | 143f134d7ee86c95717df94e96d6f518c39b6e53 | fdbased: error is specifically tcpip.Error | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/endpoint.go",
"new_path": "pkg/tcpip/link/fdbased/endpoint.go",
"diff": "@@ -556,7 +556,7 @@ func (e *endpoint) sendBatch(batchFDInfo fdInfo, pkts []*stack.PacketBuffer) (in\n// Degrade to writePacket if underlying fd is not a socket.\nif !batchFDInfo.isSocket {\nvar written int\n- var err error\n+ var err tcpip.Error\nfor written < len(pkts) {\nif err = e.writePacket(pkts[written]); err != nil {\nbreak\n"
}
] | Go | Apache License 2.0 | google/gvisor | fdbased: error is specifically tcpip.Error |
259,982 | 01.07.2022 12:56:51 | 25,200 | 81414d79c38c590f507669d491dcd67693be784c | Fixing accept/accept4 and pipe syscall values.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/points.go",
"new_path": "pkg/sentry/syscalls/linux/points.go",
"diff": "@@ -402,7 +402,7 @@ func pipeHelper(t *kernel.Task, cxtData *pb.ContextData, info kernel.SyscallInfo\nif info.Exit {\nif pipeFDAddr := info.Args[0].Pointer(); pipeFDAddr != 0 {\nvar pipeFDs [2]int32\n- if _, err := primitive.CopyInt32SliceOut(t, pipeFDAddr, pipeFDs[2:2]); err == nil { // if NO error\n+ if _, err := primitive.CopyInt32SliceIn(t, pipeFDAddr, pipeFDs[:]); err == nil { // if NO error\np.Reader = pipeFDs[0]\np.Writer = pipeFDs[1]\n}\n@@ -602,10 +602,14 @@ func acceptHelper(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextD\nFlags: flags,\n}\naddr := info.Args[1].Pointer()\n- addrLen := info.Args[2].Uint()\n+ if addrLenPointer := info.Args[2].Pointer(); addrLenPointer != 0 {\n+ var addrLen uint32\n+ if _, err := primitive.CopyUint32In(t, addrLenPointer, &addrLen); err == nil { // if NO error\nif address, err := CaptureAddress(t, addr, addrLen); err == nil { // if NO error\np.Address = address\n}\n+ }\n+ }\nif fields.Local.Contains(seccheck.FieldSyscallPath) {\np.FdPath = getFilePath(t, int32(p.Fd))\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fixing accept/accept4 and pipe syscall values.
Updates #4805
PiperOrigin-RevId: 458527328 |
259,896 | 06.07.2022 10:46:33 | 25,200 | 5b70da95255ebecca3a53fa3b3ab4dd9c7c53eb2 | Add a new control message for destroying sandbox in multi-container mode.
Adds SandboxShutdown() control message to destroy sandbox manually.
Adds a new gVisor API for destroying the sandbox in multi container mode.
Test to verify the API and the control message works correctly. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/control/lifecycle.go",
"new_path": "pkg/sentry/control/lifecycle.go",
"diff": "@@ -35,16 +35,13 @@ type Lifecycle struct {\n// Kernel is the kernel where the tasks belong to.\nKernel *kernel.Kernel\n- // StartedCh is the channel used to send a message to the sentry that\n- // all the containers in the sandbox have been started.\n- StartedCh chan struct{}\n+ // ShutdownCh is the channel used to signal the sentry to shutdown\n+ // the sentry/sandbox.\n+ ShutdownCh chan struct{}\n// mu protects the fields below.\nmu sync.RWMutex\n- // containersStarted is the number of containers started in the sandbox.\n- containersStarted int32\n-\n// MountNamespacesMap is a map of container id/names and the mount\n// namespaces.\nMountNamespacesMap map[string]*vfs.MountNamespace\n@@ -171,17 +168,9 @@ func (l *Lifecycle) StartContainer(args *StartContainerArgs, _ *uint32) error {\nreturn err\n}\n- l.mu.Lock()\n- numContainers := int32(len(l.MountNamespacesMap))\n-\n// Start the newly created process.\nl.Kernel.StartProcess(tg)\n- log.Infof(\"Started the new container %v \", l.containersStarted)\n- l.containersStarted++\n- if numContainers == l.containersStarted {\n- l.StartedCh <- struct{}{}\n- }\n- l.mu.Unlock()\n+ log.Infof(\"Started the new container %v \", initArgs.ContainerID)\nreturn nil\n}\n@@ -196,3 +185,9 @@ func (l *Lifecycle) Resume(_, _ *struct{}) error {\nl.Kernel.Unpause()\nreturn nil\n}\n+\n+// Shutdown sends signal to destroy the sentry/sandbox.\n+func (l *Lifecycle) Shutdown(_, _ *struct{}) error {\n+ close(l.ShutdownCh)\n+ return nil\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add a new control message for destroying sandbox in multi-container mode.
- Adds SandboxShutdown() control message to destroy sandbox manually.
- Adds a new gVisor API for destroying the sandbox in multi container mode.
- Test to verify the API and the control message works correctly.
PiperOrigin-RevId: 459290099 |
259,868 | 06.07.2022 12:12:44 | 25,200 | 1b60c51687643202e60267a3e9609f6fe9a7e4f4 | Makefile: Don't overwrite `RUNTIME`-related variables if they are already set.
Without this, setting `RUNTIME` in the environment has no effect. | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -105,14 +105,14 @@ endif\n## DOCKER_RELOAD_COMMAND - The command to run to reload Docker. (default: sudo systemctl reload docker).\nifeq (,$(BRANCH_NAME))\n-RUNTIME := runsc\n+RUNTIME ?= runsc\nelse\n-RUNTIME := $(BRANCH_NAME)\n+RUNTIME ?= $(BRANCH_NAME)\nendif\nRUNTIME_DIR ?= $(shell dirname $(shell mktemp -u))/$(RUNTIME)\n-RUNTIME_BIN := $(RUNTIME_DIR)/runsc\n-RUNTIME_LOG_DIR := $(RUNTIME_DIR)/logs\n-RUNTIME_LOGS := $(RUNTIME_LOG_DIR)/runsc.log.%TEST%.%TIMESTAMP%.%COMMAND%\n+RUNTIME_BIN ?= $(RUNTIME_DIR)/runsc\n+RUNTIME_LOG_DIR ?= $(RUNTIME_DIR)/logs\n+RUNTIME_LOGS ?= $(RUNTIME_LOG_DIR)/runsc.log.%TEST%.%TIMESTAMP%.%COMMAND%\nRUNTIME_ARGS ?=\nDOCKER_RELOAD_COMMAND ?= sudo systemctl reload docker\n"
}
] | Go | Apache License 2.0 | google/gvisor | Makefile: Don't overwrite `RUNTIME`-related variables if they are already set.
Without this, setting `RUNTIME` in the environment has no effect.
PiperOrigin-RevId: 459311928 |
259,896 | 06.07.2022 13:48:55 | 25,200 | d101b6b184ee22170cc2e49532328952243108db | Multi-Container: Add GetExitStatus() control message to get the exit status.
Adds a new control message GetExitStatus() which blocks until the container
has finished execution and returns the exit status.
Tests to verify that the GetExitStatus() works correctly. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/control/lifecycle.go",
"new_path": "pkg/sentry/control/lifecycle.go",
"diff": "@@ -45,6 +45,10 @@ type Lifecycle struct {\n// MountNamespacesMap is a map of container id/names and the mount\n// namespaces.\nMountNamespacesMap map[string]*vfs.MountNamespace\n+\n+ // containerInitProcessMap is a map of container ID and the init(PID 1)\n+ // threadgroup of the container.\n+ containerInitProcessMap map[string]*kernel.ThreadGroup\n}\n// StartContainerArgs is the set of arguments to start a container.\n@@ -116,6 +120,11 @@ func (l *Lifecycle) StartContainer(args *StartContainerArgs, _ *uint32) error {\nif limitSet == nil {\nlimitSet = limits.NewLimitSet()\n}\n+\n+ // Create a new pid namespace for the container. Each container must run\n+ // in its own pid namespace.\n+ pidNs := l.Kernel.RootPIDNamespace().NewChild(l.Kernel.RootUserNamespace())\n+\ninitArgs := kernel.CreateProcessArgs{\nFilename: args.Filename,\nArgv: args.Argv,\n@@ -130,7 +139,7 @@ func (l *Lifecycle) StartContainer(args *StartContainerArgs, _ *uint32) error {\nIPCNamespace: l.Kernel.RootIPCNamespace(),\nAbstractSocketNamespace: l.Kernel.RootAbstractSocketNamespace(),\nContainerID: args.ContainerID,\n- PIDNamespace: l.Kernel.RootPIDNamespace(),\n+ PIDNamespace: pidNs,\n}\nctx := initArgs.NewContext(l.Kernel)\n@@ -171,6 +180,13 @@ func (l *Lifecycle) StartContainer(args *StartContainerArgs, _ *uint32) error {\n// Start the newly created process.\nl.Kernel.StartProcess(tg)\nlog.Infof(\"Started the new container %v \", initArgs.ContainerID)\n+\n+ l.mu.Lock()\n+ if l.containerInitProcessMap == nil {\n+ l.containerInitProcessMap = make(map[string]*kernel.ThreadGroup)\n+ }\n+ l.containerInitProcessMap[initArgs.ContainerID] = tg\n+ l.mu.Unlock()\nreturn nil\n}\n@@ -191,3 +207,33 @@ func (l *Lifecycle) Shutdown(_, _ *struct{}) error {\nclose(l.ShutdownCh)\nreturn nil\n}\n+\n+func (l *Lifecycle) getInitContainerProcess(containerID string) (*kernel.ThreadGroup, error) {\n+ l.mu.Lock()\n+ defer l.mu.Unlock()\n+\n+ tg, ok := l.containerInitProcessMap[containerID]\n+ if !ok {\n+ return nil, fmt.Errorf(\"container %v not started\", containerID)\n+ }\n+ return tg, nil\n+}\n+\n+// ContainerArgs is the set of arguments for container related APIs after\n+// starting the container.\n+type ContainerArgs struct {\n+ // ContainerID.\n+ ContainerID string `json:\"containerID\"`\n+}\n+\n+// WaitContainer waits for the container to exit and returns the exit status.\n+func (l *Lifecycle) WaitContainer(args *ContainerArgs, waitStatus *uint32) error {\n+ tg, err := l.getInitContainerProcess(args.ContainerID)\n+ if err != nil {\n+ return err\n+ }\n+\n+ tg.WaitExited()\n+ *waitStatus = uint32(tg.ExitStatus())\n+ return nil\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Multi-Container: Add GetExitStatus() control message to get the exit status.
- Adds a new control message GetExitStatus() which blocks until the container
has finished execution and returns the exit status.
- Tests to verify that the GetExitStatus() works correctly.
PiperOrigin-RevId: 459333916 |
259,982 | 07.07.2022 14:07:20 | 25,200 | c8e98d9f5ea9e7d229ab49ab3f4c5d764a7f4eca | Add Points to some syscalls
Added a raw syscall points to all syscalls. Added schematized syscall
points to the following syscalls:
- timerfd_create
- timerfd_settime
- timerfd_gettime
- fork, vfork
- inotify_init, inotify_init1
- inotify_add_watch
- inotify_rm_watch
- socketpair
Updates | [
{
"change_type": "MODIFY",
"old_path": "examples/seccheck/server.cc",
"new_path": "examples/seccheck/server.cc",
"diff": "@@ -105,6 +105,14 @@ std::vector<Callback> dispatchers = {\nunpackSyscall<::gvisor::syscall::Clone>,\nunpackSyscall<::gvisor::syscall::Bind>,\nunpackSyscall<::gvisor::syscall::Accept>,\n+ unpackSyscall<::gvisor::syscall::TimerfdCreate>,\n+ unpackSyscall<::gvisor::syscall::TimerfdSetTime>,\n+ unpackSyscall<::gvisor::syscall::TimerfdGetTime>,\n+ unpackSyscall<::gvisor::syscall::Fork>,\n+ unpackSyscall<::gvisor::syscall::InotifyInit>,\n+ unpackSyscall<::gvisor::syscall::InotifyAddWatch>,\n+ unpackSyscall<::gvisor::syscall::InotifyRmWatch>,\n+ unpackSyscall<::gvisor::syscall::SocketPair>,\n};\nvoid unpack(absl::string_view buf) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/metadata_amd64.go",
"new_path": "pkg/sentry/seccheck/metadata_amd64.go",
"diff": "@@ -139,6 +139,36 @@ func init() {\nName: \"fd_path\",\n},\n})\n+ addSyscallPoint(57, \"fork\", nil)\n+ addSyscallPoint(58, \"vfork\", nil)\n+ addSyscallPoint(253, \"inotify_init\", nil)\n+ addSyscallPoint(294, \"inotify_init1\", nil)\n+ addSyscallPoint(254, \"inotify_add_watch\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(255, \"inotify_rm_watch\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(283, \"timerfd_create\", nil)\n+ addSyscallPoint(286, \"timerfd_settime\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(287, \"timerfd_gettime\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(53, \"socketpair\", nil)\nconst lastSyscallInTable = 441\nfor i := 0; i <= lastSyscallInTable; i++ {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/metadata_arm64.go",
"new_path": "pkg/sentry/seccheck/metadata_arm64.go",
"diff": "@@ -118,6 +118,34 @@ func init() {\nName: \"fd_path\",\n},\n})\n+ addSyscallPoint(26, \"inotify_init1\", nil)\n+ addSyscallPoint(27, \"inotify_add_watch\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(28, \"inotify_rm_watch\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(85, \"timerfd_create\", nil)\n+ addSyscallPoint(86, \"timerfd_settime\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(87, \"timerfd_gettime\", []FieldDesc{\n+ {\n+ ID: FieldSyscallPath,\n+ Name: \"fd_path\",\n+ },\n+ })\n+ addSyscallPoint(199, \"socketpair\", nil)\n+\nconst lastSyscallInTable = 441\nfor i := 0; i <= lastSyscallInTable; i++ {\naddRawSyscallPoint(uintptr(i))\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/points/common.proto",
"new_path": "pkg/sentry/seccheck/points/common.proto",
"diff": "@@ -123,5 +123,13 @@ enum MessageType {\nMESSAGE_SYSCALL_CLONE = 23;\nMESSAGE_SYSCALL_BIND = 24;\nMESSAGE_SYSCALL_ACCEPT = 25;\n+ MESSAGE_SYSCALL_TIMERFD_CREATE = 26;\n+ MESSAGE_SYSCALL_TIMERFD_SETTIME = 27;\n+ MESSAGE_SYSCALL_TIMERFD_GETTIME = 28;\n+ MESSAGE_SYSCALL_FORK = 29;\n+ MESSAGE_SYSCALL_INOTIFY_INIT = 30;\n+ MESSAGE_SYSCALL_INOTIFY_ADD_WATCH = 31;\n+ MESSAGE_SYSCALL_INOTIFY_RM_WATCH = 32;\n+ MESSAGE_SYSCALL_SOCKETPAIR = 33;\n}\n// LINT.ThenChange(../../../../examples/seccheck/server.cc)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/points/syscall.proto",
"new_path": "pkg/sentry/seccheck/points/syscall.proto",
"diff": "@@ -178,6 +178,7 @@ message Chroot {\nuint64 sysno = 3;\nstring pathname = 4;\n}\n+\nmessage Eventfd {\ngvisor.common.ContextData context_data = 1;\nExit exit = 2;\n@@ -214,3 +215,84 @@ message Accept {\nbytes address = 6;\nint32 flags = 7;\n}\n+\n+message TimerfdCreate {\n+ gvisor.common.ContextData context_data = 1;\n+ Exit exit = 2;\n+ uint64 sysno = 3;\n+ int32 clock_id = 4;\n+ int32 flags = 5;\n+}\n+\n+message Timespec {\n+ int64 sec = 1;\n+ int64 nsec = 2;\n+}\n+\n+message ItimerSpec {\n+ Timespec interval = 1;\n+ Timespec value = 2;\n+}\n+\n+message TimerfdSetTime {\n+ gvisor.common.ContextData context_data = 1;\n+ Exit exit = 2;\n+ uint64 sysno = 3;\n+ int32 fd = 4;\n+ string fd_path = 5;\n+ int32 flags = 6;\n+ ItimerSpec new_value = 7;\n+ ItimerSpec old_value = 8;\n+}\n+\n+message TimerfdGetTime {\n+ gvisor.common.ContextData context_data = 1;\n+ Exit exit = 2;\n+ uint64 sysno = 3;\n+ int32 fd = 4;\n+ string fd_path = 5;\n+ ItimerSpec cur_value = 6;\n+}\n+\n+message Fork {\n+ gvisor.common.ContextData context_data = 1;\n+ Exit exit = 2;\n+ uint64 sysno = 3;\n+}\n+\n+message InotifyInit {\n+ gvisor.common.ContextData context_data = 1;\n+ Exit exit = 2;\n+ uint64 sysno = 3;\n+ int32 flags = 4;\n+}\n+\n+message InotifyAddWatch{\n+ gvisor.common.ContextData context_data = 1;\n+ Exit exit = 2;\n+ uint64 sysno = 3;\n+ int32 fd = 4;\n+ string fd_path = 5;\n+ string pathname = 6;\n+ uint32 mask = 7;\n+}\n+\n+message InotifyRmWatch {\n+ gvisor.common.ContextData context_data = 1;\n+ Exit exit = 2;\n+ uint64 sysno = 3;\n+ int32 fd = 4;\n+ string fd_path = 5;\n+ int32 wd = 6;\n+}\n+\n+message SocketPair {\n+ gvisor.common.ContextData context_data = 1;\n+ Exit exit = 2;\n+ uint64 sysno = 3;\n+ int32 domain = 4;\n+ int32 type = 5;\n+ int32 protocol = 6;\n+ int32 socket1 = 7;\n+ int32 socket2 = 8;\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/linux64.go",
"new_path": "pkg/sentry/syscalls/linux/linux64.go",
"diff": "@@ -105,12 +105,12 @@ var AMD64 = &kernel.SyscallTable{\n50: syscalls.Supported(\"listen\", Listen),\n51: syscalls.Supported(\"getsockname\", GetSockName),\n52: syscalls.Supported(\"getpeername\", GetPeerName),\n- 53: syscalls.Supported(\"socketpair\", SocketPair),\n+ 53: syscalls.SupportedPoint(\"socketpair\", SocketPair, PointSocketpair),\n54: syscalls.PartiallySupported(\"setsockopt\", SetSockOpt, \"Not all socket options are supported.\", nil),\n55: syscalls.PartiallySupported(\"getsockopt\", GetSockOpt, \"Not all socket options are supported.\", nil),\n56: syscalls.PartiallySupportedPoint(\"clone\", Clone, PointClone, \"Mount namespace (CLONE_NEWNS) not supported. Options CLONE_PARENT, CLONE_SYSVSEM not supported.\", nil),\n- 57: syscalls.Supported(\"fork\", Fork),\n- 58: syscalls.Supported(\"vfork\", Vfork),\n+ 57: syscalls.SupportedPoint(\"fork\", Fork, PointFork),\n+ 58: syscalls.SupportedPoint(\"vfork\", Vfork, PointVfork),\n59: syscalls.SupportedPoint(\"execve\", Execve, PointExecve),\n60: syscalls.Supported(\"exit\", Exit),\n61: syscalls.Supported(\"wait4\", Wait4),\n@@ -305,9 +305,9 @@ var AMD64 = &kernel.SyscallTable{\n250: syscalls.Error(\"keyctl\", linuxerr.EACCES, \"Not available to user.\", nil),\n251: syscalls.CapError(\"ioprio_set\", linux.CAP_SYS_ADMIN, \"\", nil), // requires cap_sys_nice or cap_sys_admin (depending)\n252: syscalls.CapError(\"ioprio_get\", linux.CAP_SYS_ADMIN, \"\", nil), // requires cap_sys_nice or cap_sys_admin (depending)\n- 253: syscalls.PartiallySupported(\"inotify_init\", InotifyInit, \"Inotify events are only available inside the sandbox. Hard links are treated as different watch targets in gofer fs.\", nil),\n- 254: syscalls.PartiallySupported(\"inotify_add_watch\", InotifyAddWatch, \"Inotify events are only available inside the sandbox. Hard links are treated as different watch targets in gofer fs.\", nil),\n- 255: syscalls.PartiallySupported(\"inotify_rm_watch\", InotifyRmWatch, \"Inotify events are only available inside the sandbox. Hard links are treated as different watch targets in gofer fs.\", nil),\n+ 253: syscalls.PartiallySupportedPoint(\"inotify_init\", InotifyInit, PointInotifyInit, \"Inotify events are only available inside the sandbox. Hard links are treated as different watch targets in gofer fs.\", nil),\n+ 254: syscalls.PartiallySupportedPoint(\"inotify_add_watch\", InotifyAddWatch, PointInotifyAddWatch, \"Inotify events are only available inside the sandbox. Hard links are treated as different watch targets in gofer fs.\", nil),\n+ 255: syscalls.PartiallySupportedPoint(\"inotify_rm_watch\", InotifyRmWatch, PointInotifyRmWatch, \"Inotify events are only available inside the sandbox. Hard links are treated as different watch targets in gofer fs.\", nil),\n256: syscalls.CapError(\"migrate_pages\", linux.CAP_SYS_NICE, \"\", nil),\n257: syscalls.SupportedPoint(\"openat\", Openat, PointOpenat),\n258: syscalls.Supported(\"mkdirat\", Mkdirat),\n@@ -335,18 +335,18 @@ var AMD64 = &kernel.SyscallTable{\n280: syscalls.Supported(\"utimensat\", Utimensat),\n281: syscalls.Supported(\"epoll_pwait\", EpollPwait),\n282: syscalls.PartiallySupportedPoint(\"signalfd\", Signalfd, PointSignalfd, \"Semantics are slightly different.\", []string{\"gvisor.dev/issue/139\"}),\n- 283: syscalls.Supported(\"timerfd_create\", TimerfdCreate),\n+ 283: syscalls.SupportedPoint(\"timerfd_create\", TimerfdCreate, PointTimerfdCreate),\n284: syscalls.SupportedPoint(\"eventfd\", Eventfd, PointEventfd),\n285: syscalls.PartiallySupported(\"fallocate\", Fallocate, \"Not all options are supported.\", nil),\n- 286: syscalls.Supported(\"timerfd_settime\", TimerfdSettime),\n- 287: syscalls.Supported(\"timerfd_gettime\", TimerfdGettime),\n+ 286: syscalls.SupportedPoint(\"timerfd_settime\", TimerfdSettime, PointTimerfdSettime),\n+ 287: syscalls.SupportedPoint(\"timerfd_gettime\", TimerfdGettime, PointTimerfdGettime),\n288: syscalls.SupportedPoint(\"accept4\", Accept4, PointAccept4),\n289: syscalls.PartiallySupportedPoint(\"signalfd4\", Signalfd4, PointSignalfd4, \"Semantics are slightly different.\", []string{\"gvisor.dev/issue/139\"}),\n290: syscalls.SupportedPoint(\"eventfd2\", Eventfd2, PointEventfd2),\n291: syscalls.Supported(\"epoll_create1\", EpollCreate1),\n292: syscalls.SupportedPoint(\"dup3\", Dup3, PointDup3),\n293: syscalls.SupportedPoint(\"pipe2\", Pipe2, PointPipe2),\n- 294: syscalls.PartiallySupported(\"inotify_init1\", InotifyInit1, \"Inotify events are only available inside the sandbox. Hard links are treated as different watch targets in gofer fs.\", nil),\n+ 294: syscalls.PartiallySupportedPoint(\"inotify_init1\", InotifyInit1, PointInotifyInit1, \"Inotify events are only available inside the sandbox. Hard links are treated as different watch targets in gofer fs.\", nil),\n295: syscalls.Supported(\"preadv\", Preadv),\n296: syscalls.Supported(\"pwritev\", Pwritev),\n297: syscalls.Supported(\"rt_tgsigqueueinfo\", RtTgsigqueueinfo),\n@@ -456,9 +456,9 @@ var ARM64 = &kernel.SyscallTable{\n23: syscalls.SupportedPoint(\"dup\", Dup, PointDup),\n24: syscalls.SupportedPoint(\"dup3\", Dup3, PointDup3),\n25: syscalls.PartiallySupportedPoint(\"fcntl\", Fcntl, PointFcntl, \"Not all options are supported.\", nil),\n- 26: syscalls.PartiallySupported(\"inotify_init1\", InotifyInit1, \"Inotify events are only available inside the sandbox. Hard links are treated as different watch targets in gofer fs.\", nil),\n- 27: syscalls.PartiallySupported(\"inotify_add_watch\", InotifyAddWatch, \"Inotify events are only available inside the sandbox. Hard links are treated as different watch targets in gofer fs.\", nil),\n- 28: syscalls.PartiallySupported(\"inotify_rm_watch\", InotifyRmWatch, \"Inotify events are only available inside the sandbox. Hard links are treated as different watch targets in gofer fs.\", nil),\n+ 26: syscalls.PartiallySupportedPoint(\"inotify_init1\", InotifyInit1, PointInotifyInit1, \"Inotify events are only available inside the sandbox. Hard links are treated as different watch targets in gofer fs.\", nil),\n+ 27: syscalls.PartiallySupportedPoint(\"inotify_add_watch\", InotifyAddWatch, PointInotifyAddWatch, \"Inotify events are only available inside the sandbox. Hard links are treated as different watch targets in gofer fs.\", nil),\n+ 28: syscalls.PartiallySupportedPoint(\"inotify_rm_watch\", InotifyRmWatch, PointInotifyRmWatch, \"Inotify events are only available inside the sandbox. Hard links are treated as different watch targets in gofer fs.\", nil),\n29: syscalls.PartiallySupported(\"ioctl\", Ioctl, \"Only a few ioctls are implemented for backing devices and file systems.\", nil),\n30: syscalls.CapError(\"ioprio_set\", linux.CAP_SYS_ADMIN, \"\", nil), // requires cap_sys_nice or cap_sys_admin (depending)\n31: syscalls.CapError(\"ioprio_get\", linux.CAP_SYS_ADMIN, \"\", nil), // requires cap_sys_nice or cap_sys_admin (depending)\n@@ -515,9 +515,9 @@ var ARM64 = &kernel.SyscallTable{\n82: syscalls.PartiallySupported(\"fsync\", Fsync, \"Full data flush is not guaranteed at this time.\", nil),\n83: syscalls.PartiallySupported(\"fdatasync\", Fdatasync, \"Full data flush is not guaranteed at this time.\", nil),\n84: syscalls.PartiallySupported(\"sync_file_range\", SyncFileRange, \"Full data flush is not guaranteed at this time.\", nil),\n- 85: syscalls.Supported(\"timerfd_create\", TimerfdCreate),\n- 86: syscalls.Supported(\"timerfd_settime\", TimerfdSettime),\n- 87: syscalls.Supported(\"timerfd_gettime\", TimerfdGettime),\n+ 85: syscalls.SupportedPoint(\"timerfd_create\", TimerfdCreate, PointTimerfdCreate),\n+ 86: syscalls.SupportedPoint(\"timerfd_settime\", TimerfdSettime, PointTimerfdSettime),\n+ 87: syscalls.SupportedPoint(\"timerfd_gettime\", TimerfdGettime, PointTimerfdGettime),\n88: syscalls.Supported(\"utimensat\", Utimensat),\n89: syscalls.CapError(\"acct\", linux.CAP_SYS_PACCT, \"\", nil),\n90: syscalls.Supported(\"capget\", Capget),\n@@ -629,7 +629,7 @@ var ARM64 = &kernel.SyscallTable{\n196: syscalls.PartiallySupported(\"shmat\", Shmat, \"Option SHM_RND is not supported.\", nil),\n197: syscalls.Supported(\"shmdt\", Shmdt),\n198: syscalls.PartiallySupported(\"socket\", Socket, \"Limited support for AF_NETLINK, NETLINK_ROUTE sockets. Limited support for SOCK_RAW.\", nil),\n- 199: syscalls.Supported(\"socketpair\", SocketPair),\n+ 199: syscalls.SupportedPoint(\"socketpair\", SocketPair, PointSocketpair),\n200: syscalls.PartiallySupportedPoint(\"bind\", Bind, PointBind, \"Autobind for abstract Unix sockets is not supported.\", nil),\n201: syscalls.Supported(\"listen\", Listen),\n202: syscalls.SupportedPoint(\"accept\", Accept, PointAccept),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/points.go",
"new_path": "pkg/sentry/syscalls/linux/points.go",
"diff": "@@ -629,3 +629,189 @@ func PointAccept4(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextD\nflags := info.Args[3].Int()\nreturn acceptHelper(t, fields, cxtData, info, flags)\n}\n+\n+// PointTimerfdCreate converts timerfd_create(2) syscall to proto.\n+func PointTimerfdCreate(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ p := &pb.TimerfdCreate{\n+ ContextData: cxtData,\n+ Sysno: uint64(info.Sysno),\n+ ClockId: info.Args[0].Int(),\n+ Flags: info.Args[1].Int(),\n+ }\n+\n+ p.Exit = newExitMaybe(info)\n+ return p, pb.MessageType_MESSAGE_SYSCALL_TIMERFD_CREATE\n+}\n+\n+func getValues(values linux.Timespec) *pb.Timespec {\n+ return &pb.Timespec{\n+ Sec: values.Sec,\n+ Nsec: values.Nsec,\n+ }\n+}\n+\n+// PointTimerfdSettime converts timerfd_settime(2) syscall to proto.\n+func PointTimerfdSettime(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ p := &pb.TimerfdSetTime{\n+ ContextData: cxtData,\n+ Sysno: uint64(info.Sysno),\n+ Fd: info.Args[0].Int(),\n+ Flags: info.Args[1].Int(),\n+ }\n+\n+ if fields.Local.Contains(seccheck.FieldSyscallPath) {\n+ p.FdPath = getFilePath(t, int32(p.Fd))\n+ }\n+\n+ var newVal linux.Itimerspec\n+ if newValAddr := info.Args[2].Pointer(); newValAddr != 0 {\n+ if _, err := newVal.CopyIn(t, newValAddr); err == nil {\n+ p.NewValue = &pb.ItimerSpec{\n+ Interval: getValues(newVal.Interval),\n+ Value: getValues(newVal.Value),\n+ }\n+ }\n+ }\n+ if info.Exit {\n+ var oldVal linux.Itimerspec\n+ if oldValAddr := info.Args[3].Pointer(); oldValAddr != 0 {\n+ if _, err := oldVal.CopyIn(t, oldValAddr); err == nil {\n+ p.OldValue = &pb.ItimerSpec{\n+ Interval: getValues(oldVal.Interval),\n+ Value: getValues(oldVal.Value),\n+ }\n+ }\n+ }\n+ }\n+\n+ p.Exit = newExitMaybe(info)\n+ return p, pb.MessageType_MESSAGE_SYSCALL_TIMERFD_SETTIME\n+}\n+\n+// PointTimerfdGettime converts timerfd_gettime(2) syscall to proto.\n+func PointTimerfdGettime(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ p := &pb.TimerfdGetTime{\n+ ContextData: cxtData,\n+ Sysno: uint64(info.Sysno),\n+ Fd: info.Args[0].Int(),\n+ }\n+\n+ if fields.Local.Contains(seccheck.FieldSyscallPath) {\n+ p.FdPath = getFilePath(t, int32(p.Fd))\n+ }\n+\n+ if curValAddr := info.Args[1].Pointer(); curValAddr != 0 {\n+ var curVal linux.Itimerspec\n+ if _, err := curVal.CopyIn(t, curValAddr); err == nil {\n+ p.CurValue = &pb.ItimerSpec{\n+ Interval: getValues(curVal.Interval),\n+ Value: getValues(curVal.Value),\n+ }\n+ }\n+ }\n+\n+ p.Exit = newExitMaybe(info)\n+ return p, pb.MessageType_MESSAGE_SYSCALL_TIMERFD_GETTIME\n+}\n+\n+// pointForkHelper converts fork(2) and vfork(2) syscall to proto.\n+func pointForkHelper(cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ p := &pb.Fork{\n+ ContextData: cxtData,\n+ Sysno: uint64(info.Sysno),\n+ }\n+\n+ p.Exit = newExitMaybe(info)\n+ return p, pb.MessageType_MESSAGE_SYSCALL_FORK\n+}\n+\n+// PointFork converts fork(2) syscall to proto.\n+func PointFork(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ return pointForkHelper(cxtData, info)\n+}\n+\n+// PointVfork converts vfork(2) syscall to proto.\n+func PointVfork(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ return pointForkHelper(cxtData, info)\n+}\n+\n+// pointInotifyInitHelper converts inotify_init(2) and inotify_init1(2) syscall to proto.\n+func pointInotifyInitHelper(cxtData *pb.ContextData, info kernel.SyscallInfo, flags int32) (proto.Message, pb.MessageType) {\n+ p := &pb.InotifyInit{\n+ ContextData: cxtData,\n+ Sysno: uint64(info.Sysno),\n+ Flags: flags,\n+ }\n+\n+ p.Exit = newExitMaybe(info)\n+ return p, pb.MessageType_MESSAGE_SYSCALL_INOTIFY_INIT\n+}\n+\n+// PointInotifyInit converts inotify_init(2) syscall to proto.\n+func PointInotifyInit(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ return pointInotifyInitHelper(cxtData, info, 0)\n+}\n+\n+// PointInotifyInit1 converts inotify_init1(2) syscall to proto.\n+func PointInotifyInit1(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ flags := info.Args[0].Int()\n+ return pointInotifyInitHelper(cxtData, info, flags)\n+}\n+\n+// PointInotifyAddWatch converts inotify_add_watch(2) syscall to proto.\n+func PointInotifyAddWatch(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ p := &pb.InotifyAddWatch{\n+ ContextData: cxtData,\n+ Sysno: uint64(info.Sysno),\n+ Fd: info.Args[0].Int(),\n+ Mask: info.Args[2].Uint(),\n+ }\n+ if pathAddr := info.Args[1].Pointer(); pathAddr > 0 {\n+ p.Pathname, _ = t.CopyInString(pathAddr, linux.PATH_MAX)\n+ }\n+\n+ if fields.Local.Contains(seccheck.FieldSyscallPath) {\n+ p.FdPath = getFilePath(t, int32(p.Fd))\n+ }\n+\n+ p.Exit = newExitMaybe(info)\n+ return p, pb.MessageType_MESSAGE_SYSCALL_INOTIFY_ADD_WATCH\n+}\n+\n+// PointInotifyRmWatch converts inotify_add_watch(2) syscall to proto.\n+func PointInotifyRmWatch(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ p := &pb.InotifyRmWatch{\n+ ContextData: cxtData,\n+ Sysno: uint64(info.Sysno),\n+ Fd: info.Args[0].Int(),\n+ Wd: info.Args[2].Int(),\n+ }\n+\n+ if fields.Local.Contains(seccheck.FieldSyscallPath) {\n+ p.FdPath = getFilePath(t, int32(p.Fd))\n+ }\n+\n+ p.Exit = newExitMaybe(info)\n+ return p, pb.MessageType_MESSAGE_SYSCALL_INOTIFY_RM_WATCH\n+}\n+\n+// PointSocketpair converts socketpair(2) syscall to proto.\n+func PointSocketpair(t *kernel.Task, fields seccheck.FieldSet, cxtData *pb.ContextData, info kernel.SyscallInfo) (proto.Message, pb.MessageType) {\n+ p := &pb.SocketPair{\n+ ContextData: cxtData,\n+ Sysno: uint64(info.Sysno),\n+ Domain: info.Args[0].Int(),\n+ Type: info.Args[1].Int(),\n+ Protocol: info.Args[2].Int(),\n+ }\n+ if info.Exit {\n+ sockets := info.Args[3].Pointer()\n+ var fds [2]int32\n+ if _, err := primitive.CopyInt32SliceIn(t, sockets, fds[:]); err == nil { // if NO error\n+ p.Socket1 = fds[0]\n+ p.Socket2 = fds[1]\n+ }\n+ }\n+ p.Exit = newExitMaybe(info)\n+ return p, pb.MessageType_MESSAGE_SYSCALL_SOCKETPAIR\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/vfs2.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/vfs2.go",
"diff": "@@ -57,7 +57,7 @@ func Override() {\ns.Table[50] = syscalls.Supported(\"listen\", Listen)\ns.Table[51] = syscalls.Supported(\"getsockname\", GetSockName)\ns.Table[52] = syscalls.Supported(\"getpeername\", GetPeerName)\n- s.Table[53] = syscalls.Supported(\"socketpair\", SocketPair)\n+ s.Table[53] = syscalls.SupportedPoint(\"socketpair\", SocketPair, linux.PointSocketpair)\ns.Table[54] = syscalls.Supported(\"setsockopt\", SetSockOpt)\ns.Table[55] = syscalls.Supported(\"getsockopt\", GetSockOpt)\ns.Table[59] = syscalls.SupportedPoint(\"execve\", Execve, linux.PointExecve)\n@@ -115,9 +115,9 @@ func Override() {\ns.Table[235] = syscalls.Supported(\"utimes\", Utimes)\ns.Table[240] = syscalls.Supported(\"mq_open\", MqOpen)\ns.Table[241] = syscalls.Supported(\"mq_unlink\", MqUnlink)\n- s.Table[253] = syscalls.PartiallySupported(\"inotify_init\", InotifyInit, \"inotify events are only available inside the sandbox.\", nil)\n- s.Table[254] = syscalls.PartiallySupported(\"inotify_add_watch\", InotifyAddWatch, \"inotify events are only available inside the sandbox.\", nil)\n- s.Table[255] = syscalls.PartiallySupported(\"inotify_rm_watch\", InotifyRmWatch, \"inotify events are only available inside the sandbox.\", nil)\n+ s.Table[253] = syscalls.PartiallySupportedPoint(\"inotify_init\", InotifyInit, linux.PointInotifyInit, \"inotify events are only available inside the sandbox.\", nil)\n+ s.Table[254] = syscalls.PartiallySupportedPoint(\"inotify_add_watch\", InotifyAddWatch, linux.PointInotifyAddWatch, \"inotify events are only available inside the sandbox.\", nil)\n+ s.Table[255] = syscalls.PartiallySupportedPoint(\"inotify_rm_watch\", InotifyRmWatch, linux.PointInotifyRmWatch, \"inotify events are only available inside the sandbox.\", nil)\ns.Table[257] = syscalls.SupportedPoint(\"openat\", Openat, linux.PointOpenat)\ns.Table[258] = syscalls.Supported(\"mkdirat\", Mkdirat)\ns.Table[259] = syscalls.Supported(\"mknodat\", Mknodat)\n@@ -139,18 +139,18 @@ func Override() {\ns.Table[280] = syscalls.Supported(\"utimensat\", Utimensat)\ns.Table[281] = syscalls.Supported(\"epoll_pwait\", EpollPwait)\ns.Table[282] = syscalls.SupportedPoint(\"signalfd\", Signalfd, linux.PointSignalfd)\n- s.Table[283] = syscalls.Supported(\"timerfd_create\", TimerfdCreate)\n+ s.Table[283] = syscalls.SupportedPoint(\"timerfd_create\", TimerfdCreate, linux.PointTimerfdCreate)\ns.Table[284] = syscalls.SupportedPoint(\"eventfd\", Eventfd, linux.PointEventfd)\ns.Table[285] = syscalls.PartiallySupported(\"fallocate\", Fallocate, \"Not all options are supported.\", nil)\n- s.Table[286] = syscalls.Supported(\"timerfd_settime\", TimerfdSettime)\n- s.Table[287] = syscalls.Supported(\"timerfd_gettime\", TimerfdGettime)\n+ s.Table[286] = syscalls.SupportedPoint(\"timerfd_settime\", TimerfdSettime, linux.PointTimerfdSettime)\n+ s.Table[287] = syscalls.SupportedPoint(\"timerfd_gettime\", TimerfdGettime, linux.PointTimerfdGettime)\ns.Table[288] = syscalls.SupportedPoint(\"accept4\", Accept4, linux.PointAccept4)\ns.Table[289] = syscalls.SupportedPoint(\"signalfd4\", Signalfd4, linux.PointSignalfd4)\ns.Table[290] = syscalls.SupportedPoint(\"eventfd2\", Eventfd2, linux.PointEventfd2)\ns.Table[291] = syscalls.Supported(\"epoll_create1\", EpollCreate1)\ns.Table[292] = syscalls.SupportedPoint(\"dup3\", Dup3, linux.PointDup3)\ns.Table[293] = syscalls.SupportedPoint(\"pipe2\", Pipe2, linux.PointPipe2)\n- s.Table[294] = syscalls.PartiallySupported(\"inotify_init1\", InotifyInit1, \"inotify events are only available inside the sandbox.\", nil)\n+ s.Table[294] = syscalls.PartiallySupportedPoint(\"inotify_init1\", InotifyInit1, linux.PointInotifyInit1, \"inotify events are only available inside the sandbox.\", nil)\ns.Table[295] = syscalls.Supported(\"preadv\", Preadv)\ns.Table[296] = syscalls.Supported(\"pwritev\", Pwritev)\ns.Table[299] = syscalls.Supported(\"recvmmsg\", RecvMMsg)\n@@ -190,9 +190,9 @@ func Override() {\ns.Table[23] = syscalls.SupportedPoint(\"dup\", Dup, linux.PointDup)\ns.Table[24] = syscalls.SupportedPoint(\"dup3\", Dup3, linux.PointDup3)\ns.Table[25] = syscalls.SupportedPoint(\"fcntl\", Fcntl, linux.PointFcntl)\n- s.Table[26] = syscalls.PartiallySupported(\"inotify_init1\", InotifyInit1, \"inotify events are only available inside the sandbox.\", nil)\n- s.Table[27] = syscalls.PartiallySupported(\"inotify_add_watch\", InotifyAddWatch, \"inotify events are only available inside the sandbox.\", nil)\n- s.Table[28] = syscalls.PartiallySupported(\"inotify_rm_watch\", InotifyRmWatch, \"inotify events are only available inside the sandbox.\", nil)\n+ s.Table[26] = syscalls.PartiallySupportedPoint(\"inotify_init1\", InotifyInit1, linux.PointInotifyInit1, \"inotify events are only available inside the sandbox.\", nil)\n+ s.Table[27] = syscalls.PartiallySupportedPoint(\"inotify_add_watch\", InotifyAddWatch, linux.PointInotifyAddWatch, \"inotify events are only available inside the sandbox.\", nil)\n+ s.Table[28] = syscalls.PartiallySupportedPoint(\"inotify_rm_watch\", InotifyRmWatch, linux.PointInotifyRmWatch, \"inotify events are only available inside the sandbox.\", nil)\ns.Table[29] = syscalls.Supported(\"ioctl\", Ioctl)\ns.Table[32] = syscalls.Supported(\"flock\", Flock)\ns.Table[33] = syscalls.Supported(\"mknodat\", Mknodat)\n@@ -243,14 +243,14 @@ func Override() {\ns.Table[82] = syscalls.Supported(\"fsync\", Fsync)\ns.Table[83] = syscalls.Supported(\"fdatasync\", Fdatasync)\ns.Table[84] = syscalls.Supported(\"sync_file_range\", SyncFileRange)\n- s.Table[85] = syscalls.Supported(\"timerfd_create\", TimerfdCreate)\n- s.Table[86] = syscalls.Supported(\"timerfd_settime\", TimerfdSettime)\n- s.Table[87] = syscalls.Supported(\"timerfd_gettime\", TimerfdGettime)\n+ s.Table[85] = syscalls.SupportedPoint(\"timerfd_create\", TimerfdCreate, linux.PointTimerfdCreate)\n+ s.Table[86] = syscalls.SupportedPoint(\"timerfd_settime\", TimerfdSettime, linux.PointTimerfdSettime)\n+ s.Table[87] = syscalls.SupportedPoint(\"timerfd_gettime\", TimerfdGettime, linux.PointTimerfdGettime)\ns.Table[88] = syscalls.Supported(\"utimensat\", Utimensat)\ns.Table[180] = syscalls.Supported(\"mq_open\", MqOpen)\ns.Table[181] = syscalls.Supported(\"mq_unlink\", MqUnlink)\ns.Table[198] = syscalls.SupportedPoint(\"socket\", Socket, linux.PointSocket)\n- s.Table[199] = syscalls.Supported(\"socketpair\", SocketPair)\n+ s.Table[199] = syscalls.SupportedPoint(\"socketpair\", SocketPair, linux.PointSocketpair)\ns.Table[200] = syscalls.SupportedPoint(\"bind\", Bind, linux.PointBind)\ns.Table[201] = syscalls.Supported(\"listen\", Listen)\ns.Table[202] = syscalls.SupportedPoint(\"accept\", Accept, linux.PointAccept)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add Points to some syscalls
Added a raw syscall points to all syscalls. Added schematized syscall
points to the following syscalls:
- timerfd_create
- timerfd_settime
- timerfd_gettime
- fork, vfork
- inotify_init, inotify_init1
- inotify_add_watch
- inotify_rm_watch
- socketpair
Updates #4805
PiperOrigin-RevId: 459596784 |
259,978 | 07.07.2022 18:54:12 | 25,200 | 7103ddb238dc8ed75d8d24ce1aae5bd36fc61bd8 | Add checklocks to addressable_endpoint_state.go
Added checklocks annotations to `addressable_endpoint_state.go`.
Refactored slightly to appease the analyzer. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/addressable_endpoint_state.go",
"new_path": "pkg/tcpip/stack/addressable_endpoint_state.go",
"diff": "@@ -31,13 +31,12 @@ type AddressableEndpointState struct {\n//\n// AddressableEndpointState.mu\n// addressState.mu\n- mu struct {\n- sync.RWMutex\n-\n+ mu sync.RWMutex\n+ // +checklocks:mu\nendpoints map[tcpip.Address]*addressState\n+ // +checklocks:mu\nprimary []*addressState\n}\n-}\n// Init initializes the AddressableEndpointState with networkEndpoint.\n//\n@@ -47,7 +46,7 @@ func (a *AddressableEndpointState) Init(networkEndpoint NetworkEndpoint) {\na.mu.Lock()\ndefer a.mu.Unlock()\n- a.mu.endpoints = make(map[tcpip.Address]*addressState)\n+ a.endpoints = make(map[tcpip.Address]*addressState)\n}\n// GetAddress returns the AddressEndpoint for the passed address.\n@@ -60,7 +59,7 @@ func (a *AddressableEndpointState) GetAddress(addr tcpip.Address) AddressEndpoin\na.mu.RLock()\ndefer a.mu.RUnlock()\n- ep, ok := a.mu.endpoints[addr]\n+ ep, ok := a.endpoints[addr]\nif !ok {\nreturn nil\n}\n@@ -74,7 +73,7 @@ func (a *AddressableEndpointState) ForEachEndpoint(f func(AddressEndpoint) bool)\na.mu.RLock()\ndefer a.mu.RUnlock()\n- for _, ep := range a.mu.endpoints {\n+ for _, ep := range a.endpoints {\nif !f(ep) {\nreturn\n}\n@@ -88,7 +87,7 @@ func (a *AddressableEndpointState) ForEachPrimaryEndpoint(f func(AddressEndpoint\na.mu.RLock()\ndefer a.mu.RUnlock()\n- for _, ep := range a.mu.primary {\n+ for _, ep := range a.primary {\nif !f(ep) {\nreturn\n}\n@@ -101,19 +100,20 @@ func (a *AddressableEndpointState) releaseAddressState(addrState *addressState)\na.releaseAddressStateLocked(addrState)\n}\n-// releaseAddressState removes addrState from s's address state (primary and endpoints list).\n+// releaseAddressStateLocked removes addrState from a's address state\n+// (primary and endpoints list).\n//\n-// Preconditions: a.mu must be write locked.\n+// +checklocks:a.mu\nfunc (a *AddressableEndpointState) releaseAddressStateLocked(addrState *addressState) {\n- oldPrimary := a.mu.primary\n- for i, s := range a.mu.primary {\n+ oldPrimary := a.primary\n+ for i, s := range a.primary {\nif s == addrState {\n- a.mu.primary = append(a.mu.primary[:i], a.mu.primary[i+1:]...)\n+ a.primary = append(a.primary[:i], a.primary[i+1:]...)\noldPrimary[len(oldPrimary)-1] = nil\nbreak\n}\n}\n- delete(a.mu.endpoints, addrState.addr.Address)\n+ delete(a.endpoints, addrState.addr.Address)\n}\n// AddAndAcquirePermanentAddress implements AddressableEndpoint.\n@@ -179,12 +179,12 @@ func (a *AddressableEndpointState) AddAndAcquireTemporaryAddress(addr tcpip.Addr\n// address already exists in any other state, then *tcpip.ErrDuplicateAddress is\n// returned, regardless the kind of address that is being added.\n//\n-// Precondition: a.mu must be write locked.\n+// +checklocks:a.mu\nfunc (a *AddressableEndpointState) addAndAcquireAddressLocked(addr tcpip.AddressWithPrefix, properties AddressProperties, permanent bool) (*addressState, tcpip.Error) {\n// attemptAddToPrimary is false when the address is already in the primary\n// address list.\nattemptAddToPrimary := true\n- addrState, ok := a.mu.endpoints[addr.Address]\n+ addrState, ok := a.endpoints[addr.Address]\nif ok {\nif !permanent {\n// We are adding a non-permanent address but the address exists. No need\n@@ -193,20 +193,21 @@ func (a *AddressableEndpointState) addAndAcquireAddressLocked(addr tcpip.Address\nreturn nil, &tcpip.ErrDuplicateAddress{}\n}\n- addrState.mu.Lock()\n- if addrState.mu.kind.IsPermanent() {\n- addrState.mu.Unlock()\n+ addrState.mu.RLock()\n+ if addrState.refs == 0 {\n+ panic(fmt.Sprintf(\"found an address that should have been released (ref count == 0); address = %s\", addrState.addr))\n+ }\n+ isPermanent := addrState.kind.IsPermanent()\n+ addrState.mu.RUnlock()\n+\n+ if isPermanent {\n// We are adding a permanent address but a permanent address already\n// exists.\nreturn nil, &tcpip.ErrDuplicateAddress{}\n}\n- if addrState.mu.refs == 0 {\n- panic(fmt.Sprintf(\"found an address that should have been released (ref count == 0); address = %s\", addrState.addr))\n- }\n-\n// We now promote the address.\n- for i, s := range a.mu.primary {\n+ for i, s := range a.primary {\nif s == addrState {\nswitch properties.PEB {\ncase CanBePrimaryEndpoint:\n@@ -217,19 +218,17 @@ func (a *AddressableEndpointState) addAndAcquireAddressLocked(addr tcpip.Address\n// The address is already first in the primary address list.\nattemptAddToPrimary = false\n} else {\n- a.mu.primary = append(a.mu.primary[:i], a.mu.primary[i+1:]...)\n+ a.primary = append(a.primary[:i], a.primary[i+1:]...)\n}\ncase NeverPrimaryEndpoint:\n- a.mu.primary = append(a.mu.primary[:i], a.mu.primary[i+1:]...)\n+ a.primary = append(a.primary[:i], a.primary[i+1:]...)\ndefault:\npanic(fmt.Sprintf(\"unrecognized primary endpoint behaviour = %d\", properties.PEB))\n}\nbreak\n}\n}\n- }\n-\n- if addrState == nil {\n+ } else {\naddrState = &addressState{\naddressableEndpointState: a,\naddr: addr,\n@@ -238,11 +237,10 @@ func (a *AddressableEndpointState) addAndAcquireAddressLocked(addr tcpip.Address\n// results in allocations on every call.\nsubnet: addr.Subnet(),\n}\n- a.mu.endpoints[addr.Address] = addrState\n- addrState.mu.Lock()\n+ a.endpoints[addr.Address] = addrState\n// We never promote an address to temporary - it can only be added as such.\n- // If we are actaully adding a permanent address, it is promoted below.\n- addrState.mu.kind = Temporary\n+ // If we are actually adding a permanent address, it is promoted below.\n+ addrState.kind = Temporary\n}\n// At this point we have an address we are either promoting from an expired or\n@@ -250,40 +248,41 @@ func (a *AddressableEndpointState) addAndAcquireAddressLocked(addr tcpip.Address\n// or we are adding a new temporary or permanent address.\n//\n// The address MUST be write locked at this point.\n- defer addrState.mu.Unlock() // +checklocksforce\n+ addrState.mu.Lock()\n+ defer addrState.mu.Unlock()\nif permanent {\n- if addrState.mu.kind.IsPermanent() {\n+ if addrState.kind.IsPermanent() {\npanic(fmt.Sprintf(\"only non-permanent addresses should be promoted to permanent; address = %s\", addrState.addr))\n}\n// Primary addresses are biased by 1.\n- addrState.mu.refs++\n- addrState.mu.kind = Permanent\n+ addrState.refs++\n+ addrState.kind = Permanent\n}\n// Acquire the address before returning it.\n- addrState.mu.refs++\n- addrState.mu.deprecated = properties.Deprecated\n- addrState.mu.configType = properties.ConfigType\n+ addrState.refs++\n+ addrState.deprecated = properties.Deprecated\n+ addrState.configType = properties.ConfigType\nif attemptAddToPrimary {\nswitch properties.PEB {\ncase NeverPrimaryEndpoint:\ncase CanBePrimaryEndpoint:\n- a.mu.primary = append(a.mu.primary, addrState)\n+ a.primary = append(a.primary, addrState)\ncase FirstPrimaryEndpoint:\n- if cap(a.mu.primary) == len(a.mu.primary) {\n- a.mu.primary = append([]*addressState{addrState}, a.mu.primary...)\n+ if cap(a.primary) == len(a.primary) {\n+ a.primary = append([]*addressState{addrState}, a.primary...)\n} else {\n// Shift all the endpoints by 1 to make room for the new address at the\n// front. We could have just created a new slice but this saves\n// allocations when the slice has capacity for the new address.\n- primaryCount := len(a.mu.primary)\n- a.mu.primary = append(a.mu.primary, nil)\n- if n := copy(a.mu.primary[1:], a.mu.primary); n != primaryCount {\n+ primaryCount := len(a.primary)\n+ a.primary = append(a.primary, nil)\n+ if n := copy(a.primary[1:], a.primary); n != primaryCount {\npanic(fmt.Sprintf(\"copied %d elements; expected = %d elements\", n, primaryCount))\n}\n- a.mu.primary[0] = addrState\n+ a.primary[0] = addrState\n}\ndefault:\npanic(fmt.Sprintf(\"unrecognized primary endpoint behaviour = %d\", properties.PEB))\n@@ -303,9 +302,9 @@ func (a *AddressableEndpointState) RemovePermanentAddress(addr tcpip.Address) tc\n// removePermanentAddressLocked is like RemovePermanentAddress but with locking\n// requirements.\n//\n-// Precondition: a.mu must be write locked.\n+// +checklocks:a.mu\nfunc (a *AddressableEndpointState) removePermanentAddressLocked(addr tcpip.Address) tcpip.Error {\n- addrState, ok := a.mu.endpoints[addr]\n+ addrState, ok := a.endpoints[addr]\nif !ok {\nreturn &tcpip.ErrBadLocalAddress{}\n}\n@@ -329,7 +328,7 @@ func (a *AddressableEndpointState) RemovePermanentEndpoint(ep AddressEndpoint) t\n// removePermanentAddressLocked is like RemovePermanentAddress but with locking\n// requirements.\n//\n-// Precondition: a.mu must be write locked.\n+// +checklocks:a.mu\nfunc (a *AddressableEndpointState) removePermanentEndpointLocked(addrState *addressState) tcpip.Error {\nif !addrState.GetKind().IsPermanent() {\nreturn &tcpip.ErrBadLocalAddress{}\n@@ -350,25 +349,25 @@ func (a *AddressableEndpointState) decAddressRef(addrState *addressState) {\n// decAddressRefLocked is like decAddressRef but with locking requirements.\n//\n-// Precondition: a.mu must be write locked.\n+// +checklocks:a.mu\nfunc (a *AddressableEndpointState) decAddressRefLocked(addrState *addressState) {\naddrState.mu.Lock()\ndefer addrState.mu.Unlock()\n- if addrState.mu.refs == 0 {\n+ if addrState.refs == 0 {\npanic(fmt.Sprintf(\"attempted to decrease ref count for AddressEndpoint w/ addr = %s when it is already released\", addrState.addr))\n}\n- addrState.mu.refs--\n+ addrState.refs--\n- if addrState.mu.refs != 0 {\n+ if addrState.refs != 0 {\nreturn\n}\n// A non-expired permanent address must not have its reference count dropped\n// to 0.\n- if addrState.mu.kind.IsPermanent() {\n- panic(fmt.Sprintf(\"permanent addresses should be removed through the AddressableEndpoint: addr = %s, kind = %d\", addrState.addr, addrState.mu.kind))\n+ if addrState.kind.IsPermanent() {\n+ panic(fmt.Sprintf(\"permanent addresses should be removed through the AddressableEndpoint: addr = %s, kind = %d\", addrState.addr, addrState.kind))\n}\na.releaseAddressStateLocked(addrState)\n@@ -376,10 +375,10 @@ func (a *AddressableEndpointState) decAddressRefLocked(addrState *addressState)\n// SetDeprecated implements stack.AddressableEndpoint.\nfunc (a *AddressableEndpointState) SetDeprecated(addr tcpip.Address, deprecated bool) tcpip.Error {\n- a.mu.Lock()\n- defer a.mu.Unlock()\n+ a.mu.RLock()\n+ defer a.mu.RUnlock()\n- addrState, ok := a.mu.endpoints[addr]\n+ addrState, ok := a.endpoints[addr]\nif !ok {\nreturn &tcpip.ErrBadLocalAddress{}\n}\n@@ -393,24 +392,36 @@ func (a *AddressableEndpointState) MainAddress() tcpip.AddressWithPrefix {\ndefer a.mu.RUnlock()\nep := a.acquirePrimaryAddressRLocked(func(ep *addressState) bool {\n- return ep.GetKind() == Permanent\n+ switch kind := ep.GetKind(); kind {\n+ case Permanent:\n+ return true\n+ case PermanentTentative, PermanentExpired, Temporary:\n+ return false\n+ default:\n+ panic(fmt.Sprintf(\"unknown address kind: %d\", kind))\n+ }\n})\nif ep == nil {\nreturn tcpip.AddressWithPrefix{}\n}\n-\naddr := ep.AddressWithPrefix()\n- a.decAddressRefLocked(ep)\n+ // Note that when ep must have a ref count >=2, because its ref count\n+ // must be >=1 in order to be found and the ref count was incremented\n+ // when a reference was acquired. The only way for the ref count to\n+ // drop below 2 is for the endpoint to be removed, which requires a\n+ // write lock; so we're guaranteed to be able to decrement the ref\n+ // count and not need to remove the endpoint from a.primary.\n+ ep.decRefMustNotFree()\nreturn addr\n}\n// acquirePrimaryAddressRLocked returns an acquired primary address that is\n// valid according to isValid.\n//\n-// Precondition: e.mu must be read locked\n+// +checklocksread:a.mu\nfunc (a *AddressableEndpointState) acquirePrimaryAddressRLocked(isValid func(*addressState) bool) *addressState {\nvar deprecatedEndpoint *addressState\n- for _, ep := range a.mu.primary {\n+ for _, ep := range a.primary {\nif !isValid(ep) {\ncontinue\n}\n@@ -422,8 +433,13 @@ func (a *AddressableEndpointState) acquirePrimaryAddressRLocked(isValid func(*ad\n// If we kept track of a deprecated endpoint, decrement its reference\n// count since it was incremented when we decided to keep track of it.\nif deprecatedEndpoint != nil {\n- a.decAddressRefLocked(deprecatedEndpoint)\n- deprecatedEndpoint = nil\n+ // Note that when deprecatedEndpoint was found, its ref count\n+ // must have necessarily been >=1, and after incrementing it\n+ // must be >=2. The only way for the ref count to drop below 2 is\n+ // for the endpoint to be removed, which requires a write lock;\n+ // so we're guaranteed to be able to decrement the ref count\n+ // and not need to remove the endpoint from a.primary.\n+ deprecatedEndpoint.decRefMustNotFree()\n}\nreturn ep\n@@ -455,7 +471,7 @@ func (a *AddressableEndpointState) acquirePrimaryAddressRLocked(isValid func(*ad\n// returned.\nfunc (a *AddressableEndpointState) AcquireAssignedAddressOrMatching(localAddr tcpip.Address, f func(AddressEndpoint) bool, allowTemp bool, tempPEB PrimaryEndpointBehavior) AddressEndpoint {\nlookup := func() *addressState {\n- if addrState, ok := a.mu.endpoints[localAddr]; ok {\n+ if addrState, ok := a.endpoints[localAddr]; ok {\nif !addrState.IsAssigned(allowTemp) {\nreturn nil\n}\n@@ -468,7 +484,7 @@ func (a *AddressableEndpointState) AcquireAssignedAddressOrMatching(localAddr tc\n}\nif f != nil {\n- for _, addrState := range a.mu.endpoints {\n+ for _, addrState := range a.endpoints {\nif addrState.IsAssigned(allowTemp) && f(addrState) && addrState.IncRef() {\nreturn addrState\n}\n@@ -538,8 +554,8 @@ func (a *AddressableEndpointState) AcquireAssignedAddress(localAddr tcpip.Addres\n// AcquireOutgoingPrimaryAddress implements AddressableEndpoint.\nfunc (a *AddressableEndpointState) AcquireOutgoingPrimaryAddress(remoteAddr tcpip.Address, allowExpired bool) AddressEndpoint {\n- a.mu.RLock()\n- defer a.mu.RUnlock()\n+ a.mu.Lock()\n+ defer a.mu.Unlock()\nep := a.acquirePrimaryAddressRLocked(func(ep *addressState) bool {\nreturn ep.IsAssigned(allowExpired)\n@@ -557,7 +573,7 @@ func (a *AddressableEndpointState) AcquireOutgoingPrimaryAddress(remoteAddr tcpi\n// an interface value will therefore be non-nil even when the pointer value V\n// inside is nil.\n//\n- // Since acquirePrimaryAddressRLocked returns a nil value with a non-nil type,\n+ // Since acquirePrimaryAddressLocked returns a nil value with a non-nil type,\n// we need to explicitly return nil below if ep is (a typed) nil.\nif ep == nil {\nreturn nil\n@@ -572,13 +588,16 @@ func (a *AddressableEndpointState) PrimaryAddresses() []tcpip.AddressWithPrefix\ndefer a.mu.RUnlock()\nvar addrs []tcpip.AddressWithPrefix\n- for _, ep := range a.mu.primary {\n+ for _, ep := range a.primary {\n+ switch kind := ep.GetKind(); kind {\n// Don't include tentative, expired or temporary endpoints\n// to avoid confusion and prevent the caller from using\n// those.\n- switch ep.GetKind() {\ncase PermanentTentative, PermanentExpired, Temporary:\ncontinue\n+ case Permanent:\n+ default:\n+ panic(fmt.Sprintf(\"address %s has unknown kind %d\", ep.AddressWithPrefix(), kind))\n}\naddrs = append(addrs, ep.AddressWithPrefix())\n@@ -593,7 +612,7 @@ func (a *AddressableEndpointState) PermanentAddresses() []tcpip.AddressWithPrefi\ndefer a.mu.RUnlock()\nvar addrs []tcpip.AddressWithPrefix\n- for _, ep := range a.mu.endpoints {\n+ for _, ep := range a.endpoints {\nif !ep.GetKind().IsPermanent() {\ncontinue\n}\n@@ -609,7 +628,7 @@ func (a *AddressableEndpointState) Cleanup() {\na.mu.Lock()\ndefer a.mu.Unlock()\n- for _, ep := range a.mu.endpoints {\n+ for _, ep := range a.endpoints {\n// removePermanentEndpointLocked returns *tcpip.ErrBadLocalAddress if ep is\n// not a permanent address.\nswitch err := a.removePermanentEndpointLocked(ep); err.(type) {\n@@ -628,19 +647,21 @@ type addressState struct {\naddr tcpip.AddressWithPrefix\nsubnet tcpip.Subnet\ntemporary bool\n+\n// Lock ordering (from outer to inner lock ordering):\n//\n// AddressableEndpointState.mu\n// addressState.mu\n- mu struct {\n- sync.RWMutex\n-\n+ mu sync.RWMutex\n+ // checklocks:mu\nrefs uint32\n+ // checklocks:mu\nkind AddressKind\n+ // checklocks:mu\nconfigType AddressConfigType\n+ // checklocks:mu\ndeprecated bool\n}\n-}\n// AddressWithPrefix implements AddressEndpoint.\nfunc (a *addressState) AddressWithPrefix() tcpip.AddressWithPrefix {\n@@ -656,14 +677,14 @@ func (a *addressState) Subnet() tcpip.Subnet {\nfunc (a *addressState) GetKind() AddressKind {\na.mu.RLock()\ndefer a.mu.RUnlock()\n- return a.mu.kind\n+ return a.kind\n}\n// SetKind implements AddressEndpoint.\nfunc (a *addressState) SetKind(kind AddressKind) {\na.mu.Lock()\ndefer a.mu.Unlock()\n- a.mu.kind = kind\n+ a.kind = kind\n}\n// IsAssigned implements AddressEndpoint.\n@@ -686,11 +707,11 @@ func (a *addressState) IsAssigned(allowExpired bool) bool {\nfunc (a *addressState) IncRef() bool {\na.mu.Lock()\ndefer a.mu.Unlock()\n- if a.mu.refs == 0 {\n+ if a.refs == 0 {\nreturn false\n}\n- a.mu.refs++\n+ a.refs++\nreturn true\n}\n@@ -699,27 +720,43 @@ func (a *addressState) DecRef() {\na.addressableEndpointState.decAddressRef(a)\n}\n+// decRefMustNotFree decreases the reference count with the guarantee that the\n+// reference count will be greater than 0 after the decrement.\n+//\n+// Panics if the ref count is less than 2 after acquiring the lock in this\n+// function.\n+func (a *addressState) decRefMustNotFree() {\n+ a.mu.Lock()\n+ defer a.mu.Unlock()\n+\n+ if a.refs < 2 {\n+ panic(fmt.Sprintf(\"cannot decrease addressState %s ref count %d without freeing the endpoint\", a.addr, a.refs))\n+ }\n+ a.refs--\n+}\n+\n// ConfigType implements AddressEndpoint.\nfunc (a *addressState) ConfigType() AddressConfigType {\na.mu.RLock()\ndefer a.mu.RUnlock()\n- return a.mu.configType\n+ return a.configType\n}\n// SetDeprecated implements AddressEndpoint.\nfunc (a *addressState) SetDeprecated(d bool) {\na.mu.Lock()\ndefer a.mu.Unlock()\n- a.mu.deprecated = d\n+ a.deprecated = d\n}\n// Deprecated implements AddressEndpoint.\nfunc (a *addressState) Deprecated() bool {\na.mu.RLock()\ndefer a.mu.RUnlock()\n- return a.mu.deprecated\n+ return a.deprecated\n}\n+// Temporary implements AddressEndpoint.\nfunc (a *addressState) Temporary() bool {\nreturn a.temporary\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add checklocks to addressable_endpoint_state.go
Added checklocks annotations to `addressable_endpoint_state.go`.
Refactored slightly to appease the analyzer.
PiperOrigin-RevId: 459651242 |
259,909 | 11.07.2022 08:54:28 | 25,200 | 3aa77e9f0a2f1e758a5926dad7e1a63938be36f4 | Enforce a minimum Send MSS.
Without this enforcement, options larger than the specified MSS can cause
MaxPayloadSize to go negative and cause all sorts of problems. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/tcp.go",
"new_path": "pkg/tcpip/header/tcp.go",
"diff": "@@ -222,6 +222,10 @@ const (\n// same as the value TCP_MIN_MSS defined net/tcp.h.\nTCPMinimumMSS = IPv4MaximumHeaderSize + TCPHeaderMaximumSize + MinIPFragmentPayloadSize - IPv4MinimumSize - TCPMinimumSize\n+ // TCPMinimumSendMSS is the minimum value for MSS in a sender. This is the\n+ // same as the value TCP_MIN_SND_MSS in net/tcp.h.\n+ TCPMinimumSendMSS = TCPOptionsMaximumSize + MinIPFragmentPayloadSize\n+\n// TCPMaximumMSS is the maximum acceptable value for MSS.\nTCPMaximumMSS = 0xffff\n@@ -458,6 +462,9 @@ func ParseSynOptions(opts []byte, isAck bool) TCPSynOptions {\nreturn synOpts\n}\nsynOpts.MSS = mss\n+ if mss < TCPMinimumSendMSS {\n+ synOpts.MSS = TCPMinimumSendMSS\n+ }\ni += 4\ncase TCPOptionWS:\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/snd.go",
"new_path": "pkg/tcpip/transport/tcp/snd.go",
"diff": "@@ -861,11 +861,6 @@ func (s *sender) maybeSendSegment(seg *segment, limit int, end seqnum.Value) (se\nif seg.payloadSize() > available {\n// A negative value causes splitSeg to panic anyways, so just panic\n// earlier to get more information about the cause.\n- // TOOD(b/236090764): Remove this panic once the cause of negative values\n- // of \"available\" is understood.\n- if available < 0 {\n- panic(fmt.Sprintf(\"got available=%d, want available>=0. limit %d, s.MaxPayloadSize %d, seg.payloadSize() %d, gso.MaxSize %d, gso.MSS %d\", available, limit, s.MaxPayloadSize, seg.payloadSize(), s.ep.gso.MaxSize, s.ep.gso.MSS))\n- }\ns.splitSeg(seg, available)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/test/e2e/tcp_test.go",
"new_path": "pkg/tcpip/transport/tcp/test/e2e/tcp_test.go",
"diff": "@@ -3573,6 +3573,28 @@ func TestSetTTL(t *testing.T) {\n}\n}\n+func TestSendMSSLessThanOptionsSize(t *testing.T) {\n+ const mss = 10\n+ const writeSize = 300\n+ c := context.New(t, 65535)\n+ defer c.Cleanup()\n+\n+ // The sizes of these options add up to 12.\n+ c.CreateConnectedWithRawOptions(context.TestInitialSequenceNumber, 30000, -1 /* epRcvBuf */, []byte{\n+ header.TCPOptionMSS, 4, byte(mss / 256), byte(mss % 256),\n+ header.TCPOptionTS, header.TCPOptionTSLength, 1, 2, 3, 4, 5, 6, 7, 8,\n+ header.TCPOptionSACKPermitted, header.TCPOptionSackPermittedLength,\n+ })\n+ e2e.CheckBrokenUpWrite(t, c, writeSize)\n+\n+ var r bytes.Reader\n+ r.Reset(make([]byte, writeSize))\n+ _, err := c.EP.Write(&r, tcpip.WriteOptions{})\n+ if err != nil {\n+ t.Fatalf(\"Write failed: %s\", err)\n+ }\n+}\n+\nfunc TestActiveSendMSSLessThanMTU(t *testing.T) {\nconst maxPayload = 100\nc := context.New(t, 65535)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enforce a minimum Send MSS.
Without this enforcement, options larger than the specified MSS can cause
MaxPayloadSize to go negative and cause all sorts of problems.
PiperOrigin-RevId: 460224034 |
259,909 | 11.07.2022 10:11:32 | 25,200 | d217b5c69fba5f213d1f19b894f1950c16e492d6 | Refine Buffer io methods to utilize pooled views. | [
{
"change_type": "MODIFY",
"old_path": "pkg/bufferv2/buffer.go",
"new_path": "pkg/bufferv2/buffer.go",
"diff": "@@ -452,124 +452,117 @@ func (b *Buffer) Merge(other *Buffer) {\nother.size = 0\n}\n-// WriteFromReader writes to the buffer from an io.Reader.\n-//\n-// A minimum read size equal to unsafe.Sizeof(unintptr) is enforced,\n-// provided that count is greater than or equal to unsafe.Sizeof(uintptr).\n+// WriteFromReader writes to the buffer from an io.Reader. A maximum read size\n+// of MaxChunkSize is enforced to prevent allocating views from the heap.\nfunc (b *Buffer) WriteFromReader(r io.Reader, count int64) (int64, error) {\n- var (\n- done int64\n- n int\n- err error\n- )\n+ var done int64\nfor done < count {\n- view := b.data.Back()\n-\n- // Ensure we have an empty buffer.\n- if view.Full() {\n- view = NewView(int(count - done))\n- b.data.PushBack(view)\n- }\n-\n- // Is this less than the minimum batch?\n- if view.AvailableSize() < minBatch && (count-done) >= int64(minBatch) {\n- tmp := NewView(minBatch)\n- n, err = r.Read(tmp.availableSlice())\n- tmp.Grow(n)\n- b.Append(tmp)\n- done += int64(n)\n- if err != nil {\n- break\n- }\n- continue\n- }\n-\n- // Limit the read, if necessary.\n- sz := view.AvailableSize()\n- if left := count - done; int64(sz) > left {\n- sz = int(left)\n- }\n-\n- // Pass the relevant portion of the buffer.\n- n, err = r.Read(view.availableSlice()[:sz])\n- view.Grow(n)\n- done += int64(n)\n- b.size += int64(n)\n+ vsize := count - done\n+ if vsize > MaxChunkSize {\n+ vsize = MaxChunkSize\n+ }\n+ v := NewView(int(vsize))\n+ lr := io.LimitedReader{R: r, N: vsize}\n+ n, err := io.Copy(v, &lr)\n+ b.Append(v)\n+ done += n\nif err == io.EOF {\n- err = nil // Short write allowed.\n- break\n- } else if err != nil {\nbreak\n}\n- }\n+ if err != nil {\nreturn done, err\n}\n+ }\n+ return done, nil\n+}\n// ReadToWriter reads from the buffer into an io.Writer.\n//\n// N.B. This does not consume the bytes read. TrimFront should\n// be called appropriately after this call in order to do so.\n-//\n-// A minimum write size equal to unsafe.Sizeof(unintptr) is enforced,\n-// provided that count is greater than or equal to unsafe.Sizeof(uintptr).\nfunc (b *Buffer) ReadToWriter(w io.Writer, count int64) (int64, error) {\n- var (\n- done int64\n- n int\n- err error\n- )\n- offset := 0 // Spill-over for batching.\n- for view := b.data.Front(); view != nil && done < count; view = view.Next() {\n- // Has this been consumed? Skip it.\n- sz := view.Size()\n- if sz <= offset {\n- offset -= sz\n- continue\n+ bytesLeft := int(count)\n+ for v := b.data.Front(); v != nil && bytesLeft > 0; v = v.Next() {\n+ view := v.Clone()\n+ if view.Size() > bytesLeft {\n+ view.CapLength(bytesLeft)\n+ }\n+ n, err := io.Copy(w, view)\n+ bytesLeft -= int(n)\n+ view.Release()\n+ if err != nil {\n+ return count - int64(bytesLeft), err\n+ }\n+ }\n+ return count - int64(bytesLeft), nil\n}\n- sz -= offset\n- // Is this less than the minimum batch?\n- left := count - done\n- if sz < minBatch && left >= int64(minBatch) && (b.size-done) >= int64(minBatch) {\n- tmp := NewView(minBatch)\n- n, err = b.ReadAt(tmp.availableSlice()[:minBatch], done)\n- tmp.Grow(n)\n- w.Write(tmp.AsSlice())\n- tmp.Release()\n- done += int64(n)\n- offset = n - sz // Reset below.\n- if err != nil {\n- break\n+// read implements the io.Reader interface. This method is used by BufferReader\n+// to consume its underlying buffer. To perform io operations on buffers\n+// directly, use ReadToWriter or WriteToReader.\n+func (b *Buffer) read(p []byte) (int, error) {\n+ if len(p) == 0 {\n+ return 0, nil\n}\n- continue\n+ if b.Size() == 0 {\n+ return 0, io.EOF\n+ }\n+ done := 0\n+ v := b.data.Front()\n+ for v != nil && done < len(p) {\n+ n, err := v.Read(p[done:])\n+ done += n\n+ next := v.Next()\n+ if v.Size() == 0 {\n+ b.removeView(v)\n+ }\n+ b.size -= int64(n)\n+ if err != nil && err != io.EOF {\n+ return done, err\n+ }\n+ v = next\n+ }\n+ return done, nil\n}\n- // Limit the write if necessary.\n- if int64(sz) >= left {\n- sz = int(left)\n+// readByte implements the io.ByteReader interface. This method is used by\n+// BufferReader to consume its underlying buffer. To perform io operations on\n+// buffers directly, use ReadToWriter or WriteToReader.\n+func (b *Buffer) readByte() (byte, error) {\n+ if b.Size() == 0 {\n+ return 0, io.EOF\n+ }\n+ v := b.data.Front()\n+ bt := v.AsSlice()[0]\n+ b.TrimFront(1)\n+ return bt, nil\n}\n- // Perform the actual write.\n- n, err = w.Write(view.AsSlice()[offset : offset+sz])\n- done += int64(n)\n- if err != nil {\n- break\n+// AsBufferReader returns the Buffer as a BufferReader capabable of io methods.\n+// The new BufferReader takes ownership of b.\n+func (b *Buffer) AsBufferReader() BufferReader {\n+ return BufferReader{b}\n}\n- // Reset spill-over.\n- offset = 0\n+// BufferReader implements io methods on Buffer. Users must call Close()\n+// when finished with the buffer to free the underlying memory.\n+type BufferReader struct {\n+ b *Buffer\n}\n- return done, err\n+\n+// Read implements the io.Reader interface.\n+func (br *BufferReader) Read(p []byte) (int, error) {\n+ return br.b.read(p)\n}\n-// AsSlices returns a list of each of Buffer's underlying Views as Slices.\n-// The slices returned should not be modifed.\n-func (b *Buffer) AsSlices() [][]byte {\n- slices := make([][]byte, 0, b.data.Len())\n- for v := b.data.Front(); v != nil; v = v.Next() {\n- slices = append(slices, v.AsSlice())\n+// ReadByte implements the io.ByteReader interface.\n+func (br *BufferReader) ReadByte() (byte, error) {\n+ return br.b.readByte()\n}\n- return slices\n+\n+// Close implements the io.Closer interface.\n+func (br *BufferReader) Close() {\n+ br.b.Release()\n}\n// Range specifies a range of buffer.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/bufferv2/buffer_test.go",
"new_path": "pkg/bufferv2/buffer_test.go",
"diff": "@@ -630,6 +630,73 @@ func TestBufferPullUp(t *testing.T) {\n}\n}\n+func TestReadFromLargeWriter(t *testing.T) {\n+ writeSize := int64(1 << 20)\n+ largeWriter := bytes.NewBuffer(make([]byte, writeSize))\n+ b := Buffer{}\n+ // Expect this write to be buffered into several MaxChunkSize sized views.\n+ n, err := b.WriteFromReader(largeWriter, writeSize)\n+ if err != nil {\n+ t.Fatalf(\"b.WriteFromReader() failed: want err=nil, got %v\", err)\n+ }\n+ if n != writeSize {\n+ t.Errorf(\"got b.WriteFromReader()=%d, want %d\", n, writeSize)\n+ }\n+ nChunks := int(writeSize / MaxChunkSize)\n+ if b.data.Len() != nChunks {\n+ t.Errorf(\"b.WriteFromReader() failed, got b.data.Len()=%d, want %d\", b.data.Len(), nChunks)\n+ }\n+}\n+\n+func TestRead(t *testing.T) {\n+ readStrings := []string{\"abcdef\", \"123456\", \"ghijkl\"}\n+ totalSize := len(readStrings) * len(readStrings[0])\n+ for readSz := 0; readSz < totalSize+1; readSz++ {\n+ b := Buffer{}\n+ for _, s := range readStrings {\n+ v := NewViewWithData([]byte(s))\n+ b.appendOwned(v)\n+ }\n+ orig := b.Clone()\n+ orig.Truncate(int64(readSz))\n+ p := make([]byte, readSz)\n+ _, err := b.read(p)\n+ if err != nil {\n+ t.Fatalf(\"Read([]byte(%d)) failed: %v\", readSz, err)\n+ }\n+ if !bytes.Equal(p, orig.Flatten()) {\n+ t.Errorf(\"Read([]byte(%d)) failed, want p=%v, got %v\", readSz, orig.Flatten(), p)\n+ }\n+ if int(b.Size()) != totalSize-readSz {\n+ t.Errorf(\"Read([]byte(%d)) failed, want b.Size()=%v, got %v\", readSz, totalSize-readSz, b.Size())\n+ }\n+ }\n+}\n+\n+func TestReadByte(t *testing.T) {\n+ readString := \"abcdef123456ghijkl\"\n+ b := Buffer{}\n+ nViews := 3\n+ for i := 0; i < nViews; i++ {\n+ vLen := len(readString) / nViews\n+ v := NewViewWithData([]byte(readString[i*vLen : (i+1)*vLen]))\n+ b.appendOwned(v)\n+ }\n+ for i := 0; i < len(readString); i++ {\n+ orig := readString[i]\n+ bt, err := b.readByte()\n+ if err != nil {\n+ t.Fatalf(\"readByte() failed: %v\", err)\n+ }\n+ if bt != orig {\n+ t.Errorf(\"readByte() failed, want %v, got %v\", orig, bt)\n+ }\n+ if int(b.Size()) != len(readString[i+1:]) {\n+ t.Errorf(\"readByte() failed, want b.Size()=%v, got %v\", len(readString[i+1:]), b.Size())\n+ }\n+ }\n+}\n+\nfunc TestPullUpModifiedViews(t *testing.T) {\nvar b Buffer\ndefer b.Release()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/bufferv2/chunk.go",
"new_path": "pkg/bufferv2/chunk.go",
"diff": "@@ -38,9 +38,9 @@ const (\n// payloads.\nbaseChunkSize = 1 << baseChunkSizeLog2 // 64\n- // The largest payload size that we pool. Payloads larger than this will\n- // allocated from the heap and garbage collected as normal.\n- maxChunkSize = baseChunkSize << (numPools - 1) // 65536\n+ // MaxChunkSize is largest payload size that we pool. Payloads larger than\n+ // this will be allocated from the heap and garbage collected as normal.\n+ MaxChunkSize = baseChunkSize << (numPools - 1) // 64k\n// The number of chunk pools we have for use.\nnumPools = 11\n@@ -84,7 +84,7 @@ type chunk struct {\nfunc newChunk(size int) *chunk {\nvar c *chunk\n- if !PoolingEnabled || size > maxChunkSize {\n+ if !PoolingEnabled || size > MaxChunkSize {\nc = &chunk{\ndata: make([]byte, size),\n}\n@@ -100,7 +100,7 @@ func newChunk(size int) *chunk {\n}\nfunc (c *chunk) destroy() {\n- if !PoolingEnabled || len(c.data) > maxChunkSize {\n+ if !PoolingEnabled || len(c.data) > MaxChunkSize {\nc.data = nil\nreturn\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/bufferv2/view.go",
"new_path": "pkg/bufferv2/view.go",
"diff": "@@ -241,6 +241,10 @@ func (v *View) ReadFrom(r io.Reader) (n int64, err error) {\nv.chunk = v.chunk.Clone()\n}\nfor {\n+ // Check for EOF to avoid an unnnecesary allocation.\n+ if _, e := r.Read(nil); e == io.EOF {\n+ return n, nil\n+ }\nif v.AvailableSize() == 0 {\nv.growCap(ReadSize)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/bufferv2/view_test.go",
"new_path": "pkg/bufferv2/view_test.go",
"diff": "@@ -23,7 +23,7 @@ import (\n)\nfunc TestNewView(t *testing.T) {\n- for sz := baseChunkSize; sz < maxChunkSize; sz <<= 1 {\n+ for sz := baseChunkSize; sz < MaxChunkSize; sz <<= 1 {\nv := NewView(sz - 1)\ndefer v.Release()\n@@ -53,7 +53,7 @@ func TestNewView(t *testing.T) {\n// Allocating from heap should produce a chunk with the exact size requested\n// instead of a chunk where the size is contingent on the pool it came from.\n- viewSize := maxChunkSize + 1\n+ viewSize := MaxChunkSize + 1\nv := NewView(viewSize)\ndefer v.Release()\nif v.Capacity() != viewSize {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/bufferv2/view_unsafe.go",
"new_path": "pkg/bufferv2/view_unsafe.go",
"diff": "@@ -19,12 +19,6 @@ import (\n\"unsafe\"\n)\n-// minBatch is the smallest Read or Write operation that the\n-// WriteFromReader and ReadToWriter functions will use.\n-//\n-// This is defined as the size of a native pointer.\n-const minBatch = int(unsafe.Sizeof(uintptr(0)))\n-\n// BasePtr returns a pointer to the view's chunk.\nfunc (v *View) BasePtr() *byte {\nhdr := (*reflect.SliceHeader)(unsafe.Pointer(&v.chunk.data))\n"
}
] | Go | Apache License 2.0 | google/gvisor | Refine Buffer io methods to utilize pooled views.
PiperOrigin-RevId: 460241285 |
259,977 | 12.07.2022 19:33:44 | 25,200 | 69219fa35e0b37cd70020dcb6607be26e15a2995 | Log unknown network protocol numbers | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/sniffer/sniffer.go",
"new_path": "pkg/tcpip/link/sniffer/sniffer.go",
"diff": "@@ -244,7 +244,7 @@ func logPacket(prefix string, dir direction, protocol tcpip.NetworkProtocolNumbe\n)\nreturn\ndefault:\n- log.Infof(\"%s%s unknown network protocol\", prefix, directionPrefix)\n+ log.Infof(\"%s%s unknown network protocol: %d\", prefix, directionPrefix, protocol)\nreturn\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Log unknown network protocol numbers
PiperOrigin-RevId: 460608202 |