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,853 | 28.06.2019 13:22:28 | 25,200 | e21d49c2d82b7d109bc7c8955edea1787de59ac0 | platform/ptrace: return more detailed errors
Right now, if we can't create a stub process, we will see this error:
panic: unable to activate mm: resource temporarily unavailable
It would be better to know the root cause of this "resource temporarily
unavailable". | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/subprocess_linux.go",
"new_path": "pkg/sentry/platform/ptrace/subprocess_linux.go",
"diff": "@@ -306,7 +306,7 @@ func (s *subprocess) createStub() (*thread, error) {\narch.SyscallArgument{Value: 0},\narch.SyscallArgument{Value: 0})\nif err != nil {\n- return nil, err\n+ return nil, fmt.Errorf(\"creating stub process: %v\", err)\n}\n// Wait for child to enter group-stop, so we don't stop its\n@@ -325,7 +325,7 @@ func (s *subprocess) createStub() (*thread, error) {\narch.SyscallArgument{Value: 0},\narch.SyscallArgument{Value: 0})\nif err != nil {\n- return nil, err\n+ return nil, fmt.Errorf(\"waiting on stub process: %v\", err)\n}\nchildT := &thread{\n"
}
] | Go | Apache License 2.0 | google/gvisor | platform/ptrace: return more detailed errors
Right now, if we can't create a stub process, we will see this error:
panic: unable to activate mm: resource temporarily unavailable
It would be better to know the root cause of this "resource temporarily
unavailable".
PiperOrigin-RevId: 255656831 |
259,907 | 28.06.2019 16:17:19 | 25,200 | c4da599e22e1490dc2a108cbf85ba19af2f5e2df | ext4: disklayout: SuperBlock interface implementations. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext4/disklayout/BUILD",
"new_path": "pkg/sentry/fs/ext4/disklayout/BUILD",
"diff": "@@ -9,14 +9,21 @@ go_library(\n\"block_group_32.go\",\n\"block_group_64.go\",\n\"superblock.go\",\n+ \"superblock_32.go\",\n+ \"superblock_64.go\",\n+ \"superblock_old.go\",\n+ \"test_utils.go\",\n],\nimportpath = \"gvisor.dev/gvisor/pkg/sentry/fs/ext4/disklayout\",\n+ deps = [\"//pkg/binary\"],\n)\ngo_test(\nname = \"disklayout_test\",\nsize = \"small\",\n- srcs = [\"block_group_test.go\"],\n+ srcs = [\n+ \"block_group_test.go\",\n+ \"superblock_test.go\",\n+ ],\nembed = [\":disklayout\"],\n- deps = [\"//pkg/binary\"],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext4/disklayout/block_group_test.go",
"new_path": "pkg/sentry/fs/ext4/disklayout/block_group_test.go",
"diff": "@@ -16,19 +16,11 @@ package disklayout\nimport (\n\"testing\"\n-\n- \"gvisor.dev/gvisor/pkg/binary\"\n)\n-// TestBlockGroupSize tests the fact that the block group struct for\n-// 32-bit ext filesystems should be exactly 32 bytes big and for 64-bit fs it\n-// should be 64 bytes.\n+// TestBlockGroupSize tests that the block group descriptor structs are of the\n+// correct size.\nfunc TestBlockGroupSize(t *testing.T) {\n- if got, want := int(binary.Size(BlockGroup32Bit{})), 32; got != want {\n- t.Errorf(\"BlockGroup32Bit should be exactly 32 bytes but is %d bytes\", got)\n- }\n-\n- if got, want := int(binary.Size(BlockGroup64Bit{})), 64; got != want {\n- t.Errorf(\"BlockGroup64Bit should be exactly 64 bytes but is %d bytes\", got)\n- }\n+ assertSize(t, BlockGroup32Bit{}, 32)\n+ assertSize(t, BlockGroup64Bit{}, 64)\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext4/disklayout/superblock_32.go",
"diff": "+// Copyright 2019 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 disklayout\n+\n+// SuperBlock32Bit implements SuperBlock and represents the 32-bit version of\n+// the ext4_super_block struct in fs/ext4/ext4.h.\n+//\n+// The suffix `Raw` has been added to indicate that the field does not have a\n+// counterpart in the 64-bit version and to resolve name collision with the\n+// interface.\n+type SuperBlock32Bit struct {\n+ // We embed the old superblock struct here because the 32-bit version is just\n+ // an extension of the old version.\n+ SuperBlockOld\n+\n+ FirstInode uint32\n+ InodeSizeRaw uint16\n+ BlockGroupNumber uint16\n+ FeatureCompat uint32\n+ FeatureIncompat uint32\n+ FeatureRoCompat uint32\n+ UUID [16]byte\n+ VolumeName [16]byte\n+ LastMounted [64]byte\n+ AlgoUsageBitmap uint32\n+ PreallocBlocks uint8\n+ PreallocDirBlocks uint8\n+ ReservedGdtBlocks uint16\n+ JournalUUID [16]byte\n+ JournalInum uint32\n+ JournalDev uint32\n+ LastOrphan uint32\n+ HashSeed [4]uint32\n+ DefaultHashVersion uint8\n+ JnlBackupType uint8\n+ BgDescSizeRaw uint16\n+ DefaultMountOpts uint32\n+ FirstMetaBg uint32\n+ MkfsTime uint32\n+ JnlBlocks [17]uint32\n+}\n+\n+// Only override methods which change based on the additional fields above.\n+// Not overriding SuperBlock.BgDescSize because it would still return 32 here.\n+\n+// InodeSize implements SuperBlock.InodeSize.\n+func (sb *SuperBlock32Bit) InodeSize() uint16 {\n+ return sb.InodeSizeRaw\n+}\n+\n+// CompatibleFeatures implements SuperBlock.CompatibleFeatures.\n+func (sb *SuperBlock32Bit) CompatibleFeatures() CompatFeatures {\n+ return CompatFeaturesFromInt(sb.FeatureCompat)\n+}\n+\n+// IncompatibleFeatures implements SuperBlock.IncompatibleFeatures.\n+func (sb *SuperBlock32Bit) IncompatibleFeatures() IncompatFeatures {\n+ return IncompatFeaturesFromInt(sb.FeatureIncompat)\n+}\n+\n+// ReadOnlyCompatibleFeatures implements SuperBlock.ReadOnlyCompatibleFeatures.\n+func (sb *SuperBlock32Bit) ReadOnlyCompatibleFeatures() RoCompatFeatures {\n+ return RoCompatFeaturesFromInt(sb.FeatureRoCompat)\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext4/disklayout/superblock_64.go",
"diff": "+// Copyright 2019 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 disklayout\n+\n+// SuperBlock64Bit implements SuperBlock and represents the 64-bit version of\n+// the ext4_super_block struct in fs/ext4/ext4.h. This sums up to be exactly\n+// 1024 bytes (smallest possible block size) and hence the superblock always\n+// fits in no more than one data block.\n+//\n+// The suffix `Hi` here stands for upper bits because they represent the upper\n+// half of the fields.\n+type SuperBlock64Bit struct {\n+ // We embed the 32-bit struct here because 64-bit version is just an extension\n+ // of the 32-bit version.\n+ SuperBlock32Bit\n+\n+ BlocksCountHi uint32\n+ ReservedBlocksCountHi uint32\n+ FreeBlocksCountHi uint32\n+ MinInodeSize uint16\n+ WantInodeSize uint16\n+ Flags uint32\n+ RaidStride uint16\n+ MmpInterval uint16\n+ MmpBlock uint64\n+ RaidStripeWidth uint32\n+ LogGroupsPerFlex uint8\n+ ChecksumType uint8\n+ _ uint16\n+ KbytesWritten uint64\n+ SnapshotInum uint32\n+ SnapshotID uint32\n+ SnapshotRsrvBlocksCount uint64\n+ SnapshotList uint32\n+ ErrorCount uint32\n+ FirstErrorTime uint32\n+ FirstErrorInode uint32\n+ FirstErrorBlock uint64\n+ FirstErrorFunction [32]byte\n+ FirstErrorLine uint32\n+ LastErrorTime uint32\n+ LastErrorInode uint32\n+ LastErrorLine uint32\n+ LastErrorBlock uint64\n+ LastErrorFunction [32]byte\n+ MountOpts [64]byte\n+ UserQuotaInum uint32\n+ GroupQuotaInum uint32\n+ OverheadBlocks uint32\n+ BackupBgs [2]uint32\n+ EncryptAlgos [4]uint8\n+ EncryptPwSalt [16]uint8\n+ LostFoundInode uint32\n+ ProjectQuotaInode uint32\n+ ChecksumSeed uint32\n+ WtimeHi uint8\n+ MtimeHi uint8\n+ MkfsTimeHi uint8\n+ LastCheckHi uint8\n+ FirstErrorTimeHi uint8\n+ LastErrorTimeHi uint8\n+ _ [2]uint8\n+ Encoding uint16\n+ EncodingFlags uint16\n+ _ [95]uint32\n+ Checksum uint32\n+}\n+\n+// Only override methods which change based on the 64-bit feature.\n+\n+// BlocksCount implements SuperBlock.BlocksCount.\n+func (sb *SuperBlock64Bit) BlocksCount() uint64 {\n+ return (uint64(sb.BlocksCountHi) << 32) | uint64(sb.BlocksCountLo)\n+}\n+\n+// FreeBlocksCount implements SuperBlock.FreeBlocksCount.\n+func (sb *SuperBlock64Bit) FreeBlocksCount() uint64 {\n+ return (uint64(sb.FreeBlocksCountHi) << 32) | uint64(sb.FreeBlocksCountLo)\n+}\n+\n+// BgDescSize implements SuperBlock.BgDescSize.\n+func (sb *SuperBlock64Bit) BgDescSize() uint16 { return sb.BgDescSizeRaw }\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext4/disklayout/superblock_old.go",
"diff": "+// Copyright 2019 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 disklayout\n+\n+// SuperBlockOld implements SuperBlock and represents the old version of the\n+// superblock struct in ext2 and ext3 systems.\n+//\n+// The suffix `Lo` here stands for lower bits because this is also used in the\n+// 64-bit version where these fields represent the lower half of the fields.\n+// The suffix `Raw` has been added to indicate that the field does not have a\n+// counterpart in the 64-bit version and to resolve name collision with the\n+// interface.\n+type SuperBlockOld struct {\n+ InodesCountRaw uint32\n+ BlocksCountLo uint32\n+ ReservedBlocksCount uint32\n+ FreeBlocksCountLo uint32\n+ FreeInodesCountRaw uint32\n+ FirstDataBlockRaw uint32\n+ LogBlockSize uint32\n+ LogClusterSize uint32\n+ BlocksPerGroupRaw uint32\n+ ClustersPerGroupRaw uint32\n+ InodesPerGroupRaw uint32\n+ Mtime uint32\n+ Wtime uint32\n+ MountCountRaw uint16\n+ MaxMountCountRaw uint16\n+ MagicRaw uint16\n+ State uint16\n+ Errors uint16\n+ MinorRevLevel uint16\n+ LastCheck uint32\n+ CheckInterval uint32\n+ CreatorOS uint32\n+ RevLevel uint32\n+ DefResUID uint16\n+ DefResGID uint16\n+}\n+\n+// InodesCount implements SuperBlock.InodesCount.\n+func (sb *SuperBlockOld) InodesCount() uint32 { return sb.InodesCountRaw }\n+\n+// BlocksCount implements SuperBlock.BlocksCount.\n+func (sb *SuperBlockOld) BlocksCount() uint64 { return uint64(sb.BlocksCountLo) }\n+\n+// FreeBlocksCount implements SuperBlock.FreeBlocksCount.\n+func (sb *SuperBlockOld) FreeBlocksCount() uint64 { return uint64(sb.FreeBlocksCountLo) }\n+\n+// FreeInodesCount implements SuperBlock.FreeInodesCount.\n+func (sb *SuperBlockOld) FreeInodesCount() uint32 { return sb.FreeInodesCountRaw }\n+\n+// MountCount implements SuperBlock.MountCount.\n+func (sb *SuperBlockOld) MountCount() uint16 { return sb.MountCountRaw }\n+\n+// MaxMountCount implements SuperBlock.MaxMountCount.\n+func (sb *SuperBlockOld) MaxMountCount() uint16 { return sb.MaxMountCountRaw }\n+\n+// FirstDataBlock implements SuperBlock.FirstDataBlock.\n+func (sb *SuperBlockOld) FirstDataBlock() uint32 { return sb.FirstDataBlockRaw }\n+\n+// BlockSize implements SuperBlock.BlockSize.\n+func (sb *SuperBlockOld) BlockSize() uint64 { return 1 << (10 + sb.LogBlockSize) }\n+\n+// BlocksPerGroup implements SuperBlock.BlocksPerGroup.\n+func (sb *SuperBlockOld) BlocksPerGroup() uint32 { return sb.BlocksPerGroupRaw }\n+\n+// ClusterSize implements SuperBlock.ClusterSize.\n+func (sb *SuperBlockOld) ClusterSize() uint64 { return 1 << (10 + sb.LogClusterSize) }\n+\n+// ClustersPerGroup implements SuperBlock.ClustersPerGroup.\n+func (sb *SuperBlockOld) ClustersPerGroup() uint32 { return sb.ClustersPerGroupRaw }\n+\n+// InodeSize implements SuperBlock.InodeSize.\n+func (sb *SuperBlockOld) InodeSize() uint16 { return 128 }\n+\n+// InodesPerGroup implements SuperBlock.InodesPerGroup.\n+func (sb *SuperBlockOld) InodesPerGroup() uint32 { return sb.InodesPerGroupRaw }\n+\n+// BgDescSize implements SuperBlock.BgDescSize.\n+func (sb *SuperBlockOld) BgDescSize() uint16 { return 32 }\n+\n+// CompatibleFeatures implements SuperBlock.CompatibleFeatures.\n+func (sb *SuperBlockOld) CompatibleFeatures() CompatFeatures { return CompatFeatures{} }\n+\n+// IncompatibleFeatures implements SuperBlock.IncompatibleFeatures.\n+func (sb *SuperBlockOld) IncompatibleFeatures() IncompatFeatures { return IncompatFeatures{} }\n+\n+// ReadOnlyCompatibleFeatures implements SuperBlock.ReadOnlyCompatibleFeatures.\n+func (sb *SuperBlockOld) ReadOnlyCompatibleFeatures() RoCompatFeatures { return RoCompatFeatures{} }\n+\n+// Magic implements SuperBlock.Magic.\n+func (sb *SuperBlockOld) Magic() uint16 { return sb.MagicRaw }\n+\n+// Revision implements SuperBlock.Revision.\n+func (sb *SuperBlockOld) Revision() SbRevision { return SbRevision(sb.RevLevel) }\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext4/disklayout/superblock_test.go",
"diff": "+// Copyright 2019 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 disklayout\n+\n+import (\n+ \"testing\"\n+)\n+\n+// TestSuperBlockSize tests that the superblock structs are of the correct\n+// size.\n+func TestSuperBlockSize(t *testing.T) {\n+ assertSize(t, SuperBlockOld{}, 84)\n+ assertSize(t, SuperBlock32Bit{}, 336)\n+ assertSize(t, SuperBlock64Bit{}, 1024)\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext4/disklayout/test_utils.go",
"diff": "+// Copyright 2019 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 disklayout\n+\n+import (\n+ \"reflect\"\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/binary\"\n+)\n+\n+func assertSize(t *testing.T, v interface{}, want uintptr) {\n+ t.Helper()\n+\n+ if got := binary.Size(v); got != want {\n+ t.Errorf(\"struct %s should be exactly %d bytes but is %d bytes\", reflect.TypeOf(v).Name(), want, got)\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | ext4: disklayout: SuperBlock interface implementations.
PiperOrigin-RevId: 255687771 |
259,858 | 28.06.2019 20:34:03 | 25,200 | 6d204f6a3474f411dc39b59886973e3518cf1cec | Drop local_server support. | [
{
"change_type": "DELETE",
"old_path": "pkg/p9/local_server/BUILD",
"new_path": null,
"diff": "-load(\"@io_bazel_rules_go//go:def.bzl\", \"go_binary\")\n-\n-package(licenses = [\"notice\"])\n-\n-go_binary(\n- name = \"local_server\",\n- srcs = [\"local_server.go\"],\n- deps = [\n- \"//pkg/fd\",\n- \"//pkg/log\",\n- \"//pkg/p9\",\n- \"//pkg/unet\",\n- ],\n-)\n"
},
{
"change_type": "DELETE",
"old_path": "pkg/p9/local_server/local_server.go",
"new_path": null,
"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-// Binary local_server provides a local 9P2000.L server for the p9 package.\n-//\n-// To use, first start the server:\n-// local_server /tmp/my_bind_addr\n-//\n-// Then, connect using the Linux 9P filesystem:\n-// mount -t 9p -o trans=unix /tmp/my_bind_addr /mnt\n-//\n-// This package also serves as an examplar.\n-package main\n-\n-import (\n- \"os\"\n- \"path\"\n- \"syscall\"\n-\n- \"gvisor.dev/gvisor/pkg/fd\"\n- \"gvisor.dev/gvisor/pkg/log\"\n- \"gvisor.dev/gvisor/pkg/p9\"\n- \"gvisor.dev/gvisor/pkg/unet\"\n-)\n-\n-// local wraps a local file.\n-type local struct {\n- p9.DefaultWalkGetAttr\n-\n- path string\n- file *os.File\n-}\n-\n-// info constructs a QID for this file.\n-func (l *local) info() (p9.QID, os.FileInfo, error) {\n- var (\n- qid p9.QID\n- fi os.FileInfo\n- err error\n- )\n-\n- // Stat the file.\n- if l.file != nil {\n- fi, err = l.file.Stat()\n- } else {\n- fi, err = os.Lstat(l.path)\n- }\n- if err != nil {\n- log.Warningf(\"error stating %#v: %v\", l, err)\n- return qid, nil, err\n- }\n-\n- // Construct the QID type.\n- qid.Type = p9.ModeFromOS(fi.Mode()).QIDType()\n-\n- // Save the path from the Ino.\n- qid.Path = fi.Sys().(*syscall.Stat_t).Ino\n- return qid, fi, nil\n-}\n-\n-// Attach implements p9.Attacher.Attach.\n-func (l *local) Attach() (p9.File, error) {\n- return &local{path: \"/\"}, nil\n-}\n-\n-// Walk implements p9.File.Walk.\n-func (l *local) Walk(names []string) ([]p9.QID, p9.File, error) {\n- var qids []p9.QID\n- last := &local{path: l.path}\n- for _, name := range names {\n- c := &local{path: path.Join(last.path, name)}\n- qid, _, err := c.info()\n- if err != nil {\n- return nil, nil, err\n- }\n- qids = append(qids, qid)\n- last = c\n- }\n- return qids, last, nil\n-}\n-\n-// StatFS implements p9.File.StatFS.\n-//\n-// Not implemented.\n-func (l *local) StatFS() (p9.FSStat, error) {\n- return p9.FSStat{}, syscall.ENOSYS\n-}\n-\n-// FSync implements p9.File.FSync.\n-func (l *local) FSync() error {\n- return l.file.Sync()\n-}\n-\n-// GetAttr implements p9.File.GetAttr.\n-//\n-// Not fully implemented.\n-func (l *local) GetAttr(req p9.AttrMask) (p9.QID, p9.AttrMask, p9.Attr, error) {\n- qid, fi, err := l.info()\n- if err != nil {\n- return qid, p9.AttrMask{}, p9.Attr{}, err\n- }\n-\n- stat := fi.Sys().(*syscall.Stat_t)\n- attr := p9.Attr{\n- Mode: p9.FileMode(stat.Mode),\n- UID: p9.UID(stat.Uid),\n- GID: p9.GID(stat.Gid),\n- NLink: stat.Nlink,\n- RDev: stat.Rdev,\n- Size: uint64(stat.Size),\n- BlockSize: uint64(stat.Blksize),\n- Blocks: uint64(stat.Blocks),\n- ATimeSeconds: uint64(stat.Atim.Sec),\n- ATimeNanoSeconds: uint64(stat.Atim.Nsec),\n- MTimeSeconds: uint64(stat.Mtim.Sec),\n- MTimeNanoSeconds: uint64(stat.Mtim.Nsec),\n- CTimeSeconds: uint64(stat.Ctim.Sec),\n- CTimeNanoSeconds: uint64(stat.Ctim.Nsec),\n- }\n- valid := p9.AttrMask{\n- Mode: true,\n- UID: true,\n- GID: true,\n- NLink: true,\n- RDev: true,\n- Size: true,\n- Blocks: true,\n- ATime: true,\n- MTime: true,\n- CTime: true,\n- }\n-\n- return qid, valid, attr, nil\n-}\n-\n-// SetAttr implements p9.File.SetAttr.\n-//\n-// Not implemented.\n-func (l *local) SetAttr(valid p9.SetAttrMask, attr p9.SetAttr) error {\n- return syscall.ENOSYS\n-}\n-\n-// Remove implements p9.File.Remove.\n-//\n-// Not implemented.\n-func (l *local) Remove() error {\n- return syscall.ENOSYS\n-}\n-\n-// Rename implements p9.File.Rename.\n-//\n-// Not implemented.\n-func (l *local) Rename(directory p9.File, name string) error {\n- return syscall.ENOSYS\n-}\n-\n-// Close implements p9.File.Close.\n-func (l *local) Close() error {\n- if l.file != nil {\n- return l.file.Close()\n- }\n- return nil\n-}\n-\n-// Open implements p9.File.Open.\n-func (l *local) Open(mode p9.OpenFlags) (*fd.FD, p9.QID, uint32, error) {\n- qid, _, err := l.info()\n- if err != nil {\n- return nil, qid, 0, err\n- }\n-\n- // Do the actual open.\n- f, err := os.OpenFile(l.path, int(mode), 0)\n- if err != nil {\n- return nil, qid, 0, err\n- }\n- l.file = f\n-\n- // Note: we don't send the local file for this server.\n- return nil, qid, 4096, nil\n-}\n-\n-// Read implements p9.File.Read.\n-func (l *local) ReadAt(p []byte, offset uint64) (int, error) {\n- return l.file.ReadAt(p, int64(offset))\n-}\n-\n-// Write implements p9.File.Write.\n-func (l *local) WriteAt(p []byte, offset uint64) (int, error) {\n- return l.file.WriteAt(p, int64(offset))\n-}\n-\n-// Create implements p9.File.Create.\n-func (l *local) Create(name string, mode p9.OpenFlags, permissions p9.FileMode, _ p9.UID, _ p9.GID) (*fd.FD, p9.File, p9.QID, uint32, error) {\n- f, err := os.OpenFile(l.path, int(mode)|syscall.O_CREAT|syscall.O_EXCL, os.FileMode(permissions))\n- if err != nil {\n- return nil, nil, p9.QID{}, 0, err\n- }\n-\n- l2 := &local{path: path.Join(l.path, name), file: f}\n- qid, _, err := l2.info()\n- if err != nil {\n- l2.Close()\n- return nil, nil, p9.QID{}, 0, err\n- }\n-\n- return nil, l2, qid, 4096, nil\n-}\n-\n-// Mkdir implements p9.File.Mkdir.\n-//\n-// Not properly implemented.\n-func (l *local) Mkdir(name string, permissions p9.FileMode, _ p9.UID, _ p9.GID) (p9.QID, error) {\n- if err := os.Mkdir(path.Join(l.path, name), os.FileMode(permissions)); err != nil {\n- return p9.QID{}, err\n- }\n-\n- // Blank QID.\n- return p9.QID{}, nil\n-}\n-\n-// Symlink implements p9.File.Symlink.\n-//\n-// Not properly implemented.\n-func (l *local) Symlink(oldname string, newname string, _ p9.UID, _ p9.GID) (p9.QID, error) {\n- if err := os.Symlink(oldname, path.Join(l.path, newname)); err != nil {\n- return p9.QID{}, err\n- }\n-\n- // Blank QID.\n- return p9.QID{}, nil\n-}\n-\n-// Link implements p9.File.Link.\n-//\n-// Not properly implemented.\n-func (l *local) Link(target p9.File, newname string) error {\n- return os.Link(target.(*local).path, path.Join(l.path, newname))\n-}\n-\n-// Mknod implements p9.File.Mknod.\n-//\n-// Not implemented.\n-func (l *local) Mknod(name string, mode p9.FileMode, major uint32, minor uint32, _ p9.UID, _ p9.GID) (p9.QID, error) {\n- return p9.QID{}, syscall.ENOSYS\n-}\n-\n-// RenameAt implements p9.File.RenameAt.\n-//\n-// Not implemented.\n-func (l *local) RenameAt(oldname string, newdir p9.File, newname string) error {\n- return syscall.ENOSYS\n-}\n-\n-// UnlinkAt implements p9.File.UnlinkAt.\n-//\n-// Not implemented.\n-func (l *local) UnlinkAt(name string, flags uint32) error {\n- return syscall.ENOSYS\n-}\n-\n-// Readdir implements p9.File.Readdir.\n-func (l *local) Readdir(offset uint64, count uint32) ([]p9.Dirent, error) {\n- // We only do *all* dirents in single shot.\n- const maxDirentBuffer = 1024 * 1024\n- buf := make([]byte, maxDirentBuffer)\n- n, err := syscall.ReadDirent(int(l.file.Fd()), buf)\n- if err != nil {\n- // Return zero entries.\n- return nil, nil\n- }\n-\n- // Parse the entries; note that we read up to offset+count here.\n- _, newCount, newNames := syscall.ParseDirent(buf[:n], int(offset)+int(count), nil)\n- var dirents []p9.Dirent\n- for i := int(offset); i >= 0 && i < newCount; i++ {\n- entry := local{path: path.Join(l.path, newNames[i])}\n- qid, _, err := entry.info()\n- if err != nil {\n- continue\n- }\n- dirents = append(dirents, p9.Dirent{\n- QID: qid,\n- Type: qid.Type,\n- Name: newNames[i],\n- Offset: uint64(i + 1),\n- })\n- }\n-\n- return dirents, nil\n-}\n-\n-// Readlink implements p9.File.Readlink.\n-//\n-// Not properly implemented.\n-func (l *local) Readlink() (string, error) {\n- return os.Readlink(l.path)\n-}\n-\n-// Flush implements p9.File.Flush.\n-func (l *local) Flush() error {\n- return nil\n-}\n-\n-// Connect implements p9.File.Connect.\n-func (l *local) Connect(p9.ConnectFlags) (*fd.FD, error) {\n- return nil, syscall.ECONNREFUSED\n-}\n-\n-// Renamed implements p9.File.Renamed.\n-func (l *local) Renamed(parent p9.File, newName string) {\n- l.path = path.Join(parent.(*local).path, newName)\n-}\n-\n-// Allocate implements p9.File.Allocate.\n-func (l *local) Allocate(mode p9.AllocateMode, offset, length uint64) error {\n- return syscall.Fallocate(int(l.file.Fd()), mode.ToLinux(), int64(offset), int64(length))\n-}\n-\n-func main() {\n- log.SetLevel(log.Debug)\n-\n- if len(os.Args) != 2 {\n- log.Warningf(\"usage: %s <bind-addr>\", os.Args[0])\n- os.Exit(1)\n- }\n-\n- // Bind and listen on the socket.\n- serverSocket, err := unet.BindAndListen(os.Args[1], false)\n- if err != nil {\n- log.Warningf(\"err binding: %v\", err)\n- os.Exit(1)\n- }\n-\n- // Run the server.\n- s := p9.NewServer(&local{})\n- s.Serve(serverSocket)\n-}\n-\n-var (\n- _ p9.File = &local{}\n-)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Drop local_server support.
PiperOrigin-RevId: 255713414 |
259,854 | 29.06.2019 09:22:09 | 25,200 | 3446f4e29bd547e5576caf16d8c2bb45560439e9 | Add stack trace printing to reference leak checking. | [
{
"change_type": "MODIFY",
"old_path": "pkg/refs/refcounter.go",
"new_path": "pkg/refs/refcounter.go",
"diff": "package refs\nimport (\n+ \"bytes\"\n+ \"fmt\"\n\"reflect\"\n\"runtime\"\n\"sync\"\n@@ -197,6 +199,11 @@ type AtomicRefCount struct {\n// name is immutable after EnableLeakCheck is called.\nname string\n+ // stack optionally records the caller of EnableLeakCheck.\n+ //\n+ // stack is immutable after EnableLeakCheck is called.\n+ stack []uintptr\n+\n// mu protects the list below.\nmu sync.Mutex `state:\"nosave\"`\n@@ -218,6 +225,10 @@ const (\n// LeaksLogWarning indicates that a warning should be logged when leaks\n// are found.\nLeaksLogWarning\n+\n+ // LeaksLogTraces indicates that a trace collected during allocation\n+ // should be logged when leaks are found.\n+ LeaksLogTraces\n)\n// leakMode stores the current mode for the reference leak checker.\n@@ -232,6 +243,76 @@ func SetLeakMode(mode LeakMode) {\natomic.StoreUint32(&leakMode, uint32(mode))\n}\n+const maxStackFrames = 40\n+\n+type fileLine struct {\n+ file string\n+ line int\n+}\n+\n+// A stackKey is a representation of a stack frame for use as a map key.\n+//\n+// The fileLine type is used as PC values seem to vary across collections, even\n+// for the same call stack.\n+type stackKey [maxStackFrames]fileLine\n+\n+var stackCache = struct {\n+ sync.Mutex\n+ entries map[stackKey][]uintptr\n+}{entries: map[stackKey][]uintptr{}}\n+\n+func makeStackKey(pcs []uintptr) stackKey {\n+ frames := runtime.CallersFrames(pcs)\n+ var key stackKey\n+ keySlice := key[:0]\n+ for {\n+ frame, more := frames.Next()\n+ keySlice = append(keySlice, fileLine{frame.File, frame.Line})\n+\n+ if !more || len(keySlice) == len(key) {\n+ break\n+ }\n+ }\n+ return key\n+}\n+\n+func recordStack() []uintptr {\n+ pcs := make([]uintptr, maxStackFrames)\n+ n := runtime.Callers(1, pcs)\n+ if n == 0 {\n+ // No pcs available. Stop now.\n+ //\n+ // This can happen if the first argument to runtime.Callers\n+ // is large.\n+ return nil\n+ }\n+ pcs = pcs[:n]\n+ key := makeStackKey(pcs)\n+ stackCache.Lock()\n+ v, ok := stackCache.entries[key]\n+ if !ok {\n+ // Reallocate to prevent pcs from escaping.\n+ v = append([]uintptr(nil), pcs...)\n+ stackCache.entries[key] = v\n+ }\n+ stackCache.Unlock()\n+ return v\n+}\n+\n+func formatStack(pcs []uintptr) string {\n+ frames := runtime.CallersFrames(pcs)\n+ var trace bytes.Buffer\n+ for {\n+ frame, more := frames.Next()\n+ fmt.Fprintf(&trace, \"%s:%d: %s\\n\", frame.File, frame.Line, frame.Function)\n+\n+ if !more {\n+ break\n+ }\n+ }\n+ return trace.String()\n+}\n+\nfunc (r *AtomicRefCount) finalize() {\nvar note string\nswitch LeakMode(atomic.LoadUint32(&leakMode)) {\n@@ -241,7 +322,11 @@ func (r *AtomicRefCount) finalize() {\nnote = \"(Leak checker uninitialized): \"\n}\nif n := r.ReadRefs(); n != 0 {\n- log.Warningf(\"%sAtomicRefCount %p owned by %q garbage collected with ref count of %d (want 0)\", note, r, r.name, n)\n+ msg := fmt.Sprintf(\"%sAtomicRefCount %p owned by %q garbage collected with ref count of %d (want 0)\", note, r, r.name, n)\n+ if len(r.stack) != 0 {\n+ msg += \":\\nCaller:\\n\" + formatStack(r.stack)\n+ }\n+ log.Warningf(msg)\n}\n}\n@@ -258,8 +343,11 @@ func (r *AtomicRefCount) EnableLeakCheck(name string) {\nif name == \"\" {\npanic(\"invalid name\")\n}\n- if LeakMode(atomic.LoadUint32(&leakMode)) == NoLeakChecking {\n+ switch LeakMode(atomic.LoadUint32(&leakMode)) {\n+ case NoLeakChecking:\nreturn\n+ case LeaksLogTraces:\n+ r.stack = recordStack()\n}\nr.name = name\nruntime.SetFinalizer(r, (*AtomicRefCount).finalize)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add stack trace printing to reference leak checking.
PiperOrigin-RevId: 255759891 |
259,854 | 01.07.2019 17:45:19 | 25,200 | 0aa9418a778b2fffef4ea4691e97868b498e3b22 | Fix unix/transport.queue reference leaks.
Fix two leaks for connectionless Unix sockets:
* Double connect: Subsequent connects would leak a reference on the previously
connected endpoint.
* Close unconnected: Sockets which were not connected at the time of closure
would leak a reference on their receiver. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/transport/connectionless.go",
"new_path": "pkg/sentry/socket/unix/transport/connectionless.go",
"diff": "@@ -54,30 +54,25 @@ func (e *connectionlessEndpoint) isBound() bool {\n// Close puts the endpoint in a closed state and frees all resources associated\n// with it.\n-//\n-// The socket will be a fresh state after a call to close and may be reused.\n-// That is, close may be used to \"unbind\" or \"disconnect\" the socket in error\n-// paths.\nfunc (e *connectionlessEndpoint) Close() {\ne.Lock()\n- var r Receiver\n- if e.Connected() {\n- e.receiver.CloseRecv()\n- r = e.receiver\n- e.receiver = nil\n-\n+ if e.connected != nil {\ne.connected.Release()\ne.connected = nil\n}\n+\nif e.isBound() {\ne.path = \"\"\n}\n+\n+ e.receiver.CloseRecv()\n+ r := e.receiver\n+ e.receiver = nil\ne.Unlock()\n- if r != nil {\n+\nr.CloseNotify()\nr.Release()\n}\n-}\n// BidirectionalConnect implements BoundEndpoint.BidirectionalConnect.\nfunc (e *connectionlessEndpoint) BidirectionalConnect(ctx context.Context, ce ConnectingEndpoint, returnConnect func(Receiver, ConnectedEndpoint)) *syserr.Error {\n@@ -139,6 +134,9 @@ func (e *connectionlessEndpoint) Connect(ctx context.Context, server BoundEndpoi\n}\ne.Lock()\n+ if e.connected != nil {\n+ e.connected.Release()\n+ }\ne.connected = connected\ne.Unlock()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix unix/transport.queue reference leaks.
Fix two leaks for connectionless Unix sockets:
* Double connect: Subsequent connects would leak a reference on the previously
connected endpoint.
* Close unconnected: Sockets which were not connected at the time of closure
would leak a reference on their receiver.
PiperOrigin-RevId: 256070451 |
259,907 | 02.07.2019 14:03:31 | 25,200 | d8ec2fb671e68a2504c10bd254ae64f33752430d | Ext4: DiskLayout: Inode interface. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext4/disklayout/BUILD",
"new_path": "pkg/sentry/fs/ext4/disklayout/BUILD",
"diff": "@@ -8,6 +8,7 @@ go_library(\n\"block_group.go\",\n\"block_group_32.go\",\n\"block_group_64.go\",\n+ \"inode.go\",\n\"superblock.go\",\n\"superblock_32.go\",\n\"superblock_64.go\",\n@@ -15,7 +16,12 @@ go_library(\n\"test_utils.go\",\n],\nimportpath = \"gvisor.dev/gvisor/pkg/sentry/fs/ext4/disklayout\",\n- deps = [\"//pkg/binary\"],\n+ deps = [\n+ \"//pkg/abi/linux\",\n+ \"//pkg/binary\",\n+ \"//pkg/sentry/kernel/auth\",\n+ \"//pkg/sentry/kernel/time\",\n+ ],\n)\ngo_test(\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext4/disklayout/block_group.go",
"new_path": "pkg/sentry/fs/ext4/disklayout/block_group.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// Package disklayout provides ext4 disk level structures which can be directly\n-// filled with bytes from the underlying device. All structures on disk are in\n-// little-endian order. Only jbd2 (journal) structures are in big-endian order.\n-// Structs aim to emulate structures `exactly` how they are layed out on disk.\n-//\n-// Note: All fields in these structs are exported because binary.Read would\n-// panic otherwise.\npackage disklayout\n-// BlockGroup represents Linux struct ext4_group_desc which is internally\n-// called a block group descriptor. An ext4 file system is split into a series\n-// of block groups. This provides an access layer to information needed to\n-// access and use a block group.\n+// BlockGroup represents a Linux ext block group descriptor. An ext file system\n+// is split into a series of block groups. This provides an access layer to\n+// information needed to access and use a block group.\n//\n// See https://www.kernel.org/doc/html/latest/filesystems/ext4/globals.html#block-group-descriptors.\ntype BlockGroup interface {\n// InodeTable returns the absolute block number of the block containing the\n// inode table. This points to an array of Inode structs. Inode tables are\n// statically allocated at mkfs time. The superblock records the number of\n- // inodes per group (length of this table).\n+ // inodes per group (length of this table) and the size of each inode struct.\nInodeTable() uint64\n// BlockBitmap returns the absolute block number of the block containing the\n@@ -73,15 +65,15 @@ type BlockGroup interface {\n// Checksum returns this block group's checksum.\n//\n- // If RO_COMPAT_METADATA_CSUM feature is set:\n+ // If SbMetadataCsum feature is set:\n// - checksum is crc32c(FS UUID + group number + group descriptor\n// structure) & 0xFFFF.\n//\n- // If RO_COMPAT_GDT_CSUM feature is set:\n+ // If SbGdtCsum feature is set:\n// - checksum is crc16(FS UUID + group number + group descriptor\n// structure).\n//\n- // RO_COMPAT_METADATA_CSUM and RO_COMPAT_GDT_CSUM should not be both set.\n+ // SbMetadataCsum and SbGdtCsum should not be both set.\n// If they are, Linux warns and asks to run fsck.\nChecksum() uint16\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext4/disklayout/block_group_32.go",
"new_path": "pkg/sentry/fs/ext4/disklayout/block_group_32.go",
"diff": "package disklayout\n// BlockGroup32Bit emulates the first half of struct ext4_group_desc in\n-// fs/ext4/ext4.h. It is the block group descriptor struct for 32-bit ext4\n-// filesystems. It implements BlockGroup interface.\n+// fs/ext4/ext4.h. It is the block group descriptor struct for ext2, ext3 and\n+// 32-bit ext4 filesystems. It implements BlockGroup interface.\n//\n// The suffix `Lo` here stands for lower bits because this is also used in the\n// 64-bit version where these fields represent the lower half of the fields.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext4/disklayout/superblock.go",
"new_path": "pkg/sentry/fs/ext4/disklayout/superblock.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n+// Package disklayout provides Linux ext file system's disk level structures\n+// which can be directly read into from the underlying device. All structures\n+// on disk are in little-endian order. Only jbd2 (journal) structures are in\n+// big-endian order. Structs aim to emulate structures `exactly` how they are\n+// layed out on disk.\n+//\n+// This library aims to be compatible with all ext(2/3/4) systems so it\n+// provides a generic interface for all major structures and various\n+// implementations (for different versions). The user code is responsible for\n+// using appropriate implementations based on the underlying device.\n+//\n+// Notes:\n+// - All fields in these structs are exported because binary.Read would\n+// panic otherwise.\n+// - All OS dependent fields in these structures will be interpretted using\n+// the Linux version of that field.\npackage disklayout\n-// SuperBlock should be implemented by structs representing ext4 superblock.\n+// SuperBlock should be implemented by structs representing the ext superblock.\n// The superblock holds a lot of information about the enclosing filesystem.\n// This interface aims to provide access methods to important information held\n// by the superblock. It does NOT expose all fields of the superblock, only the\n@@ -23,11 +39,11 @@ package disklayout\n// Location and replication:\n// - The superblock is located at offset 1024 in block group 0.\n// - Redundant copies of the superblock and group descriptors are kept in\n-// all groups if sparse_super feature flag is NOT set. If it is set, the\n+// all groups if SbSparse feature flag is NOT set. If it is set, the\n// replicas only exist in groups whose group number is either 0 or a\n// power of 3, 5, or 7.\n// - There is also a sparse superblock feature v2 in which there are just\n-// two replicas saved in block groups pointed by the s_backup_bgs field.\n+// two replicas saved in the block groups pointed by sb.s_backup_bgs.\n//\n// Replicas should eventually be updated if the superblock is updated.\n//\n"
}
] | Go | Apache License 2.0 | google/gvisor | Ext4: DiskLayout: Inode interface.
PiperOrigin-RevId: 256234390 |
260,008 | 02.07.2019 17:56:57 | 25,200 | 1178a278ae2501cdd19ffaf6e10c2e3c34b143d0 | Mark timers_test flaky because setrlimit(RLIMIT_CPU) is broken in some kernels. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -3001,6 +3001,8 @@ cc_binary(\ntestonly = 1,\nsrcs = [\"timers.cc\"],\nlinkstatic = 1,\n+ # FIXME(b/136599201)\n+ tags = [\"flaky\"],\ndeps = [\n\"//test/util:cleanup\",\n\"//test/util:logging\",\n"
}
] | Go | Apache License 2.0 | google/gvisor | Mark timers_test flaky because setrlimit(RLIMIT_CPU) is broken in some kernels.
https://bugzilla.redhat.com/show_bug.cgi?id=1568337
PiperOrigin-RevId: 256276198 |
259,853 | 03.07.2019 13:57:24 | 25,200 | 116cac053e2e4e167caa9707439065af7c7b82b3 | netstack/udp: connect with the AF_UNSPEC address family means disconnect | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/epsocket/epsocket.go",
"new_path": "pkg/sentry/socket/epsocket/epsocket.go",
"diff": "@@ -285,14 +285,14 @@ func bytesToIPAddress(addr []byte) tcpip.Address {\n// GetAddress reads an sockaddr struct from the given address and converts it\n// to the FullAddress format. It supports AF_UNIX, AF_INET and AF_INET6\n// addresses.\n-func GetAddress(sfamily int, addr []byte) (tcpip.FullAddress, *syserr.Error) {\n+func GetAddress(sfamily int, addr []byte, strict bool) (tcpip.FullAddress, *syserr.Error) {\n// Make sure we have at least 2 bytes for the address family.\nif len(addr) < 2 {\nreturn tcpip.FullAddress{}, syserr.ErrInvalidArgument\n}\nfamily := usermem.ByteOrder.Uint16(addr)\n- if family != uint16(sfamily) {\n+ if family != uint16(sfamily) && (!strict && family != linux.AF_UNSPEC) {\nreturn tcpip.FullAddress{}, syserr.ErrAddressFamilyNotSupported\n}\n@@ -317,7 +317,7 @@ func GetAddress(sfamily int, addr []byte) (tcpip.FullAddress, *syserr.Error) {\ncase linux.AF_INET:\nvar a linux.SockAddrInet\nif len(addr) < sockAddrInetSize {\n- return tcpip.FullAddress{}, syserr.ErrBadAddress\n+ return tcpip.FullAddress{}, syserr.ErrInvalidArgument\n}\nbinary.Unmarshal(addr[:sockAddrInetSize], usermem.ByteOrder, &a)\n@@ -330,7 +330,7 @@ func GetAddress(sfamily int, addr []byte) (tcpip.FullAddress, *syserr.Error) {\ncase linux.AF_INET6:\nvar a linux.SockAddrInet6\nif len(addr) < sockAddrInet6Size {\n- return tcpip.FullAddress{}, syserr.ErrBadAddress\n+ return tcpip.FullAddress{}, syserr.ErrInvalidArgument\n}\nbinary.Unmarshal(addr[:sockAddrInet6Size], usermem.ByteOrder, &a)\n@@ -343,6 +343,9 @@ func GetAddress(sfamily int, addr []byte) (tcpip.FullAddress, *syserr.Error) {\n}\nreturn out, nil\n+ case linux.AF_UNSPEC:\n+ return tcpip.FullAddress{}, nil\n+\ndefault:\nreturn tcpip.FullAddress{}, syserr.ErrAddressFamilyNotSupported\n}\n@@ -465,7 +468,7 @@ func (s *SocketOperations) Readiness(mask waiter.EventMask) waiter.EventMask {\n// Connect implements the linux syscall connect(2) for sockets backed by\n// tpcip.Endpoint.\nfunc (s *SocketOperations) Connect(t *kernel.Task, sockaddr []byte, blocking bool) *syserr.Error {\n- addr, err := GetAddress(s.family, sockaddr)\n+ addr, err := GetAddress(s.family, sockaddr, false /* strict */)\nif err != nil {\nreturn err\n}\n@@ -498,7 +501,7 @@ func (s *SocketOperations) Connect(t *kernel.Task, sockaddr []byte, blocking boo\n// Bind implements the linux syscall bind(2) for sockets backed by\n// tcpip.Endpoint.\nfunc (s *SocketOperations) Bind(t *kernel.Task, sockaddr []byte) *syserr.Error {\n- addr, err := GetAddress(s.family, sockaddr)\n+ addr, err := GetAddress(s.family, sockaddr, true /* strict */)\nif err != nil {\nreturn err\n}\n@@ -1922,7 +1925,7 @@ func (s *SocketOperations) SendMsg(t *kernel.Task, src usermem.IOSequence, to []\nvar addr *tcpip.FullAddress\nif len(to) > 0 {\n- addrBuf, err := GetAddress(s.family, to)\n+ addrBuf, err := GetAddress(s.family, to, true /* strict */)\nif err != nil {\nreturn 0, err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/unix.go",
"new_path": "pkg/sentry/socket/unix/unix.go",
"diff": "@@ -110,7 +110,7 @@ func (s *SocketOperations) Endpoint() transport.Endpoint {\n// extractPath extracts and validates the address.\nfunc extractPath(sockaddr []byte) (string, *syserr.Error) {\n- addr, err := epsocket.GetAddress(linux.AF_UNIX, sockaddr)\n+ addr, err := epsocket.GetAddress(linux.AF_UNIX, sockaddr, true /* strict */)\nif err != nil {\nreturn \"\", err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/strace/socket.go",
"new_path": "pkg/sentry/strace/socket.go",
"diff": "@@ -332,7 +332,7 @@ func sockAddr(t *kernel.Task, addr usermem.Addr, length uint32) string {\nswitch family {\ncase linux.AF_INET, linux.AF_INET6, linux.AF_UNIX:\n- fa, err := epsocket.GetAddress(int(family), b)\n+ fa, err := epsocket.GetAddress(int(family), b, true /* strict */)\nif err != nil {\nreturn fmt.Sprintf(\"%#x {Family: %s, error extracting address: %v}\", addr, familyStr, err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/syserr/netstack.go",
"new_path": "pkg/syserr/netstack.go",
"diff": "@@ -86,6 +86,7 @@ var netstackErrorTranslations = map[*tcpip.Error]*Error{\ntcpip.ErrNoBufferSpace: ErrNoBufferSpace,\ntcpip.ErrBroadcastDisabled: ErrBroadcastDisabled,\ntcpip.ErrNotPermitted: ErrNotPermittedNet,\n+ tcpip.ErrAddressFamilyNotSupported: ErrAddressFamilyNotSupported,\n}\n// TranslateNetstackError converts an error from the tcpip package to a sentry\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -103,6 +103,7 @@ var (\nErrNoBufferSpace = &Error{msg: \"no buffer space available\"}\nErrBroadcastDisabled = &Error{msg: \"broadcast socket option disabled\"}\nErrNotPermitted = &Error{msg: \"operation not permitted\"}\n+ ErrAddressFamilyNotSupported = &Error{msg: \"address family not supported by protocol\"}\n)\n// Errors related to Subnet\n@@ -339,6 +340,10 @@ type Endpoint interface {\n// get the actual result. The first call to Connect after the socket has\n// connected returns nil. Calling connect again results in ErrAlreadyConnected.\n// Anything else -- the attempt to connect failed.\n+ //\n+ // If address.Addr is empty, this means that Enpoint has to be\n+ // disconnected if this is supported, otherwise\n+ // ErrAddressFamilyNotSupported must be returned.\nConnect(address FullAddress) *Error\n// Shutdown closes the read and/or write end of the endpoint connection\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/icmp/endpoint.go",
"new_path": "pkg/tcpip/transport/icmp/endpoint.go",
"diff": "@@ -422,6 +422,11 @@ func (e *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\ne.mu.Lock()\ndefer e.mu.Unlock()\n+ if addr.Addr == \"\" {\n+ // AF_UNSPEC isn't supported.\n+ return tcpip.ErrAddressFamilyNotSupported\n+ }\n+\nnicid := addr.NIC\nlocalPort := uint16(0)\nswitch e.state {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/raw/endpoint.go",
"new_path": "pkg/tcpip/transport/raw/endpoint.go",
"diff": "@@ -298,6 +298,11 @@ func (ep *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\nep.mu.Lock()\ndefer ep.mu.Unlock()\n+ if addr.Addr == \"\" {\n+ // AF_UNSPEC isn't supported.\n+ return tcpip.ErrAddressFamilyNotSupported\n+ }\n+\nif ep.closed {\nreturn tcpip.ErrInvalidEndpointState\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -1271,6 +1271,11 @@ func (e *endpoint) checkV4Mapped(addr *tcpip.FullAddress) (tcpip.NetworkProtocol\n// Connect connects the endpoint to its peer.\nfunc (e *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\n+ if addr.Addr == \"\" && addr.Port == 0 {\n+ // AF_UNSPEC isn't supported.\n+ return tcpip.ErrAddressFamilyNotSupported\n+ }\n+\nreturn e.connect(addr, true, true)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint_state.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint_state.go",
"diff": "@@ -342,6 +342,7 @@ func loadError(s string) *tcpip.Error {\ntcpip.ErrNoBufferSpace,\ntcpip.ErrBroadcastDisabled,\ntcpip.ErrNotPermitted,\n+ tcpip.ErrAddressFamilyNotSupported,\n}\nmessageToError = make(map[string]*tcpip.Error)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -698,8 +698,44 @@ func (e *endpoint) checkV4Mapped(addr *tcpip.FullAddress, allowMismatch bool) (t\nreturn netProto, nil\n}\n+func (e *endpoint) disconnect() *tcpip.Error {\n+ e.mu.Lock()\n+ defer e.mu.Unlock()\n+\n+ if e.state != stateConnected {\n+ return nil\n+ }\n+ id := stack.TransportEndpointID{}\n+ // Exclude ephemerally bound endpoints.\n+ if e.bindNICID != 0 || e.id.LocalAddress == \"\" {\n+ var err *tcpip.Error\n+ id = stack.TransportEndpointID{\n+ LocalPort: e.id.LocalPort,\n+ LocalAddress: e.id.LocalAddress,\n+ }\n+ id, err = e.registerWithStack(e.regNICID, e.effectiveNetProtos, id)\n+ if err != nil {\n+ return err\n+ }\n+ e.state = stateBound\n+ } else {\n+ e.state = stateInitial\n+ }\n+\n+ e.stack.UnregisterTransportEndpoint(e.regNICID, e.effectiveNetProtos, ProtocolNumber, e.id, e)\n+ e.id = id\n+ e.route.Release()\n+ e.route = stack.Route{}\n+ e.dstPort = 0\n+\n+ return nil\n+}\n+\n// Connect connects the endpoint to its peer. Specifying a NIC is optional.\nfunc (e *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\n+ if addr.Addr == \"\" {\n+ return e.disconnect()\n+ }\nif addr.Port == 0 {\n// We don't support connecting to port zero.\nreturn tcpip.ErrInvalidEndpointState\n@@ -734,12 +770,16 @@ func (e *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\ndefer r.Release()\nid := stack.TransportEndpointID{\n- LocalAddress: r.LocalAddress,\n+ LocalAddress: e.id.LocalAddress,\nLocalPort: localPort,\nRemotePort: addr.Port,\nRemoteAddress: r.RemoteAddress,\n}\n+ if e.state == stateInitial {\n+ id.LocalAddress = r.LocalAddress\n+ }\n+\n// Even if we're connected, this endpoint can still be used to send\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.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint_state.go",
"new_path": "pkg/tcpip/transport/udp/endpoint_state.go",
"diff": "@@ -92,8 +92,6 @@ func (e *endpoint) afterLoad() {\nif err != nil {\npanic(*err)\n}\n-\n- e.id.LocalAddress = e.route.LocalAddress\n} else if len(e.id.LocalAddress) != 0 { // stateBound\nif e.stack.CheckLocalAddress(e.regNICID, netProto, e.id.LocalAddress) == 0 {\npanic(tcpip.ErrBadLocalAddress)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/udp_socket.cc",
"new_path": "test/syscalls/linux/udp_socket.cc",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n+#include <arpa/inet.h>\n#include <fcntl.h>\n#include <linux/errqueue.h>\n#include <netinet/in.h>\n@@ -304,10 +305,48 @@ TEST_P(UdpSocketTest, ReceiveAfterConnect) {\nSyscallSucceedsWithValue(sizeof(buf)));\n// Receive the data.\n- char received[512];\n+ char received[sizeof(buf)];\n+ EXPECT_THAT(recv(s_, received, sizeof(received), 0),\n+ SyscallSucceedsWithValue(sizeof(received)));\n+ EXPECT_EQ(memcmp(buf, received, sizeof(buf)), 0);\n+}\n+\n+TEST_P(UdpSocketTest, ReceiveAfterDisconnect) {\n+ // Connect s_ to loopback:TestPort, and bind t_ to loopback:TestPort.\n+ ASSERT_THAT(connect(s_, addr_[0], addrlen_), SyscallSucceeds());\n+ ASSERT_THAT(bind(t_, addr_[0], addrlen_), SyscallSucceeds());\n+ ASSERT_THAT(connect(t_, addr_[1], addrlen_), SyscallSucceeds());\n+\n+ // Get the address s_ was bound to during connect.\n+ struct sockaddr_storage addr;\n+ socklen_t addrlen = sizeof(addr);\n+ EXPECT_THAT(getsockname(s_, reinterpret_cast<sockaddr*>(&addr), &addrlen),\n+ SyscallSucceeds());\n+ EXPECT_EQ(addrlen, addrlen_);\n+\n+ for (int i = 0; i < 2; i++) {\n+ // Send from t_ to s_.\n+ char buf[512];\n+ RandomizeBuffer(buf, sizeof(buf));\n+ EXPECT_THAT(getsockname(s_, reinterpret_cast<sockaddr*>(&addr), &addrlen),\n+ SyscallSucceeds());\n+ ASSERT_THAT(sendto(t_, buf, sizeof(buf), 0,\n+ reinterpret_cast<sockaddr*>(&addr), addrlen),\n+ SyscallSucceedsWithValue(sizeof(buf)));\n+\n+ // Receive the data.\n+ char received[sizeof(buf)];\nEXPECT_THAT(recv(s_, received, sizeof(received), 0),\nSyscallSucceedsWithValue(sizeof(received)));\nEXPECT_EQ(memcmp(buf, received, sizeof(buf)), 0);\n+\n+ // Disconnect s_.\n+ struct sockaddr addr = {};\n+ addr.sa_family = AF_UNSPEC;\n+ ASSERT_THAT(connect(s_, &addr, sizeof(addr.sa_family)), SyscallSucceeds());\n+ // Connect s_ loopback:TestPort.\n+ ASSERT_THAT(connect(s_, addr_[0], addrlen_), SyscallSucceeds());\n+ }\n}\nTEST_P(UdpSocketTest, Connect) {\n@@ -335,6 +374,112 @@ TEST_P(UdpSocketTest, Connect) {\nEXPECT_EQ(memcmp(&peer, addr_[2], addrlen_), 0);\n}\n+TEST_P(UdpSocketTest, DisconnectAfterBind) {\n+ ASSERT_THAT(bind(s_, addr_[1], addrlen_), SyscallSucceeds());\n+ // Connect the socket.\n+ ASSERT_THAT(connect(s_, addr_[0], addrlen_), SyscallSucceeds());\n+\n+ struct sockaddr_storage addr = {};\n+ addr.ss_family = AF_UNSPEC;\n+ EXPECT_THAT(\n+ connect(s_, reinterpret_cast<sockaddr*>(&addr), sizeof(addr.ss_family)),\n+ SyscallSucceeds());\n+\n+ // Check that we're still bound.\n+ socklen_t addrlen = sizeof(addr);\n+ EXPECT_THAT(getsockname(s_, reinterpret_cast<sockaddr*>(&addr), &addrlen),\n+ SyscallSucceeds());\n+\n+ EXPECT_EQ(addrlen, addrlen_);\n+ EXPECT_EQ(memcmp(&addr, addr_[1], addrlen_), 0);\n+\n+ addrlen = sizeof(addr);\n+ EXPECT_THAT(getpeername(s_, reinterpret_cast<sockaddr*>(&addr), &addrlen),\n+ SyscallFailsWithErrno(ENOTCONN));\n+}\n+\n+TEST_P(UdpSocketTest, DisconnectAfterBindToAny) {\n+ struct sockaddr_storage baddr = {};\n+ socklen_t addrlen;\n+ auto port = *Port(reinterpret_cast<struct sockaddr_storage*>(addr_[1]));\n+ if (addr_[0]->sa_family == AF_INET) {\n+ auto addr_in = reinterpret_cast<struct sockaddr_in*>(&baddr);\n+ addr_in->sin_family = AF_INET;\n+ addr_in->sin_port = port;\n+ inet_pton(AF_INET, \"0.0.0.0\",\n+ reinterpret_cast<void*>(&addr_in->sin_addr.s_addr));\n+ } else {\n+ auto addr_in = reinterpret_cast<struct sockaddr_in6*>(&baddr);\n+ addr_in->sin6_family = AF_INET6;\n+ addr_in->sin6_port = port;\n+ inet_pton(AF_INET6,\n+ \"::\", reinterpret_cast<void*>(&addr_in->sin6_addr.s6_addr));\n+ addr_in->sin6_scope_id = 0;\n+ }\n+ ASSERT_THAT(bind(s_, reinterpret_cast<sockaddr*>(&baddr), addrlen_),\n+ SyscallSucceeds());\n+ // Connect the socket.\n+ ASSERT_THAT(connect(s_, addr_[0], addrlen_), SyscallSucceeds());\n+\n+ struct sockaddr_storage addr = {};\n+ addr.ss_family = AF_UNSPEC;\n+ EXPECT_THAT(\n+ connect(s_, reinterpret_cast<sockaddr*>(&addr), sizeof(addr.ss_family)),\n+ SyscallSucceeds());\n+\n+ // Check that we're still bound.\n+ addrlen = sizeof(addr);\n+ EXPECT_THAT(getsockname(s_, reinterpret_cast<sockaddr*>(&addr), &addrlen),\n+ SyscallSucceeds());\n+\n+ EXPECT_EQ(addrlen, addrlen_);\n+ EXPECT_EQ(memcmp(&addr, &baddr, addrlen), 0);\n+\n+ addrlen = sizeof(addr);\n+ EXPECT_THAT(getpeername(s_, reinterpret_cast<sockaddr*>(&addr), &addrlen),\n+ SyscallFailsWithErrno(ENOTCONN));\n+}\n+\n+TEST_P(UdpSocketTest, Disconnect) {\n+ for (int i = 0; i < 2; i++) {\n+ // Try to connect again.\n+ EXPECT_THAT(connect(s_, addr_[2], addrlen_), SyscallSucceeds());\n+\n+ // Check that we're connected to the right peer.\n+ struct sockaddr_storage peer;\n+ socklen_t peerlen = sizeof(peer);\n+ EXPECT_THAT(getpeername(s_, reinterpret_cast<sockaddr*>(&peer), &peerlen),\n+ SyscallSucceeds());\n+ EXPECT_EQ(peerlen, addrlen_);\n+ EXPECT_EQ(memcmp(&peer, addr_[2], addrlen_), 0);\n+\n+ // Try to disconnect.\n+ struct sockaddr_storage addr = {};\n+ addr.ss_family = AF_UNSPEC;\n+ EXPECT_THAT(\n+ connect(s_, reinterpret_cast<sockaddr*>(&addr), sizeof(addr.ss_family)),\n+ SyscallSucceeds());\n+\n+ peerlen = sizeof(peer);\n+ EXPECT_THAT(getpeername(s_, reinterpret_cast<sockaddr*>(&peer), &peerlen),\n+ SyscallFailsWithErrno(ENOTCONN));\n+\n+ // Check that we're still bound.\n+ socklen_t addrlen = sizeof(addr);\n+ EXPECT_THAT(getsockname(s_, reinterpret_cast<sockaddr*>(&addr), &addrlen),\n+ SyscallSucceeds());\n+ EXPECT_EQ(addrlen, addrlen_);\n+ EXPECT_EQ(*Port(&addr), 0);\n+ }\n+}\n+\n+TEST_P(UdpSocketTest, ConnectBadAddress) {\n+ struct sockaddr addr = {};\n+ addr.sa_family = addr_[0]->sa_family;\n+ ASSERT_THAT(connect(s_, &addr, sizeof(addr.sa_family)),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\nTEST_P(UdpSocketTest, SendToAddressOtherThanConnected) {\nASSERT_THAT(connect(s_, addr_[0], addrlen_), SyscallSucceeds());\n@@ -397,7 +542,7 @@ TEST_P(UdpSocketTest, SendAndReceiveNotConnected) {\nSyscallSucceedsWithValue(sizeof(buf)));\n// Receive the data.\n- char received[512];\n+ char received[sizeof(buf)];\nEXPECT_THAT(recv(s_, received, sizeof(received), 0),\nSyscallSucceedsWithValue(sizeof(received)));\nEXPECT_EQ(memcmp(buf, received, sizeof(buf)), 0);\n@@ -419,7 +564,7 @@ TEST_P(UdpSocketTest, SendAndReceiveConnected) {\nSyscallSucceedsWithValue(sizeof(buf)));\n// Receive the data.\n- char received[512];\n+ char received[sizeof(buf)];\nEXPECT_THAT(recv(s_, received, sizeof(received), 0),\nSyscallSucceedsWithValue(sizeof(received)));\nEXPECT_EQ(memcmp(buf, received, sizeof(buf)), 0);\n@@ -462,7 +607,7 @@ TEST_P(UdpSocketTest, ReceiveBeforeConnect) {\nASSERT_THAT(connect(s_, addr_[1], addrlen_), SyscallSucceeds());\n// Receive the data. It works because it was sent before the connect.\n- char received[512];\n+ char received[sizeof(buf)];\nEXPECT_THAT(recv(s_, received, sizeof(received), 0),\nSyscallSucceedsWithValue(sizeof(received)));\nEXPECT_EQ(memcmp(buf, received, sizeof(buf)), 0);\n@@ -491,7 +636,7 @@ TEST_P(UdpSocketTest, ReceiveFrom) {\nSyscallSucceedsWithValue(sizeof(buf)));\n// Receive the data and sender address.\n- char received[512];\n+ char received[sizeof(buf)];\nstruct sockaddr_storage addr;\nsocklen_t addrlen = sizeof(addr);\nEXPECT_THAT(recvfrom(s_, received, sizeof(received), 0,\n"
}
] | Go | Apache License 2.0 | google/gvisor | netstack/udp: connect with the AF_UNSPEC address family means disconnect
PiperOrigin-RevId: 256433283 |
260,008 | 03.07.2019 16:00:29 | 25,200 | 9f2f9f0cab7ad9bbdcde23e8c98ea42c38c1e4e8 | futex: compare keys for equality when doing a FUTEX_UNLOCK_PI. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/futex/futex.go",
"new_path": "pkg/sentry/kernel/futex/futex.go",
"diff": "@@ -729,14 +729,14 @@ func (m *Manager) UnlockPI(t Target, addr usermem.Addr, tid uint32, private bool\n}\nb := m.lockBucket(&k)\n- err = m.unlockPILocked(t, addr, tid, b)\n+ err = m.unlockPILocked(t, addr, tid, b, &k)\nk.release()\nb.mu.Unlock()\nreturn err\n}\n-func (m *Manager) unlockPILocked(t Target, addr usermem.Addr, tid uint32, b *bucket) error {\n+func (m *Manager) unlockPILocked(t Target, addr usermem.Addr, tid uint32, b *bucket, key *Key) error {\ncur, err := t.LoadUint32(addr)\nif err != nil {\nreturn err\n@@ -746,7 +746,22 @@ func (m *Manager) unlockPILocked(t Target, addr usermem.Addr, tid uint32, b *buc\nreturn syserror.EPERM\n}\n- if b.waiters.Empty() {\n+ var next *Waiter // Who's the next owner?\n+ var next2 *Waiter // Who's the one after that?\n+ for w := b.waiters.Front(); w != nil; w = w.Next() {\n+ if !w.key.matches(key) {\n+ continue\n+ }\n+\n+ if next == nil {\n+ next = w\n+ } else {\n+ next2 = w\n+ break\n+ }\n+ }\n+\n+ if next == nil {\n// It's safe to set 0 because there are no waiters, no new owner, and the\n// executing task is the current owner (no owner died bit).\nprev, err := t.CompareAndSwapUint32(addr, cur, 0)\n@@ -761,12 +776,10 @@ func (m *Manager) unlockPILocked(t Target, addr usermem.Addr, tid uint32, b *buc\nreturn nil\n}\n- next := b.waiters.Front()\n-\n// Set next owner's TID, waiters if there are any. Resets owner died bit, if\n// set, because the executing task takes over as the owner.\nval := next.tid\n- if next.Next() != nil {\n+ if next2 != nil {\nval |= linux.FUTEX_WAITERS\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | futex: compare keys for equality when doing a FUTEX_UNLOCK_PI.
PiperOrigin-RevId: 256453827 |
259,884 | 03.07.2019 20:12:16 | 25,200 | da57fb9d25d947195147868253a928f83980c1fd | Fix syscall doc for getresgid | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/linux64.go",
"new_path": "pkg/sentry/syscalls/linux/linux64.go",
"diff": "@@ -168,7 +168,7 @@ var AMD64 = &kernel.SyscallTable{\n117: syscalls.Supported(\"setresuid\", Setresuid),\n118: syscalls.Supported(\"getresuid\", Getresuid),\n119: syscalls.Supported(\"setresgid\", Setresgid),\n- 120: syscalls.Supported(\"setresgid\", Getresgid),\n+ 120: syscalls.Supported(\"getresgid\", Getresgid),\n121: syscalls.Supported(\"getpgid\", Getpgid),\n122: syscalls.ErrorWithEvent(\"setfsuid\", syscall.ENOSYS, \"\", []string{\"gvisor.dev/issue/260\"}), // TODO(b/112851702)\n123: syscalls.ErrorWithEvent(\"setfsgid\", syscall.ENOSYS, \"\", []string{\"gvisor.dev/issue/260\"}), // TODO(b/112851702)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix syscall doc for getresgid
PiperOrigin-RevId: 256481284 |
259,907 | 08.07.2019 10:43:11 | 25,200 | 8f9b1ca8e7066df529b89422937e3212bf761262 | ext4: disklayout: inode impl. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext4/disklayout/BUILD",
"new_path": "pkg/sentry/fs/ext4/disklayout/BUILD",
"diff": "@@ -8,7 +8,10 @@ go_library(\n\"block_group.go\",\n\"block_group_32.go\",\n\"block_group_64.go\",\n+ \"disklayout.go\",\n\"inode.go\",\n+ \"inode_new.go\",\n+ \"inode_old.go\",\n\"superblock.go\",\n\"superblock_32.go\",\n\"superblock_64.go\",\n@@ -29,7 +32,9 @@ go_test(\nsize = \"small\",\nsrcs = [\n\"block_group_test.go\",\n+ \"inode_test.go\",\n\"superblock_test.go\",\n],\nembed = [\":disklayout\"],\n+ deps = [\"//pkg/sentry/kernel/time\"],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext4/disklayout/block_group_32.go",
"new_path": "pkg/sentry/fs/ext4/disklayout/block_group_32.go",
"diff": "@@ -17,12 +17,6 @@ package disklayout\n// BlockGroup32Bit emulates the first half of struct ext4_group_desc in\n// fs/ext4/ext4.h. It is the block group descriptor struct for ext2, ext3 and\n// 32-bit ext4 filesystems. It implements BlockGroup interface.\n-//\n-// The suffix `Lo` here stands for lower bits because this is also used in the\n-// 64-bit version where these fields represent the lower half of the fields.\n-// The suffix `Raw` has been added to indicate that the field does not have a\n-// counterpart in the 64-bit version and to resolve name collision with the\n-// interface.\ntype BlockGroup32Bit struct {\nBlockBitmapLo uint32\nInodeBitmapLo uint32\n@@ -38,6 +32,9 @@ type BlockGroup32Bit struct {\nChecksumRaw uint16\n}\n+// Compiles only if BlockGroup32Bit implements BlockGroup.\n+var _ BlockGroup = (*BlockGroup32Bit)(nil)\n+\n// InodeTable implements BlockGroup.InodeTable.\nfunc (bg *BlockGroup32Bit) InodeTable() uint64 { return uint64(bg.InodeTableLo) }\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext4/disklayout/block_group_64.go",
"new_path": "pkg/sentry/fs/ext4/disklayout/block_group_64.go",
"diff": "@@ -18,9 +18,6 @@ package disklayout\n// It is the block group descriptor struct for 64-bit ext4 filesystems.\n// It implements BlockGroup interface. It is an extension of the 32-bit\n// version of BlockGroup.\n-//\n-// The suffix `Hi` here stands for upper bits because they represent the upper\n-// half of the fields.\ntype BlockGroup64Bit struct {\n// We embed the 32-bit struct here because 64-bit version is just an extension\n// of the 32-bit version.\n@@ -40,6 +37,9 @@ type BlockGroup64Bit struct {\n_ uint32 // Padding to 64 bytes.\n}\n+// Compiles only if BlockGroup64Bit implements BlockGroup.\n+var _ BlockGroup = (*BlockGroup64Bit)(nil)\n+\n// Methods to override. Checksum() and Flags() are not overridden.\n// InodeTable implements BlockGroup.InodeTable.\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext4/disklayout/disklayout.go",
"diff": "+// Copyright 2019 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 disklayout provides Linux ext file system's disk level structures\n+// which can be directly read into from the underlying device. Structs aim to\n+// emulate structures `exactly` how they are layed out on disk.\n+//\n+// This library aims to be compatible with all ext(2/3/4) systems so it\n+// provides a generic interface for all major structures and various\n+// implementations (for different versions). The user code is responsible for\n+// using appropriate implementations based on the underlying device.\n+//\n+// Interfacing all major structures here serves a few purposes:\n+// - Abstracts away the complexity of the underlying structure from client\n+// code. The client only has to figure out versioning on set up and then\n+// can use these as black boxes and pass it higher up the stack.\n+// - Having pointer receivers forces the user to use pointers to these\n+// heavy structs. Hence, prevents the client code from unintentionally\n+// copying these by value while passing the interface around.\n+// - Version-based implementation selection is resolved on set up hence\n+// avoiding per call overhead of choosing implementation.\n+// - All interface methods are pretty light weight (do not take in any\n+// parameters by design). Passing pointer arguments to interface methods\n+// can lead to heap allocation as the compiler won't be able to perform\n+// escape analysis on an unknown implementation at compile time.\n+//\n+// Notes:\n+// - All fields in these structs are exported because binary.Read would\n+// panic otherwise.\n+// - All structures on disk are in little-endian order. Only jbd2 (journal)\n+// structures are in big-endian order.\n+// - All OS dependent fields in these structures will be interpretted using\n+// the Linux version of that field.\n+// - The suffix `Lo` in field names stands for lower bits of that field.\n+// - The suffix `Hi` in field names stands for upper bits of that field.\n+// - The suffix `Raw` has been added to indicate that the field is not split\n+// into Lo and Hi fields and also to resolve name collision with the\n+// respective interface.\n+package disklayout\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext4/disklayout/inode_new.go",
"diff": "+// Copyright 2019 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 disklayout\n+\n+import \"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n+\n+// InodeNew represents ext4 inode structure which can be bigger than\n+// OldInodeSize. The actual size of this struct should be determined using\n+// inode.ExtraInodeSize. Accessing any field here should be verified with the\n+// actual size. The extra space between the end of the inode struct and end of\n+// the inode record can be used to store extended attr.\n+//\n+// If the TimeExtra fields are in scope, the lower 2 bits of those are used\n+// to extend their counter part to be 34 bits wide; the rest (upper) 30 bits\n+// are used to provide nanoscond precision. Hence, these timestamps will now\n+// overflow in May 2446.\n+// See https://www.kernel.org/doc/html/latest/filesystems/ext4/dynamic.html#inode-timestamps.\n+type InodeNew struct {\n+ InodeOld\n+\n+ ExtraInodeSize uint16\n+ ChecksumHi uint16\n+ ChangeTimeExtra uint32\n+ ModificationTimeExtra uint32\n+ AccessTimeExtra uint32\n+ CreationTime uint32\n+ CreationTimeExtra uint32\n+ VersionHi uint32\n+ ProjectID uint32\n+}\n+\n+// Compiles only if InodeNew implements Inode.\n+var _ Inode = (*InodeNew)(nil)\n+\n+// fromExtraTime decodes the extra time and constructs the kernel time struct\n+// with nanosecond precision.\n+func fromExtraTime(lo int32, extra uint32) time.Time {\n+ // See description above InodeNew for format.\n+ seconds := (int64(extra&0x3) << 32) + int64(lo)\n+ nanoseconds := int64(extra >> 2)\n+ return time.FromUnix(seconds, nanoseconds)\n+}\n+\n+// Only override methods which change due to ext4 specific fields.\n+\n+// Size implements Inode.Size.\n+func (in *InodeNew) Size() uint64 {\n+ return (uint64(in.SizeHi) << 32) | uint64(in.SizeLo)\n+}\n+\n+// InodeSize implements Inode.InodeSize.\n+func (in *InodeNew) InodeSize() uint16 {\n+ return oldInodeSize + in.ExtraInodeSize\n+}\n+\n+// ChangeTime implements Inode.ChangeTime.\n+func (in *InodeNew) ChangeTime() time.Time {\n+ // Apply new timestamp logic if inode.ChangeTimeExtra is in scope.\n+ if in.ExtraInodeSize >= 8 {\n+ return fromExtraTime(in.ChangeTimeRaw, in.ChangeTimeExtra)\n+ }\n+\n+ return in.InodeOld.ChangeTime()\n+}\n+\n+// ModificationTime implements Inode.ModificationTime.\n+func (in *InodeNew) ModificationTime() time.Time {\n+ // Apply new timestamp logic if inode.ModificationTimeExtra is in scope.\n+ if in.ExtraInodeSize >= 12 {\n+ return fromExtraTime(in.ModificationTimeRaw, in.ModificationTimeExtra)\n+ }\n+\n+ return in.InodeOld.ModificationTime()\n+}\n+\n+// AccessTime implements Inode.AccessTime.\n+func (in *InodeNew) AccessTime() time.Time {\n+ // Apply new timestamp logic if inode.AccessTimeExtra is in scope.\n+ if in.ExtraInodeSize >= 16 {\n+ return fromExtraTime(in.AccessTimeRaw, in.AccessTimeExtra)\n+ }\n+\n+ return in.InodeOld.AccessTime()\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext4/disklayout/inode_old.go",
"diff": "+// Copyright 2019 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 disklayout\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n+)\n+\n+const (\n+ // oldInodeSize is the inode size in ext2/ext3.\n+ oldInodeSize = 128\n+)\n+\n+// InodeOld implements Inode interface. It emulates ext2/ext3 inode struct.\n+// Inode struct size and record size are both 128 bytes for this.\n+//\n+// All fields representing time are in seconds since the epoch. Which means that\n+// they will overflow in January 2038.\n+type InodeOld struct {\n+ ModeRaw uint16\n+ UIDLo uint16\n+ SizeLo uint32\n+\n+ // The time fields are signed integers because they could be negative to\n+ // represent time before the epoch.\n+ AccessTimeRaw int32\n+ ChangeTimeRaw int32\n+ ModificationTimeRaw int32\n+ DeletionTimeRaw int32\n+\n+ GIDLo uint16\n+ LinksCountRaw uint16\n+ BlocksCountLo uint32\n+ FlagsRaw uint32\n+ VersionLo uint32 // This is OS dependent.\n+ BlocksRaw [60]byte\n+ Generation uint32\n+ FileACLLo uint32\n+ SizeHi uint32\n+ ObsoFaddr uint32\n+\n+ // OS dependent fields have been inlined here.\n+ BlocksCountHi uint16\n+ FileACLHi uint16\n+ UIDHi uint16\n+ GIDHi uint16\n+ ChecksumLo uint16\n+ _ uint16\n+}\n+\n+// Compiles only if InodeOld implements Inode.\n+var _ Inode = (*InodeOld)(nil)\n+\n+// Mode implements Inode.Mode.\n+func (in *InodeOld) Mode() linux.FileMode { return linux.FileMode(in.ModeRaw) }\n+\n+// UID implements Inode.UID.\n+func (in *InodeOld) UID() auth.KUID {\n+ return auth.KUID((uint32(in.UIDHi) << 16) | uint32(in.UIDLo))\n+}\n+\n+// GID implements Inode.GID.\n+func (in *InodeOld) GID() auth.KGID {\n+ return auth.KGID((uint32(in.GIDHi) << 16) | uint32(in.GIDLo))\n+}\n+\n+// Size implements Inode.Size.\n+func (in *InodeOld) Size() uint64 {\n+ // In ext2/ext3, in.SizeHi did not exist, it was instead named in.DirACL.\n+ return uint64(in.SizeLo)\n+}\n+\n+// InodeSize implements Inode.InodeSize.\n+func (in *InodeOld) InodeSize() uint16 { return oldInodeSize }\n+\n+// AccessTime implements Inode.AccessTime.\n+func (in *InodeOld) AccessTime() time.Time {\n+ return time.FromUnix(int64(in.AccessTimeRaw), 0)\n+}\n+\n+// ChangeTime implements Inode.ChangeTime.\n+func (in *InodeOld) ChangeTime() time.Time {\n+ return time.FromUnix(int64(in.ChangeTimeRaw), 0)\n+}\n+\n+// ModificationTime implements Inode.ModificationTime.\n+func (in *InodeOld) ModificationTime() time.Time {\n+ return time.FromUnix(int64(in.ModificationTimeRaw), 0)\n+}\n+\n+// DeletionTime implements Inode.DeletionTime.\n+func (in *InodeOld) DeletionTime() time.Time {\n+ return time.FromUnix(int64(in.DeletionTimeRaw), 0)\n+}\n+\n+// LinksCount implements Inode.LinksCount.\n+func (in *InodeOld) LinksCount() uint16 { return in.LinksCountRaw }\n+\n+// Flags implements Inode.Flags.\n+func (in *InodeOld) Flags() InodeFlags { return InodeFlagsFromInt(in.FlagsRaw) }\n+\n+// Blocks implements Inode.Blocks.\n+func (in *InodeOld) Blocks() [60]byte { return in.BlocksRaw }\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext4/disklayout/inode_test.go",
"diff": "+// Copyright 2019 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 disklayout\n+\n+import (\n+ \"fmt\"\n+ \"strconv\"\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n+)\n+\n+// TestInodeSize tests that the inode structs are of the correct size.\n+func TestInodeSize(t *testing.T) {\n+ assertSize(t, InodeOld{}, oldInodeSize)\n+\n+ // This was updated from 156 bytes to 160 bytes in Oct 2015.\n+ assertSize(t, InodeNew{}, 160)\n+}\n+\n+// TestTimestampSeconds tests that the seconds part of [a/c/m] timestamps in\n+// ext4 inode structs are decoded correctly.\n+//\n+// These tests are derived from the table under https://www.kernel.org/doc/html/latest/filesystems/ext4/dynamic.html#inode-timestamps.\n+func TestTimestampSeconds(t *testing.T) {\n+ type timestampTest struct {\n+ // msbSet tells if the most significant bit of InodeOld.[X]TimeRaw is set.\n+ // If this is set then the 32-bit time is negative.\n+ msbSet bool\n+\n+ // lowerBound tells if we should take the lowest possible value of\n+ // InodeOld.[X]TimeRaw while satisfying test.msbSet condition. If set to\n+ // false it tells to take the highest possible value.\n+ lowerBound bool\n+\n+ // extraBits is InodeNew.[X]TimeExtra.\n+ extraBits uint32\n+\n+ // want is the kernel time struct that is expected.\n+ want time.Time\n+ }\n+\n+ tests := []timestampTest{\n+ // 1901-12-13\n+ {\n+ msbSet: true,\n+ lowerBound: true,\n+ extraBits: 0,\n+ want: time.FromUnix(int64(-0x80000000), 0),\n+ },\n+\n+ // 1969-12-31\n+ {\n+ msbSet: true,\n+ lowerBound: false,\n+ extraBits: 0,\n+ want: time.FromUnix(int64(-1), 0),\n+ },\n+\n+ // 1970-01-01\n+ {\n+ msbSet: false,\n+ lowerBound: true,\n+ extraBits: 0,\n+ want: time.FromUnix(int64(0), 0),\n+ },\n+\n+ // 2038-01-19\n+ {\n+ msbSet: false,\n+ lowerBound: false,\n+ extraBits: 0,\n+ want: time.FromUnix(int64(0x7fffffff), 0),\n+ },\n+\n+ // 2038-01-19\n+ {\n+ msbSet: true,\n+ lowerBound: true,\n+ extraBits: 1,\n+ want: time.FromUnix(int64(0x80000000), 0),\n+ },\n+\n+ // 2106-02-07\n+ {\n+ msbSet: true,\n+ lowerBound: false,\n+ extraBits: 1,\n+ want: time.FromUnix(int64(0xffffffff), 0),\n+ },\n+\n+ // 2106-02-07\n+ {\n+ msbSet: false,\n+ lowerBound: true,\n+ extraBits: 1,\n+ want: time.FromUnix(int64(0x100000000), 0),\n+ },\n+\n+ // 2174-02-25\n+ {\n+ msbSet: false,\n+ lowerBound: false,\n+ extraBits: 1,\n+ want: time.FromUnix(int64(0x17fffffff), 0),\n+ },\n+\n+ // 2174-02-25\n+ {\n+ msbSet: true,\n+ lowerBound: true,\n+ extraBits: 2,\n+ want: time.FromUnix(int64(0x180000000), 0),\n+ },\n+\n+ // 2242-03-16\n+ {\n+ msbSet: true,\n+ lowerBound: false,\n+ extraBits: 2,\n+ want: time.FromUnix(int64(0x1ffffffff), 0),\n+ },\n+\n+ // 2242-03-16\n+ {\n+ msbSet: false,\n+ lowerBound: true,\n+ extraBits: 2,\n+ want: time.FromUnix(int64(0x200000000), 0),\n+ },\n+\n+ // 2310-04-04\n+ {\n+ msbSet: false,\n+ lowerBound: false,\n+ extraBits: 2,\n+ want: time.FromUnix(int64(0x27fffffff), 0),\n+ },\n+\n+ // 2310-04-04\n+ {\n+ msbSet: true,\n+ lowerBound: true,\n+ extraBits: 3,\n+ want: time.FromUnix(int64(0x280000000), 0),\n+ },\n+\n+ // 2378-04-22\n+ {\n+ msbSet: true,\n+ lowerBound: false,\n+ extraBits: 3,\n+ want: time.FromUnix(int64(0x2ffffffff), 0),\n+ },\n+\n+ // 2378-04-22\n+ {\n+ msbSet: false,\n+ lowerBound: true,\n+ extraBits: 3,\n+ want: time.FromUnix(int64(0x300000000), 0),\n+ },\n+\n+ // 2446-05-10\n+ {\n+ msbSet: false,\n+ lowerBound: false,\n+ extraBits: 3,\n+ want: time.FromUnix(int64(0x37fffffff), 0),\n+ },\n+ }\n+\n+ lowerMSB0 := int32(0) // binary: 00000000 00000000 00000000 00000000\n+ upperMSB0 := int32(0x7fffffff) // binary: 01111111 11111111 11111111 11111111\n+ lowerMSB1 := int32(-0x80000000) // binary: 10000000 00000000 00000000 00000000\n+ upperMSB1 := int32(-1) // binary: 11111111 11111111 11111111 11111111\n+\n+ get32BitTime := func(test timestampTest) int32 {\n+ if test.msbSet {\n+ if test.lowerBound {\n+ return lowerMSB1\n+ }\n+\n+ return upperMSB1\n+ }\n+\n+ if test.lowerBound {\n+ return lowerMSB0\n+ }\n+\n+ return upperMSB0\n+ }\n+\n+ getTestName := func(test timestampTest) string {\n+ return fmt.Sprintf(\n+ \"Tests time decoding with epoch bits 0b%s and 32-bit raw time: MSB set=%t, lower bound=%t\",\n+ strconv.FormatInt(int64(test.extraBits), 2),\n+ test.msbSet,\n+ test.lowerBound,\n+ )\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(getTestName(test), func(t *testing.T) {\n+ if got := fromExtraTime(get32BitTime(test), test.extraBits); got != test.want {\n+ t.Errorf(\"Expected: %v, Got: %v\", test.want, got)\n+ }\n+ })\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext4/disklayout/superblock.go",
"new_path": "pkg/sentry/fs/ext4/disklayout/superblock.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// Package disklayout provides Linux ext file system's disk level structures\n-// which can be directly read into from the underlying device. All structures\n-// on disk are in little-endian order. Only jbd2 (journal) structures are in\n-// big-endian order. Structs aim to emulate structures `exactly` how they are\n-// layed out on disk.\n-//\n-// This library aims to be compatible with all ext(2/3/4) systems so it\n-// provides a generic interface for all major structures and various\n-// implementations (for different versions). The user code is responsible for\n-// using appropriate implementations based on the underlying device.\n-//\n-// Notes:\n-// - All fields in these structs are exported because binary.Read would\n-// panic otherwise.\n-// - All OS dependent fields in these structures will be interpretted using\n-// the Linux version of that field.\npackage disklayout\n// SuperBlock should be implemented by structs representing the ext superblock.\n@@ -109,7 +93,7 @@ type SuperBlock interface {\n// - Inode disk record size = sb.s_inode_size (function return value).\n// = 256 (default)\n// - Inode struct size = 128 + inode.i_extra_isize.\n- // = 128 + 28 = 156 (default)\n+ // = 128 + 32 = 160 (default)\nInodeSize() uint16\n// InodesPerGroup returns the number of inodes in a block group.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext4/disklayout/superblock_32.go",
"new_path": "pkg/sentry/fs/ext4/disklayout/superblock_32.go",
"diff": "@@ -16,10 +16,6 @@ package disklayout\n// SuperBlock32Bit implements SuperBlock and represents the 32-bit version of\n// the ext4_super_block struct in fs/ext4/ext4.h.\n-//\n-// The suffix `Raw` has been added to indicate that the field does not have a\n-// counterpart in the 64-bit version and to resolve name collision with the\n-// interface.\ntype SuperBlock32Bit struct {\n// We embed the old superblock struct here because the 32-bit version is just\n// an extension of the old version.\n@@ -52,6 +48,9 @@ type SuperBlock32Bit struct {\nJnlBlocks [17]uint32\n}\n+// Compiles only if SuperBlock32Bit implements SuperBlock.\n+var _ SuperBlock = (*SuperBlock32Bit)(nil)\n+\n// Only override methods which change based on the additional fields above.\n// Not overriding SuperBlock.BgDescSize because it would still return 32 here.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext4/disklayout/superblock_64.go",
"new_path": "pkg/sentry/fs/ext4/disklayout/superblock_64.go",
"diff": "@@ -18,9 +18,6 @@ package disklayout\n// the ext4_super_block struct in fs/ext4/ext4.h. This sums up to be exactly\n// 1024 bytes (smallest possible block size) and hence the superblock always\n// fits in no more than one data block.\n-//\n-// The suffix `Hi` here stands for upper bits because they represent the upper\n-// half of the fields.\ntype SuperBlock64Bit struct {\n// We embed the 32-bit struct here because 64-bit version is just an extension\n// of the 32-bit version.\n@@ -78,6 +75,9 @@ type SuperBlock64Bit struct {\nChecksum uint32\n}\n+// Compiles only if SuperBlock64Bit implements SuperBlock.\n+var _ SuperBlock = (*SuperBlock64Bit)(nil)\n+\n// Only override methods which change based on the 64-bit feature.\n// BlocksCount implements SuperBlock.BlocksCount.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext4/disklayout/superblock_old.go",
"new_path": "pkg/sentry/fs/ext4/disklayout/superblock_old.go",
"diff": "@@ -16,12 +16,6 @@ package disklayout\n// SuperBlockOld implements SuperBlock and represents the old version of the\n// superblock struct in ext2 and ext3 systems.\n-//\n-// The suffix `Lo` here stands for lower bits because this is also used in the\n-// 64-bit version where these fields represent the lower half of the fields.\n-// The suffix `Raw` has been added to indicate that the field does not have a\n-// counterpart in the 64-bit version and to resolve name collision with the\n-// interface.\ntype SuperBlockOld struct {\nInodesCountRaw uint32\nBlocksCountLo uint32\n@@ -84,7 +78,7 @@ func (sb *SuperBlockOld) ClusterSize() uint64 { return 1 << (10 + sb.LogClusterS\nfunc (sb *SuperBlockOld) ClustersPerGroup() uint32 { return sb.ClustersPerGroupRaw }\n// InodeSize implements SuperBlock.InodeSize.\n-func (sb *SuperBlockOld) InodeSize() uint16 { return 128 }\n+func (sb *SuperBlockOld) InodeSize() uint16 { return oldInodeSize }\n// InodesPerGroup implements SuperBlock.InodesPerGroup.\nfunc (sb *SuperBlockOld) InodesPerGroup() uint32 { return sb.InodesPerGroupRaw }\n"
}
] | Go | Apache License 2.0 | google/gvisor | ext4: disklayout: inode impl.
PiperOrigin-RevId: 257010414 |
259,858 | 09.07.2019 16:42:54 | 25,200 | dea3cb92f2c9fffb604cedde6998b3209c91e716 | build: add nogo for static validation | [
{
"change_type": "MODIFY",
"old_path": "BUILD",
"new_path": "BUILD",
"diff": "package(licenses = [\"notice\"]) # Apache 2.0\n-load(\"@io_bazel_rules_go//go:def.bzl\", \"go_path\")\n+load(\"@io_bazel_rules_go//go:def.bzl\", \"go_path\", \"nogo\")\nload(\"@bazel_gazelle//:def.bzl\", \"gazelle\")\n# The sandbox filegroup is used for sandbox-internal dependencies.\n@@ -29,3 +29,15 @@ go_path(\n# To update the WORKSPACE from go.mod, use:\n# bazel run //:gazelle -- update-repos -from_file=go.mod\ngazelle(name = \"gazelle\")\n+\n+# nogo applies checks to all Go source in this repository, enforcing code\n+# guidelines and restrictions. Note that the tool libraries themselves should\n+# live in the tools subdirectory (unless they are standard).\n+nogo(\n+ name = \"nogo\",\n+ config = \"tools/nogo.js\",\n+ visibility = [\"//visibility:public\"],\n+ deps = [\n+ \"//tools/checkunsafe\",\n+ ],\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "WORKSPACE",
"new_path": "WORKSPACE",
"diff": "@@ -20,7 +20,10 @@ load(\"@io_bazel_rules_go//go:deps.bzl\", \"go_rules_dependencies\", \"go_register_to\ngo_rules_dependencies()\n-go_register_toolchains(go_version = \"1.12.6\")\n+go_register_toolchains(\n+ go_version = \"1.12.6\",\n+ nogo = \"@//:nogo\",\n+)\nload(\"@bazel_gazelle//:deps.bzl\", \"gazelle_dependencies\", \"go_repository\")\n@@ -141,6 +144,12 @@ go_repository(\nimportpath = \"golang.org/x/sys\",\n)\n+go_repository(\n+ name = \"org_golang_x_tools\",\n+ commit = \"aa82965741a9fecd12b026fbb3d3c6ed3231b8f8\",\n+ importpath = \"golang.org/x/tools\",\n+)\n+\ngo_repository(\nname = \"com_github_google_btree\",\nimportpath = \"github.com/google/btree\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/BUILD",
"new_path": "pkg/sentry/kernel/BUILD",
"diff": "@@ -31,7 +31,7 @@ go_template_instance(\ngo_template_instance(\nname = \"seqatomic_taskgoroutineschedinfo\",\n- out = \"seqatomic_taskgoroutineschedinfo.go\",\n+ out = \"seqatomic_taskgoroutineschedinfo_unsafe.go\",\npackage = \"kernel\",\nsuffix = \"TaskGoroutineSchedInfo\",\ntemplate = \"//third_party/gvsync:generic_seqatomic\",\n@@ -112,7 +112,7 @@ go_library(\n\"ptrace_arm64.go\",\n\"rseq.go\",\n\"seccomp.go\",\n- \"seqatomic_taskgoroutineschedinfo.go\",\n+ \"seqatomic_taskgoroutineschedinfo_unsafe.go\",\n\"session_list.go\",\n\"sessions.go\",\n\"signal.go\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/auth/BUILD",
"new_path": "pkg/sentry/kernel/auth/BUILD",
"diff": "@@ -5,7 +5,7 @@ load(\"//tools/go_stateify:defs.bzl\", \"go_library\")\ngo_template_instance(\nname = \"atomicptr_credentials\",\n- out = \"atomicptr_credentials.go\",\n+ out = \"atomicptr_credentials_unsafe.go\",\npackage = \"auth\",\nsuffix = \"Credentials\",\ntemplate = \"//third_party/gvsync:generic_atomicptr\",\n@@ -45,7 +45,7 @@ go_template_instance(\ngo_library(\nname = \"auth\",\nsrcs = [\n- \"atomicptr_credentials.go\",\n+ \"atomicptr_credentials_unsafe.go\",\n\"auth.go\",\n\"capability_set.go\",\n\"context.go\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/futex/BUILD",
"new_path": "pkg/sentry/kernel/futex/BUILD",
"diff": "@@ -5,7 +5,7 @@ load(\"//tools/go_stateify:defs.bzl\", \"go_library\", \"go_test\")\ngo_template_instance(\nname = \"atomicptr_bucket\",\n- out = \"atomicptr_bucket.go\",\n+ out = \"atomicptr_bucket_unsafe.go\",\npackage = \"futex\",\nsuffix = \"Bucket\",\ntemplate = \"//third_party/gvsync:generic_atomicptr\",\n@@ -29,7 +29,7 @@ go_template_instance(\ngo_library(\nname = \"futex\",\nsrcs = [\n- \"atomicptr_bucket.go\",\n+ \"atomicptr_bucket_unsafe.go\",\n\"futex.go\",\n\"waiter_list.go\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/time/BUILD",
"new_path": "pkg/sentry/time/BUILD",
"diff": "@@ -6,7 +6,7 @@ load(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\ngo_template_instance(\nname = \"seqatomic_parameters\",\n- out = \"seqatomic_parameters.go\",\n+ out = \"seqatomic_parameters_unsafe.go\",\npackage = \"time\",\nsuffix = \"Parameters\",\ntemplate = \"//third_party/gvsync:generic_seqatomic\",\n@@ -27,7 +27,7 @@ go_library(\n\"parameters.go\",\n\"sampler.go\",\n\"sampler_unsafe.go\",\n- \"seqatomic_parameters.go\",\n+ \"seqatomic_parameters_unsafe.go\",\n\"tsc_amd64.s\",\n\"tsc_arm64.s\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "third_party/gvsync/atomicptrtest/BUILD",
"new_path": "third_party/gvsync/atomicptrtest/BUILD",
"diff": "@@ -6,7 +6,7 @@ load(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\ngo_template_instance(\nname = \"atomicptr_int\",\n- out = \"atomicptr_int.go\",\n+ out = \"atomicptr_int_unsafe.go\",\npackage = \"atomicptr\",\nsuffix = \"Int\",\ntemplate = \"//third_party/gvsync:generic_atomicptr\",\n@@ -17,7 +17,7 @@ go_template_instance(\ngo_library(\nname = \"atomicptr\",\n- srcs = [\"atomicptr_int.go\"],\n+ srcs = [\"atomicptr_int_unsafe.go\"],\nimportpath = \"gvisor.dev/gvisor/third_party/gvsync/atomicptr\",\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "third_party/gvsync/seqatomictest/BUILD",
"new_path": "third_party/gvsync/seqatomictest/BUILD",
"diff": "@@ -6,7 +6,7 @@ load(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\ngo_template_instance(\nname = \"seqatomic_int\",\n- out = \"seqatomic_int.go\",\n+ out = \"seqatomic_int_unsafe.go\",\npackage = \"seqatomic\",\nsuffix = \"Int\",\ntemplate = \"//third_party/gvsync:generic_seqatomic\",\n@@ -17,7 +17,7 @@ go_template_instance(\ngo_library(\nname = \"seqatomic\",\n- srcs = [\"seqatomic_int.go\"],\n+ srcs = [\"seqatomic_int_unsafe.go\"],\nimportpath = \"gvisor.dev/gvisor/third_party/gvsync/seqatomic\",\ndeps = [\n\"//third_party/gvsync\",\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tools/checkunsafe/BUILD",
"diff": "+load(\"@io_bazel_rules_go//go:def.bzl\", \"go_tool_library\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_tool_library(\n+ name = \"checkunsafe\",\n+ srcs = [\"check_unsafe.go\"],\n+ importpath = \"checkunsafe\",\n+ visibility = [\"//visibility:public\"],\n+ deps = [\n+ \"@org_golang_x_tools//go/analysis:go_tool_library\",\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tools/checkunsafe/check_unsafe.go",
"diff": "+// Copyright 2019 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 checkunsafe allows unsafe imports only in files named appropriately.\n+package checkunsafe\n+\n+import (\n+ \"fmt\"\n+ \"path\"\n+ \"strconv\"\n+ \"strings\"\n+\n+ \"golang.org/x/tools/go/analysis\"\n+)\n+\n+// Analyzer defines the entrypoint.\n+var Analyzer = &analysis.Analyzer{\n+ Name: \"checkunsafe\",\n+ Doc: \"allows unsafe use only in specified files\",\n+ Run: run,\n+}\n+\n+func run(pass *analysis.Pass) (interface{}, error) {\n+ for _, f := range pass.Files {\n+ for _, imp := range f.Imports {\n+ // Is this an unsafe import?\n+ pkg, err := strconv.Unquote(imp.Path.Value)\n+ if err != nil || pkg != \"unsafe\" {\n+ continue\n+ }\n+\n+ // Extract the filename.\n+ filename := pass.Fset.File(imp.Pos()).Name()\n+\n+ // Allow files named _unsafe.go or _test.go to opt out.\n+ if strings.HasSuffix(filename, \"_unsafe.go\") || strings.HasSuffix(filename, \"_test.go\") {\n+ continue\n+ }\n+\n+ // Throw the error.\n+ pass.Reportf(imp.Pos(), fmt.Sprintf(\"package unsafe imported by %s; must end with _unsafe.go\", path.Base(filename)))\n+ }\n+ }\n+ return nil, nil\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tools/nogo.js",
"diff": "+{\n+ \"checkunsafe\": {\n+ \"exclude_files\": {\n+ \"/external/\": \"not subject to constraint\"\n+ }\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | build: add nogo for static validation
PiperOrigin-RevId: 257297820 |
259,907 | 09.07.2019 18:34:58 | 25,200 | 7965b1272bb0579da47960e64ea902c74f49483d | ext4: disklayout: Directory Entry implementation. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext4/disklayout/BUILD",
"new_path": "pkg/sentry/fs/ext4/disklayout/BUILD",
"diff": "@@ -8,6 +8,9 @@ go_library(\n\"block_group.go\",\n\"block_group_32.go\",\n\"block_group_64.go\",\n+ \"dirent.go\",\n+ \"dirent_new.go\",\n+ \"dirent_old.go\",\n\"disklayout.go\",\n\"inode.go\",\n\"inode_new.go\",\n@@ -22,6 +25,7 @@ go_library(\ndeps = [\n\"//pkg/abi/linux\",\n\"//pkg/binary\",\n+ \"//pkg/sentry/fs\",\n\"//pkg/sentry/kernel/auth\",\n\"//pkg/sentry/kernel/time\",\n],\n@@ -32,6 +36,7 @@ go_test(\nsize = \"small\",\nsrcs = [\n\"block_group_test.go\",\n+ \"dirent_test.go\",\n\"inode_test.go\",\n\"superblock_test.go\",\n],\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext4/disklayout/dirent.go",
"diff": "+// Copyright 2019 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 disklayout\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/sentry/fs\"\n+)\n+\n+const (\n+ // MaxFileName is the maximum length of an ext fs file's name.\n+ MaxFileName = 255\n+)\n+\n+var (\n+ // inodeTypeByFileType maps ext4 file types to vfs inode types.\n+ //\n+ // See https://www.kernel.org/doc/html/latest/filesystems/ext4/dynamic.html#ftype.\n+ inodeTypeByFileType = map[uint8]fs.InodeType{\n+ 0: fs.Anonymous,\n+ 1: fs.RegularFile,\n+ 2: fs.Directory,\n+ 3: fs.CharacterDevice,\n+ 4: fs.BlockDevice,\n+ 5: fs.Pipe,\n+ 6: fs.Socket,\n+ 7: fs.Symlink,\n+ }\n+)\n+\n+// The Dirent interface should be implemented by structs representing ext\n+// directory entries. These are for the linear classical directories which\n+// just store a list of dirent structs. A directory is a series of data blocks\n+// where is each data block contains a linear array of dirents. The last entry\n+// of the block has a record size that takes it to the end of the block. The\n+// end of the directory is when you read dirInode.Size() bytes from the blocks.\n+//\n+// See https://www.kernel.org/doc/html/latest/filesystems/ext4/dynamic.html#linear-classic-directories.\n+type Dirent interface {\n+ // Inode returns the absolute inode number of the underlying inode.\n+ // Inode number 0 signifies an unused dirent.\n+ Inode() uint32\n+\n+ // RecordSize returns the record length of this dirent on disk. The next\n+ // dirent in the dirent list should be read after these many bytes from\n+ // the current dirent. Must be a multiple of 4.\n+ RecordSize() uint16\n+\n+ // FileName returns the name of the file. Can be at most 255 is length.\n+ FileName() string\n+\n+ // FileType returns the inode type of the underlying inode. This is a\n+ // performance hack so that we do not have to read the underlying inode struct\n+ // to know the type of inode. This will only work when the SbDirentFileType\n+ // feature is set. If not, the second returned value will be false indicating\n+ // that user code has to use the inode mode to extract the file type.\n+ FileType() (fs.InodeType, bool)\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext4/disklayout/dirent_new.go",
"diff": "+// Copyright 2019 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 disklayout\n+\n+import (\n+ \"fmt\"\n+\n+ \"gvisor.dev/gvisor/pkg/sentry/fs\"\n+)\n+\n+// DirentNew represents the ext4 directory entry struct. This emulates Linux's\n+// ext4_dir_entry_2 struct. The FileName can not be more than 255 bytes so we\n+// only need 8 bits to store the NameLength. As a result, NameLength has been\n+// shortened and the other 8 bits are used to encode the file type. Use the\n+// FileTypeRaw field only if the SbDirentFileType feature is set.\n+//\n+// Note: This struct can be of variable size on disk. The one described below\n+// is of maximum size and the FileName beyond NameLength bytes might contain\n+// garbage.\n+type DirentNew struct {\n+ InodeNumber uint32\n+ RecordLength uint16\n+ NameLength uint8\n+ FileTypeRaw uint8\n+ FileNameRaw [MaxFileName]byte\n+}\n+\n+// Compiles only if DirentNew implements Dirent.\n+var _ Dirent = (*DirentNew)(nil)\n+\n+// Inode implements Dirent.Inode.\n+func (d *DirentNew) Inode() uint32 { return d.InodeNumber }\n+\n+// RecordSize implements Dirent.RecordSize.\n+func (d *DirentNew) RecordSize() uint16 { return d.RecordLength }\n+\n+// FileName implements Dirent.FileName.\n+func (d *DirentNew) FileName() string {\n+ return string(d.FileNameRaw[:d.NameLength])\n+}\n+\n+// FileType implements Dirent.FileType.\n+func (d *DirentNew) FileType() (fs.InodeType, bool) {\n+ if inodeType, ok := inodeTypeByFileType[d.FileTypeRaw]; ok {\n+ return inodeType, true\n+ }\n+\n+ panic(fmt.Sprintf(\"unknown file type %v\", d.FileTypeRaw))\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext4/disklayout/dirent_old.go",
"diff": "+// Copyright 2019 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 disklayout\n+\n+import \"gvisor.dev/gvisor/pkg/sentry/fs\"\n+\n+// DirentOld represents the old directory entry struct which does not contain\n+// the file type. This emulates Linux's ext4_dir_entry struct. This is used in\n+// ext2, ext3 and sometimes in ext4.\n+//\n+// Note: This struct can be of variable size on disk. The one described below\n+// is of maximum size and the FileName beyond NameLength bytes might contain\n+// garbage.\n+type DirentOld struct {\n+ InodeNumber uint32\n+ RecordLength uint16\n+ NameLength uint16\n+ FileNameRaw [MaxFileName]byte\n+}\n+\n+// Compiles only if DirentOld implements Dirent.\n+var _ Dirent = (*DirentOld)(nil)\n+\n+// Inode implements Dirent.Inode.\n+func (d *DirentOld) Inode() uint32 { return d.InodeNumber }\n+\n+// RecordSize implements Dirent.RecordSize.\n+func (d *DirentOld) RecordSize() uint16 { return d.RecordLength }\n+\n+// FileName implements Dirent.FileName.\n+func (d *DirentOld) FileName() string {\n+ return string(d.FileNameRaw[:d.NameLength])\n+}\n+\n+// FileType implements Dirent.FileType.\n+func (d *DirentOld) FileType() (fs.InodeType, bool) {\n+ return fs.Anonymous, false\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext4/disklayout/dirent_test.go",
"diff": "+// Copyright 2019 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 disklayout\n+\n+import (\n+ \"testing\"\n+)\n+\n+// TestDirentSize tests that the dirent structs are of the correct\n+// size.\n+func TestDirentSize(t *testing.T) {\n+ want := uintptr(263)\n+\n+ assertSize(t, DirentOld{}, want)\n+ assertSize(t, DirentNew{}, want)\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | ext4: disklayout: Directory Entry implementation.
PiperOrigin-RevId: 257314911 |
259,884 | 10.07.2019 01:21:03 | 14,400 | 8a641256470955691d5851ffca9b4b890df8855c | Copy app engine app files in cloudbuild
Fixes website deploy step | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -14,9 +14,12 @@ APP_TARGET = $(patsubst cmd/gvisor-website/%,public/%,$(APP_SOURCE))\ndefault: website\n.PHONY: default\n-website: all-upstream $(APP_TARGET) public/static\n+website: all-upstream app public/static\n.PHONY: website\n+app: $(APP_TARGET)\n+.PHONY: app\n+\npublic:\nmkdir -p public\n@@ -56,9 +59,9 @@ bin/generate-syscall-docs: $(GEN_SOURCE)\nmkdir -p bin/\ngo build -o bin/generate-syscall-docs gvisor.dev/website/cmd/generate-syscall-docs\n-.PHONY: compatibility-docs\ncompatibility-docs: bin/generate-syscall-docs upstream/gvisor/bazel-bin/runsc/linux_amd64_pure_stripped/runsc\n./upstream/gvisor/bazel-bin/runsc/linux_amd64_pure_stripped/runsc help syscalls -o json | ./bin/generate-syscall-docs -out ./content/docs/user_guide/compatibility/\n+.PHONY: compatibility-docs\n# Run a local content development server. Redirects will not be supported.\nserver: all-upstream compatibility-docs\n"
},
{
"change_type": "MODIFY",
"old_path": "cloudbuild.yaml",
"new_path": "cloudbuild.yaml",
"diff": "@@ -52,6 +52,9 @@ steps:\n# Pull npm dependencies for scss\n- name: 'gcr.io/cloud-builders/npm'\nargs: ['ci']\n+ # Copy App Engine app files.\n+ - name: 'gcr.io/gvisor-website/hugo:0.53'\n+ args: [\"make\", \"app\"]\n# Generate the website.\n- name: 'gcr.io/gvisor-website/hugo:0.53'\nenv: ['HUGO_ENV=production']\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "content/docs/user_guide/compatibility/.gitignore",
"diff": "+linux\n"
},
{
"change_type": "DELETE",
"old_path": "content/docs/user_guide/compatibility/linux/.gitignore",
"new_path": null,
"diff": "-amd64.md\n"
}
] | Go | Apache License 2.0 | google/gvisor | Copy app engine app files in cloudbuild
Fixes website deploy step |
259,853 | 11.07.2019 12:52:12 | 25,200 | a018b229b57dff92ca0d99079180aa556dacbabc | kokoro: use bazel 2.27.1
The latest version 2.28.0 doesn't work:
./runsc/linux_amd64_pure_stripped/runsc: operation not permitted, want 0 | [
{
"change_type": "MODIFY",
"old_path": "tools/run_tests.sh",
"new_path": "tools/run_tests.sh",
"diff": "@@ -45,7 +45,8 @@ readonly TEST_PACKAGES=(\"//pkg/...\" \"//runsc/...\" \"//tools/...\")\n#######################\n# Install the latest version of Bazel and log the version.\n-(which use_bazel.sh && use_bazel.sh latest) || which bazel\n+# FIXME(b/137285694): Unable to build runsc with bazel 0.28.0.\n+(which use_bazel.sh && use_bazel.sh 0.27.1) || which bazel\nbazel version\n# Load the kvm module.\n"
}
] | Go | Apache License 2.0 | google/gvisor | kokoro: use bazel 2.27.1
The latest version 2.28.0 doesn't work:
./runsc/linux_amd64_pure_stripped/runsc: operation not permitted, want 0
PiperOrigin-RevId: 257663312 |
259,907 | 11.07.2019 17:16:27 | 25,200 | 2eeca68900eeb57a679eccc08fe172b1d9ddf97f | Added tiny ext4 image.
The image is of size 64Kb which supports 64 1k blocks
and 16 inodes. This is the smallest size mkfs.ext4 works with.
Added README.md documenting how this was created and included
all files on the device under assets. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext/assets/README.md",
"diff": "+### Tiny Ext4 Image\n+\n+The image is of size 64Kb which supports 64 1k blocks and 16 inodes. This is the\n+smallest size mkfs.ext4 works with.\n+\n+This image was generated using the following commands.\n+\n+```bash\n+fallocate -l 64K tiny.ext4\n+mkfs.ext4 -j tiny.ext4\n+```\n+\n+You can mount it using:\n+\n+```bash\n+sudo mount -o loop tiny.ext4 $MOUNTPOINT\n+```\n+\n+`file.txt`, `bigfile.txt` and `symlink.txt` were added to this image by just\n+mounting it and copying (while preserving links) those files to the mountpoint\n+directory using:\n+\n+```bash\n+sudo cp -P {file.txt,symlink.txt,bigfile.txt} $MOUNTPOINT/\n+```\n+\n+The files in this directory mirror the contents and organisation of the files\n+stored in the image.\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext/assets/bigfile.txt",
"diff": "+Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus faucibus eleifend orci, ut ornare nibh faucibus eu. Cras at condimentum massa. Nullam luctus, elit non porttitor congue, sapien diam feugiat sapien, sed eleifend nulla mauris non arcu. Sed lacinia mauris magna, eu mollis libero varius sit amet. Donec mollis, quam convallis commodo posuere, dolor nisi placerat nisi, in faucibus augue mi eu lorem. In pharetra consectetur faucibus. Ut euismod ex efficitur egestas tincidunt. Maecenas condimentum ut ante in rutrum. Vivamus sed arcu tempor, faucibus turpis et, lacinia diam.\n+\n+Sed in lacus vel nisl interdum bibendum in sed justo. Nunc tellus risus, molestie vitae arcu sed, molestie tempus ligula. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nunc risus neque, volutpat et ante non, ullamcorper condimentum ante. Aliquam sed metus in urna condimentum convallis. Vivamus ut libero mauris. Proin mollis posuere consequat. Vestibulum placerat mollis est et pulvinar.\n+\n+Donec rutrum odio ac diam pharetra, id fermentum magna cursus. Pellentesque in dapibus elit, et condimentum orci. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Suspendisse euismod dapibus est, id vestibulum mauris. Nulla facilisi. Nulla cursus gravida nisi. Phasellus vestibulum rutrum lectus, a dignissim mauris hendrerit vitae. In at elementum mauris. Integer vel efficitur velit. Nullam fringilla sapien mi, quis luctus neque efficitur ac. Aenean nec quam dapibus nunc commodo pharetra. Proin sapien mi, fermentum aliquet vulputate non, aliquet porttitor diam. Quisque lacinia, urna et finibus fermentum, nunc lacus vehicula ex, sed congue metus lectus ac quam. Aliquam erat volutpat. Suspendisse sodales, dolor ut tincidunt finibus, augue erat varius tellus, a interdum erat sem at nunc. Vestibulum cursus iaculis sapien, vitae feugiat dui auctor quis.\n+\n+Pellentesque nec maximus nulla, eu blandit diam. Maecenas quis arcu ornare, congue ante at, vehicula ipsum. Praesent feugiat mauris rutrum sem fermentum, nec luctus ipsum placerat. Pellentesque placerat ipsum at dignissim fringilla. Vivamus et posuere sem, eget hendrerit felis. Aenean vulputate, augue vel mollis feugiat, justo ipsum mollis dolor, eu mollis elit neque ut ipsum. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Fusce bibendum sem quam, vulputate laoreet mi dapibus imperdiet. Sed a purus non nibh pretium aliquet. Integer eget luctus augue, vitae tincidunt magna. Ut eros enim, egestas eu nulla et, lobortis egestas arcu. Cras id ipsum ac justo lacinia rutrum. Vivamus lectus leo, ultricies sed justo at, pellentesque feugiat magna. Ut sollicitudin neque elit, vel ornare mauris commodo id.\n+\n+Duis dapibus orci et sapien finibus finibus. Mauris eleifend, lacus at vestibulum maximus, quam ligula pharetra erat, sit amet dapibus neque elit vitae neque. In bibendum sollicitudin erat, eget ultricies tortor malesuada at. Sed sit amet orci turpis. Donec feugiat ligula nibh, molestie tincidunt lectus elementum id. Donec volutpat maximus nibh, in vulputate felis posuere eu. Cras tincidunt ullamcorper lacus. Phasellus porta lorem auctor, congue magna a, commodo elit.\n+\n+Etiam auctor mi quis elit sodales, eu pulvinar arcu condimentum. Aenean imperdiet risus et dapibus tincidunt. Nullam tincidunt dictum dui, sed commodo urna rutrum id. Ut mollis libero vel elit laoreet bibendum. Quisque arcu arcu, tincidunt at ultricies id, vulputate nec metus. In tristique posuere quam sit amet volutpat. Vivamus scelerisque et nunc at dapibus. Fusce finibus libero ut ligula pretium rhoncus. Mauris non elit in arcu finibus imperdiet. Pellentesque nec massa odio. Proin rutrum mauris non sagittis efficitur. Aliquam auctor quam at dignissim faucibus. Ut eget ligula in magna posuere ultricies vitae sit amet turpis. Duis maximus odio nulla. Donec gravida sem tristique tempus scelerisque.\n+\n+Interdum et malesuada fames ac ante ipsum primis in faucibus. Fusce pharetra magna vulputate aliquet tempus. Duis id hendrerit arcu. Quisque ut ex elit. Integer velit orci, venenatis ut sapien ac, placerat porttitor dui. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nunc hendrerit cursus diam, hendrerit finibus ipsum scelerisque ut. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.\n+\n+Nulla non euismod neque. Phasellus vel sapien eu metus pulvinar rhoncus. Suspendisse eu mollis tellus, quis vestibulum tortor. Maecenas interdum dolor sed nulla fermentum maximus. Donec imperdiet ullamcorper condimentum. Nam quis nibh ante. Praesent quis tellus ut tortor pulvinar blandit sit amet ut sapien. Vestibulum est orci, pellentesque vitae tristique sit amet, tristique non felis.\n+\n+Vivamus sodales pellentesque varius. Sed vel tempus ligula. Nulla tristique nisl vel dui facilisis, ac sodales augue hendrerit. Proin augue nisi, vestibulum quis augue nec, sagittis tincidunt velit. Vestibulum euismod, nulla nec sodales faucibus, urna sapien vulputate magna, id varius metus sapien ut neque. Duis in mollis urna, in scelerisque enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nunc condimentum dictum turpis, et egestas neque dapibus eget. Quisque fringilla, dui eu venenatis eleifend, erat nibh lacinia urna, at lacinia lacus sapien eu dui. Duis eu erat ut mi lacinia convallis a sed ex.\n+\n+Fusce elit metus, tincidunt nec eleifend a, hendrerit nec ligula. Duis placerat finibus sollicitudin. In euismod porta tellus, in luctus justo bibendum bibendum. Maecenas at magna eleifend lectus tincidunt suscipit ut a ligula. Nulla tempor accumsan felis, fermentum dapibus est eleifend vitae. Mauris urna sem, fringilla at ultricies non, ultrices in arcu. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam vehicula nunc at laoreet imperdiet. Nunc tristique ut risus id aliquet. Integer eleifend massa orci.\n+\n+Vestibulum sed ante sollicitudin nisi fringilla bibendum nec vel quam. Sed pretium augue eu ligula congue pulvinar. Donec vitae magna tincidunt, pharetra lacus id, convallis nulla. Cras viverra nisl nisl, varius convallis leo vulputate nec. Morbi at consequat dui, sed aliquet metus. Sed suscipit fermentum mollis. Maecenas nec mi sodales, tincidunt purus in, tristique mauris. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec interdum mi in velit efficitur, quis ultrices ex imperdiet. Sed vestibulum, magna ut tristique pretium, mi ipsum placerat tellus, non tempor enim augue et ex. Pellentesque eget felis quis ante sodales viverra ac sed lacus. Donec suscipit tempus massa, eget laoreet massa molestie at.\n+\n+Aenean fringilla dui non aliquet consectetur. Fusce cursus quam nec orci hendrerit faucibus. Donec consequat suscipit enim, non volutpat lectus auctor interdum. Proin lorem purus, maximus vel orci vitae, suscipit egestas turpis. Donec risus urna, congue a sem eu, aliquet placerat odio. Morbi gravida tristique turpis, quis efficitur enim. Nunc interdum gravida ipsum vel facilisis. Nunc congue finibus sollicitudin. Quisque euismod aliquet lectus et tincidunt. Curabitur ultrices sem ut mi fringilla fermentum. Morbi pretium, nisi sit amet dapibus congue, dolor enim consectetur risus, a interdum ligula odio sed odio. Quisque facilisis, mi at suscipit gravida, nunc sapien cursus justo, ut luctus odio nulla quis leo. Integer condimentum lobortis mauris, non egestas tellus lobortis sit amet.\n+\n+In sollicitudin velit ac ante vehicula, vitae varius tortor mollis. In hac habitasse platea dictumst. Quisque et orci lorem. Integer malesuada fringilla luctus. Pellentesque malesuada, mi non lobortis porttitor, ante ligula vulputate ante, nec dictum risus eros sit amet sapien. Nulla aliquam lorem libero, ac varius nulla tristique eget. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut pellentesque mauris orci, vel consequat mi varius a. Ut sit amet elit vulputate, lacinia metus non, fermentum nisl. Pellentesque eu nisi sed quam egestas blandit. Duis sit amet lobortis dolor. Donec consectetur sem interdum, tristique elit sit amet, sodales lacus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce id aliquam augue. Sed pretium congue risus vitae lacinia. Vestibulum non vulputate risus, ut malesuada justo.\n+\n+Sed odio elit, consectetur ac mauris quis, consequat commodo libero. Fusce sodales velit vulputate pulvinar fermentum. Donec iaculis nec nisl eget faucibus. Mauris at dictum velit. Donec fermentum lectus eu viverra volutpat. Aliquam consequat facilisis lorem, cursus consequat dui bibendum ullamcorper. Pellentesque nulla magna, imperdiet at magna et, cursus egestas enim. Nullam semper molestie lectus sit amet semper. Duis eget tincidunt est. Integer id neque risus. Integer ultricies hendrerit vestibulum. Donec blandit blandit sagittis. Nunc consectetur vitae nisi consectetur volutpat.\n+\n+Nulla id lorem fermentum, efficitur magna a, hendrerit dui. Vivamus sagittis orci gravida, bibendum quam eget, molestie est. Phasellus nec enim tincidunt, volutpat sapien non, laoreet diam. Nulla posuere enim nec porttitor lobortis. Donec auctor odio ut orci eleifend, ut eleifend purus convallis. Interdum et malesuada fames ac ante ipsum primis in faucibus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut hendrerit, purus eget viverra tincidunt, sem magna imperdiet libero, et aliquam turpis neque vitae elit. Maecenas semper varius iaculis. Cras non lorem quis quam bibendum eleifend in et libero. Curabitur at purus mauris. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus porta diam sed elit eleifend gravida.\n+\n+Nulla facilisi. Ut ultricies diam vel diam consectetur, vel porta augue molestie. Fusce interdum sapien et metus facilisis pellentesque. Nulla convallis sem at nunc vehicula facilisis. Nam ac rutrum purus. Nunc bibendum, dolor sit amet tempus ullamcorper, lorem leo tempor sem, id fringilla nunc augue scelerisque augue. Nullam sit amet rutrum nisl. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec sed mauris gravida eros vehicula sagittis at eget orci. Cras elementum, eros at accumsan bibendum, libero neque blandit purus, vitae vestibulum libero massa ac nibh. Integer at placerat nulla. Mauris eu eleifend orci. Aliquam consequat ligula vitae erat porta lobortis. Duis fermentum elit ac aliquet ornare.\n+\n+Mauris eget cursus tellus, eget sodales purus. Aliquam malesuada, augue id vulputate finibus, nisi ex bibendum nisl, sit amet laoreet quam urna a dolor. Nullam ultricies, sapien eu laoreet consequat, erat eros dignissim diam, ultrices sodales lectus mauris et leo. Morbi lacinia eu ante at tempus. Sed iaculis finibus magna malesuada efficitur. Donec faucibus erat sit amet elementum feugiat. Praesent a placerat nisi. Etiam lacinia gravida diam, et sollicitudin sapien tincidunt ut.\n+\n+Maecenas felis quam, tincidunt vitae venenatis scelerisque, viverra vitae odio. Phasellus enim neque, ultricies suscipit malesuada sit amet, vehicula sit amet purus. Nulla placerat sit amet dui vel tincidunt. Nam quis neque vel magna commodo egestas. Vestibulum sagittis rutrum lorem ut congue. Maecenas vel ultrices tellus. Donec efficitur, urna ac consequat iaculis, lorem felis pharetra eros, eget faucibus orci lectus sit amet arcu.\n+\n+Ut a tempus nisi. Nulla facilisi. Praesent vulputate maximus mi et dapibus. Sed sit amet libero ac augue hendrerit efficitur in a sapien. Mauris placerat velit sit amet tellus sollicitudin faucibus. Donec egestas a magna ac suscipit. Duis enim sapien, mollis sed egestas et, vestibulum vel leo.\n+\n+Proin quis dapibus dui. Donec eu tincidunt nunc. Vivamus eget purus consectetur, maximus ante vitae, tincidunt elit. Aenean mattis dolor a gravida aliquam. Praesent quis tellus id sem maximus vulputate nec sed nulla. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur metus nulla, volutpat volutpat est eu, hendrerit congue erat. Aliquam sollicitudin augue ante. Sed sollicitudin, magna eu consequat elementum, mi augue ullamcorper felis, molestie imperdiet erat metus iaculis est. Proin ac tortor nisi. Pellentesque quis nisi risus. Integer enim sapien, tincidunt quis tortor id, accumsan venenatis mi. Nulla facilisi.\n+\n+Cras pretium sit amet quam congue maximus. Morbi lacus libero, imperdiet commodo massa sed, scelerisque placerat libero. Cras nisl nisi, consectetur sed bibendum eu, venenatis at enim. Proin sodales justo at quam aliquam, a consectetur mi ornare. Donec porta ac est sit amet efficitur. Suspendisse vestibulum tortor id neque imperdiet, id lacinia risus vehicula. Phasellus ac eleifend purus. Mauris vel gravida ante. Aliquam vitae lobortis risus. Sed vehicula consectetur tincidunt. Nam et justo vitae purus molestie consequat. Pellentesque ipsum ex, convallis quis blandit non, gravida et urna. Donec diam ligula amet.\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext/assets/file.txt",
"diff": "+Hello World!\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext/assets/symlink.txt",
"diff": "+file.txt\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": "pkg/sentry/fs/ext/assets/tiny.ext4",
"new_path": "pkg/sentry/fs/ext/assets/tiny.ext4",
"diff": "Binary files /dev/null and b/pkg/sentry/fs/ext/assets/tiny.ext4 differ\n"
}
] | Go | Apache License 2.0 | google/gvisor | Added tiny ext4 image.
The image is of size 64Kb which supports 64 1k blocks
and 16 inodes. This is the smallest size mkfs.ext4 works with.
Added README.md documenting how this was created and included
all files on the device under assets.
PiperOrigin-RevId: 257712672 |
259,891 | 11.07.2019 21:24:27 | 25,200 | 44427d8e267b4c4445c1c217637d802f71e9bf52 | Add a stub for /dev/tty.
Actual implementation to follow, but this will satisfy applications that
want it to just exist. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/dev/BUILD",
"new_path": "pkg/sentry/fs/dev/BUILD",
"diff": "@@ -11,6 +11,7 @@ go_library(\n\"full.go\",\n\"null.go\",\n\"random.go\",\n+ \"tty.go\",\n],\nimportpath = \"gvisor.dev/gvisor/pkg/sentry/fs/dev\",\nvisibility = [\"//pkg/sentry:internal\"],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/dev/dev.go",
"new_path": "pkg/sentry/fs/dev/dev.go",
"diff": "@@ -38,12 +38,20 @@ const (\nurandomDevMinor uint32 = 9\n)\n-func newCharacterDevice(ctx context.Context, iops fs.InodeOperations, msrc *fs.MountSource) *fs.Inode {\n+// TTY major device number comes from include/uapi/linux/major.h.\n+const (\n+ ttyDevMinor = 0\n+ ttyDevMajor = 5\n+)\n+\n+func newCharacterDevice(ctx context.Context, iops fs.InodeOperations, msrc *fs.MountSource, major uint16, minor uint32) *fs.Inode {\nreturn fs.NewInode(ctx, iops, msrc, fs.StableAttr{\nDeviceID: devDevice.DeviceID(),\nInodeID: devDevice.NextIno(),\nBlockSize: usermem.PageSize,\nType: fs.CharacterDevice,\n+ DeviceFileMajor: major,\n+ DeviceFileMinor: minor,\n})\n}\n@@ -114,6 +122,8 @@ func New(ctx context.Context, msrc *fs.MountSource) *fs.Inode {\n// If no devpts is mounted, this will simply be a dangling\n// symlink, which is fine.\n\"ptmx\": newSymlink(ctx, \"pts/ptmx\", msrc),\n+\n+ \"tty\": newCharacterDevice(ctx, newTTYDevice(ctx, fs.RootOwner, 0666), msrc, ttyDevMajor, ttyDevMinor),\n}\niops := ramfs.NewDir(ctx, contents, fs.RootOwner, fs.FilePermsFromMode(0555))\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/dev/tty.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 dev\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/rand\"\n+ \"gvisor.dev/gvisor/pkg/sentry/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fs/fsutil\"\n+ \"gvisor.dev/gvisor/pkg/sentry/safemem\"\n+ \"gvisor.dev/gvisor/pkg/sentry/usermem\"\n+ \"gvisor.dev/gvisor/pkg/waiter\"\n+)\n+\n+// +stateify savable\n+type ttyInodeOperations struct {\n+ fsutil.InodeGenericChecker `state:\"nosave\"`\n+ fsutil.InodeNoExtendedAttributes `state:\"nosave\"`\n+ fsutil.InodeNoopAllocate `state:\"nosave\"`\n+ fsutil.InodeNoopRelease `state:\"nosave\"`\n+ fsutil.InodeNoopTruncate `state:\"nosave\"`\n+ fsutil.InodeNoopWriteOut `state:\"nosave\"`\n+ fsutil.InodeNotDirectory `state:\"nosave\"`\n+ fsutil.InodeNotMappable `state:\"nosave\"`\n+ fsutil.InodeNotSocket `state:\"nosave\"`\n+ fsutil.InodeNotSymlink `state:\"nosave\"`\n+ fsutil.InodeVirtual `state:\"nosave\"`\n+\n+ fsutil.InodeSimpleAttributes\n+}\n+\n+var _ fs.InodeOperations = (*ttyInodeOperations)(nil)\n+\n+func newTTYDevice(ctx context.Context, owner fs.FileOwner, mode linux.FileMode) *ttyInodeOperations {\n+ return &ttyInodeOperations{\n+ InodeSimpleAttributes: fsutil.NewInodeSimpleAttributes(ctx, owner, fs.FilePermsFromMode(mode), linux.TMPFS_MAGIC),\n+ }\n+}\n+\n+// GetFile implements fs.InodeOperations.GetFile.\n+func (*ttyInodeOperations) GetFile(ctx context.Context, dirent *fs.Dirent, flags fs.FileFlags) (*fs.File, error) {\n+ return fs.NewFile(ctx, dirent, flags, &ttyFileOperations{}), nil\n+}\n+\n+// +stateify savable\n+type ttyFileOperations struct {\n+ fsutil.FileNoSeek `state:\"nosave\"`\n+ fsutil.FileNoIoctl `state:\"nosave\"`\n+ fsutil.FileNoMMap `state:\"nosave\"`\n+ fsutil.FileNoSplice `state:\"nosave\"`\n+ fsutil.FileNoopFlush `state:\"nosave\"`\n+ fsutil.FileNoopFsync `state:\"nosave\"`\n+ fsutil.FileNoopRelease `state:\"nosave\"`\n+ fsutil.FileNoopWrite `state:\"nosave\"`\n+ fsutil.FileNoopRead `state:\"nosave\"`\n+ fsutil.FileNotDirReaddir `state:\"nosave\"`\n+ fsutil.FileUseInodeUnstableAttr `state:\"nosave\"`\n+ waiter.AlwaysReady `state:\"nosave\"`\n+}\n+\n+var _ fs.FileOperations = (*ttyFileOperations)(nil)\n+\n+// Read implements fs.FileOperations.Read.\n+func (*ttyFileOperations) Read(ctx context.Context, _ *fs.File, dst usermem.IOSequence, _ int64) (int64, error) {\n+ return dst.CopyOutFrom(ctx, safemem.FromIOReader{rand.Reader})\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/dev.cc",
"new_path": "test/syscalls/linux/dev.cc",
"diff": "// limitations under the License.\n#include <fcntl.h>\n+#include <sys/stat.h>\n+#include <sys/types.h>\n#include <unistd.h>\n#include <vector>\n@@ -143,6 +145,11 @@ TEST(DevTest, WriteDevFull) {\nEXPECT_THAT(WriteFd(fd.get(), \"a\", 1), SyscallFailsWithErrno(ENOSPC));\n}\n+TEST(DevTest, TTYExists) {\n+ struct stat statbuf = {};\n+ ASSERT_THAT(stat(\"/dev/tty\", &statbuf), SyscallSucceeds());\n+}\n+\n} // namespace\n} // namespace testing\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add a stub for /dev/tty.
Actual implementation to follow, but this will satisfy applications that
want it to just exist. |
259,891 | 11.07.2019 21:31:26 | 25,200 | ddef7f8078ba87ae2c73c6b89668e01d1da76cfe | Fix license year and remove Read. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/dev/tty.go",
"new_path": "pkg/sentry/fs/dev/tty.go",
"diff": "-// Copyright 2018 The gVisor Authors.\n+// Copyright 2019 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@@ -16,12 +16,9 @@ package dev\nimport (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n- \"gvisor.dev/gvisor/pkg/rand\"\n\"gvisor.dev/gvisor/pkg/sentry/context\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n\"gvisor.dev/gvisor/pkg/sentry/fs/fsutil\"\n- \"gvisor.dev/gvisor/pkg/sentry/safemem\"\n- \"gvisor.dev/gvisor/pkg/sentry/usermem\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n@@ -72,8 +69,3 @@ type ttyFileOperations struct {\n}\nvar _ fs.FileOperations = (*ttyFileOperations)(nil)\n-\n-// Read implements fs.FileOperations.Read.\n-func (*ttyFileOperations) Read(ctx context.Context, _ *fs.File, dst usermem.IOSequence, _ int64) (int64, error) {\n- return dst.CopyOutFrom(ctx, safemem.FromIOReader{rand.Reader})\n-}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix license year and remove Read. |
259,858 | 12.07.2019 14:33:23 | 25,200 | 4ad67050895d0129f736d8728c62ff9957ada8d7 | CONTRIBUTING: add logs access instructions. | [
{
"change_type": "MODIFY",
"old_path": "CONTRIBUTING.md",
"new_path": "CONTRIBUTING.md",
"diff": "@@ -86,6 +86,11 @@ Code changes are accepted via [pull request][github].\nWhen approved, the change will be submitted by a team member and automatically\nmerged into the repository.\n+### Presubmit checks\n+\n+Accessing check logs may require membership in the\n+[gvisor-dev mailing list][gvisor-dev-list], which is public.\n+\n### Bug IDs\nSome TODOs and NOTEs sprinkled throughout the code have associated IDs of the\n@@ -103,5 +108,6 @@ one above, the\n[gcla]: https://cla.developers.google.com/about/google-individual\n[gccla]: https://cla.developers.google.com/about/google-corporate\n[github]: https://github.com/google/gvisor/compare\n+[gvisor-dev-list]: https://groups.google.com/forum/#!forum/gvisor-dev\n[gostyle]: https://github.com/golang/go/wiki/CodeReviewComments\n[teststyle]: ./test/\n"
}
] | Go | Apache License 2.0 | google/gvisor | CONTRIBUTING: add logs access instructions.
PiperOrigin-RevId: 257870018 |
259,891 | 12.07.2019 15:16:01 | 25,200 | 6ebb925acd6336760f6f9453e860944e0e314a7b | Add permission, char device, and uid checks. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/dev.cc",
"new_path": "test/syscalls/linux/dev.cc",
"diff": "@@ -148,6 +148,10 @@ TEST(DevTest, WriteDevFull) {\nTEST(DevTest, TTYExists) {\nstruct stat statbuf = {};\nASSERT_THAT(stat(\"/dev/tty\", &statbuf), SyscallSucceeds());\n+ // Check that it's a character device with rw-rw-rw- permissions.\n+ EXPECT_EQ(statbuf.st_mode, S_IFCHR | 0666);\n+ // Check that it's owned by root.\n+ EXPECT_EQ(statbuf.st_uid, 0);\n}\n} // namespace\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add permission, char device, and uid checks.
Change-Id: I8307bfb390a56424aaa651285a218aad277c4aed |
260,008 | 15.07.2019 15:21:12 | 25,200 | ab44d145bb9806fa363d79e49b4190c62fcd669f | Fix initialization of badhandler_low_water_mark in SigaltstackTest.
It is now correctly initialized to the top of the signal stack.
Previously it was initialized to the address of 'stack.ss_sp' on
the main thread stack. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/sigaltstack.cc",
"new_path": "test/syscalls/linux/sigaltstack.cc",
"diff": "@@ -175,7 +175,7 @@ TEST(SigaltstackTest, WalksOffBottom) {\n// Trigger a single fault.\nbadhandler_low_water_mark =\n- reinterpret_cast<char*>(&stack.ss_sp) + SIGSTKSZ; // Expected top.\n+ static_cast<char*>(stack.ss_sp) + SIGSTKSZ; // Expected top.\nbadhandler_recursive_faults = 0; // Disable refault.\nFault();\nEXPECT_TRUE(badhandler_on_sigaltstack);\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix initialization of badhandler_low_water_mark in SigaltstackTest.
It is now correctly initialized to the top of the signal stack.
Previously it was initialized to the address of 'stack.ss_sp' on
the main thread stack.
PiperOrigin-RevId: 258248363 |
259,891 | 15.07.2019 17:27:54 | 25,200 | 3d78baf06d32141fb1c9c136cc01e3e204309969 | Replace vector of arrays with array of arrays.
C++ does not like vectors of arrays (because arrays are not copy-constructable). | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/raw_socket_icmp.cc",
"new_path": "test/syscalls/linux/raw_socket_icmp.cc",
"diff": "@@ -195,7 +195,7 @@ TEST_F(RawSocketICMPTest, MultipleSocketReceive) {\n// Receive on socket 1.\nconstexpr int kBufSize = kEmptyICMPSize;\n- std::vector<char[kBufSize]> recv_buf1(2);\n+ char recv_buf1[2][kBufSize];\nstruct sockaddr_in src;\nfor (int i = 0; i < 2; i++) {\nASSERT_NO_FATAL_FAILURE(ReceiveICMP(recv_buf1[i],\n@@ -205,7 +205,7 @@ TEST_F(RawSocketICMPTest, MultipleSocketReceive) {\n}\n// Receive on socket 2.\n- std::vector<char[kBufSize]> recv_buf2(2);\n+ char recv_buf2[2][kBufSize];\nfor (int i = 0; i < 2; i++) {\nASSERT_NO_FATAL_FAILURE(\nReceiveICMPFrom(recv_buf2[i], ABSL_ARRAYSIZE(recv_buf2[i]),\n@@ -221,14 +221,14 @@ TEST_F(RawSocketICMPTest, MultipleSocketReceive) {\nreinterpret_cast<struct icmphdr*>(buf + sizeof(struct iphdr));\nreturn icmp->type == type;\n};\n- const char* icmp1 =\n- *std::find_if(recv_buf1.begin(), recv_buf1.end(), match_type);\n- const char* icmp2 =\n- *std::find_if(recv_buf2.begin(), recv_buf2.end(), match_type);\n- ASSERT_NE(icmp1, *recv_buf1.end());\n- ASSERT_NE(icmp2, *recv_buf2.end());\n- EXPECT_EQ(memcmp(icmp1 + sizeof(struct iphdr), icmp2 + sizeof(struct iphdr),\n- sizeof(icmp)),\n+ auto icmp1_it =\n+ std::find_if(std::begin(recv_buf1), std::end(recv_buf1), match_type);\n+ auto icmp2_it =\n+ std::find_if(std::begin(recv_buf2), std::end(recv_buf2), match_type);\n+ ASSERT_NE(icmp1_it, std::end(recv_buf1));\n+ ASSERT_NE(icmp2_it, std::end(recv_buf2));\n+ EXPECT_EQ(memcmp(*icmp1_it + sizeof(struct iphdr),\n+ *icmp2_it + sizeof(struct iphdr), sizeof(icmp)),\n0);\n}\n}\n@@ -254,7 +254,7 @@ TEST_F(RawSocketICMPTest, RawAndPingSockets) {\n// Receive on socket 1, which receives the echo request and reply in\n// indeterminate order.\nconstexpr int kBufSize = kEmptyICMPSize;\n- std::vector<char[kBufSize]> recv_buf1(2);\n+ char recv_buf1[2][kBufSize];\nstruct sockaddr_in src;\nfor (int i = 0; i < 2; i++) {\nASSERT_NO_FATAL_FAILURE(\n@@ -274,11 +274,12 @@ TEST_F(RawSocketICMPTest, RawAndPingSockets) {\nreinterpret_cast<struct icmphdr*>(buf + sizeof(struct iphdr));\nreturn icmp->type == ICMP_ECHOREPLY;\n};\n- char* raw_reply =\n- *std::find_if(recv_buf1.begin(), recv_buf1.end(), match_type_raw);\n- ASSERT_NE(raw_reply, *recv_buf1.end());\n+ auto raw_reply_it =\n+ std::find_if(std::begin(recv_buf1), std::end(recv_buf1), match_type_raw);\n+ ASSERT_NE(raw_reply_it, std::end(recv_buf1));\nEXPECT_EQ(\n- memcmp(raw_reply + sizeof(struct iphdr), ping_recv_buf, sizeof(icmp)), 0);\n+ memcmp(*raw_reply_it + sizeof(struct iphdr), ping_recv_buf, sizeof(icmp)),\n+ 0);\n}\n// Test that connect() sends packets to the right place.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Replace vector of arrays with array of arrays.
C++ does not like vectors of arrays (because arrays are not copy-constructable).
PiperOrigin-RevId: 258270980 |
259,853 | 15.07.2019 19:26:16 | 25,200 | 6a8ff6daefc670455f40326afd53b51b632a32dc | kvm: wake up all waiter of vCPU.state
Now we call FUTEX_WAKE with ^uintptr(0) of waiters, but in this case only one
waiter will be waked up. If we want to wake up all of them, the number of
waiters has to be set to math.MaxInt32. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine_unsafe.go",
"new_path": "pkg/sentry/platform/kvm/machine_unsafe.go",
"diff": "@@ -21,6 +21,7 @@ package kvm\nimport (\n\"fmt\"\n+ \"math\"\n\"sync/atomic\"\n\"syscall\"\n\"unsafe\"\n@@ -134,7 +135,7 @@ func (c *vCPU) notify() {\nsyscall.SYS_FUTEX,\nuintptr(unsafe.Pointer(&c.state)),\nlinux.FUTEX_WAKE|linux.FUTEX_PRIVATE_FLAG,\n- ^uintptr(0), // Number of waiters.\n+ math.MaxInt32, // Number of waiters.\n0, 0, 0)\nif errno != 0 {\nthrow(\"futex wake error\")\n"
}
] | Go | Apache License 2.0 | google/gvisor | kvm: wake up all waiter of vCPU.state
Now we call FUTEX_WAKE with ^uintptr(0) of waiters, but in this case only one
waiter will be waked up. If we want to wake up all of them, the number of
waiters has to be set to math.MaxInt32.
PiperOrigin-RevId: 258285286 |
259,883 | 15.07.2019 22:49:58 | 25,200 | cf4fc510fd80c5a23e271db677a8721385c45a4d | Support /proc/net/dev
This proc file reports the stats of interfaces. We could use ifconfig
command to check the result.
COPYBARA_INTEGRATE_REVIEW=https://gvisor-review.googlesource.com/c/gvisor/+/18282/ | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/net.go",
"new_path": "pkg/sentry/fs/proc/net.go",
"diff": "@@ -155,37 +155,40 @@ func (n *netDev) ReadSeqFileData(ctx context.Context, h seqfile.SeqHandle) ([]se\ncontents[1] = \" face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed\\n\"\nfor _, i := range interfaces {\n- // TODO(b/71872867): Collect stats from each inet.Stack\n- // implementation (hostinet, epsocket, and rpcinet).\n-\n// Implements the same format as\n// net/core/net-procfs.c:dev_seq_printf_stats.\n- l := fmt.Sprintf(\"%6s: %7d %7d %4d %4d %4d %5d %10d %9d %8d %7d %4d %4d %4d %5d %7d %10d\\n\",\n+ var stats inet.StatDev\n+ if err := n.s.Statistics(&stats, i.Name); err != nil {\n+ log.Warningf(\"Failed to retrieve interface statistics for %v: %v\", i.Name, err)\n+ continue\n+ }\n+ l := fmt.Sprintf(\n+ \"%6s: %7d %7d %4d %4d %4d %5d %10d %9d %8d %7d %4d %4d %4d %5d %7d %10d\\n\",\ni.Name,\n// Received\n- 0, // bytes\n- 0, // packets\n- 0, // errors\n- 0, // dropped\n- 0, // fifo\n- 0, // frame\n- 0, // compressed\n- 0, // multicast\n+ stats[0], // bytes\n+ stats[1], // packets\n+ stats[2], // errors\n+ stats[3], // dropped\n+ stats[4], // fifo\n+ stats[5], // frame\n+ stats[6], // compressed\n+ stats[7], // multicast\n// Transmitted\n- 0, // bytes\n- 0, // packets\n- 0, // errors\n- 0, // dropped\n- 0, // fifo\n- 0, // frame\n- 0, // compressed\n- 0) // multicast\n+ stats[8], // bytes\n+ stats[9], // packets\n+ stats[10], // errors\n+ stats[11], // dropped\n+ stats[12], // fifo\n+ stats[13], // frame\n+ stats[14], // compressed\n+ stats[15]) // multicast\ncontents = append(contents, l)\n}\nvar data []seqfile.SeqData\nfor _, l := range contents {\n- data = append(data, seqfile.SeqData{Buf: []byte(l), Handle: (*ifinet6)(nil)})\n+ data = append(data, seqfile.SeqData{Buf: []byte(l), Handle: (*netDev)(nil)})\n}\nreturn data, 0\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/inet/inet.go",
"new_path": "pkg/sentry/inet/inet.go",
"diff": "@@ -49,6 +49,9 @@ type Stack interface {\n// SetTCPSACKEnabled attempts to change TCP selective acknowledgement\n// settings.\nSetTCPSACKEnabled(enabled bool) error\n+\n+ // Statistics reports stack statistics.\n+ Statistics(stat interface{}, arg string) error\n}\n// Interface contains information about a network interface.\n@@ -102,3 +105,7 @@ type TCPBufferSize struct {\n// Max is the maximum size.\nMax int\n}\n+\n+// StatDev describes one line of /proc/net/dev, i.e., stats for one network\n+// interface.\n+type StatDev [16]uint64\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/inet/test_stack.go",
"new_path": "pkg/sentry/inet/test_stack.go",
"diff": "@@ -81,3 +81,8 @@ func (s *TestStack) SetTCPSACKEnabled(enabled bool) error {\ns.TCPSACKFlag = enabled\nreturn nil\n}\n+\n+// Statistics implements inet.Stack.Statistics.\n+func (s *TestStack) Statistics(stat interface{}, arg string) error {\n+ return nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/epsocket/stack.go",
"new_path": "pkg/sentry/socket/epsocket/stack.go",
"diff": "@@ -138,3 +138,8 @@ func (s *Stack) TCPSACKEnabled() (bool, error) {\nfunc (s *Stack) SetTCPSACKEnabled(enabled bool) error {\nreturn syserr.TranslateNetstackError(s.Stack.SetTransportProtocolOption(tcp.ProtocolNumber, tcp.SACKEnabled(enabled))).ToError()\n}\n+\n+// Statistics implements inet.Stack.Statistics.\n+func (s *Stack) Statistics(stat interface{}, arg string) error {\n+ return syserr.ErrEndpointOperation.ToError()\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/hostinet/stack.go",
"new_path": "pkg/sentry/socket/hostinet/stack.go",
"diff": "@@ -244,3 +244,8 @@ func (s *Stack) TCPSACKEnabled() (bool, error) {\nfunc (s *Stack) SetTCPSACKEnabled(enabled bool) error {\nreturn syserror.EACCES\n}\n+\n+// Statistics implements inet.Stack.Statistics.\n+func (s *Stack) Statistics(stat interface{}, arg string) error {\n+ return syserror.EOPNOTSUPP\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/rpcinet/stack.go",
"new_path": "pkg/sentry/socket/rpcinet/stack.go",
"diff": "@@ -133,3 +133,8 @@ func (s *Stack) TCPSACKEnabled() (bool, error) {\nfunc (s *Stack) SetTCPSACKEnabled(enabled bool) error {\npanic(\"rpcinet handles procfs directly this method should not be called\")\n}\n+\n+// Statistics implements inet.Stack.Statistics.\n+func (s *Stack) Statistics(stat interface{}, arg string) error {\n+ return syserr.ErrEndpointOperation.ToError()\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Support /proc/net/dev
This proc file reports the stats of interfaces. We could use ifconfig
command to check the result.
Signed-off-by: Jianfeng Tan <[email protected]>
Change-Id: Ia7c1e637f5c76c30791ffda68ee61e861b6ef827
COPYBARA_INTEGRATE_REVIEW=https://gvisor-review.googlesource.com/c/gvisor/+/18282/
PiperOrigin-RevId: 258303936 |
259,853 | 16.07.2019 15:05:12 | 25,200 | 89368456d86e2329c46594490c58cfc51c9c7c92 | test/integration: wait a background process
Otherwise this process can be killed before it prints the test message. | [
{
"change_type": "MODIFY",
"old_path": "runsc/test/integration/regression_test.go",
"new_path": "runsc/test/integration/regression_test.go",
"diff": "@@ -32,7 +32,7 @@ func TestBindOverlay(t *testing.T) {\n}\nd := testutil.MakeDocker(\"bind-overlay-test\")\n- cmd := \"nc -l -U /var/run/sock& sleep 1 && echo foobar-asdf | nc -U /var/run/sock\"\n+ cmd := \"nc -l -U /var/run/sock & p=$! && sleep 1 && echo foobar-asdf | nc -U /var/run/sock && wait $p\"\ngot, err := d.RunFg(\"ubuntu:trusty\", \"bash\", \"-c\", cmd)\nif err != nil {\nt.Fatal(\"docker run failed:\", err)\n"
}
] | Go | Apache License 2.0 | google/gvisor | test/integration: wait a background process
Otherwise this process can be killed before it prints the test message.
PiperOrigin-RevId: 258448204 |
259,916 | 16.07.2019 14:03:40 | 25,200 | 02d1bd67f073dd8e99ce591d1285d1bbc152b424 | Add CLOCK_BOOTTIME tests to timerfd.cc | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/timerfd.cc",
"new_path": "test/syscalls/linux/timerfd.cc",
"diff": "@@ -44,21 +44,24 @@ PosixErrorOr<FileDescriptor> TimerfdCreate(int clockid, int flags) {\n//\n// - Because clock_gettime(CLOCK_MONOTONIC) is implemented through the VDSO,\n// it technically uses a closely-related, but distinct, time domain from the\n-// CLOCK_MONOTONIC used to trigger timerfd expirations.\n+// CLOCK_MONOTONIC used to trigger timerfd expirations. The same applies to\n+// CLOCK_BOOTTIME which is an alias for CLOCK_MONOTONIC.\nabsl::Duration TimerSlack() { return absl::Milliseconds(500); }\n-TEST(TimerfdTest, IsInitiallyStopped) {\n- auto const tfd = ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(CLOCK_MONOTONIC, 0));\n+class TimerfdTest : public ::testing::TestWithParam<int> {};\n+\n+TEST_P(TimerfdTest, IsInitiallyStopped) {\n+ auto const tfd = ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(GetParam(), 0));\nstruct itimerspec its = {};\nASSERT_THAT(timerfd_gettime(tfd.get(), &its), SyscallSucceeds());\nEXPECT_EQ(0, its.it_value.tv_sec);\nEXPECT_EQ(0, its.it_value.tv_nsec);\n}\n-TEST(TimerfdTest, SingleShot) {\n+TEST_P(TimerfdTest, SingleShot) {\nconstexpr absl::Duration kDelay = absl::Seconds(1);\n- auto const tfd = ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(CLOCK_MONOTONIC, 0));\n+ auto const tfd = ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(GetParam(), 0));\nstruct itimerspec its = {};\nits.it_value = absl::ToTimespec(kDelay);\nASSERT_THAT(timerfd_settime(tfd.get(), /* flags = */ 0, &its, nullptr),\n@@ -72,11 +75,11 @@ TEST(TimerfdTest, SingleShot) {\nEXPECT_EQ(1, val);\n}\n-TEST(TimerfdTest, Periodic) {\n+TEST_P(TimerfdTest, Periodic) {\nconstexpr absl::Duration kDelay = absl::Seconds(1);\nconstexpr int kPeriods = 3;\n- auto const tfd = ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(CLOCK_MONOTONIC, 0));\n+ auto const tfd = ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(GetParam(), 0));\nstruct itimerspec its = {};\nits.it_value = absl::ToTimespec(kDelay);\nits.it_interval = absl::ToTimespec(kDelay);\n@@ -92,10 +95,10 @@ TEST(TimerfdTest, Periodic) {\nEXPECT_GE(val, kPeriods);\n}\n-TEST(TimerfdTest, BlockingRead) {\n+TEST_P(TimerfdTest, BlockingRead) {\nconstexpr absl::Duration kDelay = absl::Seconds(3);\n- auto const tfd = ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(CLOCK_MONOTONIC, 0));\n+ auto const tfd = ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(GetParam(), 0));\nstruct itimerspec its = {};\nits.it_value.tv_sec = absl::ToInt64Seconds(kDelay);\nauto const start_time = absl::Now();\n@@ -111,11 +114,11 @@ TEST(TimerfdTest, BlockingRead) {\nEXPECT_GE((end_time - start_time) + TimerSlack(), kDelay);\n}\n-TEST(TimerfdTest, NonblockingRead_NoRandomSave) {\n+TEST_P(TimerfdTest, NonblockingRead_NoRandomSave) {\nconstexpr absl::Duration kDelay = absl::Seconds(5);\nauto const tfd =\n- ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(CLOCK_MONOTONIC, TFD_NONBLOCK));\n+ ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(GetParam(), TFD_NONBLOCK));\n// Since the timer is initially disabled and has never fired, read should\n// return EAGAIN.\n@@ -148,11 +151,11 @@ TEST(TimerfdTest, NonblockingRead_NoRandomSave) {\nSyscallFailsWithErrno(EAGAIN));\n}\n-TEST(TimerfdTest, BlockingPoll_SetTimeResetsExpirations) {\n+TEST_P(TimerfdTest, BlockingPoll_SetTimeResetsExpirations) {\nconstexpr absl::Duration kDelay = absl::Seconds(3);\nauto const tfd =\n- ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(CLOCK_MONOTONIC, TFD_NONBLOCK));\n+ ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(GetParam(), TFD_NONBLOCK));\nstruct itimerspec its = {};\nits.it_value.tv_sec = absl::ToInt64Seconds(kDelay);\nauto const start_time = absl::Now();\n@@ -181,15 +184,15 @@ TEST(TimerfdTest, BlockingPoll_SetTimeResetsExpirations) {\nSyscallFailsWithErrno(EAGAIN));\n}\n-TEST(TimerfdTest, SetAbsoluteTime) {\n+TEST_P(TimerfdTest, SetAbsoluteTime) {\nconstexpr absl::Duration kDelay = absl::Seconds(3);\n// Use a non-blocking timerfd so that if TFD_TIMER_ABSTIME is incorrectly\n// non-functional, we get EAGAIN rather than a test timeout.\nauto const tfd =\n- ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(CLOCK_MONOTONIC, TFD_NONBLOCK));\n+ ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(GetParam(), TFD_NONBLOCK));\nstruct itimerspec its = {};\n- ASSERT_THAT(clock_gettime(CLOCK_MONOTONIC, &its.it_value), SyscallSucceeds());\n+ ASSERT_THAT(clock_gettime(GetParam(), &its.it_value), SyscallSucceeds());\nits.it_value.tv_sec += absl::ToInt64Seconds(kDelay);\nASSERT_THAT(timerfd_settime(tfd.get(), TFD_TIMER_ABSTIME, &its, nullptr),\nSyscallSucceeds());\n@@ -201,7 +204,35 @@ TEST(TimerfdTest, SetAbsoluteTime) {\nEXPECT_EQ(1, val);\n}\n-TEST(TimerfdTest, ClockRealtime) {\n+TEST_P(TimerfdTest, IllegalReadWrite) {\n+ auto const tfd =\n+ ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(GetParam(), TFD_NONBLOCK));\n+ uint64_t val = 0;\n+ EXPECT_THAT(PreadFd(tfd.get(), &val, sizeof(val), 0),\n+ SyscallFailsWithErrno(ESPIPE));\n+ EXPECT_THAT(WriteFd(tfd.get(), &val, sizeof(val)),\n+ SyscallFailsWithErrno(EINVAL));\n+ EXPECT_THAT(PwriteFd(tfd.get(), &val, sizeof(val), 0),\n+ SyscallFailsWithErrno(ESPIPE));\n+}\n+\n+std::string PrintClockId(::testing::TestParamInfo<int> info) {\n+ switch (info.param) {\n+ case CLOCK_MONOTONIC:\n+ return \"CLOCK_MONOTONIC\";\n+ case CLOCK_BOOTTIME:\n+ return \"CLOCK_BOOTTIME\";\n+ default:\n+ return absl::StrCat(info.param);\n+ }\n+}\n+\n+INSTANTIATE_TEST_SUITE_P(AllTimerTypes,\n+ TimerfdTest,\n+ ::testing::Values(CLOCK_MONOTONIC, CLOCK_BOOTTIME),\n+ PrintClockId);\n+\n+TEST(TimerfdClockRealtimeTest, ClockRealtime) {\n// Since CLOCK_REALTIME can, by definition, change, we can't make any\n// non-flaky assertions about the amount of time it takes for a\n// CLOCK_REALTIME-based timer to expire. Just check that it expires at all,\n@@ -220,18 +251,6 @@ TEST(TimerfdTest, ClockRealtime) {\nEXPECT_EQ(1, val);\n}\n-TEST(TimerfdTest, IllegalReadWrite) {\n- auto const tfd =\n- ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(CLOCK_MONOTONIC, TFD_NONBLOCK));\n- uint64_t val = 0;\n- EXPECT_THAT(PreadFd(tfd.get(), &val, sizeof(val), 0),\n- SyscallFailsWithErrno(ESPIPE));\n- EXPECT_THAT(WriteFd(tfd.get(), &val, sizeof(val)),\n- SyscallFailsWithErrno(EINVAL));\n- EXPECT_THAT(PwriteFd(tfd.get(), &val, sizeof(val), 0),\n- SyscallFailsWithErrno(ESPIPE));\n-}\n-\n} // namespace\n} // namespace testing\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add CLOCK_BOOTTIME tests to timerfd.cc |
259,881 | 17.07.2019 11:13:37 | 25,200 | ca829158e385c591d4be21c87cc6ab45116a7cce | Properly invalidate cache in rename and remove
We were invalidating the wrong overlayEntry in rename and missing invalidation
in rename and remove if lower exists. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/inode_overlay.go",
"new_path": "pkg/sentry/fs/inode_overlay.go",
"diff": "@@ -339,7 +339,9 @@ func overlayRemove(ctx context.Context, o *overlayEntry, parent *Dirent, child *\n}\n}\nif child.Inode.overlay.lowerExists {\n- return overlayCreateWhiteout(o.upper, child.name)\n+ if err := overlayCreateWhiteout(o.upper, child.name); err != nil {\n+ return err\n+ }\n}\n// We've removed from the directory so we must drop the cache.\no.markDirectoryDirty()\n@@ -418,10 +420,12 @@ func overlayRename(ctx context.Context, o *overlayEntry, oldParent *Dirent, rena\nreturn err\n}\nif renamed.Inode.overlay.lowerExists {\n- return overlayCreateWhiteout(oldParent.Inode.overlay.upper, oldName)\n+ if err := overlayCreateWhiteout(oldParent.Inode.overlay.upper, oldName); err != nil {\n+ return err\n+ }\n}\n// We've changed the directory so we must drop the cache.\n- o.markDirectoryDirty()\n+ oldParent.Inode.overlay.markDirectoryDirty()\nreturn nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/getdents.cc",
"new_path": "test/syscalls/linux/getdents.cc",
"diff": "#include \"test/util/temp_path.h\"\n#include \"test/util/test_util.h\"\n+using ::testing::Contains;\nusing ::testing::IsEmpty;\nusing ::testing::IsSupersetOf;\nusing ::testing::Not;\n@@ -484,6 +485,44 @@ TEST(ReaddirTest, Bug35110122Root) {\nEXPECT_THAT(contents, Not(IsEmpty()));\n}\n+// Unlink should invalidate getdents cache.\n+TEST(ReaddirTest, GoneAfterRemoveCache) {\n+ TempPath dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(dir.path()));\n+ std::string name = std::string(Basename(file.path()));\n+\n+ auto contents = ASSERT_NO_ERRNO_AND_VALUE(ListDir(dir.path(), true));\n+ EXPECT_THAT(contents, Contains(name));\n+\n+ file.reset();\n+\n+ contents = ASSERT_NO_ERRNO_AND_VALUE(ListDir(dir.path(), true));\n+ EXPECT_THAT(contents, Not(Contains(name)));\n+}\n+\n+// Regression test for b/137398511. Rename should invalidate getdents cache.\n+TEST(ReaddirTest, GoneAfterRenameCache) {\n+ TempPath src = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ TempPath dst = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+\n+ TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(src.path()));\n+ std::string name = std::string(Basename(file.path()));\n+\n+ auto contents = ASSERT_NO_ERRNO_AND_VALUE(ListDir(src.path(), true));\n+ EXPECT_THAT(contents, Contains(name));\n+\n+ ASSERT_THAT(rename(file.path().c_str(), JoinPath(dst.path(), name).c_str()),\n+ SyscallSucceeds());\n+ // Release file since it was renamed. dst cleanup will ultimately delete it.\n+ file.release();\n+\n+ contents = ASSERT_NO_ERRNO_AND_VALUE(ListDir(src.path(), true));\n+ EXPECT_THAT(contents, Not(Contains(name)));\n+\n+ contents = ASSERT_NO_ERRNO_AND_VALUE(ListDir(dst.path(), true));\n+ EXPECT_THAT(contents, Contains(name));\n+}\n+\n} // namespace\n} // namespace testing\n"
}
] | Go | Apache License 2.0 | google/gvisor | Properly invalidate cache in rename and remove
We were invalidating the wrong overlayEntry in rename and missing invalidation
in rename and remove if lower exists.
PiperOrigin-RevId: 258604685 |
259,891 | 17.07.2019 11:47:59 | 25,200 | 9f1189130ed8c9172700a76fd5796b7319fbb8b9 | Add AF_UNIX, SOCK_RAW sockets, which exist for some reason.
tcpdump creates these. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/unix.go",
"new_path": "pkg/sentry/socket/unix/unix.go",
"diff": "@@ -68,6 +68,12 @@ func New(ctx context.Context, endpoint transport.Endpoint, stype linux.SockType)\n// NewWithDirent creates a new unix socket using an existing dirent.\nfunc NewWithDirent(ctx context.Context, d *fs.Dirent, ep transport.Endpoint, stype linux.SockType, flags fs.FileFlags) *fs.File {\n+ // You can create AF_UNIX, SOCK_RAW sockets. They're the same as\n+ // SOCK_DGRAM and don't require CAP_NET_RAW.\n+ if stype == linux.SOCK_RAW {\n+ stype = linux.SOCK_DGRAM\n+ }\n+\ns := SocketOperations{\nep: ep,\nstype: stype,\n@@ -639,7 +645,7 @@ func (*provider) Socket(t *kernel.Task, stype linux.SockType, protocol int) (*fs\n// Create the endpoint and socket.\nvar ep transport.Endpoint\nswitch stype {\n- case linux.SOCK_DGRAM:\n+ case linux.SOCK_DGRAM, linux.SOCK_RAW:\nep = transport.NewConnectionless(t)\ncase linux.SOCK_SEQPACKET, linux.SOCK_STREAM:\nep = transport.NewConnectioned(t, stype, t.Kernel())\n@@ -658,7 +664,7 @@ func (*provider) Pair(t *kernel.Task, stype linux.SockType, protocol int) (*fs.F\n}\nswitch stype {\n- case linux.SOCK_STREAM, linux.SOCK_DGRAM, linux.SOCK_SEQPACKET:\n+ case linux.SOCK_STREAM, linux.SOCK_DGRAM, linux.SOCK_SEQPACKET, linux.SOCK_RAW:\n// Ok\ndefault:\nreturn nil, nil, syserr.ErrInvalidArgument\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_unix_dgram_local.cc",
"new_path": "test/syscalls/linux/socket_unix_dgram_local.cc",
"diff": "@@ -28,15 +28,15 @@ std::vector<SocketPairKind> GetSocketPairs() {\nreturn VecCat<SocketPairKind>(VecCat<SocketPairKind>(\nApplyVec<SocketPairKind>(\nUnixDomainSocketPair,\n- AllBitwiseCombinations(List<int>{SOCK_DGRAM},\n+ AllBitwiseCombinations(List<int>{SOCK_DGRAM, SOCK_RAW},\nList<int>{0, SOCK_NONBLOCK})),\nApplyVec<SocketPairKind>(\nFilesystemBoundUnixDomainSocketPair,\n- AllBitwiseCombinations(List<int>{SOCK_DGRAM},\n+ AllBitwiseCombinations(List<int>{SOCK_DGRAM, SOCK_RAW},\nList<int>{0, SOCK_NONBLOCK})),\nApplyVec<SocketPairKind>(\nAbstractBoundUnixDomainSocketPair,\n- AllBitwiseCombinations(List<int>{SOCK_DGRAM},\n+ AllBitwiseCombinations(List<int>{SOCK_DGRAM, SOCK_RAW},\nList<int>{0, SOCK_NONBLOCK}))));\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add AF_UNIX, SOCK_RAW sockets, which exist for some reason.
tcpdump creates these.
PiperOrigin-RevId: 258611829 |
259,962 | 17.07.2019 13:55:32 | 25,200 | 542fbd01a7ed38baca941f88c0b254adef691188 | Fix race in FDTable.GetFDs(). | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/fd_table.go",
"new_path": "pkg/sentry/kernel/fd_table.go",
"diff": "@@ -81,7 +81,9 @@ type FDTable struct {\n// mu protects below.\nmu sync.Mutex `state:\"nosave\"`\n- // used contains the number of non-nil entries.\n+ // used contains the number of non-nil entries. It must be accessed\n+ // atomically. It may be read atomically without holding mu (but not\n+ // written).\nused int32\n// descriptorTable holds descriptors.\n@@ -317,7 +319,7 @@ func (f *FDTable) Get(fd int32) (*fs.File, FDFlags) {\n// GetFDs returns a list of valid fds.\nfunc (f *FDTable) GetFDs() []int32 {\n- fds := make([]int32, 0, f.used)\n+ fds := make([]int32, 0, int(atomic.LoadInt32(&f.used)))\nf.forEach(func(fd int32, file *fs.File, flags FDFlags) {\nfds = append(fds, fd)\n})\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix race in FDTable.GetFDs().
PiperOrigin-RevId: 258635459 |
259,907 | 17.07.2019 14:46:57 | 25,200 | 8e3e021aca89427381af75a47f19b1fe78bf132e | ext: Filesystem init implementation. | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/fs.go",
"new_path": "pkg/abi/linux/fs.go",
"diff": "@@ -20,6 +20,7 @@ package linux\nconst (\nANON_INODE_FS_MAGIC = 0x09041934\nDEVPTS_SUPER_MAGIC = 0x00001cd1\n+ EXT_SUPER_MAGIC = 0xef53\nOVERLAYFS_SUPER_MAGIC = 0x794c7630\nPIPEFS_MAGIC = 0x50495045\nPROC_SUPER_MAGIC = 0x9fa0\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/BUILD",
"new_path": "pkg/sentry/fs/ext/BUILD",
"diff": "@@ -4,8 +4,15 @@ load(\"//tools/go_stateify:defs.bzl\", \"go_library\")\ngo_library(\nname = \"ext\",\n- srcs = [\"ext.go\"],\n+ srcs = [\n+ \"ext.go\",\n+ \"utils.go\",\n+ ],\nimportpath = \"gvisor.dev/gvisor/pkg/sentry/fs/ext\",\nvisibility = [\"//pkg/sentry:internal\"],\n- deps = [\"//pkg/sentry/fs/ext/disklayout\"],\n+ deps = [\n+ \"//pkg/abi/linux\",\n+ \"//pkg/sentry/fs/ext/disklayout\",\n+ \"//pkg/syserror\",\n+ ],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/disklayout/block_group.go",
"new_path": "pkg/sentry/fs/ext/disklayout/block_group.go",
"diff": "@@ -18,6 +18,16 @@ package disklayout\n// is split into a series of block groups. This provides an access layer to\n// information needed to access and use a block group.\n//\n+// Location:\n+// - The block group descriptor table is always placed in the blocks\n+// immediately after the block containing the superblock.\n+// - The 1st block group descriptor in the original table is in the\n+// (sb.FirstDataBlock() + 1)th block.\n+// - See SuperBlock docs to see where the block group descriptor table is\n+// replicated.\n+// - sb.BgDescSize() must be used as the block group descriptor entry size\n+// while reading the table from disk.\n+//\n// See https://www.kernel.org/doc/html/latest/filesystems/ext4/globals.html#block-group-descriptors.\ntype BlockGroup interface {\n// InodeTable returns the absolute block number of the block containing the\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/disklayout/superblock.go",
"new_path": "pkg/sentry/fs/ext/disklayout/superblock.go",
"diff": "package disklayout\n+const (\n+ // SbOffset is the absolute offset at which the superblock is placed.\n+ SbOffset = 1024\n+)\n+\n// SuperBlock should be implemented by structs representing the ext superblock.\n// The superblock holds a lot of information about the enclosing filesystem.\n// This interface aims to provide access methods to important information held\n@@ -57,8 +62,6 @@ type SuperBlock interface {\n//\n// If the filesystem has 1kb data blocks then this should return 1. For all\n// other configurations, this typically returns 0.\n- //\n- // The first block group descriptor is in (FirstDataBlock() + 1)th block.\nFirstDataBlock() uint32\n// BlockSize returns the size of one data block in this filesystem.\n@@ -128,7 +131,7 @@ type SuperBlock interface {\n}\n// SbRevision is the type for superblock revisions.\n-type SbRevision int\n+type SbRevision uint32\n// Super block revisions.\nconst (\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/disklayout/superblock_old.go",
"new_path": "pkg/sentry/fs/ext/disklayout/superblock_old.go",
"diff": "@@ -44,6 +44,9 @@ type SuperBlockOld struct {\nDefResGID uint16\n}\n+// Compiles only if SuperBlockOld implements SuperBlock.\n+var _ SuperBlock = (*SuperBlockOld)(nil)\n+\n// InodesCount implements SuperBlock.InodesCount.\nfunc (sb *SuperBlockOld) InodesCount() uint32 { return sb.InodesCountRaw }\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/ext.go",
"new_path": "pkg/sentry/fs/ext/ext.go",
"diff": "@@ -19,7 +19,9 @@ import (\n\"io\"\n\"sync\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/sentry/fs/ext/disklayout\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n)\n// Filesystem implements vfs.FilesystemImpl.\n@@ -47,3 +49,27 @@ type Filesystem struct {\n// Immutable after initialization.\nbgs []disklayout.BlockGroup\n}\n+\n+// newFilesystem is the Filesystem constructor.\n+func newFilesystem(dev io.ReadSeeker) (*Filesystem, error) {\n+ fs := Filesystem{dev: dev}\n+ var err error\n+\n+ fs.sb, err = readSuperBlock(dev)\n+ if err != nil {\n+ return nil, err\n+ }\n+\n+ if fs.sb.Magic() != linux.EXT_SUPER_MAGIC {\n+ // mount(2) specifies that EINVAL should be returned if the superblock is\n+ // invalid.\n+ return nil, syserror.EINVAL\n+ }\n+\n+ fs.bgs, err = readBlockGroups(dev, fs.sb)\n+ if err != nil {\n+ return nil, err\n+ }\n+\n+ return &fs, nil\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext/utils.go",
"diff": "+// Copyright 2019 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 ext\n+\n+import (\n+ \"encoding/binary\"\n+ \"io\"\n+\n+ \"gvisor.dev/gvisor/pkg/sentry/fs/ext/disklayout\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+)\n+\n+// readFromDisk performs a binary read from disk into the given struct from\n+// the absolute offset provided.\n+//\n+// All disk reads should use this helper so we avoid reading from stale\n+// previously used offsets. This function forces the offset parameter.\n+func readFromDisk(dev io.ReadSeeker, abOff int64, v interface{}) error {\n+ if _, err := dev.Seek(abOff, io.SeekStart); err != nil {\n+ return syserror.EIO\n+ }\n+\n+ if err := binary.Read(dev, binary.LittleEndian, v); err != nil {\n+ return syserror.EIO\n+ }\n+\n+ return nil\n+}\n+\n+// readSuperBlock reads the SuperBlock from block group 0 in the underlying\n+// device. There are three versions of the superblock. This function identifies\n+// and returns the correct version.\n+func readSuperBlock(dev io.ReadSeeker) (disklayout.SuperBlock, error) {\n+ var sb disklayout.SuperBlock = &disklayout.SuperBlockOld{}\n+ if err := readFromDisk(dev, disklayout.SbOffset, sb); err != nil {\n+ return nil, err\n+ }\n+ if sb.Revision() == disklayout.OldRev {\n+ return sb, nil\n+ }\n+\n+ sb = &disklayout.SuperBlock32Bit{}\n+ if err := readFromDisk(dev, disklayout.SbOffset, sb); err != nil {\n+ return nil, err\n+ }\n+ if !sb.IncompatibleFeatures().Is64Bit {\n+ return sb, nil\n+ }\n+\n+ sb = &disklayout.SuperBlock64Bit{}\n+ if err := readFromDisk(dev, disklayout.SbOffset, sb); err != nil {\n+ return nil, err\n+ }\n+ return sb, nil\n+}\n+\n+// blockGroupsCount returns the number of block groups in the ext fs.\n+func blockGroupsCount(sb disklayout.SuperBlock) uint64 {\n+ blocksCount := sb.BlocksCount()\n+ blocksPerGroup := uint64(sb.BlocksPerGroup())\n+\n+ // Round up the result. float64 can compromise precision so do it manually.\n+ bgCount := blocksCount / blocksPerGroup\n+ if blocksCount%blocksPerGroup != 0 {\n+ bgCount++\n+ }\n+\n+ return bgCount\n+}\n+\n+// readBlockGroups reads the block group descriptor table from block group 0 in\n+// the underlying device.\n+func readBlockGroups(dev io.ReadSeeker, sb disklayout.SuperBlock) ([]disklayout.BlockGroup, error) {\n+ bgCount := blockGroupsCount(sb)\n+ bgdSize := uint64(sb.BgDescSize())\n+ is64Bit := sb.IncompatibleFeatures().Is64Bit\n+ bgds := make([]disklayout.BlockGroup, bgCount)\n+\n+ for i, off := uint64(0), uint64(sb.FirstDataBlock()+1)*sb.BlockSize(); i < bgCount; i, off = i+1, off+bgdSize {\n+ if is64Bit {\n+ bgds[i] = &disklayout.BlockGroup64Bit{}\n+ } else {\n+ bgds[i] = &disklayout.BlockGroup32Bit{}\n+ }\n+\n+ if err := readFromDisk(dev, int64(off), bgds[i]); err != nil {\n+ return nil, err\n+ }\n+ }\n+ return bgds, nil\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | ext: Filesystem init implementation.
PiperOrigin-RevId: 258645957 |
259,907 | 17.07.2019 15:47:45 | 25,200 | 84a59de5dc3a0b8a260c942958cd91e014dc8d9b | ext: disklayout: extents support. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/disklayout/BUILD",
"new_path": "pkg/sentry/fs/ext/disklayout/BUILD",
"diff": "@@ -12,6 +12,7 @@ go_library(\n\"dirent_new.go\",\n\"dirent_old.go\",\n\"disklayout.go\",\n+ \"extent.go\",\n\"inode.go\",\n\"inode_new.go\",\n\"inode_old.go\",\n@@ -38,6 +39,7 @@ go_test(\nsrcs = [\n\"block_group_test.go\",\n\"dirent_test.go\",\n+ \"extent_test.go\",\n\"inode_test.go\",\n\"superblock_test.go\",\n],\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext/disklayout/extent.go",
"diff": "+// Copyright 2019 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 disklayout\n+\n+// Extents were introduced in ext4 and provide huge performance gains in terms\n+// data locality and reduced metadata block usage. Extents are organized in\n+// extent trees. The root node is contained in inode.BlocksRaw.\n+//\n+// Terminology:\n+// - Physical Block:\n+// Filesystem data block which is addressed normally wrt the entire\n+// filesystem (addressed with 48 bits).\n+//\n+// - File Block:\n+// Data block containing *only* file data and addressed wrt to the file\n+// with only 32 bits. The (i)th file block contains file data from\n+// byte (i * sb.BlockSize()) to ((i+1) * sb.BlockSize()).\n+\n+const (\n+ // ExtentStructsSize is the size of all the three extent on-disk structs.\n+ ExtentStructsSize = 12\n+\n+ // ExtentMagic is the magic number which must be present in the header.\n+ ExtentMagic = 0xf30a\n+)\n+\n+// ExtentEntryPair couples an in-memory ExtendNode with the ExtentEntry that\n+// points to it. We want to cache these structs in memory to avoid repeated\n+// disk reads.\n+//\n+// Note: This struct itself does not represent an on-disk struct.\n+type ExtentEntryPair struct {\n+ // Entry points to the child node on disk.\n+ Entry ExtentEntry\n+ // Node points to child node in memory. Is nil if the current node is a leaf.\n+ Node *ExtentNode\n+}\n+\n+// ExtentNode represents an extent tree node. For internal nodes, all Entries\n+// will be ExtendIdxs. For leaf nodes, they will all be Extents.\n+//\n+// Note: This struct itself does not represent an on-disk struct.\n+type ExtentNode struct {\n+ Header ExtentHeader\n+ Entries []ExtentEntryPair\n+}\n+\n+// ExtentEntry reprsents an extent tree node entry. The entry can either be\n+// an ExtentIdx or Extent itself. This exists to simplify navigation logic.\n+type ExtentEntry interface {\n+ // FileBlock returns the first file block number covered by this entry.\n+ FileBlock() uint32\n+\n+ // PhysicalBlock returns the child physical block that this entry points to.\n+ PhysicalBlock() uint64\n+}\n+\n+// ExtentHeader emulates the ext4_extent_header struct in ext4. Each extent\n+// tree node begins with this and is followed by `NumEntries` number of:\n+// - Extent if `Depth` == 0\n+// - ExtentIdx otherwise\n+type ExtentHeader struct {\n+ // Magic in the extent magic number, must be 0xf30a.\n+ Magic uint16\n+\n+ // NumEntries indicates the number of valid entries following the header.\n+ NumEntries uint16\n+\n+ // MaxEntries that could follow the header. Used while adding entries.\n+ MaxEntries uint16\n+\n+ // Height represents the distance of this node from the farthest leaf. Please\n+ // note that Linux incorrectly calls this `Depth` (which means the distance\n+ // of the node from the root).\n+ Height uint16\n+ _ uint32\n+}\n+\n+// ExtentIdx emulates the ext4_extent_idx struct in ext4. Only present in\n+// internal nodes. Sorted in ascending order based on FirstFileBlock since\n+// Linux does a binary search on this. This points to a block containing the\n+// child node.\n+type ExtentIdx struct {\n+ FirstFileBlock uint32\n+ ChildBlockLo uint32\n+ ChildBlockHi uint16\n+ _ uint16\n+}\n+\n+// Compiles only if ExtentIdx implements ExtentEntry.\n+var _ ExtentEntry = (*ExtentIdx)(nil)\n+\n+// FileBlock implements ExtentEntry.FileBlock.\n+func (ei *ExtentIdx) FileBlock() uint32 {\n+ return ei.FirstFileBlock\n+}\n+\n+// PhysicalBlock implements ExtentEntry.PhysicalBlock. It returns the\n+// physical block number of the child block.\n+func (ei *ExtentIdx) PhysicalBlock() uint64 {\n+ return (uint64(ei.ChildBlockHi) << 32) | uint64(ei.ChildBlockLo)\n+}\n+\n+// Extent represents the ext4_extent struct in ext4. Only present in leaf\n+// nodes. Sorted in ascending order based on FirstFileBlock since Linux does a\n+// binary search on this. This points to an array of data blocks containing the\n+// file data. It covers `Length` data blocks starting from `StartBlock`.\n+type Extent struct {\n+ FirstFileBlock uint32\n+ Length uint16\n+ StartBlockHi uint16\n+ StartBlockLo uint32\n+}\n+\n+// Compiles only if Extent implements ExtentEntry.\n+var _ ExtentEntry = (*Extent)(nil)\n+\n+// FileBlock implements ExtentEntry.FileBlock.\n+func (e *Extent) FileBlock() uint32 {\n+ return e.FirstFileBlock\n+}\n+\n+// PhysicalBlock implements ExtentEntry.PhysicalBlock. It returns the\n+// physical block number of the first data block this extent covers.\n+func (e *Extent) PhysicalBlock() uint64 {\n+ return (uint64(e.StartBlockHi) << 32) | uint64(e.StartBlockLo)\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext/disklayout/extent_test.go",
"diff": "+// Copyright 2019 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 disklayout\n+\n+import (\n+ \"testing\"\n+)\n+\n+// TestExtentSize tests that the extent structs are of the correct\n+// size.\n+func TestExtentSize(t *testing.T) {\n+ assertSize(t, ExtentHeader{}, ExtentStructsSize)\n+ assertSize(t, ExtentIdx{}, ExtentStructsSize)\n+ assertSize(t, Extent{}, ExtentStructsSize)\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | ext: disklayout: extents support.
PiperOrigin-RevId: 258657776 |
259,885 | 17.07.2019 15:48:33 | 25,200 | 2bc398bfd8fbe38776a512329bd0c40c9c7a5cdf | Separate O_DSYNC and O_SYNC. | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/file.go",
"new_path": "pkg/abi/linux/file.go",
"diff": "@@ -34,13 +34,14 @@ const (\nO_TRUNC = 00001000\nO_APPEND = 00002000\nO_NONBLOCK = 00004000\n+ O_DSYNC = 00010000\nO_ASYNC = 00020000\nO_DIRECT = 00040000\nO_LARGEFILE = 00100000\nO_DIRECTORY = 00200000\nO_NOFOLLOW = 00400000\nO_CLOEXEC = 02000000\n- O_SYNC = 04010000\n+ O_SYNC = 04000000\nO_PATH = 010000000\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/flags.go",
"new_path": "pkg/sentry/fs/flags.go",
"diff": "@@ -28,7 +28,11 @@ type FileFlags struct {\n// NonBlocking indicates that I/O should not block.\nNonBlocking bool\n- // Sync indicates that any writes should be synchronous.\n+ // DSync indicates that each write will flush data and metadata required to\n+ // read the file's contents.\n+ DSync bool\n+\n+ // Sync indicates that each write will flush data and all file metadata.\nSync bool\n// Append indicates this file is append only.\n@@ -96,6 +100,9 @@ func (f FileFlags) ToLinux() (mask uint) {\nif f.NonBlocking {\nmask |= linux.O_NONBLOCK\n}\n+ if f.DSync {\n+ mask |= linux.O_DSYNC\n+ }\nif f.Sync {\nmask |= linux.O_SYNC\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/flags.go",
"new_path": "pkg/sentry/syscalls/linux/flags.go",
"diff": "@@ -41,6 +41,7 @@ func flagsToPermissions(mask uint) (p fs.PermMask) {\nfunc linuxToFlags(mask uint) fs.FileFlags {\nreturn fs.FileFlags{\nDirect: mask&linux.O_DIRECT != 0,\n+ DSync: mask&(linux.O_DSYNC|linux.O_SYNC) != 0,\nSync: mask&linux.O_SYNC != 0,\nNonBlocking: mask&linux.O_NONBLOCK != 0,\nRead: (mask & linux.O_ACCMODE) != linux.O_WRONLY,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Separate O_DSYNC and O_SYNC.
PiperOrigin-RevId: 258657913 |
259,881 | 17.07.2019 16:10:44 | 25,200 | 6f7e2bb388cb29a355dece8921671c0085f53ea9 | Take copyMu in Revalidate
copyMu is required to read child.overlay.upper. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/mount_overlay.go",
"new_path": "pkg/sentry/fs/mount_overlay.go",
"diff": "@@ -66,13 +66,17 @@ func (o *overlayMountSourceOperations) Revalidate(ctx context.Context, name stri\npanic(\"an overlay cannot revalidate file objects from the lower fs\")\n}\n- // Do we have anything to revalidate?\n- if child.overlay.upper == nil {\n- return false\n- }\n-\n+ var revalidate bool\n+ child.overlay.copyMu.RLock()\n+ if child.overlay.upper != nil {\n// Does the upper require revalidation?\n- return o.upper.Revalidate(ctx, name, parent.overlay.upper, child.overlay.upper)\n+ revalidate = o.upper.Revalidate(ctx, name, parent.overlay.upper, child.overlay.upper)\n+ } else {\n+ // Nothing to revalidate.\n+ revalidate = false\n+ }\n+ child.overlay.copyMu.RUnlock()\n+ return revalidate\n}\n// Keep implements MountSourceOperations by delegating to the upper\n"
}
] | Go | Apache License 2.0 | google/gvisor | Take copyMu in Revalidate
copyMu is required to read child.overlay.upper.
PiperOrigin-RevId: 258662209 |
259,916 | 17.07.2019 20:25:18 | 25,200 | 2d11fa05f7b705f74c737f5a59fe40414bb6f8d8 | sys_time: Wrap comments to 80 columns | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_time.go",
"new_path": "pkg/sentry/syscalls/linux/sys_time.go",
"diff": "@@ -125,9 +125,11 @@ func getClock(t *kernel.Task, clockID int32) (ktime.Clock, error) {\nlinux.CLOCK_MONOTONIC_RAW, linux.CLOCK_BOOTTIME:\n// CLOCK_MONOTONIC approximates CLOCK_MONOTONIC_RAW.\n// CLOCK_BOOTTIME is internally mapped to CLOCK_MONOTONIC, as:\n- // - CLOCK_BOOTTIME should behave as CLOCK_MONOTONIC while also including suspend time.\n+ // - CLOCK_BOOTTIME should behave as CLOCK_MONOTONIC while also\n+ // including suspend time.\n// - gVisor has no concept of suspend/resume.\n- // - CLOCK_MONOTONIC already includes save/restore time, which is the closest to suspend time.\n+ // - CLOCK_MONOTONIC already includes save/restore time, which is\n+ // the closest to suspend time.\nreturn t.Kernel().MonotonicClock(), nil\ncase linux.CLOCK_PROCESS_CPUTIME_ID:\nreturn t.ThreadGroup().CPUClock(), nil\n"
}
] | Go | Apache License 2.0 | google/gvisor | sys_time: Wrap comments to 80 columns |
259,853 | 18.07.2019 15:39:47 | 25,200 | eefa817cfdb04ff07e7069396f21bd6ba2c89957 | net/tcp/setockopt: impelment setsockopt(fd, SOL_TCP, TCP_INQ) | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/control/control.go",
"new_path": "pkg/sentry/socket/control/control.go",
"diff": "@@ -225,14 +225,14 @@ func putCmsg(buf []byte, flags int, msgType uint32, align uint, data []int32) ([\nreturn alignSlice(buf, align), flags\n}\n-func putCmsgStruct(buf []byte, msgType uint32, align uint, data interface{}) []byte {\n+func putCmsgStruct(buf []byte, msgLevel, msgType uint32, align uint, data interface{}) []byte {\nif cap(buf)-len(buf) < linux.SizeOfControlMessageHeader {\nreturn buf\n}\nob := buf\nbuf = putUint64(buf, uint64(linux.SizeOfControlMessageHeader))\n- buf = putUint32(buf, linux.SOL_SOCKET)\n+ buf = putUint32(buf, msgLevel)\nbuf = putUint32(buf, msgType)\nhdrBuf := buf\n@@ -307,12 +307,24 @@ func alignSlice(buf []byte, align uint) []byte {\nfunc PackTimestamp(t *kernel.Task, timestamp int64, buf []byte) []byte {\nreturn putCmsgStruct(\nbuf,\n+ linux.SOL_SOCKET,\nlinux.SO_TIMESTAMP,\nt.Arch().Width(),\nlinux.NsecToTimeval(timestamp),\n)\n}\n+// PackInq packs a TCP_INQ socket control message.\n+func PackInq(t *kernel.Task, inq int32, buf []byte) []byte {\n+ return putCmsgStruct(\n+ buf,\n+ linux.SOL_TCP,\n+ linux.TCP_INQ,\n+ 4,\n+ inq,\n+ )\n+}\n+\n// Parse parses a raw socket control message into portable objects.\nfunc Parse(t *kernel.Task, socketOrEndpoint interface{}, buf []byte) (transport.ControlMessages, error) {\nvar (\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/epsocket/epsocket.go",
"new_path": "pkg/sentry/socket/epsocket/epsocket.go",
"diff": "@@ -207,6 +207,10 @@ type commonEndpoint interface {\n// GetSockOpt implements tcpip.Endpoint.GetSockOpt and\n// transport.Endpoint.GetSockOpt.\nGetSockOpt(interface{}) *tcpip.Error\n+\n+ // GetSockOptInt implements tcpip.Endpoint.GetSockOptInt and\n+ // transport.Endpoint.GetSockOpt.\n+ GetSockOptInt(opt tcpip.SockOpt) (int, *tcpip.Error)\n}\n// SocketOperations encapsulates all the state needed to represent a network stack\n@@ -249,6 +253,10 @@ type SocketOperations struct {\n// timestampNS holds the timestamp to use with SIOCTSTAMP. It is only\n// valid when timestampValid is true. It is protected by readMu.\ntimestampNS int64\n+\n+ // sockOptInq corresponds to TCP_INQ. It is implemented on the epsocket\n+ // level, because it takes into account data from readView.\n+ sockOptInq bool\n}\n// New creates a new endpoint socket.\n@@ -634,6 +642,18 @@ func (s *SocketOperations) GetSockOpt(t *kernel.Task, level, name, outLen int) (\n}\nreturn val, nil\n}\n+ if level == linux.SOL_TCP && name == linux.TCP_INQ {\n+ if outLen < sizeOfInt32 {\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+ val := int32(0)\n+ s.readMu.Lock()\n+ defer s.readMu.Unlock()\n+ if s.sockOptInq {\n+ val = 1\n+ }\n+ return val, nil\n+ }\nreturn GetSockOpt(t, s, s.Endpoint, s.family, s.skType, level, name, outLen)\n}\n@@ -1048,6 +1068,15 @@ func (s *SocketOperations) SetSockOpt(t *kernel.Task, level int, name int, optVa\ns.sockOptTimestamp = usermem.ByteOrder.Uint32(optVal) != 0\nreturn nil\n}\n+ if level == linux.SOL_TCP && name == linux.TCP_INQ {\n+ if len(optVal) < sizeOfInt32 {\n+ return syserr.ErrInvalidArgument\n+ }\n+ s.readMu.Lock()\n+ defer s.readMu.Unlock()\n+ s.sockOptInq = usermem.ByteOrder.Uint32(optVal) != 0\n+ return nil\n+ }\nreturn SetSockOpt(t, s, s.Endpoint, level, name, optVal)\n}\n@@ -1267,6 +1296,7 @@ func setSockOptTCP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *\nreturn syserr.TranslateNetstackError(err)\n}\nreturn nil\n+\ncase linux.TCP_REPAIR_OPTIONS:\nt.Kernel().EmitUnimplementedEvent(t)\n@@ -1492,7 +1522,6 @@ func emitUnimplementedEventTCP(t *kernel.Task, name int) {\nlinux.TCP_FASTOPEN_CONNECT,\nlinux.TCP_FASTOPEN_KEY,\nlinux.TCP_FASTOPEN_NO_COOKIE,\n- linux.TCP_INQ,\nlinux.TCP_KEEPCNT,\nlinux.TCP_KEEPIDLE,\nlinux.TCP_KEEPINTVL,\n@@ -1747,6 +1776,18 @@ func (s *SocketOperations) coalescingRead(ctx context.Context, dst usermem.IOSeq\nreturn 0, err\n}\n+func (s *SocketOperations) fillCmsgInq(cmsg *socket.ControlMessages) {\n+ if !s.sockOptInq {\n+ return\n+ }\n+ rcvBufUsed, err := s.Endpoint.GetSockOptInt(tcpip.ReceiveQueueSizeOption)\n+ if err != nil {\n+ return\n+ }\n+ cmsg.IP.HasInq = true\n+ cmsg.IP.Inq = int32(len(s.readView) + rcvBufUsed)\n+}\n+\n// nonBlockingRead issues a non-blocking read.\n//\n// TODO(b/78348848): Support timestamps for stream sockets.\n@@ -1766,7 +1807,9 @@ func (s *SocketOperations) nonBlockingRead(ctx context.Context, dst usermem.IOSe\ns.readMu.Lock()\nn, err := s.coalescingRead(ctx, dst, trunc)\ns.readMu.Unlock()\n- return n, 0, nil, 0, socket.ControlMessages{}, err\n+ cmsg := s.controlMessages()\n+ s.fillCmsgInq(&cmsg)\n+ return n, 0, nil, 0, cmsg, err\n}\ns.readMu.Lock()\n@@ -1779,8 +1822,8 @@ func (s *SocketOperations) nonBlockingRead(ctx context.Context, dst usermem.IOSe\nif !isPacket && peek && trunc {\n// MSG_TRUNC with MSG_PEEK on a TCP socket returns the\n// amount that could be read.\n- var rql tcpip.ReceiveQueueSizeOption\n- if err := s.Endpoint.GetSockOpt(&rql); err != nil {\n+ rql, err := s.Endpoint.GetSockOptInt(tcpip.ReceiveQueueSizeOption)\n+ if err != nil {\nreturn 0, 0, nil, 0, socket.ControlMessages{}, syserr.TranslateNetstackError(err)\n}\navailable := len(s.readView) + int(rql)\n@@ -1848,7 +1891,9 @@ func (s *SocketOperations) nonBlockingRead(ctx context.Context, dst usermem.IOSe\nn = msgLen\n}\n- return n, flags, addr, addrLen, s.controlMessages(), syserr.FromError(err)\n+ cmsg := s.controlMessages()\n+ s.fillCmsgInq(&cmsg)\n+ return n, flags, addr, addrLen, cmsg, syserr.FromError(err)\n}\nfunc (s *SocketOperations) controlMessages() socket.ControlMessages {\n@@ -2086,9 +2131,9 @@ func Ioctl(ctx context.Context, ep commonEndpoint, io usermem.IO, args arch.Sysc\nreturn 0, err\ncase linux.TIOCINQ:\n- var v tcpip.ReceiveQueueSizeOption\n- if err := ep.GetSockOpt(&v); err != nil {\n- return 0, syserr.TranslateNetstackError(err).ToError()\n+ v, terr := ep.GetSockOptInt(tcpip.ReceiveQueueSizeOption)\n+ if terr != nil {\n+ return 0, syserr.TranslateNetstackError(terr).ToError()\n}\nif v > math.MaxInt32 {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/transport/unix.go",
"new_path": "pkg/sentry/socket/unix/transport/unix.go",
"diff": "@@ -179,6 +179,10 @@ type Endpoint interface {\n// tcpip.*Option types.\nGetSockOpt(opt interface{}) *tcpip.Error\n+ // GetSockOptInt gets a socket option for simple cases when a return\n+ // value has the int type.\n+ GetSockOptInt(opt tcpip.SockOpt) (int, *tcpip.Error)\n+\n// State returns the current state of the socket, as represented by Linux in\n// procfs.\nState() uint32\n@@ -834,33 +838,39 @@ func (e *baseEndpoint) SetSockOpt(opt interface{}) *tcpip.Error {\nreturn nil\n}\n-// GetSockOpt implements tcpip.Endpoint.GetSockOpt.\n-func (e *baseEndpoint) GetSockOpt(opt interface{}) *tcpip.Error {\n- switch o := opt.(type) {\n- case tcpip.ErrorOption:\n- return nil\n-\n- case *tcpip.SendQueueSizeOption:\n+func (e *baseEndpoint) GetSockOptInt(opt tcpip.SockOpt) (int, *tcpip.Error) {\n+ switch opt {\n+ case tcpip.ReceiveQueueSizeOption:\n+ v := 0\ne.Lock()\nif !e.Connected() {\ne.Unlock()\n- return tcpip.ErrNotConnected\n+ return -1, tcpip.ErrNotConnected\n}\n- qs := tcpip.SendQueueSizeOption(e.connected.SendQueuedSize())\n+ v = int(e.receiver.RecvQueuedSize())\ne.Unlock()\n- if qs < 0 {\n- return tcpip.ErrQueueSizeNotSupported\n+ if v < 0 {\n+ return -1, tcpip.ErrQueueSizeNotSupported\n}\n- *o = qs\n+ return v, nil\n+ default:\n+ return -1, tcpip.ErrUnknownProtocolOption\n+ }\n+}\n+\n+// GetSockOpt implements tcpip.Endpoint.GetSockOpt.\n+func (e *baseEndpoint) GetSockOpt(opt interface{}) *tcpip.Error {\n+ switch o := opt.(type) {\n+ case tcpip.ErrorOption:\nreturn nil\n- case *tcpip.ReceiveQueueSizeOption:\n+ case *tcpip.SendQueueSizeOption:\ne.Lock()\nif !e.Connected() {\ne.Unlock()\nreturn tcpip.ErrNotConnected\n}\n- qs := tcpip.ReceiveQueueSizeOption(e.receiver.RecvQueuedSize())\n+ qs := tcpip.SendQueueSizeOption(e.connected.SendQueuedSize())\ne.Unlock()\nif qs < 0 {\nreturn tcpip.ErrQueueSizeNotSupported\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_socket.go",
"new_path": "pkg/sentry/syscalls/linux/sys_socket.go",
"diff": "@@ -802,6 +802,11 @@ func recvSingleMsg(t *kernel.Task, s socket.Socket, msgPtr usermem.Addr, flags i\ncontrolData = control.PackTimestamp(t, cms.IP.Timestamp, controlData)\n}\n+ if cms.IP.HasInq {\n+ // In Linux, TCP_CM_INQ is added after SO_TIMESTAMP.\n+ controlData = control.PackInq(t, cms.IP.Inq, controlData)\n+ }\n+\nif cms.Unix.Rights != nil {\ncontrolData, mflags = control.PackRights(t, cms.Unix.Rights.(control.SCMRights), flags&linux.MSG_CMSG_CLOEXEC != 0, controlData, mflags)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/transport_test.go",
"new_path": "pkg/tcpip/stack/transport_test.go",
"diff": "@@ -90,6 +90,11 @@ func (*fakeTransportEndpoint) SetSockOpt(interface{}) *tcpip.Error {\nreturn tcpip.ErrInvalidEndpointState\n}\n+// GetSockOptInt implements tcpip.Endpoint.GetSockOptInt.\n+func (*fakeTransportEndpoint) GetSockOptInt(opt tcpip.SockOpt) (int, *tcpip.Error) {\n+ return -1, tcpip.ErrUnknownProtocolOption\n+}\n+\n// GetSockOpt implements tcpip.Endpoint.GetSockOpt.\nfunc (*fakeTransportEndpoint) GetSockOpt(opt interface{}) *tcpip.Error {\nswitch opt.(type) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -288,6 +288,12 @@ type ControlMessages struct {\n// Timestamp is the time (in ns) that the last packed used to create\n// the read data was received.\nTimestamp int64\n+\n+ // HasInq indicates whether Inq is valid/set.\n+ HasInq bool\n+\n+ // Inq is the number of bytes ready to be received.\n+ Inq int32\n}\n// Endpoint is the interface implemented by transport protocols (e.g., tcp, udp)\n@@ -383,6 +389,10 @@ type Endpoint interface {\n// *Option types.\nGetSockOpt(opt interface{}) *Error\n+ // GetSockOptInt gets a socket option for simple cases where a return\n+ // value has the int type.\n+ GetSockOptInt(SockOpt) (int, *Error)\n+\n// State returns a socket's lifecycle state. The returned value is\n// protocol-specific and is primarily used for diagnostics.\nState() uint32\n@@ -408,6 +418,18 @@ type WriteOptions struct {\nEndOfRecord bool\n}\n+// SockOpt represents socket options which values have the int type.\n+type SockOpt int\n+\n+const (\n+ // ReceiveQueueSizeOption is used in GetSockOpt to specify that the number of\n+ // unread bytes in the input buffer should be returned.\n+ ReceiveQueueSizeOption SockOpt = iota\n+\n+ // TODO(b/137664753): convert all int socket options to be handled via\n+ // GetSockOptInt.\n+)\n+\n// ErrorOption is used in GetSockOpt to specify that the last error reported by\n// the endpoint should be cleared and returned.\ntype ErrorOption struct{}\n@@ -424,10 +446,6 @@ type ReceiveBufferSizeOption int\n// unread bytes in the output buffer should be returned.\ntype SendQueueSizeOption int\n-// ReceiveQueueSizeOption is used in GetSockOpt to specify that the number of\n-// unread bytes in the input buffer should be returned.\n-type ReceiveQueueSizeOption int\n-\n// V6OnlyOption is used by SetSockOpt/GetSockOpt to specify whether an IPv6\n// socket is to be restricted to sending and receiving IPv6 packets only.\ntype V6OnlyOption int\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/icmp/endpoint.go",
"new_path": "pkg/tcpip/transport/icmp/endpoint.go",
"diff": "@@ -314,6 +314,22 @@ func (e *endpoint) SetSockOpt(opt interface{}) *tcpip.Error {\nreturn nil\n}\n+// GetSockOptInt implements tcpip.Endpoint.GetSockOptInt.\n+func (e *endpoint) GetSockOptInt(opt tcpip.SockOpt) (int, *tcpip.Error) {\n+ switch opt {\n+ case tcpip.ReceiveQueueSizeOption:\n+ v := 0\n+ e.rcvMu.Lock()\n+ if !e.rcvList.Empty() {\n+ p := e.rcvList.Front()\n+ v = p.data.Size()\n+ }\n+ e.rcvMu.Unlock()\n+ return v, nil\n+ }\n+ return -1, tcpip.ErrUnknownProtocolOption\n+}\n+\n// GetSockOpt implements tcpip.Endpoint.GetSockOpt.\nfunc (e *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {\nswitch o := opt.(type) {\n@@ -332,17 +348,6 @@ func (e *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {\ne.rcvMu.Unlock()\nreturn nil\n- case *tcpip.ReceiveQueueSizeOption:\n- e.rcvMu.Lock()\n- if e.rcvList.Empty() {\n- *o = 0\n- } else {\n- p := e.rcvList.Front()\n- *o = tcpip.ReceiveQueueSizeOption(p.data.Size())\n- }\n- e.rcvMu.Unlock()\n- return nil\n-\ncase *tcpip.KeepaliveEnabledOption:\n*o = 0\nreturn nil\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/raw/endpoint.go",
"new_path": "pkg/tcpip/transport/raw/endpoint.go",
"diff": "@@ -487,6 +487,23 @@ func (ep *endpoint) SetSockOpt(opt interface{}) *tcpip.Error {\nreturn nil\n}\n+// GetSockOptInt implements tcpip.Endpoint.GetSockOptInt.\n+func (ep *endpoint) GetSockOptInt(opt tcpip.SockOpt) (int, *tcpip.Error) {\n+ switch opt {\n+ case tcpip.ReceiveQueueSizeOption:\n+ v := 0\n+ ep.rcvMu.Lock()\n+ if !ep.rcvList.Empty() {\n+ p := ep.rcvList.Front()\n+ v = p.data.Size()\n+ }\n+ ep.rcvMu.Unlock()\n+ return v, nil\n+ }\n+\n+ return -1, tcpip.ErrUnknownProtocolOption\n+}\n+\n// GetSockOpt implements tcpip.Endpoint.GetSockOpt.\nfunc (ep *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {\nswitch o := opt.(type) {\n@@ -505,17 +522,6 @@ func (ep *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {\nep.rcvMu.Unlock()\nreturn nil\n- case *tcpip.ReceiveQueueSizeOption:\n- ep.rcvMu.Lock()\n- if ep.rcvList.Empty() {\n- *o = 0\n- } else {\n- p := ep.rcvList.Front()\n- *o = tcpip.ReceiveQueueSizeOption(p.data.Size())\n- }\n- ep.rcvMu.Unlock()\n- return nil\n-\ncase *tcpip.KeepaliveEnabledOption:\n*o = 0\nreturn nil\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -1100,6 +1100,15 @@ func (e *endpoint) readyReceiveSize() (int, *tcpip.Error) {\nreturn e.rcvBufUsed, nil\n}\n+// GetSockOptInt implements tcpip.Endpoint.GetSockOptInt.\n+func (e *endpoint) GetSockOptInt(opt tcpip.SockOpt) (int, *tcpip.Error) {\n+ switch opt {\n+ case tcpip.ReceiveQueueSizeOption:\n+ return e.readyReceiveSize()\n+ }\n+ return -1, tcpip.ErrUnknownProtocolOption\n+}\n+\n// GetSockOpt implements tcpip.Endpoint.GetSockOpt.\nfunc (e *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {\nswitch o := opt.(type) {\n@@ -1130,15 +1139,6 @@ func (e *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {\ne.rcvListMu.Unlock()\nreturn nil\n- case *tcpip.ReceiveQueueSizeOption:\n- v, err := e.readyReceiveSize()\n- if err != nil {\n- return err\n- }\n-\n- *o = tcpip.ReceiveQueueSizeOption(v)\n- return nil\n-\ncase *tcpip.DelayOption:\n*o = 0\nif v := atomic.LoadUint32(&e.delay); v != 0 {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -189,7 +189,6 @@ func (e *endpoint) Read(addr *tcpip.FullAddress) (buffer.View, tcpip.ControlMess\np := e.rcvList.Front()\ne.rcvList.Remove(p)\ne.rcvBufSize -= p.data.Size()\n-\ne.rcvMu.Unlock()\nif addr != nil {\n@@ -539,6 +538,22 @@ func (e *endpoint) SetSockOpt(opt interface{}) *tcpip.Error {\nreturn nil\n}\n+// GetSockOptInt implements tcpip.Endpoint.GetSockOptInt.\n+func (e *endpoint) GetSockOptInt(opt tcpip.SockOpt) (int, *tcpip.Error) {\n+ switch opt {\n+ case tcpip.ReceiveQueueSizeOption:\n+ v := 0\n+ e.rcvMu.Lock()\n+ if !e.rcvList.Empty() {\n+ p := e.rcvList.Front()\n+ v = p.data.Size()\n+ }\n+ e.rcvMu.Unlock()\n+ return v, nil\n+ }\n+ return -1, tcpip.ErrUnknownProtocolOption\n+}\n+\n// GetSockOpt implements tcpip.Endpoint.GetSockOpt.\nfunc (e *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {\nswitch o := opt.(type) {\n@@ -573,17 +588,6 @@ func (e *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {\n}\nreturn nil\n- case *tcpip.ReceiveQueueSizeOption:\n- e.rcvMu.Lock()\n- if e.rcvList.Empty() {\n- *o = 0\n- } else {\n- p := e.rcvList.Front()\n- *o = tcpip.ReceiveQueueSizeOption(p.data.Size())\n- }\n- e.rcvMu.Unlock()\n- return nil\n-\ncase *tcpip.MulticastTTLOption:\ne.mu.Lock()\n*o = tcpip.MulticastTTLOption(e.multicastTTL)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/tcp_socket.cc",
"new_path": "test/syscalls/linux/tcp_socket.cc",
"diff": "#include <netinet/in.h>\n#include <netinet/tcp.h>\n#include <poll.h>\n+#include <sys/ioctl.h>\n#include <sys/socket.h>\n#include <unistd.h>\n@@ -520,6 +521,143 @@ TEST_P(TcpSocketTest, SetNoDelay) {\nEXPECT_EQ(get, kSockOptOff);\n}\n+#ifndef TCP_INQ\n+#define TCP_INQ 36\n+#endif\n+\n+TEST_P(TcpSocketTest, TcpInqSetSockOpt) {\n+ char buf[1024];\n+ ASSERT_THAT(RetryEINTR(write)(s_, buf, sizeof(buf)),\n+ SyscallSucceedsWithValue(sizeof(buf)));\n+\n+ // TCP_INQ is disabled by default.\n+ int val = -1;\n+ socklen_t slen = sizeof(val);\n+ EXPECT_THAT(getsockopt(t_, SOL_TCP, TCP_INQ, &val, &slen),\n+ SyscallSucceedsWithValue(0));\n+ ASSERT_EQ(val, 0);\n+\n+ // Try to set TCP_INQ.\n+ val = 1;\n+ EXPECT_THAT(setsockopt(t_, SOL_TCP, TCP_INQ, &val, sizeof(val)),\n+ SyscallSucceedsWithValue(0));\n+ val = -1;\n+ slen = sizeof(val);\n+ EXPECT_THAT(getsockopt(t_, SOL_TCP, TCP_INQ, &val, &slen),\n+ SyscallSucceedsWithValue(0));\n+ ASSERT_EQ(val, 1);\n+\n+ // Try to unset TCP_INQ.\n+ val = 0;\n+ EXPECT_THAT(setsockopt(t_, SOL_TCP, TCP_INQ, &val, sizeof(val)),\n+ SyscallSucceedsWithValue(0));\n+ val = -1;\n+ slen = sizeof(val);\n+ EXPECT_THAT(getsockopt(t_, SOL_TCP, TCP_INQ, &val, &slen),\n+ SyscallSucceedsWithValue(0));\n+ ASSERT_EQ(val, 0);\n+}\n+\n+TEST_P(TcpSocketTest, TcpInq) {\n+ char buf[1024];\n+ // Write more than one TCP segment.\n+ int size = sizeof(buf);\n+ int kChunk = sizeof(buf) / 4;\n+ for (int i = 0; i < size; i += kChunk) {\n+ ASSERT_THAT(RetryEINTR(write)(s_, buf, kChunk),\n+ SyscallSucceedsWithValue(kChunk));\n+ }\n+\n+ int val = 1;\n+ kChunk = sizeof(buf) / 2;\n+ EXPECT_THAT(setsockopt(t_, SOL_TCP, TCP_INQ, &val, sizeof(val)),\n+ SyscallSucceedsWithValue(0));\n+\n+ // Wait when all data will be in the received queue.\n+ while (true) {\n+ ASSERT_THAT(ioctl(t_, TIOCINQ, &size), SyscallSucceeds());\n+ if (size == sizeof(buf)) {\n+ break;\n+ }\n+ usleep(10000);\n+ }\n+\n+ struct msghdr msg = {};\n+ std::vector<char> control(CMSG_SPACE(sizeof(int)));\n+ size = sizeof(buf);\n+ struct iovec iov;\n+ for (int i = 0; size != 0; i += kChunk) {\n+ msg.msg_control = &control[0];\n+ msg.msg_controllen = control.size();\n+\n+ iov.iov_base = buf;\n+ iov.iov_len = kChunk;\n+ msg.msg_iov = &iov;\n+ msg.msg_iovlen = 1;\n+ ASSERT_THAT(RetryEINTR(recvmsg)(t_, &msg, 0),\n+ SyscallSucceedsWithValue(kChunk));\n+ size -= kChunk;\n+\n+ struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);\n+ ASSERT_NE(cmsg, nullptr);\n+ ASSERT_EQ(cmsg->cmsg_len, CMSG_LEN(sizeof(int)));\n+ ASSERT_EQ(cmsg->cmsg_level, SOL_TCP);\n+ ASSERT_EQ(cmsg->cmsg_type, TCP_INQ);\n+\n+ int inq = 0;\n+ memcpy(&inq, CMSG_DATA(cmsg), sizeof(int));\n+ ASSERT_EQ(inq, size);\n+ }\n+}\n+\n+TEST_P(TcpSocketTest, TcpSCMPriority) {\n+ char buf[1024];\n+ ASSERT_THAT(RetryEINTR(write)(s_, buf, sizeof(buf)),\n+ SyscallSucceedsWithValue(sizeof(buf)));\n+\n+ int val = 1;\n+ EXPECT_THAT(setsockopt(t_, SOL_TCP, TCP_INQ, &val, sizeof(val)),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_THAT(setsockopt(t_, SOL_SOCKET, SO_TIMESTAMP, &val, sizeof(val)),\n+ SyscallSucceedsWithValue(0));\n+\n+ struct msghdr msg = {};\n+ std::vector<char> control(\n+ CMSG_SPACE(sizeof(struct timeval) + CMSG_SPACE(sizeof(int))));\n+ struct iovec iov;\n+ msg.msg_control = &control[0];\n+ msg.msg_controllen = control.size();\n+\n+ iov.iov_base = buf;\n+ iov.iov_len = sizeof(buf);\n+ msg.msg_iov = &iov;\n+ msg.msg_iovlen = 1;\n+ ASSERT_THAT(RetryEINTR(recvmsg)(t_, &msg, 0),\n+ SyscallSucceedsWithValue(sizeof(buf)));\n+\n+ struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);\n+ ASSERT_NE(cmsg, nullptr);\n+ // TODO(b/78348848): SO_TIMESTAMP isn't implemented for TCP sockets.\n+ if (!IsRunningOnGvisor() || cmsg->cmsg_level == SOL_SOCKET) {\n+ ASSERT_EQ(cmsg->cmsg_level, SOL_SOCKET);\n+ ASSERT_EQ(cmsg->cmsg_type, SO_TIMESTAMP);\n+ ASSERT_EQ(cmsg->cmsg_len, CMSG_LEN(sizeof(struct timeval)));\n+\n+ cmsg = CMSG_NXTHDR(&msg, cmsg);\n+ ASSERT_NE(cmsg, nullptr);\n+ }\n+ ASSERT_EQ(cmsg->cmsg_len, CMSG_LEN(sizeof(int)));\n+ ASSERT_EQ(cmsg->cmsg_level, SOL_TCP);\n+ ASSERT_EQ(cmsg->cmsg_type, TCP_INQ);\n+\n+ int inq = 0;\n+ memcpy(&inq, CMSG_DATA(cmsg), sizeof(int));\n+ ASSERT_EQ(inq, 0);\n+\n+ cmsg = CMSG_NXTHDR(&msg, cmsg);\n+ ASSERT_EQ(cmsg, nullptr);\n+}\n+\nINSTANTIATE_TEST_SUITE_P(AllInetTests, TcpSocketTest,\n::testing::Values(AF_INET, AF_INET6));\n"
}
] | Go | Apache License 2.0 | google/gvisor | net/tcp/setockopt: impelment setsockopt(fd, SOL_TCP, TCP_INQ)
PiperOrigin-RevId: 258859507 |
260,006 | 19.07.2019 09:27:33 | 25,200 | 0e040ba6e87f5fdcb23854909aad39aa1883925f | Handle interfaceAddr and NIC options separately for IP_MULTICAST_IF
This tweaks the handling code for IP_MULTICAST_IF to ignore the InterfaceAddr
if a NICID is given. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -252,7 +252,7 @@ func (e *endpoint) connectRoute(nicid tcpip.NICID, addr tcpip.FullAddress) (stac\nif nicid == 0 {\nnicid = e.multicastNICID\n}\n- if localAddr == \"\" {\n+ if localAddr == \"\" && nicid == 0 {\nlocalAddr = e.multicastAddr\n}\n}\n@@ -675,6 +675,9 @@ func sendUDP(r *stack.Route, data buffer.VectorisedView, localPort, remotePort u\nfunc (e *endpoint) checkV4Mapped(addr *tcpip.FullAddress, allowMismatch bool) (tcpip.NetworkProtocolNumber, *tcpip.Error) {\nnetProto := e.netProto\n+ if len(addr.Addr) == 0 {\n+ return netProto, nil\n+ }\nif header.IsV4MappedAddress(addr.Addr) {\n// Fail if using a v4 mapped address on a v6only endpoint.\nif e.v6only {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/udp_test.go",
"new_path": "pkg/tcpip/transport/udp/udp_test.go",
"diff": "@@ -847,9 +847,7 @@ func TestWriteIncrementsPacketsSent(t *testing.T) {\n}\n}\n-func TestTTL(t *testing.T) {\n- payload := tcpip.SlicePayload(buffer.View(newPayload()))\n-\n+func setSockOptVariants(t *testing.T, optFunc func(*testing.T, string, tcpip.NetworkProtocolNumber, string)) {\nfor _, name := range []string{\"v4\", \"v6\", \"dual\"} {\nt.Run(name, func(t *testing.T) {\nvar networkProtocolNumber tcpip.NetworkProtocolNumber\n@@ -874,6 +872,17 @@ func TestTTL(t *testing.T) {\nfor _, variant := range variants {\nt.Run(variant, func(t *testing.T) {\n+ optFunc(t, name, networkProtocolNumber, variant)\n+ })\n+ }\n+ })\n+ }\n+}\n+\n+func TestTTL(t *testing.T) {\n+ payload := tcpip.SlicePayload(buffer.View(newPayload()))\n+\n+ setSockOptVariants(t, func(t *testing.T, name string, networkProtocolNumber tcpip.NetworkProtocolNumber, variant string) {\nfor _, typ := range []string{\"unicast\", \"multicast\"} {\nt.Run(typ, func(t *testing.T) {\nvar addr tcpip.Address\n@@ -1002,6 +1011,80 @@ func TestTTL(t *testing.T) {\n}\n})\n}\n+\n+func TestMulticastInterfaceOption(t *testing.T) {\n+ setSockOptVariants(t, func(t *testing.T, name string, networkProtocolNumber tcpip.NetworkProtocolNumber, variant string) {\n+ for _, bindTyp := range []string{\"bound\", \"unbound\"} {\n+ t.Run(bindTyp, func(t *testing.T) {\n+ for _, optTyp := range []string{\"use local-addr\", \"use NICID\", \"use local-addr and NIC\"} {\n+ t.Run(optTyp, func(t *testing.T) {\n+ var mcastAddr, localIfAddr tcpip.Address\n+ switch variant {\n+ case \"v4\":\n+ mcastAddr = multicastAddr\n+ localIfAddr = stackAddr\n+ case \"mapped\":\n+ mcastAddr = multicastV4MappedAddr\n+ localIfAddr = stackAddr\n+ case \"v6\":\n+ mcastAddr = multicastV6Addr\n+ localIfAddr = stackV6Addr\n+ default:\n+ t.Fatal(\"unknown test variant\")\n+ }\n+\n+ var ifoptSet tcpip.MulticastInterfaceOption\n+ switch optTyp {\n+ case \"use local-addr\":\n+ ifoptSet.InterfaceAddr = localIfAddr\n+ case \"use NICID\":\n+ ifoptSet.NIC = 1\n+ case \"use local-addr and NIC\":\n+ ifoptSet.InterfaceAddr = localIfAddr\n+ ifoptSet.NIC = 1\n+ default:\n+ t.Fatal(\"unknown test variant\")\n+ }\n+\n+ c := newDualTestContext(t, defaultMTU)\n+ defer c.cleanup()\n+\n+ var err *tcpip.Error\n+ c.ep, err = c.s.NewEndpoint(udp.ProtocolNumber, networkProtocolNumber, &c.wq)\n+ if err != nil {\n+ c.t.Fatalf(\"NewEndpoint failed: %v\", err)\n+ }\n+\n+ if bindTyp == \"bound\" {\n+ // Bind the socket by connecting to the multicast address.\n+ // This may have an influence on how the multicast interface\n+ // is set.\n+ addr := tcpip.FullAddress{\n+ Addr: mcastAddr,\n+ Port: multicastPort,\n+ }\n+ if err := c.ep.Connect(addr); err != nil {\n+ c.t.Fatalf(\"Connect failed: %v\", err)\n+ }\n+ }\n+\n+ if err := c.ep.SetSockOpt(ifoptSet); err != nil {\n+ c.t.Fatalf(\"SetSockOpt failed: %v\", err)\n+ }\n+\n+ // Verify multicast interface addr and NIC were set correctly.\n+ // Note that NIC must be 1 since this is our outgoing interface.\n+ ifoptWant := tcpip.MulticastInterfaceOption{NIC: 1, InterfaceAddr: ifoptSet.InterfaceAddr}\n+ var ifoptGot tcpip.MulticastInterfaceOption\n+ if err := c.ep.GetSockOpt(&ifoptGot); err != nil {\n+ c.t.Fatalf(\"GetSockOpt failed: %v\", err)\n+ }\n+ if ifoptGot != ifoptWant {\n+ c.t.Errorf(\"got GetSockOpt() = %#v, want = %#v\", ifoptGot, ifoptWant)\n+ }\n})\n}\n+ })\n+ }\n+ })\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/ip_socket_test_util.cc",
"new_path": "test/syscalls/linux/ip_socket_test_util.cc",
"diff": "@@ -120,5 +120,68 @@ SocketKind IPv4TCPUnboundSocket(int type) {\nUnboundSocketCreator(AF_INET, type | SOCK_STREAM, IPPROTO_TCP)};\n}\n+PosixError IfAddrHelper::Load() {\n+ Release();\n+ RETURN_ERROR_IF_SYSCALL_FAIL(getifaddrs(&ifaddr_));\n+ return PosixError(0);\n+}\n+\n+void IfAddrHelper::Release() {\n+ if (ifaddr_) {\n+ freeifaddrs(ifaddr_);\n+ }\n+ ifaddr_ = nullptr;\n+}\n+\n+std::vector<std::string> IfAddrHelper::InterfaceList(int family) {\n+ std::vector<std::string> names;\n+ for (auto ifa = ifaddr_; ifa != NULL; ifa = ifa->ifa_next) {\n+ if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != family) {\n+ continue;\n+ }\n+ names.emplace(names.end(), ifa->ifa_name);\n+ }\n+ return names;\n+}\n+\n+sockaddr* IfAddrHelper::GetAddr(int family, std::string name) {\n+ for (auto ifa = ifaddr_; ifa != NULL; ifa = ifa->ifa_next) {\n+ if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != family) {\n+ continue;\n+ }\n+ if (name == ifa->ifa_name) {\n+ return ifa->ifa_addr;\n+ }\n+ }\n+ return nullptr;\n+}\n+\n+PosixErrorOr<int> IfAddrHelper::GetIndex(std::string name) {\n+ return InterfaceIndex(name);\n+}\n+\n+std::string GetAddr4Str(in_addr* a) {\n+ char str[INET_ADDRSTRLEN];\n+ inet_ntop(AF_INET, a, str, sizeof(str));\n+ return std::string(str);\n+}\n+\n+std::string GetAddr6Str(in6_addr* a) {\n+ char str[INET6_ADDRSTRLEN];\n+ inet_ntop(AF_INET6, a, str, sizeof(str));\n+ return std::string(str);\n+}\n+\n+std::string GetAddrStr(sockaddr* a) {\n+ if (a->sa_family == AF_INET) {\n+ auto src = &(reinterpret_cast<sockaddr_in*>(a)->sin_addr);\n+ return GetAddr4Str(src);\n+ } else if (a->sa_family == AF_INET6) {\n+ auto src = &(reinterpret_cast<sockaddr_in6*>(a)->sin6_addr);\n+ return GetAddr6Str(src);\n+ }\n+ return std::string(\"<invalid>\");\n+}\n+\n} // namespace testing\n} // namespace gvisor\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/ip_socket_test_util.h",
"new_path": "test/syscalls/linux/ip_socket_test_util.h",
"diff": "#ifndef GVISOR_TEST_SYSCALLS_IP_SOCKET_TEST_UTIL_H_\n#define GVISOR_TEST_SYSCALLS_IP_SOCKET_TEST_UTIL_H_\n+#include <arpa/inet.h>\n+#include <ifaddrs.h>\n+#include <sys/types.h>\n+\n#include <string>\n+\n#include \"test/syscalls/linux/socket_test_util.h\"\nnamespace gvisor {\n@@ -66,6 +71,35 @@ SocketKind IPv4UDPUnboundSocket(int type);\n// a SimpleSocket created with AF_INET, SOCK_STREAM and the given type.\nSocketKind IPv4TCPUnboundSocket(int type);\n+// IfAddrHelper is a helper class that determines the local interfaces present\n+// and provides functions to obtain their names, index numbers, and IP address.\n+class IfAddrHelper {\n+ public:\n+ IfAddrHelper() : ifaddr_(nullptr) {}\n+ ~IfAddrHelper() { Release(); }\n+\n+ PosixError Load();\n+ void Release();\n+\n+ std::vector<std::string> InterfaceList(int family);\n+\n+ struct sockaddr* GetAddr(int family, std::string name);\n+ PosixErrorOr<int> GetIndex(std::string name);\n+\n+ private:\n+ struct ifaddrs* ifaddr_;\n+};\n+\n+// GetAddr4Str returns the given IPv4 network address structure as a string.\n+std::string GetAddr4Str(in_addr* a);\n+\n+// GetAddr6Str returns the given IPv6 network address structure as a string.\n+std::string GetAddr6Str(in6_addr* a);\n+\n+// GetAddrStr returns the given IPv4 or IPv6 network address structure as a\n+// string.\n+std::string GetAddrStr(sockaddr* a);\n+\n} // namespace testing\n} // namespace gvisor\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ipv4_udp_unbound.cc",
"new_path": "test/syscalls/linux/socket_ipv4_udp_unbound.cc",
"diff": "@@ -40,7 +40,7 @@ TestAddress V4Multicast() {\nreturn t;\n}\n-// Check that packets are not received without a group memebership. Default send\n+// Check that packets are not received without a group membership. Default send\n// interface configured by bind.\nTEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastLoopbackNoGroup) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ipv4_udp_unbound_external_networking.cc",
"new_path": "test/syscalls/linux/socket_ipv4_udp_unbound_external_networking.cc",
"diff": "#include \"test/syscalls/linux/socket_ipv4_udp_unbound_external_networking.h\"\n#include <arpa/inet.h>\n+#include <ifaddrs.h>\n#include <netinet/in.h>\n#include <sys/socket.h>\n#include <sys/types.h>\n#include <sys/un.h>\n+\n+#include <cstdint>\n#include <cstdio>\n#include <cstring>\nnamespace gvisor {\nnamespace testing {\n+TestAddress V4EmptyAddress() {\n+ TestAddress t(\"V4Empty\");\n+ t.addr.ss_family = AF_INET;\n+ t.addr_len = sizeof(sockaddr_in);\n+ return t;\n+}\n+\n+void IPv4UDPUnboundExternalNetworkingSocketTest::SetUp() {\n+ got_if_infos_ = false;\n+\n+ // Get interface list.\n+ std::vector<std::string> if_names;\n+ ASSERT_NO_ERRNO(if_helper_.Load());\n+ if_names = if_helper_.InterfaceList(AF_INET);\n+ if (if_names.size() != 2) {\n+ return;\n+ }\n+\n+ // Figure out which interface is where.\n+ int lo = 0, eth = 1;\n+ if (if_names[lo] != \"lo\") {\n+ lo = 1;\n+ eth = 0;\n+ }\n+\n+ if (if_names[lo] != \"lo\") {\n+ return;\n+ }\n+\n+ lo_if_idx_ = ASSERT_NO_ERRNO_AND_VALUE(if_helper_.GetIndex(if_names[lo]));\n+ lo_if_addr_ = if_helper_.GetAddr(AF_INET, if_names[lo]);\n+ if (lo_if_addr_ == nullptr) {\n+ return;\n+ }\n+ lo_if_sin_addr_ = reinterpret_cast<sockaddr_in*>(lo_if_addr_)->sin_addr;\n+\n+ eth_if_idx_ = ASSERT_NO_ERRNO_AND_VALUE(if_helper_.GetIndex(if_names[eth]));\n+ eth_if_addr_ = if_helper_.GetAddr(AF_INET, if_names[eth]);\n+ if (eth_if_addr_ == nullptr) {\n+ return;\n+ }\n+ eth_if_sin_addr_ = reinterpret_cast<sockaddr_in*>(eth_if_addr_)->sin_addr;\n+\n+ got_if_infos_ = true;\n+}\n+\n// Verifies that a newly instantiated UDP socket does not have the\n// broadcast socket option enabled.\nTEST_P(IPv4UDPUnboundExternalNetworkingSocketTest, UDPBroadcastDefault) {\n@@ -658,7 +707,7 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\nsender->get(), reinterpret_cast<sockaddr*>(&sendto_addr.addr),\nsendto_addr.addr_len),\nSyscallSucceeds());\n- TestAddress sender_addr(\"\");\n+ auto sender_addr = V4EmptyAddress();\nASSERT_THAT(\ngetsockname(sender->get(), reinterpret_cast<sockaddr*>(&sender_addr.addr),\n&sender_addr.addr_len),\n@@ -674,7 +723,7 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\n// Receive a multicast packet.\nchar recv_buf[sizeof(send_buf)] = {};\n- TestAddress src_addr(\"\");\n+ auto src_addr = V4EmptyAddress();\nASSERT_THAT(\nRetryEINTR(recvfrom)(receiver->get(), recv_buf, sizeof(recv_buf), 0,\nreinterpret_cast<sockaddr*>(&src_addr.addr),\n@@ -688,5 +737,113 @@ TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\nEXPECT_EQ(sender_addr_in->sin_addr.s_addr, src_addr_in->sin_addr.s_addr);\n}\n+// Check that when setting the IP_MULTICAST_IF option to both an index pointing\n+// to the loopback interface and an address pointing to the non-loopback\n+// interface, a multicast packet sent out uses the latter as its source address.\n+TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\n+ IpMulticastLoopbackIfNicAndAddr) {\n+ // FIXME(b/137899561): Linux instance for syscall tests sometimes misses its\n+ // IPv4 address on eth0.\n+ SKIP_IF(!got_if_infos_);\n+\n+ // Create receiver, bind to ANY and join the multicast group.\n+ auto receiver = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n+ auto receiver_addr = V4Any();\n+ ASSERT_THAT(\n+ bind(receiver->get(), reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ receiver_addr.addr_len),\n+ SyscallSucceeds());\n+ socklen_t receiver_addr_len = receiver_addr.addr_len;\n+ ASSERT_THAT(getsockname(receiver->get(),\n+ reinterpret_cast<sockaddr*>(&receiver_addr.addr),\n+ &receiver_addr_len),\n+ SyscallSucceeds());\n+ EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);\n+ int receiver_port =\n+ reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;\n+ ip_mreqn group = {};\n+ group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\n+ group.imr_ifindex = lo_if_idx_;\n+ ASSERT_THAT(setsockopt(receiver->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,\n+ sizeof(group)),\n+ SyscallSucceeds());\n+\n+ // Set outgoing multicast interface config, with NIC and addr pointing to\n+ // different interfaces.\n+ auto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n+ ip_mreqn iface = {};\n+ iface.imr_ifindex = lo_if_idx_;\n+ iface.imr_address = eth_if_sin_addr_;\n+ ASSERT_THAT(setsockopt(sender->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface,\n+ sizeof(iface)),\n+ SyscallSucceeds());\n+\n+ // Send a multicast packet.\n+ auto sendto_addr = V4Multicast();\n+ reinterpret_cast<sockaddr_in*>(&sendto_addr.addr)->sin_port = receiver_port;\n+ char send_buf[4] = {};\n+ ASSERT_THAT(RetryEINTR(sendto)(sender->get(), send_buf, sizeof(send_buf), 0,\n+ reinterpret_cast<sockaddr*>(&sendto_addr.addr),\n+ sendto_addr.addr_len),\n+ SyscallSucceedsWithValue(sizeof(send_buf)));\n+\n+ // Receive a multicast packet.\n+ char recv_buf[sizeof(send_buf)] = {};\n+ auto src_addr = V4EmptyAddress();\n+ ASSERT_THAT(\n+ RetryEINTR(recvfrom)(receiver->get(), recv_buf, sizeof(recv_buf), 0,\n+ reinterpret_cast<sockaddr*>(&src_addr.addr),\n+ &src_addr.addr_len),\n+ SyscallSucceedsWithValue(sizeof(recv_buf)));\n+ ASSERT_EQ(sizeof(struct sockaddr_in), src_addr.addr_len);\n+ sockaddr_in* src_addr_in = reinterpret_cast<sockaddr_in*>(&src_addr.addr);\n+\n+ // FIXME (b/137781162): When sending a multicast packet use the proper logic\n+ // to determine the packet's src-IP.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ // Verify the received source address.\n+ EXPECT_EQ(eth_if_sin_addr_.s_addr, src_addr_in->sin_addr.s_addr);\n+}\n+\n+// Check that when we are bound to one interface we can set IP_MULTICAST_IF to\n+// another interface.\n+TEST_P(IPv4UDPUnboundExternalNetworkingSocketTest,\n+ IpMulticastLoopbackBindToOneIfSetMcastIfToAnother) {\n+ // FIXME(b/137899561): Linux instance for syscall tests sometimes misses its\n+ // IPv4 address on eth0.\n+ SKIP_IF(!got_if_infos_);\n+\n+ // FIXME (b/137790511): When bound to one interface it is not possible to set\n+ // IP_MULTICAST_IF to a different interface.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ // Create sender and bind to eth interface.\n+ auto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n+ ASSERT_THAT(bind(sender->get(), eth_if_addr_, sizeof(sockaddr_in)),\n+ SyscallSucceeds());\n+\n+ // Run through all possible combinations of index and address for\n+ // IP_MULTICAST_IF that selects the loopback interface.\n+ struct {\n+ int imr_ifindex;\n+ struct in_addr imr_address;\n+ } test_data[] = {\n+ {lo_if_idx_, {}},\n+ {0, lo_if_sin_addr_},\n+ {lo_if_idx_, lo_if_sin_addr_},\n+ {lo_if_idx_, eth_if_sin_addr_},\n+ };\n+ for (auto t : test_data) {\n+ ip_mreqn iface = {};\n+ iface.imr_ifindex = t.imr_ifindex;\n+ iface.imr_address = t.imr_address;\n+ EXPECT_THAT(setsockopt(sender->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface,\n+ sizeof(iface)),\n+ SyscallSucceeds())\n+ << \"imr_index=\" << iface.imr_ifindex\n+ << \" imr_address=\" << GetAddr4Str(&iface.imr_address);\n+ }\n+}\n} // namespace testing\n} // namespace gvisor\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ipv4_udp_unbound_external_networking.h",
"new_path": "test/syscalls/linux/socket_ipv4_udp_unbound_external_networking.h",
"diff": "#ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV4_UDP_UNBOUND_EXTERNAL_NETWORKING_H_\n#define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV4_UDP_UNBOUND_EXTERNAL_NETWORKING_H_\n+#include \"test/syscalls/linux/ip_socket_test_util.h\"\n#include \"test/syscalls/linux/socket_test_util.h\"\nnamespace gvisor {\n@@ -22,7 +23,24 @@ namespace testing {\n// Test fixture for tests that apply to unbound IPv4 UDP sockets in a sandbox\n// with external networking support.\n-using IPv4UDPUnboundExternalNetworkingSocketTest = SimpleSocketTest;\n+class IPv4UDPUnboundExternalNetworkingSocketTest : public SimpleSocketTest {\n+ protected:\n+ void SetUp();\n+\n+ IfAddrHelper if_helper_;\n+\n+ // got_if_infos_ is set to false if SetUp() could not obtain all interface\n+ // infos that we need.\n+ bool got_if_infos_;\n+\n+ // Interface infos.\n+ int lo_if_idx_;\n+ int eth_if_idx_;\n+ sockaddr* lo_if_addr_;\n+ sockaddr* eth_if_addr_;\n+ in_addr lo_if_sin_addr_;\n+ in_addr eth_if_sin_addr_;\n+};\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Handle interfaceAddr and NIC options separately for IP_MULTICAST_IF
This tweaks the handling code for IP_MULTICAST_IF to ignore the InterfaceAddr
if a NICID is given.
PiperOrigin-RevId: 258982541 |
259,918 | 19.07.2019 16:29:13 | 25,200 | 32e6be0045fde1837c5ceb4ce44bffe4e4488b05 | Create the initial binary for each of the 5 runtime's test-runner.
Repeated code is planned to be factored out to improve clarity and readability. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "runsc/test/runtimes/proctor-go.go",
"diff": "+// Copyright 2019 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+// Binary proctor-go is a utility that facilitates language testing for Go.\n+\n+// There are two types of Go tests: \"Go tool tests\" and \"Go tests on disk\".\n+// \"Go tool tests\" are found and executed using `go tool dist test`.\n+// \"Go tests on disk\" are found in the /test directory and are\n+// executed using `go run run.go`.\n+package main\n+\n+import (\n+ \"flag\"\n+ \"fmt\"\n+ \"log\"\n+ \"os\"\n+ \"os/exec\"\n+ \"path/filepath\"\n+ \"regexp\"\n+)\n+\n+var (\n+ list = flag.Bool(\"list\", false, \"list all available tests\")\n+ test = flag.String(\"test\", \"\", \"run a single test from the list of available tests\")\n+ version = flag.Bool(\"v\", false, \"print out the version of node that is installed\")\n+\n+ dir = os.Getenv(\"LANG_DIR\")\n+ testDir = filepath.Join(dir, \"test\")\n+ testRegEx = regexp.MustCompile(`^.+\\.go$`)\n+\n+ // Directories with .dir contain helper files for tests.\n+ // Exclude benchmarks and stress tests.\n+ exclDirs = regexp.MustCompile(`^.+\\/(bench|stress)\\/.+$|^.+\\.dir.+$`)\n+)\n+\n+func main() {\n+ flag.Parse()\n+\n+ if *list && *test != \"\" {\n+ flag.PrintDefaults()\n+ os.Exit(1)\n+ }\n+ if *list {\n+ listTests()\n+ return\n+ }\n+ if *version {\n+ fmt.Println(\"Go version: \", os.Getenv(\"LANG_VER\"), \" is installed.\")\n+ return\n+ }\n+ runTest(*test)\n+}\n+\n+func listTests() {\n+ // Go tool dist test tests.\n+ args := []string{\"tool\", \"dist\", \"test\", \"-list\"}\n+ cmd := exec.Command(filepath.Join(dir, \"bin/go\"), args...)\n+ cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr\n+ if err := cmd.Run(); err != nil {\n+ log.Fatalf(\"Failed to list: %v\", err)\n+ }\n+\n+ // Go tests on disk.\n+ var tests []string\n+ if err := filepath.Walk(testDir, func(path string, info os.FileInfo, err error) error {\n+ name := filepath.Base(path)\n+\n+ if info.IsDir() {\n+ return nil\n+ }\n+\n+ if !testRegEx.MatchString(name) {\n+ return nil\n+ }\n+\n+ if exclDirs.MatchString(path) {\n+ return nil\n+ }\n+\n+ tests = append(tests, path)\n+ return nil\n+ }); err != nil {\n+ log.Fatalf(\"Failed to walk %q: %v\", dir, err)\n+ }\n+\n+ for _, file := range tests {\n+ fmt.Println(file)\n+ }\n+}\n+\n+func runTest(test string) {\n+ toolArgs := []string{\n+ \"tool\",\n+ \"dist\",\n+ \"test\",\n+ }\n+ diskArgs := []string{\n+ \"run\",\n+ \"run.go\",\n+ \"-v\",\n+ }\n+ if test != \"\" {\n+ // Check if test exists on disk by searching for file of the same name.\n+ // This will determine whether or not it is a Go test on disk.\n+ if _, err := os.Stat(test); err == nil {\n+ relPath, err := filepath.Rel(testDir, test)\n+ if err != nil {\n+ log.Fatalf(\"Failed to get rel path: %v\", err)\n+ }\n+ diskArgs = append(diskArgs, \"--\", relPath)\n+ cmd := exec.Command(filepath.Join(dir, \"bin/go\"), diskArgs...)\n+ cmd.Dir = testDir\n+ cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr\n+ if err := cmd.Run(); err != nil {\n+ log.Fatalf(\"Failed to run: %v\", err)\n+ }\n+ } else if os.IsNotExist(err) {\n+ // File was not found, try running as Go tool test.\n+ toolArgs = append(toolArgs, \"-run\", test)\n+ cmd := exec.Command(filepath.Join(dir, \"bin/go\"), toolArgs...)\n+ cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr\n+ if err := cmd.Run(); err != nil {\n+ log.Fatalf(\"Failed to run: %v\", err)\n+ }\n+ } else {\n+ log.Fatalf(\"Error searching for test: %v\", err)\n+ }\n+ return\n+ }\n+ runAllTool := exec.Command(filepath.Join(dir, \"bin/go\"), toolArgs...)\n+ runAllTool.Stdout, runAllTool.Stderr = os.Stdout, os.Stderr\n+ if err := runAllTool.Run(); err != nil {\n+ log.Fatalf(\"Failed to run: %v\", err)\n+ }\n+ runAllDisk := exec.Command(filepath.Join(dir, \"bin/go\"), diskArgs...)\n+ runAllDisk.Dir = testDir\n+ runAllDisk.Stdout, runAllDisk.Stderr = os.Stdout, os.Stderr\n+ if err := runAllDisk.Run(); err != nil {\n+ log.Fatalf(\"Failed to run disk tests: %v\", err)\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "runsc/test/runtimes/proctor-java.go",
"diff": "+// Copyright 2019 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+// Binary proctor-java is a utility that facilitates language testing for Java.\n+package main\n+\n+import (\n+ \"flag\"\n+ \"fmt\"\n+ \"log\"\n+ \"os\"\n+ \"os/exec\"\n+ \"path/filepath\"\n+ \"regexp\"\n+ \"strings\"\n+)\n+\n+var (\n+ list = flag.Bool(\"list\", false, \"list all available tests\")\n+ test = flag.String(\"test\", \"\", \"run a single test from the list of available tests\")\n+ version = flag.Bool(\"v\", false, \"print out the version of node that is installed\")\n+\n+ dir = os.Getenv(\"LANG_DIR\")\n+ jtreg = filepath.Join(dir, \"jtreg/bin/jtreg\")\n+ exclDirs = regexp.MustCompile(`(^(sun\\/security)|(java\\/util\\/stream)|(java\\/time)| )`)\n+)\n+\n+func main() {\n+ flag.Parse()\n+\n+ if *list && *test != \"\" {\n+ flag.PrintDefaults()\n+ os.Exit(1)\n+ }\n+ if *list {\n+ listTests()\n+ return\n+ }\n+ if *version {\n+ fmt.Println(\"Java version: \", os.Getenv(\"LANG_VER\"), \" is installed.\")\n+ return\n+ }\n+ runTest(*test)\n+}\n+\n+func listTests() {\n+ args := []string{\n+ \"-dir:test/jdk\",\n+ \"-ignore:quiet\",\n+ \"-a\",\n+ \"-listtests\",\n+ \":jdk_core\",\n+ \":jdk_svc\",\n+ \":jdk_sound\",\n+ \":jdk_imageio\",\n+ }\n+ cmd := exec.Command(jtreg, args...)\n+ cmd.Stderr = os.Stderr\n+ out, err := cmd.Output()\n+ if err != nil {\n+ log.Fatalf(\"Failed to list: %v\", err)\n+ }\n+ allTests := string(out)\n+ for _, test := range strings.Split(allTests, \"\\n\") {\n+ if !exclDirs.MatchString(test) {\n+ fmt.Println(test)\n+ }\n+ }\n+}\n+\n+func runTest(test string) {\n+ // TODO(brettlandau): Change to use listTests() for running all tests.\n+ cmd := exec.Command(\"make\", \"run-test-tier1\")\n+ if test != \"\" {\n+ args := []string{\"-dir:test/jdk/\", test}\n+ cmd = exec.Command(jtreg, args...)\n+ }\n+ cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr\n+ if err := cmd.Run(); err != nil {\n+ log.Fatalf(\"Failed to run: %v\", err)\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "runsc/test/runtimes/proctor-nodejs.go",
"diff": "+// Copyright 2019 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+// Binary proctor-nodejs is a utility that facilitates language testing for NodeJS.\n+package main\n+\n+import (\n+ \"flag\"\n+ \"fmt\"\n+ \"log\"\n+ \"os\"\n+ \"os/exec\"\n+ \"path/filepath\"\n+ \"regexp\"\n+)\n+\n+var (\n+ list = flag.Bool(\"list\", false, \"list all available tests\")\n+ test = flag.String(\"test\", \"\", \"run a single test from the list of available tests\")\n+ version = flag.Bool(\"v\", false, \"print out the version of node that is installed\")\n+\n+ dir = os.Getenv(\"LANG_DIR\")\n+ testRegEx = regexp.MustCompile(`^test-.+\\.js$`)\n+)\n+\n+func main() {\n+ flag.Parse()\n+\n+ if *list && *test != \"\" {\n+ flag.PrintDefaults()\n+ os.Exit(1)\n+ }\n+ if *list {\n+ listTests()\n+ return\n+ }\n+ if *version {\n+ fmt.Println(\"Node.js version: \", os.Getenv(\"LANG_VER\"), \" is installed.\")\n+ return\n+ }\n+ runTest(*test)\n+}\n+\n+func listTests() {\n+ var files []string\n+ root := filepath.Join(dir, \"test\")\n+\n+ err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {\n+ name := filepath.Base(path)\n+\n+ if info.IsDir() || !testRegEx.MatchString(name) {\n+ return nil\n+ }\n+\n+ relPath, err := filepath.Rel(root, path)\n+ if err != nil {\n+ return err\n+ }\n+ files = append(files, relPath)\n+ return nil\n+ })\n+\n+ if err != nil {\n+ log.Fatalf(\"Failed to walk %q: %v\", root, err)\n+ }\n+\n+ for _, file := range files {\n+ fmt.Println(file)\n+ }\n+}\n+\n+func runTest(test string) {\n+ args := []string{filepath.Join(dir, \"tools\", \"test.py\")}\n+ if test != \"\" {\n+ args = append(args, test)\n+ }\n+ cmd := exec.Command(\"/usr/bin/python\", args...)\n+ cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr\n+ if err := cmd.Run(); err != nil {\n+ log.Fatalf(\"Failed to run: %v\", err)\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "runsc/test/runtimes/proctor-php.go",
"diff": "+// Copyright 2019 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+// Binary proctor-php is a utility that facilitates language testing for PHP.\n+package main\n+\n+import (\n+ \"flag\"\n+ \"fmt\"\n+ \"log\"\n+ \"os\"\n+ \"os/exec\"\n+ \"path/filepath\"\n+ \"regexp\"\n+)\n+\n+var (\n+ list = flag.Bool(\"list\", false, \"list all available tests\")\n+ test = flag.String(\"test\", \"\", \"run a single test from the list of available tests\")\n+ version = flag.Bool(\"v\", false, \"print out the version of node that is installed\")\n+\n+ dir = os.Getenv(\"LANG_DIR\")\n+ testRegEx = regexp.MustCompile(`^.+\\.phpt$`)\n+)\n+\n+func main() {\n+ flag.Parse()\n+\n+ if *list && *test != \"\" {\n+ flag.PrintDefaults()\n+ os.Exit(1)\n+ }\n+ if *list {\n+ listTests()\n+ return\n+ }\n+ if *version {\n+ fmt.Println(\"PHP version: \", os.Getenv(\"LANG_VER\"), \" is installed.\")\n+ return\n+ }\n+ runTest(*test)\n+}\n+\n+func listTests() {\n+ var files []string\n+\n+ err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {\n+ name := filepath.Base(path)\n+\n+ if info.IsDir() || !testRegEx.MatchString(name) {\n+ return nil\n+ }\n+\n+ relPath, err := filepath.Rel(dir, path)\n+ if err != nil {\n+ return err\n+ }\n+ files = append(files, relPath)\n+ return nil\n+ })\n+\n+ if err != nil {\n+ log.Fatalf(\"Failed to walk %q: %v\", dir, err)\n+ }\n+\n+ for _, file := range files {\n+ fmt.Println(file)\n+ }\n+}\n+\n+func runTest(test string) {\n+ args := []string{\"test\", \"TESTS=\"}\n+ if test != \"\" {\n+ args[1] = args[1] + test\n+ }\n+ cmd := exec.Command(\"make\", args...)\n+ cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr\n+ if err := cmd.Run(); err != nil {\n+ log.Fatalf(\"Failed to run: %v\", err)\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "runsc/test/runtimes/proctor-python.go",
"diff": "+// Copyright 2019 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+// Binary proctor-python is a utility that facilitates language testing for Pyhton.\n+package main\n+\n+import (\n+ \"flag\"\n+ \"fmt\"\n+ \"log\"\n+ \"os\"\n+ \"os/exec\"\n+ \"path/filepath\"\n+ \"regexp\"\n+)\n+\n+var (\n+ list = flag.Bool(\"list\", false, \"list all available tests\")\n+ test = flag.String(\"test\", \"\", \"run a single test from the list of available tests\")\n+ version = flag.Bool(\"v\", false, \"print out the version of node that is installed\")\n+\n+ dir = os.Getenv(\"LANG_DIR\")\n+ testRegEx = regexp.MustCompile(`^test_.+\\.py$`)\n+)\n+\n+func main() {\n+ flag.Parse()\n+\n+ if *list && *test != \"\" {\n+ flag.PrintDefaults()\n+ os.Exit(1)\n+ }\n+ if *list {\n+ listTests()\n+ return\n+ }\n+ if *version {\n+ fmt.Println(\"Python version: \", os.Getenv(\"LANG_VER\"), \" is installed.\")\n+ return\n+ }\n+ runTest(*test)\n+}\n+\n+func listTests() {\n+ var files []string\n+ root := filepath.Join(dir, \"Lib/test\")\n+\n+ err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {\n+ name := filepath.Base(path)\n+\n+ if info.IsDir() || !testRegEx.MatchString(name) {\n+ return nil\n+ }\n+\n+ relPath, err := filepath.Rel(root, path)\n+ if err != nil {\n+ return err\n+ }\n+ files = append(files, relPath)\n+ return nil\n+ })\n+\n+ if err != nil {\n+ log.Fatalf(\"Failed to walk %q: %v\", root, err)\n+ }\n+\n+ for _, file := range files {\n+ fmt.Println(file)\n+ }\n+}\n+\n+func runTest(test string) {\n+ args := []string{\"-m\", \"test\"}\n+ if test != \"\" {\n+ args = append(args, test)\n+ }\n+ cmd := exec.Command(filepath.Join(dir, \"python\"), args...)\n+ cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr\n+ if err := cmd.Run(); err != nil {\n+ log.Fatalf(\"Failed to run: %v\", err)\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Create the initial binary for each of the 5 runtime's test-runner.
Repeated code is planned to be factored out to improve clarity and readability.
PiperOrigin-RevId: 259059978 |
259,853 | 22.07.2019 13:27:13 | 25,200 | ec906e46c0f99ab4d134c1d7bd84b48ea0a78488 | kvm: fix race between machine.Put and machine.Get
m.available.Signal() has to be called under m.mu.RLock, otherwise it can
race with machine.Get:
m.Get | m.Put
m.mu.Lock() |
Seatching available vcpu|
| m.available.Signal()
m.available.Wait | | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine.go",
"new_path": "pkg/sentry/platform/kvm/machine.go",
"diff": "@@ -388,7 +388,10 @@ func (m *machine) Get() *vCPU {\nfunc (m *machine) Put(c *vCPU) {\nc.unlock()\nruntime.UnlockOSThread()\n+\n+ m.mu.RLock()\nm.available.Signal()\n+ m.mu.RUnlock()\n}\n// newDirtySet returns a new dirty set.\n"
}
] | Go | Apache License 2.0 | google/gvisor | kvm: fix race between machine.Put and machine.Get
m.available.Signal() has to be called under m.mu.RLock, otherwise it can
race with machine.Get:
m.Get | m.Put
-------------------------------------
m.mu.Lock() |
Seatching available vcpu|
| m.available.Signal()
m.available.Wait |
PiperOrigin-RevId: 259394051 |
259,891 | 22.07.2019 17:05:02 | 25,200 | 5ddf9adb2b12a2cbccdcf609c5cc140fa0dbd81d | Fix up and add some iptables ABI. | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/BUILD",
"new_path": "pkg/abi/linux/BUILD",
"diff": "package(licenses = [\"notice\"])\n-load(\"//tools/go_stateify:defs.bzl\", \"go_library\")\n+load(\"//tools/go_stateify:defs.bzl\", \"go_library\", \"go_test\")\ngo_library(\nname = \"linux\",\n@@ -62,3 +62,13 @@ go_library(\n\"//pkg/bits\",\n],\n)\n+\n+go_test(\n+ name = \"linux_test\",\n+ size = \"small\",\n+ srcs = [\"netfilter_test.go\"],\n+ embed = [\":linux\"],\n+ deps = [\n+ \"//pkg/binary\",\n+ ],\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/netfilter.go",
"new_path": "pkg/abi/linux/netfilter.go",
"diff": "@@ -100,6 +100,21 @@ type IPTEntry struct {\n// Elems [0]byte\n}\n+// SizeOfIPTEntry is the size of an IPTEntry.\n+const SizeOfIPTEntry = 112\n+\n+// KernelIPTEntry is identical to IPTEntry, but includes the Elems field. This\n+// struct marshaled via the binary package to write an IPTEntry to userspace.\n+type KernelIPTEntry struct {\n+ IPTEntry\n+\n+ // Elems holds the data for all this rule's matches followed by the\n+ // target. It is variable length -- users have to iterate over any\n+ // matches and use TargetOffset and NextOffset to make sense of the\n+ // data.\n+ Elems []byte\n+}\n+\n// IPTIP contains information for matching a packet's IP header.\n// It corresponds to struct ipt_ip in\n// include/uapi/linux/netfilter_ipv4/ip_tables.h.\n@@ -123,10 +138,10 @@ type IPTIP struct {\nOutputInterface [IFNAMSIZ]byte\n// InputInterfaceMask is the intput interface mask.\n- InputInterfaceMast [IFNAMSIZ]byte\n+ InputInterfaceMask [IFNAMSIZ]byte\n// OuputInterfaceMask is the output interface mask.\n- OuputInterfaceMask [IFNAMSIZ]byte\n+ OutputInterfaceMask [IFNAMSIZ]byte\n// Protocol is the transport protocol.\nProtocol uint16\n@@ -138,6 +153,9 @@ type IPTIP struct {\nInverseFlags uint8\n}\n+// SizeOfIPTIP is the size of an IPTIP.\n+const SizeOfIPTIP = 84\n+\n// XTCounters holds packet and byte counts for a rule. It corresponds to struct\n// xt_counters in include/uapi/linux/netfilter/x_tables.h.\ntype XTCounters struct {\n@@ -148,6 +166,9 @@ type XTCounters struct {\nBcnt uint64\n}\n+// SizeOfXTCounters is the size of an XTCounters.\n+const SizeOfXTCounters = 16\n+\n// XTEntryMatch holds a match for a rule. For example, a user using the\n// addrtype iptables match extension would put the data for that match into an\n// XTEntryMatch. iptables-extensions(8) has a list of possible matches.\n@@ -160,11 +181,14 @@ type XTEntryMatch struct {\nMatchSize uint16\nName [XT_EXTENSION_MAXNAMELEN]byte\nRevision uint8\n- // Data is omitted here because it would cause XTEntryTarget to be an\n+ // Data is omitted here because it would cause XTEntryMatch to be an\n// extra byte larger (see http://www.catb.org/esr/structure-packing/).\n// Data [0]byte\n}\n+// SizeOfXTEntryMatch is the size of an XTEntryMatch.\n+const SizeOfXTEntryMatch = 32\n+\n// XTEntryTarget holds a target for a rule. For example, it can specify that\n// packets matching the rule should DROP, ACCEPT, or use an extension target.\n// iptables-extension(8) has a list of possible targets.\n@@ -174,7 +198,7 @@ type XTEntryMatch struct {\n// exposing different data to the user and kernel, but this struct holds only\n// the user data.\ntype XTEntryTarget struct {\n- MatchSize uint16\n+ TargetSize uint16\nName [XT_EXTENSION_MAXNAMELEN]byte\nRevision uint8\n// Data is omitted here because it would cause XTEntryTarget to be an\n@@ -182,14 +206,21 @@ type XTEntryTarget struct {\n// Data [0]byte\n}\n+// SizeOfXTEntryTarget is the size of an XTEntryTarget.\n+const SizeOfXTEntryTarget = 32\n+\n// XTStandardTarget is a builtin target, one of ACCEPT, DROP, JUMP, QUEUE, or\n// RETURN. It corresponds to struct xt_standard_target in\n// include/uapi/linux/netfilter/x_tables.h.\ntype XTStandardTarget struct {\nTarget XTEntryTarget\nVerdict int32\n+ _ [4]byte\n}\n+// SizeOfXTStandardTarget is the size of an XTStandardTarget.\n+const SizeOfXTStandardTarget = 40\n+\n// XTErrorTarget triggers an error when reached. It is also used to mark the\n// beginning of user-defined chains by putting the name of the chain in\n// ErrorName. It corresponds to struct xt_error_target in\n@@ -197,8 +228,12 @@ type XTStandardTarget struct {\ntype XTErrorTarget struct {\nTarget XTEntryTarget\nErrorName [XT_FUNCTION_MAXNAMELEN]byte\n+ _ [2]byte\n}\n+// SizeOfXTErrorTarget is the size of an XTErrorTarget.\n+const SizeOfXTErrorTarget = 64\n+\n// IPTGetinfo is the argument for the IPT_SO_GET_INFO sockopt. It corresponds\n// to struct ipt_getinfo in include/uapi/linux/netfilter_ipv4/ip_tables.h.\ntype IPTGetinfo struct {\n@@ -210,18 +245,50 @@ type IPTGetinfo struct {\nSize uint32\n}\n+// SizeOfIPTGetinfo is the size of an IPTGetinfo.\n+const SizeOfIPTGetinfo = 84\n+\n+// TableName returns the table name.\n+func (info *IPTGetinfo) TableName() string {\n+ return tableName(info.Name[:])\n+}\n+\n// IPTGetEntries is the argument for the IPT_SO_GET_ENTRIES sockopt. It\n// corresponds to struct ipt_get_entries in\n// include/uapi/linux/netfilter_ipv4/ip_tables.h.\ntype IPTGetEntries struct {\nName [XT_TABLE_MAXNAMELEN]byte\nSize uint32\n+ _ [4]byte\n// Entrytable is omitted here because it would cause IPTGetEntries to\n// be an extra byte longer (see\n// http://www.catb.org/esr/structure-packing/).\n// Entrytable [0]IPTEntry\n}\n+// TableName returns the entries' table name.\n+func (entries *IPTGetEntries) TableName() string {\n+ return tableName(entries.Name[:])\n+}\n+\n+// SizeOfIPTGetEntries is the size of an IPTGetEntries.\n+const SizeOfIPTGetEntries = 40\n+\n+// KernelIPTGetEntries is identical to IPTEntry, but includes the Elems field.\n+// This struct marshaled via the binary package to write an KernelIPTGetEntries\n+// to userspace.\n+type KernelIPTGetEntries struct {\n+ Name [XT_TABLE_MAXNAMELEN]byte\n+ Size uint32\n+ _ [4]byte\n+ Entrytable []KernelIPTEntry\n+}\n+\n+// TableName returns the entries' table name.\n+func (entries *KernelIPTGetEntries) TableName() string {\n+ return tableName(entries.Name[:])\n+}\n+\n// IPTReplace is the argument for the IPT_SO_SET_REPLACE sockopt. It\n// corresponds to struct ipt_replace in\n// include/uapi/linux/netfilter_ipv4/ip_tables.h.\n@@ -233,8 +300,20 @@ type IPTReplace struct {\nHookEntry [NF_INET_NUMHOOKS]uint32\nUnderflow [NF_INET_NUMHOOKS]uint32\nNumCounters uint32\n- Counters *XTCounters\n+ Counters uint64 // This is really a *XTCounters.\n// Entries is omitted here because it would cause IPTReplace to be an\n// extra byte longer (see http://www.catb.org/esr/structure-packing/).\n// Entries [0]IPTEntry\n}\n+\n+// SizeOfIPTReplace is the size of an IPTReplace.\n+const SizeOfIPTReplace = 96\n+\n+func tableName(name []byte) string {\n+ for i, c := range name {\n+ if c == 0 {\n+ return string(name[:i])\n+ }\n+ }\n+ return string(name)\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/abi/linux/netfilter_test.go",
"diff": "+// Copyright 2019 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 linux\n+\n+import (\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/binary\"\n+)\n+\n+func TestSizes(t *testing.T) {\n+ testCases := []struct {\n+ typ interface{}\n+ defined uintptr\n+ }{\n+ {IPTEntry{}, SizeOfIPTEntry},\n+ {IPTGetEntries{}, SizeOfIPTGetEntries},\n+ {IPTGetinfo{}, SizeOfIPTGetinfo},\n+ {IPTIP{}, SizeOfIPTIP},\n+ {IPTReplace{}, SizeOfIPTReplace},\n+ {XTCounters{}, SizeOfXTCounters},\n+ {XTEntryMatch{}, SizeOfXTEntryMatch},\n+ {XTEntryTarget{}, SizeOfXTEntryTarget},\n+ {XTErrorTarget{}, SizeOfXTErrorTarget},\n+ {XTStandardTarget{}, SizeOfXTStandardTarget},\n+ }\n+\n+ for _, tc := range testCases {\n+ if calculated := binary.Size(tc.typ); calculated != tc.defined {\n+ t.Errorf(\"%T has a defined size of %d and calculated size of %d\", tc.typ, tc.defined, calculated)\n+ }\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix up and add some iptables ABI.
PiperOrigin-RevId: 259437060 |
259,907 | 23.07.2019 15:50:35 | 25,200 | bd7708956f0c9e00e88eff9b35b22eea75e71f5f | ext: Added extent tree building logic. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/BUILD",
"new_path": "pkg/sentry/fs/ext/BUILD",
"diff": "package(licenses = [\"notice\"])\n-load(\"//tools/go_stateify:defs.bzl\", \"go_library\")\n+load(\"//tools/go_stateify:defs.bzl\", \"go_library\", \"go_test\")\ngo_library(\nname = \"ext\",\nsrcs = [\n+ \"dentry.go\",\n\"ext.go\",\n+ \"inode.go\",\n\"utils.go\",\n],\nimportpath = \"gvisor.dev/gvisor/pkg/sentry/fs/ext\",\nvisibility = [\"//pkg/sentry:internal\"],\ndeps = [\n\"//pkg/abi/linux\",\n+ \"//pkg/binary\",\n\"//pkg/sentry/fs/ext/disklayout\",\n\"//pkg/syserror\",\n],\n)\n+\n+go_test(\n+ name = \"ext_test\",\n+ size = \"small\",\n+ srcs = [\"extent_test.go\"],\n+ embed = [\":ext\"],\n+ deps = [\n+ \"//pkg/binary\",\n+ \"//pkg/sentry/fs/ext/disklayout\",\n+ \"@com_github_google_go-cmp//cmp:go_default_library\",\n+ \"@com_github_google_go-cmp//cmp/cmpopts:go_default_library\",\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext/dentry.go",
"diff": "+// Copyright 2019 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 ext\n+\n+// dentry implements vfs.DentryImpl.\n+type dentry struct {\n+ // inode is the inode represented by this dentry. Multiple Dentries may\n+ // share a single non-directory Inode (with hard links). inode is\n+ // immutable.\n+ inode *inode\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/disklayout/inode.go",
"new_path": "pkg/sentry/fs/ext/disklayout/inode.go",
"diff": "@@ -107,16 +107,17 @@ type Inode interface {\n// Flags returns InodeFlags which represents the inode flags.\nFlags() InodeFlags\n- // Blocks returns the underlying inode.i_block array. This field is special\n- // and is used to store various kinds of things depending on the filesystem\n- // version and inode type.\n+ // Data returns the underlying inode.i_block array as a slice so it's\n+ // modifiable. This field is special and is used to store various kinds of\n+ // things depending on the filesystem version and inode type. The underlying\n+ // field name in Linux is a little misleading.\n// - In ext2/ext3, it contains the block map.\n- // - In ext4, it contains the extent tree.\n+ // - In ext4, it contains the extent tree root node.\n// - For inline files, it contains the file contents.\n// - For symlinks, it contains the link path (if it fits here).\n//\n// See https://www.kernel.org/doc/html/latest/filesystems/ext4/dynamic.html#the-contents-of-inode-i-block.\n- Blocks() [60]byte\n+ Data() []byte\n}\n// Inode flags. This is not comprehensive and flags which were not used in\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/disklayout/inode_old.go",
"new_path": "pkg/sentry/fs/ext/disklayout/inode_old.go",
"diff": "@@ -47,7 +47,7 @@ type InodeOld struct {\nBlocksCountLo uint32\nFlagsRaw uint32\nVersionLo uint32 // This is OS dependent.\n- BlocksRaw [60]byte\n+ DataRaw [60]byte\nGeneration uint32\nFileACLLo uint32\nSizeHi uint32\n@@ -113,5 +113,5 @@ func (in *InodeOld) LinksCount() uint16 { return in.LinksCountRaw }\n// Flags implements Inode.Flags.\nfunc (in *InodeOld) Flags() InodeFlags { return InodeFlagsFromInt(in.FlagsRaw) }\n-// Blocks implements Inode.Blocks.\n-func (in *InodeOld) Blocks() [60]byte { return in.BlocksRaw }\n+// Data implements Inode.Data.\n+func (in *InodeOld) Data() []byte { return in.DataRaw[:] }\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/ext.go",
"new_path": "pkg/sentry/fs/ext/ext.go",
"diff": "@@ -24,8 +24,8 @@ import (\n\"gvisor.dev/gvisor/pkg/syserror\"\n)\n-// Filesystem implements vfs.FilesystemImpl.\n-type Filesystem struct {\n+// filesystem implements vfs.FilesystemImpl.\n+type filesystem struct {\n// dev is the ReadSeeker for the underlying fs device and is protected by mu.\ndev io.ReadSeeker\n@@ -50,9 +50,9 @@ type Filesystem struct {\nbgs []disklayout.BlockGroup\n}\n-// newFilesystem is the Filesystem constructor.\n-func newFilesystem(dev io.ReadSeeker) (*Filesystem, error) {\n- fs := Filesystem{dev: dev}\n+// newFilesystem is the filesystem constructor.\n+func newFilesystem(dev io.ReadSeeker) (*filesystem, error) {\n+ fs := filesystem{dev: dev}\nvar err error\nfs.sb, err = readSuperBlock(dev)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext/extent_test.go",
"diff": "+// Copyright 2019 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 ext\n+\n+import (\n+ \"bytes\"\n+ \"testing\"\n+\n+ \"github.com/google/go-cmp/cmp\"\n+ \"github.com/google/go-cmp/cmp/cmpopts\"\n+ \"gvisor.dev/gvisor/pkg/binary\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fs/ext/disklayout\"\n+)\n+\n+// TestExtentTree tests the extent tree building logic.\n+//\n+// Test tree:\n+// 0.{Head}[Idx][Idx]\n+// / \\\n+// / \\\n+// 1.{Head}[Ext][Ext] 2.{Head}[Idx]\n+// / | \\\n+// [Phy] [Phy, Phy] 3.{Head}[Ext]\n+// |\n+// [Phy, Phy, Phy]\n+//\n+// Legend:\n+// - Head = ExtentHeader\n+// - Idx = ExtentIdx\n+// - Ext = Extent\n+// - Phy = Physical Block\n+//\n+// Please note that ext4 might not construct extent trees looking like this.\n+// This is purely for testing the tree traversal logic.\n+func TestExtentTree(t *testing.T) {\n+ blkSize := uint64(64) // No block has more than 1 header + 4 entries.\n+ mockDisk := make([]byte, blkSize*10)\n+ mockInode := &inode{diskInode: &disklayout.InodeNew{}}\n+\n+ node3 := &disklayout.ExtentNode{\n+ Header: disklayout.ExtentHeader{\n+ Magic: disklayout.ExtentMagic,\n+ NumEntries: 1,\n+ MaxEntries: 4,\n+ Height: 0,\n+ },\n+ Entries: []disklayout.ExtentEntryPair{\n+ {\n+ Entry: &disklayout.Extent{\n+ FirstFileBlock: 3,\n+ Length: 3,\n+ StartBlockLo: 6,\n+ },\n+ Node: nil,\n+ },\n+ },\n+ }\n+\n+ node2 := &disklayout.ExtentNode{\n+ Header: disklayout.ExtentHeader{\n+ Magic: disklayout.ExtentMagic,\n+ NumEntries: 1,\n+ MaxEntries: 4,\n+ Height: 1,\n+ },\n+ Entries: []disklayout.ExtentEntryPair{\n+ {\n+ Entry: &disklayout.ExtentIdx{\n+ FirstFileBlock: 3,\n+ ChildBlockLo: 2,\n+ },\n+ Node: node3,\n+ },\n+ },\n+ }\n+\n+ node1 := &disklayout.ExtentNode{\n+ Header: disklayout.ExtentHeader{\n+ Magic: disklayout.ExtentMagic,\n+ NumEntries: 2,\n+ MaxEntries: 4,\n+ Height: 0,\n+ },\n+ Entries: []disklayout.ExtentEntryPair{\n+ {\n+ Entry: &disklayout.Extent{\n+ FirstFileBlock: 0,\n+ Length: 1,\n+ StartBlockLo: 3,\n+ },\n+ Node: nil,\n+ },\n+ {\n+ Entry: &disklayout.Extent{\n+ FirstFileBlock: 1,\n+ Length: 2,\n+ StartBlockLo: 4,\n+ },\n+ Node: nil,\n+ },\n+ },\n+ }\n+\n+ node0 := &disklayout.ExtentNode{\n+ Header: disklayout.ExtentHeader{\n+ Magic: disklayout.ExtentMagic,\n+ NumEntries: 2,\n+ MaxEntries: 4,\n+ Height: 2,\n+ },\n+ Entries: []disklayout.ExtentEntryPair{\n+ {\n+ Entry: &disklayout.ExtentIdx{\n+ FirstFileBlock: 0,\n+ ChildBlockLo: 0,\n+ },\n+ Node: node1,\n+ },\n+ {\n+ Entry: &disklayout.ExtentIdx{\n+ FirstFileBlock: 3,\n+ ChildBlockLo: 1,\n+ },\n+ Node: node2,\n+ },\n+ },\n+ }\n+\n+ writeTree(mockInode, mockDisk, node0, blkSize)\n+\n+ r := bytes.NewReader(mockDisk)\n+ if err := mockInode.buildExtTree(r, blkSize); err != nil {\n+ t.Fatalf(\"inode.buildExtTree failed: %v\", err)\n+ }\n+\n+ if diff := cmp.Diff(&mockInode.root, node0, cmpopts.IgnoreUnexported(disklayout.ExtentNode{})); diff != \"\" {\n+ t.Errorf(\"extent tree mismatch (-want +got):\\n%s\", diff)\n+ }\n+}\n+\n+// writeTree writes the tree represented by `root` to the inode and disk passed.\n+func writeTree(in *inode, disk []byte, root *disklayout.ExtentNode, blkSize uint64) {\n+ rootData := binary.Marshal(nil, binary.LittleEndian, root.Header)\n+ for _, ep := range root.Entries {\n+ rootData = binary.Marshal(rootData, binary.LittleEndian, ep.Entry)\n+ }\n+\n+ copy(in.diskInode.Data(), rootData)\n+\n+ if root.Header.Height > 0 {\n+ for _, ep := range root.Entries {\n+ writeTreeToDisk(disk, ep, blkSize)\n+ }\n+ }\n+}\n+\n+// writeTreeToDisk is the recursive step for writeTree which writes the tree\n+// on the disk only.\n+func writeTreeToDisk(disk []byte, curNode disklayout.ExtentEntryPair, blkSize uint64) {\n+ nodeData := binary.Marshal(nil, binary.LittleEndian, curNode.Node.Header)\n+ for _, ep := range curNode.Node.Entries {\n+ nodeData = binary.Marshal(nodeData, binary.LittleEndian, ep.Entry)\n+ }\n+\n+ copy(disk[curNode.Entry.PhysicalBlock()*blkSize:], nodeData)\n+\n+ if curNode.Node.Header.Height > 0 {\n+ for _, ep := range curNode.Node.Entries {\n+ writeTreeToDisk(disk, ep, blkSize)\n+ }\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext/inode.go",
"diff": "+// Copyright 2019 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 ext\n+\n+import (\n+ \"io\"\n+ \"sync/atomic\"\n+\n+ \"gvisor.dev/gvisor/pkg/binary\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fs/ext/disklayout\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+)\n+\n+// inode represents an ext inode.\n+type inode struct {\n+ // refs is a reference count. refs is accessed using atomic memory operations.\n+ refs int64\n+\n+ // diskInode gives us access to the inode struct on disk. Immutable.\n+ diskInode disklayout.Inode\n+\n+ // root is the root extent node. This lives in the 60 byte diskInode.Blocks().\n+ // Immutable.\n+ root disklayout.ExtentNode\n+}\n+\n+// incRef increments the inode ref count.\n+func (in *inode) incRef() {\n+ atomic.AddInt64(&in.refs, 1)\n+}\n+\n+// tryIncRef tries to increment the ref count. Returns true if successful.\n+func (in *inode) tryIncRef() bool {\n+ for {\n+ refs := atomic.LoadInt64(&in.refs)\n+ if refs == 0 {\n+ return false\n+ }\n+ if atomic.CompareAndSwapInt64(&in.refs, refs, refs+1) {\n+ return true\n+ }\n+ }\n+}\n+\n+// decRef decrements the inode ref count.\n+func (in *inode) decRef() {\n+ if refs := atomic.AddInt64(&in.refs, -1); refs < 0 {\n+ panic(\"ext.inode.decRef() called without holding a reference\")\n+ }\n+}\n+\n+// buildExtTree builds the extent tree by reading it from disk by doing\n+// running a simple DFS. It first reads the root node from the inode struct in\n+// memory. Then it recursively builds the rest of the tree by reading it off\n+// disk.\n+//\n+// Preconditions:\n+// - Must have mutual exclusion on device fd.\n+// - Inode flag InExtents must be set.\n+func (in *inode) buildExtTree(dev io.ReadSeeker, blkSize uint64) error {\n+ rootNodeData := in.diskInode.Data()\n+\n+ var rootHeader disklayout.ExtentHeader\n+ binary.Unmarshal(rootNodeData[:disklayout.ExtentStructsSize], binary.LittleEndian, &rootHeader)\n+\n+ // Root node can not have more than 4 entries: 60 bytes = 1 header + 4 entries.\n+ if rootHeader.NumEntries > 4 {\n+ // read(2) specifies that EINVAL should be returned if the file is unsuitable\n+ // for reading.\n+ return syserror.EINVAL\n+ }\n+\n+ rootEntries := make([]disklayout.ExtentEntryPair, rootHeader.NumEntries)\n+ for i, off := uint16(0), disklayout.ExtentStructsSize; i < rootHeader.NumEntries; i, off = i+1, off+disklayout.ExtentStructsSize {\n+ var curEntry disklayout.ExtentEntry\n+ if rootHeader.Height == 0 {\n+ // Leaf node.\n+ curEntry = &disklayout.Extent{}\n+ } else {\n+ // Internal node.\n+ curEntry = &disklayout.ExtentIdx{}\n+ }\n+ binary.Unmarshal(rootNodeData[off:off+disklayout.ExtentStructsSize], binary.LittleEndian, curEntry)\n+ rootEntries[i].Entry = curEntry\n+ }\n+\n+ // If this node is internal, perform DFS.\n+ if rootHeader.Height > 0 {\n+ for i := uint16(0); i < rootHeader.NumEntries; i++ {\n+ var err error\n+ if rootEntries[i].Node, err = buildExtTreeFromDisk(dev, rootEntries[i].Entry, blkSize); err != nil {\n+ return err\n+ }\n+ }\n+ }\n+\n+ in.root = disklayout.ExtentNode{rootHeader, rootEntries}\n+ return nil\n+}\n+\n+// buildExtTreeFromDisk reads the extent tree nodes from disk and recursively\n+// builds the tree. Performs a simple DFS. It returns the ExtentNode pointed to\n+// by the ExtentEntry.\n+//\n+// Preconditions: Must have mutual exclusion on device fd.\n+func buildExtTreeFromDisk(dev io.ReadSeeker, entry disklayout.ExtentEntry, blkSize uint64) (*disklayout.ExtentNode, error) {\n+ var header disklayout.ExtentHeader\n+ off := entry.PhysicalBlock() * blkSize\n+ if err := readFromDisk(dev, int64(off), &header); err != nil {\n+ return nil, err\n+ }\n+\n+ entries := make([]disklayout.ExtentEntryPair, header.NumEntries)\n+ for i, off := uint16(0), off+disklayout.ExtentStructsSize; i < header.NumEntries; i, off = i+1, off+disklayout.ExtentStructsSize {\n+ var curEntry disklayout.ExtentEntry\n+ if header.Height == 0 {\n+ // Leaf node.\n+ curEntry = &disklayout.Extent{}\n+ } else {\n+ // Internal node.\n+ curEntry = &disklayout.ExtentIdx{}\n+ }\n+\n+ if err := readFromDisk(dev, int64(off), curEntry); err != nil {\n+ return nil, err\n+ }\n+ entries[i].Entry = curEntry\n+ }\n+\n+ // If this node is internal, perform DFS.\n+ if header.Height > 0 {\n+ for i := uint16(0); i < header.NumEntries; i++ {\n+ var err error\n+ entries[i].Node, err = buildExtTreeFromDisk(dev, entries[i].Entry, blkSize)\n+ if err != nil {\n+ return nil, err\n+ }\n+ }\n+ }\n+\n+ return &disklayout.ExtentNode{header, entries}, nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/utils.go",
"new_path": "pkg/sentry/fs/ext/utils.go",
"diff": "@@ -27,6 +27,8 @@ import (\n//\n// All disk reads should use this helper so we avoid reading from stale\n// previously used offsets. This function forces the offset parameter.\n+//\n+// Precondition: Must have mutual exclusion on device fd.\nfunc readFromDisk(dev io.ReadSeeker, abOff int64, v interface{}) error {\nif _, err := dev.Seek(abOff, io.SeekStart); err != nil {\nreturn syserror.EIO\n@@ -42,6 +44,8 @@ func readFromDisk(dev io.ReadSeeker, abOff int64, v interface{}) error {\n// readSuperBlock reads the SuperBlock from block group 0 in the underlying\n// device. There are three versions of the superblock. This function identifies\n// and returns the correct version.\n+//\n+// Precondition: Must have mutual exclusion on device fd.\nfunc readSuperBlock(dev io.ReadSeeker) (disklayout.SuperBlock, error) {\nvar sb disklayout.SuperBlock = &disklayout.SuperBlockOld{}\nif err := readFromDisk(dev, disklayout.SbOffset, sb); err != nil {\n@@ -82,6 +86,8 @@ func blockGroupsCount(sb disklayout.SuperBlock) uint64 {\n// readBlockGroups reads the block group descriptor table from block group 0 in\n// the underlying device.\n+//\n+// Precondition: Must have mutual exclusion on device fd.\nfunc readBlockGroups(dev io.ReadSeeker, sb disklayout.SuperBlock) ([]disklayout.BlockGroup, error) {\nbgCount := blockGroupsCount(sb)\nbgdSize := uint64(sb.BgDescSize())\n"
}
] | Go | Apache License 2.0 | google/gvisor | ext: Added extent tree building logic.
PiperOrigin-RevId: 259628657 |
259,907 | 23.07.2019 18:59:55 | 25,200 | d7bb79b6f177e8c58d47695e0ee1a072475463c4 | ext: Add ext2 and ext3 tiny images. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/assets/README.md",
"new_path": "pkg/sentry/fs/ext/assets/README.md",
"diff": "-### Tiny Ext4 Image\n+### Tiny Ext(2/3/4) Images\n-The image is of size 64Kb which supports 64 1k blocks and 16 inodes. This is the\n-smallest size mkfs.ext4 works with.\n+The images are of size 64Kb which supports 64 1k blocks and 16 inodes. This is\n+the smallest size mkfs.ext(2/3/4) works with.\n-This image was generated using the following commands.\n+These images were generated using the following commands.\n```bash\n-fallocate -l 64K tiny.ext4\n-mkfs.ext4 -j tiny.ext4\n+fallocate -l 64K tiny.ext$VERSION\n+mkfs.ext$VERSION -j tiny.ext$VERSION\n```\n+where `VERSION` is `2`, `3` or `4`.\n+\nYou can mount it using:\n```bash\n-sudo mount -o loop tiny.ext4 $MOUNTPOINT\n+sudo mount -o loop tiny.ext$VERSION $MOUNTPOINT\n```\n`file.txt`, `bigfile.txt` and `symlink.txt` were added to this image by just\n@@ -21,8 +23,14 @@ mounting it and copying (while preserving links) those files to the mountpoint\ndirectory using:\n```bash\n-sudo cp -P {file.txt,symlink.txt,bigfile.txt} $MOUNTPOINT/\n+sudo cp -P {file.txt,symlink.txt,bigfile.txt} $MOUNTPOINT\n```\nThe files in this directory mirror the contents and organisation of the files\nstored in the image.\n+\n+You can umount the filesystem using:\n+\n+```bash\n+sudo umount $MOUNTPOINT\n+```\n"
},
{
"change_type": "ADD",
"old_path": "pkg/sentry/fs/ext/assets/tiny.ext2",
"new_path": "pkg/sentry/fs/ext/assets/tiny.ext2",
"diff": "Binary files /dev/null and b/pkg/sentry/fs/ext/assets/tiny.ext2 differ\n"
},
{
"change_type": "ADD",
"old_path": "pkg/sentry/fs/ext/assets/tiny.ext3",
"new_path": "pkg/sentry/fs/ext/assets/tiny.ext3",
"diff": "Binary files /dev/null and b/pkg/sentry/fs/ext/assets/tiny.ext3 differ\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/extent_test.go",
"new_path": "pkg/sentry/fs/ext/extent_test.go",
"diff": "@@ -145,7 +145,8 @@ func TestExtentTree(t *testing.T) {\nt.Fatalf(\"inode.buildExtTree failed: %v\", err)\n}\n- if diff := cmp.Diff(&mockInode.root, node0, cmpopts.IgnoreUnexported(disklayout.ExtentNode{})); diff != \"\" {\n+ opt := cmpopts.IgnoreUnexported(disklayout.ExtentIdx{}, disklayout.ExtentHeader{})\n+ if diff := cmp.Diff(&mockInode.root, node0, opt); diff != \"\" {\nt.Errorf(\"extent tree mismatch (-want +got):\\n%s\", diff)\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | ext: Add ext2 and ext3 tiny images.
PiperOrigin-RevId: 259657917 |
259,907 | 23.07.2019 20:34:49 | 25,200 | 7e38d643334647fb79c7cc8be35745699de264e6 | ext: Inode creation logic. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/disklayout/inode_new.go",
"new_path": "pkg/sentry/fs/ext/disklayout/inode_new.go",
"diff": "@@ -62,7 +62,7 @@ func (in *InodeNew) Size() uint64 {\n// InodeSize implements Inode.InodeSize.\nfunc (in *InodeNew) InodeSize() uint16 {\n- return oldInodeSize + in.ExtraInodeSize\n+ return OldInodeSize + in.ExtraInodeSize\n}\n// ChangeTime implements Inode.ChangeTime.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/disklayout/inode_old.go",
"new_path": "pkg/sentry/fs/ext/disklayout/inode_old.go",
"diff": "@@ -21,8 +21,8 @@ import (\n)\nconst (\n- // oldInodeSize is the inode size in ext2/ext3.\n- oldInodeSize = 128\n+ // OldInodeSize is the inode size in ext2/ext3.\n+ OldInodeSize = 128\n)\n// InodeOld implements Inode interface. It emulates ext2/ext3 inode struct.\n@@ -85,7 +85,7 @@ func (in *InodeOld) Size() uint64 {\n}\n// InodeSize implements Inode.InodeSize.\n-func (in *InodeOld) InodeSize() uint16 { return oldInodeSize }\n+func (in *InodeOld) InodeSize() uint16 { return OldInodeSize }\n// AccessTime implements Inode.AccessTime.\nfunc (in *InodeOld) AccessTime() time.Time {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/disklayout/inode_test.go",
"new_path": "pkg/sentry/fs/ext/disklayout/inode_test.go",
"diff": "@@ -24,7 +24,7 @@ import (\n// TestInodeSize tests that the inode structs are of the correct size.\nfunc TestInodeSize(t *testing.T) {\n- assertSize(t, InodeOld{}, oldInodeSize)\n+ assertSize(t, InodeOld{}, OldInodeSize)\n// This was updated from 156 bytes to 160 bytes in Oct 2015.\nassertSize(t, InodeNew{}, 160)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/disklayout/superblock_old.go",
"new_path": "pkg/sentry/fs/ext/disklayout/superblock_old.go",
"diff": "@@ -81,7 +81,7 @@ func (sb *SuperBlockOld) ClusterSize() uint64 { return 1 << (10 + sb.LogClusterS\nfunc (sb *SuperBlockOld) ClustersPerGroup() uint32 { return sb.ClustersPerGroupRaw }\n// InodeSize implements SuperBlock.InodeSize.\n-func (sb *SuperBlockOld) InodeSize() uint16 { return oldInodeSize }\n+func (sb *SuperBlockOld) InodeSize() uint16 { return OldInodeSize }\n// InodesPerGroup implements SuperBlock.InodesPerGroup.\nfunc (sb *SuperBlockOld) InodesPerGroup() uint32 { return sb.InodesPerGroupRaw }\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/ext.go",
"new_path": "pkg/sentry/fs/ext/ext.go",
"diff": "@@ -26,21 +26,29 @@ import (\n// filesystem implements vfs.FilesystemImpl.\ntype filesystem struct {\n- // dev is the ReadSeeker for the underlying fs device and is protected by mu.\n- dev io.ReadSeeker\n+ // mu serializes changes to the Dentry tree and the usage of the read seeker.\n+ mu sync.Mutex\n- // mu synchronizes the usage of dev. The ext filesystems take locality into\n- // condsideration, i.e. data blocks of a file will tend to be placed close\n- // together. On a spinning disk, locality reduces the amount of movement of\n- // the head hence speeding up IO operations. On an SSD there are no moving\n- // parts but locality increases the size of each transer request. Hence,\n- // having mutual exclusion on the read seeker while reading a file *should*\n- // help in achieving the intended performance gains.\n+ // dev is the ReadSeeker for the underlying fs device. It is protected by mu.\n+ //\n+ // The ext filesystems aim to maximize locality, i.e. place all the data\n+ // blocks of a file close together. On a spinning disk, locality reduces the\n+ // amount of movement of the head hence speeding up IO operations. On an SSD\n+ // there are no moving parts but locality increases the size of each transer\n+ // request. Hence, having mutual exclusion on the read seeker while reading a\n+ // file *should* help in achieving the intended performance gains.\n//\n// Note: This synchronization was not coupled with the ReadSeeker itself\n// because we want to synchronize across read/seek operations for the\n// performance gains mentioned above. Helps enforcing one-file-at-a-time IO.\n- mu sync.Mutex\n+ dev io.ReadSeeker\n+\n+ // inodeCache maps absolute inode numbers to the corresponding Inode struct.\n+ // Inodes should be removed from this once their reference count hits 0.\n+ //\n+ // Protected by mu because every addition and removal from this corresponds to\n+ // a change in the dentry tree.\n+ inodeCache map[uint32]*inode\n// sb represents the filesystem superblock. Immutable after initialization.\nsb disklayout.SuperBlock\n@@ -52,7 +60,7 @@ type filesystem struct {\n// newFilesystem is the filesystem constructor.\nfunc newFilesystem(dev io.ReadSeeker) (*filesystem, error) {\n- fs := filesystem{dev: dev}\n+ fs := filesystem{dev: dev, inodeCache: make(map[uint32]*inode)}\nvar err error\nfs.sb, err = readSuperBlock(dev)\n@@ -73,3 +81,21 @@ func newFilesystem(dev io.ReadSeeker) (*filesystem, error) {\nreturn &fs, nil\n}\n+\n+// getOrCreateInode gets the inode corresponding to the inode number passed in.\n+// It creates a new one with the given inode number if one does not exist.\n+//\n+// Preconditions: must be holding fs.mu.\n+func (fs *filesystem) getOrCreateInode(inodeNum uint32) (*inode, error) {\n+ if in, ok := fs.inodeCache[inodeNum]; ok {\n+ return in, nil\n+ }\n+\n+ in, err := newInode(fs.dev, fs.sb, fs.bgs, inodeNum)\n+ if err != nil {\n+ return nil, err\n+ }\n+\n+ fs.inodeCache[inodeNum] = in\n+ return in, nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/extent_test.go",
"new_path": "pkg/sentry/fs/ext/extent_test.go",
"diff": "@@ -146,7 +146,7 @@ func TestExtentTree(t *testing.T) {\n}\nopt := cmpopts.IgnoreUnexported(disklayout.ExtentIdx{}, disklayout.ExtentHeader{})\n- if diff := cmp.Diff(&mockInode.root, node0, opt); diff != \"\" {\n+ if diff := cmp.Diff(mockInode.root, node0, opt); diff != \"\" {\nt.Errorf(\"extent tree mismatch (-want +got):\\n%s\", diff)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/inode.go",
"new_path": "pkg/sentry/fs/ext/inode.go",
"diff": "@@ -28,12 +28,16 @@ type inode struct {\n// refs is a reference count. refs is accessed using atomic memory operations.\nrefs int64\n+ // inodeNum is the inode number of this inode on disk. This is used to\n+ // identify inodes within the ext filesystem.\n+ inodeNum uint32\n+\n// diskInode gives us access to the inode struct on disk. Immutable.\ndiskInode disklayout.Inode\n// root is the root extent node. This lives in the 60 byte diskInode.Blocks().\n- // Immutable.\n- root disklayout.ExtentNode\n+ // Immutable. Nil if the inode does not use extents.\n+ root *disklayout.ExtentNode\n}\n// incRef increments the inode ref count.\n@@ -54,20 +58,71 @@ func (in *inode) tryIncRef() bool {\n}\n}\n-// decRef decrements the inode ref count.\n-func (in *inode) decRef() {\n- if refs := atomic.AddInt64(&in.refs, -1); refs < 0 {\n+// decRef decrements the inode ref count and releases the inode resources if\n+// the ref count hits 0.\n+//\n+// Preconditions: Must have locked fs.mu.\n+func (in *inode) decRef(fs *filesystem) {\n+ if refs := atomic.AddInt64(&in.refs, -1); refs == 0 {\n+ delete(fs.inodeCache, in.inodeNum)\n+ } else if refs < 0 {\npanic(\"ext.inode.decRef() called without holding a reference\")\n}\n}\n+// newInode is the inode constructor. Reads the inode off disk. Identifies\n+// inodes based on the absolute inode number on disk.\n+//\n+// Preconditions: Must hold the mutex of the filesystem containing dev.\n+func newInode(dev io.ReadSeeker, sb disklayout.SuperBlock, bgs []disklayout.BlockGroup, inodeNum uint32) (*inode, error) {\n+ if inodeNum == 0 {\n+ panic(\"inode number 0 on ext filesystems is not possible\")\n+ }\n+\n+ in := &inode{refs: 1, inodeNum: inodeNum}\n+ inodeRecordSize := sb.InodeSize()\n+ if inodeRecordSize == disklayout.OldInodeSize {\n+ in.diskInode = &disklayout.InodeOld{}\n+ } else {\n+ in.diskInode = &disklayout.InodeNew{}\n+ }\n+\n+ // Calculate where the inode is actually placed.\n+ inodesPerGrp := sb.InodesPerGroup()\n+ blkSize := sb.BlockSize()\n+ inodeTableOff := bgs[getBGNum(inodeNum, inodesPerGrp)].InodeTable() * blkSize\n+ inodeOff := inodeTableOff + uint64(uint32(inodeRecordSize)*getBGOff(inodeNum, inodesPerGrp))\n+\n+ // Read it from disk and figure out which type of inode this is.\n+ if err := readFromDisk(dev, int64(inodeOff), in.diskInode); err != nil {\n+ return nil, err\n+ }\n+\n+ if in.diskInode.Flags().Extents {\n+ in.buildExtTree(dev, blkSize)\n+ }\n+\n+ return in, nil\n+}\n+\n+// getBGNum returns the block group number that a given inode belongs to.\n+func getBGNum(inodeNum uint32, inodesPerGrp uint32) uint32 {\n+ return (inodeNum - 1) / inodesPerGrp\n+}\n+\n+// getBGOff returns the offset at which the given inode lives in the block\n+// group's inode table, i.e. the index of the inode in the inode table.\n+func getBGOff(inodeNum uint32, inodesPerGrp uint32) uint32 {\n+ return (inodeNum - 1) % inodesPerGrp\n+}\n+\n// buildExtTree builds the extent tree by reading it from disk by doing\n// running a simple DFS. It first reads the root node from the inode struct in\n// memory. Then it recursively builds the rest of the tree by reading it off\n// disk.\n//\n// Preconditions:\n-// - Must have mutual exclusion on device fd.\n+// - Must hold the mutex of the filesystem containing dev.\n// - Inode flag InExtents must be set.\nfunc (in *inode) buildExtTree(dev io.ReadSeeker, blkSize uint64) error {\nrootNodeData := in.diskInode.Data()\n@@ -106,7 +161,7 @@ func (in *inode) buildExtTree(dev io.ReadSeeker, blkSize uint64) error {\n}\n}\n- in.root = disklayout.ExtentNode{rootHeader, rootEntries}\n+ in.root = &disklayout.ExtentNode{rootHeader, rootEntries}\nreturn nil\n}\n@@ -114,7 +169,7 @@ func (in *inode) buildExtTree(dev io.ReadSeeker, blkSize uint64) error {\n// builds the tree. Performs a simple DFS. It returns the ExtentNode pointed to\n// by the ExtentEntry.\n//\n-// Preconditions: Must have mutual exclusion on device fd.\n+// Preconditions: Must hold the mutex of the filesystem containing dev.\nfunc buildExtTreeFromDisk(dev io.ReadSeeker, entry disklayout.ExtentEntry, blkSize uint64) (*disklayout.ExtentNode, error) {\nvar header disklayout.ExtentHeader\noff := entry.PhysicalBlock() * blkSize\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/utils.go",
"new_path": "pkg/sentry/fs/ext/utils.go",
"diff": "@@ -28,7 +28,7 @@ import (\n// All disk reads should use this helper so we avoid reading from stale\n// previously used offsets. This function forces the offset parameter.\n//\n-// Precondition: Must have mutual exclusion on device fd.\n+// Precondition: Must hold the mutex of the filesystem containing dev.\nfunc readFromDisk(dev io.ReadSeeker, abOff int64, v interface{}) error {\nif _, err := dev.Seek(abOff, io.SeekStart); err != nil {\nreturn syserror.EIO\n@@ -45,7 +45,7 @@ func readFromDisk(dev io.ReadSeeker, abOff int64, v interface{}) error {\n// device. There are three versions of the superblock. This function identifies\n// and returns the correct version.\n//\n-// Precondition: Must have mutual exclusion on device fd.\n+// Precondition: Must hold the mutex of the filesystem containing dev.\nfunc readSuperBlock(dev io.ReadSeeker) (disklayout.SuperBlock, error) {\nvar sb disklayout.SuperBlock = &disklayout.SuperBlockOld{}\nif err := readFromDisk(dev, disklayout.SbOffset, sb); err != nil {\n@@ -87,7 +87,7 @@ func blockGroupsCount(sb disklayout.SuperBlock) uint64 {\n// readBlockGroups reads the block group descriptor table from block group 0 in\n// the underlying device.\n//\n-// Precondition: Must have mutual exclusion on device fd.\n+// Precondition: Must hold the mutex of the filesystem containing dev.\nfunc readBlockGroups(dev io.ReadSeeker, sb disklayout.SuperBlock) ([]disklayout.BlockGroup, error) {\nbgCount := blockGroupsCount(sb)\nbgdSize := uint64(sb.BgDescSize())\n"
}
] | Go | Apache License 2.0 | google/gvisor | ext: Inode creation logic.
PiperOrigin-RevId: 259666476 |
259,976 | 30.04.2019 23:35:36 | -28,800 | 1c5b6d9bd26ba090610d05366df90d4fee91c677 | Use different pidns among different containers
The different containers in a sandbox used only one pid
namespace before. This results in that a container can see
the processes in another container in the same sandbox.
This patch use different pid namespace for different containers. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/control/proc.go",
"new_path": "pkg/sentry/control/proc.go",
"diff": "@@ -92,6 +92,9 @@ type ExecArgs struct {\n// ContainerID is the container for the process being executed.\nContainerID string\n+\n+ // PIDNamespace is the pid namespace for the process being executed.\n+ PIDNamespace *kernel.PIDNamespace\n}\n// String prints the arguments as a string.\n@@ -162,6 +165,7 @@ func (proc *Proc) execAsync(args *ExecArgs) (*kernel.ThreadGroup, kernel.ThreadI\nIPCNamespace: proc.Kernel.RootIPCNamespace(),\nAbstractSocketNamespace: proc.Kernel.RootAbstractSocketNamespace(),\nContainerID: args.ContainerID,\n+ PIDNamespace: args.PIDNamespace,\n}\nif initArgs.Root != nil {\n// initArgs must hold a reference on Root, which will be\n@@ -341,7 +345,7 @@ func Processes(k *kernel.Kernel, containerID string, out *[]*Process) error {\nts := k.TaskSet()\nnow := k.RealtimeClock().Now()\nfor _, tg := range ts.Root.ThreadGroups() {\n- pid := ts.Root.IDOfThreadGroup(tg)\n+ pid := tg.PIDNamespace().IDOfThreadGroup(tg)\n// If tg has already been reaped ignore it.\nif pid == 0 {\ncontinue\n@@ -352,7 +356,7 @@ func Processes(k *kernel.Kernel, containerID string, out *[]*Process) error {\nppid := kernel.ThreadID(0)\nif p := tg.Leader().Parent(); p != nil {\n- ppid = ts.Root.IDOfThreadGroup(p.ThreadGroup())\n+ ppid = p.PIDNamespace().IDOfThreadGroup(p.ThreadGroup())\n}\n*out = append(*out, &Process{\nUID: tg.Leader().Credentials().EffectiveKUID,\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/kernel.go",
"new_path": "pkg/sentry/kernel/kernel.go",
"diff": "@@ -622,6 +622,9 @@ type CreateProcessArgs struct {\n// IPCNamespace is the initial IPC namespace.\nIPCNamespace *IPCNamespace\n+ // PIDNamespace is the initial PID Namespace.\n+ PIDNamespace *PIDNamespace\n+\n// AbstractSocketNamespace is the initial Abstract Socket namespace.\nAbstractSocketNamespace *AbstractSocketNamespace\n@@ -668,9 +671,7 @@ func (ctx *createProcessContext) Value(key interface{}) interface{} {\ncase CtxKernel:\nreturn ctx.k\ncase CtxPIDNamespace:\n- // \"The new task ... is in the root PID namespace.\" -\n- // Kernel.CreateProcess\n- return ctx.k.tasks.Root\n+ return ctx.args.PIDNamespace\ncase CtxUTSNamespace:\nreturn ctx.args.UTSNamespace\ncase CtxIPCNamespace:\n@@ -745,7 +746,7 @@ func (k *Kernel) CreateProcess(args CreateProcessArgs) (*ThreadGroup, ThreadID,\nmounts.IncRef()\n}\n- tg := k.newThreadGroup(mounts, k.tasks.Root, NewSignalHandlers(), linux.SIGCHLD, args.Limits, k.monotonicClock)\n+ tg := k.newThreadGroup(mounts, args.PIDNamespace, NewSignalHandlers(), linux.SIGCHLD, args.Limits, k.monotonicClock)\nctx := args.NewContext(k)\n// Grab the root directory.\n@@ -1018,6 +1019,11 @@ func (k *Kernel) RootIPCNamespace() *IPCNamespace {\nreturn k.rootIPCNamespace\n}\n+// RootPIDNamespace returns the root PIDNamespace.\n+func (k *Kernel) RootPIDNamespace() *PIDNamespace {\n+ return k.tasks.Root\n+}\n+\n// RootAbstractSocketNamespace returns the root AbstractSocketNamespace.\nfunc (k *Kernel) RootAbstractSocketNamespace() *AbstractSocketNamespace {\nreturn k.rootAbstractSocketNamespace\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/fs.go",
"new_path": "runsc/boot/fs.go",
"diff": "@@ -505,6 +505,7 @@ func (c *containerMounter) setupFS(ctx context.Context, conf *Config, procArgs *\nCredentials: auth.NewRootCredentials(creds.UserNamespace),\nUmask: 0022,\nMaxSymlinkTraversals: linux.MaxSymlinkTraversals,\n+ PIDNamespace: procArgs.PIDNamespace,\n}\nrootCtx := rootProcArgs.NewContext(c.k)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader.go",
"new_path": "runsc/boot/loader.go",
"diff": "@@ -138,6 +138,9 @@ type execProcess struct {\n// tty will be nil if the process is not attached to a terminal.\ntty *host.TTYFileOperations\n+\n+ // pidnsPath is the pid namespace path in spec\n+ pidnsPath string\n}\nfunc init() {\n@@ -298,7 +301,7 @@ func New(args Args) (*Loader, error) {\n// Create a watchdog.\ndog := watchdog.New(k, watchdog.DefaultTimeout, args.Conf.WatchdogAction)\n- procArgs, err := newProcess(args.ID, args.Spec, creds, k)\n+ procArgs, err := newProcess(args.ID, args.Spec, creds, k, k.RootPIDNamespace())\nif err != nil {\nreturn nil, fmt.Errorf(\"creating init process for root container: %v\", err)\n}\n@@ -376,7 +379,7 @@ func New(args Args) (*Loader, error) {\n}\n// newProcess creates a process that can be run with kernel.CreateProcess.\n-func newProcess(id string, spec *specs.Spec, creds *auth.Credentials, k *kernel.Kernel) (kernel.CreateProcessArgs, error) {\n+func newProcess(id string, spec *specs.Spec, creds *auth.Credentials, k *kernel.Kernel, pidns *kernel.PIDNamespace) (kernel.CreateProcessArgs, error) {\n// Create initial limits.\nls, err := createLimitSet(spec)\nif err != nil {\n@@ -396,7 +399,9 @@ func newProcess(id string, spec *specs.Spec, creds *auth.Credentials, k *kernel.\nIPCNamespace: k.RootIPCNamespace(),\nAbstractSocketNamespace: k.RootAbstractSocketNamespace(),\nContainerID: id,\n+ PIDNamespace: pidns,\n}\n+\nreturn procArgs, nil\n}\n@@ -559,6 +564,9 @@ func (l *Loader) run() error {\n}\nep.tg = l.k.GlobalInit()\n+ if ns, ok := specutils.GetNS(specs.PIDNamespace, l.spec); ok {\n+ ep.pidnsPath = ns.Path\n+ }\nif l.console {\nttyFile, _ := l.rootProcArgs.FDTable.Get(0)\ndefer ttyFile.DecRef()\n@@ -627,7 +635,24 @@ func (l *Loader) startContainer(spec *specs.Spec, conf *Config, cid string, file\ncaps,\nl.k.RootUserNamespace())\n- procArgs, err := newProcess(cid, spec, creds, l.k)\n+ var pidns *kernel.PIDNamespace\n+ if ns, ok := specutils.GetNS(specs.PIDNamespace, spec); ok {\n+ if ns.Path != \"\" {\n+ for _, p := range l.processes {\n+ if ns.Path == p.pidnsPath {\n+ pidns = p.tg.PIDNamespace()\n+ break\n+ }\n+ }\n+ }\n+ if pidns == nil {\n+ pidns = l.k.RootPIDNamespace().NewChild(l.k.RootUserNamespace())\n+ }\n+ l.processes[eid].pidnsPath = ns.Path\n+ } else {\n+ pidns = l.k.RootPIDNamespace()\n+ }\n+ procArgs, err := newProcess(cid, spec, creds, l.k, pidns)\nif err != nil {\nreturn fmt.Errorf(\"creating new process: %v\", err)\n}\n@@ -749,6 +774,7 @@ func (l *Loader) executeAsync(args *control.ExecArgs) (kernel.ThreadID, error) {\n// Start the process.\nproc := control.Proc{Kernel: l.k}\n+ args.PIDNamespace = tg.PIDNamespace()\nnewTG, tgid, ttyFile, err := control.ExecAsync(&proc, args)\nif err != nil {\nreturn 0, err\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/container_test.go",
"new_path": "runsc/container/container_test.go",
"diff": "@@ -714,6 +714,16 @@ func TestKillPid(t *testing.T) {\nif err := waitForProcessCount(cont, nProcs-1); err != nil {\nt.Fatal(err)\n}\n+\n+ procs, err = cont.Processes()\n+ if err != nil {\n+ t.Fatalf(\"failed to get process list: %v\", err)\n+ }\n+ for _, p := range procs {\n+ if pid == int32(p.PID) {\n+ t.Fatalf(\"pid %d is still alive, which should be killed\", pid)\n+ }\n+ }\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/multi_container_test.go",
"new_path": "runsc/container/multi_container_test.go",
"diff": "@@ -165,6 +165,104 @@ func TestMultiContainerSanity(t *testing.T) {\n}\n}\n+// TestMultiPIDNS checks that it is possible to run 2 dead-simple\n+// containers in the same sandbox with different pidns.\n+func TestMultiPIDNS(t *testing.T) {\n+ for _, conf := range configs(all...) {\n+ t.Logf(\"Running test with conf: %+v\", conf)\n+\n+ // Setup the containers.\n+ sleep := []string{\"sleep\", \"100\"}\n+ testSpecs, ids := createSpecs(sleep, sleep)\n+ testSpecs[1].Linux = &specs.Linux{\n+ Namespaces: []specs.LinuxNamespace{\n+ {\n+ Type: \"pid\",\n+ },\n+ },\n+ }\n+\n+ containers, cleanup, err := startContainers(conf, testSpecs, ids)\n+ if err != nil {\n+ t.Fatalf(\"error starting containers: %v\", err)\n+ }\n+ defer cleanup()\n+\n+ // Check via ps that multiple processes are running.\n+ expectedPL := []*control.Process{\n+ {PID: 1, Cmd: \"sleep\"},\n+ }\n+ if err := waitForProcessList(containers[0], expectedPL); err != nil {\n+ t.Errorf(\"failed to wait for sleep to start: %v\", err)\n+ }\n+ expectedPL = []*control.Process{\n+ {PID: 1, Cmd: \"sleep\"},\n+ }\n+ if err := waitForProcessList(containers[1], expectedPL); err != nil {\n+ t.Errorf(\"failed to wait for sleep to start: %v\", err)\n+ }\n+ }\n+}\n+\n+// TestMultiPIDNSPath checks the pidns path.\n+func TestMultiPIDNSPath(t *testing.T) {\n+ for _, conf := range configs(all...) {\n+ t.Logf(\"Running test with conf: %+v\", conf)\n+\n+ // Setup the containers.\n+ sleep := []string{\"sleep\", \"100\"}\n+ testSpecs, ids := createSpecs(sleep, sleep, sleep)\n+ testSpecs[0].Linux = &specs.Linux{\n+ Namespaces: []specs.LinuxNamespace{\n+ {\n+ Type: \"pid\",\n+ Path: \"/proc/1/ns/pid\",\n+ },\n+ },\n+ }\n+ testSpecs[1].Linux = &specs.Linux{\n+ Namespaces: []specs.LinuxNamespace{\n+ {\n+ Type: \"pid\",\n+ Path: \"/proc/1/ns/pid\",\n+ },\n+ },\n+ }\n+ testSpecs[2].Linux = &specs.Linux{\n+ Namespaces: []specs.LinuxNamespace{\n+ {\n+ Type: \"pid\",\n+ Path: \"/proc/2/ns/pid\",\n+ },\n+ },\n+ }\n+\n+ containers, cleanup, err := startContainers(conf, testSpecs, ids)\n+ if err != nil {\n+ t.Fatalf(\"error starting containers: %v\", err)\n+ }\n+ defer cleanup()\n+\n+ // Check via ps that multiple processes are running.\n+ expectedPL := []*control.Process{\n+ {PID: 1, Cmd: \"sleep\"},\n+ }\n+ if err := waitForProcessList(containers[0], expectedPL); err != nil {\n+ t.Errorf(\"failed to wait for sleep to start: %v\", err)\n+ }\n+ if err := waitForProcessList(containers[2], expectedPL); err != nil {\n+ t.Errorf(\"failed to wait for sleep to start: %v\", err)\n+ }\n+\n+ expectedPL = []*control.Process{\n+ {PID: 2, Cmd: \"sleep\"},\n+ }\n+ if err := waitForProcessList(containers[1], expectedPL); err != nil {\n+ t.Errorf(\"failed to wait for sleep to start: %v\", err)\n+ }\n+ }\n+}\n+\nfunc TestMultiContainerWait(t *testing.T) {\n// The first container should run the entire duration of the test.\ncmd1 := []string{\"sleep\", \"100\"}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use different pidns among different containers
The different containers in a sandbox used only one pid
namespace before. This results in that a container can see
the processes in another container in the same sandbox.
This patch use different pid namespace for different containers.
Signed-off-by: chris.zn <[email protected]> |
259,907 | 24.07.2019 16:02:07 | 25,200 | 2ed832ff86ee29970d0a3991297de818bda67b9c | ext: testing environment setup with VFS2 support. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/BUILD",
"new_path": "pkg/sentry/fs/ext/BUILD",
"diff": "@@ -15,7 +15,10 @@ go_library(\ndeps = [\n\"//pkg/abi/linux\",\n\"//pkg/binary\",\n+ \"//pkg/sentry/context\",\n\"//pkg/sentry/fs/ext/disklayout\",\n+ \"//pkg/sentry/kernel/auth\",\n+ \"//pkg/sentry/vfs\",\n\"//pkg/syserror\",\n],\n)\n@@ -23,11 +26,26 @@ go_library(\ngo_test(\nname = \"ext_test\",\nsize = \"small\",\n- srcs = [\"extent_test.go\"],\n+ srcs = [\n+ \"ext_test.go\",\n+ \"extent_test.go\",\n+ ],\n+ data = [\n+ \"//pkg/sentry/fs/ext:assets/bigfile.txt\",\n+ \"//pkg/sentry/fs/ext:assets/file.txt\",\n+ \"//pkg/sentry/fs/ext:assets/tiny.ext2\",\n+ \"//pkg/sentry/fs/ext:assets/tiny.ext3\",\n+ \"//pkg/sentry/fs/ext:assets/tiny.ext4\",\n+ ],\nembed = [\":ext\"],\ndeps = [\n+ \"//pkg/abi/linux\",\n\"//pkg/binary\",\n+ \"//pkg/sentry/context\",\n+ \"//pkg/sentry/context/contexttest\",\n\"//pkg/sentry/fs/ext/disklayout\",\n+ \"//pkg/sentry/vfs\",\n+ \"//runsc/test/testutil\",\n\"@com_github_google_go-cmp//cmp:go_default_library\",\n\"@com_github_google_go-cmp//cmp/cmpopts:go_default_library\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/dentry.go",
"new_path": "pkg/sentry/fs/ext/dentry.go",
"diff": "package ext\n+import (\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+)\n+\n// dentry implements vfs.DentryImpl.\ntype dentry struct {\n+ vfsd vfs.Dentry\n+\n// inode is the inode represented by this dentry. Multiple Dentries may\n// share a single non-directory Inode (with hard links). inode is\n// immutable.\ninode *inode\n}\n+\n+// Compiles only if dentry implements vfs.DentryImpl.\n+var _ vfs.DentryImpl = (*dentry)(nil)\n+\n+// IncRef implements vfs.DentryImpl.IncRef.\n+func (d *dentry) IncRef(vfsfs *vfs.Filesystem) {\n+ d.inode.incRef()\n+}\n+\n+// TryIncRef implements vfs.DentryImpl.TryIncRef.\n+func (d *dentry) TryIncRef(vfsfs *vfs.Filesystem) bool {\n+ return d.inode.tryIncRef()\n+}\n+\n+// DecRef implements vfs.DentryImpl.DecRef.\n+func (d *dentry) DecRef(vfsfs *vfs.Filesystem) {\n+ d.inode.decRef(vfsfs.Impl().(*filesystem))\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/disklayout/dirent_old.go",
"new_path": "pkg/sentry/fs/ext/disklayout/dirent_old.go",
"diff": "@@ -17,8 +17,7 @@ package disklayout\nimport \"gvisor.dev/gvisor/pkg/sentry/fs\"\n// DirentOld represents the old directory entry struct which does not contain\n-// the file type. This emulates Linux's ext4_dir_entry struct. This is used in\n-// ext2, ext3 and sometimes in ext4.\n+// the file type. This emulates Linux's ext4_dir_entry struct.\n//\n// Note: This struct can be of variable size on disk. The one described below\n// is of maximum size and the FileName beyond NameLength bytes might contain\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/disklayout/superblock_32.go",
"new_path": "pkg/sentry/fs/ext/disklayout/superblock_32.go",
"diff": "package disklayout\n// SuperBlock32Bit implements SuperBlock and represents the 32-bit version of\n-// the ext4_super_block struct in fs/ext4/ext4.h.\n+// the ext4_super_block struct in fs/ext4/ext4.h. Should be used only if\n+// RevLevel = DynamicRev and 64-bit feature is disabled.\ntype SuperBlock32Bit struct {\n// We embed the old superblock struct here because the 32-bit version is just\n// an extension of the old version.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/disklayout/superblock_64.go",
"new_path": "pkg/sentry/fs/ext/disklayout/superblock_64.go",
"diff": "@@ -17,7 +17,8 @@ package disklayout\n// SuperBlock64Bit implements SuperBlock and represents the 64-bit version of\n// the ext4_super_block struct in fs/ext4/ext4.h. This sums up to be exactly\n// 1024 bytes (smallest possible block size) and hence the superblock always\n-// fits in no more than one data block.\n+// fits in no more than one data block. Should only be used when the 64-bit\n+// feature is set.\ntype SuperBlock64Bit struct {\n// We embed the 32-bit struct here because 64-bit version is just an extension\n// of the 32-bit version.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/disklayout/superblock_old.go",
"new_path": "pkg/sentry/fs/ext/disklayout/superblock_old.go",
"diff": "package disklayout\n// SuperBlockOld implements SuperBlock and represents the old version of the\n-// superblock struct in ext2 and ext3 systems.\n+// superblock struct. Should be used only if RevLevel = OldRev.\ntype SuperBlockOld struct {\nInodesCountRaw uint32\nBlocksCountLo uint32\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/ext.go",
"new_path": "pkg/sentry/fs/ext/ext.go",
"diff": "package ext\nimport (\n+ \"errors\"\n+ \"fmt\"\n\"io\"\n+ \"os\"\n\"sync\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/sentry/context\"\n\"gvisor.dev/gvisor/pkg/sentry/fs/ext/disklayout\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n)\n+// filesystemType implements vfs.FilesystemType.\n+type filesystemType struct{}\n+\n+// Compiles only if filesystemType implements vfs.FilesystemType.\n+var _ vfs.FilesystemType = (*filesystemType)(nil)\n+\n// filesystem implements vfs.FilesystemImpl.\ntype filesystem struct {\n- // mu serializes changes to the Dentry tree and the usage of the read seeker.\n+ // TODO(b/134676337): Remove when all methods have been implemented.\n+ vfs.FilesystemImpl\n+\n+ vfsfs vfs.Filesystem\n+\n+ // mu serializes changes to the dentry tree and the usage of the read seeker.\nmu sync.Mutex\n// dev is the ReadSeeker for the underlying fs device. It is protected by mu.\n@@ -58,28 +75,63 @@ type filesystem struct {\nbgs []disklayout.BlockGroup\n}\n-// newFilesystem is the filesystem constructor.\n-func newFilesystem(dev io.ReadSeeker) (*filesystem, error) {\n- fs := filesystem{dev: dev, inodeCache: make(map[uint32]*inode)}\n- var err error\n+// Compiles only if filesystem implements vfs.FilesystemImpl.\n+var _ vfs.FilesystemImpl = (*filesystem)(nil)\n+\n+// getDeviceFd returns the read seeker to the underlying device.\n+// Currently there are two ways of mounting an ext(2/3/4) fs:\n+// 1. Specify a mount with our internal special MountType in the OCI spec.\n+// 2. Expose the device to the container and mount it from application layer.\n+func getDeviceFd(source string, opts vfs.NewFilesystemOptions) (io.ReadSeeker, error) {\n+ if opts.InternalData == nil {\n+ // User mount call.\n+ // TODO(b/134676337): Open the device specified by `source` and return that.\n+ panic(\"unimplemented\")\n+ }\n+\n+ // NewFilesystem call originated from within the sentry.\n+ fd, ok := opts.InternalData.(uintptr)\n+ if !ok {\n+ return nil, errors.New(\"internal data for ext fs must be a uintptr containing the file descriptor to device\")\n+ }\n+\n+ // We do not close this file because that would close the underlying device\n+ // file descriptor (which is required for reading the fs from disk).\n+ // TODO(b/134676337): Use pkg/fd instead.\n+ deviceFile := os.NewFile(fd, source)\n+ if deviceFile == nil {\n+ return nil, fmt.Errorf(\"ext4 device file descriptor is not valid: %d\", fd)\n+ }\n+\n+ return deviceFile, nil\n+}\n+// NewFilesystem implements vfs.FilesystemType.NewFilesystem.\n+func (fstype filesystemType) NewFilesystem(ctx context.Context, creds *auth.Credentials, source string, opts vfs.NewFilesystemOptions) (*vfs.Filesystem, *vfs.Dentry, error) {\n+ dev, err := getDeviceFd(source, opts)\n+ if err != nil {\n+ return nil, nil, err\n+ }\n+\n+ fs := filesystem{dev: dev, inodeCache: make(map[uint32]*inode)}\n+ fs.vfsfs.Init(&fs)\nfs.sb, err = readSuperBlock(dev)\nif err != nil {\n- return nil, err\n+ return nil, nil, err\n}\nif fs.sb.Magic() != linux.EXT_SUPER_MAGIC {\n// mount(2) specifies that EINVAL should be returned if the superblock is\n// invalid.\n- return nil, syserror.EINVAL\n+ return nil, nil, syserror.EINVAL\n}\nfs.bgs, err = readBlockGroups(dev, fs.sb)\nif err != nil {\n- return nil, err\n+ return nil, nil, err\n}\n- return &fs, nil\n+ return &fs.vfsfs, nil, nil\n}\n// getOrCreateInode gets the inode corresponding to the inode number passed in.\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext/ext_test.go",
"diff": "+// Copyright 2019 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 ext\n+\n+import (\n+ \"fmt\"\n+ \"os\"\n+ \"path\"\n+ \"testing\"\n+\n+ \"github.com/google/go-cmp/cmp\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/sentry/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/context/contexttest\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fs/ext/disklayout\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+\n+ \"gvisor.dev/gvisor/runsc/test/testutil\"\n+)\n+\n+const (\n+ assetsDir = \"pkg/sentry/fs/ext/assets\"\n+)\n+\n+var (\n+ ext2ImagePath = path.Join(assetsDir, \"tiny.ext2\")\n+ ext3ImagePath = path.Join(assetsDir, \"tiny.ext3\")\n+ ext4ImagePath = path.Join(assetsDir, \"tiny.ext4\")\n+)\n+\n+func beginning(_ uint64) uint64 {\n+ return 0\n+}\n+\n+func middle(i uint64) uint64 {\n+ return i / 2\n+}\n+\n+func end(i uint64) uint64 {\n+ return i\n+}\n+\n+// setUp opens imagePath as an ext Filesystem and returns all necessary\n+// elements required to run tests. If error is non-nil, it also returns a tear\n+// down function which must be called after the test is run for clean up.\n+func setUp(t *testing.T, imagePath string) (context.Context, *vfs.Filesystem, *vfs.Dentry, func(), error) {\n+ localImagePath, err := testutil.FindFile(imagePath)\n+ if err != nil {\n+ return nil, nil, nil, nil, fmt.Errorf(\"failed to open local image at path %s: %v\", imagePath, err)\n+ }\n+\n+ f, err := os.Open(localImagePath)\n+ if err != nil {\n+ return nil, nil, nil, nil, err\n+ }\n+\n+ // Mount the ext4 fs and retrieve the inode structure for the file.\n+ mockCtx := contexttest.Context(t)\n+ fs, d, err := filesystemType{}.NewFilesystem(mockCtx, nil, localImagePath, vfs.NewFilesystemOptions{InternalData: f.Fd()})\n+ if err != nil {\n+ f.Close()\n+ return nil, nil, nil, nil, err\n+ }\n+\n+ tearDown := func() {\n+ if err := f.Close(); err != nil {\n+ t.Fatalf(\"tearDown failed: %v\", err)\n+ }\n+ }\n+ return mockCtx, fs, d, tearDown, nil\n+}\n+\n+// TestFilesystemInit tests that the filesystem superblock and block group\n+// descriptors are correctly read in and initialized.\n+func TestFilesystemInit(t *testing.T) {\n+ // sb only contains the immutable properties of the superblock.\n+ type sb struct {\n+ InodesCount uint32\n+ BlocksCount uint64\n+ MaxMountCount uint16\n+ FirstDataBlock uint32\n+ BlockSize uint64\n+ BlocksPerGroup uint32\n+ ClusterSize uint64\n+ ClustersPerGroup uint32\n+ InodeSize uint16\n+ InodesPerGroup uint32\n+ BgDescSize uint16\n+ Magic uint16\n+ Revision disklayout.SbRevision\n+ CompatFeatures disklayout.CompatFeatures\n+ IncompatFeatures disklayout.IncompatFeatures\n+ RoCompatFeatures disklayout.RoCompatFeatures\n+ }\n+\n+ // bg only contains the immutable properties of the block group descriptor.\n+ type bg struct {\n+ InodeTable uint64\n+ BlockBitmap uint64\n+ InodeBitmap uint64\n+ ExclusionBitmap uint64\n+ Flags disklayout.BGFlags\n+ }\n+\n+ type fsInitTest struct {\n+ name string\n+ image string\n+ wantSb sb\n+ wantBgs []bg\n+ }\n+\n+ tests := []fsInitTest{\n+ {\n+ name: \"ext4 filesystem init\",\n+ image: ext4ImagePath,\n+ wantSb: sb{\n+ InodesCount: 0x10,\n+ BlocksCount: 0x40,\n+ MaxMountCount: 0xffff,\n+ FirstDataBlock: 0x1,\n+ BlockSize: 0x400,\n+ BlocksPerGroup: 0x2000,\n+ ClusterSize: 0x400,\n+ ClustersPerGroup: 0x2000,\n+ InodeSize: 0x80,\n+ InodesPerGroup: 0x10,\n+ BgDescSize: 0x40,\n+ Magic: linux.EXT_SUPER_MAGIC,\n+ Revision: disklayout.DynamicRev,\n+ CompatFeatures: disklayout.CompatFeatures{\n+ ExtAttr: true,\n+ ResizeInode: true,\n+ DirIndex: true,\n+ },\n+ IncompatFeatures: disklayout.IncompatFeatures{\n+ DirentFileType: true,\n+ Extents: true,\n+ Is64Bit: true,\n+ FlexBg: true,\n+ },\n+ RoCompatFeatures: disklayout.RoCompatFeatures{\n+ Sparse: true,\n+ LargeFile: true,\n+ HugeFile: true,\n+ DirNlink: true,\n+ ExtraIsize: true,\n+ MetadataCsum: true,\n+ },\n+ },\n+ wantBgs: []bg{\n+ {\n+ InodeTable: 0x23,\n+ BlockBitmap: 0x3,\n+ InodeBitmap: 0x13,\n+ Flags: disklayout.BGFlags{\n+ InodeZeroed: true,\n+ },\n+ },\n+ },\n+ },\n+ {\n+ name: \"ext3 filesystem init\",\n+ image: ext3ImagePath,\n+ wantSb: sb{\n+ InodesCount: 0x10,\n+ BlocksCount: 0x40,\n+ MaxMountCount: 0xffff,\n+ FirstDataBlock: 0x1,\n+ BlockSize: 0x400,\n+ BlocksPerGroup: 0x2000,\n+ ClusterSize: 0x400,\n+ ClustersPerGroup: 0x2000,\n+ InodeSize: 0x80,\n+ InodesPerGroup: 0x10,\n+ BgDescSize: 0x20,\n+ Magic: linux.EXT_SUPER_MAGIC,\n+ Revision: disklayout.DynamicRev,\n+ CompatFeatures: disklayout.CompatFeatures{\n+ ExtAttr: true,\n+ ResizeInode: true,\n+ DirIndex: true,\n+ },\n+ IncompatFeatures: disklayout.IncompatFeatures{\n+ DirentFileType: true,\n+ },\n+ RoCompatFeatures: disklayout.RoCompatFeatures{\n+ Sparse: true,\n+ LargeFile: true,\n+ },\n+ },\n+ wantBgs: []bg{\n+ {\n+ InodeTable: 0x5,\n+ BlockBitmap: 0x3,\n+ InodeBitmap: 0x4,\n+ Flags: disklayout.BGFlags{\n+ InodeZeroed: true,\n+ },\n+ },\n+ },\n+ },\n+ {\n+ name: \"ext2 filesystem init\",\n+ image: ext2ImagePath,\n+ wantSb: sb{\n+ InodesCount: 0x10,\n+ BlocksCount: 0x40,\n+ MaxMountCount: 0xffff,\n+ FirstDataBlock: 0x1,\n+ BlockSize: 0x400,\n+ BlocksPerGroup: 0x2000,\n+ ClusterSize: 0x400,\n+ ClustersPerGroup: 0x2000,\n+ InodeSize: 0x80,\n+ InodesPerGroup: 0x10,\n+ BgDescSize: 0x20,\n+ Magic: linux.EXT_SUPER_MAGIC,\n+ Revision: disklayout.DynamicRev,\n+ CompatFeatures: disklayout.CompatFeatures{\n+ ExtAttr: true,\n+ ResizeInode: true,\n+ DirIndex: true,\n+ },\n+ IncompatFeatures: disklayout.IncompatFeatures{\n+ DirentFileType: true,\n+ },\n+ RoCompatFeatures: disklayout.RoCompatFeatures{\n+ Sparse: true,\n+ LargeFile: true,\n+ },\n+ },\n+ wantBgs: []bg{\n+ {\n+ InodeTable: 0x5,\n+ BlockBitmap: 0x3,\n+ InodeBitmap: 0x4,\n+ Flags: disklayout.BGFlags{\n+ InodeZeroed: true,\n+ },\n+ },\n+ },\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ _, vfsfs, _, tearDown, err := setUp(t, test.image)\n+ if err != nil {\n+ t.Fatalf(\"setUp failed: %v\", err)\n+ }\n+ defer tearDown()\n+\n+ fs, ok := vfsfs.Impl().(*filesystem)\n+ if !ok {\n+ t.Fatalf(\"ext filesystem of incorrect type: %T\", vfsfs.Impl())\n+ }\n+\n+ // Offload superblock and block group descriptors contents into\n+ // local structs for comparison.\n+ totalFreeInodes := uint32(0)\n+ totalFreeBlocks := uint64(0)\n+ gotSb := sb{\n+ InodesCount: fs.sb.InodesCount(),\n+ BlocksCount: fs.sb.BlocksCount(),\n+ MaxMountCount: fs.sb.MaxMountCount(),\n+ FirstDataBlock: fs.sb.FirstDataBlock(),\n+ BlockSize: fs.sb.BlockSize(),\n+ BlocksPerGroup: fs.sb.BlocksPerGroup(),\n+ ClusterSize: fs.sb.ClusterSize(),\n+ ClustersPerGroup: fs.sb.ClustersPerGroup(),\n+ InodeSize: fs.sb.InodeSize(),\n+ InodesPerGroup: fs.sb.InodesPerGroup(),\n+ BgDescSize: fs.sb.BgDescSize(),\n+ Magic: fs.sb.Magic(),\n+ Revision: fs.sb.Revision(),\n+ CompatFeatures: fs.sb.CompatibleFeatures(),\n+ IncompatFeatures: fs.sb.IncompatibleFeatures(),\n+ RoCompatFeatures: fs.sb.ReadOnlyCompatibleFeatures(),\n+ }\n+ gotNumBgs := len(fs.bgs)\n+ gotBgs := make([]bg, gotNumBgs)\n+ for i := 0; i < gotNumBgs; i++ {\n+ gotBgs[i].InodeTable = fs.bgs[i].InodeTable()\n+ gotBgs[i].BlockBitmap = fs.bgs[i].BlockBitmap()\n+ gotBgs[i].InodeBitmap = fs.bgs[i].InodeBitmap()\n+ gotBgs[i].ExclusionBitmap = fs.bgs[i].ExclusionBitmap()\n+ gotBgs[i].Flags = fs.bgs[i].Flags()\n+\n+ totalFreeInodes += fs.bgs[i].FreeInodesCount()\n+ totalFreeBlocks += uint64(fs.bgs[i].FreeBlocksCount())\n+ }\n+\n+ if diff := cmp.Diff(gotSb, test.wantSb); diff != \"\" {\n+ t.Errorf(\"superblock mismatch (-want +got):\\n%s\", diff)\n+ }\n+\n+ if diff := cmp.Diff(gotBgs, test.wantBgs); diff != \"\" {\n+ t.Errorf(\"block group descriptors mismatch (-want +got):\\n%s\", diff)\n+ }\n+\n+ if diff := cmp.Diff(totalFreeInodes, fs.sb.FreeInodesCount()); diff != \"\" {\n+ t.Errorf(\"total free inodes mismatch (-want +got):\\n%s\", diff)\n+ }\n+\n+ if diff := cmp.Diff(totalFreeBlocks, fs.sb.FreeBlocksCount()); diff != \"\" {\n+ t.Errorf(\"total free blocks mismatch (-want +got):\\n%s\", diff)\n+ }\n+ })\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | ext: testing environment setup with VFS2 support.
PiperOrigin-RevId: 259835948 |
259,907 | 24.07.2019 17:58:28 | 25,200 | 417096f781c4fe74ff8a6db5c0fa0d46ba08e81d | ext: Add tests for root directory inode. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/BUILD",
"new_path": "pkg/sentry/fs/ext/BUILD",
"diff": "@@ -44,6 +44,7 @@ go_test(\n\"//pkg/sentry/context\",\n\"//pkg/sentry/context/contexttest\",\n\"//pkg/sentry/fs/ext/disklayout\",\n+ \"//pkg/sentry/kernel/auth\",\n\"//pkg/sentry/vfs\",\n\"//runsc/test/testutil\",\n\"@com_github_google_go-cmp//cmp:go_default_library\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/dentry.go",
"new_path": "pkg/sentry/fs/ext/dentry.go",
"diff": "@@ -31,6 +31,15 @@ type dentry struct {\n// Compiles only if dentry implements vfs.DentryImpl.\nvar _ vfs.DentryImpl = (*dentry)(nil)\n+// newDentry is the dentry constructor.\n+func newDentry(in *inode) *dentry {\n+ d := &dentry{\n+ inode: in,\n+ }\n+ d.vfsd.Init(d)\n+ return d\n+}\n+\n// IncRef implements vfs.DentryImpl.IncRef.\nfunc (d *dentry) IncRef(vfsfs *vfs.Filesystem) {\nd.inode.incRef()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/disklayout/inode.go",
"new_path": "pkg/sentry/fs/ext/disklayout/inode.go",
"diff": "@@ -20,6 +20,12 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n)\n+// Special inodes. See https://www.kernel.org/doc/html/latest/filesystems/ext4/overview.html#special-inodes.\n+const (\n+ // RootDirInode is the inode number of the root directory inode.\n+ RootDirInode = 2\n+)\n+\n// The Inode interface must be implemented by structs representing ext inodes.\n// The inode stores all the metadata pertaining to the file (except for the\n// file name which is held by the directory entry). It does NOT expose all\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/ext.go",
"new_path": "pkg/sentry/fs/ext/ext.go",
"diff": "@@ -131,7 +131,12 @@ func (fstype filesystemType) NewFilesystem(ctx context.Context, creds *auth.Cred\nreturn nil, nil, err\n}\n- return &fs.vfsfs, nil, nil\n+ rootInode, err := fs.getOrCreateInode(disklayout.RootDirInode)\n+ if err != nil {\n+ return nil, nil, err\n+ }\n+\n+ return &fs.vfsfs, &newDentry(rootInode).vfsd, nil\n}\n// getOrCreateInode gets the inode corresponding to the inode number passed in.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/ext_test.go",
"new_path": "pkg/sentry/fs/ext/ext_test.go",
"diff": "@@ -25,6 +25,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/context\"\n\"gvisor.dev/gvisor/pkg/sentry/context/contexttest\"\n\"gvisor.dev/gvisor/pkg/sentry/fs/ext/disklayout\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/runsc/test/testutil\"\n@@ -82,6 +83,90 @@ func setUp(t *testing.T, imagePath string) (context.Context, *vfs.Filesystem, *v\nreturn mockCtx, fs, d, tearDown, nil\n}\n+// TestRootDir tests that the root directory inode is correctly initialized and\n+// returned from setUp.\n+func TestRootDir(t *testing.T) {\n+ type inodeProps struct {\n+ Mode linux.FileMode\n+ UID auth.KUID\n+ GID auth.KGID\n+ Size uint64\n+ InodeSize uint16\n+ Links uint16\n+ Flags disklayout.InodeFlags\n+ }\n+\n+ type rootDirTest struct {\n+ name string\n+ image string\n+ wantInode inodeProps\n+ }\n+\n+ tests := []rootDirTest{\n+ {\n+ name: \"ext4 root dir\",\n+ image: ext4ImagePath,\n+ wantInode: inodeProps{\n+ Mode: linux.ModeDirectory | 0755,\n+ Size: 0x400,\n+ InodeSize: 0x80,\n+ Links: 3,\n+ Flags: disklayout.InodeFlags{Extents: true},\n+ },\n+ },\n+ {\n+ name: \"ext3 root dir\",\n+ image: ext3ImagePath,\n+ wantInode: inodeProps{\n+ Mode: linux.ModeDirectory | 0755,\n+ Size: 0x400,\n+ InodeSize: 0x80,\n+ Links: 3,\n+ },\n+ },\n+ {\n+ name: \"ext2 root dir\",\n+ image: ext2ImagePath,\n+ wantInode: inodeProps{\n+ Mode: linux.ModeDirectory | 0755,\n+ Size: 0x400,\n+ InodeSize: 0x80,\n+ Links: 3,\n+ },\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ _, _, vfsd, tearDown, err := setUp(t, test.image)\n+ if err != nil {\n+ t.Fatalf(\"setUp failed: %v\", err)\n+ }\n+ defer tearDown()\n+\n+ d, ok := vfsd.Impl().(*dentry)\n+ if !ok {\n+ t.Fatalf(\"ext dentry of incorrect type: %T\", vfsd.Impl())\n+ }\n+\n+ // Offload inode contents into local structs for comparison.\n+ gotInode := inodeProps{\n+ Mode: d.inode.diskInode.Mode(),\n+ UID: d.inode.diskInode.UID(),\n+ GID: d.inode.diskInode.GID(),\n+ Size: d.inode.diskInode.Size(),\n+ InodeSize: d.inode.diskInode.InodeSize(),\n+ Links: d.inode.diskInode.LinksCount(),\n+ Flags: d.inode.diskInode.Flags(),\n+ }\n+\n+ if diff := cmp.Diff(gotInode, test.wantInode); diff != \"\" {\n+ t.Errorf(\"inode mismatch (-want +got):\\n%s\", diff)\n+ }\n+ })\n+ }\n+}\n+\n// TestFilesystemInit tests that the filesystem superblock and block group\n// descriptors are correctly read in and initialized.\nfunc TestFilesystemInit(t *testing.T) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | ext: Add tests for root directory inode.
PiperOrigin-RevId: 259856442 |
259,907 | 24.07.2019 19:06:52 | 25,200 | 83767574951f8ab4727070741451991ba848f6a6 | ext: filesystem boilerplate code. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/BUILD",
"new_path": "pkg/sentry/fs/ext/BUILD",
"diff": "@@ -7,6 +7,7 @@ go_library(\nsrcs = [\n\"dentry.go\",\n\"ext.go\",\n+ \"filesystem.go\",\n\"inode.go\",\n\"utils.go\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/ext.go",
"new_path": "pkg/sentry/fs/ext/ext.go",
"diff": "@@ -20,7 +20,6 @@ import (\n\"fmt\"\n\"io\"\n\"os\"\n- \"sync\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/sentry/context\"\n@@ -36,48 +35,6 @@ type filesystemType struct{}\n// Compiles only if filesystemType implements vfs.FilesystemType.\nvar _ vfs.FilesystemType = (*filesystemType)(nil)\n-// filesystem implements vfs.FilesystemImpl.\n-type filesystem struct {\n- // TODO(b/134676337): Remove when all methods have been implemented.\n- vfs.FilesystemImpl\n-\n- vfsfs vfs.Filesystem\n-\n- // mu serializes changes to the dentry tree and the usage of the read seeker.\n- mu sync.Mutex\n-\n- // dev is the ReadSeeker for the underlying fs device. It is protected by mu.\n- //\n- // The ext filesystems aim to maximize locality, i.e. place all the data\n- // blocks of a file close together. On a spinning disk, locality reduces the\n- // amount of movement of the head hence speeding up IO operations. On an SSD\n- // there are no moving parts but locality increases the size of each transer\n- // request. Hence, having mutual exclusion on the read seeker while reading a\n- // file *should* help in achieving the intended performance gains.\n- //\n- // Note: This synchronization was not coupled with the ReadSeeker itself\n- // because we want to synchronize across read/seek operations for the\n- // performance gains mentioned above. Helps enforcing one-file-at-a-time IO.\n- dev io.ReadSeeker\n-\n- // inodeCache maps absolute inode numbers to the corresponding Inode struct.\n- // Inodes should be removed from this once their reference count hits 0.\n- //\n- // Protected by mu because every addition and removal from this corresponds to\n- // a change in the dentry tree.\n- inodeCache map[uint32]*inode\n-\n- // sb represents the filesystem superblock. Immutable after initialization.\n- sb disklayout.SuperBlock\n-\n- // bgs represents all the block group descriptors for the filesystem.\n- // Immutable after initialization.\n- bgs []disklayout.BlockGroup\n-}\n-\n-// Compiles only if filesystem implements vfs.FilesystemImpl.\n-var _ vfs.FilesystemImpl = (*filesystem)(nil)\n-\n// getDeviceFd returns the read seeker to the underlying device.\n// Currently there are two ways of mounting an ext(2/3/4) fs:\n// 1. Specify a mount with our internal special MountType in the OCI spec.\n@@ -138,21 +95,3 @@ func (fstype filesystemType) NewFilesystem(ctx context.Context, creds *auth.Cred\nreturn &fs.vfsfs, &newDentry(rootInode).vfsd, nil\n}\n-\n-// getOrCreateInode gets the inode corresponding to the inode number passed in.\n-// It creates a new one with the given inode number if one does not exist.\n-//\n-// Preconditions: must be holding fs.mu.\n-func (fs *filesystem) getOrCreateInode(inodeNum uint32) (*inode, error) {\n- if in, ok := fs.inodeCache[inodeNum]; ok {\n- return in, nil\n- }\n-\n- in, err := newInode(fs.dev, fs.sb, fs.bgs, inodeNum)\n- if err != nil {\n- return nil, err\n- }\n-\n- fs.inodeCache[inodeNum] = in\n- return in, nil\n-}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext/filesystem.go",
"diff": "+// Copyright 2019 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 ext\n+\n+import (\n+ \"io\"\n+ \"sync\"\n+\n+ \"gvisor.dev/gvisor/pkg/sentry/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fs/ext/disklayout\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+)\n+\n+// filesystem implements vfs.FilesystemImpl.\n+type filesystem struct {\n+ // TODO(b/134676337): Remove when all methods have been implemented.\n+ vfs.FilesystemImpl\n+\n+ vfsfs vfs.Filesystem\n+\n+ // mu serializes changes to the Dentry tree and the usage of the read seeker.\n+ mu sync.Mutex\n+\n+ // dev is the ReadSeeker for the underlying fs device. It is protected by mu.\n+ //\n+ // The ext filesystems aim to maximize locality, i.e. place all the data\n+ // blocks of a file close together. On a spinning disk, locality reduces the\n+ // amount of movement of the head hence speeding up IO operations. On an SSD\n+ // there are no moving parts but locality increases the size of each transer\n+ // request. Hence, having mutual exclusion on the read seeker while reading a\n+ // file *should* help in achieving the intended performance gains.\n+ //\n+ // Note: This synchronization was not coupled with the ReadSeeker itself\n+ // because we want to synchronize across read/seek operations for the\n+ // performance gains mentioned above. Helps enforcing one-file-at-a-time IO.\n+ dev io.ReadSeeker\n+\n+ // inodeCache maps absolute inode numbers to the corresponding Inode struct.\n+ // Inodes should be removed from this once their reference count hits 0.\n+ //\n+ // Protected by mu because every addition and removal from this corresponds to\n+ // a change in the dentry tree.\n+ inodeCache map[uint32]*inode\n+\n+ // sb represents the filesystem superblock. Immutable after initialization.\n+ sb disklayout.SuperBlock\n+\n+ // bgs represents all the block group descriptors for the filesystem.\n+ // Immutable after initialization.\n+ bgs []disklayout.BlockGroup\n+}\n+\n+// Compiles only if filesystem implements vfs.FilesystemImpl.\n+var _ vfs.FilesystemImpl = (*filesystem)(nil)\n+\n+// getOrCreateInode gets the inode corresponding to the inode number passed in.\n+// It creates a new one with the given inode number if one does not exist.\n+//\n+// Preconditions: must be holding fs.mu.\n+func (fs *filesystem) getOrCreateInode(inodeNum uint32) (*inode, error) {\n+ if in, ok := fs.inodeCache[inodeNum]; ok {\n+ return in, nil\n+ }\n+\n+ in, err := newInode(fs.dev, fs.sb, fs.bgs, inodeNum)\n+ if err != nil {\n+ return nil, err\n+ }\n+\n+ fs.inodeCache[inodeNum] = in\n+ return in, nil\n+}\n+\n+// Release implements vfs.FilesystemImpl.Release.\n+func (fs *filesystem) Release() {\n+}\n+\n+// Sync implements vfs.FilesystemImpl.Sync.\n+func (fs *filesystem) Sync(ctx context.Context) error {\n+ // This is a readonly filesystem for now.\n+ return nil\n+}\n+\n+// The vfs.FilesystemImpl functions below return EROFS because their respective\n+// man pages say that EROFS must be returned if the path resolves to a file on\n+// a read-only filesystem.\n+\n+// TODO(b/134676337): Implement path traversal and return EROFS only if the\n+// path resolves to a Dentry within ext fs.\n+\n+// MkdirAt implements vfs.FilesystemImpl.MkdirAt.\n+func (fs *filesystem) MkdirAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.MkdirOptions) error {\n+ return syserror.EROFS\n+}\n+\n+// MknodAt implements vfs.FilesystemImpl.MknodAt.\n+func (fs *filesystem) MknodAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.MknodOptions) error {\n+ return syserror.EROFS\n+}\n+\n+// RenameAt implements vfs.FilesystemImpl.RenameAt.\n+func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, vd vfs.VirtualDentry, opts vfs.RenameOptions) error {\n+ return syserror.EROFS\n+}\n+\n+// RmdirAt implements vfs.FilesystemImpl.RmdirAt.\n+func (fs *filesystem) RmdirAt(ctx context.Context, rp *vfs.ResolvingPath) error {\n+ return syserror.EROFS\n+}\n+\n+// SetStatAt implements vfs.FilesystemImpl.SetStatAt.\n+func (fs *filesystem) SetStatAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.SetStatOptions) error {\n+ return syserror.EROFS\n+}\n+\n+// SymlinkAt implements vfs.FilesystemImpl.SymlinkAt.\n+func (fs *filesystem) SymlinkAt(ctx context.Context, rp *vfs.ResolvingPath, target string) error {\n+ return syserror.EROFS\n+}\n+\n+// UnlinkAt implements vfs.FilesystemImpl.UnlinkAt.\n+func (fs *filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error {\n+ return syserror.EROFS\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | ext: filesystem boilerplate code.
PiperOrigin-RevId: 259865366 |
259,992 | 26.07.2019 15:46:13 | 25,200 | 2762692621aec8b3d1e1839c2dc18965a4af0a18 | Add debug symbols to published runsc binary
This allows published binary to be debugged if needed. | [
{
"change_type": "MODIFY",
"old_path": "tools/run_build.sh",
"new_path": "tools/run_build.sh",
"diff": "@@ -31,16 +31,19 @@ elif [[ -v KOKORO_GIT_COMMIT ]] && [[ -d github/repo ]]; then\nfi\n# Build runsc.\n-bazel build //runsc\n+bazel build -c opt --strip=never //runsc\n# Move the runsc binary into \"latest\" directory, and also a directory with the\n# current date.\nif [[ -v KOKORO_ARTIFACTS_DIR ]]; then\nlatest_dir=\"${KOKORO_ARTIFACTS_DIR}\"/latest\ntoday_dir=\"${KOKORO_ARTIFACTS_DIR}\"/\"$(date -Idate)\"\n+ runsc=\"bazel-bin/runsc/linux_amd64_pure/runsc\"\n+\nmkdir -p \"${latest_dir}\" \"${today_dir}\"\n- cp bazel-bin/runsc/linux_amd64_pure_stripped/runsc \"${latest_dir}\"\n+ cp \"${runsc}\" \"${latest_dir}\"\n+ cp \"${runsc}\" \"${today_dir}\"\n+\nsha512sum \"${latest_dir}\"/runsc | awk '{print $1 \" runsc\"}' > \"${latest_dir}\"/runsc.sha512\n- cp bazel-bin/runsc/linux_amd64_pure_stripped/runsc \"${today_dir}\"\n- sha512sum \"${today_dir}\"/runsc | awk '{print $1 \" runsc\"}' > \"${today_dir}\"/runsc.sha512\n+ cp \"${latest_dir}\"/runsc.sha512 \"${today_dir}\"/runsc.sha512\nfi\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add debug symbols to published runsc binary
This allows published binary to be debugged if needed.
PiperOrigin-RevId: 260228367 |
259,853 | 26.07.2019 16:52:28 | 25,200 | 4183b9021ac1d055085dc1fd2f525689fc055d78 | runsc: propagate the alsologtostderr to sub-commands | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/config.go",
"new_path": "runsc/boot/config.go",
"diff": "@@ -198,6 +198,9 @@ type Config struct {\n// sandbox and Gofer process run as root inside a user namespace with root\n// mapped to the caller's user.\nRootless bool\n+\n+ // AlsoLogToStderr allows to send log messages to stderr.\n+ AlsoLogToStderr bool\n}\n// ToFlags returns a slice of flags that correspond to the given Config.\n@@ -223,6 +226,7 @@ func (c *Config) ToFlags() []string {\n\"--net-raw=\" + strconv.FormatBool(c.EnableRaw),\n\"--num-network-channels=\" + strconv.Itoa(c.NumNetworkChannels),\n\"--rootless=\" + strconv.FormatBool(c.Rootless),\n+ \"--alsologtostderr=\" + strconv.FormatBool(c.AlsoLogToStderr),\n}\nif c.TestOnlyAllowRunAsCurrentUserWithoutChroot {\n// Only include if set since it is never to be used by users.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/main.go",
"new_path": "runsc/main.go",
"diff": "@@ -190,6 +190,7 @@ func main() {\nEnableRaw: *netRaw,\nNumNetworkChannels: *numNetworkChannels,\nRootless: *rootless,\n+ AlsoLogToStderr: *alsoLogToStderr,\nTestOnlyAllowRunAsCurrentUserWithoutChroot: *testOnlyAllowRunAsCurrentUserWithoutChroot,\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | runsc: propagate the alsologtostderr to sub-commands
PiperOrigin-RevId: 260239119 |
259,891 | 29.07.2019 13:18:58 | 25,200 | 09be87bbee1e4338b488f22199d0f079ffec8d0e | Add iptables types for syscalls tests.
Unfortunately, Linux's ip_tables.h header doesn't compile in C++ because it
implicitly converts from void* to struct xt_entry_target*. C allows this, but
C++ does not. So we have to re-implement many types ourselves.
Relevant code here: | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -904,6 +904,14 @@ cc_binary(\n],\n)\n+cc_library(\n+ name = \"iptables_types\",\n+ testonly = 1,\n+ hdrs = [\n+ \"iptables.h\",\n+ ],\n+)\n+\ncc_binary(\nname = \"itimer_test\",\ntestonly = 1,\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/iptables.h",
"diff": "+// Copyright 2019 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+// There are a number of structs and values that we can't #include because of a\n+// difference between C and C++ (C++ won't let you implicitly cast from void* to\n+// struct something*). We re-define them here.\n+\n+#ifndef GVISOR_TEST_SYSCALLS_IPTABLES_TYPES_H_\n+#define GVISOR_TEST_SYSCALLS_IPTABLES_TYPES_H_\n+\n+// Netfilter headers require some headers to preceed them.\n+// clang-format off\n+#include <netinet/in.h>\n+#include <stddef.h>\n+// clang-format on\n+\n+#include <linux/netfilter/x_tables.h>\n+#include <linux/netfilter_ipv4.h>\n+#include <net/if.h>\n+#include <netinet/ip.h>\n+#include <stdint.h>\n+\n+#define ipt_standard_target xt_standard_target\n+#define ipt_entry_target xt_entry_target\n+#define ipt_error_target xt_error_target\n+\n+enum SockOpts {\n+ // For setsockopt.\n+ BASE_CTL = 64,\n+ SO_SET_REPLACE = BASE_CTL,\n+ SO_SET_ADD_COUNTERS,\n+ SO_SET_MAX = SO_SET_ADD_COUNTERS,\n+\n+ // For getsockopt.\n+ SO_GET_INFO = BASE_CTL,\n+ SO_GET_ENTRIES,\n+ SO_GET_REVISION_MATCH,\n+ SO_GET_REVISION_TARGET,\n+ SO_GET_MAX = SO_GET_REVISION_TARGET\n+};\n+\n+// ipt_ip specifies basic matching criteria that can be applied by examining\n+// only the IP header of a packet.\n+struct ipt_ip {\n+ // Source IP address.\n+ struct in_addr src;\n+\n+ // Destination IP address.\n+ struct in_addr dst;\n+\n+ // Source IP address mask.\n+ struct in_addr smsk;\n+\n+ // Destination IP address mask.\n+ struct in_addr dmsk;\n+\n+ // Input interface.\n+ char iniface[IFNAMSIZ];\n+\n+ // Output interface.\n+ char outiface[IFNAMSIZ];\n+\n+ // Input interface mask.\n+ unsigned char iniface_mask[IFNAMSIZ];\n+\n+ // Output interface mask.\n+ unsigned char outiface_mask[IFNAMSIZ];\n+\n+ // Transport protocol.\n+ uint16_t proto;\n+\n+ // Flags.\n+ uint8_t flags;\n+\n+ // Inverse flags.\n+ uint8_t invflags;\n+};\n+\n+// ipt_entry is an iptables rule. It contains information about what packets the\n+// rule matches and what action (target) to perform for matching packets.\n+struct ipt_entry {\n+ // Basic matching information used to match a packet's IP header.\n+ struct ipt_ip ip;\n+\n+ // A caching field that isn't used by userspace.\n+ unsigned int nfcache;\n+\n+ // The number of bytes between the start of this ipt_entry struct and the\n+ // rule's target.\n+ uint16_t target_offset;\n+\n+ // The total size of this rule, from the beginning of the entry to the end of\n+ // the target.\n+ uint16_t next_offset;\n+\n+ // A return pointer not used by userspace.\n+ unsigned int comefrom;\n+\n+ // Counters for packets and bytes, which we don't yet implement.\n+ struct xt_counters counters;\n+\n+ // The data for all this rules matches followed by the target. This runs\n+ // beyond the value of sizeof(struct ipt_entry).\n+ unsigned char elems[0];\n+};\n+\n+// Passed to getsockopt(SO_GET_INFO).\n+struct ipt_getinfo {\n+ // The name of the table. The user only fills this in, the rest is filled in\n+ // when returning from getsockopt. Currently \"nat\" and \"mangle\" are supported.\n+ char name[XT_TABLE_MAXNAMELEN];\n+\n+ // A bitmap of which hooks apply to the table. For example, a table with hooks\n+ // PREROUTING and FORWARD has the value\n+ // (1 << NF_IP_PRE_REOUTING) | (1 << NF_IP_FORWARD).\n+ unsigned int valid_hooks;\n+\n+ // The offset into the entry table for each valid hook. The entry table is\n+ // returned by getsockopt(SO_GET_ENTRIES).\n+ unsigned int hook_entry[NF_IP_NUMHOOKS];\n+\n+ // For each valid hook, the underflow is the offset into the entry table to\n+ // jump to in case traversing the table yields no verdict (although I have no\n+ // clue how that could happen - builtin chains always end with a policy, and\n+ // user-defined chains always end with a RETURN.\n+ //\n+ // The entry referred to must be an \"unconditional\" entry, meaning it has no\n+ // matches, specifies no IP criteria, and either DROPs or ACCEPTs packets. It\n+ // basically has to be capable of making a definitive decision no matter what\n+ // it's passed.\n+ unsigned int underflow[NF_IP_NUMHOOKS];\n+\n+ // The number of entries in the entry table returned by\n+ // getsockopt(SO_GET_ENTRIES).\n+ unsigned int num_entries;\n+\n+ // The size of the entry table returned by getsockopt(SO_GET_ENTRIES).\n+ unsigned int size;\n+};\n+\n+// Passed to getsockopt(SO_GET_ENTRIES).\n+struct ipt_get_entries {\n+ // The name of the table. The user fills this in. Currently \"nat\" and \"mangle\"\n+ // are supported.\n+ char name[XT_TABLE_MAXNAMELEN];\n+\n+ // The size of the entry table in bytes. The user fills this in with the value\n+ // from struct ipt_getinfo.size.\n+ unsigned int size;\n+\n+ // The entries for the given table. This will run past the size defined by\n+ // sizeof(struct ipt_get_entries).\n+ struct ipt_entry entrytable[0];\n+};\n+\n+// Passed to setsockopt(SO_SET_REPLACE).\n+struct ipt_replace {\n+ // The name of the table.\n+ char name[XT_TABLE_MAXNAMELEN];\n+\n+ // The same as struct ipt_getinfo.valid_hooks. Users don't change this.\n+ unsigned int valid_hooks;\n+\n+ // The same as struct ipt_getinfo.num_entries.\n+ unsigned int num_entries;\n+\n+ // The same as struct ipt_getinfo.size.\n+ unsigned int size;\n+\n+ // The same as struct ipt_getinfo.hook_entry.\n+ unsigned int hook_entry[NF_IP_NUMHOOKS];\n+\n+ // The same as struct ipt_getinfo.underflow.\n+ unsigned int underflow[NF_IP_NUMHOOKS];\n+\n+ // The number of counters, which should equal the number of entries.\n+ unsigned int num_counters;\n+\n+ // The unchanged values from each ipt_entry's counters.\n+ struct xt_counters *counters;\n+\n+ // The entries to write to the table. This will run past the size defined by\n+ // sizeof(srtuct ipt_replace);\n+ struct ipt_entry entries[0];\n+};\n+\n+#endif // GVISOR_TEST_SYSCALLS_IPTABLES_TYPES_H_\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add iptables types for syscalls tests.
Unfortunately, Linux's ip_tables.h header doesn't compile in C++ because it
implicitly converts from void* to struct xt_entry_target*. C allows this, but
C++ does not. So we have to re-implement many types ourselves.
Relevant code here:
https://github.com/torvalds/linux/blob/master/include/uapi/linux/netfilter_ipv4/ip_tables.h#L222
PiperOrigin-RevId: 260565570 |
259,975 | 29.07.2019 16:46:28 | 25,200 | f0507e1db1574ff165000fa5e34b651413f37aae | Fix flaky stat.cc test.
This test flaked on my current CL. Linux makes no guarantee
that two inodes will consecutive (overflows happen). | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/stat.cc",
"new_path": "test/syscalls/linux/stat.cc",
"diff": "@@ -539,9 +539,8 @@ TEST(SimpleStatTest, AnonDeviceAllocatesUniqueInodesAcrossSaveRestore) {\nASSERT_THAT(fstat(fd1.get(), &st1), SyscallSucceeds());\nASSERT_THAT(fstat(fd2.get(), &st2), SyscallSucceeds());\n- // The two fds should have different inode numbers. Specifically, since fd2\n- // was created later, it should have a higher inode number.\n- EXPECT_GT(st2.st_ino, st1.st_ino);\n+ // The two fds should have different inode numbers.\n+ EXPECT_NE(st2.st_ino, st1.st_ino);\n// Verify again after another S/R cycle. The inode numbers should remain the\n// same.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix flaky stat.cc test.
This test flaked on my current CL. Linux makes no guarantee
that two inodes will consecutive (overflows happen).
https://github.com/avagin/linux-task-diag/blob/master/fs/inode.c#L880
PiperOrigin-RevId: 260608240 |
259,956 | 29.07.2019 17:17:58 | 25,200 | a3e9031e665e5707ff1d181a577a808ff6d67452 | Use x/sys/unix for sentry/host interaction; abi is for guest/sentry. | [
{
"change_type": "MODIFY",
"old_path": "pkg/unet/BUILD",
"new_path": "pkg/unet/BUILD",
"diff": "@@ -11,8 +11,8 @@ go_library(\nimportpath = \"gvisor.dev/gvisor/pkg/unet\",\nvisibility = [\"//visibility:public\"],\ndeps = [\n- \"//pkg/abi/linux\",\n\"//pkg/gate\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/unet/unet_unsafe.go",
"new_path": "pkg/unet/unet_unsafe.go",
"diff": "@@ -21,7 +21,7 @@ import (\n\"syscall\"\n\"unsafe\"\n- \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"golang.org/x/sys/unix\"\n)\n// wait blocks until the socket FD is ready for reading or writing, depending\n@@ -37,20 +37,20 @@ func (s *Socket) wait(write bool) error {\nreturn errClosing\n}\n- events := []linux.PollFD{\n+ events := []unix.PollFd{\n{\n// The actual socket FD.\n- FD: fd,\n- Events: linux.POLLIN,\n+ Fd: fd,\n+ Events: unix.POLLIN,\n},\n{\n// The eventfd, signaled when we are closing.\n- FD: int32(s.efd),\n- Events: linux.POLLIN,\n+ Fd: int32(s.efd),\n+ Events: unix.POLLIN,\n},\n}\nif write {\n- events[0].Events = linux.POLLOUT\n+ events[0].Events = unix.POLLOUT\n}\n_, _, e := syscall.Syscall(syscall.SYS_POLL, uintptr(unsafe.Pointer(&events[0])), 2, uintptr(math.MaxUint64))\n@@ -61,7 +61,7 @@ func (s *Socket) wait(write bool) error {\nreturn e\n}\n- if events[1].REvents&linux.POLLIN == linux.POLLIN {\n+ if events[1].Revents&unix.POLLIN == unix.POLLIN {\n// eventfd signaled, we're closing.\nreturn errClosing\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use x/sys/unix for sentry/host interaction; abi is for guest/sentry.
PiperOrigin-RevId: 260613864 |
259,907 | 29.07.2019 19:16:07 | 25,200 | ddf25e3331a18a74d0e01d74fee7f82963fe778c | ext: extent reader implementation. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/BUILD",
"new_path": "pkg/sentry/fs/ext/BUILD",
"diff": "@@ -42,6 +42,7 @@ go_library(\n\"//pkg/sentry/fs/ext/disklayout\",\n\"//pkg/sentry/kernel/auth\",\n\"//pkg/sentry/kernel/pipe\",\n+ \"//pkg/sentry/safemem\",\n\"//pkg/sentry/usermem\",\n\"//pkg/sentry/vfs\",\n\"//pkg/syserror\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/extent_file.go",
"new_path": "pkg/sentry/fs/ext/extent_file.go",
"diff": "@@ -16,6 +16,7 @@ package ext\nimport (\n\"io\"\n+ \"sort\"\n\"gvisor.dev/gvisor/pkg/binary\"\n\"gvisor.dev/gvisor/pkg/sentry/fs/ext/disklayout\"\n@@ -36,7 +37,12 @@ var _ fileReader = (*extentFile)(nil)\n// Read implements fileReader.getFileReader.\nfunc (f *extentFile) getFileReader(dev io.ReadSeeker, blkSize uint64, offset uint64) io.Reader {\n- panic(\"unimplemented\")\n+ return &extentReader{\n+ dev: dev,\n+ file: f,\n+ fileOff: offset,\n+ blkSize: blkSize,\n+ }\n}\n// newExtentFile is the extent file constructor. It reads the entire extent\n@@ -145,3 +151,113 @@ func buildExtTreeFromDisk(dev io.ReadSeeker, entry disklayout.ExtentEntry, blkSi\nreturn &disklayout.ExtentNode{header, entries}, nil\n}\n+\n+// extentReader implements io.Reader which can traverse the extent tree and\n+// read file data. This is not thread safe.\n+type extentReader struct {\n+ dev io.ReadSeeker\n+ file *extentFile\n+ fileOff uint64 // Represents the current file offset being read from.\n+ blkSize uint64\n+}\n+\n+// Compiles only if inlineReader implements io.Reader.\n+var _ io.Reader = (*extentReader)(nil)\n+\n+// Read implements io.Reader.Read.\n+func (r *extentReader) Read(dst []byte) (int, error) {\n+ if len(dst) == 0 {\n+ return 0, nil\n+ }\n+\n+ if r.fileOff >= r.file.regFile.inode.diskInode.Size() {\n+ return 0, io.EOF\n+ }\n+\n+ return r.read(&r.file.root, dst)\n+}\n+\n+// read is a helper which traverses the extent tree and reads data.\n+func (r *extentReader) read(node *disklayout.ExtentNode, dst []byte) (int, error) {\n+ // Perform a binary search for the node covering bytes starting at r.fileOff.\n+ // A highly fragmented filesystem can have upto 340 entries and so linear\n+ // search should be avoided. Finds the first entry which does not cover the\n+ // file block we want and subtracts 1 to get the desired index.\n+ fileBlk := r.fileBlock()\n+ n := len(node.Entries)\n+ found := sort.Search(n, func(i int) bool {\n+ return node.Entries[i].Entry.FileBlock() > fileBlk\n+ }) - 1\n+\n+ // We should be in this recursive step only if the data we want exists under\n+ // the current node.\n+ if found < 0 {\n+ panic(\"searching for a file block in an extent entry which does not cover it\")\n+ }\n+\n+ read := 0\n+ toRead := len(dst)\n+ var curR int\n+ var err error\n+ for i := found; i < n && read < toRead; i++ {\n+ if node.Header.Height == 0 {\n+ curR, err = r.readFromExtent(node.Entries[i].Entry.(*disklayout.Extent), dst[read:])\n+ } else {\n+ curR, err = r.read(node.Entries[i].Node, dst[read:])\n+ }\n+\n+ read += curR\n+ if err != nil {\n+ return read, err\n+ }\n+ }\n+\n+ return read, nil\n+}\n+\n+// readFromExtent reads file data from the extent. It takes advantage of the\n+// sequential nature of extents and reads file data from multiple blocks in one\n+// call. Also updates the file offset.\n+//\n+// A non-nil error indicates that this is a partial read and there is probably\n+// more to read from this extent. The caller should propagate the error upward\n+// and not move to the next extent in the tree.\n+//\n+// A subsequent call to extentReader.Read should continue reading from where we\n+// left off as expected.\n+func (r *extentReader) readFromExtent(ex *disklayout.Extent, dst []byte) (int, error) {\n+ curFileBlk := r.fileBlock()\n+ exFirstFileBlk := ex.FileBlock()\n+ exLastFileBlk := exFirstFileBlk + uint32(ex.Length) // This is exclusive.\n+\n+ // We should be in this recursive step only if the data we want exists under\n+ // the current extent.\n+ if curFileBlk < exFirstFileBlk || exLastFileBlk <= curFileBlk {\n+ panic(\"searching for a file block in an extent which does not cover it\")\n+ }\n+\n+ curPhyBlk := uint64(curFileBlk-exFirstFileBlk) + ex.PhysicalBlock()\n+ readStart := curPhyBlk*r.blkSize + r.fileBlockOff()\n+\n+ endPhyBlk := ex.PhysicalBlock() + uint64(ex.Length)\n+ extentEnd := endPhyBlk * r.blkSize // This is exclusive.\n+\n+ toRead := int(extentEnd - readStart)\n+ if len(dst) < toRead {\n+ toRead = len(dst)\n+ }\n+\n+ n, err := readFull(r.dev, int64(readStart), dst[:toRead])\n+ r.fileOff += uint64(n)\n+ return n, err\n+}\n+\n+// fileBlock returns the file block number we are currently reading.\n+func (r *extentReader) fileBlock() uint32 {\n+ return uint32(r.fileOff / r.blkSize)\n+}\n+\n+// fileBlockOff returns the current offset within the current file block.\n+func (r *extentReader) fileBlockOff() uint64 {\n+ return r.fileOff % r.blkSize\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/extent_test.go",
"new_path": "pkg/sentry/fs/ext/extent_test.go",
"diff": "@@ -16,6 +16,8 @@ package ext\nimport (\n\"bytes\"\n+ \"io\"\n+ \"math/rand\"\n\"testing\"\n\"github.com/google/go-cmp/cmp\"\n@@ -24,9 +26,14 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/fs/ext/disklayout\"\n)\n-// TestExtentTree tests the extent tree building logic.\n+const (\n+ // mockExtentBlkSize is the mock block size used for testing.\n+ // No block has more than 1 header + 4 entries.\n+ mockExtentBlkSize = uint64(64)\n+)\n+\n+// The tree described below looks like:\n//\n-// Test tree:\n// 0.{Head}[Idx][Idx]\n// / \\\n// / \\\n@@ -44,18 +51,8 @@ import (\n//\n// Please note that ext4 might not construct extent trees looking like this.\n// This is purely for testing the tree traversal logic.\n-func TestExtentTree(t *testing.T) {\n- blkSize := uint64(64) // No block has more than 1 header + 4 entries.\n- mockDisk := make([]byte, blkSize*10)\n- mockExtentFile := extentFile{\n- regFile: regularFile{\n- inode: inode{\n- diskInode: &disklayout.InodeNew{},\n- },\n- },\n- }\n-\n- node3 := &disklayout.ExtentNode{\n+var (\n+ node3 = &disklayout.ExtentNode{\nHeader: disklayout.ExtentHeader{\nMagic: disklayout.ExtentMagic,\nNumEntries: 1,\n@@ -74,7 +71,7 @@ func TestExtentTree(t *testing.T) {\n},\n}\n- node2 := &disklayout.ExtentNode{\n+ node2 = &disklayout.ExtentNode{\nHeader: disklayout.ExtentHeader{\nMagic: disklayout.ExtentMagic,\nNumEntries: 1,\n@@ -92,7 +89,7 @@ func TestExtentTree(t *testing.T) {\n},\n}\n- node1 := &disklayout.ExtentNode{\n+ node1 = &disklayout.ExtentNode{\nHeader: disklayout.ExtentHeader{\nMagic: disklayout.ExtentMagic,\nNumEntries: 2,\n@@ -119,7 +116,7 @@ func TestExtentTree(t *testing.T) {\n},\n}\n- node0 := &disklayout.ExtentNode{\n+ node0 = &disklayout.ExtentNode{\nHeader: disklayout.ExtentHeader{\nMagic: disklayout.ExtentMagic,\nNumEntries: 2,\n@@ -143,13 +140,57 @@ func TestExtentTree(t *testing.T) {\n},\n},\n}\n+)\n- writeTree(&mockExtentFile.regFile.inode, mockDisk, node0, blkSize)\n+// TestExtentReader tests extentReader functionality. We should be able to use\n+// the file reader like any other io.Reader.\n+func TestExtentReader(t *testing.T) {\n+ type extentReaderTest struct {\n+ name string\n+ from func(uint64) uint64\n+ to func(uint64) uint64\n+ }\n- r := bytes.NewReader(mockDisk)\n- if err := mockExtentFile.buildExtTree(r, blkSize); err != nil {\n- t.Fatalf(\"inode.buildExtTree failed: %v\", err)\n+ tests := []extentReaderTest{\n+ {\n+ name: \"read first half\",\n+ from: beginning,\n+ to: middle,\n+ },\n+ {\n+ name: \"read entire file\",\n+ from: beginning,\n+ to: end,\n+ },\n+ {\n+ name: \"read second half\",\n+ from: middle,\n+ to: end,\n+ },\n+ }\n+\n+ dev, mockExtentFile, want := extentTreeSetUp(t, node0)\n+ size := mockExtentFile.regFile.inode.diskInode.Size()\n+\n+ for _, test := range tests {\n+ from := test.from(size)\n+ to := test.to(size)\n+ fileReader := mockExtentFile.getFileReader(dev, mockExtentBlkSize, from)\n+\n+ got := make([]byte, to-from)\n+ if _, err := io.ReadFull(fileReader, got); err != nil {\n+ t.Errorf(\"file read failed: %v\", err)\n+ }\n+\n+ if diff := cmp.Diff(got, want[from:to]); diff != \"\" {\n+ t.Errorf(\"file data mismatch (-want +got):\\n%s\", diff)\n}\n+ }\n+}\n+\n+// TestBuildExtentTree tests the extent tree building logic.\n+func TestBuildExtentTree(t *testing.T) {\n+ _, mockExtentFile, _ := extentTreeSetUp(t, node0)\nopt := cmpopts.IgnoreUnexported(disklayout.ExtentIdx{}, disklayout.ExtentHeader{})\nif diff := cmp.Diff(&mockExtentFile.root, node0, opt); diff != \"\" {\n@@ -157,8 +198,37 @@ func TestExtentTree(t *testing.T) {\n}\n}\n-// writeTree writes the tree represented by `root` to the inode and disk passed.\n-func writeTree(in *inode, disk []byte, root *disklayout.ExtentNode, blkSize uint64) {\n+// extentTreeSetUp writes the passed extent tree to a mock disk as an extent\n+// tree. It also constucts a mock extent file with the same tree built in it.\n+// It also writes random data file data and returns it.\n+func extentTreeSetUp(t *testing.T, root *disklayout.ExtentNode) (io.ReadSeeker, *extentFile, []byte) {\n+ t.Helper()\n+\n+ mockDisk := make([]byte, mockExtentBlkSize*10)\n+ mockExtentFile := &extentFile{\n+ regFile: regularFile{\n+ inode: inode{\n+ diskInode: &disklayout.InodeNew{\n+ InodeOld: disklayout.InodeOld{\n+ SizeLo: uint32(mockExtentBlkSize) * getNumPhyBlks(root),\n+ },\n+ },\n+ },\n+ },\n+ }\n+\n+ fileData := writeTree(&mockExtentFile.regFile.inode, mockDisk, node0, mockExtentBlkSize)\n+\n+ r := bytes.NewReader(mockDisk)\n+ if err := mockExtentFile.buildExtTree(r, mockExtentBlkSize); err != nil {\n+ t.Fatalf(\"inode.buildExtTree failed: %v\", err)\n+ }\n+ return r, mockExtentFile, fileData\n+}\n+\n+// writeTree writes the tree represented by `root` to the inode and disk. It\n+// also writes random file data on disk.\n+func writeTree(in *inode, disk []byte, root *disklayout.ExtentNode, mockExtentBlkSize uint64) []byte {\nrootData := binary.Marshal(nil, binary.LittleEndian, root.Header)\nfor _, ep := range root.Entries {\nrootData = binary.Marshal(rootData, binary.LittleEndian, ep.Entry)\n@@ -166,26 +236,57 @@ func writeTree(in *inode, disk []byte, root *disklayout.ExtentNode, blkSize uint\ncopy(in.diskInode.Data(), rootData)\n- if root.Header.Height > 0 {\n+ var fileData []byte\nfor _, ep := range root.Entries {\n- writeTreeToDisk(disk, ep, blkSize)\n+ if root.Header.Height == 0 {\n+ fileData = append(fileData, writeRandomFileData(disk, ep.Entry.(*disklayout.Extent))...)\n+ } else {\n+ fileData = append(fileData, writeTreeToDisk(disk, ep)...)\n}\n}\n+ return fileData\n}\n// writeTreeToDisk is the recursive step for writeTree which writes the tree\n-// on the disk only.\n-func writeTreeToDisk(disk []byte, curNode disklayout.ExtentEntryPair, blkSize uint64) {\n+// on the disk only. Also writes random file data on disk.\n+func writeTreeToDisk(disk []byte, curNode disklayout.ExtentEntryPair) []byte {\nnodeData := binary.Marshal(nil, binary.LittleEndian, curNode.Node.Header)\nfor _, ep := range curNode.Node.Entries {\nnodeData = binary.Marshal(nodeData, binary.LittleEndian, ep.Entry)\n}\n- copy(disk[curNode.Entry.PhysicalBlock()*blkSize:], nodeData)\n+ copy(disk[curNode.Entry.PhysicalBlock()*mockExtentBlkSize:], nodeData)\n- if curNode.Node.Header.Height > 0 {\n+ var fileData []byte\nfor _, ep := range curNode.Node.Entries {\n- writeTreeToDisk(disk, ep, blkSize)\n+ if curNode.Node.Header.Height == 0 {\n+ fileData = append(fileData, writeRandomFileData(disk, ep.Entry.(*disklayout.Extent))...)\n+ } else {\n+ fileData = append(fileData, writeTreeToDisk(disk, ep)...)\n+ }\n+ }\n+ return fileData\n+}\n+\n+// writeRandomFileData writes random bytes to the blocks on disk that the\n+// passed extent points to.\n+func writeRandomFileData(disk []byte, ex *disklayout.Extent) []byte {\n+ phyExStartBlk := ex.PhysicalBlock()\n+ phyExStartOff := phyExStartBlk * mockExtentBlkSize\n+ phyExEndOff := phyExStartOff + uint64(ex.Length)*mockExtentBlkSize\n+ rand.Read(disk[phyExStartOff:phyExEndOff])\n+ return disk[phyExStartOff:phyExEndOff]\n+}\n+\n+// getNumPhyBlks returns the number of physical blocks covered under the node.\n+func getNumPhyBlks(node *disklayout.ExtentNode) uint32 {\n+ var res uint32\n+ for _, ep := range node.Entries {\n+ if node.Header.Height == 0 {\n+ res += uint32(ep.Entry.(*disklayout.Extent).Length)\n+ } else {\n+ res += getNumPhyBlks(ep.Node)\n}\n}\n+ return res\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/inline_file.go",
"new_path": "pkg/sentry/fs/ext/inline_file.go",
"diff": "@@ -40,7 +40,8 @@ func newInlineFile(regFile regularFile) *inlineFile {\nreturn file\n}\n-// inlineReader implements io.Reader which can read the underlying data.\n+// inlineReader implements io.Reader which can read the underlying data. This\n+// is not thread safe.\ntype inlineReader struct {\noffset uint64\ndata []byte\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/utils.go",
"new_path": "pkg/sentry/fs/ext/utils.go",
"diff": "@@ -41,6 +41,23 @@ func readFromDisk(dev io.ReadSeeker, abOff int64, v interface{}) error {\nreturn nil\n}\n+// readFull is a wrapper around io.ReadFull which enforces the absolute offset\n+// parameter so that we can ensure that we do not perform incorrect reads from\n+// stale previously used offsets.\n+//\n+// Precondition: Must hold the mutex of the filesystem containing dev.\n+func readFull(dev io.ReadSeeker, abOff int64, dst []byte) (int, error) {\n+ if _, err := dev.Seek(abOff, io.SeekStart); err != nil {\n+ return 0, syserror.EIO\n+ }\n+\n+ n, err := io.ReadFull(dev, dst)\n+ if err != nil {\n+ err = syserror.EIO\n+ }\n+ return n, err\n+}\n+\n// readSuperBlock reads the SuperBlock from block group 0 in the underlying\n// device. There are three versions of the superblock. This function identifies\n// and returns the correct version.\n"
}
] | Go | Apache License 2.0 | google/gvisor | ext: extent reader implementation.
PiperOrigin-RevId: 260629559 |
259,979 | 30.07.2019 10:53:55 | -28,800 | 50f3447786e09bb6c7bc4255c01a7339193a66a0 | Combine multiple epoll events copies
Allocate a larger memory buffer and combine multiple copies into one copy,
to reduce the number of copies from kernel memory to user memory. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_epoll.go",
"new_path": "pkg/sentry/syscalls/linux/sys_epoll.go",
"diff": "@@ -107,20 +107,21 @@ func EpollCtl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\n// copyOutEvents copies epoll events from the kernel to user memory.\nfunc copyOutEvents(t *kernel.Task, addr usermem.Addr, e []epoll.Event) error {\nconst itemLen = 12\n- if _, ok := addr.AddLength(uint64(len(e)) * itemLen); !ok {\n+ buffLen := len(e) * itemLen\n+ if _, ok := addr.AddLength(uint64(buffLen)); !ok {\nreturn syserror.EFAULT\n}\n- b := t.CopyScratchBuffer(itemLen)\n+ b := t.CopyScratchBuffer(buffLen)\nfor i := range e {\n- usermem.ByteOrder.PutUint32(b[0:], e[i].Events)\n- usermem.ByteOrder.PutUint32(b[4:], uint32(e[i].Data[0]))\n- usermem.ByteOrder.PutUint32(b[8:], uint32(e[i].Data[1]))\n+ usermem.ByteOrder.PutUint32(b[i*itemLen:], e[i].Events)\n+ usermem.ByteOrder.PutUint32(b[i*itemLen+4:], uint32(e[i].Data[0]))\n+ usermem.ByteOrder.PutUint32(b[i*itemLen+8:], uint32(e[i].Data[1]))\n+ }\n+\nif _, err := t.CopyOutBytes(addr, b); err != nil {\nreturn err\n}\n- addr += itemLen\n- }\nreturn nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Combine multiple epoll events copies
Allocate a larger memory buffer and combine multiple copies into one copy,
to reduce the number of copies from kernel memory to user memory.
Signed-off-by: Hang Su <[email protected]> |
259,974 | 30.07.2019 10:59:57 | 25,200 | 1decf764718f66097ce5bbfe2cd14a883a4ef713 | Change syscall.POLL to syscall.PPOLL.
syscall.POLL is not supported on arm64, using syscall.PPOLL
to support both the x86 and arm64. refs
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/gvisor/pull/543 from xiaobo55x:master | [
{
"change_type": "MODIFY",
"old_path": "pkg/fdnotifier/poll_unsafe.go",
"new_path": "pkg/fdnotifier/poll_unsafe.go",
"diff": "@@ -35,8 +35,14 @@ func NonBlockingPoll(fd int32, mask waiter.EventMask) waiter.EventMask {\nevents: int16(mask.ToLinux()),\n}\n+ ts := syscall.Timespec{\n+ Sec: 0,\n+ Nsec: 0,\n+ }\n+\nfor {\n- n, _, err := syscall.RawSyscall(syscall.SYS_POLL, uintptr(unsafe.Pointer(&e)), 1, 0)\n+ n, _, err := syscall.RawSyscall6(syscall.SYS_PPOLL, uintptr(unsafe.Pointer(&e)), 1,\n+ uintptr(unsafe.Pointer(&ts)), 0, 0, 0)\n// Interrupted by signal, try again.\nif err == syscall.EINTR {\ncontinue\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/seccomp/seccomp_test_victim.go",
"new_path": "pkg/seccomp/seccomp_test_victim.go",
"diff": "@@ -70,7 +70,7 @@ func main() {\nsyscall.SYS_NANOSLEEP: {},\nsyscall.SYS_NEWFSTATAT: {},\nsyscall.SYS_OPEN: {},\n- syscall.SYS_POLL: {},\n+ syscall.SYS_PPOLL: {},\nsyscall.SYS_PREAD64: {},\nsyscall.SYS_PSELECT6: {},\nsyscall.SYS_PWRITE64: {},\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/mmap_amd64.go",
"new_path": "pkg/tcpip/link/fdbased/mmap_amd64.go",
"diff": "@@ -134,7 +134,7 @@ func (d *packetMMapDispatcher) readMMappedPacket() ([]byte, *tcpip.Error) {\nFD: int32(d.fd),\nEvents: unix.POLLIN | unix.POLLERR,\n}\n- if _, errno := rawfile.BlockingPoll(&event, 1, -1); errno != 0 {\n+ if _, errno := rawfile.BlockingPoll(&event, 1, nil); errno != 0 {\nif errno == syscall.EINTR {\ncontinue\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/rawfile/blockingpoll_amd64_unsafe.go",
"new_path": "pkg/tcpip/link/rawfile/blockingpoll_amd64_unsafe.go",
"diff": "@@ -26,7 +26,7 @@ import (\n)\n//go:noescape\n-func BlockingPoll(fds *PollEvent, nfds int, timeout int64) (int, syscall.Errno)\n+func BlockingPoll(fds *PollEvent, nfds int, timeout *syscall.Timespec) (int, syscall.Errno)\n// Use go:linkname to call into the runtime. As of Go 1.12 this has to\n// be done from Go code so that we make an ABIInternal call to an\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/rawfile/blockingpoll_unsafe.go",
"new_path": "pkg/tcpip/link/rawfile/blockingpoll_unsafe.go",
"diff": "@@ -21,9 +21,11 @@ import (\n\"unsafe\"\n)\n-// BlockingPoll is just a stub function that forwards to the poll() system call\n+// BlockingPoll is just a stub function that forwards to the ppoll() system call\n// on non-amd64 platforms.\n-func BlockingPoll(fds *PollEvent, nfds int, timeout int64) (int, syscall.Errno) {\n- n, _, e := syscall.Syscall(syscall.SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout))\n+func BlockingPoll(fds *PollEvent, nfds int, timeout *syscall.Timespec) (int, syscall.Errno) {\n+ n, _, e := syscall.Syscall6(syscall.SYS_PPOLL, uintptr(unsafe.Pointer(fds)),\n+ uintptr(nfds), uintptr(unsafe.Pointer(timeout)), 0, 0, 0)\n+\nreturn int(n), e\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/rawfile/rawfile_unsafe.go",
"new_path": "pkg/tcpip/link/rawfile/rawfile_unsafe.go",
"diff": "@@ -123,7 +123,7 @@ func BlockingRead(fd int, b []byte) (int, *tcpip.Error) {\nEvents: 1, // POLLIN\n}\n- _, e = BlockingPoll(&event, 1, -1)\n+ _, e = BlockingPoll(&event, 1, nil)\nif e != 0 && e != syscall.EINTR {\nreturn 0, TranslateErrno(e)\n}\n@@ -145,7 +145,7 @@ func BlockingReadv(fd int, iovecs []syscall.Iovec) (int, *tcpip.Error) {\nEvents: 1, // POLLIN\n}\n- _, e = BlockingPoll(&event, 1, -1)\n+ _, e = BlockingPoll(&event, 1, nil)\nif e != 0 && e != syscall.EINTR {\nreturn 0, TranslateErrno(e)\n}\n@@ -175,7 +175,7 @@ func BlockingRecvMMsg(fd int, msgHdrs []MMsgHdr) (int, *tcpip.Error) {\nEvents: 1, // POLLIN\n}\n- if _, e := BlockingPoll(&event, 1, -1); e != 0 && e != syscall.EINTR {\n+ if _, e := BlockingPoll(&event, 1, nil); e != 0 && e != syscall.EINTR {\nreturn 0, TranslateErrno(e)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/unet/unet_unsafe.go",
"new_path": "pkg/unet/unet_unsafe.go",
"diff": "@@ -16,7 +16,6 @@ package unet\nimport (\n\"io\"\n- \"math\"\n\"sync/atomic\"\n\"syscall\"\n\"unsafe\"\n@@ -53,7 +52,7 @@ func (s *Socket) wait(write bool) error {\nevents[0].Events = unix.POLLOUT\n}\n- _, _, e := syscall.Syscall(syscall.SYS_POLL, uintptr(unsafe.Pointer(&events[0])), 2, uintptr(math.MaxUint64))\n+ _, _, e := syscall.Syscall6(syscall.SYS_PPOLL, uintptr(unsafe.Pointer(&events[0])), 2, 0, 0, 0, 0)\nif e == syscall.EINTR {\ncontinue\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/filter/config.go",
"new_path": "runsc/boot/filter/config.go",
"diff": "@@ -207,7 +207,7 @@ var allowedSyscalls = seccomp.SyscallRules{\nsyscall.SYS_MPROTECT: {},\nsyscall.SYS_MUNMAP: {},\nsyscall.SYS_NANOSLEEP: {},\n- syscall.SYS_POLL: {},\n+ syscall.SYS_PPOLL: {},\nsyscall.SYS_PREAD64: {},\nsyscall.SYS_PWRITE64: {},\nsyscall.SYS_READ: {},\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/filter/config.go",
"new_path": "runsc/fsgofer/filter/config.go",
"diff": "@@ -138,7 +138,7 @@ var allowedSyscalls = seccomp.SyscallRules{\nsyscall.SYS_NANOSLEEP: {},\nsyscall.SYS_NEWFSTATAT: {},\nsyscall.SYS_OPENAT: {},\n- syscall.SYS_POLL: {},\n+ syscall.SYS_PPOLL: {},\nsyscall.SYS_PREAD64: {},\nsyscall.SYS_PWRITE64: {},\nsyscall.SYS_READ: {},\n"
}
] | Go | Apache License 2.0 | google/gvisor | Change syscall.POLL to syscall.PPOLL.
syscall.POLL is not supported on arm64, using syscall.PPOLL
to support both the x86 and arm64. refs #63
Signed-off-by: Haibo Xu <[email protected]>
Change-Id: I2c81a063d3ec4e7e6b38fe62f17a0924977f505e
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/gvisor/pull/543 from xiaobo55x:master ba598263fd3748d1addd48e4194080aa12085164
PiperOrigin-RevId: 260752049 |
259,884 | 30.07.2019 16:55:05 | 25,200 | 885e17f890d1d7c559871f720c40cef5cad69bc2 | Remove unused const variables | [
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/network.go",
"new_path": "runsc/sandbox/network.go",
"diff": "@@ -33,13 +33,6 @@ import (\n\"gvisor.dev/gvisor/runsc/specutils\"\n)\n-const (\n- // Annotations used to indicate whether the container corresponds to a\n- // pod or a container within a pod.\n- crioContainerTypeAnnotation = \"io.kubernetes.cri-o.ContainerType\"\n- containerdContainerTypeAnnotation = \"io.kubernetes.cri.container-type\"\n-)\n-\n// setupNetwork configures the network stack to mimic the local network\n// configuration. Docker uses network namespaces with vnets to configure the\n// network for the container. The untrusted app expects to see the same network\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove unused const variables
PiperOrigin-RevId: 260824989 |
259,907 | 30.07.2019 18:19:15 | 25,200 | 9fbe984dc13f1af42bf3a73b696f7358794dd2d4 | ext: block map file reader implementation.
Also adds stress tests for block map reader and intensifies extent reader tests. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/BUILD",
"new_path": "pkg/sentry/fs/ext/BUILD",
"diff": "@@ -54,6 +54,7 @@ go_test(\nname = \"ext_test\",\nsize = \"small\",\nsrcs = [\n+ \"block_map_test.go\",\n\"ext_test.go\",\n\"extent_test.go\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/block_map_file.go",
"new_path": "pkg/sentry/fs/ext/block_map_file.go",
"diff": "@@ -16,9 +16,15 @@ package ext\nimport (\n\"io\"\n- \"sync\"\n+ \"math\"\n\"gvisor.dev/gvisor/pkg/binary\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+)\n+\n+const (\n+ // numDirectBlks is the number of direct blocks in ext block map inodes.\n+ numDirectBlks = 12\n)\n// blockMapFile is a type of regular file which uses direct/indirect block\n@@ -26,14 +32,25 @@ import (\ntype blockMapFile struct {\nregFile regularFile\n- // mu serializes changes to fileToPhysBlks.\n- mu sync.RWMutex\n+ // directBlks are the direct blocks numbers. The physical blocks pointed by\n+ // these holds file data. Contains file blocks 0 to 11.\n+ directBlks [numDirectBlks]uint32\n+\n+ // indirectBlk is the physical block which contains (blkSize/4) direct block\n+ // numbers (as uint32 integers).\n+ indirectBlk uint32\n- // fileToPhysBlks maps the file block numbers to the physical block numbers.\n- // the physical block number for the (i)th file block is stored in the (i)th\n- // index. This is initialized (at max) with the first 12 entries. The rest\n- // have to be read in from disk when required. Protected by mu.\n- fileToPhysBlks []uint32\n+ // doubleIndirectBlk is the physical block which contains (blkSize/4) indirect\n+ // block numbers (as uint32 integers).\n+ doubleIndirectBlk uint32\n+\n+ // tripleIndirectBlk is the physical block which contains (blkSize/4) doubly\n+ // indirect block numbers (as uint32 integers).\n+ tripleIndirectBlk uint32\n+\n+ // coverage at (i)th index indicates the amount of file data a node at\n+ // height (i) covers. Height 0 is the direct block.\n+ coverage [4]uint64\n}\n// Compiles only if blockMapFile implements fileReader.\n@@ -41,7 +58,12 @@ var _ fileReader = (*blockMapFile)(nil)\n// Read implements fileReader.getFileReader.\nfunc (f *blockMapFile) getFileReader(dev io.ReaderAt, blkSize uint64, offset uint64) io.Reader {\n- panic(\"unimplemented\")\n+ return &blockMapReader{\n+ dev: dev,\n+ file: f,\n+ fileOff: offset,\n+ blkSize: blkSize,\n+ }\n}\n// newBlockMapFile is the blockMapFile constructor. It initializes the file to\n@@ -50,16 +72,138 @@ func newBlockMapFile(blkSize uint64, regFile regularFile) (*blockMapFile, error)\nfile := &blockMapFile{regFile: regFile}\nfile.regFile.impl = file\n- toFill := uint64(12)\n- blksUsed := regFile.blksUsed(blkSize)\n- if blksUsed < toFill {\n- toFill = blksUsed\n+ for i := uint(0); i < 4; i++ {\n+ file.coverage[i] = getCoverage(blkSize, i)\n}\nblkMap := regFile.inode.diskInode.Data()\n- file.fileToPhysBlks = make([]uint32, toFill)\n- for i := uint64(0); i < toFill; i++ {\n- binary.Unmarshal(blkMap[i*4:(i+1)*4], binary.LittleEndian, &file.fileToPhysBlks[i])\n- }\n+ binary.Unmarshal(blkMap[:numDirectBlks*4], binary.LittleEndian, &file.directBlks)\n+ binary.Unmarshal(blkMap[numDirectBlks*4:(numDirectBlks+1)*4], binary.LittleEndian, &file.indirectBlk)\n+ binary.Unmarshal(blkMap[(numDirectBlks+1)*4:(numDirectBlks+2)*4], binary.LittleEndian, &file.doubleIndirectBlk)\n+ binary.Unmarshal(blkMap[(numDirectBlks+2)*4:(numDirectBlks+3)*4], binary.LittleEndian, &file.tripleIndirectBlk)\nreturn file, nil\n}\n+\n+// blockMapReader implements io.Reader which will fetch fill data from the\n+// block maps and build the blockMapFile.fileToPhyBlks array if required.\n+type blockMapReader struct {\n+ dev io.ReaderAt\n+ file *blockMapFile\n+ fileOff uint64\n+ blkSize uint64\n+}\n+\n+// Compiles only if blockMapReader implements io.Reader.\n+var _ io.Reader = (*blockMapReader)(nil)\n+\n+// Read implements io.Reader.Read.\n+func (r *blockMapReader) Read(dst []byte) (int, error) {\n+ if len(dst) == 0 {\n+ return 0, nil\n+ }\n+\n+ if r.fileOff >= r.file.regFile.inode.diskInode.Size() {\n+ return 0, io.EOF\n+ }\n+\n+ // dirBlksEnd is the file offset until which direct blocks cover file data.\n+ // Direct blocks cover 0 <= file offset < dirBlksEnd.\n+ dirBlksEnd := numDirectBlks * r.file.coverage[0]\n+\n+ // indirBlkEnd is the file offset until which the indirect block covers file\n+ // data. The indirect block covers dirBlksEnd <= file offset < indirBlkEnd.\n+ indirBlkEnd := dirBlksEnd + r.file.coverage[1]\n+\n+ // doubIndirBlkEnd is the file offset until which the double indirect block\n+ // covers file data. The double indirect block covers the range\n+ // indirBlkEnd <= file offset < doubIndirBlkEnd.\n+ doubIndirBlkEnd := indirBlkEnd + r.file.coverage[2]\n+\n+ read := 0\n+ toRead := len(dst)\n+ for read < toRead {\n+ var err error\n+ var curR int\n+\n+ // Figure out which block to delegate the read to.\n+ switch {\n+ case r.fileOff < dirBlksEnd:\n+ // Direct block.\n+ curR, err = r.read(r.file.directBlks[r.fileOff/r.blkSize], r.fileOff%r.blkSize, 0, dst[read:])\n+ case r.fileOff < indirBlkEnd:\n+ // Indirect block.\n+ curR, err = r.read(r.file.indirectBlk, r.fileOff-dirBlksEnd, 1, dst[read:])\n+ case r.fileOff < doubIndirBlkEnd:\n+ // Doubly indirect block.\n+ curR, err = r.read(r.file.doubleIndirectBlk, r.fileOff-indirBlkEnd, 2, dst[read:])\n+ default:\n+ // Triply indirect block.\n+ curR, err = r.read(r.file.tripleIndirectBlk, r.fileOff-doubIndirBlkEnd, 3, dst[read:])\n+ }\n+\n+ read += curR\n+ if err != nil {\n+ return read, err\n+ }\n+ }\n+\n+ return read, nil\n+}\n+\n+// read is the recursive step of the Read function. It relies on knowing the\n+// current node's location on disk (curPhyBlk) and its height in the block map\n+// tree. A height of 0 shows that the current node is actually holding file\n+// data. relFileOff tells the offset from which we need to start to reading\n+// under the current node. It is completely relative to the current node.\n+func (r *blockMapReader) read(curPhyBlk uint32, relFileOff uint64, height uint, dst []byte) (int, error) {\n+ curPhyBlkOff := int64(curPhyBlk) * int64(r.blkSize)\n+ if height == 0 {\n+ toRead := int(r.blkSize - relFileOff)\n+ if len(dst) < toRead {\n+ toRead = len(dst)\n+ }\n+\n+ n, _ := r.dev.ReadAt(dst[:toRead], curPhyBlkOff+int64(relFileOff))\n+ r.fileOff += uint64(n)\n+ if n < toRead {\n+ return n, syserror.EIO\n+ }\n+ return n, nil\n+ }\n+\n+ childCov := r.file.coverage[height-1]\n+ startIdx := relFileOff / childCov\n+ endIdx := r.blkSize / 4 // This is exclusive.\n+ wantEndIdx := (relFileOff + uint64(len(dst))) / childCov\n+ wantEndIdx++ // Make this exclusive.\n+ if wantEndIdx < endIdx {\n+ endIdx = wantEndIdx\n+ }\n+\n+ read := 0\n+ curChildOff := relFileOff % childCov\n+ for i := startIdx; i < endIdx; i++ {\n+ var childPhyBlk uint32\n+ if err := readFromDisk(r.dev, curPhyBlkOff+int64(i*4), &childPhyBlk); err != nil {\n+ return read, err\n+ }\n+\n+ n, err := r.read(childPhyBlk, curChildOff, height-1, dst[read:])\n+ read += n\n+ if err != nil {\n+ return read, err\n+ }\n+\n+ curChildOff = 0\n+ }\n+\n+ return read, nil\n+}\n+\n+// getCoverage returns the number of bytes a node at the given height covers.\n+// Height 0 is the file data block itself. Height 1 is the indirect block.\n+//\n+// Formula: blkSize * ((blkSize / 4)^height)\n+func getCoverage(blkSize uint64, height uint) uint64 {\n+ return blkSize * uint64(math.Pow(float64(blkSize/4), float64(height)))\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/ext/block_map_test.go",
"diff": "+// Copyright 2019 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 ext\n+\n+import (\n+ \"bytes\"\n+ \"io\"\n+ \"math/rand\"\n+ \"testing\"\n+\n+ \"github.com/google/go-cmp/cmp\"\n+ \"gvisor.dev/gvisor/pkg/binary\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fs/ext/disklayout\"\n+)\n+\n+// These consts are for mocking the block map tree.\n+const (\n+ mockBMBlkSize = uint32(16)\n+ mockBMDiskSize = 2500\n+)\n+\n+// TestBlockMapReader stress tests block map reader functionality. It performs\n+// random length reads from all possible positions in the block map structure.\n+func TestBlockMapReader(t *testing.T) {\n+ dev, mockBMFile, want := blockMapSetUp(t)\n+ n := len(want)\n+\n+ for from := 0; from < n; from++ {\n+ fileReader := mockBMFile.getFileReader(dev, uint64(mockBMBlkSize), uint64(from))\n+ got := make([]byte, n-from)\n+\n+ if read, err := io.ReadFull(fileReader, got); err != nil {\n+ t.Fatalf(\"file read operation from offset %d to %d only read %d bytes: %v\", from, n, read, err)\n+ }\n+\n+ if diff := cmp.Diff(got, want[from:]); diff != \"\" {\n+ t.Fatalf(\"file data from offset %d to %d mismatched (-want +got):\\n%s\", from, n, diff)\n+ }\n+ }\n+}\n+\n+// blkNumGen is a number generator which gives block numbers for building the\n+// block map file on disk. It gives unique numbers in a random order which\n+// facilitates in creating an extremely fragmented filesystem.\n+type blkNumGen struct {\n+ nums []uint32\n+}\n+\n+// newBlkNumGen is the blkNumGen constructor.\n+func newBlkNumGen() *blkNumGen {\n+ blkNums := &blkNumGen{}\n+ lim := mockBMDiskSize / mockBMBlkSize\n+ blkNums.nums = make([]uint32, lim)\n+ for i := uint32(0); i < lim; i++ {\n+ blkNums.nums[i] = i\n+ }\n+\n+ rand.Shuffle(int(lim), func(i, j int) {\n+ blkNums.nums[i], blkNums.nums[j] = blkNums.nums[j], blkNums.nums[i]\n+ })\n+ return blkNums\n+}\n+\n+// next returns the next random block number.\n+func (n *blkNumGen) next() uint32 {\n+ ret := n.nums[0]\n+ n.nums = n.nums[1:]\n+ return ret\n+}\n+\n+// blockMapSetUp creates a mock disk and a block map file. It initializes the\n+// block map file with 12 direct block, 1 indirect block, 1 double indirect\n+// block and 1 triple indirect block (basically fill it till the rim). It\n+// initializes the disk to reflect the inode. Also returns the file data that\n+// the inode covers and that is written to disk.\n+func blockMapSetUp(t *testing.T) (io.ReaderAt, *blockMapFile, []byte) {\n+ mockDisk := make([]byte, mockBMDiskSize)\n+ regFile := regularFile{\n+ inode: inode{\n+ diskInode: &disklayout.InodeNew{\n+ InodeOld: disklayout.InodeOld{\n+ SizeLo: getMockBMFileFize(),\n+ },\n+ },\n+ },\n+ }\n+\n+ var fileData []byte\n+ blkNums := newBlkNumGen()\n+ var data []byte\n+\n+ // Write the direct blocks.\n+ for i := 0; i < numDirectBlks; i++ {\n+ curBlkNum := blkNums.next()\n+ data = binary.Marshal(data, binary.LittleEndian, curBlkNum)\n+ fileData = append(fileData, writeFileDataToBlock(mockDisk, curBlkNum, 0, blkNums)...)\n+ }\n+\n+ // Write to indirect block.\n+ indirectBlk := blkNums.next()\n+ data = binary.Marshal(data, binary.LittleEndian, indirectBlk)\n+ fileData = append(fileData, writeFileDataToBlock(mockDisk, indirectBlk, 1, blkNums)...)\n+\n+ // Write to indirect block.\n+ doublyIndirectBlk := blkNums.next()\n+ data = binary.Marshal(data, binary.LittleEndian, doublyIndirectBlk)\n+ fileData = append(fileData, writeFileDataToBlock(mockDisk, doublyIndirectBlk, 2, blkNums)...)\n+\n+ // Write to indirect block.\n+ triplyIndirectBlk := blkNums.next()\n+ data = binary.Marshal(data, binary.LittleEndian, triplyIndirectBlk)\n+ fileData = append(fileData, writeFileDataToBlock(mockDisk, triplyIndirectBlk, 3, blkNums)...)\n+\n+ copy(regFile.inode.diskInode.Data(), data)\n+\n+ mockFile, err := newBlockMapFile(uint64(mockBMBlkSize), regFile)\n+ if err != nil {\n+ t.Fatalf(\"newBlockMapFile failed: %v\", err)\n+ }\n+ return bytes.NewReader(mockDisk), mockFile, fileData\n+}\n+\n+// writeFileDataToBlock writes random bytes to the block on disk.\n+func writeFileDataToBlock(disk []byte, blkNum uint32, height uint, blkNums *blkNumGen) []byte {\n+ if height == 0 {\n+ start := blkNum * mockBMBlkSize\n+ end := start + mockBMBlkSize\n+ rand.Read(disk[start:end])\n+ return disk[start:end]\n+ }\n+\n+ var fileData []byte\n+ for off := blkNum * mockBMBlkSize; off < (blkNum+1)*mockBMBlkSize; off += 4 {\n+ curBlkNum := blkNums.next()\n+ copy(disk[off:off+4], binary.Marshal(nil, binary.LittleEndian, curBlkNum))\n+ fileData = append(fileData, writeFileDataToBlock(disk, curBlkNum, height-1, blkNums)...)\n+ }\n+ return fileData\n+}\n+\n+// getMockBMFileFize gets the size of the mock block map file which is used for\n+// testing.\n+func getMockBMFileFize() uint32 {\n+ return uint32(numDirectBlks*getCoverage(uint64(mockBMBlkSize), 0) + getCoverage(uint64(mockBMBlkSize), 1) + getCoverage(uint64(mockBMBlkSize), 2) + getCoverage(uint64(mockBMBlkSize), 3))\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/ext_test.go",
"new_path": "pkg/sentry/fs/ext/ext_test.go",
"diff": "@@ -41,18 +41,6 @@ var (\next4ImagePath = path.Join(assetsDir, \"tiny.ext4\")\n)\n-func beginning(_ uint64) uint64 {\n- return 0\n-}\n-\n-func middle(i uint64) uint64 {\n- return i / 2\n-}\n-\n-func end(i uint64) uint64 {\n- return i\n-}\n-\n// setUp opens imagePath as an ext Filesystem and returns all necessary\n// elements required to run tests. If error is non-nil, it also returns a tear\n// down function which must be called after the test is run for clean up.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/extent_test.go",
"new_path": "pkg/sentry/fs/ext/extent_test.go",
"diff": "@@ -142,48 +142,22 @@ var (\n}\n)\n-// TestExtentReader tests extentReader functionality. We should be able to use\n-// the file reader like any other io.Reader.\n+// TestExtentReader stress tests extentReader functionality. It performs random\n+// length reads from all possible positions in the extent tree.\nfunc TestExtentReader(t *testing.T) {\n- type extentReaderTest struct {\n- name string\n- from func(uint64) uint64\n- to func(uint64) uint64\n- }\n-\n- tests := []extentReaderTest{\n- {\n- name: \"read first half\",\n- from: beginning,\n- to: middle,\n- },\n- {\n- name: \"read entire file\",\n- from: beginning,\n- to: end,\n- },\n- {\n- name: \"read second half\",\n- from: middle,\n- to: end,\n- },\n- }\n-\ndev, mockExtentFile, want := extentTreeSetUp(t, node0)\n- size := mockExtentFile.regFile.inode.diskInode.Size()\n+ n := len(want)\n- for _, test := range tests {\n- from := test.from(size)\n- to := test.to(size)\n- fileReader := mockExtentFile.getFileReader(dev, mockExtentBlkSize, from)\n+ for from := 0; from < n; from++ {\n+ fileReader := mockExtentFile.getFileReader(dev, mockExtentBlkSize, uint64(from))\n+ got := make([]byte, n-from)\n- got := make([]byte, to-from)\n- if _, err := io.ReadFull(fileReader, got); err != nil {\n- t.Errorf(\"file read failed: %v\", err)\n+ if read, err := io.ReadFull(fileReader, got); err != nil {\n+ t.Fatalf(\"file read operation from offset %d to %d only read %d bytes: %v\", from, n, read, err)\n}\n- if diff := cmp.Diff(got, want[from:to]); diff != \"\" {\n- t.Errorf(\"file data mismatch (-want +got):\\n%s\", diff)\n+ if diff := cmp.Diff(got, want[from:]); diff != \"\" {\n+ t.Fatalf(\"file data from offset %d to %d mismatched (-want +got):\\n%s\", from, n, diff)\n}\n}\n}\n@@ -239,7 +213,7 @@ func writeTree(in *inode, disk []byte, root *disklayout.ExtentNode, mockExtentBl\nvar fileData []byte\nfor _, ep := range root.Entries {\nif root.Header.Height == 0 {\n- fileData = append(fileData, writeRandomFileData(disk, ep.Entry.(*disklayout.Extent))...)\n+ fileData = append(fileData, writeFileDataToExtent(disk, ep.Entry.(*disklayout.Extent))...)\n} else {\nfileData = append(fileData, writeTreeToDisk(disk, ep)...)\n}\n@@ -260,7 +234,7 @@ func writeTreeToDisk(disk []byte, curNode disklayout.ExtentEntryPair) []byte {\nvar fileData []byte\nfor _, ep := range curNode.Node.Entries {\nif curNode.Node.Header.Height == 0 {\n- fileData = append(fileData, writeRandomFileData(disk, ep.Entry.(*disklayout.Extent))...)\n+ fileData = append(fileData, writeFileDataToExtent(disk, ep.Entry.(*disklayout.Extent))...)\n} else {\nfileData = append(fileData, writeTreeToDisk(disk, ep)...)\n}\n@@ -268,9 +242,9 @@ func writeTreeToDisk(disk []byte, curNode disklayout.ExtentEntryPair) []byte {\nreturn fileData\n}\n-// writeRandomFileData writes random bytes to the blocks on disk that the\n+// writeFileDataToExtent writes random bytes to the blocks on disk that the\n// passed extent points to.\n-func writeRandomFileData(disk []byte, ex *disklayout.Extent) []byte {\n+func writeFileDataToExtent(disk []byte, ex *disklayout.Extent) []byte {\nphyExStartBlk := ex.PhysicalBlock()\nphyExStartOff := phyExStartBlk * mockExtentBlkSize\nphyExEndOff := phyExStartOff + uint64(ex.Length)*mockExtentBlkSize\n"
}
] | Go | Apache License 2.0 | google/gvisor | ext: block map file reader implementation.
Also adds stress tests for block map reader and intensifies extent reader tests.
PiperOrigin-RevId: 260838177 |
259,885 | 30.07.2019 20:31:29 | 25,200 | a7d5e0d254f22dc7d76f7f5bc86b8793f67e2f5f | Cache pages in CachingInodeOperations.Read when memory evictions are delayed. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/fsutil/inode_cached.go",
"new_path": "pkg/sentry/fs/fsutil/inode_cached.go",
"diff": "@@ -568,21 +568,30 @@ type inodeReadWriter struct {\n// ReadToBlocks implements safemem.Reader.ReadToBlocks.\nfunc (rw *inodeReadWriter) ReadToBlocks(dsts safemem.BlockSeq) (uint64, error) {\n+ mem := rw.c.mfp.MemoryFile()\n+ fillCache := !rw.c.useHostPageCache() && mem.ShouldCacheEvictable()\n+\n// Hot path. Avoid defers.\n+ var unlock func()\n+ if fillCache {\n+ rw.c.dataMu.Lock()\n+ unlock = rw.c.dataMu.Unlock\n+ } else {\nrw.c.dataMu.RLock()\n+ unlock = rw.c.dataMu.RUnlock\n+ }\n// Compute the range to read.\nif rw.offset >= rw.c.attr.Size {\n- rw.c.dataMu.RUnlock()\n+ unlock()\nreturn 0, io.EOF\n}\nend := fs.ReadEndOffset(rw.offset, int64(dsts.NumBytes()), rw.c.attr.Size)\nif end == rw.offset { // dsts.NumBytes() == 0?\n- rw.c.dataMu.RUnlock()\n+ unlock()\nreturn 0, nil\n}\n- mem := rw.c.mfp.MemoryFile()\nvar done uint64\nseg, gap := rw.c.cache.Find(uint64(rw.offset))\nfor rw.offset < end {\n@@ -592,7 +601,7 @@ func (rw *inodeReadWriter) ReadToBlocks(dsts safemem.BlockSeq) (uint64, error) {\n// Get internal mappings from the cache.\nims, err := mem.MapInternal(seg.FileRangeOf(seg.Range().Intersect(mr)), usermem.Read)\nif err != nil {\n- rw.c.dataMu.RUnlock()\n+ unlock()\nreturn done, err\n}\n@@ -602,7 +611,7 @@ func (rw *inodeReadWriter) ReadToBlocks(dsts safemem.BlockSeq) (uint64, error) {\nrw.offset += int64(n)\ndsts = dsts.DropFirst64(n)\nif err != nil {\n- rw.c.dataMu.RUnlock()\n+ unlock()\nreturn done, err\n}\n@@ -610,27 +619,48 @@ func (rw *inodeReadWriter) ReadToBlocks(dsts safemem.BlockSeq) (uint64, error) {\nseg, gap = seg.NextNonEmpty()\ncase gap.Ok():\n+ gapMR := gap.Range().Intersect(mr)\n+ if fillCache {\n+ // Read into the cache, then re-enter the loop to read from the\n+ // cache.\n+ reqMR := memmap.MappableRange{\n+ Start: uint64(usermem.Addr(gapMR.Start).RoundDown()),\n+ End: fs.OffsetPageEnd(int64(gapMR.End)),\n+ }\n+ optMR := gap.Range()\n+ err := rw.c.cache.Fill(rw.ctx, reqMR, maxFillRange(reqMR, optMR), mem, usage.PageCache, rw.c.backingFile.ReadToBlocksAt)\n+ mem.MarkEvictable(rw.c, pgalloc.EvictableRange{optMR.Start, optMR.End})\n+ seg, gap = rw.c.cache.Find(uint64(rw.offset))\n+ if !seg.Ok() {\n+ unlock()\n+ return done, err\n+ }\n+ // err might have occurred in part of gap.Range() outside\n+ // gapMR. Forget about it for now; if the error matters and\n+ // persists, we'll run into it again in a later iteration of\n+ // this loop.\n+ } else {\n// Read directly from the backing file.\n- gapmr := gap.Range().Intersect(mr)\n- dst := dsts.TakeFirst64(gapmr.Length())\n- n, err := rw.c.backingFile.ReadToBlocksAt(rw.ctx, dst, gapmr.Start)\n+ dst := dsts.TakeFirst64(gapMR.Length())\n+ n, err := rw.c.backingFile.ReadToBlocksAt(rw.ctx, dst, gapMR.Start)\ndone += n\nrw.offset += int64(n)\ndsts = dsts.DropFirst64(n)\n// Partial reads are fine. But we must stop reading.\nif n != dst.NumBytes() || err != nil {\n- rw.c.dataMu.RUnlock()\n+ unlock()\nreturn done, err\n}\n// Continue.\nseg, gap = gap.NextSegment(), FileRangeGapIterator{}\n+ }\ndefault:\nbreak\n}\n}\n- rw.c.dataMu.RUnlock()\n+ unlock()\nreturn done, nil\n}\n@@ -700,7 +730,10 @@ func (rw *inodeReadWriter) WriteFromBlocks(srcs safemem.BlockSeq) (uint64, error\nseg, gap = seg.NextNonEmpty()\ncase gap.Ok() && gap.Start() < mr.End:\n- // Write directly to the backing file.\n+ // Write directly to the backing file. At present, we never fill\n+ // the cache when writing, since doing so can convert small writes\n+ // into inefficient read-modify-write cycles, and we have no\n+ // mechanism for detecting or avoiding this.\ngapmr := gap.Range().Intersect(mr)\nsrc := srcs.TakeFirst64(gapmr.Length())\nn, err := rw.c.backingFile.WriteFromBlocksAt(rw.ctx, src, gapmr.Start)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/pgalloc/pgalloc.go",
"new_path": "pkg/sentry/pgalloc/pgalloc.go",
"diff": "@@ -285,7 +285,10 @@ func NewMemoryFile(file *os.File, opts MemoryFileOpts) (*MemoryFile, error) {\nswitch opts.DelayedEviction {\ncase DelayedEvictionDefault:\nopts.DelayedEviction = DelayedEvictionEnabled\n- case DelayedEvictionDisabled, DelayedEvictionEnabled, DelayedEvictionManual:\n+ case DelayedEvictionDisabled, DelayedEvictionManual:\n+ opts.UseHostMemcgPressure = false\n+ case DelayedEvictionEnabled:\n+ // ok\ndefault:\nreturn nil, fmt.Errorf(\"invalid MemoryFileOpts.DelayedEviction: %v\", opts.DelayedEviction)\n}\n@@ -777,6 +780,14 @@ func (f *MemoryFile) MarkAllUnevictable(user EvictableMemoryUser) {\n}\n}\n+// ShouldCacheEvictable returns true if f is meaningfully delaying evictions of\n+// evictable memory, such that it may be advantageous to cache data in\n+// evictable memory. The value returned by ShouldCacheEvictable may change\n+// between calls.\n+func (f *MemoryFile) ShouldCacheEvictable() bool {\n+ return f.opts.DelayedEviction == DelayedEvictionManual || f.opts.UseHostMemcgPressure\n+}\n+\n// UpdateUsage ensures that the memory usage statistics in\n// usage.MemoryAccounting are up to date.\nfunc (f *MemoryFile) UpdateUsage() error {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Cache pages in CachingInodeOperations.Read when memory evictions are delayed.
PiperOrigin-RevId: 260851452 |
259,904 | 31.07.2019 11:25:25 | 25,200 | 12c4eb294a43f4a84a789871730869d164ef52c9 | Fix ICMPv4 EchoReply packet checksum
The checksum was not being reset before being re-calculated and sent out.
This caused the sent checksum to always be `0x0800`.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/icmp.go",
"new_path": "pkg/tcpip/network/ipv4/icmp.go",
"diff": "@@ -94,6 +94,7 @@ func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, vv buffer.V\npkt := header.ICMPv4(hdr.Prepend(header.ICMPv4MinimumSize))\ncopy(pkt, h)\npkt.SetType(header.ICMPv4EchoReply)\n+ pkt.SetChecksum(0)\npkt.SetChecksum(^header.Checksum(pkt, header.ChecksumVV(vv, 0)))\nsent := stats.ICMP.V4PacketsSent\nif err := r.WritePacket(nil /* gso */, hdr, vv, header.ICMPv4ProtocolNumber, r.DefaultTTL()); err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/raw_socket_icmp.cc",
"new_path": "test/syscalls/linux/raw_socket_icmp.cc",
"diff": "@@ -470,9 +470,8 @@ void RawSocketICMPTest::ExpectICMPSuccess(const struct icmphdr& icmp) {\nEXPECT_EQ(recvd_icmp->un.echo.id, icmp.un.echo.id);\n// A couple are different.\nEXPECT_EQ(recvd_icmp->type, ICMP_ECHOREPLY);\n- // The checksum is computed in such a way that it is guaranteed to have\n- // changed.\n- EXPECT_NE(recvd_icmp->checksum, icmp.checksum);\n+ // The checksum computed over the reply should still be valid.\n+ EXPECT_EQ(Checksum(recvd_icmp), 0);\nbreak;\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix ICMPv4 EchoReply packet checksum
The checksum was not being reset before being re-calculated and sent out.
This caused the sent checksum to always be `0x0800`.
Fixes #605.
PiperOrigin-RevId: 260965059 |
259,884 | 31.07.2019 20:29:07 | 25,200 | 0a246fab80581351309cdfe39ffeeffa00f811b1 | Basic support for 'ip route'
Implements support for RTM_GETROUTE requests for netlink sockets.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/netlink_route.go",
"new_path": "pkg/abi/linux/netlink_route.go",
"diff": "@@ -189,3 +189,139 @@ const (\nconst (\nARPHRD_LOOPBACK = 772\n)\n+\n+// RouteMessage struct rtmsg, from uapi/linux/rtnetlink.h.\n+type RouteMessage struct {\n+ Family uint8\n+ DstLen uint8\n+ SrcLen uint8\n+ TOS uint8\n+\n+ Table uint8\n+ Protocol uint8\n+ Scope uint8\n+ Type uint8\n+\n+ Flags uint32\n+}\n+\n+// Route types, from uapi/linux/rtnetlink.h.\n+const (\n+ // RTN_UNSPEC represents an unspecified route type.\n+ RTN_UNSPEC = 0\n+\n+ // RTN_UNICAST represents a unicast route.\n+ RTN_UNICAST = 1\n+\n+ // RTN_LOCAL represents a route that is accepted locally.\n+ RTN_LOCAL = 2\n+\n+ // RTN_BROADCAST represents a broadcast route (Traffic is accepted locally\n+ // as broadcast, and sent as broadcast).\n+ RTN_BROADCAST = 3\n+\n+ // RTN_ANYCAST represents a anycast route (Traffic is accepted locally as\n+ // broadcast but sent as unicast).\n+ RTN_ANYCAST = 6\n+\n+ // RTN_MULTICAST represents a multicast route.\n+ RTN_MULTICAST = 5\n+\n+ // RTN_BLACKHOLE represents a route where all traffic is dropped.\n+ RTN_BLACKHOLE = 6\n+\n+ // RTN_UNREACHABLE represents a route where the destination is unreachable.\n+ RTN_UNREACHABLE = 7\n+\n+ RTN_PROHIBIT = 8\n+ RTN_THROW = 9\n+ RTN_NAT = 10\n+ RTN_XRESOLVE = 11\n+)\n+\n+// Route protocols/origins, from uapi/linux/rtnetlink.h.\n+const (\n+ RTPROT_UNSPEC = 0\n+ RTPROT_REDIRECT = 1\n+ RTPROT_KERNEL = 2\n+ RTPROT_BOOT = 3\n+ RTPROT_STATIC = 4\n+ RTPROT_GATED = 8\n+ RTPROT_RA = 9\n+ RTPROT_MRT = 10\n+ RTPROT_ZEBRA = 11\n+ RTPROT_BIRD = 12\n+ RTPROT_DNROUTED = 13\n+ RTPROT_XORP = 14\n+ RTPROT_NTK = 15\n+ RTPROT_DHCP = 16\n+ RTPROT_MROUTED = 17\n+ RTPROT_BABEL = 42\n+ RTPROT_BGP = 186\n+ RTPROT_ISIS = 187\n+ RTPROT_OSPF = 188\n+ RTPROT_RIP = 189\n+ RTPROT_EIGRP = 192\n+)\n+\n+// Route scopes, from uapi/linux/rtnetlink.h.\n+const (\n+ RT_SCOPE_UNIVERSE = 0\n+ RT_SCOPE_SITE = 200\n+ RT_SCOPE_LINK = 253\n+ RT_SCOPE_HOST = 254\n+ RT_SCOPE_NOWHERE = 255\n+)\n+\n+// Route flags, from uapi/linux/rtnetlink.h.\n+const (\n+ RTM_F_NOTIFY = 0x100\n+ RTM_F_CLONED = 0x200\n+ RTM_F_EQUALIZE = 0x400\n+ RTM_F_PREFIX = 0x800\n+ RTM_F_LOOKUP_TABLE = 0x1000\n+ RTM_F_FIB_MATCH = 0x2000\n+)\n+\n+// Route tables, from uapi/linux/rtnetlink.h.\n+const (\n+ RT_TABLE_UNSPEC = 0\n+ RT_TABLE_COMPAT = 252\n+ RT_TABLE_DEFAULT = 253\n+ RT_TABLE_MAIN = 254\n+ RT_TABLE_LOCAL = 255\n+)\n+\n+// Route attributes, from uapi/linux/rtnetlink.h.\n+const (\n+ RTA_UNSPEC = 0\n+ RTA_DST = 1\n+ RTA_SRC = 2\n+ RTA_IIF = 3\n+ RTA_OIF = 4\n+ RTA_GATEWAY = 5\n+ RTA_PRIORITY = 6\n+ RTA_PREFSRC = 7\n+ RTA_METRICS = 8\n+ RTA_MULTIPATH = 9\n+ RTA_PROTOINFO = 10\n+ RTA_FLOW = 11\n+ RTA_CACHEINFO = 12\n+ RTA_SESSION = 13\n+ RTA_MP_ALGO = 14\n+ RTA_TABLE = 15\n+ RTA_MARK = 16\n+ RTA_MFC_STATS = 17\n+ RTA_VIA = 18\n+ RTA_NEWDST = 19\n+ RTA_PREF = 20\n+ RTA_ENCAP_TYPE = 21\n+ RTA_ENCAP = 22\n+ RTA_EXPIRES = 23\n+ RTA_PAD = 24\n+ RTA_UID = 25\n+ RTA_TTL_PROPAGATE = 26\n+ RTA_IP_PROTO = 27\n+ RTA_SPORT = 28\n+ RTA_DPORT = 29\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/inet/inet.go",
"new_path": "pkg/sentry/inet/inet.go",
"diff": "@@ -52,12 +52,13 @@ type Stack interface {\n// Statistics reports stack statistics.\nStatistics(stat interface{}, arg string) error\n+\n+ // RouteTable returns the network stack's route table.\n+ RouteTable() []Route\n}\n// Interface contains information about a network interface.\ntype Interface struct {\n- // Keep these fields sorted in the order they appear in rtnetlink(7).\n-\n// DeviceType is the device type, a Linux ARPHRD_* constant.\nDeviceType uint16\n@@ -77,8 +78,6 @@ type Interface struct {\n// InterfaceAddr contains information about a network interface address.\ntype InterfaceAddr struct {\n- // Keep these fields sorted in the order they appear in rtnetlink(7).\n-\n// Family is the address family, a Linux AF_* constant.\nFamily uint8\n@@ -109,3 +108,45 @@ type TCPBufferSize struct {\n// StatDev describes one line of /proc/net/dev, i.e., stats for one network\n// interface.\ntype StatDev [16]uint64\n+\n+// Route contains information about a network route.\n+type Route struct {\n+ // Family is the address family, a Linux AF_* constant.\n+ Family uint8\n+\n+ // DstLen is the length of the destination address.\n+ DstLen uint8\n+\n+ // SrcLen is the length of the source address.\n+ SrcLen uint8\n+\n+ // TOS is the Type of Service filter.\n+ TOS uint8\n+\n+ // Table is the routing table ID.\n+ Table uint8\n+\n+ // Protocol is the route origin, a Linux RTPROT_* constant.\n+ Protocol uint8\n+\n+ // Scope is the distance to destination, a Linux RT_SCOPE_* constant.\n+ Scope uint8\n+\n+ // Type is the route origin, a Linux RTN_* constant.\n+ Type uint8\n+\n+ // Flags are route flags. See rtnetlink(7) under \"rtm_flags\".\n+ Flags uint32\n+\n+ // DstAddr is the route destination address (RTA_DST).\n+ DstAddr []byte\n+\n+ // SrcAddr is the route source address (RTA_SRC).\n+ SrcAddr []byte\n+\n+ // OutputInterface is the output interface index (RTA_OIF).\n+ OutputInterface int32\n+\n+ // GatewayAddr is the route gateway address (RTA_GATEWAY).\n+ GatewayAddr []byte\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/inet/test_stack.go",
"new_path": "pkg/sentry/inet/test_stack.go",
"diff": "@@ -18,6 +18,7 @@ package inet\ntype TestStack struct {\nInterfacesMap map[int32]Interface\nInterfaceAddrsMap map[int32][]InterfaceAddr\n+ RouteList []Route\nSupportsIPv6Flag bool\nTCPRecvBufSize TCPBufferSize\nTCPSendBufSize TCPBufferSize\n@@ -86,3 +87,8 @@ func (s *TestStack) SetTCPSACKEnabled(enabled bool) error {\nfunc (s *TestStack) Statistics(stat interface{}, arg string) error {\nreturn nil\n}\n+\n+// RouteTable implements Stack.RouteTable.\n+func (s *TestStack) RouteTable() []Route {\n+ return s.RouteList\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/epsocket/epsocket.go",
"new_path": "pkg/sentry/socket/epsocket/epsocket.go",
"diff": "@@ -2252,19 +2252,19 @@ func interfaceIoctl(ctx context.Context, io usermem.IO, arg int, ifr *linux.IFRe\ncase syscall.SIOCGIFMAP:\n// Gets the hardware parameters of the device.\n- // TODO(b/71872867): Implement.\n+ // TODO(gvisor.dev/issue/505): Implement.\ncase syscall.SIOCGIFTXQLEN:\n// Gets the transmit queue length of the device.\n- // TODO(b/71872867): Implement.\n+ // TODO(gvisor.dev/issue/505): Implement.\ncase syscall.SIOCGIFDSTADDR:\n// Gets the destination address of a point-to-point device.\n- // TODO(b/71872867): Implement.\n+ // TODO(gvisor.dev/issue/505): Implement.\ncase syscall.SIOCGIFBRDADDR:\n// Gets the broadcast address of a device.\n- // TODO(b/71872867): Implement.\n+ // TODO(gvisor.dev/issue/505): Implement.\ncase syscall.SIOCGIFNETMASK:\n// Gets the network mask of a device.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/epsocket/stack.go",
"new_path": "pkg/sentry/socket/epsocket/stack.go",
"diff": "@@ -19,6 +19,8 @@ import (\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/inet\"\n\"gvisor.dev/gvisor/pkg/syserr\"\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv4\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv6\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n@@ -143,3 +145,46 @@ func (s *Stack) SetTCPSACKEnabled(enabled bool) error {\nfunc (s *Stack) Statistics(stat interface{}, arg string) error {\nreturn syserr.ErrEndpointOperation.ToError()\n}\n+\n+// RouteTable implements inet.Stack.RouteTable.\n+func (s *Stack) RouteTable() []inet.Route {\n+ var routeTable []inet.Route\n+\n+ for _, rt := range s.Stack.GetRouteTable() {\n+ var family uint8\n+ switch len(rt.Destination) {\n+ case header.IPv4AddressSize:\n+ family = linux.AF_INET\n+ case header.IPv6AddressSize:\n+ family = linux.AF_INET6\n+ default:\n+ log.Warningf(\"Unknown network protocol in route %+v\", rt)\n+ continue\n+ }\n+\n+ dstSubnet, err := tcpip.NewSubnet(rt.Destination, rt.Mask)\n+ if err != nil {\n+ log.Warningf(\"Invalid destination & mask in route: %s(%s): %v\", rt.Destination, rt.Mask, err)\n+ continue\n+ }\n+ routeTable = append(routeTable, inet.Route{\n+ Family: family,\n+ DstLen: uint8(dstSubnet.Prefix()), // The CIDR prefix for the destination.\n+\n+ // Always return unspecified protocol since we have no notion of\n+ // protocol for routes.\n+ Protocol: linux.RTPROT_UNSPEC,\n+ // Set statically to LINK scope for now.\n+ //\n+ // TODO(gvisor.dev/issue/595): Set scope for routes.\n+ Scope: linux.RT_SCOPE_LINK,\n+ Type: linux.RTN_UNICAST,\n+\n+ DstAddr: []byte(rt.Destination),\n+ OutputInterface: int32(rt.NIC),\n+ GatewayAddr: []byte(rt.Gateway),\n+ })\n+ }\n+\n+ return routeTable\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/hostinet/stack.go",
"new_path": "pkg/sentry/socket/hostinet/stack.go",
"diff": "@@ -46,6 +46,7 @@ type Stack struct {\n// Stack is immutable.\ninterfaces map[int32]inet.Interface\ninterfaceAddrs map[int32][]inet.InterfaceAddr\n+ routes []inet.Route\nsupportsIPv6 bool\ntcpRecvBufSize inet.TCPBufferSize\ntcpSendBufSize inet.TCPBufferSize\n@@ -66,6 +67,10 @@ func (s *Stack) Configure() error {\nreturn err\n}\n+ if err := addHostRoutes(s); err != nil {\n+ return err\n+ }\n+\nif _, err := os.Stat(\"/proc/net/if_inet6\"); err == nil {\ns.supportsIPv6 = true\n}\n@@ -161,6 +166,54 @@ func ExtractHostInterfaces(links []syscall.NetlinkMessage, addrs []syscall.Netli\nreturn nil\n}\n+// ExtractHostRoutes populates the given routes slice with the data from the\n+// host route table.\n+func ExtractHostRoutes(routeMsgs []syscall.NetlinkMessage) ([]inet.Route, error) {\n+ var routes []inet.Route\n+ for _, routeMsg := range routeMsgs {\n+ if routeMsg.Header.Type != syscall.RTM_NEWROUTE {\n+ continue\n+ }\n+\n+ var ifRoute syscall.RtMsg\n+ binary.Unmarshal(routeMsg.Data[:syscall.SizeofRtMsg], usermem.ByteOrder, &ifRoute)\n+ inetRoute := inet.Route{\n+ Family: ifRoute.Family,\n+ DstLen: ifRoute.Dst_len,\n+ SrcLen: ifRoute.Src_len,\n+ TOS: ifRoute.Tos,\n+ Table: ifRoute.Table,\n+ Protocol: ifRoute.Protocol,\n+ Scope: ifRoute.Scope,\n+ Type: ifRoute.Type,\n+ Flags: ifRoute.Flags,\n+ }\n+\n+ // Not clearly documented: syscall.ParseNetlinkRouteAttr will check the\n+ // syscall.NetlinkMessage.Header.Type and skip the struct rtmsg\n+ // accordingly.\n+ attrs, err := syscall.ParseNetlinkRouteAttr(&routeMsg)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"RTM_GETROUTE returned RTM_NEWROUTE message with invalid rtattrs: %v\", err)\n+ }\n+\n+ for _, attr := range attrs {\n+ switch attr.Attr.Type {\n+ case syscall.RTA_DST:\n+ inetRoute.DstAddr = attr.Value\n+ case syscall.RTA_SRC:\n+ inetRoute.SrcAddr = attr.Value\n+ case syscall.RTA_OIF:\n+ inetRoute.GatewayAddr = attr.Value\n+ }\n+ }\n+\n+ routes = append(routes, inetRoute)\n+ }\n+\n+ return routes, nil\n+}\n+\nfunc addHostInterfaces(s *Stack) error {\nlinks, err := doNetlinkRouteRequest(syscall.RTM_GETLINK)\nif err != nil {\n@@ -175,6 +228,20 @@ func addHostInterfaces(s *Stack) error {\nreturn ExtractHostInterfaces(links, addrs, s.interfaces, s.interfaceAddrs)\n}\n+func addHostRoutes(s *Stack) error {\n+ routes, err := doNetlinkRouteRequest(syscall.RTM_GETROUTE)\n+ if err != nil {\n+ return fmt.Errorf(\"RTM_GETROUTE failed: %v\", err)\n+ }\n+\n+ s.routes, err = ExtractHostRoutes(routes)\n+ if err != nil {\n+ return err\n+ }\n+\n+ return nil\n+}\n+\nfunc doNetlinkRouteRequest(req int) ([]syscall.NetlinkMessage, error) {\ndata, err := syscall.NetlinkRIB(req, syscall.AF_UNSPEC)\nif err != nil {\n@@ -202,12 +269,20 @@ func readTCPBufferSizeFile(filename string) (inet.TCPBufferSize, error) {\n// Interfaces implements inet.Stack.Interfaces.\nfunc (s *Stack) Interfaces() map[int32]inet.Interface {\n- return s.interfaces\n+ interfaces := make(map[int32]inet.Interface)\n+ for k, v := range s.interfaces {\n+ interfaces[k] = v\n+ }\n+ return interfaces\n}\n// InterfaceAddrs implements inet.Stack.InterfaceAddrs.\nfunc (s *Stack) InterfaceAddrs() map[int32][]inet.InterfaceAddr {\n- return s.interfaceAddrs\n+ addrs := make(map[int32][]inet.InterfaceAddr)\n+ for k, v := range s.interfaceAddrs {\n+ addrs[k] = append([]inet.InterfaceAddr(nil), v...)\n+ }\n+ return addrs\n}\n// SupportsIPv6 implements inet.Stack.SupportsIPv6.\n@@ -249,3 +324,8 @@ func (s *Stack) SetTCPSACKEnabled(enabled bool) error {\nfunc (s *Stack) Statistics(stat interface{}, arg string) error {\nreturn syserror.EOPNOTSUPP\n}\n+\n+// RouteTable implements inet.Stack.RouteTable.\n+func (s *Stack) RouteTable() []inet.Route {\n+ return append([]inet.Route(nil), s.routes...)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netlink/route/protocol.go",
"new_path": "pkg/sentry/socket/netlink/route/protocol.go",
"diff": "@@ -110,7 +110,7 @@ func (p *Protocol) dumpLinks(ctx context.Context, hdr linux.NetlinkMessageHeader\nm.PutAttr(linux.IFLA_ADDRESS, mac)\nm.PutAttr(linux.IFLA_BROADCAST, brd)\n- // TODO(b/68878065): There are many more attributes.\n+ // TODO(gvisor.dev/issue/578): There are many more attributes.\n}\nreturn nil\n@@ -151,13 +151,69 @@ func (p *Protocol) dumpAddrs(ctx context.Context, hdr linux.NetlinkMessageHeader\nm.PutAttr(linux.IFA_ADDRESS, []byte(a.Addr))\n- // TODO(b/68878065): There are many more attributes.\n+ // TODO(gvisor.dev/issue/578): There are many more attributes.\n}\n}\nreturn nil\n}\n+// dumpRoutes handles RTM_GETROUTE + NLM_F_DUMP requests.\n+func (p *Protocol) dumpRoutes(ctx context.Context, hdr linux.NetlinkMessageHeader, data []byte, ms *netlink.MessageSet) *syserr.Error {\n+ // RTM_GETROUTE dump requests need not contain anything more than the\n+ // netlink header and 1 byte protocol family common to all\n+ // NETLINK_ROUTE requests.\n+\n+ // We always send back an NLMSG_DONE.\n+ ms.Multi = true\n+\n+ stack := inet.StackFromContext(ctx)\n+ if stack == nil {\n+ // No network routes.\n+ return nil\n+ }\n+\n+ for _, rt := range stack.RouteTable() {\n+ m := ms.AddMessage(linux.NetlinkMessageHeader{\n+ Type: linux.RTM_NEWROUTE,\n+ })\n+\n+ m.Put(linux.RouteMessage{\n+ Family: rt.Family,\n+ DstLen: rt.DstLen,\n+ SrcLen: rt.SrcLen,\n+ TOS: rt.TOS,\n+\n+ // Always return the main table since we don't have multiple\n+ // routing tables.\n+ Table: linux.RT_TABLE_MAIN,\n+ Protocol: rt.Protocol,\n+ Scope: rt.Scope,\n+ Type: rt.Type,\n+\n+ Flags: rt.Flags,\n+ })\n+\n+ m.PutAttr(254, []byte{123})\n+ if rt.DstLen > 0 {\n+ m.PutAttr(linux.RTA_DST, rt.DstAddr)\n+ }\n+ if rt.SrcLen > 0 {\n+ m.PutAttr(linux.RTA_SRC, rt.SrcAddr)\n+ }\n+ if rt.OutputInterface != 0 {\n+ m.PutAttr(linux.RTA_OIF, rt.OutputInterface)\n+ }\n+ if len(rt.GatewayAddr) > 0 {\n+ m.PutAttr(linux.RTA_GATEWAY, rt.GatewayAddr)\n+ }\n+\n+ // TODO(gvisor.dev/issue/578): There are many more attributes.\n+ }\n+\n+ return nil\n+}\n+\n// ProcessMessage implements netlink.Protocol.ProcessMessage.\nfunc (p *Protocol) ProcessMessage(ctx context.Context, hdr linux.NetlinkMessageHeader, data []byte, ms *netlink.MessageSet) *syserr.Error {\n// All messages start with a 1 byte protocol family.\n@@ -186,6 +242,8 @@ func (p *Protocol) ProcessMessage(ctx context.Context, hdr linux.NetlinkMessageH\nreturn p.dumpLinks(ctx, hdr, data, ms)\ncase linux.RTM_GETADDR:\nreturn p.dumpAddrs(ctx, hdr, data, ms)\n+ case linux.RTM_GETROUTE:\n+ return p.dumpRoutes(ctx, hdr, data, ms)\ndefault:\nreturn syserr.ErrNotSupported\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/rpcinet/stack.go",
"new_path": "pkg/sentry/socket/rpcinet/stack.go",
"diff": "@@ -30,6 +30,7 @@ import (\ntype Stack struct {\ninterfaces map[int32]inet.Interface\ninterfaceAddrs map[int32][]inet.InterfaceAddr\n+ routes []inet.Route\nrpcConn *conn.RPCConnection\nnotifier *notifier.Notifier\n}\n@@ -69,6 +70,16 @@ func NewStack(fd int32) (*Stack, error) {\nreturn nil, e\n}\n+ routes, err := stack.DoNetlinkRouteRequest(syscall.RTM_GETROUTE)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"RTM_GETROUTE failed: %v\", err)\n+ }\n+\n+ stack.routes, e = hostinet.ExtractHostRoutes(routes)\n+ if e != nil {\n+ return nil, e\n+ }\n+\nreturn stack, nil\n}\n@@ -89,12 +100,20 @@ func (s *Stack) RPCWriteFile(path string, data []byte) (int64, *syserr.Error) {\n// Interfaces implements inet.Stack.Interfaces.\nfunc (s *Stack) Interfaces() map[int32]inet.Interface {\n- return s.interfaces\n+ interfaces := make(map[int32]inet.Interface)\n+ for k, v := range s.interfaces {\n+ interfaces[k] = v\n+ }\n+ return interfaces\n}\n// InterfaceAddrs implements inet.Stack.InterfaceAddrs.\nfunc (s *Stack) InterfaceAddrs() map[int32][]inet.InterfaceAddr {\n- return s.interfaceAddrs\n+ addrs := make(map[int32][]inet.InterfaceAddr)\n+ for k, v := range s.interfaceAddrs {\n+ addrs[k] = append([]inet.InterfaceAddr(nil), v...)\n+ }\n+ return addrs\n}\n// SupportsIPv6 implements inet.Stack.SupportsIPv6.\n@@ -138,3 +157,8 @@ func (s *Stack) SetTCPSACKEnabled(enabled bool) error {\nfunc (s *Stack) Statistics(stat interface{}, arg string) error {\nreturn syserr.ErrEndpointOperation.ToError()\n}\n+\n+// RouteTable implements inet.Stack.RouteTable.\n+func (s *Stack) RouteTable() []inet.Route {\n+ return append([]inet.Route(nil), s.routes...)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_netlink_route.cc",
"new_path": "test/syscalls/linux/socket_netlink_route.cc",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n+#include <arpa/inet.h>\n#include <ifaddrs.h>\n#include <linux/netlink.h>\n#include <linux/rtnetlink.h>\n@@ -425,6 +426,78 @@ TEST(NetlinkRouteTest, LookupAll) {\nASSERT_GT(count, 0);\n}\n+// GetRouteDump tests a RTM_GETROUTE + NLM_F_DUMP request.\n+TEST(NetlinkRouteTest, GetRouteDump) {\n+ FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(NetlinkBoundSocket());\n+ uint32_t port = ASSERT_NO_ERRNO_AND_VALUE(NetlinkPortID(fd.get()));\n+\n+ struct request {\n+ struct nlmsghdr hdr;\n+ struct rtmsg rtm;\n+ };\n+\n+ constexpr uint32_t kSeq = 12345;\n+\n+ struct request req = {};\n+ req.hdr.nlmsg_len = sizeof(req);\n+ req.hdr.nlmsg_type = RTM_GETROUTE;\n+ req.hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;\n+ req.hdr.nlmsg_seq = kSeq;\n+ req.rtm.rtm_family = AF_UNSPEC;\n+\n+ bool routeFound = false;\n+ bool dstFound = true;\n+ ASSERT_NO_ERRNO(NetlinkRequestResponse(\n+ fd, &req, sizeof(req), [&](const struct nlmsghdr* hdr) {\n+ // Validate the reponse to RTM_GETROUTE + NLM_F_DUMP.\n+ EXPECT_THAT(hdr->nlmsg_type, AnyOf(Eq(RTM_NEWROUTE), Eq(NLMSG_DONE)));\n+\n+ EXPECT_TRUE((hdr->nlmsg_flags & NLM_F_MULTI) == NLM_F_MULTI)\n+ << std::hex << hdr->nlmsg_flags;\n+\n+ EXPECT_EQ(hdr->nlmsg_seq, kSeq);\n+ EXPECT_EQ(hdr->nlmsg_pid, port);\n+\n+ // The test should not proceed if it's not a RTM_NEWROUTE message.\n+ if (hdr->nlmsg_type != RTM_NEWROUTE) {\n+ return;\n+ }\n+\n+ // RTM_NEWROUTE contains at least the header and rtmsg.\n+ ASSERT_GE(hdr->nlmsg_len, NLMSG_SPACE(sizeof(struct rtmsg)));\n+ const struct rtmsg* msg =\n+ reinterpret_cast<const struct rtmsg*>(NLMSG_DATA(hdr));\n+ // NOTE: rtmsg fields are char fields.\n+ std::cout << \"Found route table=\" << static_cast<int>(msg->rtm_table)\n+ << \", protocol=\" << static_cast<int>(msg->rtm_protocol)\n+ << \", scope=\" << static_cast<int>(msg->rtm_scope)\n+ << \", type=\" << static_cast<int>(msg->rtm_type);\n+\n+ int len = RTM_PAYLOAD(hdr);\n+ bool rtDstFound = false;\n+ for (struct rtattr* attr = RTM_RTA(msg); RTA_OK(attr, len);\n+ attr = RTA_NEXT(attr, len)) {\n+ if (attr->rta_type == RTA_DST) {\n+ char address[INET_ADDRSTRLEN] = {};\n+ inet_ntop(AF_INET, RTA_DATA(attr), address, sizeof(address));\n+ std::cout << \", dst=\" << address;\n+ rtDstFound = true;\n+ }\n+ }\n+\n+ std::cout << std::endl;\n+\n+ if (msg->rtm_table == RT_TABLE_MAIN) {\n+ routeFound = true;\n+ dstFound = rtDstFound && dstFound;\n+ }\n+ }));\n+ // At least one route found in main route table.\n+ EXPECT_TRUE(routeFound);\n+ // Found RTA_DST for each route in main table.\n+ EXPECT_TRUE(dstFound);\n+}\n+\n} // namespace\n} // namespace testing\n"
}
] | Go | Apache License 2.0 | google/gvisor | Basic support for 'ip route'
Implements support for RTM_GETROUTE requests for netlink sockets.
Fixes #507
PiperOrigin-RevId: 261051045 |
259,985 | 01.08.2019 13:57:41 | 25,200 | 79511e8a50facd509b8180d0160762b510dd6196 | Implement getsockopt(TCP_INFO).
Export some readily-available fields for TCP_INFO and stub out the rest. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/epsocket/epsocket.go",
"new_path": "pkg/sentry/socket/epsocket/epsocket.go",
"diff": "@@ -845,6 +845,68 @@ func getSockOptSocket(t *kernel.Task, s socket.Socket, ep commonEndpoint, family\nreturn nil, syserr.ErrProtocolNotAvailable\n}\n+func toLinuxTCPInfo(i tcp.InfoOption) linux.TCPInfo {\n+ // Unimplemented fields are explicitly initialized to zero below.\n+ return linux.TCPInfo{\n+ State: uint8(translateTCPState(tcp.EndpointState(i.ProtocolState))),\n+ CaState: 0,\n+ Retransmits: 0,\n+ Probes: 0,\n+ Backoff: 0,\n+ Options: 0,\n+ WindowScale: uint8((i.Sender.SndWndScale&0xf)<<4 | (i.Receiver.RcvWndScale & 0xf)),\n+ DeliveryRateAppLimited: 0,\n+\n+ RTO: uint32(i.Sender.RTO / time.Microsecond),\n+ ATO: 0,\n+ SndMss: uint32(i.Sender.MSS),\n+ RcvMss: uint32(i.RcvMSS),\n+\n+ Unacked: uint32(i.Sender.Outstanding),\n+ Sacked: uint32(i.SACK.Sacked),\n+ Lost: 0,\n+ Retrans: 0,\n+ Fackets: 0,\n+\n+ LastDataSent: uint32(i.Sender.LastSendTime.UnixNano() / int64(time.Millisecond)),\n+ LastAckSent: 0, // Not tracked by Linux.\n+ LastDataRecv: uint32(i.RcvLastDataNanos / int64(time.Millisecond)),\n+ LastAckRecv: uint32(i.RcvLastAckNanos / int64(time.Millisecond)),\n+\n+ PMTU: uint32(i.SndMTU),\n+ RcvSsthresh: 0,\n+ RTT: uint32(i.Sender.SRTT / time.Microsecond),\n+ RTTVar: uint32(i.Sender.RTTVar / time.Microsecond),\n+ SndSsthresh: uint32(i.Sender.Ssthresh),\n+ SndCwnd: uint32(i.Sender.SndCwnd),\n+ Advmss: uint32(i.AMSS),\n+ Reordering: 0,\n+\n+ RcvRTT: uint32(i.RcvAutoParams.RTT / time.Microsecond),\n+ RcvSpace: uint32(i.RcvBufSize),\n+\n+ TotalRetrans: 0,\n+\n+ PacingRate: 0,\n+ MaxPacingRate: 0,\n+ BytesAcked: 0,\n+ BytesReceived: 0,\n+ SegsOut: 0,\n+ SegsIn: 0,\n+\n+ NotSentBytes: 0,\n+ MinRTT: uint32(i.RcvAutoParams.RTT / time.Microsecond),\n+ DataSegsIn: 0,\n+ DataSegsOut: 0,\n+\n+ DeliveryRate: 0,\n+\n+ BusyTime: 0,\n+ RwndLimited: 0,\n+ SndBufLimited: 0,\n+ }\n+}\n+\n// getSockOptTCP implements GetSockOpt when level is SOL_TCP.\nfunc getSockOptTCP(t *kernel.Task, ep commonEndpoint, name, outLen int) (interface{}, *syserr.Error) {\nswitch name {\n@@ -924,17 +986,14 @@ func getSockOptTCP(t *kernel.Task, ep commonEndpoint, name, outLen int) (interfa\nreturn int32(time.Duration(v) / time.Second), nil\ncase linux.TCP_INFO:\n- var v tcpip.TCPInfoOption\n+ var v tcp.InfoOption\nif err := ep.GetSockOpt(&v); err != nil {\nreturn nil, syserr.TranslateNetstackError(err)\n}\n-\n- // TODO(b/64800844): Translate fields once they are added to\n- // tcpip.TCPInfoOption.\n- info := linux.TCPInfo{}\n+ info := toLinuxTCPInfo(v)\n// Linux truncates the output binary to outLen.\n- ib := binary.Marshal(nil, usermem.ByteOrder, &info)\n+ ib := binary.Marshal(nil, usermem.ByteOrder, info)\nif len(ib) > outLen {\nib = ib[:outLen]\n}\n@@ -2375,17 +2434,10 @@ func nicStateFlagsToLinux(f stack.NICStateFlags) uint32 {\nreturn rv\n}\n-// State implements socket.Socket.State. State translates the internal state\n-// returned by netstack to values defined by Linux.\n-func (s *SocketOperations) State() uint32 {\n- if s.family != linux.AF_INET && s.family != linux.AF_INET6 {\n- // States not implemented for this socket's family.\n- return 0\n- }\n-\n- if !s.isPacketBased() {\n- // TCP socket.\n- switch tcp.EndpointState(s.Endpoint.State()) {\n+// translateTCPState translates an internal endpoint state to the equivalent\n+// state in the Linux ABI.\n+func translateTCPState(s tcp.EndpointState) uint32 {\n+ switch s {\ncase tcp.StateEstablished:\nreturn linux.TCP_ESTABLISHED\ncase tcp.StateSynSent:\n@@ -2414,6 +2466,19 @@ func (s *SocketOperations) State() uint32 {\n}\n}\n+// State implements socket.Socket.State. State translates the internal state\n+// returned by netstack to values defined by Linux.\n+func (s *SocketOperations) State() uint32 {\n+ if s.family != linux.AF_INET && s.family != linux.AF_INET6 {\n+ // States not implemented for this socket's family.\n+ return 0\n+ }\n+\n+ if !s.isPacketBased() {\n+ // TCP socket.\n+ return translateTCPState(tcp.EndpointState(s.Endpoint.State()))\n+ }\n+\n// TODO(b/112063468): Export states for UDP, ICMP, and raw sockets.\nreturn 0\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -208,6 +208,10 @@ type TCPSenderState struct {\n// Cubic holds the state related to CUBIC congestion control.\nCubic TCPCubicState\n+\n+ // MSS is the size of the largest segment that can be sent without\n+ // fragmentation.\n+ MSS int\n}\n// TCPSACKInfo holds TCP SACK related information for a given TCP endpoint.\n@@ -220,6 +224,9 @@ type TCPSACKInfo struct {\n// from the peer endpoint.\nReceivedBlocks []header.SACKBlock\n+ // Sacked is the current number of bytes held in the SACK scoreboard.\n+ Sacked seqnum.Size\n+\n// MaxSACKED is the highest sequence number that has been SACKED\n// by the peer.\nMaxSACKED seqnum.Value\n@@ -269,6 +276,14 @@ type TCPEndpointState struct {\n// ID is a copy of the TransportEndpointID for the endpoint.\nID TCPEndpointID\n+ // ProtocolState denotes the TCP state the endpoint is currently\n+ // in, encoded in a netstack-specific manner. Should be translated\n+ // to the Linux ABI before exposing to userspace.\n+ ProtocolState uint32\n+\n+ // AMSS is the MSS advertised to the peer by this endpoint.\n+ AMSS uint16\n+\n// SegTime denotes the absolute time when this segment was received.\nSegTime time.Time\n@@ -286,6 +301,18 @@ type TCPEndpointState struct {\n// RcvClosed if true, indicates the endpoint has been closed for reading.\nRcvClosed bool\n+ // RcvLastAck is the time of receipt of the last packet with the\n+ // ACK flag set.\n+ RcvLastAckNanos int64\n+\n+ // RcvLastData is the time of reciept of the last packet\n+ // containing data.\n+ RcvLastDataNanos int64\n+\n+ // RcvMSS is the size of the largest segment the receiver is willing to\n+ // accept, not including TCP headers and options.\n+ RcvMSS int\n+\n// SendTSOk is used to indicate when the TS Option has been negotiated.\n// When sendTSOk is true every non-RST segment should carry a TS as per\n// RFC7323#section-1.1.\n@@ -326,6 +353,9 @@ type TCPEndpointState struct {\n// SndMTU is the smallest MTU seen in the control packets received.\nSndMTU int\n+ // MaxOptionSize is the maximum size of TCP options.\n+ MaxOptionSize int\n+\n// Receiver holds variables related to the TCP receiver for the endpoint.\nReceiver TCPReceiverState\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -476,14 +476,6 @@ type QuickAckOption int\n// Only supported on Unix sockets.\ntype PasscredOption int\n-// TCPInfoOption is used by GetSockOpt to expose TCP statistics.\n-//\n-// TODO(b/64800844): Add and populate stat fields.\n-type TCPInfoOption struct {\n- RTT time.Duration\n- RTTVar time.Duration\n-}\n-\n// KeepaliveEnabledOption is used by SetSockOpt/GetSockOpt to specify whether\n// TCP keepalive is enabled for this socket.\ntype KeepaliveEnabledOption int\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -108,6 +108,9 @@ func (s EndpointState) String() string {\n}\n}\n+// InfoOption is used by GetSockOpt to expose TCP endpoint state.\n+type InfoOption stack.TCPEndpointState\n+\n// Reasons for notifying the protocol goroutine.\nconst (\nnotifyNonZeroReceiveWindow = 1 << iota\n@@ -208,6 +211,8 @@ type endpoint struct {\nrcvBufSize int\nrcvBufUsed int\nrcvAutoParams rcvBufAutoTuneParams\n+ rcvLastAckNanos int64 // timestamp\n+ rcvLastDataNanos int64 // timestamp\n// zeroWindow indicates that the window was closed due to receive buffer\n// space being filled up. This is set by the worker goroutine before\n// moving a segment to the rcvList. This setting is cleared by the\n@@ -1198,17 +1203,10 @@ func (e *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {\n}\nreturn nil\n- case *tcpip.TCPInfoOption:\n- *o = tcpip.TCPInfoOption{}\n- e.mu.RLock()\n- snd := e.snd\n- e.mu.RUnlock()\n- if snd != nil {\n- snd.rtt.Lock()\n- o.RTT = snd.rtt.srtt\n- o.RTTVar = snd.rtt.rttvar\n- snd.rtt.Unlock()\n- }\n+ case *InfoOption:\n+ e.workMu.Lock()\n+ *o = InfoOption(e.completeState())\n+ e.workMu.Unlock()\nreturn nil\ncase *tcpip.KeepaliveEnabledOption:\n@@ -1933,22 +1931,27 @@ func (e *endpoint) maxOptionSize() (size int) {\n}\n// completeState makes a full copy of the endpoint and returns it. This is used\n-// before invoking the probe. The state returned may not be fully consistent if\n-// there are intervening syscalls when the state is being copied.\n+// before invoking the probe and for getsockopt(TCP_INFO). The state returned\n+// may not be fully consistent if there are intervening syscalls when the state\n+// is being copied.\nfunc (e *endpoint) completeState() stack.TCPEndpointState {\nvar s stack.TCPEndpointState\ns.SegTime = time.Now()\n- // Copy EndpointID.\n- e.mu.Lock()\n+ e.mu.RLock()\ns.ID = stack.TCPEndpointID(e.id)\n- e.mu.Unlock()\n+ s.ProtocolState = uint32(e.state)\n+ s.AMSS = e.amss\n+ s.RcvMSS = int(e.amss) - e.maxOptionSize()\n+ e.mu.RUnlock()\n// Copy endpoint rcv state.\ne.rcvListMu.Lock()\ns.RcvBufSize = e.rcvBufSize\ns.RcvBufUsed = e.rcvBufUsed\ns.RcvClosed = e.rcvClosed\n+ s.RcvLastAckNanos = e.rcvLastAckNanos\n+ s.RcvLastDataNanos = e.rcvLastDataNanos\ns.RcvAutoParams.MeasureTime = e.rcvAutoParams.measureTime\ns.RcvAutoParams.CopiedBytes = e.rcvAutoParams.copied\ns.RcvAutoParams.PrevCopiedBytes = e.rcvAutoParams.prevCopied\n@@ -1956,6 +1959,7 @@ func (e *endpoint) completeState() stack.TCPEndpointState {\ns.RcvAutoParams.RTTMeasureSeqNumber = e.rcvAutoParams.rttMeasureSeqNumber\ns.RcvAutoParams.RTTMeasureTime = e.rcvAutoParams.rttMeasureTime\ns.RcvAutoParams.Disabled = e.rcvAutoParams.disabled\n+\ne.rcvListMu.Unlock()\n// Endpoint TCP Option state.\n@@ -1965,7 +1969,7 @@ func (e *endpoint) completeState() stack.TCPEndpointState {\ns.SACKPermitted = e.sackPermitted\ns.SACK.Blocks = make([]header.SACKBlock, e.sack.NumBlocks)\ncopy(s.SACK.Blocks, e.sack.Blocks[:e.sack.NumBlocks])\n- s.SACK.ReceivedBlocks, s.SACK.MaxSACKED = e.scoreboard.Copy()\n+ s.SACK.ReceivedBlocks, s.SACK.Sacked, s.SACK.MaxSACKED = e.scoreboard.Copy()\n// Copy endpoint send state.\ne.sndBufMu.Lock()\n@@ -2009,12 +2013,14 @@ func (e *endpoint) completeState() stack.TCPEndpointState {\nRTTMeasureTime: e.snd.rttMeasureTime,\nClosed: e.snd.closed,\nRTO: e.snd.rto,\n+ MSS: e.snd.mss,\nMaxPayloadSize: e.snd.maxPayloadSize,\nSndWndScale: e.snd.sndWndScale,\nMaxSentAck: e.snd.maxSentAck,\n}\ne.snd.rtt.Lock()\ns.Sender.SRTT = e.snd.rtt.srtt\n+ s.Sender.RTTVar = e.snd.rtt.rttvar\ns.Sender.SRTTInited = e.snd.rtt.srttInited\ne.snd.rtt.Unlock()\n@@ -2059,8 +2065,8 @@ func (e *endpoint) initGSO() {\n// State implements tcpip.Endpoint.State. It exports the endpoint's protocol\n// state for diagnostics.\nfunc (e *endpoint) State() uint32 {\n- e.mu.Lock()\n- defer e.mu.Unlock()\n+ e.mu.RLock()\n+ defer e.mu.RUnlock()\nreturn uint32(e.state)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/rcv.go",
"new_path": "pkg/tcpip/transport/tcp/rcv.go",
"diff": "@@ -220,25 +220,24 @@ func (r *receiver) consumeSegment(s *segment, segSeq seqnum.Value, segLen seqnum\nreturn true\n}\n-// updateRTT updates the receiver RTT measurement based on the sequence number\n-// of the received segment.\n-func (r *receiver) updateRTT() {\n+// updateRTTLocked updates the receiver RTT measurement based on the sequence\n+// number of the received segment.\n+//\n+// Precondition: Caller must hold r.ep.rcvListMu.\n+func (r *receiver) updateRTTLocked() {\n// From: https://public.lanl.gov/radiant/pubs/drs/sc2001-poster.pdf\n//\n// A system that is only transmitting acknowledgements can still\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.rcvListMu.Lock()\nif r.ep.rcvAutoParams.rttMeasureTime.IsZero() {\n// New measurement.\nr.ep.rcvAutoParams.rttMeasureTime = time.Now()\nr.ep.rcvAutoParams.rttMeasureSeqNumber = r.rcvNxt.Add(r.rcvWnd)\n- r.ep.rcvListMu.Unlock()\nreturn\n}\nif r.rcvNxt.LessThan(r.ep.rcvAutoParams.rttMeasureSeqNumber) {\n- r.ep.rcvListMu.Unlock()\nreturn\n}\nrtt := time.Since(r.ep.rcvAutoParams.rttMeasureTime)\n@@ -250,7 +249,6 @@ func (r *receiver) updateRTT() {\n}\nr.ep.rcvAutoParams.rttMeasureTime = time.Now()\nr.ep.rcvAutoParams.rttMeasureSeqNumber = r.rcvNxt.Add(r.rcvWnd)\n- r.ep.rcvListMu.Unlock()\n}\n// handleRcvdSegment handles TCP segments directed at the connection managed by\n@@ -291,11 +289,20 @@ func (r *receiver) handleRcvdSegment(s *segment) {\nreturn\n}\n- // Since we consumed a segment update the receiver's RTT estimate\n- // if required.\n+ r.ep.rcvListMu.Lock()\n+ // FIXME(b/137581805): Using the runtime clock here is incorrect as it\n+ // doesn't account for potentially virtualized time.\n+ now := time.Now().UnixNano()\n+ if s.flagIsSet(header.TCPFlagAck) {\n+ r.ep.rcvLastAckNanos = now\n+ }\nif segLen > 0 {\n- r.updateRTT()\n+ // Since we consumed a segment update the receiver's RTT estimate if\n+ // required.\n+ r.ep.rcvLastDataNanos = now\n+ r.updateRTTLocked()\n}\n+ r.ep.rcvListMu.Unlock()\n// By consuming the current segment, we may have filled a gap in the\n// sequence number domain that allows pending segments to be consumed\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/sack_scoreboard.go",
"new_path": "pkg/tcpip/transport/tcp/sack_scoreboard.go",
"diff": "@@ -208,12 +208,12 @@ func (s *SACKScoreboard) Delete(seq seqnum.Value) {\n}\n// Copy provides a copy of the SACK scoreboard.\n-func (s *SACKScoreboard) Copy() (sackBlocks []header.SACKBlock, maxSACKED seqnum.Value) {\n+func (s *SACKScoreboard) Copy() (sackBlocks []header.SACKBlock, sacked seqnum.Size, maxSACKED seqnum.Value) {\ns.ranges.Ascend(func(i btree.Item) bool {\nsackBlocks = append(sackBlocks, i.(header.SACKBlock))\nreturn true\n})\n- return sackBlocks, s.maxSACKED\n+ return sackBlocks, s.sacked, s.maxSACKED\n}\n// IsRangeLost implements the IsLost(SeqNum) operation defined in RFC 6675\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/snd.go",
"new_path": "pkg/tcpip/transport/tcp/snd.go",
"diff": "@@ -124,6 +124,10 @@ type sender struct {\nrtt rtt\nrto time.Duration\n+ // mss is the largest segment that can be sent without fragmentation.\n+ // Initialized when then sender is created, read-only afterwards.\n+ mss int\n+\n// maxPayloadSize is the maximum size of the payload of a given segment.\n// It is initialized on demand.\nmaxPayloadSize int\n@@ -201,6 +205,7 @@ func newSender(ep *endpoint, iss, irs seqnum.Value, sndWnd seqnum.Size, mss uint\nrto: 1 * time.Second,\nrttMeasureSeqNum: iss + 1,\nlastSendTime: time.Now(),\n+ mss: int(mss),\nmaxPayloadSize: maxPayloadSize,\nmaxSentAck: irs + 1,\nfr: fastRecovery{\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ip_tcp_generic.cc",
"new_path": "test/syscalls/linux/socket_ip_tcp_generic.cc",
"diff": "@@ -697,5 +697,28 @@ TEST_P(TCPSocketPairTest, SetCongestionControlFailsForUnsupported) {\nEXPECT_EQ(0, memcmp(got_cc, old_cc, sizeof(old_cc)));\n}\n+TEST_P(TCPSocketPairTest, GetSockOptTCPInfo) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+ struct tcp_info info;\n+ socklen_t optlen = sizeof(info);\n+ ASSERT_THAT(\n+ getsockopt(sockets->first_fd(), SOL_TCP, TCP_INFO, &info, &optlen),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(optlen, sizeof(info));\n+\n+ EXPECT_EQ(info.tcpi_state, TCP_ESTABLISHED);\n+\n+ EXPECT_GT(info.tcpi_rto, 0);\n+\n+ // IPv4 MSS is 536 bytes by default, and IPv6 is 1220 bytes.\n+ EXPECT_GE(info.tcpi_snd_mss, 536);\n+ EXPECT_GE(info.tcpi_rcv_mss, 536);\n+ EXPECT_GE(info.tcpi_advmss, 536);\n+\n+ // MTU is typically 1500 for ethernet, but this is highly protocol\n+ // dependent. Opt for a safe lower bound.\n+ EXPECT_GT(info.tcpi_pmtu, 500);\n+}\n+\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement getsockopt(TCP_INFO).
Export some readily-available fields for TCP_INFO and stub out the rest.
PiperOrigin-RevId: 261191548 |
259,884 | 01.08.2019 00:50:46 | 14,400 | 46ee8873ffca2468eecf813cb2163f1d31ce390f | Remove superfluous redirects | [
{
"change_type": "MODIFY",
"old_path": "content/_index.html",
"new_path": "content/_index.html",
"diff": "@@ -41,7 +41,7 @@ Read the [documentation](./docs/) to understand gVisor, its architecture and tra\n{{% /blocks/feature %}}\n{{% blocks/feature icon=\"fas fa-code-branch\" title=\"Contribute to gVisor\" %}}\n-Anyone is welcome to be a gVisor contributor. Please check out the [community information](./docs/community) to get started.\n+Anyone is welcome to be a gVisor contributor. Please check out the [community information](./docs/community/) to get started.\n{{% /blocks/feature %}}\n{{% blocks/feature icon=\"fab fa-github\" title=\"Give Feedback\" %}}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove superfluous redirects |
259,992 | 29.07.2019 18:35:27 | 25,200 | 6ee109aca465e88b6e00a7b36b865649afb4e809 | Added section about attaching debugger | [
{
"change_type": "MODIFY",
"old_path": "content/docs/user_guide/debugging.md",
"new_path": "content/docs/user_guide/debugging.md",
"diff": "@@ -56,6 +56,30 @@ sudo runsc --root /var/run/docker/runtime-runsc/moby debug --stacks 63254c6ab3a6\n> `/var/run/docker/runtime-[runtime-name]/moby`. If in doubt, `--root` is logged to\n> `runsc` logs.\n+## Debugger\n+\n+You can debug gVisor like any other Golang program. If you're running with Docker,\n+you'll need to find the sandbox PID and attach the debugger as root. Other than\n+that, it's business as usual.\n+\n+```bash\n+# Start the container you want to debug.\n+docker run --runtime=runsc --rm --name=test -d alpine sleep 1000\n+\n+# Find the sandbox PID.\n+docker inspect test | grep Pid | head -n 1\n+\n+# Attach your favorite debugger.\n+sudo dlv attach <PID>\n+\n+# Set a breakpoint and resume.\n+break mm.MemoryManager.MMap\n+continue\n+```\n+\n+> Note: if the debugger cannot find symbols, rebuild runsc in debug mode:\n+> `bazel build -c dbg //runsc:runsc`\n+\n## Profiling\n`runsc` integrates with Go profiling tools and gives you easy commands to profile\n"
}
] | Go | Apache License 2.0 | google/gvisor | Added section about attaching debugger |
259,884 | 01.08.2019 18:47:55 | 25,200 | 3eff0531adc6d28eea49be65fa747e2b3163f44d | Set sandbox oom_score_adj
Set /proc/self/oom_score_adj based on oomScoreAdj specified in the OCI bundle.
When new containers are added to the sandbox oom_score_adj for the sandbox and
all other gofers are adjusted so that oom_score_adj is equal to the lowest
oom_score_adj of all containers in the sandbox.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "runsc/container/container.go",
"new_path": "runsc/container/container.go",
"diff": "@@ -475,7 +475,13 @@ func (c *Container) Start(conf *boot.Config) error {\n}\nc.changeStatus(Running)\n- return c.save()\n+ if err := c.save(); err != nil {\n+ return err\n+ }\n+\n+ // Adjust the oom_score_adj for sandbox and gofers. This must be done after\n+ // save().\n+ return c.adjustOOMScoreAdj(conf)\n}\n// Restore takes a container and replaces its kernel and file system\n@@ -1098,3 +1104,90 @@ func runInCgroup(cg *cgroup.Cgroup, fn func() error) error {\n}\nreturn fn()\n}\n+\n+// adjustOOMScoreAdj sets the oom_score_adj for the sandbox and all gofers.\n+// oom_score_adj is set to the lowest oom_score_adj among the containers\n+// running in the sandbox.\n+func (c *Container) adjustOOMScoreAdj(conf *boot.Config) error {\n+ // If this container's OOMScoreAdj is nil then we can exit early as no\n+ // change should be made to oom_score_adj for the sandbox.\n+ if c.Spec.Process.OOMScoreAdj == nil {\n+ return nil\n+ }\n+\n+ ids, err := List(conf.RootDir)\n+ if err != nil {\n+ return err\n+ }\n+\n+ // Load the container metadata.\n+ var containers []*Container\n+ for _, id := range ids {\n+ container, err := Load(conf.RootDir, id)\n+ if err != nil {\n+ return fmt.Errorf(\"loading container %q: %v\", id, err)\n+ }\n+ if container.Sandbox.ID == c.Sandbox.ID {\n+ containers = append(containers, container)\n+ }\n+ }\n+\n+ // Get the lowest score for all containers.\n+ var lowScore int\n+ scoreFound := false\n+ for _, container := range containers {\n+ if container.Spec.Process.OOMScoreAdj != nil && (!scoreFound || *container.Spec.Process.OOMScoreAdj < lowScore) {\n+ scoreFound = true\n+ lowScore = *container.Spec.Process.OOMScoreAdj\n+ }\n+ }\n+\n+ // Only set oom_score_adj if one of the containers has oom_score_adj set\n+ // in the OCI bundle. If not, we need to inherit the parent process's\n+ // oom_score_adj.\n+ // See: https://github.com/opencontainers/runtime-spec/blob/master/config.md#linux-process\n+ if !scoreFound {\n+ return nil\n+ }\n+\n+ // Set oom_score_adj for the sandbox.\n+ if err := setOOMScoreAdj(c.Sandbox.Pid, lowScore); err != nil {\n+ return fmt.Errorf(\"setting oom_score_adj for sandbox %q: %v\", c.Sandbox.ID, err)\n+ }\n+\n+ // Set the gofer's oom_score_adj to the minimum of -500 and the\n+ // sandbox's oom_score_adj to better ensure that the sandbox is killed\n+ // before the gofer.\n+ //\n+ // TODO(gvisor.dev/issue/601) Set oom_score_adj for the gofer to\n+ // the same oom_score_adj as the sandbox.\n+ goferScoreAdj := -500\n+ if lowScore < goferScoreAdj {\n+ goferScoreAdj = lowScore\n+ }\n+\n+ // Set oom_score_adj for gofers for all containers in the sandbox.\n+ for _, container := range containers {\n+ err := setOOMScoreAdj(container.GoferPid, goferScoreAdj)\n+ if err != nil {\n+ return fmt.Errorf(\"setting oom_score_adj for container %q: %v\", container.ID, err)\n+ }\n+ }\n+\n+ return nil\n+}\n+\n+// setOOMScoreAdj sets oom_score_adj to the given value for the given PID.\n+// /proc must be available and mounted read-write. scoreAdj should be between\n+// -1000 and 1000.\n+func setOOMScoreAdj(pid int, scoreAdj int) error {\n+ f, err := os.OpenFile(fmt.Sprintf(\"/proc/%d/oom_score_adj\", pid), os.O_WRONLY, 0644)\n+ if err != nil {\n+ return err\n+ }\n+ defer f.Close()\n+ if _, err := f.WriteString(strconv.Itoa(scoreAdj)); err != nil {\n+ return err\n+ }\n+ return nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -54,7 +54,7 @@ type Sandbox struct {\n// ID as the first container run in the sandbox.\nID string `json:\"id\"`\n- // Pid is the pid of the running sandbox (immutable). May be 0 is the sandbox\n+ // Pid is the pid of the running sandbox (immutable). May be 0 if the sandbox\n// is not running.\nPid int `json:\"pid\"`\n"
}
] | Go | Apache License 2.0 | google/gvisor | Set sandbox oom_score_adj
Set /proc/self/oom_score_adj based on oomScoreAdj specified in the OCI bundle.
When new containers are added to the sandbox oom_score_adj for the sandbox and
all other gofers are adjusted so that oom_score_adj is equal to the lowest
oom_score_adj of all containers in the sandbox.
Fixes #512
PiperOrigin-RevId: 261242725 |
259,992 | 02.08.2019 13:46:42 | 25,200 | b461be88a8036ca0455aceb8b6c723d6b6fded4f | Stops container if gofer is killed
Each gofer now has a goroutine that polls on the FDs used
to communicate with the sandbox. The respective gofer is
destroyed if any of the FDs is closed.
Closes | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/BUILD",
"new_path": "runsc/boot/BUILD",
"diff": "@@ -88,6 +88,7 @@ go_library(\n\"//runsc/specutils\",\n\"@com_github_golang_protobuf//proto:go_default_library\",\n\"@com_github_opencontainers_runtime-spec//specs-go:go_default_library\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/controller.go",
"new_path": "runsc/boot/controller.go",
"diff": "@@ -347,7 +347,7 @@ func (cm *containerManager) Restore(o *RestoreOpts, _ *struct{}) error {\ncm.l.k = k\n// Set up the restore environment.\n- mntr := newContainerMounter(cm.l.spec, \"\", cm.l.goferFDs, cm.l.k, cm.l.mountHints)\n+ mntr := newContainerMounter(cm.l.spec, cm.l.goferFDs, cm.l.k, cm.l.mountHints)\nrenv, err := mntr.createRestoreEnvironment(cm.l.conf)\nif err != nil {\nreturn fmt.Errorf(\"creating RestoreEnvironment: %v\", err)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/fs.go",
"new_path": "runsc/boot/fs.go",
"diff": "@@ -476,9 +476,6 @@ func (p *podMountHints) findMount(mount specs.Mount) *mountHint {\n}\ntype containerMounter struct {\n- // cid is the container ID. May be set to empty for the root container.\n- cid string\n-\nroot *specs.Root\n// mounts is the set of submounts for the container. It's a copy from the spec\n@@ -493,9 +490,8 @@ type containerMounter struct {\nhints *podMountHints\n}\n-func newContainerMounter(spec *specs.Spec, cid string, goferFDs []int, k *kernel.Kernel, hints *podMountHints) *containerMounter {\n+func newContainerMounter(spec *specs.Spec, goferFDs []int, k *kernel.Kernel, hints *podMountHints) *containerMounter {\nreturn &containerMounter{\n- cid: cid,\nroot: spec.Root,\nmounts: compileMounts(spec),\nfds: fdDispenser{fds: goferFDs},\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader.go",
"new_path": "runsc/boot/loader.go",
"diff": "@@ -27,6 +27,7 @@ import (\ngtime \"time\"\nspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n+ \"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/cpuid\"\n\"gvisor.dev/gvisor/pkg/log\"\n@@ -524,11 +525,9 @@ func (l *Loader) run() error {\n// ours either way.\nl.rootProcArgs.FDTable = fdTable\n- // cid for root container can be empty. Only subcontainers need it to set\n- // the mount location.\n- mntr := newContainerMounter(l.spec, \"\", l.goferFDs, l.k, l.mountHints)\n-\n- // Setup the root container.\n+ // Setup the root container file system.\n+ l.startGoferMonitor(l.sandboxID, l.goferFDs)\n+ mntr := newContainerMounter(l.spec, l.goferFDs, l.k, l.mountHints)\nif err := mntr.setupRootContainer(ctx, ctx, l.conf, func(mns *fs.MountNamespace) {\nl.rootProcArgs.MountNamespace = mns\n}); err != nil {\n@@ -687,7 +686,9 @@ func (l *Loader) startContainer(spec *specs.Spec, conf *Config, cid string, file\ngoferFDs = append(goferFDs, fd)\n}\n- mntr := newContainerMounter(spec, cid, goferFDs, l.k, l.mountHints)\n+ // Setup the child container file system.\n+ l.startGoferMonitor(cid, goferFDs)\n+ mntr := newContainerMounter(spec, goferFDs, l.k, l.mountHints)\nif err := mntr.setupChildContainer(conf, &procArgs); err != nil {\nreturn fmt.Errorf(\"configuring container FS: %v\", err)\n}\n@@ -710,17 +711,59 @@ func (l *Loader) startContainer(spec *specs.Spec, conf *Config, cid string, file\nreturn nil\n}\n+// startGoferMonitor runs a goroutine to monitor gofer's health. It polls on\n+// the gofer FDs looking for disconnects, and destroys the container if a\n+// disconnect occurs in any of the gofer FDs.\n+func (l *Loader) startGoferMonitor(cid string, goferFDs []int) {\n+ go func() {\n+ log.Debugf(\"Monitoring gofer health for container %q\", cid)\n+ var events []unix.PollFd\n+ for _, fd := range goferFDs {\n+ events = append(events, unix.PollFd{\n+ Fd: int32(fd),\n+ Events: unix.POLLHUP | unix.POLLRDHUP,\n+ })\n+ }\n+ _, _, err := specutils.RetryEintr(func() (uintptr, uintptr, error) {\n+ // Use ppoll instead of poll because it's already whilelisted in seccomp.\n+ n, err := unix.Ppoll(events, nil, nil)\n+ return uintptr(n), 0, err\n+ })\n+ if err != nil {\n+ panic(fmt.Sprintf(\"Error monitoring gofer FDs: %v\", err))\n+ }\n+\n+ // Check if the gofer has stopped as part of normal container destruction.\n+ // This is done just to avoid sending an annoying error message to the log.\n+ // Note that there is a small race window in between mu.Unlock() and the\n+ // lock being reacquired in destroyContainer(), but it's harmless to call\n+ // destroyContainer() multiple times.\n+ l.mu.Lock()\n+ _, ok := l.processes[execID{cid: cid}]\n+ l.mu.Unlock()\n+ if ok {\n+ log.Infof(\"Gofer socket disconnected, destroying container %q\", cid)\n+ if err := l.destroyContainer(cid); err != nil {\n+ log.Warningf(\"Error destroying container %q after gofer stopped: %v\", cid, err)\n+ }\n+ }\n+ }()\n+}\n+\n// destroyContainer stops a container if it is still running and cleans up its\n// filesystem.\nfunc (l *Loader) destroyContainer(cid string) error {\nl.mu.Lock()\ndefer l.mu.Unlock()\n- // Has the container started?\n- _, _, err := l.threadGroupFromIDLocked(execID{cid: cid})\n+ _, _, started, err := l.threadGroupFromIDLocked(execID{cid: cid})\n+ if err != nil {\n+ // Container doesn't exist.\n+ return err\n+ }\n- // If the container has started, kill and wait for all processes.\n- if err == nil {\n+ // The container exists, has it been started?\n+ if started {\nif err := l.signalAllProcesses(cid, int32(linux.SIGKILL)); err != nil {\nreturn fmt.Errorf(\"sending SIGKILL to all container processes: %v\", err)\n}\n@@ -754,9 +797,12 @@ func (l *Loader) executeAsync(args *control.ExecArgs) (kernel.ThreadID, error) {\nl.mu.Lock()\ndefer l.mu.Unlock()\n- tg, _, err := l.threadGroupFromIDLocked(execID{cid: args.ContainerID})\n+ tg, _, started, err := l.threadGroupFromIDLocked(execID{cid: args.ContainerID})\nif err != nil {\n- return 0, fmt.Errorf(\"no such container: %q\", args.ContainerID)\n+ return 0, err\n+ }\n+ if !started {\n+ return 0, fmt.Errorf(\"container %q not started\", args.ContainerID)\n}\n// Get the container MountNamespace from the Task.\n@@ -1018,22 +1064,30 @@ func (l *Loader) signalAllProcesses(cid string, signo int32) error {\nfunc (l *Loader) threadGroupFromID(key execID) (*kernel.ThreadGroup, *host.TTYFileOperations, error) {\nl.mu.Lock()\ndefer l.mu.Unlock()\n- return l.threadGroupFromIDLocked(key)\n+ tg, tty, ok, err := l.threadGroupFromIDLocked(key)\n+ if err != nil {\n+ return nil, nil, err\n+ }\n+ if !ok {\n+ return nil, nil, fmt.Errorf(\"container %q not started\", key.cid)\n+ }\n+ return tg, tty, nil\n}\n// threadGroupFromIDLocked returns the thread group and TTY for the given\n// execution ID. TTY may be nil if the process is not attached to a terminal.\n-// Returns error if execution ID is invalid or if container/process has not\n-// started yet. Caller must hold 'mu'.\n-func (l *Loader) threadGroupFromIDLocked(key execID) (*kernel.ThreadGroup, *host.TTYFileOperations, error) {\n+// Also returns a boolean indicating whether the container has already started.\n+// Returns error if execution ID is invalid or if the container cannot be\n+// found (maybe it has been deleted). Caller must hold 'mu'.\n+func (l *Loader) threadGroupFromIDLocked(key execID) (*kernel.ThreadGroup, *host.TTYFileOperations, bool, error) {\nep := l.processes[key]\nif ep == nil {\n- return nil, nil, fmt.Errorf(\"container not found\")\n+ return nil, nil, false, fmt.Errorf(\"container %q not found\", key.cid)\n}\nif ep.tg == nil {\n- return nil, nil, fmt.Errorf(\"container not started\")\n+ return nil, nil, false, nil\n}\n- return ep.tg, ep.tty, nil\n+ return ep.tg, ep.tty, true, nil\n}\nfunc init() {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader_test.go",
"new_path": "runsc/boot/loader_test.go",
"diff": "@@ -408,7 +408,7 @@ func TestCreateMountNamespace(t *testing.T) {\nmns = m\nctx.(*contexttest.TestContext).RegisterValue(fs.CtxRoot, mns.Root())\n}\n- mntr := newContainerMounter(&tc.spec, \"\", []int{sandEnd}, nil, &podMountHints{})\n+ mntr := newContainerMounter(&tc.spec, []int{sandEnd}, nil, &podMountHints{})\nif err := mntr.setupRootContainer(ctx, ctx, conf, setMountNS); err != nil {\nt.Fatalf(\"createMountNamespace test case %q failed: %v\", tc.name, err)\n}\n@@ -614,7 +614,7 @@ func TestRestoreEnvironment(t *testing.T) {\nfor _, tc := range testCases {\nt.Run(tc.name, func(t *testing.T) {\nconf := testConfig()\n- mntr := newContainerMounter(tc.spec, \"\", tc.ioFDs, nil, &podMountHints{})\n+ mntr := newContainerMounter(tc.spec, tc.ioFDs, nil, &podMountHints{})\nactualRenv, err := mntr.createRestoreEnvironment(conf)\nif !tc.errorExpected && err != nil {\nt.Fatalf(\"could not create restore environment for test:%s\", tc.name)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/user_test.go",
"new_path": "runsc/boot/user_test.go",
"diff": "@@ -169,7 +169,7 @@ func TestGetExecUserHome(t *testing.T) {\nmns = m\nctx.(*contexttest.TestContext).RegisterValue(fs.CtxRoot, mns.Root())\n}\n- mntr := newContainerMounter(spec, \"\", []int{sandEnd}, nil, &podMountHints{})\n+ mntr := newContainerMounter(spec, []int{sandEnd}, nil, &podMountHints{})\nif err := mntr.setupRootContainer(ctx, ctx, conf, setMountNS); err != nil {\nt.Fatalf(\"failed to create mount namespace: %v\", err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/BUILD",
"new_path": "runsc/container/BUILD",
"diff": "@@ -49,6 +49,7 @@ go_test(\n\"//pkg/abi/linux\",\n\"//pkg/log\",\n\"//pkg/sentry/control\",\n+ \"//pkg/sentry/kernel\",\n\"//pkg/sentry/kernel/auth\",\n\"//pkg/unet\",\n\"//pkg/urpc\",\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/container_test.go",
"new_path": "runsc/container/container_test.go",
"diff": "@@ -76,7 +76,7 @@ func waitForProcessCount(cont *Container, want int) error {\n}\nfunc blockUntilWaitable(pid int) error {\n- _, _, err := testutil.RetryEintr(func() (uintptr, uintptr, error) {\n+ _, _, err := specutils.RetryEintr(func() (uintptr, uintptr, error) {\nvar err error\n_, _, err1 := syscall.Syscall6(syscall.SYS_WAITID, 1, uintptr(pid), 0, syscall.WEXITED|syscall.WNOWAIT, 0, 0)\nif err1 != 0 {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/multi_container_test.go",
"new_path": "runsc/container/multi_container_test.go",
"diff": "@@ -29,6 +29,7 @@ import (\nspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n\"gvisor.dev/gvisor/pkg/sentry/control\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/runsc/boot\"\n\"gvisor.dev/gvisor/runsc/specutils\"\n\"gvisor.dev/gvisor/runsc/test/testutil\"\n@@ -488,7 +489,7 @@ func TestMultiContainerSignal(t *testing.T) {\nif err := containers[1].Destroy(); err != nil {\nt.Errorf(\"failed to destroy container: %v\", err)\n}\n- _, _, err = testutil.RetryEintr(func() (uintptr, uintptr, error) {\n+ _, _, err = specutils.RetryEintr(func() (uintptr, uintptr, error) {\ncpid, err := syscall.Wait4(goferPid, nil, 0, nil)\nreturn uintptr(cpid), 0, err\n})\n@@ -905,9 +906,9 @@ func TestMultiContainerDifferentFilesystems(t *testing.T) {\n}\n}\n-// TestMultiContainerGoferStop tests that IO operations continue to work after\n-// containers have been stopped and gofers killed.\n-func TestMultiContainerGoferStop(t *testing.T) {\n+// TestMultiContainerContainerDestroyStress tests that IO operations continue\n+// to work after containers have been stopped and gofers killed.\n+func TestMultiContainerContainerDestroyStress(t *testing.T) {\napp, err := testutil.FindFile(\"runsc/container/test_app/test_app\")\nif err != nil {\nt.Fatal(\"error finding test_app:\", err)\n@@ -1345,3 +1346,80 @@ func TestMultiContainerMultiRootCanHandleFDs(t *testing.T) {\n}\n}\n}\n+\n+// Test that container is destroyed when Gofer is killed.\n+func TestMultiContainerGoferKilled(t *testing.T) {\n+ sleep := []string{\"sleep\", \"100\"}\n+ specs, ids := createSpecs(sleep, sleep, sleep)\n+ conf := testutil.TestConfig()\n+ containers, cleanup, err := startContainers(conf, specs, ids)\n+ if err != nil {\n+ t.Fatalf(\"error starting containers: %v\", err)\n+ }\n+ defer cleanup()\n+\n+ // Ensure container is running\n+ c := containers[2]\n+ expectedPL := []*control.Process{\n+ {PID: 3, Cmd: \"sleep\"},\n+ }\n+ if err := waitForProcessList(c, expectedPL); err != nil {\n+ t.Errorf(\"failed to wait for sleep to start: %v\", err)\n+ }\n+\n+ // Kill container's gofer.\n+ if err := syscall.Kill(c.GoferPid, syscall.SIGKILL); err != nil {\n+ t.Fatalf(\"syscall.Kill(%d, SIGKILL)=%v\", c.GoferPid, err)\n+ }\n+\n+ // Wait until container stops.\n+ if err := waitForProcessList(c, nil); err != nil {\n+ t.Errorf(\"Container %q was not stopped after gofer death: %v\", c.ID, err)\n+ }\n+\n+ // Check that container isn't running anymore.\n+ args := &control.ExecArgs{Argv: []string{\"/bin/true\"}}\n+ if _, err := c.executeSync(args); err == nil {\n+ t.Fatalf(\"Container %q was not stopped after gofer death\", c.ID)\n+ }\n+\n+ // Check that other containers are unaffected.\n+ for i, c := range containers {\n+ if i == 2 {\n+ continue // container[2] has been killed.\n+ }\n+ pl := []*control.Process{\n+ {PID: kernel.ThreadID(i + 1), Cmd: \"sleep\"},\n+ }\n+ if err := waitForProcessList(c, pl); err != nil {\n+ t.Errorf(\"Container %q was affected by another container: %v\", c.ID, err)\n+ }\n+ args := &control.ExecArgs{Argv: []string{\"/bin/true\"}}\n+ if _, err := c.executeSync(args); err != nil {\n+ t.Fatalf(\"Container %q was affected by another container: %v\", c.ID, err)\n+ }\n+ }\n+\n+ // Kill root container's gofer to bring entire sandbox down.\n+ c = containers[0]\n+ if err := syscall.Kill(c.GoferPid, syscall.SIGKILL); err != nil {\n+ t.Fatalf(\"syscall.Kill(%d, SIGKILL)=%v\", c.GoferPid, err)\n+ }\n+\n+ // Wait until sandbox stops. waitForProcessList will loop until sandbox exits\n+ // and RPC errors out.\n+ impossiblePL := []*control.Process{\n+ {PID: 100, Cmd: \"non-existent-process\"},\n+ }\n+ if err := waitForProcessList(c, impossiblePL); err == nil {\n+ t.Fatalf(\"Sandbox was not killed after gofer death\")\n+ }\n+\n+ // Check that entire sandbox isn't running anymore.\n+ for _, c := range containers {\n+ args := &control.ExecArgs{Argv: []string{\"/bin/true\"}}\n+ if _, err := c.executeSync(args); err == nil {\n+ t.Fatalf(\"Container %q was not stopped after gofer death\", c.ID)\n+ }\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/specutils/specutils.go",
"new_path": "runsc/specutils/specutils.go",
"diff": "@@ -492,3 +492,14 @@ func (c *Cleanup) Clean() {\nfunc (c *Cleanup) Release() {\nc.clean = nil\n}\n+\n+// RetryEintr retries the function until an error different than EINTR is\n+// returned.\n+func RetryEintr(f func() (uintptr, uintptr, error)) (uintptr, uintptr, error) {\n+ for {\n+ r1, r2, err := f()\n+ if err != syscall.EINTR {\n+ return r1, r2, err\n+ }\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/test/testutil/testutil.go",
"new_path": "runsc/test/testutil/testutil.go",
"diff": "@@ -348,17 +348,6 @@ func StartReaper() func() {\nreturn r.Stop\n}\n-// RetryEintr retries the function until an error different than EINTR is\n-// returned.\n-func RetryEintr(f func() (uintptr, uintptr, error)) (uintptr, uintptr, error) {\n- for {\n- r1, r2, err := f()\n- if err != syscall.EINTR {\n- return r1, r2, err\n- }\n- }\n-}\n-\n// WaitUntilRead reads from the given reader until the wanted string is found\n// or until timeout.\nfunc WaitUntilRead(r io.Reader, want string, split bufio.SplitFunc, timeout time.Duration) error {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Stops container if gofer is killed
Each gofer now has a goroutine that polls on the FDs used
to communicate with the sandbox. The respective gofer is
destroyed if any of the FDs is closed.
Closes #601
PiperOrigin-RevId: 261383725 |
259,992 | 02.08.2019 16:33:51 | 25,200 | 960a5e5536d5d961028ef60123e3b00ff3c04a56 | Remove stale TODO
This was done in commit | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader.go",
"new_path": "runsc/boot/loader.go",
"diff": "@@ -630,7 +630,6 @@ func (l *Loader) startContainer(spec *specs.Spec, conf *Config, cid string, file\n// sentry currently supports only 1 mount namespace, which is tied to a\n// single user namespace. Thus we must run in the same user namespace\n// to access mounts.\n- // TODO(b/63601033): Create a new mount namespace for the container.\ncreds := auth.NewUserCredentials(\nauth.KUID(spec.Process.User.UID),\nauth.KGID(spec.Process.User.GID),\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove stale TODO
This was done in commit 04cbb13ce9b151cf906f42e3f18ce3a875f01f63
PiperOrigin-RevId: 261414748 |
259,884 | 11.07.2019 08:41:52 | -32,400 | 5f6e3739ef5d4d4bb761ec8a2a764976326b05fb | runsc permissions update in install instructions
Make the instructions clearer by putting the chown and chmod together and make it match the FAQ by setting the permissions bits exactly. | [
{
"change_type": "MODIFY",
"old_path": "content/docs/includes/install_gvisor.md",
"new_path": "content/docs/includes/install_gvisor.md",
"diff": "@@ -19,9 +19,9 @@ a good place to put the `runsc` binary.\nwget https://storage.googleapis.com/gvisor/releases/nightly/latest/runsc\nwget https://storage.googleapis.com/gvisor/releases/nightly/latest/runsc.sha512\nsha512sum -c runsc.sha512\n- chmod a+x runsc\nsudo mv runsc /usr/local/bin\nsudo chown root:root /usr/local/bin/runsc\n+ chmod 0755 /usr/local/bin/runsc\n)\n```\n"
}
] | Go | Apache License 2.0 | google/gvisor | runsc permissions update in install instructions
Make the instructions clearer by putting the chown and chmod together and make it match the FAQ by setting the permissions bits exactly. |
259,997 | 06.08.2019 01:15:48 | -36,000 | 607be0585fdc659ec3c043c989a8a6f86fcc14db | Add option to configure reference leak checking | [
{
"change_type": "MODIFY",
"old_path": "pkg/refs/refcounter.go",
"new_path": "pkg/refs/refcounter.go",
"diff": "@@ -231,6 +231,20 @@ const (\nLeaksLogTraces\n)\n+// String returns LeakMode's string representation.\n+func (l LeakMode) String() string {\n+ switch l {\n+ case NoLeakChecking:\n+ return \"NoLeakChecking\"\n+ case LeaksLogWarning:\n+ return \"LeaksLogWarning\"\n+ case LeaksLogTraces:\n+ return \"LeaksLogTraces\"\n+ default:\n+ panic(fmt.Sprintf(\"Invalid leakmode: %d\", l))\n+ }\n+}\n+\n// leakMode stores the current mode for the reference leak checker.\n//\n// Values must be one of the LeakMode values.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/config.go",
"new_path": "runsc/boot/config.go",
"diff": "@@ -19,6 +19,7 @@ import (\n\"strconv\"\n\"strings\"\n+ \"gvisor.dev/gvisor/pkg/refs\"\n\"gvisor.dev/gvisor/pkg/sentry/watchdog\"\n)\n@@ -112,6 +113,20 @@ func MakeWatchdogAction(s string) (watchdog.Action, error) {\n}\n}\n+// MakeRefsLeakMode converts type from string\n+func MakeRefsLeakMode(s string) (refs.LeakMode, error) {\n+ switch strings.ToLower(s) {\n+ case \"nocheck\":\n+ return refs.NoLeakChecking, nil\n+ case \"warning\":\n+ return refs.LeaksLogWarning, nil\n+ case \"traces\":\n+ return refs.LeaksLogTraces, nil\n+ default:\n+ return 0, fmt.Errorf(\"invalid refs leakmode %q\", s)\n+ }\n+}\n+\n// Config holds configuration that is not part of the runtime spec.\ntype Config struct {\n// RootDir is the runtime root directory.\n@@ -201,6 +216,9 @@ type Config struct {\n// AlsoLogToStderr allows to send log messages to stderr.\nAlsoLogToStderr bool\n+\n+ // ReferenceLeakMode sets reference leak check mode\n+ ReferenceLeakMode refs.LeakMode\n}\n// ToFlags returns a slice of flags that correspond to the given Config.\n@@ -227,6 +245,7 @@ func (c *Config) ToFlags() []string {\n\"--num-network-channels=\" + strconv.Itoa(c.NumNetworkChannels),\n\"--rootless=\" + strconv.FormatBool(c.Rootless),\n\"--alsologtostderr=\" + strconv.FormatBool(c.AlsoLogToStderr),\n+ \"--refs-leak-mode=\" + c.ReferenceLeakMode.String(),\n}\nif c.TestOnlyAllowRunAsCurrentUserWithoutChroot {\n// Only include if set since it is never to be used by users.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader.go",
"new_path": "runsc/boot/loader.go",
"diff": "@@ -191,6 +191,9 @@ func New(args Args) (*Loader, error) {\nreturn nil, fmt.Errorf(\"setting up memory usage: %v\", err)\n}\n+ // Sets the refs leak check mode\n+ refs.SetLeakMode(args.Conf.ReferenceLeakMode)\n+\n// Create kernel and platform.\np, err := createPlatform(args.Conf, args.Device)\nif err != nil {\n@@ -1040,8 +1043,3 @@ func (l *Loader) threadGroupFromIDLocked(key execID) (*kernel.ThreadGroup, *host\n}\nreturn ep.tg, ep.tty, nil\n}\n-\n-func init() {\n- // TODO(gvisor.dev/issue/365): Make this configurable.\n- refs.SetLeakMode(refs.NoLeakChecking)\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/main.go",
"new_path": "runsc/main.go",
"diff": "@@ -73,6 +73,7 @@ var (\nnetRaw = flag.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.\")\nnumNetworkChannels = flag.Int(\"num-network-channels\", 1, \"number of underlying channels(FDs) to use for network link endpoints.\")\nrootless = flag.Bool(\"rootless\", false, \"it allows the sandbox to be started with a user that is not root. Sandbox and Gofer processes may run with same privileges as current user.\")\n+ referenceLeakMode = flag.String(\"refs-leak-mode\", \"nocheck\", \"sets reference leak check mode: nocheck (default), warning, traces.\")\n// Test flags, not to be used outside tests, ever.\ntestOnlyAllowRunAsCurrentUserWithoutChroot = flag.Bool(\"TESTONLY-unsafe-nonroot\", false, \"TEST ONLY; do not ever use! This skips many security measures that isolate the host from the sandbox.\")\n@@ -168,6 +169,11 @@ func main() {\ncmd.Fatalf(\"num_network_channels must be > 0, got: %d\", *numNetworkChannels)\n}\n+ refsLeakMode, err := boot.MakeRefsLeakMode(*referenceLeakMode)\n+ if err != nil {\n+ cmd.Fatalf(\"%v\", err)\n+ }\n+\n// Create a new Config from the flags.\nconf := &boot.Config{\nRootDir: *rootDir,\n@@ -191,6 +197,7 @@ func main() {\nNumNetworkChannels: *numNetworkChannels,\nRootless: *rootless,\nAlsoLogToStderr: *alsoLogToStderr,\n+ ReferenceLeakMode: refsLeakMode,\nTestOnlyAllowRunAsCurrentUserWithoutChroot: *testOnlyAllowRunAsCurrentUserWithoutChroot,\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add option to configure reference leak checking |
259,974 | 05.08.2019 03:16:50 | 0 | 83fdb7739e2da5636147bac89d2508be507801dc | Change syscall.EPOLLET to unix.EPOLLET
syscall.EPOLLET has been defined with different values on amd64 and
arm64(-0x80000000 on amd64, and 0x80000000 on arm64), while unix.EPOLLET
has been unified this value to 0x80000000(golang/go#5328). ref | [
{
"change_type": "MODIFY",
"old_path": "pkg/fdnotifier/BUILD",
"new_path": "pkg/fdnotifier/BUILD",
"diff": "@@ -10,5 +10,8 @@ go_library(\n],\nimportpath = \"gvisor.dev/gvisor/pkg/fdnotifier\",\nvisibility = [\"//:sandbox\"],\n- deps = [\"//pkg/waiter\"],\n+ deps = [\n+ \"//pkg/waiter\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n+ ],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/fdnotifier/fdnotifier.go",
"new_path": "pkg/fdnotifier/fdnotifier.go",
"diff": "@@ -25,6 +25,7 @@ import (\n\"sync\"\n\"syscall\"\n+ \"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n@@ -72,7 +73,7 @@ func (n *notifier) waitFD(fd int32, fi *fdInfo, mask waiter.EventMask) error {\n}\ne := syscall.EpollEvent{\n- Events: mask.ToLinux() | -syscall.EPOLLET,\n+ Events: mask.ToLinux() | unix.EPOLLET,\nFd: fd,\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/rpcinet/notifier/BUILD",
"new_path": "pkg/sentry/socket/rpcinet/notifier/BUILD",
"diff": "@@ -11,5 +11,6 @@ go_library(\n\"//pkg/sentry/socket/rpcinet:syscall_rpc_go_proto\",\n\"//pkg/sentry/socket/rpcinet/conn\",\n\"//pkg/waiter\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/rpcinet/notifier/notifier.go",
"new_path": "pkg/sentry/socket/rpcinet/notifier/notifier.go",
"diff": "@@ -20,6 +20,7 @@ import (\n\"sync\"\n\"syscall\"\n+ \"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/rpcinet/conn\"\npb \"gvisor.dev/gvisor/pkg/sentry/socket/rpcinet/syscall_rpc_go_proto\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n@@ -76,7 +77,7 @@ func (n *Notifier) waitFD(fd uint32, fi *fdInfo, mask waiter.EventMask) error {\n}\ne := pb.EpollEvent{\n- Events: mask.ToLinux() | -syscall.EPOLLET,\n+ Events: mask.ToLinux() | unix.EPOLLET,\nFd: fd,\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Change syscall.EPOLLET to unix.EPOLLET
syscall.EPOLLET has been defined with different values on amd64 and
arm64(-0x80000000 on amd64, and 0x80000000 on arm64), while unix.EPOLLET
has been unified this value to 0x80000000(golang/go#5328). ref #63
Signed-off-by: Haibo Xu <[email protected]>
Change-Id: Id97d075c4e79d86a2ea3227ffbef02d8b00ffbb8 |
259,997 | 06.08.2019 11:57:50 | -36,000 | 8d89c0d92b3839eed0839b1a9bc7666e6261d972 | Remove traces option for ref leak mode | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/config.go",
"new_path": "runsc/boot/config.go",
"diff": "@@ -116,12 +116,10 @@ func MakeWatchdogAction(s string) (watchdog.Action, error) {\n// MakeRefsLeakMode converts type from string\nfunc MakeRefsLeakMode(s string) (refs.LeakMode, error) {\nswitch strings.ToLower(s) {\n- case \"nocheck\":\n+ case \"disabled\":\nreturn refs.NoLeakChecking, nil\ncase \"warning\":\nreturn refs.LeaksLogWarning, nil\n- case \"traces\":\n- return refs.LeaksLogTraces, nil\ndefault:\nreturn 0, fmt.Errorf(\"invalid refs leakmode %q\", s)\n}\n@@ -245,7 +243,7 @@ func (c *Config) ToFlags() []string {\n\"--num-network-channels=\" + strconv.Itoa(c.NumNetworkChannels),\n\"--rootless=\" + strconv.FormatBool(c.Rootless),\n\"--alsologtostderr=\" + strconv.FormatBool(c.AlsoLogToStderr),\n- \"--refs-leak-mode=\" + c.ReferenceLeakMode.String(),\n+ \"--ref-leak-mode=\" + c.ReferenceLeakMode.String(),\n}\nif c.TestOnlyAllowRunAsCurrentUserWithoutChroot {\n// Only include if set since it is never to be used by users.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader.go",
"new_path": "runsc/boot/loader.go",
"diff": "@@ -181,6 +181,9 @@ type Args struct {\n// New initializes a new kernel loader configured by spec.\n// New also handles setting up a kernel for restoring a container.\nfunc New(args Args) (*Loader, error) {\n+ // Sets the reference leak check mode\n+ refs.SetLeakMode(args.Conf.ReferenceLeakMode)\n+\n// We initialize the rand package now to make sure /dev/urandom is pre-opened\n// on kernels that do not support getrandom(2).\nif err := rand.Init(); err != nil {\n@@ -191,9 +194,6 @@ func New(args Args) (*Loader, error) {\nreturn nil, fmt.Errorf(\"setting up memory usage: %v\", err)\n}\n- // Sets the refs leak check mode\n- refs.SetLeakMode(args.Conf.ReferenceLeakMode)\n-\n// Create kernel and platform.\np, err := createPlatform(args.Conf, args.Device)\nif err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/main.go",
"new_path": "runsc/main.go",
"diff": "@@ -73,7 +73,7 @@ var (\nnetRaw = flag.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.\")\nnumNetworkChannels = flag.Int(\"num-network-channels\", 1, \"number of underlying channels(FDs) to use for network link endpoints.\")\nrootless = flag.Bool(\"rootless\", false, \"it allows the sandbox to be started with a user that is not root. Sandbox and Gofer processes may run with same privileges as current user.\")\n- referenceLeakMode = flag.String(\"refs-leak-mode\", \"nocheck\", \"sets reference leak check mode: nocheck (default), warning, traces.\")\n+ referenceLeakMode = flag.String(\"ref-leak-mode\", \"disabled\", \"sets reference leak check mode: disabled (default), warning.\")\n// Test flags, not to be used outside tests, ever.\ntestOnlyAllowRunAsCurrentUserWithoutChroot = flag.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 | Remove traces option for ref leak mode |
259,881 | 06.08.2019 10:34:06 | 25,200 | 704f9610f3d1add26c266888de62d884338f52cc | Require pread/pwrite for splice file offsets
If there is an offset, the file must support pread/pwrite. See
fs/splice.c:do_splice. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_splice.go",
"new_path": "pkg/sentry/syscalls/linux/sys_splice.go",
"diff": "@@ -207,6 +207,10 @@ func Splice(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\nreturn 0, nil, syserror.ESPIPE\n}\nif outOffset != 0 {\n+ if !outFile.Flags().Pwrite {\n+ return 0, nil, syserror.EINVAL\n+ }\n+\nvar offset int64\nif _, err := t.CopyIn(outOffset, &offset); err != nil {\nreturn 0, nil, err\n@@ -220,6 +224,10 @@ func Splice(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\nreturn 0, nil, syserror.ESPIPE\n}\nif inOffset != 0 {\n+ if !inFile.Flags().Pread {\n+ return 0, nil, syserror.EINVAL\n+ }\n+\nvar offset int64\nif _, err := t.CopyIn(inOffset, &offset); err != nil {\nreturn 0, nil, err\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/splice.cc",
"new_path": "test/syscalls/linux/splice.cc",
"diff": "// limitations under the License.\n#include <fcntl.h>\n+#include <sys/eventfd.h>\n#include <sys/sendfile.h>\n#include <unistd.h>\n@@ -135,6 +136,80 @@ TEST(SpliceTest, PipeOffsets) {\nSyscallFailsWithErrno(ESPIPE));\n}\n+// Event FDs may be used with splice without an offset.\n+TEST(SpliceTest, FromEventFD) {\n+ // Open the input eventfd with an initial value so that it is readable.\n+ constexpr uint64_t kEventFDValue = 1;\n+ int efd;\n+ ASSERT_THAT(efd = eventfd(kEventFDValue, 0), SyscallSucceeds());\n+ const FileDescriptor inf(efd);\n+\n+ // Create a new pipe.\n+ int fds[2];\n+ ASSERT_THAT(pipe(fds), SyscallSucceeds());\n+ const FileDescriptor rfd(fds[0]);\n+ const FileDescriptor wfd(fds[1]);\n+\n+ // Splice 8-byte eventfd value to pipe.\n+ constexpr int kEventFDSize = 8;\n+ EXPECT_THAT(splice(inf.get(), nullptr, wfd.get(), nullptr, kEventFDSize, 0),\n+ SyscallSucceedsWithValue(kEventFDSize));\n+\n+ // Contents should be equal.\n+ std::vector<char> rbuf(kEventFDSize);\n+ ASSERT_THAT(read(rfd.get(), rbuf.data(), rbuf.size()),\n+ SyscallSucceedsWithValue(kEventFDSize));\n+ EXPECT_EQ(memcmp(rbuf.data(), &kEventFDValue, rbuf.size()), 0);\n+}\n+\n+// Event FDs may not be used with splice with an offset.\n+TEST(SpliceTest, FromEventFDOffset) {\n+ int efd;\n+ ASSERT_THAT(efd = eventfd(0, 0), SyscallSucceeds());\n+ const FileDescriptor inf(efd);\n+\n+ // Create a new pipe.\n+ int fds[2];\n+ ASSERT_THAT(pipe(fds), SyscallSucceeds());\n+ const FileDescriptor rfd(fds[0]);\n+ const FileDescriptor wfd(fds[1]);\n+\n+ // Attempt to splice 8-byte eventfd value to pipe with offset.\n+ //\n+ // This is not allowed because eventfd doesn't support pread.\n+ constexpr int kEventFDSize = 8;\n+ loff_t in_off = 0;\n+ EXPECT_THAT(splice(inf.get(), &in_off, wfd.get(), nullptr, kEventFDSize, 0),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\n+// Event FDs may not be used with splice with an offset.\n+TEST(SpliceTest, ToEventFDOffset) {\n+ // Create a new pipe.\n+ int fds[2];\n+ ASSERT_THAT(pipe(fds), SyscallSucceeds());\n+ const FileDescriptor rfd(fds[0]);\n+ const FileDescriptor wfd(fds[1]);\n+\n+ // Fill with a value.\n+ constexpr int kEventFDSize = 8;\n+ std::vector<char> buf(kEventFDSize);\n+ buf[0] = 1;\n+ ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),\n+ SyscallSucceedsWithValue(kEventFDSize));\n+\n+ int efd;\n+ ASSERT_THAT(efd = eventfd(0, 0), SyscallSucceeds());\n+ const FileDescriptor outf(efd);\n+\n+ // Attempt to splice 8-byte eventfd value to pipe with offset.\n+ //\n+ // This is not allowed because eventfd doesn't support pwrite.\n+ loff_t out_off = 0;\n+ EXPECT_THAT(splice(rfd.get(), nullptr, outf.get(), &out_off, kEventFDSize, 0),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\nTEST(SpliceTest, ToPipe) {\n// Open the input file.\nconst TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n"
}
] | Go | Apache License 2.0 | google/gvisor | Require pread/pwrite for splice file offsets
If there is an offset, the file must support pread/pwrite. See
fs/splice.c:do_splice.
PiperOrigin-RevId: 261944932 |
259,884 | 10.07.2019 01:41:06 | 14,400 | 000ed17d48a09821c23eddac5087197fd1692e14 | Add redirect from old URL.
Adds url redirect from old syscall docs url to new url
make server now runs the Go server and implements redirects.
make devserver runs the hugo dev server. | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -64,10 +64,14 @@ compatibility-docs: bin/generate-syscall-docs upstream/gvisor/bazel-bin/runsc/li\n.PHONY: compatibility-docs\n# Run a local content development server. Redirects will not be supported.\n-server: all-upstream compatibility-docs\n+devserver: all-upstream compatibility-docs\n$(HUGO) server -FD --port 8080\n.PHONY: server\n+server: website\n+ cd public/ && go run main.go --custom-domain localhost\n+.PHONY: server\n+\n# Deploy the website to App Engine.\ndeploy: $(APP_TARGET)\ncd public && $(GCLOUD) app deploy\n"
},
{
"change_type": "MODIFY",
"old_path": "cmd/gvisor-website/main.go",
"new_path": "cmd/gvisor-website/main.go",
"diff": "@@ -36,8 +36,11 @@ var redirects = map[string]string{\n\"/pr\": \"https://github.com/google/gvisor/pulls\",\n// Redirects to compatibility docs.\n- \"/c\": \"/docs/user_guide/compatibility\",\n- \"/c/linux/amd64\": \"/docs/user_guide/compatibility/linux/amd64\",\n+ \"/c\": \"/docs/user_guide/compatibility/\",\n+ \"/c/linux/amd64\": \"/docs/user_guide/compatibility/linux/amd64/\",\n+ // Redirect for old url\n+ \"/docs/user_guide/compatibility/amd64\": \"/docs/user_guide/compatibility/linux/amd64/\",\n+ \"/docs/user_guide/compatibility/amd64/\": \"/docs/user_guide/compatibility/linux/amd64/\",\n// Deprecated, but links continue to work.\n\"/cl\": \"https://gvisor-review.googlesource.com\",\n@@ -230,5 +233,6 @@ func main() {\nregisterRebuild(nil)\nregisterStatic(nil, *staticDir)\n+ log.Printf(\"Listening on %s...\", *addr)\nlog.Fatal(http.ListenAndServe(*addr, nil))\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add redirect from old URL.
- Adds url redirect from old syscall docs url to new url
- make server now runs the Go server and implements redirects.
- make devserver runs the hugo dev server. |
259,992 | 06.08.2019 23:25:28 | 25,200 | e70eafc9e5bb5b1ffd6fb7001c2c0d77a5368486 | Make loading container in a sandbox more robust | [
{
"change_type": "MODIFY",
"old_path": "runsc/container/container.go",
"new_path": "runsc/container/container.go",
"diff": "@@ -138,6 +138,34 @@ type Container struct {\nRootContainerDir string\n}\n+// loadSandbox loads all containers that belong to the sandbox with the given\n+// ID.\n+func loadSandbox(rootDir, id string) ([]*Container, error) {\n+ cids, err := List(rootDir)\n+ if err != nil {\n+ return nil, err\n+ }\n+\n+ // Load the container metadata.\n+ var containers []*Container\n+ for _, cid := range cids {\n+ container, err := Load(rootDir, cid)\n+ if err != nil {\n+ // Container file may not exist if it raced with creation/deletion or\n+ // directory was left behind. Load provides a snapshot in time, so it's\n+ // fine to skip it.\n+ if os.IsNotExist(err) {\n+ continue\n+ }\n+ return nil, fmt.Errorf(\"loading container %q: %v\", id, err)\n+ }\n+ if container.Sandbox.ID == id {\n+ containers = append(containers, container)\n+ }\n+ }\n+ return containers, nil\n+}\n+\n// Load loads a container with the given id from a metadata file. id may be an\n// abbreviation of the full container id, in which case Load loads the\n// container to which id unambiguously refers to.\n@@ -180,7 +208,7 @@ func Load(rootDir, id string) (*Container, error) {\n// If the status is \"Running\" or \"Created\", check that the sandbox\n// process still exists, and set it to Stopped if it does not.\n//\n- // This is inherently racey.\n+ // This is inherently racy.\nif c.Status == Running || c.Status == Created {\n// Check if the sandbox process is still running.\nif !c.isSandboxRunning() {\n@@ -237,8 +265,14 @@ func List(rootDir string) ([]string, error) {\n}\nvar out []string\nfor _, f := range fs {\n+ // Filter out directories that do no belong to a container.\n+ cid := f.Name()\n+ if validateID(cid) == nil {\n+ if _, err := os.Stat(filepath.Join(rootDir, cid, metadataFilename)); err == nil {\nout = append(out, f.Name())\n}\n+ }\n+ }\nreturn out, nil\n}\n@@ -1108,6 +1142,10 @@ func runInCgroup(cg *cgroup.Cgroup, fn func() error) error {\n// adjustOOMScoreAdj sets the oom_score_adj for the sandbox and all gofers.\n// oom_score_adj is set to the lowest oom_score_adj among the containers\n// running in the sandbox.\n+//\n+// TODO(gvisor.dev/issue/512): This call could race with other containers being\n+// created at the same time and end up setting the wrong oom_score_adj to the\n+// sandbox.\nfunc (c *Container) adjustOOMScoreAdj(conf *boot.Config) error {\n// If this container's OOMScoreAdj is nil then we can exit early as no\n// change should be made to oom_score_adj for the sandbox.\n@@ -1115,21 +1153,9 @@ func (c *Container) adjustOOMScoreAdj(conf *boot.Config) error {\nreturn nil\n}\n- ids, err := List(conf.RootDir)\n- if err != nil {\n- return err\n- }\n-\n- // Load the container metadata.\n- var containers []*Container\n- for _, id := range ids {\n- container, err := Load(conf.RootDir, id)\n+ containers, err := loadSandbox(conf.RootDir, c.Sandbox.ID)\nif err != nil {\n- return fmt.Errorf(\"loading container %q: %v\", id, err)\n- }\n- if container.Sandbox.ID == c.Sandbox.ID {\n- containers = append(containers, container)\n- }\n+ return fmt.Errorf(\"loading sandbox containers: %v\", err)\n}\n// Get the lowest score for all containers.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/multi_container_test.go",
"new_path": "runsc/container/multi_container_test.go",
"diff": "@@ -60,11 +60,14 @@ func createSpecs(cmds ...[]string) ([]*specs.Spec, []string) {\n}\nfunc startContainers(conf *boot.Config, specs []*specs.Spec, ids []string) ([]*Container, func(), error) {\n+ // Setup root dir if one hasn't been provided.\n+ if len(conf.RootDir) == 0 {\nrootDir, err := testutil.SetupRootDir()\nif err != nil {\nreturn nil, nil, fmt.Errorf(\"error creating root dir: %v\", err)\n}\nconf.RootDir = rootDir\n+ }\nvar containers []*Container\nvar bundles []string\n@@ -75,7 +78,7 @@ func startContainers(conf *boot.Config, specs []*specs.Spec, ids []string) ([]*C\nfor _, b := range bundles {\nos.RemoveAll(b)\n}\n- os.RemoveAll(rootDir)\n+ os.RemoveAll(conf.RootDir)\n}\nfor i, spec := range specs {\nbundleDir, err := testutil.SetupBundleDir(spec)\n@@ -1423,3 +1426,62 @@ func TestMultiContainerGoferKilled(t *testing.T) {\n}\n}\n}\n+\n+func TestMultiContainerLoadSandbox(t *testing.T) {\n+ sleep := []string{\"sleep\", \"100\"}\n+ specs, ids := createSpecs(sleep, sleep, sleep)\n+ conf := testutil.TestConfig()\n+\n+ // Create containers for the sandbox.\n+ wants, cleanup, err := startContainers(conf, specs, ids)\n+ if err != nil {\n+ t.Fatalf(\"error starting containers: %v\", err)\n+ }\n+ defer cleanup()\n+\n+ // Then create unrelated containers.\n+ for i := 0; i < 3; i++ {\n+ specs, ids = createSpecs(sleep, sleep, sleep)\n+ _, cleanup, err = startContainers(conf, specs, ids)\n+ if err != nil {\n+ t.Fatalf(\"error starting containers: %v\", err)\n+ }\n+ defer cleanup()\n+ }\n+\n+ // Create an unrelated directory under root.\n+ dir := filepath.Join(conf.RootDir, \"not-a-container\")\n+ if err := os.MkdirAll(dir, 0755); err != nil {\n+ t.Fatalf(\"os.MkdirAll(%q)=%v\", dir, err)\n+ }\n+\n+ // Create a valid but empty container directory.\n+ randomCID := testutil.UniqueContainerID()\n+ dir = filepath.Join(conf.RootDir, randomCID)\n+ if err := os.MkdirAll(dir, 0755); err != nil {\n+ t.Fatalf(\"os.MkdirAll(%q)=%v\", dir, err)\n+ }\n+\n+ // Load the sandbox and check that the correct containers were returned.\n+ id := wants[0].Sandbox.ID\n+ gots, err := loadSandbox(conf.RootDir, id)\n+ if err != nil {\n+ t.Fatalf(\"loadSandbox()=%v\", err)\n+ }\n+ wantIDs := make(map[string]struct{})\n+ for _, want := range wants {\n+ wantIDs[want.ID] = struct{}{}\n+ }\n+ for _, got := range gots {\n+ if got.Sandbox.ID != id {\n+ t.Errorf(\"wrong sandbox ID, got: %v, want: %v\", got.Sandbox.ID, id)\n+ }\n+ if _, ok := wantIDs[got.ID]; !ok {\n+ t.Errorf(\"wrong container ID, got: %v, wants: %v\", got.ID, wantIDs)\n+ }\n+ delete(wantIDs, got.ID)\n+ }\n+ if len(wantIDs) != 0 {\n+ t.Errorf(\"containers not found: %v\", wantIDs)\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/test/testutil/testutil.go",
"new_path": "runsc/test/testutil/testutil.go",
"diff": "@@ -189,11 +189,14 @@ func SetupRootDir() (string, error) {\n// SetupContainer creates a bundle and root dir for the container, generates a\n// test config, and writes the spec to config.json in the bundle dir.\nfunc SetupContainer(spec *specs.Spec, conf *boot.Config) (rootDir, bundleDir string, err error) {\n+ // Setup root dir if one hasn't been provided.\n+ if len(conf.RootDir) == 0 {\nrootDir, err = SetupRootDir()\nif err != nil {\nreturn \"\", \"\", err\n}\nconf.RootDir = rootDir\n+ }\nbundleDir, err = SetupBundleDir(spec)\nreturn rootDir, bundleDir, err\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Make loading container in a sandbox more robust
PiperOrigin-RevId: 262071646 |
259,992 | 07.08.2019 12:53:44 | 25,200 | 79cc4397fd99fbdd5c74ac5bb7804a463d7981d8 | Set gofer's OOM score adjustment
Updates | [
{
"change_type": "MODIFY",
"old_path": "runsc/container/container.go",
"new_path": "runsc/container/container.go",
"diff": "@@ -1176,30 +1176,16 @@ func (c *Container) adjustOOMScoreAdj(conf *boot.Config) error {\nreturn nil\n}\n- // Set oom_score_adj for the sandbox.\n+ // Set the lowest of all containers oom_score_adj to the sandbox.\nif err := setOOMScoreAdj(c.Sandbox.Pid, lowScore); err != nil {\nreturn fmt.Errorf(\"setting oom_score_adj for sandbox %q: %v\", c.Sandbox.ID, err)\n}\n- // Set the gofer's oom_score_adj to the minimum of -500 and the\n- // sandbox's oom_score_adj to better ensure that the sandbox is killed\n- // before the gofer.\n- //\n- // TODO(gvisor.dev/issue/601) Set oom_score_adj for the gofer to\n- // the same oom_score_adj as the sandbox.\n- goferScoreAdj := -500\n- if lowScore < goferScoreAdj {\n- goferScoreAdj = lowScore\n+ // Set container's oom_score_adj to the gofer since it is dedicated to the\n+ // container, in case the gofer uses up too much memory.\n+ if err := setOOMScoreAdj(c.GoferPid, *c.Spec.Process.OOMScoreAdj); err != nil {\n+ return fmt.Errorf(\"setting gofer oom_score_adj for container %q: %v\", c.ID, err)\n}\n-\n- // Set oom_score_adj for gofers for all containers in the sandbox.\n- for _, container := range containers {\n- err := setOOMScoreAdj(container.GoferPid, goferScoreAdj)\n- if err != nil {\n- return fmt.Errorf(\"setting oom_score_adj for container %q: %v\", container.ID, err)\n- }\n- }\n-\nreturn nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Set gofer's OOM score adjustment
Updates #512
PiperOrigin-RevId: 262195448 |
259,907 | 07.08.2019 15:23:19 | 25,200 | ad67e5a7a0869f475f923a0ce4c9446340c6a11a | ext: IterDirent unit tests. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/ext_test.go",
"new_path": "pkg/sentry/fs/ext/ext_test.go",
"diff": "@@ -18,6 +18,7 @@ import (\n\"fmt\"\n\"os\"\n\"path\"\n+ \"sort\"\n\"testing\"\n\"github.com/google/go-cmp/cmp\"\n@@ -79,6 +80,120 @@ func setUp(t *testing.T, imagePath string) (context.Context, *vfs.VirtualFilesys\nreturn ctx, vfsObj, &root, tearDown, nil\n}\n+// iterDirentsCb is a simple callback which just keeps adding the dirents to an\n+// internal list. Implements vfs.IterDirentsCallback.\n+type iterDirentsCb struct {\n+ dirents []vfs.Dirent\n+}\n+\n+// Compiles only if iterDirentCb implements vfs.IterDirentsCallback.\n+var _ vfs.IterDirentsCallback = (*iterDirentsCb)(nil)\n+\n+// newIterDirentsCb is the iterDirent\n+func newIterDirentCb() *iterDirentsCb {\n+ return &iterDirentsCb{dirents: make([]vfs.Dirent, 0)}\n+}\n+\n+// Handle implements vfs.IterDirentsCallback.Handle.\n+func (cb *iterDirentsCb) Handle(dirent vfs.Dirent) bool {\n+ cb.dirents = append(cb.dirents, dirent)\n+ return true\n+}\n+\n+// TestIterDirents tests the FileDescriptionImpl.IterDirents functionality.\n+func TestIterDirents(t *testing.T) {\n+ type iterDirentTest struct {\n+ name string\n+ image string\n+ path string\n+ want []vfs.Dirent\n+ }\n+\n+ wantDirents := []vfs.Dirent{\n+ vfs.Dirent{\n+ Name: \".\",\n+ Type: linux.DT_DIR,\n+ },\n+ vfs.Dirent{\n+ Name: \"..\",\n+ Type: linux.DT_DIR,\n+ },\n+ vfs.Dirent{\n+ Name: \"lost+found\",\n+ Type: linux.DT_DIR,\n+ },\n+ vfs.Dirent{\n+ Name: \"file.txt\",\n+ Type: linux.DT_REG,\n+ },\n+ vfs.Dirent{\n+ Name: \"bigfile.txt\",\n+ Type: linux.DT_REG,\n+ },\n+ vfs.Dirent{\n+ Name: \"symlink.txt\",\n+ Type: linux.DT_LNK,\n+ },\n+ }\n+ tests := []iterDirentTest{\n+ {\n+ name: \"ext4 root dir iteration\",\n+ image: ext4ImagePath,\n+ path: \"/\",\n+ want: wantDirents,\n+ },\n+ {\n+ name: \"ext3 root dir iteration\",\n+ image: ext3ImagePath,\n+ path: \"/\",\n+ want: wantDirents,\n+ },\n+ {\n+ name: \"ext2 root dir iteration\",\n+ image: ext2ImagePath,\n+ path: \"/\",\n+ want: wantDirents,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ ctx, vfsfs, root, tearDown, err := setUp(t, test.image)\n+ if err != nil {\n+ t.Fatalf(\"setUp failed: %v\", err)\n+ }\n+ defer tearDown()\n+\n+ fd, err := vfsfs.OpenAt(\n+ ctx,\n+ auth.CredentialsFromContext(ctx),\n+ &vfs.PathOperation{Root: *root, Start: *root, Pathname: test.path},\n+ &vfs.OpenOptions{},\n+ )\n+ if err != nil {\n+ t.Fatalf(\"vfsfs.OpenAt failed: %v\", err)\n+ }\n+\n+ cb := &iterDirentsCb{}\n+ if err = fd.Impl().IterDirents(ctx, cb); err != nil {\n+ t.Fatalf(\"dir fd.IterDirents() failed: %v\", err)\n+ }\n+\n+ sort.Slice(cb.dirents, func(i int, j int) bool { return cb.dirents[i].Name < cb.dirents[j].Name })\n+ sort.Slice(test.want, func(i int, j int) bool { return test.want[i].Name < test.want[j].Name })\n+\n+ // Ignore the inode number and offset of dirents because those are likely to\n+ // change as the underlying image changes.\n+ cmpIgnoreFields := cmp.FilterPath(func(p cmp.Path) bool {\n+ return p.String() == \"Ino\" || p.String() == \"Off\"\n+ }, cmp.Ignore())\n+ if diff := cmp.Diff(cb.dirents, test.want, cmpIgnoreFields); diff != \"\" {\n+ t.Errorf(\"dirents mismatch (-want +got):\\n%s\", diff)\n+ }\n+ })\n+ }\n+}\n+\n// TestRootDir tests that the root directory inode is correctly initialized and\n// returned from setUp.\nfunc TestRootDir(t *testing.T) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | ext: IterDirent unit tests.
PiperOrigin-RevId: 262226761 |
259,907 | 07.08.2019 16:43:08 | 25,200 | 3b368cabf9a6c08a19724a1a0f2f52c16461b7a9 | ext: Read unit tests. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/BUILD",
"new_path": "pkg/sentry/fs/ext/BUILD",
"diff": "@@ -76,6 +76,7 @@ go_test(\n\"//pkg/sentry/context/contexttest\",\n\"//pkg/sentry/fs/ext/disklayout\",\n\"//pkg/sentry/kernel/auth\",\n+ \"//pkg/sentry/usermem\",\n\"//pkg/sentry/vfs\",\n\"//runsc/test/testutil\",\n\"@com_github_google_go-cmp//cmp:go_default_library\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/ext_test.go",
"new_path": "pkg/sentry/fs/ext/ext_test.go",
"diff": "@@ -16,6 +16,7 @@ package ext\nimport (\n\"fmt\"\n+ \"io\"\n\"os\"\n\"path\"\n\"sort\"\n@@ -27,6 +28,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/context/contexttest\"\n\"gvisor.dev/gvisor/pkg/sentry/fs/ext/disklayout\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/usermem\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/runsc/test/testutil\"\n@@ -80,6 +82,107 @@ func setUp(t *testing.T, imagePath string) (context.Context, *vfs.VirtualFilesys\nreturn ctx, vfsObj, &root, tearDown, nil\n}\n+// TestRead tests the read functionality for vfs file descriptions.\n+func TestRead(t *testing.T) {\n+ type readTest struct {\n+ name string\n+ image string\n+ absPath string\n+ }\n+\n+ tests := []readTest{\n+ {\n+ name: \"ext4 read small file\",\n+ image: ext4ImagePath,\n+ absPath: \"/file.txt\",\n+ },\n+ {\n+ name: \"ext3 read small file\",\n+ image: ext3ImagePath,\n+ absPath: \"/file.txt\",\n+ },\n+ {\n+ name: \"ext2 read small file\",\n+ image: ext2ImagePath,\n+ absPath: \"/file.txt\",\n+ },\n+ {\n+ name: \"ext4 read big file\",\n+ image: ext4ImagePath,\n+ absPath: \"/bigfile.txt\",\n+ },\n+ {\n+ name: \"ext3 read big file\",\n+ image: ext3ImagePath,\n+ absPath: \"/bigfile.txt\",\n+ },\n+ {\n+ name: \"ext2 read big file\",\n+ image: ext2ImagePath,\n+ absPath: \"/bigfile.txt\",\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ ctx, vfsfs, root, tearDown, err := setUp(t, test.image)\n+ if err != nil {\n+ t.Fatalf(\"setUp failed: %v\", err)\n+ }\n+ defer tearDown()\n+\n+ fd, err := vfsfs.OpenAt(\n+ ctx,\n+ auth.CredentialsFromContext(ctx),\n+ &vfs.PathOperation{Root: *root, Start: *root, Pathname: test.absPath},\n+ &vfs.OpenOptions{},\n+ )\n+ if err != nil {\n+ t.Fatalf(\"vfsfs.OpenAt failed: %v\", err)\n+ }\n+\n+ // Get a local file descriptor and compare its functionality with a vfs file\n+ // description for the same file.\n+ localFile, err := testutil.FindFile(path.Join(assetsDir, test.absPath))\n+ if err != nil {\n+ t.Fatalf(\"testutil.FindFile failed for %s: %v\", test.absPath, err)\n+ }\n+\n+ f, err := os.Open(localFile)\n+ if err != nil {\n+ t.Fatalf(\"os.Open failed for %s: %v\", localFile, err)\n+ }\n+ defer f.Close()\n+\n+ // Read the entire file by reading one byte repeatedly. Doing this stress\n+ // tests the underlying file reader implementation.\n+ got := make([]byte, 1)\n+ want := make([]byte, 1)\n+ for {\n+ n, err := f.Read(want)\n+ fd.Impl().Read(ctx, usermem.BytesIOSequence(got), vfs.ReadOptions{})\n+\n+ if diff := cmp.Diff(got, want); diff != \"\" {\n+ t.Errorf(\"file data mismatch (-want +got):\\n%s\", diff)\n+ }\n+\n+ // Make sure there is no more file data left after getting EOF.\n+ if n == 0 || err == io.EOF {\n+ if n, _ := fd.Impl().Read(ctx, usermem.BytesIOSequence(got), vfs.ReadOptions{}); n != 0 {\n+ t.Errorf(\"extra unexpected file data in file %s in image %s\", test.absPath, test.image)\n+ }\n+\n+ break\n+ }\n+\n+ if err != nil {\n+ t.Fatalf(\"read failed: %v\", err)\n+ }\n+ }\n+ })\n+ }\n+}\n+\n// iterDirentsCb is a simple callback which just keeps adding the dirents to an\n// internal list. Implements vfs.IterDirentsCallback.\ntype iterDirentsCb struct {\n"
}
] | Go | Apache License 2.0 | google/gvisor | ext: Read unit tests.
PiperOrigin-RevId: 262242410 |
259,907 | 07.08.2019 17:19:43 | 25,200 | 40d6d8c15b7deb8c1df1d8e764b014ca7140873e | ext: StatAt unit tests. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/ext_test.go",
"new_path": "pkg/sentry/fs/ext/ext_test.go",
"diff": "@@ -23,6 +23,7 @@ import (\n\"testing\"\n\"github.com/google/go-cmp/cmp\"\n+ \"github.com/google/go-cmp/cmp/cmpopts\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/sentry/context\"\n\"gvisor.dev/gvisor/pkg/sentry/context/contexttest\"\n@@ -82,6 +83,181 @@ func setUp(t *testing.T, imagePath string) (context.Context, *vfs.VirtualFilesys\nreturn ctx, vfsObj, &root, tearDown, nil\n}\n+// TestStatAt tests filesystem.StatAt functionality.\n+func TestStatAt(t *testing.T) {\n+ type statAtTest struct {\n+ name string\n+ image string\n+ path string\n+ want linux.Statx\n+ }\n+\n+ tests := []statAtTest{\n+ {\n+ name: \"ext4 statx small file\",\n+ image: ext4ImagePath,\n+ path: \"/file.txt\",\n+ want: linux.Statx{\n+ Blksize: 0x400,\n+ Nlink: 1,\n+ UID: 0,\n+ GID: 0,\n+ Mode: 0644 | linux.ModeRegular,\n+ Size: 13,\n+ },\n+ },\n+ {\n+ name: \"ext3 statx small file\",\n+ image: ext3ImagePath,\n+ path: \"/file.txt\",\n+ want: linux.Statx{\n+ Blksize: 0x400,\n+ Nlink: 1,\n+ UID: 0,\n+ GID: 0,\n+ Mode: 0644 | linux.ModeRegular,\n+ Size: 13,\n+ },\n+ },\n+ {\n+ name: \"ext2 statx small file\",\n+ image: ext2ImagePath,\n+ path: \"/file.txt\",\n+ want: linux.Statx{\n+ Blksize: 0x400,\n+ Nlink: 1,\n+ UID: 0,\n+ GID: 0,\n+ Mode: 0644 | linux.ModeRegular,\n+ Size: 13,\n+ },\n+ },\n+ {\n+ name: \"ext4 statx big file\",\n+ image: ext4ImagePath,\n+ path: \"/bigfile.txt\",\n+ want: linux.Statx{\n+ Blksize: 0x400,\n+ Nlink: 1,\n+ UID: 0,\n+ GID: 0,\n+ Mode: 0644 | linux.ModeRegular,\n+ Size: 13042,\n+ },\n+ },\n+ {\n+ name: \"ext3 statx big file\",\n+ image: ext3ImagePath,\n+ path: \"/bigfile.txt\",\n+ want: linux.Statx{\n+ Blksize: 0x400,\n+ Nlink: 1,\n+ UID: 0,\n+ GID: 0,\n+ Mode: 0644 | linux.ModeRegular,\n+ Size: 13042,\n+ },\n+ },\n+ {\n+ name: \"ext2 statx big file\",\n+ image: ext2ImagePath,\n+ path: \"/bigfile.txt\",\n+ want: linux.Statx{\n+ Blksize: 0x400,\n+ Nlink: 1,\n+ UID: 0,\n+ GID: 0,\n+ Mode: 0644 | linux.ModeRegular,\n+ Size: 13042,\n+ },\n+ },\n+ {\n+ name: \"ext4 statx symlink file\",\n+ image: ext4ImagePath,\n+ path: \"/symlink.txt\",\n+ want: linux.Statx{\n+ Blksize: 0x400,\n+ Nlink: 1,\n+ UID: 0,\n+ GID: 0,\n+ Mode: 0777 | linux.ModeSymlink,\n+ Size: 8,\n+ },\n+ },\n+ {\n+ name: \"ext3 statx symlink file\",\n+ image: ext3ImagePath,\n+ path: \"/symlink.txt\",\n+ want: linux.Statx{\n+ Blksize: 0x400,\n+ Nlink: 1,\n+ UID: 0,\n+ GID: 0,\n+ Mode: 0777 | linux.ModeSymlink,\n+ Size: 8,\n+ },\n+ },\n+ {\n+ name: \"ext2 statx symlink file\",\n+ image: ext2ImagePath,\n+ path: \"/symlink.txt\",\n+ want: linux.Statx{\n+ Blksize: 0x400,\n+ Nlink: 1,\n+ UID: 0,\n+ GID: 0,\n+ Mode: 0777 | linux.ModeSymlink,\n+ Size: 8,\n+ },\n+ },\n+ }\n+\n+ // Ignore the fields that are not supported by filesystem.StatAt yet and\n+ // those which are likely to change as the image does.\n+ ignoredFields := map[string]bool{\n+ \"Attributes\": true,\n+ \"AttributesMask\": true,\n+ \"Atime\": true,\n+ \"Blocks\": true,\n+ \"Btime\": true,\n+ \"Ctime\": true,\n+ \"DevMajor\": true,\n+ \"DevMinor\": true,\n+ \"Ino\": true,\n+ \"Mask\": true,\n+ \"Mtime\": true,\n+ \"RdevMajor\": true,\n+ \"RdevMinor\": true,\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ ctx, vfsfs, root, tearDown, err := setUp(t, test.image)\n+ if err != nil {\n+ t.Fatalf(\"setUp failed: %v\", err)\n+ }\n+ defer tearDown()\n+\n+ got, err := vfsfs.StatAt(ctx,\n+ auth.CredentialsFromContext(ctx),\n+ &vfs.PathOperation{Root: *root, Start: *root, Pathname: test.path},\n+ &vfs.StatOptions{},\n+ )\n+ if err != nil {\n+ t.Fatalf(\"vfsfs.StatAt failed for file %s in image %s: %v\", test.path, test.image, err)\n+ }\n+\n+ cmpIgnoreFields := cmp.FilterPath(func(p cmp.Path) bool {\n+ _, ok := ignoredFields[p.String()]\n+ return ok\n+ }, cmp.Ignore())\n+ if diff := cmp.Diff(got, test.want, cmpIgnoreFields, cmpopts.IgnoreUnexported(linux.Statx{})); diff != \"\" {\n+ t.Errorf(\"stat mismatch (-want +got):\\n%s\", diff)\n+ }\n+ })\n+ }\n+}\n+\n// TestRead tests the read functionality for vfs file descriptions.\nfunc TestRead(t *testing.T) {\ntype readTest struct {\n"
}
] | Go | Apache License 2.0 | google/gvisor | ext: StatAt unit tests.
PiperOrigin-RevId: 262249166 |
259,907 | 07.08.2019 19:12:48 | 25,200 | 08cd5e1d368716f262ba9c31d94b1d7a29dbc5cf | ext: Seek unit tests. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/BUILD",
"new_path": "pkg/sentry/fs/ext/BUILD",
"diff": "@@ -78,6 +78,7 @@ go_test(\n\"//pkg/sentry/kernel/auth\",\n\"//pkg/sentry/usermem\",\n\"//pkg/sentry/vfs\",\n+ \"//pkg/syserror\",\n\"//runsc/test/testutil\",\n\"@com_github_google_go-cmp//cmp:go_default_library\",\n\"@com_github_google_go-cmp//cmp/cmpopts:go_default_library\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/directory.go",
"new_path": "pkg/sentry/fs/ext/directory.go",
"diff": "@@ -217,7 +217,9 @@ func (fd *directoryFD) Seek(ctx context.Context, offset int64, whence int32) (in\ndefer dir.mu.Unlock()\n// Find resulting offset.\n+ if whence == linux.SEEK_CUR {\noffset += fd.off\n+ }\nif offset < 0 {\n// lseek(2) specifies that EINVAL should be returned if the resulting offset\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/ext/ext_test.go",
"new_path": "pkg/sentry/fs/ext/ext_test.go",
"diff": "@@ -31,6 +31,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/usermem\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n\"gvisor.dev/gvisor/runsc/test/testutil\"\n)\n@@ -83,6 +84,125 @@ func setUp(t *testing.T, imagePath string) (context.Context, *vfs.VirtualFilesys\nreturn ctx, vfsObj, &root, tearDown, nil\n}\n+// TODO(b/134676337): Test vfs.FilesystemImpl.ReadlinkAt and\n+// vfs.FilesystemImpl.StatFSAt which are not implemented in\n+// vfs.VirtualFilesystem yet.\n+\n+// TestSeek tests vfs.FileDescriptionImpl.Seek functionality.\n+func TestSeek(t *testing.T) {\n+ type seekTest struct {\n+ name string\n+ image string\n+ path string\n+ }\n+\n+ tests := []seekTest{\n+ {\n+ name: \"ext4 root dir seek\",\n+ image: ext4ImagePath,\n+ path: \"/\",\n+ },\n+ {\n+ name: \"ext3 root dir seek\",\n+ image: ext3ImagePath,\n+ path: \"/\",\n+ },\n+ {\n+ name: \"ext2 root dir seek\",\n+ image: ext2ImagePath,\n+ path: \"/\",\n+ },\n+ {\n+ name: \"ext4 reg file seek\",\n+ image: ext4ImagePath,\n+ path: \"/file.txt\",\n+ },\n+ {\n+ name: \"ext3 reg file seek\",\n+ image: ext3ImagePath,\n+ path: \"/file.txt\",\n+ },\n+ {\n+ name: \"ext2 reg file seek\",\n+ image: ext2ImagePath,\n+ path: \"/file.txt\",\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ ctx, vfsfs, root, tearDown, err := setUp(t, test.image)\n+ if err != nil {\n+ t.Fatalf(\"setUp failed: %v\", err)\n+ }\n+ defer tearDown()\n+\n+ fd, err := vfsfs.OpenAt(\n+ ctx,\n+ auth.CredentialsFromContext(ctx),\n+ &vfs.PathOperation{Root: *root, Start: *root, Pathname: test.path},\n+ &vfs.OpenOptions{},\n+ )\n+ if err != nil {\n+ t.Fatalf(\"vfsfs.OpenAt failed: %v\", err)\n+ }\n+\n+ if n, err := fd.Impl().Seek(ctx, 0, linux.SEEK_SET); n != 0 || err != nil {\n+ t.Errorf(\"expected seek position 0, got %d and error %v\", n, err)\n+ }\n+\n+ stat, err := fd.Impl().Stat(ctx, vfs.StatOptions{})\n+ if err != nil {\n+ t.Errorf(\"fd.stat failed for file %s in image %s: %v\", test.path, test.image, err)\n+ }\n+\n+ // We should be able to seek beyond the end of file.\n+ size := int64(stat.Size)\n+ if n, err := fd.Impl().Seek(ctx, size, linux.SEEK_SET); n != size || err != nil {\n+ t.Errorf(\"expected seek position %d, got %d and error %v\", size, n, err)\n+ }\n+\n+ // EINVAL should be returned if the resulting offset is negative.\n+ if _, err := fd.Impl().Seek(ctx, -1, linux.SEEK_SET); err != syserror.EINVAL {\n+ t.Errorf(\"expected error EINVAL but got %v\", err)\n+ }\n+\n+ if n, err := fd.Impl().Seek(ctx, 3, linux.SEEK_CUR); n != size+3 || err != nil {\n+ t.Errorf(\"expected seek position %d, got %d and error %v\", size+3, n, err)\n+ }\n+\n+ // Make sure negative offsets work with SEEK_CUR.\n+ if n, err := fd.Impl().Seek(ctx, -2, linux.SEEK_CUR); n != size+1 || err != nil {\n+ t.Errorf(\"expected seek position %d, got %d and error %v\", size+1, n, err)\n+ }\n+\n+ // EINVAL should be returned if the resulting offset is negative.\n+ if _, err := fd.Impl().Seek(ctx, -(size + 2), linux.SEEK_CUR); err != syserror.EINVAL {\n+ t.Errorf(\"expected error EINVAL but got %v\", err)\n+ }\n+\n+ // Make sure SEEK_END works with regular files.\n+ switch fd.Impl().(type) {\n+ case *regularFileFD:\n+ // Seek back to 0.\n+ if n, err := fd.Impl().Seek(ctx, -size, linux.SEEK_END); n != 0 || err != nil {\n+ t.Errorf(\"expected seek position %d, got %d and error %v\", 0, n, err)\n+ }\n+\n+ // Seek forward beyond EOF.\n+ if n, err := fd.Impl().Seek(ctx, 1, linux.SEEK_END); n != size+1 || err != nil {\n+ t.Errorf(\"expected seek position %d, got %d and error %v\", size+1, n, err)\n+ }\n+\n+ // EINVAL should be returned if the resulting offset is negative.\n+ if _, err := fd.Impl().Seek(ctx, -(size + 1), linux.SEEK_END); err != syserror.EINVAL {\n+ t.Errorf(\"expected error EINVAL but got %v\", err)\n+ }\n+ }\n+ })\n+ }\n+}\n+\n// TestStatAt tests filesystem.StatAt functionality.\nfunc TestStatAt(t *testing.T) {\ntype statAtTest struct {\n"
}
] | Go | Apache License 2.0 | google/gvisor | ext: Seek unit tests.
PiperOrigin-RevId: 262264674 |
259,885 | 08.08.2019 11:45:33 | 25,200 | 06102af65ad2d0e5a89c5e7dfe281afd5346ed4f | memfs fixes.
Unexport Filesystem/Dentry/Inode.
Support SEEK_CUR in directoryFD.Seek().
Hold Filesystem.mu before touching directoryFD.off in
directoryFD.Seek().
Remove deleted Dentries from their parent directory.childLists.
Remove invalid FIXMEs. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/memfs/BUILD",
"new_path": "pkg/sentry/fsimpl/memfs/BUILD",
"diff": "@@ -11,8 +11,8 @@ go_template_instance(\nprefix = \"dentry\",\ntemplate = \"//pkg/ilist:generic_list\",\ntypes = {\n- \"Element\": \"*Dentry\",\n- \"Linker\": \"*Dentry\",\n+ \"Element\": \"*dentry\",\n+ \"Linker\": \"*dentry\",\n},\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/memfs/directory.go",
"new_path": "pkg/sentry/fsimpl/memfs/directory.go",
"diff": "@@ -23,23 +23,23 @@ import (\n)\ntype directory struct {\n- inode Inode\n+ inode inode\n// childList is a list containing (1) child Dentries and (2) fake Dentries\n// (with inode == nil) that represent the iteration position of\n// directoryFDs. childList is used to support directoryFD.IterDirents()\n- // efficiently. childList is protected by Filesystem.mu.\n+ // efficiently. childList is protected by filesystem.mu.\nchildList dentryList\n}\n-func (fs *Filesystem) newDirectory(creds *auth.Credentials, mode uint16) *Inode {\n+func (fs *filesystem) newDirectory(creds *auth.Credentials, mode uint16) *inode {\ndir := &directory{}\ndir.inode.init(dir, fs, creds, mode)\ndir.inode.nlink = 2 // from \".\" and parent directory or \"..\" for root\nreturn &dir.inode\n}\n-func (i *Inode) isDir() bool {\n+func (i *inode) isDir() bool {\n_, ok := i.impl.(*directory)\nreturn ok\n}\n@@ -48,8 +48,8 @@ type directoryFD struct {\nfileDescription\nvfs.DirectoryFileDescriptionDefaultImpl\n- // Protected by Filesystem.mu.\n- iter *Dentry\n+ // Protected by filesystem.mu.\n+ iter *dentry\noff int64\n}\n@@ -68,7 +68,7 @@ func (fd *directoryFD) Release() {\n// IterDirents implements vfs.FileDescriptionImpl.IterDirents.\nfunc (fd *directoryFD) IterDirents(ctx context.Context, cb vfs.IterDirentsCallback) error {\nfs := fd.filesystem()\n- d := fd.vfsfd.VirtualDentry().Dentry()\n+ vfsd := fd.vfsfd.VirtualDentry().Dentry()\nfs.mu.Lock()\ndefer fs.mu.Unlock()\n@@ -77,7 +77,7 @@ func (fd *directoryFD) IterDirents(ctx context.Context, cb vfs.IterDirentsCallba\nif !cb.Handle(vfs.Dirent{\nName: \".\",\nType: linux.DT_DIR,\n- Ino: d.Impl().(*Dentry).inode.ino,\n+ Ino: vfsd.Impl().(*dentry).inode.ino,\nOff: 0,\n}) {\nreturn nil\n@@ -85,7 +85,7 @@ func (fd *directoryFD) IterDirents(ctx context.Context, cb vfs.IterDirentsCallba\nfd.off++\n}\nif fd.off == 1 {\n- parentInode := d.ParentOrSelf().Impl().(*Dentry).inode\n+ parentInode := vfsd.ParentOrSelf().Impl().(*dentry).inode\nif !cb.Handle(vfs.Dirent{\nName: \"..\",\nType: parentInode.direntType(),\n@@ -97,12 +97,12 @@ func (fd *directoryFD) IterDirents(ctx context.Context, cb vfs.IterDirentsCallba\nfd.off++\n}\n- dir := d.Impl().(*Dentry).inode.impl.(*directory)\n- var child *Dentry\n+ dir := vfsd.Impl().(*dentry).inode.impl.(*directory)\n+ var child *dentry\nif fd.iter == nil {\n// Start iteration at the beginning of dir.\nchild = dir.childList.Front()\n- fd.iter = &Dentry{}\n+ fd.iter = &dentry{}\n} else {\n// Continue iteration from where we left off.\nchild = fd.iter.Next()\n@@ -130,32 +130,41 @@ func (fd *directoryFD) IterDirents(ctx context.Context, cb vfs.IterDirentsCallba\n// Seek implements vfs.FileDescriptionImpl.Seek.\nfunc (fd *directoryFD) Seek(ctx context.Context, offset int64, whence int32) (int64, error) {\n- if whence != linux.SEEK_SET {\n- // TODO: Linux also allows SEEK_CUR.\n+ fs := fd.filesystem()\n+ fs.mu.Lock()\n+ defer fs.mu.Unlock()\n+\n+ switch whence {\n+ case linux.SEEK_SET:\n+ // Use offset as given.\n+ case linux.SEEK_CUR:\n+ offset += fd.off\n+ default:\nreturn 0, syserror.EINVAL\n}\nif offset < 0 {\nreturn 0, syserror.EINVAL\n}\n+ // If the offset isn't changing (e.g. due to lseek(0, SEEK_CUR)), don't\n+ // seek even if doing so might reposition the iterator due to concurrent\n+ // mutation of the directory. Compare fs/libfs.c:dcache_dir_lseek().\n+ if fd.off == offset {\n+ return offset, nil\n+ }\n+\nfd.off = offset\n// Compensate for \".\" and \"..\".\n- var remChildren int64\n- if offset < 2 {\n- remChildren = 0\n- } else {\n+ remChildren := int64(0)\n+ if offset >= 2 {\nremChildren = offset - 2\n}\n- fs := fd.filesystem()\ndir := fd.inode().impl.(*directory)\n- fs.mu.Lock()\n- defer fs.mu.Unlock()\n-\n// Ensure that fd.iter exists and is not linked into dir.childList.\nif fd.iter == nil {\n- fd.iter = &Dentry{}\n+ fd.iter = &dentry{}\n} else {\ndir.childList.Remove(fd.iter)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/memfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/memfs/filesystem.go",
"diff": "@@ -28,9 +28,9 @@ import (\n//\n// stepLocked is loosely analogous to fs/namei.c:walk_component().\n//\n-// Preconditions: Filesystem.mu must be locked. !rp.Done(). inode ==\n-// vfsd.Impl().(*Dentry).inode.\n-func stepLocked(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, inode *Inode) (*vfs.Dentry, *Inode, error) {\n+// Preconditions: filesystem.mu must be locked. !rp.Done(). inode ==\n+// vfsd.Impl().(*dentry).inode.\n+func stepLocked(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, inode *inode) (*vfs.Dentry, *inode, error) {\nif !inode.isDir() {\nreturn nil, nil, syserror.ENOTDIR\n}\n@@ -47,7 +47,7 @@ afterSymlink:\n// not in the Dentry tree, it doesn't exist.\nreturn nil, nil, syserror.ENOENT\n}\n- nextInode := nextVFSD.Impl().(*Dentry).inode\n+ nextInode := nextVFSD.Impl().(*dentry).inode\nif symlink, ok := nextInode.impl.(*symlink); ok && rp.ShouldFollowSymlink() {\n// TODO: symlink traversals update access time\nif err := rp.HandleSymlink(symlink.target); err != nil {\n@@ -64,10 +64,10 @@ afterSymlink:\n// walkExistingLocked is loosely analogous to Linux's\n// fs/namei.c:path_lookupat().\n//\n-// Preconditions: Filesystem.mu must be locked.\n-func walkExistingLocked(rp *vfs.ResolvingPath) (*vfs.Dentry, *Inode, error) {\n+// Preconditions: filesystem.mu must be locked.\n+func walkExistingLocked(rp *vfs.ResolvingPath) (*vfs.Dentry, *inode, error) {\nvfsd := rp.Start()\n- inode := vfsd.Impl().(*Dentry).inode\n+ inode := vfsd.Impl().(*dentry).inode\nfor !rp.Done() {\nvar err error\nvfsd, inode, err = stepLocked(rp, vfsd, inode)\n@@ -88,10 +88,10 @@ func walkExistingLocked(rp *vfs.ResolvingPath) (*vfs.Dentry, *Inode, error) {\n// walkParentDirLocked is loosely analogous to Linux's\n// fs/namei.c:path_parentat().\n//\n-// Preconditions: Filesystem.mu must be locked. !rp.Done().\n-func walkParentDirLocked(rp *vfs.ResolvingPath) (*vfs.Dentry, *Inode, error) {\n+// Preconditions: filesystem.mu must be locked. !rp.Done().\n+func walkParentDirLocked(rp *vfs.ResolvingPath) (*vfs.Dentry, *inode, error) {\nvfsd := rp.Start()\n- inode := vfsd.Impl().(*Dentry).inode\n+ inode := vfsd.Impl().(*dentry).inode\nfor !rp.Final() {\nvar err error\nvfsd, inode, err = stepLocked(rp, vfsd, inode)\n@@ -108,9 +108,9 @@ func walkParentDirLocked(rp *vfs.ResolvingPath) (*vfs.Dentry, *Inode, error) {\n// checkCreateLocked checks that a file named rp.Component() may be created in\n// directory parentVFSD, then returns rp.Component().\n//\n-// Preconditions: Filesystem.mu must be locked. parentInode ==\n-// parentVFSD.Impl().(*Dentry).inode. parentInode.isDir() == true.\n-func checkCreateLocked(rp *vfs.ResolvingPath, parentVFSD *vfs.Dentry, parentInode *Inode) (string, error) {\n+// Preconditions: filesystem.mu must be locked. parentInode ==\n+// parentVFSD.Impl().(*dentry).inode. parentInode.isDir() == true.\n+func checkCreateLocked(rp *vfs.ResolvingPath, parentVFSD *vfs.Dentry, parentInode *inode) (string, error) {\nif err := parentInode.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec, true); err != nil {\nreturn \"\", err\n}\n@@ -144,7 +144,7 @@ func checkDeleteLocked(vfsd *vfs.Dentry) error {\n}\n// GetDentryAt implements vfs.FilesystemImpl.GetDentryAt.\n-func (fs *Filesystem) GetDentryAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.GetDentryOptions) (*vfs.Dentry, error) {\n+func (fs *filesystem) GetDentryAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.GetDentryOptions) (*vfs.Dentry, error) {\nfs.mu.RLock()\ndefer fs.mu.RUnlock()\nvfsd, inode, err := walkExistingLocked(rp)\n@@ -164,7 +164,7 @@ func (fs *Filesystem) GetDentryAt(ctx context.Context, rp *vfs.ResolvingPath, op\n}\n// LinkAt implements vfs.FilesystemImpl.LinkAt.\n-func (fs *Filesystem) LinkAt(ctx context.Context, rp *vfs.ResolvingPath, vd vfs.VirtualDentry) error {\n+func (fs *filesystem) LinkAt(ctx context.Context, rp *vfs.ResolvingPath, vd vfs.VirtualDentry) error {\nif rp.Done() {\nreturn syserror.EEXIST\n}\n@@ -185,7 +185,7 @@ func (fs *Filesystem) LinkAt(ctx context.Context, rp *vfs.ResolvingPath, vd vfs.\nreturn err\n}\ndefer rp.Mount().EndWrite()\n- d := vd.Dentry().Impl().(*Dentry)\n+ d := vd.Dentry().Impl().(*dentry)\nif d.inode.isDir() {\nreturn syserror.EPERM\n}\n@@ -197,7 +197,7 @@ func (fs *Filesystem) LinkAt(ctx context.Context, rp *vfs.ResolvingPath, vd vfs.\n}\n// MkdirAt implements vfs.FilesystemImpl.MkdirAt.\n-func (fs *Filesystem) MkdirAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.MkdirOptions) error {\n+func (fs *filesystem) MkdirAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.MkdirOptions) error {\nif rp.Done() {\nreturn syserror.EEXIST\n}\n@@ -223,7 +223,7 @@ func (fs *Filesystem) MkdirAt(ctx context.Context, rp *vfs.ResolvingPath, opts v\n}\n// MknodAt implements vfs.FilesystemImpl.MknodAt.\n-func (fs *Filesystem) MknodAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.MknodOptions) error {\n+func (fs *filesystem) MknodAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.MknodOptions) error {\nif rp.Done() {\nreturn syserror.EEXIST\n}\n@@ -246,7 +246,7 @@ func (fs *Filesystem) MknodAt(ctx context.Context, rp *vfs.ResolvingPath, opts v\n}\n// OpenAt implements vfs.FilesystemImpl.OpenAt.\n-func (fs *Filesystem) OpenAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n+func (fs *filesystem) OpenAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n// Filter out flags that are not supported by memfs. O_DIRECTORY and\n// O_NOFOLLOW have no effect here (they're handled by VFS by setting\n// appropriate bits in rp), but are returned by\n@@ -265,11 +265,10 @@ func (fs *Filesystem) OpenAt(ctx context.Context, rp *vfs.ResolvingPath, opts vf\nmustCreate := opts.Flags&linux.O_EXCL != 0\nvfsd := rp.Start()\n- inode := vfsd.Impl().(*Dentry).inode\n+ inode := vfsd.Impl().(*dentry).inode\nfs.mu.Lock()\ndefer fs.mu.Unlock()\nif rp.Done() {\n- // FIXME: ???\nif rp.MustBeDir() {\nreturn nil, syserror.EISDIR\n}\n@@ -327,7 +326,7 @@ afterTrailingSymlink:\nif mustCreate {\nreturn nil, syserror.EEXIST\n}\n- childInode := childVFSD.Impl().(*Dentry).inode\n+ childInode := childVFSD.Impl().(*dentry).inode\nif symlink, ok := childInode.impl.(*symlink); ok && rp.ShouldFollowSymlink() {\n// TODO: symlink traversals update access time\nif err := rp.HandleSymlink(symlink.target); err != nil {\n@@ -340,7 +339,7 @@ afterTrailingSymlink:\nreturn childInode.open(rp, childVFSD, opts.Flags, false)\n}\n-func (i *Inode) open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, flags uint32, afterCreate bool) (*vfs.FileDescription, error) {\n+func (i *inode) open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, flags uint32, afterCreate bool) (*vfs.FileDescription, error) {\nats := vfs.AccessTypesForOpenFlags(flags)\nif !afterCreate {\nif err := i.checkPermissions(rp.Credentials(), ats, i.isDir()); err != nil {\n@@ -385,7 +384,7 @@ func (i *Inode) open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, flags uint32, afte\n}\n// ReadlinkAt implements vfs.FilesystemImpl.ReadlinkAt.\n-func (fs *Filesystem) ReadlinkAt(ctx context.Context, rp *vfs.ResolvingPath) (string, error) {\n+func (fs *filesystem) ReadlinkAt(ctx context.Context, rp *vfs.ResolvingPath) (string, error) {\nfs.mu.RLock()\n_, inode, err := walkExistingLocked(rp)\nfs.mu.RUnlock()\n@@ -400,9 +399,8 @@ func (fs *Filesystem) ReadlinkAt(ctx context.Context, rp *vfs.ResolvingPath) (st\n}\n// RenameAt implements vfs.FilesystemImpl.RenameAt.\n-func (fs *Filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, vd vfs.VirtualDentry, opts vfs.RenameOptions) error {\n+func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, vd vfs.VirtualDentry, opts vfs.RenameOptions) error {\nif rp.Done() {\n- // FIXME\nreturn syserror.ENOENT\n}\nfs.mu.Lock()\n@@ -424,7 +422,7 @@ func (fs *Filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, vd vf\n}\n// RmdirAt implements vfs.FilesystemImpl.RmdirAt.\n-func (fs *Filesystem) RmdirAt(ctx context.Context, rp *vfs.ResolvingPath) error {\n+func (fs *filesystem) RmdirAt(ctx context.Context, rp *vfs.ResolvingPath) error {\nfs.mu.Lock()\ndefer fs.mu.Unlock()\nvfsd, inode, err := walkExistingLocked(rp)\n@@ -447,12 +445,14 @@ func (fs *Filesystem) RmdirAt(ctx context.Context, rp *vfs.ResolvingPath) error\nif err := rp.VirtualFilesystem().DeleteDentry(vfs.MountNamespaceFromContext(ctx), vfsd); err != nil {\nreturn err\n}\n+ // Remove from parent directory's childList.\n+ vfsd.Parent().Impl().(*dentry).inode.impl.(*directory).childList.Remove(vfsd.Impl().(*dentry))\ninode.decRef()\nreturn nil\n}\n// SetStatAt implements vfs.FilesystemImpl.SetStatAt.\n-func (fs *Filesystem) SetStatAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.SetStatOptions) error {\n+func (fs *filesystem) SetStatAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.SetStatOptions) error {\nfs.mu.RLock()\n_, _, err := walkExistingLocked(rp)\nfs.mu.RUnlock()\n@@ -462,12 +462,12 @@ func (fs *Filesystem) SetStatAt(ctx context.Context, rp *vfs.ResolvingPath, opts\nif opts.Stat.Mask == 0 {\nreturn nil\n}\n- // TODO: implement Inode.setStat\n+ // TODO: implement inode.setStat\nreturn syserror.EPERM\n}\n// StatAt implements vfs.FilesystemImpl.StatAt.\n-func (fs *Filesystem) StatAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.StatOptions) (linux.Statx, error) {\n+func (fs *filesystem) StatAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.StatOptions) (linux.Statx, error) {\nfs.mu.RLock()\n_, inode, err := walkExistingLocked(rp)\nfs.mu.RUnlock()\n@@ -480,7 +480,7 @@ func (fs *Filesystem) StatAt(ctx context.Context, rp *vfs.ResolvingPath, opts vf\n}\n// StatFSAt implements vfs.FilesystemImpl.StatFSAt.\n-func (fs *Filesystem) StatFSAt(ctx context.Context, rp *vfs.ResolvingPath) (linux.Statfs, error) {\n+func (fs *filesystem) StatFSAt(ctx context.Context, rp *vfs.ResolvingPath) (linux.Statfs, error) {\nfs.mu.RLock()\n_, _, err := walkExistingLocked(rp)\nfs.mu.RUnlock()\n@@ -492,7 +492,7 @@ func (fs *Filesystem) StatFSAt(ctx context.Context, rp *vfs.ResolvingPath) (linu\n}\n// SymlinkAt implements vfs.FilesystemImpl.SymlinkAt.\n-func (fs *Filesystem) SymlinkAt(ctx context.Context, rp *vfs.ResolvingPath, target string) error {\n+func (fs *filesystem) SymlinkAt(ctx context.Context, rp *vfs.ResolvingPath, target string) error {\nif rp.Done() {\nreturn syserror.EEXIST\n}\n@@ -517,7 +517,7 @@ func (fs *Filesystem) SymlinkAt(ctx context.Context, rp *vfs.ResolvingPath, targ\n}\n// UnlinkAt implements vfs.FilesystemImpl.UnlinkAt.\n-func (fs *Filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error {\n+func (fs *filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error {\nfs.mu.Lock()\ndefer fs.mu.Unlock()\nvfsd, inode, err := walkExistingLocked(rp)\n@@ -537,6 +537,8 @@ func (fs *Filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\nif err := rp.VirtualFilesystem().DeleteDentry(vfs.MountNamespaceFromContext(ctx), vfsd); err != nil {\nreturn err\n}\n+ // Remove from parent directory's childList.\n+ vfsd.Parent().Impl().(*dentry).inode.impl.(*directory).childList.Remove(vfsd.Impl().(*dentry))\ninode.decLinksLocked()\nreturn nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/memfs/memfs.go",
"new_path": "pkg/sentry/fsimpl/memfs/memfs.go",
"diff": "//\n// Lock order:\n//\n-// Filesystem.mu\n+// filesystem.mu\n// regularFileFD.offMu\n// regularFile.mu\n-// Inode.mu\n+// inode.mu\npackage memfs\nimport (\n@@ -42,8 +42,8 @@ import (\n// FilesystemType implements vfs.FilesystemType.\ntype FilesystemType struct{}\n-// Filesystem implements vfs.FilesystemImpl.\n-type Filesystem struct {\n+// filesystem implements vfs.FilesystemImpl.\n+type filesystem struct {\nvfsfs vfs.Filesystem\n// mu serializes changes to the Dentry tree.\n@@ -54,44 +54,44 @@ type Filesystem struct {\n// NewFilesystem implements vfs.FilesystemType.NewFilesystem.\nfunc (fstype FilesystemType) NewFilesystem(ctx context.Context, creds *auth.Credentials, source string, opts vfs.NewFilesystemOptions) (*vfs.Filesystem, *vfs.Dentry, error) {\n- var fs Filesystem\n+ var fs filesystem\nfs.vfsfs.Init(&fs)\nroot := fs.newDentry(fs.newDirectory(creds, 01777))\nreturn &fs.vfsfs, &root.vfsd, nil\n}\n// Release implements vfs.FilesystemImpl.Release.\n-func (fs *Filesystem) Release() {\n+func (fs *filesystem) Release() {\n}\n// Sync implements vfs.FilesystemImpl.Sync.\n-func (fs *Filesystem) Sync(ctx context.Context) error {\n+func (fs *filesystem) Sync(ctx context.Context) error {\n// All filesystem state is in-memory.\nreturn nil\n}\n-// Dentry implements vfs.DentryImpl.\n-type Dentry struct {\n+// dentry implements vfs.DentryImpl.\n+type dentry struct {\nvfsd vfs.Dentry\n- // inode is the inode represented by this Dentry. Multiple Dentries may\n- // share a single non-directory Inode (with hard links). inode is\n+ // inode is the inode represented by this dentry. Multiple Dentries may\n+ // share a single non-directory inode (with hard links). inode is\n// immutable.\n- inode *Inode\n+ inode *inode\n- // memfs doesn't count references on Dentries; because the Dentry tree is\n+ // memfs doesn't count references on dentries; because the dentry tree is\n// the sole source of truth, it is by definition always consistent with the\n- // state of the filesystem. However, it does count references on Inodes,\n- // because Inode resources are released when all references are dropped.\n+ // state of the filesystem. However, it does count references on inodes,\n+ // because inode resources are released when all references are dropped.\n// (memfs doesn't really have resources to release, but we implement\n// reference counting because tmpfs regular files will.)\n- // dentryEntry (ugh) links Dentries into their parent directory.childList.\n+ // dentryEntry (ugh) links dentries into their parent directory.childList.\ndentryEntry\n}\n-func (fs *Filesystem) newDentry(inode *Inode) *Dentry {\n- d := &Dentry{\n+func (fs *filesystem) newDentry(inode *inode) *dentry {\n+ d := &dentry{\ninode: inode,\n}\nd.vfsd.Init(d)\n@@ -99,37 +99,37 @@ func (fs *Filesystem) newDentry(inode *Inode) *Dentry {\n}\n// IncRef implements vfs.DentryImpl.IncRef.\n-func (d *Dentry) IncRef(vfsfs *vfs.Filesystem) {\n+func (d *dentry) IncRef(vfsfs *vfs.Filesystem) {\nd.inode.incRef()\n}\n// TryIncRef implements vfs.DentryImpl.TryIncRef.\n-func (d *Dentry) TryIncRef(vfsfs *vfs.Filesystem) bool {\n+func (d *dentry) TryIncRef(vfsfs *vfs.Filesystem) bool {\nreturn d.inode.tryIncRef()\n}\n// DecRef implements vfs.DentryImpl.DecRef.\n-func (d *Dentry) DecRef(vfsfs *vfs.Filesystem) {\n+func (d *dentry) DecRef(vfsfs *vfs.Filesystem) {\nd.inode.decRef()\n}\n-// Inode represents a filesystem object.\n-type Inode struct {\n+// inode represents a filesystem object.\n+type inode struct {\n// refs is a reference count. refs is accessed using atomic memory\n// operations.\n//\n- // A reference is held on all Inodes that are reachable in the filesystem\n+ // A reference is held on all inodes that are reachable in the filesystem\n// tree. For non-directories (which may have multiple hard links), this\n// means that a reference is dropped when nlink reaches 0. For directories,\n// nlink never reaches 0 due to the \".\" entry; instead,\n- // Filesystem.RmdirAt() drops the reference.\n+ // filesystem.RmdirAt() drops the reference.\nrefs int64\n// Inode metadata; protected by mu and accessed using atomic memory\n// operations unless otherwise specified.\nmu sync.RWMutex\nmode uint32 // excluding file type bits, which are based on impl\n- nlink uint32 // protected by Filesystem.mu instead of Inode.mu\n+ nlink uint32 // protected by filesystem.mu instead of inode.mu\nuid uint32 // auth.KUID, but stored as raw uint32 for sync/atomic\ngid uint32 // auth.KGID, but ...\nino uint64 // immutable\n@@ -137,7 +137,7 @@ type Inode struct {\nimpl interface{} // immutable\n}\n-func (i *Inode) init(impl interface{}, fs *Filesystem, creds *auth.Credentials, mode uint16) {\n+func (i *inode) init(impl interface{}, fs *filesystem, creds *auth.Credentials, mode uint16) {\ni.refs = 1\ni.mode = uint32(mode)\ni.uid = uint32(creds.EffectiveKUID)\n@@ -147,29 +147,29 @@ func (i *Inode) init(impl interface{}, fs *Filesystem, creds *auth.Credentials,\ni.impl = impl\n}\n-// Preconditions: Filesystem.mu must be locked for writing.\n-func (i *Inode) incLinksLocked() {\n+// Preconditions: filesystem.mu must be locked for writing.\n+func (i *inode) incLinksLocked() {\nif atomic.AddUint32(&i.nlink, 1) <= 1 {\n- panic(\"memfs.Inode.incLinksLocked() called with no existing links\")\n+ panic(\"memfs.inode.incLinksLocked() called with no existing links\")\n}\n}\n-// Preconditions: Filesystem.mu must be locked for writing.\n-func (i *Inode) decLinksLocked() {\n+// Preconditions: filesystem.mu must be locked for writing.\n+func (i *inode) decLinksLocked() {\nif nlink := atomic.AddUint32(&i.nlink, ^uint32(0)); nlink == 0 {\ni.decRef()\n} else if nlink == ^uint32(0) { // negative overflow\n- panic(\"memfs.Inode.decLinksLocked() called with no existing links\")\n+ panic(\"memfs.inode.decLinksLocked() called with no existing links\")\n}\n}\n-func (i *Inode) incRef() {\n+func (i *inode) incRef() {\nif atomic.AddInt64(&i.refs, 1) <= 1 {\n- panic(\"memfs.Inode.incRef() called without holding a reference\")\n+ panic(\"memfs.inode.incRef() called without holding a reference\")\n}\n}\n-func (i *Inode) tryIncRef() bool {\n+func (i *inode) tryIncRef() bool {\nfor {\nrefs := atomic.LoadInt64(&i.refs)\nif refs == 0 {\n@@ -181,7 +181,7 @@ func (i *Inode) tryIncRef() bool {\n}\n}\n-func (i *Inode) decRef() {\n+func (i *inode) decRef() {\nif refs := atomic.AddInt64(&i.refs, -1); refs == 0 {\n// This is unnecessary; it's mostly to simulate what tmpfs would do.\nif regfile, ok := i.impl.(*regularFile); ok {\n@@ -191,18 +191,18 @@ func (i *Inode) decRef() {\nregfile.mu.Unlock()\n}\n} else if refs < 0 {\n- panic(\"memfs.Inode.decRef() called without holding a reference\")\n+ panic(\"memfs.inode.decRef() called without holding a reference\")\n}\n}\n-func (i *Inode) checkPermissions(creds *auth.Credentials, ats vfs.AccessTypes, isDir bool) error {\n+func (i *inode) checkPermissions(creds *auth.Credentials, ats vfs.AccessTypes, isDir bool) error {\nreturn vfs.GenericCheckPermissions(creds, ats, isDir, uint16(atomic.LoadUint32(&i.mode)), auth.KUID(atomic.LoadUint32(&i.uid)), auth.KGID(atomic.LoadUint32(&i.gid)))\n}\n// Go won't inline this function, and returning linux.Statx (which is quite\n// big) means spending a lot of time in runtime.duffcopy(), so instead it's an\n// output parameter.\n-func (i *Inode) statTo(stat *linux.Statx) {\n+func (i *inode) statTo(stat *linux.Statx) {\nstat.Mask = linux.STATX_TYPE | linux.STATX_MODE | linux.STATX_NLINK | linux.STATX_UID | linux.STATX_GID | linux.STATX_INO\nstat.Blksize = 1 // usermem.PageSize in tmpfs\nstat.Nlink = atomic.LoadUint32(&i.nlink)\n@@ -241,7 +241,7 @@ func allocatedBlocksForSize(size uint64) uint64 {\nreturn (size + 511) / 512\n}\n-func (i *Inode) direntType() uint8 {\n+func (i *inode) direntType() uint8 {\nswitch i.impl.(type) {\ncase *regularFile:\nreturn linux.DT_REG\n@@ -262,12 +262,12 @@ type fileDescription struct {\nflags uint32 // status flags; immutable\n}\n-func (fd *fileDescription) filesystem() *Filesystem {\n- return fd.vfsfd.VirtualDentry().Mount().Filesystem().Impl().(*Filesystem)\n+func (fd *fileDescription) filesystem() *filesystem {\n+ return fd.vfsfd.VirtualDentry().Mount().Filesystem().Impl().(*filesystem)\n}\n-func (fd *fileDescription) inode() *Inode {\n- return fd.vfsfd.VirtualDentry().Dentry().Impl().(*Dentry).inode\n+func (fd *fileDescription) inode() *inode {\n+ return fd.vfsfd.VirtualDentry().Dentry().Impl().(*dentry).inode\n}\n// StatusFlags implements vfs.FileDescriptionImpl.StatusFlags.\n@@ -294,6 +294,6 @@ func (fd *fileDescription) SetStat(ctx context.Context, opts vfs.SetStatOptions)\nif opts.Stat.Mask == 0 {\nreturn nil\n}\n- // TODO: implement Inode.setStat\n+ // TODO: implement inode.setStat\nreturn syserror.EPERM\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/memfs/regular_file.go",
"new_path": "pkg/sentry/fsimpl/memfs/regular_file.go",
"diff": "@@ -28,16 +28,16 @@ import (\n)\ntype regularFile struct {\n- inode Inode\n+ inode inode\nmu sync.RWMutex\ndata []byte\n// dataLen is len(data), but accessed using atomic memory operations to\n- // avoid locking in Inode.stat().\n+ // avoid locking in inode.stat().\ndataLen int64\n}\n-func (fs *Filesystem) newRegularFile(creds *auth.Credentials, mode uint16) *Inode {\n+func (fs *filesystem) newRegularFile(creds *auth.Credentials, mode uint16) *inode {\nfile := ®ularFile{}\nfile.inode.init(file, fs, creds, mode)\nfile.inode.nlink = 1 // from parent directory\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/memfs/symlink.go",
"new_path": "pkg/sentry/fsimpl/memfs/symlink.go",
"diff": "@@ -19,11 +19,11 @@ import (\n)\ntype symlink struct {\n- inode Inode\n+ inode inode\ntarget string // immutable\n}\n-func (fs *Filesystem) newSymlink(creds *auth.Credentials, target string) *Inode {\n+func (fs *filesystem) newSymlink(creds *auth.Credentials, target string) *inode {\nlink := &symlink{\ntarget: target,\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | memfs fixes.
- Unexport Filesystem/Dentry/Inode.
- Support SEEK_CUR in directoryFD.Seek().
- Hold Filesystem.mu before touching directoryFD.off in
directoryFD.Seek().
- Remove deleted Dentries from their parent directory.childLists.
- Remove invalid FIXMEs.
PiperOrigin-RevId: 262400633 |
259,997 | 09.08.2019 17:13:06 | -36,000 | 73985c6545d887644d8aa4f0e00491cc903501c7 | Fix the Stringer for leak mode | [
{
"change_type": "MODIFY",
"old_path": "pkg/refs/refcounter.go",
"new_path": "pkg/refs/refcounter.go",
"diff": "@@ -235,11 +235,11 @@ const (\nfunc (l LeakMode) String() string {\nswitch l {\ncase NoLeakChecking:\n- return \"NoLeakChecking\"\n+ return \"disabled\"\ncase LeaksLogWarning:\n- return \"LeaksLogWarning\"\n+ return \"warning\"\ncase LeaksLogTraces:\n- return \"LeaksLogTraces\"\n+ return \"traces\"\ndefault:\npanic(fmt.Sprintf(\"Invalid leakmode: %d\", l))\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/config.go",
"new_path": "runsc/boot/config.go",
"diff": "@@ -120,6 +120,8 @@ func MakeRefsLeakMode(s string) (refs.LeakMode, error) {\nreturn refs.NoLeakChecking, nil\ncase \"warning\":\nreturn refs.LeaksLogWarning, nil\n+ case \"traces\":\n+ return refs.LeaksLogTraces, nil\ndefault:\nreturn 0, fmt.Errorf(\"invalid refs leakmode %q\", s)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/main.go",
"new_path": "runsc/main.go",
"diff": "@@ -73,7 +73,7 @@ var (\nnetRaw = flag.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.\")\nnumNetworkChannels = flag.Int(\"num-network-channels\", 1, \"number of underlying channels(FDs) to use for network link endpoints.\")\nrootless = flag.Bool(\"rootless\", false, \"it allows the sandbox to be started with a user that is not root. Sandbox and Gofer processes may run with same privileges as current user.\")\n- referenceLeakMode = flag.String(\"ref-leak-mode\", \"disabled\", \"sets reference leak check mode: disabled (default), warning.\")\n+ referenceLeakMode = flag.String(\"ref-leak-mode\", \"disabled\", \"sets reference leak check mode: disabled (default), warning, traces.\")\n// Test flags, not to be used outside tests, ever.\ntestOnlyAllowRunAsCurrentUserWithoutChroot = flag.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 | Fix the Stringer for leak mode |
259,974 | 09.08.2019 13:16:46 | 25,200 | 1c9da886e72aebc1c44c66715e3ec45f6d5eff5b | Add initial ptrace stub and syscall support for arm64. | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/elf.go",
"new_path": "pkg/abi/linux/elf.go",
"diff": "@@ -89,3 +89,17 @@ const (\n// AT_SYSINFO_EHDR is the address of the VDSO.\nAT_SYSINFO_EHDR = 33\n)\n+\n+// ELF ET_CORE and ptrace GETREGSET/SETREGSET register set types.\n+//\n+// See include/uapi/linux/elf.h.\n+const (\n+ // NT_PRSTATUS is for general purpose register.\n+ NT_PRSTATUS = 0x1\n+\n+ // NT_PRFPREG is for float point register.\n+ NT_PRFPREG = 0x2\n+\n+ // NT_X86_XSTATE is for x86 extended state using xsave.\n+ NT_X86_XSTATE = 0x202\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/BUILD",
"new_path": "pkg/sentry/platform/ptrace/BUILD",
"diff": "@@ -7,13 +7,17 @@ go_library(\nsrcs = [\n\"filters.go\",\n\"ptrace.go\",\n+ \"ptrace_amd64.go\",\n+ \"ptrace_arm64.go\",\n\"ptrace_unsafe.go\",\n\"stub_amd64.s\",\n+ \"stub_arm64.s\",\n\"stub_unsafe.go\",\n\"subprocess.go\",\n\"subprocess_amd64.go\",\n+ \"subprocess_arm64.go\",\n\"subprocess_linux.go\",\n- \"subprocess_linux_amd64_unsafe.go\",\n+ \"subprocess_linux_unsafe.go\",\n\"subprocess_unsafe.go\",\n],\nimportpath = \"gvisor.dev/gvisor/pkg/sentry/platform/ptrace\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/ptrace.go",
"new_path": "pkg/sentry/platform/ptrace/ptrace.go",
"diff": "@@ -60,7 +60,7 @@ var (\n// maximum user address. This is valid only after a call to stubInit.\n//\n// We attempt to link the stub here, and adjust downward as needed.\n- stubStart uintptr = 0x7fffffff0000\n+ stubStart uintptr = stubInitAddress\n// stubEnd is the first byte past the end of the stub, as with\n// stubStart this is valid only after a call to stubInit.\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/platform/ptrace/ptrace_amd64.go",
"diff": "+// Copyright 2019 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 ptrace\n+\n+import (\n+ \"syscall\"\n+\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+)\n+\n+// fpRegSet returns the GETREGSET/SETREGSET register set type to be used.\n+func fpRegSet(useXsave bool) uintptr {\n+ if useXsave {\n+ return linux.NT_X86_XSTATE\n+ }\n+ return linux.NT_PRFPREG\n+}\n+\n+func stackPointer(r *syscall.PtraceRegs) uintptr {\n+ return uintptr(r.Rsp)\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/platform/ptrace/ptrace_arm64.go",
"diff": "+// Copyright 2019 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 ptrace\n+\n+import (\n+ \"syscall\"\n+\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+)\n+\n+// fpRegSet returns the GETREGSET/SETREGSET register set type to be used.\n+func fpRegSet(_ bool) uintptr {\n+ return linux.NT_PRFPREG\n+}\n+\n+func stackPointer(r *syscall.PtraceRegs) uintptr {\n+ return uintptr(r.Sp)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/ptrace_unsafe.go",
"new_path": "pkg/sentry/platform/ptrace/ptrace_unsafe.go",
"diff": "@@ -18,37 +18,23 @@ import (\n\"syscall\"\n\"unsafe\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/usermem\"\n)\n-// GETREGSET/SETREGSET register set types.\n-//\n-// See include/uapi/linux/elf.h.\n-const (\n- // _NT_PRFPREG is for x86 floating-point state without using xsave.\n- _NT_PRFPREG = 0x2\n-\n- // _NT_X86_XSTATE is for x86 extended state using xsave.\n- _NT_X86_XSTATE = 0x202\n-)\n-\n-// fpRegSet returns the GETREGSET/SETREGSET register set type to be used.\n-func fpRegSet(useXsave bool) uintptr {\n- if useXsave {\n- return _NT_X86_XSTATE\n- }\n- return _NT_PRFPREG\n-}\n-\n-// getRegs sets the regular register set.\n+// getRegs gets the general purpose register set.\nfunc (t *thread) getRegs(regs *syscall.PtraceRegs) error {\n+ iovec := syscall.Iovec{\n+ Base: (*byte)(unsafe.Pointer(regs)),\n+ Len: uint64(unsafe.Sizeof(*regs)),\n+ }\n_, _, errno := syscall.RawSyscall6(\nsyscall.SYS_PTRACE,\n- syscall.PTRACE_GETREGS,\n+ syscall.PTRACE_GETREGSET,\nuintptr(t.tid),\n- 0,\n- uintptr(unsafe.Pointer(regs)),\n+ linux.NT_PRSTATUS,\n+ uintptr(unsafe.Pointer(&iovec)),\n0, 0)\nif errno != 0 {\nreturn errno\n@@ -56,14 +42,18 @@ func (t *thread) getRegs(regs *syscall.PtraceRegs) error {\nreturn nil\n}\n-// setRegs sets the regular register set.\n+// setRegs sets the general purpose register set.\nfunc (t *thread) setRegs(regs *syscall.PtraceRegs) error {\n+ iovec := syscall.Iovec{\n+ Base: (*byte)(unsafe.Pointer(regs)),\n+ Len: uint64(unsafe.Sizeof(*regs)),\n+ }\n_, _, errno := syscall.RawSyscall6(\nsyscall.SYS_PTRACE,\n- syscall.PTRACE_SETREGS,\n+ syscall.PTRACE_SETREGSET,\nuintptr(t.tid),\n- 0,\n- uintptr(unsafe.Pointer(regs)),\n+ linux.NT_PRSTATUS,\n+ uintptr(unsafe.Pointer(&iovec)),\n0, 0)\nif errno != 0 {\nreturn errno\n@@ -131,7 +121,7 @@ func (t *thread) getSignalInfo(si *arch.SignalInfo) error {\n//\n// Precondition: the OS thread must be locked and own t.\nfunc (t *thread) clone() (*thread, error) {\n- r, ok := usermem.Addr(t.initRegs.Rsp).RoundUp()\n+ r, ok := usermem.Addr(stackPointer(&t.initRegs)).RoundUp()\nif !ok {\nreturn nil, syscall.EINVAL\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/subprocess.go",
"new_path": "pkg/sentry/platform/ptrace/subprocess.go",
"diff": "@@ -28,6 +28,16 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/usermem\"\n)\n+// Linux kernel errnos which \"should never be seen by user programs\", but will\n+// be revealed to ptrace syscall exit tracing.\n+//\n+// These constants are only used in subprocess.go.\n+const (\n+ ERESTARTSYS = syscall.Errno(512)\n+ ERESTARTNOINTR = syscall.Errno(513)\n+ ERESTARTNOHAND = syscall.Errno(514)\n+)\n+\n// globalPool exists to solve two distinct problems:\n//\n// 1) Subprocesses can't always be killed properly (see Release).\n@@ -282,7 +292,7 @@ func (t *thread) grabInitRegs() {\nif err := t.getRegs(&t.initRegs); err != nil {\npanic(fmt.Sprintf(\"ptrace get regs failed: %v\", err))\n}\n- t.initRegs.Rip -= initRegsRipAdjustment\n+ t.adjustInitRegsRip()\n}\n// detach detaches from the thread.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/subprocess_amd64.go",
"new_path": "pkg/sentry/platform/ptrace/subprocess_amd64.go",
"diff": "@@ -28,20 +28,13 @@ const (\n// maximumUserAddress is the largest possible user address.\nmaximumUserAddress = 0x7ffffffff000\n+ // stubInitAddress is the initial attempt link address for the stub.\n+ stubInitAddress = 0x7fffffff0000\n+\n// initRegsRipAdjustment is the size of the syscall instruction.\ninitRegsRipAdjustment = 2\n)\n-// Linux kernel errnos which \"should never be seen by user programs\", but will\n-// be revealed to ptrace syscall exit tracing.\n-//\n-// These constants are used in subprocess.go.\n-const (\n- ERESTARTSYS = syscall.Errno(512)\n- ERESTARTNOINTR = syscall.Errno(513)\n- ERESTARTNOHAND = syscall.Errno(514)\n-)\n-\n// resetSysemuRegs sets up emulation registers.\n//\n// This should be called prior to calling sysemu.\n@@ -139,3 +132,14 @@ func dumpRegs(regs *syscall.PtraceRegs) string {\nreturn m.String()\n}\n+\n+// adjustInitregsRip adjust the current register RIP value to\n+// be just before the system call instruction excution\n+func (t *thread) adjustInitRegsRip() {\n+ t.initRegs.Rip -= initRegsRipAdjustment\n+}\n+\n+// Pass the expected PPID to the child via R15 when creating stub process\n+func initChildProcessPPID(initregs *syscall.PtraceRegs, ppid int32) {\n+ initregs.R15 = uint64(ppid)\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/platform/ptrace/subprocess_arm64.go",
"diff": "+// Copyright 2019 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// +build arm64\n+\n+package ptrace\n+\n+import (\n+ \"syscall\"\n+\n+ \"gvisor.dev/gvisor/pkg/sentry/arch\"\n+)\n+\n+const (\n+ // maximumUserAddress is the largest possible user address.\n+ maximumUserAddress = 0xfffffffff000\n+\n+ // stubInitAddress is the initial attempt link address for the stub.\n+ // Only support 48bits VA currently.\n+ stubInitAddress = 0xffffffff0000\n+\n+ // initRegsRipAdjustment is the size of the svc instruction.\n+ initRegsRipAdjustment = 4\n+)\n+\n+// resetSysemuRegs sets up emulation registers.\n+//\n+// This should be called prior to calling sysemu.\n+func (s *subprocess) resetSysemuRegs(regs *syscall.PtraceRegs) {\n+}\n+\n+// createSyscallRegs sets up syscall registers.\n+//\n+// This should be called to generate registers for a system call.\n+func createSyscallRegs(initRegs *syscall.PtraceRegs, sysno uintptr, args ...arch.SyscallArgument) syscall.PtraceRegs {\n+ // Copy initial registers (Pc, Sp, etc.).\n+ regs := *initRegs\n+\n+ // Set our syscall number.\n+ // r8 for the syscall number.\n+ // r0-r6 is used to store the parameters.\n+ regs.Regs[8] = uint64(sysno)\n+ if len(args) >= 1 {\n+ regs.Regs[0] = args[0].Uint64()\n+ }\n+ if len(args) >= 2 {\n+ regs.Regs[1] = args[1].Uint64()\n+ }\n+ if len(args) >= 3 {\n+ regs.Regs[2] = args[2].Uint64()\n+ }\n+ if len(args) >= 4 {\n+ regs.Regs[3] = args[3].Uint64()\n+ }\n+ if len(args) >= 5 {\n+ regs.Regs[4] = args[4].Uint64()\n+ }\n+ if len(args) >= 6 {\n+ regs.Regs[5] = args[5].Uint64()\n+ }\n+\n+ return regs\n+}\n+\n+// isSingleStepping determines if the registers indicate single-stepping.\n+func isSingleStepping(regs *syscall.PtraceRegs) bool {\n+ // Refer to the ARM SDM D2.12.3: software step state machine\n+ // return (regs.Pstate.SS == 1) && (MDSCR_EL1.SS == 1).\n+ //\n+ // Since the host Linux kernel will set MDSCR_EL1.SS on our behalf\n+ // when we call a single-step ptrace command, we only need to check\n+ // the Pstate.SS bit here.\n+ return (regs.Pstate & arch.ARMTrapFlag) != 0\n+}\n+\n+// updateSyscallRegs updates registers after finishing sysemu.\n+func updateSyscallRegs(regs *syscall.PtraceRegs) {\n+ // No special work is necessary.\n+ return\n+}\n+\n+// syscallReturnValue extracts a sensible return from registers.\n+func syscallReturnValue(regs *syscall.PtraceRegs) (uintptr, error) {\n+ rval := int64(regs.Regs[0])\n+ if rval < 0 {\n+ return 0, syscall.Errno(-rval)\n+ }\n+ return uintptr(rval), nil\n+}\n+\n+func dumpRegs(regs *syscall.PtraceRegs) string {\n+ var m strings.Builder\n+\n+ fmt.Fprintf(&m, \"Registers:\\n\")\n+\n+ for i := 0; i < 31; i++ {\n+ fmt.Fprintf(&m, \"\\tRegs[%d]\\t = %016x\\n\", i, regs.Regs[i])\n+ }\n+ fmt.Fprintf(&m, \"\\tSp\\t = %016x\\n\", regs.Sp)\n+ fmt.Fprintf(&m, \"\\tPc\\t = %016x\\n\", regs.Pc)\n+ fmt.Fprintf(&m, \"\\tPstate\\t = %016x\\n\", regs.Pstate)\n+\n+ return m.String()\n+}\n+\n+// adjustInitregsRip adjust the current register RIP value to\n+// be just before the system call instruction excution\n+func (t *thread) adjustInitRegsRip() {\n+ t.initRegs.Pc -= initRegsRipAdjustment\n+}\n+\n+// Pass the expected PPID to the child via X7 when creating stub process\n+func initChildProcessPPID(initregs *syscall.PtraceRegs, ppid int32) {\n+ initregs.Regs[7] = uint64(ppid)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/subprocess_linux.go",
"new_path": "pkg/sentry/platform/ptrace/subprocess_linux.go",
"diff": "@@ -284,7 +284,7 @@ func (s *subprocess) createStub() (*thread, error) {\n// Pass the expected PPID to the child via R15.\nregs := t.initRegs\n- regs.R15 = uint64(t.tgid)\n+ initChildProcessPPID(®s, t.tgid)\n// Call fork in a subprocess.\n//\n"
},
{
"change_type": "RENAME",
"old_path": "pkg/sentry/platform/ptrace/subprocess_linux_amd64_unsafe.go",
"new_path": "pkg/sentry/platform/ptrace/subprocess_linux_unsafe.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build amd64 linux\n+// +build linux\n+// +build amd64 arm64\npackage ptrace\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add initial ptrace stub and syscall support for arm64.
Signed-off-by: Haibo Xu <[email protected]>
Change-Id: I1dbd23bb240cca71d0cc30fc75ca5be28cb4c37c
PiperOrigin-RevId: 262619519 |
259,962 | 09.08.2019 14:49:05 | 25,200 | 5a38eb120abe0aecd4b64cf9e3a9e1ff1dc0edd7 | Add congestion control states to sender.
This change just introduces different congestion control states and
ensures the sender.state is updated to reflect the current state
of the connection.
It is not used for any decisions yet but this is required before
algorithms like Eiffel/PRR can be implemented.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/snd.go",
"new_path": "pkg/tcpip/transport/tcp/snd.go",
"diff": "@@ -39,6 +39,28 @@ const (\nnDupAckThreshold = 3\n)\n+// ccState indicates the current congestion control state for this sender.\n+type ccState int\n+\n+const (\n+ // Open indicates that the sender is receiving acks in order and\n+ // no loss or dupACK's etc have been detected.\n+ Open ccState = iota\n+ // RTORecovery indicates that an RTO has occurred and the sender\n+ // has entered an RTO based recovery phase.\n+ RTORecovery\n+ // FastRecovery indicates that the sender has entered FastRecovery\n+ // based on receiving nDupAck's. This state is entered only when\n+ // SACK is not in use.\n+ FastRecovery\n+ // SACKRecovery indicates that the sender has entered SACK based\n+ // recovery.\n+ SACKRecovery\n+ // Disorder indicates the sender either received some SACK blocks\n+ // or dupACK's.\n+ Disorder\n+)\n+\n// congestionControl is an interface that must be implemented by any supported\n// congestion control algorithm.\ntype congestionControl interface {\n@@ -138,6 +160,9 @@ type sender struct {\n// maxSentAck is the maxium acknowledgement actually sent.\nmaxSentAck seqnum.Value\n+ // state is the current state of congestion control for this endpoint.\n+ state ccState\n+\n// cc is the congestion control algorithm in use for this sender.\ncc congestionControl\n}\n@@ -435,6 +460,7 @@ func (s *sender) retransmitTimerExpired() bool {\ns.leaveFastRecovery()\n}\n+ s.state = RTORecovery\ns.cc.HandleRTOExpired()\n// Mark the next segment to be sent as the first unacknowledged one and\n@@ -820,9 +846,11 @@ func (s *sender) enterFastRecovery() {\ns.fr.last = s.sndNxt - 1\ns.fr.maxCwnd = s.sndCwnd + s.outstanding\nif s.ep.sackPermitted {\n+ s.state = SACKRecovery\ns.ep.stack.Stats().TCP.SACKRecovery.Increment()\nreturn\n}\n+ s.state = FastRecovery\ns.ep.stack.Stats().TCP.FastRecovery.Increment()\n}\n@@ -981,6 +1009,7 @@ func (s *sender) checkDuplicateAck(seg *segment) (rtx bool) {\ns.fr.highRxt = s.sndUna - 1\n// Do run SetPipe() to calculate the outstanding segments.\ns.SetPipe()\n+ s.state = Disorder\nreturn false\n}\n@@ -1112,6 +1141,9 @@ func (s *sender) handleRcvdSegment(seg *segment) {\n// window based on the number of acknowledged packets.\nif !s.fr.active {\ns.cc.Update(originalOutstanding - s.outstanding)\n+ if s.fr.last.LessThan(s.sndUna) {\n+ s.state = Open\n+ }\n}\n// It is possible for s.outstanding to drop below zero if we get\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add congestion control states to sender.
This change just introduces different congestion control states and
ensures the sender.state is updated to reflect the current state
of the connection.
It is not used for any decisions yet but this is required before
algorithms like Eiffel/PRR can be implemented.
Fixes #394
PiperOrigin-RevId: 262638292 |
259,853 | 09.08.2019 22:33:40 | 25,200 | af90e68623c729d0e3b06a1e838c5584d2d8b7c2 | netlink: return an error in nlmsgerr
Now if a process sends an unsupported netlink requests,
an error is returned from the send system call.
The linux kernel works differently in this case. It returns errors in the
nlmsgerr netlink message.
Reported-by: | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/netlink.go",
"new_path": "pkg/abi/linux/netlink.go",
"diff": "@@ -122,3 +122,9 @@ const (\nNETLINK_EXT_ACK = 11\nNETLINK_DUMP_STRICT_CHK = 12\n)\n+\n+// NetlinkErrorMessage is struct nlmsgerr, from uapi/linux/netlink.h.\n+type NetlinkErrorMessage struct {\n+ Error int32\n+ Header NetlinkMessageHeader\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netlink/socket.go",
"new_path": "pkg/sentry/socket/netlink/socket.go",
"diff": "@@ -511,6 +511,19 @@ func (s *Socket) sendResponse(ctx context.Context, ms *MessageSet) *syserr.Error\nreturn nil\n}\n+func (s *Socket) dumpErrorMesage(ctx context.Context, hdr linux.NetlinkMessageHeader, ms *MessageSet, err *syserr.Error) *syserr.Error {\n+ m := ms.AddMessage(linux.NetlinkMessageHeader{\n+ Type: linux.NLMSG_ERROR,\n+ })\n+\n+ m.Put(linux.NetlinkErrorMessage{\n+ Error: int32(-err.ToLinux().Number()),\n+ Header: hdr,\n+ })\n+ return nil\n+\n+}\n+\n// processMessages handles each message in buf, passing it to the protocol\n// handler for final handling.\nfunc (s *Socket) processMessages(ctx context.Context, buf []byte) *syserr.Error {\n@@ -545,15 +558,21 @@ func (s *Socket) processMessages(ctx context.Context, buf []byte) *syserr.Error\ncontinue\n}\n+ ms := NewMessageSet(s.portID, hdr.Seq)\n+ var err *syserr.Error\n// TODO(b/68877377): ACKs not supported yet.\nif hdr.Flags&linux.NLM_F_ACK == linux.NLM_F_ACK {\n- return syserr.ErrNotSupported\n- }\n+ err = syserr.ErrNotSupported\n+ } else {\n- ms := NewMessageSet(s.portID, hdr.Seq)\n- if err := s.protocol.ProcessMessage(ctx, hdr, data, ms); err != nil {\n+ err = s.protocol.ProcessMessage(ctx, hdr, data, ms)\n+ }\n+ if err != nil {\n+ ms = NewMessageSet(s.portID, hdr.Seq)\n+ if err := s.dumpErrorMesage(ctx, hdr, ms, err); err != nil {\nreturn err\n}\n+ }\nif err := s.sendResponse(ctx, ms); err != nil {\nreturn err\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_netdevice.cc",
"new_path": "test/syscalls/linux/socket_netdevice.cc",
"diff": "@@ -89,7 +89,8 @@ TEST(NetdeviceTest, Netmask) {\n// (i.e. netmask) for the loopback device.\nint prefixlen = -1;\nASSERT_NO_ERRNO(NetlinkRequestResponse(\n- fd, &req, sizeof(req), [&](const struct nlmsghdr *hdr) {\n+ fd, &req, sizeof(req),\n+ [&](const struct nlmsghdr *hdr) {\nEXPECT_THAT(hdr->nlmsg_type, AnyOf(Eq(RTM_NEWADDR), Eq(NLMSG_DONE)));\nEXPECT_TRUE((hdr->nlmsg_flags & NLM_F_MULTI) == NLM_F_MULTI)\n@@ -111,7 +112,8 @@ TEST(NetdeviceTest, Netmask) {\nifaddrmsg->ifa_family == AF_INET) {\nprefixlen = ifaddrmsg->ifa_prefixlen;\n}\n- }));\n+ },\n+ false));\nASSERT_GE(prefixlen, 0);\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_netlink_route.cc",
"new_path": "test/syscalls/linux/socket_netlink_route.cc",
"diff": "@@ -238,7 +238,8 @@ TEST(NetlinkRouteTest, GetLinkDump) {\n// Loopback is common among all tests, check that it's found.\nbool loopbackFound = false;\nASSERT_NO_ERRNO(NetlinkRequestResponse(\n- fd, &req, sizeof(req), [&](const struct nlmsghdr* hdr) {\n+ fd, &req, sizeof(req),\n+ [&](const struct nlmsghdr* hdr) {\nCheckGetLinkResponse(hdr, kSeq, port);\nif (hdr->nlmsg_type != RTM_NEWLINK) {\nreturn;\n@@ -252,10 +253,44 @@ TEST(NetlinkRouteTest, GetLinkDump) {\nloopbackFound = true;\nEXPECT_NE(msg->ifi_flags & IFF_LOOPBACK, 0);\n}\n- }));\n+ },\n+ false));\nEXPECT_TRUE(loopbackFound);\n}\n+TEST(NetlinkRouteTest, MsgHdrMsgUnsuppType) {\n+ FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(NetlinkBoundSocket());\n+\n+ struct request {\n+ struct nlmsghdr hdr;\n+ struct ifinfomsg ifm;\n+ };\n+\n+ constexpr uint32_t kSeq = 12345;\n+\n+ struct request req = {};\n+ req.hdr.nlmsg_len = sizeof(req);\n+ // If type & 0x3 is equal to 0x2, this means a get request\n+ // which doesn't require CAP_SYS_ADMIN.\n+ req.hdr.nlmsg_type = ((__RTM_MAX + 1024) & (~0x3)) | 0x2;\n+ req.hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;\n+ req.hdr.nlmsg_seq = kSeq;\n+ req.ifm.ifi_family = AF_UNSPEC;\n+\n+ ASSERT_NO_ERRNO(NetlinkRequestResponse(\n+ fd, &req, sizeof(req),\n+ [&](const struct nlmsghdr* hdr) {\n+ EXPECT_THAT(hdr->nlmsg_type, Eq(NLMSG_ERROR));\n+ EXPECT_EQ(hdr->nlmsg_seq, kSeq);\n+ EXPECT_GE(hdr->nlmsg_len, sizeof(*hdr) + sizeof(struct nlmsgerr));\n+\n+ const struct nlmsgerr* msg =\n+ reinterpret_cast<const struct nlmsgerr*>(NLMSG_DATA(hdr));\n+ EXPECT_EQ(msg->error, -EOPNOTSUPP);\n+ },\n+ true));\n+}\n+\nTEST(NetlinkRouteTest, MsgHdrMsgTrunc) {\nFileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(NetlinkBoundSocket());\n@@ -364,9 +399,11 @@ TEST(NetlinkRouteTest, ControlMessageIgnored) {\nreq.ifm.ifi_family = AF_UNSPEC;\nASSERT_NO_ERRNO(NetlinkRequestResponse(\n- fd, &req, sizeof(req), [&](const struct nlmsghdr* hdr) {\n+ fd, &req, sizeof(req),\n+ [&](const struct nlmsghdr* hdr) {\nCheckGetLinkResponse(hdr, kSeq, port);\n- }));\n+ },\n+ false));\n}\nTEST(NetlinkRouteTest, GetAddrDump) {\n@@ -388,7 +425,8 @@ TEST(NetlinkRouteTest, GetAddrDump) {\nreq.rgm.rtgen_family = AF_UNSPEC;\nASSERT_NO_ERRNO(NetlinkRequestResponse(\n- fd, &req, sizeof(req), [&](const struct nlmsghdr* hdr) {\n+ fd, &req, sizeof(req),\n+ [&](const struct nlmsghdr* hdr) {\nEXPECT_THAT(hdr->nlmsg_type, AnyOf(Eq(RTM_NEWADDR), Eq(NLMSG_DONE)));\nEXPECT_TRUE((hdr->nlmsg_flags & NLM_F_MULTI) == NLM_F_MULTI)\n@@ -405,7 +443,8 @@ TEST(NetlinkRouteTest, GetAddrDump) {\nEXPECT_GE(hdr->nlmsg_len, sizeof(*hdr) + sizeof(struct ifaddrmsg));\n// TODO(mpratt): Check ifaddrmsg contents and following attrs.\n- }));\n+ },\n+ false));\n}\nTEST(NetlinkRouteTest, LookupAll) {\n@@ -448,7 +487,8 @@ TEST(NetlinkRouteTest, GetRouteDump) {\nbool routeFound = false;\nbool dstFound = true;\nASSERT_NO_ERRNO(NetlinkRequestResponse(\n- fd, &req, sizeof(req), [&](const struct nlmsghdr* hdr) {\n+ fd, &req, sizeof(req),\n+ [&](const struct nlmsghdr* hdr) {\n// Validate the reponse to RTM_GETROUTE + NLM_F_DUMP.\nEXPECT_THAT(hdr->nlmsg_type, AnyOf(Eq(RTM_NEWROUTE), Eq(NLMSG_DONE)));\n@@ -491,7 +531,8 @@ TEST(NetlinkRouteTest, GetRouteDump) {\nrouteFound = true;\ndstFound = rtDstFound && dstFound;\n}\n- }));\n+ },\n+ false));\n// At least one route found in main route table.\nEXPECT_TRUE(routeFound);\n// Found RTA_DST for each route in main table.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_netlink_util.cc",
"new_path": "test/syscalls/linux/socket_netlink_util.cc",
"diff": "@@ -54,7 +54,8 @@ PosixErrorOr<uint32_t> NetlinkPortID(int fd) {\nPosixError NetlinkRequestResponse(\nconst FileDescriptor& fd, void* request, size_t len,\n- const std::function<void(const struct nlmsghdr* hdr)>& fn) {\n+ const std::function<void(const struct nlmsghdr* hdr)>& fn,\n+ bool expect_nlmsgerr) {\nstruct iovec iov = {};\niov.iov_base = request;\niov.iov_len = len;\n@@ -93,7 +94,11 @@ PosixError NetlinkRequestResponse(\n}\n} while (type != NLMSG_DONE && type != NLMSG_ERROR);\n+ if (expect_nlmsgerr) {\n+ EXPECT_EQ(type, NLMSG_ERROR);\n+ } else {\nEXPECT_EQ(type, NLMSG_DONE);\n+ }\nreturn NoError();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_netlink_util.h",
"new_path": "test/syscalls/linux/socket_netlink_util.h",
"diff": "@@ -34,7 +34,8 @@ PosixErrorOr<uint32_t> NetlinkPortID(int fd);\n// Send the passed request and call fn will all response netlink messages.\nPosixError NetlinkRequestResponse(\nconst FileDescriptor& fd, void* request, size_t len,\n- const std::function<void(const struct nlmsghdr* hdr)>& fn);\n+ const std::function<void(const struct nlmsghdr* hdr)>& fn,\n+ bool expect_nlmsgerr);\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | netlink: return an error in nlmsgerr
Now if a process sends an unsupported netlink requests,
an error is returned from the send system call.
The linux kernel works differently in this case. It returns errors in the
nlmsgerr netlink message.
Reported-by: [email protected]
PiperOrigin-RevId: 262690453 |
259,854 | 12.08.2019 13:29:47 | 25,200 | eac690e358e25897bb878fdfd1ad7036054162e2 | Fix netstack build error on non-AMD64.
This stub had the wrong function signature. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/mmap.go",
"new_path": "pkg/tcpip/link/fdbased/mmap.go",
"diff": "package fdbased\n-import \"gvisor.dev/gvisor/pkg/tcpip\"\n-\n// Stubbed out version for non-linux/non-amd64 platforms.\n-func newPacketMMapDispatcher(fd int, e *endpoint) (linkDispatcher, *tcpip.Error) {\n+func newPacketMMapDispatcher(fd int, e *endpoint) (linkDispatcher, error) {\nreturn nil, nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix netstack build error on non-AMD64.
This stub had the wrong function signature.
PiperOrigin-RevId: 262992682 |
259,985 | 12.08.2019 17:33:26 | 25,200 | 691c2f8173dfe7349e8289697299839cda32b495 | Compute size of struct tcp_info instead of hardcoding it. | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/socket.go",
"new_path": "pkg/abi/linux/socket.go",
"diff": "@@ -366,7 +366,7 @@ type TCPInfo struct {\n}\n// SizeOfTCPInfo is the binary size of a TCPInfo struct.\n-const SizeOfTCPInfo = 104\n+var SizeOfTCPInfo = int(binary.Size(TCPInfo{}))\n// Control message types, from linux/socket.h.\nconst (\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/proc_net_tcp.cc",
"new_path": "test/syscalls/linux/proc_net_tcp.cc",
"diff": "@@ -187,9 +187,9 @@ TEST(ProcNetTCP, EntryUID) {\nstd::vector<TCPEntry> entries =\nASSERT_NO_ERRNO_AND_VALUE(ProcNetTCPEntries());\nTCPEntry e;\n- EXPECT_TRUE(FindByLocalAddr(entries, &e, sockets->first_addr()));\n+ ASSERT_TRUE(FindByLocalAddr(entries, &e, sockets->first_addr()));\nEXPECT_EQ(e.uid, geteuid());\n- EXPECT_TRUE(FindByRemoteAddr(entries, &e, sockets->first_addr()));\n+ ASSERT_TRUE(FindByRemoteAddr(entries, &e, sockets->first_addr()));\nEXPECT_EQ(e.uid, geteuid());\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Compute size of struct tcp_info instead of hardcoding it.
PiperOrigin-RevId: 263040624 |
259,853 | 13.08.2019 11:54:59 | 25,200 | 8d97b22aa8e565ff05c5e9209f13d2394e9706c8 | tests: print stack traces if test failed by timeout | [
{
"change_type": "MODIFY",
"old_path": "runsc/main.go",
"new_path": "runsc/main.go",
"diff": "@@ -22,6 +22,7 @@ import (\n\"io\"\n\"io/ioutil\"\n\"os\"\n+ \"os/signal\"\n\"path/filepath\"\n\"strings\"\n\"syscall\"\n@@ -116,6 +117,13 @@ func main() {\n// All subcommands must be registered before flag parsing.\nflag.Parse()\n+ if *testOnlyAllowRunAsCurrentUserWithoutChroot {\n+ // SIGTERM is sent to all processes if a test exceeds its\n+ // timeout and this case is handled by syscall_test_runner.\n+ log.Warningf(\"Block the TERM signal. This is only safe in tests!\")\n+ signal.Ignore(syscall.SIGTERM)\n+ }\n+\n// Are we showing the version?\nif *showVersion {\n// The format here is the same as runc.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -361,6 +361,8 @@ func (s *Sandbox) createSandboxProcess(conf *boot.Config, args *Args, startSyncF\nnextFD++\n}\n+ cmd.Args = append(cmd.Args, \"--panic-signal=\"+strconv.Itoa(int(syscall.SIGTERM)))\n+\n// Add the \"boot\" command to the args.\n//\n// All flags after this must be for the boot command\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/syscall_test_runner.go",
"new_path": "test/syscalls/syscall_test_runner.go",
"diff": "@@ -23,11 +23,13 @@ import (\n\"math\"\n\"os\"\n\"os/exec\"\n+ \"os/signal\"\n\"path/filepath\"\n\"strconv\"\n\"strings\"\n\"syscall\"\n\"testing\"\n+ \"time\"\nspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n\"golang.org/x/sys/unix\"\n@@ -189,6 +191,8 @@ func runTestCaseRunsc(testBin string, tc gtest.TestCase, t *testing.T) {\n\"-log-format=text\",\n\"-TESTONLY-unsafe-nonroot=true\",\n\"-net-raw=true\",\n+ fmt.Sprintf(\"-panic-signal=%d\", syscall.SIGTERM),\n+ \"-watchdog-action=panic\",\n}\nif *overlay {\nargs = append(args, \"-overlay\")\n@@ -220,8 +224,8 @@ func runTestCaseRunsc(testBin string, tc gtest.TestCase, t *testing.T) {\n// Current process doesn't have CAP_SYS_ADMIN, create user namespace and run\n// as root inside that namespace to get it.\n- args = append(args, \"run\", \"--bundle\", bundleDir, id)\n- cmd := exec.Command(*runscPath, args...)\n+ rArgs := append(args, \"run\", \"--bundle\", bundleDir, id)\n+ cmd := exec.Command(*runscPath, rArgs...)\ncmd.SysProcAttr = &syscall.SysProcAttr{\nCloneflags: syscall.CLONE_NEWUSER | syscall.CLONE_NEWNS,\n// Set current user/group as root inside the namespace.\n@@ -239,9 +243,44 @@ func runTestCaseRunsc(testBin string, tc gtest.TestCase, t *testing.T) {\n}\ncmd.Stdout = os.Stdout\ncmd.Stderr = os.Stderr\n+ sig := make(chan os.Signal, 1)\n+ signal.Notify(sig, syscall.SIGTERM)\n+ go func() {\n+ s, ok := <-sig\n+ if !ok {\n+ return\n+ }\n+ t.Errorf(\"%s: Got signal: %v\", tc.FullName(), s)\n+ done := make(chan bool)\n+ go func() {\n+ dArgs := append(args, \"-alsologtostderr=true\", \"debug\", \"--stacks\", id)\n+ cmd := exec.Command(*runscPath, dArgs...)\n+ cmd.Stdout = os.Stdout\n+ cmd.Stderr = os.Stderr\n+ cmd.Run()\n+ done <- true\n+ }()\n+\n+ timeout := time.Tick(3 * time.Second)\n+ select {\n+ case <-timeout:\n+ t.Logf(\"runsc debug --stacks is timeouted\")\n+ case <-done:\n+ }\n+\n+ t.Logf(\"Send SIGTERM to the sandbox process\")\n+ dArgs := append(args, \"debug\",\n+ fmt.Sprintf(\"--signal=%d\", syscall.SIGTERM),\n+ id)\n+ cmd = exec.Command(*runscPath, dArgs...)\n+ cmd.Stdout = os.Stdout\n+ cmd.Stderr = os.Stderr\n+ cmd.Run()\n+ }()\nif err = cmd.Run(); err != nil {\nt.Errorf(\"test %q exited with status %v, want 0\", tc.FullName(), err)\n}\n+ close(sig)\n}\n// filterEnv returns an environment with the blacklisted variables removed.\n@@ -277,7 +316,7 @@ func main() {\nfatalf(\"test-name flag must be provided\")\n}\n- log.SetLevel(log.Warning)\n+ log.SetLevel(log.Info)\nif *debug {\nlog.SetLevel(log.Debug)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | tests: print stack traces if test failed by timeout
PiperOrigin-RevId: 263184083 |
259,854 | 13.08.2019 12:09:48 | 25,200 | 99bf75a6dc1cbad2d688ef80354f45940a40a3a1 | gonet: Replace NewPacketConn with DialUDP.
This better matches the standard library and allows creating connected
PacketConns. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/adapters/gonet/gonet.go",
"new_path": "pkg/tcpip/adapters/gonet/gonet.go",
"diff": "@@ -556,32 +556,50 @@ type PacketConn struct {\nwq *waiter.Queue\n}\n-// NewPacketConn creates a new PacketConn.\n-func NewPacketConn(s *stack.Stack, addr tcpip.FullAddress, network tcpip.NetworkProtocolNumber) (*PacketConn, error) {\n- // Create UDP endpoint and bind it.\n+// DialUDP creates a new PacketConn.\n+//\n+// If laddr is nil, a local address is automatically chosen.\n+//\n+// If raddr is nil, the PacketConn is left unconnected.\n+func DialUDP(s *stack.Stack, laddr, raddr *tcpip.FullAddress, network tcpip.NetworkProtocolNumber) (*PacketConn, error) {\nvar wq waiter.Queue\nep, err := s.NewEndpoint(udp.ProtocolNumber, network, &wq)\nif err != nil {\nreturn nil, errors.New(err.String())\n}\n- if err := ep.Bind(addr); err != nil {\n+ if laddr != nil {\n+ if err := ep.Bind(*laddr); err != nil {\nep.Close()\nreturn nil, &net.OpError{\nOp: \"bind\",\nNet: \"udp\",\n- Addr: fullToUDPAddr(addr),\n+ Addr: fullToUDPAddr(*laddr),\nErr: errors.New(err.String()),\n}\n}\n+ }\n- c := &PacketConn{\n+ c := PacketConn{\nstack: s,\nep: ep,\nwq: &wq,\n}\nc.deadlineTimer.init()\n- return c, nil\n+\n+ if raddr != nil {\n+ if err := c.ep.Connect(*raddr); err != nil {\n+ c.ep.Close()\n+ return nil, &net.OpError{\n+ Op: \"connect\",\n+ Net: \"udp\",\n+ Addr: fullToUDPAddr(*raddr),\n+ Err: errors.New(err.String()),\n+ }\n+ }\n+ }\n+\n+ return &c, nil\n}\nfunc (c *PacketConn) newOpError(op string, err error) *net.OpError {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/adapters/gonet/gonet_test.go",
"new_path": "pkg/tcpip/adapters/gonet/gonet_test.go",
"diff": "@@ -371,9 +371,9 @@ func TestUDPForwarder(t *testing.T) {\n})\ns.SetTransportProtocolHandler(udp.ProtocolNumber, fwd.HandlePacket)\n- c2, err := NewPacketConn(s, addr2, ipv4.ProtocolNumber)\n+ c2, err := DialUDP(s, &addr2, nil, ipv4.ProtocolNumber)\nif err != nil {\n- t.Fatal(\"NewPacketConn(port 5):\", err)\n+ t.Fatal(\"DialUDP(bind port 5):\", err)\n}\nsent := \"abc123\"\n@@ -452,13 +452,13 @@ func TestPacketConnTransfer(t *testing.T) {\naddr2 := tcpip.FullAddress{NICID, ip2, 11311}\ns.AddAddress(NICID, ipv4.ProtocolNumber, ip2)\n- c1, err := NewPacketConn(s, addr1, ipv4.ProtocolNumber)\n+ c1, err := DialUDP(s, &addr1, nil, ipv4.ProtocolNumber)\nif err != nil {\n- t.Fatal(\"NewPacketConn(port 4):\", err)\n+ t.Fatal(\"DialUDP(bind port 4):\", err)\n}\n- c2, err := NewPacketConn(s, addr2, ipv4.ProtocolNumber)\n+ c2, err := DialUDP(s, &addr2, nil, ipv4.ProtocolNumber)\nif err != nil {\n- t.Fatal(\"NewPacketConn(port 5):\", err)\n+ t.Fatal(\"DialUDP(bind port 5):\", err)\n}\nc1.SetDeadline(time.Now().Add(time.Second))\n@@ -491,6 +491,50 @@ func TestPacketConnTransfer(t *testing.T) {\n}\n}\n+func TestConnectedPacketConnTransfer(t *testing.T) {\n+ s, e := newLoopbackStack()\n+ if e != nil {\n+ t.Fatalf(\"newLoopbackStack() = %v\", e)\n+ }\n+\n+ ip := tcpip.Address(net.IPv4(169, 254, 10, 1).To4())\n+ addr := tcpip.FullAddress{NICID, ip, 11211}\n+ s.AddAddress(NICID, ipv4.ProtocolNumber, ip)\n+\n+ c1, err := DialUDP(s, &addr, nil, ipv4.ProtocolNumber)\n+ if err != nil {\n+ t.Fatal(\"DialUDP(bind port 4):\", err)\n+ }\n+ c2, err := DialUDP(s, nil, &addr, ipv4.ProtocolNumber)\n+ if err != nil {\n+ t.Fatal(\"DialUDP(bind port 5):\", err)\n+ }\n+\n+ c1.SetDeadline(time.Now().Add(time.Second))\n+ c2.SetDeadline(time.Now().Add(time.Second))\n+\n+ sent := \"abc123\"\n+ if n, err := c2.Write([]byte(sent)); err != nil || n != len(sent) {\n+ t.Errorf(\"got c2.Write(%q) = %d, %v, want = %d, %v\", sent, n, err, len(sent), nil)\n+ }\n+ recv := make([]byte, len(sent))\n+ n, err := c1.Read(recv)\n+ if err != nil || n != len(recv) {\n+ t.Errorf(\"got c1.Read() = %d, %v, want = %d, %v\", n, err, len(recv), nil)\n+ }\n+\n+ if recv := string(recv); recv != sent {\n+ t.Errorf(\"got recv = %q, want = %q\", recv, sent)\n+ }\n+\n+ if err := c1.Close(); err != nil {\n+ t.Error(\"c1.Close():\", err)\n+ }\n+ if err := c2.Close(); err != nil {\n+ t.Error(\"c2.Close():\", err)\n+ }\n+}\n+\nfunc makePipe() (c1, c2 net.Conn, stop func(), err error) {\ns, e := newLoopbackStack()\nif e != nil {\n"
}
] | Go | Apache License 2.0 | google/gvisor | gonet: Replace NewPacketConn with DialUDP.
This better matches the standard library and allows creating connected
PacketConns.
PiperOrigin-RevId: 263187462 |
259,992 | 13.08.2019 12:21:33 | 25,200 | c386f046c1db5b065acf52ad3dde8080a38ddf01 | Fix file mode check in fsgofer Attach | [
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/fsgofer.go",
"new_path": "runsc/fsgofer/fsgofer.go",
"diff": "@@ -125,7 +125,7 @@ func (a *attachPoint) Attach() (p9.File, error) {\nreturn nil, fmt.Errorf(\"stat file %q, err: %v\", a.prefix, err)\n}\nmode := syscall.O_RDWR\n- if a.conf.ROMount || stat.Mode&syscall.S_IFDIR != 0 {\n+ if a.conf.ROMount || (stat.Mode&syscall.S_IFMT) == syscall.S_IFDIR {\nmode = syscall.O_RDONLY\n}\n@@ -141,9 +141,13 @@ func (a *attachPoint) Attach() (p9.File, error) {\nf.Close()\nreturn nil, fmt.Errorf(\"attach point already attached, prefix: %s\", a.prefix)\n}\n- a.attached = true\n- return newLocalFile(a, f, a.prefix, stat)\n+ rv, err := newLocalFile(a, f, a.prefix, stat)\n+ if err != nil {\n+ return nil, err\n+ }\n+ a.attached = true\n+ return rv, nil\n}\n// makeQID returns a unique QID for the given stat buffer.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/fsgofer_test.go",
"new_path": "runsc/fsgofer/fsgofer_test.go",
"diff": "@@ -17,8 +17,10 @@ package fsgofer\nimport (\n\"fmt\"\n\"io/ioutil\"\n+ \"net\"\n\"os\"\n\"path\"\n+ \"path/filepath\"\n\"syscall\"\n\"testing\"\n@@ -621,6 +623,46 @@ func TestAttachFile(t *testing.T) {\n}\n}\n+func TestAttachInvalidType(t *testing.T) {\n+ dir, err := ioutil.TempDir(\"\", \"attach-\")\n+ if err != nil {\n+ t.Fatalf(\"ioutil.TempDir() failed, err: %v\", err)\n+ }\n+ defer os.RemoveAll(dir)\n+\n+ fifo := filepath.Join(dir, \"fifo\")\n+ if err := syscall.Mkfifo(fifo, 0755); err != nil {\n+ t.Fatalf(\"Mkfifo(%q): %v\", fifo, err)\n+ }\n+\n+ socket := filepath.Join(dir, \"socket\")\n+ l, err := net.Listen(\"unix\", socket)\n+ if err != nil {\n+ t.Fatalf(\"net.Listen(unix, %q): %v\", socket, err)\n+ }\n+ defer l.Close()\n+\n+ for _, tc := range []struct {\n+ name string\n+ path string\n+ }{\n+ {name: \"fifo\", path: fifo},\n+ {name: \"socket\", path: socket},\n+ } {\n+ t.Run(tc.name, func(t *testing.T) {\n+ conf := Config{ROMount: false}\n+ a, err := NewAttachPoint(tc.path, conf)\n+ if err != nil {\n+ t.Fatalf(\"NewAttachPoint failed: %v\", err)\n+ }\n+ f, err := a.Attach()\n+ if f != nil || err == nil {\n+ t.Fatalf(\"Attach should have failed, got (%v, nil)\", f)\n+ }\n+ })\n+ }\n+}\n+\nfunc TestDoubleAttachError(t *testing.T) {\nconf := Config{ROMount: false}\nroot, err := ioutil.TempDir(\"\", \"root-\")\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix file mode check in fsgofer Attach
PiperOrigin-RevId: 263189654 |
259,854 | 13.08.2019 12:47:46 | 25,200 | 072d941e325686e877395dabb4320c39e5e82a8a | Add note to name logging mentioning trace logging should be enabled to debug. | [
{
"change_type": "MODIFY",
"old_path": "pkg/refs/refcounter.go",
"new_path": "pkg/refs/refcounter.go",
"diff": "@@ -325,6 +325,8 @@ func (r *AtomicRefCount) finalize() {\nmsg := fmt.Sprintf(\"%sAtomicRefCount %p owned by %q garbage collected with ref count of %d (want 0)\", note, r, r.name, n)\nif len(r.stack) != 0 {\nmsg += \":\\nCaller:\\n\" + formatStack(r.stack)\n+ } else {\n+ msg += \" (enable trace logging to debug)\"\n}\nlog.Warningf(msg)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add note to name logging mentioning trace logging should be enabled to debug.
PiperOrigin-RevId: 263194584 |
259,992 | 13.08.2019 13:32:18 | 25,200 | 0e907c4298e635d5960b1aeefde2294a6a795cbc | Fix file mode check in pipeOperations | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/fdpipe/pipe.go",
"new_path": "pkg/sentry/fs/fdpipe/pipe.go",
"diff": "@@ -87,7 +87,7 @@ func (p *pipeOperations) init() error {\nlog.Warningf(\"pipe: cannot stat fd %d: %v\", p.file.FD(), err)\nreturn syscall.EINVAL\n}\n- if s.Mode&syscall.S_IFIFO != syscall.S_IFIFO {\n+ if (s.Mode & syscall.S_IFMT) != syscall.S_IFIFO {\nlog.Warningf(\"pipe: cannot load fd %d as pipe, file type: %o\", p.file.FD(), s.Mode)\nreturn syscall.EINVAL\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix file mode check in pipeOperations
PiperOrigin-RevId: 263203441 |
260,015 | 13.08.2019 16:25:09 | 25,200 | 462bafb2e7a4d56b788a7467a9e7c05604f55a15 | Add variable controlling the go binary path. | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "# Base path used to install.\nDESTDIR=/usr/local\n+GC=go\nGO_BUILD_FLAGS=\nGO_TAGS=\nGO_LDFLAGS=-ldflags '-s -w -extldflags \"-static\"'\n@@ -12,10 +13,10 @@ all: binaries\nbinaries: bin/gvisor-containerd-shim bin/containerd-shim-runsc-v1\nbin/gvisor-containerd-shim: $(SOURCES)\n- CGO_ENABLED=0 go build ${GO_BUILD_FLAGS} -o bin/gvisor-containerd-shim ${SHIM_GO_LDFLAGS} ${GO_TAGS} ./cmd/gvisor-containerd-shim\n+ CGO_ENABLED=0 ${GC} build ${GO_BUILD_FLAGS} -o bin/gvisor-containerd-shim ${SHIM_GO_LDFLAGS} ${GO_TAGS} ./cmd/gvisor-containerd-shim\nbin/containerd-shim-runsc-v1: $(SOURCES)\n- CGO_ENABLED=0 go build ${GO_BUILD_FLAGS} -o bin/containerd-shim-runsc-v1 ${SHIM_GO_LDFLAGS} ${GO_TAGS} ./cmd/containerd-shim-runsc-v1\n+ CGO_ENABLED=0 ${GC} build ${GO_BUILD_FLAGS} -o bin/containerd-shim-runsc-v1 ${SHIM_GO_LDFLAGS} ${GO_TAGS} ./cmd/containerd-shim-runsc-v1\ninstall: bin/gvisor-containerd-shim\nmkdir -p $(DESTDIR)/bin\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add variable controlling the go binary path. (#35) |
259,885 | 13.08.2019 17:52:53 | 25,200 | cee044c2ab009c9faae154e1751eef93430fc141 | Add vfs.DynamicBytesFileDescriptionImpl.
This replaces fs/proc/seqfile for vfs2-based filesystems. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/BUILD",
"new_path": "pkg/sentry/vfs/BUILD",
"diff": "@@ -18,6 +18,7 @@ go_library(\n\"permissions.go\",\n\"resolving_path.go\",\n\"syscalls.go\",\n+ \"testutil.go\",\n\"vfs.go\",\n],\nimportpath = \"gvisor.dev/gvisor/pkg/sentry/vfs\",\n@@ -40,7 +41,16 @@ go_test(\nname = \"vfs_test\",\nsize = \"small\",\nsrcs = [\n+ \"file_description_impl_util_test.go\",\n\"mount_test.go\",\n],\nembed = [\":vfs\"],\n+ deps = [\n+ \"//pkg/abi/linux\",\n+ \"//pkg/sentry/context\",\n+ \"//pkg/sentry/context/contexttest\",\n+ \"//pkg/sentry/kernel/auth\",\n+ \"//pkg/sentry/usermem\",\n+ \"//pkg/syserror\",\n+ ],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/file_description_impl_util.go",
"new_path": "pkg/sentry/vfs/file_description_impl_util.go",
"diff": "package vfs\nimport (\n+ \"bytes\"\n+ \"io\"\n+ \"sync\"\n+\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/context\"\n@@ -140,3 +144,106 @@ func (DirectoryFileDescriptionDefaultImpl) PWrite(ctx context.Context, src userm\nfunc (DirectoryFileDescriptionDefaultImpl) Write(ctx context.Context, src usermem.IOSequence, opts WriteOptions) (int64, error) {\nreturn 0, syserror.EISDIR\n}\n+\n+// DynamicBytesFileDescriptionImpl may be embedded by implementations of\n+// FileDescriptionImpl that represent read-only regular files whose contents\n+// are backed by a bytes.Buffer that is regenerated when necessary, consistent\n+// with Linux's fs/seq_file.c:single_open().\n+//\n+// DynamicBytesFileDescriptionImpl.SetDataSource() must be called before first\n+// use.\n+type DynamicBytesFileDescriptionImpl struct {\n+ FileDescriptionDefaultImpl\n+\n+ data DynamicBytesSource // immutable\n+ mu sync.Mutex // protects the following fields\n+ buf bytes.Buffer\n+ off int64\n+ lastRead int64 // offset at which the last Read, PRead, or Seek ended\n+}\n+\n+// DynamicBytesSource represents a data source for a\n+// DynamicBytesFileDescriptionImpl.\n+type DynamicBytesSource interface {\n+ // Generate writes the file's contents to buf.\n+ Generate(ctx context.Context, buf *bytes.Buffer) error\n+}\n+\n+// SetDataSource must be called exactly once on fd before first use.\n+func (fd *DynamicBytesFileDescriptionImpl) SetDataSource(data DynamicBytesSource) {\n+ fd.data = data\n+}\n+\n+// Preconditions: fd.mu must be locked.\n+func (fd *DynamicBytesFileDescriptionImpl) preadLocked(ctx context.Context, dst usermem.IOSequence, offset int64, opts *ReadOptions) (int64, error) {\n+ // Regenerate the buffer if it's empty, or before pread() at a new offset.\n+ // Compare fs/seq_file.c:seq_read() => traverse().\n+ switch {\n+ case offset != fd.lastRead:\n+ fd.buf.Reset()\n+ fallthrough\n+ case fd.buf.Len() == 0:\n+ if err := fd.data.Generate(ctx, &fd.buf); err != nil {\n+ fd.buf.Reset()\n+ // fd.off is not updated in this case.\n+ fd.lastRead = 0\n+ return 0, err\n+ }\n+ }\n+ bs := fd.buf.Bytes()\n+ if offset >= int64(len(bs)) {\n+ return 0, io.EOF\n+ }\n+ n, err := dst.CopyOut(ctx, bs[offset:])\n+ fd.lastRead = offset + int64(n)\n+ return int64(n), err\n+}\n+\n+// PRead implements FileDescriptionImpl.PRead.\n+func (fd *DynamicBytesFileDescriptionImpl) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts ReadOptions) (int64, error) {\n+ fd.mu.Lock()\n+ n, err := fd.preadLocked(ctx, dst, offset, &opts)\n+ fd.mu.Unlock()\n+ return n, err\n+}\n+\n+// Read implements FileDescriptionImpl.Read.\n+func (fd *DynamicBytesFileDescriptionImpl) Read(ctx context.Context, dst usermem.IOSequence, opts ReadOptions) (int64, error) {\n+ fd.mu.Lock()\n+ n, err := fd.preadLocked(ctx, dst, fd.off, &opts)\n+ fd.off += n\n+ fd.mu.Unlock()\n+ return n, err\n+}\n+\n+// Seek implements FileDescriptionImpl.Seek.\n+func (fd *DynamicBytesFileDescriptionImpl) Seek(ctx context.Context, offset int64, whence int32) (int64, error) {\n+ fd.mu.Lock()\n+ defer fd.mu.Unlock()\n+ switch whence {\n+ case linux.SEEK_SET:\n+ // Use offset as given.\n+ case linux.SEEK_CUR:\n+ offset += fd.off\n+ default:\n+ // fs/seq_file:seq_lseek() rejects SEEK_END etc.\n+ return 0, syserror.EINVAL\n+ }\n+ if offset < 0 {\n+ return 0, syserror.EINVAL\n+ }\n+ if offset != fd.lastRead {\n+ // Regenerate the file's contents immediately. Compare\n+ // fs/seq_file.c:seq_lseek() => traverse().\n+ fd.buf.Reset()\n+ if err := fd.data.Generate(ctx, &fd.buf); err != nil {\n+ fd.buf.Reset()\n+ fd.off = 0\n+ fd.lastRead = 0\n+ return 0, err\n+ }\n+ fd.lastRead = offset\n+ }\n+ fd.off = offset\n+ return offset, nil\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/vfs/file_description_impl_util_test.go",
"diff": "+// Copyright 2019 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 vfs\n+\n+import (\n+ \"bytes\"\n+ \"fmt\"\n+ \"io\"\n+ \"sync/atomic\"\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/sentry/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/context/contexttest\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/usermem\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+)\n+\n+// genCountFD is a read-only FileDescriptionImpl representing a regular file\n+// that contains the number of times its DynamicBytesSource.Generate()\n+// implementation has been called.\n+type genCountFD struct {\n+ vfsfd FileDescription\n+ DynamicBytesFileDescriptionImpl\n+\n+ count uint64 // accessed using atomic memory ops\n+}\n+\n+func newGenCountFD(mnt *Mount, vfsd *Dentry) *FileDescription {\n+ var fd genCountFD\n+ fd.vfsfd.Init(&fd, mnt, vfsd)\n+ fd.DynamicBytesFileDescriptionImpl.SetDataSource(&fd)\n+ return &fd.vfsfd\n+}\n+\n+// Release implements FileDescriptionImpl.Release.\n+func (fd *genCountFD) Release() {\n+}\n+\n+// StatusFlags implements FileDescriptionImpl.StatusFlags.\n+func (fd *genCountFD) StatusFlags(ctx context.Context) (uint32, error) {\n+ return 0, nil\n+}\n+\n+// SetStatusFlags implements FileDescriptionImpl.SetStatusFlags.\n+func (fd *genCountFD) SetStatusFlags(ctx context.Context, flags uint32) error {\n+ return syserror.EPERM\n+}\n+\n+// Stat implements FileDescriptionImpl.Stat.\n+func (fd *genCountFD) Stat(ctx context.Context, opts StatOptions) (linux.Statx, error) {\n+ // Note that Statx.Mask == 0 in the return value.\n+ return linux.Statx{}, nil\n+}\n+\n+// SetStat implements FileDescriptionImpl.SetStat.\n+func (fd *genCountFD) SetStat(ctx context.Context, opts SetStatOptions) error {\n+ return syserror.EPERM\n+}\n+\n+// Generate implements DynamicBytesSource.Generate.\n+func (fd *genCountFD) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+ fmt.Fprintf(buf, \"%d\", atomic.AddUint64(&fd.count, 1))\n+ return nil\n+}\n+\n+func TestGenCountFD(t *testing.T) {\n+ ctx := contexttest.Context(t)\n+ creds := auth.CredentialsFromContext(ctx)\n+\n+ vfsObj := New() // vfs.New()\n+ vfsObj.MustRegisterFilesystemType(\"testfs\", FDTestFilesystemType{})\n+ mntns, err := vfsObj.NewMountNamespace(ctx, creds, \"\", \"testfs\", &NewFilesystemOptions{})\n+ if err != nil {\n+ t.Fatalf(\"failed to create testfs root mount: %v\", err)\n+ }\n+ vd := mntns.Root()\n+ defer vd.DecRef()\n+\n+ fd := newGenCountFD(vd.Mount(), vd.Dentry())\n+ defer fd.DecRef()\n+\n+ // The first read causes Generate to be called to fill the FD's buffer.\n+ buf := make([]byte, 2)\n+ ioseq := usermem.BytesIOSequence(buf)\n+ n, err := fd.Impl().Read(ctx, ioseq, ReadOptions{})\n+ if n != 1 || (err != nil && err != io.EOF) {\n+ t.Fatalf(\"first Read: got (%d, %v), wanted (1, nil or EOF)\", n, err)\n+ }\n+ if want := byte('1'); buf[0] != want {\n+ t.Errorf(\"first Read: got byte %c, wanted %c\", buf[0], want)\n+ }\n+\n+ // A second read without seeking is still at EOF.\n+ n, err = fd.Impl().Read(ctx, ioseq, ReadOptions{})\n+ if n != 0 || err != io.EOF {\n+ t.Fatalf(\"second Read: got (%d, %v), wanted (0, EOF)\", n, err)\n+ }\n+\n+ // Seeking to the beginning of the file causes it to be regenerated.\n+ n, err = fd.Impl().Seek(ctx, 0, linux.SEEK_SET)\n+ if n != 0 || err != nil {\n+ t.Fatalf(\"Seek: got (%d, %v), wanted (0, nil)\", n, err)\n+ }\n+ n, err = fd.Impl().Read(ctx, ioseq, ReadOptions{})\n+ if n != 1 || (err != nil && err != io.EOF) {\n+ t.Fatalf(\"Read after Seek: got (%d, %v), wanted (1, nil or EOF)\", n, err)\n+ }\n+ if want := byte('2'); buf[0] != want {\n+ t.Errorf(\"Read after Seek: got byte %c, wanted %c\", buf[0], want)\n+ }\n+\n+ // PRead at the beginning of the file also causes it to be regenerated.\n+ n, err = fd.Impl().PRead(ctx, ioseq, 0, ReadOptions{})\n+ if n != 1 || (err != nil && err != io.EOF) {\n+ t.Fatalf(\"PRead: got (%d, %v), wanted (1, nil or EOF)\", n, err)\n+ }\n+ if want := byte('3'); buf[0] != want {\n+ t.Errorf(\"PRead: got byte %c, wanted %c\", buf[0], want)\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/vfs/testutil.go",
"diff": "+// Copyright 2019 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 vfs\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/sentry/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+)\n+\n+// FDTestFilesystemType is a test-only FilesystemType that produces Filesystems\n+// for which all FilesystemImpl methods taking a path return EPERM. It is used\n+// to produce Mounts and Dentries for testing of FileDescriptionImpls that do\n+// not depend on their originating Filesystem.\n+type FDTestFilesystemType struct{}\n+\n+// FDTestFilesystem is a test-only FilesystemImpl produced by\n+// FDTestFilesystemType.\n+type FDTestFilesystem struct {\n+ vfsfs Filesystem\n+}\n+\n+// NewFilesystem implements FilesystemType.NewFilesystem.\n+func (fstype FDTestFilesystemType) NewFilesystem(ctx context.Context, creds *auth.Credentials, source string, opts NewFilesystemOptions) (*Filesystem, *Dentry, error) {\n+ var fs FDTestFilesystem\n+ fs.vfsfs.Init(&fs)\n+ return &fs.vfsfs, fs.NewDentry(), nil\n+}\n+\n+// Release implements FilesystemImpl.Release.\n+func (fs *FDTestFilesystem) Release() {\n+}\n+\n+// Sync implements FilesystemImpl.Sync.\n+func (fs *FDTestFilesystem) Sync(ctx context.Context) error {\n+ return nil\n+}\n+\n+// GetDentryAt implements FilesystemImpl.GetDentryAt.\n+func (fs *FDTestFilesystem) GetDentryAt(ctx context.Context, rp *ResolvingPath, opts GetDentryOptions) (*Dentry, error) {\n+ return nil, syserror.EPERM\n+}\n+\n+// LinkAt implements FilesystemImpl.LinkAt.\n+func (fs *FDTestFilesystem) LinkAt(ctx context.Context, rp *ResolvingPath, vd VirtualDentry) error {\n+ return syserror.EPERM\n+}\n+\n+// MkdirAt implements FilesystemImpl.MkdirAt.\n+func (fs *FDTestFilesystem) MkdirAt(ctx context.Context, rp *ResolvingPath, opts MkdirOptions) error {\n+ return syserror.EPERM\n+}\n+\n+// MknodAt implements FilesystemImpl.MknodAt.\n+func (fs *FDTestFilesystem) MknodAt(ctx context.Context, rp *ResolvingPath, opts MknodOptions) error {\n+ return syserror.EPERM\n+}\n+\n+// OpenAt implements FilesystemImpl.OpenAt.\n+func (fs *FDTestFilesystem) OpenAt(ctx context.Context, rp *ResolvingPath, opts OpenOptions) (*FileDescription, error) {\n+ return nil, syserror.EPERM\n+}\n+\n+// ReadlinkAt implements FilesystemImpl.ReadlinkAt.\n+func (fs *FDTestFilesystem) ReadlinkAt(ctx context.Context, rp *ResolvingPath) (string, error) {\n+ return \"\", syserror.EPERM\n+}\n+\n+// RenameAt implements FilesystemImpl.RenameAt.\n+func (fs *FDTestFilesystem) RenameAt(ctx context.Context, rp *ResolvingPath, vd VirtualDentry, opts RenameOptions) error {\n+ return syserror.EPERM\n+}\n+\n+// RmdirAt implements FilesystemImpl.RmdirAt.\n+func (fs *FDTestFilesystem) RmdirAt(ctx context.Context, rp *ResolvingPath) error {\n+ return syserror.EPERM\n+}\n+\n+// SetStatAt implements FilesystemImpl.SetStatAt.\n+func (fs *FDTestFilesystem) SetStatAt(ctx context.Context, rp *ResolvingPath, opts SetStatOptions) error {\n+ return syserror.EPERM\n+}\n+\n+// StatAt implements FilesystemImpl.StatAt.\n+func (fs *FDTestFilesystem) StatAt(ctx context.Context, rp *ResolvingPath, opts StatOptions) (linux.Statx, error) {\n+ return linux.Statx{}, syserror.EPERM\n+}\n+\n+// StatFSAt implements FilesystemImpl.StatFSAt.\n+func (fs *FDTestFilesystem) StatFSAt(ctx context.Context, rp *ResolvingPath) (linux.Statfs, error) {\n+ return linux.Statfs{}, syserror.EPERM\n+}\n+\n+// SymlinkAt implements FilesystemImpl.SymlinkAt.\n+func (fs *FDTestFilesystem) SymlinkAt(ctx context.Context, rp *ResolvingPath, target string) error {\n+ return syserror.EPERM\n+}\n+\n+// UnlinkAt implements FilesystemImpl.UnlinkAt.\n+func (fs *FDTestFilesystem) UnlinkAt(ctx context.Context, rp *ResolvingPath) error {\n+ return syserror.EPERM\n+}\n+\n+type fdTestDentry struct {\n+ vfsd Dentry\n+}\n+\n+// NewDentry returns a new Dentry.\n+func (fs *FDTestFilesystem) NewDentry() *Dentry {\n+ var d fdTestDentry\n+ d.vfsd.Init(&d)\n+ return &d.vfsd\n+}\n+\n+// IncRef implements DentryImpl.IncRef.\n+func (d *fdTestDentry) IncRef(vfsfs *Filesystem) {\n+}\n+\n+// TryIncRef implements DentryImpl.TryIncRef.\n+func (d *fdTestDentry) TryIncRef(vfsfs *Filesystem) bool {\n+ return true\n+}\n+\n+// DecRef implements DentryImpl.DecRef.\n+func (d *fdTestDentry) DecRef(vfsfs *Filesystem) {\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add vfs.DynamicBytesFileDescriptionImpl.
This replaces fs/proc/seqfile for vfs2-based filesystems.
PiperOrigin-RevId: 263254647 |
259,884 | 14.08.2019 10:05:14 | 14,400 | 76a12063a6566a2e1c8e2c3589ebf90e91da3dc7 | Fix performance graph shortcode invocations | [
{
"change_type": "MODIFY",
"old_path": "content/docs/architecture_guide/performance.md",
"new_path": "content/docs/architecture_guide/performance.md",
"diff": "@@ -68,7 +68,7 @@ accesses. Page faults and other Operating System (OS) mechanisms are translated\nthrough the Sentry, but once mappings are installed and available to the\napplication, there is no additional overhead.\n-{{< graph id=\"sysbench-memory\" url=\"/performance/sysbench-memory.csv\" title=\"perf.py sysbench.memory --runtime=runc --runtime=runsc\" >}}\n+{{< graph id=\"sysbench-memory\" url=\"/performance/sysbench-memory.csv\" title=\"perf.py sysbench.memory --runtime=runc --runtime=runsc\" >}}\nThe above figure demonstrates the memory transfer rate as measured by\n`sysbench`.\n@@ -84,7 +84,7 @@ For many use cases, fixed memory overheads are a primary concern. This may be\nbecause sandboxed containers handle a low volume of requests, and it is\ntherefore important to achieve high densities for efficiency.\n-{{< graph id=\"density\" url=\"/performance/density.csv\" title=\"perf.py density --runtime=runc --runtime=runsc\" log=\"true\" y_min=\"100000\" >}}\n+{{< graph id=\"density\" url=\"/performance/density.csv\" title=\"perf.py density --runtime=runc --runtime=runsc\" log=\"true\" y_min=\"100000\" >}}\nThe above figure demonstrates these costs based on three sample applications.\nThis test is the result of running many instances of a container (50, or 5 in\n@@ -107,7 +107,7 @@ gVisor does not perform emulation or otherwise interfere with the raw execution\nof CPU instructions by the application. Therefore, there is no runtime cost\nimposed for CPU operations.\n-{{< graph id=\"sysbench-cpu\" url=\"/performance/sysbench-cpu.csv\" title=\"perf.py sysbench.cpu --runtime=runc --runtime=runsc\" >}}\n+{{< graph id=\"sysbench-cpu\" url=\"/performance/sysbench-cpu.csv\" title=\"perf.py sysbench.cpu --runtime=runc --runtime=runsc\" >}}\nThe above figure demonstrates the `sysbench` measurement of CPU events per\nsecond. Events per second is based on a CPU-bound loop that calculates all prime\n@@ -118,7 +118,7 @@ This has important consequences for classes of workloads that are often\nCPU-bound, such as data processing or machine learning. In these cases, `runsc`\nwill similarly impose minimal runtime overhead.\n-{{< graph id=\"tensorflow\" url=\"/performance/tensorflow.csv\" title=\"perf.py tensorflow --runtime=runc --runtime=runsc\" >}}\n+{{< graph id=\"tensorflow\" url=\"/performance/tensorflow.csv\" title=\"perf.py tensorflow --runtime=runc --runtime=runsc\" >}}\nFor example, the above figure shows a sample TensorFlow workload, the\n[convolutional neural network example][cnn]. The time indicated includes the\n@@ -132,7 +132,7 @@ supports a variety of platforms. These platforms present distinct performance,\ncompatibility and security trade-offs. For example, the KVM platform has low\noverhead system call interception but runs poorly with nested virtualization.\n-{{< graph id=\"syscall\" url=\"/performance/syscall.csv\" title=\"perf.py syscall --runtime=runc --runtime=runsc-ptrace --runtime=runsc-kvm\" y_min=\"100\" log=\"true\" >}}\n+{{< graph id=\"syscall\" url=\"/performance/syscall.csv\" title=\"perf.py syscall --runtime=runc --runtime=runsc-ptrace --runtime=runsc-kvm\" y_min=\"100\" log=\"true\" >}}\nThe above figure demonstrates the time required for a raw system call on various\nplatforms. The test is implemented by a custom binary which performs a large\n@@ -143,7 +143,7 @@ tend to be high-performance data stores and static network services. In general,\nthe impact of system call interception will be lower the more work an\napplication does.\n-{{< graph id=\"redis\" url=\"/performance/redis.csv\" title=\"perf.py redis --runtime=runc --runtime=runsc\" >}}\n+{{< graph id=\"redis\" url=\"/performance/redis.csv\" title=\"perf.py redis --runtime=runc --runtime=runsc\" >}}\nFor example, `redis` is an application that performs relatively little work in\nuserspace: in general it reads from a connected socket, reads or modifies some\n@@ -163,7 +163,7 @@ For many use cases, the ability to spin-up containers quickly and efficiently is\nimportant. A sandbox may be short-lived and perform minimal user work (e.g. a\nfunction invocation).\n-{{< graph id=\"startup\" url=\"/performance/startup.csv\" title=\"perf.py startup --runtime=runc --runtime=runsc\" >}}\n+{{< graph id=\"startup\" url=\"/performance/startup.csv\" title=\"perf.py startup --runtime=runc --runtime=runsc\" >}}\nThe above figure indicates how total time required to start a container through\n[Docker][docker]. This benchmark uses three different applications. First, an\n@@ -186,14 +186,14 @@ While typically not an important metric in practice for common sandbox use\ncases, nevertheless `iperf` is a common microbenchmark used to measure raw\nthroughput.\n-{{< graph id=\"iperf\" url=\"/performance/iperf.csv\" title=\"perf.py iperf --runtime=runc --runtime=runsc\" >}}\n+{{< graph id=\"iperf\" url=\"/performance/iperf.csv\" title=\"perf.py iperf --runtime=runc --runtime=runsc\" >}}\nThe above figure shows the result of an `iperf` test between two instances. For\nthe upload case, the specified runtime is used for the `iperf` client, and in\nthe download case, the specified runtime is the server. A native runtime is\nalways used for the other endpoint in the test.\n-{{< graph id=\"applications\" metric=\"requests_per_second\" url=\"/performance/applications.csv\" title=\"perf.py http.(node|ruby) --connections=25 --runtime=runc --runtime=runsc\" >}}\n+{{< graph id=\"applications\" metric=\"requests_per_second\" url=\"/performance/applications.csv\" title=\"perf.py http.(node|ruby) --connections=25 --runtime=runc --runtime=runsc\" >}}\nThe above figure shows the result of simple `node` and `ruby` web services that\nrender a template upon receiving a request. Because these synthetic benchmarks\n@@ -214,20 +214,20 @@ through the [Gofer](../) as a result of our [security model](../security/), but\nin most cases are dominated by **implementation costs**, due to an internal\n[Virtual File System][vfs] (VFS) implementation that needs improvement.\n-{{< graph id=\"fio-bw\" url=\"/performance/fio.csv\" title=\"perf.py fio --engine=sync --runtime=runc --runtime=runsc\" log=\"true\" >}}\n+{{< graph id=\"fio-bw\" url=\"/performance/fio.csv\" title=\"perf.py fio --engine=sync --runtime=runc --runtime=runsc\" log=\"true\" >}}\nThe above figures demonstrate the results of `fio` for reads and writes to and\nfrom the disk. In this case, the disk quickly becomes the bottleneck and\ndominates other costs.\n-{{< graph id=\"fio-tmpfs-bw\" url=\"/performance/fio-tmpfs.csv\" title=\"perf.py fio --engine=sync --runtime=runc --tmpfs=True --runtime=runsc\" log=\"true\" >}}\n+{{< graph id=\"fio-tmpfs-bw\" url=\"/performance/fio-tmpfs.csv\" title=\"perf.py fio --engine=sync --runtime=runc --tmpfs=True --runtime=runsc\" log=\"true\" >}}\nThe above figure shows the raw I/O performance of using a `tmpfs` mount which is\nsandbox-internal in the case of `runsc`. Generally these operations are\nsimilarly bound to the cost of copying around data in-memory, and we don't see\nthe cost of VFS operations.\n-{{< graph id=\"httpd100k\" metric=\"transfer_rate\" url=\"/performance/httpd100k.csv\" title=\"perf.py http.httpd --connections=1 --connections=5 --connections=10 --connections=25 --runtime=runc --runtime=runsc\" >}}\n+{{< graph id=\"httpd100k\" metric=\"transfer_rate\" url=\"/performance/httpd100k.csv\" title=\"perf.py http.httpd --connections=1 --connections=5 --connections=10 --connections=25 --runtime=runc --runtime=runsc\" >}}\nThe high costs of VFS operations can manifest in benchmarks that execute many\nsuch operations in the hot path for serving requests, for example. The above\n@@ -240,7 +240,7 @@ internal serialization points (since all requests are reading the same file).\nNote that some of some of network stack performance issues also impact this\nbenchmark.\n-{{< graph id=\"ffmpeg\" url=\"/performance/ffmpeg.csv\" title=\"perf.py media.ffmpeg --runtime=runc --runtime=runsc\" >}}\n+{{< graph id=\"ffmpeg\" url=\"/performance/ffmpeg.csv\" title=\"perf.py media.ffmpeg --runtime=runc --runtime=runsc\" >}}\nFor benchmarks that are bound by raw disk I/O and a mix of compute, file system\noperations are less of an issue. The above figure shows the total time required\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix performance graph shortcode invocations |
259,974 | 15.08.2019 02:04:47 | 0 | 0624858593847096b68ecbd262e2cae6ea79048a | Rename rawfile/blockingpoll_unsafe.go to rawfile/blockingpoll_stub_unsafe.go. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/rawfile/BUILD",
"new_path": "pkg/tcpip/link/rawfile/BUILD",
"diff": "@@ -7,7 +7,7 @@ go_library(\nsrcs = [\n\"blockingpoll_amd64.s\",\n\"blockingpoll_amd64_unsafe.go\",\n- \"blockingpoll_unsafe.go\",\n+ \"blockingpoll_stub_unsafe.go\",\n\"errors.go\",\n\"rawfile_unsafe.go\",\n],\n"
},
{
"change_type": "RENAME",
"old_path": "pkg/tcpip/link/rawfile/blockingpoll_unsafe.go",
"new_path": "pkg/tcpip/link/rawfile/blockingpoll_stub_unsafe.go",
"diff": ""
}
] | Go | Apache License 2.0 | google/gvisor | Rename rawfile/blockingpoll_unsafe.go to rawfile/blockingpoll_stub_unsafe.go.
Signed-off-by: Haibo Xu [email protected]
Change-Id: I2376e502c1a860d5e624c8a8e3afab5da4c53022 |
259,974 | 15.08.2019 02:20:30 | 0 | 52843719ca8f4e5a91fed4916ecb0e483ac025b9 | Rename fdbased/mmap.go to fdbased/mmap_stub.go. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/BUILD",
"new_path": "pkg/tcpip/link/fdbased/BUILD",
"diff": "@@ -7,9 +7,9 @@ go_library(\nsrcs = [\n\"endpoint.go\",\n\"endpoint_unsafe.go\",\n- \"mmap.go\",\n\"mmap_amd64.go\",\n\"mmap_amd64_unsafe.go\",\n+ \"mmap_stub.go\",\n\"packet_dispatchers.go\",\n],\nimportpath = \"gvisor.dev/gvisor/pkg/tcpip/link/fdbased\",\n"
},
{
"change_type": "RENAME",
"old_path": "pkg/tcpip/link/fdbased/mmap.go",
"new_path": "pkg/tcpip/link/fdbased/mmap_stub.go",
"diff": ""
}
] | Go | Apache License 2.0 | google/gvisor | Rename fdbased/mmap.go to fdbased/mmap_stub.go.
Signed-off-by: Haibo Xu [email protected]
Change-Id: Id4489554b9caa332695df8793d361f8332f6a13b |
259,974 | 15.08.2019 03:11:15 | 0 | 1b1e39d7a1846e9afa9b794c5780a703f4b05211 | Enabling pkg/tcpip/link support on arm64. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/BUILD",
"new_path": "pkg/tcpip/link/fdbased/BUILD",
"diff": "@@ -7,9 +7,9 @@ go_library(\nsrcs = [\n\"endpoint.go\",\n\"endpoint_unsafe.go\",\n- \"mmap_amd64.go\",\n- \"mmap_amd64_unsafe.go\",\n+ \"mmap.go\",\n\"mmap_stub.go\",\n+ \"mmap_unsafe.go\",\n\"packet_dispatchers.go\",\n],\nimportpath = \"gvisor.dev/gvisor/pkg/tcpip/link/fdbased\",\n"
},
{
"change_type": "RENAME",
"old_path": "pkg/tcpip/link/fdbased/mmap_amd64.go",
"new_path": "pkg/tcpip/link/fdbased/mmap.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build linux,amd64\n+// +build linux,amd64 linux,arm64\npackage fdbased\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/mmap_stub.go",
"new_path": "pkg/tcpip/link/fdbased/mmap_stub.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build !linux !amd64\n+// +build !linux !amd64,!arm64\npackage fdbased\n-// Stubbed out version for non-linux/non-amd64 platforms.\n+// Stubbed out version for non-linux/non-amd64/non-arm64 platforms.\nfunc newPacketMMapDispatcher(fd int, e *endpoint) (linkDispatcher, error) {\nreturn nil, nil\n"
},
{
"change_type": "RENAME",
"old_path": "pkg/tcpip/link/fdbased/mmap_amd64_unsafe.go",
"new_path": "pkg/tcpip/link/fdbased/mmap_unsafe.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build linux,amd64\n+// +build linux,amd64 linux,arm64\npackage fdbased\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/rawfile/BUILD",
"new_path": "pkg/tcpip/link/rawfile/BUILD",
"diff": "@@ -6,7 +6,8 @@ go_library(\nname = \"rawfile\",\nsrcs = [\n\"blockingpoll_amd64.s\",\n- \"blockingpoll_amd64_unsafe.go\",\n+ \"blockingpoll_arm64.s\",\n+ \"blockingpoll_unsafe.go\",\n\"blockingpoll_stub_unsafe.go\",\n\"errors.go\",\n\"rawfile_unsafe.go\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/rawfile/blockingpoll_stub_unsafe.go",
"new_path": "pkg/tcpip/link/rawfile/blockingpoll_stub_unsafe.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build linux,!amd64\n+// +build linux,!amd64,!arm64\npackage rawfile\n@@ -22,7 +22,7 @@ import (\n)\n// BlockingPoll is just a stub function that forwards to the ppoll() system call\n-// on non-amd64 platforms.\n+// on non-amd64 and non-arm64 platforms.\nfunc BlockingPoll(fds *PollEvent, nfds int, timeout *syscall.Timespec) (int, syscall.Errno) {\nn, _, e := syscall.Syscall6(syscall.SYS_PPOLL, uintptr(unsafe.Pointer(fds)),\nuintptr(nfds), uintptr(unsafe.Pointer(timeout)), 0, 0, 0)\n"
},
{
"change_type": "RENAME",
"old_path": "pkg/tcpip/link/rawfile/blockingpoll_amd64_unsafe.go",
"new_path": "pkg/tcpip/link/rawfile/blockingpoll_unsafe.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build linux,amd64\n+// +build linux,amd64 linux,arm64\n// +build go1.12\n// +build !go1.14\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enabling pkg/tcpip/link support on arm64.
Signed-off-by: Haibo Xu [email protected]
Change-Id: Ib6b4aa2db19032e58bf0395f714e6883caee460a |
259,985 | 15.08.2019 14:04:44 | 25,200 | 6cfc76798b586a6c33c1ec311cb5f0d82b90ca72 | Document source and versioning of the TCPInfo struct. | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/socket.go",
"new_path": "pkg/abi/linux/socket.go",
"diff": "@@ -292,7 +292,10 @@ const SizeOfLinger = 8\n// TCPInfo is a collection of TCP statistics.\n//\n-// From uapi/linux/tcp.h.\n+// From uapi/linux/tcp.h. Newer versions of Linux continue to add new fields to\n+// the end of this struct or within existing unusued space, so its size grows\n+// over time. The current iteration is based on linux v4.17. New versions are\n+// always backwards compatible.\ntype TCPInfo struct {\nState uint8\nCaState uint8\n"
}
] | Go | Apache License 2.0 | google/gvisor | Document source and versioning of the TCPInfo struct.
PiperOrigin-RevId: 263637194 |
259,891 | 15.08.2019 16:30:25 | 25,200 | ef045b914bc8d9795f9184aed4b13351be70a3cf | Add tests for "cooked" AF_PACKET sockets. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -249,6 +249,8 @@ syscall_test(\ntest = \"//test/syscalls/linux:open_test\",\n)\n+syscall_test(test = \"//test/syscalls/linux:packet_socket_test\")\n+\nsyscall_test(test = \"//test/syscalls/linux:partial_bad_buffer_test\")\nsyscall_test(test = \"//test/syscalls/linux:pause_test\")\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -1208,6 +1208,24 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"packet_socket_test\",\n+ testonly = 1,\n+ srcs = [\"packet_socket.cc\"],\n+ linkstatic = 1,\n+ deps = [\n+ \":socket_test_util\",\n+ \":unix_domain_socket_test_util\",\n+ \"//test/util:capability_util\",\n+ \"//test/util:file_descriptor\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ \"@com_google_absl//absl/base:core_headers\",\n+ \"@com_google_absl//absl/base:endian\",\n+ \"@com_google_googletest//:gtest\",\n+ ],\n+)\n+\ncc_binary(\nname = \"pty_test\",\ntestonly = 1,\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/packet_socket.cc",
"diff": "+// Copyright 2019 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <arpa/inet.h>\n+#include <linux/capability.h>\n+#include <linux/if_arp.h>\n+#include <linux/if_packet.h>\n+#include <net/ethernet.h>\n+#include <netinet/in.h>\n+#include <netinet/ip.h>\n+#include <netinet/udp.h>\n+#include <poll.h>\n+#include <sys/ioctl.h>\n+#include <sys/socket.h>\n+#include <sys/types.h>\n+#include <unistd.h>\n+\n+#include \"gtest/gtest.h\"\n+#include \"absl/base/internal/endian.h\"\n+#include \"test/syscalls/linux/socket_test_util.h\"\n+#include \"test/syscalls/linux/unix_domain_socket_test_util.h\"\n+#include \"test/util/capability_util.h\"\n+#include \"test/util/file_descriptor.h\"\n+#include \"test/util/test_util.h\"\n+\n+// Some of these tests involve sending packets via AF_PACKET sockets and the\n+// loopback interface. Because AF_PACKET circumvents so much of the networking\n+// stack, Linux sees these packets as \"martian\", i.e. they claim to be to/from\n+// localhost but don't have the usual associated data. Thus Linux drops them by\n+// default. You can see where this happens by following the code at:\n+//\n+// - net/ipv4/ip_input.c:ip_rcv_finish, which calls\n+// - net/ipv4/route.c:ip_route_input_noref, which calls\n+// - net/ipv4/route.c:ip_route_input_slow, which finds and drops martian\n+// packets.\n+//\n+// To tell Linux not to drop these packets, you need to tell it to accept our\n+// funny packets (which are completely valid and correct, but lack associated\n+// in-kernel data because we use AF_PACKET):\n+//\n+// echo 1 >> /proc/sys/net/ipv4/conf/lo/accept_local\n+// echo 1 >> /proc/sys/net/ipv4/conf/lo/route_localnet\n+//\n+// These tests require CAP_NET_RAW to run.\n+\n+// TODO(gvisor.dev/issue/173): gVisor support.\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+constexpr char kMessage[] = \"soweoneul malhaebwa\";\n+constexpr in_port_t kPort = 0x409c; // htons(40000)\n+\n+//\n+// \"Cooked\" tests. Cooked AF_PACKET sockets do not contain link layer\n+// headers, and provide link layer destination/source information via a\n+// returned struct sockaddr_ll.\n+//\n+\n+// Send kMessage via sock to loopback\n+void SendUDPMessage(int sock) {\n+ struct sockaddr_in dest = {};\n+ dest.sin_port = kPort;\n+ dest.sin_addr.s_addr = htonl(INADDR_LOOPBACK);\n+ dest.sin_family = AF_INET;\n+ EXPECT_THAT(sendto(sock, kMessage, sizeof(kMessage), 0,\n+ reinterpret_cast<struct sockaddr*>(&dest), sizeof(dest)),\n+ SyscallSucceedsWithValue(sizeof(kMessage)));\n+}\n+\n+// Send an IP packet and make sure ETH_P_<something else> doesn't pick it up.\n+TEST(BasicCookedPacketTest, WrongType) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ FileDescriptor sock =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_PACKET, SOCK_DGRAM, ETH_P_PUP));\n+\n+ // Let's use a simple IP payload: a UDP datagram.\n+ FileDescriptor udp_sock =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));\n+ SendUDPMessage(udp_sock.get());\n+\n+ // Wait and make sure the socket never becomes readable.\n+ struct pollfd pfd = {};\n+ pfd.fd = sock.get();\n+ pfd.events = POLLIN;\n+ EXPECT_THAT(RetryEINTR(poll)(&pfd, 1, 1000), SyscallSucceedsWithValue(0));\n+}\n+\n+// Tests for \"cooked\" (SOCK_DGRAM) packet(7) sockets.\n+class CookedPacketTest : public ::testing::TestWithParam<int> {\n+ protected:\n+ // Creates a socket to be used in tests.\n+ void SetUp() override;\n+\n+ // Closes the socket created by SetUp().\n+ void TearDown() override;\n+\n+ // Gets the device index of the loopback device.\n+ int GetLoopbackIndex();\n+\n+ // The socket used for both reading and writing.\n+ int socket_;\n+};\n+\n+void CookedPacketTest::SetUp() {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ ASSERT_THAT(socket_ = socket(AF_PACKET, SOCK_DGRAM, htons(GetParam())),\n+ SyscallSucceeds());\n+}\n+\n+void CookedPacketTest::TearDown() {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ EXPECT_THAT(close(socket_), SyscallSucceeds());\n+}\n+\n+int CookedPacketTest::GetLoopbackIndex() {\n+ struct ifreq ifr;\n+ snprintf(ifr.ifr_name, IFNAMSIZ, \"lo\");\n+ EXPECT_THAT(ioctl(socket_, SIOCGIFINDEX, &ifr), SyscallSucceeds());\n+ EXPECT_NE(ifr.ifr_ifindex, 0);\n+ return ifr.ifr_ifindex;\n+}\n+\n+// Receive via a packet socket.\n+TEST_P(CookedPacketTest, Receive) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ // Let's use a simple IP payload: a UDP datagram.\n+ FileDescriptor udp_sock =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));\n+ SendUDPMessage(udp_sock.get());\n+\n+ // Wait for the socket to become readable.\n+ struct pollfd pfd = {};\n+ pfd.fd = socket_;\n+ pfd.events = POLLIN;\n+ EXPECT_THAT(RetryEINTR(poll)(&pfd, 1, 2000), SyscallSucceedsWithValue(1));\n+\n+ // Read and verify the data.\n+ constexpr size_t packet_size =\n+ sizeof(struct iphdr) + sizeof(struct udphdr) + sizeof(kMessage);\n+ char buf[64];\n+ struct sockaddr_ll src = {};\n+ socklen_t src_len = sizeof(src);\n+ ASSERT_THAT(recvfrom(socket_, buf, sizeof(buf), 0,\n+ reinterpret_cast<struct sockaddr*>(&src), &src_len),\n+ SyscallSucceedsWithValue(packet_size));\n+ ASSERT_EQ(src_len, sizeof(src));\n+\n+ // Verify the source address.\n+ EXPECT_EQ(src.sll_family, AF_PACKET);\n+ EXPECT_EQ(src.sll_protocol, htons(ETH_P_IP));\n+ EXPECT_EQ(src.sll_ifindex, GetLoopbackIndex());\n+ EXPECT_EQ(src.sll_hatype, ARPHRD_LOOPBACK);\n+ EXPECT_EQ(src.sll_halen, ETH_ALEN);\n+ // This came from the loopback device, so the address is all 0s.\n+ for (int i = 0; i < src.sll_halen; i++) {\n+ EXPECT_EQ(src.sll_addr[i], 0);\n+ }\n+\n+ // Verify the IP header. We memcpy to deal with pointer aligment.\n+ struct iphdr ip = {};\n+ memcpy(&ip, buf, sizeof(ip));\n+ EXPECT_EQ(ip.ihl, 5);\n+ EXPECT_EQ(ip.version, 4);\n+ EXPECT_EQ(ip.tot_len, htons(packet_size));\n+ EXPECT_EQ(ip.protocol, IPPROTO_UDP);\n+ EXPECT_EQ(ip.daddr, htonl(INADDR_LOOPBACK));\n+ EXPECT_EQ(ip.saddr, htonl(INADDR_LOOPBACK));\n+\n+ // Verify the UDP header. We memcpy to deal with pointer aligment.\n+ struct udphdr udp = {};\n+ memcpy(&udp, buf + sizeof(iphdr), sizeof(udp));\n+ EXPECT_EQ(udp.dest, kPort);\n+ EXPECT_EQ(udp.len, htons(sizeof(udphdr) + sizeof(kMessage)));\n+\n+ // Verify the payload.\n+ char* payload = reinterpret_cast<char*>(buf + sizeof(iphdr) + sizeof(udphdr));\n+ EXPECT_EQ(strncmp(payload, kMessage, sizeof(kMessage)), 0);\n+}\n+\n+// Send via a packet socket.\n+TEST_P(CookedPacketTest, Send) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ // Let's send a UDP packet and receive it using a regular UDP socket.\n+ FileDescriptor udp_sock =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));\n+ struct sockaddr_in bind_addr = {};\n+ bind_addr.sin_family = AF_INET;\n+ bind_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);\n+ bind_addr.sin_port = kPort;\n+ ASSERT_THAT(\n+ bind(udp_sock.get(), reinterpret_cast<struct sockaddr*>(&bind_addr),\n+ sizeof(bind_addr)),\n+ SyscallSucceeds());\n+\n+ // Set up the destination physical address.\n+ struct sockaddr_ll dest = {};\n+ dest.sll_family = AF_PACKET;\n+ dest.sll_halen = ETH_ALEN;\n+ dest.sll_ifindex = GetLoopbackIndex();\n+ dest.sll_protocol = htons(ETH_P_IP);\n+ // We're sending to the loopback device, so the address is all 0s.\n+ memset(dest.sll_addr, 0x00, ETH_ALEN);\n+\n+ // Set up the IP header.\n+ struct iphdr iphdr = {0};\n+ iphdr.ihl = 5;\n+ iphdr.version = 4;\n+ iphdr.tos = 0;\n+ iphdr.tot_len =\n+ htons(sizeof(struct iphdr) + sizeof(struct udphdr) + sizeof(kMessage));\n+ // Get a pseudo-random ID. If we clash with an in-use ID the test will fail,\n+ // but we have no way of getting an ID we know to be good.\n+ srand(*reinterpret_cast<unsigned int*>(&iphdr));\n+ iphdr.id = rand();\n+ // Linux sets this bit (\"do not fragment\") for small packets.\n+ iphdr.frag_off = 1 << 6;\n+ iphdr.ttl = 64;\n+ iphdr.protocol = IPPROTO_UDP;\n+ iphdr.daddr = htonl(INADDR_LOOPBACK);\n+ iphdr.saddr = htonl(INADDR_LOOPBACK);\n+ iphdr.check = IPChecksum(iphdr);\n+\n+ // Set up the UDP header.\n+ struct udphdr udphdr = {};\n+ udphdr.source = kPort;\n+ udphdr.dest = kPort;\n+ udphdr.len = htons(sizeof(udphdr) + sizeof(kMessage));\n+ udphdr.check = UDPChecksum(iphdr, udphdr, kMessage, sizeof(kMessage));\n+\n+ // Copy both headers and the payload into our packet buffer.\n+ char send_buf[sizeof(iphdr) + sizeof(udphdr) + sizeof(kMessage)];\n+ memcpy(send_buf, &iphdr, sizeof(iphdr));\n+ memcpy(send_buf + sizeof(iphdr), &udphdr, sizeof(udphdr));\n+ memcpy(send_buf + sizeof(iphdr) + sizeof(udphdr), kMessage, sizeof(kMessage));\n+\n+ // Send it.\n+ ASSERT_THAT(sendto(socket_, send_buf, sizeof(send_buf), 0,\n+ reinterpret_cast<struct sockaddr*>(&dest), sizeof(dest)),\n+ SyscallSucceedsWithValue(sizeof(send_buf)));\n+\n+ // Wait for the packet to become available on both sockets.\n+ struct pollfd pfd = {};\n+ pfd.fd = udp_sock.get();\n+ pfd.events = POLLIN;\n+ ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, 5000), SyscallSucceedsWithValue(1));\n+ pfd.fd = socket_;\n+ pfd.events = POLLIN;\n+ ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, 5000), SyscallSucceedsWithValue(1));\n+\n+ // Receive on the packet socket.\n+ char recv_buf[sizeof(send_buf)];\n+ ASSERT_THAT(recv(socket_, recv_buf, sizeof(recv_buf), 0),\n+ SyscallSucceedsWithValue(sizeof(recv_buf)));\n+ ASSERT_EQ(memcmp(recv_buf, send_buf, sizeof(send_buf)), 0);\n+\n+ // Receive on the UDP socket.\n+ struct sockaddr_in src;\n+ socklen_t src_len = sizeof(src);\n+ ASSERT_THAT(recvfrom(udp_sock.get(), recv_buf, sizeof(recv_buf), MSG_DONTWAIT,\n+ reinterpret_cast<struct sockaddr*>(&src), &src_len),\n+ SyscallSucceedsWithValue(sizeof(kMessage)));\n+ // Check src and payload.\n+ EXPECT_EQ(strncmp(recv_buf, kMessage, sizeof(kMessage)), 0);\n+ EXPECT_EQ(src.sin_family, AF_INET);\n+ EXPECT_EQ(src.sin_port, kPort);\n+ EXPECT_EQ(src.sin_addr.s_addr, htonl(INADDR_LOOPBACK));\n+}\n+\n+INSTANTIATE_TEST_SUITE_P(AllInetTests, CookedPacketTest,\n+ ::testing::Values(ETH_P_IP, ETH_P_ALL));\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/raw_socket_icmp.cc",
"new_path": "test/syscalls/linux/raw_socket_icmp.cc",
"diff": "@@ -35,32 +35,6 @@ namespace testing {\nnamespace {\n-// Compute the internet checksum of the ICMP header (assuming no payload).\n-static uint16_t Checksum(struct icmphdr* icmp) {\n- uint32_t total = 0;\n- uint16_t* num = reinterpret_cast<uint16_t*>(icmp);\n-\n- // This is just the ICMP header, so there's an even number of bytes.\n- static_assert(\n- sizeof(*icmp) % sizeof(*num) == 0,\n- \"sizeof(struct icmphdr) is not an integer multiple of sizeof(uint16_t)\");\n- for (unsigned int i = 0; i < sizeof(*icmp); i += sizeof(*num)) {\n- total += *num;\n- num++;\n- }\n-\n- // Combine the upper and lower 16 bits. This happens twice in case the first\n- // combination causes a carry.\n- unsigned short upper = total >> 16;\n- unsigned short lower = total & 0xffff;\n- total = upper + lower;\n- upper = total >> 16;\n- lower = total & 0xffff;\n- total = upper + lower;\n-\n- return ~total;\n-}\n-\n// The size of an empty ICMP packet and IP header together.\nconstexpr size_t kEmptyICMPSize = 28;\n@@ -164,7 +138,7 @@ TEST_F(RawSocketICMPTest, SendAndReceive) {\nicmp.checksum = 0;\nicmp.un.echo.sequence = 2012;\nicmp.un.echo.id = 2014;\n- icmp.checksum = Checksum(&icmp);\n+ icmp.checksum = ICMPChecksum(icmp, NULL, 0);\nASSERT_NO_FATAL_FAILURE(SendEmptyICMP(icmp));\nASSERT_NO_FATAL_FAILURE(ExpectICMPSuccess(icmp));\n@@ -187,7 +161,7 @@ TEST_F(RawSocketICMPTest, MultipleSocketReceive) {\nicmp.checksum = 0;\nicmp.un.echo.sequence = 2016;\nicmp.un.echo.id = 2018;\n- icmp.checksum = Checksum(&icmp);\n+ icmp.checksum = ICMPChecksum(icmp, NULL, 0);\nASSERT_NO_FATAL_FAILURE(SendEmptyICMP(icmp));\n// Both sockets will receive the echo request and reply in indeterminate\n@@ -297,7 +271,7 @@ TEST_F(RawSocketICMPTest, ShortEchoRawAndPingSockets) {\nicmp.un.echo.sequence = 0;\nicmp.un.echo.id = 6789;\nicmp.checksum = 0;\n- icmp.checksum = Checksum(&icmp);\n+ icmp.checksum = ICMPChecksum(icmp, NULL, 0);\n// Omit 2 bytes from ICMP packet.\nconstexpr int kShortICMPSize = sizeof(icmp) - 2;\n@@ -338,7 +312,7 @@ TEST_F(RawSocketICMPTest, ShortEchoReplyRawAndPingSockets) {\nicmp.un.echo.sequence = 0;\nicmp.un.echo.id = 6789;\nicmp.checksum = 0;\n- icmp.checksum = Checksum(&icmp);\n+ icmp.checksum = ICMPChecksum(icmp, NULL, 0);\n// Omit 2 bytes from ICMP packet.\nconstexpr int kShortICMPSize = sizeof(icmp) - 2;\n@@ -381,7 +355,7 @@ TEST_F(RawSocketICMPTest, SendAndReceiveViaConnect) {\nicmp.checksum = 0;\nicmp.un.echo.sequence = 2003;\nicmp.un.echo.id = 2004;\n- icmp.checksum = Checksum(&icmp);\n+ icmp.checksum = ICMPChecksum(icmp, NULL, 0);\nASSERT_THAT(send(s_, &icmp, sizeof(icmp), 0),\nSyscallSucceedsWithValue(sizeof(icmp)));\n@@ -405,7 +379,7 @@ TEST_F(RawSocketICMPTest, BindSendAndReceive) {\nicmp.checksum = 0;\nicmp.un.echo.sequence = 2004;\nicmp.un.echo.id = 2007;\n- icmp.checksum = Checksum(&icmp);\n+ icmp.checksum = ICMPChecksum(icmp, NULL, 0);\nASSERT_NO_FATAL_FAILURE(SendEmptyICMP(icmp));\nASSERT_NO_FATAL_FAILURE(ExpectICMPSuccess(icmp));\n@@ -431,7 +405,7 @@ TEST_F(RawSocketICMPTest, BindConnectSendAndReceive) {\nicmp.checksum = 0;\nicmp.un.echo.sequence = 2010;\nicmp.un.echo.id = 7;\n- icmp.checksum = Checksum(&icmp);\n+ icmp.checksum = ICMPChecksum(icmp, NULL, 0);\nASSERT_NO_FATAL_FAILURE(SendEmptyICMP(icmp));\nASSERT_NO_FATAL_FAILURE(ExpectICMPSuccess(icmp));\n@@ -471,7 +445,7 @@ void RawSocketICMPTest::ExpectICMPSuccess(const struct icmphdr& icmp) {\n// A couple are different.\nEXPECT_EQ(recvd_icmp->type, ICMP_ECHOREPLY);\n// The checksum computed over the reply should still be valid.\n- EXPECT_EQ(Checksum(recvd_icmp), 0);\n+ EXPECT_EQ(ICMPChecksum(*recvd_icmp, NULL, 0), 0);\nbreak;\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_test_util.cc",
"new_path": "test/syscalls/linux/socket_test_util.cc",
"diff": "@@ -744,5 +744,74 @@ TestAddress V6Loopback() {\nreturn t;\n}\n+// Checksum computes the internet checksum of a buffer.\n+uint16_t Checksum(uint16_t* buf, ssize_t buf_size) {\n+ // Add up the 16-bit values in the buffer.\n+ uint32_t total = 0;\n+ for (unsigned int i = 0; i < buf_size; i += sizeof(*buf)) {\n+ total += *buf;\n+ buf++;\n+ }\n+\n+ // If buf has an odd size, add the remaining byte.\n+ if (buf_size % 2) {\n+ total += *(reinterpret_cast<unsigned char*>(buf) - 1);\n+ }\n+\n+ // This carries any bits past the lower 16 until everything fits in 16 bits.\n+ while (total >> 16) {\n+ uint16_t lower = total & 0xffff;\n+ uint16_t upper = total >> 16;\n+ total = lower + upper;\n+ }\n+\n+ return ~total;\n+}\n+\n+uint16_t IPChecksum(struct iphdr ip) {\n+ return Checksum(reinterpret_cast<uint16_t*>(&ip), sizeof(ip));\n+}\n+\n+// The pseudo-header defined in RFC 768 for calculating the UDP checksum.\n+struct udp_pseudo_hdr {\n+ uint32_t srcip;\n+ uint32_t destip;\n+ char zero;\n+ char protocol;\n+ uint16_t udplen;\n+};\n+\n+uint16_t UDPChecksum(struct iphdr iphdr, struct udphdr udphdr,\n+ const char* payload, ssize_t payload_len) {\n+ struct udp_pseudo_hdr phdr = {};\n+ phdr.srcip = iphdr.saddr;\n+ phdr.destip = iphdr.daddr;\n+ phdr.zero = 0;\n+ phdr.protocol = IPPROTO_UDP;\n+ phdr.udplen = udphdr.len;\n+\n+ ssize_t buf_size = sizeof(phdr) + sizeof(udphdr) + payload_len;\n+ char* buf = static_cast<char*>(malloc(buf_size));\n+ memcpy(buf, &phdr, sizeof(phdr));\n+ memcpy(buf + sizeof(phdr), &udphdr, sizeof(udphdr));\n+ memcpy(buf + sizeof(phdr) + sizeof(udphdr), payload, payload_len);\n+\n+ uint16_t csum = Checksum(reinterpret_cast<uint16_t*>(buf), buf_size);\n+ free(buf);\n+ return csum;\n+}\n+\n+uint16_t ICMPChecksum(struct icmphdr icmphdr, const char* payload,\n+ ssize_t payload_len) {\n+ ssize_t buf_size = sizeof(icmphdr) + payload_len;\n+ char* buf = static_cast<char*>(malloc(buf_size));\n+ memcpy(buf, &icmphdr, sizeof(icmphdr));\n+ memcpy(buf + sizeof(icmphdr), payload, payload_len);\n+\n+ uint16_t csum = Checksum(reinterpret_cast<uint16_t*>(buf), buf_size);\n+ free(buf);\n+ return csum;\n+}\n+\n} // namespace testing\n} // namespace gvisor\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_test_util.h",
"new_path": "test/syscalls/linux/socket_test_util.h",
"diff": "#include <errno.h>\n#include <netinet/ip.h>\n+#include <netinet/ip_icmp.h>\n+#include <netinet/udp.h>\n#include <sys/socket.h>\n#include <sys/types.h>\n#include <sys/un.h>\n+\n#include <functional>\n#include <memory>\n#include <string>\n@@ -478,6 +481,17 @@ TestAddress V4MappedLoopback();\nTestAddress V6Any();\nTestAddress V6Loopback();\n+// Compute the internet checksum of an IP header.\n+uint16_t IPChecksum(struct iphdr ip);\n+\n+// Compute the internet checksum of a UDP header.\n+uint16_t UDPChecksum(struct iphdr iphdr, struct udphdr udphdr,\n+ const char* payload, ssize_t payload_len);\n+\n+// Compute the internet checksum of an ICMP header.\n+uint16_t ICMPChecksum(struct icmphdr icmphdr, const char* payload,\n+ ssize_t payload_len);\n+\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add tests for "cooked" AF_PACKET sockets.
PiperOrigin-RevId: 263666789 |
259,907 | 16.08.2019 10:18:58 | 25,200 | 4bab7d7f084c4ce4a8bf5860b71df6aee757cd5c | vfs: Remove vfs.DefaultDirectoryFD from embedding vfs.DefaultFD.
This fixes the implementation ambiguity issues when a filesystem
implementation embeds vfs.DefaultDirectoryFD to its directory FD along
with an internal common fileDescription utility.
For similar reasons also removes FileDescriptionDefaultImpl from
DynamicBytesFileDescriptionImpl. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/ext/file_description.go",
"new_path": "pkg/sentry/fsimpl/ext/file_description.go",
"diff": "@@ -16,18 +16,16 @@ package ext\nimport (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n- \"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/context\"\n- \"gvisor.dev/gvisor/pkg/sentry/usermem\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n- \"gvisor.dev/gvisor/pkg/waiter\"\n)\n// fileDescription is embedded by ext implementations of\n// vfs.FileDescriptionImpl.\ntype fileDescription struct {\nvfsfd vfs.FileDescription\n+ vfs.FileDescriptionDefaultImpl\n// flags is the same as vfs.OpenOptions.Flags which are passed to\n// vfs.FilesystemImpl.OpenAt.\n@@ -82,29 +80,7 @@ func (fd *fileDescription) StatFS(ctx context.Context) (linux.Statfs, error) {\nreturn stat, nil\n}\n-// Readiness implements waiter.Waitable.Readiness analogously to\n-// file_operations::poll == NULL in Linux.\n-func (fd *fileDescription) Readiness(mask waiter.EventMask) waiter.EventMask {\n- // include/linux/poll.h:vfs_poll() => DEFAULT_POLLMASK\n- return waiter.EventIn | waiter.EventOut\n-}\n-\n-// EventRegister implements waiter.Waitable.EventRegister analogously to\n-// file_operations::poll == NULL in Linux.\n-func (fd *fileDescription) EventRegister(e *waiter.Entry, mask waiter.EventMask) {}\n-\n-// EventUnregister implements waiter.Waitable.EventUnregister analogously to\n-// file_operations::poll == NULL in Linux.\n-func (fd *fileDescription) EventUnregister(e *waiter.Entry) {}\n-\n// Sync implements vfs.FileDescriptionImpl.Sync.\nfunc (fd *fileDescription) Sync(ctx context.Context) error {\nreturn nil\n}\n-\n-// Ioctl implements vfs.FileDescriptionImpl.Ioctl.\n-func (fd *fileDescription) Ioctl(ctx context.Context, uio usermem.IO, args arch.SyscallArguments) (uintptr, error) {\n- // ioctl(2) specifies that ENOTTY must be returned if the file descriptor is\n- // not associated with a character special device (which is unimplemented).\n- return 0, syserror.ENOTTY\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/memfs/memfs.go",
"new_path": "pkg/sentry/fsimpl/memfs/memfs.go",
"diff": "@@ -258,6 +258,7 @@ func (i *inode) direntType() uint8 {\n// vfs.FileDescriptionImpl.\ntype fileDescription struct {\nvfsfd vfs.FileDescription\n+ vfs.FileDescriptionDefaultImpl\nflags uint32 // status flags; immutable\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/memfs/regular_file.go",
"new_path": "pkg/sentry/fsimpl/memfs/regular_file.go",
"diff": "@@ -46,7 +46,6 @@ func (fs *filesystem) newRegularFile(creds *auth.Credentials, mode uint16) *inod\ntype regularFileFD struct {\nfileDescription\n- vfs.FileDescriptionDefaultImpl\n// These are immutable.\nreadable bool\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/file_description_impl_util.go",
"new_path": "pkg/sentry/vfs/file_description_impl_util.go",
"diff": "@@ -28,6 +28,16 @@ import (\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n+// The following design pattern is strongly recommended for filesystem\n+// implementations to adapt:\n+// - Have a local fileDescription struct (containing FileDescription) which\n+// embeds FileDescriptionDefaultImpl and overrides the default methods\n+// which are common to all fd implementations for that for that filesystem\n+// like StatusFlags, SetStatusFlags, Stat, SetStat, StatFS, etc.\n+// - This should be embedded in all file description implementations as the\n+// first field by value.\n+// - Directory FDs would also embed DirectoryFileDescriptionDefaultImpl.\n+\n// FileDescriptionDefaultImpl may be embedded by implementations of\n// FileDescriptionImpl to obtain implementations of many FileDescriptionImpl\n// methods with default behavior analogous to Linux's.\n@@ -119,11 +129,8 @@ func (FileDescriptionDefaultImpl) Ioctl(ctx context.Context, uio usermem.IO, arg\n// DirectoryFileDescriptionDefaultImpl may be embedded by implementations of\n// FileDescriptionImpl that always represent directories to obtain\n-// implementations of non-directory I/O methods that return EISDIR, and\n-// implementations of other methods consistent with FileDescriptionDefaultImpl.\n-type DirectoryFileDescriptionDefaultImpl struct {\n- FileDescriptionDefaultImpl\n-}\n+// implementations of non-directory I/O methods that return EISDIR.\n+type DirectoryFileDescriptionDefaultImpl struct{}\n// PRead implements FileDescriptionImpl.PRead.\nfunc (DirectoryFileDescriptionDefaultImpl) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts ReadOptions) (int64, error) {\n@@ -153,8 +160,6 @@ func (DirectoryFileDescriptionDefaultImpl) Write(ctx context.Context, src userme\n// DynamicBytesFileDescriptionImpl.SetDataSource() must be called before first\n// use.\ntype DynamicBytesFileDescriptionImpl struct {\n- FileDescriptionDefaultImpl\n-\ndata DynamicBytesSource // immutable\nmu sync.Mutex // protects the following fields\nbuf bytes.Buffer\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/file_description_impl_util_test.go",
"new_path": "pkg/sentry/vfs/file_description_impl_util_test.go",
"diff": "@@ -29,11 +29,18 @@ import (\n\"gvisor.dev/gvisor/pkg/syserror\"\n)\n+// fileDescription is the common fd struct which a filesystem implementation\n+// embeds in all of its file description implementations as required.\n+type fileDescription struct {\n+ vfsfd FileDescription\n+ FileDescriptionDefaultImpl\n+}\n+\n// genCountFD is a read-only FileDescriptionImpl representing a regular file\n// that contains the number of times its DynamicBytesSource.Generate()\n// implementation has been called.\ntype genCountFD struct {\n- vfsfd FileDescription\n+ fileDescription\nDynamicBytesFileDescriptionImpl\ncount uint64 // accessed using atomic memory ops\n"
}
] | Go | Apache License 2.0 | google/gvisor | vfs: Remove vfs.DefaultDirectoryFD from embedding vfs.DefaultFD.
This fixes the implementation ambiguity issues when a filesystem
implementation embeds vfs.DefaultDirectoryFD to its directory FD along
with an internal common fileDescription utility.
For similar reasons also removes FileDescriptionDefaultImpl from
DynamicBytesFileDescriptionImpl.
PiperOrigin-RevId: 263795513 |
260,006 | 16.08.2019 15:57:46 | 25,200 | f7114e0a27db788af512af8678595954996bcd7f | Add subnet checking to NIC.findEndpoint and consolidate with NIC.getRef
This adds the same logic to NIC.findEndpoint that is already done in
NIC.getRef. Since this makes the two functions very similar they were combined
into one with the originals being wrappers. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic.go",
"new_path": "pkg/tcpip/stack/nic.go",
"diff": "@@ -186,41 +186,73 @@ func (n *NIC) primaryEndpoint(protocol tcpip.NetworkProtocolNumber) *referencedN\nreturn nil\n}\n+func (n *NIC) getRef(protocol tcpip.NetworkProtocolNumber, dst tcpip.Address) *referencedNetworkEndpoint {\n+ return n.getRefOrCreateTemp(protocol, dst, CanBePrimaryEndpoint, n.promiscuous)\n+}\n+\n// findEndpoint finds the endpoint, if any, with the given address.\nfunc (n *NIC) findEndpoint(protocol tcpip.NetworkProtocolNumber, address tcpip.Address, peb PrimaryEndpointBehavior) *referencedNetworkEndpoint {\n+ return n.getRefOrCreateTemp(protocol, address, peb, n.spoofing)\n+}\n+\n+// getRefEpOrCreateTemp returns the referenced network endpoint for the given\n+// protocol and address. If none exists a temporary one may be created if\n+// requested.\n+func (n *NIC) getRefOrCreateTemp(protocol tcpip.NetworkProtocolNumber, address tcpip.Address, peb PrimaryEndpointBehavior, allowTemp bool) *referencedNetworkEndpoint {\nid := NetworkEndpointID{address}\nn.mu.RLock()\n- ref := n.endpoints[id]\n- if ref != nil && !ref.tryIncRef() {\n- ref = nil\n+\n+ if ref, ok := n.endpoints[id]; ok && ref.tryIncRef() {\n+ n.mu.RUnlock()\n+ return ref\n}\n- spoofing := n.spoofing\n+\n+ // The address was not found, create a temporary one if requested by the\n+ // caller or if the address is found in the NIC's subnets.\n+ createTempEP := allowTemp\n+ if !createTempEP {\n+ for _, sn := range n.subnets {\n+ if sn.Contains(address) {\n+ createTempEP = true\n+ break\n+ }\n+ }\n+ }\n+\nn.mu.RUnlock()\n- if ref != nil || !spoofing {\n- return ref\n+ if !createTempEP {\n+ return nil\n}\n// Try again with the lock in exclusive mode. If we still can't get the\n// endpoint, create a new \"temporary\" endpoint. It will only exist while\n// there's a route through it.\nn.mu.Lock()\n- ref = n.endpoints[id]\n- if ref == nil || !ref.tryIncRef() {\n- if netProto, ok := n.stack.networkProtocols[protocol]; ok {\n- ref, _ = n.addAddressLocked(tcpip.ProtocolAddress{\n+ if ref, ok := n.endpoints[id]; ok && ref.tryIncRef() {\n+ n.mu.Unlock()\n+ return ref\n+ }\n+\n+ netProto, ok := n.stack.networkProtocols[protocol]\n+ if !ok {\n+ n.mu.Unlock()\n+ return nil\n+ }\n+\n+ ref, _ := n.addAddressLocked(tcpip.ProtocolAddress{\nProtocol: protocol,\nAddressWithPrefix: tcpip.AddressWithPrefix{\nAddress: address,\nPrefixLen: netProto.DefaultPrefixLen(),\n},\n}, peb, true)\n+\nif ref != nil {\nref.holdsInsertRef = false\n}\n- }\n- }\n+\nn.mu.Unlock()\nreturn ref\n}\n@@ -553,57 +585,6 @@ func (n *NIC) DeliverNetworkPacket(linkEP LinkEndpoint, remote, _ tcpip.LinkAddr\nn.stack.stats.IP.InvalidAddressesReceived.Increment()\n}\n-func (n *NIC) getRef(protocol tcpip.NetworkProtocolNumber, dst tcpip.Address) *referencedNetworkEndpoint {\n- id := NetworkEndpointID{dst}\n-\n- n.mu.RLock()\n- if ref, ok := n.endpoints[id]; ok && ref.tryIncRef() {\n- n.mu.RUnlock()\n- return ref\n- }\n-\n- promiscuous := n.promiscuous\n- // Check if the packet is for a subnet this NIC cares about.\n- if !promiscuous {\n- for _, sn := range n.subnets {\n- if sn.Contains(dst) {\n- promiscuous = true\n- break\n- }\n- }\n- }\n- n.mu.RUnlock()\n- if promiscuous {\n- // Try again with the lock in exclusive mode. If we still can't\n- // get the endpoint, create a new \"temporary\" one. It will only\n- // exist while there's a route through it.\n- n.mu.Lock()\n- if ref, ok := n.endpoints[id]; ok && ref.tryIncRef() {\n- n.mu.Unlock()\n- return ref\n- }\n- netProto, ok := n.stack.networkProtocols[protocol]\n- if !ok {\n- n.mu.Unlock()\n- return nil\n- }\n- ref, err := n.addAddressLocked(tcpip.ProtocolAddress{\n- Protocol: protocol,\n- AddressWithPrefix: tcpip.AddressWithPrefix{\n- Address: dst,\n- PrefixLen: netProto.DefaultPrefixLen(),\n- },\n- }, CanBePrimaryEndpoint, true)\n- n.mu.Unlock()\n- if err == nil {\n- ref.holdsInsertRef = false\n- return ref\n- }\n- }\n-\n- return nil\n-}\n-\n// DeliverTransportPacket delivers the packets to the appropriate transport\n// protocol endpoint.\nfunc (n *NIC) DeliverTransportPacket(r *Route, protocol tcpip.TransportProtocolNumber, netHeader buffer.View, vv buffer.VectorisedView) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack_test.go",
"new_path": "pkg/tcpip/stack/stack_test.go",
"diff": "@@ -830,6 +830,48 @@ func TestSubnetAcceptsMatchingPacket(t *testing.T) {\n}\n}\n+// Set the subnet, then check that CheckLocalAddress returns the correct NIC.\n+func TestCheckLocalAddressForSubnet(t *testing.T) {\n+ const nicID tcpip.NICID = 1\n+ s := stack.New([]string{\"fakeNet\"}, nil, stack.Options{})\n+\n+ id, _ := channel.New(10, defaultMTU, \"\")\n+ if err := s.CreateNIC(nicID, id); err != nil {\n+ t.Fatal(\"CreateNIC failed:\", err)\n+ }\n+\n+ s.SetRouteTable([]tcpip.Route{\n+ {\"\\x00\", \"\\x00\", \"\\x00\", nicID}, // default route\n+ })\n+\n+ subnet, err := tcpip.NewSubnet(tcpip.Address(\"\\xa0\"), tcpip.AddressMask(\"\\xf0\"))\n+\n+ if err != nil {\n+ t.Fatal(\"NewSubnet failed:\", err)\n+ }\n+ if err := s.AddSubnet(nicID, fakeNetNumber, subnet); err != nil {\n+ t.Fatal(\"AddSubnet failed:\", err)\n+ }\n+\n+ // Loop over all subnet addresses and check them.\n+ numOfAddresses := (1 << uint((8 - subnet.Prefix())))\n+ if numOfAddresses < 1 || numOfAddresses > 255 {\n+ t.Fatalf(\"got numOfAddresses = %d, want = [1 .. 255] (subnet=%s)\", numOfAddresses, subnet)\n+ }\n+ addr := []byte(subnet.ID())\n+ for i := 0; i < numOfAddresses; i++ {\n+ if gotNicID := s.CheckLocalAddress(0, fakeNetNumber, tcpip.Address(addr)); gotNicID != nicID {\n+ t.Errorf(\"got CheckLocalAddress(0, %d, %s) = %d, want = %d\", fakeNetNumber, tcpip.Address(addr), gotNicID, nicID)\n+ }\n+ addr[0]++\n+ }\n+\n+ // Trying the next address should fail since it is outside the subnet range.\n+ if gotNicID := s.CheckLocalAddress(0, fakeNetNumber, tcpip.Address(addr)); gotNicID != 0 {\n+ t.Errorf(\"got CheckLocalAddress(0, %d, %s) = %d, want = %d\", fakeNetNumber, tcpip.Address(addr), gotNicID, 0)\n+ }\n+}\n+\n// Set destination outside the subnet, then check it doesn't get delivered.\nfunc TestSubnetRejectsNonmatchingPacket(t *testing.T) {\ns := stack.New([]string{\"fakeNet\"}, nil, stack.Options{})\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -168,6 +168,11 @@ func NewSubnet(a Address, m AddressMask) (Subnet, error) {\nreturn Subnet{a, m}, nil\n}\n+// String implements Stringer.\n+func (s Subnet) String() string {\n+ return fmt.Sprintf(\"%s/%d\", s.ID(), s.Prefix())\n+}\n+\n// Contains returns true iff the address is of the same length and matches the\n// subnet address and mask.\nfunc (s *Subnet) Contains(a Address) bool {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add subnet checking to NIC.findEndpoint and consolidate with NIC.getRef
This adds the same logic to NIC.findEndpoint that is already done in
NIC.getRef. Since this makes the two functions very similar they were combined
into one with the originals being wrappers.
PiperOrigin-RevId: 263864708 |
259,853 | 16.08.2019 17:32:20 | 25,200 | 2a1303357c3d928cca95601241fc16baca0e5f41 | ptrace: detect if a stub process exited unexpectedly | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/subprocess.go",
"new_path": "pkg/sentry/platform/ptrace/subprocess.go",
"diff": "@@ -354,6 +354,9 @@ func (t *thread) wait(outcome waitOutcome) syscall.Signal {\ncontinue // Spurious stop.\n}\nif stopSig == syscall.SIGTRAP {\n+ if status.TrapCause() == syscall.PTRACE_EVENT_EXIT {\n+ t.dumpAndPanic(\"wait failed: the process exited\")\n+ }\n// Re-encode the trap cause the way it's expected.\nreturn stopSig | syscall.Signal(status.TrapCause()<<8)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | ptrace: detect if a stub process exited unexpectedly
PiperOrigin-RevId: 263880577 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.