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,962 | 13.11.2019 14:27:46 | 28,800 | 6dd4c9ee74828b27cd12ea343756f5625bae683c | Fix flaky behaviour during S/R. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/connect.go",
"new_path": "pkg/tcpip/transport/tcp/connect.go",
"diff": "@@ -1229,7 +1229,9 @@ func (e *endpoint) protocolMainLoop(handshake bool) *tcpip.Error {\nreturn err\n}\n}\n- if e.state != StateError {\n+ if e.state != StateClose && e.state != StateError {\n+ // Only block the worker if the endpoint\n+ // is not in closed state or error state.\nclose(e.drainDone)\n<-e.undrain\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix flaky behaviour during S/R.
PiperOrigin-RevId: 280280156 |
259,853 | 13.11.2019 15:34:47 | 28,800 | 1e55eb3800a60c1a1118b84f2534b78481702f38 | test/syscalls/proc: check an return code of waitid | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/proc.cc",
"new_path": "test/syscalls/linux/proc.cc",
"diff": "@@ -183,7 +183,8 @@ PosixError WithSubprocess(SubprocessCallback const& running,\nsiginfo_t info;\n// Wait until the child process has exited (WEXITED flag) but don't\n// reap the child (WNOWAIT flag).\n- waitid(P_PID, child_pid, &info, WNOWAIT | WEXITED);\n+ EXPECT_THAT(waitid(P_PID, child_pid, &info, WNOWAIT | WEXITED),\n+ SyscallSucceeds());\nif (zombied) {\n// Arg of \"Z\" refers to a Zombied Process.\n"
}
] | Go | Apache License 2.0 | google/gvisor | test/syscalls/proc: check an return code of waitid
PiperOrigin-RevId: 280295208 |
259,884 | 14.11.2019 13:32:40 | 18,000 | b94ef2075a78c3d7c6e479f152e48ab85db0f84e | Added info on styles to README | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -61,6 +61,27 @@ go run main.go\nAccess the site at http://localhost:8080\n+## Updating Styles\n+\n+If you want to update style on the website you can do this by updating\n+templates or CSS for the website. Check out the [Hugo\n+documentation](https://gohugo.io/documentation/) for info on hugo templating.\n+Check out the [Docsy documentation](https://www.docsy.dev/docs/) for info on\n+the Docsy theme.\n+\n+### Custom templates, partials, and shortcodes\n+\n+Custom templates, including partials and shortcodes, should go under the\n+[layouts/](layouts) directory.\n+\n+## Custom CSS\n+\n+Custom CSS styles should go into the\n+[_styles_project.scss](assets/scss/_styles_project.scss) file.\n+\n+If you need to override or create variables used in scss styles, update the\n+[_variables_project.scss](assets/scss/_variables_project.scss) file.\n+\n## Troubleshooting\n#### I get errors when building the website.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Added info on styles to README |
259,885 | 14.11.2019 14:03:24 | 28,800 | 9ca15dbf14ac6318a34540354020b8a71d789077 | Avoid unnecessary slice allocation in usermem.BytesIO.blocksFromAddrRanges(). | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/usermem/bytes_io.go",
"new_path": "pkg/sentry/usermem/bytes_io.go",
"diff": "@@ -102,12 +102,18 @@ func (b *BytesIO) rangeCheck(addr Addr, length int) (int, error) {\n}\nfunc (b *BytesIO) blocksFromAddrRanges(ars AddrRangeSeq) (safemem.BlockSeq, error) {\n+ switch ars.NumRanges() {\n+ case 0:\n+ return safemem.BlockSeq{}, nil\n+ case 1:\n+ block, err := b.blockFromAddrRange(ars.Head())\n+ return safemem.BlockSeqOf(block), err\n+ default:\nblocks := make([]safemem.Block, 0, ars.NumRanges())\nfor !ars.IsEmpty() {\n- ar := ars.Head()\n- n, err := b.rangeCheck(ar.Start, int(ar.Length()))\n- if n != 0 {\n- blocks = append(blocks, safemem.BlockFromSafeSlice(b.Bytes[int(ar.Start):int(ar.Start)+n]))\n+ block, err := b.blockFromAddrRange(ars.Head())\n+ if block.Len() != 0 {\n+ blocks = append(blocks, block)\n}\nif err != nil {\nreturn safemem.BlockSeqFromSlice(blocks), err\n@@ -116,6 +122,15 @@ func (b *BytesIO) blocksFromAddrRanges(ars AddrRangeSeq) (safemem.BlockSeq, erro\n}\nreturn safemem.BlockSeqFromSlice(blocks), nil\n}\n+}\n+\n+func (b *BytesIO) blockFromAddrRange(ar AddrRange) (safemem.Block, error) {\n+ n, err := b.rangeCheck(ar.Start, int(ar.Length()))\n+ if n == 0 {\n+ return safemem.Block{}, err\n+ }\n+ return safemem.BlockFromSafeSlice(b.Bytes[int(ar.Start) : int(ar.Start)+n]), err\n+}\n// BytesIOSequence returns an IOSequence representing the given byte slice.\nfunc BytesIOSequence(buf []byte) IOSequence {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Avoid unnecessary slice allocation in usermem.BytesIO.blocksFromAddrRanges().
PiperOrigin-RevId: 280507239 |
259,891 | 14.11.2019 15:04:25 | 28,800 | 1e1f5ce08210af6211bcb1c8da293a63a79165fe | Allow all runtime tests for a language to be run via a single command.
This was intended behavior per the README, but running tests without the --test
flag caused an error. Users can now omit the --test flag to run every test for a
runtime. | [
{
"change_type": "MODIFY",
"old_path": "test/runtimes/images/proctor/proctor.go",
"new_path": "test/runtimes/images/proctor/proctor.go",
"diff": "@@ -41,7 +41,7 @@ type TestRunner interface {\nvar (\nruntime = flag.String(\"runtime\", \"\", \"name of runtime\")\nlist = flag.Bool(\"list\", false, \"list all available tests\")\n- test = flag.String(\"test\", \"\", \"run a single test from the list of available tests\")\n+ testName = flag.String(\"test\", \"\", \"run a single test from the list of available tests\")\npause = flag.Bool(\"pause\", false, \"cause container to pause indefinitely, reaping any zombie children\")\n)\n@@ -74,16 +74,25 @@ func main() {\nreturn\n}\n+ var tests []string\n+ if *testName == \"\" {\n+ // Run every test.\n+ tests, err = tr.ListTests()\n+ if err != nil {\n+ log.Fatalf(\"failed to get all tests: %v\", err)\n+ }\n+ } else {\n// Run a single test.\n- if *test == \"\" {\n- log.Fatalf(\"test flag must be provided\")\n+ tests = []string{*testName}\n}\n- cmd := tr.TestCmd(*test)\n+ for _, test := range tests {\n+ cmd := tr.TestCmd(test)\ncmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr\nif err := cmd.Run(); err != nil {\nlog.Fatalf(\"FAIL: %v\", err)\n}\n}\n+}\n// testRunnerForRuntime returns a new TestRunner for the given runtime.\nfunc testRunnerForRuntime(runtime string) (TestRunner, error) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow all runtime tests for a language to be run via a single command.
This was intended behavior per the README, but running tests without the --test
flag caused an error. Users can now omit the --test flag to run every test for a
runtime.
PiperOrigin-RevId: 280522025 |
259,891 | 14.11.2019 15:55:07 | 28,800 | 339536de5eefe782813aabae4aeeb312b3c4dde7 | Check that a file is a regular file with open(O_TRUNC).
It was possible to panic the sentry by opening a cache revalidating folder with
O_TRUNC|O_CREAT.
Avoids breaking php tests. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/inode.go",
"new_path": "pkg/sentry/fs/inode.go",
"diff": "@@ -344,6 +344,10 @@ func (i *Inode) SetTimestamps(ctx context.Context, d *Dirent, ts TimeSpec) error\n// Truncate calls i.InodeOperations.Truncate with i as the Inode.\nfunc (i *Inode) Truncate(ctx context.Context, d *Dirent, size int64) error {\n+ if IsDir(i.StableAttr) {\n+ return syserror.EISDIR\n+ }\n+\nif i.overlay != nil {\nreturn overlayTruncate(ctx, i.overlay, d, size)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/tty/master.go",
"new_path": "pkg/sentry/fs/tty/master.go",
"diff": "@@ -32,6 +32,7 @@ import (\n// +stateify savable\ntype masterInodeOperations struct {\nfsutil.SimpleFileInode\n+ fsutil.InodeNoopTruncate\n// d is the containing dir.\nd *dirInodeOperations\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/tty/slave.go",
"new_path": "pkg/sentry/fs/tty/slave.go",
"diff": "@@ -31,6 +31,7 @@ import (\n// +stateify savable\ntype slaveInodeOperations struct {\nfsutil.SimpleFileInode\n+ fsutil.InodeNoopTruncate\n// d is the containing dir.\nd *dirInodeOperations\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_file.go",
"new_path": "pkg/sentry/syscalls/linux/sys_file.go",
"diff": "@@ -169,12 +169,13 @@ func openAt(t *kernel.Task, dirFD int32, addr usermem.Addr, flags uint) (fd uint\nif dirPath {\nreturn syserror.ENOTDIR\n}\n+ }\n+\nif flags&linux.O_TRUNC != 0 {\nif err := d.Inode.Truncate(t, d, 0); err != nil {\nreturn err\n}\n}\n- }\nfile, err := d.Inode.GetFile(t, d, fileFlags)\nif err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/open.cc",
"new_path": "test/syscalls/linux/open.cc",
"diff": "@@ -73,6 +73,28 @@ class OpenTest : public FileTest {\nconst std::string test_data_ = \"hello world\\n\";\n};\n+TEST_F(OpenTest, OTrunc) {\n+ auto dirpath = JoinPath(GetAbsoluteTestTmpdir(), \"truncd\");\n+ ASSERT_THAT(mkdir(dirpath.c_str(), 0777), SyscallSucceeds());\n+ ASSERT_THAT(open(dirpath.c_str(), O_TRUNC, 0666),\n+ SyscallFailsWithErrno(EISDIR));\n+}\n+\n+TEST_F(OpenTest, OTruncAndReadOnlyDir) {\n+ auto dirpath = JoinPath(GetAbsoluteTestTmpdir(), \"truncd\");\n+ ASSERT_THAT(mkdir(dirpath.c_str(), 0777), SyscallSucceeds());\n+ ASSERT_THAT(open(dirpath.c_str(), O_TRUNC | O_RDONLY, 0666),\n+ SyscallFailsWithErrno(EISDIR));\n+}\n+\n+TEST_F(OpenTest, OTruncAndReadOnlyFile) {\n+ auto dirpath = JoinPath(GetAbsoluteTestTmpdir(), \"truncfile\");\n+ const FileDescriptor existing =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(dirpath.c_str(), O_RDWR | O_CREAT, 0666));\n+ const FileDescriptor otrunc = ASSERT_NO_ERRNO_AND_VALUE(\n+ Open(dirpath.c_str(), O_TRUNC | O_RDONLY, 0666));\n+}\n+\nTEST_F(OpenTest, ReadOnly) {\nchar buf;\nconst FileDescriptor ro_file =\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/open_create.cc",
"new_path": "test/syscalls/linux/open_create.cc",
"diff": "@@ -88,6 +88,30 @@ TEST(CreateTest, CreateExclusively) {\nSyscallFailsWithErrno(EEXIST));\n}\n+TEST(CreateTeast, CreatWithOTrunc) {\n+ std::string dirpath = JoinPath(GetAbsoluteTestTmpdir(), \"truncd\");\n+ ASSERT_THAT(mkdir(dirpath.c_str(), 0777), SyscallSucceeds());\n+ ASSERT_THAT(open(dirpath.c_str(), O_CREAT | O_TRUNC, 0666),\n+ SyscallFailsWithErrno(EISDIR));\n+}\n+\n+TEST(CreateTeast, CreatDirWithOTruncAndReadOnly) {\n+ std::string dirpath = JoinPath(GetAbsoluteTestTmpdir(), \"truncd\");\n+ ASSERT_THAT(mkdir(dirpath.c_str(), 0777), SyscallSucceeds());\n+ ASSERT_THAT(open(dirpath.c_str(), O_CREAT | O_TRUNC | O_RDONLY, 0666),\n+ SyscallFailsWithErrno(EISDIR));\n+}\n+\n+TEST(CreateTeast, CreatFileWithOTruncAndReadOnly) {\n+ std::string dirpath = JoinPath(GetAbsoluteTestTmpdir(), \"truncfile\");\n+ int dirfd;\n+ ASSERT_THAT(dirfd = open(dirpath.c_str(), O_RDWR | O_CREAT, 0666),\n+ SyscallSucceeds());\n+ ASSERT_THAT(open(dirpath.c_str(), O_CREAT | O_TRUNC | O_RDONLY, 0666),\n+ SyscallSucceeds());\n+ ASSERT_THAT(close(dirfd), SyscallSucceeds());\n+}\n+\nTEST(CreateTest, CreateFailsOnUnpermittedDir) {\n// Make sure we don't have CAP_DAC_OVERRIDE, since that allows the user to\n// always override directory permissions.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/pty.cc",
"new_path": "test/syscalls/linux/pty.cc",
"diff": "@@ -70,6 +70,8 @@ constexpr absl::Duration kTimeout = absl::Seconds(20);\n// The maximum line size in bytes returned per read from a pty file.\nconstexpr int kMaxLineSize = 4096;\n+constexpr char kMasterPath[] = \"/dev/ptmx\";\n+\n// glibc defines its own, different, version of struct termios. We care about\n// what the kernel does, not glibc.\n#define KERNEL_NCCS 19\n@@ -376,9 +378,25 @@ PosixErrorOr<size_t> PollAndReadFd(int fd, void* buf, size_t count,\nreturn PosixError(ETIMEDOUT, \"Poll timed out\");\n}\n+TEST(PtyTrunc, Truncate) {\n+ // Opening PTYs with O_TRUNC shouldn't cause an error, but calls to\n+ // (f)truncate should.\n+ FileDescriptor master =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(kMasterPath, O_RDWR | O_TRUNC));\n+ int n = ASSERT_NO_ERRNO_AND_VALUE(SlaveID(master));\n+ std::string spath = absl::StrCat(\"/dev/pts/\", n);\n+ FileDescriptor slave =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(spath, O_RDWR | O_NONBLOCK | O_TRUNC));\n+\n+ EXPECT_THAT(truncate(kMasterPath, 0), SyscallFailsWithErrno(EINVAL));\n+ EXPECT_THAT(truncate(spath.c_str(), 0), SyscallFailsWithErrno(EINVAL));\n+ EXPECT_THAT(ftruncate(master.get(), 0), SyscallFailsWithErrno(EINVAL));\n+ EXPECT_THAT(ftruncate(slave.get(), 0), SyscallFailsWithErrno(EINVAL));\n+}\n+\nTEST(BasicPtyTest, StatUnopenedMaster) {\nstruct stat s;\n- ASSERT_THAT(stat(\"/dev/ptmx\", &s), SyscallSucceeds());\n+ ASSERT_THAT(stat(kMasterPath, &s), SyscallSucceeds());\nEXPECT_EQ(s.st_rdev, makedev(TTYAUX_MAJOR, kPtmxMinor));\nEXPECT_EQ(s.st_size, 0);\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/pty_util.cc",
"new_path": "test/util/pty_util.cc",
"diff": "@@ -24,6 +24,14 @@ namespace gvisor {\nnamespace testing {\nPosixErrorOr<FileDescriptor> OpenSlave(const FileDescriptor& master) {\n+ PosixErrorOr<int> n = SlaveID(master);\n+ if (!n.ok()) {\n+ return PosixErrorOr<FileDescriptor>(n.error());\n+ }\n+ return Open(absl::StrCat(\"/dev/pts/\", n.ValueOrDie()), O_RDWR | O_NONBLOCK);\n+}\n+\n+PosixErrorOr<int> SlaveID(const FileDescriptor& master) {\n// Get pty index.\nint n;\nint ret = ioctl(master.get(), TIOCGPTN, &n);\n@@ -38,7 +46,7 @@ PosixErrorOr<FileDescriptor> OpenSlave(const FileDescriptor& master) {\nreturn PosixError(errno, \"ioctl(TIOSPTLCK) failed\");\n}\n- return Open(absl::StrCat(\"/dev/pts/\", n), O_RDWR | O_NONBLOCK);\n+ return n;\n}\n} // namespace testing\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/pty_util.h",
"new_path": "test/util/pty_util.h",
"diff": "@@ -24,6 +24,9 @@ namespace testing {\n// Opens the slave end of the passed master as R/W and nonblocking.\nPosixErrorOr<FileDescriptor> OpenSlave(const FileDescriptor& master);\n+// Get the number of the slave end of the master.\n+PosixErrorOr<int> SlaveID(const FileDescriptor& master);\n+\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Check that a file is a regular file with open(O_TRUNC).
It was possible to panic the sentry by opening a cache revalidating folder with
O_TRUNC|O_CREAT.
Avoids breaking php tests.
PiperOrigin-RevId: 280533213 |
260,003 | 14.11.2019 17:02:59 | 28,800 | af323eb7c1830053627de6161f8ce73ac5f06d4e | Fix return codes for {get,set}sockopt for some nullptr cases.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_socket.go",
"new_path": "pkg/sentry/syscalls/linux/sys_socket.go",
"diff": "@@ -447,17 +447,14 @@ func GetSockOpt(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sy\nreturn 0, nil, syserror.ENOTSOCK\n}\n- // Read the length if present. Reject negative values.\n+ // Read the length. Reject negative values.\noptLen := int32(0)\n- if optLenAddr != 0 {\nif _, err := t.CopyIn(optLenAddr, &optLen); err != nil {\nreturn 0, nil, err\n}\n-\nif optLen < 0 {\nreturn 0, nil, syserror.EINVAL\n}\n- }\n// Call syscall implementation then copy both value and value len out.\nv, e := getSockOpt(t, s, int(level), int(name), optValAddr, int(optLen))\n@@ -465,12 +462,10 @@ func GetSockOpt(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sy\nreturn 0, nil, e.ToError()\n}\n- if optLenAddr != 0 {\nvLen := int32(binary.Size(v))\nif _, err := t.CopyOut(optLenAddr, vLen); err != nil {\nreturn 0, nil, err\n}\n- }\nif v != nil {\nif _, err := t.CopyOut(optValAddr, v); err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ip_unbound.cc",
"new_path": "test/syscalls/linux/socket_ip_unbound.cc",
"diff": "@@ -354,6 +354,38 @@ TEST_P(IPUnboundSocketTest, InvalidNegativeTOS) {\nEXPECT_EQ(get, expect);\n}\n+TEST_P(IPUnboundSocketTest, NullTOS) {\n+ auto socket = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n+ TOSOption t = GetTOSOption(GetParam().domain);\n+ int set_sz = sizeof(int);\n+ if (GetParam().domain == AF_INET) {\n+ EXPECT_THAT(setsockopt(socket->get(), t.level, t.option, nullptr, set_sz),\n+ SyscallFailsWithErrno(EFAULT));\n+ } else { // AF_INET6\n+ // The AF_INET6 behavior is not yet compatible. gVisor will try to read\n+ // optval from user memory at syscall handler, it needs substantial\n+ // refactoring to implement this behavior just for IPv6.\n+ if (IsRunningOnGvisor()) {\n+ EXPECT_THAT(setsockopt(socket->get(), t.level, t.option, nullptr, set_sz),\n+ SyscallFailsWithErrno(EFAULT));\n+ } else {\n+ // Linux's IPv6 stack treats nullptr optval as input of 0, so the call\n+ // succeeds. (net/ipv6/ipv6_sockglue.c, do_ipv6_setsockopt())\n+ //\n+ // Linux's implementation would need fixing as passing a nullptr as optval\n+ // and non-zero optlen may not be valid.\n+ EXPECT_THAT(setsockopt(socket->get(), t.level, t.option, nullptr, set_sz),\n+ SyscallSucceedsWithValue(0));\n+ }\n+ }\n+ socklen_t get_sz = sizeof(int);\n+ EXPECT_THAT(getsockopt(socket->get(), t.level, t.option, nullptr, &get_sz),\n+ SyscallFailsWithErrno(EFAULT));\n+ int get = -1;\n+ EXPECT_THAT(getsockopt(socket->get(), t.level, t.option, &get, nullptr),\n+ SyscallFailsWithErrno(EFAULT));\n+}\n+\nINSTANTIATE_TEST_SUITE_P(\nIPUnboundSockets, IPUnboundSocketTest,\n::testing::ValuesIn(VecCat<SocketKind>(VecCat<SocketKind>(\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix return codes for {get,set}sockopt for some nullptr cases.
Updates #1092
PiperOrigin-RevId: 280547239 |
259,891 | 14.11.2019 22:54:01 | 28,800 | 23574b1b87ce5aed7b78a53663eac61ae030e9d5 | Fix panic when logging raw packets via sniffer.
Sniffer assumed that outgoing packets have transport headers, but
users can write packets via SOCK_RAW with arbitrary transport headers that
netstack doesn't know about. We now explicitly check for the presence of network
and transport headers before assuming they exist. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/sniffer/sniffer.go",
"new_path": "pkg/tcpip/link/sniffer/sniffer.go",
"diff": "@@ -118,7 +118,7 @@ func NewWithFile(lower stack.LinkEndpoint, file *os.File, snapLen uint32) (stack\n// logs the packet before forwarding to the actual dispatcher.\nfunc (e *endpoint) DeliverNetworkPacket(linkEP stack.LinkEndpoint, remote, local tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, pkt tcpip.PacketBuffer) {\nif atomic.LoadUint32(&LogPackets) == 1 && e.file == nil {\n- logPacket(\"recv\", protocol, pkt.Data.First(), nil)\n+ logPacket(\"recv\", protocol, pkt, nil)\n}\nif e.file != nil && atomic.LoadUint32(&LogPacketsToFile) == 1 {\nvs := pkt.Data.Views()\n@@ -195,7 +195,7 @@ func (e *endpoint) GSOMaxSize() uint32 {\nfunc (e *endpoint) dumpPacket(gso *stack.GSO, protocol tcpip.NetworkProtocolNumber, pkt tcpip.PacketBuffer) {\nif atomic.LoadUint32(&LogPackets) == 1 && e.file == nil {\n- logPacket(\"send\", protocol, pkt.Header.View(), gso)\n+ logPacket(\"send\", protocol, pkt, gso)\n}\nif e.file != nil && atomic.LoadUint32(&LogPacketsToFile) == 1 {\nhdrBuf := pkt.Header.View()\n@@ -247,7 +247,7 @@ func (e *endpoint) WritePackets(r *stack.Route, gso *stack.GSO, hdrs []stack.Pac\n// WriteRawPacket implements stack.LinkEndpoint.WriteRawPacket.\nfunc (e *endpoint) WriteRawPacket(vv buffer.VectorisedView) *tcpip.Error {\nif atomic.LoadUint32(&LogPackets) == 1 && e.file == nil {\n- logPacket(\"send\", 0, buffer.View(\"[raw packet, no header available]\"), nil /* gso */)\n+ logPacket(\"send raw packet\", 0, tcpip.PacketBuffer{}, nil /* gso */)\n}\nif e.file != nil && atomic.LoadUint32(&LogPacketsToFile) == 1 {\nlength := vv.Size()\n@@ -289,7 +289,7 @@ func logVectorisedView(vv buffer.VectorisedView, length int, buf *bytes.Buffer)\n// Wait implements stack.LinkEndpoint.Wait.\nfunc (*endpoint) Wait() {}\n-func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, b buffer.View, gso *stack.GSO) {\n+func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, pkt tcpip.PacketBuffer, gso *stack.GSO) {\n// Figure out the network layer info.\nvar transProto uint8\nsrc := tcpip.Address(\"unknown\")\n@@ -298,28 +298,28 @@ func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, b buffer.Vie\nsize := uint16(0)\nvar fragmentOffset uint16\nvar moreFragments bool\n+\n+ if pkt.NetworkHeader != nil {\nswitch protocol {\ncase header.IPv4ProtocolNumber:\n- ipv4 := header.IPv4(b)\n+ ipv4 := header.IPv4(pkt.NetworkHeader)\nfragmentOffset = ipv4.FragmentOffset()\nmoreFragments = ipv4.Flags()&header.IPv4FlagMoreFragments == header.IPv4FlagMoreFragments\nsrc = ipv4.SourceAddress()\ndst = ipv4.DestinationAddress()\ntransProto = ipv4.Protocol()\nsize = ipv4.TotalLength() - uint16(ipv4.HeaderLength())\n- b = b[ipv4.HeaderLength():]\nid = int(ipv4.ID())\ncase header.IPv6ProtocolNumber:\n- ipv6 := header.IPv6(b)\n+ ipv6 := header.IPv6(pkt.NetworkHeader)\nsrc = ipv6.SourceAddress()\ndst = ipv6.DestinationAddress()\ntransProto = ipv6.NextHeader()\nsize = ipv6.PayloadLength()\n- b = b[header.IPv6MinimumSize:]\ncase header.ARPProtocolNumber:\n- arp := header.ARP(b)\n+ arp := header.ARP(pkt.NetworkHeader)\nlog.Infof(\n\"%s arp %v (%v) -> %v (%v) valid:%v\",\nprefix,\n@@ -332,16 +332,18 @@ func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, b buffer.Vie\nlog.Infof(\"%s unknown network protocol\", prefix)\nreturn\n}\n+ }\n// Figure out the transport layer info.\ntransName := \"unknown\"\nsrcPort := uint16(0)\ndstPort := uint16(0)\ndetails := \"\"\n+ if pkt.TransportHeader != nil {\nswitch tcpip.TransportProtocolNumber(transProto) {\ncase header.ICMPv4ProtocolNumber:\ntransName = \"icmp\"\n- icmp := header.ICMPv4(b)\n+ icmp := header.ICMPv4(pkt.TransportHeader)\nicmpType := \"unknown\"\nif fragmentOffset == 0 {\nswitch icmp.Type() {\n@@ -374,7 +376,7 @@ func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, b buffer.Vie\ncase header.ICMPv6ProtocolNumber:\ntransName = \"icmp\"\n- icmp := header.ICMPv6(b)\n+ icmp := header.ICMPv6(pkt.TransportHeader)\nicmpType := \"unknown\"\nswitch icmp.Type() {\ncase header.ICMPv6DstUnreachable:\n@@ -405,7 +407,7 @@ func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, b buffer.Vie\ncase header.UDPProtocolNumber:\ntransName = \"udp\"\n- udp := header.UDP(b)\n+ udp := header.UDP(pkt.TransportHeader)\nif fragmentOffset == 0 && len(udp) >= header.UDPMinimumSize {\nsrcPort = udp.SourcePort()\ndstPort = udp.DestinationPort()\n@@ -415,7 +417,7 @@ func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, b buffer.Vie\ncase header.TCPProtocolNumber:\ntransName = \"tcp\"\n- tcp := header.TCP(b)\n+ tcp := header.TCP(pkt.TransportHeader)\nif fragmentOffset == 0 && len(tcp) >= header.TCPMinimumSize {\noffset := int(tcp.DataOffset())\nif offset < header.TCPMinimumSize {\n@@ -451,6 +453,7 @@ func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, b buffer.Vie\nlog.Infof(\"%s %v -> %v unknown transport protocol: %d\", prefix, src, dst, transProto)\nreturn\n}\n+ }\nif gso != nil {\ndetails += fmt.Sprintf(\" gso: %+v\", gso)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix panic when logging raw packets via sniffer.
Sniffer assumed that outgoing packets have transport headers, but
users can write packets via SOCK_RAW with arbitrary transport headers that
netstack doesn't know about. We now explicitly check for the presence of network
and transport headers before assuming they exist.
PiperOrigin-RevId: 280594395 |
259,885 | 15.11.2019 11:39:25 | 28,800 | 76039f895995c3fe0deef5958f843868685ecc38 | Do not set finalizer on p9.ClientFile.
Aside from the performance hit, there is no guarantee that p9.ClientFile's
finalizer runs before the associated p9.Client is closed. | [
{
"change_type": "MODIFY",
"old_path": "pkg/p9/client_file.go",
"new_path": "pkg/p9/client_file.go",
"diff": "@@ -17,7 +17,6 @@ package p9\nimport (\n\"fmt\"\n\"io\"\n- \"runtime\"\n\"sync/atomic\"\n\"syscall\"\n@@ -45,15 +44,10 @@ func (c *Client) Attach(name string) (File, error) {\n// newFile returns a new client file.\nfunc (c *Client) newFile(fid FID) *clientFile {\n- cf := &clientFile{\n+ return &clientFile{\nclient: c,\nfid: fid,\n}\n-\n- // Make sure the file is closed.\n- runtime.SetFinalizer(cf, (*clientFile).Close)\n-\n- return cf\n}\n// clientFile is provided to clients.\n@@ -192,7 +186,6 @@ func (c *clientFile) Remove() error {\nif !atomic.CompareAndSwapUint32(&c.closed, 0, 1) {\nreturn syscall.EBADF\n}\n- runtime.SetFinalizer(c, nil)\n// Send the remove message.\nif err := c.client.sendRecv(&Tremove{FID: c.fid}, &Rremove{}); err != nil {\n@@ -214,7 +207,6 @@ func (c *clientFile) Close() error {\nif !atomic.CompareAndSwapUint32(&c.closed, 0, 1) {\nreturn syscall.EBADF\n}\n- runtime.SetFinalizer(c, nil)\n// Send the close message.\nif err := c.client.sendRecv(&Tclunk{FID: c.fid}, &Rclunk{}); err != nil {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Do not set finalizer on p9.ClientFile.
Aside from the performance hit, there is no guarantee that p9.ClientFile's
finalizer runs before the associated p9.Client is closed.
PiperOrigin-RevId: 280702509 |
260,023 | 15.11.2019 11:44:02 | 28,800 | 3e534f2974f469a889534221b83c3bbbd1b0318c | Handle in-flight TCP segments when moving to CLOSE.
As we move to CLOSE state from LAST-ACK or TIME-WAIT,
ensure that we re-match all in-flight segments to any
listening endpoint.
Also fix LISTEN state handling of any ACK segments as per RFC793.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/accept.go",
"new_path": "pkg/tcpip/transport/tcp/accept.go",
"diff": "@@ -419,8 +419,8 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) {\n// TODO(b/143300739): Use the userMSS of the listening socket\n// for accepted sockets.\n- switch s.flags {\n- case header.TCPFlagSyn:\n+ switch {\n+ case s.flags == header.TCPFlagSyn:\nopts := parseSynSegmentOptions(s)\nif incSynRcvdCount() {\n// Only handle the syn if the following conditions hold\n@@ -464,7 +464,7 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) {\ne.stack.Stats().TCP.ListenOverflowSynCookieSent.Increment()\n}\n- case header.TCPFlagAck:\n+ case (s.flags & header.TCPFlagAck) != 0:\nif e.acceptQueueIsFull() {\n// Silently drop the ack as the application can't accept\n// the connection at this point. The ack will be\n@@ -478,6 +478,14 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) {\n}\nif !synCookiesInUse() {\n+ // When not using SYN cookies, as per RFC 793, section 3.9, page 64:\n+ // Any acknowledgment is bad if it arrives on a connection still in\n+ // the LISTEN state. An acceptable reset segment should be formed\n+ // for any arriving ACK-bearing segment. The RST should be\n+ // formatted as follows:\n+ //\n+ // <SEQ=SEG.ACK><CTL=RST>\n+ //\n// Send a reset as this is an ACK for which there is no\n// half open connections and we are not using cookies\n// yet.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/connect.go",
"new_path": "pkg/tcpip/transport/tcp/connect.go",
"diff": "@@ -865,6 +865,33 @@ func (e *endpoint) completeWorkerLocked() {\n}\n}\n+// transitionToStateCloseLocked ensures that the endpoint is\n+// cleaned up from the transport demuxer, \"before\" moving to\n+// StateClose. This will ensure that no packet will be\n+// delivered to this endpoint from the demuxer when the endpoint\n+// is transitioned to StateClose.\n+func (e *endpoint) transitionToStateCloseLocked() {\n+ if e.state == StateClose {\n+ return\n+ }\n+ e.cleanupLocked()\n+ e.state = StateClose\n+}\n+\n+// tryDeliverSegmentFromClosedEndpoint attempts to deliver the parsed\n+// segment to any other endpoint other than the current one. This is called\n+// only when the endpoint is in StateClose and we want to deliver the segment\n+// to any other listening endpoint. We reply with RST if we cannot find one.\n+func (e *endpoint) tryDeliverSegmentFromClosedEndpoint(s *segment) {\n+ ep := e.stack.FindTransportEndpoint(e.NetProto, e.TransProto, e.ID, &s.route)\n+ if ep == nil {\n+ replyWithReset(s)\n+ s.decRef()\n+ return\n+ }\n+ ep.(*endpoint).enqueueSegment(s)\n+}\n+\nfunc (e *endpoint) handleReset(s *segment) (ok bool, err *tcpip.Error) {\nif e.rcv.acceptable(s.sequenceNumber, 0) {\n// RFC 793, page 37 states that \"in all states\n@@ -894,12 +921,8 @@ func (e *endpoint) handleReset(s *segment) (ok bool, err *tcpip.Error) {\n// general \"connection reset\" signal. Enter the CLOSED state,\n// delete the TCB, and return.\ncase StateCloseWait:\n- e.state = StateClose\n+ e.transitionToStateCloseLocked()\ne.HardError = tcpip.ErrAborted\n- // We need to set this explicitly here because otherwise\n- // the port registrations will not be released till the\n- // endpoint is actively closed by the application.\n- e.workerCleanup = true\ne.mu.Unlock()\nreturn false, nil\ndefault:\n@@ -915,6 +938,20 @@ func (e *endpoint) handleReset(s *segment) (ok bool, err *tcpip.Error) {\nfunc (e *endpoint) handleSegments() *tcpip.Error {\ncheckRequeue := true\nfor i := 0; i < maxSegmentsPerWake; i++ {\n+ e.mu.RLock()\n+ state := e.state\n+ e.mu.RUnlock()\n+ if state == StateClose {\n+ // When we get into StateClose while processing from the queue,\n+ // return immediately and let the protocolMainloop handle it.\n+ //\n+ // We can reach StateClose only while processing a previous segment\n+ // or a notification from the protocolMainLoop (caller goroutine).\n+ // This means that with this return, the segment dequeue below can\n+ // never occur on a closed endpoint.\n+ return nil\n+ }\n+\ns := e.segmentQueue.dequeue()\nif s == nil {\ncheckRequeue = false\n@@ -1160,7 +1197,7 @@ func (e *endpoint) protocolMainLoop(handshake bool) *tcpip.Error {\n// to the TCP_FIN_WAIT2 timeout was hit. Just\n// mark the socket as closed.\ne.mu.Lock()\n- e.state = StateClose\n+ e.transitionToStateCloseLocked()\ne.mu.Unlock()\nreturn nil\n},\n@@ -1321,12 +1358,21 @@ func (e *endpoint) protocolMainLoop(handshake bool) *tcpip.Error {\nif e.state != StateError {\ne.stack.Stats().TCP.EstablishedResets.Increment()\ne.stack.Stats().TCP.CurrentEstablished.Decrement()\n- e.state = StateClose\n+ e.transitionToStateCloseLocked()\n}\n// Lock released below.\nepilogue()\n+ // epilogue removes the endpoint from the transport-demuxer and\n+ // unlocks e.mu. Now that no new segments can get enqueued to this\n+ // endpoint, try to re-match the segment to a different endpoint\n+ // as the current endpoint is closed.\n+ for !e.segmentQueue.empty() {\n+ s := e.segmentQueue.dequeue()\n+ e.tryDeliverSegmentFromClosedEndpoint(s)\n+ }\n+\n// A new SYN was received during TIME_WAIT and we need to abort\n// the timewait and redirect the segment to the listener queue\nif reuseTW != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/rcv.go",
"new_path": "pkg/tcpip/transport/tcp/rcv.go",
"diff": "@@ -218,7 +218,7 @@ func (r *receiver) consumeSegment(s *segment, segSeq seqnum.Value, segLen seqnum\ncase StateClosing:\nr.ep.state = StateTimeWait\ncase StateLastAck:\n- r.ep.state = StateClose\n+ r.ep.transitionToStateCloseLocked()\n}\nr.ep.mu.Unlock()\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"new_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"diff": "@@ -454,6 +454,112 @@ func TestConnectResetAfterClose(t *testing.T) {\n}\n}\n+// TestClosingWithEnqueuedSegments tests handling of\n+// still enqueued segments when the endpoint transitions\n+// to StateClose. The in-flight segments would be re-enqueued\n+// to a any listening endpoint.\n+func TestClosingWithEnqueuedSegments(t *testing.T) {\n+ c := context.New(t, defaultMTU)\n+ defer c.Cleanup()\n+\n+ c.CreateConnected(789, 30000, -1 /* epRcvBuf */)\n+ ep := c.EP\n+ c.EP = nil\n+\n+ if got, want := tcp.EndpointState(ep.State()), tcp.StateEstablished; got != want {\n+ t.Errorf(\"Unexpected endpoint state: want %v, got %v\", want, got)\n+ }\n+\n+ // Send a FIN for ESTABLISHED --> CLOSED-WAIT\n+ c.SendPacket(nil, &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: c.Port,\n+ Flags: header.TCPFlagFin | header.TCPFlagAck,\n+ SeqNum: 790,\n+ AckNum: c.IRS.Add(1),\n+ RcvWnd: 30000,\n+ })\n+\n+ // Get the ACK for the FIN we sent.\n+ checker.IPv4(t, c.GetPacket(),\n+ checker.TCP(\n+ checker.DstPort(context.TestPort),\n+ checker.SeqNum(uint32(c.IRS)+1),\n+ checker.AckNum(791),\n+ checker.TCPFlags(header.TCPFlagAck),\n+ ),\n+ )\n+\n+ if got, want := tcp.EndpointState(ep.State()), tcp.StateCloseWait; got != want {\n+ t.Errorf(\"Unexpected endpoint state: want %v, got %v\", want, got)\n+ }\n+\n+ // Close the application endpoint for CLOSE_WAIT --> LAST_ACK\n+ ep.Close()\n+\n+ // Get the FIN\n+ checker.IPv4(t, c.GetPacket(),\n+ checker.TCP(\n+ checker.DstPort(context.TestPort),\n+ checker.SeqNum(uint32(c.IRS)+1),\n+ checker.AckNum(791),\n+ checker.TCPFlags(header.TCPFlagAck|header.TCPFlagFin),\n+ ),\n+ )\n+\n+ if got, want := tcp.EndpointState(ep.State()), tcp.StateLastAck; got != want {\n+ t.Errorf(\"Unexpected endpoint state: want %v, got %v\", want, got)\n+ }\n+\n+ // Pause the endpoint`s protocolMainLoop.\n+ ep.(interface{ StopWork() }).StopWork()\n+\n+ // Enqueue last ACK followed by an ACK matching the endpoint\n+ //\n+ // Send Last ACK for LAST_ACK --> CLOSED\n+ c.SendPacket(nil, &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: c.Port,\n+ Flags: header.TCPFlagAck,\n+ SeqNum: 791,\n+ AckNum: c.IRS.Add(2),\n+ RcvWnd: 30000,\n+ })\n+\n+ // Send a packet with ACK set, this would generate RST when\n+ // not using SYN cookies as in this test.\n+ c.SendPacket(nil, &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: c.Port,\n+ Flags: header.TCPFlagAck | header.TCPFlagFin,\n+ SeqNum: 792,\n+ AckNum: c.IRS.Add(2),\n+ RcvWnd: 30000,\n+ })\n+\n+ // Unpause endpoint`s protocolMainLoop.\n+ ep.(interface{ ResumeWork() }).ResumeWork()\n+\n+ // Wait for the protocolMainLoop to resume and update state.\n+ time.Sleep(1 * time.Millisecond)\n+\n+ // Expect the endpoint to be closed.\n+ if got, want := tcp.EndpointState(ep.State()), tcp.StateClose; got != want {\n+ t.Errorf(\"Unexpected endpoint state: want %v, got %v\", want, got)\n+ }\n+\n+ // Check if the endpoint was moved to CLOSED and netstack a reset in\n+ // response to the ACK packet that we sent after last-ACK.\n+ checker.IPv4(t, c.GetPacket(),\n+ checker.TCP(\n+ checker.DstPort(context.TestPort),\n+ checker.SeqNum(uint32(c.IRS)+2),\n+ checker.AckNum(793),\n+ checker.TCPFlags(header.TCPFlagAck|header.TCPFlagRst),\n+ ),\n+ )\n+}\n+\nfunc TestSimpleReceive(t *testing.T) {\nc := context.New(t, defaultMTU)\ndefer c.Cleanup()\n@@ -686,6 +792,96 @@ func TestSendRstOnListenerRxSynAckV6(t *testing.T) {\nchecker.SeqNum(200)))\n}\n+func TestSendRstOnListenerRxAckV4(t *testing.T) {\n+ c := context.New(t, defaultMTU)\n+ defer c.Cleanup()\n+\n+ c.Create(-1 /* epRcvBuf */)\n+\n+ if err := c.EP.Bind(tcpip.FullAddress{Port: context.StackPort}); err != nil {\n+ t.Fatal(\"Bind failed:\", err)\n+ }\n+\n+ if err := c.EP.Listen(10 /* backlog */); err != nil {\n+ t.Fatal(\"Listen failed:\", err)\n+ }\n+\n+ c.SendPacket(nil, &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: context.StackPort,\n+ Flags: header.TCPFlagFin | header.TCPFlagAck,\n+ SeqNum: 100,\n+ AckNum: 200,\n+ })\n+\n+ checker.IPv4(t, c.GetPacket(), checker.TCP(\n+ checker.DstPort(context.TestPort),\n+ checker.TCPFlags(header.TCPFlagRst|header.TCPFlagAck),\n+ checker.SeqNum(200)))\n+}\n+\n+func TestSendRstOnListenerRxAckV6(t *testing.T) {\n+ c := context.New(t, defaultMTU)\n+ defer c.Cleanup()\n+\n+ c.CreateV6Endpoint(true /* v6Only */)\n+\n+ if err := c.EP.Bind(tcpip.FullAddress{Port: context.StackPort}); err != nil {\n+ t.Fatal(\"Bind failed:\", err)\n+ }\n+\n+ if err := c.EP.Listen(10 /* backlog */); err != nil {\n+ t.Fatal(\"Listen failed:\", err)\n+ }\n+\n+ c.SendV6Packet(nil, &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: context.StackPort,\n+ Flags: header.TCPFlagFin | header.TCPFlagAck,\n+ SeqNum: 100,\n+ AckNum: 200,\n+ })\n+\n+ checker.IPv6(t, c.GetV6Packet(), checker.TCP(\n+ checker.DstPort(context.TestPort),\n+ checker.TCPFlags(header.TCPFlagRst|header.TCPFlagAck),\n+ checker.SeqNum(200)))\n+}\n+\n+// TestListenShutdown tests for the listening endpoint not processing\n+// any receive when it is on read shutdown.\n+func TestListenShutdown(t *testing.T) {\n+ c := context.New(t, defaultMTU)\n+ defer c.Cleanup()\n+\n+ c.Create(-1 /* epRcvBuf */)\n+\n+ if err := c.EP.Bind(tcpip.FullAddress{Port: context.StackPort}); err != nil {\n+ t.Fatal(\"Bind failed:\", err)\n+ }\n+\n+ if err := c.EP.Listen(10 /* backlog */); err != nil {\n+ t.Fatal(\"Listen failed:\", err)\n+ }\n+\n+ if err := c.EP.Shutdown(tcpip.ShutdownRead); err != nil {\n+ t.Fatal(\"Shutdown failed:\", err)\n+ }\n+\n+ // Wait for the endpoint state to be propagated.\n+ time.Sleep(10 * time.Millisecond)\n+\n+ c.SendPacket(nil, &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: context.StackPort,\n+ Flags: header.TCPFlagSyn,\n+ SeqNum: 100,\n+ AckNum: 200,\n+ })\n+\n+ c.CheckNoPacket(\"Packet received when listening socket was shutdown\")\n+}\n+\nfunc TestTOSV4(t *testing.T) {\nc := context.New(t, defaultMTU)\ndefer c.Cleanup()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Handle in-flight TCP segments when moving to CLOSE.
As we move to CLOSE state from LAST-ACK or TIME-WAIT,
ensure that we re-match all in-flight segments to any
listening endpoint.
Also fix LISTEN state handling of any ACK segments as per RFC793.
Fixes #1153
PiperOrigin-RevId: 280703556 |
259,858 | 18.11.2019 11:21:18 | 28,800 | 96019436854b0c59ae380a4920381586d05d9c31 | release: fix tag script
The tag script, when not run interactively, will fail without a provided commit
message (since it now uses annotated tags). For now, use a trivial message. In
the future, this could be extended to provide automated release notes. | [
{
"change_type": "MODIFY",
"old_path": "tools/tag_release.sh",
"new_path": "tools/tag_release.sh",
"diff": "@@ -64,5 +64,6 @@ fi\n# Tag the given commit (annotated, to record the committer).\ndeclare -r tag=\"release-${release}\"\n-(git tag -a \"${tag}\" \"${commit}\" && git push origin tag \"${tag}\") || \\\n+(git tag -m \"Release ${release}\" -a \"${tag}\" \"${commit}\" && \\\n+ git push origin tag \"${tag}\") || \\\n(git tag -d \"${tag}\" && false)\n"
}
] | Go | Apache License 2.0 | google/gvisor | release: fix tag script
The tag script, when not run interactively, will fail without a provided commit
message (since it now uses annotated tags). For now, use a trivial message. In
the future, this could be extended to provide automated release notes.
PiperOrigin-RevId: 281112651 |
259,853 | 18.11.2019 14:55:30 | 28,800 | 26b3341b9ae08bb72971d5465c77e6c8db82c996 | platform/ptrace: use host.GetCPU instead of the getcpu syscall
This should save ~200ns from switchToApp (on ptrace too). // mpratt | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/BUILD",
"new_path": "pkg/sentry/platform/ptrace/BUILD",
"diff": "@@ -28,6 +28,7 @@ go_library(\n\"//pkg/procid\",\n\"//pkg/seccomp\",\n\"//pkg/sentry/arch\",\n+ \"//pkg/sentry/hostcpu\",\n\"//pkg/sentry/platform\",\n\"//pkg/sentry/platform/interrupt\",\n\"//pkg/sentry/platform/safecopy\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/subprocess_linux_unsafe.go",
"new_path": "pkg/sentry/platform/ptrace/subprocess_linux_unsafe.go",
"diff": "@@ -25,6 +25,7 @@ import (\n\"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/sentry/hostcpu\"\n)\n// maskPool contains reusable CPU masks for setting affinity. Unfortunately,\n@@ -49,20 +50,6 @@ func unmaskAllSignals() syscall.Errno {\nreturn errno\n}\n-// getCPU gets the current CPU.\n-//\n-// Precondition: the current runtime thread should be locked.\n-func getCPU() (uint32, error) {\n- var cpu uintptr\n- if _, _, errno := syscall.RawSyscall(\n- unix.SYS_GETCPU,\n- uintptr(unsafe.Pointer(&cpu)),\n- 0, 0); errno != 0 {\n- return 0, errno\n- }\n- return uint32(cpu), nil\n-}\n-\n// setCPU sets the CPU affinity.\nfunc (t *thread) setCPU(cpu uint32) error {\nmask := maskPool.Get().([]uintptr)\n@@ -93,10 +80,8 @@ func (t *thread) setCPU(cpu uint32) error {\n//\n// Precondition: the current runtime thread should be locked.\nfunc (t *thread) bind() {\n- currentCPU, err := getCPU()\n- if err != nil {\n- return\n- }\n+ currentCPU := hostcpu.GetCPU()\n+\nif oldCPU := atomic.SwapUint32(&t.cpu, currentCPU); oldCPU != currentCPU {\n// Set the affinity on the thread and save the CPU for next\n// round; we don't expect CPUs to bounce around too frequently.\n"
}
] | Go | Apache License 2.0 | google/gvisor | platform/ptrace: use host.GetCPU instead of the getcpu syscall
This should save ~200ns from switchToApp (on ptrace too). // mpratt
PiperOrigin-RevId: 281159895 |
259,885 | 18.11.2019 16:25:03 | 28,800 | ef6f93625457c166628fc9de57c15d986ae83159 | Add vfs.GenericParseMountOptions().
Equivalent to fs.GenericMountSourceOptions(). | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/BUILD",
"new_path": "pkg/sentry/vfs/BUILD",
"diff": "@@ -12,6 +12,7 @@ go_library(\n\"file_description.go\",\n\"file_description_impl_util.go\",\n\"filesystem.go\",\n+ \"filesystem_impl_util.go\",\n\"filesystem_type.go\",\n\"mount.go\",\n\"mount_unsafe.go\",\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/vfs/filesystem_impl_util.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+ \"strings\"\n+)\n+\n+// GenericParseMountOptions parses a comma-separated list of options of the\n+// form \"key\" or \"key=value\", where neither key nor value contain commas, and\n+// returns it as a map. If str contains duplicate keys, then the last value\n+// wins. For example:\n+//\n+// str = \"key0=value0,key1,key2=value2,key0=value3\" -> map{'key0':'value3','key1':'','key2':'value2'}\n+//\n+// GenericParseMountOptions is not appropriate if values may contain commas,\n+// e.g. in the case of the mpol mount option for tmpfs(5).\n+func GenericParseMountOptions(str string) map[string]string {\n+ m := make(map[string]string)\n+ for _, opt := range strings.Split(str, \",\") {\n+ if len(opt) > 0 {\n+ res := strings.SplitN(opt, \"=\", 2)\n+ if len(res) == 2 {\n+ m[res[0]] = res[1]\n+ } else {\n+ m[opt] = \"\"\n+ }\n+ }\n+ }\n+ return m\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add vfs.GenericParseMountOptions().
Equivalent to fs.GenericMountSourceOptions().
PiperOrigin-RevId: 281179287 |
259,884 | 18.10.2019 05:28:45 | 14,400 | d9f1d86286a2a376f554d43a69c9ee849f1b83ab | Added base blog content. | [
{
"change_type": "MODIFY",
"old_path": "config.toml",
"new_path": "config.toml",
"diff": "@@ -35,8 +35,12 @@ pygmentsStyle = \"tango\"\nweight = -100\nurl = \"/docs/\"\n[[menu.main]]\n- name = \"GitHub\"\n+ name = \"Blog\"\nweight = -99\n+ url = \"/blog/\"\n+[[menu.main]]\n+ name = \"GitHub\"\n+ weight = -98\nurl = \"https://github.com/google/gvisor\"\n# First one is picked as the Twitter card image if not set on page.\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "content/blog/_index.md",
"diff": "+---\n+title: \"gVisor Blog\"\n+linkTitle: \"Blog\"\n+---\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "content/blog/first-post/index.md",
"diff": "+---\n+date: 2019-10-17\n+title: \"First Blog Post\"\n+linkTitle: \"First Blog Post\"\n+description: \"\"\n+author: John Doe\n+---\n+\n+This is a test blog post.\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "content/blog/second-post/index.md",
"diff": "+---\n+date: 2019-10-18\n+title: \"Second Blog Post\"\n+linkTitle: \"Second Blog Post\"\n+description: \"\"\n+author: John Doe\n+---\n+\n+This is a second test blog post.\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "layouts/blog/baseof.html",
"diff": "+<!doctype html>\n+<html lang=\"{{ .Site.Language.Lang }}\" class=\"no-js\">\n+ <head>\n+ {{ partial \"head.html\" . }}\n+ <title>{{ if .IsHome }}{{ .Site.Title }}{{ else }}{{ with .Title }}{{ . }} | {{ end }}{{ .Site.Title }}{{ end }}</title>\n+ </head>\n+ <body class=\"td-{{ .Kind }} td-blog\">\n+ <header>\n+ {{ partial \"navbar.html\" . }}\n+ </header>\n+ <div class=\"container-fluid td-outer\">\n+ <div class=\"td-main\">\n+ <div class=\"row flex-xl-nowrap\">\n+ <div class=\"col-12 col-md-3 col-xl-2 td-sidebar d-print-none\">\n+ {{ partial \"sidebar.html\" . }}\n+ </div>\n+ <div class=\"d-none d-xl-block col-xl-2 td-toc d-print-none\"> </div>\n+ <main class=\"col-12 col-md-9 col-xl-8 pl-md-5 pr-md-4\" role=\"main\">\n+ {{ with .CurrentSection.OutputFormats.Get \"rss\" -}}\n+ <a class=\"btn btn-lg -bg-orange td-rss-button d-none d-lg-block\" href=\"{{ .Permalink | safeURL }}\" target=\"_blank\">\n+ RSS <i class=\"fa fa-rss ml-2 \"></i>\n+ </a>\n+ {{ end -}}\n+ {{ block \"main\" . }}{{ end }}\n+ </main>\n+ </div>\n+ </div>\n+ {{ partial \"footer.html\" . }}\n+ </div>\n+ {{ partial \"scripts.html\" . }}\n+ </body>\n+</html>\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "layouts/blog/content.html",
"diff": "+<div class=\"td-content\">\n+ <h1>{{ .Title }}</h1>\n+ {{ with .Params.description }}<div class=\"lead\">{{ . | markdownify }}</div>{{ end }}\n+ <div class=\"td-byline mb-4\">\n+ {{ with .Params.author }}{{ T \"post_byline_by\" }} <b>{{ . | markdownify }}</b> |{{ end}}\n+ <time datetime=\"{{ $.Date.Format \"2006-01-02\" }}\" class=\"text-muted\">{{ $.Date.Format $.Site.Params.time_format_blog }}</time>\n+ </div>\n+ {{ .Content }}\n+ {{ if (.Site.DisqusShortname) }}\n+ <br />\n+ {{ partial \"disqus-comment.html\" . }}\n+ <br />\n+ {{ end }}\n+</div>\n"
}
] | Go | Apache License 2.0 | google/gvisor | Added base blog content. |
259,884 | 12.11.2019 19:00:30 | 18,000 | a253368f7695c33ce88a2363426c710f0069500e | Add fragment links only on docs pages
Add fragment links only on docs pages and only when there is an 'id'
attribute. | [
{
"change_type": "MODIFY",
"old_path": "layouts/partials/scripts.html",
"new_path": "layouts/partials/scripts.html",
"diff": "{{ partial \"hooks/body-end.html\" . }}\n<script type=\"text/javascript\">\n+ if (location.pathname == \"/docs\" || location.pathname.startsWith(\"/docs/\")) {\n$(\"body.td-page,body.td-section\").find(\"main h2,h3,h4\").each(function() {\nvar fragment = $(this).attr('id');\n+ if (fragment !== undefined && fragment !== \"\") {\n$(this).append(' <a href=\"#'+fragment+'\" class=\"header-link\"><i class=\"fas fa-link\"></i></a>');\n+ }\n});\n+ }\n</script>\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add fragment links only on docs pages
Add fragment links only on docs pages and only when there is an 'id'
attribute. |
259,975 | 15.11.2019 10:02:02 | 28,800 | de56e7893445b09c9854ff6f79c4ed187e01be52 | Adding first blog post. | [
{
"change_type": "ADD",
"old_path": "content/blog/1_security_basics/figure1.png",
"new_path": "content/blog/1_security_basics/figure1.png",
"diff": "Binary files /dev/null and b/content/blog/1_security_basics/figure1.png differ\n"
},
{
"change_type": "ADD",
"old_path": "content/blog/1_security_basics/figure2.png",
"new_path": "content/blog/1_security_basics/figure2.png",
"diff": "Binary files /dev/null and b/content/blog/1_security_basics/figure2.png differ\n"
},
{
"change_type": "ADD",
"old_path": "content/blog/1_security_basics/figure3.png",
"new_path": "content/blog/1_security_basics/figure3.png",
"diff": "Binary files /dev/null and b/content/blog/1_security_basics/figure3.png differ\n"
},
{
"change_type": "DELETE",
"old_path": "content/blog/first-post/index.md",
"new_path": null,
"diff": "----\n-date: 2019-10-17\n-title: \"First Blog Post\"\n-linkTitle: \"First Blog Post\"\n-description: \"\"\n-author: John Doe\n----\n-\n-This is a test blog post.\n"
},
{
"change_type": "DELETE",
"old_path": "content/blog/second-post/index.md",
"new_path": null,
"diff": "----\n-date: 2019-10-18\n-title: \"Second Blog Post\"\n-linkTitle: \"Second Blog Post\"\n-description: \"\"\n-author: John Doe\n----\n-\n-This is a second test blog post.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Adding first blog post. |
259,884 | 18.10.2019 01:37:17 | 14,400 | 00471432c45e215081020b0fac54a27f4bcbf565 | Update to Go 1.12 runtime.
Update to the Go 1.12 runtime.
The login option in app.yaml is no longer supported. Check the
X-Appengine-Cron http header instead.
Add a 'stage' make target that allows you to easily stage a change. | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -14,7 +14,7 @@ APP_TARGET = $(patsubst cmd/gvisor-website/%,public/%,$(APP_SOURCE))\ndefault: website\n.PHONY: default\n-website: all-upstream app public/static\n+website: all-upstream app static-production\n.PHONY: website\napp: $(APP_TARGET)\n@@ -44,8 +44,13 @@ content/docs/community/sigs: upstream/community $(wildcard upstream/community/si\n$(APP_TARGET): public $(APP_SOURCE)\ncp -a cmd/gvisor-website/$(patsubst public/%,%,$@) public/\n-public/static: compatibility-docs node_modules config.toml $(shell find archetypes assets content themes -type f | sed 's/ /\\\\ /g')\n+static-production: compatibility-docs node_modules config.toml $(shell find archetypes assets content themes -type f | sed 's/ /\\\\ /g')\nHUGO_ENV=\"production\" $(HUGO)\n+.PHONY: static-production\n+\n+static-staging: compatibility-docs node_modules config.toml $(shell find archetypes assets content themes -type f | sed 's/ /\\\\ /g')\n+ $(HUGO) -b \"https://staging-$(shell git branch | grep \\* | cut -d ' ' -f2)-dot-gvisor-website.appspot.com\"\n+.PHONY: static-staging\nnode_modules: package.json package-lock.json\n# Use npm ci because npm install will update the package-lock.json.\n@@ -77,10 +82,17 @@ server: website\n.PHONY: server\n# Deploy the website to App Engine.\n-deploy: $(APP_TARGET)\n+deploy: website\ncd public && $(GCLOUD) app deploy\n.PHONY: deploy\n+# Stage the website to App Engine at a version based on the git branch name.\n+stage: all-upstream app static-staging\n+ # Disallow indexing staged content.\n+ printf \"User-agent: *\\nDisallow: /\" > public/static/robots.txt\n+ cd public && $(GCLOUD) app deploy -v staging-$(shell git branch | grep \\* | cut -d ' ' -f2) --no-promote\n+.PHONY: stage\n+\n# CI related Commmands\n##############################################################################\n"
},
{
"change_type": "MODIFY",
"old_path": "cmd/gvisor-website/app.yaml",
"new_path": "cmd/gvisor-website/app.yaml",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-runtime: go111\n+runtime: go112\nhandlers:\n- url: /.*\n@@ -21,4 +21,3 @@ handlers:\n- url: /rebuild\nsecure: always\nscript: auto\n- login: admin\n"
},
{
"change_type": "MODIFY",
"old_path": "cmd/gvisor-website/main.go",
"new_path": "cmd/gvisor-website/main.go",
"diff": "@@ -71,6 +71,20 @@ var (\ngoGetHTML5 = `<!doctype html><html><head><meta charset=utf-8>` + goGetHeader + `<title>Go-get</title></head><body></html>`\n)\n+// cronHandler wraps an http.Handler to check that the request is from the App\n+// Engine Cron service.\n+// See: https://cloud.google.com/appengine/docs/standard/go112/scheduling-jobs-with-cron-yaml#validating_cron_requests\n+func cronHandler(h http.Handler) http.Handler {\n+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n+ if r.Header.Get(\"X-Appengine-Cron\") != \"true\" {\n+ http.NotFound(w, r)\n+ return\n+ }\n+ // Fallthrough.\n+ h.ServeHTTP(w, r)\n+ })\n+}\n+\n// wrappedHandler wraps an http.Handler.\n//\n// If the query parameters include go-get=1, then we redirect to a single\n@@ -174,7 +188,7 @@ func registerRebuild(mux *http.ServeMux) {\nmux = http.DefaultServeMux\n}\n- mux.Handle(\"/rebuild\", wrappedHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n+ mux.Handle(\"/rebuild\", cronHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\nctx := context.Background()\ncredentials, err := google.FindDefaultCredentials(ctx, cloudbuild.CloudPlatformScope)\nif err != nil {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update to Go 1.12 runtime.
Update to the Go 1.12 runtime.
- The login option in app.yaml is no longer supported. Check the
X-Appengine-Cron http header instead.
- Add a 'stage' make target that allows you to easily stage a change. |
259,858 | 20.11.2019 15:28:02 | 28,800 | b6a00aa375e674617f1914b90db5ddb222b5a04e | Use a GitHub credential for tagging a release. | [
{
"change_type": "MODIFY",
"old_path": "kokoro/release.cfg",
"new_path": "kokoro/release.cfg",
"diff": "build_file: \"repo/scripts/release.sh\"\n+\n+before_action {\n+ fetch_keystore {\n+ keystore_resource {\n+ keystore_config_id: 73898\n+ keyname: \"kokoro-github-access-token\"\n+ }\n+ }\n+}\n+\n+env_vars {\n+ key: \"KOKORO_GITHUB_ACCESS_TOKEN\"\n+ value: \"73898_kokoro-github-access-token\"\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/release.sh",
"new_path": "scripts/release.sh",
"diff": "@@ -34,5 +34,16 @@ declare -r EMAIL=${EMAIL:-${KOKORO_RELEASE_AUTHOR}@google.com}\ngit config --get user.name || git config user.name \"gVisor-bot\"\ngit config --get user.email || git config user.email \"${EMAIL}\"\n+# Provide a credential if available.\n+if [[ -v KOKORO_GITHUB_ACCESS_TOKEN ]]; then\n+ git config --global credential.helper cache\n+ git credential approve <<EOF\n+protocol=https\n+host=github.com\n+username=$(cat \"${KOKORO_KEYSTORE_DIR}/${KOKORO_GITHUB_ACCESS_TOKEN}\")\n+password=x-oauth-basic\n+EOF\n+fi\n+\n# Run the release tool, which pushes to the origin repository.\ntools/tag_release.sh \"${KOKORO_RELEASE_COMMIT}\" \"${KOKORO_RELEASE_TAG}\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use a GitHub credential for tagging a release.
PiperOrigin-RevId: 281617882 |
259,858 | 05.11.2019 17:55:06 | 18,000 | 4e4d55b9436df5a8e284074c5dda5cffca262005 | Re-add apt-based installation instructions. | [
{
"change_type": "MODIFY",
"old_path": "content/docs/user_guide/install.md",
"new_path": "content/docs/user_guide/install.md",
"diff": "@@ -13,12 +13,21 @@ release channels. You should pick the version you'd like to install. For\nexperimentation, the nightly release is recommended. For production use, the\nlatest release is recommended.\n-<!--\n-\nAfter selecting an appropriate release channel from the options below, proceed\nto the preferred installation mechanism: manual or from an `apt` repository.\n- -->\n+### HEAD\n+\n+Binaries are available for every commit on the `master` branch, and are\n+available at the following URL:\n+\n+ `https://storage.googleapis.com/gvisor/releases/master/latest/runsc`\n+\n+Checksums for the release binary are at:\n+\n+ `https://storage.googleapis.com/gvisor/releases/master/latest/runsc.sha512`\n+\n+For `apt` installation, use the `master` as the `${DIST}` below.\n### Nightly\n@@ -37,10 +46,7 @@ Specific nightly releases can be found at:\nNote that a release may not be available for every day.\n-<!--\n-\n-To use a nightly release, use one of the above URLs for `URL` in the manual\n-instructions below. For `apt`, use `nightly` for `DIST` below.\n+For `apt` installation, use the `nightly` as the `${DIST}` below.\n### Latest release\n@@ -48,8 +54,7 @@ The latest official release is available at the following URL:\n`https://storage.googleapis.com/gvisor/releases/release/latest`\n-To use the latest release, use the above URL for `URL` in the manual\n-instructions below. For `apt`, use `latest` for `DIST` below.\n+For `apt` installation, use the `release` as the `${DIST}` below.\n### Specific release\n@@ -59,11 +64,10 @@ A given release release is available at the following URL:\nSee the [releases][releases] page for information about specific releases.\n+For `apt` installation of a specific release, which may include point updates,\n+use the date of the release, e.g. `${yyyymmdd}`, as the `${DIST}` below.\n-This will include point updates for the release, if required. To use a specific\n-release, use the above URL for `URL` in the manual instructions below. For\n-`apt`, use `${yyyymmdd}` for `DIST` below.\n-\n+> Note: only newer releases may be available as `apt` repositories.\n### Point release\n@@ -71,14 +75,9 @@ A given point release is available at the following URL:\n`https://storage.googleapis.com/gvisor/releases/release/${yyyymmdd}.${rc}`\n+Note that `apt` installation of a specific point release is not supported.\n-Unlike the specific release above, which may include updates, this release will\n-not change. To use a specific point release, use the above URL for `URL` in the\n-manual instructions below. For apt, use `${yyyymmdd}.${rc}` for `DIST` below.\n-\n- -->\n-\n-<!-- Install from an `apt` repository\n+## Install from an `apt` repository\nFirst, appropriate dependencies must be installed to allow `apt` to install\npackages via https:\n@@ -102,27 +101,21 @@ curl -fsSL https://gvisor.dev/archive.key | sudo apt-key add -\nBased on the release type, you will need to substitute `${DIST}` below, using\none of:\n- * `nightly`: For all nightly releases.\n- * `latest`: For the latest release.\n- * `${yyyymmdd}`: For specific releases.\n- * `${yyyymmdd}.${rc}`: For a specific point release.\n+ * `master`: For HEAD.\n+ * `nightly`: For nightly releases.\n+ * `release`: For the latest release.\n+ * `${yyyymmdd}`: For a specific releases (see above).\nThe repository for the release you wish to install should be added:\n```bash\n-sudo add-apt-repository \\\n- \"deb https://storage.googleapis.com/gvisor/releases\" \\\n- \"${DIST}\" \\\n- main\n+sudo add-apt-repository \"deb https://storage.googleapis.com/gvisor/releases ${DIST} main\"\n```\nFor example, to install the latest official release, you can use:\n```bash\n-sudo add-apt-repository \\\n- \"deb https://storage.googleapis.com/gvisor/releases\" \\\n- latest \\\n- main\n+sudo add-apt-repository \"deb https://storage.googleapis.com/gvisor/releases release main\"\n```\nNow the runsc package can be installed:\n@@ -133,10 +126,11 @@ sudo apt-get update && sudo apt-get install -y runsc\nIf you have Docker installed, it will be automatically configured.\n--->\n+## Install directly\n-For example, the latest nightly binary can be downloaded, validated,\n-and placed in an appropriate location by running:\n+The binary URLs provided above can be used to install directly. For example, the\n+latest nightly binary can be downloaded, validated, and placed in an appropriate\n+location by running:\n```bash\n(\n"
}
] | Go | Apache License 2.0 | google/gvisor | Re-add apt-based installation instructions. |
259,853 | 22.11.2019 10:42:57 | 28,800 | 4e27ba372e12e3186c0d03b32a7829b0d50f7a89 | tests: include sys/socket.h before linux/if_arp.h
This is how it has to be accoding to the man page. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_netlink_util.h",
"new_path": "test/syscalls/linux/socket_netlink_util.h",
"diff": "#ifndef GVISOR_TEST_SYSCALLS_SOCKET_NETLINK_UTIL_H_\n#define GVISOR_TEST_SYSCALLS_SOCKET_NETLINK_UTIL_H_\n+#include <sys/socket.h>\n+// socket.h has to be included before if_arp.h.\n#include <linux/if_arp.h>\n#include <linux/netlink.h>\n"
}
] | Go | Apache License 2.0 | google/gvisor | tests: include sys/socket.h before linux/if_arp.h
This is how it has to be accoding to the man page.
PiperOrigin-RevId: 281998068 |
259,914 | 22.11.2019 11:54:04 | 28,800 | 07635d20d40e1a279c4b063abaaad51048400ed7 | enable ring0/pagetables to support arm64
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/gvisor/pull/891 from lubinszARM:pr_pagetable | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/pagetables/BUILD",
"new_path": "pkg/sentry/platform/ring0/pagetables/BUILD",
"diff": "-load(\"//tools/go_stateify:defs.bzl\", \"go_library\")\nload(\"@io_bazel_rules_go//go:def.bzl\", \"go_test\")\n+load(\"//tools/go_stateify:defs.bzl\", \"go_library\")\nload(\"//tools/go_generics:defs.bzl\", \"go_template\", \"go_template_instance\")\npackage(licenses = [\"notice\"])\n+config_setting(\n+ name = \"aarch64\",\n+ constraint_values = [\"@bazel_tools//platforms:aarch64\"],\n+)\n+\ngo_template(\nname = \"generic_walker\",\n- srcs = [\n- \"walker_amd64.go\",\n- ],\n+ srcs = [\"walker_amd64.go\"],\nopt_types = [\n\"Visitor\",\n],\n@@ -76,9 +79,13 @@ go_library(\n\"allocator.go\",\n\"allocator_unsafe.go\",\n\"pagetables.go\",\n+ \"pagetables_aarch64.go\",\n\"pagetables_amd64.go\",\n+ \"pagetables_arm64.go\",\n\"pagetables_x86.go\",\n\"pcids_x86.go\",\n+ \"walker_amd64.go\",\n+ \"walker_arm64.go\",\n\"walker_empty.go\",\n\"walker_lookup.go\",\n\"walker_map.go\",\n@@ -97,6 +104,7 @@ go_test(\nsize = \"small\",\nsrcs = [\n\"pagetables_amd64_test.go\",\n+ \"pagetables_arm64_test.go\",\n\"pagetables_test.go\",\n\"walker_check.go\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/pagetables/pagetables.go",
"new_path": "pkg/sentry/platform/ring0/pagetables/pagetables.go",
"diff": "@@ -48,15 +48,6 @@ func New(a Allocator) *PageTables {\nreturn p\n}\n-// Init initializes a set of PageTables.\n-//\n-//go:nosplit\n-func (p *PageTables) Init(allocator Allocator) {\n- p.Allocator = allocator\n- p.root = p.Allocator.NewPTEs()\n- p.rootPhysical = p.Allocator.PhysicalFor(p.root)\n-}\n-\n// mapVisitor is used for map.\ntype mapVisitor struct {\ntarget uintptr // Input.\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/platform/ring0/pagetables/pagetables_aarch64.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 pagetables\n+\n+import (\n+ \"sync/atomic\"\n+\n+ \"gvisor.dev/gvisor/pkg/sentry/usermem\"\n+)\n+\n+// archPageTables is architecture-specific data.\n+type archPageTables struct {\n+ // root is the pagetable root for kernel space.\n+ root *PTEs\n+\n+ // rootPhysical is the cached physical address of the root.\n+ //\n+ // This is saved only to prevent constant translation.\n+ rootPhysical uintptr\n+\n+ asid uint16\n+}\n+\n+// TTBR0_EL1 returns the translation table base register 0.\n+//\n+//go:nosplit\n+func (p *PageTables) TTBR0_EL1(noFlush bool, asid uint16) uint64 {\n+ return uint64(p.rootPhysical) | (uint64(asid)&ttbrASIDMask)<<ttbrASIDOffset\n+}\n+\n+// TTBR1_EL1 returns the translation table base register 1.\n+//\n+//go:nosplit\n+func (p *PageTables) TTBR1_EL1(noFlush bool, asid uint16) uint64 {\n+ return uint64(p.archPageTables.rootPhysical) | (uint64(asid)&ttbrASIDMask)<<ttbrASIDOffset\n+}\n+\n+// Bits in page table entries.\n+const (\n+ typeTable = 0x3 << 0\n+ typeSect = 0x1 << 0\n+ typePage = 0x3 << 0\n+ pteValid = 0x1 << 0\n+ pteTableBit = 0x1 << 1\n+ pteTypeMask = 0x3 << 0\n+ present = pteValid | pteTableBit\n+ user = 0x1 << 6 /* AP[1] */\n+ readOnly = 0x1 << 7 /* AP[2] */\n+ accessed = 0x1 << 10\n+ dbm = 0x1 << 51\n+ writable = dbm\n+ cont = 0x1 << 52\n+ pxn = 0x1 << 53\n+ xn = 0x1 << 54\n+ dirty = 0x1 << 55\n+ nG = 0x1 << 11\n+ shared = 0x3 << 8\n+)\n+\n+const (\n+ mtNormal = 0x4 << 2\n+)\n+\n+const (\n+ executeDisable = xn\n+ optionMask = 0xfff | 0xfff<<48\n+ protDefault = accessed | shared | mtNormal\n+)\n+\n+// MapOpts are x86 options.\n+type MapOpts struct {\n+ // AccessType defines permissions.\n+ AccessType usermem.AccessType\n+\n+ // Global indicates the page is globally accessible.\n+ Global bool\n+\n+ // User indicates the page is a user page.\n+ User bool\n+}\n+\n+// PTE is a page table entry.\n+type PTE uintptr\n+\n+// Clear clears this PTE, including sect page information.\n+//\n+//go:nosplit\n+func (p *PTE) Clear() {\n+ atomic.StoreUintptr((*uintptr)(p), 0)\n+}\n+\n+// Valid returns true iff this entry is valid.\n+//\n+//go:nosplit\n+func (p *PTE) Valid() bool {\n+ return atomic.LoadUintptr((*uintptr)(p))&present != 0\n+}\n+\n+// Opts returns the PTE options.\n+//\n+// These are all options except Valid and Sect.\n+//\n+//go:nosplit\n+func (p *PTE) Opts() MapOpts {\n+ v := atomic.LoadUintptr((*uintptr)(p))\n+\n+ return MapOpts{\n+ AccessType: usermem.AccessType{\n+ Read: true,\n+ Write: v&readOnly == 0,\n+ Execute: v&xn == 0,\n+ },\n+ Global: v&nG == 0,\n+ User: v&user != 0,\n+ }\n+}\n+\n+// SetSect sets this page as a sect page.\n+//\n+// The page must not be valid or a panic will result.\n+//\n+//go:nosplit\n+func (p *PTE) SetSect() {\n+ if p.Valid() {\n+ // This is not allowed.\n+ panic(\"SetSect called on valid page!\")\n+ }\n+ atomic.StoreUintptr((*uintptr)(p), typeSect)\n+}\n+\n+// IsSect returns true iff this page is a sect page.\n+//\n+//go:nosplit\n+func (p *PTE) IsSect() bool {\n+ return atomic.LoadUintptr((*uintptr)(p))&pteTypeMask == typeSect\n+}\n+\n+// Set sets this PTE value.\n+//\n+// This does not change the sect page property.\n+//\n+//go:nosplit\n+func (p *PTE) Set(addr uintptr, opts MapOpts) {\n+ if !opts.AccessType.Any() {\n+ p.Clear()\n+ return\n+ }\n+ v := (addr &^ optionMask) | protDefault | nG | readOnly\n+\n+ if p.IsSect() {\n+ // Note that this is inherited from the previous instance. Set\n+ // does not change the value of Sect. See above.\n+ v |= typeSect\n+ } else {\n+ v |= typePage\n+ }\n+\n+ if opts.Global {\n+ v = v &^ nG\n+ }\n+\n+ if opts.AccessType.Execute {\n+ v = v &^ executeDisable\n+ } else {\n+ v |= executeDisable\n+ }\n+ if opts.AccessType.Write {\n+ v = v &^ readOnly\n+ }\n+\n+ if opts.User {\n+ v |= user\n+ } else {\n+ v = v &^ user\n+ }\n+ atomic.StoreUintptr((*uintptr)(p), v)\n+}\n+\n+// setPageTable sets this PTE value and forces the write bit and sect bit to\n+// be cleared. This is used explicitly for breaking sect pages.\n+//\n+//go:nosplit\n+func (p *PTE) setPageTable(pt *PageTables, ptes *PTEs) {\n+ addr := pt.Allocator.PhysicalFor(ptes)\n+ if addr&^optionMask != addr {\n+ // This should never happen.\n+ panic(\"unaligned physical address!\")\n+ }\n+ v := addr | typeTable | protDefault\n+ atomic.StoreUintptr((*uintptr)(p), v)\n+}\n+\n+// Address extracts the address. This should only be used if Valid returns true.\n+//\n+//go:nosplit\n+func (p *PTE) Address() uintptr {\n+ return atomic.LoadUintptr((*uintptr)(p)) &^ optionMask\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/pagetables/pagetables_amd64.go",
"new_path": "pkg/sentry/platform/ring0/pagetables/pagetables_amd64.go",
"diff": "@@ -41,5 +41,14 @@ const (\nentriesPerPage = 512\n)\n+// Init initializes a set of PageTables.\n+//\n+//go:nosplit\n+func (p *PageTables) Init(allocator Allocator) {\n+ p.Allocator = allocator\n+ p.root = p.Allocator.NewPTEs()\n+ p.rootPhysical = p.Allocator.PhysicalFor(p.root)\n+}\n+\n// PTEs is a collection of entries.\ntype PTEs [entriesPerPage]PTE\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/platform/ring0/pagetables/pagetables_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 pagetables\n+\n+// Address constraints.\n+//\n+// The lowerTop and upperBottom currently apply to four-level pagetables;\n+// additional refactoring would be necessary to support five-level pagetables.\n+const (\n+ lowerTop = 0x0000ffffffffffff\n+ upperBottom = 0xffff000000000000\n+ pteShift = 12\n+ pmdShift = 21\n+ pudShift = 30\n+ pgdShift = 39\n+\n+ pteMask = 0x1ff << pteShift\n+ pmdMask = 0x1ff << pmdShift\n+ pudMask = 0x1ff << pudShift\n+ pgdMask = 0x1ff << pgdShift\n+\n+ pteSize = 1 << pteShift\n+ pmdSize = 1 << pmdShift\n+ pudSize = 1 << pudShift\n+ pgdSize = 1 << pgdShift\n+\n+ ttbrASIDOffset = 55\n+ ttbrASIDMask = 0xff\n+\n+ entriesPerPage = 512\n+)\n+\n+// Init initializes a set of PageTables.\n+//\n+//go:nosplit\n+func (p *PageTables) Init(allocator Allocator) {\n+ p.Allocator = allocator\n+ p.root = p.Allocator.NewPTEs()\n+ p.rootPhysical = p.Allocator.PhysicalFor(p.root)\n+ p.archPageTables.root = p.Allocator.NewPTEs()\n+ p.archPageTables.rootPhysical = p.Allocator.PhysicalFor(p.archPageTables.root)\n+}\n+\n+// PTEs is a collection of entries.\n+type PTEs [entriesPerPage]PTE\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/platform/ring0/pagetables/pagetables_arm64_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+// +build arm64\n+\n+package pagetables\n+\n+import (\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/sentry/usermem\"\n+)\n+\n+func Test2MAnd4K(t *testing.T) {\n+ pt := New(NewRuntimeAllocator())\n+\n+ // Map a small page and a huge page.\n+ pt.Map(0x400000, pteSize, MapOpts{AccessType: usermem.ReadWrite, User: true}, pteSize*42)\n+ pt.Map(0x0000ff0000000000, pmdSize, MapOpts{AccessType: usermem.Read, User: true}, pmdSize*47)\n+\n+ pt.Map(0xffff000000400000, pteSize, MapOpts{AccessType: usermem.ReadWrite, User: false}, pteSize*42)\n+ pt.Map(0xffffff0000000000, pmdSize, MapOpts{AccessType: usermem.Read, User: false}, pmdSize*47)\n+\n+ checkMappings(t, pt, []mapping{\n+ {0x400000, pteSize, pteSize * 42, MapOpts{AccessType: usermem.ReadWrite, User: true}},\n+ {0x0000ff0000000000, pmdSize, pmdSize * 47, MapOpts{AccessType: usermem.Read, User: true}},\n+ {0xffff000000400000, pteSize, pteSize * 42, MapOpts{AccessType: usermem.ReadWrite, User: false}},\n+ {0xffffff0000000000, pmdSize, pmdSize * 47, MapOpts{AccessType: usermem.Read, User: false}},\n+ })\n+}\n+\n+func Test1GAnd4K(t *testing.T) {\n+ pt := New(NewRuntimeAllocator())\n+\n+ // Map a small page and a super page.\n+ pt.Map(0x400000, pteSize, MapOpts{AccessType: usermem.ReadWrite, User: true}, pteSize*42)\n+ pt.Map(0x0000ff0000000000, pudSize, MapOpts{AccessType: usermem.Read, User: true}, pudSize*47)\n+\n+ checkMappings(t, pt, []mapping{\n+ {0x400000, pteSize, pteSize * 42, MapOpts{AccessType: usermem.ReadWrite, User: true}},\n+ {0x0000ff0000000000, pudSize, pudSize * 47, MapOpts{AccessType: usermem.Read, User: true}},\n+ })\n+}\n+\n+func TestSplit1GPage(t *testing.T) {\n+ pt := New(NewRuntimeAllocator())\n+\n+ // Map a super page and knock out the middle.\n+ pt.Map(0x0000ff0000000000, pudSize, MapOpts{AccessType: usermem.Read, User: true}, pudSize*42)\n+ pt.Unmap(usermem.Addr(0x0000ff0000000000+pteSize), pudSize-(2*pteSize))\n+\n+ checkMappings(t, pt, []mapping{\n+ {0x0000ff0000000000, pteSize, pudSize * 42, MapOpts{AccessType: usermem.Read, User: true}},\n+ {0x0000ff0000000000 + pudSize - pteSize, pteSize, pudSize*42 + pudSize - pteSize, MapOpts{AccessType: usermem.Read, User: true}},\n+ })\n+}\n+\n+func TestSplit2MPage(t *testing.T) {\n+ pt := New(NewRuntimeAllocator())\n+\n+ // Map a huge page and knock out the middle.\n+ pt.Map(0x0000ff0000000000, pmdSize, MapOpts{AccessType: usermem.Read, User: true}, pmdSize*42)\n+ pt.Unmap(usermem.Addr(0x0000ff0000000000+pteSize), pmdSize-(2*pteSize))\n+\n+ checkMappings(t, pt, []mapping{\n+ {0x0000ff0000000000, pteSize, pmdSize * 42, MapOpts{AccessType: usermem.Read, User: true}},\n+ {0x0000ff0000000000 + pmdSize - pteSize, pteSize, pmdSize*42 + pmdSize - pteSize, MapOpts{AccessType: usermem.Read, User: true}},\n+ })\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/platform/ring0/pagetables/walker_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 pagetables\n+\n+// Visitor is a generic type.\n+type Visitor interface {\n+ // visit is called on each PTE.\n+ visit(start uintptr, pte *PTE, align uintptr)\n+\n+ // requiresAlloc indicates that new entries should be allocated within\n+ // the walked range.\n+ requiresAlloc() bool\n+\n+ // requiresSplit indicates that entries in the given range should be\n+ // split if they are huge or jumbo pages.\n+ requiresSplit() bool\n+}\n+\n+// Walker walks page tables.\n+type Walker struct {\n+ // pageTables are the tables to walk.\n+ pageTables *PageTables\n+\n+ // Visitor is the set of arguments.\n+ visitor Visitor\n+}\n+\n+// iterateRange iterates over all appropriate levels of page tables for the given range.\n+//\n+// If requiresAlloc is true, then Set _must_ be called on all given PTEs. The\n+// exception is sect pages. If a valid sect page (huge or jumbo) cannot be\n+// installed, then the walk will continue to individual entries.\n+//\n+// This algorithm will attempt to maximize the use of sect pages whenever\n+// possible. Whether a sect page is provided will be clear through the range\n+// provided in the callback.\n+//\n+// Note that if requiresAlloc is true, then no gaps will be present. However,\n+// if alloc is not set, then the iteration will likely be full of gaps.\n+//\n+// Note that this function should generally be avoided in favor of Map, Unmap,\n+// etc. when not necessary.\n+//\n+// Precondition: start must be page-aligned.\n+//\n+// Precondition: start must be less than end.\n+//\n+// Precondition: If requiresAlloc is true, then start and end should not span\n+// non-canonical ranges. If they do, a panic will result.\n+//\n+//go:nosplit\n+func (w *Walker) iterateRange(start, end uintptr) {\n+ if start%pteSize != 0 {\n+ panic(\"unaligned start\")\n+ }\n+ if end < start {\n+ panic(\"start > end\")\n+ }\n+ if start < lowerTop {\n+ if end <= lowerTop {\n+ w.iterateRangeCanonical(start, end)\n+ } else if end > lowerTop && end <= upperBottom {\n+ if w.visitor.requiresAlloc() {\n+ panic(\"alloc spans non-canonical range\")\n+ }\n+ w.iterateRangeCanonical(start, lowerTop)\n+ } else {\n+ if w.visitor.requiresAlloc() {\n+ panic(\"alloc spans non-canonical range\")\n+ }\n+ w.iterateRangeCanonical(start, lowerTop)\n+ w.iterateRangeCanonical(upperBottom, end)\n+ }\n+ } else if start < upperBottom {\n+ if end <= upperBottom {\n+ if w.visitor.requiresAlloc() {\n+ panic(\"alloc spans non-canonical range\")\n+ }\n+ } else {\n+ if w.visitor.requiresAlloc() {\n+ panic(\"alloc spans non-canonical range\")\n+ }\n+ w.iterateRangeCanonical(upperBottom, end)\n+ }\n+ } else {\n+ w.iterateRangeCanonical(start, end)\n+ }\n+}\n+\n+// next returns the next address quantized by the given size.\n+//\n+//go:nosplit\n+func next(start uintptr, size uintptr) uintptr {\n+ start &= ^(size - 1)\n+ start += size\n+ return start\n+}\n+\n+// iterateRangeCanonical walks a canonical range.\n+//\n+//go:nosplit\n+func (w *Walker) iterateRangeCanonical(start, end uintptr) {\n+ pgdEntryIndex := w.pageTables.root\n+ if start >= upperBottom {\n+ pgdEntryIndex = w.pageTables.archPageTables.root\n+ }\n+\n+ for pgdIndex := (uint16((start & pgdMask) >> pgdShift)); start < end && pgdIndex < entriesPerPage; pgdIndex++ {\n+ var (\n+ pgdEntry = &pgdEntryIndex[pgdIndex]\n+ pudEntries *PTEs\n+ )\n+ if !pgdEntry.Valid() {\n+ if !w.visitor.requiresAlloc() {\n+ // Skip over this entry.\n+ start = next(start, pgdSize)\n+ continue\n+ }\n+\n+ // Allocate a new pgd.\n+ pudEntries = w.pageTables.Allocator.NewPTEs()\n+ pgdEntry.setPageTable(w.pageTables, pudEntries)\n+ } else {\n+ pudEntries = w.pageTables.Allocator.LookupPTEs(pgdEntry.Address())\n+ }\n+\n+ // Map the next level.\n+ clearPUDEntries := uint16(0)\n+\n+ for pudIndex := uint16((start & pudMask) >> pudShift); start < end && pudIndex < entriesPerPage; pudIndex++ {\n+ var (\n+ pudEntry = &pudEntries[pudIndex]\n+ pmdEntries *PTEs\n+ )\n+ if !pudEntry.Valid() {\n+ if !w.visitor.requiresAlloc() {\n+ // Skip over this entry.\n+ clearPUDEntries++\n+ start = next(start, pudSize)\n+ continue\n+ }\n+\n+ // This level has 1-GB sect pages. Is this\n+ // entire region at least as large as a single\n+ // PUD entry? If so, we can skip allocating a\n+ // new page for the pmd.\n+ if start&(pudSize-1) == 0 && end-start >= pudSize {\n+ pudEntry.SetSect()\n+ w.visitor.visit(uintptr(start), pudEntry, pudSize-1)\n+ if pudEntry.Valid() {\n+ start = next(start, pudSize)\n+ continue\n+ }\n+ }\n+\n+ // Allocate a new pud.\n+ pmdEntries = w.pageTables.Allocator.NewPTEs()\n+ pudEntry.setPageTable(w.pageTables, pmdEntries)\n+\n+ } else if pudEntry.IsSect() {\n+ // Does this page need to be split?\n+ if w.visitor.requiresSplit() && (start&(pudSize-1) != 0 || end < next(start, pudSize)) {\n+ // Install the relevant entries.\n+ pmdEntries = w.pageTables.Allocator.NewPTEs()\n+ for index := uint16(0); index < entriesPerPage; index++ {\n+ pmdEntries[index].SetSect()\n+ pmdEntries[index].Set(\n+ pudEntry.Address()+(pmdSize*uintptr(index)),\n+ pudEntry.Opts())\n+ }\n+ pudEntry.setPageTable(w.pageTables, pmdEntries)\n+ } else {\n+ // A sect page to be checked directly.\n+ w.visitor.visit(uintptr(start), pudEntry, pudSize-1)\n+\n+ // Might have been cleared.\n+ if !pudEntry.Valid() {\n+ clearPUDEntries++\n+ }\n+\n+ // Note that the sect page was changed.\n+ start = next(start, pudSize)\n+ continue\n+ }\n+\n+ } else {\n+ pmdEntries = w.pageTables.Allocator.LookupPTEs(pudEntry.Address())\n+ }\n+\n+ // Map the next level, since this is valid.\n+ clearPMDEntries := uint16(0)\n+\n+ for pmdIndex := uint16((start & pmdMask) >> pmdShift); start < end && pmdIndex < entriesPerPage; pmdIndex++ {\n+ var (\n+ pmdEntry = &pmdEntries[pmdIndex]\n+ pteEntries *PTEs\n+ )\n+ if !pmdEntry.Valid() {\n+ if !w.visitor.requiresAlloc() {\n+ // Skip over this entry.\n+ clearPMDEntries++\n+ start = next(start, pmdSize)\n+ continue\n+ }\n+\n+ // This level has 2-MB huge pages. If this\n+ // region is contined in a single PMD entry?\n+ // As above, we can skip allocating a new page.\n+ if start&(pmdSize-1) == 0 && end-start >= pmdSize {\n+ pmdEntry.SetSect()\n+ w.visitor.visit(uintptr(start), pmdEntry, pmdSize-1)\n+ if pmdEntry.Valid() {\n+ start = next(start, pmdSize)\n+ continue\n+ }\n+ }\n+\n+ // Allocate a new pmd.\n+ pteEntries = w.pageTables.Allocator.NewPTEs()\n+ pmdEntry.setPageTable(w.pageTables, pteEntries)\n+\n+ } else if pmdEntry.IsSect() {\n+ // Does this page need to be split?\n+ if w.visitor.requiresSplit() && (start&(pmdSize-1) != 0 || end < next(start, pmdSize)) {\n+ // Install the relevant entries.\n+ pteEntries = w.pageTables.Allocator.NewPTEs()\n+ for index := uint16(0); index < entriesPerPage; index++ {\n+ pteEntries[index].Set(\n+ pmdEntry.Address()+(pteSize*uintptr(index)),\n+ pmdEntry.Opts())\n+ }\n+ pmdEntry.setPageTable(w.pageTables, pteEntries)\n+ } else {\n+ // A huge page to be checked directly.\n+ w.visitor.visit(uintptr(start), pmdEntry, pmdSize-1)\n+\n+ // Might have been cleared.\n+ if !pmdEntry.Valid() {\n+ clearPMDEntries++\n+ }\n+\n+ // Note that the huge page was changed.\n+ start = next(start, pmdSize)\n+ continue\n+ }\n+\n+ } else {\n+ pteEntries = w.pageTables.Allocator.LookupPTEs(pmdEntry.Address())\n+ }\n+\n+ // Map the next level, since this is valid.\n+ clearPTEEntries := uint16(0)\n+\n+ for pteIndex := uint16((start & pteMask) >> pteShift); start < end && pteIndex < entriesPerPage; pteIndex++ {\n+ var (\n+ pteEntry = &pteEntries[pteIndex]\n+ )\n+ if !pteEntry.Valid() && !w.visitor.requiresAlloc() {\n+ clearPTEEntries++\n+ start += pteSize\n+ continue\n+ }\n+\n+ // At this point, we are guaranteed that start%pteSize == 0.\n+ w.visitor.visit(uintptr(start), pteEntry, pteSize-1)\n+ if !pteEntry.Valid() {\n+ if w.visitor.requiresAlloc() {\n+ panic(\"PTE not set after iteration with requiresAlloc!\")\n+ }\n+ clearPTEEntries++\n+ }\n+\n+ // Note that the pte was changed.\n+ start += pteSize\n+ continue\n+ }\n+\n+ // Check if we no longer need this page.\n+ if clearPTEEntries == entriesPerPage {\n+ pmdEntry.Clear()\n+ w.pageTables.Allocator.FreePTEs(pteEntries)\n+ clearPMDEntries++\n+ }\n+ }\n+\n+ // Check if we no longer need this page.\n+ if clearPMDEntries == entriesPerPage {\n+ pudEntry.Clear()\n+ w.pageTables.Allocator.FreePTEs(pmdEntries)\n+ clearPUDEntries++\n+ }\n+ }\n+\n+ // Check if we no longer need this page.\n+ if clearPUDEntries == entriesPerPage {\n+ pgdEntry.Clear()\n+ w.pageTables.Allocator.FreePTEs(pudEntries)\n+ }\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | enable ring0/pagetables to support arm64
Signed-off-by: Bin Lu <[email protected]>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/gvisor/pull/891 from lubinszARM:pr_pagetable 2385de75a8662af3ab1ae289dd74dd0e5dcfaf66
PiperOrigin-RevId: 282013224 |
260,023 | 22.11.2019 12:53:49 | 28,800 | f27f38d13717a25721efb2b37fabadae5c34e374 | Add segment dequeue check while emptying segment queue. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/connect.go",
"new_path": "pkg/tcpip/transport/tcp/connect.go",
"diff": "@@ -1368,8 +1368,11 @@ func (e *endpoint) protocolMainLoop(handshake bool) *tcpip.Error {\n// unlocks e.mu. Now that no new segments can get enqueued to this\n// endpoint, try to re-match the segment to a different endpoint\n// as the current endpoint is closed.\n- for !e.segmentQueue.empty() {\n+ for {\ns := e.segmentQueue.dequeue()\n+ if s == nil {\n+ break\n+ }\ne.tryDeliverSegmentFromClosedEndpoint(s)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add segment dequeue check while emptying segment queue.
PiperOrigin-RevId: 282023891 |
259,854 | 22.11.2019 14:56:54 | 28,800 | 8eb68912e40bc87c932baeb13d151fd590d7d279 | Store SO_BINDTODEVICE state at bind.
This allows us to ensure that the correct port reservation is released.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/accept.go",
"new_path": "pkg/tcpip/transport/tcp/accept.go",
"diff": "@@ -243,7 +243,7 @@ func (l *listenContext) createConnectingEndpoint(s *segment, iss seqnum.Value, i\nn.initGSO()\n// Register new endpoint so that packets are routed to it.\n- if err := n.stack.RegisterTransportEndpoint(n.boundNICID, n.effectiveNetProtos, ProtocolNumber, n.ID, n, n.reusePort, n.bindToDevice); err != nil {\n+ if err := n.stack.RegisterTransportEndpoint(n.boundNICID, n.effectiveNetProtos, ProtocolNumber, n.ID, n, n.reusePort, n.boundBindToDevice); err != nil {\nn.Close()\nreturn nil, err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -340,6 +340,9 @@ type endpoint struct {\n// TCP should never broadcast but Linux nevertheless supports enabling/\n// disabling SO_BROADCAST, albeit as a NOOP.\nbroadcast bool\n+ // Values used to reserve a port or register a transport endpoint\n+ // (which ever happens first).\n+ boundBindToDevice tcpip.NICID\n// effectiveNetProtos contains the network protocols actually in use. In\n// most cases it will only contain \"netProto\", but in cases like IPv6\n@@ -730,12 +733,13 @@ func (e *endpoint) Close() {\n// in Listen() when trying to register.\nif e.state == StateListen && e.isPortReserved {\nif e.isRegistered {\n- e.stack.StartTransportEndpointCleanup(e.boundNICID, e.effectiveNetProtos, ProtocolNumber, e.ID, e, e.bindToDevice)\n+ e.stack.StartTransportEndpointCleanup(e.boundNICID, e.effectiveNetProtos, ProtocolNumber, e.ID, e, e.boundBindToDevice)\ne.isRegistered = false\n}\n- e.stack.ReleasePort(e.effectiveNetProtos, ProtocolNumber, e.ID.LocalAddress, e.ID.LocalPort, e.bindToDevice)\n+ e.stack.ReleasePort(e.effectiveNetProtos, ProtocolNumber, e.ID.LocalAddress, e.ID.LocalPort, e.boundBindToDevice)\ne.isPortReserved = false\n+ e.boundBindToDevice = 0\n}\n// Mark endpoint as closed.\n@@ -791,14 +795,15 @@ func (e *endpoint) cleanupLocked() {\ne.workerCleanup = false\nif e.isRegistered {\n- e.stack.StartTransportEndpointCleanup(e.boundNICID, e.effectiveNetProtos, ProtocolNumber, e.ID, e, e.bindToDevice)\n+ e.stack.StartTransportEndpointCleanup(e.boundNICID, e.effectiveNetProtos, ProtocolNumber, e.ID, e, e.boundBindToDevice)\ne.isRegistered = false\n}\nif e.isPortReserved {\n- e.stack.ReleasePort(e.effectiveNetProtos, ProtocolNumber, e.ID.LocalAddress, e.ID.LocalPort, e.bindToDevice)\n+ e.stack.ReleasePort(e.effectiveNetProtos, ProtocolNumber, e.ID.LocalAddress, e.ID.LocalPort, e.boundBindToDevice)\ne.isPortReserved = false\n}\n+ e.boundBindToDevice = 0\ne.route.Release()\ne.stack.CompleteTransportEndpointCleanup(e)\n@@ -1741,7 +1746,7 @@ func (e *endpoint) connect(addr tcpip.FullAddress, handshake bool, run bool) *tc\nif e.ID.LocalPort != 0 {\n// The endpoint is bound to a port, attempt to register it.\n- err := e.stack.RegisterTransportEndpoint(nicID, netProtos, ProtocolNumber, e.ID, e, e.reusePort, e.bindToDevice)\n+ err := e.stack.RegisterTransportEndpoint(nicID, netProtos, ProtocolNumber, e.ID, e, e.reusePort, e.boundBindToDevice)\nif err != nil {\nreturn err\n}\n@@ -1778,7 +1783,10 @@ func (e *endpoint) connect(addr tcpip.FullAddress, handshake bool, run bool) *tc\nid.LocalPort = p\nswitch e.stack.RegisterTransportEndpoint(nicID, netProtos, ProtocolNumber, id, e, e.reusePort, e.bindToDevice) {\ncase nil:\n+ // Port picking successful. Save the details of\n+ // the selected port.\ne.ID = id\n+ e.boundBindToDevice = e.bindToDevice\nreturn true, nil\ncase tcpip.ErrPortInUse:\nreturn false, nil\n@@ -1794,7 +1802,7 @@ func (e *endpoint) connect(addr tcpip.FullAddress, handshake bool, run bool) *tc\n// before Connect: in such a case we don't want to hold on to\n// reservations anymore.\nif e.isPortReserved {\n- e.stack.ReleasePort(e.effectiveNetProtos, ProtocolNumber, origID.LocalAddress, origID.LocalPort, e.bindToDevice)\n+ e.stack.ReleasePort(e.effectiveNetProtos, ProtocolNumber, origID.LocalAddress, origID.LocalPort, e.boundBindToDevice)\ne.isPortReserved = false\n}\n@@ -1950,7 +1958,7 @@ func (e *endpoint) listen(backlog int) *tcpip.Error {\n}\n// Register the endpoint.\n- if err := e.stack.RegisterTransportEndpoint(e.boundNICID, e.effectiveNetProtos, ProtocolNumber, e.ID, e, e.reusePort, e.bindToDevice); err != nil {\n+ if err := e.stack.RegisterTransportEndpoint(e.boundNICID, e.effectiveNetProtos, ProtocolNumber, e.ID, e, e.reusePort, e.boundBindToDevice); err != nil {\nreturn err\n}\n@@ -2031,6 +2039,7 @@ func (e *endpoint) Bind(addr tcpip.FullAddress) (err *tcpip.Error) {\nreturn err\n}\n+ e.boundBindToDevice = e.bindToDevice\ne.isPortReserved = true\ne.effectiveNetProtos = netProtos\ne.ID.LocalPort = port\n@@ -2044,8 +2053,9 @@ func (e *endpoint) Bind(addr tcpip.FullAddress) (err *tcpip.Error) {\ne.ID.LocalPort = 0\ne.ID.LocalAddress = \"\"\ne.boundNICID = 0\n+ e.boundBindToDevice = 0\n}\n- }(e.bindToDevice)\n+ }(e.boundBindToDevice)\n// If an address is specified, we must ensure that it's one of our\n// local addresses.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -104,6 +104,10 @@ type endpoint struct {\nbindToDevice tcpip.NICID\nbroadcast bool\n+ // Values used to reserve a port or register a transport endpoint.\n+ // (which ever happens first).\n+ boundBindToDevice tcpip.NICID\n+\n// sendTOS represents IPv4 TOS or IPv6 TrafficClass,\n// applied while sending packets. Defaults to 0 as on Linux.\nsendTOS uint8\n@@ -175,8 +179,9 @@ func (e *endpoint) Close() {\nswitch e.state {\ncase StateBound, StateConnected:\n- e.stack.UnregisterTransportEndpoint(e.RegisterNICID, e.effectiveNetProtos, ProtocolNumber, e.ID, e, e.bindToDevice)\n- e.stack.ReleasePort(e.effectiveNetProtos, ProtocolNumber, e.ID.LocalAddress, e.ID.LocalPort, e.bindToDevice)\n+ e.stack.UnregisterTransportEndpoint(e.RegisterNICID, e.effectiveNetProtos, ProtocolNumber, e.ID, e, e.boundBindToDevice)\n+ e.stack.ReleasePort(e.effectiveNetProtos, ProtocolNumber, e.ID.LocalAddress, e.ID.LocalPort, e.boundBindToDevice)\n+ e.boundBindToDevice = 0\n}\nfor _, mem := range e.multicastMemberships {\n@@ -870,7 +875,10 @@ func (e *endpoint) Disconnect() *tcpip.Error {\nif e.state != StateConnected {\nreturn nil\n}\n- id := stack.TransportEndpointID{}\n+ var (\n+ id stack.TransportEndpointID\n+ btd tcpip.NICID\n+ )\n// Exclude ephemerally bound endpoints.\nif e.BindNICID != 0 || e.ID.LocalAddress == \"\" {\nvar err *tcpip.Error\n@@ -878,7 +886,7 @@ func (e *endpoint) Disconnect() *tcpip.Error {\nLocalPort: e.ID.LocalPort,\nLocalAddress: e.ID.LocalAddress,\n}\n- id, err = e.registerWithStack(e.RegisterNICID, e.effectiveNetProtos, id)\n+ id, btd, err = e.registerWithStack(e.RegisterNICID, e.effectiveNetProtos, id)\nif err != nil {\nreturn err\n}\n@@ -886,13 +894,14 @@ func (e *endpoint) Disconnect() *tcpip.Error {\n} else {\nif e.ID.LocalPort != 0 {\n// Release the ephemeral port.\n- e.stack.ReleasePort(e.effectiveNetProtos, ProtocolNumber, e.ID.LocalAddress, e.ID.LocalPort, e.bindToDevice)\n+ e.stack.ReleasePort(e.effectiveNetProtos, ProtocolNumber, e.ID.LocalAddress, e.ID.LocalPort, e.boundBindToDevice)\n}\ne.state = StateInitial\n}\n- e.stack.UnregisterTransportEndpoint(e.RegisterNICID, e.effectiveNetProtos, ProtocolNumber, e.ID, e, e.bindToDevice)\n+ e.stack.UnregisterTransportEndpoint(e.RegisterNICID, e.effectiveNetProtos, ProtocolNumber, e.ID, e, e.boundBindToDevice)\ne.ID = id\n+ e.boundBindToDevice = btd\ne.route.Release()\ne.route = stack.Route{}\ne.dstPort = 0\n@@ -961,17 +970,18 @@ func (e *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\n}\n}\n- id, err = e.registerWithStack(nicID, netProtos, id)\n+ id, btd, err := e.registerWithStack(nicID, netProtos, id)\nif err != nil {\nreturn err\n}\n// Remove the old registration.\nif e.ID.LocalPort != 0 {\n- e.stack.UnregisterTransportEndpoint(e.RegisterNICID, e.effectiveNetProtos, ProtocolNumber, e.ID, e, e.bindToDevice)\n+ e.stack.UnregisterTransportEndpoint(e.RegisterNICID, e.effectiveNetProtos, ProtocolNumber, e.ID, e, e.boundBindToDevice)\n}\ne.ID = id\n+ e.boundBindToDevice = btd\ne.route = r.Clone()\ne.dstPort = addr.Port\ne.RegisterNICID = nicID\n@@ -1029,11 +1039,11 @@ func (*endpoint) Accept() (tcpip.Endpoint, *waiter.Queue, *tcpip.Error) {\nreturn nil, nil, tcpip.ErrNotSupported\n}\n-func (e *endpoint) registerWithStack(nicID tcpip.NICID, netProtos []tcpip.NetworkProtocolNumber, id stack.TransportEndpointID) (stack.TransportEndpointID, *tcpip.Error) {\n+func (e *endpoint) registerWithStack(nicID tcpip.NICID, netProtos []tcpip.NetworkProtocolNumber, id stack.TransportEndpointID) (stack.TransportEndpointID, tcpip.NICID, *tcpip.Error) {\nif e.ID.LocalPort == 0 {\nport, err := e.stack.ReservePort(netProtos, ProtocolNumber, id.LocalAddress, id.LocalPort, e.reusePort, e.bindToDevice)\nif err != nil {\n- return id, err\n+ return id, e.bindToDevice, err\n}\nid.LocalPort = port\n}\n@@ -1042,7 +1052,7 @@ func (e *endpoint) registerWithStack(nicID tcpip.NICID, netProtos []tcpip.Networ\nif err != nil {\ne.stack.ReleasePort(netProtos, ProtocolNumber, id.LocalAddress, id.LocalPort, e.bindToDevice)\n}\n- return id, err\n+ return id, e.bindToDevice, err\n}\nfunc (e *endpoint) bindLocked(addr tcpip.FullAddress) *tcpip.Error {\n@@ -1081,12 +1091,13 @@ func (e *endpoint) bindLocked(addr tcpip.FullAddress) *tcpip.Error {\nLocalPort: addr.Port,\nLocalAddress: addr.Addr,\n}\n- id, err = e.registerWithStack(nicID, netProtos, id)\n+ id, btd, err := e.registerWithStack(nicID, netProtos, id)\nif err != nil {\nreturn err\n}\ne.ID = id\n+ e.boundBindToDevice = btd\ne.RegisterNICID = nicID\ne.effectiveNetProtos = netProtos\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint_state.go",
"new_path": "pkg/tcpip/transport/udp/endpoint_state.go",
"diff": "@@ -109,7 +109,7 @@ func (e *endpoint) Resume(s *stack.Stack) {\n// pass it to the reservation machinery.\nid := e.ID\ne.ID.LocalPort = 0\n- e.ID, err = e.registerWithStack(e.RegisterNICID, e.effectiveNetProtos, id)\n+ e.ID, e.boundBindToDevice, err = e.registerWithStack(e.RegisterNICID, e.effectiveNetProtos, id)\nif err != nil {\npanic(err)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Store SO_BINDTODEVICE state at bind.
This allows us to ensure that the correct port reservation is released.
Fixes #1217
PiperOrigin-RevId: 282048155 |
259,891 | 25.11.2019 08:35:09 | 28,800 | 2b1b51f1d7dd96f14b0af3b2663c33bc7ab67f63 | Fix panic in sniffer.
Packets written via SOCK_RAW are guaranteed to have network headers, but not
transport headers. Check first whether there are enough bytes left in the packet
to contain a transport header before attempting to parse it. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/sniffer/sniffer.go",
"new_path": "pkg/tcpip/link/sniffer/sniffer.go",
"diff": "@@ -49,6 +49,13 @@ var LogPackets uint32 = 1\n// LogPacketsToFile must be accessed atomically.\nvar LogPacketsToFile uint32 = 1\n+var transportProtocolMinSizes map[tcpip.TransportProtocolNumber]int = map[tcpip.TransportProtocolNumber]int{\n+ header.ICMPv4ProtocolNumber: header.IPv4MinimumSize,\n+ header.ICMPv6ProtocolNumber: header.IPv6MinimumSize,\n+ header.UDPProtocolNumber: header.UDPMinimumSize,\n+ header.TCPProtocolNumber: header.TCPMinimumSize,\n+}\n+\ntype endpoint struct {\ndispatcher stack.NetworkDispatcher\nlower stack.LinkEndpoint\n@@ -333,6 +340,13 @@ func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, b buffer.Vie\nreturn\n}\n+ // We aren't guaranteed to have a transport header - it's possible for\n+ // writes via raw endpoints to contain only network headers.\n+ if minSize, ok := transportProtocolMinSizes[tcpip.TransportProtocolNumber(transProto)]; ok && len(b) < minSize {\n+ log.Infof(\"%s %v -> %v transport protocol: %d, but no transport header found (possible raw packet)\", prefix, src, dst, transProto)\n+ return\n+ }\n+\n// Figure out the transport layer info.\ntransName := \"unknown\"\nsrcPort := uint16(0)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix panic in sniffer.
Packets written via SOCK_RAW are guaranteed to have network headers, but not
transport headers. Check first whether there are enough bytes left in the packet
to contain a transport header before attempting to parse it.
PiperOrigin-RevId: 282363895 |
259,891 | 25.11.2019 09:26:30 | 28,800 | 1641338b14204ea941c547cf4c1a70665922ca05 | Set transport and network headers on outbound packets.
These are necessary for iptables to read and parse headers for packet filtering. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4.go",
"diff": "@@ -240,8 +240,11 @@ func (e *endpoint) addIPHeader(r *stack.Route, hdr *buffer.Prependable, payloadS\n// WritePacket writes a packet to the given destination address and protocol.\nfunc (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, params stack.NetworkHeaderParams, loop stack.PacketLooping, pkt tcpip.PacketBuffer) *tcpip.Error {\nip := e.addIPHeader(r, &pkt.Header, pkt.Data.Size(), params)\n+ pkt.NetworkHeader = buffer.View(ip)\nif loop&stack.PacketLoop != 0 {\n+ // The inbound path expects the network header to still be in\n+ // the PacketBuffer's Data field.\nviews := make([]buffer.View, 1, 1+len(pkt.Data.Views()))\nviews[0] = pkt.Header.View()\nviews = append(views, pkt.Data.Views()...)\n@@ -249,7 +252,6 @@ func (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, params stack.Netw\ne.HandlePacket(&loopedR, tcpip.PacketBuffer{\nData: buffer.NewVectorisedView(len(views[0])+pkt.Data.Size(), views),\n- NetworkHeader: buffer.View(ip),\n})\nloopedR.Release()\n@@ -277,7 +279,8 @@ func (e *endpoint) WritePackets(r *stack.Route, gso *stack.GSO, pkts []tcpip.Pac\n}\nfor i := range pkts {\n- e.addIPHeader(r, &pkts[i].Header, pkts[i].DataSize, params)\n+ ip := e.addIPHeader(r, &pkts[i].Header, pkts[i].DataSize, params)\n+ pkts[i].NetworkHeader = buffer.View(ip)\n}\nn, err := e.linkEP.WritePackets(r, gso, pkts, ProtocolNumber)\nr.Stats().IP.PacketsSent.IncrementBy(uint64(n))\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6.go",
"diff": "@@ -114,8 +114,11 @@ func (e *endpoint) addIPHeader(r *stack.Route, hdr *buffer.Prependable, payloadS\n// WritePacket writes a packet to the given destination address and protocol.\nfunc (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, params stack.NetworkHeaderParams, loop stack.PacketLooping, pkt tcpip.PacketBuffer) *tcpip.Error {\nip := e.addIPHeader(r, &pkt.Header, pkt.Data.Size(), params)\n+ pkt.NetworkHeader = buffer.View(ip)\nif loop&stack.PacketLoop != 0 {\n+ // The inbound path expects the network header to still be in\n+ // the PacketBuffer's Data field.\nviews := make([]buffer.View, 1, 1+len(pkt.Data.Views()))\nviews[0] = pkt.Header.View()\nviews = append(views, pkt.Data.Views()...)\n@@ -123,7 +126,6 @@ func (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, params stack.Netw\ne.HandlePacket(&loopedR, tcpip.PacketBuffer{\nData: buffer.NewVectorisedView(len(views[0])+pkt.Data.Size(), views),\n- NetworkHeader: buffer.View(ip),\n})\nloopedR.Release()\n@@ -148,7 +150,8 @@ func (e *endpoint) WritePackets(r *stack.Route, gso *stack.GSO, pkts []tcpip.Pac\nfor i := range pkts {\nhdr := &pkts[i].Header\nsize := pkts[i].DataSize\n- e.addIPHeader(r, hdr, size, params)\n+ ip := e.addIPHeader(r, hdr, size, params)\n+ pkts[i].NetworkHeader = buffer.View(ip)\n}\nn, err := e.linkEP.WritePackets(r, gso, pkts, ProtocolNumber)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/connect.go",
"new_path": "pkg/tcpip/transport/tcp/connect.go",
"diff": "@@ -647,6 +647,7 @@ func buildTCPHdr(r *stack.Route, id stack.TransportEndpointID, pkt *tcpip.Packet\noff := pkt.DataOffset\n// Initialize the header.\ntcp := header.TCP(hdr.Prepend(header.TCPMinimumSize + optLen))\n+ pkt.TransportHeader = buffer.View(tcp)\ntcp.Encode(&header.TCPFields{\nSrcPort: id.LocalPort,\nDstPort: id.RemotePort,\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -825,6 +825,7 @@ func sendUDP(r *stack.Route, data buffer.VectorisedView, localPort, remotePort u\nif err := r.WritePacket(nil /* gso */, stack.NetworkHeaderParams{Protocol: ProtocolNumber, TTL: ttl, TOS: tos}, tcpip.PacketBuffer{\nHeader: hdr,\nData: data,\n+ TransportHeader: buffer.View(udp),\n}); err != nil {\nr.Stats().UDP.PacketSendErrors.Increment()\nreturn err\n"
}
] | Go | Apache License 2.0 | google/gvisor | Set transport and network headers on outbound packets.
These are necessary for iptables to read and parse headers for packet filtering.
PiperOrigin-RevId: 282372811 |
259,992 | 25.11.2019 11:41:39 | 28,800 | 97d2c9a94e802bcb450e50816a913dfc18afc0e3 | Use mount hints to determine FileAccessType | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/fs.go",
"new_path": "runsc/boot/fs.go",
"diff": "@@ -465,6 +465,13 @@ func (m *mountHint) checkCompatible(mount specs.Mount) error {\nreturn nil\n}\n+func (m *mountHint) fileAccessType() FileAccessType {\n+ if m.share == container {\n+ return FileAccessExclusive\n+ }\n+ return FileAccessShared\n+}\n+\nfunc filterUnsupportedOptions(mount specs.Mount) []string {\nrv := make([]string, 0, len(mount.Options))\nfor _, o := range mount.Options {\n@@ -764,8 +771,7 @@ func (c *containerMounter) getMountNameAndOptions(conf *Config, m specs.Mount) (\ncase bind:\nfd := c.fds.remove()\nfsName = \"9p\"\n- // Non-root bind mounts are always shared.\n- opts = p9MountOptions(fd, FileAccessShared)\n+ opts = p9MountOptions(fd, c.getMountAccessType(m))\n// If configured, add overlay to all writable mounts.\nuseOverlay = conf.Overlay && !mountFlags(m.Options).ReadOnly\n@@ -778,6 +784,14 @@ func (c *containerMounter) getMountNameAndOptions(conf *Config, m specs.Mount) (\nreturn fsName, opts, useOverlay, nil\n}\n+func (c *containerMounter) getMountAccessType(mount specs.Mount) FileAccessType {\n+ if hint := c.hints.findMount(mount); hint != nil {\n+ return hint.fileAccessType()\n+ }\n+ // Non-root bind mounts are always shared if no hints were provided.\n+ return FileAccessShared\n+}\n+\n// mountSubmount mounts volumes inside the container's root. Because mounts may\n// be readonly, a lower ramfs overlay is added to create the mount point dir.\n// Another overlay is added with tmpfs on top if Config.Overlay is true.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/fs_test.go",
"new_path": "runsc/boot/fs_test.go",
"diff": "@@ -191,3 +191,61 @@ func TestPodMountHintsErrors(t *testing.T) {\n})\n}\n}\n+\n+func TestGetMountAccessType(t *testing.T) {\n+ const source = \"foo\"\n+ for _, tst := range []struct {\n+ name string\n+ annotations map[string]string\n+ want FileAccessType\n+ }{\n+ {\n+ name: \"container=exclusive\",\n+ annotations: map[string]string{\n+ path.Join(MountPrefix, \"mount1\", \"source\"): source,\n+ path.Join(MountPrefix, \"mount1\", \"type\"): \"bind\",\n+ path.Join(MountPrefix, \"mount1\", \"share\"): \"container\",\n+ },\n+ want: FileAccessExclusive,\n+ },\n+ {\n+ name: \"pod=shared\",\n+ annotations: map[string]string{\n+ path.Join(MountPrefix, \"mount1\", \"source\"): source,\n+ path.Join(MountPrefix, \"mount1\", \"type\"): \"bind\",\n+ path.Join(MountPrefix, \"mount1\", \"share\"): \"pod\",\n+ },\n+ want: FileAccessShared,\n+ },\n+ {\n+ name: \"shared=shared\",\n+ annotations: map[string]string{\n+ path.Join(MountPrefix, \"mount1\", \"source\"): source,\n+ path.Join(MountPrefix, \"mount1\", \"type\"): \"bind\",\n+ path.Join(MountPrefix, \"mount1\", \"share\"): \"shared\",\n+ },\n+ want: FileAccessShared,\n+ },\n+ {\n+ name: \"default=shared\",\n+ annotations: map[string]string{\n+ path.Join(MountPrefix, \"mount1\", \"source\"): source + \"mismatch\",\n+ path.Join(MountPrefix, \"mount1\", \"type\"): \"bind\",\n+ path.Join(MountPrefix, \"mount1\", \"share\"): \"container\",\n+ },\n+ want: FileAccessShared,\n+ },\n+ } {\n+ t.Run(tst.name, func(t *testing.T) {\n+ spec := &specs.Spec{Annotations: tst.annotations}\n+ podHints, err := newPodMountHints(spec)\n+ if err != nil {\n+ t.Fatalf(\"newPodMountHints failed: %v\", err)\n+ }\n+ mounter := containerMounter{hints: podHints}\n+ if got := mounter.getMountAccessType(specs.Mount{Source: source}); got != tst.want {\n+ t.Errorf(\"getMountAccessType(), want: %v, got: %v\", tst.want, got)\n+ }\n+ })\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use mount hints to determine FileAccessType
PiperOrigin-RevId: 282401165 |
259,858 | 25.11.2019 13:51:13 | 28,800 | d92dc065fd98b5875a0945ccc062f91fc4d39190 | Fix typo in go_branch.sh script.
With the ticks, the command `master` is actually be run and the output included
(which is nothing). This is confusing, as we actually mean to say "master" in
the description of the Go branch. | [
{
"change_type": "MODIFY",
"old_path": "tools/go_branch.sh",
"new_path": "tools/go_branch.sh",
"diff": "@@ -78,7 +78,7 @@ cat > README.md <<EOF\n# gVisor\nThis branch is a synthetic branch, containing only Go sources, that is\n-compatible with standard Go tools. See the `master` branch for authoritative\n+compatible with standard Go tools. See the master branch for authoritative\nsources and tests.\nEOF\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix typo in go_branch.sh script.
With the ticks, the command `master` is actually be run and the output included
(which is nothing). This is confusing, as we actually mean to say "master" in
the description of the Go branch.
PiperOrigin-RevId: 282426081 |
259,992 | 25.11.2019 17:10:10 | 28,800 | 67745b88e0ddcc44dcc7629be0334a7d970d6e09 | Handle any volume type, not only tmpfs | [
{
"change_type": "MODIFY",
"old_path": "pkg/v1/utils/volumes.go",
"new_path": "pkg/v1/utils/volumes.go",
"diff": "@@ -117,10 +117,6 @@ func UpdateVolumeAnnotations(bundle string, s *specs.Spec) error {\nif volumeFieldName(k) != \"type\" {\ncontinue\n}\n- if v != \"tmpfs\" {\n- // Only tmpfs is supported now.\n- continue\n- }\nvolume := volumeName(k)\nif uid != \"\" {\n// This is a sandbox\n@@ -143,8 +139,8 @@ func UpdateVolumeAnnotations(bundle string, s *specs.Spec) error {\n// more accurate matching.\nif yes, _ := isVolumePath(volume, s.Mounts[i].Source); yes {\n// gVisor requires the container mount type to match\n- // sandbox mount type for tmpfs.\n- s.Mounts[i].Type = \"tmpfs\"\n+ // sandbox mount type.\n+ s.Mounts[i].Type = v\nupdated = true\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/v1/utils/volumes_test.go",
"new_path": "pkg/v1/utils/volumes_test.go",
"diff": "@@ -103,7 +103,7 @@ func TestUpdateVolumeAnnotations(t *testing.T) {\nexpectUpdate: true,\n},\n{\n- desc: \"volume annotations for container\",\n+ desc: \"tmpfs: volume annotations for container\",\nspec: &specs.Spec{\nMounts: []specs.Mount{\n{\n@@ -150,6 +150,42 @@ func TestUpdateVolumeAnnotations(t *testing.T) {\n},\nexpectUpdate: true,\n},\n+ {\n+ desc: \"bind: volume annotations for container\",\n+ spec: &specs.Spec{\n+ Mounts: []specs.Mount{\n+ {\n+ Destination: \"/test\",\n+ Type: \"bind\",\n+ Source: testVolumePath,\n+ Options: []string{\"ro\"},\n+ },\n+ },\n+ Annotations: map[string]string{\n+ annotations.ContainerType: annotations.ContainerTypeContainer,\n+ \"gvisor.dev/spec/mount/\" + testVolumeName + \"/share\": \"container\",\n+ \"gvisor.dev/spec/mount/\" + testVolumeName + \"/type\": \"bind\",\n+ \"gvisor.dev/spec/mount/\" + testVolumeName + \"/options\": \"ro\",\n+ },\n+ },\n+ expected: &specs.Spec{\n+ Mounts: []specs.Mount{\n+ {\n+ Destination: \"/test\",\n+ Type: \"bind\",\n+ Source: testVolumePath,\n+ Options: []string{\"ro\"},\n+ },\n+ },\n+ Annotations: map[string]string{\n+ annotations.ContainerType: annotations.ContainerTypeContainer,\n+ \"gvisor.dev/spec/mount/\" + testVolumeName + \"/share\": \"container\",\n+ \"gvisor.dev/spec/mount/\" + testVolumeName + \"/type\": \"bind\",\n+ \"gvisor.dev/spec/mount/\" + testVolumeName + \"/options\": \"ro\",\n+ },\n+ },\n+ expectUpdate: true,\n+ },\n{\ndesc: \"should not return error without pod log directory\",\nspec: &specs.Spec{\n"
}
] | Go | Apache License 2.0 | google/gvisor | Handle any volume type, not only tmpfs (#42) |
259,860 | 26.11.2019 17:01:56 | 28,800 | 519ceabdf90129664fa1f70f49d0472a9106910f | Mark execveat as supported for linux64_arm64. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/linux64_arm64.go",
"new_path": "pkg/sentry/syscalls/linux/linux64_arm64.go",
"diff": "@@ -295,7 +295,7 @@ var ARM64 = &kernel.SyscallTable{\n278: syscalls.Supported(\"getrandom\", GetRandom),\n279: syscalls.Supported(\"memfd_create\", MemfdCreate),\n280: syscalls.CapError(\"bpf\", linux.CAP_SYS_ADMIN, \"\", nil),\n- 281: syscalls.ErrorWithEvent(\"execveat\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/265\"}), // TODO(b/118901836)\n+ 281: syscalls.Supported(\"execveat\", Execveat),\n282: syscalls.ErrorWithEvent(\"userfaultfd\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/266\"}), // TODO(b/118906345)\n283: syscalls.ErrorWithEvent(\"membarrier\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/267\"}), // TODO(gvisor.dev/issue/267)\n284: syscalls.PartiallySupported(\"mlock2\", Mlock2, \"Stub implementation. The sandbox lacks appropriate permissions.\", nil),\n"
}
] | Go | Apache License 2.0 | google/gvisor | Mark execveat as supported for linux64_arm64.
PiperOrigin-RevId: 282667122 |
259,881 | 27.11.2019 13:47:44 | 28,800 | 58afb4be695e6804925ba2be5f2d8c245f079cba | Add floating point exception tests | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/exceptions.cc",
"new_path": "test/syscalls/linux/exceptions.cc",
"diff": "namespace gvisor {\nnamespace testing {\n+// Default value for the x87 FPU control word. See Intel SDM Vol 1, Ch 8.1.5\n+// \"x87 FPU Control Word\".\n+constexpr uint16_t kX87ControlWordDefault = 0x37f;\n+\n+// Mask for the divide-by-zero exception.\n+constexpr uint16_t kX87ControlWordDiv0Mask = 1 << 2;\n+\n+// Default value for the SSE control register (MXCSR). See Intel SDM Vol 1, Ch\n+// 11.6.4 \"Initialization of SSE/SSE3 Extensions\".\n+constexpr uint32_t kMXCSRDefault = 0x1f80;\n+\n+// Mask for the divide-by-zero exception.\n+constexpr uint32_t kMXCSRDiv0Mask = 1 << 9;\n+\n+// Flag for a pending divide-by-zero exception.\n+constexpr uint32_t kMXCSRDiv0Flag = 1 << 2;\n+\nvoid inline Halt() { asm(\"hlt\\r\\n\"); }\nvoid inline SetAlignmentCheck() {\n@@ -107,6 +124,170 @@ TEST(ExceptionTest, DivideByZero) {\n::testing::KilledBySignal(SIGFPE), \"\");\n}\n+// By default, x87 exceptions are masked and simply return a default value.\n+TEST(ExceptionTest, X87DivideByZeroMasked) {\n+ int32_t quotient;\n+ int32_t value = 1;\n+ int32_t divisor = 0;\n+ asm(\"fildl %[value]\\r\\n\"\n+ \"fidivl %[divisor]\\r\\n\"\n+ \"fistpl %[quotient]\\r\\n\"\n+ : [ quotient ] \"=m\"(quotient)\n+ : [ value ] \"m\"(value), [ divisor ] \"m\"(divisor));\n+\n+ EXPECT_EQ(quotient, INT32_MIN);\n+}\n+\n+// When unmasked, division by zero raises SIGFPE.\n+TEST(ExceptionTest, X87DivideByZeroUnmasked) {\n+ // See above.\n+ struct sigaction sa = {};\n+ sa.sa_handler = SIG_DFL;\n+ auto const cleanup = ASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGFPE, sa));\n+\n+ EXPECT_EXIT(\n+ {\n+ // Clear the divide by zero exception mask.\n+ constexpr uint16_t kControlWord =\n+ kX87ControlWordDefault & ~kX87ControlWordDiv0Mask;\n+\n+ int32_t quotient;\n+ int32_t value = 1;\n+ int32_t divisor = 0;\n+ asm volatile(\n+ \"fldcw %[cw]\\r\\n\"\n+ \"fildl %[value]\\r\\n\"\n+ \"fidivl %[divisor]\\r\\n\"\n+ \"fistpl %[quotient]\\r\\n\"\n+ : [ quotient ] \"=m\"(quotient)\n+ : [ cw ] \"m\"(kControlWord), [ value ] \"m\"(value),\n+ [ divisor ] \"m\"(divisor));\n+ },\n+ ::testing::KilledBySignal(SIGFPE), \"\");\n+}\n+\n+// Pending exceptions in the x87 status register are not clobbered by syscalls.\n+TEST(ExceptionTest, X87StatusClobber) {\n+ // See above.\n+ struct sigaction sa = {};\n+ sa.sa_handler = SIG_DFL;\n+ auto const cleanup = ASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGFPE, sa));\n+\n+ EXPECT_EXIT(\n+ {\n+ // Clear the divide by zero exception mask.\n+ constexpr uint16_t kControlWord =\n+ kX87ControlWordDefault & ~kX87ControlWordDiv0Mask;\n+\n+ int32_t quotient;\n+ int32_t value = 1;\n+ int32_t divisor = 0;\n+ asm volatile(\n+ \"fildl %[value]\\r\\n\"\n+ \"fidivl %[divisor]\\r\\n\"\n+ // Exception is masked, so it does not occur here.\n+ \"fistpl %[quotient]\\r\\n\"\n+\n+ // SYS_getpid placed in rax by constraint.\n+ \"syscall\\r\\n\"\n+\n+ // Unmask exception. The syscall didn't clobber the pending\n+ // exception, so now it can be raised.\n+ //\n+ // N.B. \"a floating-point exception will be generated upon execution\n+ // of the *next* floating-point instruction\".\n+ \"fldcw %[cw]\\r\\n\"\n+ \"fwait\\r\\n\"\n+ : [ quotient ] \"=m\"(quotient)\n+ : [ value ] \"m\"(value), [ divisor ] \"m\"(divisor), \"a\"(SYS_getpid),\n+ [ cw ] \"m\"(kControlWord)\n+ : \"rcx\", \"r11\");\n+ },\n+ ::testing::KilledBySignal(SIGFPE), \"\");\n+}\n+\n+// By default, SSE exceptions are masked and simply return a default value.\n+TEST(ExceptionTest, SSEDivideByZeroMasked) {\n+ uint32_t status;\n+ int32_t quotient;\n+ int32_t value = 1;\n+ int32_t divisor = 0;\n+ asm(\"cvtsi2ssl %[value], %%xmm0\\r\\n\"\n+ \"cvtsi2ssl %[divisor], %%xmm1\\r\\n\"\n+ \"divss %%xmm1, %%xmm0\\r\\n\"\n+ \"cvtss2sil %%xmm0, %[quotient]\\r\\n\"\n+ : [ quotient ] \"=r\"(quotient), [ status ] \"=r\"(status)\n+ : [ value ] \"r\"(value), [ divisor ] \"r\"(divisor)\n+ : \"xmm0\", \"xmm1\");\n+\n+ EXPECT_EQ(quotient, INT32_MIN);\n+}\n+\n+// When unmasked, division by zero raises SIGFPE.\n+TEST(ExceptionTest, SSEDivideByZeroUnmasked) {\n+ // See above.\n+ struct sigaction sa = {};\n+ sa.sa_handler = SIG_DFL;\n+ auto const cleanup = ASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGFPE, sa));\n+\n+ EXPECT_EXIT(\n+ {\n+ // Clear the divide by zero exception mask.\n+ constexpr uint32_t kMXCSR = kMXCSRDefault & ~kMXCSRDiv0Mask;\n+\n+ int32_t quotient;\n+ int32_t value = 1;\n+ int32_t divisor = 0;\n+ asm volatile(\n+ \"ldmxcsr %[mxcsr]\\r\\n\"\n+ \"cvtsi2ssl %[value], %%xmm0\\r\\n\"\n+ \"cvtsi2ssl %[divisor], %%xmm1\\r\\n\"\n+ \"divss %%xmm1, %%xmm0\\r\\n\"\n+ \"cvtss2sil %%xmm0, %[quotient]\\r\\n\"\n+ : [ quotient ] \"=r\"(quotient)\n+ : [ mxcsr ] \"m\"(kMXCSR), [ value ] \"r\"(value),\n+ [ divisor ] \"r\"(divisor)\n+ : \"xmm0\", \"xmm1\");\n+ },\n+ ::testing::KilledBySignal(SIGFPE), \"\");\n+}\n+\n+// Pending exceptions in the SSE status register are not clobbered by syscalls.\n+TEST(ExceptionTest, SSEStatusClobber) {\n+ uint32_t mxcsr;\n+ int32_t quotient;\n+ int32_t value = 1;\n+ int32_t divisor = 0;\n+ asm(\"cvtsi2ssl %[value], %%xmm0\\r\\n\"\n+ \"cvtsi2ssl %[divisor], %%xmm1\\r\\n\"\n+ \"divss %%xmm1, %%xmm0\\r\\n\"\n+ // Exception is masked, so it does not occur here.\n+ \"cvtss2sil %%xmm0, %[quotient]\\r\\n\"\n+\n+ // SYS_getpid placed in rax by constraint.\n+ \"syscall\\r\\n\"\n+\n+ // Intel SDM Vol 1, Ch 10.2.3.1 \"SIMD Floating-Point Mask and Flag Bits\":\n+ // \"If LDMXCSR or FXRSTOR clears a mask bit and sets the corresponding\n+ // exception flag bit, a SIMD floating-point exception will not be\n+ // generated as a result of this change. The unmasked exception will be\n+ // generated only upon the execution of the next SSE/SSE2/SSE3 instruction\n+ // that detects the unmasked exception condition.\"\n+ //\n+ // Though ambiguous, empirical evidence indicates that this means that\n+ // exception flags set in the status register will never cause an\n+ // exception to be raised; only a new exception condition will do so.\n+ //\n+ // Thus here we just check for the flag itself rather than trying to raise\n+ // the exception.\n+ \"stmxcsr %[mxcsr]\\r\\n\"\n+ : [ quotient ] \"=r\"(quotient), [ mxcsr ] \"+m\"(mxcsr)\n+ : [ value ] \"r\"(value), [ divisor ] \"r\"(divisor), \"a\"(SYS_getpid)\n+ : \"xmm0\", \"xmm1\", \"rcx\", \"r11\");\n+\n+ EXPECT_TRUE(mxcsr & kMXCSRDiv0Flag);\n+}\n+\nTEST(ExceptionTest, IOAccessFault) {\n// See above.\nstruct sigaction sa = {};\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add floating point exception tests
PiperOrigin-RevId: 282828273 |
259,860 | 27.11.2019 16:19:35 | 28,800 | 684f757a228f88e5fabe6ebe6ed54f0db20fd63d | Add support for receiving TOS and TCLASS control messages in hostinet.
This involves allowing getsockopt/setsockopt for the corresponding socket
options, as well as allowing hostinet to process control messages received from
the actual recvmsg syscall. | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/socket.go",
"new_path": "pkg/abi/linux/socket.go",
"diff": "@@ -422,6 +422,15 @@ type ControlMessageRights []int32\n// ControlMessageRights.\nconst SizeOfControlMessageRight = 4\n+// SizeOfControlMessageInq is the size of a TCP_INQ control message.\n+const SizeOfControlMessageInq = 4\n+\n+// SizeOfControlMessageTOS is the size of an IP_TOS control message.\n+const SizeOfControlMessageTOS = 1\n+\n+// SizeOfControlMessageTClass is the size of an IPV6_TCLASS control message.\n+const SizeOfControlMessageTClass = 4\n+\n// SCM_MAX_FD is the maximum number of FDs accepted in a single sendmsg call.\n// From net/scm.h.\nconst SCM_MAX_FD = 253\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/control/control.go",
"new_path": "pkg/sentry/socket/control/control.go",
"diff": "@@ -320,11 +320,33 @@ func PackInq(t *kernel.Task, inq int32, buf []byte) []byte {\nbuf,\nlinux.SOL_TCP,\nlinux.TCP_INQ,\n- 4,\n+ t.Arch().Width(),\ninq,\n)\n}\n+// PackTOS packs an IP_TOS socket control message.\n+func PackTOS(t *kernel.Task, tos int8, buf []byte) []byte {\n+ return putCmsgStruct(\n+ buf,\n+ linux.SOL_IP,\n+ linux.IP_TOS,\n+ t.Arch().Width(),\n+ tos,\n+ )\n+}\n+\n+// PackTClass packs an IPV6_TCLASS socket control message.\n+func PackTClass(t *kernel.Task, tClass int32, buf []byte) []byte {\n+ return putCmsgStruct(\n+ buf,\n+ linux.SOL_IPV6,\n+ linux.IPV6_TCLASS,\n+ t.Arch().Width(),\n+ tClass,\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/hostinet/BUILD",
"new_path": "pkg/sentry/socket/hostinet/BUILD",
"diff": "@@ -34,5 +34,6 @@ go_library(\n\"//pkg/syserror\",\n\"//pkg/tcpip/stack\",\n\"//pkg/waiter\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/hostinet/socket.go",
"new_path": "pkg/sentry/socket/hostinet/socket.go",
"diff": "@@ -18,6 +18,7 @@ import (\n\"fmt\"\n\"syscall\"\n+ \"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/binary\"\n\"gvisor.dev/gvisor/pkg/fdnotifier\"\n@@ -41,6 +42,10 @@ const (\n// sizeofSockaddr is the size in bytes of the largest sockaddr type\n// supported by this package.\nsizeofSockaddr = syscall.SizeofSockaddrInet6 // sizeof(sockaddr_in6) > sizeof(sockaddr_in)\n+\n+ // maxControlLen is the maximum size of a control message buffer used in a\n+ // recvmsg syscall.\n+ maxControlLen = 1024\n)\n// socketOperations implements fs.FileOperations and socket.Socket for a socket\n@@ -281,26 +286,32 @@ func (s *socketOperations) GetSockOpt(t *kernel.Task, level int, name int, outPt\n// Whitelist options and constrain option length.\nvar optlen int\nswitch level {\n- case syscall.SOL_IPV6:\n+ case linux.SOL_IP:\nswitch name {\n- case syscall.IPV6_V6ONLY:\n+ case linux.IP_RECVTOS:\noptlen = sizeofInt32\n}\n- case syscall.SOL_SOCKET:\n+ case linux.SOL_IPV6:\nswitch name {\n- case syscall.SO_ERROR, syscall.SO_KEEPALIVE, syscall.SO_SNDBUF, syscall.SO_RCVBUF, syscall.SO_REUSEADDR:\n+ case linux.IPV6_RECVTCLASS, linux.IPV6_V6ONLY:\noptlen = sizeofInt32\n- case syscall.SO_LINGER:\n+ }\n+ case linux.SOL_SOCKET:\n+ switch name {\n+ case linux.SO_ERROR, linux.SO_KEEPALIVE, linux.SO_SNDBUF, linux.SO_RCVBUF, linux.SO_REUSEADDR:\n+ optlen = sizeofInt32\n+ case linux.SO_LINGER:\noptlen = syscall.SizeofLinger\n}\n- case syscall.SOL_TCP:\n+ case linux.SOL_TCP:\nswitch name {\n- case syscall.TCP_NODELAY:\n+ case linux.TCP_NODELAY:\noptlen = sizeofInt32\n- case syscall.TCP_INFO:\n+ case linux.TCP_INFO:\noptlen = int(linux.SizeOfTCPInfo)\n}\n}\n+\nif optlen == 0 {\nreturn nil, syserr.ErrProtocolNotAvailable // ENOPROTOOPT\n}\n@@ -320,19 +331,24 @@ func (s *socketOperations) SetSockOpt(t *kernel.Task, level int, name int, opt [\n// Whitelist options and constrain option length.\nvar optlen int\nswitch level {\n- case syscall.SOL_IPV6:\n+ case linux.SOL_IP:\nswitch name {\n- case syscall.IPV6_V6ONLY:\n+ case linux.IP_RECVTOS:\noptlen = sizeofInt32\n}\n- case syscall.SOL_SOCKET:\n+ case linux.SOL_IPV6:\nswitch name {\n- case syscall.SO_SNDBUF, syscall.SO_RCVBUF, syscall.SO_REUSEADDR:\n+ case linux.IPV6_RECVTCLASS, linux.IPV6_V6ONLY:\noptlen = sizeofInt32\n}\n- case syscall.SOL_TCP:\n+ case linux.SOL_SOCKET:\nswitch name {\n- case syscall.TCP_NODELAY:\n+ case linux.SO_SNDBUF, linux.SO_RCVBUF, linux.SO_REUSEADDR:\n+ optlen = sizeofInt32\n+ }\n+ case linux.SOL_TCP:\n+ switch name {\n+ case linux.TCP_NODELAY:\noptlen = sizeofInt32\n}\n}\n@@ -354,11 +370,11 @@ func (s *socketOperations) SetSockOpt(t *kernel.Task, level int, name int, opt [\n}\n// RecvMsg implements socket.Socket.RecvMsg.\n-func (s *socketOperations) RecvMsg(t *kernel.Task, dst usermem.IOSequence, flags int, haveDeadline bool, deadline ktime.Time, senderRequested bool, controlDataLen uint64) (int, int, linux.SockAddr, uint32, socket.ControlMessages, *syserr.Error) {\n+func (s *socketOperations) RecvMsg(t *kernel.Task, dst usermem.IOSequence, flags int, haveDeadline bool, deadline ktime.Time, senderRequested bool, controlLen uint64) (int, int, linux.SockAddr, uint32, socket.ControlMessages, *syserr.Error) {\n// Whitelist flags.\n//\n// FIXME(jamieliu): We can't support MSG_ERRQUEUE because it uses ancillary\n- // messages that netstack/tcpip/transport/unix doesn't understand. Kill the\n+ // messages that gvisor/pkg/tcpip/transport/unix doesn't understand. Kill the\n// Socket interface's dependence on netstack.\nif flags&^(syscall.MSG_DONTWAIT|syscall.MSG_PEEK|syscall.MSG_TRUNC) != 0 {\nreturn 0, 0, nil, 0, socket.ControlMessages{}, syserr.ErrInvalidArgument\n@@ -370,6 +386,7 @@ func (s *socketOperations) RecvMsg(t *kernel.Task, dst usermem.IOSequence, flags\nsenderAddrBuf = make([]byte, sizeofSockaddr)\n}\n+ var controlBuf []byte\nvar msgFlags int\nrecvmsgToBlocks := safemem.ReaderFunc(func(dsts safemem.BlockSeq) (uint64, error) {\n@@ -384,11 +401,6 @@ func (s *socketOperations) RecvMsg(t *kernel.Task, dst usermem.IOSequence, flags\n// We always do a non-blocking recv*().\nsysflags := flags | syscall.MSG_DONTWAIT\n- if dsts.NumBlocks() == 1 {\n- // Skip allocating []syscall.Iovec.\n- return recvfrom(s.fd, dsts.Head().ToSlice(), sysflags, &senderAddrBuf)\n- }\n-\niovs := iovecsFromBlockSeq(dsts)\nmsg := syscall.Msghdr{\nIov: &iovs[0],\n@@ -398,12 +410,18 @@ func (s *socketOperations) RecvMsg(t *kernel.Task, dst usermem.IOSequence, flags\nmsg.Name = &senderAddrBuf[0]\nmsg.Namelen = uint32(len(senderAddrBuf))\n}\n+ if controlLen > 0 {\n+ controlBuf = make([]byte, maxControlLen)\n+ msg.Control = &controlBuf[0]\n+ msg.Controllen = maxControlLen\n+ }\nn, err := recvmsg(s.fd, &msg, sysflags)\nif err != nil {\nreturn 0, err\n}\nsenderAddrBuf = senderAddrBuf[:msg.Namelen]\nmsgFlags = int(msg.Flags)\n+ controlLen = uint64(msg.Controllen)\nreturn n, nil\n})\n@@ -429,14 +447,38 @@ func (s *socketOperations) RecvMsg(t *kernel.Task, dst usermem.IOSequence, flags\nn, err = dst.CopyOutFrom(t, recvmsgToBlocks)\n}\n}\n-\n- // We don't allow control messages.\n- msgFlags &^= linux.MSG_CTRUNC\n+ if err != nil {\n+ return 0, 0, nil, 0, socket.ControlMessages{}, syserr.FromError(err)\n+ }\nif senderRequested {\nsenderAddr = socket.UnmarshalSockAddr(s.family, senderAddrBuf)\n}\n- return int(n), msgFlags, senderAddr, uint32(len(senderAddrBuf)), socket.ControlMessages{}, syserr.FromError(err)\n+\n+ unixControlMessages, err := unix.ParseSocketControlMessage(controlBuf[:controlLen])\n+ if err != nil {\n+ return 0, 0, nil, 0, socket.ControlMessages{}, syserr.FromError(err)\n+ }\n+\n+ controlMessages := socket.ControlMessages{}\n+ for _, unixCmsg := range unixControlMessages {\n+ switch unixCmsg.Header.Level {\n+ case syscall.SOL_IP:\n+ switch unixCmsg.Header.Type {\n+ case syscall.IP_TOS:\n+ controlMessages.IP.HasTOS = true\n+ binary.Unmarshal(unixCmsg.Data[:linux.SizeOfControlMessageTOS], usermem.ByteOrder, &controlMessages.IP.TOS)\n+ }\n+ case syscall.SOL_IPV6:\n+ switch unixCmsg.Header.Type {\n+ case syscall.IPV6_TCLASS:\n+ controlMessages.IP.HasTClass = true\n+ binary.Unmarshal(unixCmsg.Data[:linux.SizeOfControlMessageTClass], usermem.ByteOrder, &controlMessages.IP.TClass)\n+ }\n+ }\n+ }\n+\n+ return int(n), msgFlags, senderAddr, uint32(len(senderAddrBuf)), controlMessages, nil\n}\n// SendMsg implements socket.Socket.SendMsg.\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,14 @@ func recvSingleMsg(t *kernel.Task, s socket.Socket, msgPtr usermem.Addr, flags i\ncontrolData = control.PackInq(t, cms.IP.Inq, controlData)\n}\n+ if cms.IP.HasTOS {\n+ controlData = control.PackTOS(t, cms.IP.TOS, controlData)\n+ }\n+\n+ if cms.IP.HasTClass {\n+ controlData = control.PackTClass(t, cms.IP.TClass, 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/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -308,7 +308,7 @@ type ControlMessages struct {\n// HasTimestamp indicates whether Timestamp is valid/set.\nHasTimestamp bool\n- // Timestamp is the time (in ns) that the last packed used to create\n+ // Timestamp is the time (in ns) that the last packet used to create\n// the read data was received.\nTimestamp int64\n@@ -317,6 +317,18 @@ type ControlMessages struct {\n// Inq is the number of bytes ready to be received.\nInq int32\n+\n+ // HasTOS indicates whether Tos is valid/set.\n+ HasTOS bool\n+\n+ // TOS is the IPv4 type of service of the associated packet.\n+ TOS int8\n+\n+ // HasTClass indicates whether Tclass is valid/set.\n+ HasTClass bool\n+\n+ // Tclass is the IPv6 traffic class of the associated packet.\n+ TClass int32\n}\n// Endpoint is the interface implemented by transport protocols (e.g., tcp, udp)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/filter/config.go",
"new_path": "runsc/boot/filter/config.go",
"diff": "@@ -134,11 +134,6 @@ var allowedSyscalls = seccomp.SyscallRules{\nseccomp.AllowValue(syscall.SOL_SOCKET),\nseccomp.AllowValue(syscall.SO_SNDBUF),\n},\n- {\n- seccomp.AllowAny{},\n- seccomp.AllowValue(syscall.SOL_SOCKET),\n- seccomp.AllowValue(syscall.SO_REUSEADDR),\n- },\n},\nsyscall.SYS_GETTID: {},\nsyscall.SYS_GETTIMEOFDAY: {},\n@@ -315,6 +310,16 @@ func hostInetFilters() seccomp.SyscallRules {\nsyscall.SYS_GETPEERNAME: {},\nsyscall.SYS_GETSOCKNAME: {},\nsyscall.SYS_GETSOCKOPT: []seccomp.Rule{\n+ {\n+ seccomp.AllowAny{},\n+ seccomp.AllowValue(syscall.SOL_IP),\n+ seccomp.AllowValue(syscall.IP_RECVTOS),\n+ },\n+ {\n+ seccomp.AllowAny{},\n+ seccomp.AllowValue(syscall.SOL_IPV6),\n+ seccomp.AllowValue(syscall.IPV6_RECVTCLASS),\n+ },\n{\nseccomp.AllowAny{},\nseccomp.AllowValue(syscall.SOL_IPV6),\n@@ -418,6 +423,20 @@ func hostInetFilters() seccomp.SyscallRules {\nseccomp.AllowAny{},\nseccomp.AllowValue(4),\n},\n+ {\n+ seccomp.AllowAny{},\n+ seccomp.AllowValue(syscall.SOL_IP),\n+ seccomp.AllowValue(syscall.IP_RECVTOS),\n+ seccomp.AllowAny{},\n+ seccomp.AllowValue(4),\n+ },\n+ {\n+ seccomp.AllowAny{},\n+ seccomp.AllowValue(syscall.SOL_IPV6),\n+ seccomp.AllowValue(syscall.IPV6_RECVTCLASS),\n+ seccomp.AllowAny{},\n+ seccomp.AllowValue(4),\n+ },\n},\nsyscall.SYS_SHUTDOWN: []seccomp.Rule{\n{\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add support for receiving TOS and TCLASS control messages in hostinet.
This involves allowing getsockopt/setsockopt for the corresponding socket
options, as well as allowing hostinet to process control messages received from
the actual recvmsg syscall.
PiperOrigin-RevId: 282851425 |
260,004 | 28.11.2019 17:13:46 | 28,800 | 10bbcf97d25b824aa0565af114e3272d3e314d19 | Test handling segments on completed but not yet accepted TCP connections
This change does not introduce any new features, or modify existing ones.
This change tests handling TCP segments right away for connections that were
completed from a listening endpoint. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"new_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"diff": "@@ -792,6 +792,82 @@ func TestSendRstOnListenerRxSynAckV6(t *testing.T) {\nchecker.SeqNum(200)))\n}\n+// TestTCPAckBeforeAcceptV4 tests that once the 3-way handshake is complete,\n+// peers can send data and expect a response within a reasonable ammount of time\n+// without calling Accept on the listening endpoint first.\n+//\n+// This test uses IPv4.\n+func TestTCPAckBeforeAcceptV4(t *testing.T) {\n+ c := context.New(t, defaultMTU)\n+ defer c.Cleanup()\n+\n+ c.Create(-1)\n+\n+ if err := c.EP.Bind(tcpip.FullAddress{Port: context.StackPort}); err != nil {\n+ t.Fatal(\"Bind failed:\", err)\n+ }\n+\n+ if err := c.EP.Listen(10); err != nil {\n+ t.Fatal(\"Listen failed:\", err)\n+ }\n+\n+ irs, iss := executeHandshake(t, c, context.TestPort, false /* synCookiesInUse */)\n+\n+ // Send data before accepting the connection.\n+ c.SendPacket([]byte{1, 2, 3, 4}, &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: context.StackPort,\n+ Flags: header.TCPFlagAck,\n+ SeqNum: irs + 1,\n+ AckNum: iss + 1,\n+ })\n+\n+ // Receive ACK for the data we sent.\n+ checker.IPv4(t, c.GetPacket(), checker.TCP(\n+ checker.DstPort(context.TestPort),\n+ checker.TCPFlags(header.TCPFlagAck),\n+ checker.SeqNum(uint32(iss+1)),\n+ checker.AckNum(uint32(irs+5))))\n+}\n+\n+// TestTCPAckBeforeAcceptV6 tests that once the 3-way handshake is complete,\n+// peers can send data and expect a response within a reasonable ammount of time\n+// without calling Accept on the listening endpoint first.\n+//\n+// This test uses IPv6.\n+func TestTCPAckBeforeAcceptV6(t *testing.T) {\n+ c := context.New(t, defaultMTU)\n+ defer c.Cleanup()\n+\n+ c.CreateV6Endpoint(true)\n+\n+ if err := c.EP.Bind(tcpip.FullAddress{Port: context.StackPort}); err != nil {\n+ t.Fatal(\"Bind failed:\", err)\n+ }\n+\n+ if err := c.EP.Listen(10); err != nil {\n+ t.Fatal(\"Listen failed:\", err)\n+ }\n+\n+ irs, iss := executeV6Handshake(t, c, context.TestPort, false /* synCookiesInUse */)\n+\n+ // Send data before accepting the connection.\n+ c.SendV6Packet([]byte{1, 2, 3, 4}, &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: context.StackPort,\n+ Flags: header.TCPFlagAck,\n+ SeqNum: irs + 1,\n+ AckNum: iss + 1,\n+ })\n+\n+ // Receive ACK for the data we sent.\n+ checker.IPv6(t, c.GetV6Packet(), checker.TCP(\n+ checker.DstPort(context.TestPort),\n+ checker.TCPFlags(header.TCPFlagAck),\n+ checker.SeqNum(uint32(iss+1)),\n+ checker.AckNum(uint32(irs+5))))\n+}\n+\nfunc TestSendRstOnListenerRxAckV4(t *testing.T) {\nc := context.New(t, defaultMTU)\ndefer c.Cleanup()\n@@ -4303,7 +4379,7 @@ func executeHandshake(t *testing.T, c *context.Context, srcPort uint16, synCooki\nRcvWnd: 30000,\n})\n- // Receive the SYN-ACK reply.w\n+ // Receive the SYN-ACK reply.\nb := c.GetPacket()\ntcp := header.TCP(header.IPv4(b).Payload())\niss = seqnum.Value(tcp.SequenceNumber())\n@@ -4336,6 +4412,50 @@ func executeHandshake(t *testing.T, c *context.Context, srcPort uint16, synCooki\nreturn irs, iss\n}\n+func executeV6Handshake(t *testing.T, c *context.Context, srcPort uint16, synCookieInUse bool) (irs, iss seqnum.Value) {\n+ // Send a SYN request.\n+ irs = seqnum.Value(789)\n+ c.SendV6Packet(nil, &context.Headers{\n+ SrcPort: srcPort,\n+ DstPort: context.StackPort,\n+ Flags: header.TCPFlagSyn,\n+ SeqNum: irs,\n+ RcvWnd: 30000,\n+ })\n+\n+ // Receive the SYN-ACK reply.\n+ b := c.GetV6Packet()\n+ tcp := header.TCP(header.IPv6(b).Payload())\n+ iss = seqnum.Value(tcp.SequenceNumber())\n+ tcpCheckers := []checker.TransportChecker{\n+ checker.SrcPort(context.StackPort),\n+ checker.DstPort(srcPort),\n+ checker.TCPFlags(header.TCPFlagAck | header.TCPFlagSyn),\n+ checker.AckNum(uint32(irs) + 1),\n+ }\n+\n+ if synCookieInUse {\n+ // When cookies are in use window scaling is disabled.\n+ tcpCheckers = append(tcpCheckers, checker.TCPSynOptions(header.TCPSynOptions{\n+ WS: -1,\n+ MSS: c.MSSWithoutOptionsV6(),\n+ }))\n+ }\n+\n+ checker.IPv6(t, b, checker.TCP(tcpCheckers...))\n+\n+ // Send ACK.\n+ c.SendV6Packet(nil, &context.Headers{\n+ SrcPort: srcPort,\n+ DstPort: context.StackPort,\n+ Flags: header.TCPFlagAck,\n+ SeqNum: irs + 1,\n+ AckNum: iss + 1,\n+ RcvWnd: 30000,\n+ })\n+ return irs, iss\n+}\n+\n// TestListenBacklogFull tests that netstack does not complete handshakes if the\n// listen backlog for the endpoint is full.\nfunc TestListenBacklogFull(t *testing.T) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/testing/context/context.go",
"new_path": "pkg/tcpip/transport/tcp/testing/context/context.go",
"diff": "@@ -1089,3 +1089,9 @@ func (c *Context) SetGSOEnabled(enable bool) {\nfunc (c *Context) MSSWithoutOptions() uint16 {\nreturn uint16(c.linkEP.MTU() - header.IPv4MinimumSize - header.TCPMinimumSize)\n}\n+\n+// MSSWithoutOptionsV6 returns the value for the MSS used by the stack when no\n+// options are in use for IPv6 packets.\n+func (c *Context) MSSWithoutOptionsV6() uint16 {\n+ return uint16(c.linkEP.MTU() - header.IPv6MinimumSize - header.TCPMinimumSize)\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Test handling segments on completed but not yet accepted TCP connections
This change does not introduce any new features, or modify existing ones.
This change tests handling TCP segments right away for connections that were
completed from a listening endpoint.
PiperOrigin-RevId: 282986457 |
259,860 | 02.12.2019 08:38:45 | 28,800 | 9194aab2aaada137b377fdfcb812a7c015857d5d | Support sending IP_TOS and IPV6_TCLASS control messages with hostinet sockets.
There are two potential ways of sending a TOS byte with outgoing packets:
including a control message in sendmsg, or setting the IP_TOS/IPV6_TCLASS
socket options (for IPV4 and IPV6 respectively). This change lets hostinet
support the former. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/control/BUILD",
"new_path": "pkg/sentry/socket/control/BUILD",
"diff": "@@ -17,6 +17,7 @@ go_library(\n\"//pkg/sentry/fs\",\n\"//pkg/sentry/kernel\",\n\"//pkg/sentry/kernel/auth\",\n+ \"//pkg/sentry/socket\",\n\"//pkg/sentry/socket/unix/transport\",\n\"//pkg/sentry/usermem\",\n\"//pkg/syserror\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/control/control.go",
"new_path": "pkg/sentry/socket/control/control.go",
"diff": "@@ -23,6 +23,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/socket\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport\"\n\"gvisor.dev/gvisor/pkg/sentry/usermem\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n@@ -347,30 +348,63 @@ func PackTClass(t *kernel.Task, tClass int32, buf []byte) []byte {\n)\n}\n+func addSpaceForCmsg(cmsgDataLen int, buf []byte) []byte {\n+ newBuf := make([]byte, 0, len(buf)+linux.SizeOfControlMessageHeader+cmsgDataLen)\n+ return append(newBuf, buf...)\n+}\n+\n+// PackControlMessages converts the given ControlMessages struct into a buffer.\n+// We skip control messages specific to Unix domain sockets.\n+func PackControlMessages(t *kernel.Task, cmsgs socket.ControlMessages) []byte {\n+ var buf []byte\n+ // The use of t.Arch().Width() is analogous to Linux's use of sizeof(long) in\n+ // CMSG_ALIGN.\n+ width := t.Arch().Width()\n+\n+ if cmsgs.IP.HasTimestamp {\n+ buf = addSpaceForCmsg(int(width), buf)\n+ buf = PackTimestamp(t, cmsgs.IP.Timestamp, buf)\n+ }\n+\n+ if cmsgs.IP.HasInq {\n+ // In Linux, TCP_CM_INQ is added after SO_TIMESTAMP.\n+ buf = addSpaceForCmsg(AlignUp(linux.SizeOfControlMessageInq, width), buf)\n+ buf = PackInq(t, cmsgs.IP.Inq, buf)\n+ }\n+\n+ if cmsgs.IP.HasTOS {\n+ buf = addSpaceForCmsg(AlignUp(linux.SizeOfControlMessageTOS, width), buf)\n+ buf = PackTOS(t, cmsgs.IP.TOS, buf)\n+ }\n+\n+ if cmsgs.IP.HasTClass {\n+ buf = addSpaceForCmsg(AlignUp(linux.SizeOfControlMessageTClass, width), buf)\n+ buf = PackTClass(t, cmsgs.IP.TClass, buf)\n+ }\n+\n+ return buf\n+}\n+\n// Parse parses a raw socket control message into portable objects.\n-func Parse(t *kernel.Task, socketOrEndpoint interface{}, buf []byte) (transport.ControlMessages, error) {\n+func Parse(t *kernel.Task, socketOrEndpoint interface{}, buf []byte) (socket.ControlMessages, error) {\nvar (\n+ cmsgs socket.ControlMessages\nfds linux.ControlMessageRights\n- haveCreds bool\n- creds linux.ControlMessageCredentials\n)\nfor i := 0; i < len(buf); {\nif i+linux.SizeOfControlMessageHeader > len(buf) {\n- return transport.ControlMessages{}, syserror.EINVAL\n+ return cmsgs, syserror.EINVAL\n}\nvar h linux.ControlMessageHeader\nbinary.Unmarshal(buf[i:i+linux.SizeOfControlMessageHeader], usermem.ByteOrder, &h)\nif h.Length < uint64(linux.SizeOfControlMessageHeader) {\n- return transport.ControlMessages{}, syserror.EINVAL\n+ return socket.ControlMessages{}, syserror.EINVAL\n}\nif h.Length > uint64(len(buf)-i) {\n- return transport.ControlMessages{}, syserror.EINVAL\n- }\n- if h.Level != linux.SOL_SOCKET {\n- return transport.ControlMessages{}, syserror.EINVAL\n+ return socket.ControlMessages{}, syserror.EINVAL\n}\ni += linux.SizeOfControlMessageHeader\n@@ -380,13 +414,15 @@ func Parse(t *kernel.Task, socketOrEndpoint interface{}, buf []byte) (transport.\n// sizeof(long) in CMSG_ALIGN.\nwidth := t.Arch().Width()\n+ switch h.Level {\n+ case linux.SOL_SOCKET:\nswitch h.Type {\ncase linux.SCM_RIGHTS:\nrightsSize := AlignDown(length, linux.SizeOfControlMessageRight)\nnumRights := rightsSize / linux.SizeOfControlMessageRight\nif len(fds)+numRights > linux.SCM_MAX_FD {\n- return transport.ControlMessages{}, syserror.EINVAL\n+ return socket.ControlMessages{}, syserror.EINVAL\n}\nfor j := i; j < i+rightsSize; j += linux.SizeOfControlMessageRight {\n@@ -397,42 +433,60 @@ func Parse(t *kernel.Task, socketOrEndpoint interface{}, buf []byte) (transport.\ncase linux.SCM_CREDENTIALS:\nif length < linux.SizeOfControlMessageCredentials {\n- return transport.ControlMessages{}, syserror.EINVAL\n+ return socket.ControlMessages{}, syserror.EINVAL\n}\n+ var creds linux.ControlMessageCredentials\nbinary.Unmarshal(buf[i:i+linux.SizeOfControlMessageCredentials], usermem.ByteOrder, &creds)\n- haveCreds = true\n+ scmCreds, err := NewSCMCredentials(t, creds)\n+ if err != nil {\n+ return socket.ControlMessages{}, err\n+ }\n+ cmsgs.Unix.Credentials = scmCreds\ni += AlignUp(length, width)\ndefault:\n// Unknown message type.\n- return transport.ControlMessages{}, syserror.EINVAL\n+ return socket.ControlMessages{}, syserror.EINVAL\n}\n+ case linux.SOL_IP:\n+ switch h.Type {\n+ case linux.IP_TOS:\n+ cmsgs.IP.HasTOS = true\n+ binary.Unmarshal(buf[i:i+linux.SizeOfControlMessageTOS], usermem.ByteOrder, &cmsgs.IP.TOS)\n+ i += AlignUp(length, width)\n+\n+ default:\n+ return socket.ControlMessages{}, syserror.EINVAL\n}\n+ case linux.SOL_IPV6:\n+ switch h.Type {\n+ case linux.IPV6_TCLASS:\n+ cmsgs.IP.HasTClass = true\n+ binary.Unmarshal(buf[i:i+linux.SizeOfControlMessageTClass], usermem.ByteOrder, &cmsgs.IP.TClass)\n+ i += AlignUp(length, width)\n- var credentials SCMCredentials\n- if haveCreds {\n- var err error\n- if credentials, err = NewSCMCredentials(t, creds); err != nil {\n- return transport.ControlMessages{}, err\n+ default:\n+ return socket.ControlMessages{}, syserror.EINVAL\n}\n- } else {\n- credentials = makeCreds(t, socketOrEndpoint)\n+ default:\n+ return socket.ControlMessages{}, syserror.EINVAL\n}\n-\n- var rights SCMRights\n- if len(fds) > 0 {\n- var err error\n- if rights, err = NewSCMRights(t, fds); err != nil {\n- return transport.ControlMessages{}, err\n}\n+\n+ if cmsgs.Unix.Credentials == nil {\n+ cmsgs.Unix.Credentials = makeCreds(t, socketOrEndpoint)\n}\n- if credentials == nil && rights == nil {\n- return transport.ControlMessages{}, nil\n+ if len(fds) > 0 {\n+ rights, err := NewSCMRights(t, fds)\n+ if err != nil {\n+ return socket.ControlMessages{}, err\n+ }\n+ cmsgs.Unix.Rights = rights\n}\n- return transport.ControlMessages{Credentials: credentials, Rights: rights}, nil\n+ return cmsgs, nil\n}\nfunc makeCreds(t *kernel.Task, socketOrEndpoint interface{}) SCMCredentials {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/hostinet/BUILD",
"new_path": "pkg/sentry/socket/hostinet/BUILD",
"diff": "@@ -29,6 +29,7 @@ go_library(\n\"//pkg/sentry/kernel/time\",\n\"//pkg/sentry/safemem\",\n\"//pkg/sentry/socket\",\n+ \"//pkg/sentry/socket/control\",\n\"//pkg/sentry/usermem\",\n\"//pkg/syserr\",\n\"//pkg/syserror\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/hostinet/socket.go",
"new_path": "pkg/sentry/socket/hostinet/socket.go",
"diff": "@@ -30,6 +30,7 @@ import (\nktime \"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n\"gvisor.dev/gvisor/pkg/sentry/safemem\"\n\"gvisor.dev/gvisor/pkg/sentry/socket\"\n+ \"gvisor.dev/gvisor/pkg/sentry/socket/control\"\n\"gvisor.dev/gvisor/pkg/sentry/usermem\"\n\"gvisor.dev/gvisor/pkg/syserr\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n@@ -488,6 +489,7 @@ func (s *socketOperations) SendMsg(t *kernel.Task, src usermem.IOSequence, to []\nreturn 0, syserr.ErrInvalidArgument\n}\n+ controlBuf := control.PackControlMessages(t, controlMessages)\nsendmsgFromBlocks := safemem.WriterFunc(func(srcs safemem.BlockSeq) (uint64, error) {\n// Refuse to do anything if any part of src.Addrs was unusable.\nif uint64(src.NumBytes()) != srcs.NumBytes() {\n@@ -500,7 +502,7 @@ func (s *socketOperations) SendMsg(t *kernel.Task, src usermem.IOSequence, to []\n// We always do a non-blocking send*().\nsysflags := flags | syscall.MSG_DONTWAIT\n- if srcs.NumBlocks() == 1 {\n+ if srcs.NumBlocks() == 1 && len(controlBuf) == 0 {\n// Skip allocating []syscall.Iovec.\nsrc := srcs.Head()\nn, _, errno := syscall.Syscall6(syscall.SYS_SENDTO, uintptr(s.fd), src.Addr(), uintptr(src.Len()), uintptr(sysflags), uintptr(firstBytePtr(to)), uintptr(len(to)))\n@@ -519,6 +521,10 @@ func (s *socketOperations) SendMsg(t *kernel.Task, src usermem.IOSequence, to []\nmsg.Name = &to[0]\nmsg.Namelen = uint32(len(to))\n}\n+ if len(controlBuf) != 0 {\n+ msg.Control = &controlBuf[0]\n+ msg.Controllen = uint64(len(controlBuf))\n+ }\nreturn sendmsg(s.fd, &msg, sysflags)\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_socket.go",
"new_path": "pkg/sentry/syscalls/linux/sys_socket.go",
"diff": "@@ -1068,10 +1068,10 @@ func sendSingleMsg(t *kernel.Task, s socket.Socket, file *fs.File, msgPtr userme\n}\n// Call the syscall implementation.\n- n, e := s.SendMsg(t, src, to, int(flags), haveDeadline, deadline, socket.ControlMessages{Unix: controlMessages})\n+ n, e := s.SendMsg(t, src, to, int(flags), haveDeadline, deadline, controlMessages)\nerr = handleIOError(t, n != 0, e.ToError(), kernel.ERESTARTSYS, \"sendmsg\", file)\nif err != nil {\n- controlMessages.Release()\n+ controlMessages.Unix.Release()\n}\nreturn uintptr(n), err\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Support sending IP_TOS and IPV6_TCLASS control messages with hostinet sockets.
There are two potential ways of sending a TOS byte with outgoing packets:
including a control message in sendmsg, or setting the IP_TOS/IPV6_TCLASS
socket options (for IPV4 and IPV6 respectively). This change lets hostinet
support the former.
PiperOrigin-RevId: 283346737 |
259,853 | 02.12.2019 15:35:51 | 28,800 | b41277049c6c6c15581d8698fd9418ef9c2cec8a | test/syscal: Don't skip ClockGettime.CputimeId
We skipped it due to the issue in the golang scheduler
which has been fixed in go1.13. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/clock_gettime.cc",
"new_path": "test/syscalls/linux/clock_gettime.cc",
"diff": "@@ -56,11 +56,6 @@ void spin_ns(int64_t ns) {\n// Test that CLOCK_PROCESS_CPUTIME_ID is a superset of CLOCK_THREAD_CPUTIME_ID.\nTEST(ClockGettime, CputimeId) {\n- // TODO(b/128871825,golang.org/issue/10958): Test times out when there is a\n- // small number of core because one goroutine starves the others.\n- printf(\"CPUS: %d\\n\", std::thread::hardware_concurrency());\n- SKIP_IF(std::thread::hardware_concurrency() <= 2);\n-\nconstexpr int kNumThreads = 13; // arbitrary\nabsl::Duration spin_time = absl::Seconds(1);\n"
}
] | Go | Apache License 2.0 | google/gvisor | test/syscal: Don't skip ClockGettime.CputimeId
We skipped it due to the issue in the golang scheduler
which has been fixed in go1.13.
PiperOrigin-RevId: 283432226 |
259,884 | 02.12.2019 17:59:08 | 28,800 | 7ac46c50486eef252ecaa4de1a2fe2581f73f79c | Allow non-unique UIDs in bazel docker containers
Allow non-unique UIDs in the bazel docker container in order to avoid failures
using host UIDs that are already present in the image.
Issue | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -22,7 +22,7 @@ bazel-server-start: docker-build\n--privileged \\\ngvisor-bazel \\\nsh -c \"while :; do sleep 100; done\" && \\\n- docker exec --user 0:0 -i gvisor-bazel sh -c \"groupadd --gid $(GID) --non-unique gvisor && useradd --uid $(UID) --gid $(GID) -d $(HOME) gvisor\"\n+ docker exec --user 0:0 -i gvisor-bazel sh -c \"groupadd --gid $(GID) --non-unique gvisor && useradd --uid $(UID) --non-unique --gid $(GID) -d $(HOME) gvisor\"\nbazel-server:\ndocker exec gvisor-bazel true || \\\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow non-unique UIDs in bazel docker containers
Allow non-unique UIDs in the bazel docker container in order to avoid failures
using host UIDs that are already present in the image.
Issue #1267
PiperOrigin-RevId: 283456369 |
259,961 | 02.12.2019 21:13:34 | 18,000 | 1547f2451927d95f9da1a24479e57a47405dc1ed | Add documentation for configuring shim runtime options | [
{
"change_type": "MODIFY",
"old_path": "docs/README.md",
"new_path": "docs/README.md",
"diff": "@@ -5,3 +5,4 @@ Everything you need to know about gvisor-containerd-shim\n- [Untrusted Workload Quick Start (containerd >=1.1)](untrusted-workload-quickstart.md)\n- [Runtime Handler Quick Start (containerd >=1.2)](runtime-handler-quickstart.md)\n- [Runtime Handler Quick Start (shim v2) (containerd >=1.2)](runtime-handler-shim-v2-quickstart.md)\n+- [Configure containerd-shim-runsc-v1 (shim v2) (containerd >= 1.3)](configure-containerd-shim-runsc-v1.md)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "docs/configure-containerd-shim-runsc-v1.md",
"diff": "+# Configure containerd-shim-runsc-v1 (Shim V2)\n+\n+This document describes how to configure runtime options for `containerd-shim-runsc-v1`.\n+This is follows on to the instructions of [Runtime Handler Quick Start (shim v2) (containerd >=1.2)](runtime-handler-shim-v2-quickstart.md) and requires containerd 1.3 or later.\n+\n+## Configuration\n+\n+`containerd-shim-runsc-v1` supports a few different configuration options based on the version of containerd that is used. For versions >= 1.3, it supports a configurable config path in the containerd runtime configuration.\n+\n+1. Update `/etc/containerd/config.toml` to point to a configuration file for `containerd-shim-runsc-v1`.\n+\n+```shell\n+{ # Step 1: Update runtime options for runsc in containerd config.toml\n+cat <<EOF | sudo tee /etc/containerd/config.toml\n+disabled_plugins = [\"restart\"]\n+[plugins.linux]\n+ shim_debug = true\n+[plugins.cri.containerd.runtimes.runsc]\n+ runtime_type = \"io.containerd.runsc.v1\"\n+[plugins.cri.containerd.runtimes.runsc.options]\n+ TypeUrl = \"io.containerd.runsc.v1.options\"\n+ ConfigPath = \"/etc/containerd/runsc.toml\"\n+EOF\n+}\n+```\n+\n+2. Configure `/etc/containerd/runsc.toml` with the desired options. The set of options that can be configured can be found in [options.go](../pkg/v2/options/options.go). This example shows how to configure `containerd-shim-runsc-v1` to use gvisor with the kvm platform.\n+\n+```shell\n+{ # Step 2: Create containerd-shim-runsc-v1 runtime options config\n+cat <<EOF | sudo tee /etc/containerd/runsc.toml\n+[runsc_config]\n+platform = \"kvm\"\n+EOF\n+}\n+```\n+\n+3. Restart `containerd`\n+\n+```shell\n+sudo systemctl restart containerd\n+```\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add documentation for configuring shim runtime options (#43) |
259,974 | 18.11.2019 09:07:00 | 0 | 61f2274cb6f05579e4abe1e794182c04a622b58f | Enable runsc compatLog support on arm64. | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/BUILD",
"new_path": "runsc/boot/BUILD",
"diff": "@@ -7,6 +7,7 @@ go_library(\nsrcs = [\n\"compat.go\",\n\"compat_amd64.go\",\n+ \"compat_arm64.go\",\n\"config.go\",\n\"controller.go\",\n\"debug.go\",\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/compat.go",
"new_path": "runsc/boot/compat.go",
"diff": "@@ -21,10 +21,8 @@ import (\n\"syscall\"\n\"github.com/golang/protobuf/proto\"\n- \"gvisor.dev/gvisor/pkg/abi\"\n\"gvisor.dev/gvisor/pkg/eventchannel\"\n\"gvisor.dev/gvisor/pkg/log\"\n- \"gvisor.dev/gvisor/pkg/sentry/arch\"\nrpb \"gvisor.dev/gvisor/pkg/sentry/arch/registers_go_proto\"\nucspb \"gvisor.dev/gvisor/pkg/sentry/kernel/uncaught_signal_go_proto\"\n\"gvisor.dev/gvisor/pkg/sentry/strace\"\n@@ -53,9 +51,9 @@ type compatEmitter struct {\n}\nfunc newCompatEmitter(logFD int) (*compatEmitter, error) {\n- nameMap, ok := strace.Lookup(abi.Linux, arch.AMD64)\n+ nameMap, ok := getSyscallNameMap()\nif !ok {\n- return nil, fmt.Errorf(\"amd64 Linux syscall table not found\")\n+ return nil, fmt.Errorf(\"Linux syscall table not found\")\n}\nc := &compatEmitter{\n@@ -86,16 +84,16 @@ func (c *compatEmitter) Emit(msg proto.Message) (bool, error) {\n}\nfunc (c *compatEmitter) emitUnimplementedSyscall(us *spb.UnimplementedSyscall) {\n- regs := us.Registers.GetArch().(*rpb.Registers_Amd64).Amd64\n+ regs := us.Registers\nc.mu.Lock()\ndefer c.mu.Unlock()\n- sysnr := regs.OrigRax\n+ sysnr := syscallNum(regs)\ntr := c.trackers[sysnr]\nif tr == nil {\nswitch sysnr {\n- case syscall.SYS_PRCTL, syscall.SYS_ARCH_PRCTL:\n+ case syscall.SYS_PRCTL:\n// args: cmd, ...\ntr = newArgsTracker(0)\n@@ -112,10 +110,11 @@ func (c *compatEmitter) emitUnimplementedSyscall(us *spb.UnimplementedSyscall) {\ntr = newArgsTracker(2)\ndefault:\n- tr = &onceTracker{}\n+ tr = newArchArgsTracker(sysnr)\n}\nc.trackers[sysnr] = tr\n}\n+\nif tr.shouldReport(regs) {\nc.sink.Infof(\"Unsupported syscall: %s, regs: %+v\", c.nameMap.Name(uintptr(sysnr)), regs)\ntr.onReported(regs)\n@@ -139,10 +138,10 @@ func (c *compatEmitter) Close() error {\n// the syscall and arguments.\ntype syscallTracker interface {\n// shouldReport returns true is the syscall should be reported.\n- shouldReport(regs *rpb.AMD64Registers) bool\n+ shouldReport(regs *rpb.Registers) bool\n// onReported marks the syscall as reported.\n- onReported(regs *rpb.AMD64Registers)\n+ onReported(regs *rpb.Registers)\n}\n// onceTracker reports only a single time, used for most syscalls.\n@@ -150,10 +149,45 @@ type onceTracker struct {\nreported bool\n}\n-func (o *onceTracker) shouldReport(_ *rpb.AMD64Registers) bool {\n+func (o *onceTracker) shouldReport(_ *rpb.Registers) bool {\nreturn !o.reported\n}\n-func (o *onceTracker) onReported(_ *rpb.AMD64Registers) {\n+func (o *onceTracker) onReported(_ *rpb.Registers) {\no.reported = true\n}\n+\n+// argsTracker reports only once for each different combination of arguments.\n+// It's used for generic syscalls like ioctl to report once per 'cmd'.\n+type argsTracker struct {\n+ // argsIdx is the syscall arguments to use as unique ID.\n+ argsIdx []int\n+ reported map[string]struct{}\n+ count int\n+}\n+\n+func newArgsTracker(argIdx ...int) *argsTracker {\n+ return &argsTracker{argsIdx: argIdx, reported: make(map[string]struct{})}\n+}\n+\n+// key returns the command based on the syscall argument index.\n+func (a *argsTracker) key(regs *rpb.Registers) string {\n+ var rv string\n+ for _, idx := range a.argsIdx {\n+ rv += fmt.Sprintf(\"%d|\", argVal(idx, regs))\n+ }\n+ return rv\n+}\n+\n+func (a *argsTracker) shouldReport(regs *rpb.Registers) bool {\n+ if a.count >= reportLimit {\n+ return false\n+ }\n+ _, ok := a.reported[a.key(regs)]\n+ return !ok\n+}\n+\n+func (a *argsTracker) onReported(regs *rpb.Registers) {\n+ a.count++\n+ a.reported[a.key(regs)] = struct{}{}\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/compat_amd64.go",
"new_path": "runsc/boot/compat_amd64.go",
"diff": "@@ -16,62 +16,83 @@ package boot\nimport (\n\"fmt\"\n+ \"syscall\"\n+ \"gvisor.dev/gvisor/pkg/abi\"\n+ \"gvisor.dev/gvisor/pkg/sentry/arch\"\nrpb \"gvisor.dev/gvisor/pkg/sentry/arch/registers_go_proto\"\n+ \"gvisor.dev/gvisor/pkg/sentry/strace\"\n)\n// reportLimit is the max number of events that should be reported per tracker.\nconst reportLimit = 100\n-// argsTracker reports only once for each different combination of arguments.\n-// It's used for generic syscalls like ioctl to report once per 'cmd'.\n-type argsTracker struct {\n- // argsIdx is the syscall arguments to use as unique ID.\n- argsIdx []int\n- reported map[string]struct{}\n- count int\n+// newRegs create a empty Registers instance.\n+func newRegs() *rpb.Registers {\n+ return &rpb.Registers{\n+ Arch: &rpb.Registers_Amd64{\n+ Amd64: &rpb.AMD64Registers{},\n+ },\n}\n-\n-func newArgsTracker(argIdx ...int) *argsTracker {\n- return &argsTracker{argsIdx: argIdx, reported: make(map[string]struct{})}\n}\n-// cmd returns the command based on the syscall argument index.\n-func (a *argsTracker) key(regs *rpb.AMD64Registers) string {\n- var rv string\n- for _, idx := range a.argsIdx {\n- rv += fmt.Sprintf(\"%d|\", argVal(idx, regs))\n+func argVal(argIdx int, regs *rpb.Registers) uint32 {\n+ amd64Regs := regs.GetArch().(*rpb.Registers_Amd64).Amd64\n+\n+ switch argIdx {\n+ case 0:\n+ return uint32(amd64Regs.Rdi)\n+ case 1:\n+ return uint32(amd64Regs.Rsi)\n+ case 2:\n+ return uint32(amd64Regs.Rdx)\n+ case 3:\n+ return uint32(amd64Regs.R10)\n+ case 4:\n+ return uint32(amd64Regs.R8)\n+ case 5:\n+ return uint32(amd64Regs.R9)\n}\n- return rv\n+ panic(fmt.Sprintf(\"invalid syscall argument index %d\", argIdx))\n}\n-func argVal(argIdx int, regs *rpb.AMD64Registers) uint32 {\n+func setArgVal(argIdx int, argVal uint64, regs *rpb.Registers) {\n+ amd64Regs := regs.GetArch().(*rpb.Registers_Amd64).Amd64\n+\nswitch argIdx {\ncase 0:\n- return uint32(regs.Rdi)\n+ amd64Regs.Rdi = argVal\ncase 1:\n- return uint32(regs.Rsi)\n+ amd64Regs.Rsi = argVal\ncase 2:\n- return uint32(regs.Rdx)\n+ amd64Regs.Rdx = argVal\ncase 3:\n- return uint32(regs.R10)\n+ amd64Regs.R10 = argVal\ncase 4:\n- return uint32(regs.R8)\n+ amd64Regs.R8 = argVal\ncase 5:\n- return uint32(regs.R9)\n- }\n+ amd64Regs.R9 = argVal\n+ default:\npanic(fmt.Sprintf(\"invalid syscall argument index %d\", argIdx))\n}\n+}\n-func (a *argsTracker) shouldReport(regs *rpb.AMD64Registers) bool {\n- if a.count >= reportLimit {\n- return false\n+func getSyscallNameMap() (strace.SyscallMap, bool) {\n+ return strace.Lookup(abi.Linux, arch.AMD64)\n}\n- _, ok := a.reported[a.key(regs)]\n- return !ok\n+\n+func syscallNum(regs *rpb.Registers) uint64 {\n+ amd64Regs := regs.GetArch().(*rpb.Registers_Amd64).Amd64\n+ return amd64Regs.OrigRax\n}\n-func (a *argsTracker) onReported(regs *rpb.AMD64Registers) {\n- a.count++\n- a.reported[a.key(regs)] = struct{}{}\n+func newArchArgsTracker(sysnr uint64) syscallTracker {\n+ switch sysnr {\n+ case syscall.SYS_ARCH_PRCTL:\n+ // args: cmd, ...\n+ return newArgsTracker(0)\n+\n+ default:\n+ return &onceTracker{}\n+ }\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "runsc/boot/compat_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 boot\n+\n+import (\n+ \"fmt\"\n+ \"syscall\"\n+\n+ \"gvisor.dev/gvisor/pkg/abi\"\n+ \"gvisor.dev/gvisor/pkg/sentry/arch\"\n+ rpb \"gvisor.dev/gvisor/pkg/sentry/arch/registers_go_proto\"\n+ \"gvisor.dev/gvisor/pkg/sentry/strace\"\n+)\n+\n+// reportLimit is the max number of events that should be reported per tracker.\n+const reportLimit = 100\n+\n+// newRegs create a empty Registers instance.\n+func newRegs() *rpb.Registers {\n+ return &rpb.Registers{\n+ Arch: &rpb.Registers_Arm64{\n+ Arm64: &rpb.ARM64Registers{},\n+ },\n+ }\n+}\n+\n+func argVal(argIdx int, regs *rpb.Registers) uint32 {\n+ arm64Regs := regs.GetArch().(*rpb.Registers_Arm64).Arm64\n+\n+ switch argIdx {\n+ case 0:\n+ return uint32(arm64Regs.R0)\n+ case 1:\n+ return uint32(arm64Regs.R1)\n+ case 2:\n+ return uint32(arm64Regs.R2)\n+ case 3:\n+ return uint32(arm64Regs.R3)\n+ case 4:\n+ return uint32(arm64Regs.R4)\n+ case 5:\n+ return uint32(arm64Regs.R5)\n+ }\n+ panic(fmt.Sprintf(\"invalid syscall argument index %d\", argIdx))\n+}\n+\n+func setArgVal(argIdx int, argVal uint64, regs *rpb.Registers) {\n+ arm64Regs := regs.GetArch().(*rpb.Registers_Arm64).Arm64\n+\n+ switch argIdx {\n+ case 0:\n+ arm64Regs.R0 = argVal\n+ case 1:\n+ arm64Regs.R1 = argVal\n+ case 2:\n+ arm64Regs.R2 = argVal\n+ case 3:\n+ arm64Regs.R3 = argVal\n+ case 4:\n+ arm64Regs.R4 = argVal\n+ case 5:\n+ arm64Regs.R5 = argVal\n+ default:\n+ panic(fmt.Sprintf(\"invalid syscall argument index %d\", argIdx))\n+ }\n+}\n+\n+func getSyscallNameMap() (strace.SyscallMap, bool) {\n+ return strace.Lookup(abi.Linux, arch.ARM64)\n+}\n+\n+func syscallNum(regs *rpb.Registers) uint64 {\n+ arm64Regs := regs.GetArch().(*rpb.Registers_Arm64).Arm64\n+ return arm64Regs.R8\n+}\n+\n+func newArchArgsTracker(sysnr uint64) syscallTracker {\n+\n+ switch sysnr {\n+ // currently, no arch specific syscalls need to be handled here.\n+ default:\n+ return &onceTracker{}\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/compat_test.go",
"new_path": "runsc/boot/compat_test.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,8 +16,6 @@ package boot\nimport (\n\"testing\"\n-\n- rpb \"gvisor.dev/gvisor/pkg/sentry/arch/registers_go_proto\"\n)\nfunc TestOnceTracker(t *testing.T) {\n@@ -37,29 +35,32 @@ func TestArgsTracker(t *testing.T) {\nfor _, tc := range []struct {\nname string\nidx []int\n- rdi1 uint64\n- rdi2 uint64\n- rsi1 uint64\n- rsi2 uint64\n+ arg1_1 uint64\n+ arg1_2 uint64\n+ arg2_1 uint64\n+ arg2_2 uint64\nwant bool\n}{\n- {name: \"same rdi\", idx: []int{0}, rdi1: 123, rdi2: 123, want: false},\n- {name: \"same rsi\", idx: []int{1}, rsi1: 123, rsi2: 123, want: false},\n- {name: \"diff rdi\", idx: []int{0}, rdi1: 123, rdi2: 321, want: true},\n- {name: \"diff rsi\", idx: []int{1}, rsi1: 123, rsi2: 321, want: true},\n- {name: \"cmd is uint32\", idx: []int{0}, rsi1: 0xdead00000123, rsi2: 0xbeef00000123, want: false},\n- {name: \"same 2 args\", idx: []int{0, 1}, rsi1: 123, rdi1: 321, rsi2: 123, rdi2: 321, want: false},\n- {name: \"diff 2 args\", idx: []int{0, 1}, rsi1: 123, rdi1: 321, rsi2: 789, rdi2: 987, want: true},\n+ {name: \"same arg1\", idx: []int{0}, arg1_1: 123, arg1_2: 123, want: false},\n+ {name: \"same arg2\", idx: []int{1}, arg2_1: 123, arg2_2: 123, want: false},\n+ {name: \"diff arg1\", idx: []int{0}, arg1_1: 123, arg1_2: 321, want: true},\n+ {name: \"diff arg2\", idx: []int{1}, arg2_1: 123, arg2_2: 321, want: true},\n+ {name: \"cmd is uint32\", idx: []int{0}, arg2_1: 0xdead00000123, arg2_2: 0xbeef00000123, want: false},\n+ {name: \"same 2 args\", idx: []int{0, 1}, arg2_1: 123, arg1_1: 321, arg2_2: 123, arg1_2: 321, want: false},\n+ {name: \"diff 2 args\", idx: []int{0, 1}, arg2_1: 123, arg1_1: 321, arg2_2: 789, arg1_2: 987, want: true},\n} {\nt.Run(tc.name, func(t *testing.T) {\nc := newArgsTracker(tc.idx...)\n- regs := &rpb.AMD64Registers{Rdi: tc.rdi1, Rsi: tc.rsi1}\n+ regs := newRegs()\n+ setArgVal(0, tc.arg1_1, regs)\n+ setArgVal(1, tc.arg2_1, regs)\nif !c.shouldReport(regs) {\nt.Error(\"first call to shouldReport, got: false, want: true\")\n}\nc.onReported(regs)\n- regs.Rdi, regs.Rsi = tc.rdi2, tc.rsi2\n+ setArgVal(0, tc.arg1_2, regs)\n+ setArgVal(1, tc.arg2_2, regs)\nif got := c.shouldReport(regs); tc.want != got {\nt.Errorf(\"second call to shouldReport, got: %t, want: %t\", got, tc.want)\n}\n@@ -70,7 +71,9 @@ func TestArgsTracker(t *testing.T) {\nfunc TestArgsTrackerLimit(t *testing.T) {\nc := newArgsTracker(0, 1)\nfor i := 0; i < reportLimit; i++ {\n- regs := &rpb.AMD64Registers{Rdi: 123, Rsi: uint64(i)}\n+ regs := newRegs()\n+ setArgVal(0, 123, regs)\n+ setArgVal(1, uint64(i), regs)\nif !c.shouldReport(regs) {\nt.Error(\"shouldReport before limit was reached, got: false, want: true\")\n}\n@@ -78,7 +81,9 @@ func TestArgsTrackerLimit(t *testing.T) {\n}\n// Should hit the count limit now.\n- regs := &rpb.AMD64Registers{Rdi: 123, Rsi: 123456}\n+ regs := newRegs()\n+ setArgVal(0, 123, regs)\n+ setArgVal(1, 123456, regs)\nif c.shouldReport(regs) {\nt.Error(\"shouldReport after limit was reached, got: true, want: false\")\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enable runsc compatLog support on arm64.
Signed-off-by: Haibo Xu <[email protected]>
Change-Id: I3fd5e552f5f03b5144ed52647f75af3b8253b1d6 |
259,974 | 20.11.2019 09:24:41 | 0 | 03760e5623f3ee736252fda7da033fd51144af1e | platform/ptrace: make some operations arch specific
Make the patchSignalInfo/cpuid faulting/initial thread seccomp rules
operations architecture dependent. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/subprocess_amd64.go",
"new_path": "pkg/sentry/platform/ptrace/subprocess_amd64.go",
"diff": "@@ -21,6 +21,8 @@ import (\n\"strings\"\n\"syscall\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/seccomp\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n)\n@@ -143,3 +145,43 @@ func (t *thread) adjustInitRegsRip() {\nfunc initChildProcessPPID(initregs *syscall.PtraceRegs, ppid int32) {\ninitregs.R15 = uint64(ppid)\n}\n+\n+// patchSignalInfo patches the signal info to account for hitting the seccomp\n+// filters from vsyscall emulation, specified below. We allow for SIGSYS as a\n+// synchronous trap, but patch the structure to appear like a SIGSEGV with the\n+// Rip as the faulting address.\n+//\n+// Note that this should only be called after verifying that the signalInfo has\n+// been generated by the kernel.\n+func patchSignalInfo(regs *syscall.PtraceRegs, signalInfo *arch.SignalInfo) {\n+ if linux.Signal(signalInfo.Signo) == linux.SIGSYS {\n+ signalInfo.Signo = int32(linux.SIGSEGV)\n+\n+ // Unwind the kernel emulation, if any has occurred. A SIGSYS is delivered\n+ // with the si_call_addr field pointing to the current RIP. This field\n+ // aligns with the si_addr field for a SIGSEGV, so we don't need to touch\n+ // anything there. We do need to unwind emulation however, so we set the\n+ // instruction pointer to the faulting value, and \"unpop\" the stack.\n+ regs.Rip = signalInfo.Addr()\n+ regs.Rsp -= 8\n+ }\n+}\n+\n+// enableCpuidFault enable cpuid-faulting; this may fail on older kernels or hardware,\n+// so we just disregard the result. Host CPUID will be enabled.\n+func enableCpuidFault() {\n+ syscall.RawSyscall6(syscall.SYS_ARCH_PRCTL, linux.ARCH_SET_CPUID, 0, 0, 0, 0, 0)\n+}\n+\n+// appendArchSeccompRules append architecture specific seccomp rules when creating BPF program.\n+// Ref attachedThread() for more detail.\n+func appendArchSeccompRules(rules []seccomp.RuleSet) []seccomp.RuleSet {\n+ return append(rules, seccomp.RuleSet{\n+ Rules: seccomp.SyscallRules{\n+ syscall.SYS_ARCH_PRCTL: []seccomp.Rule{\n+ {seccomp.AllowValue(linux.ARCH_SET_CPUID), seccomp.AllowValue(0)},\n+ },\n+ },\n+ Action: linux.SECCOMP_RET_ALLOW,\n+ })\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/subprocess_arm64.go",
"new_path": "pkg/sentry/platform/ptrace/subprocess_arm64.go",
"diff": "package ptrace\nimport (\n+ \"fmt\"\n+ \"strings\"\n\"syscall\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/seccomp\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n)\n@@ -37,7 +41,7 @@ const (\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+func (t *thread) resetSysemuRegs(regs *syscall.PtraceRegs) {\n}\n// createSyscallRegs sets up syscall registers.\n@@ -124,3 +128,34 @@ func (t *thread) adjustInitRegsRip() {\nfunc initChildProcessPPID(initregs *syscall.PtraceRegs, ppid int32) {\ninitregs.Regs[7] = uint64(ppid)\n}\n+\n+// patchSignalInfo patches the signal info to account for hitting the seccomp\n+// filters from vsyscall emulation, specified below. We allow for SIGSYS as a\n+// synchronous trap, but patch the structure to appear like a SIGSEGV with the\n+// Rip as the faulting address.\n+//\n+// Note that this should only be called after verifying that the signalInfo has\n+// been generated by the kernel.\n+func patchSignalInfo(regs *syscall.PtraceRegs, signalInfo *arch.SignalInfo) {\n+ if linux.Signal(signalInfo.Signo) == linux.SIGSYS {\n+ signalInfo.Signo = int32(linux.SIGSEGV)\n+\n+ // Unwind the kernel emulation, if any has occurred. A SIGSYS is delivered\n+ // with the si_call_addr field pointing to the current RIP. This field\n+ // aligns with the si_addr field for a SIGSEGV, so we don't need to touch\n+ // anything there. We do need to unwind emulation however, so we set the\n+ // instruction pointer to the faulting value, and \"unpop\" the stack.\n+ regs.Pc = signalInfo.Addr()\n+ regs.Sp -= 8\n+ }\n+}\n+\n+// Noop on arm64.\n+func enableCpuidFault() {\n+}\n+\n+// appendArchSeccompRules append architecture specific seccomp rules when creating BPF program.\n+// Ref attachedThread() for more detail.\n+func appendArchSeccompRules(rules []seccomp.RuleSet) []seccomp.RuleSet {\n+ return rules\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/subprocess_linux.go",
"new_path": "pkg/sentry/platform/ptrace/subprocess_linux.go",
"diff": "@@ -20,6 +20,7 @@ import (\n\"fmt\"\n\"syscall\"\n+ \"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/procid\"\n@@ -77,27 +78,6 @@ func probeSeccomp() bool {\n}\n}\n-// patchSignalInfo patches the signal info to account for hitting the seccomp\n-// filters from vsyscall emulation, specified below. We allow for SIGSYS as a\n-// synchronous trap, but patch the structure to appear like a SIGSEGV with the\n-// Rip as the faulting address.\n-//\n-// Note that this should only be called after verifying that the signalInfo has\n-// been generated by the kernel.\n-func patchSignalInfo(regs *syscall.PtraceRegs, signalInfo *arch.SignalInfo) {\n- if linux.Signal(signalInfo.Signo) == linux.SIGSYS {\n- signalInfo.Signo = int32(linux.SIGSEGV)\n-\n- // Unwind the kernel emulation, if any has occurred. A SIGSYS is delivered\n- // with the si_call_addr field pointing to the current RIP. This field\n- // aligns with the si_addr field for a SIGSEGV, so we don't need to touch\n- // anything there. We do need to unwind emulation however, so we set the\n- // instruction pointer to the faulting value, and \"unpop\" the stack.\n- regs.Rip = signalInfo.Addr()\n- regs.Rsp -= 8\n- }\n-}\n-\n// createStub creates a fresh stub processes.\n//\n// Precondition: the runtime OS thread must be locked.\n@@ -149,7 +129,7 @@ func attachedThread(flags uintptr, defaultAction linux.BPFAction) (*thread, erro\nRules: seccomp.SyscallRules{\nsyscall.SYS_GETTIMEOFDAY: {},\nsyscall.SYS_TIME: {},\n- 309: {}, // SYS_GETCPU.\n+ unix.SYS_GETCPU: {}, // SYS_GETCPU was not defined in package syscall on amd64.\n},\nAction: linux.SECCOMP_RET_TRAP,\nVsyscall: true,\n@@ -173,9 +153,6 @@ func attachedThread(flags uintptr, defaultAction linux.BPFAction) (*thread, erro\n// For the initial process creation.\nsyscall.SYS_WAIT4: {},\n- syscall.SYS_ARCH_PRCTL: []seccomp.Rule{\n- {seccomp.AllowValue(linux.ARCH_SET_CPUID), seccomp.AllowValue(0)},\n- },\nsyscall.SYS_EXIT: {},\n// For the stub prctl dance (all).\n@@ -196,6 +173,8 @@ func attachedThread(flags uintptr, defaultAction linux.BPFAction) (*thread, erro\n},\nAction: linux.SECCOMP_RET_ALLOW,\n})\n+\n+ rules = appendArchSeccompRules(rules)\n}\ninstrs, err := seccomp.BuildProgram(rules, defaultAction)\nif err != nil {\n@@ -267,9 +246,8 @@ func attachedThread(flags uintptr, defaultAction linux.BPFAction) (*thread, erro\nsyscall.RawSyscall(syscall.SYS_EXIT, uintptr(errno), 0, 0)\n}\n- // Enable cpuid-faulting; this may fail on older kernels or hardware,\n- // so we just disregard the result. Host CPUID will be enabled.\n- syscall.RawSyscall6(syscall.SYS_ARCH_PRCTL, linux.ARCH_SET_CPUID, 0, 0, 0, 0, 0)\n+ // Enable cpuid-faulting.\n+ enableCpuidFault()\n// Call the stub; should not return.\nstubCall(stubStart, ppid)\n"
}
] | Go | Apache License 2.0 | google/gvisor | platform/ptrace: make some operations arch specific
Make the patchSignalInfo/cpuid faulting/initial thread seccomp rules
operations architecture dependent.
Signed-off-by: Haibo Xu <[email protected]>
Change-Id: Iaf692dbe3700d2e01168ec2f1b4beeda9136fd62 |
259,860 | 03.12.2019 08:32:03 | 28,800 | 19b2d997ec702e559bdb5f5e60634a7c5d7d288e | Support IP_TOS and IPV6_TCLASS socket options for hostinet sockets.
There are two potential ways of sending a TOS byte with outgoing packets:
including a control message in sendmsg, or setting the IP_TOS/IPV6_TCLASS
socket options (for IPV4 and IPV6 respectively). This change lets hostinet
support the latter.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/hostinet/socket.go",
"new_path": "pkg/sentry/socket/hostinet/socket.go",
"diff": "@@ -289,12 +289,12 @@ func (s *socketOperations) GetSockOpt(t *kernel.Task, level int, name int, outPt\nswitch level {\ncase linux.SOL_IP:\nswitch name {\n- case linux.IP_RECVTOS:\n+ case linux.IP_TOS, linux.IP_RECVTOS:\noptlen = sizeofInt32\n}\ncase linux.SOL_IPV6:\nswitch name {\n- case linux.IPV6_RECVTCLASS, linux.IPV6_V6ONLY:\n+ case linux.IPV6_TCLASS, linux.IPV6_RECVTCLASS, linux.IPV6_V6ONLY:\noptlen = sizeofInt32\n}\ncase linux.SOL_SOCKET:\n@@ -334,12 +334,12 @@ func (s *socketOperations) SetSockOpt(t *kernel.Task, level int, name int, opt [\nswitch level {\ncase linux.SOL_IP:\nswitch name {\n- case linux.IP_RECVTOS:\n+ case linux.IP_TOS, linux.IP_RECVTOS:\noptlen = sizeofInt32\n}\ncase linux.SOL_IPV6:\nswitch name {\n- case linux.IPV6_RECVTCLASS, linux.IPV6_V6ONLY:\n+ case linux.IPV6_TCLASS, linux.IPV6_RECVTCLASS, linux.IPV6_V6ONLY:\noptlen = sizeofInt32\n}\ncase linux.SOL_SOCKET:\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/filter/config.go",
"new_path": "runsc/boot/filter/config.go",
"diff": "@@ -310,11 +310,21 @@ func hostInetFilters() seccomp.SyscallRules {\nsyscall.SYS_GETPEERNAME: {},\nsyscall.SYS_GETSOCKNAME: {},\nsyscall.SYS_GETSOCKOPT: []seccomp.Rule{\n+ {\n+ seccomp.AllowAny{},\n+ seccomp.AllowValue(syscall.SOL_IP),\n+ seccomp.AllowValue(syscall.IP_TOS),\n+ },\n{\nseccomp.AllowAny{},\nseccomp.AllowValue(syscall.SOL_IP),\nseccomp.AllowValue(syscall.IP_RECVTOS),\n},\n+ {\n+ seccomp.AllowAny{},\n+ seccomp.AllowValue(syscall.SOL_IPV6),\n+ seccomp.AllowValue(syscall.IPV6_TCLASS),\n+ },\n{\nseccomp.AllowAny{},\nseccomp.AllowValue(syscall.SOL_IPV6),\n@@ -423,6 +433,13 @@ func hostInetFilters() seccomp.SyscallRules {\nseccomp.AllowAny{},\nseccomp.AllowValue(4),\n},\n+ {\n+ seccomp.AllowAny{},\n+ seccomp.AllowValue(syscall.SOL_IP),\n+ seccomp.AllowValue(syscall.IP_TOS),\n+ seccomp.AllowAny{},\n+ seccomp.AllowValue(4),\n+ },\n{\nseccomp.AllowAny{},\nseccomp.AllowValue(syscall.SOL_IP),\n@@ -430,6 +447,13 @@ func hostInetFilters() seccomp.SyscallRules {\nseccomp.AllowAny{},\nseccomp.AllowValue(4),\n},\n+ {\n+ seccomp.AllowAny{},\n+ seccomp.AllowValue(syscall.SOL_IPV6),\n+ seccomp.AllowValue(syscall.IPV6_TCLASS),\n+ seccomp.AllowAny{},\n+ seccomp.AllowValue(4),\n+ },\n{\nseccomp.AllowAny{},\nseccomp.AllowValue(syscall.SOL_IPV6),\n"
}
] | Go | Apache License 2.0 | google/gvisor | Support IP_TOS and IPV6_TCLASS socket options for hostinet sockets.
There are two potential ways of sending a TOS byte with outgoing packets:
including a control message in sendmsg, or setting the IP_TOS/IPV6_TCLASS
socket options (for IPV4 and IPV6 respectively). This change lets hostinet
support the latter.
Fixes #1188
PiperOrigin-RevId: 283550925 |
259,975 | 03.12.2019 10:22:01 | 28,800 | 812189664cab0a17ae29095e4029e2f8762a6779 | Remove TODO for obsolete bug. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/rpcinet/syscall_rpc.proto",
"new_path": "pkg/sentry/socket/rpcinet/syscall_rpc.proto",
"diff": "@@ -3,7 +3,6 @@ syntax = \"proto3\";\n// package syscall_rpc is a set of networking related system calls that can be\n// forwarded to a socket gofer.\n//\n-// TODO(b/77963526): Document individual RPCs.\npackage syscall_rpc;\nmessage SendmsgRequest {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove TODO for obsolete bug.
PiperOrigin-RevId: 283571456 |
259,881 | 03.12.2019 12:45:43 | 28,800 | d7cc2480cb6e465ce01eb245e7edbad2c68c44d8 | Add RunfilesPath to test_util
A few tests have their own ad-hoc implementations. Add a single common one. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/exec.cc",
"new_path": "test/syscalls/linux/exec.cc",
"diff": "@@ -47,23 +47,14 @@ namespace testing {\nnamespace {\n-constexpr char kBasicWorkload[] = \"exec_basic_workload\";\n-constexpr char kExitScript[] = \"exit_script\";\n-constexpr char kStateWorkload[] = \"exec_state_workload\";\n-constexpr char kProcExeWorkload[] = \"exec_proc_exe_workload\";\n-constexpr char kAssertClosedWorkload[] = \"exec_assert_closed_workload\";\n-constexpr char kPriorityWorkload[] = \"priority_execve\";\n-\n-std::string WorkloadPath(absl::string_view binary) {\n- std::string full_path;\n- char* test_src = getenv(\"TEST_SRCDIR\");\n- if (test_src) {\n- full_path = JoinPath(test_src, \"__main__/test/syscalls/linux\", binary);\n- }\n-\n- TEST_CHECK(full_path.empty() == false);\n- return full_path;\n-}\n+constexpr char kBasicWorkload[] = \"test/syscalls/linux/exec_basic_workload\";\n+constexpr char kExitScript[] = \"test/syscalls/linux/exit_script\";\n+constexpr char kStateWorkload[] = \"test/syscalls/linux/exec_state_workload\";\n+constexpr char kProcExeWorkload[] =\n+ \"test/syscalls/linux/exec_proc_exe_workload\";\n+constexpr char kAssertClosedWorkload[] =\n+ \"test/syscalls/linux/exec_assert_closed_workload\";\n+constexpr char kPriorityWorkload[] = \"test/syscalls/linux/priority_execve\";\nconstexpr char kExit42[] = \"--exec_exit_42\";\nconstexpr char kExecWithThread[] = \"--exec_exec_with_thread\";\n@@ -171,44 +162,44 @@ TEST(ExecTest, EmptyPath) {\n}\nTEST(ExecTest, Basic) {\n- CheckExec(WorkloadPath(kBasicWorkload), {WorkloadPath(kBasicWorkload)}, {},\n+ CheckExec(RunfilePath(kBasicWorkload), {RunfilePath(kBasicWorkload)}, {},\nArgEnvExitStatus(0, 0),\n- absl::StrCat(WorkloadPath(kBasicWorkload), \"\\n\"));\n+ absl::StrCat(RunfilePath(kBasicWorkload), \"\\n\"));\n}\nTEST(ExecTest, OneArg) {\n- CheckExec(WorkloadPath(kBasicWorkload), {WorkloadPath(kBasicWorkload), \"1\"},\n- {}, ArgEnvExitStatus(1, 0),\n- absl::StrCat(WorkloadPath(kBasicWorkload), \"\\n1\\n\"));\n+ CheckExec(RunfilePath(kBasicWorkload), {RunfilePath(kBasicWorkload), \"1\"}, {},\n+ ArgEnvExitStatus(1, 0),\n+ absl::StrCat(RunfilePath(kBasicWorkload), \"\\n1\\n\"));\n}\nTEST(ExecTest, FiveArg) {\n- CheckExec(WorkloadPath(kBasicWorkload),\n- {WorkloadPath(kBasicWorkload), \"1\", \"2\", \"3\", \"4\", \"5\"}, {},\n+ CheckExec(RunfilePath(kBasicWorkload),\n+ {RunfilePath(kBasicWorkload), \"1\", \"2\", \"3\", \"4\", \"5\"}, {},\nArgEnvExitStatus(5, 0),\n- absl::StrCat(WorkloadPath(kBasicWorkload), \"\\n1\\n2\\n3\\n4\\n5\\n\"));\n+ absl::StrCat(RunfilePath(kBasicWorkload), \"\\n1\\n2\\n3\\n4\\n5\\n\"));\n}\nTEST(ExecTest, OneEnv) {\n- CheckExec(WorkloadPath(kBasicWorkload), {WorkloadPath(kBasicWorkload)}, {\"1\"},\n+ CheckExec(RunfilePath(kBasicWorkload), {RunfilePath(kBasicWorkload)}, {\"1\"},\nArgEnvExitStatus(0, 1),\n- absl::StrCat(WorkloadPath(kBasicWorkload), \"\\n1\\n\"));\n+ absl::StrCat(RunfilePath(kBasicWorkload), \"\\n1\\n\"));\n}\nTEST(ExecTest, FiveEnv) {\n- CheckExec(WorkloadPath(kBasicWorkload), {WorkloadPath(kBasicWorkload)},\n+ CheckExec(RunfilePath(kBasicWorkload), {RunfilePath(kBasicWorkload)},\n{\"1\", \"2\", \"3\", \"4\", \"5\"}, ArgEnvExitStatus(0, 5),\n- absl::StrCat(WorkloadPath(kBasicWorkload), \"\\n1\\n2\\n3\\n4\\n5\\n\"));\n+ absl::StrCat(RunfilePath(kBasicWorkload), \"\\n1\\n2\\n3\\n4\\n5\\n\"));\n}\nTEST(ExecTest, OneArgOneEnv) {\n- CheckExec(WorkloadPath(kBasicWorkload), {WorkloadPath(kBasicWorkload), \"arg\"},\n+ CheckExec(RunfilePath(kBasicWorkload), {RunfilePath(kBasicWorkload), \"arg\"},\n{\"env\"}, ArgEnvExitStatus(1, 1),\n- absl::StrCat(WorkloadPath(kBasicWorkload), \"\\narg\\nenv\\n\"));\n+ absl::StrCat(RunfilePath(kBasicWorkload), \"\\narg\\nenv\\n\"));\n}\nTEST(ExecTest, InterpreterScript) {\n- CheckExec(WorkloadPath(kExitScript), {WorkloadPath(kExitScript), \"25\"}, {},\n+ CheckExec(RunfilePath(kExitScript), {RunfilePath(kExitScript), \"25\"}, {},\nArgEnvExitStatus(25, 0), \"\");\n}\n@@ -216,7 +207,7 @@ TEST(ExecTest, InterpreterScript) {\nTEST(ExecTest, InterpreterScriptArgSplit) {\n// Symlink through /tmp to ensure the path is short enough.\nTempPath link = ASSERT_NO_ERRNO_AND_VALUE(\n- TempPath::CreateSymlinkTo(\"/tmp\", WorkloadPath(kBasicWorkload)));\n+ TempPath::CreateSymlinkTo(\"/tmp\", RunfilePath(kBasicWorkload)));\nTempPath script = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\nGetAbsoluteTestTmpdir(), absl::StrCat(\"#!\", link.path(), \" foo bar\"),\n@@ -230,7 +221,7 @@ TEST(ExecTest, InterpreterScriptArgSplit) {\nTEST(ExecTest, InterpreterScriptArgvZero) {\n// Symlink through /tmp to ensure the path is short enough.\nTempPath link = ASSERT_NO_ERRNO_AND_VALUE(\n- TempPath::CreateSymlinkTo(\"/tmp\", WorkloadPath(kBasicWorkload)));\n+ TempPath::CreateSymlinkTo(\"/tmp\", RunfilePath(kBasicWorkload)));\nTempPath script = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\nGetAbsoluteTestTmpdir(), absl::StrCat(\"#!\", link.path()), 0755));\n@@ -244,7 +235,7 @@ TEST(ExecTest, InterpreterScriptArgvZero) {\nTEST(ExecTest, InterpreterScriptArgvZeroRelative) {\n// Symlink through /tmp to ensure the path is short enough.\nTempPath link = ASSERT_NO_ERRNO_AND_VALUE(\n- TempPath::CreateSymlinkTo(\"/tmp\", WorkloadPath(kBasicWorkload)));\n+ TempPath::CreateSymlinkTo(\"/tmp\", RunfilePath(kBasicWorkload)));\nTempPath script = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\nGetAbsoluteTestTmpdir(), absl::StrCat(\"#!\", link.path()), 0755));\n@@ -261,7 +252,7 @@ TEST(ExecTest, InterpreterScriptArgvZeroRelative) {\nTEST(ExecTest, InterpreterScriptArgvZeroAdded) {\n// Symlink through /tmp to ensure the path is short enough.\nTempPath link = ASSERT_NO_ERRNO_AND_VALUE(\n- TempPath::CreateSymlinkTo(\"/tmp\", WorkloadPath(kBasicWorkload)));\n+ TempPath::CreateSymlinkTo(\"/tmp\", RunfilePath(kBasicWorkload)));\nTempPath script = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\nGetAbsoluteTestTmpdir(), absl::StrCat(\"#!\", link.path()), 0755));\n@@ -274,7 +265,7 @@ TEST(ExecTest, InterpreterScriptArgvZeroAdded) {\nTEST(ExecTest, InterpreterScriptArgNUL) {\n// Symlink through /tmp to ensure the path is short enough.\nTempPath link = ASSERT_NO_ERRNO_AND_VALUE(\n- TempPath::CreateSymlinkTo(\"/tmp\", WorkloadPath(kBasicWorkload)));\n+ TempPath::CreateSymlinkTo(\"/tmp\", RunfilePath(kBasicWorkload)));\nTempPath script = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\nGetAbsoluteTestTmpdir(),\n@@ -289,7 +280,7 @@ TEST(ExecTest, InterpreterScriptArgNUL) {\nTEST(ExecTest, InterpreterScriptTrailingWhitespace) {\n// Symlink through /tmp to ensure the path is short enough.\nTempPath link = ASSERT_NO_ERRNO_AND_VALUE(\n- TempPath::CreateSymlinkTo(\"/tmp\", WorkloadPath(kBasicWorkload)));\n+ TempPath::CreateSymlinkTo(\"/tmp\", RunfilePath(kBasicWorkload)));\nTempPath script = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\nGetAbsoluteTestTmpdir(), absl::StrCat(\"#!\", link.path(), \" \"), 0755));\n@@ -302,7 +293,7 @@ TEST(ExecTest, InterpreterScriptTrailingWhitespace) {\nTEST(ExecTest, InterpreterScriptArgWhitespace) {\n// Symlink through /tmp to ensure the path is short enough.\nTempPath link = ASSERT_NO_ERRNO_AND_VALUE(\n- TempPath::CreateSymlinkTo(\"/tmp\", WorkloadPath(kBasicWorkload)));\n+ TempPath::CreateSymlinkTo(\"/tmp\", RunfilePath(kBasicWorkload)));\nTempPath script = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\nGetAbsoluteTestTmpdir(), absl::StrCat(\"#!\", link.path(), \" foo\"), 0755));\n@@ -325,7 +316,7 @@ TEST(ExecTest, InterpreterScriptNoPath) {\nTEST(ExecTest, ExecFn) {\n// Symlink through /tmp to ensure the path is short enough.\nTempPath link = ASSERT_NO_ERRNO_AND_VALUE(\n- TempPath::CreateSymlinkTo(\"/tmp\", WorkloadPath(kStateWorkload)));\n+ TempPath::CreateSymlinkTo(\"/tmp\", RunfilePath(kStateWorkload)));\nTempPath script = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\nGetAbsoluteTestTmpdir(), absl::StrCat(\"#!\", link.path(), \" PrintExecFn\"),\n@@ -342,7 +333,7 @@ TEST(ExecTest, ExecFn) {\n}\nTEST(ExecTest, ExecName) {\n- std::string path = WorkloadPath(kStateWorkload);\n+ std::string path = RunfilePath(kStateWorkload);\nCheckExec(path, {path, \"PrintExecName\"}, {}, ArgEnvExitStatus(0, 0),\nabsl::StrCat(Basename(path).substr(0, 15), \"\\n\"));\n@@ -351,7 +342,7 @@ TEST(ExecTest, ExecName) {\nTEST(ExecTest, ExecNameScript) {\n// Symlink through /tmp to ensure the path is short enough.\nTempPath link = ASSERT_NO_ERRNO_AND_VALUE(\n- TempPath::CreateSymlinkTo(\"/tmp\", WorkloadPath(kStateWorkload)));\n+ TempPath::CreateSymlinkTo(\"/tmp\", RunfilePath(kStateWorkload)));\nTempPath script = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\nGetAbsoluteTestTmpdir(),\n@@ -405,13 +396,13 @@ TEST(ExecStateTest, HandlerReset) {\nASSERT_THAT(sigaction(SIGUSR1, &sa, nullptr), SyscallSucceeds());\nExecveArray args = {\n- WorkloadPath(kStateWorkload),\n+ RunfilePath(kStateWorkload),\n\"CheckSigHandler\",\nabsl::StrCat(SIGUSR1),\nabsl::StrCat(absl::Hex(reinterpret_cast<uintptr_t>(SIG_DFL))),\n};\n- CheckExec(WorkloadPath(kStateWorkload), args, {}, W_EXITCODE(0, 0), \"\");\n+ CheckExec(RunfilePath(kStateWorkload), args, {}, W_EXITCODE(0, 0), \"\");\n}\n// Ignored signal dispositions are not reset.\n@@ -421,13 +412,13 @@ TEST(ExecStateTest, IgnorePreserved) {\nASSERT_THAT(sigaction(SIGUSR1, &sa, nullptr), SyscallSucceeds());\nExecveArray args = {\n- WorkloadPath(kStateWorkload),\n+ RunfilePath(kStateWorkload),\n\"CheckSigHandler\",\nabsl::StrCat(SIGUSR1),\nabsl::StrCat(absl::Hex(reinterpret_cast<uintptr_t>(SIG_IGN))),\n};\n- CheckExec(WorkloadPath(kStateWorkload), args, {}, W_EXITCODE(0, 0), \"\");\n+ CheckExec(RunfilePath(kStateWorkload), args, {}, W_EXITCODE(0, 0), \"\");\n}\n// Signal masks are not reset on exec\n@@ -438,12 +429,12 @@ TEST(ExecStateTest, SignalMask) {\nASSERT_THAT(sigprocmask(SIG_BLOCK, &s, nullptr), SyscallSucceeds());\nExecveArray args = {\n- WorkloadPath(kStateWorkload),\n+ RunfilePath(kStateWorkload),\n\"CheckSigBlocked\",\nabsl::StrCat(SIGUSR1),\n};\n- CheckExec(WorkloadPath(kStateWorkload), args, {}, W_EXITCODE(0, 0), \"\");\n+ CheckExec(RunfilePath(kStateWorkload), args, {}, W_EXITCODE(0, 0), \"\");\n}\n// itimers persist across execve.\n@@ -471,7 +462,7 @@ TEST(ExecStateTest, ItimerPreserved) {\n}\n};\n- std::string filename = WorkloadPath(kStateWorkload);\n+ std::string filename = RunfilePath(kStateWorkload);\nExecveArray argv = {\nfilename,\n\"CheckItimerEnabled\",\n@@ -495,8 +486,8 @@ TEST(ExecStateTest, ItimerPreserved) {\nTEST(ProcSelfExe, ChangesAcrossExecve) {\n// See exec_proc_exe_workload for more details. We simply\n// assert that the /proc/self/exe link changes across execve.\n- CheckExec(WorkloadPath(kProcExeWorkload),\n- {WorkloadPath(kProcExeWorkload),\n+ CheckExec(RunfilePath(kProcExeWorkload),\n+ {RunfilePath(kProcExeWorkload),\nASSERT_NO_ERRNO_AND_VALUE(ProcessExePath(getpid()))},\n{}, W_EXITCODE(0, 0), \"\");\n}\n@@ -507,8 +498,8 @@ TEST(ExecTest, CloexecNormalFile) {\nconst FileDescriptor fd_closed_on_exec =\nASSERT_NO_ERRNO_AND_VALUE(Open(tempFile.path(), O_RDONLY | O_CLOEXEC));\n- CheckExec(WorkloadPath(kAssertClosedWorkload),\n- {WorkloadPath(kAssertClosedWorkload),\n+ CheckExec(RunfilePath(kAssertClosedWorkload),\n+ {RunfilePath(kAssertClosedWorkload),\nabsl::StrCat(fd_closed_on_exec.get())},\n{}, W_EXITCODE(0, 0), \"\");\n@@ -517,9 +508,9 @@ TEST(ExecTest, CloexecNormalFile) {\nconst FileDescriptor fd_open_on_exec =\nASSERT_NO_ERRNO_AND_VALUE(Open(tempFile.path(), O_RDONLY));\n- CheckExec(WorkloadPath(kAssertClosedWorkload),\n- {WorkloadPath(kAssertClosedWorkload),\n- absl::StrCat(fd_open_on_exec.get())},\n+ CheckExec(\n+ RunfilePath(kAssertClosedWorkload),\n+ {RunfilePath(kAssertClosedWorkload), absl::StrCat(fd_open_on_exec.get())},\n{}, W_EXITCODE(2, 0), \"\");\n}\n@@ -528,15 +519,15 @@ TEST(ExecTest, CloexecEventfd) {\nASSERT_THAT(efd = eventfd(0, EFD_CLOEXEC), SyscallSucceeds());\nFileDescriptor fd(efd);\n- CheckExec(WorkloadPath(kAssertClosedWorkload),\n- {WorkloadPath(kAssertClosedWorkload), absl::StrCat(fd.get())}, {},\n+ CheckExec(RunfilePath(kAssertClosedWorkload),\n+ {RunfilePath(kAssertClosedWorkload), absl::StrCat(fd.get())}, {},\nW_EXITCODE(0, 0), \"\");\n}\nconstexpr int kLinuxMaxSymlinks = 40;\nTEST(ExecTest, SymlinkLimitExceeded) {\n- std::string path = WorkloadPath(kBasicWorkload);\n+ std::string path = RunfilePath(kBasicWorkload);\n// Hold onto TempPath objects so they are not destructed prematurely.\nstd::vector<TempPath> symlinks;\n@@ -575,13 +566,13 @@ TEST(ExecTest, SymlinkLimitRefreshedForInterpreter) {\n}\nTEST(ExecveatTest, BasicWithFDCWD) {\n- std::string path = WorkloadPath(kBasicWorkload);\n+ std::string path = RunfilePath(kBasicWorkload);\nCheckExecveat(AT_FDCWD, path, {path}, {}, /*flags=*/0, ArgEnvExitStatus(0, 0),\nabsl::StrCat(path, \"\\n\"));\n}\nTEST(ExecveatTest, Basic) {\n- std::string absolute_path = WorkloadPath(kBasicWorkload);\n+ std::string absolute_path = RunfilePath(kBasicWorkload);\nstd::string parent_dir = std::string(Dirname(absolute_path));\nstd::string base = std::string(Basename(absolute_path));\nconst FileDescriptor dirfd =\n@@ -592,7 +583,7 @@ TEST(ExecveatTest, Basic) {\n}\nTEST(ExecveatTest, FDNotADirectory) {\n- std::string absolute_path = WorkloadPath(kBasicWorkload);\n+ std::string absolute_path = RunfilePath(kBasicWorkload);\nstd::string base = std::string(Basename(absolute_path));\nconst FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(absolute_path, 0));\n@@ -604,13 +595,13 @@ TEST(ExecveatTest, FDNotADirectory) {\n}\nTEST(ExecveatTest, AbsolutePathWithFDCWD) {\n- std::string path = WorkloadPath(kBasicWorkload);\n+ std::string path = RunfilePath(kBasicWorkload);\nCheckExecveat(AT_FDCWD, path, {path}, {}, ArgEnvExitStatus(0, 0), 0,\nabsl::StrCat(path, \"\\n\"));\n}\nTEST(ExecveatTest, AbsolutePath) {\n- std::string path = WorkloadPath(kBasicWorkload);\n+ std::string path = RunfilePath(kBasicWorkload);\n// File descriptor should be ignored when an absolute path is given.\nconst int32_t badFD = -1;\nCheckExecveat(badFD, path, {path}, {}, ArgEnvExitStatus(0, 0), 0,\n@@ -618,7 +609,7 @@ TEST(ExecveatTest, AbsolutePath) {\n}\nTEST(ExecveatTest, EmptyPathBasic) {\n- std::string path = WorkloadPath(kBasicWorkload);\n+ std::string path = RunfilePath(kBasicWorkload);\nconst FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(path, O_PATH));\nCheckExecveat(fd.get(), \"\", {path}, {}, AT_EMPTY_PATH, ArgEnvExitStatus(0, 0),\n@@ -626,7 +617,7 @@ TEST(ExecveatTest, EmptyPathBasic) {\n}\nTEST(ExecveatTest, EmptyPathWithDirFD) {\n- std::string path = WorkloadPath(kBasicWorkload);\n+ std::string path = RunfilePath(kBasicWorkload);\nstd::string parent_dir = std::string(Dirname(path));\nconst FileDescriptor dirfd =\nASSERT_NO_ERRNO_AND_VALUE(Open(parent_dir, O_DIRECTORY));\n@@ -639,7 +630,7 @@ TEST(ExecveatTest, EmptyPathWithDirFD) {\n}\nTEST(ExecveatTest, EmptyPathWithoutEmptyPathFlag) {\n- std::string path = WorkloadPath(kBasicWorkload);\n+ std::string path = RunfilePath(kBasicWorkload);\nconst FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(path, O_PATH));\nint execve_errno;\n@@ -649,7 +640,7 @@ TEST(ExecveatTest, EmptyPathWithoutEmptyPathFlag) {\n}\nTEST(ExecveatTest, AbsolutePathWithEmptyPathFlag) {\n- std::string path = WorkloadPath(kBasicWorkload);\n+ std::string path = RunfilePath(kBasicWorkload);\nconst FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(path, O_PATH));\nCheckExecveat(fd.get(), path, {path}, {}, AT_EMPTY_PATH,\n@@ -657,7 +648,7 @@ TEST(ExecveatTest, AbsolutePathWithEmptyPathFlag) {\n}\nTEST(ExecveatTest, RelativePathWithEmptyPathFlag) {\n- std::string absolute_path = WorkloadPath(kBasicWorkload);\n+ std::string absolute_path = RunfilePath(kBasicWorkload);\nstd::string parent_dir = std::string(Dirname(absolute_path));\nstd::string base = std::string(Basename(absolute_path));\nconst FileDescriptor dirfd =\n@@ -670,7 +661,7 @@ TEST(ExecveatTest, RelativePathWithEmptyPathFlag) {\nTEST(ExecveatTest, SymlinkNoFollowWithRelativePath) {\nstd::string parent_dir = \"/tmp\";\nTempPath link = ASSERT_NO_ERRNO_AND_VALUE(\n- TempPath::CreateSymlinkTo(parent_dir, WorkloadPath(kBasicWorkload)));\n+ TempPath::CreateSymlinkTo(parent_dir, RunfilePath(kBasicWorkload)));\nconst FileDescriptor dirfd =\nASSERT_NO_ERRNO_AND_VALUE(Open(parent_dir, O_DIRECTORY));\nstd::string base = std::string(Basename(link.path()));\n@@ -685,7 +676,7 @@ TEST(ExecveatTest, SymlinkNoFollowWithRelativePath) {\nTEST(ExecveatTest, SymlinkNoFollowWithAbsolutePath) {\nstd::string parent_dir = \"/tmp\";\nTempPath link = ASSERT_NO_ERRNO_AND_VALUE(\n- TempPath::CreateSymlinkTo(parent_dir, WorkloadPath(kBasicWorkload)));\n+ TempPath::CreateSymlinkTo(parent_dir, RunfilePath(kBasicWorkload)));\nstd::string path = link.path();\nint execve_errno;\n@@ -697,7 +688,7 @@ TEST(ExecveatTest, SymlinkNoFollowWithAbsolutePath) {\nTEST(ExecveatTest, SymlinkNoFollowAndEmptyPath) {\nTempPath link = ASSERT_NO_ERRNO_AND_VALUE(\n- TempPath::CreateSymlinkTo(\"/tmp\", WorkloadPath(kBasicWorkload)));\n+ TempPath::CreateSymlinkTo(\"/tmp\", RunfilePath(kBasicWorkload)));\nstd::string path = link.path();\nconst FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(path, 0));\n@@ -723,7 +714,7 @@ TEST(ExecveatTest, SymlinkNoFollowWithNormalFile) {\n}\nTEST(ExecveatTest, BasicWithCloexecFD) {\n- std::string path = WorkloadPath(kBasicWorkload);\n+ std::string path = RunfilePath(kBasicWorkload);\nconst FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(path, O_CLOEXEC));\nCheckExecveat(fd.get(), \"\", {path}, {}, AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH,\n@@ -731,7 +722,7 @@ TEST(ExecveatTest, BasicWithCloexecFD) {\n}\nTEST(ExecveatTest, InterpreterScriptWithCloexecFD) {\n- std::string path = WorkloadPath(kExitScript);\n+ std::string path = RunfilePath(kExitScript);\nconst FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(path, O_CLOEXEC));\nint execve_errno;\n@@ -742,7 +733,7 @@ TEST(ExecveatTest, InterpreterScriptWithCloexecFD) {\n}\nTEST(ExecveatTest, InterpreterScriptWithCloexecDirFD) {\n- std::string absolute_path = WorkloadPath(kExitScript);\n+ std::string absolute_path = RunfilePath(kExitScript);\nstd::string parent_dir = std::string(Dirname(absolute_path));\nstd::string base = std::string(Basename(absolute_path));\nconst FileDescriptor dirfd =\n@@ -775,7 +766,7 @@ TEST(GetpriorityTest, ExecveMaintainsPriority) {\n// Program run (priority_execve) will exit(X) where\n// X=getpriority(PRIO_PROCESS,0). Check that this exit value is prio.\n- CheckExec(WorkloadPath(kPriorityWorkload), {WorkloadPath(kPriorityWorkload)},\n+ CheckExec(RunfilePath(kPriorityWorkload), {RunfilePath(kPriorityWorkload)},\n{}, W_EXITCODE(expected_exit_code, 0), \"\");\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/sigaltstack.cc",
"new_path": "test/syscalls/linux/sigaltstack.cc",
"diff": "@@ -95,13 +95,7 @@ TEST(SigaltstackTest, ResetByExecve) {\nauto const cleanup_sigstack =\nASSERT_NO_ERRNO_AND_VALUE(ScopedSigaltstack(stack));\n- std::string full_path;\n- char* test_src = getenv(\"TEST_SRCDIR\");\n- if (test_src) {\n- full_path = JoinPath(test_src, \"../../linux/sigaltstack_check\");\n- }\n-\n- ASSERT_FALSE(full_path.empty());\n+ std::string full_path = RunfilePath(\"test/syscalls/linux/sigaltstack_check\");\npid_t child_pid = -1;\nint execve_errno = 0;\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/BUILD",
"new_path": "test/util/BUILD",
"diff": "@@ -237,6 +237,7 @@ cc_library(\n] + select_for_linux(\n[\n\"test_util_impl.cc\",\n+ \"test_util_runfiles.cc\",\n],\n),\nhdrs = [\"test_util.h\"],\n@@ -245,6 +246,7 @@ cc_library(\n\":logging\",\n\":posix_error\",\n\":save_util\",\n+ \"@bazel_tools//tools/cpp/runfiles\",\n\"@com_google_absl//absl/base:core_headers\",\n\"@com_google_absl//absl/flags:flag\",\n\"@com_google_absl//absl/flags:parse\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/test_util.h",
"new_path": "test/util/test_util.h",
"diff": "@@ -764,6 +764,12 @@ MATCHER_P2(EquivalentWithin, target, tolerance,\nreturn Equivalent(arg, target, tolerance);\n}\n+// Returns the absolute path to the a data dependency. 'path' is the runfile\n+// location relative to workspace root.\n+#ifdef __linux__\n+std::string RunfilePath(std::string path);\n+#endif\n+\nvoid TestInit(int* argc, char*** argv);\n} // namespace testing\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/util/test_util_runfiles.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 <iostream>\n+#include <string>\n+\n+#include \"test/util/fs_util.h\"\n+#include \"test/util/test_util.h\"\n+#include \"tools/cpp/runfiles/runfiles.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+std::string RunfilePath(std::string path) {\n+ static const bazel::tools::cpp::runfiles::Runfiles* const runfiles = [] {\n+ std::string error;\n+ auto* runfiles =\n+ bazel::tools::cpp::runfiles::Runfiles::CreateForTest(&error);\n+ if (runfiles == nullptr) {\n+ std::cerr << \"Unable to find runfiles: \" << error << std::endl;\n+ }\n+ return runfiles;\n+ }();\n+\n+ if (!runfiles) {\n+ // Can't find runfiles? This probably won't work, but __main__/path is our\n+ // best guess.\n+ return JoinPath(\"__main__\", path);\n+ }\n+\n+ return runfiles->Rlocation(JoinPath(\"__main__\", path));\n+}\n+\n+} // namespace testing\n+} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add RunfilesPath to test_util
A few tests have their own ad-hoc implementations. Add a single common one.
PiperOrigin-RevId: 283601666 |
259,992 | 03.12.2019 13:31:07 | 28,800 | 3e832bec1b48b95951c3b83eb5a7b70f29b1f10f | Point TODOs to gvisor.dev | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/filesystems.go",
"new_path": "pkg/sentry/fsimpl/proc/filesystems.go",
"diff": "@@ -19,7 +19,7 @@ package proc\n// +stateify savable\ntype filesystemsData struct{}\n-// TODO(b/138862512): Implement vfs.DynamicBytesSource.Generate for\n+// TODO(gvisor.dev/issue/1195): Implement vfs.DynamicBytesSource.Generate for\n// filesystemsData. We would need to retrive filesystem names from\n// vfs.VirtualFilesystem. Also needs vfs replacement for\n// fs.Filesystem.AllowUserList() and fs.FilesystemRequiresDev.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/mounts.go",
"new_path": "pkg/sentry/fsimpl/proc/mounts.go",
"diff": "@@ -16,7 +16,7 @@ package proc\nimport \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n-// TODO(b/138862512): Implement mountInfoFile and mountsFile.\n+// TODO(gvisor.dev/issue/1195): Implement mountInfoFile and mountsFile.\n// mountInfoFile implements vfs.DynamicBytesSource for /proc/[pid]/mountinfo.\n//\n"
}
] | Go | Apache License 2.0 | google/gvisor | Point TODOs to gvisor.dev
PiperOrigin-RevId: 283610781 |
259,992 | 03.12.2019 13:42:30 | 28,800 | 154dcdec072ddad9e1c96b56e023d7f77fecf2ad | Remove watchdog TODO
I have not seen a false positive stuck task yet.
Biggest offender was whitelistfs which is going away. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/watchdog/watchdog.go",
"new_path": "pkg/sentry/watchdog/watchdog.go",
"diff": "@@ -287,7 +287,9 @@ func (w *Watchdog) runTurn() {\nif !ok {\n// New stuck task detected.\n//\n- // TODO(b/65849403): Tasks blocked doing IO may be considered stuck in kernel.\n+ // Note that tasks blocked doing IO may be considered stuck in kernel,\n+ // unless they are surrounded b\n+ // Task.UninterruptibleSleepStart/Finish.\ntc = &offender{lastUpdateTime: lastUpdateTime}\nstuckTasks.Increment()\nnewTaskFound = true\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove watchdog TODO
I have not seen a false positive stuck task yet.
Biggest offender was whitelistfs which is going away.
PiperOrigin-RevId: 283613064 |
259,853 | 03.12.2019 13:46:09 | 28,800 | 43643752f05a0b25259b116558ccd870a539cc05 | strace: don't create a slice with a negative value | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/strace/socket.go",
"new_path": "pkg/sentry/strace/socket.go",
"diff": "@@ -208,6 +208,15 @@ func cmsghdr(t *kernel.Task, addr usermem.Addr, length uint64, maxBytes uint64)\ni += linux.SizeOfControlMessageHeader\nwidth := t.Arch().Width()\nlength := int(h.Length) - linux.SizeOfControlMessageHeader\n+ if length < 0 {\n+ strs = append(strs, fmt.Sprintf(\n+ \"{level=%s, type=%s, length=%d, content too short}\",\n+ level,\n+ typ,\n+ h.Length,\n+ ))\n+ break\n+ }\nif skipData {\nstrs = append(strs, fmt.Sprintf(\"{level=%s, type=%s, length=%d}\", level, typ, h.Length))\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_unix_cmsg.cc",
"new_path": "test/syscalls/linux/socket_unix_cmsg.cc",
"diff": "@@ -149,6 +149,35 @@ TEST_P(UnixSocketPairCmsgTest, BadFDPass) {\nSyscallFailsWithErrno(EBADF));\n}\n+TEST_P(UnixSocketPairCmsgTest, ShortCmsg) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ char sent_data[20];\n+ RandomizeBuffer(sent_data, sizeof(sent_data));\n+\n+ int sent_fd = -1;\n+\n+ struct msghdr msg = {};\n+ char control[CMSG_SPACE(sizeof(sent_fd))];\n+ msg.msg_control = control;\n+ msg.msg_controllen = sizeof(control);\n+\n+ struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);\n+ cmsg->cmsg_len = 1;\n+ cmsg->cmsg_level = SOL_SOCKET;\n+ cmsg->cmsg_type = SCM_RIGHTS;\n+ memcpy(CMSG_DATA(cmsg), &sent_fd, sizeof(sent_fd));\n+\n+ struct iovec iov;\n+ iov.iov_base = sent_data;\n+ iov.iov_len = sizeof(sent_data);\n+ msg.msg_iov = &iov;\n+ msg.msg_iovlen = 1;\n+\n+ ASSERT_THAT(RetryEINTR(sendmsg)(sockets->first_fd(), &msg, 0),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\n// BasicFDPassNoSpace starts off by sending a single FD just like BasicFDPass.\n// The difference is that when calling recvmsg, no space for FDs is provided,\n// only space for the cmsg header.\n"
}
] | Go | Apache License 2.0 | google/gvisor | strace: don't create a slice with a negative value
PiperOrigin-RevId: 283613824 |
259,975 | 03.12.2019 15:06:18 | 28,800 | 035407153989b189a3ce42df43d6f528fa95444f | Fix printing /proc/[pid]/io for /proc/[pid]/task/[tid]/io. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/task.go",
"new_path": "pkg/sentry/fs/proc/task.go",
"diff": "@@ -639,7 +639,7 @@ func (i *ioData) ReadSeqFileData(ctx context.Context, h seqfile.SeqHandle) ([]se\nio.Accumulate(i.IOUsage())\nvar buf bytes.Buffer\n- fmt.Fprintf(&buf, \"char: %d\\n\", io.CharsRead)\n+ fmt.Fprintf(&buf, \"rchar: %d\\n\", io.CharsRead)\nfmt.Fprintf(&buf, \"wchar: %d\\n\", io.CharsWritten)\nfmt.Fprintf(&buf, \"syscr: %d\\n\", io.ReadSyscalls)\nfmt.Fprintf(&buf, \"syscw: %d\\n\", io.WriteSyscalls)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix printing /proc/[pid]/io for /proc/[pid]/task/[tid]/io.
PiperOrigin-RevId: 283630669 |
259,853 | 03.12.2019 16:30:38 | 28,800 | cf7f27c16793eaa41743e96488dad2ddfd1f5d59 | net/udp: return a local route address as the bound-to address
If the socket is bound to ANY and connected to a loopback address,
getsockname() has to return the loopback address. Without this fix,
getsockname() returns ANY. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -1134,9 +1134,14 @@ func (e *endpoint) GetLocalAddress() (tcpip.FullAddress, *tcpip.Error) {\ne.mu.RLock()\ndefer e.mu.RUnlock()\n+ addr := e.ID.LocalAddress\n+ if e.state == StateConnected {\n+ addr = e.route.LocalAddress\n+ }\n+\nreturn tcpip.FullAddress{\nNIC: e.RegisterNICID,\n- Addr: e.ID.LocalAddress,\n+ Addr: addr,\nPort: e.ID.LocalPort,\n}, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/udp_socket_test_cases.cc",
"new_path": "test/syscalls/linux/udp_socket_test_cases.cc",
"diff": "@@ -527,6 +527,45 @@ TEST_P(UdpSocketTest, DisconnectAfterBind) {\nSyscallFailsWithErrno(ENOTCONN));\n}\n+TEST_P(UdpSocketTest, BindToAnyConnnectToLocalhost) {\n+ struct sockaddr_storage baddr = {};\n+ auto port = *Port(reinterpret_cast<struct sockaddr_storage*>(addr_[1]));\n+ if (GetParam() == AddressFamily::kIpv4) {\n+ auto addr_in = reinterpret_cast<struct sockaddr_in*>(&baddr);\n+ addr_in->sin_family = AF_INET;\n+ addr_in->sin_port = port;\n+ addr_in->sin_addr.s_addr = htonl(INADDR_ANY);\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+ addr_in->sin6_scope_id = 0;\n+ addr_in->sin6_addr = IN6ADDR_ANY_INIT;\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+ socklen_t addrlen = sizeof(addr);\n+ EXPECT_THAT(getsockname(s_, reinterpret_cast<sockaddr*>(&addr), &addrlen),\n+ SyscallSucceeds());\n+\n+ // If the socket is bound to ANY and connected to a loopback address,\n+ // getsockname() has to return the loopback address.\n+ if (GetParam() == AddressFamily::kIpv4) {\n+ auto addr_out = reinterpret_cast<struct sockaddr_in*>(&addr);\n+ EXPECT_EQ(addrlen, sizeof(*addr_out));\n+ EXPECT_EQ(addr_out->sin_addr.s_addr, htonl(INADDR_LOOPBACK));\n+ } else {\n+ auto addr_out = reinterpret_cast<struct sockaddr_in6*>(&addr);\n+ struct in6_addr loopback = IN6ADDR_LOOPBACK_INIT;\n+ EXPECT_EQ(addrlen, sizeof(*addr_out));\n+ EXPECT_EQ(memcmp(&addr_out->sin6_addr, &loopback, sizeof(in6_addr)), 0);\n+ }\n+}\n+\nTEST_P(UdpSocketTest, DisconnectAfterBindToAny) {\nstruct sockaddr_storage baddr = {};\nsocklen_t addrlen;\n"
}
] | Go | Apache License 2.0 | google/gvisor | net/udp: return a local route address as the bound-to address
If the socket is bound to ANY and connected to a loopback address,
getsockname() has to return the loopback address. Without this fix,
getsockname() returns ANY.
PiperOrigin-RevId: 283647781 |
259,992 | 03.12.2019 17:32:27 | 28,800 | bb641c54035e79e3e4c2752e07e6ac55c620b93f | Point TODO to gvisor.dev | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/aio.cc",
"new_path": "test/syscalls/linux/aio.cc",
"diff": "@@ -129,7 +129,7 @@ TEST_F(AIOTest, BasicWrite) {\n// aio implementation uses aio_ring. gVisor doesn't and returns all zeroes.\n// Linux implements aio_ring, so skip the zeroes check.\n//\n- // TODO(b/65486370): Remove when gVisor implements aio_ring.\n+ // TODO(gvisor.dev/issue/204): Remove when gVisor implements aio_ring.\nauto ring = reinterpret_cast<struct aio_ring*>(ctx_);\nauto magic = IsRunningOnGvisor() ? 0 : AIO_RING_MAGIC;\nEXPECT_EQ(ring->magic, magic);\n"
}
] | Go | Apache License 2.0 | google/gvisor | Point TODO to gvisor.dev
PiperOrigin-RevId: 283657725 |
259,860 | 03.12.2019 19:40:56 | 28,800 | 80b7ba0c9709c0c7f4c3aef5637d23225bcb866b | Clean up readv_socket test suite.
Get rid of the SocketTest class, which is only extended by ReadvSocketTest.
Also, get rid of TCP sockets (which were unused anyway) from readv_socket.cc.
This is a very old test suite that isn't the right place for TCP loopback
tests. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -1795,7 +1795,6 @@ cc_binary(\nname = \"readv_socket_test\",\ntestonly = 1,\nsrcs = [\n- \"file_base.h\",\n\"readv_common.cc\",\n\"readv_common.h\",\n\"readv_socket.cc\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/file_base.h",
"new_path": "test/syscalls/linux/file_base.h",
"diff": "@@ -111,95 +111,6 @@ class FileTest : public ::testing::Test {\nint test_pipe_[2];\n};\n-class SocketTest : public ::testing::Test {\n- public:\n- void SetUp() override {\n- test_unix_stream_socket_[0] = -1;\n- test_unix_stream_socket_[1] = -1;\n- test_unix_dgram_socket_[0] = -1;\n- test_unix_dgram_socket_[1] = -1;\n- test_unix_seqpacket_socket_[0] = -1;\n- test_unix_seqpacket_socket_[1] = -1;\n- test_tcp_socket_[0] = -1;\n- test_tcp_socket_[1] = -1;\n-\n- ASSERT_THAT(socketpair(AF_UNIX, SOCK_STREAM, 0, test_unix_stream_socket_),\n- SyscallSucceeds());\n- ASSERT_THAT(fcntl(test_unix_stream_socket_[0], F_SETFL, O_NONBLOCK),\n- SyscallSucceeds());\n- ASSERT_THAT(socketpair(AF_UNIX, SOCK_DGRAM, 0, test_unix_dgram_socket_),\n- SyscallSucceeds());\n- ASSERT_THAT(fcntl(test_unix_dgram_socket_[0], F_SETFL, O_NONBLOCK),\n- SyscallSucceeds());\n- ASSERT_THAT(\n- socketpair(AF_UNIX, SOCK_SEQPACKET, 0, test_unix_seqpacket_socket_),\n- SyscallSucceeds());\n- ASSERT_THAT(fcntl(test_unix_seqpacket_socket_[0], F_SETFL, O_NONBLOCK),\n- SyscallSucceeds());\n- }\n-\n- void TearDown() override {\n- close(test_unix_stream_socket_[0]);\n- close(test_unix_stream_socket_[1]);\n-\n- close(test_unix_dgram_socket_[0]);\n- close(test_unix_dgram_socket_[1]);\n-\n- close(test_unix_seqpacket_socket_[0]);\n- close(test_unix_seqpacket_socket_[1]);\n-\n- close(test_tcp_socket_[0]);\n- close(test_tcp_socket_[1]);\n- }\n-\n- int test_unix_stream_socket_[2];\n- int test_unix_dgram_socket_[2];\n- int test_unix_seqpacket_socket_[2];\n- int test_tcp_socket_[2];\n-};\n-\n-// MatchesStringLength checks that a tuple argument of (struct iovec *, int)\n-// corresponding to an iovec array and its length, contains data that matches\n-// the string length strlen.\n-MATCHER_P(MatchesStringLength, strlen, \"\") {\n- struct iovec* iovs = arg.first;\n- int niov = arg.second;\n- int offset = 0;\n- for (int i = 0; i < niov; i++) {\n- offset += iovs[i].iov_len;\n- }\n- if (offset != static_cast<int>(strlen)) {\n- *result_listener << offset;\n- return false;\n- }\n- return true;\n-}\n-\n-// MatchesStringValue checks that a tuple argument of (struct iovec *, int)\n-// corresponding to an iovec array and its length, contains data that matches\n-// the string value str.\n-MATCHER_P(MatchesStringValue, str, \"\") {\n- struct iovec* iovs = arg.first;\n- int len = strlen(str);\n- int niov = arg.second;\n- int offset = 0;\n- for (int i = 0; i < niov; i++) {\n- struct iovec iov = iovs[i];\n- if (len < offset) {\n- *result_listener << \"strlen \" << len << \" < offset \" << offset;\n- return false;\n- }\n- if (strncmp(static_cast<char*>(iov.iov_base), &str[offset], iov.iov_len)) {\n- absl::string_view iovec_string(static_cast<char*>(iov.iov_base),\n- iov.iov_len);\n- *result_listener << iovec_string << \" @offset \" << offset;\n- return false;\n- }\n- offset += iov.iov_len;\n- }\n- return true;\n-}\n-\n} // namespace testing\n} // namespace gvisor\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/readv_common.cc",
"new_path": "test/syscalls/linux/readv_common.cc",
"diff": "#include <unistd.h>\n#include \"gtest/gtest.h\"\n-#include \"test/syscalls/linux/file_base.h\"\n#include \"test/util/test_util.h\"\nnamespace gvisor {\nnamespace testing {\n+// MatchesStringLength checks that a tuple argument of (struct iovec *, int)\n+// corresponding to an iovec array and its length, contains data that matches\n+// the string length strlen.\n+MATCHER_P(MatchesStringLength, strlen, \"\") {\n+ struct iovec* iovs = arg.first;\n+ int niov = arg.second;\n+ int offset = 0;\n+ for (int i = 0; i < niov; i++) {\n+ offset += iovs[i].iov_len;\n+ }\n+ if (offset != static_cast<int>(strlen)) {\n+ *result_listener << offset;\n+ return false;\n+ }\n+ return true;\n+}\n+\n+// MatchesStringValue checks that a tuple argument of (struct iovec *, int)\n+// corresponding to an iovec array and its length, contains data that matches\n+// the string value str.\n+MATCHER_P(MatchesStringValue, str, \"\") {\n+ struct iovec* iovs = arg.first;\n+ int len = strlen(str);\n+ int niov = arg.second;\n+ int offset = 0;\n+ for (int i = 0; i < niov; i++) {\n+ struct iovec iov = iovs[i];\n+ if (len < offset) {\n+ *result_listener << \"strlen \" << len << \" < offset \" << offset;\n+ return false;\n+ }\n+ if (strncmp(static_cast<char*>(iov.iov_base), &str[offset], iov.iov_len)) {\n+ absl::string_view iovec_string(static_cast<char*>(iov.iov_base),\n+ iov.iov_len);\n+ *result_listener << iovec_string << \" @offset \" << offset;\n+ return false;\n+ }\n+ offset += iov.iov_len;\n+ }\n+ return true;\n+}\n+\nextern const char kReadvTestData[] =\n\"127.0.0.1 localhost\"\n\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/readv_socket.cc",
"new_path": "test/syscalls/linux/readv_socket.cc",
"diff": "#include <unistd.h>\n#include \"gtest/gtest.h\"\n-#include \"test/syscalls/linux/file_base.h\"\n#include \"test/syscalls/linux/readv_common.h\"\n#include \"test/util/test_util.h\"\n@@ -28,9 +27,30 @@ namespace testing {\nnamespace {\n-class ReadvSocketTest : public SocketTest {\n+class ReadvSocketTest : public ::testing::Test {\n+ public:\nvoid SetUp() override {\n- SocketTest::SetUp();\n+ test_unix_stream_socket_[0] = -1;\n+ test_unix_stream_socket_[1] = -1;\n+ test_unix_dgram_socket_[0] = -1;\n+ test_unix_dgram_socket_[1] = -1;\n+ test_unix_seqpacket_socket_[0] = -1;\n+ test_unix_seqpacket_socket_[1] = -1;\n+\n+ ASSERT_THAT(socketpair(AF_UNIX, SOCK_STREAM, 0, test_unix_stream_socket_),\n+ SyscallSucceeds());\n+ ASSERT_THAT(fcntl(test_unix_stream_socket_[0], F_SETFL, O_NONBLOCK),\n+ SyscallSucceeds());\n+ ASSERT_THAT(socketpair(AF_UNIX, SOCK_DGRAM, 0, test_unix_dgram_socket_),\n+ SyscallSucceeds());\n+ ASSERT_THAT(fcntl(test_unix_dgram_socket_[0], F_SETFL, O_NONBLOCK),\n+ SyscallSucceeds());\n+ ASSERT_THAT(\n+ socketpair(AF_UNIX, SOCK_SEQPACKET, 0, test_unix_seqpacket_socket_),\n+ SyscallSucceeds());\n+ ASSERT_THAT(fcntl(test_unix_seqpacket_socket_[0], F_SETFL, O_NONBLOCK),\n+ SyscallSucceeds());\n+\nASSERT_THAT(\nwrite(test_unix_stream_socket_[1], kReadvTestData, kReadvTestDataSize),\nSyscallSucceedsWithValue(kReadvTestDataSize));\n@@ -40,11 +60,22 @@ class ReadvSocketTest : public SocketTest {\nASSERT_THAT(write(test_unix_seqpacket_socket_[1], kReadvTestData,\nkReadvTestDataSize),\nSyscallSucceedsWithValue(kReadvTestDataSize));\n- // FIXME(b/69821513): Enable when possible.\n- // ASSERT_THAT(write(test_tcp_socket_[1], kReadvTestData,\n- // kReadvTestDataSize),\n- // SyscallSucceedsWithValue(kReadvTestDataSize));\n}\n+\n+ void TearDown() override {\n+ close(test_unix_stream_socket_[0]);\n+ close(test_unix_stream_socket_[1]);\n+\n+ close(test_unix_dgram_socket_[0]);\n+ close(test_unix_dgram_socket_[1]);\n+\n+ close(test_unix_seqpacket_socket_[0]);\n+ close(test_unix_seqpacket_socket_[1]);\n+ }\n+\n+ int test_unix_stream_socket_[2];\n+ int test_unix_dgram_socket_[2];\n+ int test_unix_seqpacket_socket_[2];\n};\nTEST_F(ReadvSocketTest, ReadOneBufferPerByte_StreamSocket) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Clean up readv_socket test suite.
Get rid of the SocketTest class, which is only extended by ReadvSocketTest.
Also, get rid of TCP sockets (which were unused anyway) from readv_socket.cc.
This is a very old test suite that isn't the right place for TCP loopback
tests.
PiperOrigin-RevId: 283672772 |
259,992 | 04.12.2019 13:53:08 | 28,800 | 1eda90d0848658f330e5f37ce18209bd3d069766 | Remove TODO since we don't plan to support debug registers | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/arch/arch_amd64.go",
"new_path": "pkg/sentry/arch/arch_amd64.go",
"diff": "@@ -305,7 +305,7 @@ func (c *context64) PtracePeekUser(addr uintptr) (interface{}, error) {\nbuf := binary.Marshal(nil, usermem.ByteOrder, c.ptraceGetRegs())\nreturn c.Native(uintptr(usermem.ByteOrder.Uint64(buf[addr:]))), nil\n}\n- // TODO(b/34088053): debug registers\n+ // Note: x86 debug registers are missing.\nreturn c.Native(0), nil\n}\n@@ -320,6 +320,6 @@ func (c *context64) PtracePokeUser(addr, data uintptr) error {\n_, err := c.PtraceSetRegs(bytes.NewBuffer(buf))\nreturn err\n}\n- // TODO(b/34088053): debug registers\n+ // Note: x86 debug registers are missing.\nreturn nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove TODO since we don't plan to support debug registers
PiperOrigin-RevId: 283828423 |
259,860 | 04.12.2019 23:44:25 | 28,800 | 6ae64d793593eaf3c1364354ef01a555f230a0fe | Allow syscall tests to run with hostinet.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/build_defs.bzl",
"new_path": "test/syscalls/build_defs.bzl",
"diff": "@@ -9,6 +9,7 @@ def syscall_test(\nuse_tmpfs = False,\nadd_overlay = False,\nadd_uds_tree = False,\n+ add_hostinet = False,\ntags = None):\n_syscall_test(\ntest = test,\n@@ -65,6 +66,18 @@ def syscall_test(\nfile_access = \"shared\",\n)\n+ if add_hostinet:\n+ _syscall_test(\n+ test = test,\n+ shard_count = shard_count,\n+ size = size,\n+ platform = \"ptrace\",\n+ use_tmpfs = use_tmpfs,\n+ network = \"host\",\n+ add_uds_tree = add_uds_tree,\n+ tags = tags,\n+ )\n+\ndef _syscall_test(\ntest,\nshard_count,\n@@ -72,6 +85,7 @@ def _syscall_test(\nplatform,\nuse_tmpfs,\ntags,\n+ network = \"none\",\nfile_access = \"exclusive\",\noverlay = False,\nadd_uds_tree = False):\n@@ -85,6 +99,8 @@ def _syscall_test(\nname += \"_shared\"\nif overlay:\nname += \"_overlay\"\n+ if network != \"none\":\n+ name += \"_\" + network + \"net\"\nif tags == None:\ntags = []\n@@ -107,6 +123,7 @@ def _syscall_test(\n# Arguments are passed directly to syscall_test_runner binary.\n\"--test-name=\" + test_name,\n\"--platform=\" + platform,\n+ \"--network=\" + network,\n\"--use-tmpfs=\" + str(use_tmpfs),\n\"--file-access=\" + file_access,\n\"--overlay=\" + str(overlay),\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/syscall_test_runner.go",
"new_path": "test/syscalls/syscall_test_runner.go",
"diff": "@@ -46,6 +46,7 @@ var (\ndebug = flag.Bool(\"debug\", false, \"enable debug logs\")\nstrace = flag.Bool(\"strace\", false, \"enable strace logs\")\nplatform = flag.String(\"platform\", \"ptrace\", \"platform to run on\")\n+ network = flag.String(\"network\", \"none\", \"network stack to run on (sandbox, host, none)\")\nuseTmpfs = flag.Bool(\"use-tmpfs\", false, \"mounts tmpfs for /tmp\")\nfileAccess = flag.String(\"file-access\", \"exclusive\", \"mounts root in exclusive or shared mode\")\noverlay = flag.Bool(\"overlay\", false, \"wrap filesystem mounts with writable tmpfs overlay\")\n@@ -137,7 +138,7 @@ func runRunsc(tc gtest.TestCase, spec *specs.Spec) error {\nargs := []string{\n\"-root\", rootDir,\n- \"-network=none\",\n+ \"-network\", *network,\n\"-log-format=text\",\n\"-TESTONLY-unsafe-nonroot=true\",\n\"-net-raw=true\",\n@@ -335,10 +336,11 @@ func runTestCaseRunsc(testBin string, tc gtest.TestCase, t *testing.T) {\n})\n}\n- // Set environment variable that indicates we are\n- // running in gVisor and with the given platform.\n+ // Set environment variables that indicate we are\n+ // running in gVisor with the given platform and network.\nplatformVar := \"TEST_ON_GVISOR\"\n- env := append(os.Environ(), platformVar+\"=\"+*platform)\n+ networkVar := \"GVISOR_NETWORK\"\n+ env := append(os.Environ(), platformVar+\"=\"+*platform, networkVar+\"=\"+*network)\n// Remove env variables that cause the gunit binary to write output\n// files, since they will stomp on eachother, and on the output files\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/test_util.cc",
"new_path": "test/util/test_util.cc",
"diff": "@@ -41,6 +41,7 @@ namespace gvisor {\nnamespace testing {\n#define TEST_ON_GVISOR \"TEST_ON_GVISOR\"\n+#define GVISOR_NETWORK \"GVISOR_NETWORK\"\nbool IsRunningOnGvisor() { return GvisorPlatform() != Platform::kNative; }\n@@ -60,6 +61,11 @@ Platform GvisorPlatform() {\nabort();\n}\n+bool IsRunningWithHostinet() {\n+ char* env = getenv(GVISOR_NETWORK);\n+ return env && strcmp(env, \"host\") == 0;\n+}\n+\n// Inline cpuid instruction. Preserve %ebx/%rbx register. In PIC compilations\n// %ebx contains the address of the global offset table. %rbx is occasionally\n// used to address stack variables in presence of dynamic allocas.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/test_util.h",
"new_path": "test/util/test_util.h",
"diff": "@@ -220,6 +220,7 @@ enum class Platform {\n};\nbool IsRunningOnGvisor();\nPlatform GvisorPlatform();\n+bool IsRunningWithHostinet();\n#ifdef __linux__\nvoid SetupGvisorDeathTest();\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow syscall tests to run with hostinet.
Fixes #1207
PiperOrigin-RevId: 283914438 |
260,004 | 05.12.2019 10:40:18 | 28,800 | 10f7b109ab98c95783357b82e1934586f338c2b3 | Add a type to represent the NDP Recursive DNS Server option
This change adds a type to represent the NDP Recursive DNS Server option, as
defined by RFC 8106 section 5.1. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/BUILD",
"new_path": "pkg/tcpip/header/BUILD",
"diff": "@@ -55,5 +55,8 @@ go_test(\n\"ndp_test.go\",\n],\nembed = [\":header\"],\n- deps = [\"//pkg/tcpip\"],\n+ deps = [\n+ \"//pkg/tcpip\",\n+ \"@com_github_google_go-cmp//cmp:go_default_library\",\n+ ],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/ndp_options.go",
"new_path": "pkg/tcpip/header/ndp_options.go",
"diff": "@@ -85,6 +85,23 @@ const (\n// within an NDPPrefixInformation.\nndpPrefixInformationPrefixOffset = 14\n+ // NDPRecursiveDNSServerOptionType is the type of the Recursive DNS\n+ // Server option, as per RFC 8106 section 5.1.\n+ NDPRecursiveDNSServerOptionType = 25\n+\n+ // ndpRecursiveDNSServerLifetimeOffset is the start of the 4-byte\n+ // Lifetime field within an NDPRecursiveDNSServer.\n+ ndpRecursiveDNSServerLifetimeOffset = 2\n+\n+ // ndpRecursiveDNSServerAddressesOffset is the start of the addresses\n+ // for IPv6 Recursive DNS Servers within an NDPRecursiveDNSServer.\n+ ndpRecursiveDNSServerAddressesOffset = 6\n+\n+ // minNDPRecursiveDNSServerLength is the minimum NDP Recursive DNS\n+ // Server option's length field value when it contains at least one\n+ // IPv6 address.\n+ minNDPRecursiveDNSServerLength = 3\n+\n// lengthByteUnits is the multiplier factor for the Length field of an\n// NDP option. That is, the length field for NDP options is in units of\n// 8 octets, as per RFC 4861 section 4.6.\n@@ -92,13 +109,13 @@ const (\n)\nvar (\n- // NDPPrefixInformationInfiniteLifetime is a value that represents\n+ // NDPInfiniteLifetime is a value that represents\n// infinity for the Valid and Preferred Lifetime fields in a NDP Prefix\n// Information option. Its value is (2^32 - 1)s = 4294967295s\n//\n// This is a variable instead of a constant so that tests can change\n// this value to a smaller value. It should only be modified by tests.\n- NDPPrefixInformationInfiniteLifetime = time.Second * 4294967295\n+ NDPInfiniteLifetime = time.Second * 4294967295\n)\n// NDPOptionIterator is an iterator of NDPOption.\n@@ -118,6 +135,7 @@ var (\nErrNDPOptBufExhausted = errors.New(\"Buffer unexpectedly exhausted\")\nErrNDPOptZeroLength = errors.New(\"NDP option has zero-valued Length field\")\nErrNDPOptMalformedBody = errors.New(\"NDP option has a malformed body\")\n+ ErrNDPInvalidLength = errors.New(\"NDP option's Length value is invalid as per relevant RFC\")\n)\n// Next returns the next element in the backing NDPOptions, or true if we are\n@@ -182,6 +200,22 @@ func (i *NDPOptionIterator) Next() (NDPOption, bool, error) {\n}\nreturn NDPPrefixInformation(body), false, nil\n+\n+ case NDPRecursiveDNSServerOptionType:\n+ // RFC 8106 section 5.3.1 outlines that the RDNSS option\n+ // must have a minimum length of 3 so it contains at\n+ // least one IPv6 address.\n+ if l < minNDPRecursiveDNSServerLength {\n+ return nil, true, ErrNDPInvalidLength\n+ }\n+\n+ opt := NDPRecursiveDNSServer(body)\n+ if len(opt.Addresses()) == 0 {\n+ return nil, true, ErrNDPOptMalformedBody\n+ }\n+\n+ return opt, false, nil\n+\ndefault:\n// We do not yet recognize the option, just skip for\n// now. This is okay because RFC 4861 allows us to\n@@ -434,7 +468,7 @@ func (o NDPPrefixInformation) AutonomousAddressConfigurationFlag() bool {\n//\n// Note, a value of 0 implies the prefix should not be considered as on-link,\n// and a value of infinity/forever is represented by\n-// NDPPrefixInformationInfiniteLifetime.\n+// NDPInfiniteLifetime.\nfunc (o NDPPrefixInformation) ValidLifetime() time.Duration {\n// The field is the time in seconds, as per RFC 4861 section 4.6.2.\nreturn time.Second * time.Duration(binary.BigEndian.Uint32(o[ndpPrefixInformationValidLifetimeOffset:]))\n@@ -447,7 +481,7 @@ func (o NDPPrefixInformation) ValidLifetime() time.Duration {\n//\n// Note, a value of 0 implies that addresses generated from the prefix should\n// no longer remain preferred, and a value of infinity is represented by\n-// NDPPrefixInformationInfiniteLifetime.\n+// NDPInfiniteLifetime.\n//\n// Also note that the value of this field MUST NOT exceed the Valid Lifetime\n// field to avoid preferring addresses that are no longer valid, for the\n@@ -476,3 +510,79 @@ func (o NDPPrefixInformation) Subnet() tcpip.Subnet {\n}\nreturn addrWithPrefix.Subnet()\n}\n+\n+// NDPRecursiveDNSServer is the NDP Recursive DNS Server option, as defined by\n+// RFC 8106 section 5.1.\n+//\n+// To make sure that the option meets its minimum length and does not end in the\n+// middle of a DNS server's IPv6 address, the length of a valid\n+// NDPRecursiveDNSServer must meet the following constraint:\n+// (Length - ndpRecursiveDNSServerAddressesOffset) % IPv6AddressSize == 0\n+type NDPRecursiveDNSServer []byte\n+\n+// Type returns the type of an NDP Recursive DNS Server option.\n+//\n+// Type implements NDPOption.Type.\n+func (NDPRecursiveDNSServer) Type() uint8 {\n+ return NDPRecursiveDNSServerOptionType\n+}\n+\n+// Length implements NDPOption.Length.\n+func (o NDPRecursiveDNSServer) Length() int {\n+ return len(o)\n+}\n+\n+// serializeInto implements NDPOption.serializeInto.\n+func (o NDPRecursiveDNSServer) serializeInto(b []byte) int {\n+ used := copy(b, o)\n+\n+ // Zero out the reserved bytes that are before the Lifetime field.\n+ for i := 0; i < ndpRecursiveDNSServerLifetimeOffset; i++ {\n+ b[i] = 0\n+ }\n+\n+ return used\n+}\n+\n+// Lifetime returns the length of time that the DNS server addresses\n+// in this option may be used for name resolution.\n+//\n+// Note, a value of 0 implies the addresses should no longer be used,\n+// and a value of infinity/forever is represented by NDPInfiniteLifetime.\n+//\n+// Lifetime may panic if o does not have enough bytes to hold the Lifetime\n+// field.\n+func (o NDPRecursiveDNSServer) Lifetime() time.Duration {\n+ // The field is the time in seconds, as per RFC 8106 section 5.1.\n+ return time.Second * time.Duration(binary.BigEndian.Uint32(o[ndpRecursiveDNSServerLifetimeOffset:]))\n+}\n+\n+// Addresses returns the recursive DNS server IPv6 addresses that may be\n+// used for name resolution.\n+//\n+// Note, some of the addresses returned MAY be link-local addresses.\n+//\n+// Addresses may panic if o does not hold valid IPv6 addresses.\n+func (o NDPRecursiveDNSServer) Addresses() []tcpip.Address {\n+ l := len(o)\n+ if l < ndpRecursiveDNSServerAddressesOffset {\n+ return nil\n+ }\n+\n+ l -= ndpRecursiveDNSServerAddressesOffset\n+ if l%IPv6AddressSize != 0 {\n+ return nil\n+ }\n+\n+ buf := o[ndpRecursiveDNSServerAddressesOffset:]\n+ var addrs []tcpip.Address\n+ for len(buf) > 0 {\n+ addr := tcpip.Address(buf[:IPv6AddressSize])\n+ if !IsV6UnicastAddress(addr) {\n+ return nil\n+ }\n+ addrs = append(addrs, addr)\n+ buf = buf[IPv6AddressSize:]\n+ }\n+ return addrs\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/ndp_test.go",
"new_path": "pkg/tcpip/header/ndp_test.go",
"diff": "@@ -19,6 +19,7 @@ import (\n\"testing\"\n\"time\"\n+ \"github.com/google/go-cmp/cmp\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n)\n@@ -369,6 +370,175 @@ func TestNDPPrefixInformationOption(t *testing.T) {\n}\n}\n+func TestNDPRecursiveDNSServerOptionSerialize(t *testing.T) {\n+ b := []byte{\n+ 9, 8,\n+ 1, 2, 4, 8,\n+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n+ }\n+ targetBuf := []byte{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}\n+ expected := []byte{\n+ 25, 3, 0, 0,\n+ 1, 2, 4, 8,\n+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n+ }\n+ opts := NDPOptions(targetBuf)\n+ serializer := NDPOptionsSerializer{\n+ NDPRecursiveDNSServer(b),\n+ }\n+ if got, want := opts.Serialize(serializer), len(expected); got != want {\n+ t.Errorf(\"got Serialize = %d, want = %d\", got, want)\n+ }\n+ if !bytes.Equal(targetBuf, expected) {\n+ t.Fatalf(\"got targetBuf = %x, want = %x\", targetBuf, expected)\n+ }\n+\n+ it, err := opts.Iter(true)\n+ if err != nil {\n+ t.Fatalf(\"got Iter = (_, %s), want = (_, nil)\", err)\n+ }\n+\n+ next, done, err := it.Next()\n+ if err != nil {\n+ t.Fatalf(\"got Next = (_, _, %s), want = (_, _, nil)\", err)\n+ }\n+ if done {\n+ t.Fatal(\"got Next = (_, true, _), want = (_, false, _)\")\n+ }\n+ if got := next.Type(); got != NDPRecursiveDNSServerOptionType {\n+ t.Errorf(\"got Type = %d, want = %d\", got, NDPRecursiveDNSServerOptionType)\n+ }\n+\n+ opt, ok := next.(NDPRecursiveDNSServer)\n+ if !ok {\n+ t.Fatalf(\"next (type = %T) cannot be casted to an NDPRecursiveDNSServer\", next)\n+ }\n+ if got := opt.Type(); got != 25 {\n+ t.Errorf(\"got Type = %d, want = 31\", got)\n+ }\n+ if got := opt.Length(); got != 22 {\n+ t.Errorf(\"got Length = %d, want = 22\", got)\n+ }\n+ if got, want := opt.Lifetime(), 16909320*time.Second; got != want {\n+ t.Errorf(\"got Lifetime = %s, want = %s\", got, want)\n+ }\n+ want := []tcpip.Address{\n+ \"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\",\n+ }\n+ if got := opt.Addresses(); !cmp.Equal(got, want) {\n+ t.Errorf(\"got Addresses = %v, want = %v\", got, want)\n+ }\n+\n+ // Iterator should not return anything else.\n+ next, done, err = it.Next()\n+ if err != nil {\n+ t.Errorf(\"got Next = (_, _, %s), want = (_, _, nil)\", err)\n+ }\n+ if !done {\n+ t.Error(\"got Next = (_, false, _), want = (_, true, _)\")\n+ }\n+ if next != nil {\n+ t.Errorf(\"got Next = (%x, _, _), want = (nil, _, _)\", next)\n+ }\n+}\n+\n+func TestNDPRecursiveDNSServerOption(t *testing.T) {\n+ tests := []struct {\n+ name string\n+ buf []byte\n+ lifetime time.Duration\n+ addrs []tcpip.Address\n+ }{\n+ {\n+ \"Valid1Addr\",\n+ []byte{\n+ 25, 3, 0, 0,\n+ 0, 0, 0, 0,\n+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n+ },\n+ 0,\n+ []tcpip.Address{\n+ \"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\",\n+ },\n+ },\n+ {\n+ \"Valid2Addr\",\n+ []byte{\n+ 25, 5, 0, 0,\n+ 0, 0, 0, 0,\n+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n+ 17, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16,\n+ },\n+ 0,\n+ []tcpip.Address{\n+ \"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\",\n+ \"\\x11\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x10\",\n+ },\n+ },\n+ {\n+ \"Valid3Addr\",\n+ []byte{\n+ 25, 7, 0, 0,\n+ 0, 0, 0, 0,\n+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n+ 17, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16,\n+ 17, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17,\n+ },\n+ 0,\n+ []tcpip.Address{\n+ \"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\",\n+ \"\\x11\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x10\",\n+ \"\\x11\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x11\",\n+ },\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ opts := NDPOptions(test.buf)\n+ it, err := opts.Iter(true)\n+ if err != nil {\n+ t.Fatalf(\"got Iter = (_, %s), want = (_, nil)\", err)\n+ }\n+\n+ // Iterator should get our option.\n+ next, done, err := it.Next()\n+ if err != nil {\n+ t.Fatalf(\"got Next = (_, _, %s), want = (_, _, nil)\", err)\n+ }\n+ if done {\n+ t.Fatal(\"got Next = (_, true, _), want = (_, false, _)\")\n+ }\n+ if got := next.Type(); got != NDPRecursiveDNSServerOptionType {\n+ t.Fatalf(\"got Type %= %d, want = %d\", got, NDPRecursiveDNSServerOptionType)\n+ }\n+\n+ opt, ok := next.(NDPRecursiveDNSServer)\n+ if !ok {\n+ t.Fatalf(\"next (type = %T) cannot be casted to an NDPRecursiveDNSServer\", next)\n+ }\n+ if got := opt.Lifetime(); got != test.lifetime {\n+ t.Errorf(\"got Lifetime = %d, want = %d\", got, test.lifetime)\n+ }\n+ if got := opt.Addresses(); !cmp.Equal(got, test.addrs) {\n+ t.Errorf(\"got Addresses = %v, want = %v\", got, test.addrs)\n+ }\n+\n+ // Iterator should not return anything else.\n+ next, done, err = it.Next()\n+ if err != nil {\n+ t.Errorf(\"got Next = (_, _, %s), want = (_, _, nil)\", err)\n+ }\n+ if !done {\n+ t.Error(\"got Next = (_, false, _), want = (_, true, _)\")\n+ }\n+ if next != nil {\n+ t.Errorf(\"got Next = (%x, _, _), want = (nil, _, _)\", next)\n+ }\n+ })\n+ }\n+}\n+\n// TestNDPOptionsIterCheck tests that Iter will return false if the NDPOptions\n// the iterator was returned for is malformed.\nfunc TestNDPOptionsIterCheck(t *testing.T) {\n@@ -473,6 +643,51 @@ func TestNDPOptionsIterCheck(t *testing.T) {\n},\nnil,\n},\n+ {\n+ \"InvalidRecursiveDNSServerCutsOffAddress\",\n+ []byte{\n+ 25, 4, 0, 0,\n+ 0, 0, 0, 0,\n+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,\n+ 0, 1, 2, 3, 4, 5, 6, 7,\n+ },\n+ ErrNDPOptMalformedBody,\n+ },\n+ {\n+ \"InvalidRecursiveDNSServerInvalidLengthField\",\n+ []byte{\n+ 25, 2, 0, 0,\n+ 0, 0, 0, 0,\n+ 0, 1, 2, 3, 4, 5, 6, 7, 8,\n+ },\n+ ErrNDPInvalidLength,\n+ },\n+ {\n+ \"RecursiveDNSServerTooSmall\",\n+ []byte{\n+ 25, 1, 0, 0,\n+ 0, 0, 0,\n+ },\n+ ErrNDPOptBufExhausted,\n+ },\n+ {\n+ \"RecursiveDNSServerMulticast\",\n+ []byte{\n+ 25, 3, 0, 0,\n+ 0, 0, 0, 0,\n+ 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,\n+ },\n+ ErrNDPOptMalformedBody,\n+ },\n+ {\n+ \"RecursiveDNSServerUnspecified\",\n+ []byte{\n+ 25, 3, 0, 0,\n+ 0, 0, 0, 0,\n+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n+ },\n+ ErrNDPOptMalformedBody,\n+ },\n}\nfor _, test := range tests {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/ndp.go",
"new_path": "pkg/tcpip/stack/ndp.go",
"diff": "@@ -596,7 +596,7 @@ func (ndp *ndpState) handleRA(ip tcpip.Address, ra header.NDPRouterAdvert) {\n// Update the invalidation timer.\ntimer := prefixState.invalidationTimer\n- if timer == nil && vl >= header.NDPPrefixInformationInfiniteLifetime {\n+ if timer == nil && vl >= header.NDPInfiniteLifetime {\n// Had infinite valid lifetime before and\n// continues to have an invalid lifetime. Do\n// nothing further.\n@@ -615,7 +615,7 @@ func (ndp *ndpState) handleRA(ip tcpip.Address, ra header.NDPRouterAdvert) {\n*prefixState.doNotInvalidate = true\n}\n- if vl >= header.NDPPrefixInformationInfiniteLifetime {\n+ if vl >= header.NDPInfiniteLifetime {\n// Prefix is now valid forever so we don't need\n// an invalidation timer.\nprefixState.invalidationTimer = nil\n@@ -734,7 +734,7 @@ func (ndp *ndpState) rememberOnLinkPrefix(prefix tcpip.Subnet, l time.Duration)\nvar timer *time.Timer\n// Only create a timer if the lifetime is not infinite.\n- if l < header.NDPPrefixInformationInfiniteLifetime {\n+ if l < header.NDPInfiniteLifetime {\ntimer = ndp.prefixInvalidationCallback(prefix, l, &doNotInvalidate)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/ndp_test.go",
"new_path": "pkg/tcpip/stack/ndp_test.go",
"diff": "@@ -1364,10 +1364,10 @@ func TestPrefixDiscoveryWithInfiniteLifetime(t *testing.T) {\n// invalidate the prefix.\nconst testInfiniteLifetimeSeconds = 2\nconst testInfiniteLifetime = testInfiniteLifetimeSeconds * time.Second\n- saved := header.NDPPrefixInformationInfiniteLifetime\n- header.NDPPrefixInformationInfiniteLifetime = testInfiniteLifetime\n+ saved := header.NDPInfiniteLifetime\n+ header.NDPInfiniteLifetime = testInfiniteLifetime\ndefer func() {\n- header.NDPPrefixInformationInfiniteLifetime = saved\n+ header.NDPInfiniteLifetime = saved\n}()\nprefix := tcpip.AddressWithPrefix{\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add a type to represent the NDP Recursive DNS Server option
This change adds a type to represent the NDP Recursive DNS Server option, as
defined by RFC 8106 section 5.1.
PiperOrigin-RevId: 284005493 |
259,885 | 05.12.2019 12:56:31 | 28,800 | 02258607f97353932d56bfde9274d50dda18e374 | Add vfs.CheckSetStat() and its dependencies. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/permissions.go",
"new_path": "pkg/sentry/vfs/permissions.go",
"diff": "@@ -119,3 +119,65 @@ func MayWriteFileWithOpenFlags(flags uint32) bool {\nreturn false\n}\n}\n+\n+// CheckSetStat checks that creds has permission to change the metadata of a\n+// file with the given permissions, UID, and GID as specified by stat, subject\n+// to the rules of Linux's fs/attr.c:setattr_prepare().\n+func CheckSetStat(creds *auth.Credentials, stat *linux.Statx, mode uint16, kuid auth.KUID, kgid auth.KGID) error {\n+ if stat.Mask&linux.STATX_MODE != 0 {\n+ if !CanActAsOwner(creds, kuid) {\n+ return syserror.EPERM\n+ }\n+ // TODO(b/30815691): \"If the calling process is not privileged (Linux:\n+ // does not have the CAP_FSETID capability), and the group of the file\n+ // does not match the effective group ID of the process or one of its\n+ // supplementary group IDs, the S_ISGID bit will be turned off, but\n+ // this will not cause an error to be returned.\" - chmod(2)\n+ }\n+ if stat.Mask&linux.STATX_UID != 0 {\n+ if !((creds.EffectiveKUID == kuid && auth.KUID(stat.UID) == kuid) ||\n+ HasCapabilityOnFile(creds, linux.CAP_CHOWN, kuid, kgid)) {\n+ return syserror.EPERM\n+ }\n+ }\n+ if stat.Mask&linux.STATX_GID != 0 {\n+ if !((creds.EffectiveKUID == kuid && creds.InGroup(auth.KGID(stat.GID))) ||\n+ HasCapabilityOnFile(creds, linux.CAP_CHOWN, kuid, kgid)) {\n+ return syserror.EPERM\n+ }\n+ }\n+ if stat.Mask&(linux.STATX_ATIME|linux.STATX_MTIME|linux.STATX_CTIME) != 0 {\n+ if !CanActAsOwner(creds, kuid) {\n+ if (stat.Mask&linux.STATX_ATIME != 0 && stat.Atime.Nsec != linux.UTIME_NOW) ||\n+ (stat.Mask&linux.STATX_MTIME != 0 && stat.Mtime.Nsec != linux.UTIME_NOW) ||\n+ (stat.Mask&linux.STATX_CTIME != 0 && stat.Ctime.Nsec != linux.UTIME_NOW) {\n+ return syserror.EPERM\n+ }\n+ // isDir is irrelevant in the following call to\n+ // GenericCheckPermissions since ats == MayWrite means that\n+ // CAP_DAC_READ_SEARCH does not apply, and CAP_DAC_OVERRIDE\n+ // applies, regardless of isDir.\n+ if err := GenericCheckPermissions(creds, MayWrite, false /* isDir */, mode, kuid, kgid); err != nil {\n+ return err\n+ }\n+ }\n+ }\n+ return nil\n+}\n+\n+// CanActAsOwner returns true if creds can act as the owner of a file with the\n+// given owning UID, consistent with Linux's\n+// fs/inode.c:inode_owner_or_capable().\n+func CanActAsOwner(creds *auth.Credentials, kuid auth.KUID) bool {\n+ if creds.EffectiveKUID == kuid {\n+ return true\n+ }\n+ return creds.HasCapability(linux.CAP_FOWNER) && creds.UserNamespace.MapFromKUID(kuid).Ok()\n+}\n+\n+// HasCapabilityOnFile returns true if creds has the given capability with\n+// respect to a file with the given owning UID and GID, consistent with Linux's\n+// kernel/capability.c:capable_wrt_inode_uidgid().\n+func HasCapabilityOnFile(creds *auth.Credentials, cp linux.Capability, kuid auth.KUID, kgid auth.KGID) bool {\n+ return creds.HasCapability(cp) && creds.UserNamespace.MapFromKUID(kuid).Ok() && creds.UserNamespace.MapFromKGID(kgid).Ok()\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add vfs.CheckSetStat() and its dependencies.
PiperOrigin-RevId: 284033820 |
259,975 | 05.12.2019 13:22:31 | 28,800 | 0a32c0235744191947a6bf890031026e06788837 | Create correct file for /proc/[pid]/task/[tid]/io | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/task.go",
"new_path": "pkg/sentry/fs/proc/task.go",
"diff": "@@ -67,7 +67,7 @@ type taskDir struct {\nvar _ fs.InodeOperations = (*taskDir)(nil)\n// newTaskDir creates a new proc task entry.\n-func (p *proc) newTaskDir(t *kernel.Task, msrc *fs.MountSource, showSubtasks bool) *fs.Inode {\n+func (p *proc) newTaskDir(t *kernel.Task, msrc *fs.MountSource, isThreadGroup bool) *fs.Inode {\ncontents := map[string]*fs.Inode{\n\"auxv\": newAuxvec(t, msrc),\n\"cmdline\": newExecArgInode(t, msrc, cmdlineExecArg),\n@@ -77,19 +77,18 @@ func (p *proc) newTaskDir(t *kernel.Task, msrc *fs.MountSource, showSubtasks boo\n\"fd\": newFdDir(t, msrc),\n\"fdinfo\": newFdInfoDir(t, msrc),\n\"gid_map\": newGIDMap(t, msrc),\n- // FIXME(b/123511468): create the correct io file for threads.\n- \"io\": newIO(t, msrc),\n+ \"io\": newIO(t, msrc, isThreadGroup),\n\"maps\": newMaps(t, msrc),\n\"mountinfo\": seqfile.NewSeqFileInode(t, &mountInfoFile{t: t}, msrc),\n\"mounts\": seqfile.NewSeqFileInode(t, &mountsFile{t: t}, msrc),\n\"ns\": newNamespaceDir(t, msrc),\n\"smaps\": newSmaps(t, msrc),\n- \"stat\": newTaskStat(t, msrc, showSubtasks, p.pidns),\n+ \"stat\": newTaskStat(t, msrc, isThreadGroup, p.pidns),\n\"statm\": newStatm(t, msrc),\n\"status\": newStatus(t, msrc, p.pidns),\n\"uid_map\": newUIDMap(t, msrc),\n}\n- if showSubtasks {\n+ if isThreadGroup {\ncontents[\"task\"] = p.newSubtasks(t, msrc)\n}\nif len(p.cgroupControllers) > 0 {\n@@ -619,9 +618,12 @@ type ioData struct {\nioUsage\n}\n-func newIO(t *kernel.Task, msrc *fs.MountSource) *fs.Inode {\n+func newIO(t *kernel.Task, msrc *fs.MountSource, isThreadGroup bool) *fs.Inode {\n+ if isThreadGroup {\nreturn newProcInode(t, seqfile.NewSeqFile(t, &ioData{t.ThreadGroup()}), msrc, fs.SpecialFile, t)\n}\n+ return newProcInode(t, seqfile.NewSeqFile(t, &ioData{t}), msrc, fs.SpecialFile, t)\n+}\n// NeedsUpdate returns whether the generation is old or not.\nfunc (i *ioData) NeedsUpdate(generation int64) bool {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/proc.cc",
"new_path": "test/syscalls/linux/proc.cc",
"diff": "#include <map>\n#include <memory>\n#include <ostream>\n+#include <regex>\n#include <string>\n#include <unordered_set>\n#include <utility>\n#include \"absl/strings/str_split.h\"\n#include \"absl/strings/string_view.h\"\n#include \"absl/synchronization/mutex.h\"\n+#include \"absl/synchronization/notification.h\"\n#include \"absl/time/clock.h\"\n#include \"absl/time/time.h\"\n#include \"test/util/capability_util.h\"\n@@ -1988,6 +1990,44 @@ TEST(Proc, GetdentsEnoent) {\nSyscallFailsWithErrno(ENOENT));\n}\n+void CheckSyscwFromIOFile(const std::string& path, const std::string& regex) {\n+ std::string output;\n+ ASSERT_NO_ERRNO(GetContents(path, &output));\n+ ASSERT_THAT(output, ContainsRegex(absl::StrCat(\"syscw:\\\\s+\", regex, \"\\n\")));\n+}\n+\n+// Checks that there is variable accounting of IO between threads/tasks.\n+TEST(Proc, PidTidIOAccounting) {\n+ absl::Notification notification;\n+\n+ // Run a thread with a bunch of writes. Check that io account records exactly\n+ // the number of write calls. File open/close is there to prevent buffering.\n+ ScopedThread writer([¬ification] {\n+ const int num_writes = 100;\n+ for (int i = 0; i < num_writes; i++) {\n+ auto path = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n+ ASSERT_NO_ERRNO(SetContents(path.path(), \"a\"));\n+ }\n+ notification.Notify();\n+ const std::string& writer_dir =\n+ absl::StrCat(\"/proc/\", getpid(), \"/task/\", gettid(), \"/io\");\n+\n+ CheckSyscwFromIOFile(writer_dir, std::to_string(num_writes));\n+ });\n+\n+ // Run a thread and do no writes. Check that no writes are recorded.\n+ ScopedThread noop([¬ification] {\n+ notification.WaitForNotification();\n+ const std::string& noop_dir =\n+ absl::StrCat(\"/proc/\", getpid(), \"/task/\", gettid(), \"/io\");\n+\n+ CheckSyscwFromIOFile(noop_dir, \"0\");\n+ });\n+\n+ writer.Join();\n+ noop.Join();\n+}\n+\n} // namespace\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Create correct file for /proc/[pid]/task/[tid]/io
PiperOrigin-RevId: 284038840 |
259,884 | 06.12.2019 06:39:35 | -32,400 | 757adfa287c17d925aec7976a86986bd5b52229c | Add docs for Kubernetes Runtime Class.
Adds doc to explicitly create the Kubernetes RuntimeClass object needed
to use the shim via the Kubernetes API. | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -13,8 +13,8 @@ gvisor-containerd-shim is a containerd shim for [gVisor](https://github.com/goog\n## Installation\n- [Untrusted Workload Quick Start (containerd >=1.1)](docs/untrusted-workload-quickstart.md)\n-- [Runtime Handler Quick Start (containerd >=1.2)](docs/runtime-handler-quickstart.md)\n-- [Runtime Handler Quick Start (shim v2) (containerd >=1.2)](docs/runtime-handler-shim-v2-quickstart.md)\n+- [Runtime Handler/RuntimeClass Quick Start (containerd >=1.2)](docs/runtime-handler-quickstart.md)\n+- [Runtime Handler/RuntimeClass Quick Start (shim v2) (containerd >=1.2)](docs/runtime-handler-shim-v2-quickstart.md)\n# Contributing\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/runtime-handler-quickstart.md",
"new_path": "docs/runtime-handler-quickstart.md",
"diff": "@@ -204,3 +204,48 @@ sudo crictl inspect ${CONTAINER_ID}\nsudo crictl exec ${CONTAINER_ID} dmesg | grep -i gvisor\n}\n```\n+\n+### Set up the Kubernetes Runtime Class\n+\n+1. Install the Runtime Class for gVisor\n+\n+[embedmd]:# (../test/e2e/runtimeclass-install.sh shell /{ # Step 1/ /^}/)\n+```shell\n+{ # Step 1: Install a RuntimeClass\n+cat <<EOF | kubectl apply -f -\n+apiVersion: node.k8s.io/v1beta1\n+kind: RuntimeClass\n+metadata:\n+ name: gvisor\n+handler: runsc\n+EOF\n+}\n+```\n+\n+2. Create a Pod with the gVisor Runtime Class\n+\n+[embedmd]:# (../test/e2e/runtimeclass-install.sh shell /{ # Step 2/ /^}/)\n+```shell\n+{ # Step 2: Create a pod\n+cat <<EOF | kubectl apply -f -\n+apiVersion: v1\n+kind: Pod\n+metadata:\n+ name: nginx-gvisor\n+spec:\n+ runtimeClassName: gvisor\n+ containers:\n+ - name: nginx\n+ image: nginx\n+EOF\n+}\n+```\n+\n+3. Verify that the Pod is running\n+\n+[embedmd]:# (../test/e2e/runtimeclass-install.sh shell /{ # Step 3/ /^}/)\n+```shell\n+{ # Step 3: Get the pod\n+kubectl get pod nginx-gvisor -o wide\n+}\n+```\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/runtime-handler-shim-v2-quickstart.md",
"new_path": "docs/runtime-handler-shim-v2-quickstart.md",
"diff": "@@ -185,3 +185,48 @@ sudo crictl inspect ${CONTAINER_ID}\nsudo crictl exec ${CONTAINER_ID} dmesg | grep -i gvisor\n}\n```\n+\n+### Set up the Kubernetes Runtime Class\n+\n+1. Install the Runtime Class for gVisor\n+\n+[embedmd]:# (../test/e2e/runtimeclass-install.sh shell /{ # Step 1/ /^}/)\n+```shell\n+{ # Step 1: Install a RuntimeClass\n+cat <<EOF | kubectl apply -f -\n+apiVersion: node.k8s.io/v1beta1\n+kind: RuntimeClass\n+metadata:\n+ name: gvisor\n+handler: runsc\n+EOF\n+}\n+```\n+\n+2. Create a Pod with the gVisor Runtime Class\n+\n+[embedmd]:# (../test/e2e/runtimeclass-install.sh shell /{ # Step 2/ /^}/)\n+```shell\n+{ # Step 2: Create a pod\n+cat <<EOF | kubectl apply -f -\n+apiVersion: v1\n+kind: Pod\n+metadata:\n+ name: nginx-gvisor\n+spec:\n+ runtimeClassName: gvisor\n+ containers:\n+ - name: nginx\n+ image: nginx\n+EOF\n+}\n+```\n+\n+3. Verify that the Pod is running\n+\n+[embedmd]:# (../test/e2e/runtimeclass-install.sh shell /{ # Step 3/ /^}/)\n+```shell\n+{ # Step 3: Get the pod\n+kubectl get pod nginx-gvisor -o wide\n+}\n+```\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/e2e/runtimeclass-install.sh",
"diff": "+#!/bin/bash\n+\n+# A sample script to test installing a RuntimeClass\n+\n+set -ex\n+\n+{ # Step 1: Install a RuntimeClass\n+cat <<EOF | kubectl apply -f -\n+apiVersion: node.k8s.io/v1beta1\n+kind: RuntimeClass\n+metadata:\n+ name: gvisor\n+handler: runsc\n+EOF\n+}\n+\n+{ # Step 2: Create a pod\n+cat <<EOF | kubectl apply -f -\n+apiVersion: v1\n+kind: Pod\n+metadata:\n+ name: nginx-gvisor\n+spec:\n+ runtimeClassName: gvisor\n+ containers:\n+ - name: nginx\n+ image: nginx\n+EOF\n+}\n+\n+{ # Step 3: Get the pod\n+kubectl get pod nginx-gvisor -o wide\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add docs for Kubernetes Runtime Class. (#33)
Adds doc to explicitly create the Kubernetes RuntimeClass object needed
to use the shim via the Kubernetes API. |
259,992 | 05.12.2019 16:36:24 | 28,800 | e83ba107367ac3a25725d8857c2ba3cc9adbeb71 | Make EmptyDir annotations compliant with K8s and OCI
Change annotation from 'gvisor.dev/spec/mount/NAME/share',
which is invalid because it has more than one '/', to
'dev.gvisor.spec.mount.NAME.share'. | [
{
"change_type": "MODIFY",
"old_path": "pkg/v1/utils/volumes.go",
"new_path": "pkg/v1/utils/volumes.go",
"diff": "@@ -29,20 +29,20 @@ import (\n\"github.com/sirupsen/logrus\"\n)\n-const volumeKeyPrefix = \"gvisor.dev/spec/mount/\"\n+const volumeKeyPrefix = \"dev.gvisor.spec.mount.\"\nvar kubeletPodsDir = \"/var/lib/kubelet/pods\"\n// volumeName gets volume name from volume annotation key, example:\n-// gvisor.dev/spec/mount/NAME/share\n+// dev.gvisor.spec.mount.NAME.share\nfunc volumeName(k string) string {\n- return strings.SplitN(strings.TrimPrefix(k, volumeKeyPrefix), \"/\", 2)[0]\n+ return strings.SplitN(strings.TrimPrefix(k, volumeKeyPrefix), \".\", 2)[0]\n}\n// volumeFieldName gets volume field name from volume annotation key, example:\n-// `type` is the field of gvisor.dev/spec/mount/NAME/type\n+// `type` is the field of dev.gvisor.spec.mount.NAME.type\nfunc volumeFieldName(k string) string {\n- parts := strings.Split(strings.TrimPrefix(k, volumeKeyPrefix), \"/\")\n+ parts := strings.Split(strings.TrimPrefix(k, volumeKeyPrefix), \".\")\nreturn parts[len(parts)-1]\n}\n@@ -69,7 +69,7 @@ func isVolumeKey(k string) bool {\n// volumeSourceKey constructs the annotation key for volume source.\nfunc volumeSourceKey(volume string) string {\n- return volumeKeyPrefix + volume + \"/source\"\n+ return volumeKeyPrefix + volume + \".source\"\n}\n// volumePath searches the volume path in the kubelet pod directory.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/v1/utils/volumes_test.go",
"new_path": "pkg/v1/utils/volumes_test.go",
"diff": "@@ -62,19 +62,19 @@ func TestUpdateVolumeAnnotations(t *testing.T) {\nAnnotations: map[string]string{\nannotations.SandboxLogDir: testLogDirPath,\nannotations.ContainerType: annotations.ContainerTypeSandbox,\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/share\": \"pod\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/type\": \"tmpfs\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/options\": \"ro\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".share\": \"pod\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".type\": \"tmpfs\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".options\": \"ro\",\n},\n},\nexpected: &specs.Spec{\nAnnotations: map[string]string{\nannotations.SandboxLogDir: testLogDirPath,\nannotations.ContainerType: annotations.ContainerTypeSandbox,\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/share\": \"pod\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/type\": \"tmpfs\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/options\": \"ro\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/source\": testVolumePath,\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".share\": \"pod\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".type\": \"tmpfs\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".options\": \"ro\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".source\": testVolumePath,\n},\n},\nexpectUpdate: true,\n@@ -85,19 +85,19 @@ func TestUpdateVolumeAnnotations(t *testing.T) {\nAnnotations: map[string]string{\nannotations.SandboxLogDir: testLegacyLogDirPath,\nannotations.ContainerType: annotations.ContainerTypeSandbox,\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/share\": \"pod\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/type\": \"tmpfs\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/options\": \"ro\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".share\": \"pod\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".type\": \"tmpfs\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".options\": \"ro\",\n},\n},\nexpected: &specs.Spec{\nAnnotations: map[string]string{\nannotations.SandboxLogDir: testLegacyLogDirPath,\nannotations.ContainerType: annotations.ContainerTypeSandbox,\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/share\": \"pod\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/type\": \"tmpfs\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/options\": \"ro\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/source\": testVolumePath,\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".share\": \"pod\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".type\": \"tmpfs\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".options\": \"ro\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".source\": testVolumePath,\n},\n},\nexpectUpdate: true,\n@@ -121,9 +121,9 @@ func TestUpdateVolumeAnnotations(t *testing.T) {\n},\nAnnotations: map[string]string{\nannotations.ContainerType: annotations.ContainerTypeContainer,\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/share\": \"pod\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/type\": \"tmpfs\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/options\": \"ro\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".share\": \"pod\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".type\": \"tmpfs\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".options\": \"ro\",\n},\n},\nexpected: &specs.Spec{\n@@ -143,9 +143,9 @@ func TestUpdateVolumeAnnotations(t *testing.T) {\n},\nAnnotations: map[string]string{\nannotations.ContainerType: annotations.ContainerTypeContainer,\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/share\": \"pod\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/type\": \"tmpfs\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/options\": \"ro\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".share\": \"pod\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".type\": \"tmpfs\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".options\": \"ro\",\n},\n},\nexpectUpdate: true,\n@@ -163,9 +163,9 @@ func TestUpdateVolumeAnnotations(t *testing.T) {\n},\nAnnotations: map[string]string{\nannotations.ContainerType: annotations.ContainerTypeContainer,\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/share\": \"container\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/type\": \"bind\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/options\": \"ro\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".share\": \"container\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".type\": \"bind\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".options\": \"ro\",\n},\n},\nexpected: &specs.Spec{\n@@ -179,9 +179,9 @@ func TestUpdateVolumeAnnotations(t *testing.T) {\n},\nAnnotations: map[string]string{\nannotations.ContainerType: annotations.ContainerTypeContainer,\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/share\": \"container\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/type\": \"bind\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/options\": \"ro\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".share\": \"container\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".type\": \"bind\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".options\": \"ro\",\n},\n},\nexpectUpdate: true,\n@@ -191,17 +191,17 @@ func TestUpdateVolumeAnnotations(t *testing.T) {\nspec: &specs.Spec{\nAnnotations: map[string]string{\nannotations.ContainerType: annotations.ContainerTypeSandbox,\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/share\": \"pod\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/type\": \"tmpfs\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/options\": \"ro\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".share\": \"pod\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".type\": \"tmpfs\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".options\": \"ro\",\n},\n},\nexpected: &specs.Spec{\nAnnotations: map[string]string{\nannotations.ContainerType: annotations.ContainerTypeSandbox,\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/share\": \"pod\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/type\": \"tmpfs\",\n- \"gvisor.dev/spec/mount/\" + testVolumeName + \"/options\": \"ro\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".share\": \"pod\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".type\": \"tmpfs\",\n+ \"dev.gvisor.spec.mount.\" + testVolumeName + \".options\": \"ro\",\n},\n},\n},\n@@ -211,9 +211,9 @@ func TestUpdateVolumeAnnotations(t *testing.T) {\nAnnotations: map[string]string{\nannotations.SandboxLogDir: testLogDirPath,\nannotations.ContainerType: annotations.ContainerTypeSandbox,\n- \"gvisor.dev/spec/mount/notexist/share\": \"pod\",\n- \"gvisor.dev/spec/mount/notexist/type\": \"tmpfs\",\n- \"gvisor.dev/spec/mount/notexist/options\": \"ro\",\n+ \"dev.gvisor.spec.mount.notexist.share\": \"pod\",\n+ \"dev.gvisor.spec.mount.notexist.type\": \"tmpfs\",\n+ \"dev.gvisor.spec.mount.notexist.options\": \"ro\",\n},\n},\nexpectErr: true,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Make EmptyDir annotations compliant with K8s and OCI (#44)
Change annotation from 'gvisor.dev/spec/mount/NAME/share',
which is invalid because it has more than one '/', to
'dev.gvisor.spec.mount.NAME.share'. |
259,854 | 05.12.2019 17:27:15 | 28,800 | 13f0f6069af4d49e236cbee4f0284c190784db37 | Implement F_GETOWN_EX and F_SETOWN_EX.
Some versions of glibc will convert F_GETOWN fcntl(2) calls into F_GETOWN_EX in
some cases. | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/fcntl.go",
"new_path": "pkg/abi/linux/fcntl.go",
"diff": "@@ -16,15 +16,17 @@ package linux\n// Commands from linux/fcntl.h.\nconst (\n- F_DUPFD = 0x0\n- F_GETFD = 0x1\n- F_SETFD = 0x2\n- F_GETFL = 0x3\n- F_SETFL = 0x4\n- F_SETLK = 0x6\n- F_SETLKW = 0x7\n- F_SETOWN = 0x8\n- F_GETOWN = 0x9\n+ F_DUPFD = 0\n+ F_GETFD = 1\n+ F_SETFD = 2\n+ F_GETFL = 3\n+ F_SETFL = 4\n+ F_SETLK = 6\n+ F_SETLKW = 7\n+ F_SETOWN = 8\n+ F_GETOWN = 9\n+ F_SETOWN_EX = 15\n+ F_GETOWN_EX = 16\nF_DUPFD_CLOEXEC = 1024 + 6\nF_SETPIPE_SZ = 1024 + 7\nF_GETPIPE_SZ = 1024 + 8\n@@ -32,9 +34,9 @@ const (\n// Commands for F_SETLK.\nconst (\n- F_RDLCK = 0x0\n- F_WRLCK = 0x1\n- F_UNLCK = 0x2\n+ F_RDLCK = 0\n+ F_WRLCK = 1\n+ F_UNLCK = 2\n)\n// Flags for fcntl.\n@@ -42,7 +44,7 @@ const (\nFD_CLOEXEC = 00000001\n)\n-// Lock structure for F_SETLK.\n+// Flock is the lock structure for F_SETLK.\ntype Flock struct {\nType int16\nWhence int16\n@@ -52,3 +54,16 @@ type Flock struct {\nPid int32\n_ [4]byte\n}\n+\n+// Flags for F_SETOWN_EX and F_GETOWN_EX.\n+const (\n+ F_OWNER_TID = 0\n+ F_OWNER_PID = 1\n+ F_OWNER_PGRP = 2\n+)\n+\n+// FOwnerEx is the owner structure for F_SETOWN_EX and F_GETOWN_EX.\n+type FOwnerEx struct {\n+ Type int32\n+ PID int32\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_file.go",
"new_path": "pkg/sentry/syscalls/linux/sys_file.go",
"diff": "@@ -840,23 +840,40 @@ func Dup3(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallC\nreturn uintptr(newfd), nil, nil\n}\n-func fGetOwn(t *kernel.Task, file *fs.File) int32 {\n+func fGetOwnEx(t *kernel.Task, file *fs.File) linux.FOwnerEx {\nma := file.Async(nil)\nif ma == nil {\n- return 0\n+ return linux.FOwnerEx{}\n}\na := ma.(*fasync.FileAsync)\not, otg, opg := a.Owner()\nswitch {\ncase ot != nil:\n- return int32(t.PIDNamespace().IDOfTask(ot))\n+ return linux.FOwnerEx{\n+ Type: linux.F_OWNER_TID,\n+ PID: int32(t.PIDNamespace().IDOfTask(ot)),\n+ }\ncase otg != nil:\n- return int32(t.PIDNamespace().IDOfThreadGroup(otg))\n+ return linux.FOwnerEx{\n+ Type: linux.F_OWNER_PID,\n+ PID: int32(t.PIDNamespace().IDOfThreadGroup(otg)),\n+ }\ncase opg != nil:\n- return int32(-t.PIDNamespace().IDOfProcessGroup(opg))\n+ return linux.FOwnerEx{\n+ Type: linux.F_OWNER_PGRP,\n+ PID: int32(t.PIDNamespace().IDOfProcessGroup(opg)),\n+ }\ndefault:\n- return 0\n+ return linux.FOwnerEx{}\n+ }\n+}\n+\n+func fGetOwn(t *kernel.Task, file *fs.File) int32 {\n+ owner := fGetOwnEx(t, file)\n+ if owner.Type == linux.F_OWNER_PGRP {\n+ return -owner.PID\n}\n+ return owner.PID\n}\n// fSetOwn sets the file's owner with the semantics of F_SETOWN in Linux.\n@@ -901,11 +918,13 @@ func Fcntl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\nt.FDTable().SetFlags(fd, kernel.FDFlags{\nCloseOnExec: flags&linux.FD_CLOEXEC != 0,\n})\n+ return 0, nil, nil\ncase linux.F_GETFL:\nreturn uintptr(file.Flags().ToLinux()), nil, nil\ncase linux.F_SETFL:\nflags := uint(args[2].Uint())\nfile.SetFlags(linuxToFlags(flags).Settable())\n+ return 0, nil, nil\ncase linux.F_SETLK, linux.F_SETLKW:\n// In Linux the file system can choose to provide lock operations for an inode.\n// Normally pipe and socket types lack lock operations. We diverge and use a heavy\n@@ -1008,6 +1027,44 @@ func Fcntl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\ncase linux.F_SETOWN:\nfSetOwn(t, file, args[2].Int())\nreturn 0, nil, nil\n+ case linux.F_GETOWN_EX:\n+ addr := args[2].Pointer()\n+ owner := fGetOwnEx(t, file)\n+ _, err := t.CopyOut(addr, &owner)\n+ return 0, nil, err\n+ case linux.F_SETOWN_EX:\n+ addr := args[2].Pointer()\n+ var owner linux.FOwnerEx\n+ n, err := t.CopyIn(addr, &owner)\n+ if err != nil {\n+ return 0, nil, err\n+ }\n+ a := file.Async(fasync.New).(*fasync.FileAsync)\n+ switch owner.Type {\n+ case linux.F_OWNER_TID:\n+ task := t.PIDNamespace().TaskWithID(kernel.ThreadID(owner.PID))\n+ if task == nil {\n+ return 0, nil, syserror.ESRCH\n+ }\n+ a.SetOwnerTask(t, task)\n+ return uintptr(n), nil, nil\n+ case linux.F_OWNER_PID:\n+ tg := t.PIDNamespace().ThreadGroupWithID(kernel.ThreadID(owner.PID))\n+ if tg == nil {\n+ return 0, nil, syserror.ESRCH\n+ }\n+ a.SetOwnerThreadGroup(t, tg)\n+ return uintptr(n), nil, nil\n+ case linux.F_OWNER_PGRP:\n+ pg := t.PIDNamespace().ProcessGroupWithID(kernel.ProcessGroupID(owner.PID))\n+ if pg == nil {\n+ return 0, nil, syserror.ESRCH\n+ }\n+ a.SetOwnerProcessGroup(t, pg)\n+ return uintptr(n), nil, nil\n+ default:\n+ return 0, nil, syserror.EINVAL\n+ }\ncase linux.F_GET_SEALS:\nval, err := tmpfs.GetSeals(file.Dirent.Inode)\nreturn uintptr(val), nil, err\n@@ -1035,7 +1092,6 @@ func Fcntl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\n// Everything else is not yet supported.\nreturn 0, nil, syserror.EINVAL\n}\n- return 0, nil, nil\n}\nconst (\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -753,6 +753,7 @@ cc_binary(\n\"//test/util:eventfd_util\",\n\"//test/util:multiprocess_util\",\n\"//test/util:posix_error\",\n+ \"//test/util:save_util\",\n\"//test/util:temp_path\",\n\"//test/util:test_util\",\n\"//test/util:timer_util\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/fcntl.cc",
"new_path": "test/syscalls/linux/fcntl.cc",
"diff": "#include <fcntl.h>\n#include <signal.h>\n+#include <sys/types.h>\n#include <syscall.h>\n#include <unistd.h>\n#include \"test/util/eventfd_util.h\"\n#include \"test/util/multiprocess_util.h\"\n#include \"test/util/posix_error.h\"\n+#include \"test/util/save_util.h\"\n#include \"test/util/temp_path.h\"\n#include \"test/util/test_util.h\"\n#include \"test/util/timer_util.h\"\n@@ -910,8 +912,166 @@ TEST(FcntlTest, GetOwn) {\nFileDescriptor s = ASSERT_NO_ERRNO_AND_VALUE(\nSocket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));\n- ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_GETOWN),\n+ EXPECT_EQ(syscall(__NR_fcntl, s.get(), F_GETOWN), 0);\n+ MaybeSave();\n+}\n+\n+TEST(FcntlTest, GetOwnEx) {\n+ FileDescriptor s = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));\n+\n+ f_owner_ex owner = {};\n+ EXPECT_THAT(syscall(__NR_fcntl, s.get(), F_GETOWN_EX, &owner),\n+ SyscallSucceedsWithValue(0));\n+}\n+\n+TEST(FcntlTest, SetOwnExInvalidType) {\n+ FileDescriptor s = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));\n+\n+ f_owner_ex owner = {};\n+ owner.type = __pid_type(-1);\n+ EXPECT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN_EX, &owner),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\n+TEST(FcntlTest, SetOwnExInvalidTid) {\n+ FileDescriptor s = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));\n+\n+ f_owner_ex owner = {};\n+ owner.type = F_OWNER_TID;\n+ owner.pid = -1;\n+\n+ EXPECT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN_EX, &owner),\n+ SyscallFailsWithErrno(ESRCH));\n+}\n+\n+TEST(FcntlTest, SetOwnExInvalidPid) {\n+ FileDescriptor s = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));\n+\n+ f_owner_ex owner = {};\n+ owner.type = F_OWNER_PID;\n+ owner.pid = -1;\n+\n+ EXPECT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN_EX, &owner),\n+ SyscallFailsWithErrno(ESRCH));\n+}\n+\n+TEST(FcntlTest, SetOwnExInvalidPgrp) {\n+ FileDescriptor s = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));\n+\n+ f_owner_ex owner = {};\n+ owner.type = F_OWNER_PGRP;\n+ owner.pid = -1;\n+\n+ EXPECT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN_EX, &owner),\n+ SyscallFailsWithErrno(ESRCH));\n+}\n+\n+TEST(FcntlTest, SetOwnExTid) {\n+ FileDescriptor s = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));\n+\n+ f_owner_ex owner = {};\n+ owner.type = F_OWNER_TID;\n+ EXPECT_THAT(owner.pid = syscall(__NR_gettid), SyscallSucceeds());\n+\n+ ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN_EX, &owner),\n+ SyscallSucceeds());\n+\n+ EXPECT_EQ(syscall(__NR_fcntl, s.get(), F_GETOWN), owner.pid);\n+ MaybeSave();\n+}\n+\n+TEST(FcntlTest, SetOwnExPid) {\n+ FileDescriptor s = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));\n+\n+ f_owner_ex owner = {};\n+ owner.type = F_OWNER_PID;\n+ EXPECT_THAT(owner.pid = getpid(), SyscallSucceeds());\n+\n+ ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN_EX, &owner),\n+ SyscallSucceeds());\n+\n+ EXPECT_EQ(syscall(__NR_fcntl, s.get(), F_GETOWN), owner.pid);\n+ MaybeSave();\n+}\n+\n+TEST(FcntlTest, SetOwnExPgrp) {\n+ FileDescriptor s = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));\n+\n+ f_owner_ex owner = {};\n+ owner.type = F_OWNER_PGRP;\n+ EXPECT_THAT(owner.pid = getpgrp(), SyscallSucceeds());\n+\n+ ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN_EX, &owner),\n+ SyscallSucceeds());\n+\n+ // NOTE(igudger): I don't understand why, but this is flaky on Linux.\n+ // GetOwnExPgrp (below) does not have this issue.\n+ SKIP_IF(!IsRunningOnGvisor());\n+\n+ EXPECT_EQ(syscall(__NR_fcntl, s.get(), F_GETOWN), -owner.pid);\n+ MaybeSave();\n+}\n+\n+TEST(FcntlTest, GetOwnExTid) {\n+ FileDescriptor s = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));\n+\n+ f_owner_ex set_owner = {};\n+ set_owner.type = F_OWNER_TID;\n+ EXPECT_THAT(set_owner.pid = syscall(__NR_gettid), SyscallSucceeds());\n+\n+ ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN_EX, &set_owner),\n+ SyscallSucceeds());\n+\n+ f_owner_ex got_owner = {};\n+ ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_GETOWN_EX, &got_owner),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(got_owner.type, set_owner.type);\n+ EXPECT_EQ(got_owner.pid, set_owner.pid);\n+}\n+\n+TEST(FcntlTest, GetOwnExPid) {\n+ FileDescriptor s = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));\n+\n+ f_owner_ex set_owner = {};\n+ set_owner.type = F_OWNER_PID;\n+ EXPECT_THAT(set_owner.pid = getpid(), SyscallSucceeds());\n+\n+ ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN_EX, &set_owner),\n+ SyscallSucceeds());\n+\n+ f_owner_ex got_owner = {};\n+ ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_GETOWN_EX, &got_owner),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(got_owner.type, set_owner.type);\n+ EXPECT_EQ(got_owner.pid, set_owner.pid);\n+}\n+\n+TEST(FcntlTest, GetOwnExPgrp) {\n+ FileDescriptor s = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));\n+\n+ f_owner_ex set_owner = {};\n+ set_owner.type = F_OWNER_PGRP;\n+ EXPECT_THAT(set_owner.pid = getpgrp(), SyscallSucceeds());\n+\n+ ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_SETOWN_EX, &set_owner),\n+ SyscallSucceeds());\n+\n+ f_owner_ex got_owner = {};\n+ ASSERT_THAT(syscall(__NR_fcntl, s.get(), F_GETOWN_EX, &got_owner),\nSyscallSucceedsWithValue(0));\n+ EXPECT_EQ(got_owner.type, set_owner.type);\n+ EXPECT_EQ(got_owner.pid, set_owner.pid);\n}\n} // namespace\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/ioctl.cc",
"new_path": "test/syscalls/linux/ioctl.cc",
"diff": "@@ -215,7 +215,8 @@ TEST_F(IoctlTest, FIOASYNCSelfTarget2) {\nauto mask_cleanup =\nASSERT_NO_ERRNO_AND_VALUE(ScopedSignalMask(SIG_UNBLOCK, SIGIO));\n- pid_t pid = getpid();\n+ pid_t pid = -1;\n+ EXPECT_THAT(pid = getpid(), SyscallSucceeds());\nEXPECT_THAT(ioctl(pair->second_fd(), FIOSETOWN, &pid), SyscallSucceeds());\nint set = 1;\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement F_GETOWN_EX and F_SETOWN_EX.
Some versions of glibc will convert F_GETOWN fcntl(2) calls into F_GETOWN_EX in
some cases.
PiperOrigin-RevId: 284089373 |
259,992 | 05.12.2019 17:57:07 | 28,800 | 40035d7d9c18d0467075cdaebe3d26d2dbd2720b | Fix possible race condition destroying container
When the sandbox is destroyed, making URPC calls to destroy the
container will fail. The code was checking if the sandbox was
running before attempting to make the URPC call, but that is racy. | [
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -1004,16 +1004,22 @@ func (s *Sandbox) ChangeLogging(args control.LoggingArgs) error {\n// DestroyContainer destroys the given container. If it is the root container,\n// then the entire sandbox is destroyed.\nfunc (s *Sandbox) DestroyContainer(cid string) error {\n+ if err := s.destroyContainer(cid); err != nil {\n+ // If the sandbox isn't running, the container has already been destroyed,\n+ // ignore the error in this case.\n+ if s.IsRunning() {\n+ return err\n+ }\n+ }\n+ return nil\n+}\n+\n+func (s *Sandbox) destroyContainer(cid string) error {\nif s.IsRootContainer(cid) {\nlog.Debugf(\"Destroying root container %q by destroying sandbox\", cid)\nreturn s.destroy()\n}\n- if !s.IsRunning() {\n- // Sandbox isn't running anymore, container is already destroyed.\n- return nil\n- }\n-\nlog.Debugf(\"Destroying container %q in sandbox %q\", cid, s.ID)\nconn, err := s.sandboxConnect()\nif err != nil {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix possible race condition destroying container
When the sandbox is destroyed, making URPC calls to destroy the
container will fail. The code was checking if the sandbox was
running before attempting to make the URPC call, but that is racy.
PiperOrigin-RevId: 284093764 |
259,881 | 06.12.2019 08:35:18 | 28,800 | f8bb3f79041bf819cdf803c1009a442154692301 | Document ELF PT_LOAD difference from Linux | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/loader/elf.go",
"new_path": "pkg/sentry/loader/elf.go",
"diff": "@@ -408,6 +408,8 @@ func loadParsedELF(ctx context.Context, m *mm.MemoryManager, f *fs.File, info el\nstart = vaddr\n}\nif vaddr < end {\n+ // NOTE(b/37474556): Linux allows out-of-order\n+ // segments, in violation of the spec.\nctx.Infof(\"PT_LOAD headers out-of-order. %#x < %#x\", vaddr, end)\nreturn loadedELF{}, syserror.ENOEXEC\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Document ELF PT_LOAD difference from Linux
PiperOrigin-RevId: 284191345 |
259,860 | 06.12.2019 12:12:27 | 28,800 | b0066217ecd830be1d816d2b4d824f89b278c556 | Add hostinet tests for UDP sockets.
We need to skip a subset of the tests, because of features that hostinet does
not currently support.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -669,6 +669,7 @@ syscall_test(test = \"//test/syscalls/linux:udp_bind_test\")\nsyscall_test(\nsize = \"medium\",\n+ add_hostinet = True,\nshard_count = 10,\ntest = \"//test/syscalls/linux:udp_socket_test\",\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/udp_socket_test_cases.cc",
"new_path": "test/syscalls/linux/udp_socket_test_cases.cc",
"diff": "@@ -656,6 +656,9 @@ TEST_P(UdpSocketTest, SendToAddressOtherThanConnected) {\n}\nTEST_P(UdpSocketTest, ZerolengthWriteAllowed) {\n+ // TODO(gvisor.dev/issue/1202): Hostinet does not support zero length writes.\n+ SKIP_IF(IsRunningWithHostinet());\n+\n// Bind s_ to loopback:TestPort, and connect to loopback:TestPort+1.\nASSERT_THAT(bind(s_, addr_[0], addrlen_), SyscallSucceeds());\nASSERT_THAT(connect(s_, addr_[1], addrlen_), SyscallSucceeds());\n@@ -673,6 +676,9 @@ TEST_P(UdpSocketTest, ZerolengthWriteAllowed) {\n}\nTEST_P(UdpSocketTest, ZerolengthWriteAllowedNonBlockRead) {\n+ // TODO(gvisor.dev/issue/1202): Hostinet does not support zero length writes.\n+ SKIP_IF(IsRunningWithHostinet());\n+\n// Bind s_ to loopback:TestPort, and connect to loopback:TestPort+1.\nASSERT_THAT(bind(s_, addr_[0], addrlen_), SyscallSucceeds());\nASSERT_THAT(connect(s_, addr_[1], addrlen_), SyscallSucceeds());\n@@ -878,6 +884,10 @@ TEST_P(UdpSocketTest, ReadShutdownSameSocketResetsShutdownState) {\n}\nTEST_P(UdpSocketTest, ReadShutdown) {\n+ // TODO(gvisor.dev/issue/1202): Calling recv() after shutdown without\n+ // MSG_DONTWAIT blocks indefinitely.\n+ SKIP_IF(IsRunningWithHostinet());\n+\nchar received[512];\nEXPECT_THAT(recv(s_, received, sizeof(received), MSG_DONTWAIT),\nSyscallFailsWithErrno(EWOULDBLOCK));\n@@ -900,6 +910,10 @@ TEST_P(UdpSocketTest, ReadShutdown) {\n}\nTEST_P(UdpSocketTest, ReadShutdownDifferentThread) {\n+ // TODO(gvisor.dev/issue/1202): Calling recv() after shutdown without\n+ // MSG_DONTWAIT blocks indefinitely.\n+ SKIP_IF(IsRunningWithHostinet());\n+\nchar received[512];\nEXPECT_THAT(recv(s_, received, sizeof(received), MSG_DONTWAIT),\nSyscallFailsWithErrno(EWOULDBLOCK));\n@@ -1189,6 +1203,10 @@ TEST_P(UdpSocketTest, FIONREADZeroLengthWriteShutdown) {\n}\nTEST_P(UdpSocketTest, SoTimestampOffByDefault) {\n+ // TODO(gvisor.dev/issue/1202): SO_TIMESTAMP socket option not supported by\n+ // hostinet.\n+ SKIP_IF(IsRunningWithHostinet());\n+\nint v = -1;\nsocklen_t optlen = sizeof(v);\nASSERT_THAT(getsockopt(s_, SOL_SOCKET, SO_TIMESTAMP, &v, &optlen),\n@@ -1198,6 +1216,10 @@ TEST_P(UdpSocketTest, SoTimestampOffByDefault) {\n}\nTEST_P(UdpSocketTest, SoTimestamp) {\n+ // TODO(gvisor.dev/issue/1202): ioctl() and SO_TIMESTAMP socket option are not\n+ // supported by hostinet.\n+ SKIP_IF(IsRunningWithHostinet());\n+\nASSERT_THAT(bind(s_, addr_[0], addrlen_), SyscallSucceeds());\nASSERT_THAT(connect(t_, addr_[0], addrlen_), SyscallSucceeds());\n@@ -1241,6 +1263,9 @@ TEST_P(UdpSocketTest, WriteShutdownNotConnected) {\n}\nTEST_P(UdpSocketTest, TimestampIoctl) {\n+ // TODO(gvisor.dev/issue/1202): ioctl() is not supported by hostinet.\n+ SKIP_IF(IsRunningWithHostinet());\n+\nASSERT_THAT(bind(s_, addr_[0], addrlen_), SyscallSucceeds());\nASSERT_THAT(connect(t_, addr_[0], addrlen_), SyscallSucceeds());\n@@ -1259,7 +1284,10 @@ TEST_P(UdpSocketTest, TimestampIoctl) {\nASSERT_TRUE(tv.tv_sec != 0 || tv.tv_usec != 0);\n}\n-TEST_P(UdpSocketTest, TimetstampIoctlNothingRead) {\n+TEST_P(UdpSocketTest, TimestampIoctlNothingRead) {\n+ // TODO(gvisor.dev/issue/1202): ioctl() is not supported by hostinet.\n+ SKIP_IF(IsRunningWithHostinet());\n+\nASSERT_THAT(bind(s_, addr_[0], addrlen_), SyscallSucceeds());\nASSERT_THAT(connect(t_, addr_[0], addrlen_), SyscallSucceeds());\n@@ -1270,6 +1298,10 @@ TEST_P(UdpSocketTest, TimetstampIoctlNothingRead) {\n// Test that the timestamp accessed via SIOCGSTAMP is still accessible after\n// SO_TIMESTAMP is enabled and used to retrieve a timestamp.\nTEST_P(UdpSocketTest, TimestampIoctlPersistence) {\n+ // TODO(gvisor.dev/issue/1202): ioctl() and SO_TIMESTAMP socket option are not\n+ // supported by hostinet.\n+ SKIP_IF(IsRunningWithHostinet());\n+\nASSERT_THAT(bind(s_, addr_[0], addrlen_), SyscallSucceeds());\nASSERT_THAT(connect(t_, addr_[0], addrlen_), SyscallSucceeds());\n@@ -1304,7 +1336,6 @@ TEST_P(UdpSocketTest, TimestampIoctlPersistence) {\nmsg.msg_controllen = sizeof(cmsgbuf);\nASSERT_THAT(RetryEINTR(recvmsg)(s_, &msg, 0), SyscallSucceedsWithValue(0));\nstruct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);\n- cmsg = CMSG_FIRSTHDR(&msg);\nASSERT_NE(cmsg, nullptr);\n// The ioctl should return the exact same values as before.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add hostinet tests for UDP sockets.
We need to skip a subset of the tests, because of features that hostinet does
not currently support.
Fixes #1209
PiperOrigin-RevId: 284235911 |
259,992 | 06.12.2019 13:50:12 | 28,800 | ea7a100202f01601fba613a76f106a9a45c817c8 | Make annotations OCI compliant
Changed annotation to follow the standard defined here: | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/fs.go",
"new_path": "runsc/boot/fs.go",
"diff": "@@ -16,7 +16,6 @@ package boot\nimport (\n\"fmt\"\n- \"path\"\n\"path/filepath\"\n\"sort\"\n\"strconv\"\n@@ -52,7 +51,7 @@ const (\nrootDevice = \"9pfs-/\"\n// MountPrefix is the annotation prefix for mount hints.\n- MountPrefix = \"gvisor.dev/spec/mount\"\n+ MountPrefix = \"dev.gvisor.spec.mount.\"\n// Filesystems that runsc supports.\nbind = \"bind\"\n@@ -490,14 +489,15 @@ type podMountHints struct {\nfunc newPodMountHints(spec *specs.Spec) (*podMountHints, error) {\nmnts := make(map[string]*mountHint)\nfor k, v := range spec.Annotations {\n- // Look for 'gvisor.dev/spec/mount' annotations and parse them.\n+ // Look for 'dev.gvisor.spec.mount' annotations and parse them.\nif strings.HasPrefix(k, MountPrefix) {\n- parts := strings.Split(k, \"/\")\n- if len(parts) != 5 {\n+ // Remove the prefix and split the rest.\n+ parts := strings.Split(k[len(MountPrefix):], \".\")\n+ if len(parts) != 2 {\nreturn nil, fmt.Errorf(\"invalid mount annotation: %s=%s\", k, v)\n}\n- name := parts[3]\n- if len(name) == 0 || path.Clean(name) != name {\n+ name := parts[0]\n+ if len(name) == 0 {\nreturn nil, fmt.Errorf(\"invalid mount name: %s\", name)\n}\nmnt := mnts[name]\n@@ -505,7 +505,7 @@ func newPodMountHints(spec *specs.Spec) (*podMountHints, error) {\nmnt = &mountHint{name: name}\nmnts[name] = mnt\n}\n- if err := mnt.setField(parts[4], v); err != nil {\n+ if err := mnt.setField(parts[1], v); err != nil {\nreturn nil, err\n}\n}\n@@ -575,6 +575,11 @@ func newContainerMounter(spec *specs.Spec, goferFDs []int, k *kernel.Kernel, hin\nfunc (c *containerMounter) processHints(conf *Config) error {\nctx := c.k.SupervisorContext()\nfor _, hint := range c.hints.mounts {\n+ // TODO(b/142076984): Only support tmpfs for now. Bind mounts require a\n+ // common gofer to mount all shared volumes.\n+ if hint.mount.Type != tmpfs {\n+ continue\n+ }\nlog.Infof(\"Mounting master of shared mount %q from %q type %q\", hint.name, hint.mount.Source, hint.mount.Type)\ninode, err := c.mountSharedMaster(ctx, conf, hint)\nif err != nil {\n@@ -851,7 +856,7 @@ func (c *containerMounter) mountSubmount(ctx context.Context, conf *Config, mns\nreturn fmt.Errorf(\"mount %q error: %v\", m.Destination, err)\n}\n- log.Infof(\"Mounted %q to %q type %s\", m.Source, m.Destination, m.Type)\n+ log.Infof(\"Mounted %q to %q type: %s, internal-options: %q\", m.Source, m.Destination, m.Type, opts)\nreturn nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/fs_test.go",
"new_path": "runsc/boot/fs_test.go",
"diff": "package boot\nimport (\n- \"path\"\n\"reflect\"\n\"strings\"\n\"testing\"\n@@ -26,19 +25,19 @@ import (\nfunc TestPodMountHintsHappy(t *testing.T) {\nspec := &specs.Spec{\nAnnotations: map[string]string{\n- path.Join(MountPrefix, \"mount1\", \"source\"): \"foo\",\n- path.Join(MountPrefix, \"mount1\", \"type\"): \"tmpfs\",\n- path.Join(MountPrefix, \"mount1\", \"share\"): \"pod\",\n+ MountPrefix + \"mount1.source\": \"foo\",\n+ MountPrefix + \"mount1.type\": \"tmpfs\",\n+ MountPrefix + \"mount1.share\": \"pod\",\n- path.Join(MountPrefix, \"mount2\", \"source\"): \"bar\",\n- path.Join(MountPrefix, \"mount2\", \"type\"): \"bind\",\n- path.Join(MountPrefix, \"mount2\", \"share\"): \"container\",\n- path.Join(MountPrefix, \"mount2\", \"options\"): \"rw,private\",\n+ MountPrefix + \"mount2.source\": \"bar\",\n+ MountPrefix + \"mount2.type\": \"bind\",\n+ MountPrefix + \"mount2.share\": \"container\",\n+ MountPrefix + \"mount2.options\": \"rw,private\",\n},\n}\npodHints, err := newPodMountHints(spec)\nif err != nil {\n- t.Errorf(\"newPodMountHints failed: %v\", err)\n+ t.Fatalf(\"newPodMountHints failed: %v\", err)\n}\n// Check that fields were set correctly.\n@@ -86,95 +85,95 @@ func TestPodMountHintsErrors(t *testing.T) {\n{\nname: \"too short\",\nannotations: map[string]string{\n- path.Join(MountPrefix, \"mount1\"): \"foo\",\n+ MountPrefix + \"mount1\": \"foo\",\n},\nerror: \"invalid mount annotation\",\n},\n{\nname: \"no name\",\nannotations: map[string]string{\n- MountPrefix + \"//source\": \"foo\",\n+ MountPrefix + \".source\": \"foo\",\n},\nerror: \"invalid mount name\",\n},\n{\nname: \"missing source\",\nannotations: map[string]string{\n- path.Join(MountPrefix, \"mount1\", \"type\"): \"tmpfs\",\n- path.Join(MountPrefix, \"mount1\", \"share\"): \"pod\",\n+ MountPrefix + \"mount1.type\": \"tmpfs\",\n+ MountPrefix + \"mount1.share\": \"pod\",\n},\nerror: \"source field\",\n},\n{\nname: \"missing type\",\nannotations: map[string]string{\n- path.Join(MountPrefix, \"mount1\", \"source\"): \"foo\",\n- path.Join(MountPrefix, \"mount1\", \"share\"): \"pod\",\n+ MountPrefix + \"mount1.source\": \"foo\",\n+ MountPrefix + \"mount1.share\": \"pod\",\n},\nerror: \"type field\",\n},\n{\nname: \"missing share\",\nannotations: map[string]string{\n- path.Join(MountPrefix, \"mount1\", \"source\"): \"foo\",\n- path.Join(MountPrefix, \"mount1\", \"type\"): \"tmpfs\",\n+ MountPrefix + \"mount1.source\": \"foo\",\n+ MountPrefix + \"mount1.type\": \"tmpfs\",\n},\nerror: \"share field\",\n},\n{\nname: \"invalid field name\",\nannotations: map[string]string{\n- path.Join(MountPrefix, \"mount1\", \"invalid\"): \"foo\",\n+ MountPrefix + \"mount1.invalid\": \"foo\",\n},\nerror: \"invalid mount annotation\",\n},\n{\nname: \"invalid source\",\nannotations: map[string]string{\n- path.Join(MountPrefix, \"mount1\", \"source\"): \"\",\n- path.Join(MountPrefix, \"mount1\", \"type\"): \"tmpfs\",\n- path.Join(MountPrefix, \"mount1\", \"share\"): \"pod\",\n+ MountPrefix + \"mount1.source\": \"\",\n+ MountPrefix + \"mount1.type\": \"tmpfs\",\n+ MountPrefix + \"mount1.share\": \"pod\",\n},\nerror: \"source cannot be empty\",\n},\n{\nname: \"invalid type\",\nannotations: map[string]string{\n- path.Join(MountPrefix, \"mount1\", \"source\"): \"foo\",\n- path.Join(MountPrefix, \"mount1\", \"type\"): \"invalid-type\",\n- path.Join(MountPrefix, \"mount1\", \"share\"): \"pod\",\n+ MountPrefix + \"mount1.source\": \"foo\",\n+ MountPrefix + \"mount1.type\": \"invalid-type\",\n+ MountPrefix + \"mount1.share\": \"pod\",\n},\nerror: \"invalid type\",\n},\n{\nname: \"invalid share\",\nannotations: map[string]string{\n- path.Join(MountPrefix, \"mount1\", \"source\"): \"foo\",\n- path.Join(MountPrefix, \"mount1\", \"type\"): \"tmpfs\",\n- path.Join(MountPrefix, \"mount1\", \"share\"): \"invalid-share\",\n+ MountPrefix + \"mount1.source\": \"foo\",\n+ MountPrefix + \"mount1.type\": \"tmpfs\",\n+ MountPrefix + \"mount1.share\": \"invalid-share\",\n},\nerror: \"invalid share\",\n},\n{\nname: \"invalid options\",\nannotations: map[string]string{\n- path.Join(MountPrefix, \"mount1\", \"source\"): \"foo\",\n- path.Join(MountPrefix, \"mount1\", \"type\"): \"tmpfs\",\n- path.Join(MountPrefix, \"mount1\", \"share\"): \"pod\",\n- path.Join(MountPrefix, \"mount1\", \"options\"): \"invalid-option\",\n+ MountPrefix + \"mount1.source\": \"foo\",\n+ MountPrefix + \"mount1.type\": \"tmpfs\",\n+ MountPrefix + \"mount1.share\": \"pod\",\n+ MountPrefix + \"mount1.options\": \"invalid-option\",\n},\nerror: \"unknown mount option\",\n},\n{\nname: \"duplicate source\",\nannotations: map[string]string{\n- path.Join(MountPrefix, \"mount1\", \"source\"): \"foo\",\n- path.Join(MountPrefix, \"mount1\", \"type\"): \"tmpfs\",\n- path.Join(MountPrefix, \"mount1\", \"share\"): \"pod\",\n+ MountPrefix + \"mount1.source\": \"foo\",\n+ MountPrefix + \"mount1.type\": \"tmpfs\",\n+ MountPrefix + \"mount1.share\": \"pod\",\n- path.Join(MountPrefix, \"mount2\", \"source\"): \"foo\",\n- path.Join(MountPrefix, \"mount2\", \"type\"): \"bind\",\n- path.Join(MountPrefix, \"mount2\", \"share\"): \"container\",\n+ MountPrefix + \"mount2.source\": \"foo\",\n+ MountPrefix + \"mount2.type\": \"bind\",\n+ MountPrefix + \"mount2.share\": \"container\",\n},\nerror: \"have the same mount source\",\n},\n@@ -202,36 +201,36 @@ func TestGetMountAccessType(t *testing.T) {\n{\nname: \"container=exclusive\",\nannotations: map[string]string{\n- path.Join(MountPrefix, \"mount1\", \"source\"): source,\n- path.Join(MountPrefix, \"mount1\", \"type\"): \"bind\",\n- path.Join(MountPrefix, \"mount1\", \"share\"): \"container\",\n+ MountPrefix + \"mount1.source\": source,\n+ MountPrefix + \"mount1.type\": \"bind\",\n+ MountPrefix + \"mount1.share\": \"container\",\n},\nwant: FileAccessExclusive,\n},\n{\nname: \"pod=shared\",\nannotations: map[string]string{\n- path.Join(MountPrefix, \"mount1\", \"source\"): source,\n- path.Join(MountPrefix, \"mount1\", \"type\"): \"bind\",\n- path.Join(MountPrefix, \"mount1\", \"share\"): \"pod\",\n+ MountPrefix + \"mount1.source\": source,\n+ MountPrefix + \"mount1.type\": \"bind\",\n+ MountPrefix + \"mount1.share\": \"pod\",\n},\nwant: FileAccessShared,\n},\n{\nname: \"shared=shared\",\nannotations: map[string]string{\n- path.Join(MountPrefix, \"mount1\", \"source\"): source,\n- path.Join(MountPrefix, \"mount1\", \"type\"): \"bind\",\n- path.Join(MountPrefix, \"mount1\", \"share\"): \"shared\",\n+ MountPrefix + \"mount1.source\": source,\n+ MountPrefix + \"mount1.type\": \"bind\",\n+ MountPrefix + \"mount1.share\": \"shared\",\n},\nwant: FileAccessShared,\n},\n{\nname: \"default=shared\",\nannotations: map[string]string{\n- path.Join(MountPrefix, \"mount1\", \"source\"): source + \"mismatch\",\n- path.Join(MountPrefix, \"mount1\", \"type\"): \"bind\",\n- path.Join(MountPrefix, \"mount1\", \"share\"): \"container\",\n+ MountPrefix + \"mount1.source\": source + \"mismatch\",\n+ MountPrefix + \"mount1.type\": \"bind\",\n+ MountPrefix + \"mount1.share\": \"container\",\n},\nwant: FileAccessShared,\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/multi_container_test.go",
"new_path": "runsc/container/multi_container_test.go",
"diff": "@@ -123,11 +123,11 @@ func execMany(execs []execDesc) error {\nfunc createSharedMount(mount specs.Mount, name string, pod ...*specs.Spec) {\nfor _, spec := range pod {\n- spec.Annotations[path.Join(boot.MountPrefix, name, \"source\")] = mount.Source\n- spec.Annotations[path.Join(boot.MountPrefix, name, \"type\")] = mount.Type\n- spec.Annotations[path.Join(boot.MountPrefix, name, \"share\")] = \"pod\"\n+ spec.Annotations[boot.MountPrefix+name+\".source\"] = mount.Source\n+ spec.Annotations[boot.MountPrefix+name+\".type\"] = mount.Type\n+ spec.Annotations[boot.MountPrefix+name+\".share\"] = \"pod\"\nif len(mount.Options) > 0 {\n- spec.Annotations[path.Join(boot.MountPrefix, name, \"options\")] = strings.Join(mount.Options, \",\")\n+ spec.Annotations[boot.MountPrefix+name+\".options\"] = strings.Join(mount.Options, \",\")\n}\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Make annotations OCI compliant
Changed annotation to follow the standard defined here:
https://github.com/opencontainers/image-spec/blob/master/annotations.md
PiperOrigin-RevId: 284254847 |
259,858 | 06.12.2019 16:58:28 | 28,800 | 371e210b83c244d8828ad2fa1b3d7cef15fbf463 | Add runtime tracing.
This adds meaningful annotations to the trace generated by the runtime/trace
package. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/control/pprof.go",
"new_path": "pkg/sentry/control/pprof.go",
"diff": "@@ -22,6 +22,7 @@ import (\n\"sync\"\n\"gvisor.dev/gvisor/pkg/fd\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/urpc\"\n)\n@@ -56,6 +57,9 @@ type Profile struct {\n// traceFile is the current execution trace output file.\ntraceFile *fd.FD\n+\n+ // Kernel is the kernel under profile.\n+ Kernel *kernel.Kernel\n}\n// StartCPUProfile is an RPC stub which starts recording the CPU profile in a\n@@ -147,6 +151,9 @@ func (p *Profile) StartTrace(o *ProfileOpts, _ *struct{}) error {\nreturn err\n}\n+ // Ensure all trace contexts are registered.\n+ p.Kernel.RebuildTraceContexts()\n+\np.traceFile = output\nreturn nil\n}\n@@ -158,9 +165,15 @@ func (p *Profile) StopTrace(_, _ *struct{}) error {\ndefer p.mu.Unlock()\nif p.traceFile == nil {\n- return errors.New(\"Execution tracing not start\")\n+ return errors.New(\"Execution tracing not started\")\n}\n+ // Similarly to the case above, if tasks have not ended traces, we will\n+ // lose information. Thus we need to rebuild the tasks in order to have\n+ // complete information. This will not lose information if multiple\n+ // traces are overlapping.\n+ p.Kernel.RebuildTraceContexts()\n+\ntrace.Stop()\np.traceFile.Close()\np.traceFile = nil\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/kernel.go",
"new_path": "pkg/sentry/kernel/kernel.go",
"diff": "@@ -841,9 +841,11 @@ func (k *Kernel) CreateProcess(args CreateProcessArgs) (*ThreadGroup, ThreadID,\nAbstractSocketNamespace: args.AbstractSocketNamespace,\nContainerID: args.ContainerID,\n}\n- if _, err := k.tasks.NewTask(config); err != nil {\n+ t, err := k.tasks.NewTask(config)\n+ if err != nil {\nreturn nil, 0, err\n}\n+ t.traceExecEvent(tc) // Simulate exec for tracing.\n// Success.\ntgid := k.tasks.Root.IDOfThreadGroup(tg)\n@@ -1118,6 +1120,22 @@ func (k *Kernel) SendContainerSignal(cid string, info *arch.SignalInfo) error {\nreturn lastErr\n}\n+// RebuildTraceContexts rebuilds the trace context for all tasks.\n+//\n+// Unfortunately, if these are built while tracing is not enabled, then we will\n+// not have meaningful trace data. Rebuilding here ensures that we can do so\n+// after tracing has been enabled.\n+func (k *Kernel) RebuildTraceContexts() {\n+ k.extMu.Lock()\n+ defer k.extMu.Unlock()\n+ k.tasks.mu.RLock()\n+ defer k.tasks.mu.RUnlock()\n+\n+ for t, tid := range k.tasks.Root.tids {\n+ t.rebuildTraceContext(tid)\n+ }\n+}\n+\n// FeatureSet returns the FeatureSet.\nfunc (k *Kernel) FeatureSet() *cpuid.FeatureSet {\nreturn k.featureSet\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/syscalls.go",
"new_path": "pkg/sentry/kernel/syscalls.go",
"diff": "@@ -339,6 +339,14 @@ func (s *SyscallTable) Lookup(sysno uintptr) SyscallFn {\nreturn nil\n}\n+// LookupName looks up a syscall name.\n+func (s *SyscallTable) LookupName(sysno uintptr) string {\n+ if sc, ok := s.Table[sysno]; ok {\n+ return sc.Name\n+ }\n+ return fmt.Sprintf(\"sys_%d\", sysno) // Unlikely.\n+}\n+\n// LookupEmulate looks up an emulation syscall number.\nfunc (s *SyscallTable) LookupEmulate(addr usermem.Addr) (uintptr, bool) {\nsysno, ok := s.Emulate[addr]\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task.go",
"new_path": "pkg/sentry/kernel/task.go",
"diff": "package kernel\nimport (\n+ gocontext \"context\"\n+ \"runtime/trace\"\n\"sync\"\n\"sync/atomic\"\n@@ -390,7 +392,14 @@ type Task struct {\n// logPrefix is a string containing the task's thread ID in the root PID\n// namespace, and is prepended to log messages emitted by Task.Infof etc.\n- logPrefix atomic.Value `state:\".(string)\"`\n+ logPrefix atomic.Value `state:\"nosave\"`\n+\n+ // traceContext and traceTask are both used for tracing, and are\n+ // updated along with the logPrefix in updateInfoLocked.\n+ //\n+ // These are exclusive to the task goroutine.\n+ traceContext gocontext.Context `state:\"nosave\"`\n+ traceTask *trace.Task `state:\"nosave\"`\n// creds is the task's credentials.\n//\n@@ -528,14 +537,6 @@ func (t *Task) loadPtraceTracer(tracer *Task) {\nt.ptraceTracer.Store(tracer)\n}\n-func (t *Task) saveLogPrefix() string {\n- return t.logPrefix.Load().(string)\n-}\n-\n-func (t *Task) loadLogPrefix(prefix string) {\n- t.logPrefix.Store(prefix)\n-}\n-\nfunc (t *Task) saveSyscallFilters() []bpf.Program {\nif f := t.syscallFilters.Load(); f != nil {\nreturn f.([]bpf.Program)\n@@ -549,6 +550,7 @@ func (t *Task) loadSyscallFilters(filters []bpf.Program) {\n// afterLoad is invoked by stateify.\nfunc (t *Task) afterLoad() {\n+ t.updateInfoLocked()\nt.interruptChan = make(chan struct{}, 1)\nt.gosched.State = TaskGoroutineNonexistent\nif t.stop != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_block.go",
"new_path": "pkg/sentry/kernel/task_block.go",
"diff": "@@ -16,6 +16,7 @@ package kernel\nimport (\n\"runtime\"\n+ \"runtime/trace\"\n\"time\"\nktime \"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n@@ -133,19 +134,24 @@ func (t *Task) block(C <-chan struct{}, timerChan <-chan struct{}) error {\nruntime.Gosched()\n}\n+ region := trace.StartRegion(t.traceContext, blockRegion)\nselect {\ncase <-C:\n+ region.End()\nt.SleepFinish(true)\n+ // Woken by event.\nreturn nil\ncase <-interrupt:\n+ region.End()\nt.SleepFinish(false)\n// Return the indicated error on interrupt.\nreturn syserror.ErrInterrupted\ncase <-timerChan:\n- // We've timed out.\n+ region.End()\nt.SleepFinish(true)\n+ // We've timed out.\nreturn syserror.ETIMEDOUT\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_clone.go",
"new_path": "pkg/sentry/kernel/task_clone.go",
"diff": "@@ -299,6 +299,7 @@ func (t *Task) Clone(opts *CloneOptions) (ThreadID, *SyscallControl, error) {\n// nt that it must receive before its task goroutine starts running.\ntid := nt.k.tasks.Root.IDOfTask(nt)\ndefer nt.Start(tid)\n+ t.traceCloneEvent(tid)\n// \"If fork/clone and execve are allowed by @prog, any child processes will\n// be constrained to the same filters and system call ABI as the parent.\" -\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_exec.go",
"new_path": "pkg/sentry/kernel/task_exec.go",
"diff": "@@ -129,6 +129,7 @@ type runSyscallAfterExecStop struct {\n}\nfunc (r *runSyscallAfterExecStop) execute(t *Task) taskRunState {\n+ t.traceExecEvent(r.tc)\nt.tg.pidns.owner.mu.Lock()\nt.tg.execing = nil\nif t.killed() {\n@@ -253,7 +254,7 @@ func (t *Task) promoteLocked() {\nt.tg.leader = t\nt.Infof(\"Becoming TID %d (in root PID namespace)\", t.tg.pidns.owner.Root.tids[t])\n- t.updateLogPrefixLocked()\n+ t.updateInfoLocked()\n// Reap the original leader. If it has a tracer, detach it instead of\n// waiting for it to acknowledge the original leader's death.\noldLeader.exitParentNotified = true\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_exit.go",
"new_path": "pkg/sentry/kernel/task_exit.go",
"diff": "@@ -236,6 +236,7 @@ func (*runExit) execute(t *Task) taskRunState {\ntype runExitMain struct{}\nfunc (*runExitMain) execute(t *Task) taskRunState {\n+ t.traceExitEvent()\nlastExiter := t.exitThreadGroup()\n// If the task has a cleartid, and the thread group wasn't killed by a\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_log.go",
"new_path": "pkg/sentry/kernel/task_log.go",
"diff": "@@ -16,6 +16,7 @@ package kernel\nimport (\n\"fmt\"\n+ \"runtime/trace\"\n\"sort\"\n\"gvisor.dev/gvisor/pkg/log\"\n@@ -127,11 +128,88 @@ func (t *Task) debugDumpStack() {\n}\n}\n-// updateLogPrefix updates the task's cached log prefix to reflect its\n-// current thread ID.\n+// trace definitions.\n+//\n+// Note that all region names are prefixed by ':' in order to ensure that they\n+// are lexically ordered before all system calls, which use the naked system\n+// call name (e.g. \"read\") for maximum clarity.\n+const (\n+ traceCategory = \"task\"\n+ runRegion = \":run\"\n+ blockRegion = \":block\"\n+ cpuidRegion = \":cpuid\"\n+ faultRegion = \":fault\"\n+)\n+\n+// updateInfoLocked updates the task's cached log prefix and tracing\n+// information to reflect its current thread ID.\n//\n// Preconditions: The task's owning TaskSet.mu must be locked.\n-func (t *Task) updateLogPrefixLocked() {\n+func (t *Task) updateInfoLocked() {\n// Use the task's TID in the root PID namespace for logging.\n- t.logPrefix.Store(fmt.Sprintf(\"[% 4d] \", t.tg.pidns.owner.Root.tids[t]))\n+ tid := t.tg.pidns.owner.Root.tids[t]\n+ t.logPrefix.Store(fmt.Sprintf(\"[% 4d] \", tid))\n+ t.rebuildTraceContext(tid)\n+}\n+\n+// rebuildTraceContext rebuilds the trace context.\n+//\n+// Precondition: the passed tid must be the tid in the root namespace.\n+func (t *Task) rebuildTraceContext(tid ThreadID) {\n+ // Re-initialize the trace context.\n+ if t.traceTask != nil {\n+ t.traceTask.End()\n+ }\n+\n+ // Note that we define the \"task type\" to be the dynamic TID. This does\n+ // not align perfectly with the documentation for \"tasks\" in the\n+ // tracing package. Tasks may be assumed to be bounded by analysis\n+ // tools. However, if we just use a generic \"task\" type here, then the\n+ // \"user-defined tasks\" page on the tracing dashboard becomes nearly\n+ // unusable, as it loads all traces from all tasks.\n+ //\n+ // We can assume that the number of tasks in the system is not\n+ // arbitrarily large (in general it won't be, especially for cases\n+ // where we're collecting a brief profile), so using the TID is a\n+ // reasonable compromise in this case.\n+ t.traceContext, t.traceTask = trace.NewTask(t, fmt.Sprintf(\"tid:%d\", tid))\n+}\n+\n+// traceCloneEvent is called when a new task is spawned.\n+//\n+// ntid must be the new task's ThreadID in the root namespace.\n+func (t *Task) traceCloneEvent(ntid ThreadID) {\n+ if !trace.IsEnabled() {\n+ return\n+ }\n+ trace.Logf(t.traceContext, traceCategory, \"spawn: %d\", ntid)\n+}\n+\n+// traceExitEvent is called when a task exits.\n+func (t *Task) traceExitEvent() {\n+ if !trace.IsEnabled() {\n+ return\n+ }\n+ trace.Logf(t.traceContext, traceCategory, \"exit status: 0x%x\", t.exitStatus.Status())\n+}\n+\n+// traceExecEvent is called when a task calls exec.\n+func (t *Task) traceExecEvent(tc *TaskContext) {\n+ if !trace.IsEnabled() {\n+ return\n+ }\n+ d := tc.MemoryManager.Executable()\n+ if d == nil {\n+ trace.Logf(t.traceContext, traceCategory, \"exec: << unknown >>\")\n+ return\n+ }\n+ defer d.DecRef()\n+ root := t.fsContext.RootDirectory()\n+ if root == nil {\n+ trace.Logf(t.traceContext, traceCategory, \"exec: << no root directory >>\")\n+ return\n+ }\n+ defer root.DecRef()\n+ n, _ := d.FullName(root)\n+ trace.Logf(t.traceContext, traceCategory, \"exec: %s\", n)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_run.go",
"new_path": "pkg/sentry/kernel/task_run.go",
"diff": "@@ -17,6 +17,7 @@ package kernel\nimport (\n\"bytes\"\n\"runtime\"\n+ \"runtime/trace\"\n\"sync/atomic\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n@@ -205,9 +206,11 @@ func (*runApp) execute(t *Task) taskRunState {\nt.tg.pidns.owner.mu.RUnlock()\n}\n+ region := trace.StartRegion(t.traceContext, runRegion)\nt.accountTaskGoroutineEnter(TaskGoroutineRunningApp)\ninfo, at, err := t.p.Switch(t.MemoryManager().AddressSpace(), t.Arch(), t.rseqCPU)\nt.accountTaskGoroutineLeave(TaskGoroutineRunningApp)\n+ region.End()\nif clearSinglestep {\nt.Arch().ClearSingleStep()\n@@ -225,6 +228,7 @@ func (*runApp) execute(t *Task) taskRunState {\ncase platform.ErrContextSignalCPUID:\n// Is this a CPUID instruction?\n+ region := trace.StartRegion(t.traceContext, cpuidRegion)\nexpected := arch.CPUIDInstruction[:]\nfound := make([]byte, len(expected))\n_, err := t.CopyIn(usermem.Addr(t.Arch().IP()), &found)\n@@ -232,10 +236,12 @@ func (*runApp) execute(t *Task) taskRunState {\n// Skip the cpuid instruction.\nt.Arch().CPUIDEmulate(t)\nt.Arch().SetIP(t.Arch().IP() + uintptr(len(expected)))\n+ region.End()\n// Resume execution.\nreturn (*runApp)(nil)\n}\n+ region.End() // Not an actual CPUID, but required copy-in.\n// The instruction at the given RIP was not a CPUID, and we\n// fallthrough to the default signal deliver behavior below.\n@@ -251,8 +257,10 @@ func (*runApp) execute(t *Task) taskRunState {\n// an application-generated signal and we should continue execution\n// normally.\nif at.Any() {\n+ region := trace.StartRegion(t.traceContext, faultRegion)\naddr := usermem.Addr(info.Addr())\nerr := t.MemoryManager().HandleUserFault(t, addr, at, usermem.Addr(t.Arch().Stack()))\n+ region.End()\nif err == nil {\n// The fault was handled appropriately.\n// We can resume running the application.\n@@ -260,6 +268,12 @@ func (*runApp) execute(t *Task) taskRunState {\n}\n// Is this a vsyscall that we need emulate?\n+ //\n+ // Note that we don't track vsyscalls as part of a\n+ // specific trace region. This is because regions don't\n+ // stack, and the actual system call will count as a\n+ // region. We should be able to easily identify\n+ // vsyscalls by having a <fault><syscall> pair.\nif at.Execute {\nif sysno, ok := t.tc.st.LookupEmulate(addr); ok {\nreturn t.doVsyscall(addr, sysno)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_start.go",
"new_path": "pkg/sentry/kernel/task_start.go",
"diff": "@@ -154,10 +154,10 @@ func (ts *TaskSet) newTask(cfg *TaskConfig) (*Task, error) {\n// Below this point, newTask is expected not to fail (there is no rollback\n// of assignTIDsLocked or any of the following).\n- // Logging on t's behalf will panic if t.logPrefix hasn't been initialized.\n- // This is the earliest point at which we can do so (since t now has thread\n- // IDs).\n- t.updateLogPrefixLocked()\n+ // Logging on t's behalf will panic if t.logPrefix hasn't been\n+ // initialized. This is the earliest point at which we can do so\n+ // (since t now has thread IDs).\n+ t.updateInfoLocked()\nif cfg.InheritParent != nil {\nt.parent = cfg.InheritParent.parent\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_syscall.go",
"new_path": "pkg/sentry/kernel/task_syscall.go",
"diff": "@@ -17,6 +17,7 @@ package kernel\nimport (\n\"fmt\"\n\"os\"\n+ \"runtime/trace\"\n\"syscall\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n@@ -160,6 +161,10 @@ func (t *Task) executeSyscall(sysno uintptr, args arch.SyscallArguments) (rval u\nctrl = ctrlStopAndReinvokeSyscall\n} else {\nfn := s.Lookup(sysno)\n+ var region *trace.Region // Only non-nil if tracing == true.\n+ if trace.IsEnabled() {\n+ region = trace.StartRegion(t.traceContext, s.LookupName(sysno))\n+ }\nif fn != nil {\n// Call our syscall implementation.\nrval, ctrl, err = fn(t, args)\n@@ -167,6 +172,9 @@ func (t *Task) executeSyscall(sysno uintptr, args arch.SyscallArguments) (rval u\n// Use the missing function if not found.\nrval, err = t.SyscallTable().Missing(t, sysno, args)\n}\n+ if region != nil {\n+ region.End()\n+ }\n}\nif bits.IsOn32(fe, ExternalAfterEnable) && (s.ExternalFilterAfter == nil || s.ExternalFilterAfter(t, sysno, args)) {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/controller.go",
"new_path": "runsc/boot/controller.go",
"diff": "@@ -152,7 +152,9 @@ func newController(fd int, l *Loader) (*controller, error) {\nsrv.Register(&debug{})\nsrv.Register(&control.Logging{})\nif l.conf.ProfileEnable {\n- srv.Register(&control.Profile{})\n+ srv.Register(&control.Profile{\n+ Kernel: l.k,\n+ })\n}\nreturn &controller{\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/debug.go",
"new_path": "runsc/cmd/debug.go",
"diff": "@@ -37,11 +37,11 @@ type Debug struct {\nsignal int\nprofileHeap string\nprofileCPU string\n- profileDelay int\ntrace string\nstrace string\nlogLevel string\nlogPackets string\n+ duration time.Duration\n}\n// Name implements subcommands.Command.\n@@ -65,7 +65,7 @@ func (d *Debug) SetFlags(f *flag.FlagSet) {\nf.BoolVar(&d.stacks, \"stacks\", false, \"if true, dumps all sandbox stacks to the log\")\nf.StringVar(&d.profileHeap, \"profile-heap\", \"\", \"writes heap profile to the given file.\")\nf.StringVar(&d.profileCPU, \"profile-cpu\", \"\", \"writes CPU profile to the given file.\")\n- f.IntVar(&d.profileDelay, \"profile-delay\", 5, \"amount of time to wait before stoping CPU profile\")\n+ f.DurationVar(&d.duration, \"duration\", time.Second, \"amount of time to wait for CPU and trace profiles\")\nf.StringVar(&d.trace, \"trace\", \"\", \"writes an execution trace to the given file.\")\nf.IntVar(&d.signal, \"signal\", -1, \"sends signal to the sandbox\")\nf.StringVar(&d.strace, \"strace\", \"\", `A comma separated list of syscalls to trace. \"all\" enables all traces, \"off\" disables all`)\n@@ -163,7 +163,7 @@ func (d *Debug) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\nif err := c.Sandbox.StartCPUProfile(f); err != nil {\nreturn Errorf(err.Error())\n}\n- log.Infof(\"CPU profile started for %d sec, writing to %q\", d.profileDelay, d.profileCPU)\n+ log.Infof(\"CPU profile started for %v, writing to %q\", d.duration, d.profileCPU)\n}\nif d.trace != \"\" {\ndelay = true\n@@ -181,8 +181,7 @@ func (d *Debug) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\nif err := c.Sandbox.StartTrace(f); err != nil {\nreturn Errorf(err.Error())\n}\n- log.Infof(\"Tracing started for %d sec, writing to %q\", d.profileDelay, d.trace)\n-\n+ log.Infof(\"Tracing started for %v, writing to %q\", d.duration, d.trace)\n}\nif d.strace != \"\" || len(d.logLevel) != 0 || len(d.logPackets) != 0 {\n@@ -243,7 +242,7 @@ func (d *Debug) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\n}\nif delay {\n- time.Sleep(time.Duration(d.profileDelay) * time.Second)\n+ time.Sleep(d.duration)\n}\nreturn subcommands.ExitSuccess\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/dev.sh",
"new_path": "scripts/dev.sh",
"diff": "@@ -54,9 +54,10 @@ declare OUTPUT=\"$(build //runsc)\"\nif [[ ${REFRESH} -eq 0 ]]; then\ninstall_runsc \"${RUNTIME}\" --net-raw\ninstall_runsc \"${RUNTIME}-d\" --net-raw --debug --strace --log-packets\n+ install_runsc \"${RUNTIME}-p\" --net-raw --profile\necho\n- echo \"Runtimes ${RUNTIME} and ${RUNTIME}-d (debug enabled) setup.\"\n+ echo \"Runtimes ${RUNTIME}, ${RUNTIME}-d (debug enabled), and ${RUNTIME}-p installed.\"\necho \"Use --runtime=\"${RUNTIME}\" with your Docker command.\"\necho \" docker run --rm --runtime=\"${RUNTIME}\" hello-world\"\necho\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add runtime tracing.
This adds meaningful annotations to the trace generated by the runtime/trace
package.
PiperOrigin-RevId: 284290115 |
260,023 | 06.12.2019 17:15:52 | 28,800 | b1d44be7ad893bd6bdfd164a54a7142f4462414b | Add TCP stats for connection close and keep-alive timeouts.
Fix bugs in updates to TCP CurrentEstablished stat.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/netstack.go",
"new_path": "pkg/sentry/socket/netstack/netstack.go",
"diff": "@@ -151,6 +151,8 @@ var Metrics = tcpip.Stats{\nPassiveConnectionOpenings: mustCreateMetric(\"/netstack/tcp/passive_connection_openings\", \"Number of connections opened successfully via Listen.\"),\nCurrentEstablished: mustCreateMetric(\"/netstack/tcp/current_established\", \"Number of connections in either ESTABLISHED or CLOSE-WAIT state now.\"),\nEstablishedResets: mustCreateMetric(\"/netstack/tcp/established_resets\", \"Number of times TCP connections have made a direct transition to the CLOSED state from either the ESTABLISHED state or the CLOSE-WAIT state\"),\n+ EstablishedClosed: mustCreateMetric(\"/netstack/tcp/established_closed\", \"number of times established TCP connections made a transition to CLOSED state.\"),\n+ EstablishedTimedout: mustCreateMetric(\"/netstack/tcp/established_timedout\", \"Number of times an established connection was reset because of keep-alive time out.\"),\nListenOverflowSynDrop: mustCreateMetric(\"/netstack/tcp/listen_overflow_syn_drop\", \"Number of times the listen queue overflowed and a SYN was dropped.\"),\nListenOverflowAckDrop: mustCreateMetric(\"/netstack/tcp/listen_overflow_ack_drop\", \"Number of times the listen queue overflowed and the final ACK in the handshake was dropped.\"),\nListenOverflowSynCookieSent: mustCreateMetric(\"/netstack/tcp/listen_overflow_syn_cookie_sent\", \"Number of times a SYN cookie was sent.\"),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -924,6 +924,14 @@ type TCPStats struct {\n// ESTABLISHED state or the CLOSE-WAIT state.\nEstablishedResets *StatCounter\n+ // EstablishedClosed is the number of times established TCP connections\n+ // made a transition to CLOSED state.\n+ EstablishedClosed *StatCounter\n+\n+ // EstablishedTimedout is the number of times an established connection\n+ // was reset because of keep-alive time out.\n+ EstablishedTimedout *StatCounter\n+\n// ListenOverflowSynDrop is the number of times the listen queue overflowed\n// and a SYN was dropped.\nListenOverflowSynDrop *StatCounter\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/connect.go",
"new_path": "pkg/tcpip/transport/tcp/connect.go",
"diff": "@@ -924,6 +924,7 @@ func (e *endpoint) transitionToStateCloseLocked() {\n}\ne.cleanupLocked()\ne.state = StateClose\n+ e.stack.Stats().TCP.EstablishedClosed.Increment()\n}\n// tryDeliverSegmentFromClosedEndpoint attempts to deliver the parsed\n@@ -1094,6 +1095,7 @@ func (e *endpoint) keepaliveTimerExpired() *tcpip.Error {\nif e.keepalive.unacked >= e.keepalive.count {\ne.keepalive.Unlock()\n+ e.stack.Stats().TCP.EstablishedTimedout.Increment()\nreturn tcpip.ErrTimeout\n}\n@@ -1179,8 +1181,6 @@ func (e *endpoint) protocolMainLoop(handshake bool) *tcpip.Error {\ne.lastErrorMu.Unlock()\ne.mu.Lock()\n- e.stack.Stats().TCP.EstablishedResets.Increment()\n- e.stack.Stats().TCP.CurrentEstablished.Decrement()\ne.state = StateError\ne.HardError = err\n@@ -1389,7 +1389,6 @@ func (e *endpoint) protocolMainLoop(handshake bool) *tcpip.Error {\n// Mark endpoint as closed.\ne.mu.Lock()\nif e.state != StateError {\n- e.stack.Stats().TCP.EstablishedResets.Increment()\ne.stack.Stats().TCP.CurrentEstablished.Decrement()\ne.transitionToStateCloseLocked()\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/snd.go",
"new_path": "pkg/tcpip/transport/tcp/snd.go",
"diff": "@@ -674,7 +674,6 @@ func (s *sender) maybeSendSegment(seg *segment, limit int, end seqnum.Value) (se\ndefault:\ns.ep.state = StateFinWait1\n}\n- s.ep.stack.Stats().TCP.CurrentEstablished.Decrement()\ns.ep.mu.Unlock()\n} else {\n// We're sending a non-FIN segment.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"new_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"diff": "@@ -75,6 +75,20 @@ func TestGiveUpConnect(t *testing.T) {\nif err := ep.GetSockOpt(tcpip.ErrorOption{}); err != tcpip.ErrAborted {\nt.Fatalf(\"got ep.GetSockOpt(tcpip.ErrorOption{}) = %v, want = %v\", err, tcpip.ErrAborted)\n}\n+\n+ // Call Connect again to retreive the handshake failure status\n+ // and stats updates.\n+ if err := ep.Connect(tcpip.FullAddress{Addr: context.TestAddr, Port: context.TestPort}); err != tcpip.ErrAborted {\n+ t.Fatalf(\"got ep.Connect(...) = %v, want = %v\", err, tcpip.ErrAborted)\n+ }\n+\n+ if got := c.Stack().Stats().TCP.FailedConnectionAttempts.Value(); got != 1 {\n+ t.Errorf(\"got stats.TCP.FailedConnectionAttempts.Value() = %v, want = 1\", got)\n+ }\n+\n+ if got := c.Stack().Stats().TCP.CurrentEstablished.Value(); got != 0 {\n+ t.Errorf(\"got stats.TCP.CurrentEstablished.Value() = %v, want = 0\", got)\n+ }\n}\nfunc TestConnectIncrementActiveConnection(t *testing.T) {\n@@ -548,6 +562,14 @@ func TestClosingWithEnqueuedSegments(t *testing.T) {\nt.Errorf(\"Unexpected endpoint state: want %v, got %v\", want, got)\n}\n+ if got := c.Stack().Stats().TCP.EstablishedClosed.Value(); got != 1 {\n+ t.Errorf(\"got c.Stack().Stats().TCP.EstablishedClosed = %v, want = 1\", got)\n+ }\n+\n+ if got := c.Stack().Stats().TCP.CurrentEstablished.Value(); got != 0 {\n+ t.Errorf(\"got stats.TCP.CurrentEstablished.Value() = %v, want = 0\", got)\n+ }\n+\n// Check if the endpoint was moved to CLOSED and netstack a reset in\n// response to the ACK packet that we sent after last-ACK.\nchecker.IPv4(t, c.GetPacket(),\n@@ -2694,6 +2716,13 @@ loop:\nif tcp.EndpointState(c.EP.State()) != tcp.StateError {\nt.Fatalf(\"got EP state is not StateError\")\n}\n+\n+ if got := c.Stack().Stats().TCP.EstablishedResets.Value(); got != 1 {\n+ t.Errorf(\"got stats.TCP.EstablishedResets.Value() = %v, want = 1\", got)\n+ }\n+ if got := c.Stack().Stats().TCP.CurrentEstablished.Value(); got != 0 {\n+ t.Errorf(\"got stats.TCP.CurrentEstablished.Value() = %v, want = 0\", got)\n+ }\n}\nfunc TestSendOnResetConnection(t *testing.T) {\n@@ -4363,9 +4392,17 @@ func TestKeepalive(t *testing.T) {\n),\n)\n+ if got := c.Stack().Stats().TCP.EstablishedTimedout.Value(); got != 1 {\n+ t.Errorf(\"got c.Stack().Stats().TCP.EstablishedTimedout.Value() = %v, want = 1\", got)\n+ }\n+\nif _, _, err := c.EP.Read(nil); err != tcpip.ErrTimeout {\nt.Fatalf(\"got c.EP.Read(nil) = %v, want = %v\", err, tcpip.ErrTimeout)\n}\n+\n+ if got := c.Stack().Stats().TCP.CurrentEstablished.Value(); got != 0 {\n+ t.Errorf(\"got stats.TCP.CurrentEstablished.Value() = %v, want = 0\", got)\n+ }\n}\nfunc executeHandshake(t *testing.T, c *context.Context, srcPort uint16, synCookieInUse bool) (irs, iss seqnum.Value) {\n@@ -5992,6 +6029,8 @@ func TestTCPTimeWaitDuplicateFINExtendsTimeWait(t *testing.T) {\nt.Fatalf(\"c.stack.SetTransportProtocolOption(tcp, tcpip.TCPLingerTimeoutOption(%d) failed: %s\", tcpTimeWaitTimeout, err)\n}\n+ want := c.Stack().Stats().TCP.EstablishedClosed.Value() + 1\n+\nwq := &waiter.Queue{}\nep, err := c.Stack().NewEndpoint(tcp.ProtocolNumber, ipv4.ProtocolNumber, wq)\nif err != nil {\n@@ -6120,6 +6159,13 @@ func TestTCPTimeWaitDuplicateFINExtendsTimeWait(t *testing.T) {\nchecker.SeqNum(uint32(ackHeaders.AckNum)),\nchecker.AckNum(uint32(ackHeaders.SeqNum)),\nchecker.TCPFlags(header.TCPFlagRst|header.TCPFlagAck)))\n+\n+ if got := c.Stack().Stats().TCP.EstablishedClosed.Value(); got != want {\n+ t.Errorf(\"got c.Stack().Stats().TCP.EstablishedClosed = %v, want = %v\", got, want)\n+ }\n+ if got := c.Stack().Stats().TCP.CurrentEstablished.Value(); got != 0 {\n+ t.Errorf(\"got stats.TCP.CurrentEstablished.Value() = %v, want = 0\", got)\n+ }\n}\nfunc TestTCPCloseWithData(t *testing.T) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add TCP stats for connection close and keep-alive timeouts.
Fix bugs in updates to TCP CurrentEstablished stat.
Fixes #1277
PiperOrigin-RevId: 284292459 |
259,992 | 06.12.2019 20:11:51 | 28,800 | 3c2e2f7d12285e6093ecc225e0379fe59e8fd93f | Update Kokoro image to install Golang 1.13 | [
{
"change_type": "MODIFY",
"old_path": "kokoro/ubuntu1604/10_core.sh",
"new_path": "kokoro/ubuntu1604/10_core.sh",
"diff": "@@ -21,8 +21,8 @@ apt-get update && apt-get -y install make git-core build-essential linux-headers\n# Install a recent go toolchain.\nif ! [[ -d /usr/local/go ]]; then\n- wget https://dl.google.com/go/go1.12.linux-amd64.tar.gz\n- tar -xvf go1.12.linux-amd64.tar.gz\n+ wget https://dl.google.com/go/go1.13.5.linux-amd64.tar.gz\n+ tar -xvf go1.13.5.linux-amd64.tar.gz\nmv go /usr/local\nfi\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "kokoro/ubuntu1604/README.md",
"diff": "+## Image Update\n+\n+After making changes to files in the directory, you must run the following\n+commands to update the image Kokoro uses:\n+\n+```shell\n+gcloud config set project gvisor-kokoro-testing\n+third_party/gvisor/kokoro/ubuntu1604/build.sh\n+third_party/gvisor/kokoro/ubuntu1804/build.sh\n+```\n+\n+Note: the command above will change your default project for `gcloud`. Run\n+`gcloud config set project` again to revert back to your default project.\n+\n+Note: Files in `third_party/gvisor/kokoro/ubuntu1804/` as symlinks to\n+`ubuntu1604`, therefore both images must be updated.\n+\n+After the script finishes, the last few lines of the output will container the\n+image name. If the output was lost, you can run `build.sh` again to print the\n+image name.\n+\n+```\n+NAME PROJECT FAMILY DEPRECATED STATUS\n+image-6777fa4666a968c8 gvisor-kokoro-testing READY\n++ cleanup\n++ gcloud compute instances delete --quiet build-tlfrdv\n+Deleted [https://www.googleapis.com/compute/v1/projects/gvisor-kokoro-testing/zones/us-central1-f/instances/build-tlfrdv].\n+```\n+\n+To setup Kokoro to use the new image, copy the image names to their\n+corresponding file below:\n+\n+* //devtools/kokoro/config/gcp/gvisor/ubuntu1604.gcl\n+* //devtools/kokoro/config/gcp/gvisor/ubuntu1804.gcl\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/go.sh",
"new_path": "scripts/go.sh",
"diff": "@@ -25,6 +25,8 @@ tools/go_branch.sh\n# Checkout the new branch.\ngit checkout go && git clean -f\n+go version\n+\n# Build everything.\ngo build ./...\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update Kokoro image to install Golang 1.13
PiperOrigin-RevId: 284308422 |
259,992 | 06.12.2019 23:08:39 | 28,800 | 01eadf51ea54b8f478c49b755d712f11fff2b28c | Bump up Go 1.13 as minimum requirement | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/sighandling/sighandling.go",
"new_path": "pkg/sentry/sighandling/sighandling.go",
"diff": "package sighandling\nimport (\n- \"fmt\"\n\"os\"\n\"os/signal\"\n\"reflect\"\n@@ -31,37 +30,25 @@ const numSignals = 32\n// handleSignals listens for incoming signals and calls the given handler\n// function.\n//\n-// It starts when the start channel is closed, stops when the stop channel\n-// is closed, and closes done once it will no longer deliver signals to k.\n-func handleSignals(sigchans []chan os.Signal, handler func(linux.Signal), start, stop, done chan struct{}) {\n+// It stops when the stop channel is closed. The done channel is closed once it\n+// will no longer deliver signals to k.\n+func handleSignals(sigchans []chan os.Signal, handler func(linux.Signal), stop, done chan struct{}) {\n// Build a select case.\n- sc := []reflect.SelectCase{{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(start)}}\n+ sc := []reflect.SelectCase{{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(stop)}}\nfor _, sigchan := range sigchans {\nsc = append(sc, reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(sigchan)})\n}\n- started := false\nfor {\n// Wait for a notification.\nindex, _, ok := reflect.Select(sc)\n- // Was it the start / stop channel?\n+ // Was it the stop channel?\nif index == 0 {\nif !ok {\n- if !started {\n- // start channel; start forwarding and\n- // swap this case for the stop channel\n- // to select stop requests.\n- started = true\n- sc[0] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(stop)}\n- } else {\n- // stop channel; stop forwarding and\n- // clear this case so it is never\n- // selected again.\n- started = false\n+ // Stop forwarding and notify that it's done.\nclose(done)\n- sc[0].Chan = reflect.Value{}\n- }\n+ return\n}\ncontinue\n}\n@@ -73,44 +60,17 @@ func handleSignals(sigchans []chan os.Signal, handler func(linux.Signal), start,\n// Otherwise, it was a signal on channel N. Index 0 represents the stop\n// channel, so index N represents the channel for signal N.\n- signal := linux.Signal(index)\n-\n- if !started {\n- // Kernel cannot receive signals, either because it is\n- // not ready yet or is shutting down.\n- //\n- // Kill ourselves if this signal would have killed the\n- // process before PrepareForwarding was called. i.e., all\n- // _SigKill signals; see Go\n- // src/runtime/sigtab_linux_generic.go.\n- //\n- // Otherwise ignore the signal.\n- //\n- // TODO(b/114489875): Drop in Go 1.12, which uses tgkill\n- // in runtime.raise.\n- switch signal {\n- case linux.SIGHUP, linux.SIGINT, linux.SIGTERM:\n- dieFromSignal(signal)\n- panic(fmt.Sprintf(\"Failed to die from signal %d\", signal))\n- default:\n- continue\n+ handler(linux.Signal(index))\n}\n}\n- // Pass the signal to the handler.\n- handler(signal)\n- }\n-}\n-\n-// PrepareHandler ensures that synchronous signals are passed to the given\n-// handler function and returns a callback that starts signal delivery, which\n-// itself returns a callback that stops signal handling.\n+// StartSignalForwarding ensures that synchronous signals are passed to the\n+// given handler function and returns a callback that stops signal delivery.\n//\n// Note that this function permanently takes over signal handling. After the\n// stop callback, signals revert to the default Go runtime behavior, which\n// cannot be overridden with external calls to signal.Notify.\n-func PrepareHandler(handler func(linux.Signal)) func() func() {\n- start := make(chan struct{})\n+func StartSignalForwarding(handler func(linux.Signal)) func() {\nstop := make(chan struct{})\ndone := make(chan struct{})\n@@ -128,13 +88,10 @@ func PrepareHandler(handler func(linux.Signal)) func() func() {\nsignal.Notify(sigchan, syscall.Signal(sig))\n}\n// Start up our listener.\n- go handleSignals(sigchans, handler, start, stop, done) // S/R-SAFE: synchronized by Kernel.extMu.\n+ go handleSignals(sigchans, handler, stop, done) // S/R-SAFE: synchronized by Kernel.extMu.\n- return func() func() {\n- close(start)\nreturn func() {\nclose(stop)\n<-done\n}\n}\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/sighandling/sighandling_unsafe.go",
"new_path": "pkg/sentry/sighandling/sighandling_unsafe.go",
"diff": "package sighandling\nimport (\n- \"fmt\"\n- \"runtime\"\n\"syscall\"\n\"unsafe\"\n@@ -48,27 +46,3 @@ func IgnoreChildStop() error {\nreturn nil\n}\n-\n-// dieFromSignal kills the current process with sig.\n-//\n-// Preconditions: The default action of sig is termination.\n-func dieFromSignal(sig linux.Signal) {\n- runtime.LockOSThread()\n- defer runtime.UnlockOSThread()\n-\n- sa := sigaction{handler: linux.SIG_DFL}\n- if _, _, e := syscall.RawSyscall6(syscall.SYS_RT_SIGACTION, uintptr(sig), uintptr(unsafe.Pointer(&sa)), 0, linux.SignalSetSize, 0, 0); e != 0 {\n- panic(fmt.Sprintf(\"rt_sigaction failed: %v\", e))\n- }\n-\n- set := linux.MakeSignalSet(sig)\n- if _, _, e := syscall.RawSyscall6(syscall.SYS_RT_SIGPROCMASK, linux.SIG_UNBLOCK, uintptr(unsafe.Pointer(&set)), 0, linux.SignalSetSize, 0, 0); e != 0 {\n- panic(fmt.Sprintf(\"rt_sigprocmask failed: %v\", e))\n- }\n-\n- if err := syscall.Tgkill(syscall.Getpid(), syscall.Gettid(), syscall.Signal(sig)); err != nil {\n- panic(fmt.Sprintf(\"tgkill failed: %v\", err))\n- }\n-\n- panic(\"failed to die\")\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/syncutil/BUILD",
"new_path": "pkg/syncutil/BUILD",
"diff": "@@ -31,8 +31,6 @@ go_template(\ngo_library(\nname = \"syncutil\",\nsrcs = [\n- \"downgradable_rwmutex_1_12_unsafe.go\",\n- \"downgradable_rwmutex_1_13_unsafe.go\",\n\"downgradable_rwmutex_unsafe.go\",\n\"memmove_unsafe.go\",\n\"norace_unsafe.go\",\n"
},
{
"change_type": "DELETE",
"old_path": "pkg/syncutil/downgradable_rwmutex_1_12_unsafe.go",
"new_path": null,
"diff": "-// Copyright 2009 The Go Authors. All rights reserved.\n-// Copyright 2019 The gVisor Authors.\n-// Use of this source code is governed by a BSD-style\n-// license that can be found in the LICENSE file.\n-\n-// +build go1.12\n-// +build !go1.13\n-\n-// TODO(b/133868570): Delete once Go 1.12 is no longer supported.\n-\n-package syncutil\n-\n-import _ \"unsafe\"\n-\n-//go:linkname runtimeSemrelease112 sync.runtime_Semrelease\n-func runtimeSemrelease112(s *uint32, handoff bool)\n-\n-func runtimeSemrelease(s *uint32, handoff bool, skipframes int) {\n- // 'skipframes' is only available starting from 1.13.\n- runtimeSemrelease112(s, handoff)\n-}\n"
},
{
"change_type": "DELETE",
"old_path": "pkg/syncutil/downgradable_rwmutex_1_13_unsafe.go",
"new_path": null,
"diff": "-// Copyright 2009 The Go Authors. All rights reserved.\n-// Copyright 2019 The gVisor Authors.\n-// Use of this source code is governed by a BSD-style\n-// license that can be found in the LICENSE file.\n-\n-// +build go1.13\n-// +build !go1.15\n-\n-// Check go:linkname function signatures when updating Go version.\n-\n-package syncutil\n-\n-import _ \"unsafe\"\n-\n-//go:linkname runtimeSemrelease sync.runtime_Semrelease\n-func runtimeSemrelease(s *uint32, handoff bool, skipframes int)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/syncutil/downgradable_rwmutex_unsafe.go",
"new_path": "pkg/syncutil/downgradable_rwmutex_unsafe.go",
"diff": "// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n-// +build go1.12\n+// +build go1.13\n// +build !go1.15\n// Check go:linkname function signatures when updating Go version.\n@@ -27,6 +27,9 @@ import (\n//go:linkname runtimeSemacquire sync.runtime_Semacquire\nfunc runtimeSemacquire(s *uint32)\n+//go:linkname runtimeSemrelease sync.runtime_Semrelease\n+func runtimeSemrelease(s *uint32, handoff bool, skipframes int)\n+\n// DowngradableRWMutex is identical to sync.RWMutex, but adds the DowngradeLock\n// method.\ntype DowngradableRWMutex struct {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader.go",
"new_path": "runsc/boot/loader.go",
"diff": "@@ -93,10 +93,6 @@ type Loader struct {\n// spec is the base configuration for the root container.\nspec *specs.Spec\n- // startSignalForwarding enables forwarding of signals to the sandboxed\n- // container. It should be called after the init process is loaded.\n- startSignalForwarding func() func()\n-\n// stopSignalForwarding disables forwarding of signals to the sandboxed\n// container. It should be called when a sandbox is destroyed.\nstopSignalForwarding func()\n@@ -336,29 +332,6 @@ func New(args Args) (*Loader, error) {\nreturn nil, fmt.Errorf(\"ignore child stop signals failed: %v\", err)\n}\n- // Handle signals by forwarding them to the root container process\n- // (except for panic signal, which should cause a panic).\n- l.startSignalForwarding = sighandling.PrepareHandler(func(sig linux.Signal) {\n- // Panic signal should cause a panic.\n- if args.Conf.PanicSignal != -1 && sig == linux.Signal(args.Conf.PanicSignal) {\n- panic(\"Signal-induced panic\")\n- }\n-\n- // Otherwise forward to root container.\n- deliveryMode := DeliverToProcess\n- if args.Console {\n- // Since we are running with a console, we should\n- // forward the signal to the foreground process group\n- // so that job control signals like ^C can be handled\n- // properly.\n- deliveryMode = DeliverToForegroundProcessGroup\n- }\n- log.Infof(\"Received external signal %d, mode: %v\", sig, deliveryMode)\n- if err := l.signal(args.ID, 0, int32(sig), deliveryMode); err != nil {\n- log.Warningf(\"error sending signal %v to container %q: %v\", sig, args.ID, err)\n- }\n- })\n-\n// Create the control server using the provided FD.\n//\n// This must be done *after* we have initialized the kernel since the\n@@ -566,8 +539,27 @@ func (l *Loader) run() error {\nep.tty.InitForegroundProcessGroup(ep.tg.ProcessGroup())\n}\n- // Start signal forwarding only after an init process is created.\n- l.stopSignalForwarding = l.startSignalForwarding()\n+ // Handle signals by forwarding them to the root container process\n+ // (except for panic signal, which should cause a panic).\n+ l.stopSignalForwarding = sighandling.StartSignalForwarding(func(sig linux.Signal) {\n+ // Panic signal should cause a panic.\n+ if l.conf.PanicSignal != -1 && sig == linux.Signal(l.conf.PanicSignal) {\n+ panic(\"Signal-induced panic\")\n+ }\n+\n+ // Otherwise forward to root container.\n+ deliveryMode := DeliverToProcess\n+ if l.console {\n+ // Since we are running with a console, we should forward the signal to\n+ // the foreground process group so that job control signals like ^C can\n+ // be handled properly.\n+ deliveryMode = DeliverToForegroundProcessGroup\n+ }\n+ log.Infof(\"Received external signal %d, mode: %v\", sig, deliveryMode)\n+ if err := l.signal(l.sandboxID, 0, int32(sig), deliveryMode); err != nil {\n+ log.Warningf(\"error sending signal %v to container %q: %v\", sig, l.sandboxID, err)\n+ }\n+ })\nlog.Infof(\"Process should have started...\")\nl.watchdog.Start()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Bump up Go 1.13 as minimum requirement
PiperOrigin-RevId: 284320186 |
259,858 | 09.12.2019 11:21:37 | 28,800 | cf477c86ca8bfd27551c97aa4015364d30b98f2e | Mark runner_test as manual.
Because it is local-only, it should also be marked manual. | [
{
"change_type": "MODIFY",
"old_path": "benchmarks/runner/BUILD",
"new_path": "benchmarks/runner/BUILD",
"diff": "@@ -34,7 +34,10 @@ py_test(\nname = \"runner_test\",\nsrcs = [\"runner_test.py\"],\npython_version = \"PY3\",\n- tags = [\"local\"],\n+ tags = [\n+ \"local\",\n+ \"manual\",\n+ ],\ndeps = [\n\":runner\",\nrequirement(\"click\", True),\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/simple_tests.sh",
"new_path": "scripts/simple_tests.sh",
"diff": "source $(dirname $0)/common.sh\n# Run all simple tests (locally).\n-test //pkg/... //runsc/... //tools/... //benchmarks/...\n+test //pkg/... //runsc/... //tools/... //benchmarks/... //benchmarks/runner:runner_test\n"
}
] | Go | Apache License 2.0 | google/gvisor | Mark runner_test as manual.
Because it is local-only, it should also be marked manual.
PiperOrigin-RevId: 284596186 |
259,962 | 09.12.2019 12:03:16 | 28,800 | cb5f9b8f863c93bb7e3757c1f4b3e1a64e6acdfb | Mark test as non flaky. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -3272,8 +3272,6 @@ cc_binary(\ntestonly = 1,\nsrcs = [\"tcp_socket.cc\"],\nlinkstatic = 1,\n- # FIXME(b/135470853)\n- tags = [\"flaky\"],\ndeps = [\n\":socket_test_util\",\n\"//test/util:file_descriptor\",\n"
}
] | Go | Apache License 2.0 | google/gvisor | Mark test as non flaky.
PiperOrigin-RevId: 284606133 |
259,992 | 09.12.2019 12:03:31 | 28,800 | 898dcc2f839a975a9171271824af32176c2e5c27 | Redirect TODOs to gvisor.dev | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/gofer/session.go",
"new_path": "pkg/sentry/fs/gofer/session.go",
"diff": "@@ -143,9 +143,9 @@ type session struct {\n// socket files. This allows unix domain sockets to be used with paths that\n// belong to a gofer.\n//\n- // TODO(b/77154739): there are few possible races with someone stat'ing the\n- // file and another deleting it concurrently, where the file will not be\n- // reported as socket file.\n+ // TODO(gvisor.dev/issue/1200): there are few possible races with someone\n+ // stat'ing the file and another deleting it concurrently, where the file\n+ // will not be reported as socket file.\nendpoints *endpointMaps `state:\"wait\"`\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/semaphore/semaphore.go",
"new_path": "pkg/sentry/kernel/semaphore/semaphore.go",
"diff": "@@ -302,7 +302,7 @@ func (s *Set) SetVal(ctx context.Context, num int32, val int16, creds *auth.Cred\nreturn syserror.ERANGE\n}\n- // TODO(b/29354920): Clear undo entries in all processes\n+ // TODO(gvisor.dev/issue/137): Clear undo entries in all processes.\nsem.value = val\nsem.pid = pid\ns.changeTime = ktime.NowFromContext(ctx)\n@@ -336,7 +336,7 @@ func (s *Set) SetValAll(ctx context.Context, vals []uint16, creds *auth.Credenti\nfor i, val := range vals {\nsem := &s.sems[i]\n- // TODO(b/29354920): Clear undo entries in all processes\n+ // TODO(gvisor.dev/issue/137): Clear undo entries in all processes.\nsem.value = int16(val)\nsem.pid = pid\nsem.wakeWaiters()\n@@ -481,7 +481,7 @@ func (s *Set) executeOps(ctx context.Context, ops []linux.Sembuf, pid int32) (ch\n}\n// All operations succeeded, apply them.\n- // TODO(b/29354920): handle undo operations.\n+ // TODO(gvisor.dev/issue/137): handle undo operations.\nfor i, v := range tmpVals {\ns.sems[i].value = v\ns.sems[i].wakeWaiters()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/linux64_amd64.go",
"new_path": "pkg/sentry/syscalls/linux/linux64_amd64.go",
"diff": "@@ -260,7 +260,7 @@ var AMD64 = &kernel.SyscallTable{\n217: syscalls.Supported(\"getdents64\", Getdents64),\n218: syscalls.Supported(\"set_tid_address\", SetTidAddress),\n219: syscalls.Supported(\"restart_syscall\", RestartSyscall),\n- 220: syscalls.ErrorWithEvent(\"semtimedop\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/137\"}), // TODO(b/29354920)\n+ 220: syscalls.ErrorWithEvent(\"semtimedop\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/137\"}),\n221: syscalls.PartiallySupported(\"fadvise64\", Fadvise64, \"Not all options are supported.\", nil),\n222: syscalls.Supported(\"timer_create\", TimerCreate),\n223: syscalls.Supported(\"timer_settime\", TimerSettime),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/linux64_arm64.go",
"new_path": "pkg/sentry/syscalls/linux/linux64_arm64.go",
"diff": "@@ -224,7 +224,7 @@ var ARM64 = &kernel.SyscallTable{\n189: syscalls.ErrorWithEvent(\"msgsnd\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n190: syscalls.Supported(\"semget\", Semget),\n191: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options IPC_INFO, SEM_INFO, IPC_STAT, SEM_STAT, SEM_STAT_ANY, GETNCNT, GETZCNT not supported.\", nil),\n- 192: syscalls.ErrorWithEvent(\"semtimedop\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/137\"}), // TODO(b/29354920)\n+ 192: syscalls.ErrorWithEvent(\"semtimedop\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/137\"}),\n193: syscalls.PartiallySupported(\"semop\", Semop, \"Option SEM_UNDO not supported.\", nil),\n194: syscalls.PartiallySupported(\"shmget\", Shmget, \"Option SHM_HUGETLB is not supported.\", nil),\n195: syscalls.PartiallySupported(\"shmctl\", Shmctl, \"Options SHM_LOCK, SHM_UNLOCK are not supported.\", nil),\n"
}
] | Go | Apache License 2.0 | google/gvisor | Redirect TODOs to gvisor.dev
PiperOrigin-RevId: 284606233 |
259,854 | 09.12.2019 20:07:14 | 28,800 | 98aafb1334b816596b462ad12fa3e96784703061 | Add test for SO_BINDTODEVICE state bug.
This was accidentally dropped from the change which fixed the bug.
Updates | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_bind_to_device_sequence.cc",
"new_path": "test/syscalls/linux/socket_bind_to_device_sequence.cc",
"diff": "@@ -97,6 +97,16 @@ class BindToDeviceSequenceTest : public ::testing::TestWithParam<SocketKind> {\nsockets_to_close_.erase(socket_id);\n}\n+ // SetDevice changes the bind_to_device option. It does not bind or re-bind.\n+ void SetDevice(int socket_id, int device_id) {\n+ auto socket_fd = sockets_to_close_[socket_id]->get();\n+ string device_name;\n+ ASSERT_NO_FATAL_FAILURE(GetDevice(device_id, &device_name));\n+ EXPECT_THAT(setsockopt(socket_fd, SOL_SOCKET, SO_BINDTODEVICE,\n+ device_name.c_str(), device_name.size() + 1),\n+ SyscallSucceedsWithValue(0));\n+ }\n+\n// Bind a socket with the reuse options and bind_to_device options. Checks\n// that all steps succeed and that the bind command's error matches want.\n// Sets the socket_id to uniquely identify the socket bound if it is not\n@@ -474,6 +484,25 @@ TEST_P(BindToDeviceSequenceTest,\n/* bind_to_device */ 0));\n}\n+// Repro test for gvisor.dev/issue/1217. Not replicated in ports_test.go as this\n+// test is different from the others and wouldn't fit well there.\n+TEST_P(BindToDeviceSequenceTest, BindAndReleaseDifferentDevice) {\n+ int to_release;\n+ ASSERT_NO_FATAL_FAILURE(BindSocket(/* reuse_port */ false,\n+ /* reuse_addr */ false,\n+ /* bind_to_device */ 3, 0, &to_release));\n+ ASSERT_NO_FATAL_FAILURE(BindSocket(/* reuse_port */ false,\n+ /* reuse_addr */ false,\n+ /* bind_to_device */ 3, EADDRINUSE));\n+ // Change the device. Since the socket was already bound, this should have no\n+ // effect.\n+ SetDevice(to_release, 2);\n+ // Release the bind to device 3 and try again.\n+ ASSERT_NO_FATAL_FAILURE(ReleaseSocket(to_release));\n+ ASSERT_NO_FATAL_FAILURE(BindSocket(\n+ /* reuse_port */ false, /* reuse_addr */ false, /* bind_to_device */ 3));\n+}\n+\nINSTANTIATE_TEST_SUITE_P(BindToDeviceTest, BindToDeviceSequenceTest,\n::testing::Values(IPv4UDPUnboundSocket(0),\nIPv4TCPUnboundSocket(0)));\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add test for SO_BINDTODEVICE state bug.
This was accidentally dropped from the change which fixed the bug.
Updates #1217
PiperOrigin-RevId: 284689362 |
259,860 | 10.12.2019 09:32:47 | 28,800 | 4a19ebd431659578c9af0a91ff35d8b6d9de190e | Add hostinet tests for sendmsg and recvmsg with TOS/TCLASS. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/udp_socket_test_cases.cc",
"new_path": "test/syscalls/linux/udp_socket_test_cases.cc",
"diff": "@@ -1345,5 +1345,154 @@ TEST_P(UdpSocketTest, TimestampIoctlPersistence) {\nASSERT_EQ(tv.tv_usec, tv2.tv_usec);\n}\n+// Test that a socket with IP_TOS or IPV6_TCLASS set will set the TOS byte on\n+// outgoing packets, and that a receiving socket with IP_RECVTOS or\n+// IPV6_RECVTCLASS will create the corresponding control message.\n+TEST_P(UdpSocketTest, SetAndReceiveTOS) {\n+ // TODO(b/68320120): IP_RECVTOS/IPV6_RECVTCLASS not supported for netstack.\n+ SKIP_IF(IsRunningOnGvisor() && !IsRunningWithHostinet());\n+ ASSERT_THAT(bind(s_, addr_[0], addrlen_), SyscallSucceeds());\n+ ASSERT_THAT(connect(t_, addr_[0], addrlen_), SyscallSucceeds());\n+\n+ // Allow socket to receive control message.\n+ int recv_level = SOL_IP;\n+ int recv_type = IP_RECVTOS;\n+ if (GetParam() != AddressFamily::kIpv4) {\n+ recv_level = SOL_IPV6;\n+ recv_type = IPV6_RECVTCLASS;\n+ }\n+ ASSERT_THAT(\n+ setsockopt(s_, recv_level, recv_type, &kSockOptOn, sizeof(kSockOptOn)),\n+ SyscallSucceeds());\n+\n+ // Set socket TOS.\n+ int sent_level = recv_level;\n+ int sent_type = IP_TOS;\n+ if (sent_level == SOL_IPV6) {\n+ sent_type = IPV6_TCLASS;\n+ }\n+ int sent_tos = IPTOS_LOWDELAY; // Choose some TOS value.\n+ ASSERT_THAT(\n+ setsockopt(t_, sent_level, sent_type, &sent_tos, sizeof(sent_tos)),\n+ SyscallSucceeds());\n+\n+ // Prepare message to send.\n+ constexpr size_t kDataLength = 1024;\n+ struct msghdr sent_msg = {};\n+ struct iovec sent_iov = {};\n+ char sent_data[kDataLength];\n+ sent_iov.iov_base = &sent_data[0];\n+ sent_iov.iov_len = kDataLength;\n+ sent_msg.msg_iov = &sent_iov;\n+ sent_msg.msg_iovlen = 1;\n+\n+ ASSERT_THAT(RetryEINTR(sendmsg)(t_, &sent_msg, 0),\n+ SyscallSucceedsWithValue(kDataLength));\n+\n+ // Receive message.\n+ struct msghdr received_msg = {};\n+ struct iovec received_iov = {};\n+ char received_data[kDataLength];\n+ received_iov.iov_base = &received_data[0];\n+ received_iov.iov_len = kDataLength;\n+ received_msg.msg_iov = &received_iov;\n+ received_msg.msg_iovlen = 1;\n+ size_t cmsg_data_len = sizeof(int8_t);\n+ if (sent_type == IPV6_TCLASS) {\n+ cmsg_data_len = sizeof(int);\n+ }\n+ std::vector<char> received_cmsgbuf(CMSG_SPACE(cmsg_data_len));\n+ received_msg.msg_control = &received_cmsgbuf[0];\n+ received_msg.msg_controllen = received_cmsgbuf.size();\n+ ASSERT_THAT(RetryEINTR(recvmsg)(s_, &received_msg, 0),\n+ SyscallSucceedsWithValue(kDataLength));\n+\n+ struct cmsghdr* cmsg = CMSG_FIRSTHDR(&received_msg);\n+ ASSERT_NE(cmsg, nullptr);\n+ EXPECT_EQ(cmsg->cmsg_len, CMSG_LEN(cmsg_data_len));\n+ EXPECT_EQ(cmsg->cmsg_level, sent_level);\n+ EXPECT_EQ(cmsg->cmsg_type, sent_type);\n+ int8_t received_tos = 0;\n+ memcpy(&received_tos, CMSG_DATA(cmsg), sizeof(received_tos));\n+ EXPECT_EQ(received_tos, sent_tos);\n+}\n+\n+// Test that sendmsg with IP_TOS and IPV6_TCLASS control messages will set the\n+// TOS byte on outgoing packets, and that a receiving socket with IP_RECVTOS or\n+// IPV6_RECVTCLASS will create the corresponding control message.\n+TEST_P(UdpSocketTest, SendAndReceiveTOS) {\n+ // TODO(b/68320120): IP_RECVTOS/IPV6_RECVTCLASS not supported for netstack.\n+ SKIP_IF(IsRunningOnGvisor() && !IsRunningWithHostinet());\n+ ASSERT_THAT(bind(s_, addr_[0], addrlen_), SyscallSucceeds());\n+ ASSERT_THAT(connect(t_, addr_[0], addrlen_), SyscallSucceeds());\n+\n+ // Allow socket to receive control message.\n+ int recv_level = SOL_IP;\n+ int recv_type = IP_RECVTOS;\n+ if (GetParam() != AddressFamily::kIpv4) {\n+ recv_level = SOL_IPV6;\n+ recv_type = IPV6_RECVTCLASS;\n+ }\n+ int recv_opt = kSockOptOn;\n+ ASSERT_THAT(\n+ setsockopt(s_, recv_level, recv_type, &recv_opt, sizeof(recv_opt)),\n+ SyscallSucceeds());\n+\n+ // Prepare message to send.\n+ constexpr size_t kDataLength = 1024;\n+ int sent_level = recv_level;\n+ int sent_type = IP_TOS;\n+ int sent_tos = IPTOS_LOWDELAY; // Choose some TOS value.\n+\n+ struct msghdr sent_msg = {};\n+ struct iovec sent_iov = {};\n+ char sent_data[kDataLength];\n+ sent_iov.iov_base = &sent_data[0];\n+ sent_iov.iov_len = kDataLength;\n+ sent_msg.msg_iov = &sent_iov;\n+ sent_msg.msg_iovlen = 1;\n+ size_t cmsg_data_len = sizeof(int8_t);\n+ if (sent_level == SOL_IPV6) {\n+ sent_type = IPV6_TCLASS;\n+ cmsg_data_len = sizeof(int);\n+ }\n+ std::vector<char> sent_cmsgbuf(CMSG_SPACE(cmsg_data_len));\n+ sent_msg.msg_control = &sent_cmsgbuf[0];\n+ sent_msg.msg_controllen = CMSG_LEN(cmsg_data_len);\n+\n+ // Manually add control message.\n+ struct cmsghdr* sent_cmsg = CMSG_FIRSTHDR(&sent_msg);\n+ sent_cmsg->cmsg_len = CMSG_LEN(cmsg_data_len);\n+ sent_cmsg->cmsg_level = sent_level;\n+ sent_cmsg->cmsg_type = sent_type;\n+ *(int8_t*)CMSG_DATA(sent_cmsg) = sent_tos;\n+\n+ ASSERT_THAT(RetryEINTR(sendmsg)(t_, &sent_msg, 0),\n+ SyscallSucceedsWithValue(kDataLength));\n+\n+ // Receive message.\n+ struct msghdr received_msg = {};\n+ struct iovec received_iov = {};\n+ char received_data[kDataLength];\n+ received_iov.iov_base = &received_data[0];\n+ received_iov.iov_len = kDataLength;\n+ received_msg.msg_iov = &received_iov;\n+ received_msg.msg_iovlen = 1;\n+ std::vector<char> received_cmsgbuf(CMSG_SPACE(cmsg_data_len));\n+ received_msg.msg_control = &received_cmsgbuf[0];\n+ received_msg.msg_controllen = CMSG_LEN(cmsg_data_len);\n+ ASSERT_THAT(RetryEINTR(recvmsg)(s_, &received_msg, 0),\n+ SyscallSucceedsWithValue(kDataLength));\n+\n+ struct cmsghdr* cmsg = CMSG_FIRSTHDR(&received_msg);\n+ ASSERT_NE(cmsg, nullptr);\n+ EXPECT_EQ(cmsg->cmsg_len, CMSG_LEN(cmsg_data_len));\n+ EXPECT_EQ(cmsg->cmsg_level, sent_level);\n+ EXPECT_EQ(cmsg->cmsg_type, sent_type);\n+ int8_t received_tos = 0;\n+ memcpy(&received_tos, CMSG_DATA(cmsg), sizeof(received_tos));\n+ EXPECT_EQ(received_tos, sent_tos);\n+}\n+\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add hostinet tests for sendmsg and recvmsg with TOS/TCLASS.
PiperOrigin-RevId: 284786069 |
259,860 | 10.12.2019 09:36:52 | 28,800 | aadbf322c63b0aa1d34cd9755dc1266af2e5ac58 | Disable execveat test that is causing files in /bin to be deleted.
Disable until gvisor.dev/issue/1366 is resolved.
Updates | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/exec.cc",
"new_path": "test/syscalls/linux/exec.cc",
"diff": "@@ -696,15 +696,6 @@ TEST(ExecveatTest, SymlinkNoFollowAndEmptyPath) {\nArgEnvExitStatus(0, 0), absl::StrCat(path, \"\\n\"));\n}\n-TEST(ExecveatTest, SymlinkNoFollowIgnoreSymlinkAncestor) {\n- TempPath parent_link =\n- ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateSymlinkTo(\"/tmp\", \"/bin\"));\n- std::string path_with_symlink = JoinPath(parent_link.path(), \"echo\");\n-\n- CheckExecveat(AT_FDCWD, path_with_symlink, {path_with_symlink}, {},\n- AT_SYMLINK_NOFOLLOW, ArgEnvExitStatus(0, 0), \"\");\n-}\n-\nTEST(ExecveatTest, SymlinkNoFollowWithNormalFile) {\nconst FileDescriptor dirfd =\nASSERT_NO_ERRNO_AND_VALUE(Open(\"/bin\", O_DIRECTORY));\n"
}
] | Go | Apache License 2.0 | google/gvisor | Disable execveat test that is causing files in /bin to be deleted.
Disable until gvisor.dev/issue/1366 is resolved.
Updates #1366
PiperOrigin-RevId: 284786895 |
259,860 | 10.12.2019 09:59:36 | 28,800 | 30f7316dc4a5fe0346c6e2e8e6854bd48a316a82 | Make comments clearer for control message handling. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/control/control.go",
"new_path": "pkg/sentry/socket/control/control.go",
"diff": "@@ -195,15 +195,15 @@ func putCmsg(buf []byte, flags int, msgType uint32, align uint, data []int32) ([\n// the available space, we must align down.\n//\n// align must be >= 4 and each data int32 is 4 bytes. The length of the\n- // header is already aligned, so if we align to the with of the data there\n+ // header is already aligned, so if we align to the width of the data there\n// are two cases:\n// 1. The aligned length is less than the length of the header. The\n// unaligned length was also less than the length of the header, so we\n// can't write anything.\n// 2. The aligned length is greater than or equal to the length of the\n- // header. We can write the header plus zero or more datas. We can't write\n- // a partial int32, so the length of the message will be\n- // min(aligned length, header + datas).\n+ // header. We can write the header plus zero or more bytes of data. We can't\n+ // write a partial int32, so the length of the message will be\n+ // min(aligned length, header + data).\nif space < linux.SizeOfControlMessageHeader {\nflags |= linux.MSG_CTRUNC\nreturn buf, flags\n@@ -240,12 +240,12 @@ func putCmsgStruct(buf []byte, msgLevel, msgType uint32, align uint, data interf\nbuf = binary.Marshal(buf, usermem.ByteOrder, data)\n- // Check if we went over.\n+ // If the control message data brought us over capacity, omit it.\nif cap(buf) != cap(ob) {\nreturn hdrBuf\n}\n- // Fix up length.\n+ // Update control message length to include data.\nputUint64(ob, uint64(len(buf)-len(ob)))\nreturn alignSlice(buf, align)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Make comments clearer for control message handling.
PiperOrigin-RevId: 284791600 |
259,860 | 10.12.2019 10:55:08 | 28,800 | f47eaffd5c59445b8cafda1b7a51e7f4be5d254a | Do not consider symlinks as directories in fs utils.
IsDirectory() is used in RecursivelyDelete(), which should not follow symlinks.
The only other use (syscalls/linux/rename.cc) is not affected by this change.
Updates | [
{
"change_type": "MODIFY",
"old_path": "test/util/fs_util.cc",
"new_path": "test/util/fs_util.cc",
"diff": "@@ -105,6 +105,15 @@ PosixErrorOr<struct stat> Stat(absl::string_view path) {\nreturn stat_buf;\n}\n+PosixErrorOr<struct stat> Lstat(absl::string_view path) {\n+ struct stat stat_buf;\n+ int res = lstat(std::string(path).c_str(), &stat_buf);\n+ if (res < 0) {\n+ return PosixError(errno, absl::StrCat(\"lstat \", path));\n+ }\n+ return stat_buf;\n+}\n+\nPosixErrorOr<struct stat> Fstat(int fd) {\nstruct stat stat_buf;\nint res = fstat(fd, &stat_buf);\n@@ -127,7 +136,7 @@ PosixErrorOr<bool> Exists(absl::string_view path) {\n}\nPosixErrorOr<bool> IsDirectory(absl::string_view path) {\n- ASSIGN_OR_RETURN_ERRNO(struct stat stat_buf, Stat(path));\n+ ASSIGN_OR_RETURN_ERRNO(struct stat stat_buf, Lstat(path));\nif (S_ISDIR(stat_buf.st_mode)) {\nreturn true;\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Do not consider symlinks as directories in fs utils.
IsDirectory() is used in RecursivelyDelete(), which should not follow symlinks.
The only other use (syscalls/linux/rename.cc) is not affected by this change.
Updates #1366.
PiperOrigin-RevId: 284803968 |
259,860 | 10.12.2019 10:56:51 | 28,800 | f6e87be82f189d7d2176dc2ca4a2d261481a032a | Let socket.ControlMessages Release() the underlying transport.ControlMessages. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/socket.go",
"new_path": "pkg/sentry/socket/socket.go",
"diff": "@@ -43,6 +43,11 @@ type ControlMessages struct {\nIP tcpip.ControlMessages\n}\n+// Release releases Unix domain socket credentials and rights.\n+func (c *ControlMessages) Release() {\n+ c.Unix.Release()\n+}\n+\n// Socket is the interface containing socket syscalls used by the syscall layer\n// to redirect them to the appropriate implementation.\ntype Socket interface {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_socket.go",
"new_path": "pkg/sentry/syscalls/linux/sys_socket.go",
"diff": "@@ -764,7 +764,7 @@ func recvSingleMsg(t *kernel.Task, s socket.Socket, msgPtr usermem.Addr, flags i\n}\nif !cms.Unix.Empty() {\nmflags |= linux.MSG_CTRUNC\n- cms.Unix.Release()\n+ cms.Release()\n}\nif int(msg.Flags) != mflags {\n@@ -784,7 +784,7 @@ func recvSingleMsg(t *kernel.Task, s socket.Socket, msgPtr usermem.Addr, flags i\nif e != nil {\nreturn 0, syserror.ConvertIntr(e.ToError(), kernel.ERESTARTSYS)\n}\n- defer cms.Unix.Release()\n+ defer cms.Release()\ncontrolData := make([]byte, 0, msg.ControlLen)\n@@ -885,7 +885,7 @@ func recvFrom(t *kernel.Task, fd int32, bufPtr usermem.Addr, bufLen uint64, flag\n}\nn, _, sender, senderLen, cm, e := s.RecvMsg(t, dst, int(flags), haveDeadline, deadline, nameLenPtr != 0, 0)\n- cm.Unix.Release()\n+ cm.Release()\nif e != nil {\nreturn 0, syserror.ConvertIntr(e.ToError(), kernel.ERESTARTSYS)\n}\n@@ -1071,7 +1071,7 @@ func sendSingleMsg(t *kernel.Task, s socket.Socket, file *fs.File, msgPtr userme\nn, e := s.SendMsg(t, src, to, int(flags), haveDeadline, deadline, controlMessages)\nerr = handleIOError(t, n != 0, e.ToError(), kernel.ERESTARTSYS, \"sendmsg\", file)\nif err != nil {\n- controlMessages.Unix.Release()\n+ controlMessages.Release()\n}\nreturn uintptr(n), err\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Let socket.ControlMessages Release() the underlying transport.ControlMessages.
PiperOrigin-RevId: 284804370 |
259,860 | 10.12.2019 11:40:29 | 28,800 | 769e1cdcbe539ca2347ad5ccd2706ae17777aed9 | Re-enable execveat test that was causing files in /bin to be deleted.
Test now no longer deletes files incorrectly, due to a fix in fs utils
used by TempPath (github.com/google/gvisor/pull/1368).
Fixes | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/exec.cc",
"new_path": "test/syscalls/linux/exec.cc",
"diff": "@@ -696,6 +696,15 @@ TEST(ExecveatTest, SymlinkNoFollowAndEmptyPath) {\nArgEnvExitStatus(0, 0), absl::StrCat(path, \"\\n\"));\n}\n+TEST(ExecveatTest, SymlinkNoFollowIgnoreSymlinkAncestor) {\n+ TempPath parent_link =\n+ ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateSymlinkTo(\"/tmp\", \"/bin\"));\n+ std::string path_with_symlink = JoinPath(parent_link.path(), \"echo\");\n+\n+ CheckExecveat(AT_FDCWD, path_with_symlink, {path_with_symlink}, {},\n+ AT_SYMLINK_NOFOLLOW, ArgEnvExitStatus(0, 0), \"\");\n+}\n+\nTEST(ExecveatTest, SymlinkNoFollowWithNormalFile) {\nconst FileDescriptor dirfd =\nASSERT_NO_ERRNO_AND_VALUE(Open(\"/bin\", O_DIRECTORY));\n"
}
] | Go | Apache License 2.0 | google/gvisor | Re-enable execveat test that was causing files in /bin to be deleted.
Test now no longer deletes files incorrectly, due to a fix in fs utils
used by TempPath (github.com/google/gvisor/pull/1368).
Fixes #1366
PiperOrigin-RevId: 284814605 |
259,860 | 10.12.2019 13:04:32 | 28,800 | 39386d78bb9636e52d6a0487d5fa7bff6beab64e | Format fd_set parameters in select(2)/pselect(2) for strace.
I1202 14:55:06.835076 7991 x:0] [ 1] select_test E
select(0xa, 0x7fc6ce924c28 [0 1], null, null, 0x7fc6ce924c08 {sec=0 usec=0})
I1202 14:55:06.835102 7991 x:0] [ 1] select_test X
select(0xa, 0x7fc6ce924c28 [0 1], null, null, 0x7fc6ce924c08 {sec=0 usec=0}) | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/strace/BUILD",
"new_path": "pkg/sentry/strace/BUILD",
"diff": "@@ -14,6 +14,7 @@ go_library(\n\"open.go\",\n\"poll.go\",\n\"ptrace.go\",\n+ \"select.go\",\n\"signal.go\",\n\"socket.go\",\n\"strace.go\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/strace/linux64.go",
"new_path": "pkg/sentry/strace/linux64.go",
"diff": "@@ -40,7 +40,7 @@ var linuxAMD64 = SyscallMap{\n20: makeSyscallInfo(\"writev\", FD, WriteIOVec, Hex),\n21: makeSyscallInfo(\"access\", Path, Oct),\n22: makeSyscallInfo(\"pipe\", PipeFDs),\n- 23: makeSyscallInfo(\"select\", Hex, Hex, Hex, Hex, Timeval),\n+ 23: makeSyscallInfo(\"select\", Hex, SelectFDSet, SelectFDSet, SelectFDSet, Timeval),\n24: makeSyscallInfo(\"sched_yield\"),\n25: makeSyscallInfo(\"mremap\", Hex, Hex, Hex, Hex, Hex),\n26: makeSyscallInfo(\"msync\", Hex, Hex, Hex),\n@@ -287,7 +287,7 @@ var linuxAMD64 = SyscallMap{\n267: makeSyscallInfo(\"readlinkat\", FD, Path, ReadBuffer, Hex),\n268: makeSyscallInfo(\"fchmodat\", FD, Path, Mode),\n269: makeSyscallInfo(\"faccessat\", FD, Path, Oct, Hex),\n- 270: makeSyscallInfo(\"pselect6\", Hex, Hex, Hex, Hex, Hex, Hex),\n+ 270: makeSyscallInfo(\"pselect6\", Hex, SelectFDSet, SelectFDSet, SelectFDSet, Timespec, SigSet),\n271: makeSyscallInfo(\"ppoll\", PollFDs, Hex, Timespec, SigSet, Hex),\n272: makeSyscallInfo(\"unshare\", CloneFlags),\n273: makeSyscallInfo(\"set_robust_list\", Hex, Hex),\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/strace/select.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 strace\n+\n+import (\n+ \"fmt\"\n+\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/syscalls/linux\"\n+ \"gvisor.dev/gvisor/pkg/sentry/usermem\"\n+)\n+\n+func fdsFromSet(t *kernel.Task, set []byte) []int {\n+ var fds []int\n+ // Append n if the n-th bit is 1.\n+ for i, v := range set {\n+ for j := 0; j < 8; j++ {\n+ if (v>>uint(j))&1 == 1 {\n+ fds = append(fds, i*8+j)\n+ }\n+ }\n+ }\n+ return fds\n+}\n+\n+func fdSet(t *kernel.Task, nfds int, addr usermem.Addr) string {\n+ if addr == 0 {\n+ return \"null\"\n+ }\n+\n+ // Calculate the size of the fd set (one bit per fd).\n+ nBytes := (nfds + 7) / 8\n+ nBitsInLastPartialByte := uint(nfds % 8)\n+\n+ set, err := linux.CopyInFDSet(t, addr, nBytes, nBitsInLastPartialByte)\n+ if err != nil {\n+ return fmt.Sprintf(\"%#x (error decoding fdset: %s)\", addr, err)\n+ }\n+\n+ return fmt.Sprintf(\"%#x %v\", addr, fdsFromSet(t, set))\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/strace/strace.go",
"new_path": "pkg/sentry/strace/strace.go",
"diff": "@@ -439,6 +439,8 @@ func (i *SyscallInfo) pre(t *kernel.Task, args arch.SyscallArguments, maximumBlo\noutput = append(output, capData(t, args[arg-1].Pointer(), args[arg].Pointer()))\ncase PollFDs:\noutput = append(output, pollFDs(t, args[arg].Pointer(), uint(args[arg+1].Uint()), false))\n+ case SelectFDSet:\n+ output = append(output, fdSet(t, int(args[0].Int()), args[arg].Pointer()))\ncase Oct:\noutput = append(output, \"0o\"+strconv.FormatUint(args[arg].Uint64(), 8))\ncase Hex:\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/strace/syscalls.go",
"new_path": "pkg/sentry/strace/syscalls.go",
"diff": "@@ -206,6 +206,10 @@ const (\n// PollFDs is an array of struct pollfd. The number of entries in the\n// array is in the next argument.\nPollFDs\n+\n+ // SelectFDSet is an fd_set argument in select(2)/pselect(2). The number of\n+ // fds represented must be the first argument.\n+ SelectFDSet\n)\n// defaultFormat is the syscall argument format to use if the actual format is\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_poll.go",
"new_path": "pkg/sentry/syscalls/linux/sys_poll.go",
"diff": "@@ -197,53 +197,51 @@ func doPoll(t *kernel.Task, addr usermem.Addr, nfds uint, timeout time.Duration)\nreturn remainingTimeout, n, err\n}\n-func doSelect(t *kernel.Task, nfds int, readFDs, writeFDs, exceptFDs usermem.Addr, timeout time.Duration) (uintptr, error) {\n- if nfds < 0 || nfds > fileCap {\n- return 0, syserror.EINVAL\n- }\n+// CopyInFDSet copies an fd set from select(2)/pselect(2).\n+func CopyInFDSet(t *kernel.Task, addr usermem.Addr, nBytes int, nBitsInLastPartialByte uint) ([]byte, error) {\n+ set := make([]byte, nBytes)\n- // Capture all the provided input vectors.\n+ if addr != 0 {\n+ if _, err := t.CopyIn(addr, &set); err != nil {\n+ return nil, err\n+ }\n+ // If we only use part of the last byte, mask out the extraneous bits.\n//\n// N.B. This only works on little-endian architectures.\n- byteCount := (nfds + 7) / 8\n-\n- bitsInLastPartialByte := uint(nfds % 8)\n- r := make([]byte, byteCount)\n- w := make([]byte, byteCount)\n- e := make([]byte, byteCount)\n-\n- if readFDs != 0 {\n- if _, err := t.CopyIn(readFDs, &r); err != nil {\n- return 0, err\n+ if nBitsInLastPartialByte != 0 {\n+ set[nBytes-1] &^= byte(0xff) << nBitsInLastPartialByte\n}\n- // Mask out bits above nfds.\n- if bitsInLastPartialByte != 0 {\n- r[byteCount-1] &^= byte(0xff) << bitsInLastPartialByte\n}\n+ return set, nil\n}\n- if writeFDs != 0 {\n- if _, err := t.CopyIn(writeFDs, &w); err != nil {\n- return 0, err\n- }\n- if bitsInLastPartialByte != 0 {\n- w[byteCount-1] &^= byte(0xff) << bitsInLastPartialByte\n- }\n+func doSelect(t *kernel.Task, nfds int, readFDs, writeFDs, exceptFDs usermem.Addr, timeout time.Duration) (uintptr, error) {\n+ if nfds < 0 || nfds > fileCap {\n+ return 0, syserror.EINVAL\n}\n- if exceptFDs != 0 {\n- if _, err := t.CopyIn(exceptFDs, &e); err != nil {\n+ // Calculate the size of the fd sets (one bit per fd).\n+ nBytes := (nfds + 7) / 8\n+ nBitsInLastPartialByte := uint(nfds % 8)\n+\n+ // Capture all the provided input vectors.\n+ r, err := CopyInFDSet(t, readFDs, nBytes, nBitsInLastPartialByte)\n+ if err != nil {\nreturn 0, err\n}\n- if bitsInLastPartialByte != 0 {\n- e[byteCount-1] &^= byte(0xff) << bitsInLastPartialByte\n+ w, err := CopyInFDSet(t, writeFDs, nBytes, nBitsInLastPartialByte)\n+ if err != nil {\n+ return 0, err\n}\n+ e, err := CopyInFDSet(t, exceptFDs, nBytes, nBitsInLastPartialByte)\n+ if err != nil {\n+ return 0, err\n}\n// Count how many FDs are actually being requested so that we can build\n// a PollFD array.\nfdCount := 0\n- for i := 0; i < byteCount; i++ {\n+ for i := 0; i < nBytes; i++ {\nv := r[i] | w[i] | e[i]\nfor v != 0 {\nv &= (v - 1)\n@@ -254,7 +252,7 @@ func doSelect(t *kernel.Task, nfds int, readFDs, writeFDs, exceptFDs usermem.Add\n// Build the PollFD array.\npfd := make([]linux.PollFD, 0, fdCount)\nvar fd int32\n- for i := 0; i < byteCount; i++ {\n+ for i := 0; i < nBytes; i++ {\nrV, wV, eV := r[i], w[i], e[i]\nv := rV | wV | eV\nm := byte(1)\n@@ -295,8 +293,7 @@ func doSelect(t *kernel.Task, nfds int, readFDs, writeFDs, exceptFDs usermem.Add\n}\n// Do the syscall, then count the number of bits set.\n- _, _, err := pollBlock(t, pfd, timeout)\n- if err != nil {\n+ if _, _, err = pollBlock(t, pfd, timeout); err != nil {\nreturn 0, syserror.ConvertIntr(err, syserror.EINTR)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Format fd_set parameters in select(2)/pselect(2) for strace.
I1202 14:55:06.835076 7991 x:0] [ 1] select_test E
select(0xa, 0x7fc6ce924c28 [0 1], null, null, 0x7fc6ce924c08 {sec=0 usec=0})
I1202 14:55:06.835102 7991 x:0] [ 1] select_test X
select(0xa, 0x7fc6ce924c28 [0 1], null, null, 0x7fc6ce924c08 {sec=0 usec=0})
PiperOrigin-RevId: 284831805 |
259,847 | 10.12.2019 13:24:11 | 28,800 | 87337e92e3a65e69f6bfc6ac7d162c1b6ed18048 | Add Kokoro configs for publishing Kythe xrefs. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "kokoro/kythe/generate_xrefs.cfg",
"diff": "+build_file: \"gvisor/kokoro/kythe/generate_xrefs.sh\"\n+\n+before_action {\n+ fetch_keystore {\n+ keystore_resource {\n+ keystore_config_id: 73898\n+ keyname: \"kokoro-rbe-service-account\"\n+ }\n+ }\n+}\n+\n+bazel_setting {\n+ project_id: \"gvisor-rbe\"\n+ local_execution: false\n+ auth_credential: {\n+ keystore_config_id: 73898\n+ keyname: \"kokoro-rbe-service-account\"\n+ }\n+ bes_backend_address: \"buildeventservice.googleapis.com\"\n+ foundry_backend_address: \"remotebuildexecution.googleapis.com\"\n+ upsalite_frontend_address: \"https://source.cloud.google.com\"\n+}\n+\n+action {\n+ define_artifacts {\n+ regex: \"*.kzip\"\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "kokoro/kythe/generate_xrefs.sh",
"diff": "+#!/bin/bash\n+\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+# 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+set -ex\n+\n+# Install the latest version of Bazel. The default on Kokoro images is out of\n+# date.\n+if command -v use_bazel.sh >/dev/null; then\n+ use_bazel.sh latest\n+fi\n+bazel version\n+\n+# We need to use python 3.6 (the Kokoro PY3 default is 3.4) to compile `//...`\n+# because benchmarktools requires a version of `requests` that is not a\n+# available in 3.4.\n+pyenv versions\n+pyenv global 3.6.1\n+\n+readonly KYTHE_VERSION='v0.0.37'\n+readonly WORKDIR=\"$(mktemp -d)\"\n+readonly KYTHE_DIR=\"${WORKDIR}/kythe-${KYTHE_VERSION}\"\n+if [[ -n \"$KOKORO_GIT_COMMIT\" ]]; then\n+ readonly KZIP_FILENAME=\"${KOKORO_ARTIFACTS_DIR}/${KOKORO_GIT_COMMIT}.kzip\"\n+else\n+ readonly KZIP_FILENAME=\"$(git rev-parse HEAD).kzip\"\n+fi\n+\n+wget -q -O \"${WORKDIR}/kythe.tar.gz\" \\\n+ \"https://github.com/kythe/kythe/releases/download/${KYTHE_VERSION}/kythe-${KYTHE_VERSION}.tar.gz\"\n+tar --no-same-owner -xzf \"${WORKDIR}/kythe.tar.gz\" --directory \"$WORKDIR\"\n+\n+if [[ -n \"$KOKORO_ARTIFACTS_DIR\" ]]; then\n+ cd \"${KOKORO_ARTIFACTS_DIR}/github/gvisor\"\n+fi\n+bazel \\\n+ --bazelrc=\"${KYTHE_DIR}/extractors.bazelrc\" \\\n+ build \\\n+ --override_repository kythe_release=\"${KYTHE_DIR}\" \\\n+ --define=kythe_corpus=gvisor.dev \\\n+ //...\n+\n+\"${KYTHE_DIR}/tools/kzip\" merge \\\n+ --output \"$KZIP_FILENAME\" \\\n+ $(find -L bazel-out/*/extra_actions/ -name '*.kzip')\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add Kokoro configs for publishing Kythe xrefs.
PiperOrigin-RevId: 284835614 |
259,847 | 10.12.2019 14:54:04 | 28,800 | a0aa784ecfb0d5ef94decf3c2be3e1cd44b6cbc6 | Remove pyenv calls but log the python 3 version in use.
Apparently our Kokoro VM images don't have pyenv -- I previously tested this on
the Kokoro QA shared pool. | [
{
"change_type": "MODIFY",
"old_path": "kokoro/kythe/generate_xrefs.sh",
"new_path": "kokoro/kythe/generate_xrefs.sh",
"diff": "@@ -23,11 +23,7 @@ if command -v use_bazel.sh >/dev/null; then\nfi\nbazel version\n-# We need to use python 3.6 (the Kokoro PY3 default is 3.4) to compile `//...`\n-# because benchmarktools requires a version of `requests` that is not a\n-# available in 3.4.\n-pyenv versions\n-pyenv global 3.6.1\n+python3 -V\nreadonly KYTHE_VERSION='v0.0.37'\nreadonly WORKDIR=\"$(mktemp -d)\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove pyenv calls but log the python 3 version in use.
Apparently our Kokoro VM images don't have pyenv -- I previously tested this on
the Kokoro QA shared pool.
PiperOrigin-RevId: 284855160 |
259,860 | 10.12.2019 19:14:05 | 28,800 | 2e3b9b0a68d8f191d061008feda6e4a4ce202a78 | Deduplicate and simplify control message processing for recvmsg and sendmsg.
Also, improve performance by calculating how much space is needed before making
an allocation for sendmsg in hostinet. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/control/control.go",
"new_path": "pkg/sentry/socket/control/control.go",
"diff": "@@ -348,43 +348,62 @@ func PackTClass(t *kernel.Task, tClass int32, buf []byte) []byte {\n)\n}\n-func addSpaceForCmsg(cmsgDataLen int, buf []byte) []byte {\n- newBuf := make([]byte, 0, len(buf)+linux.SizeOfControlMessageHeader+cmsgDataLen)\n- return append(newBuf, buf...)\n-}\n-\n-// PackControlMessages converts the given ControlMessages struct into a buffer.\n+// PackControlMessages packs control messages into the given buffer.\n+//\n// We skip control messages specific to Unix domain sockets.\n-func PackControlMessages(t *kernel.Task, cmsgs socket.ControlMessages) []byte {\n- var buf []byte\n- // The use of t.Arch().Width() is analogous to Linux's use of sizeof(long) in\n- // CMSG_ALIGN.\n- width := t.Arch().Width()\n-\n+//\n+// Note that some control messages may be truncated if they do not fit under\n+// the capacity of buf.\n+func PackControlMessages(t *kernel.Task, cmsgs socket.ControlMessages, buf []byte) []byte {\nif cmsgs.IP.HasTimestamp {\n- buf = addSpaceForCmsg(int(width), buf)\nbuf = PackTimestamp(t, cmsgs.IP.Timestamp, buf)\n}\nif cmsgs.IP.HasInq {\n// In Linux, TCP_CM_INQ is added after SO_TIMESTAMP.\n- buf = addSpaceForCmsg(AlignUp(linux.SizeOfControlMessageInq, width), buf)\nbuf = PackInq(t, cmsgs.IP.Inq, buf)\n}\nif cmsgs.IP.HasTOS {\n- buf = addSpaceForCmsg(AlignUp(linux.SizeOfControlMessageTOS, width), buf)\nbuf = PackTOS(t, cmsgs.IP.TOS, buf)\n}\nif cmsgs.IP.HasTClass {\n- buf = addSpaceForCmsg(AlignUp(linux.SizeOfControlMessageTClass, width), buf)\nbuf = PackTClass(t, cmsgs.IP.TClass, buf)\n}\nreturn buf\n}\n+// cmsgSpace is equivalent to CMSG_SPACE in Linux.\n+func cmsgSpace(t *kernel.Task, dataLen int) int {\n+ return linux.SizeOfControlMessageHeader + AlignUp(dataLen, t.Arch().Width())\n+}\n+\n+// CmsgsSpace returns the number of bytes needed to fit the control messages\n+// represented in cmsgs.\n+func CmsgsSpace(t *kernel.Task, cmsgs socket.ControlMessages) int {\n+ space := 0\n+\n+ if cmsgs.IP.HasTimestamp {\n+ space += cmsgSpace(t, linux.SizeOfTimeval)\n+ }\n+\n+ if cmsgs.IP.HasInq {\n+ space += cmsgSpace(t, linux.SizeOfControlMessageInq)\n+ }\n+\n+ if cmsgs.IP.HasTOS {\n+ space += cmsgSpace(t, linux.SizeOfControlMessageTOS)\n+ }\n+\n+ if cmsgs.IP.HasTClass {\n+ space += cmsgSpace(t, linux.SizeOfControlMessageTClass)\n+ }\n+\n+ return space\n+}\n+\n// Parse parses a raw socket control message into portable objects.\nfunc Parse(t *kernel.Task, socketOrEndpoint interface{}, buf []byte) (socket.ControlMessages, error) {\nvar (\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/hostinet/socket.go",
"new_path": "pkg/sentry/socket/hostinet/socket.go",
"diff": "@@ -45,7 +45,7 @@ const (\nsizeofSockaddr = syscall.SizeofSockaddrInet6 // sizeof(sockaddr_in6) > sizeof(sockaddr_in)\n// maxControlLen is the maximum size of a control message buffer used in a\n- // recvmsg syscall.\n+ // recvmsg or sendmsg syscall.\nmaxControlLen = 1024\n)\n@@ -412,9 +412,12 @@ func (s *socketOperations) RecvMsg(t *kernel.Task, dst usermem.IOSequence, flags\nmsg.Namelen = uint32(len(senderAddrBuf))\n}\nif controlLen > 0 {\n- controlBuf = make([]byte, maxControlLen)\n+ if controlLen > maxControlLen {\n+ controlLen = maxControlLen\n+ }\n+ controlBuf = make([]byte, controlLen)\nmsg.Control = &controlBuf[0]\n- msg.Controllen = maxControlLen\n+ msg.Controllen = controlLen\n}\nn, err := recvmsg(s.fd, &msg, sysflags)\nif err != nil {\n@@ -489,7 +492,14 @@ func (s *socketOperations) SendMsg(t *kernel.Task, src usermem.IOSequence, to []\nreturn 0, syserr.ErrInvalidArgument\n}\n- controlBuf := control.PackControlMessages(t, controlMessages)\n+ space := uint64(control.CmsgsSpace(t, controlMessages))\n+ if space > maxControlLen {\n+ space = maxControlLen\n+ }\n+ controlBuf := make([]byte, 0, space)\n+ // PackControlMessages will append up to space bytes to controlBuf.\n+ controlBuf = control.PackControlMessages(t, controlMessages, controlBuf)\n+\nsendmsgFromBlocks := safemem.WriterFunc(func(srcs safemem.BlockSeq) (uint64, error) {\n// Refuse to do anything if any part of src.Addrs was unusable.\nif uint64(src.NumBytes()) != srcs.NumBytes() {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_socket.go",
"new_path": "pkg/sentry/syscalls/linux/sys_socket.go",
"diff": "@@ -787,29 +787,13 @@ func recvSingleMsg(t *kernel.Task, s socket.Socket, msgPtr usermem.Addr, flags i\ndefer cms.Release()\ncontrolData := make([]byte, 0, msg.ControlLen)\n+ controlData = control.PackControlMessages(t, cms, controlData)\nif cr, ok := s.(transport.Credentialer); ok && cr.Passcred() {\ncreds, _ := cms.Unix.Credentials.(control.SCMCredentials)\ncontrolData, mflags = control.PackCredentials(t, creds, controlData, mflags)\n}\n- if cms.IP.HasTimestamp {\n- controlData = control.PackTimestamp(t, cms.IP.Timestamp, controlData)\n- }\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-\n- if cms.IP.HasTOS {\n- controlData = control.PackTOS(t, cms.IP.TOS, controlData)\n- }\n-\n- if cms.IP.HasTClass {\n- controlData = control.PackTClass(t, cms.IP.TClass, 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"
}
] | Go | Apache License 2.0 | google/gvisor | Deduplicate and simplify control message processing for recvmsg and sendmsg.
Also, improve performance by calculating how much space is needed before making
an allocation for sendmsg in hostinet.
PiperOrigin-RevId: 284898581 |
259,860 | 11.12.2019 10:23:54 | 28,800 | 1643224af0f099d55d7ae7934606ec1987658dfc | Finish incomplete comment. | [
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/fsgofer.go",
"new_path": "runsc/fsgofer/fsgofer.go",
"diff": "@@ -199,6 +199,7 @@ func (a *attachPoint) makeQID(stat syscall.Stat_t) p9.QID {\n// The reason that the file is not opened initially as read-write is for better\n// performance with 'overlay2' storage driver. overlay2 eagerly copies the\n// entire file up when it's opened in write mode, and would perform badly when\n+// multiple files are only being opened for read (esp. startup).\ntype localFile struct {\np9.DefaultWalkGetAttr\n"
}
] | Go | Apache License 2.0 | google/gvisor | Finish incomplete comment.
PiperOrigin-RevId: 285012278 |
259,885 | 11.12.2019 13:40:57 | 28,800 | 481dbfa5ab24ec2c0752b9e748d3617285603c4e | Add vfs.Pathname{WithDeleted,ForGetcwd}.
The former is needed for vfs.FileDescription to implement
memmap.MappingIdentity, and the latter is needed to implement getcwd(2). | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/ext/BUILD",
"new_path": "pkg/sentry/fsimpl/ext/BUILD",
"diff": "@@ -38,6 +38,7 @@ go_library(\n\"//pkg/abi/linux\",\n\"//pkg/binary\",\n\"//pkg/fd\",\n+ \"//pkg/fspath\",\n\"//pkg/log\",\n\"//pkg/sentry/arch\",\n\"//pkg/sentry/context\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/ext/filesystem.go",
"new_path": "pkg/sentry/fsimpl/ext/filesystem.go",
"diff": "@@ -20,6 +20,7 @@ import (\n\"sync\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/sentry/context\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/ext/disklayout\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n@@ -441,3 +442,10 @@ func (fs *filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\nreturn syserror.EROFS\n}\n+\n+// PrependPath implements vfs.FilesystemImpl.PrependPath.\n+func (fs *filesystem) PrependPath(ctx context.Context, vfsroot, vd vfs.VirtualDentry, b *fspath.Builder) error {\n+ fs.mu.RLock()\n+ defer fs.mu.RUnlock()\n+ return vfs.GenericPrependPath(vfsroot, vd, b)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/memfs/BUILD",
"new_path": "pkg/sentry/fsimpl/memfs/BUILD",
"diff": "@@ -32,6 +32,7 @@ go_library(\ndeps = [\n\"//pkg/abi/linux\",\n\"//pkg/amutex\",\n+ \"//pkg/fspath\",\n\"//pkg/sentry/arch\",\n\"//pkg/sentry/context\",\n\"//pkg/sentry/kernel/auth\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/memfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/memfs/filesystem.go",
"diff": "@@ -19,6 +19,7 @@ import (\n\"sync/atomic\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/sentry/context\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n@@ -582,3 +583,10 @@ func (fs *filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\ninode.decLinksLocked()\nreturn nil\n}\n+\n+// PrependPath implements vfs.FilesystemImpl.PrependPath.\n+func (fs *filesystem) PrependPath(ctx context.Context, vfsroot, vd vfs.VirtualDentry, b *fspath.Builder) error {\n+ fs.mu.RLock()\n+ defer fs.mu.RUnlock()\n+ return vfs.GenericPrependPath(vfsroot, vd, b)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/BUILD",
"new_path": "pkg/sentry/vfs/BUILD",
"diff": "@@ -17,6 +17,7 @@ go_library(\n\"mount.go\",\n\"mount_unsafe.go\",\n\"options.go\",\n+ \"pathname.go\",\n\"permissions.go\",\n\"resolving_path.go\",\n\"testutil.go\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/filesystem.go",
"new_path": "pkg/sentry/vfs/filesystem.go",
"diff": "@@ -18,6 +18,7 @@ import (\n\"sync/atomic\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/sentry/context\"\n)\n@@ -185,5 +186,56 @@ type FilesystemImpl interface {\n// UnlinkAt removes the non-directory file at rp.\nUnlinkAt(ctx context.Context, rp *ResolvingPath) error\n- // TODO: d_path(); extended attributes; inotify_add_watch(); bind()\n+ // PrependPath prepends a path from vd to vd.Mount().Root() to b.\n+ //\n+ // If vfsroot.Ok(), it is the contextual VFS root; if it is encountered\n+ // before vd.Mount().Root(), PrependPath should stop prepending path\n+ // components and return a PrependPathAtVFSRootError.\n+ //\n+ // If traversal of vd.Dentry()'s ancestors encounters an independent\n+ // (\"root\") Dentry that is not vd.Mount().Root() (i.e. vd.Dentry() is not a\n+ // descendant of vd.Mount().Root()), PrependPath should stop prepending\n+ // path components and return a PrependPathAtNonMountRootError.\n+ //\n+ // Filesystems for which Dentries do not have meaningful paths may prepend\n+ // an arbitrary descriptive string to b and then return a\n+ // PrependPathSyntheticError.\n+ //\n+ // Most implementations can acquire the appropriate locks to ensure that\n+ // Dentry.Name() and Dentry.Parent() are fixed for vd.Dentry() and all of\n+ // its ancestors, then call GenericPrependPath.\n+ //\n+ // Preconditions: vd.Mount().Filesystem().Impl() == this FilesystemImpl.\n+ PrependPath(ctx context.Context, vfsroot, vd VirtualDentry, b *fspath.Builder) error\n+\n+ // TODO: extended attributes; inotify_add_watch(); bind()\n+}\n+\n+// PrependPathAtVFSRootError is returned by implementations of\n+// FilesystemImpl.PrependPath() when they encounter the contextual VFS root.\n+type PrependPathAtVFSRootError struct{}\n+\n+// Error implements error.Error.\n+func (PrependPathAtVFSRootError) Error() string {\n+ return \"vfs.FilesystemImpl.PrependPath() reached VFS root\"\n+}\n+\n+// PrependPathAtNonMountRootError is returned by implementations of\n+// FilesystemImpl.PrependPath() when they encounter an independent ancestor\n+// Dentry that is not the Mount root.\n+type PrependPathAtNonMountRootError struct{}\n+\n+// Error implements error.Error.\n+func (PrependPathAtNonMountRootError) Error() string {\n+ return \"vfs.FilesystemImpl.PrependPath() reached root other than Mount root\"\n+}\n+\n+// PrependPathSyntheticError is returned by implementations of\n+// FilesystemImpl.PrependPath() for which prepended names do not represent real\n+// paths.\n+type PrependPathSyntheticError struct{}\n+\n+// Error implements error.Error.\n+func (PrependPathSyntheticError) Error() string {\n+ return \"vfs.FilesystemImpl.PrependPath() prepended synthetic name\"\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/filesystem_impl_util.go",
"new_path": "pkg/sentry/vfs/filesystem_impl_util.go",
"diff": "@@ -16,6 +16,8 @@ package vfs\nimport (\n\"strings\"\n+\n+ \"gvisor.dev/gvisor/pkg/fspath\"\n)\n// GenericParseMountOptions parses a comma-separated list of options of the\n@@ -41,3 +43,27 @@ func GenericParseMountOptions(str string) map[string]string {\n}\nreturn m\n}\n+\n+// GenericPrependPath may be used by implementations of\n+// FilesystemImpl.PrependPath() for which a single statically-determined lock\n+// or set of locks is sufficient to ensure its preconditions (as opposed to\n+// e.g. per-Dentry locks).\n+//\n+// Preconditions: Dentry.Name() and Dentry.Parent() must be held constant for\n+// vd.Dentry() and all of its ancestors.\n+func GenericPrependPath(vfsroot, vd VirtualDentry, b *fspath.Builder) error {\n+ mnt, d := vd.mount, vd.dentry\n+ for {\n+ if mnt == vfsroot.mount && d == vfsroot.dentry {\n+ return PrependPathAtVFSRootError{}\n+ }\n+ if d == mnt.root {\n+ return nil\n+ }\n+ if d.parent == nil {\n+ return PrependPathAtNonMountRootError{}\n+ }\n+ b.PrependComponent(d.name)\n+ d = d.parent\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/vfs/pathname.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+ \"sync\"\n+\n+ \"gvisor.dev/gvisor/pkg/fspath\"\n+ \"gvisor.dev/gvisor/pkg/sentry/context\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+)\n+\n+var fspathBuilderPool = sync.Pool{\n+ New: func() interface{} {\n+ return &fspath.Builder{}\n+ },\n+}\n+\n+func getFSPathBuilder() *fspath.Builder {\n+ return fspathBuilderPool.Get().(*fspath.Builder)\n+}\n+\n+func putFSPathBuilder(b *fspath.Builder) {\n+ // No methods can be called on b after b.String(), so reset it to its zero\n+ // value (as returned by fspathBuilderPool.New) instead.\n+ *b = fspath.Builder{}\n+ fspathBuilderPool.Put(b)\n+}\n+\n+// PathnameWithDeleted returns an absolute pathname to vd, consistent with\n+// Linux's d_path(). In particular, if vd.Dentry() has been disowned,\n+// PathnameWithDeleted appends \" (deleted)\" to the returned pathname.\n+func (vfs *VirtualFilesystem) PathnameWithDeleted(ctx context.Context, vfsroot, vd VirtualDentry) (string, error) {\n+ b := getFSPathBuilder()\n+ defer putFSPathBuilder(b)\n+ haveRef := false\n+ defer func() {\n+ if haveRef {\n+ vd.DecRef()\n+ }\n+ }()\n+\n+ origD := vd.dentry\n+loop:\n+ for {\n+ err := vd.mount.fs.impl.PrependPath(ctx, vfsroot, vd, b)\n+ switch err.(type) {\n+ case nil:\n+ if vd.mount == vfsroot.mount && vd.mount.root == vfsroot.dentry {\n+ // GenericPrependPath() will have returned\n+ // PrependPathAtVFSRootError in this case since it checks\n+ // against vfsroot before mnt.root, but other implementations\n+ // of FilesystemImpl.PrependPath() may return nil instead.\n+ break loop\n+ }\n+ nextVD := vfs.getMountpointAt(vd.mount, vfsroot)\n+ if !nextVD.Ok() {\n+ break loop\n+ }\n+ if haveRef {\n+ vd.DecRef()\n+ }\n+ vd = nextVD\n+ haveRef = true\n+ // continue loop\n+ case PrependPathSyntheticError:\n+ // Skip prepending \"/\" and appending \" (deleted)\".\n+ return b.String(), nil\n+ case PrependPathAtVFSRootError, PrependPathAtNonMountRootError:\n+ break loop\n+ default:\n+ return \"\", err\n+ }\n+ }\n+ b.PrependByte('/')\n+ if origD.IsDisowned() {\n+ b.AppendString(\" (deleted)\")\n+ }\n+ return b.String(), nil\n+}\n+\n+// PathnameForGetcwd returns an absolute pathname to vd, consistent with\n+// Linux's sys_getcwd().\n+func (vfs *VirtualFilesystem) PathnameForGetcwd(ctx context.Context, vfsroot, vd VirtualDentry) (string, error) {\n+ if vd.dentry.IsDisowned() {\n+ return \"\", syserror.ENOENT\n+ }\n+\n+ b := getFSPathBuilder()\n+ defer putFSPathBuilder(b)\n+ haveRef := false\n+ defer func() {\n+ if haveRef {\n+ vd.DecRef()\n+ }\n+ }()\n+ unreachable := false\n+loop:\n+ for {\n+ err := vd.mount.fs.impl.PrependPath(ctx, vfsroot, vd, b)\n+ switch err.(type) {\n+ case nil:\n+ if vd.mount == vfsroot.mount && vd.mount.root == vfsroot.dentry {\n+ break loop\n+ }\n+ nextVD := vfs.getMountpointAt(vd.mount, vfsroot)\n+ if !nextVD.Ok() {\n+ unreachable = true\n+ break loop\n+ }\n+ if haveRef {\n+ vd.DecRef()\n+ }\n+ vd = nextVD\n+ haveRef = true\n+ case PrependPathAtVFSRootError:\n+ break loop\n+ case PrependPathAtNonMountRootError, PrependPathSyntheticError:\n+ unreachable = true\n+ break loop\n+ default:\n+ return \"\", err\n+ }\n+ }\n+ b.PrependByte('/')\n+ if unreachable {\n+ b.PrependString(\"(unreachable)\")\n+ }\n+ return b.String(), nil\n+}\n+\n+// As of this writing, we do not have equivalents to:\n+//\n+// - d_absolute_path(), which returns EINVAL if (effectively) any call to\n+// FilesystemImpl.PrependPath() would return PrependPathAtNonMountRootError.\n+//\n+// - dentry_path(), which does not walk up mounts (and only returns the path\n+// relative to Filesystem root), but also appends \"//deleted\" for disowned\n+// Dentries.\n+//\n+// These should be added as necessary.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/testutil.go",
"new_path": "pkg/sentry/vfs/testutil.go",
"diff": "package vfs\nimport (\n+ \"fmt\"\n+\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/sentry/context\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n@@ -114,6 +117,12 @@ func (fs *FDTestFilesystem) UnlinkAt(ctx context.Context, rp *ResolvingPath) err\nreturn syserror.EPERM\n}\n+// PrependPath implements FilesystemImpl.PrependPath.\n+func (fs *FDTestFilesystem) PrependPath(ctx context.Context, vfsroot, vd VirtualDentry, b *fspath.Builder) error {\n+ b.PrependComponent(fmt.Sprintf(\"vfs.fdTestDentry:%p\", vd.dentry.impl.(*fdTestDentry)))\n+ return PrependPathSyntheticError{}\n+}\n+\ntype fdTestDentry struct {\nvfsd Dentry\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add vfs.Pathname{WithDeleted,ForGetcwd}.
The former is needed for vfs.FileDescription to implement
memmap.MappingIdentity, and the latter is needed to implement getcwd(2).
PiperOrigin-RevId: 285051855 |
259,860 | 11.12.2019 16:39:58 | 28,800 | 1601e78a52e9181d1ea8a3ff36399575e95ad0bf | Add syscall tests for getxattr and setxattr.
Support for getxattr and setxattr are in subsequent commits. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -717,6 +717,11 @@ syscall_test(test = \"//test/syscalls/linux:proc_net_tcp_test\")\nsyscall_test(test = \"//test/syscalls/linux:proc_net_udp_test\")\n+syscall_test(\n+ add_overlay = True,\n+ test = \"//test/syscalls/linux:xattr_test\",\n+)\n+\ngo_binary(\nname = \"syscall_test_runner\",\ntestonly = 1,\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -3722,3 +3722,24 @@ cc_binary(\n\"@com_google_googletest//:gtest\",\n],\n)\n+\n+cc_binary(\n+ name = \"xattr_test\",\n+ testonly = 1,\n+ srcs = [\n+ \"file_base.h\",\n+ \"xattr.cc\",\n+ ],\n+ linkstatic = 1,\n+ deps = [\n+ \"//test/util:capability_util\",\n+ \"//test/util:file_descriptor\",\n+ \"//test/util:fs_util\",\n+ \"//test/util:posix_error\",\n+ \"//test/util:temp_path\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ \"@com_google_absl//absl/strings\",\n+ \"@com_google_googletest//:gtest\",\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/xattr.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 <errno.h>\n+#include <fcntl.h>\n+#include <limits.h>\n+#include <sys/types.h>\n+#include <sys/xattr.h>\n+#include <unistd.h>\n+\n+#include <string>\n+#include <vector>\n+\n+#include \"gmock/gmock.h\"\n+#include \"gtest/gtest.h\"\n+#include \"test/syscalls/linux/file_base.h\"\n+#include \"test/util/capability_util.h\"\n+#include \"test/util/posix_error.h\"\n+#include \"test/util/temp_path.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+class XattrTest : public FileTest {};\n+\n+TEST_F(XattrTest, XattrNullName) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+\n+ EXPECT_THAT(setxattr(path, nullptr, nullptr, 0, /*flags=*/0),\n+ SyscallFailsWithErrno(EFAULT));\n+ EXPECT_THAT(getxattr(path, nullptr, nullptr, 0),\n+ SyscallFailsWithErrno(EFAULT));\n+}\n+\n+TEST_F(XattrTest, XattrEmptyName) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+\n+ EXPECT_THAT(setxattr(path, \"\", nullptr, 0, /*flags=*/0),\n+ SyscallFailsWithErrno(ERANGE));\n+ EXPECT_THAT(getxattr(path, \"\", nullptr, 0), SyscallFailsWithErrno(ERANGE));\n+}\n+\n+TEST_F(XattrTest, XattrLargeName) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+ std::string name = \"user.\";\n+ name += std::string(XATTR_NAME_MAX - name.length(), 'a');\n+ EXPECT_THAT(setxattr(path, name.c_str(), nullptr, 0, /*flags=*/0),\n+ SyscallSucceeds());\n+ EXPECT_THAT(getxattr(path, name.c_str(), nullptr, 0),\n+ SyscallSucceedsWithValue(0));\n+\n+ name += \"a\";\n+ EXPECT_THAT(setxattr(path, name.c_str(), nullptr, 0, /*flags=*/0),\n+ SyscallFailsWithErrno(ERANGE));\n+ EXPECT_THAT(getxattr(path, name.c_str(), nullptr, 0),\n+ SyscallFailsWithErrno(ERANGE));\n+}\n+\n+TEST_F(XattrTest, XattrInvalidPrefix) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+ std::string name(XATTR_NAME_MAX, 'a');\n+ EXPECT_THAT(setxattr(path, name.c_str(), nullptr, 0, /*flags=*/0),\n+ SyscallFailsWithErrno(EOPNOTSUPP));\n+ EXPECT_THAT(getxattr(path, name.c_str(), nullptr, 0),\n+ SyscallFailsWithErrno(EOPNOTSUPP));\n+}\n+\n+TEST_F(XattrTest, XattrReadOnly) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ // Drop capabilities that allow us to override file and directory permissions.\n+ ASSERT_NO_ERRNO(SetCapability(CAP_DAC_OVERRIDE, false));\n+ ASSERT_NO_ERRNO(SetCapability(CAP_DAC_READ_SEARCH, false));\n+\n+ const char* path = test_file_name_.c_str();\n+ char name[] = \"user.abc\";\n+ char val = 'a';\n+ size_t size = sizeof(val);\n+ EXPECT_THAT(setxattr(path, name, &val, size, /*flags=*/0), SyscallSucceeds());\n+\n+ ASSERT_NO_ERRNO(testing::Chmod(test_file_name_, S_IRUSR));\n+\n+ EXPECT_THAT(setxattr(path, name, &val, size, /*flags=*/0),\n+ SyscallFailsWithErrno(EACCES));\n+\n+ char buf = '-';\n+ EXPECT_THAT(getxattr(path, name, &buf, size), SyscallSucceedsWithValue(size));\n+ EXPECT_EQ(buf, val);\n+}\n+\n+TEST_F(XattrTest, XattrWriteOnly) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ // Drop capabilities that allow us to override file and directory permissions.\n+ ASSERT_NO_ERRNO(SetCapability(CAP_DAC_OVERRIDE, false));\n+ ASSERT_NO_ERRNO(SetCapability(CAP_DAC_READ_SEARCH, false));\n+\n+ ASSERT_NO_ERRNO(testing::Chmod(test_file_name_, S_IWUSR));\n+\n+ const char* path = test_file_name_.c_str();\n+ char name[] = \"user.abc\";\n+ char val = 'a';\n+ size_t size = sizeof(val);\n+ EXPECT_THAT(setxattr(path, name, &val, size, /*flags=*/0), SyscallSucceeds());\n+\n+ EXPECT_THAT(getxattr(path, name, nullptr, 0), SyscallFailsWithErrno(EACCES));\n+}\n+\n+TEST_F(XattrTest, XattrTrustedWithNonadmin) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+ SKIP_IF(ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN)));\n+\n+ const char* path = test_file_name_.c_str();\n+ const char name[] = \"trusted.abc\";\n+ EXPECT_THAT(setxattr(path, name, nullptr, 0, /*flags=*/0),\n+ SyscallFailsWithErrno(EPERM));\n+ EXPECT_THAT(getxattr(path, name, nullptr, 0), SyscallFailsWithErrno(ENODATA));\n+}\n+\n+TEST_F(XattrTest, XattrOnDirectory) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ TempPath dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ char name[] = \"user.abc\";\n+ EXPECT_THAT(setxattr(dir.path().c_str(), name, NULL, 0, /*flags=*/0),\n+ SyscallSucceeds());\n+ EXPECT_THAT(getxattr(dir.path().c_str(), name, NULL, 0),\n+ SyscallSucceedsWithValue(0));\n+}\n+\n+TEST_F(XattrTest, XattrOnSymlink) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ TempPath dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ TempPath link = ASSERT_NO_ERRNO_AND_VALUE(\n+ TempPath::CreateSymlinkTo(dir.path(), test_file_name_));\n+ char name[] = \"user.abc\";\n+ EXPECT_THAT(setxattr(link.path().c_str(), name, NULL, 0, /*flags=*/0),\n+ SyscallSucceeds());\n+ EXPECT_THAT(getxattr(link.path().c_str(), name, NULL, 0),\n+ SyscallSucceedsWithValue(0));\n+}\n+\n+TEST_F(XattrTest, XattrOnInvalidFileTypes) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ char name[] = \"user.abc\";\n+\n+ char char_device[] = \"/dev/zero\";\n+ EXPECT_THAT(setxattr(char_device, name, NULL, 0, /*flags=*/0),\n+ SyscallFailsWithErrno(EPERM));\n+ EXPECT_THAT(getxattr(char_device, name, NULL, 0),\n+ SyscallFailsWithErrno(ENODATA));\n+\n+ // Use tmpfs, where creation of named pipes is supported.\n+ const std::string fifo = NewTempAbsPathInDir(\"/dev/shm\");\n+ const char* path = fifo.c_str();\n+ EXPECT_THAT(mknod(path, S_IFIFO | S_IRUSR | S_IWUSR, 0), SyscallSucceeds());\n+ EXPECT_THAT(setxattr(path, name, NULL, 0, /*flags=*/0),\n+ SyscallFailsWithErrno(EPERM));\n+ EXPECT_THAT(getxattr(path, name, NULL, 0), SyscallFailsWithErrno(ENODATA));\n+}\n+\n+TEST_F(XattrTest, SetxattrSizeSmallerThanValue) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+ char name[] = \"user.abc\";\n+ std::vector<char> val = {'a', 'a'};\n+ size_t size = 1;\n+ EXPECT_THAT(setxattr(path, name, val.data(), size, /*flags=*/0),\n+ SyscallSucceeds());\n+\n+ std::vector<char> buf = {'-', '-'};\n+ std::vector<char> expected_buf = {'a', '-'};\n+ EXPECT_THAT(getxattr(path, name, buf.data(), buf.size()),\n+ SyscallSucceedsWithValue(size));\n+ EXPECT_EQ(buf, expected_buf);\n+}\n+\n+TEST_F(XattrTest, SetxattrZeroSize) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+ char name[] = \"user.abc\";\n+ char val = 'a';\n+ EXPECT_THAT(setxattr(path, name, &val, 0, /*flags=*/0), SyscallSucceeds());\n+\n+ char buf = '-';\n+ EXPECT_THAT(getxattr(path, name, &buf, XATTR_SIZE_MAX),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(buf, '-');\n+}\n+\n+TEST_F(XattrTest, SetxattrSizeTooLarge) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+ char name[] = \"user.abc\";\n+\n+ // Note that each particular fs implementation may stipulate a lower size\n+ // limit, in which case we actually may fail (e.g. error with ENOSPC) for\n+ // some sizes under XATTR_SIZE_MAX.\n+ size_t size = XATTR_SIZE_MAX + 1;\n+ std::vector<char> val(size);\n+ EXPECT_THAT(setxattr(path, name, val.data(), size, /*flags=*/0),\n+ SyscallFailsWithErrno(E2BIG));\n+\n+ EXPECT_THAT(getxattr(path, name, nullptr, 0), SyscallFailsWithErrno(ENODATA));\n+}\n+\n+TEST_F(XattrTest, SetxattrNullValueAndNonzeroSize) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+ char name[] = \"user.abc\";\n+ EXPECT_THAT(setxattr(path, name, nullptr, 1, /*flags=*/0),\n+ SyscallFailsWithErrno(EFAULT));\n+\n+ EXPECT_THAT(getxattr(path, name, nullptr, 0), SyscallFailsWithErrno(ENODATA));\n+}\n+\n+TEST_F(XattrTest, SetxattrNullValueAndZeroSize) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+ char name[] = \"user.abc\";\n+ EXPECT_THAT(setxattr(path, name, nullptr, 0, /*flags=*/0), SyscallSucceeds());\n+\n+ EXPECT_THAT(getxattr(path, name, nullptr, 0), SyscallSucceedsWithValue(0));\n+}\n+\n+TEST_F(XattrTest, SetxattrValueTooLargeButOKSize) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+ char name[] = \"user.abc\";\n+ std::vector<char> val(XATTR_SIZE_MAX + 1);\n+ std::fill(val.begin(), val.end(), 'a');\n+ size_t size = 1;\n+ EXPECT_THAT(setxattr(path, name, val.data(), size, /*flags=*/0),\n+ SyscallSucceeds());\n+\n+ std::vector<char> buf = {'-', '-'};\n+ std::vector<char> expected_buf = {'a', '-'};\n+ EXPECT_THAT(getxattr(path, name, buf.data(), size),\n+ SyscallSucceedsWithValue(size));\n+ EXPECT_EQ(buf, expected_buf);\n+}\n+\n+TEST_F(XattrTest, SetxattrReplaceWithSmaller) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+ char name[] = \"user.abc\";\n+ std::vector<char> val = {'a', 'a'};\n+ EXPECT_THAT(setxattr(path, name, val.data(), 2, /*flags=*/0),\n+ SyscallSucceeds());\n+ EXPECT_THAT(setxattr(path, name, val.data(), 1, /*flags=*/0),\n+ SyscallSucceeds());\n+\n+ std::vector<char> buf = {'-', '-'};\n+ std::vector<char> expected_buf = {'a', '-'};\n+ EXPECT_THAT(getxattr(path, name, buf.data(), 2), SyscallSucceedsWithValue(1));\n+ EXPECT_EQ(buf, expected_buf);\n+}\n+\n+TEST_F(XattrTest, SetxattrReplaceWithLarger) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+ char name[] = \"user.abc\";\n+ std::vector<char> val = {'a', 'a'};\n+ EXPECT_THAT(setxattr(path, name, val.data(), 1, /*flags=*/0),\n+ SyscallSucceeds());\n+ EXPECT_THAT(setxattr(path, name, val.data(), 2, /*flags=*/0),\n+ SyscallSucceeds());\n+\n+ std::vector<char> buf = {'-', '-'};\n+ EXPECT_THAT(getxattr(path, name, buf.data(), 2), SyscallSucceedsWithValue(2));\n+ EXPECT_EQ(buf, val);\n+}\n+\n+TEST_F(XattrTest, SetxattrCreateFlag) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+ char name[] = \"user.abc\";\n+ EXPECT_THAT(setxattr(path, name, nullptr, 0, XATTR_CREATE),\n+ SyscallSucceeds());\n+ EXPECT_THAT(setxattr(path, name, nullptr, 0, XATTR_CREATE),\n+ SyscallFailsWithErrno(EEXIST));\n+\n+ EXPECT_THAT(getxattr(path, name, nullptr, 0), SyscallSucceedsWithValue(0));\n+}\n+\n+TEST_F(XattrTest, SetxattrReplaceFlag) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+ char name[] = \"user.abc\";\n+ EXPECT_THAT(setxattr(path, name, nullptr, 0, XATTR_REPLACE),\n+ SyscallFailsWithErrno(ENODATA));\n+ EXPECT_THAT(setxattr(path, name, nullptr, 0, /*flags=*/0), SyscallSucceeds());\n+ EXPECT_THAT(setxattr(path, name, nullptr, 0, XATTR_REPLACE),\n+ SyscallSucceeds());\n+\n+ EXPECT_THAT(getxattr(path, name, nullptr, 0), SyscallSucceedsWithValue(0));\n+}\n+\n+TEST_F(XattrTest, SetxattrInvalidFlags) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+ int invalid_flags = 0xff;\n+ EXPECT_THAT(setxattr(path, nullptr, nullptr, 0, invalid_flags),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\n+TEST_F(XattrTest, Getxattr) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+ char name[] = \"user.abc\";\n+ int val = 1234;\n+ size_t size = sizeof(val);\n+ EXPECT_THAT(setxattr(path, name, &val, size, /*flags=*/0), SyscallSucceeds());\n+\n+ int buf = 0;\n+ EXPECT_THAT(getxattr(path, name, &buf, size), SyscallSucceedsWithValue(size));\n+ EXPECT_EQ(buf, val);\n+}\n+\n+TEST_F(XattrTest, GetxattrSizeSmallerThanValue) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+ char name[] = \"user.abc\";\n+ std::vector<char> val = {'a', 'a'};\n+ size_t size = val.size();\n+ EXPECT_THAT(setxattr(path, name, &val, size, /*flags=*/0), SyscallSucceeds());\n+\n+ char buf = '-';\n+ EXPECT_THAT(getxattr(path, name, &buf, 1), SyscallFailsWithErrno(ERANGE));\n+ EXPECT_EQ(buf, '-');\n+}\n+\n+TEST_F(XattrTest, GetxattrSizeLargerThanValue) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+ char name[] = \"user.abc\";\n+ char val = 'a';\n+ EXPECT_THAT(setxattr(path, name, &val, 1, /*flags=*/0), SyscallSucceeds());\n+\n+ std::vector<char> buf(XATTR_SIZE_MAX);\n+ std::fill(buf.begin(), buf.end(), '-');\n+ std::vector<char> expected_buf = buf;\n+ expected_buf[0] = 'a';\n+ EXPECT_THAT(getxattr(path, name, buf.data(), buf.size()),\n+ SyscallSucceedsWithValue(1));\n+ EXPECT_EQ(buf, expected_buf);\n+}\n+\n+TEST_F(XattrTest, GetxattrZeroSize) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+ char name[] = \"user.abc\";\n+ char val = 'a';\n+ EXPECT_THAT(setxattr(path, name, &val, sizeof(val), /*flags=*/0),\n+ SyscallSucceeds());\n+\n+ char buf = '-';\n+ EXPECT_THAT(getxattr(path, name, &buf, 0),\n+ SyscallSucceedsWithValue(sizeof(val)));\n+ EXPECT_EQ(buf, '-');\n+}\n+\n+TEST_F(XattrTest, GetxattrSizeTooLarge) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+ char name[] = \"user.abc\";\n+ char val = 'a';\n+ EXPECT_THAT(setxattr(path, name, &val, sizeof(val), /*flags=*/0),\n+ SyscallSucceeds());\n+\n+ std::vector<char> buf(XATTR_SIZE_MAX + 1);\n+ std::fill(buf.begin(), buf.end(), '-');\n+ std::vector<char> expected_buf = buf;\n+ expected_buf[0] = 'a';\n+ EXPECT_THAT(getxattr(path, name, buf.data(), buf.size()),\n+ SyscallSucceedsWithValue(sizeof(val)));\n+ EXPECT_EQ(buf, expected_buf);\n+}\n+\n+TEST_F(XattrTest, GetxattrNullValue) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+ char name[] = \"user.abc\";\n+ char val = 'a';\n+ size_t size = sizeof(val);\n+ EXPECT_THAT(setxattr(path, name, &val, size, /*flags=*/0), SyscallSucceeds());\n+\n+ EXPECT_THAT(getxattr(path, name, nullptr, size),\n+ SyscallFailsWithErrno(EFAULT));\n+}\n+\n+TEST_F(XattrTest, GetxattrNullValueAndZeroSize) {\n+ // TODO(b/127675828): Support setxattr and getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+ char name[] = \"user.abc\";\n+ char val = 'a';\n+ size_t size = sizeof(val);\n+ // Set value with zero size.\n+ EXPECT_THAT(setxattr(path, name, &val, 0, /*flags=*/0), SyscallSucceeds());\n+ // Get value with nonzero size.\n+ EXPECT_THAT(getxattr(path, name, nullptr, size), SyscallSucceedsWithValue(0));\n+\n+ // Set value with nonzero size.\n+ EXPECT_THAT(setxattr(path, name, &val, size, /*flags=*/0), SyscallSucceeds());\n+ // Get value with zero size.\n+ EXPECT_THAT(getxattr(path, name, nullptr, 0), SyscallSucceedsWithValue(size));\n+}\n+\n+TEST_F(XattrTest, GetxattrNonexistentName) {\n+ // TODO(b/127675828): Support getxattr.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ const char* path = test_file_name_.c_str();\n+ std::string name = \"user.nonexistent\";\n+ EXPECT_THAT(getxattr(path, name.c_str(), nullptr, 0),\n+ SyscallFailsWithErrno(ENODATA));\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add syscall tests for getxattr and setxattr.
Support for getxattr and setxattr are in subsequent commits.
PiperOrigin-RevId: 285088817 |
259,962 | 11.12.2019 19:12:51 | 28,800 | b9aa62b9f907e8de5244ac7cdb518960faafa307 | Enable IPv6 in runsc
Fixes | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/network.go",
"new_path": "runsc/boot/network.go",
"diff": "@@ -80,7 +80,8 @@ type CreateLinksAndRoutesArgs struct {\nLoopbackLinks []LoopbackLink\nFDBasedLinks []FDBasedLink\n- DefaultGateway DefaultRoute\n+ Defaultv4Gateway DefaultRoute\n+ Defaultv6Gateway DefaultRoute\n}\n// Empty returns true if route hasn't been set.\n@@ -122,10 +123,10 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\nnicID++\nnicids[link.Name] = nicID\n- ep := loopback.New()\n+ linkEP := loopback.New()\nlog.Infof(\"Enabling loopback interface %q with id %d on addresses %+v\", link.Name, nicID, link.Addresses)\n- if err := n.createNICWithAddrs(nicID, link.Name, ep, link.Addresses, true /* loopback */); err != nil {\n+ if err := n.createNICWithAddrs(nicID, link.Name, linkEP, link.Addresses, true /* loopback */); err != nil {\nreturn err\n}\n@@ -157,7 +158,7 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\n}\nmac := tcpip.LinkAddress(link.LinkAddress)\n- ep, err := fdbased.New(&fdbased.Options{\n+ linkEP, err := fdbased.New(&fdbased.Options{\nFDs: FDs,\nMTU: uint32(link.MTU),\nEthernetHeader: true,\n@@ -172,7 +173,7 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\n}\nlog.Infof(\"Enabling interface %q with id %d on addresses %+v (%v) w/ %d channels\", link.Name, nicID, link.Addresses, mac, link.NumChannels)\n- if err := n.createNICWithAddrs(nicID, link.Name, ep, link.Addresses, false /* loopback */); err != nil {\n+ if err := n.createNICWithAddrs(nicID, link.Name, linkEP, link.Addresses, false /* loopback */); err != nil {\nreturn err\n}\n@@ -186,12 +187,24 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\n}\n}\n- if !args.DefaultGateway.Route.Empty() {\n- nicID, ok := nicids[args.DefaultGateway.Name]\n+ if !args.Defaultv4Gateway.Route.Empty() {\n+ nicID, ok := nicids[args.Defaultv4Gateway.Name]\nif !ok {\n- return fmt.Errorf(\"invalid interface name %q for default route\", args.DefaultGateway.Name)\n+ return fmt.Errorf(\"invalid interface name %q for default route\", args.Defaultv4Gateway.Name)\n}\n- route, err := args.DefaultGateway.Route.toTcpipRoute(nicID)\n+ route, err := args.Defaultv4Gateway.Route.toTcpipRoute(nicID)\n+ if err != nil {\n+ return err\n+ }\n+ routes = append(routes, route)\n+ }\n+\n+ if !args.Defaultv6Gateway.Route.Empty() {\n+ nicID, ok := nicids[args.Defaultv6Gateway.Name]\n+ if !ok {\n+ return fmt.Errorf(\"invalid interface name %q for default route\", args.Defaultv6Gateway.Name)\n+ }\n+ route, err := args.Defaultv6Gateway.Route.toTcpipRoute(nicID)\nif err != nil {\nreturn err\n}\n@@ -208,11 +221,11 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\nfunc (n *Network) createNICWithAddrs(id tcpip.NICID, name string, ep stack.LinkEndpoint, addrs []net.IP, loopback bool) error {\nif loopback {\nif err := n.Stack.CreateNamedLoopbackNIC(id, name, sniffer.New(ep)); err != nil {\n- return fmt.Errorf(\"CreateNamedLoopbackNIC(%v, %v) failed: %v\", id, name, err)\n+ return fmt.Errorf(\"CreateNamedLoopbackNIC(%v, %v, %v) failed: %v\", id, name, ep, err)\n}\n} else {\nif err := n.Stack.CreateNamedNIC(id, name, sniffer.New(ep)); err != nil {\n- return fmt.Errorf(\"CreateNamedNIC(%v, %v) failed: %v\", id, name, err)\n+ return fmt.Errorf(\"CreateNamedNIC(%v, %v, %v) failed: %v\", id, name, ep, err)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/BUILD",
"new_path": "runsc/sandbox/BUILD",
"diff": "@@ -19,6 +19,7 @@ go_library(\n\"//pkg/log\",\n\"//pkg/sentry/control\",\n\"//pkg/sentry/platform\",\n+ \"//pkg/tcpip/header\",\n\"//pkg/tcpip/stack\",\n\"//pkg/urpc\",\n\"//runsc/boot\",\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/network.go",
"new_path": "runsc/sandbox/network.go",
"diff": "@@ -28,6 +28,7 @@ import (\n\"github.com/vishvananda/netlink\"\n\"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/log\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n\"gvisor.dev/gvisor/pkg/urpc\"\n\"gvisor.dev/gvisor/runsc/boot\"\n@@ -183,36 +184,39 @@ func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, hardwareG\ncontinue\n}\n- // Keep only IPv4 addresses.\n- var ip4addrs []*net.IPNet\n+ var ipAddrs []*net.IPNet\nfor _, ifaddr := range allAddrs {\nipNet, ok := ifaddr.(*net.IPNet)\nif !ok {\nreturn fmt.Errorf(\"address is not IPNet: %+v\", ifaddr)\n}\n- if ipNet.IP.To4() == nil {\n- log.Warningf(\"IPv6 is not supported, skipping: %v\", ipNet)\n- continue\n- }\n- ip4addrs = append(ip4addrs, ipNet)\n+ ipAddrs = append(ipAddrs, ipNet)\n}\n- if len(ip4addrs) == 0 {\n- log.Warningf(\"No IPv4 address found for interface %q, skipping\", iface.Name)\n+ if len(ipAddrs) == 0 {\n+ log.Warningf(\"No usable IP addresses found for interface %q, skipping\", iface.Name)\ncontinue\n}\n// Scrape the routes before removing the address, since that\n// will remove the routes as well.\n- routes, def, err := routesForIface(iface)\n+ routes, defv4, defv6, err := routesForIface(iface)\nif err != nil {\nreturn fmt.Errorf(\"getting routes for interface %q: %v\", iface.Name, err)\n}\n- if def != nil {\n- if !args.DefaultGateway.Route.Empty() {\n- return fmt.Errorf(\"more than one default route found, interface: %v, route: %v, default route: %+v\", iface.Name, def, args.DefaultGateway)\n+ if defv4 != nil {\n+ if !args.Defaultv4Gateway.Route.Empty() {\n+ return fmt.Errorf(\"more than one default route found, interface: %v, route: %v, default route: %+v\", iface.Name, defv4, args.Defaultv4Gateway)\n+ }\n+ args.Defaultv4Gateway.Route = *defv4\n+ args.Defaultv4Gateway.Name = iface.Name\n+ }\n+\n+ if defv6 != nil {\n+ if !args.Defaultv6Gateway.Route.Empty() {\n+ return fmt.Errorf(\"more than one default route found, interface: %v, route: %v, default route: %+v\", iface.Name, defv6, args.Defaultv6Gateway)\n}\n- args.DefaultGateway.Route = *def\n- args.DefaultGateway.Name = iface.Name\n+ args.Defaultv6Gateway.Route = *defv6\n+ args.Defaultv6Gateway.Name = iface.Name\n}\nlink := boot.FDBasedLink{\n@@ -247,6 +251,7 @@ func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, hardwareG\n}\nargs.FilePayload.Files = append(args.FilePayload.Files, socketEntry.deviceFile)\n}\n+\nif link.GSOMaxSize == 0 && softwareGSO {\n// Hardware GSO is disabled. Let's enable software GSO.\nlink.GSOMaxSize = stack.SoftwareGSOMaxSize\n@@ -255,7 +260,7 @@ func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, hardwareG\n// Collect the addresses for the interface, enable forwarding,\n// and remove them from the host.\n- for _, addr := range ip4addrs {\n+ for _, addr := range ipAddrs {\nlink.Addresses = append(link.Addresses, addr.IP)\n// Steal IP address from NIC.\n@@ -351,46 +356,56 @@ func loopbackLinks(iface net.Interface, addrs []net.Addr) ([]boot.LoopbackLink,\n}\n// routesForIface iterates over all routes for the given interface and converts\n-// them to boot.Routes.\n-func routesForIface(iface net.Interface) ([]boot.Route, *boot.Route, error) {\n+// them to boot.Routes. It also returns the a default v4/v6 route if found.\n+func routesForIface(iface net.Interface) ([]boot.Route, *boot.Route, *boot.Route, error) {\nlink, err := netlink.LinkByIndex(iface.Index)\nif err != nil {\n- return nil, nil, err\n+ return nil, nil, nil, err\n}\nrs, err := netlink.RouteList(link, netlink.FAMILY_ALL)\nif err != nil {\n- return nil, nil, fmt.Errorf(\"getting routes from %q: %v\", iface.Name, err)\n+ return nil, nil, nil, fmt.Errorf(\"getting routes from %q: %v\", iface.Name, err)\n}\n- var def *boot.Route\n+ var defv4, defv6 *boot.Route\nvar routes []boot.Route\nfor _, r := range rs {\n// Is it a default route?\nif r.Dst == nil {\nif r.Gw == nil {\n- return nil, nil, fmt.Errorf(\"default route with no gateway %q: %+v\", iface.Name, r)\n- }\n- if r.Gw.To4() == nil {\n- log.Warningf(\"IPv6 is not supported, skipping default route: %v\", r)\n- continue\n- }\n- if def != nil {\n- return nil, nil, fmt.Errorf(\"more than one default route found %q, def: %+v, route: %+v\", iface.Name, def, r)\n+ return nil, nil, nil, fmt.Errorf(\"default route with no gateway %q: %+v\", iface.Name, r)\n}\n// Create a catch all route to the gateway.\n- def = &boot.Route{\n+ switch len(r.Gw) {\n+ case header.IPv4AddressSize:\n+ if defv4 != nil {\n+ return nil, nil, nil, fmt.Errorf(\"more than one default route found %q, def: %+v, route: %+v\", iface.Name, defv4, r)\n+ }\n+ defv4 = &boot.Route{\nDestination: net.IPNet{\nIP: net.IPv4zero,\nMask: net.IPMask(net.IPv4zero),\n},\nGateway: r.Gw,\n}\n- continue\n+ case header.IPv6AddressSize:\n+ if defv6 != nil {\n+ return nil, nil, nil, fmt.Errorf(\"more than one default route found %q, def: %+v, route: %+v\", iface.Name, defv6, r)\n+ }\n+\n+ defv6 = &boot.Route{\n+ Destination: net.IPNet{\n+ IP: net.IPv6zero,\n+ Mask: net.IPMask(net.IPv6zero),\n+ },\n+ Gateway: r.Gw,\n+ }\n+ default:\n+ return nil, nil, nil, fmt.Errorf(\"unexpected address size for gateway: %+v for route: %+v\", r.Gw, r)\n}\n- if r.Dst.IP.To4() == nil {\n- log.Warningf(\"IPv6 is not supported, skipping route: %v\", r)\ncontinue\n}\n+\ndst := *r.Dst\ndst.IP = dst.IP.Mask(dst.Mask)\nroutes = append(routes, boot.Route{\n@@ -398,7 +413,7 @@ func routesForIface(iface net.Interface) ([]boot.Route, *boot.Route, error) {\nGateway: r.Gw,\n})\n}\n- return routes, def, nil\n+ return routes, defv4, defv6, nil\n}\n// removeAddress removes IP address from network device. It's equivalent to:\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enable IPv6 in runsc
Fixes #1341
PiperOrigin-RevId: 285108973 |
259,853 | 12.12.2019 11:07:25 | 28,800 | 378d6c1f3697b8b939e6632e980562bfc8fb2781 | unix: allow to bind unix sockets only to AF_UNIX addresses
Reported-by: | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/netstack.go",
"new_path": "pkg/sentry/socket/netstack/netstack.go",
"diff": "@@ -326,7 +326,7 @@ func AddressAndFamily(sfamily int, addr []byte, strict bool) (tcpip.FullAddress,\n}\nfamily := usermem.ByteOrder.Uint16(addr)\n- if family != uint16(sfamily) && (!strict && family != linux.AF_UNSPEC) {\n+ if family != uint16(sfamily) && (strict || family != linux.AF_UNSPEC) {\nreturn tcpip.FullAddress{}, family, syserr.ErrAddressFamilyNotSupported\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/unix.go",
"new_path": "pkg/sentry/socket/unix/unix.go",
"diff": "@@ -118,6 +118,9 @@ func (s *SocketOperations) Endpoint() transport.Endpoint {\nfunc extractPath(sockaddr []byte) (string, *syserr.Error) {\naddr, _, err := netstack.AddressAndFamily(linux.AF_UNIX, sockaddr, true /* strict */)\nif err != nil {\n+ if err == syserr.ErrAddressFamilyNotSupported {\n+ err = syserr.ErrInvalidArgument\n+ }\nreturn \"\", err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_unix.cc",
"new_path": "test/syscalls/linux/socket_unix.cc",
"diff": "@@ -65,6 +65,21 @@ TEST_P(UnixSocketPairTest, BindToBadName) {\nSyscallFailsWithErrno(ENOENT));\n}\n+TEST_P(UnixSocketPairTest, BindToBadFamily) {\n+ auto pair =\n+ ASSERT_NO_ERRNO_AND_VALUE(UnixDomainSocketPair(SOCK_SEQPACKET).Create());\n+\n+ constexpr char kBadName[] = \"/some/path/that/does/not/exist\";\n+ sockaddr_un sockaddr;\n+ sockaddr.sun_family = AF_INET;\n+ memcpy(sockaddr.sun_path, kBadName, sizeof(kBadName));\n+\n+ EXPECT_THAT(\n+ bind(pair->first_fd(), reinterpret_cast<struct sockaddr*>(&sockaddr),\n+ sizeof(sockaddr)),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\nTEST_P(UnixSocketPairTest, RecvmmsgTimeoutAfterRecv) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\nchar sent_data[10];\n"
}
] | Go | Apache License 2.0 | google/gvisor | unix: allow to bind unix sockets only to AF_UNIX addresses
Reported-by: [email protected]
PiperOrigin-RevId: 285228312 |
259,885 | 12.12.2019 13:17:47 | 28,800 | 93d429d5b1e3801fb4c29568bcd40d6854c9fe94 | Implement memmap.MappingIdentity for vfs.FileDescription. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/memmap/BUILD",
"new_path": "pkg/sentry/memmap/BUILD",
"diff": "@@ -41,7 +41,6 @@ go_library(\nvisibility = [\"//pkg/sentry:internal\"],\ndeps = [\n\"//pkg/log\",\n- \"//pkg/refs\",\n\"//pkg/sentry/context\",\n\"//pkg/sentry/platform\",\n\"//pkg/sentry/usermem\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/memmap/memmap.go",
"new_path": "pkg/sentry/memmap/memmap.go",
"diff": "@@ -18,7 +18,6 @@ package memmap\nimport (\n\"fmt\"\n- \"gvisor.dev/gvisor/pkg/refs\"\n\"gvisor.dev/gvisor/pkg/sentry/context\"\n\"gvisor.dev/gvisor/pkg/sentry/platform\"\n\"gvisor.dev/gvisor/pkg/sentry/usermem\"\n@@ -235,8 +234,11 @@ type InvalidateOpts struct {\n// coincidental; fs.File implements MappingIdentity, and some\n// fs.InodeOperations implement Mappable.)\ntype MappingIdentity interface {\n- // MappingIdentity is reference-counted.\n- refs.RefCounter\n+ // IncRef increments the MappingIdentity's reference count.\n+ IncRef()\n+\n+ // DecRef decrements the MappingIdentity's reference count.\n+ DecRef()\n// MappedName returns the application-visible name shown in\n// /proc/[pid]/maps.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/context.go",
"new_path": "pkg/sentry/vfs/context.go",
"diff": "@@ -24,6 +24,9 @@ type contextID int\nconst (\n// CtxMountNamespace is a Context.Value key for a MountNamespace.\nCtxMountNamespace contextID = iota\n+\n+ // CtxRoot is a Context.Value key for a VFS root.\n+ CtxRoot\n)\n// MountNamespaceFromContext returns the MountNamespace used by ctx. It does\n@@ -35,3 +38,13 @@ func MountNamespaceFromContext(ctx context.Context) *MountNamespace {\n}\nreturn nil\n}\n+\n+// RootFromContext returns the VFS root used by ctx. It takes a reference on\n+// the returned VirtualDentry. If ctx does not have a specific VFS root,\n+// RootFromContext returns a zero-value VirtualDentry.\n+func RootFromContext(ctx context.Context) VirtualDentry {\n+ if v := ctx.Value(CtxRoot); v != nil {\n+ return v.(VirtualDentry)\n+ }\n+ return VirtualDentry{}\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/file_description.go",
"new_path": "pkg/sentry/vfs/file_description.go",
"diff": "@@ -334,3 +334,47 @@ func (fd *FileDescription) Ioctl(ctx context.Context, uio usermem.IO, args arch.\nfunc (fd *FileDescription) SyncFS(ctx context.Context) error {\nreturn fd.vd.mount.fs.impl.Sync(ctx)\n}\n+\n+// MappedName implements memmap.MappingIdentity.MappedName.\n+func (fd *FileDescription) MappedName(ctx context.Context) string {\n+ vfsroot := RootFromContext(ctx)\n+ s, _ := fd.vd.mount.vfs.PathnameWithDeleted(ctx, vfsroot, fd.vd)\n+ if vfsroot.Ok() {\n+ vfsroot.DecRef()\n+ }\n+ return s\n+}\n+\n+// DeviceID implements memmap.MappingIdentity.DeviceID.\n+func (fd *FileDescription) DeviceID() uint64 {\n+ stat, err := fd.impl.Stat(context.Background(), StatOptions{\n+ // There is no STATX_DEV; we assume that Stat will return it if it's\n+ // available regardless of mask.\n+ Mask: 0,\n+ // fs/proc/task_mmu.c:show_map_vma() just reads inode::i_sb->s_dev\n+ // directly.\n+ Sync: linux.AT_STATX_DONT_SYNC,\n+ })\n+ if err != nil {\n+ return 0\n+ }\n+ return uint64(linux.MakeDeviceID(uint16(stat.DevMajor), stat.DevMinor))\n+}\n+\n+// InodeID implements memmap.MappingIdentity.InodeID.\n+func (fd *FileDescription) InodeID() uint64 {\n+ stat, err := fd.impl.Stat(context.Background(), StatOptions{\n+ Mask: linux.STATX_INO,\n+ // fs/proc/task_mmu.c:show_map_vma() just reads inode::i_ino directly.\n+ Sync: linux.AT_STATX_DONT_SYNC,\n+ })\n+ if err != nil || stat.Mask&linux.STATX_INO == 0 {\n+ return 0\n+ }\n+ return stat.Ino\n+}\n+\n+// Msync implements memmap.MappingIdentity.Msync.\n+func (fd *FileDescription) Msync(ctx context.Context, mr memmap.MappableRange) error {\n+ return fd.impl.Sync(ctx)\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": "@@ -252,3 +252,12 @@ func (fd *DynamicBytesFileDescriptionImpl) Seek(ctx context.Context, offset int6\nfd.off = offset\nreturn offset, nil\n}\n+\n+// GenericConfigureMMap may be used by most implementations of\n+// FileDescriptionImpl.ConfigureMMap.\n+func GenericConfigureMMap(fd *FileDescription, m memmap.Mappable, opts *memmap.MMapOpts) error {\n+ opts.Mappable = m\n+ opts.MappingIdentity = fd\n+ fd.IncRef()\n+ return nil\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement memmap.MappingIdentity for vfs.FileDescription.
PiperOrigin-RevId: 285255855 |
260,004 | 13.12.2019 16:26:06 | 28,800 | ad80dcf47077a1938631fe36f6b406256f3f3f4f | Properly generate the EUI64 interface identifier from an Ethernet address
Fixed a bug where the interface identifier was not properly generated from an
Ethernet address.
Tests: Unittests to make sure the functions generating the EUI64 interface
identifier are correct. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/BUILD",
"new_path": "pkg/tcpip/header/BUILD",
"diff": "@@ -38,12 +38,15 @@ go_test(\nsize = \"small\",\nsrcs = [\n\"checksum_test.go\",\n+ \"ipv6_test.go\",\n\"ipversion_test.go\",\n\"tcp_test.go\",\n],\ndeps = [\n\":header\",\n+ \"//pkg/tcpip\",\n\"//pkg/tcpip/buffer\",\n+ \"@com_github_google_go-cmp//cmp:go_default_library\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/ipv6.go",
"new_path": "pkg/tcpip/header/ipv6.go",
"diff": "@@ -278,33 +278,34 @@ func SolicitedNodeAddr(addr tcpip.Address) tcpip.Address {\nreturn solicitedNodeMulticastPrefix + addr[len(addr)-3:]\n}\n-// EthernetAdddressToEUI64IntoBuf populates buf with a EUI-64 from a 48-bit\n-// Ethernet/MAC address.\n+// EthernetAdddressToModifiedEUI64IntoBuf populates buf with a modified EUI-64\n+// from a 48-bit Ethernet/MAC address, as per RFC 4291 section 2.5.1.\n//\n// buf MUST be at least 8 bytes.\n-func EthernetAdddressToEUI64IntoBuf(linkAddr tcpip.LinkAddress, buf []byte) {\n+func EthernetAdddressToModifiedEUI64IntoBuf(linkAddr tcpip.LinkAddress, buf []byte) {\nbuf[0] = linkAddr[0] ^ 2\nbuf[1] = linkAddr[1]\nbuf[2] = linkAddr[2]\n- buf[3] = 0xFE\n+ buf[3] = 0xFF\nbuf[4] = 0xFE\nbuf[5] = linkAddr[3]\nbuf[6] = linkAddr[4]\nbuf[7] = linkAddr[5]\n}\n-// EthernetAddressToEUI64 computes an EUI-64 from a 48-bit Ethernet/MAC address.\n-func EthernetAddressToEUI64(linkAddr tcpip.LinkAddress) [IIDSize]byte {\n+// EthernetAddressToModifiedEUI64 computes a modified EUI-64 from a 48-bit\n+// Ethernet/MAC address, as per RFC 4291 section 2.5.1.\n+func EthernetAddressToModifiedEUI64(linkAddr tcpip.LinkAddress) [IIDSize]byte {\nvar buf [IIDSize]byte\n- EthernetAdddressToEUI64IntoBuf(linkAddr, buf[:])\n+ EthernetAdddressToModifiedEUI64IntoBuf(linkAddr, buf[:])\nreturn buf\n}\n// LinkLocalAddr computes the default IPv6 link-local address from a link-layer\n// (MAC) address.\nfunc LinkLocalAddr(linkAddr tcpip.LinkAddress) tcpip.Address {\n- // Convert a 48-bit MAC to an EUI-64 and then prepend the link-local\n- // header, FE80::.\n+ // Convert a 48-bit MAC to a modified EUI-64 and then prepend the\n+ // link-local header, FE80::.\n//\n// The conversion is very nearly:\n// aa:bb:cc:dd:ee:ff => FE80::Aabb:ccFF:FEdd:eeff\n@@ -313,7 +314,7 @@ func LinkLocalAddr(linkAddr tcpip.LinkAddress) tcpip.Address {\n0: 0xFE,\n1: 0x80,\n}\n- EthernetAdddressToEUI64IntoBuf(linkAddr, lladdrb[IIDOffsetInIPv6Address:])\n+ EthernetAdddressToModifiedEUI64IntoBuf(linkAddr, lladdrb[IIDOffsetInIPv6Address:])\nreturn tcpip.Address(lladdrb[:])\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/tcpip/header/ipv6_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 header_test\n+\n+import (\n+ \"testing\"\n+\n+ \"github.com/google/go-cmp/cmp\"\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n+)\n+\n+const linkAddr = tcpip.LinkAddress(\"\\x02\\x02\\x03\\x04\\x05\\x06\")\n+\n+func TestEthernetAdddressToModifiedEUI64(t *testing.T) {\n+ expectedIID := [header.IIDSize]byte{0, 2, 3, 255, 254, 4, 5, 6}\n+\n+ if diff := cmp.Diff(expectedIID, header.EthernetAddressToModifiedEUI64(linkAddr)); diff != \"\" {\n+ t.Errorf(\"EthernetAddressToModifiedEUI64(%s) mismatch (-want +got):\\n%s\", linkAddr, diff)\n+ }\n+\n+ var buf [header.IIDSize]byte\n+ header.EthernetAdddressToModifiedEUI64IntoBuf(linkAddr, buf[:])\n+ if diff := cmp.Diff(expectedIID, buf); diff != \"\" {\n+ t.Errorf(\"EthernetAddressToModifiedEUI64IntoBuf(%s, _) mismatch (-want +got):\\n%s\", linkAddr, diff)\n+ }\n+}\n+\n+func TestLinkLocalAddr(t *testing.T) {\n+ if got, want := header.LinkLocalAddr(linkAddr), tcpip.Address(\"\\xfe\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x03\\xff\\xfe\\x04\\x05\\x06\"); got != want {\n+ t.Errorf(\"got LinkLocalAddr(%s) = %s, want = %s\", linkAddr, got, want)\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/ndp.go",
"new_path": "pkg/tcpip/stack/ndp.go",
"diff": "@@ -1049,11 +1049,11 @@ func (ndp *ndpState) handleAutonomousPrefixInformation(pi header.NDPPrefixInform\nreturn\n}\n- // Generate an address within prefix from the EUI-64 of ndp's NIC's\n- // Ethernet MAC address.\n+ // Generate an address within prefix from the modified EUI-64 of ndp's\n+ // NIC's Ethernet MAC address.\naddrBytes := make([]byte, header.IPv6AddressSize)\ncopy(addrBytes[:header.IIDOffsetInIPv6Address], prefix.ID()[:header.IIDOffsetInIPv6Address])\n- header.EthernetAdddressToEUI64IntoBuf(linkAddr, addrBytes[header.IIDOffsetInIPv6Address:])\n+ header.EthernetAdddressToModifiedEUI64IntoBuf(linkAddr, addrBytes[header.IIDOffsetInIPv6Address:])\naddr := tcpip.Address(addrBytes)\naddrWithPrefix := tcpip.AddressWithPrefix{\nAddress: addr,\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/ndp_test.go",
"new_path": "pkg/tcpip/stack/ndp_test.go",
"diff": "@@ -62,7 +62,7 @@ func prefixSubnetAddr(offset uint8, linkAddr tcpip.LinkAddress) (tcpip.AddressWi\nvar addr tcpip.AddressWithPrefix\nif header.IsValidUnicastEthernetAddress(linkAddr) {\naddrBytes := []byte(subnet.ID())\n- header.EthernetAdddressToEUI64IntoBuf(linkAddr, addrBytes[header.IIDOffsetInIPv6Address:])\n+ header.EthernetAdddressToModifiedEUI64IntoBuf(linkAddr, addrBytes[header.IIDOffsetInIPv6Address:])\naddr = tcpip.AddressWithPrefix{\nAddress: tcpip.Address(addrBytes),\nPrefixLen: 64,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Properly generate the EUI64 interface identifier from an Ethernet address
Fixed a bug where the interface identifier was not properly generated from an
Ethernet address.
Tests: Unittests to make sure the functions generating the EUI64 interface
identifier are correct.
PiperOrigin-RevId: 285494562 |
259,887 | 15.12.2019 20:57:23 | -10,800 | 8782f0e287df2a2fd9f9dfb3f0e1589cc15a4f91 | Set CPU number to CPU quota
When application is not cgroups-aware, it can spawn excessive threads
which often defaults to CPU number.
Introduce a opt-in flag that will set CPU number accordingly to CPU
quota (if available).
Fixes | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/config.go",
"new_path": "runsc/boot/config.go",
"diff": "@@ -250,6 +250,12 @@ type Config struct {\n// multiple tests are run in parallel, since there is no way to pass\n// parameters to the runtime from docker.\nTestOnlyTestNameEnv string\n+\n+ // CPUNumFromQuota sets CPU number count to available CPU quota, using\n+ // least integer value greater than or equal to quota.\n+ //\n+ // E.g. 0.2 CPU quota would result in 1, and 1.9 in 2.\n+ CPUNumFromQuota bool\n}\n// ToFlags returns a slice of flags that correspond to the given Config.\n@@ -282,6 +288,9 @@ func (c *Config) ToFlags() []string {\n\"--software-gso=\" + strconv.FormatBool(c.SoftwareGSO),\n\"--overlayfs-stale-read=\" + strconv.FormatBool(c.OverlayfsStaleRead),\n}\n+ if c.CPUNumFromQuota {\n+ f = append(f, \"--cpu-num-from-quota\")\n+ }\n// Only include these if set since it is never to be used by users.\nif c.TestOnlyAllowRunAsCurrentUserWithoutChroot {\nf = append(f, \"--TESTONLY-unsafe-nonroot=true\")\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cgroup/cgroup.go",
"new_path": "runsc/cgroup/cgroup.go",
"diff": "@@ -101,6 +101,14 @@ func getValue(path, name string) (string, error) {\nreturn string(out), nil\n}\n+func getInt(path, name string) (int, error) {\n+ s, err := getValue(path, name)\n+ if err != nil {\n+ return 0, err\n+ }\n+ return strconv.Atoi(strings.TrimSpace(s))\n+}\n+\n// fillFromAncestor sets the value of a cgroup file from the first ancestor\n// that has content. It does nothing if the file in 'path' has already been set.\nfunc fillFromAncestor(path string) (string, error) {\n@@ -323,6 +331,22 @@ func (c *Cgroup) Join() (func(), error) {\nreturn undo, nil\n}\n+func (c *Cgroup) CPUQuota() (float64, error) {\n+ path := c.makePath(\"cpu\")\n+ quota, err := getInt(path, \"cpu.cfs_quota_us\")\n+ if err != nil {\n+ return -1, err\n+ }\n+ period, err := getInt(path, \"cpu.cfs_period_us\")\n+ if err != nil {\n+ return -1, err\n+ }\n+ if quota <= 0 || period <= 0 {\n+ return -1, err\n+ }\n+ return float64(quota) / float64(period), nil\n+}\n+\n// NumCPU returns the number of CPUs configured in 'cpuset/cpuset.cpus'.\nfunc (c *Cgroup) NumCPU() (int, error) {\npath := c.makePath(\"cpuset\")\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/main.go",
"new_path": "runsc/main.go",
"diff": "@@ -82,6 +82,7 @@ var (\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.\")\nreferenceLeakMode = flag.String(\"ref-leak-mode\", \"disabled\", \"sets reference leak check mode: disabled (default), log-names, log-traces.\")\n+ cpuNumFromQuota = flag.Bool(\"cpu-num-from-quota\", false, \"set cpu number to cpu quota (least integer greater than quota value)\")\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@@ -225,6 +226,7 @@ func main() {\nAlsoLogToStderr: *alsoLogToStderr,\nReferenceLeakMode: refsLeakMode,\nOverlayfsStaleRead: *overlayfsStaleRead,\n+ CPUNumFromQuota: *cpuNumFromQuota,\nTestOnlyAllowRunAsCurrentUserWithoutChroot: *testOnlyAllowRunAsCurrentUserWithoutChroot,\nTestOnlyTestNameEnv: *testOnlyTestNameEnv,\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -18,6 +18,7 @@ package sandbox\nimport (\n\"context\"\n\"fmt\"\n+ \"math\"\n\"os\"\n\"os/exec\"\n\"strconv\"\n@@ -631,6 +632,15 @@ func (s *Sandbox) createSandboxProcess(conf *boot.Config, args *Args, startSyncF\nif err != nil {\nreturn fmt.Errorf(\"getting cpu count from cgroups: %v\", err)\n}\n+ if conf.CPUNumFromQuota {\n+ quota, err := s.Cgroup.CPUQuota()\n+ if err != nil {\n+ return fmt.Errorf(\"getting cpu qouta from cgroups: %v\", err)\n+ }\n+ if quota > 0 {\n+ cpuNum = int(math.Ceil(quota))\n+ }\n+ }\ncmd.Args = append(cmd.Args, \"--cpu-num\", strconv.Itoa(cpuNum))\nmem, err := s.Cgroup.MemoryLimit()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Set CPU number to CPU quota
When application is not cgroups-aware, it can spawn excessive threads
which often defaults to CPU number.
Introduce a opt-in flag that will set CPU number accordingly to CPU
quota (if available).
Fixes #1391 |
259,860 | 16.12.2019 14:40:01 | 28,800 | 3193b2fff8149fe43a3a59c266359e7f443a1563 | Drop unnecessary cast.
Bitshift operators with signed int is supported in Go 1.13. | [
{
"change_type": "MODIFY",
"old_path": "go.mod",
"new_path": "go.mod",
"diff": "module gvisor.dev/gvisor\n-go 1.12\n+go 1.13\nrequire (\ngithub.com/cenkalti/backoff v0.0.0-20190506075156-2146c9339422\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/strace/select.go",
"new_path": "pkg/sentry/strace/select.go",
"diff": "@@ -27,7 +27,7 @@ func fdsFromSet(t *kernel.Task, set []byte) []int {\n// Append n if the n-th bit is 1.\nfor i, v := range set {\nfor j := 0; j < 8; j++ {\n- if (v>>uint(j))&1 == 1 {\n+ if (v>>j)&1 == 1 {\nfds = append(fds, i*8+j)\n}\n}\n@@ -42,7 +42,7 @@ func fdSet(t *kernel.Task, nfds int, addr usermem.Addr) string {\n// Calculate the size of the fd set (one bit per fd).\nnBytes := (nfds + 7) / 8\n- nBitsInLastPartialByte := uint(nfds % 8)\n+ nBitsInLastPartialByte := nfds % 8\nset, err := linux.CopyInFDSet(t, addr, nBytes, nBitsInLastPartialByte)\nif err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_poll.go",
"new_path": "pkg/sentry/syscalls/linux/sys_poll.go",
"diff": "@@ -198,7 +198,7 @@ func doPoll(t *kernel.Task, addr usermem.Addr, nfds uint, timeout time.Duration)\n}\n// CopyInFDSet copies an fd set from select(2)/pselect(2).\n-func CopyInFDSet(t *kernel.Task, addr usermem.Addr, nBytes int, nBitsInLastPartialByte uint) ([]byte, error) {\n+func CopyInFDSet(t *kernel.Task, addr usermem.Addr, nBytes, nBitsInLastPartialByte int) ([]byte, error) {\nset := make([]byte, nBytes)\nif addr != 0 {\n@@ -222,7 +222,7 @@ func doSelect(t *kernel.Task, nfds int, readFDs, writeFDs, exceptFDs usermem.Add\n// Calculate the size of the fd sets (one bit per fd).\nnBytes := (nfds + 7) / 8\n- nBitsInLastPartialByte := uint(nfds % 8)\n+ nBitsInLastPartialByte := nfds % 8\n// Capture all the provided input vectors.\nr, err := CopyInFDSet(t, readFDs, nBytes, nBitsInLastPartialByte)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Drop unnecessary cast.
Bitshift operators with signed int is supported in Go 1.13.
PiperOrigin-RevId: 285853622 |
259,887 | 17.12.2019 20:41:02 | -10,800 | 67f678be27b3f4545d41539bd6855527da53a250 | Leave minimum CPU number as a constant
Remove introduced CPUNumMin config and hard-code it as 2. | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/config.go",
"new_path": "runsc/boot/config.go",
"diff": "@@ -256,12 +256,6 @@ type Config struct {\n//\n// E.g. 0.2 CPU quota will result in 1, and 1.9 in 2.\nCPUNumFromQuota bool\n-\n- // CPUNumMin is minimum value of CPU number setting when CPUNumFromQuota\n- // strategy is active.\n- //\n- // E.g. when CPUNumMin is 2, 0.2 CPU quota will result in 2 instead of 1.\n- CPUNumMin int\n}\n// ToFlags returns a slice of flags that correspond to the given Config.\n@@ -295,9 +289,7 @@ func (c *Config) ToFlags() []string {\n\"--overlayfs-stale-read=\" + strconv.FormatBool(c.OverlayfsStaleRead),\n}\nif c.CPUNumFromQuota {\n- f = append(f, \"--cpu-num-from-quota\",\n- \"--cpu-num-min=\"+strconv.Itoa(c.CPUNumMin),\n- )\n+ f = append(f, \"--cpu-num-from-quota\")\n}\n// Only include these if set since it is never to be used by users.\nif c.TestOnlyAllowRunAsCurrentUserWithoutChroot {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/main.go",
"new_path": "runsc/main.go",
"diff": "@@ -82,8 +82,7 @@ var (\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.\")\nreferenceLeakMode = flag.String(\"ref-leak-mode\", \"disabled\", \"sets reference leak check mode: disabled (default), log-names, log-traces.\")\n- cpuNumFromQuota = flag.Bool(\"cpu-num-from-quota\", false, \"set cpu number to cpu quota (least integer greater or equal to quota value)\")\n- cpuNumMin = flag.Int(\"cpu-num-min\", 2, \"minimum number of cpu to use with --cpu-num-from-quota\")\n+ cpuNumFromQuota = flag.Bool(\"cpu-num-from-quota\", false, \"set cpu number to cpu quota (least integer greater or equal to quota value, but not less than 2)\")\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@@ -228,7 +227,6 @@ func main() {\nReferenceLeakMode: refsLeakMode,\nOverlayfsStaleRead: *overlayfsStaleRead,\nCPUNumFromQuota: *cpuNumFromQuota,\n- CPUNumMin: *cpuNumMin,\nTestOnlyAllowRunAsCurrentUserWithoutChroot: *testOnlyAllowRunAsCurrentUserWithoutChroot,\nTestOnlyTestNameEnv: *testOnlyTestNameEnv,\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -633,13 +633,18 @@ func (s *Sandbox) createSandboxProcess(conf *boot.Config, args *Args, startSyncF\nreturn fmt.Errorf(\"getting cpu count from cgroups: %v\", err)\n}\nif conf.CPUNumFromQuota {\n+ // Dropping below 2 CPUs can trigger application to disable\n+ // locks that can lead do hard to debug errors, so just\n+ // leaving two cores as reasonable default.\n+ const minCPUs = 2\n+\nquota, err := s.Cgroup.CPUQuota()\nif err != nil {\nreturn fmt.Errorf(\"getting cpu qouta from cgroups: %v\", err)\n}\nif n := int(math.Ceil(quota)); n > 0 {\n- if n < conf.CPUNumMin {\n- n = conf.CPUNumMin\n+ if n < minCPUs {\n+ n = minCPUs\n}\nif n < cpuNum {\n// Only lower the cpu number.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Leave minimum CPU number as a constant
Remove introduced CPUNumMin config and hard-code it as 2. |
259,881 | 17.12.2019 13:57:39 | 28,800 | 91f1ac731933ac1fe0f9ef30f4c9d06fa4031021 | Mark enableCpuidFault nosplit
This is called after fork, so it must be nosplit.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/subprocess_amd64.go",
"new_path": "pkg/sentry/platform/ptrace/subprocess_amd64.go",
"diff": "@@ -167,8 +167,14 @@ func patchSignalInfo(regs *syscall.PtraceRegs, signalInfo *arch.SignalInfo) {\n}\n}\n-// enableCpuidFault enable cpuid-faulting; this may fail on older kernels or hardware,\n-// so we just disregard the result. Host CPUID will be enabled.\n+// enableCpuidFault enables cpuid-faulting.\n+//\n+// This may fail on older kernels or hardware, so we just disregard the result.\n+// Host CPUID will be enabled.\n+//\n+// This is safe to call in an afterFork context.\n+//\n+//go:nosplit\nfunc enableCpuidFault() {\nsyscall.RawSyscall6(syscall.SYS_ARCH_PRCTL, linux.ARCH_SET_CPUID, 0, 0, 0, 0, 0)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/subprocess_arm64.go",
"new_path": "pkg/sentry/platform/ptrace/subprocess_arm64.go",
"diff": "@@ -151,6 +151,8 @@ func patchSignalInfo(regs *syscall.PtraceRegs, signalInfo *arch.SignalInfo) {\n}\n// Noop on arm64.\n+//\n+//go:nosplit\nfunc enableCpuidFault() {\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Mark enableCpuidFault nosplit
This is called after fork, so it must be nosplit.
Updates #1408
PiperOrigin-RevId: 286053054 |
259,974 | 18.11.2019 09:34:02 | 0 | cb533f18cbb93e3f236ba191d1693e93716313b5 | Enable pkg/sentry/strace support on arm64. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/strace/BUILD",
"new_path": "pkg/sentry/strace/BUILD",
"diff": "@@ -10,7 +10,8 @@ go_library(\n\"capability.go\",\n\"clone.go\",\n\"futex.go\",\n- \"linux64.go\",\n+ \"linux64_amd64.go\",\n+ \"linux64_arm64.go\",\n\"open.go\",\n\"poll.go\",\n\"ptrace.go\",\n"
},
{
"change_type": "RENAME",
"old_path": "pkg/sentry/strace/linux64.go",
"new_path": "pkg/sentry/strace/linux64_amd64.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// See the License for the specific language governing permissions and\n// limitations under the License.\n+// +build amd64\n+\npackage strace\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi\"\n+ \"gvisor.dev/gvisor/pkg/sentry/arch\"\n+)\n+\n// linuxAMD64 provides a mapping of the Linux amd64 syscalls and their argument\n// types for display / formatting.\nvar linuxAMD64 = SyscallMap{\n@@ -365,3 +372,11 @@ var linuxAMD64 = SyscallMap{\n434: makeSyscallInfo(\"pidfd_open\", Hex, Hex),\n435: makeSyscallInfo(\"clone3\", Hex, Hex),\n}\n+\n+func init() {\n+ syscallTables = append(syscallTables,\n+ syscallTable{\n+ os: abi.Linux,\n+ arch: arch.AMD64,\n+ syscalls: linuxAMD64})\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/strace/linux64_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 strace\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi\"\n+ \"gvisor.dev/gvisor/pkg/sentry/arch\"\n+)\n+\n+// linuxARM64 provides a mapping of the Linux arm64 syscalls and their argument\n+// types for display / formatting.\n+var linuxARM64 = SyscallMap{\n+ 0: makeSyscallInfo(\"io_setup\", Hex, Hex),\n+ 1: makeSyscallInfo(\"io_destroy\", Hex),\n+ 2: makeSyscallInfo(\"io_submit\", Hex, Hex, Hex),\n+ 3: makeSyscallInfo(\"io_cancel\", Hex, Hex, Hex),\n+ 4: makeSyscallInfo(\"io_getevents\", Hex, Hex, Hex, Hex, Timespec),\n+ 5: makeSyscallInfo(\"setxattr\", Path, Path, Hex, Hex, Hex),\n+ 6: makeSyscallInfo(\"lsetxattr\", Path, Path, Hex, Hex, Hex),\n+ 7: makeSyscallInfo(\"fsetxattr\", FD, Path, Hex, Hex, Hex),\n+ 8: makeSyscallInfo(\"getxattr\", Path, Path, Hex, Hex),\n+ 9: makeSyscallInfo(\"lgetxattr\", Path, Path, Hex, Hex),\n+ 10: makeSyscallInfo(\"fgetxattr\", FD, Path, Hex, Hex),\n+ 11: makeSyscallInfo(\"listxattr\", Path, Path, Hex),\n+ 12: makeSyscallInfo(\"llistxattr\", Path, Path, Hex),\n+ 13: makeSyscallInfo(\"flistxattr\", FD, Path, Hex),\n+ 14: makeSyscallInfo(\"removexattr\", Path, Path),\n+ 15: makeSyscallInfo(\"lremovexattr\", Path, Path),\n+ 16: makeSyscallInfo(\"fremovexattr\", FD, Path),\n+ 17: makeSyscallInfo(\"getcwd\", PostPath, Hex),\n+ 18: makeSyscallInfo(\"lookup_dcookie\", Hex, Hex, Hex),\n+ 19: makeSyscallInfo(\"eventfd2\", Hex, Hex),\n+ 20: makeSyscallInfo(\"epoll_create1\", Hex),\n+ 21: makeSyscallInfo(\"epoll_ctl\", Hex, Hex, FD, Hex),\n+ 22: makeSyscallInfo(\"epoll_pwait\", Hex, Hex, Hex, Hex, SigSet, Hex),\n+ 23: makeSyscallInfo(\"dup\", FD),\n+ 24: makeSyscallInfo(\"dup3\", FD, FD, Hex),\n+ 25: makeSyscallInfo(\"fcntl\", FD, Hex, Hex),\n+ 26: makeSyscallInfo(\"inotify_init1\", Hex),\n+ 27: makeSyscallInfo(\"inotify_add_watch\", Hex, Path, Hex),\n+ 28: makeSyscallInfo(\"inotify_rm_watch\", Hex, Hex),\n+ 29: makeSyscallInfo(\"ioctl\", FD, Hex, Hex),\n+ 30: makeSyscallInfo(\"ioprio_set\", Hex, Hex, Hex),\n+ 31: makeSyscallInfo(\"ioprio_get\", Hex, Hex),\n+ 32: makeSyscallInfo(\"flock\", FD, Hex),\n+ 33: makeSyscallInfo(\"mknodat\", FD, Path, Mode, Hex),\n+ 34: makeSyscallInfo(\"mkdirat\", FD, Path, Hex),\n+ 35: makeSyscallInfo(\"unlinkat\", FD, Path, Hex),\n+ 36: makeSyscallInfo(\"symlinkat\", Path, Hex, Path),\n+ 37: makeSyscallInfo(\"linkat\", FD, Path, Hex, Path, Hex),\n+ 38: makeSyscallInfo(\"renameat\", FD, Path, Hex, Path),\n+ 39: makeSyscallInfo(\"umount2\", Path, Hex),\n+ 40: makeSyscallInfo(\"mount\", Path, Path, Path, Hex, Path),\n+ 41: makeSyscallInfo(\"pivot_root\", Path, Path),\n+ 42: makeSyscallInfo(\"nfsservctl\", Hex, Hex, Hex),\n+ 43: makeSyscallInfo(\"statfs\", Path, Hex),\n+ 44: makeSyscallInfo(\"fstatfs\", FD, Hex),\n+ 45: makeSyscallInfo(\"truncate\", Path, Hex),\n+ 46: makeSyscallInfo(\"ftruncate\", FD, Hex),\n+ 47: makeSyscallInfo(\"fallocate\", FD, Hex, Hex, Hex),\n+ 48: makeSyscallInfo(\"faccessat\", FD, Path, Oct, Hex),\n+ 49: makeSyscallInfo(\"chdir\", Path),\n+ 50: makeSyscallInfo(\"fchdir\", FD),\n+ 51: makeSyscallInfo(\"chroot\", Path),\n+ 52: makeSyscallInfo(\"fchmod\", FD, Mode),\n+ 53: makeSyscallInfo(\"fchmodat\", FD, Path, Mode),\n+ 54: makeSyscallInfo(\"fchownat\", FD, Path, Hex, Hex, Hex),\n+ 55: makeSyscallInfo(\"fchown\", FD, Hex, Hex),\n+ 56: makeSyscallInfo(\"openat\", FD, Path, OpenFlags, Mode),\n+ 57: makeSyscallInfo(\"close\", FD),\n+ 58: makeSyscallInfo(\"vhangup\"),\n+ 59: makeSyscallInfo(\"pipe2\", PipeFDs, Hex),\n+ 60: makeSyscallInfo(\"quotactl\", Hex, Hex, Hex, Hex),\n+ 61: makeSyscallInfo(\"getdents64\", FD, Hex, Hex),\n+ 62: makeSyscallInfo(\"lseek\", Hex, Hex, Hex),\n+ 63: makeSyscallInfo(\"read\", FD, ReadBuffer, Hex),\n+ 64: makeSyscallInfo(\"write\", FD, WriteBuffer, Hex),\n+ 65: makeSyscallInfo(\"readv\", FD, ReadIOVec, Hex),\n+ 66: makeSyscallInfo(\"writev\", FD, WriteIOVec, Hex),\n+ 67: makeSyscallInfo(\"pread64\", FD, ReadBuffer, Hex, Hex),\n+ 68: makeSyscallInfo(\"pwrite64\", FD, WriteBuffer, Hex, Hex),\n+ 69: makeSyscallInfo(\"preadv\", FD, ReadIOVec, Hex, Hex),\n+ 70: makeSyscallInfo(\"pwritev\", FD, WriteIOVec, Hex, Hex),\n+ 71: makeSyscallInfo(\"sendfile\", FD, FD, Hex, Hex),\n+ 72: makeSyscallInfo(\"pselect6\", Hex, Hex, Hex, Hex, Hex, Hex),\n+ 73: makeSyscallInfo(\"ppoll\", PollFDs, Hex, Timespec, SigSet, Hex),\n+ 74: makeSyscallInfo(\"signalfd4\", Hex, Hex, Hex, Hex),\n+ 75: makeSyscallInfo(\"vmsplice\", FD, Hex, Hex, Hex),\n+ 76: makeSyscallInfo(\"splice\", FD, Hex, FD, Hex, Hex, Hex),\n+ 77: makeSyscallInfo(\"tee\", FD, FD, Hex, Hex),\n+ 78: makeSyscallInfo(\"readlinkat\", FD, Path, ReadBuffer, Hex),\n+ 79: makeSyscallInfo(\"fstatat\", FD, Path, Stat, Hex),\n+ 80: makeSyscallInfo(\"fstat\", FD, Stat),\n+ 81: makeSyscallInfo(\"sync\"),\n+ 82: makeSyscallInfo(\"fsync\", FD),\n+ 83: makeSyscallInfo(\"fdatasync\", FD),\n+ 84: makeSyscallInfo(\"sync_file_range\", FD, Hex, Hex, Hex),\n+ 85: makeSyscallInfo(\"timerfd_create\", Hex, Hex),\n+ 86: makeSyscallInfo(\"timerfd_settime\", FD, Hex, ItimerSpec, PostItimerSpec),\n+ 87: makeSyscallInfo(\"timerfd_gettime\", FD, PostItimerSpec),\n+ 88: makeSyscallInfo(\"utimensat\", FD, Path, UTimeTimespec, Hex),\n+ 89: makeSyscallInfo(\"acct\", Hex),\n+ 90: makeSyscallInfo(\"capget\", CapHeader, PostCapData),\n+ 91: makeSyscallInfo(\"capset\", CapHeader, CapData),\n+ 92: makeSyscallInfo(\"personality\", Hex),\n+ 93: makeSyscallInfo(\"exit\", Hex),\n+ 94: makeSyscallInfo(\"exit_group\", Hex),\n+ 95: makeSyscallInfo(\"waitid\", Hex, Hex, Hex, Hex, Rusage),\n+ 96: makeSyscallInfo(\"set_tid_address\", Hex),\n+ 97: makeSyscallInfo(\"unshare\", CloneFlags),\n+ 98: makeSyscallInfo(\"futex\", Hex, FutexOp, Hex, Timespec, Hex, Hex),\n+ 99: makeSyscallInfo(\"set_robust_list\", Hex, Hex),\n+ 100: makeSyscallInfo(\"get_robust_list\", Hex, Hex, Hex),\n+ 101: makeSyscallInfo(\"nanosleep\", Timespec, PostTimespec),\n+ 102: makeSyscallInfo(\"getitimer\", ItimerType, PostItimerVal),\n+ 103: makeSyscallInfo(\"setitimer\", ItimerType, ItimerVal, PostItimerVal),\n+ 104: makeSyscallInfo(\"kexec_load\", Hex, Hex, Hex, Hex),\n+ 105: makeSyscallInfo(\"init_module\", Hex, Hex, Hex),\n+ 106: makeSyscallInfo(\"delete_module\", Hex, Hex),\n+ 107: makeSyscallInfo(\"timer_create\", Hex, Hex, Hex),\n+ 108: makeSyscallInfo(\"timer_gettime\", Hex, PostItimerSpec),\n+ 109: makeSyscallInfo(\"timer_getoverrun\", Hex),\n+ 110: makeSyscallInfo(\"timer_settime\", Hex, Hex, ItimerSpec, PostItimerSpec),\n+ 111: makeSyscallInfo(\"timer_delete\", Hex),\n+ 112: makeSyscallInfo(\"clock_settime\", Hex, Timespec),\n+ 113: makeSyscallInfo(\"clock_gettime\", Hex, PostTimespec),\n+ 114: makeSyscallInfo(\"clock_getres\", Hex, PostTimespec),\n+ 115: makeSyscallInfo(\"clock_nanosleep\", Hex, Hex, Timespec, PostTimespec),\n+ 116: makeSyscallInfo(\"syslog\", Hex, Hex, Hex),\n+ 117: makeSyscallInfo(\"ptrace\", PtraceRequest, Hex, Hex, Hex),\n+ 118: makeSyscallInfo(\"sched_setparam\", Hex, Hex),\n+ 119: makeSyscallInfo(\"sched_setscheduler\", Hex, Hex, Hex),\n+ 120: makeSyscallInfo(\"sched_getscheduler\", Hex),\n+ 121: makeSyscallInfo(\"sched_getparam\", Hex, Hex),\n+ 122: makeSyscallInfo(\"sched_setaffinity\", Hex, Hex, Hex),\n+ 123: makeSyscallInfo(\"sched_getaffinity\", Hex, Hex, Hex),\n+ 124: makeSyscallInfo(\"sched_yield\"),\n+ 125: makeSyscallInfo(\"sched_get_priority_max\", Hex),\n+ 126: makeSyscallInfo(\"sched_get_priority_min\", Hex),\n+ 127: makeSyscallInfo(\"sched_rr_get_interval\", Hex, Hex),\n+ 128: makeSyscallInfo(\"restart_syscall\"),\n+ 129: makeSyscallInfo(\"kill\", Hex, Signal),\n+ 130: makeSyscallInfo(\"tkill\", Hex, Signal),\n+ 131: makeSyscallInfo(\"tgkill\", Hex, Hex, Signal),\n+ 132: makeSyscallInfo(\"sigaltstack\", Hex, Hex),\n+ 133: makeSyscallInfo(\"rt_sigsuspend\", Hex),\n+ 134: makeSyscallInfo(\"rt_sigaction\", Signal, SigAction, PostSigAction),\n+ 135: makeSyscallInfo(\"rt_sigprocmask\", SignalMaskAction, SigSet, PostSigSet, Hex),\n+ 136: makeSyscallInfo(\"rt_sigpending\", Hex),\n+ 137: makeSyscallInfo(\"rt_sigtimedwait\", SigSet, Hex, Timespec, Hex),\n+ 138: makeSyscallInfo(\"rt_sigqueueinfo\", Hex, Signal, Hex),\n+ 139: makeSyscallInfo(\"rt_sigreturn\"),\n+ 140: makeSyscallInfo(\"setpriority\", Hex, Hex, Hex),\n+ 141: makeSyscallInfo(\"getpriority\", Hex, Hex),\n+ 142: makeSyscallInfo(\"reboot\", Hex, Hex, Hex, Hex),\n+ 143: makeSyscallInfo(\"setregid\", Hex, Hex),\n+ 144: makeSyscallInfo(\"setgid\", Hex),\n+ 145: makeSyscallInfo(\"setreuid\", Hex, Hex),\n+ 146: makeSyscallInfo(\"setuid\", Hex),\n+ 147: makeSyscallInfo(\"setresuid\", Hex, Hex, Hex),\n+ 148: makeSyscallInfo(\"getresuid\", Hex, Hex, Hex),\n+ 149: makeSyscallInfo(\"setresgid\", Hex, Hex, Hex),\n+ 150: makeSyscallInfo(\"getresgid\", Hex, Hex, Hex),\n+ 151: makeSyscallInfo(\"setfsuid\", Hex),\n+ 152: makeSyscallInfo(\"setfsgid\", Hex),\n+ 153: makeSyscallInfo(\"times\", Hex),\n+ 154: makeSyscallInfo(\"setpgid\", Hex, Hex),\n+ 155: makeSyscallInfo(\"getpgid\", Hex),\n+ 156: makeSyscallInfo(\"getsid\", Hex),\n+ 157: makeSyscallInfo(\"setsid\"),\n+ 158: makeSyscallInfo(\"getgroups\", Hex, Hex),\n+ 159: makeSyscallInfo(\"setgroups\", Hex, Hex),\n+ 160: makeSyscallInfo(\"uname\", Uname),\n+ 161: makeSyscallInfo(\"sethostname\", Hex, Hex),\n+ 162: makeSyscallInfo(\"setdomainname\", Hex, Hex),\n+ 163: makeSyscallInfo(\"getrlimit\", Hex, Hex),\n+ 164: makeSyscallInfo(\"setrlimit\", Hex, Hex),\n+ 165: makeSyscallInfo(\"getrusage\", Hex, Rusage),\n+ 166: makeSyscallInfo(\"umask\", Hex),\n+ 167: makeSyscallInfo(\"prctl\", Hex, Hex, Hex, Hex, Hex),\n+ 168: makeSyscallInfo(\"getcpu\", Hex, Hex, Hex),\n+ 169: makeSyscallInfo(\"gettimeofday\", Timeval, Hex),\n+ 170: makeSyscallInfo(\"settimeofday\", Timeval, Hex),\n+ 171: makeSyscallInfo(\"adjtimex\", Hex),\n+ 172: makeSyscallInfo(\"getpid\"),\n+ 173: makeSyscallInfo(\"getppid\"),\n+ 174: makeSyscallInfo(\"getuid\"),\n+ 175: makeSyscallInfo(\"geteuid\"),\n+ 176: makeSyscallInfo(\"getgid\"),\n+ 177: makeSyscallInfo(\"getegid\"),\n+ 178: makeSyscallInfo(\"gettid\"),\n+ 179: makeSyscallInfo(\"sysinfo\", Hex),\n+ 180: makeSyscallInfo(\"mq_open\", Hex, Hex, Hex, Hex),\n+ 181: makeSyscallInfo(\"mq_unlink\", Hex),\n+ 182: makeSyscallInfo(\"mq_timedsend\", Hex, Hex, Hex, Hex, Hex),\n+ 183: makeSyscallInfo(\"mq_timedreceive\", Hex, Hex, Hex, Hex, Hex),\n+ 184: makeSyscallInfo(\"mq_notify\", Hex, Hex),\n+ 185: makeSyscallInfo(\"mq_getsetattr\", Hex, Hex, Hex),\n+ 186: makeSyscallInfo(\"msgget\", Hex, Hex),\n+ 187: makeSyscallInfo(\"msgctl\", Hex, Hex, Hex),\n+ 188: makeSyscallInfo(\"msgrcv\", Hex, Hex, Hex, Hex, Hex),\n+ 189: makeSyscallInfo(\"msgsnd\", Hex, Hex, Hex, Hex),\n+ 190: makeSyscallInfo(\"semget\", Hex, Hex, Hex),\n+ 191: makeSyscallInfo(\"semctl\", Hex, Hex, Hex, Hex),\n+ 192: makeSyscallInfo(\"semtimedop\", Hex, Hex, Hex, Hex),\n+ 193: makeSyscallInfo(\"semop\", Hex, Hex, Hex),\n+ 194: makeSyscallInfo(\"shmget\", Hex, Hex, Hex),\n+ 195: makeSyscallInfo(\"shmctl\", Hex, Hex, Hex),\n+ 196: makeSyscallInfo(\"shmat\", Hex, Hex, Hex),\n+ 197: makeSyscallInfo(\"shmdt\", Hex),\n+ 198: makeSyscallInfo(\"socket\", SockFamily, SockType, SockProtocol),\n+ 199: makeSyscallInfo(\"socketpair\", SockFamily, SockType, SockProtocol, Hex),\n+ 200: makeSyscallInfo(\"bind\", FD, SockAddr, Hex),\n+ 201: makeSyscallInfo(\"listen\", FD, Hex),\n+ 202: makeSyscallInfo(\"accept\", FD, PostSockAddr, SockLen),\n+ 203: makeSyscallInfo(\"connect\", FD, SockAddr, Hex),\n+ 204: makeSyscallInfo(\"getsockname\", FD, PostSockAddr, SockLen),\n+ 205: makeSyscallInfo(\"getpeername\", FD, PostSockAddr, SockLen),\n+ 206: makeSyscallInfo(\"sendto\", FD, Hex, Hex, Hex, SockAddr, Hex),\n+ 207: makeSyscallInfo(\"recvfrom\", FD, Hex, Hex, Hex, PostSockAddr, SockLen),\n+ 208: makeSyscallInfo(\"setsockopt\", FD, Hex, Hex, Hex, Hex),\n+ 209: makeSyscallInfo(\"getsockopt\", FD, Hex, Hex, Hex, Hex),\n+ 210: makeSyscallInfo(\"shutdown\", FD, Hex),\n+ 211: makeSyscallInfo(\"sendmsg\", FD, SendMsgHdr, Hex),\n+ 212: makeSyscallInfo(\"recvmsg\", FD, RecvMsgHdr, Hex),\n+ 213: makeSyscallInfo(\"readahead\", Hex, Hex, Hex),\n+ 214: makeSyscallInfo(\"brk\", Hex),\n+ 215: makeSyscallInfo(\"munmap\", Hex, Hex),\n+ 216: makeSyscallInfo(\"mremap\", Hex, Hex, Hex, Hex, Hex),\n+ 217: makeSyscallInfo(\"add_key\", Hex, Hex, Hex, Hex, Hex),\n+ 218: makeSyscallInfo(\"request_key\", Hex, Hex, Hex, Hex),\n+ 219: makeSyscallInfo(\"keyctl\", Hex, Hex, Hex, Hex, Hex),\n+ 220: makeSyscallInfo(\"clone\", CloneFlags, Hex, Hex, Hex, Hex),\n+ 221: makeSyscallInfo(\"execve\", Path, ExecveStringVector, ExecveStringVector),\n+ 222: makeSyscallInfo(\"mmap\", Hex, Hex, Hex, Hex, FD, Hex),\n+ 223: makeSyscallInfo(\"fadvise64\", FD, Hex, Hex, Hex),\n+ 224: makeSyscallInfo(\"swapon\", Hex, Hex),\n+ 225: makeSyscallInfo(\"swapoff\", Hex),\n+ 226: makeSyscallInfo(\"mprotect\", Hex, Hex, Hex),\n+ 227: makeSyscallInfo(\"msync\", Hex, Hex, Hex),\n+ 228: makeSyscallInfo(\"mlock\", Hex, Hex),\n+ 229: makeSyscallInfo(\"munlock\", Hex, Hex),\n+ 230: makeSyscallInfo(\"mlockall\", Hex),\n+ 231: makeSyscallInfo(\"munlockall\"),\n+ 232: makeSyscallInfo(\"mincore\", Hex, Hex, Hex),\n+ 233: makeSyscallInfo(\"madvise\", Hex, Hex, Hex),\n+ 234: makeSyscallInfo(\"remap_file_pages\", Hex, Hex, Hex, Hex, Hex),\n+ 235: makeSyscallInfo(\"mbind\", Hex, Hex, Hex, Hex, Hex, Hex),\n+ 236: makeSyscallInfo(\"get_mempolicy\", Hex, Hex, Hex, Hex, Hex),\n+ 237: makeSyscallInfo(\"set_mempolicy\", Hex, Hex, Hex),\n+ 238: makeSyscallInfo(\"migrate_pages\", Hex, Hex, Hex, Hex),\n+ 239: makeSyscallInfo(\"move_pages\", Hex, Hex, Hex, Hex, Hex, Hex),\n+ 240: makeSyscallInfo(\"rt_tgsigqueueinfo\", Hex, Hex, Signal, Hex),\n+ 241: makeSyscallInfo(\"perf_event_open\", Hex, Hex, Hex, Hex, Hex),\n+ 242: makeSyscallInfo(\"accept4\", FD, PostSockAddr, SockLen, SockFlags),\n+ 243: makeSyscallInfo(\"recvmmsg\", FD, Hex, Hex, Hex, Hex),\n+\n+ 260: makeSyscallInfo(\"wait4\", Hex, Hex, Hex, Rusage),\n+ 261: makeSyscallInfo(\"prlimit64\", Hex, Hex, Hex, Hex),\n+ 262: makeSyscallInfo(\"fanotify_init\", Hex, Hex),\n+ 263: makeSyscallInfo(\"fanotify_mark\", Hex, Hex, Hex, Hex, Hex),\n+ 264: makeSyscallInfo(\"name_to_handle_at\", FD, Hex, Hex, Hex, Hex),\n+ 265: makeSyscallInfo(\"open_by_handle_at\", FD, Hex, Hex),\n+ 266: makeSyscallInfo(\"clock_adjtime\", Hex, Hex),\n+ 267: makeSyscallInfo(\"syncfs\", FD),\n+ 268: makeSyscallInfo(\"setns\", FD, Hex),\n+ 269: makeSyscallInfo(\"sendmmsg\", FD, Hex, Hex, Hex),\n+ 270: makeSyscallInfo(\"process_vm_readv\", Hex, ReadIOVec, Hex, IOVec, Hex, Hex),\n+ 271: makeSyscallInfo(\"process_vm_writev\", Hex, IOVec, Hex, WriteIOVec, Hex, Hex),\n+ 272: makeSyscallInfo(\"kcmp\", Hex, Hex, Hex, Hex, Hex),\n+ 273: makeSyscallInfo(\"finit_module\", Hex, Hex, Hex),\n+ 274: makeSyscallInfo(\"sched_setattr\", Hex, Hex, Hex),\n+ 275: makeSyscallInfo(\"sched_getattr\", Hex, Hex, Hex),\n+ 276: makeSyscallInfo(\"renameat2\", FD, Path, Hex, Path, Hex),\n+ 277: makeSyscallInfo(\"seccomp\", Hex, Hex, Hex),\n+ 278: makeSyscallInfo(\"getrandom\", Hex, Hex, Hex),\n+ 279: makeSyscallInfo(\"memfd_create\", Path, Hex),\n+ 280: makeSyscallInfo(\"bpf\", Hex, Hex, Hex),\n+ 281: makeSyscallInfo(\"execveat\", FD, Path, Hex, Hex, Hex),\n+ 282: makeSyscallInfo(\"userfaultfd\", Hex),\n+ 283: makeSyscallInfo(\"membarrier\", Hex),\n+ 284: makeSyscallInfo(\"mlock2\", Hex, Hex, Hex),\n+ 285: makeSyscallInfo(\"copy_file_range\", FD, Hex, FD, Hex, Hex, Hex),\n+ 286: makeSyscallInfo(\"preadv2\", FD, ReadIOVec, Hex, Hex, Hex),\n+ 287: makeSyscallInfo(\"pwritev2\", FD, WriteIOVec, Hex, Hex, Hex),\n+ 291: makeSyscallInfo(\"statx\", FD, Path, Hex, Hex, Hex),\n+ 292: makeSyscallInfo(\"io_pgetevents\", Hex, Hex, Hex, Hex, Timespec, SigSet),\n+ 293: makeSyscallInfo(\"rseq\", Hex, Hex, Hex, Hex),\n+ 424: makeSyscallInfo(\"pidfd_send_signal\", FD, Signal, Hex, Hex),\n+ 425: makeSyscallInfo(\"io_uring_setup\", Hex, Hex),\n+ 426: makeSyscallInfo(\"io_uring_enter\", FD, Hex, Hex, Hex, SigSet, Hex),\n+ 427: makeSyscallInfo(\"io_uring_register\", FD, Hex, Hex, Hex),\n+ 428: makeSyscallInfo(\"open_tree\", FD, Path, Hex),\n+ 429: makeSyscallInfo(\"move_mount\", FD, Path, FD, Path, Hex),\n+ 430: makeSyscallInfo(\"fsopen\", Path, Hex), // Not quite a path, but close.\n+ 431: makeSyscallInfo(\"fsconfig\", FD, Hex, Hex, Hex, Hex),\n+ 432: makeSyscallInfo(\"fsmount\", FD, Hex, Hex),\n+ 433: makeSyscallInfo(\"fspick\", FD, Path, Hex),\n+ 434: makeSyscallInfo(\"pidfd_open\", Hex, Hex),\n+ 435: makeSyscallInfo(\"clone3\", Hex, Hex),\n+}\n+\n+func init() {\n+ syscallTables = append(syscallTables,\n+ syscallTable{\n+ os: abi.Linux,\n+ arch: arch.ARM64,\n+ syscalls: linuxARM64})\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/strace/syscalls.go",
"new_path": "pkg/sentry/strace/syscalls.go",
"diff": "@@ -250,14 +250,7 @@ type syscallTable struct {\nsyscalls SyscallMap\n}\n-// syscallTables contains all syscall tables.\n-var syscallTables = []syscallTable{\n- {\n- os: abi.Linux,\n- arch: arch.AMD64,\n- syscalls: linuxAMD64,\n- },\n-}\n+var syscallTables []syscallTable\n// Lookup returns the SyscallMap for the OS/Arch combination. The returned map\n// must not be changed.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enable pkg/sentry/strace support on arm64.
Signed-off-by: Haibo Xu <[email protected]>
Change-Id: I006a1845b6aab2c2fdb9d80fffc1868a6a132ecd |
259,881 | 18.12.2019 12:20:16 | 28,800 | 803437c96bb4b212dba425f0378ce4f6c0c9fff9 | Upgrade to Python 3
Python 3 tools must be listed in exec_tools for genrules. | [
{
"change_type": "MODIFY",
"old_path": "vdso/BUILD",
"new_path": "vdso/BUILD",
"diff": "@@ -68,14 +68,14 @@ genrule(\n\"&& $(location :check_vdso) \" +\n\"--check-data \" +\n\"--vdso $(location vdso.so) \",\n+ exec_tools = [\n+ \":check_vdso\",\n+ ],\nfeatures = [\"-pie\"],\ntoolchains = [\n\"@bazel_tools//tools/cpp:current_cc_toolchain\",\n\":no_pie_cc_flags\",\n],\n- tools = [\n- \":check_vdso\",\n- ],\nvisibility = [\"//:sandbox\"],\n)\n@@ -87,6 +87,6 @@ cc_flags_supplier(\npy_binary(\nname = \"check_vdso\",\nsrcs = [\"check_vdso.py\"],\n- python_version = \"PY2\",\n+ python_version = \"PY3\",\nvisibility = [\"//:sandbox\"],\n)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Upgrade to Python 3
Python 3 tools must be listed in exec_tools for genrules.
PiperOrigin-RevId: 286241702 |
259,881 | 18.12.2019 12:59:32 | 28,800 | 334a513f11f0ecc260abcce549b1f1a74edc2c51 | Add Mems_allowed to /proc/PID/status | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/task.go",
"new_path": "pkg/sentry/fs/proc/task.go",
"diff": "@@ -604,6 +604,10 @@ func (s *statusData) ReadSeqFileData(ctx context.Context, h seqfile.SeqHandle) (\nfmt.Fprintf(&buf, \"CapEff:\\t%016x\\n\", creds.EffectiveCaps)\nfmt.Fprintf(&buf, \"CapBnd:\\t%016x\\n\", creds.BoundingCaps)\nfmt.Fprintf(&buf, \"Seccomp:\\t%d\\n\", s.t.SeccompMode())\n+ // We unconditionally report a single NUMA node. See\n+ // pkg/sentry/syscalls/linux/sys_mempolicy.go.\n+ fmt.Fprintf(&buf, \"Mems_allowed:\\t1\\n\")\n+ fmt.Fprintf(&buf, \"Mems_allowed_list:\\t0\\n\")\nreturn []seqfile.SeqData{{Buf: buf.Bytes(), Handle: (*statusData)(nil)}}, 0\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/task.go",
"new_path": "pkg/sentry/fsimpl/proc/task.go",
"diff": "@@ -229,6 +229,10 @@ func (s *statusData) Generate(ctx context.Context, buf *bytes.Buffer) error {\nfmt.Fprintf(buf, \"CapEff:\\t%016x\\n\", creds.EffectiveCaps)\nfmt.Fprintf(buf, \"CapBnd:\\t%016x\\n\", creds.BoundingCaps)\nfmt.Fprintf(buf, \"Seccomp:\\t%d\\n\", s.t.SeccompMode())\n+ // We unconditionally report a single NUMA node. See\n+ // pkg/sentry/syscalls/linux/sys_mempolicy.go.\n+ fmt.Fprintf(buf, \"Mems_allowed:\\t1\\n\")\n+ fmt.Fprintf(buf, \"Mems_allowed_list:\\t0\\n\")\nreturn nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add Mems_allowed to /proc/PID/status
PiperOrigin-RevId: 286248378 |
259,885 | 18.12.2019 15:47:24 | 28,800 | 744401297a8c93ce5992ba99aa84f3dcdc19ae9e | Add VFS2 plumbing for extended attributes. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/ext/filesystem.go",
"new_path": "pkg/sentry/fsimpl/ext/filesystem.go",
"diff": "@@ -443,6 +443,42 @@ func (fs *filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\nreturn syserror.EROFS\n}\n+// ListxattrAt implements vfs.FilesystemImpl.ListxattrAt.\n+func (fs *filesystem) ListxattrAt(ctx context.Context, rp *vfs.ResolvingPath) ([]string, error) {\n+ _, _, err := fs.walk(rp, false)\n+ if err != nil {\n+ return nil, err\n+ }\n+ return nil, syserror.ENOTSUP\n+}\n+\n+// GetxattrAt implements vfs.FilesystemImpl.GetxattrAt.\n+func (fs *filesystem) GetxattrAt(ctx context.Context, rp *vfs.ResolvingPath, name string) (string, error) {\n+ _, _, err := fs.walk(rp, false)\n+ if err != nil {\n+ return \"\", err\n+ }\n+ return \"\", syserror.ENOTSUP\n+}\n+\n+// SetxattrAt implements vfs.FilesystemImpl.SetxattrAt.\n+func (fs *filesystem) SetxattrAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.SetxattrOptions) error {\n+ _, _, err := fs.walk(rp, false)\n+ if err != nil {\n+ return err\n+ }\n+ return syserror.ENOTSUP\n+}\n+\n+// RemovexattrAt implements vfs.FilesystemImpl.RemovexattrAt.\n+func (fs *filesystem) RemovexattrAt(ctx context.Context, rp *vfs.ResolvingPath, name string) error {\n+ _, _, err := fs.walk(rp, false)\n+ if err != nil {\n+ return err\n+ }\n+ return syserror.ENOTSUP\n+}\n+\n// PrependPath implements vfs.FilesystemImpl.PrependPath.\nfunc (fs *filesystem) PrependPath(ctx context.Context, vfsroot, vd vfs.VirtualDentry, b *fspath.Builder) error {\nfs.mu.RLock()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go",
"diff": "@@ -683,6 +683,58 @@ func (fs *Filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\nreturn nil\n}\n+// ListxattrAt implements vfs.FilesystemImpl.ListxattrAt.\n+func (fs *Filesystem) ListxattrAt(ctx context.Context, rp *vfs.ResolvingPath) ([]string, error) {\n+ fs.mu.RLock()\n+ _, _, err := fs.walkExistingLocked(ctx, rp)\n+ fs.mu.RUnlock()\n+ fs.processDeferredDecRefs()\n+ if err != nil {\n+ return nil, err\n+ }\n+ // kernfs currently does not support extended attributes.\n+ return nil, syserror.ENOTSUP\n+}\n+\n+// GetxattrAt implements vfs.FilesystemImpl.GetxattrAt.\n+func (fs *Filesystem) GetxattrAt(ctx context.Context, rp *vfs.ResolvingPath, name string) (string, error) {\n+ fs.mu.RLock()\n+ _, _, err := fs.walkExistingLocked(ctx, rp)\n+ fs.mu.RUnlock()\n+ fs.processDeferredDecRefs()\n+ if err != nil {\n+ return \"\", err\n+ }\n+ // kernfs currently does not support extended attributes.\n+ return \"\", syserror.ENOTSUP\n+}\n+\n+// SetxattrAt implements vfs.FilesystemImpl.SetxattrAt.\n+func (fs *Filesystem) SetxattrAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.SetxattrOptions) error {\n+ fs.mu.RLock()\n+ _, _, err := fs.walkExistingLocked(ctx, rp)\n+ fs.mu.RUnlock()\n+ fs.processDeferredDecRefs()\n+ if err != nil {\n+ return err\n+ }\n+ // kernfs currently does not support extended attributes.\n+ return syserror.ENOTSUP\n+}\n+\n+// RemovexattrAt implements vfs.FilesystemImpl.RemovexattrAt.\n+func (fs *Filesystem) RemovexattrAt(ctx context.Context, rp *vfs.ResolvingPath, name string) error {\n+ fs.mu.RLock()\n+ _, _, err := fs.walkExistingLocked(ctx, rp)\n+ fs.mu.RUnlock()\n+ fs.processDeferredDecRefs()\n+ if err != nil {\n+ return err\n+ }\n+ // kernfs currently does not support extended attributes.\n+ return syserror.ENOTSUP\n+}\n+\n// PrependPath implements vfs.FilesystemImpl.PrependPath.\nfunc (fs *Filesystem) PrependPath(ctx context.Context, vfsroot, vd vfs.VirtualDentry, b *fspath.Builder) error {\nfs.mu.RLock()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/memfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/memfs/filesystem.go",
"diff": "@@ -584,6 +584,54 @@ func (fs *filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\nreturn nil\n}\n+// ListxattrAt implements vfs.FilesystemImpl.ListxattrAt.\n+func (fs *filesystem) ListxattrAt(ctx context.Context, rp *vfs.ResolvingPath) ([]string, error) {\n+ fs.mu.RLock()\n+ defer fs.mu.RUnlock()\n+ _, _, err := walkExistingLocked(rp)\n+ if err != nil {\n+ return nil, err\n+ }\n+ // TODO(b/127675828): support extended attributes\n+ return nil, syserror.ENOTSUP\n+}\n+\n+// GetxattrAt implements vfs.FilesystemImpl.GetxattrAt.\n+func (fs *filesystem) GetxattrAt(ctx context.Context, rp *vfs.ResolvingPath, name string) (string, error) {\n+ fs.mu.RLock()\n+ defer fs.mu.RUnlock()\n+ _, _, err := walkExistingLocked(rp)\n+ if err != nil {\n+ return \"\", err\n+ }\n+ // TODO(b/127675828): support extended attributes\n+ return \"\", syserror.ENOTSUP\n+}\n+\n+// SetxattrAt implements vfs.FilesystemImpl.SetxattrAt.\n+func (fs *filesystem) SetxattrAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.SetxattrOptions) error {\n+ fs.mu.RLock()\n+ defer fs.mu.RUnlock()\n+ _, _, err := walkExistingLocked(rp)\n+ if err != nil {\n+ return err\n+ }\n+ // TODO(b/127675828): support extended attributes\n+ return syserror.ENOTSUP\n+}\n+\n+// RemovexattrAt implements vfs.FilesystemImpl.RemovexattrAt.\n+func (fs *filesystem) RemovexattrAt(ctx context.Context, rp *vfs.ResolvingPath, name string) error {\n+ fs.mu.RLock()\n+ defer fs.mu.RUnlock()\n+ _, _, err := walkExistingLocked(rp)\n+ if err != nil {\n+ return err\n+ }\n+ // TODO(b/127675828): support extended attributes\n+ return syserror.ENOTSUP\n+}\n+\n// PrependPath implements vfs.FilesystemImpl.PrependPath.\nfunc (fs *filesystem) PrependPath(ctx context.Context, vfsroot, vd vfs.VirtualDentry, b *fspath.Builder) error {\nfs.mu.RLock()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/file_description.go",
"new_path": "pkg/sentry/vfs/file_description.go",
"diff": "@@ -22,6 +22,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/context\"\n\"gvisor.dev/gvisor/pkg/sentry/memmap\"\n\"gvisor.dev/gvisor/pkg/sentry/usermem\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n@@ -212,7 +213,21 @@ type FileDescriptionImpl interface {\n// Ioctl implements the ioctl(2) syscall.\nIoctl(ctx context.Context, uio usermem.IO, args arch.SyscallArguments) (uintptr, error)\n- // TODO: extended attributes; file locking\n+ // Listxattr returns all extended attribute names for the file.\n+ Listxattr(ctx context.Context) ([]string, error)\n+\n+ // Getxattr returns the value associated with the given extended attribute\n+ // for the file.\n+ Getxattr(ctx context.Context, name string) (string, error)\n+\n+ // Setxattr changes the value associated with the given extended attribute\n+ // for the file.\n+ Setxattr(ctx context.Context, opts SetxattrOptions) error\n+\n+ // Removexattr removes the given extended attribute from the file.\n+ Removexattr(ctx context.Context, name string) error\n+\n+ // TODO: file locking\n}\n// Dirent holds the information contained in struct linux_dirent64.\n@@ -329,6 +344,38 @@ func (fd *FileDescription) Ioctl(ctx context.Context, uio usermem.IO, args arch.\nreturn fd.impl.Ioctl(ctx, uio, args)\n}\n+// Listxattr returns all extended attribute names for the file represented by\n+// fd.\n+func (fd *FileDescription) Listxattr(ctx context.Context) ([]string, error) {\n+ names, err := fd.impl.Listxattr(ctx)\n+ if err == syserror.ENOTSUP {\n+ // Linux doesn't actually return ENOTSUP in this case; instead,\n+ // fs/xattr.c:vfs_listxattr() falls back to allowing the security\n+ // subsystem to return security extended attributes, which by default\n+ // don't exist.\n+ return nil, nil\n+ }\n+ return names, err\n+}\n+\n+// Getxattr returns the value associated with the given extended attribute for\n+// the file represented by fd.\n+func (fd *FileDescription) Getxattr(ctx context.Context, name string) (string, error) {\n+ return fd.impl.Getxattr(ctx, name)\n+}\n+\n+// Setxattr changes the value associated with the given extended attribute for\n+// the file represented by fd.\n+func (fd *FileDescription) Setxattr(ctx context.Context, opts SetxattrOptions) error {\n+ return fd.impl.Setxattr(ctx, opts)\n+}\n+\n+// Removexattr removes the given extended attribute from the file represented\n+// by fd.\n+func (fd *FileDescription) Removexattr(ctx context.Context, name string) error {\n+ return fd.impl.Removexattr(ctx, name)\n+}\n+\n// SyncFS instructs the filesystem containing fd to execute the semantics of\n// syncfs(2).\nfunc (fd *FileDescription) SyncFS(ctx context.Context) error {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/file_description_impl_util.go",
"new_path": "pkg/sentry/vfs/file_description_impl_util.go",
"diff": "@@ -127,6 +127,31 @@ func (FileDescriptionDefaultImpl) Ioctl(ctx context.Context, uio usermem.IO, arg\nreturn 0, syserror.ENOTTY\n}\n+// Listxattr implements FileDescriptionImpl.Listxattr analogously to\n+// inode_operations::listxattr == NULL in Linux.\n+func (FileDescriptionDefaultImpl) Listxattr(ctx context.Context) ([]string, error) {\n+ // This isn't exactly accurate; see FileDescription.Listxattr.\n+ return nil, syserror.ENOTSUP\n+}\n+\n+// Getxattr implements FileDescriptionImpl.Getxattr analogously to\n+// inode::i_opflags & IOP_XATTR == 0 in Linux.\n+func (FileDescriptionDefaultImpl) Getxattr(ctx context.Context, name string) (string, error) {\n+ return \"\", syserror.ENOTSUP\n+}\n+\n+// Setxattr implements FileDescriptionImpl.Setxattr analogously to\n+// inode::i_opflags & IOP_XATTR == 0 in Linux.\n+func (FileDescriptionDefaultImpl) Setxattr(ctx context.Context, opts SetxattrOptions) error {\n+ return syserror.ENOTSUP\n+}\n+\n+// Removexattr implements FileDescriptionImpl.Removexattr analogously to\n+// inode::i_opflags & IOP_XATTR == 0 in Linux.\n+func (FileDescriptionDefaultImpl) Removexattr(ctx context.Context, name string) error {\n+ return syserror.ENOTSUP\n+}\n+\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.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/filesystem.go",
"new_path": "pkg/sentry/vfs/filesystem.go",
"diff": "@@ -186,6 +186,20 @@ type FilesystemImpl interface {\n// UnlinkAt removes the non-directory file at rp.\nUnlinkAt(ctx context.Context, rp *ResolvingPath) error\n+ // ListxattrAt returns all extended attribute names for the file at rp.\n+ ListxattrAt(ctx context.Context, rp *ResolvingPath) ([]string, error)\n+\n+ // GetxattrAt returns the value associated with the given extended\n+ // attribute for the file at rp.\n+ GetxattrAt(ctx context.Context, rp *ResolvingPath, name string) (string, error)\n+\n+ // SetxattrAt changes the value associated with the given extended\n+ // attribute for the file at rp.\n+ SetxattrAt(ctx context.Context, rp *ResolvingPath, opts SetxattrOptions) error\n+\n+ // RemovexattrAt removes the given extended attribute from the file at rp.\n+ RemovexattrAt(ctx context.Context, rp *ResolvingPath, name string) error\n+\n// PrependPath prepends a path from vd to vd.Mount().Root() to b.\n//\n// If vfsroot.Ok(), it is the contextual VFS root; if it is encountered\n@@ -208,7 +222,7 @@ type FilesystemImpl interface {\n// Preconditions: vd.Mount().Filesystem().Impl() == this FilesystemImpl.\nPrependPath(ctx context.Context, vfsroot, vd VirtualDentry, b *fspath.Builder) error\n- // TODO: extended attributes; inotify_add_watch(); bind()\n+ // TODO: inotify_add_watch(); bind()\n}\n// PrependPathAtVFSRootError is returned by implementations of\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/options.go",
"new_path": "pkg/sentry/vfs/options.go",
"diff": "@@ -101,6 +101,20 @@ type SetStatOptions struct {\nStat linux.Statx\n}\n+// SetxattrOptions contains options to VirtualFilesystem.SetxattrAt(),\n+// FilesystemImpl.SetxattrAt(), FileDescription.Setxattr(), and\n+// FileDescriptionImpl.Setxattr().\n+type SetxattrOptions struct {\n+ // Name is the name of the extended attribute being mutated.\n+ Name string\n+\n+ // Value is the extended attribute's new value.\n+ Value string\n+\n+ // Flags contains flags as specified for setxattr/lsetxattr/fsetxattr(2).\n+ Flags uint32\n+}\n+\n// StatOptions contains options to VirtualFilesystem.StatAt(),\n// FilesystemImpl.StatAt(), FileDescription.Stat(), and\n// FileDescriptionImpl.Stat().\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/testutil.go",
"new_path": "pkg/sentry/vfs/testutil.go",
"diff": "@@ -117,6 +117,26 @@ func (fs *FDTestFilesystem) UnlinkAt(ctx context.Context, rp *ResolvingPath) err\nreturn syserror.EPERM\n}\n+// ListxattrAt implements FilesystemImpl.ListxattrAt.\n+func (fs *FDTestFilesystem) ListxattrAt(ctx context.Context, rp *ResolvingPath) ([]string, error) {\n+ return nil, syserror.EPERM\n+}\n+\n+// GetxattrAt implements FilesystemImpl.GetxattrAt.\n+func (fs *FDTestFilesystem) GetxattrAt(ctx context.Context, rp *ResolvingPath, name string) (string, error) {\n+ return \"\", syserror.EPERM\n+}\n+\n+// SetxattrAt implements FilesystemImpl.SetxattrAt.\n+func (fs *FDTestFilesystem) SetxattrAt(ctx context.Context, rp *ResolvingPath, opts SetxattrOptions) error {\n+ return syserror.EPERM\n+}\n+\n+// RemovexattrAt implements FilesystemImpl.RemovexattrAt.\n+func (fs *FDTestFilesystem) RemovexattrAt(ctx context.Context, rp *ResolvingPath, name string) error {\n+ return syserror.EPERM\n+}\n+\n// PrependPath implements FilesystemImpl.PrependPath.\nfunc (fs *FDTestFilesystem) PrependPath(ctx context.Context, vfsroot, vd VirtualDentry, b *fspath.Builder) error {\nb.PrependComponent(fmt.Sprintf(\"vfs.fdTestDentry:%p\", vd.dentry.impl.(*fdTestDentry)))\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/vfs.go",
"new_path": "pkg/sentry/vfs/vfs.go",
"diff": "@@ -440,6 +440,93 @@ func (vfs *VirtualFilesystem) UnlinkAt(ctx context.Context, creds *auth.Credenti\n}\n}\n+// ListxattrAt returns all extended attribute names for the file at the given\n+// path.\n+func (vfs *VirtualFilesystem) ListxattrAt(ctx context.Context, creds *auth.Credentials, pop *PathOperation) ([]string, error) {\n+ rp, err := vfs.getResolvingPath(creds, pop)\n+ if err != nil {\n+ return nil, err\n+ }\n+ for {\n+ names, err := rp.mount.fs.impl.ListxattrAt(ctx, rp)\n+ if err == nil {\n+ vfs.putResolvingPath(rp)\n+ return names, nil\n+ }\n+ if err == syserror.ENOTSUP {\n+ // Linux doesn't actually return ENOTSUP in this case; instead,\n+ // fs/xattr.c:vfs_listxattr() falls back to allowing the security\n+ // subsystem to return security extended attributes, which by\n+ // default don't exist.\n+ vfs.putResolvingPath(rp)\n+ return nil, nil\n+ }\n+ if !rp.handleError(err) {\n+ vfs.putResolvingPath(rp)\n+ return nil, err\n+ }\n+ }\n+}\n+\n+// GetxattrAt returns the value associated with the given extended attribute\n+// for the file at the given path.\n+func (vfs *VirtualFilesystem) GetxattrAt(ctx context.Context, creds *auth.Credentials, pop *PathOperation, name string) (string, error) {\n+ rp, err := vfs.getResolvingPath(creds, pop)\n+ if err != nil {\n+ return \"\", err\n+ }\n+ for {\n+ val, err := rp.mount.fs.impl.GetxattrAt(ctx, rp, name)\n+ if err == nil {\n+ vfs.putResolvingPath(rp)\n+ return val, nil\n+ }\n+ if !rp.handleError(err) {\n+ vfs.putResolvingPath(rp)\n+ return \"\", err\n+ }\n+ }\n+}\n+\n+// SetxattrAt changes the value associated with the given extended attribute\n+// for the file at the given path.\n+func (vfs *VirtualFilesystem) SetxattrAt(ctx context.Context, creds *auth.Credentials, pop *PathOperation, opts *SetxattrOptions) error {\n+ rp, err := vfs.getResolvingPath(creds, pop)\n+ if err != nil {\n+ return err\n+ }\n+ for {\n+ err := rp.mount.fs.impl.SetxattrAt(ctx, rp, *opts)\n+ if err == nil {\n+ vfs.putResolvingPath(rp)\n+ return nil\n+ }\n+ if !rp.handleError(err) {\n+ vfs.putResolvingPath(rp)\n+ return err\n+ }\n+ }\n+}\n+\n+// RemovexattrAt removes the given extended attribute from the file at rp.\n+func (vfs *VirtualFilesystem) RemovexattrAt(ctx context.Context, creds *auth.Credentials, pop *PathOperation, name string) error {\n+ rp, err := vfs.getResolvingPath(creds, pop)\n+ if err != nil {\n+ return err\n+ }\n+ for {\n+ err := rp.mount.fs.impl.RemovexattrAt(ctx, rp, name)\n+ if err == nil {\n+ vfs.putResolvingPath(rp)\n+ return nil\n+ }\n+ if !rp.handleError(err) {\n+ vfs.putResolvingPath(rp)\n+ return err\n+ }\n+ }\n+}\n+\n// SyncAllFilesystems has the semantics of Linux's sync(2).\nfunc (vfs *VirtualFilesystem) SyncAllFilesystems(ctx context.Context) error {\nfss := make(map[*Filesystem]struct{})\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add VFS2 plumbing for extended attributes.
PiperOrigin-RevId: 286281274 |
259,992 | 18.12.2019 17:09:08 | 28,800 | 0d475cdb019e659c84e767a7d89452cd12332257 | Increase waitForProcessList timeout
It can take more than 10 seconds when running under --race. | [
{
"change_type": "MODIFY",
"old_path": "runsc/container/container_test.go",
"new_path": "runsc/container/container_test.go",
"diff": "@@ -60,7 +60,7 @@ func waitForProcessList(cont *Container, want []*control.Process) error {\nreturn nil\n}\n// Gives plenty of time as tests can run slow under --race.\n- return testutil.Poll(cb, 10*time.Second)\n+ return testutil.Poll(cb, 30*time.Second)\n}\nfunc waitForProcessCount(cont *Container, want int) error {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Increase waitForProcessList timeout
It can take more than 10 seconds when running under --race.
PiperOrigin-RevId: 286296060 |
259,853 | 18.12.2019 18:22:50 | 28,800 | 57ce26c0b465dce332a59c9fabb05f737ff4241d | net/tcp: allow to call listen without bind
When listen(2) is called on an unbound socket, the socket is
automatically bound to a random free port with the local address
set to INADDR_ANY. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -1974,6 +1974,15 @@ func (e *endpoint) listen(backlog int) *tcpip.Error {\nreturn nil\n}\n+ if e.state == StateInitial {\n+ // The listen is called on an unbound socket, the socket is\n+ // automatically bound to a random free port with the local\n+ // address set to INADDR_ANY.\n+ if err := e.bindLocked(tcpip.FullAddress{}); err != nil {\n+ return err\n+ }\n+ }\n+\n// Endpoint must be bound before it can transition to listen mode.\nif e.state != StateBound {\ne.stats.ReadErrors.InvalidEndpointState.Increment()\n@@ -2033,6 +2042,10 @@ func (e *endpoint) Bind(addr tcpip.FullAddress) (err *tcpip.Error) {\ne.mu.Lock()\ndefer e.mu.Unlock()\n+ return e.bindLocked(addr)\n+}\n+\n+func (e *endpoint) bindLocked(addr tcpip.FullAddress) (err *tcpip.Error) {\n// Don't allow binding once endpoint is not in the initial state\n// anymore. This is because once the endpoint goes into a connected or\n// listen state, it is already bound.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_inet_loopback.cc",
"new_path": "test/syscalls/linux/socket_inet_loopback.cc",
"diff": "@@ -102,19 +102,17 @@ TEST(BadSocketPairArgs, ValidateErrForBadCallsToSocketPair) {\nSyscallFailsWithErrno(EAFNOSUPPORT));\n}\n-TEST_P(SocketInetLoopbackTest, TCP) {\n- auto const& param = GetParam();\n-\n- TestAddress const& listener = param.listener;\n- TestAddress const& connector = param.connector;\n-\n+void tcpSimpleConnectTest(TestAddress const& listener,\n+ TestAddress const& connector, bool unbound) {\n// Create the listening socket.\nconst FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(\nSocket(listener.family(), SOCK_STREAM, IPPROTO_TCP));\nsockaddr_storage listen_addr = listener.addr;\n+ if (!unbound) {\nASSERT_THAT(bind(listen_fd.get(), reinterpret_cast<sockaddr*>(&listen_addr),\nlistener.addr_len),\nSyscallSucceeds());\n+ }\nASSERT_THAT(listen(listen_fd.get(), SOMAXCONN), SyscallSucceeds());\n// Get the port bound by the listening socket.\n@@ -148,6 +146,23 @@ TEST_P(SocketInetLoopbackTest, TCP) {\nASSERT_THAT(shutdown(conn_fd.get(), SHUT_RDWR), SyscallSucceeds());\n}\n+TEST_P(SocketInetLoopbackTest, TCP) {\n+ auto const& param = GetParam();\n+ TestAddress const& listener = param.listener;\n+ TestAddress const& connector = param.connector;\n+\n+ tcpSimpleConnectTest(listener, connector, true);\n+}\n+\n+TEST_P(SocketInetLoopbackTest, TCPListenUnbound) {\n+ auto const& param = GetParam();\n+\n+ TestAddress const& listener = param.listener;\n+ TestAddress const& connector = param.connector;\n+\n+ tcpSimpleConnectTest(listener, connector, false);\n+}\n+\nTEST_P(SocketInetLoopbackTest, TCPListenClose) {\nauto const& param = GetParam();\n"
}
] | Go | Apache License 2.0 | google/gvisor | net/tcp: allow to call listen without bind
When listen(2) is called on an unbound socket, the socket is
automatically bound to a random free port with the local address
set to INADDR_ANY.
PiperOrigin-RevId: 286305906 |
259,847 | 19.12.2019 15:24:15 | 28,800 | 80c8aecd51c8cda02fe36ed663d09e5b71a5b682 | Install python2 in the Dockerfile.
Without it, we get a build failure (inside the container) when trying to build
//runsc. | [
{
"change_type": "MODIFY",
"old_path": "Dockerfile",
"new_path": "Dockerfile",
"diff": "FROM ubuntu:bionic\n-RUN apt-get update && apt-get install -y curl gnupg2 git python3 python3-distutils python3-pip\n+RUN apt-get update && apt-get install -y curl gnupg2 git python python3 python3-distutils python3-pip\nRUN echo \"deb [arch=amd64] http://storage.googleapis.com/bazel-apt stable jdk1.8\" | tee /etc/apt/sources.list.d/bazel.list && \\\ncurl https://bazel.build/bazel-release.pub.gpg | apt-key add -\nRUN apt-get update && apt-get install -y bazel && apt-get clean\n"
}
] | Go | Apache License 2.0 | google/gvisor | Install python2 in the Dockerfile.
Without it, we get a build failure (inside the container) when trying to build
//runsc.
PiperOrigin-RevId: 286474518 |
259,860 | 19.12.2019 16:05:35 | 28,800 | 7419e0e5d74621b2be60e9b18e4e2d7bb2a65cc3 | Parameterize mmap tests.
This test suite has existed for quite a while and has become kind of messy.
Various tests can be joined together by parameterizing. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/mmap.cc",
"new_path": "test/syscalls/linux/mmap.cc",
"diff": "@@ -814,22 +814,26 @@ class MMapFileTest : public MMapTest {\n}\n};\n+class MMapFileParamTest\n+ : public MMapFileTest,\n+ public ::testing::WithParamInterface<std::tuple<int, int>> {\n+ protected:\n+ int prot() const { return std::get<0>(GetParam()); }\n+\n+ int flags() const { return std::get<1>(GetParam()); }\n+};\n+\n// MAP_POPULATE allowed.\n// There isn't a good way to verify it actually did anything.\n-//\n-// FIXME(b/37222275): Parameterize.\n-TEST_F(MMapFileTest, MapPopulate) {\n- ASSERT_THAT(\n- Map(0, kPageSize, PROT_READ, MAP_PRIVATE | MAP_POPULATE, fd_.get(), 0),\n+TEST_P(MMapFileParamTest, MapPopulate) {\n+ ASSERT_THAT(Map(0, kPageSize, prot(), flags() | MAP_POPULATE, fd_.get(), 0),\nSyscallSucceeds());\n}\n// MAP_POPULATE on a short file.\n-//\n-// FIXME(b/37222275): Parameterize.\n-TEST_F(MMapFileTest, MapPopulateShort) {\n- ASSERT_THAT(Map(0, 2 * kPageSize, PROT_READ, MAP_PRIVATE | MAP_POPULATE,\n- fd_.get(), 0),\n+TEST_P(MMapFileParamTest, MapPopulateShort) {\n+ ASSERT_THAT(\n+ Map(0, 2 * kPageSize, prot(), flags() | MAP_POPULATE, fd_.get(), 0),\nSyscallSucceeds());\n}\n@@ -901,16 +905,6 @@ TEST_F(MMapFileTest, WritePrivateOnReadOnlyFd) {\nreinterpret_cast<volatile char*>(addr));\n}\n-// MAP_PRIVATE PROT_READ is not allowed on write-only FDs.\n-TEST_F(MMapFileTest, ReadPrivateOnWriteOnlyFd) {\n- const FileDescriptor fd =\n- ASSERT_NO_ERRNO_AND_VALUE(Open(filename_, O_WRONLY));\n-\n- uintptr_t addr;\n- EXPECT_THAT(addr = Map(0, kPageSize, PROT_READ, MAP_PRIVATE, fd.get(), 0),\n- SyscallFailsWithErrno(EACCES));\n-}\n-\n// MAP_SHARED PROT_WRITE not allowed on read-only FDs.\nTEST_F(MMapFileTest, WriteSharedOnReadOnlyFd) {\nconst FileDescriptor fd =\n@@ -922,28 +916,13 @@ TEST_F(MMapFileTest, WriteSharedOnReadOnlyFd) {\nSyscallFailsWithErrno(EACCES));\n}\n-// MAP_SHARED PROT_READ not allowed on write-only FDs.\n-//\n-// FIXME(b/37222275): Parameterize.\n-TEST_F(MMapFileTest, ReadSharedOnWriteOnlyFd) {\n- const FileDescriptor fd =\n- ASSERT_NO_ERRNO_AND_VALUE(Open(filename_, O_WRONLY));\n-\n- uintptr_t addr;\n- EXPECT_THAT(addr = Map(0, kPageSize, PROT_READ, MAP_SHARED, fd.get(), 0),\n- SyscallFailsWithErrno(EACCES));\n-}\n-\n-// MAP_SHARED PROT_WRITE not allowed on write-only FDs.\n-// The FD must always be readable.\n-//\n-// FIXME(b/37222275): Parameterize.\n-TEST_F(MMapFileTest, WriteSharedOnWriteOnlyFd) {\n+// The FD must be readable.\n+TEST_P(MMapFileParamTest, WriteOnlyFd) {\nconst FileDescriptor fd =\nASSERT_NO_ERRNO_AND_VALUE(Open(filename_, O_WRONLY));\nuintptr_t addr;\n- EXPECT_THAT(addr = Map(0, kPageSize, PROT_WRITE, MAP_SHARED, fd.get(), 0),\n+ EXPECT_THAT(addr = Map(0, kPageSize, prot(), flags(), fd.get(), 0),\nSyscallFailsWithErrno(EACCES));\n}\n@@ -1182,7 +1161,7 @@ TEST_F(MMapFileTest, ReadSharedTruncateDownThenUp) {\nASSERT_THAT(addr = Map(0, kPageSize, PROT_READ, MAP_SHARED, fd_.get(), 0),\nSyscallSucceeds());\n- // Check that the memory contains he file data.\n+ // Check that the memory contains the file data.\nEXPECT_EQ(0, memcmp(reinterpret_cast<void*>(addr), buf.c_str(), kPageSize));\n// Truncate down, then up.\n@@ -1371,125 +1350,68 @@ TEST_F(MMapFileTest, WritePrivate) {\nEqualsMemory(std::string(len, '\\0')));\n}\n-// SIGBUS raised when writing past end of file to a private mapping.\n-//\n-// FIXME(b/37222275): Parameterize.\n-TEST_F(MMapFileTest, SigBusDeathWritePrivate) {\n+// SIGBUS raised when reading or writing past end of a mapped file.\n+TEST_P(MMapFileParamTest, SigBusDeath) {\nSetupGvisorDeathTest();\nuintptr_t addr;\n- ASSERT_THAT(addr = Map(0, 2 * kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE,\n- fd_.get(), 0),\n+ ASSERT_THAT(addr = Map(0, 2 * kPageSize, prot(), flags(), fd_.get(), 0),\nSyscallSucceeds());\n- // MMapFileTest makes a file kPageSize/2 long. The entire first page will be\n- // accessible. Write just beyond that.\n+ auto* start = reinterpret_cast<volatile char*>(addr + kPageSize);\n+\n+ // MMapFileTest makes a file kPageSize/2 long. The entire first page should be\n+ // accessible, but anything beyond it should not.\n+ if (prot() & PROT_WRITE) {\n+ // Write beyond first page.\nsize_t len = strlen(kFileContents);\n- EXPECT_EXIT(std::copy(kFileContents, kFileContents + len,\n- reinterpret_cast<volatile char*>(addr + kPageSize)),\n+ EXPECT_EXIT(std::copy(kFileContents, kFileContents + len, start),\n::testing::KilledBySignal(SIGBUS), \"\");\n-}\n-\n-// SIGBUS raised when reading past end of file on a shared mapping.\n-//\n-// FIXME(b/37222275): Parameterize.\n-TEST_F(MMapFileTest, SigBusDeathReadShared) {\n- SetupGvisorDeathTest();\n-\n- uintptr_t addr;\n- ASSERT_THAT(addr = Map(0, 2 * kPageSize, PROT_READ, MAP_SHARED, fd_.get(), 0),\n- SyscallSucceeds());\n-\n- // MMapFileTest makes a file kPageSize/2 long. The entire first page will be\n- // accessible. Read just beyond that.\n+ } else {\n+ // Read beyond first page.\nstd::vector<char> in(kPageSize);\n- EXPECT_EXIT(\n- std::copy(reinterpret_cast<volatile char*>(addr + kPageSize),\n- reinterpret_cast<volatile char*>(addr + kPageSize) + kPageSize,\n- in.data()),\n+ EXPECT_EXIT(std::copy(start, start + kPageSize, in.data()),\n::testing::KilledBySignal(SIGBUS), \"\");\n}\n-\n-// SIGBUS raised when reading past end of file on a shared mapping.\n-//\n-// FIXME(b/37222275): Parameterize.\n-TEST_F(MMapFileTest, SigBusDeathWriteShared) {\n- SetupGvisorDeathTest();\n-\n- uintptr_t addr;\n- ASSERT_THAT(addr = Map(0, 2 * kPageSize, PROT_READ | PROT_WRITE, MAP_SHARED,\n- fd_.get(), 0),\n- SyscallSucceeds());\n-\n- // MMapFileTest makes a file kPageSize/2 long. The entire first page will be\n- // accessible. Write just beyond that.\n- size_t len = strlen(kFileContents);\n- EXPECT_EXIT(std::copy(kFileContents, kFileContents + len,\n- reinterpret_cast<volatile char*>(addr + kPageSize)),\n- ::testing::KilledBySignal(SIGBUS), \"\");\n}\n-// Tests that SIGBUS is not raised when writing to a file-mapped page before\n-// EOF, even if part of the mapping extends beyond EOF.\n-TEST_F(MMapFileTest, NoSigBusOnPagesBeforeEOF) {\n+// Tests that SIGBUS is not raised when reading or writing to a file-mapped\n+// page before EOF, even if part of the mapping extends beyond EOF.\n+//\n+// See b/27877699.\n+TEST_P(MMapFileParamTest, NoSigBusOnPagesBeforeEOF) {\nuintptr_t addr;\n- ASSERT_THAT(addr = Map(0, 2 * kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE,\n- fd_.get(), 0),\n+ ASSERT_THAT(addr = Map(0, 2 * kPageSize, prot(), flags(), fd_.get(), 0),\nSyscallSucceeds());\n// The test passes if this survives.\n+ auto* start = reinterpret_cast<volatile char*>(addr + (kPageSize / 2) + 1);\nsize_t len = strlen(kFileContents);\n- std::copy(kFileContents, kFileContents + len,\n- reinterpret_cast<volatile char*>(addr));\n+ if (prot() & PROT_WRITE) {\n+ std::copy(kFileContents, kFileContents + len, start);\n+ } else {\n+ std::vector<char> in(len);\n+ std::copy(start, start + len, in.data());\n}\n-\n-// Tests that SIGBUS is not raised when writing to a file-mapped page containing\n-// EOF, *after* the EOF for a private mapping.\n-TEST_F(MMapFileTest, NoSigBusOnPageContainingEOFWritePrivate) {\n- uintptr_t addr;\n- ASSERT_THAT(addr = Map(0, 2 * kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE,\n- fd_.get(), 0),\n- SyscallSucceeds());\n-\n- // The test passes if this survives. (Technically addr+kPageSize/2 is already\n- // beyond EOF, but +1 to check for fencepost errors.)\n- size_t len = strlen(kFileContents);\n- std::copy(kFileContents, kFileContents + len,\n- reinterpret_cast<volatile char*>(addr + (kPageSize / 2) + 1));\n}\n-// Tests that SIGBUS is not raised when reading from a file-mapped page\n-// containing EOF, *after* the EOF for a shared mapping.\n-//\n-// FIXME(b/37222275): Parameterize.\n-TEST_F(MMapFileTest, NoSigBusOnPageContainingEOFReadShared) {\n+// Tests that SIGBUS is not raised when reading or writing from a file-mapped\n+// page containing EOF, *after* the EOF.\n+TEST_P(MMapFileParamTest, NoSigBusOnPageContainingEOF) {\nuintptr_t addr;\n- ASSERT_THAT(addr = Map(0, 2 * kPageSize, PROT_READ, MAP_SHARED, fd_.get(), 0),\n+ ASSERT_THAT(addr = Map(0, 2 * kPageSize, prot(), flags(), fd_.get(), 0),\nSyscallSucceeds());\n// The test passes if this survives. (Technically addr+kPageSize/2 is already\n// beyond EOF, but +1 to check for fencepost errors.)\nauto* start = reinterpret_cast<volatile char*>(addr + (kPageSize / 2) + 1);\nsize_t len = strlen(kFileContents);\n+ if (prot() & PROT_WRITE) {\n+ std::copy(kFileContents, kFileContents + len, start);\n+ } else {\nstd::vector<char> in(len);\nstd::copy(start, start + len, in.data());\n}\n-\n-// Tests that SIGBUS is not raised when writing to a file-mapped page containing\n-// EOF, *after* the EOF for a shared mapping.\n-//\n-// FIXME(b/37222275): Parameterize.\n-TEST_F(MMapFileTest, NoSigBusOnPageContainingEOFWriteShared) {\n- uintptr_t addr;\n- ASSERT_THAT(addr = Map(0, 2 * kPageSize, PROT_READ | PROT_WRITE, MAP_SHARED,\n- fd_.get(), 0),\n- SyscallSucceeds());\n-\n- // The test passes if this survives. (Technically addr+kPageSize/2 is already\n- // beyond EOF, but +1 to check for fencepost errors.)\n- size_t len = strlen(kFileContents);\n- std::copy(kFileContents, kFileContents + len,\n- reinterpret_cast<volatile char*>(addr + (kPageSize / 2) + 1));\n}\n// Tests that reading from writable shared file-mapped pages succeeds.\n@@ -1733,6 +1655,15 @@ TEST(MMapNoFixtureTest, Map32Bit) {\n#endif // defined(__x86_64__)\n+INSTANTIATE_TEST_SUITE_P(\n+ ReadWriteSharedPrivate, MMapFileParamTest,\n+ ::testing::Combine(::testing::ValuesIn({\n+ PROT_READ,\n+ PROT_WRITE,\n+ PROT_READ | PROT_WRITE,\n+ }),\n+ ::testing::ValuesIn({MAP_SHARED, MAP_PRIVATE})));\n+\n} // namespace\n} // namespace testing\n"
}
] | Go | Apache License 2.0 | google/gvisor | Parameterize mmap tests.
This test suite has existed for quite a while and has become kind of messy.
Various tests can be joined together by parameterizing.
PiperOrigin-RevId: 286482240 |
259,860 | 20.12.2019 08:43:15 | 28,800 | 822d847ccaa1e6016b818bee289b5e33335f9fee | Check for valid nfds before copying in an fd set.
Otherwise, CopyInFDSet will try to allocate a negative-length slice. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/strace/select.go",
"new_path": "pkg/sentry/strace/select.go",
"diff": "@@ -36,6 +36,9 @@ func fdsFromSet(t *kernel.Task, set []byte) []int {\n}\nfunc fdSet(t *kernel.Task, nfds int, addr usermem.Addr) string {\n+ if nfds < 0 {\n+ return fmt.Sprintf(\"%#x (negative nfds)\", addr)\n+ }\nif addr == 0 {\nreturn \"null\"\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Check for valid nfds before copying in an fd set.
Otherwise, CopyInFDSet will try to allocate a negative-length slice.
PiperOrigin-RevId: 286584907 |
259,885 | 20.12.2019 11:52:24 | 28,800 | 3eb489ed6c67b069bc135ab92cb031ce80b40d8f | Move VFS2 file description status flags to vfs.FileDescription. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/ext/file_description.go",
"new_path": "pkg/sentry/fsimpl/ext/file_description.go",
"diff": "@@ -26,13 +26,6 @@ import (\ntype fileDescription struct {\nvfsfd vfs.FileDescription\nvfs.FileDescriptionDefaultImpl\n-\n- // flags is the same as vfs.OpenOptions.Flags which are passed to\n- // vfs.FilesystemImpl.OpenAt.\n- // TODO(b/134676337): syscalls like read(2), write(2), fchmod(2), fchown(2),\n- // fgetxattr(2), ioctl(2), mmap(2) should fail with EBADF if O_PATH is set.\n- // Only close(2), fstat(2), fstatfs(2) should work.\n- flags uint32\n}\nfunc (fd *fileDescription) filesystem() *filesystem {\n@@ -43,18 +36,6 @@ func (fd *fileDescription) inode() *inode {\nreturn fd.vfsfd.Dentry().Impl().(*dentry).inode\n}\n-// StatusFlags implements vfs.FileDescriptionImpl.StatusFlags.\n-func (fd *fileDescription) StatusFlags(ctx context.Context) (uint32, error) {\n- return fd.flags, nil\n-}\n-\n-// SetStatusFlags implements vfs.FileDescriptionImpl.SetStatusFlags.\n-func (fd *fileDescription) SetStatusFlags(ctx context.Context, flags uint32) error {\n- // None of the flags settable by fcntl(F_SETFL) are supported, so this is a\n- // no-op.\n- return nil\n-}\n-\n// Stat implements vfs.FileDescriptionImpl.Stat.\nfunc (fd *fileDescription) Stat(ctx context.Context, opts vfs.StatOptions) (linux.Statx, error) {\nvar stat linux.Statx\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/ext/inode.go",
"new_path": "pkg/sentry/fsimpl/ext/inode.go",
"diff": "@@ -157,10 +157,9 @@ func (in *inode) open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, flags uint32) (*v\nswitch in.impl.(type) {\ncase *regularFile:\nvar fd regularFileFD\n- fd.flags = flags\nmnt.IncRef()\nvfsd.IncRef()\n- fd.vfsfd.Init(&fd, mnt, vfsd)\n+ fd.vfsfd.Init(&fd, flags, mnt, vfsd, &vfs.FileDescriptionOptions{})\nreturn &fd.vfsfd, nil\ncase *directory:\n// Can't open directories writably. This check is not necessary for a read\n@@ -169,10 +168,9 @@ func (in *inode) open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, flags uint32) (*v\nreturn nil, syserror.EISDIR\n}\nvar fd directoryFD\n- fd.flags = flags\nmnt.IncRef()\nvfsd.IncRef()\n- fd.vfsfd.Init(&fd, mnt, vfsd)\n+ fd.vfsfd.Init(&fd, flags, mnt, vfsd, &vfs.FileDescriptionOptions{})\nreturn &fd.vfsfd, nil\ncase *symlink:\nif flags&linux.O_PATH == 0 {\n@@ -180,10 +178,9 @@ func (in *inode) open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, flags uint32) (*v\nreturn nil, syserror.ELOOP\n}\nvar fd symlinkFD\n- fd.flags = flags\nmnt.IncRef()\nvfsd.IncRef()\n- fd.vfsfd.Init(&fd, mnt, vfsd)\n+ fd.vfsfd.Init(&fd, flags, mnt, vfsd, &vfs.FileDescriptionOptions{})\nreturn &fd.vfsfd, nil\ndefault:\npanic(fmt.Sprintf(\"unknown inode type: %T\", in.impl))\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/dynamic_bytes_file.go",
"new_path": "pkg/sentry/fsimpl/kernfs/dynamic_bytes_file.go",
"diff": "@@ -65,17 +65,15 @@ type DynamicBytesFD struct {\nvfsfd vfs.FileDescription\ninode Inode\n- flags uint32\n}\n// Init initializes a DynamicBytesFD.\nfunc (fd *DynamicBytesFD) Init(m *vfs.Mount, d *vfs.Dentry, data vfs.DynamicBytesSource, flags uint32) {\nm.IncRef() // DecRef in vfs.FileDescription.vd.DecRef on final ref.\nd.IncRef() // DecRef in vfs.FileDescription.vd.DecRef on final ref.\n- fd.flags = flags\nfd.inode = d.Impl().(*Dentry).inode\nfd.SetDataSource(data)\n- fd.vfsfd.Init(fd, m, d)\n+ fd.vfsfd.Init(fd, flags, m, d, &vfs.FileDescriptionOptions{})\n}\n// Seek implements vfs.FileDescriptionImpl.Seek.\n@@ -117,15 +115,3 @@ func (fd *DynamicBytesFD) SetStat(context.Context, vfs.SetStatOptions) error {\n// DynamicBytesFiles are immutable.\nreturn syserror.EPERM\n}\n-\n-// StatusFlags implements vfs.FileDescriptionImpl.StatusFlags.\n-func (fd *DynamicBytesFD) StatusFlags(ctx context.Context) (uint32, error) {\n- return fd.flags, nil\n-}\n-\n-// SetStatusFlags implements vfs.FileDescriptionImpl.SetStatusFlags.\n-func (fd *DynamicBytesFD) SetStatusFlags(ctx context.Context, flags uint32) error {\n- // None of the flags settable by fcntl(F_SETFL) are supported, so this is a\n- // no-op.\n- return nil\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/fd_impl_util.go",
"new_path": "pkg/sentry/fsimpl/kernfs/fd_impl_util.go",
"diff": "@@ -39,7 +39,6 @@ type GenericDirectoryFD struct {\nvfsfd vfs.FileDescription\nchildren *OrderedChildren\n- flags uint32\noff int64\n}\n@@ -48,8 +47,7 @@ func (fd *GenericDirectoryFD) Init(m *vfs.Mount, d *vfs.Dentry, children *Ordere\nm.IncRef() // DecRef in vfs.FileDescription.vd.DecRef on final ref.\nd.IncRef() // DecRef in vfs.FileDescription.vd.DecRef on final ref.\nfd.children = children\n- fd.flags = flags\n- fd.vfsfd.Init(fd, m, d)\n+ fd.vfsfd.Init(fd, flags, m, d, &vfs.FileDescriptionOptions{})\n}\n// VFSFileDescription returns a pointer to the vfs.FileDescription representing\n@@ -180,18 +178,6 @@ func (fd *GenericDirectoryFD) Seek(ctx context.Context, offset int64, whence int\nreturn offset, nil\n}\n-// StatusFlags implements vfs.FileDescriptionImpl.StatusFlags.\n-func (fd *GenericDirectoryFD) StatusFlags(ctx context.Context) (uint32, error) {\n- return fd.flags, nil\n-}\n-\n-// SetStatusFlags implements vfs.FileDescriptionImpl.SetStatusFlags.\n-func (fd *GenericDirectoryFD) SetStatusFlags(ctx context.Context, flags uint32) error {\n- // None of the flags settable by fcntl(F_SETFL) are supported, so this is a\n- // no-op.\n- return nil\n-}\n-\n// Stat implements vfs.FileDescriptionImpl.Stat.\nfunc (fd *GenericDirectoryFD) Stat(ctx context.Context, opts vfs.StatOptions) (linux.Statx, error) {\nfs := fd.filesystem()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/memfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/memfs/filesystem.go",
"diff": "@@ -282,9 +282,8 @@ func (fs *filesystem) MknodAt(ctx context.Context, rp *vfs.ResolvingPath, opts v\nfunc (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- // FileDescriptionImpl.StatusFlags(). O_NONBLOCK is supported only by\n- // pipes.\n+ // appropriate bits in rp), but are visible in FD status flags. O_NONBLOCK\n+ // is supported only by pipes.\nopts.Flags &= linux.O_ACCMODE | linux.O_CREAT | linux.O_EXCL | linux.O_TRUNC | linux.O_DIRECTORY | linux.O_NOFOLLOW | linux.O_NONBLOCK\nif opts.Flags&linux.O_CREAT == 0 {\n@@ -384,7 +383,6 @@ func (i *inode) open(ctx context.Context, rp *vfs.ResolvingPath, vfsd *vfs.Dentr\nswitch impl := i.impl.(type) {\ncase *regularFile:\nvar fd regularFileFD\n- fd.flags = flags\nfd.readable = vfs.MayReadFileWithOpenFlags(flags)\nfd.writable = vfs.MayWriteFileWithOpenFlags(flags)\nif fd.writable {\n@@ -395,7 +393,7 @@ func (i *inode) open(ctx context.Context, rp *vfs.ResolvingPath, vfsd *vfs.Dentr\n}\nmnt.IncRef()\nvfsd.IncRef()\n- fd.vfsfd.Init(&fd, mnt, vfsd)\n+ fd.vfsfd.Init(&fd, flags, mnt, vfsd, &vfs.FileDescriptionOptions{})\nif flags&linux.O_TRUNC != 0 {\nimpl.mu.Lock()\nimpl.data = impl.data[:0]\n@@ -411,8 +409,7 @@ func (i *inode) open(ctx context.Context, rp *vfs.ResolvingPath, vfsd *vfs.Dentr\nvar fd directoryFD\nmnt.IncRef()\nvfsd.IncRef()\n- fd.vfsfd.Init(&fd, mnt, vfsd)\n- fd.flags = flags\n+ fd.vfsfd.Init(&fd, flags, mnt, vfsd, &vfs.FileDescriptionOptions{})\nreturn &fd.vfsfd, nil\ncase *symlink:\n// Can't open symlinks without O_PATH (which is unimplemented).\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/memfs/memfs.go",
"new_path": "pkg/sentry/fsimpl/memfs/memfs.go",
"diff": "@@ -261,8 +261,6 @@ func (i *inode) direntType() uint8 {\ntype fileDescription struct {\nvfsfd vfs.FileDescription\nvfs.FileDescriptionDefaultImpl\n-\n- flags uint32 // status flags; immutable\n}\nfunc (fd *fileDescription) filesystem() *filesystem {\n@@ -273,18 +271,6 @@ func (fd *fileDescription) inode() *inode {\nreturn fd.vfsfd.Dentry().Impl().(*dentry).inode\n}\n-// StatusFlags implements vfs.FileDescriptionImpl.StatusFlags.\n-func (fd *fileDescription) StatusFlags(ctx context.Context) (uint32, error) {\n- return fd.flags, nil\n-}\n-\n-// SetStatusFlags implements vfs.FileDescriptionImpl.SetStatusFlags.\n-func (fd *fileDescription) SetStatusFlags(ctx context.Context, flags uint32) error {\n- // None of the flags settable by fcntl(F_SETFL) are supported, so this is a\n- // no-op.\n- return nil\n-}\n-\n// Stat implements vfs.FileDescriptionImpl.Stat.\nfunc (fd *fileDescription) Stat(ctx context.Context, opts vfs.StatOptions) (linux.Statx, error) {\nvar stat linux.Statx\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/memfs/named_pipe.go",
"new_path": "pkg/sentry/fsimpl/memfs/named_pipe.go",
"diff": "@@ -57,6 +57,6 @@ func newNamedPipeFD(ctx context.Context, np *namedPipe, rp *vfs.ResolvingPath, v\nmnt := rp.Mount()\nmnt.IncRef()\nvfsd.IncRef()\n- fd.vfsfd.Init(&fd, mnt, vfsd)\n+ fd.vfsfd.Init(&fd, flags, mnt, vfsd, &vfs.FileDescriptionOptions{})\nreturn &fd.vfsfd, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/file_description.go",
"new_path": "pkg/sentry/vfs/file_description.go",
"diff": "@@ -20,6 +20,7 @@ import (\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/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/memmap\"\n\"gvisor.dev/gvisor/pkg/sentry/usermem\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n@@ -39,49 +40,43 @@ type FileDescription struct {\n// operations.\nrefs int64\n+ // statusFlags contains status flags, \"initialized by open(2) and possibly\n+ // modified by fcntl()\" - fcntl(2). statusFlags is accessed using atomic\n+ // memory operations.\n+ statusFlags uint32\n+\n// vd is the filesystem location at which this FileDescription was opened.\n// A reference is held on vd. vd is immutable.\nvd VirtualDentry\n+ opts FileDescriptionOptions\n+\n// impl is the FileDescriptionImpl associated with this Filesystem. impl is\n// immutable. This should be the last field in FileDescription.\nimpl FileDescriptionImpl\n}\n+// FileDescriptionOptions contains options to FileDescription.Init().\n+type FileDescriptionOptions struct {\n+ // If AllowDirectIO is true, allow O_DIRECT to be set on the file. This is\n+ // usually only the case if O_DIRECT would actually have an effect.\n+ AllowDirectIO bool\n+}\n+\n// Init must be called before first use of fd. It takes ownership of references\n-// on mnt and d held by the caller.\n-func (fd *FileDescription) Init(impl FileDescriptionImpl, mnt *Mount, d *Dentry) {\n+// on mnt and d held by the caller. statusFlags is the initial file description\n+// status flags, which is usually the full set of flags passed to open(2).\n+func (fd *FileDescription) Init(impl FileDescriptionImpl, statusFlags uint32, mnt *Mount, d *Dentry, opts *FileDescriptionOptions) {\nfd.refs = 1\n+ fd.statusFlags = statusFlags | linux.O_LARGEFILE\nfd.vd = VirtualDentry{\nmount: mnt,\ndentry: d,\n}\n+ fd.opts = *opts\nfd.impl = impl\n}\n-// Impl returns the FileDescriptionImpl associated with fd.\n-func (fd *FileDescription) Impl() FileDescriptionImpl {\n- return fd.impl\n-}\n-\n-// Mount returns the mount on which fd was opened. It does not take a reference\n-// on the returned Mount.\n-func (fd *FileDescription) Mount() *Mount {\n- return fd.vd.mount\n-}\n-\n-// Dentry returns the dentry at which fd was opened. It does not take a\n-// reference on the returned Dentry.\n-func (fd *FileDescription) Dentry() *Dentry {\n- return fd.vd.dentry\n-}\n-\n-// VirtualDentry returns the location at which fd was opened. It does not take\n-// a reference on the returned VirtualDentry.\n-func (fd *FileDescription) VirtualDentry() VirtualDentry {\n- return fd.vd\n-}\n-\n// IncRef increments fd's reference count.\nfunc (fd *FileDescription) IncRef() {\natomic.AddInt64(&fd.refs, 1)\n@@ -113,6 +108,82 @@ func (fd *FileDescription) DecRef() {\n}\n}\n+// Mount returns the mount on which fd was opened. It does not take a reference\n+// on the returned Mount.\n+func (fd *FileDescription) Mount() *Mount {\n+ return fd.vd.mount\n+}\n+\n+// Dentry returns the dentry at which fd was opened. It does not take a\n+// reference on the returned Dentry.\n+func (fd *FileDescription) Dentry() *Dentry {\n+ return fd.vd.dentry\n+}\n+\n+// VirtualDentry returns the location at which fd was opened. It does not take\n+// a reference on the returned VirtualDentry.\n+func (fd *FileDescription) VirtualDentry() VirtualDentry {\n+ return fd.vd\n+}\n+\n+// StatusFlags returns file description status flags, as for fcntl(F_GETFL).\n+func (fd *FileDescription) StatusFlags() uint32 {\n+ return atomic.LoadUint32(&fd.statusFlags)\n+}\n+\n+// SetStatusFlags sets file description status flags, as for fcntl(F_SETFL).\n+func (fd *FileDescription) SetStatusFlags(ctx context.Context, creds *auth.Credentials, flags uint32) error {\n+ // Compare Linux's fs/fcntl.c:setfl().\n+ oldFlags := fd.StatusFlags()\n+ // Linux documents this check as \"O_APPEND cannot be cleared if the file is\n+ // marked as append-only and the file is open for write\", which would make\n+ // sense. However, the check as actually implemented seems to be \"O_APPEND\n+ // cannot be changed if the file is marked as append-only\".\n+ if (flags^oldFlags)&linux.O_APPEND != 0 {\n+ stat, err := fd.impl.Stat(ctx, StatOptions{\n+ // There is no mask bit for stx_attributes.\n+ Mask: 0,\n+ // Linux just reads inode::i_flags directly.\n+ Sync: linux.AT_STATX_DONT_SYNC,\n+ })\n+ if err != nil {\n+ return err\n+ }\n+ if (stat.AttributesMask&linux.STATX_ATTR_APPEND != 0) && (stat.Attributes&linux.STATX_ATTR_APPEND != 0) {\n+ return syserror.EPERM\n+ }\n+ }\n+ if (flags&linux.O_NOATIME != 0) && (oldFlags&linux.O_NOATIME == 0) {\n+ stat, err := fd.impl.Stat(ctx, StatOptions{\n+ Mask: linux.STATX_UID,\n+ // Linux's inode_owner_or_capable() just reads inode::i_uid\n+ // directly.\n+ Sync: linux.AT_STATX_DONT_SYNC,\n+ })\n+ if err != nil {\n+ return err\n+ }\n+ if stat.Mask&linux.STATX_UID == 0 {\n+ return syserror.EPERM\n+ }\n+ if !CanActAsOwner(creds, auth.KUID(stat.UID)) {\n+ return syserror.EPERM\n+ }\n+ }\n+ if flags&linux.O_DIRECT != 0 && !fd.opts.AllowDirectIO {\n+ return syserror.EINVAL\n+ }\n+ // TODO(jamieliu): FileDescriptionImpl.SetOAsync()?\n+ const settableFlags = linux.O_APPEND | linux.O_ASYNC | linux.O_DIRECT | linux.O_NOATIME | linux.O_NONBLOCK\n+ atomic.StoreUint32(&fd.statusFlags, (oldFlags&^settableFlags)|(flags&settableFlags))\n+ return nil\n+}\n+\n+// Impl returns the FileDescriptionImpl associated with fd.\n+func (fd *FileDescription) Impl() FileDescriptionImpl {\n+ return fd.impl\n+}\n+\n// FileDescriptionImpl contains implementation details for an FileDescription.\n// Implementations of FileDescriptionImpl should contain their associated\n// FileDescription by value as their first field.\n@@ -132,14 +203,6 @@ type FileDescriptionImpl interface {\n// prevent the file descriptor from being closed.\nOnClose(ctx context.Context) error\n- // StatusFlags returns file description status flags, as for\n- // fcntl(F_GETFL).\n- StatusFlags(ctx context.Context) (uint32, error)\n-\n- // SetStatusFlags sets file description status flags, as for\n- // fcntl(F_SETFL).\n- SetStatusFlags(ctx context.Context, flags uint32) error\n-\n// Stat returns metadata for the file represented by the FileDescription.\nStat(ctx context.Context, opts StatOptions) (linux.Statx, error)\n@@ -264,18 +327,6 @@ func (fd *FileDescription) OnClose(ctx context.Context) error {\nreturn fd.impl.OnClose(ctx)\n}\n-// StatusFlags returns file description status flags, as for fcntl(F_GETFL).\n-func (fd *FileDescription) StatusFlags(ctx context.Context) (uint32, error) {\n- flags, err := fd.impl.StatusFlags(ctx)\n- flags |= linux.O_LARGEFILE\n- return flags, err\n-}\n-\n-// SetStatusFlags sets file description status flags, as for fcntl(F_SETFL).\n-func (fd *FileDescription) SetStatusFlags(ctx context.Context, flags uint32) error {\n- return fd.impl.SetStatusFlags(ctx, flags)\n-}\n-\n// Stat returns metadata for the file represented by fd.\nfunc (fd *FileDescription) Stat(ctx context.Context, opts StatOptions) (linux.Statx, error) {\nreturn fd.impl.Stat(ctx, opts)\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": "@@ -48,7 +48,7 @@ type genCountFD struct {\nfunc newGenCountFD(mnt *Mount, vfsd *Dentry) *FileDescription {\nvar fd genCountFD\n- fd.vfsfd.Init(&fd, mnt, vfsd)\n+ fd.vfsfd.Init(&fd, 0 /* statusFlags */, mnt, vfsd, &FileDescriptionOptions{})\nfd.DynamicBytesFileDescriptionImpl.SetDataSource(&fd)\nreturn &fd.vfsfd\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Move VFS2 file description status flags to vfs.FileDescription.
PiperOrigin-RevId: 286616668 |
259,891 | 20.12.2019 14:17:57 | 28,800 | 08c39e25870821f84f6da1915ceefe13b3196e02 | Change TODO to track correct bug. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6.go",
"diff": "@@ -162,7 +162,7 @@ func (e *endpoint) WritePackets(r *stack.Route, gso *stack.GSO, pkts []tcpip.Pac\n// WriteHeaderIncludedPacker implements stack.NetworkEndpoint. It is not yet\n// supported by IPv6.\nfunc (*endpoint) WriteHeaderIncludedPacket(r *stack.Route, loop stack.PacketLooping, pkt tcpip.PacketBuffer) *tcpip.Error {\n- // TODO(b/119580726): Support IPv6 header-included packets.\n+ // TODO(b/146666412): Support IPv6 header-included packets.\nreturn tcpip.ErrNotSupported\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Change TODO to track correct bug.
PiperOrigin-RevId: 286639163 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.