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,858 | 11.02.2020 16:01:42 | 28,800 | e5d9a4010bdbea10320348b022ee5b761c1eba07 | Add ability to execute go.mod in gopath context. | [
{
"change_type": "MODIFY",
"old_path": "CONTRIBUTING.md",
"new_path": "CONTRIBUTING.md",
"diff": "@@ -32,6 +32,9 @@ will need to be added to the appropriate `BUILD` files, and the `:gopath` target\nwill need to be re-run to generate appropriate symlinks in the `GOPATH`\ndirectory tree.\n+Dependencies can be added by using `go mod get`. In order to keep the\n+`WORKSPACE` file in sync, run `tools/go_mod.sh` in place of `go mod`.\n+\n### Coding Guidelines\nAll Go code should conform to the [Go style guidelines][gostyle]. C++ code\n"
},
{
"change_type": "MODIFY",
"old_path": "WORKSPACE",
"new_path": "WORKSPACE",
"diff": "@@ -20,7 +20,7 @@ http_archive(\n],\n)\n-load(\"@io_bazel_rules_go//go:deps.bzl\", \"go_rules_dependencies\", \"go_register_toolchains\")\n+load(\"@io_bazel_rules_go//go:deps.bzl\", \"go_register_toolchains\", \"go_rules_dependencies\")\ngo_rules_dependencies()\n@@ -43,8 +43,8 @@ gazelle_dependencies()\ngo_repository(\nname = \"org_golang_x_sys\",\nimportpath = \"golang.org/x/sys\",\n- sum = \"h1:72l8qCJ1nGxMGH26QVBVIxKd/D34cfGt0OvrPtpemyY=\",\n- version = \"v0.0.0-20191220220014-0732a990476f\",\n+ sum = \"h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU=\",\n+ version = \"v0.0.0-20190215142949-d0b11bdaac8a\",\n)\n# Load C++ rules.\n@@ -68,8 +68,11 @@ http_archive(\n\"https://github.com/bazelbuild/rules_proto/archive/97d8af4dc474595af3900dd85cb3a29ad28cc313.tar.gz\",\n],\n)\n+\nload(\"@rules_proto//proto:repositories.bzl\", \"rules_proto_dependencies\", \"rules_proto_toolchains\")\n+\nrules_proto_dependencies()\n+\nrules_proto_toolchains()\n# Load python dependencies.\n@@ -146,9 +149,9 @@ load(\n# This container is built from the Dockerfile in test/iptables/runner.\ncontainer_pull(\nname = \"iptables-test\",\n+ digest = \"sha256:a137d692a2eb9fc7bf95c5f4a568da090e2c31098e93634421ed88f3a3f1db65\",\nregistry = \"gcr.io\",\nrepository = \"gvisor-presubmit/iptables-test\",\n- digest = \"sha256:a137d692a2eb9fc7bf95c5f4a568da090e2c31098e93634421ed88f3a3f1db65\",\n)\nload(\n@@ -201,6 +204,13 @@ go_repository(\nversion = \"v0.0.0-20171129191014-dec09d789f3d\",\n)\n+go_repository(\n+ name = \"com_github_kr_pretty\",\n+ importpath = \"github.com/kr/pretty\",\n+ sum = \"h1:s5hAObm+yFO5uHYt5dYjxi2rXrsnmRpJx4OYvIWUaQs=\",\n+ version = \"v0.2.0\",\n+)\n+\ngo_repository(\nname = \"com_github_kr_pty\",\nimportpath = \"github.com/kr/pty\",\n@@ -208,6 +218,13 @@ go_repository(\nversion = \"v1.1.1\",\n)\n+go_repository(\n+ name = \"com_github_kr_text\",\n+ importpath = \"github.com/kr/text\",\n+ sum = \"h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=\",\n+ version = \"v0.1.0\",\n+)\n+\ngo_repository(\nname = \"com_github_opencontainers_runtime-spec\",\nimportpath = \"github.com/opencontainers/runtime-spec\",\n@@ -236,6 +253,13 @@ go_repository(\nversion = \"v0.0.0-20171111001504-be1fbeda1936\",\n)\n+go_repository(\n+ name = \"in_gopkg_check_v1\",\n+ importpath = \"gopkg.in/check.v1\",\n+ sum = \"h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=\",\n+ version = \"v1.0.0-20190902080502-41f04d3bba15\",\n+)\n+\ngo_repository(\nname = \"org_golang_x_crypto\",\nimportpath = \"golang.org/x/crypto\",\n@@ -257,12 +281,6 @@ go_repository(\nversion = \"v0.3.0\",\n)\n-go_repository(\n- name = \"org_golang_x_tools\",\n- commit = \"36563e24a262\",\n- importpath = \"golang.org/x/tools\",\n-)\n-\ngo_repository(\nname = \"org_golang_x_sync\",\nimportpath = \"golang.org/x/sync\",\n@@ -272,8 +290,9 @@ go_repository(\ngo_repository(\nname = \"org_golang_x_time\",\n- commit = \"c4c64cad1fd0a1a8dab2523e04e61d35308e131e\",\nimportpath = \"golang.org/x/time\",\n+ sum = \"h1:/5xXl8Y5W96D+TtHSlonuFqGHIWVuyCkGJLwGh9JJFs=\",\n+ version = \"v0.0.0-20191024005414-555d28b269f0\",\n)\ngo_repository(\n"
},
{
"change_type": "MODIFY",
"old_path": "go.mod",
"new_path": "go.mod",
"diff": "@@ -5,19 +5,16 @@ go 1.13\nrequire (\ngithub.com/cenkalti/backoff v0.0.0-20190506075156-2146c9339422\ngithub.com/gofrs/flock v0.6.1-0.20180915234121-886344bea079\n- github.com/golang/mock v1.3.1\ngithub.com/golang/protobuf v1.3.1\ngithub.com/google/btree v1.0.0\n- github.com/google/go-cmp v0.2.0\n- github.com/google/go-github/v28 v28.1.1\ngithub.com/google/subcommands v0.0.0-20190508160503-636abe8753b8\n- github.com/google/uuid v0.0.0-20171129191014-dec09d789f3d\n+ github.com/kr/pretty v0.2.0 // indirect\ngithub.com/kr/pty v1.1.1\ngithub.com/opencontainers/runtime-spec v0.1.2-0.20171211145439-b2d941ef6a78\ngithub.com/syndtr/gocapability v0.0.0-20180916011248-d98352740cb2\ngithub.com/vishvananda/netlink v1.0.1-0.20190318003149-adb577d4a45e\n- github.com/vishvananda/netns v0.0.0-20171111001504-be1fbeda1936\n- golang.org/x/net v0.0.0-20190311183353-d8887717615a\n- golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6\n+ github.com/vishvananda/netns v0.0.0-20171111001504-be1fbeda1936 // indirect\ngolang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a\n+ golang.org/x/time v0.0.0-20191024005414-555d28b269f0\n+ gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "go.sum",
"new_path": "go.sum",
"diff": "+github.com/cenkalti/backoff v0.0.0-20190506075156-2146c9339422 h1:+FKjzBIdfBHYDvxCv+djmDJdes/AoDtg8gpcxowBlF8=\ngithub.com/cenkalti/backoff v0.0.0-20190506075156-2146c9339422/go.mod h1:b6Nc7NRH5C4aCISLry0tLnTjcuTEvoiqcWDdsU0sOGM=\n+github.com/gofrs/flock v0.6.1-0.20180915234121-886344bea079 h1:JFTFz3HZTGmgMz4E1TabNBNJljROSYgja1b4l50FNVs=\ngithub.com/gofrs/flock v0.6.1-0.20180915234121-886344bea079/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU=\n-github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y=\n+github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg=\ngithub.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=\n+github.com/google/btree v1.0.0 h1:0udJVsspx3VBr5FwtLhQQtuAsVc79tTq0ocGIPAU6qo=\ngithub.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=\n-github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=\n-github.com/google/go-github/v28 v28.1.1/go.mod h1:bsqJWQX05omyWVmc00nEUql9mhQyv38lDZ8kPZcQVoM=\n+github.com/google/subcommands v0.0.0-20190508160503-636abe8753b8 h1:GZGUPQiZfYrd9uOqyqwbQcHPkz/EZJVkZB1MkaO9UBI=\ngithub.com/google/subcommands v0.0.0-20190508160503-636abe8753b8/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk=\n-github.com/google/uuid v0.0.0-20171129191014-dec09d789f3d/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\n+github.com/kr/pretty v0.2.0 h1:s5hAObm+yFO5uHYt5dYjxi2rXrsnmRpJx4OYvIWUaQs=\n+github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=\n+github.com/kr/pty v1.1.1 h1:VkoXIwSboBpnk99O/KFauAEILuNHv5DVFKZMBN/gUgw=\ngithub.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=\n+github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=\n+github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=\n+github.com/opencontainers/runtime-spec v0.1.2-0.20171211145439-b2d941ef6a78 h1:d9F+LNYwMyi3BDN4GzZdaSiq4otb8duVEWyZjeUtOQI=\ngithub.com/opencontainers/runtime-spec v0.1.2-0.20171211145439-b2d941ef6a78/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0=\n+github.com/syndtr/gocapability v0.0.0-20180916011248-d98352740cb2 h1:b6uOv7YOFK0TYG7HtkIgExQo+2RdLuwRft63jn2HWj8=\ngithub.com/syndtr/gocapability v0.0.0-20180916011248-d98352740cb2/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww=\n+github.com/vishvananda/netlink v1.0.1-0.20190318003149-adb577d4a45e h1:/Tdc23Arz1OtdIsBY2utWepGRQ9fEAJlhkdoLzWMK8Q=\ngithub.com/vishvananda/netlink v1.0.1-0.20190318003149-adb577d4a45e/go.mod h1:+SR5DhBJrl6ZM7CoCKvpw5BKroDKQ+PJqOg65H/2ktk=\n+github.com/vishvananda/netns v0.0.0-20171111001504-be1fbeda1936 h1:J9gO8RJCAFlln1jsvRba/CWVUnMHwObklfxxjErl1uk=\ngithub.com/vishvananda/netns v0.0.0-20171111001504-be1fbeda1936/go.mod h1:ZjcWmFBXmLKZu9Nxj3WKYEafiSqer2rnvPr0en9UNpI=\n-golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=\n-golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=\n-golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=\n-golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\n+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU=\ngolang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=\n-golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=\n-golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=\n+golang.org/x/time v0.0.0-20191024005414-555d28b269f0 h1:/5xXl8Y5W96D+TtHSlonuFqGHIWVuyCkGJLwGh9JJFs=\n+golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=\n+gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=\n+gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tools/go_mod.sh",
"diff": "+#!/bin/bash\n+\n+# Copyright 2020 The gVisor Authors.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+set -eo pipefail\n+\n+# Build the :gopath target.\n+bazel build //:gopath\n+declare -r gopathdir=\"bazel-bin/gopath/src/gvisor.dev/gvisor/\"\n+\n+# Copy go.mod and execute the command.\n+cp -a go.mod go.sum \"${gopathdir}\"\n+(cd \"${gopathdir}\" && go mod \"$@\")\n+cp -a \"${gopathdir}/go.mod\" \"${gopathdir}/go.sum\" .\n+\n+# Cleanup the WORKSPACE file.\n+bazel run //:gazelle -- update-repos -from_file=go.mod\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add ability to execute go.mod in gopath context. |
260,003 | 28.02.2020 10:37:52 | 28,800 | 6b4d36e3253238dd72d0861ac1220d147e1de8dd | Hide /dev/net/tun when using hostinet.
/dev/net/tun does not currently work with hostinet. This has caused some
program starts failing because it thinks the feature exists. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/dev/BUILD",
"new_path": "pkg/sentry/fs/dev/BUILD",
"diff": "@@ -26,6 +26,7 @@ go_library(\n\"//pkg/sentry/fs/fsutil\",\n\"//pkg/sentry/fs/ramfs\",\n\"//pkg/sentry/fs/tmpfs\",\n+ \"//pkg/sentry/inet\",\n\"//pkg/sentry/kernel\",\n\"//pkg/sentry/memmap\",\n\"//pkg/sentry/mm\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/dev/dev.go",
"new_path": "pkg/sentry/fs/dev/dev.go",
"diff": "@@ -22,6 +22,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n\"gvisor.dev/gvisor/pkg/sentry/fs/ramfs\"\n\"gvisor.dev/gvisor/pkg/sentry/fs/tmpfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/inet\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n@@ -124,10 +125,12 @@ func New(ctx context.Context, msrc *fs.MountSource) *fs.Inode {\n\"ptmx\": newSymlink(ctx, \"pts/ptmx\", msrc),\n\"tty\": newCharacterDevice(ctx, newTTYDevice(ctx, fs.RootOwner, 0666), msrc, ttyDevMajor, ttyDevMinor),\n+ }\n- \"net\": newDirectory(ctx, map[string]*fs.Inode{\n+ if isNetTunSupported(inet.StackFromContext(ctx)) {\n+ contents[\"net\"] = newDirectory(ctx, map[string]*fs.Inode{\n\"tun\": newCharacterDevice(ctx, newNetTunDevice(ctx, fs.RootOwner, 0666), msrc, netTunDevMajor, netTunDevMinor),\n- }, msrc),\n+ }, msrc)\n}\niops := ramfs.NewDir(ctx, contents, fs.RootOwner, fs.FilePermsFromMode(0555))\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/dev/net_tun.go",
"new_path": "pkg/sentry/fs/dev/net_tun.go",
"diff": "@@ -20,6 +20,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n\"gvisor.dev/gvisor/pkg/sentry/fs/fsutil\"\n+ \"gvisor.dev/gvisor/pkg/sentry/inet\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/netstack\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n@@ -168,3 +169,9 @@ func (fops *netTunFileOperations) EventRegister(e *waiter.Entry, mask waiter.Eve\nfunc (fops *netTunFileOperations) EventUnregister(e *waiter.Entry) {\nfops.device.EventUnregister(e)\n}\n+\n+// isNetTunSupported returns whether /dev/net/tun device is supported for s.\n+func isNetTunSupported(s inet.Stack) bool {\n+ _, ok := s.(*netstack.Stack)\n+ return ok\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/kernel.go",
"new_path": "pkg/sentry/kernel/kernel.go",
"diff": "@@ -755,6 +755,8 @@ func (ctx *createProcessContext) Value(key interface{}) interface{} {\nreturn ctx.k.GlobalInit().Leader().MountNamespaceVFS2()\ncase fs.CtxDirentCacheLimiter:\nreturn ctx.k.DirentCacheLimiter\n+ case inet.CtxStack:\n+ return ctx.k.RootNetworkNamespace().Stack()\ncase ktime.CtxRealtimeClock:\nreturn ctx.k.RealtimeClock()\ncase limits.CtxLimits:\n@@ -1481,6 +1483,8 @@ func (ctx supervisorContext) Value(key interface{}) interface{} {\nreturn ctx.k.GlobalInit().Leader().MountNamespaceVFS2()\ncase fs.CtxDirentCacheLimiter:\nreturn ctx.k.DirentCacheLimiter\n+ case inet.CtxStack:\n+ return ctx.k.RootNetworkNamespace().Stack()\ncase ktime.CtxRealtimeClock:\nreturn ctx.k.RealtimeClock()\ncase limits.CtxLimits:\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -680,6 +680,11 @@ syscall_test(\nsyscall_test(test = \"//test/syscalls/linux:tuntap_test\")\n+syscall_test(\n+ add_hostinet = True,\n+ test = \"//test/syscalls/linux:tuntap_hostinet_test\",\n+)\n+\nsyscall_test(test = \"//test/syscalls/linux:udp_bind_test\")\nsyscall_test(\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -3460,6 +3460,18 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"tuntap_hostinet_test\",\n+ testonly = 1,\n+ srcs = [\"tuntap_hostinet.cc\"],\n+ linkstatic = 1,\n+ deps = [\n+ gtest,\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n+\ncc_library(\nname = \"udp_socket_test_cases\",\ntestonly = 1,\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/dev.cc",
"new_path": "test/syscalls/linux/dev.cc",
"diff": "@@ -153,13 +153,6 @@ TEST(DevTest, TTYExists) {\nEXPECT_EQ(statbuf.st_mode, S_IFCHR | 0666);\n}\n-TEST(DevTest, NetTunExists) {\n- struct stat statbuf = {};\n- ASSERT_THAT(stat(\"/dev/net/tun\", &statbuf), SyscallSucceeds());\n- // Check that it's a character device with rw-rw-rw- permissions.\n- EXPECT_EQ(statbuf.st_mode, S_IFCHR | 0666);\n-}\n-\n} // namespace\n} // namespace testing\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/tuntap.cc",
"new_path": "test/syscalls/linux/tuntap.cc",
"diff": "@@ -153,6 +153,13 @@ std::string CreateArpPacket(const uint8_t srcmac[ETH_ALEN], const char* srcip,\n} // namespace\n+TEST(TuntapStaticTest, NetTunExists) {\n+ struct stat statbuf;\n+ ASSERT_THAT(stat(kDevNetTun, &statbuf), SyscallSucceeds());\n+ // Check that it's a character device with rw-rw-rw- permissions.\n+ EXPECT_EQ(statbuf.st_mode, S_IFCHR | 0666);\n+}\n+\nclass TuntapTest : public ::testing::Test {\nprotected:\nvoid TearDown() override {\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/tuntap_hostinet.cc",
"diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <sys/stat.h>\n+#include <sys/types.h>\n+#include <unistd.h>\n+\n+#include \"gtest/gtest.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+TEST(TuntapHostInetTest, NoNetTun) {\n+ SKIP_IF(!IsRunningOnGvisor());\n+\n+ struct stat statbuf;\n+ ASSERT_THAT(stat(\"/dev/net/tun\", &statbuf), SyscallFailsWithErrno(ENOENT));\n+}\n+\n+} // namespace\n+} // namespace testing\n+\n+} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Hide /dev/net/tun when using hostinet.
/dev/net/tun does not currently work with hostinet. This has caused some
program starts failing because it thinks the feature exists.
PiperOrigin-RevId: 297876196 |
259,975 | 28.02.2020 13:21:33 | 28,800 | df8740b8a7fb8fa05d7a0387749b61d57a74c06c | Mark gettid and getdents as nogotsan | [
{
"change_type": "MODIFY",
"old_path": "test/perf/BUILD",
"new_path": "test/perf/BUILD",
"diff": "@@ -30,6 +30,7 @@ syscall_test(\nsyscall_test(\nsize = \"enormous\",\n+ tags = [\"nogotsan\"],\ntest = \"//test/perf/linux:getdents_benchmark\",\n)\n@@ -40,6 +41,7 @@ syscall_test(\nsyscall_test(\nsize = \"enormous\",\n+ tags = [\"nogotsan\"],\ntest = \"//test/perf/linux:gettid_benchmark\",\n)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Mark gettid and getdents as nogotsan
PiperOrigin-RevId: 297915815 |
259,853 | 28.02.2020 17:53:25 | 28,800 | ab7ecdd66d2aa4835bbe655ba672bd30813a2a88 | watchdog: print panic error message before other messages
This is needed for syzkaller to proper classify issues.
Right now, all watchdog issues are duped to one with the
subject "panic: Sentry detected stuck task(s). See stack
trace and message above for more details". | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/watchdog/watchdog.go",
"new_path": "pkg/sentry/watchdog/watchdog.go",
"diff": "@@ -221,7 +221,7 @@ func (w *Watchdog) waitForStart() {\nreturn\n}\nvar buf bytes.Buffer\n- buf.WriteString(\"Watchdog.Start() not called within %s:\\n\")\n+ buf.WriteString(fmt.Sprintf(\"Watchdog.Start() not called within %s\", w.StartupTimeout))\nw.doAction(w.StartupTimeoutAction, false, &buf)\n}\n@@ -325,7 +325,7 @@ func (w *Watchdog) report(offenders map[*kernel.Task]*offender, newTaskFound boo\nfunc (w *Watchdog) reportStuckWatchdog() {\nvar buf bytes.Buffer\n- buf.WriteString(\"Watchdog goroutine is stuck:\\n\")\n+ buf.WriteString(\"Watchdog goroutine is stuck:\")\nw.doAction(w.TaskTimeoutAction, false, &buf)\n}\n@@ -359,7 +359,7 @@ func (w *Watchdog) doAction(action Action, skipStack bool, msg *bytes.Buffer) {\ncase <-metricsEmitted:\ncase <-time.After(1 * time.Second):\n}\n- panic(fmt.Sprintf(\"Stack for running G's are skipped while panicking.\\n%s\", msg.String()))\n+ panic(fmt.Sprintf(\"%s\\nStack for running G's are skipped while panicking.\", msg.String()))\ndefault:\npanic(fmt.Sprintf(\"Unknown watchdog action %v\", action))\n"
}
] | Go | Apache License 2.0 | google/gvisor | watchdog: print panic error message before other messages
This is needed for syzkaller to proper classify issues.
Right now, all watchdog issues are duped to one with the
subject "panic: Sentry detected stuck task(s). See stack
trace and message above for more details".
PiperOrigin-RevId: 297975363 |
259,974 | 02.03.2020 07:13:47 | 0 | 36b193b1db60cad3c1c65ce3abef03a6a0594e3e | Fix syscall test build error on arm64.
The error was introduced in the merge of PR
Some codes are missing when adding bazel select_arch
command to the test/syscall/linux/BUILD file. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -608,7 +608,10 @@ cc_binary(\ncc_binary(\nname = \"exceptions_test\",\ntestonly = 1,\n- srcs = [\"exceptions.cc\"],\n+ srcs = select_arch(\n+ amd64 = [\"exceptions.cc\"],\n+ arm64 = [],\n+ ),\nlinkstatic = 1,\ndeps = [\ngtest,\n@@ -1475,7 +1478,10 @@ cc_binary(\ncc_binary(\nname = \"arch_prctl_test\",\ntestonly = 1,\n- srcs = [\"arch_prctl.cc\"],\n+ srcs = select_arch(\n+ amd64 = [\"arch_prctl.cc\"],\n+ arm64 = [],\n+ ),\nlinkstatic = 1,\ndeps = [\n\"//test/util:file_descriptor\",\n@@ -3322,7 +3328,10 @@ cc_binary(\ncc_binary(\nname = \"sysret_test\",\ntestonly = 1,\n- srcs = [\"sysret.cc\"],\n+ srcs = select_arch(\n+ amd64 = [\"sysret.cc\"],\n+ arm64 = [],\n+ ),\nlinkstatic = 1,\ndeps = [\ngtest,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix syscall test build error on arm64.
The error was introduced in the merge of PR #1471.
Some codes are missing when adding bazel select_arch
command to the test/syscall/linux/BUILD file.
Signed-off-by: Haibo Xu <[email protected]>
Change-Id: I8cae3f4ae78c2e14671f3ac6e7361dc2806d9305 |
259,881 | 02.03.2020 10:05:52 | 28,800 | 62bd3ca8a37543c060292ca86669e537b9ebf36d | Take write lock when removing xattr | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/fsutil/inode.go",
"new_path": "pkg/sentry/fs/fsutil/inode.go",
"diff": "@@ -259,8 +259,8 @@ func (i *InodeSimpleExtendedAttributes) ListXattr(context.Context, *fs.Inode, ui\n// RemoveXattr implements fs.InodeOperations.RemoveXattr.\nfunc (i *InodeSimpleExtendedAttributes) RemoveXattr(_ context.Context, _ *fs.Inode, name string) error {\n- i.mu.RLock()\n- defer i.mu.RUnlock()\n+ i.mu.Lock()\n+ defer i.mu.Unlock()\nif _, ok := i.xattrs[name]; ok {\ndelete(i.xattrs, name)\nreturn nil\n"
}
] | Go | Apache License 2.0 | google/gvisor | Take write lock when removing xattr
PiperOrigin-RevId: 298380654 |
259,962 | 02.03.2020 14:43:52 | 28,800 | 33101752501fafea99d77f34bbd65f3e0083d22e | Fix data-race when reading/writing e.amss. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/connect.go",
"new_path": "pkg/tcpip/transport/tcp/connect.go",
"diff": "@@ -295,6 +295,7 @@ func (h *handshake) synSentState(s *segment) *tcpip.Error {\nh.state = handshakeSynRcvd\nh.ep.mu.Lock()\nttl := h.ep.ttl\n+ amss := h.ep.amss\nh.ep.setEndpointState(StateSynRecv)\nh.ep.mu.Unlock()\nsynOpts := header.TCPSynOptions{\n@@ -307,7 +308,7 @@ func (h *handshake) synSentState(s *segment) *tcpip.Error {\n// permits SACK. This is not explicitly defined in the RFC but\n// this is the behaviour implemented by Linux.\nSACKPermitted: rcvSynOpts.SACKPermitted,\n- MSS: h.ep.amss,\n+ MSS: amss,\n}\nif ttl == 0 {\nttl = s.route.DefaultTTL()\n@@ -356,6 +357,10 @@ func (h *handshake) synRcvdState(s *segment) *tcpip.Error {\nreturn tcpip.ErrInvalidEndpointState\n}\n+ h.ep.mu.RLock()\n+ amss := h.ep.amss\n+ h.ep.mu.RUnlock()\n+\nh.resetState()\nsynOpts := header.TCPSynOptions{\nWS: h.rcvWndScale,\n@@ -363,7 +368,7 @@ func (h *handshake) synRcvdState(s *segment) *tcpip.Error {\nTSVal: h.ep.timestamp(),\nTSEcr: h.ep.recentTimestamp(),\nSACKPermitted: h.ep.sackPermitted,\n- MSS: h.ep.amss,\n+ MSS: amss,\n}\nh.ep.sendSynTCP(&s.route, h.ep.ID, h.ep.ttl, h.ep.sendTOS, h.flags, h.iss, h.ackNum, h.rcvWnd, synOpts)\nreturn nil\n@@ -530,6 +535,7 @@ func (h *handshake) execute() *tcpip.Error {\n// Send the initial SYN segment and loop until the handshake is\n// completed.\n+ h.ep.mu.Lock()\nh.ep.amss = calculateAdvertisedMSS(h.ep.userMSS, h.ep.route)\nsynOpts := header.TCPSynOptions{\n@@ -540,6 +546,7 @@ func (h *handshake) execute() *tcpip.Error {\nSACKPermitted: bool(sackEnabled),\nMSS: h.ep.amss,\n}\n+ h.ep.mu.Unlock()\n// Execute is also called in a listen context so we want to make sure we\n// only send the TS/SACK option when we received the TS/SACK in the\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -959,15 +959,18 @@ func (e *endpoint) initialReceiveWindow() int {\n// ModerateRecvBuf adjusts the receive buffer and the advertised window\n// based on the number of bytes copied to user space.\nfunc (e *endpoint) ModerateRecvBuf(copied int) {\n+ e.mu.RLock()\ne.rcvListMu.Lock()\nif e.rcvAutoParams.disabled {\ne.rcvListMu.Unlock()\n+ e.mu.RUnlock()\nreturn\n}\nnow := time.Now()\nif rtt := e.rcvAutoParams.rtt; rtt == 0 || now.Sub(e.rcvAutoParams.measureTime) < rtt {\ne.rcvAutoParams.copied += copied\ne.rcvListMu.Unlock()\n+ e.mu.RUnlock()\nreturn\n}\nprevRTTCopied := e.rcvAutoParams.copied + copied\n@@ -1008,7 +1011,7 @@ func (e *endpoint) ModerateRecvBuf(copied int) {\ne.rcvBufSize = rcvWnd\navailAfter := e.receiveBufferAvailableLocked()\nmask := uint32(notifyReceiveWindowChanged)\n- if crossed, above := e.windowCrossedACKThreshold(availAfter - availBefore); crossed && above {\n+ if crossed, above := e.windowCrossedACKThresholdLocked(availAfter - availBefore); crossed && above {\nmask |= notifyNonZeroReceiveWindow\n}\ne.notifyProtocolGoroutine(mask)\n@@ -1023,6 +1026,7 @@ func (e *endpoint) ModerateRecvBuf(copied int) {\ne.rcvAutoParams.measureTime = now\ne.rcvAutoParams.copied = 0\ne.rcvListMu.Unlock()\n+ e.mu.RUnlock()\n}\n// IPTables implements tcpip.Endpoint.IPTables.\n@@ -1052,7 +1056,6 @@ func (e *endpoint) Read(*tcpip.FullAddress) (buffer.View, tcpip.ControlMessages,\nv, err := e.readLocked()\ne.rcvListMu.Unlock()\n-\ne.mu.RUnlock()\nif err == tcpip.ErrClosedForReceive {\n@@ -1085,7 +1088,7 @@ func (e *endpoint) readLocked() (buffer.View, *tcpip.Error) {\n// enough buffer space, to either fit an aMSS or half a receive buffer\n// (whichever smaller), then notify the protocol goroutine to send a\n// window update.\n- if crossed, above := e.windowCrossedACKThreshold(len(v)); crossed && above {\n+ if crossed, above := e.windowCrossedACKThresholdLocked(len(v)); crossed && above {\ne.notifyProtocolGoroutine(notifyNonZeroReceiveWindow)\n}\n@@ -1303,9 +1306,9 @@ func (e *endpoint) Peek(vec [][]byte) (int64, tcpip.ControlMessages, *tcpip.Erro\nreturn num, tcpip.ControlMessages{}, nil\n}\n-// windowCrossedACKThreshold checks if the receive window to be announced now\n-// would be under aMSS or under half receive buffer, whichever smaller. This is\n-// useful as a receive side silly window syndrome prevention mechanism. If\n+// windowCrossedACKThresholdLocked checks if the receive window to be announced\n+// now would be under aMSS or under half receive buffer, whichever smaller. This\n+// is useful as a receive side silly window syndrome prevention mechanism. If\n// window grows to reasonable value, we should send ACK to the sender to inform\n// the rx space is now large. We also want ensure a series of small read()'s\n// won't trigger a flood of spurious tiny ACK's.\n@@ -1316,7 +1319,9 @@ func (e *endpoint) Peek(vec [][]byte) (int64, tcpip.ControlMessages, *tcpip.Erro\n// crossed will be true if the window size crossed the ACK threshold.\n// above will be true if the new window is >= ACK threshold and false\n// otherwise.\n-func (e *endpoint) windowCrossedACKThreshold(deltaBefore int) (crossed bool, above bool) {\n+//\n+// Precondition: e.mu and e.rcvListMu must be held.\n+func (e *endpoint) windowCrossedACKThresholdLocked(deltaBefore int) (crossed bool, above bool) {\nnewAvail := e.receiveBufferAvailableLocked()\noldAvail := newAvail - deltaBefore\nif oldAvail < 0 {\n@@ -1379,6 +1384,7 @@ func (e *endpoint) SetSockOptInt(opt tcpip.SockOptInt, v int) *tcpip.Error {\nmask := uint32(notifyReceiveWindowChanged)\n+ e.mu.RLock()\ne.rcvListMu.Lock()\n// Make sure the receive buffer size allows us to send a\n@@ -1405,11 +1411,11 @@ func (e *endpoint) SetSockOptInt(opt tcpip.SockOptInt, v int) *tcpip.Error {\n// Immediately send an ACK to uncork the sender silly window\n// syndrome prevetion, when our available space grows above aMSS\n// or half receive buffer, whichever smaller.\n- if crossed, above := e.windowCrossedACKThreshold(availAfter - availBefore); crossed && above {\n+ if crossed, above := e.windowCrossedACKThresholdLocked(availAfter - availBefore); crossed && above {\nmask |= notifyNonZeroReceiveWindow\n}\ne.rcvListMu.Unlock()\n-\n+ e.mu.RUnlock()\ne.notifyProtocolGoroutine(mask)\nreturn nil\n@@ -2414,13 +2420,14 @@ func (e *endpoint) updateSndBufferUsage(v int) {\n// to be read, or when the connection is closed for receiving (in which case\n// s will be nil).\nfunc (e *endpoint) readyToRead(s *segment) {\n+ e.mu.RLock()\ne.rcvListMu.Lock()\nif s != nil {\ns.incRef()\ne.rcvBufUsed += s.data.Size()\n// Increase counter if the receive window falls down below MSS\n// or half receive buffer size, whichever smaller.\n- if crossed, above := e.windowCrossedACKThreshold(-s.data.Size()); crossed && !above {\n+ if crossed, above := e.windowCrossedACKThresholdLocked(-s.data.Size()); crossed && !above {\ne.stats.ReceiveErrors.ZeroRcvWindowState.Increment()\n}\ne.rcvList.PushBack(s)\n@@ -2428,7 +2435,7 @@ func (e *endpoint) readyToRead(s *segment) {\ne.rcvClosed = true\n}\ne.rcvListMu.Unlock()\n-\n+ e.mu.RUnlock()\ne.waiterQueue.Notify(waiter.EventIn)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/tcp_socket.cc",
"new_path": "test/syscalls/linux/tcp_socket.cc",
"diff": "@@ -1349,6 +1349,21 @@ TEST_P(SimpleTcpSocketTest, RecvOnClosedSocket) {\nSyscallFailsWithErrno(ENOTCONN));\n}\n+TEST_P(SimpleTcpSocketTest, TCPConnectSoRcvBufRace) {\n+ auto s = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(GetParam(), SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP));\n+ sockaddr_storage addr =\n+ ASSERT_NO_ERRNO_AND_VALUE(InetLoopbackAddr(GetParam()));\n+ socklen_t addrlen = sizeof(addr);\n+\n+ RetryEINTR(connect)(s.get(), reinterpret_cast<struct sockaddr*>(&addr),\n+ addrlen);\n+ int buf_sz = 1 << 18;\n+ EXPECT_THAT(\n+ setsockopt(s.get(), SOL_SOCKET, SO_RCVBUF, &buf_sz, sizeof(buf_sz)),\n+ SyscallSucceedsWithValue(0));\n+}\n+\nINSTANTIATE_TEST_SUITE_P(AllInetTests, SimpleTcpSocketTest,\n::testing::Values(AF_INET, AF_INET6));\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix data-race when reading/writing e.amss.
PiperOrigin-RevId: 298451319 |
259,896 | 02.03.2020 16:30:51 | 28,800 | 43abb24657e737dee1108ff0d512b2e1b6d8a3f6 | Fix panic caused by invalid address for Bind in packet sockets. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/netstack.go",
"new_path": "pkg/sentry/socket/netstack/netstack.go",
"diff": "@@ -712,6 +712,10 @@ func (s *SocketOperations) Connect(t *kernel.Task, sockaddr []byte, blocking boo\n// Bind implements the linux syscall bind(2) for sockets backed by\n// tcpip.Endpoint.\nfunc (s *SocketOperations) Bind(t *kernel.Task, sockaddr []byte) *syserr.Error {\n+ if len(sockaddr) < 2 {\n+ return syserr.ErrInvalidArgument\n+ }\n+\nfamily := usermem.ByteOrder.Uint16(sockaddr)\nvar addr tcpip.FullAddress\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/packet_socket.cc",
"new_path": "test/syscalls/linux/packet_socket.cc",
"diff": "@@ -417,6 +417,19 @@ TEST_P(CookedPacketTest, BindDrop) {\nEXPECT_THAT(RetryEINTR(poll)(&pfd, 1, 1000), SyscallSucceedsWithValue(0));\n}\n+// Bind with invalid address.\n+TEST_P(CookedPacketTest, BindFail) {\n+ // Null address.\n+ ASSERT_THAT(bind(socket_, nullptr, sizeof(struct sockaddr)),\n+ SyscallFailsWithErrno(EFAULT));\n+\n+ // Address of size 1.\n+ uint8_t addr = 0;\n+ ASSERT_THAT(\n+ bind(socket_, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\nINSTANTIATE_TEST_SUITE_P(AllInetTests, CookedPacketTest,\n::testing::Values(ETH_P_IP, ETH_P_ALL));\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix panic caused by invalid address for Bind in packet sockets.
PiperOrigin-RevId: 298476533 |
259,858 | 03.03.2020 12:36:37 | 28,800 | b3c549d8391e7cadd82a5ab9280bc63bb372aa97 | Move temp_umask to test/util. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -166,11 +166,6 @@ cc_library(\n],\n)\n-cc_library(\n- name = \"temp_umask\",\n- hdrs = [\"temp_umask.h\"],\n-)\n-\ncc_library(\nname = \"unix_domain_socket_test_util\",\ntestonly = 1,\n@@ -1140,11 +1135,11 @@ cc_binary(\nsrcs = [\"mkdir.cc\"],\nlinkstatic = 1,\ndeps = [\n- \":temp_umask\",\n\"//test/util:capability_util\",\n\"//test/util:fs_util\",\ngtest,\n\"//test/util:temp_path\",\n+ \"//test/util:temp_umask\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n],\n@@ -1299,12 +1294,12 @@ cc_binary(\nsrcs = [\"open_create.cc\"],\nlinkstatic = 1,\ndeps = [\n- \":temp_umask\",\n\"//test/util:capability_util\",\n\"//test/util:file_descriptor\",\n\"//test/util:fs_util\",\ngtest,\n\"//test/util:temp_path\",\n+ \"//test/util:temp_umask\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/mkdir.cc",
"new_path": "test/syscalls/linux/mkdir.cc",
"diff": "#include <unistd.h>\n#include \"gtest/gtest.h\"\n-#include \"test/syscalls/linux/temp_umask.h\"\n#include \"test/util/capability_util.h\"\n#include \"test/util/fs_util.h\"\n#include \"test/util/temp_path.h\"\n+#include \"test/util/temp_umask.h\"\n#include \"test/util/test_util.h\"\nnamespace gvisor {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/open_create.cc",
"new_path": "test/syscalls/linux/open_create.cc",
"diff": "#include <unistd.h>\n#include \"gtest/gtest.h\"\n-#include \"test/syscalls/linux/temp_umask.h\"\n#include \"test/util/capability_util.h\"\n#include \"test/util/file_descriptor.h\"\n#include \"test/util/fs_util.h\"\n#include \"test/util/temp_path.h\"\n+#include \"test/util/temp_umask.h\"\n#include \"test/util/test_util.h\"\nnamespace gvisor {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/BUILD",
"new_path": "test/util/BUILD",
"diff": "@@ -350,3 +350,9 @@ cc_library(\n\":save_util\",\n],\n)\n+\n+cc_library(\n+ name = \"temp_umask\",\n+ testonly = 1,\n+ hdrs = [\"temp_umask.h\"],\n+)\n"
},
{
"change_type": "RENAME",
"old_path": "test/syscalls/linux/temp_umask.h",
"new_path": "test/util/temp_umask.h",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-#ifndef GVISOR_TEST_SYSCALLS_TEMP_UMASK_H_\n-#define GVISOR_TEST_SYSCALLS_TEMP_UMASK_H_\n+#ifndef GVISOR_TEST_UTIL_TEMP_UMASK_H_\n+#define GVISOR_TEST_UTIL_TEMP_UMASK_H_\n#include <sys/stat.h>\n#include <sys/types.h>\n@@ -36,4 +36,4 @@ class TempUmask {\n} // namespace testing\n} // namespace gvisor\n-#endif // GVISOR_TEST_SYSCALLS_TEMP_UMASK_H_\n+#endif // GVISOR_TEST_UTIL_TEMP_UMASK_H_\n"
}
] | Go | Apache License 2.0 | google/gvisor | Move temp_umask to test/util.
PiperOrigin-RevId: 298667595 |
259,853 | 03.03.2020 14:34:36 | 28,800 | 277a0d5a1fbe8272d4729c01ee4c6e374d047ebc | platform/ptrace: don't call probeSeccomp on arm64
The support of PTRACE_SYSEMU on arm64 was added in the 5.3 kernel,
so we can be sure that the current version is higher that 5.3.
And this change moves vsyscall seccomp rules to the arch specific file,
because vsyscall isn't supported on arm64. | [
{
"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,7 @@ import (\n\"strings\"\n\"syscall\"\n+ \"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/seccomp\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n@@ -183,8 +184,21 @@ func enableCpuidFault() {\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+func appendArchSeccompRules(rules []seccomp.RuleSet, defaultAction linux.BPFAction) []seccomp.RuleSet {\n+ rules = append(rules,\n+ // Rules for trapping vsyscall access.\n+ seccomp.RuleSet{\n+ Rules: seccomp.SyscallRules{\n+ syscall.SYS_GETTIMEOFDAY: {},\n+ syscall.SYS_TIME: {},\n+ unix.SYS_GETCPU: {}, // SYS_GETCPU was not defined in package syscall on amd64.\n+ },\n+ Action: linux.SECCOMP_RET_TRAP,\n+ Vsyscall: true,\n+ })\n+ if defaultAction != linux.SECCOMP_RET_ALLOW {\n+ rules = append(rules,\n+ seccomp.RuleSet{\nRules: seccomp.SyscallRules{\nsyscall.SYS_ARCH_PRCTL: []seccomp.Rule{\n{seccomp.AllowValue(linux.ARCH_SET_CPUID), seccomp.AllowValue(0)},\n@@ -193,3 +207,53 @@ func appendArchSeccompRules(rules []seccomp.RuleSet) []seccomp.RuleSet {\nAction: linux.SECCOMP_RET_ALLOW,\n})\n}\n+ return rules\n+}\n+\n+// probeSeccomp returns true iff seccomp is run after ptrace notifications,\n+// which is generally the case for kernel version >= 4.8. This check is dynamic\n+// because kernels have be backported behavior.\n+//\n+// See createStub for more information.\n+//\n+// Precondition: the runtime OS thread must be locked.\n+func probeSeccomp() bool {\n+ // Create a completely new, destroyable process.\n+ t, err := attachedThread(0, linux.SECCOMP_RET_ERRNO)\n+ if err != nil {\n+ panic(fmt.Sprintf(\"seccomp probe failed: %v\", err))\n+ }\n+ defer t.destroy()\n+\n+ // Set registers to the yield system call. This call is not allowed\n+ // by the filters specified in the attachThread function.\n+ regs := createSyscallRegs(&t.initRegs, syscall.SYS_SCHED_YIELD)\n+ if err := t.setRegs(®s); err != nil {\n+ panic(fmt.Sprintf(\"ptrace set regs failed: %v\", err))\n+ }\n+\n+ for {\n+ // Attempt an emulation.\n+ if _, _, errno := syscall.RawSyscall6(syscall.SYS_PTRACE, unix.PTRACE_SYSEMU, uintptr(t.tid), 0, 0, 0, 0); errno != 0 {\n+ panic(fmt.Sprintf(\"ptrace syscall-enter failed: %v\", errno))\n+ }\n+\n+ sig := t.wait(stopped)\n+ if sig == (syscallEvent | syscall.SIGTRAP) {\n+ // Did the seccomp errno hook already run? This would\n+ // indicate that seccomp is first in line and we're\n+ // less than 4.8.\n+ if err := t.getRegs(®s); err != nil {\n+ panic(fmt.Sprintf(\"ptrace get-regs failed: %v\", err))\n+ }\n+ if _, err := syscallReturnValue(®s); err == nil {\n+ // The seccomp errno mode ran first, and reset\n+ // the error in the registers.\n+ return false\n+ }\n+ // The seccomp hook did not run yet, and therefore it\n+ // is safe to use RET_KILL mode for dispatched calls.\n+ return true\n+ }\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": "@@ -160,6 +160,15 @@ func enableCpuidFault() {\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+func appendArchSeccompRules(rules []seccomp.RuleSet, defaultAction linux.BPFAction) []seccomp.RuleSet {\nreturn rules\n}\n+\n+// probeSeccomp returns true if seccomp is run after ptrace notifications,\n+// which is generally the case for kernel version >= 4.8.\n+//\n+// On arm64, the support of PTRACE_SYSEMU was added in the 5.3 kernel, so\n+// probeSeccomp can always return true.\n+func probeSeccomp() bool {\n+ return true\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,7 +20,6 @@ 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@@ -30,54 +29,6 @@ import (\nconst syscallEvent syscall.Signal = 0x80\n-// probeSeccomp returns true iff seccomp is run after ptrace notifications,\n-// which is generally the case for kernel version >= 4.8. This check is dynamic\n-// because kernels have be backported behavior.\n-//\n-// See createStub for more information.\n-//\n-// Precondition: the runtime OS thread must be locked.\n-func probeSeccomp() bool {\n- // Create a completely new, destroyable process.\n- t, err := attachedThread(0, linux.SECCOMP_RET_ERRNO)\n- if err != nil {\n- panic(fmt.Sprintf(\"seccomp probe failed: %v\", err))\n- }\n- defer t.destroy()\n-\n- // Set registers to the yield system call. This call is not allowed\n- // by the filters specified in the attachThread function.\n- regs := createSyscallRegs(&t.initRegs, syscall.SYS_SCHED_YIELD)\n- if err := t.setRegs(®s); err != nil {\n- panic(fmt.Sprintf(\"ptrace set regs failed: %v\", err))\n- }\n-\n- for {\n- // Attempt an emulation.\n- if _, _, errno := syscall.RawSyscall6(syscall.SYS_PTRACE, unix.PTRACE_SYSEMU, uintptr(t.tid), 0, 0, 0, 0); errno != 0 {\n- panic(fmt.Sprintf(\"ptrace syscall-enter failed: %v\", errno))\n- }\n-\n- sig := t.wait(stopped)\n- if sig == (syscallEvent | syscall.SIGTRAP) {\n- // Did the seccomp errno hook already run? This would\n- // indicate that seccomp is first in line and we're\n- // less than 4.8.\n- if err := t.getRegs(®s); err != nil {\n- panic(fmt.Sprintf(\"ptrace get-regs failed: %v\", err))\n- }\n- if _, err := syscallReturnValue(®s); err == nil {\n- // The seccomp errno mode ran first, and reset\n- // the error in the registers.\n- return false\n- }\n- // The seccomp hook did not run yet, and therefore it\n- // is safe to use RET_KILL mode for dispatched calls.\n- return true\n- }\n- }\n-}\n-\n// createStub creates a fresh stub processes.\n//\n// Precondition: the runtime OS thread must be locked.\n@@ -123,18 +74,7 @@ func attachedThread(flags uintptr, defaultAction linux.BPFAction) (*thread, erro\n// stub and all its children. This is used to create child stubs\n// (below), so we must include the ability to fork, but otherwise lock\n// down available calls only to what is needed.\n- rules := []seccomp.RuleSet{\n- // Rules for trapping vsyscall access.\n- {\n- Rules: seccomp.SyscallRules{\n- syscall.SYS_GETTIMEOFDAY: {},\n- syscall.SYS_TIME: {},\n- unix.SYS_GETCPU: {}, // SYS_GETCPU was not defined in package syscall on amd64.\n- },\n- Action: linux.SECCOMP_RET_TRAP,\n- Vsyscall: true,\n- },\n- }\n+ rules := []seccomp.RuleSet{}\nif defaultAction != linux.SECCOMP_RET_ALLOW {\nrules = append(rules, seccomp.RuleSet{\nRules: seccomp.SyscallRules{\n@@ -173,9 +113,8 @@ func attachedThread(flags uintptr, defaultAction linux.BPFAction) (*thread, erro\n},\nAction: linux.SECCOMP_RET_ALLOW,\n})\n-\n- rules = appendArchSeccompRules(rules)\n}\n+ rules = appendArchSeccompRules(rules, defaultAction)\ninstrs, err := seccomp.BuildProgram(rules, defaultAction)\nif err != nil {\nreturn nil, err\n"
}
] | Go | Apache License 2.0 | google/gvisor | platform/ptrace: don't call probeSeccomp on arm64
The support of PTRACE_SYSEMU on arm64 was added in the 5.3 kernel,
so we can be sure that the current version is higher that 5.3.
And this change moves vsyscall seccomp rules to the arch specific file,
because vsyscall isn't supported on arm64.
PiperOrigin-RevId: 298696493 |
259,992 | 03.03.2020 15:27:23 | 28,800 | 122d47aed17abf4301596e19fc8ac9cdad8118d9 | Update cached file size when cache is skipped
gofer.dentryReadWriter.WriteFromBlocks was not updating
gofer.dentry.size after a write operation that skips the
cache.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/regular_file.go",
"new_path": "pkg/sentry/fsimpl/gofer/regular_file.go",
"diff": "@@ -361,8 +361,15 @@ func (rw *dentryReadWriter) WriteFromBlocks(srcs safemem.BlockSeq) (uint64, erro\nrw.d.handleMu.RLock()\nif (rw.d.handle.fd >= 0 && !rw.d.fs.opts.forcePageCache) || rw.d.fs.opts.interop == InteropModeShared || rw.direct {\nn, err := rw.d.handle.writeFromBlocksAt(rw.ctx, srcs, rw.off)\n- rw.d.handleMu.RUnlock()\nrw.off += n\n+ rw.d.dataMu.Lock()\n+ if rw.off > rw.d.size {\n+ atomic.StoreUint64(&rw.d.size, rw.off)\n+ // The remote file's size will implicitly be extended to the correct\n+ // value when we write back to it.\n+ }\n+ rw.d.dataMu.Unlock()\n+ rw.d.handleMu.RUnlock()\nreturn n, err\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update cached file size when cache is skipped
gofer.dentryReadWriter.WriteFromBlocks was not updating
gofer.dentry.size after a write operation that skips the
cache.
Updates #1198
PiperOrigin-RevId: 298708646 |
259,846 | 03.03.2020 16:53:53 | 28,800 | fa5f99187bb28a0f363ddce82cefe92a002edc0f | Gather and return real statistics in Stats() | [
{
"change_type": "MODIFY",
"old_path": "pkg/v2/service.go",
"new_path": "pkg/v2/service.go",
"diff": "@@ -565,8 +565,77 @@ func (s *service) Shutdown(ctx context.Context, r *taskAPI.ShutdownRequest) (*pt\n}\nfunc (s *service) Stats(ctx context.Context, r *taskAPI.StatsRequest) (*taskAPI.StatsResponse, error) {\n- // TODO(random-liu): Use `runsc events --stats`.\n- data, err := typeurl.MarshalAny(&cgroups.Metrics{})\n+ path, err := os.Getwd()\n+ if err != nil {\n+ return nil, err\n+ }\n+ ns, err := namespaces.NamespaceRequired(ctx)\n+ if err != nil {\n+ return nil, err\n+ }\n+ runtime, err := s.readRuntime(path)\n+ if err != nil {\n+ return nil, err\n+ }\n+ rs := proc.NewRunsc(proc.RunscRoot, path, ns, runtime, nil)\n+ stats, err := rs.Stats(ctx, s.id)\n+ if err != nil {\n+ return nil, err\n+ }\n+\n+ // gvisor currently (as of 2020-03-03) only returns the total memory\n+ // usage and current PID value[0]. However, we copy the common fields here\n+ // so that future updates will propagate correct information. We're\n+ // using the cgroups.Metrics structure so we're returning the same type\n+ // as runc.\n+ //\n+ // [0]: https://github.com/google/gvisor/blob/277a0d5a1fbe8272d4729c01ee4c6e374d047ebc/runsc/boot/events.go#L61-L81\n+ data, err := typeurl.MarshalAny(&cgroups.Metrics{\n+ CPU: &cgroups.CPUStat{\n+ Usage: &cgroups.CPUUsage{\n+ Total: stats.Cpu.Usage.Total,\n+ Kernel: stats.Cpu.Usage.Kernel,\n+ User: stats.Cpu.Usage.User,\n+ PerCPU: stats.Cpu.Usage.Percpu,\n+ },\n+ Throttling: &cgroups.Throttle{\n+ Periods: stats.Cpu.Throttling.Periods,\n+ ThrottledPeriods: stats.Cpu.Throttling.ThrottledPeriods,\n+ ThrottledTime: stats.Cpu.Throttling.ThrottledTime,\n+ },\n+ },\n+ Memory: &cgroups.MemoryStat{\n+ Cache: stats.Memory.Cache,\n+ Usage: &cgroups.MemoryEntry{\n+ Limit: stats.Memory.Usage.Limit,\n+ Usage: stats.Memory.Usage.Usage,\n+ Max: stats.Memory.Usage.Max,\n+ Failcnt: stats.Memory.Usage.Failcnt,\n+ },\n+ Swap: &cgroups.MemoryEntry{\n+ Limit: stats.Memory.Swap.Limit,\n+ Usage: stats.Memory.Swap.Usage,\n+ Max: stats.Memory.Swap.Max,\n+ Failcnt: stats.Memory.Swap.Failcnt,\n+ },\n+ Kernel: &cgroups.MemoryEntry{\n+ Limit: stats.Memory.Kernel.Limit,\n+ Usage: stats.Memory.Kernel.Usage,\n+ Max: stats.Memory.Kernel.Max,\n+ Failcnt: stats.Memory.Kernel.Failcnt,\n+ },\n+ KernelTCP: &cgroups.MemoryEntry{\n+ Limit: stats.Memory.KernelTCP.Limit,\n+ Usage: stats.Memory.KernelTCP.Usage,\n+ Max: stats.Memory.KernelTCP.Max,\n+ Failcnt: stats.Memory.KernelTCP.Failcnt,\n+ },\n+ },\n+ Pids: &cgroups.PidsStat{\n+ Current: stats.Pids.Current,\n+ Limit: stats.Pids.Limit,\n+ },\n+ })\nif err != nil {\nreturn nil, err\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Gather and return real statistics in Stats() (#50) |
259,972 | 04.03.2020 00:14:41 | 28,800 | ef1219c1451a75916693a54ddad39d04cf763d90 | Use shuf instead of $RANDOM everywhere.
$RANDOM can cause collisions but shuf uses /dev/urandom so it ought to cause
fewer. | [
{
"change_type": "MODIFY",
"old_path": "test/packetdrill/packetdrill_test.sh",
"new_path": "test/packetdrill/packetdrill_test.sh",
"diff": "@@ -91,8 +91,8 @@ fi\n# Variables specific to the test runner start with TEST_RUNNER_.\ndeclare -r PACKETDRILL=\"/packetdrill/gtests/net/packetdrill/packetdrill\"\n# Use random numbers so that test networks don't collide.\n-declare -r CTRL_NET=\"ctrl_net-${RANDOM}${RANDOM}\"\n-declare -r TEST_NET=\"test_net-${RANDOM}${RANDOM}\"\n+declare -r CTRL_NET=\"ctrl_net-$(shuf -i 0-99999999 -n 1)\"\n+declare -r TEST_NET=\"test_net-$(shuf -i 0-99999999 -n 1)\"\ndeclare -r tolerance_usecs=100000\n# On both DUT and test runner, testing packets are on the eth2 interface.\ndeclare -r TEST_DEVICE=\"eth2\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use shuf instead of $RANDOM everywhere.
$RANDOM can cause collisions but shuf uses /dev/urandom so it ought to cause
fewer.
PiperOrigin-RevId: 298786344 |
259,885 | 04.03.2020 14:29:11 | 28,800 | a690b5762480ae80ef4264402fcfa8d84b57339a | Ensure that safemem.BlockSeqOf(safemem.Block{}) produces an empty BlockSeq. | [
{
"change_type": "MODIFY",
"old_path": "pkg/safemem/seq_test.go",
"new_path": "pkg/safemem/seq_test.go",
"diff": "@@ -20,6 +20,27 @@ import (\n\"testing\"\n)\n+func TestBlockSeqOfEmptyBlock(t *testing.T) {\n+ bs := BlockSeqOf(Block{})\n+ if !bs.IsEmpty() {\n+ t.Errorf(\"BlockSeqOf(Block{}).IsEmpty(): got false, wanted true; BlockSeq is %v\", bs)\n+ }\n+}\n+\n+func TestBlockSeqOfNonemptyBlock(t *testing.T) {\n+ b := BlockFromSafeSlice(make([]byte, 1))\n+ bs := BlockSeqOf(b)\n+ if bs.IsEmpty() {\n+ t.Fatalf(\"BlockSeqOf(non-empty Block).IsEmpty(): got true, wanted false; BlockSeq is %v\", bs)\n+ }\n+ if head := bs.Head(); head != b {\n+ t.Fatalf(\"BlockSeqOf(non-empty Block).Head(): got %v, wanted %v\", head, b)\n+ }\n+ if tail := bs.Tail(); !tail.IsEmpty() {\n+ t.Fatalf(\"BlockSeqOf(non-empty Block).Tail().IsEmpty(): got false, wanted true: tail is %v\", tail)\n+ }\n+}\n+\ntype blockSeqTest struct {\ndesc string\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/safemem/seq_unsafe.go",
"new_path": "pkg/safemem/seq_unsafe.go",
"diff": "@@ -56,6 +56,9 @@ type BlockSeq struct {\n// BlockSeqOf returns a BlockSeq representing the single Block b.\nfunc BlockSeqOf(b Block) BlockSeq {\n+ if b.length == 0 {\n+ return BlockSeq{}\n+ }\nbs := BlockSeq{\ndata: b.start,\nlength: -1,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Ensure that safemem.BlockSeqOf(safemem.Block{}) produces an empty BlockSeq.
PiperOrigin-RevId: 298941855 |
259,854 | 05.03.2020 15:55:40 | 28,800 | 9b3aad33c4470908953b7b548b12cba77799f342 | Use a pool of arrays to avoid slice headers from escaping in TCP options pool.
By putting slices into the pool, the slice header escapes. This can be avoided
by not putting the slice header into the pool.
This removes an allocation from the TCP segment send path. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/BUILD",
"new_path": "pkg/tcpip/transport/tcp/BUILD",
"diff": "@@ -32,6 +32,7 @@ go_library(\nsrcs = [\n\"accept.go\",\n\"connect.go\",\n+ \"connect_unsafe.go\",\n\"cubic.go\",\n\"cubic_state.go\",\n\"dispatcher.go\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/connect.go",
"new_path": "pkg/tcpip/transport/tcp/connect.go",
"diff": "@@ -624,17 +624,17 @@ func parseSynSegmentOptions(s *segment) header.TCPSynOptions {\nvar optionPool = sync.Pool{\nNew: func() interface{} {\n- return make([]byte, maxOptionSize)\n+ return &[maxOptionSize]byte{}\n},\n}\nfunc getOptions() []byte {\n- return optionPool.Get().([]byte)\n+ return (*optionPool.Get().(*[maxOptionSize]byte))[:]\n}\nfunc putOptions(options []byte) {\n// Reslice to full capacity.\n- optionPool.Put(options[0:cap(options)])\n+ optionPool.Put(optionsToArray(options))\n}\nfunc makeSynOptions(opts header.TCPSynOptions) []byte {\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/tcpip/transport/tcp/connect_unsafe.go",
"diff": "+// Copyright 2018 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package tcp\n+\n+import (\n+ \"reflect\"\n+ \"unsafe\"\n+)\n+\n+// optionsToArray converts a slice of capacity >-= maxOptionSize to an array.\n+//\n+// optionsToArray panics if the capacity of options is smaller than\n+// maxOptionSize.\n+func optionsToArray(options []byte) *[maxOptionSize]byte {\n+ // Reslice to full capacity.\n+ options = options[0:maxOptionSize]\n+ return (*[maxOptionSize]byte)(unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&options)).Data))\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use a pool of arrays to avoid slice headers from escaping in TCP options pool.
By putting slices into the pool, the slice header escapes. This can be avoided
by not putting the slice header into the pool.
This removes an allocation from the TCP segment send path.
PiperOrigin-RevId: 299215480 |
260,003 | 05.03.2020 17:39:11 | 28,800 | 9b64b658c1b9a4986bc5a4ebd9e5ddeb9f52dfa3 | Fix S/R on inet.Namespace. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/inet/namespace.go",
"new_path": "pkg/sentry/inet/namespace.go",
"diff": "@@ -23,7 +23,10 @@ type Namespace struct {\n// creator allows kernel to create new network stack for network namespaces.\n// If nil, no networking will function if network is namespaced.\n- creator NetworkStackCreator\n+ //\n+ // At afterLoad(), creator will be used to create network stack. Stateify\n+ // needs to wait for this field to be loaded before calling afterLoad().\n+ creator NetworkStackCreator `state:\"wait\"`\n// isRoot indicates whether this is the root network namespace.\nisRoot bool\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix S/R on inet.Namespace.
PiperOrigin-RevId: 299238067 |
259,884 | 05.03.2020 18:21:39 | 28,800 | da48fc6cca23a38faef51c5b5f8ae609940773a0 | Stub oom_score_adj and oom_score.
Adds an oom_score_adj and oom_score proc file stub. oom_score_adj accepts
writes of values -1000 to 1000 and persists the value with the task. New tasks
inherit the parent's oom_score_adj.
oom_score is a read-only stub that always returns the value '0'.
Issue | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/task.go",
"new_path": "pkg/sentry/fs/proc/task.go",
"diff": "@@ -85,6 +85,8 @@ func (p *proc) newTaskDir(t *kernel.Task, msrc *fs.MountSource, isThreadGroup bo\n\"mountinfo\": seqfile.NewSeqFileInode(t, &mountInfoFile{t: t}, msrc),\n\"mounts\": seqfile.NewSeqFileInode(t, &mountsFile{t: t}, msrc),\n\"ns\": newNamespaceDir(t, msrc),\n+ \"oom_score\": newOOMScore(t, msrc),\n+ \"oom_score_adj\": newOOMScoreAdj(t, msrc),\n\"smaps\": newSmaps(t, msrc),\n\"stat\": newTaskStat(t, msrc, isThreadGroup, p.pidns),\n\"statm\": newStatm(t, msrc),\n@@ -796,4 +798,92 @@ func (f *auxvecFile) Read(ctx context.Context, _ *fs.File, dst usermem.IOSequenc\nreturn int64(n), err\n}\n+// newOOMScore returns a oom_score file. It is a stub that always returns 0.\n+// TODO(gvisor.dev/issue/1967)\n+func newOOMScore(t *kernel.Task, msrc *fs.MountSource) *fs.Inode {\n+ return newStaticProcInode(t, msrc, []byte(\"0\\n\"))\n+}\n+\n+// oomScoreAdj is a file containing the oom_score adjustment for a task.\n+//\n+// +stateify savable\n+type oomScoreAdj struct {\n+ fsutil.SimpleFileInode\n+\n+ t *kernel.Task\n+}\n+\n+// +stateify savable\n+type oomScoreAdjFile struct {\n+ fsutil.FileGenericSeek `state:\"nosave\"`\n+ fsutil.FileNoIoctl `state:\"nosave\"`\n+ fsutil.FileNoMMap `state:\"nosave\"`\n+ fsutil.FileNoSplice `state:\"nosave\"`\n+ fsutil.FileNoopFlush `state:\"nosave\"`\n+ fsutil.FileNoopFsync `state:\"nosave\"`\n+ fsutil.FileNoopRelease `state:\"nosave\"`\n+ fsutil.FileNotDirReaddir `state:\"nosave\"`\n+ fsutil.FileUseInodeUnstableAttr `state:\"nosave\"`\n+ waiter.AlwaysReady `state:\"nosave\"`\n+\n+ t *kernel.Task\n+}\n+\n+// newOOMScoreAdj returns a oom_score_adj file.\n+func newOOMScoreAdj(t *kernel.Task, msrc *fs.MountSource) *fs.Inode {\n+ i := &oomScoreAdj{\n+ SimpleFileInode: *fsutil.NewSimpleFileInode(t, fs.RootOwner, fs.FilePermsFromMode(0644), linux.PROC_SUPER_MAGIC),\n+ t: t,\n+ }\n+ return newProcInode(t, i, msrc, fs.SpecialFile, t)\n+}\n+\n+// Truncate implements fs.InodeOperations.Truncate. Truncate is called when\n+// O_TRUNC is specified for any kind of existing Dirent but is not called via\n+// (f)truncate for proc files.\n+func (*oomScoreAdj) Truncate(context.Context, *fs.Inode, int64) error {\n+ return nil\n+}\n+\n+// GetFile implements fs.InodeOperations.GetFile.\n+func (o *oomScoreAdj) GetFile(ctx context.Context, dirent *fs.Dirent, flags fs.FileFlags) (*fs.File, error) {\n+ return fs.NewFile(ctx, dirent, flags, &oomScoreAdjFile{t: o.t}), nil\n+}\n+\n+// Read implements fs.FileOperations.Read.\n+func (f *oomScoreAdjFile) Read(ctx context.Context, _ *fs.File, dst usermem.IOSequence, offset int64) (int64, error) {\n+ if offset != 0 {\n+ return 0, io.EOF\n+ }\n+ adj, err := f.t.OOMScoreAdj()\n+ if err != nil {\n+ return 0, err\n+ }\n+ adjBytes := []byte(strconv.FormatInt(int64(adj), 10) + \"\\n\")\n+ n, err := dst.CopyOut(ctx, adjBytes)\n+ return int64(n), err\n+}\n+\n+// Write implements fs.FileOperations.Write.\n+func (f *oomScoreAdjFile) Write(ctx context.Context, _ *fs.File, src usermem.IOSequence, offset int64) (int64, error) {\n+ if src.NumBytes() == 0 {\n+ return 0, nil\n+ }\n+\n+ // Limit input size so as not to impact performance if input size is large.\n+ src = src.TakeFirst(usermem.PageSize - 1)\n+\n+ var v int32\n+ n, err := usermem.CopyInt32StringInVec(ctx, src.IO, src.Addrs, &v, src.Opts)\n+ if err != nil {\n+ return 0, err\n+ }\n+\n+ if err := f.t.SetOOMScoreAdj(v); err != nil {\n+ return 0, err\n+ }\n+\n+ return n, nil\n+}\n+\n// LINT.ThenChange(../../fsimpl/proc/task.go|../../fsimpl/proc/task_files.go)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/task.go",
"new_path": "pkg/sentry/fsimpl/proc/task.go",
"diff": "@@ -62,6 +62,8 @@ func newTaskInode(inoGen InoGenerator, task *kernel.Task, pidns *kernel.PIDNames\n\"pid\": newNamespaceSymlink(task, inoGen.NextIno(), \"pid\"),\n\"user\": newNamespaceSymlink(task, inoGen.NextIno(), \"user\"),\n}),\n+ \"oom_score\": newTaskOwnedFile(task, inoGen.NextIno(), 0444, newStaticFile(\"0\\n\")),\n+ \"oom_score_adj\": newTaskOwnedFile(task, inoGen.NextIno(), 0644, &oomScoreAdj{task: task}),\n\"smaps\": newTaskOwnedFile(task, inoGen.NextIno(), 0444, &smapsData{task: task}),\n\"stat\": newTaskOwnedFile(task, inoGen.NextIno(), 0444, &taskStatData{task: task, pidns: pidns, tgstats: isThreadGroup}),\n\"statm\": newTaskOwnedFile(task, inoGen.NextIno(), 0444, &statmData{task: task}),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/task_files.go",
"new_path": "pkg/sentry/fsimpl/proc/task_files.go",
"diff": "@@ -525,3 +525,46 @@ func (i *ioData) Generate(ctx context.Context, buf *bytes.Buffer) error {\nfmt.Fprintf(buf, \"cancelled_write_bytes: %d\\n\", io.BytesWriteCancelled)\nreturn nil\n}\n+\n+// oomScoreAdj is a stub of the /proc/<pid>/oom_score_adj file.\n+//\n+// +stateify savable\n+type oomScoreAdj struct {\n+ kernfs.DynamicBytesFile\n+\n+ task *kernel.Task\n+}\n+\n+var _ vfs.WritableDynamicBytesSource = (*oomScoreAdj)(nil)\n+\n+// Generate implements vfs.DynamicBytesSource.Generate.\n+func (o *oomScoreAdj) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+ adj, err := o.task.OOMScoreAdj()\n+ if err != nil {\n+ return err\n+ }\n+ fmt.Fprintf(buf, \"%d\\n\", adj)\n+ return nil\n+}\n+\n+// Write implements vfs.WritableDynamicBytesSource.Write.\n+func (o *oomScoreAdj) Write(ctx context.Context, src usermem.IOSequence, offset int64) (int64, error) {\n+ if src.NumBytes() == 0 {\n+ return 0, nil\n+ }\n+\n+ // Limit input size so as not to impact performance if input size is large.\n+ src = src.TakeFirst(usermem.PageSize - 1)\n+\n+ var v int32\n+ n, err := usermem.CopyInt32StringInVec(ctx, src.IO, src.Addrs, &v, src.Opts)\n+ if err != nil {\n+ return 0, err\n+ }\n+\n+ if err := o.task.SetOOMScoreAdj(v); err != nil {\n+ return 0, err\n+ }\n+\n+ return n, nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/tasks_test.go",
"new_path": "pkg/sentry/fsimpl/proc/tasks_test.go",
"diff": "@@ -72,6 +72,8 @@ var (\n\"io\": linux.DT_REG,\n\"maps\": linux.DT_REG,\n\"ns\": linux.DT_DIR,\n+ \"oom_score\": linux.DT_REG,\n+ \"oom_score_adj\": linux.DT_REG,\n\"smaps\": linux.DT_REG,\n\"stat\": linux.DT_REG,\n\"statm\": linux.DT_REG,\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task.go",
"new_path": "pkg/sentry/kernel/task.go",
"diff": "@@ -37,6 +37,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/usage\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/sync\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n@@ -554,6 +555,13 @@ type Task struct {\n//\n// startTime is protected by mu.\nstartTime ktime.Time\n+\n+ // oomScoreAdj is the task's OOM score adjustment. This is currently not\n+ // used but is maintained for consistency.\n+ // TODO(gvisor.dev/issue/1967)\n+ //\n+ // oomScoreAdj is protected by mu, and is owned by the task goroutine.\n+ oomScoreAdj int32\n}\nfunc (t *Task) savePtraceTracer() *Task {\n@@ -847,3 +855,28 @@ func (t *Task) AbstractSockets() *AbstractSocketNamespace {\nfunc (t *Task) ContainerID() string {\nreturn t.containerID\n}\n+\n+// OOMScoreAdj gets the task's OOM score adjustment.\n+func (t *Task) OOMScoreAdj() (int32, error) {\n+ t.mu.Lock()\n+ defer t.mu.Unlock()\n+ if t.ExitState() == TaskExitDead {\n+ return 0, syserror.ESRCH\n+ }\n+ return t.oomScoreAdj, nil\n+}\n+\n+// SetOOMScoreAdj sets the task's OOM score adjustment. The value should be\n+// between -1000 and 1000 inclusive.\n+func (t *Task) SetOOMScoreAdj(adj int32) error {\n+ t.mu.Lock()\n+ defer t.mu.Unlock()\n+ if t.ExitState() == TaskExitDead {\n+ return syserror.ESRCH\n+ }\n+ if adj > 1000 || adj < -1000 {\n+ return syserror.EINVAL\n+ }\n+ t.oomScoreAdj = adj\n+ return nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_clone.go",
"new_path": "pkg/sentry/kernel/task_clone.go",
"diff": "@@ -264,6 +264,11 @@ func (t *Task) Clone(opts *CloneOptions) (ThreadID, *SyscallControl, error) {\nrseqSignature = t.rseqSignature\n}\n+ adj, err := t.OOMScoreAdj()\n+ if err != nil {\n+ return 0, nil, err\n+ }\n+\ncfg := &TaskConfig{\nKernel: t.k,\nThreadGroup: tg,\n@@ -282,6 +287,7 @@ func (t *Task) Clone(opts *CloneOptions) (ThreadID, *SyscallControl, error) {\nRSeqAddr: rseqAddr,\nRSeqSignature: rseqSignature,\nContainerID: t.ContainerID(),\n+ OOMScoreAdj: adj,\n}\nif opts.NewThreadGroup {\ncfg.Parent = t\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_start.go",
"new_path": "pkg/sentry/kernel/task_start.go",
"diff": "@@ -93,6 +93,9 @@ type TaskConfig struct {\n// ContainerID is the container the new task belongs to.\nContainerID string\n+\n+ // oomScoreAdj is the task's OOM score adjustment.\n+ OOMScoreAdj int32\n}\n// NewTask creates a new task defined by cfg.\n@@ -143,6 +146,7 @@ func (ts *TaskSet) newTask(cfg *TaskConfig) (*Task, error) {\nrseqSignature: cfg.RSeqSignature,\nfutexWaiter: futex.NewWaiter(),\ncontainerID: cfg.ContainerID,\n+ oomScoreAdj: cfg.OOMScoreAdj,\n}\nt.creds.Store(cfg.Credentials)\nt.endStopCond.L = &t.tg.signalHandlers.mu\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -318,10 +318,14 @@ syscall_test(\ntest = \"//test/syscalls/linux:proc_test\",\n)\n-syscall_test(test = \"//test/syscalls/linux:proc_pid_uid_gid_map_test\")\n-\nsyscall_test(test = \"//test/syscalls/linux:proc_net_test\")\n+syscall_test(test = \"//test/syscalls/linux:proc_pid_oomscore_test\")\n+\n+syscall_test(test = \"//test/syscalls/linux:proc_pid_smaps_test\")\n+\n+syscall_test(test = \"//test/syscalls/linux:proc_pid_uid_gid_map_test\")\n+\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:pselect_test\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -1631,6 +1631,19 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"proc_pid_oomscore_test\",\n+ testonly = 1,\n+ srcs = [\"proc_pid_oomscore.cc\"],\n+ linkstatic = 1,\n+ deps = [\n+ \"//test/util:fs_util\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ \"@com_google_absl//absl/strings\",\n+ ],\n+)\n+\ncc_binary(\nname = \"proc_pid_smaps_test\",\ntestonly = 1,\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/proc.cc",
"new_path": "test/syscalls/linux/proc.cc",
"diff": "@@ -1431,6 +1431,12 @@ TEST(ProcPidFile, SubprocessRunning) {\nEXPECT_THAT(ReadWhileRunning(\"uid_map\", buf, sizeof(buf)),\nSyscallSucceedsWithValue(sizeof(buf)));\n+\n+ EXPECT_THAT(ReadWhileRunning(\"oom_score\", buf, sizeof(buf)),\n+ SyscallSucceedsWithValue(sizeof(buf)));\n+\n+ EXPECT_THAT(ReadWhileRunning(\"oom_score_adj\", buf, sizeof(buf)),\n+ SyscallSucceedsWithValue(sizeof(buf)));\n}\n// Test whether /proc/PID/ files can be read for a zombie process.\n@@ -1466,6 +1472,12 @@ TEST(ProcPidFile, SubprocessZombie) {\nEXPECT_THAT(ReadWhileZombied(\"uid_map\", buf, sizeof(buf)),\nSyscallSucceedsWithValue(sizeof(buf)));\n+ EXPECT_THAT(ReadWhileZombied(\"oom_score\", buf, sizeof(buf)),\n+ SyscallSucceedsWithValue(sizeof(buf)));\n+\n+ EXPECT_THAT(ReadWhileZombied(\"oom_score_adj\", buf, sizeof(buf)),\n+ SyscallSucceedsWithValue(sizeof(buf)));\n+\n// FIXME(gvisor.dev/issue/164): Inconsistent behavior between gVisor and linux\n// on proc files.\n//\n@@ -1527,6 +1539,15 @@ TEST(ProcPidFile, SubprocessExited) {\nEXPECT_THAT(ReadWhileExited(\"uid_map\", buf, sizeof(buf)),\nSyscallSucceedsWithValue(sizeof(buf)));\n+\n+ if (!IsRunningOnGvisor()) {\n+ // FIXME(gvisor.dev/issue/164): Succeeds on gVisor.\n+ EXPECT_THAT(ReadWhileExited(\"oom_score\", buf, sizeof(buf)),\n+ SyscallFailsWithErrno(ESRCH));\n+ }\n+\n+ EXPECT_THAT(ReadWhileExited(\"oom_score_adj\", buf, sizeof(buf)),\n+ SyscallFailsWithErrno(ESRCH));\n}\nPosixError DirContainsImpl(absl::string_view path,\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/proc_pid_oomscore.cc",
"diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <errno.h>\n+\n+#include <exception>\n+#include <iostream>\n+#include <string>\n+\n+#include \"test/util/fs_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+PosixErrorOr<int> ReadProcNumber(std::string path) {\n+ ASSIGN_OR_RETURN_ERRNO(std::string contents, GetContents(path));\n+ EXPECT_EQ(contents[contents.length() - 1], '\\n');\n+\n+ int num;\n+ if (!absl::SimpleAtoi(contents, &num)) {\n+ return PosixError(EINVAL, \"invalid value: \" + contents);\n+ }\n+\n+ return num;\n+}\n+\n+TEST(ProcPidOomscoreTest, BasicRead) {\n+ auto const oom_score =\n+ ASSERT_NO_ERRNO_AND_VALUE(ReadProcNumber(\"/proc/self/oom_score\"));\n+ EXPECT_LE(oom_score, 1000);\n+ EXPECT_GE(oom_score, -1000);\n+}\n+\n+TEST(ProcPidOomscoreAdjTest, BasicRead) {\n+ auto const oom_score =\n+ ASSERT_NO_ERRNO_AND_VALUE(ReadProcNumber(\"/proc/self/oom_score_adj\"));\n+\n+ // oom_score_adj defaults to 0.\n+ EXPECT_EQ(oom_score, 0);\n+}\n+\n+TEST(ProcPidOomscoreAdjTest, BasicWrite) {\n+ constexpr int test_value = 7;\n+ FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(\"/proc/self/oom_score_adj\", O_WRONLY));\n+ ASSERT_THAT(\n+ RetryEINTR(write)(fd.get(), std::to_string(test_value).c_str(), 1),\n+ SyscallSucceeds());\n+\n+ auto const oom_score =\n+ ASSERT_NO_ERRNO_AND_VALUE(ReadProcNumber(\"/proc/self/oom_score_adj\"));\n+ EXPECT_EQ(oom_score, test_value);\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Stub oom_score_adj and oom_score.
Adds an oom_score_adj and oom_score proc file stub. oom_score_adj accepts
writes of values -1000 to 1000 and persists the value with the task. New tasks
inherit the parent's oom_score_adj.
oom_score is a read-only stub that always returns the value '0'.
Issue #202
PiperOrigin-RevId: 299245355 |
260,004 | 06.03.2020 08:01:45 | 28,800 | d6f5e71df2c8ff3d763cba703786af68af1f9841 | Get strings for stack.DHCPv6ConfigurationFromNDPRA
Useful for logs to print the string representation of the value
instead of the integer value. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/BUILD",
"new_path": "pkg/tcpip/stack/BUILD",
"diff": "@@ -18,6 +18,7 @@ go_template_instance(\ngo_library(\nname = \"stack\",\nsrcs = [\n+ \"dhcpv6configurationfromndpra_string.go\",\n\"icmp_rate_limit.go\",\n\"linkaddrcache.go\",\n\"linkaddrentry_list.go\",\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/tcpip/stack/dhcpv6configurationfromndpra_string.go",
"diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// Code generated by \"stringer -type=DHCPv6ConfigurationFromNDPRA\"; DO NOT EDIT.\n+\n+package stack\n+\n+import \"strconv\"\n+\n+func _() {\n+ // An \"invalid array index\" compiler error signifies that the constant values have changed.\n+ // Re-run the stringer command to generate them again.\n+ var x [1]struct{}\n+ _ = x[DHCPv6NoConfiguration-0]\n+ _ = x[DHCPv6ManagedAddress-1]\n+ _ = x[DHCPv6OtherConfigurations-2]\n+}\n+\n+const _DHCPv6ConfigurationFromNDPRA_name = \"DHCPv6NoConfigurationDHCPv6ManagedAddressDHCPv6OtherConfigurations\"\n+\n+var _DHCPv6ConfigurationFromNDPRA_index = [...]uint8{0, 21, 41, 66}\n+\n+func (i DHCPv6ConfigurationFromNDPRA) String() string {\n+ if i < 0 || i >= DHCPv6ConfigurationFromNDPRA(len(_DHCPv6ConfigurationFromNDPRA_index)-1) {\n+ return \"DHCPv6ConfigurationFromNDPRA(\" + strconv.FormatInt(int64(i), 10) + \")\"\n+ }\n+ return _DHCPv6ConfigurationFromNDPRA_name[_DHCPv6ConfigurationFromNDPRA_index[i]:_DHCPv6ConfigurationFromNDPRA_index[i+1]]\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Get strings for stack.DHCPv6ConfigurationFromNDPRA
Useful for logs to print the string representation of the value
instead of the integer value.
PiperOrigin-RevId: 299356847 |
259,896 | 06.03.2020 09:25:32 | 28,800 | 1e8c0bcedb265d3149e5d2ab1181628d013539c4 | Add nat table support for iptables. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/iptables/targets.go",
"new_path": "pkg/tcpip/iptables/targets.go",
"diff": "@@ -69,7 +69,7 @@ func (ReturnTarget) Action(tcpip.PacketBuffer) (RuleVerdict, int) {\n// Min and Max values for IP and Ports in the struct indicate the range of\n// values which can be used to redirect.\ntype RedirectTarget struct {\n- // TODO(gvisor.dev/issue/170): Other flags need to be aded after\n+ // TODO(gvisor.dev/issue/170): Other flags need to be added after\n// we support them.\n// RangeProtoSpecified flag indicates single port is specified to\n// redirect.\n@@ -98,7 +98,7 @@ func (rt RedirectTarget) Action(pkt tcpip.PacketBuffer) (RuleVerdict, int) {\n// Set network header.\nheaderView := newPkt.Data.First()\nnetHeader := header.IPv4(headerView)\n- newPkt.NetworkHeader = headerView[:netHeader.HeaderLength()]\n+ newPkt.NetworkHeader = headerView[:header.IPv4MinimumSize]\nhlen := int(netHeader.HeaderLength())\ntlen := int(netHeader.TotalLength())\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add nat table support for iptables. |
259,972 | 06.03.2020 11:22:55 | 28,800 | 20170d4fd5c26def584664762f4e639f0b43ff6e | Move packetdrill tests to open-source | [
{
"change_type": "MODIFY",
"old_path": "test/packetdrill/BUILD",
"new_path": "test/packetdrill/BUILD",
"diff": "-load(\"defs.bzl\", \"packetdrill_test\")\n+load(\"defs.bzl\", \"packetdrill_linux_test\", \"packetdrill_netstack_test\", \"packetdrill_test\")\npackage(licenses = [\"notice\"])\npacketdrill_test(\n- name = \"fin_wait2_timeout\",\n+ name = \"packetdrill_sanity_test\",\n+ scripts = [\"sanity_test.pkt\"],\n+)\n+\n+packetdrill_test(\n+ name = \"accept_ack_drop_test\",\n+ scripts = [\"accept_ack_drop.pkt\"],\n+)\n+\n+packetdrill_test(\n+ name = \"fin_wait2_timeout_test\",\nscripts = [\"fin_wait2_timeout.pkt\"],\n)\n+\n+packetdrill_linux_test(\n+ name = \"tcp_user_timeout_test_linux_test\",\n+ scripts = [\"linux/tcp_user_timeout.pkt\"],\n+)\n+\n+packetdrill_netstack_test(\n+ name = \"tcp_user_timeout_test_netstack_test\",\n+ scripts = [\"netstack/tcp_user_timeout.pkt\"],\n+)\n+\n+packetdrill_test(\n+ name = \"listen_close_before_handshake_complete_test\",\n+ scripts = [\"listen_close_before_handshake_complete.pkt\"],\n+)\n+\n+packetdrill_test(\n+ name = \"no_rst_to_rst_test\",\n+ scripts = [\"no_rst_to_rst.pkt\"],\n+)\n+\n+packetdrill_test(\n+ name = \"tcp_defer_accept_test\",\n+ scripts = [\"tcp_defer_accept.pkt\"],\n+)\n+\n+packetdrill_test(\n+ name = \"tcp_defer_accept_timeout_test\",\n+ scripts = [\"tcp_defer_accept_timeout.pkt\"],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/packetdrill/accept_ack_drop.pkt",
"diff": "+// Test that the accept works if the final ACK is dropped and an ack with data\n+// follows the dropped ack.\n+\n+0 socket(..., SOCK_STREAM, IPPROTO_TCP) = 3\n++0 bind(3, ..., ...) = 0\n+\n+// Set backlog to 1 so that we can easily test.\n++0 listen(3, 1) = 0\n+\n+// Establish a connection without timestamps.\n++0.0 < S 0:0(0) win 32792 <mss 1460,sackOK,nop,nop,nop,wscale 7>\n++0.0 > S. 0:0(0) ack 1 <...>\n+\n++0.0 < . 1:5(4) ack 1 win 257\n++0.0 > . 1:1(0) ack 5 <...>\n+\n+// This should cause connection to transition to connected state.\n++0.000 accept(3, ..., ...) = 4\n++0.000 fcntl(4, F_SETFL, O_RDWR|O_NONBLOCK) = 0\n+\n+// Now read the data and we should get 4 bytes.\n++0.000 read(4,..., 4) = 4\n++0.000 close(4) = 0\n+\n++0.0 > F. 1:1(0) ack 5 <...>\n++0.0 < F. 5:5(0) ack 2 win 257\n++0.01 > . 2:2(0) ack 6 <...>\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetdrill/defs.bzl",
"new_path": "test/packetdrill/defs.bzl",
"diff": "@@ -66,7 +66,7 @@ def packetdrill_linux_test(name, **kwargs):\nif \"tags\" not in kwargs:\nkwargs[\"tags\"] = _PACKETDRILL_TAGS\n_packetdrill_test(\n- name = name + \"_linux_test\",\n+ name = name,\nflags = [\"--dut_platform\", \"linux\"],\n**kwargs\n)\n@@ -75,13 +75,13 @@ def packetdrill_netstack_test(name, **kwargs):\nif \"tags\" not in kwargs:\nkwargs[\"tags\"] = _PACKETDRILL_TAGS\n_packetdrill_test(\n- name = name + \"_netstack_test\",\n+ name = name,\n# This is the default runtime unless\n# \"--test_arg=--runtime=OTHER_RUNTIME\" is used to override the value.\nflags = [\"--dut_platform\", \"netstack\", \"--runtime\", \"runsc-d\"],\n**kwargs\n)\n-def packetdrill_test(**kwargs):\n- packetdrill_linux_test(**kwargs)\n- packetdrill_netstack_test(**kwargs)\n+def packetdrill_test(name, **kwargs):\n+ packetdrill_linux_test(name + \"_linux_test\", **kwargs)\n+ packetdrill_netstack_test(name + \"_netstack_test\", **kwargs)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/packetdrill/linux/tcp_user_timeout.pkt",
"diff": "+// Test that a socket w/ TCP_USER_TIMEOUT set aborts the connection\n+// if there is pending unacked data after the user specified timeout.\n+\n+0 socket(..., SOCK_STREAM, IPPROTO_TCP) = 3\n++0 bind(3, ..., ...) = 0\n+\n++0 listen(3, 1) = 0\n+\n+// Establish a connection without timestamps.\n++0 < S 0:0(0) win 32792 <mss 1460,sackOK,nop,nop,nop,wscale 7>\n++0 > S. 0:0(0) ack 1 <...>\n++0.1 < . 1:1(0) ack 1 win 32792\n+\n++0.100 accept(3, ..., ...) = 4\n+\n+// Okay, we received nothing, and decide to close this idle socket.\n+// We set TCP_USER_TIMEOUT to 3 seconds because really it is not worth\n+// trying hard to cleanly close this flow, at the price of keeping\n+// a TCP structure in kernel for about 1 minute!\n++2 setsockopt(4, SOL_TCP, TCP_USER_TIMEOUT, [3000], 4) = 0\n+\n+// The write/ack is required mainly for netstack as netstack does\n+// not update its RTO during the handshake.\n++0 write(4, ..., 100) = 100\n++0 > P. 1:101(100) ack 1 <...>\n++0 < . 1:1(0) ack 101 win 32792\n+\n++0 close(4) = 0\n+\n++0 > F. 101:101(0) ack 1 <...>\n++.3~+.400 > F. 101:101(0) ack 1 <...>\n++.3~+.400 > F. 101:101(0) ack 1 <...>\n++.6~+.800 > F. 101:101(0) ack 1 <...>\n++1.2~+1.300 > F. 101:101(0) ack 1 <...>\n+\n+// We finally receive something from the peer, but it is way too late\n+// Our socket vanished because TCP_USER_TIMEOUT was really small.\n++.1 < . 1:2(1) ack 102 win 32792\n++0 > R 102:102(0) win 0\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/packetdrill/listen_close_before_handshake_complete.pkt",
"diff": "+// Test that closing a listening socket closes any connections in SYN-RCVD\n+// state and any packets bound for these connections generate a RESET.\n+\n+0 socket(..., SOCK_STREAM, IPPROTO_TCP) = 3\n++0 bind(3, ..., ...) = 0\n+\n+// Set backlog to 1 so that we can easily test.\n++0 listen(3, 1) = 0\n+\n+// Establish a connection without timestamps.\n++0 < S 0:0(0) win 32792 <mss 1460,sackOK,nop,nop,nop,wscale 7>\n++0 > S. 0:0(0) ack 1 <...>\n+\n++0.100 close(3) = 0\n++0.1 < P. 1:1(0) ack 1 win 257\n+\n+// Linux generates a reset with no ack number/bit set. This is contradictory to\n+// what is specified in Rule 1 under Reset Generation in\n+// https://tools.ietf.org/html/rfc793#section-3.4.\n+// \"1. If the connection does not exist (CLOSED) then a reset is sent\n+// in response to any incoming segment except another reset. In\n+// particular, SYNs addressed to a non-existent connection are rejected\n+// by this means.\n+//\n+// If the incoming segment has an ACK field, the reset takes its\n+// sequence number from the ACK field of the segment, otherwise the\n+// reset has sequence number zero and the ACK field is set to the sum\n+// of the sequence number and segment length of the incoming segment.\n+// The connection remains in the CLOSED state.\"\n+\n++0.0 > R 1:1(0) win 0\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/packetdrill/netstack/tcp_user_timeout.pkt",
"diff": "+// Test that a socket w/ TCP_USER_TIMEOUT set aborts the connection\n+// if there is pending unacked data after the user specified timeout.\n+\n+0 socket(..., SOCK_STREAM, IPPROTO_TCP) = 3\n++0 bind(3, ..., ...) = 0\n+\n++0 listen(3, 1) = 0\n+\n+// Establish a connection without timestamps.\n++0 < S 0:0(0) win 32792 <mss 1460,sackOK,nop,nop,nop,wscale 7>\n++0 > S. 0:0(0) ack 1 <...>\n++0.1 < . 1:1(0) ack 1 win 32792\n+\n++0.100 accept(3, ..., ...) = 4\n+\n+// Okay, we received nothing, and decide to close this idle socket.\n+// We set TCP_USER_TIMEOUT to 3 seconds because really it is not worth\n+// trying hard to cleanly close this flow, at the price of keeping\n+// a TCP structure in kernel for about 1 minute!\n++2 setsockopt(4, SOL_TCP, TCP_USER_TIMEOUT, [3000], 4) = 0\n+\n+// The write/ack is required mainly for netstack as netstack does\n+// not update its RTO during the handshake.\n++0 write(4, ..., 100) = 100\n++0 > P. 1:101(100) ack 1 <...>\n++0 < . 1:1(0) ack 101 win 32792\n+\n++0 close(4) = 0\n+\n++0 > F. 101:101(0) ack 1 <...>\n++.2~+.300 > F. 101:101(0) ack 1 <...>\n++.4~+.500 > F. 101:101(0) ack 1 <...>\n++.8~+.900 > F. 101:101(0) ack 1 <...>\n+\n+// We finally receive something from the peer, but it is way too late\n+// Our socket vanished because TCP_USER_TIMEOUT was really small.\n++1.61 < . 1:2(1) ack 102 win 32792\n++0 > R 102:102(0) win 0\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/packetdrill/no_rst_to_rst.pkt",
"diff": "+// Test a RST is not generated in response to a RST and a RST is correctly\n+// generated when an accepted endpoint is RST due to an incoming RST.\n+\n+0 socket(..., SOCK_STREAM, IPPROTO_TCP) = 3\n++0 bind(3, ..., ...) = 0\n+\n++0 listen(3, 1) = 0\n+\n+// Establish a connection without timestamps.\n++0 < S 0:0(0) win 32792 <mss 1460,sackOK,nop,nop,nop,wscale 7>\n++0 > S. 0:0(0) ack 1 <...>\n++0 < P. 1:1(0) ack 1 win 257\n+\n++0.100 accept(3, ..., ...) = 4\n+\n++0.200 < R 1:1(0) win 0\n+\n++0.300 read(4,..., 4) = -1 ECONNRESET (Connection Reset by Peer)\n+\n++0.00 < . 1:1(0) ack 1 win 257\n+\n+// Linux generates a reset with no ack number/bit set. This is contradictory to\n+// what is specified in Rule 1 under Reset Generation in\n+// https://tools.ietf.org/html/rfc793#section-3.4.\n+// \"1. If the connection does not exist (CLOSED) then a reset is sent\n+// in response to any incoming segment except another reset. In\n+// particular, SYNs addressed to a non-existent connection are rejected\n+// by this means.\n+//\n+// If the incoming segment has an ACK field, the reset takes its\n+// sequence number from the ACK field of the segment, otherwise the\n+// reset has sequence number zero and the ACK field is set to the sum\n+// of the sequence number and segment length of the incoming segment.\n+// The connection remains in the CLOSED state.\"\n+\n++0.00 > R 1:1(0) win 0\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/packetdrill/reset_for_ack_when_no_syn_cookies_in_use.pkt",
"diff": "+// Test that a listening socket generates a RST when it receives an\n+// ACK and syn cookies are not in use.\n+\n+0 socket(..., SOCK_STREAM, IPPROTO_TCP) = 3\n++0 bind(3, ..., ...) = 0\n+\n++0 listen(3, 1) = 0\n++0.1 < . 1:1(0) ack 1 win 32792\n++0 > R 1:1(0) ack 0 win 0\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/packetdrill/sanity_test.pkt",
"diff": "+// Basic sanity test. One system call.\n+//\n+// All of the plumbing has to be working however, and the packetdrill wire\n+// client needs to be able to connect to the wire server and send the script,\n+// probe local interfaces, run through the test w/ timings, etc.\n+\n+0.000 socket(..., SOCK_STREAM, IPPROTO_TCP) = 3\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/packetdrill/tcp_defer_accept.pkt",
"diff": "+// Test that a bare ACK does not complete a connection when TCP_DEFER_ACCEPT\n+// timeout is not hit but an ACK w/ data does complete and deliver the\n+// connection to the accept queue.\n+\n+0 socket(..., SOCK_STREAM, IPPROTO_TCP) = 3\n++0 setsockopt(3, SOL_TCP, TCP_DEFER_ACCEPT, [5], 4) = 0\n++0.000 fcntl(3, F_SETFL, O_RDWR|O_NONBLOCK) = 0\n++0 bind(3, ..., ...) = 0\n+\n+// Set backlog to 1 so that we can easily test.\n++0 listen(3, 1) = 0\n+\n+// Establish a connection without timestamps.\n++0.0 < S 0:0(0) win 32792 <mss 1460,sackOK,nop,nop,nop,wscale 7>\n++0.0 > S. 0:0(0) ack 1 <...>\n+\n+// Send a bare ACK this should not complete the connection as we\n+// set the TCP_DEFER_ACCEPT above.\n++0.0 < . 1:1(0) ack 1 win 257\n+\n+// The bare ACK should be dropped and no connection should be delivered\n+// to the accept queue.\n++0.100 accept(3, ..., ...) = -1 EWOULDBLOCK (operation would block)\n+\n+// Send another bare ACK and it should still fail we set TCP_DEFER_ACCEPT\n+// to 5 seconds above.\n++2.5 < . 1:1(0) ack 1 win 257\n++0.100 accept(3, ..., ...) = -1 EWOULDBLOCK (operation would block)\n+\n+// set accept socket back to blocking.\n++0.000 fcntl(3, F_SETFL, O_RDWR) = 0\n+\n+// Now send an ACK w/ data. This should complete the connection\n+// and deliver the socket to the accept queue.\n++0.1 < . 1:5(4) ack 1 win 257\n++0.0 > . 1:1(0) ack 5 <...>\n+\n+// This should cause connection to transition to connected state.\n++0.000 accept(3, ..., ...) = 4\n++0.000 fcntl(4, F_SETFL, O_RDWR|O_NONBLOCK) = 0\n+\n+// Now read the data and we should get 4 bytes.\n++0.000 read(4,..., 4) = 4\n++0.000 close(4) = 0\n+\n++0.0 > F. 1:1(0) ack 5 <...>\n++0.0 < F. 5:5(0) ack 2 win 257\n++0.01 > . 2:2(0) ack 6 <...>\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/packetdrill/tcp_defer_accept_timeout.pkt",
"diff": "+// Test that a bare ACK is accepted after TCP_DEFER_ACCEPT timeout\n+// is hit and a connection is delivered.\n+\n+0 socket(..., SOCK_STREAM, IPPROTO_TCP) = 3\n++0 setsockopt(3, SOL_TCP, TCP_DEFER_ACCEPT, [3], 4) = 0\n++0.000 fcntl(3, F_SETFL, O_RDWR|O_NONBLOCK) = 0\n++0 bind(3, ..., ...) = 0\n+\n+// Set backlog to 1 so that we can easily test.\n++0 listen(3, 1) = 0\n+\n+// Establish a connection without timestamps.\n++0.0 < S 0:0(0) win 32792 <mss 1460,sackOK,nop,nop,nop,wscale 7>\n++0.0 > S. 0:0(0) ack 1 <...>\n+\n+// Send a bare ACK this should not complete the connection as we\n+// set the TCP_DEFER_ACCEPT above.\n++0.0 < . 1:1(0) ack 1 win 257\n+\n+// The bare ACK should be dropped and no connection should be delivered\n+// to the accept queue.\n++0.100 accept(3, ..., ...) = -1 EWOULDBLOCK (operation would block)\n+\n+// Send another bare ACK and it should still fail we set TCP_DEFER_ACCEPT\n+// to 5 seconds above.\n++2.5 < . 1:1(0) ack 1 win 257\n++0.100 accept(3, ..., ...) = -1 EWOULDBLOCK (operation would block)\n+\n+// set accept socket back to blocking.\n++0.000 fcntl(3, F_SETFL, O_RDWR) = 0\n+\n+// We should see one more retransmit of the SYN-ACK as a last ditch\n+// attempt when TCP_DEFER_ACCEPT timeout is hit to trigger another\n+// ACK or a packet with data.\n++.35~+2.35 > S. 0:0(0) ack 1 <...>\n+\n+// Now send another bare ACK after TCP_DEFER_ACCEPT time has been passed.\n++0.0 < . 1:1(0) ack 1 win 257\n+\n+// The ACK above should cause connection to transition to connected state.\n++0.000 accept(3, ..., ...) = 4\n++0.000 fcntl(4, F_SETFL, O_RDWR|O_NONBLOCK) = 0\n+\n++0.000 close(4) = 0\n+\n++0.0 > F. 1:1(0) ack 1 <...>\n++0.0 < F. 1:1(0) ack 2 win 257\n++0.01 > . 2:2(0) ack 2 <...>\n"
}
] | Go | Apache License 2.0 | google/gvisor | Move packetdrill tests to open-source
PiperOrigin-RevId: 299396286 |
260,004 | 06.03.2020 11:32:13 | 28,800 | f50d9a31e9e734a02e0191f6bc91b387bb21f9ab | Specify the source of outgoing NDP RS
If the NIC has a valid IPv6 address assigned, use it as the
source address for outgoing NDP Router Solicitation packets.
Test: stack_test.TestRouterSolicitation | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/checker/checker.go",
"new_path": "pkg/tcpip/checker/checker.go",
"diff": "@@ -785,26 +785,23 @@ func NDPNSTargetAddress(want tcpip.Address) TransportChecker {\n}\n}\n-// NDPNSOptions creates a checker that checks that the packet contains the\n-// provided NDP options within an NDP Neighbor Solicitation message.\n-//\n-// The returned TransportChecker assumes that a valid ICMPv6 is passed to it\n-// containing a valid NDPNS message as far as the size is concerned.\n-func NDPNSOptions(opts []header.NDPOption) TransportChecker {\n- return func(t *testing.T, h header.Transport) {\n+// ndpOptions checks that optsBuf only contains opts.\n+func ndpOptions(t *testing.T, optsBuf header.NDPOptions, opts []header.NDPOption) {\nt.Helper()\n- icmp := h.(header.ICMPv6)\n- ns := header.NDPNeighborSolicit(icmp.NDPPayload())\n- it, err := ns.Options().Iter(true)\n+ it, err := optsBuf.Iter(true)\nif err != nil {\n- t.Errorf(\"opts.Iter(true): %s\", err)\n+ t.Errorf(\"optsBuf.Iter(true): %s\", err)\nreturn\n}\ni := 0\nfor {\n- opt, done, _ := it.Next()\n+ opt, done, err := it.Next()\n+ if err != nil {\n+ // This should never happen as Iter(true) above did not return an error.\n+ t.Fatalf(\"unexpected error when iterating over NDP options: %s\", err)\n+ }\nif done {\nbreak\n}\n@@ -823,7 +820,7 @@ func NDPNSOptions(opts []header.NDPOption) TransportChecker {\nt.Errorf(\"got EthernetAddress() = %s at index %d, want = %s\", got, i, want)\n}\ndefault:\n- panic(\"not implemented\")\n+ t.Fatalf(\"checker not implemented for expected NDP option: %T\", wantOpt)\n}\ni++\n@@ -833,10 +830,43 @@ func NDPNSOptions(opts []header.NDPOption) TransportChecker {\nt.Errorf(\"missing options: %s\", missing)\n}\n}\n+\n+// NDPNSOptions creates a checker that checks that the packet contains the\n+// provided NDP options within an NDP Neighbor Solicitation message.\n+//\n+// The returned TransportChecker assumes that a valid ICMPv6 is passed to it\n+// containing a valid NDPNS message as far as the size is concerned.\n+func NDPNSOptions(opts []header.NDPOption) TransportChecker {\n+ return func(t *testing.T, h header.Transport) {\n+ t.Helper()\n+\n+ icmp := h.(header.ICMPv6)\n+ ns := header.NDPNeighborSolicit(icmp.NDPPayload())\n+ ndpOptions(t, ns.Options(), opts)\n+ }\n}\n// NDPRS creates a checker that checks that the packet contains a valid NDP\n// Router Solicitation message (as per the raw wire format).\n-func NDPRS() NetworkChecker {\n- return NDP(header.ICMPv6RouterSolicit, header.NDPRSMinimumSize)\n+//\n+// checkers may assume that a valid ICMPv6 is passed to it containing a valid\n+// NDPRS as far as the size of the message is concerned. The values within the\n+// message are up to checkers to validate.\n+func NDPRS(checkers ...TransportChecker) NetworkChecker {\n+ return NDP(header.ICMPv6RouterSolicit, header.NDPRSMinimumSize, checkers...)\n+}\n+\n+// NDPRSOptions creates a checker that checks that the packet contains the\n+// provided NDP options within an NDP Router Solicitation message.\n+//\n+// The returned TransportChecker assumes that a valid ICMPv6 is passed to it\n+// containing a valid NDPRS message as far as the size is concerned.\n+func NDPRSOptions(opts []header.NDPOption) TransportChecker {\n+ return func(t *testing.T, h header.Transport) {\n+ t.Helper()\n+\n+ icmp := h.(header.ICMPv6)\n+ rs := header.NDPRouterSolicit(icmp.NDPPayload())\n+ ndpOptions(t, rs.Options(), opts)\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/ndp.go",
"new_path": "pkg/tcpip/stack/ndp.go",
"diff": "@@ -1220,9 +1220,15 @@ func (ndp *ndpState) startSolicitingRouters() {\n}\nndp.rtrSolicitTimer = time.AfterFunc(delay, func() {\n- // Send an RS message with the unspecified source address.\n- ref := ndp.nic.getRefOrCreateTemp(header.IPv6ProtocolNumber, header.IPv6Any, NeverPrimaryEndpoint, forceSpoofing)\n- r := makeRoute(header.IPv6ProtocolNumber, header.IPv6Any, header.IPv6AllRoutersMulticastAddress, ndp.nic.linkEP.LinkAddress(), ref, false, false)\n+ // As per RFC 4861 section 4.1, the source of the RS is an address assigned\n+ // to the sending interface, or the unspecified address if no address is\n+ // assigned to the sending interface.\n+ ref := ndp.nic.primaryIPv6Endpoint(header.IPv6AllRoutersMulticastAddress)\n+ if ref == nil {\n+ ref = ndp.nic.getRefOrCreateTemp(header.IPv6ProtocolNumber, header.IPv6Any, NeverPrimaryEndpoint, forceSpoofing)\n+ }\n+ localAddr := ref.ep.ID().LocalAddress\n+ r := makeRoute(header.IPv6ProtocolNumber, localAddr, header.IPv6AllRoutersMulticastAddress, ndp.nic.linkEP.LinkAddress(), ref, false, false)\ndefer r.Release()\n// Route should resolve immediately since\n@@ -1234,10 +1240,25 @@ func (ndp *ndpState) startSolicitingRouters() {\nlog.Fatalf(\"ndp: route resolution not immediate for route to send NDP RS (%s -> %s on NIC(%d))\", header.IPv6Any, header.IPv6AllRoutersMulticastAddress, ndp.nic.ID())\n}\n- payloadSize := header.ICMPv6HeaderSize + header.NDPRSMinimumSize\n+ // As per RFC 4861 section 4.1, an NDP RS SHOULD include the source\n+ // link-layer address option if the source address of the NDP RS is\n+ // specified. This option MUST NOT be included if the source address is\n+ // unspecified.\n+ //\n+ // TODO(b/141011931): Validate a LinkEndpoint's link address (provided by\n+ // LinkEndpoint.LinkAddress) before reaching this point.\n+ var optsSerializer header.NDPOptionsSerializer\n+ if localAddr != header.IPv6Any && header.IsValidUnicastEthernetAddress(r.LocalLinkAddress) {\n+ optsSerializer = header.NDPOptionsSerializer{\n+ header.NDPSourceLinkLayerAddressOption(r.LocalLinkAddress),\n+ }\n+ }\n+ payloadSize := header.ICMPv6HeaderSize + header.NDPRSMinimumSize + int(optsSerializer.Length())\nhdr := buffer.NewPrependable(int(r.MaxHeaderLength()) + payloadSize)\npkt := header.ICMPv6(hdr.Prepend(payloadSize))\npkt.SetType(header.ICMPv6RouterSolicit)\n+ rs := header.NDPRouterSolicit(pkt.NDPPayload())\n+ rs.Options().Serialize(optsSerializer)\npkt.SetChecksum(header.ICMPv6Checksum(pkt, r.LocalAddress, r.RemoteAddress, buffer.VectorisedView{}))\nsent := r.Stats().ICMP.V6PacketsSent\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/ndp_test.go",
"new_path": "pkg/tcpip/stack/ndp_test.go",
"diff": "@@ -3384,6 +3384,10 @@ func TestRouterSolicitation(t *testing.T) {\ntests := []struct {\nname string\nlinkHeaderLen uint16\n+ linkAddr tcpip.LinkAddress\n+ nicAddr tcpip.Address\n+ expectedSrcAddr tcpip.Address\n+ expectedNDPOpts []header.NDPOption\nmaxRtrSolicit uint8\nrtrSolicitInt time.Duration\neffectiveRtrSolicitInt time.Duration\n@@ -3392,6 +3396,7 @@ func TestRouterSolicitation(t *testing.T) {\n}{\n{\nname: \"Single RS with delay\",\n+ expectedSrcAddr: header.IPv6Any,\nmaxRtrSolicit: 1,\nrtrSolicitInt: time.Second,\neffectiveRtrSolicitInt: time.Second,\n@@ -3401,6 +3406,8 @@ func TestRouterSolicitation(t *testing.T) {\n{\nname: \"Two RS with delay\",\nlinkHeaderLen: 1,\n+ nicAddr: llAddr1,\n+ expectedSrcAddr: llAddr1,\nmaxRtrSolicit: 2,\nrtrSolicitInt: time.Second,\neffectiveRtrSolicitInt: time.Second,\n@@ -3410,6 +3417,12 @@ func TestRouterSolicitation(t *testing.T) {\n{\nname: \"Single RS without delay\",\nlinkHeaderLen: 2,\n+ linkAddr: linkAddr1,\n+ nicAddr: llAddr1,\n+ expectedSrcAddr: llAddr1,\n+ expectedNDPOpts: []header.NDPOption{\n+ header.NDPSourceLinkLayerAddressOption(linkAddr1),\n+ },\nmaxRtrSolicit: 1,\nrtrSolicitInt: time.Second,\neffectiveRtrSolicitInt: time.Second,\n@@ -3419,6 +3432,8 @@ func TestRouterSolicitation(t *testing.T) {\n{\nname: \"Two RS without delay and invalid zero interval\",\nlinkHeaderLen: 3,\n+ linkAddr: linkAddr1,\n+ expectedSrcAddr: header.IPv6Any,\nmaxRtrSolicit: 2,\nrtrSolicitInt: 0,\neffectiveRtrSolicitInt: 4 * time.Second,\n@@ -3427,6 +3442,8 @@ func TestRouterSolicitation(t *testing.T) {\n},\n{\nname: \"Three RS without delay\",\n+ linkAddr: linkAddr1,\n+ expectedSrcAddr: header.IPv6Any,\nmaxRtrSolicit: 3,\nrtrSolicitInt: 500 * time.Millisecond,\neffectiveRtrSolicitInt: 500 * time.Millisecond,\n@@ -3435,6 +3452,8 @@ func TestRouterSolicitation(t *testing.T) {\n},\n{\nname: \"Two RS with invalid negative delay\",\n+ linkAddr: linkAddr1,\n+ expectedSrcAddr: header.IPv6Any,\nmaxRtrSolicit: 2,\nrtrSolicitInt: time.Second,\neffectiveRtrSolicitInt: time.Second,\n@@ -3457,7 +3476,7 @@ func TestRouterSolicitation(t *testing.T) {\nt.Run(test.name, func(t *testing.T) {\nt.Parallel()\ne := channelLinkWithHeaderLength{\n- Endpoint: channel.New(int(test.maxRtrSolicit), 1280, linkAddr1),\n+ Endpoint: channel.New(int(test.maxRtrSolicit), 1280, test.linkAddr),\nheaderLength: test.linkHeaderLen,\n}\ne.Endpoint.LinkEPCapabilities |= stack.CapabilityResolutionRequired\n@@ -3481,10 +3500,10 @@ func TestRouterSolicitation(t *testing.T) {\nchecker.IPv6(t,\np.Pkt.Header.View(),\n- checker.SrcAddr(header.IPv6Any),\n+ checker.SrcAddr(test.expectedSrcAddr),\nchecker.DstAddr(header.IPv6AllRoutersMulticastAddress),\nchecker.TTL(header.NDPHopLimit),\n- checker.NDPRS(),\n+ checker.NDPRS(checker.NDPRSOptions(test.expectedNDPOpts)),\n)\nif l, want := p.Pkt.Header.AvailableLength(), int(test.linkHeaderLen); l != want {\n@@ -3510,13 +3529,19 @@ func TestRouterSolicitation(t *testing.T) {\nt.Fatalf(\"CreateNIC(%d, _) = %s\", nicID, err)\n}\n- // Make sure each RS got sent at the right\n- // times.\n+ if addr := test.nicAddr; addr != \"\" {\n+ if err := s.AddAddress(nicID, header.IPv6ProtocolNumber, addr); err != nil {\n+ t.Fatalf(\"AddAddress(%d, %d, %s) = %s\", nicID, header.IPv6ProtocolNumber, addr, err)\n+ }\n+ }\n+\n+ // Make sure each RS is sent at the right time.\nremaining := test.maxRtrSolicit\nif remaining > 0 {\nwaitForPkt(test.effectiveMaxRtrSolicitDelay + defaultAsyncEventTimeout)\nremaining--\n}\n+\nfor ; remaining > 0; remaining-- {\nwaitForNothing(test.effectiveRtrSolicitInt - defaultTimeout)\nwaitForPkt(defaultAsyncEventTimeout)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Specify the source of outgoing NDP RS
If the NIC has a valid IPv6 address assigned, use it as the
source address for outgoing NDP Router Solicitation packets.
Test: stack_test.TestRouterSolicitation
PiperOrigin-RevId: 299398763 |
259,972 | 06.03.2020 11:41:10 | 28,800 | d5dbe366bf7c9f5b648b8114a9dc7f45589899b1 | shutdown(s, SHUT_WR) in TIME-WAIT returns ENOTCONN
From RFC 793 s3.9 p61 Event Processing:
CLOSE Call during TIME-WAIT: return with "error: connection closing"
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -2117,10 +2117,13 @@ func (e *endpoint) Shutdown(flags tcpip.ShutdownFlags) *tcpip.Error {\n// Close for write.\nif (e.shutdownFlags & tcpip.ShutdownWrite) != 0 {\ne.sndBufMu.Lock()\n-\nif e.sndClosed {\n// Already closed.\ne.sndBufMu.Unlock()\n+ if e.EndpointState() == StateTimeWait {\n+ e.mu.Unlock()\n+ return tcpip.ErrNotConnected\n+ }\nbreak\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/tcp_socket.cc",
"new_path": "test/syscalls/linux/tcp_socket.cc",
"diff": "@@ -143,6 +143,20 @@ TEST_P(TcpSocketTest, ConnectOnEstablishedConnection) {\nSyscallFailsWithErrno(EISCONN));\n}\n+TEST_P(TcpSocketTest, ShutdownWriteInTimeWait) {\n+ EXPECT_THAT(shutdown(t_, SHUT_WR), SyscallSucceeds());\n+ EXPECT_THAT(shutdown(s_, SHUT_RDWR), SyscallSucceeds());\n+ absl::SleepFor(absl::Seconds(1)); // Wait to enter TIME_WAIT.\n+ EXPECT_THAT(shutdown(t_, SHUT_WR), SyscallFailsWithErrno(ENOTCONN));\n+}\n+\n+TEST_P(TcpSocketTest, ShutdownWriteInFinWait1) {\n+ EXPECT_THAT(shutdown(t_, SHUT_WR), SyscallSucceeds());\n+ EXPECT_THAT(shutdown(t_, SHUT_WR), SyscallSucceeds());\n+ absl::SleepFor(absl::Seconds(1)); // Wait to enter FIN-WAIT2.\n+ EXPECT_THAT(shutdown(t_, SHUT_WR), SyscallSucceeds());\n+}\n+\nTEST_P(TcpSocketTest, DataCoalesced) {\nchar buf[10];\n"
}
] | Go | Apache License 2.0 | google/gvisor | shutdown(s, SHUT_WR) in TIME-WAIT returns ENOTCONN
From RFC 793 s3.9 p61 Event Processing:
CLOSE Call during TIME-WAIT: return with "error: connection closing"
Fixes #1603
PiperOrigin-RevId: 299401353 |
259,860 | 06.03.2020 15:22:30 | 28,800 | 228813fd26aadea012cd8c39e084e4b0fb23d273 | Update comments and debug level for profiling options. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/control/pprof.go",
"new_path": "pkg/sentry/control/pprof.go",
"diff": "@@ -117,15 +117,15 @@ func (p *Profile) HeapProfile(o *ProfileOpts, _ *struct{}) error {\nreturn nil\n}\n-// GoroutineProfile is an RPC stub which dumps out the stack trace for all running\n-// goroutines.\n+// GoroutineProfile is an RPC stub which dumps out the stack trace for all\n+// running goroutines.\nfunc (p *Profile) GoroutineProfile(o *ProfileOpts, _ *struct{}) error {\nif len(o.FilePayload.Files) < 1 {\nreturn errNoOutput\n}\noutput := o.FilePayload.Files[0]\ndefer output.Close()\n- if err := pprof.Lookup(\"goroutine\").WriteTo(output, 0); err != nil {\n+ if err := pprof.Lookup(\"goroutine\").WriteTo(output, 2); err != nil {\nreturn err\n}\nreturn nil\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update comments and debug level for profiling options.
PiperOrigin-RevId: 299448307 |
259,974 | 13.01.2020 07:44:58 | 0 | c04958e2fa456587277baef361868bddc0df9e49 | Enable thread local storage support on arm64.
Linux use the task.thread.uw.tp_value field to store the
TLS pointer on arm64 platform, and we use a similar way
in gvisor to store it in the arch/State struct. | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/elf.go",
"new_path": "pkg/abi/linux/elf.go",
"diff": "@@ -102,4 +102,7 @@ const (\n// NT_X86_XSTATE is for x86 extended state using xsave.\nNT_X86_XSTATE = 0x202\n+\n+ // NT_ARM_TLS is for ARM TLS register.\n+ NT_ARM_TLS = 0x401\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/arch/arch_aarch64.go",
"new_path": "pkg/sentry/arch/arch_aarch64.go",
"diff": "@@ -95,6 +95,9 @@ type State struct {\n// Our floating point state.\naarch64FPState `state:\"wait\"`\n+ // TLS pointer\n+ TPValue uint64\n+\n// FeatureSet is a pointer to the currently active feature set.\nFeatureSet *cpuid.FeatureSet\n}\n@@ -145,6 +148,7 @@ func (s *State) Fork() State {\nreturn State{\nRegs: s.Regs,\naarch64FPState: s.aarch64FPState.fork(),\n+ TPValue: s.TPValue,\nFeatureSet: s.FeatureSet,\n}\n}\n@@ -255,6 +259,7 @@ func (s *State) PtraceSetFPRegs(src io.Reader) (int, error) {\nconst (\n_NT_PRSTATUS = 1\n_NT_PRFPREG = 2\n+ _NT_ARM_TLS = 0x401\n)\n// PtraceGetRegSet implements Context.PtraceGetRegSet.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/arch/arch_arm64.go",
"new_path": "pkg/sentry/arch/arch_arm64.go",
"diff": "@@ -140,18 +140,19 @@ func (c *context64) SetStack(value uintptr) {\n// TLS returns the current TLS pointer.\nfunc (c *context64) TLS() uintptr {\n- // TODO(gvisor.dev/issue/1238): TLS is not supported.\n- // MRS_TPIDR_EL0\n- return 0\n+ return uintptr(c.TPValue)\n}\n// SetTLS sets the current TLS pointer. Returns false if value is invalid.\nfunc (c *context64) SetTLS(value uintptr) bool {\n- // TODO(gvisor.dev/issue/1238): TLS is not supported.\n- // MSR_TPIDR_EL0\n+ if value >= uintptr(maxAddr64) {\nreturn false\n}\n+ c.TPValue = uint64(value)\n+ return true\n+}\n+\n// SetOldRSeqInterruptedIP implements Context.SetOldRSeqInterruptedIP.\nfunc (c *context64) SetOldRSeqInterruptedIP(value uintptr) {\nc.Regs.Regs[3] = uint64(value)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/BUILD",
"new_path": "pkg/sentry/platform/ptrace/BUILD",
"diff": "@@ -9,6 +9,7 @@ go_library(\n\"ptrace.go\",\n\"ptrace_amd64.go\",\n\"ptrace_arm64.go\",\n+ \"ptrace_arm64_unsafe.go\",\n\"ptrace_unsafe.go\",\n\"stub_amd64.s\",\n\"stub_arm64.s\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/ptrace_amd64.go",
"new_path": "pkg/sentry/platform/ptrace/ptrace_amd64.go",
"diff": "@@ -31,3 +31,17 @@ func fpRegSet(useXsave bool) uintptr {\nfunc stackPointer(r *syscall.PtraceRegs) uintptr {\nreturn uintptr(r.Rsp)\n}\n+\n+// x86 use the fs_base register to store the TLS pointer which can be\n+// get/set in \"func (t *thread) get/setRegs(regs *syscall.PtraceRegs)\".\n+// So both of the get/setTLS() operations are noop here.\n+\n+// getTLS gets the thread local storage register.\n+func (t *thread) getTLS(tls *uint64) error {\n+ return nil\n+}\n+\n+// setTLS sets the thread local storage register.\n+func (t *thread) setTLS(tls *uint64) error {\n+ return nil\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/platform/ptrace/ptrace_arm64_unsafe.go",
"diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// +build arm64\n+\n+package ptrace\n+\n+import (\n+ \"syscall\"\n+ \"unsafe\"\n+\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+)\n+\n+// getTLS gets the thread local storage register.\n+func (t *thread) getTLS(tls *uint64) error {\n+ iovec := syscall.Iovec{\n+ Base: (*byte)(unsafe.Pointer(tls)),\n+ Len: uint64(unsafe.Sizeof(*tls)),\n+ }\n+ _, _, errno := syscall.RawSyscall6(\n+ syscall.SYS_PTRACE,\n+ syscall.PTRACE_GETREGSET,\n+ uintptr(t.tid),\n+ linux.NT_ARM_TLS,\n+ uintptr(unsafe.Pointer(&iovec)),\n+ 0, 0)\n+ if errno != 0 {\n+ return errno\n+ }\n+ return nil\n+}\n+\n+// setTLS sets the thread local storage register.\n+func (t *thread) setTLS(tls *uint64) error {\n+ iovec := syscall.Iovec{\n+ Base: (*byte)(unsafe.Pointer(tls)),\n+ Len: uint64(unsafe.Sizeof(*tls)),\n+ }\n+ _, _, errno := syscall.RawSyscall6(\n+ syscall.SYS_PTRACE,\n+ syscall.PTRACE_SETREGSET,\n+ uintptr(t.tid),\n+ linux.NT_ARM_TLS,\n+ uintptr(unsafe.Pointer(&iovec)),\n+ 0, 0)\n+ if errno != 0 {\n+ return errno\n+ }\n+ return nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/subprocess.go",
"new_path": "pkg/sentry/platform/ptrace/subprocess.go",
"diff": "@@ -506,6 +506,9 @@ func (s *subprocess) switchToApp(c *context, ac arch.Context) bool {\nregs := &ac.StateData().Regs\nt.resetSysemuRegs(regs)\n+ // Extract TLS register\n+ tls := uint64(ac.TLS())\n+\n// Check for interrupts, and ensure that future interrupts will signal t.\nif !c.interrupt.Enable(t) {\n// Pending interrupt; simulate.\n@@ -526,6 +529,9 @@ func (s *subprocess) switchToApp(c *context, ac arch.Context) bool {\nif err := t.setFPRegs(fpState, uint64(fpLen), useXsave); err != nil {\npanic(fmt.Sprintf(\"ptrace set fpregs (%+v) failed: %v\", fpState, err))\n}\n+ if err := t.setTLS(&tls); err != nil {\n+ panic(fmt.Sprintf(\"ptrace set tls (%+v) failed: %v\", tls, err))\n+ }\nfor {\n// Start running until the next system call.\n@@ -555,6 +561,12 @@ func (s *subprocess) switchToApp(c *context, ac arch.Context) bool {\nif err := t.getFPRegs(fpState, uint64(fpLen), useXsave); err != nil {\npanic(fmt.Sprintf(\"ptrace get fpregs failed: %v\", err))\n}\n+ if err := t.getTLS(&tls); err != nil {\n+ panic(fmt.Sprintf(\"ptrace get tls failed: %v\", err))\n+ }\n+ if !ac.SetTLS(uintptr(tls)) {\n+ panic(fmt.Sprintf(\"tls value %v is invalid\", tls))\n+ }\n// Is it a system call?\nif sig == (syscallEvent | syscall.SIGTRAP) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enable thread local storage support on arm64.
Linux use the task.thread.uw.tp_value field to store the
TLS pointer on arm64 platform, and we use a similar way
in gvisor to store it in the arch/State struct.
Signed-off-by: Haibo Xu <[email protected]>
Change-Id: Ie76b5c6d109bc27ccfd594008a96753806db7764 |
259,853 | 09.03.2020 11:52:32 | 25,200 | 2446161b3faa352bf28dc83e338f10967f0224c2 | perf/signal: rewrite code in assembly to avoid compiler optimizations
Without this change, the assembly code of this test compiled without
optimizations:
mov -0x150(%rbp),%rax
movl $0x77777777,(%rax)
lea -0x128(%rbp),%rax
with optimizations:
movl $0x77777777,0x0
This code doesn't work properly, because the test changes rax in the segv
handler. | [
{
"change_type": "MODIFY",
"old_path": "test/perf/linux/signal_benchmark.cc",
"new_path": "test/perf/linux/signal_benchmark.cc",
"diff": "@@ -43,11 +43,13 @@ void BM_FaultSignalFixup(benchmark::State& state) {\n// Fault, fault, fault.\nfor (auto _ : state) {\n- register volatile unsigned int* ptr asm(\"rax\");\n-\n// Trigger the segfault.\n- ptr = nullptr;\n- *ptr = 0;\n+ asm volatile(\n+ \"movq $0, %%rax\\n\"\n+ \"movq $0x77777777, (%%rax)\\n\"\n+ :\n+ :\n+ : \"rax\");\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | perf/signal: rewrite code in assembly to avoid compiler optimizations
Without this change, the assembly code of this test compiled without
optimizations:
mov -0x150(%rbp),%rax
movl $0x77777777,(%rax)
lea -0x128(%rbp),%rax
with optimizations:
movl $0x77777777,0x0
This code doesn't work properly, because the test changes rax in the segv
handler.
PiperOrigin-RevId: 299896117 |
260,003 | 09.03.2020 19:57:35 | 25,200 | b36de6e7be0542b410901d3cbcd1b3c0fc493cf5 | Move /proc/net to /proc/PID/net, and make /proc/net -> /proc/self/net.
Issue | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/net.go",
"new_path": "pkg/sentry/fs/proc/net.go",
"diff": "@@ -40,47 +40,48 @@ import (\n// LINT.IfChange\n-// newNet creates a new proc net entry.\n-func (p *proc) newNetDir(ctx context.Context, k *kernel.Kernel, msrc *fs.MountSource) *fs.Inode {\n+// newNetDir creates a new proc net entry.\n+func newNetDir(t *kernel.Task, msrc *fs.MountSource) *fs.Inode {\n+ k := t.Kernel()\n+\nvar contents map[string]*fs.Inode\n- // TODO(gvisor.dev/issue/1833): Support for using the network stack in the\n- // network namespace of the calling process. We should make this per-process,\n- // a.k.a. /proc/PID/net, and make /proc/net a symlink to /proc/self/net.\n- if s := p.k.RootNetworkNamespace().Stack(); s != nil {\n+ if s := t.NetworkNamespace().Stack(); s != nil {\n+ // TODO(gvisor.dev/issue/1833): Make sure file contents reflect the task\n+ // network namespace.\ncontents = map[string]*fs.Inode{\n- \"dev\": seqfile.NewSeqFileInode(ctx, &netDev{s: s}, msrc),\n- \"snmp\": seqfile.NewSeqFileInode(ctx, &netSnmp{s: s}, msrc),\n+ \"dev\": seqfile.NewSeqFileInode(t, &netDev{s: s}, msrc),\n+ \"snmp\": seqfile.NewSeqFileInode(t, &netSnmp{s: s}, msrc),\n// The following files are simple stubs until they are\n// implemented in netstack, if the file contains a\n// header the stub is just the header otherwise it is\n// an empty file.\n- \"arp\": newStaticProcInode(ctx, msrc, []byte(\"IP address HW type Flags HW address Mask Device\\n\")),\n+ \"arp\": newStaticProcInode(t, msrc, []byte(\"IP address HW type Flags HW address Mask Device\\n\")),\n- \"netlink\": newStaticProcInode(ctx, msrc, []byte(\"sk Eth Pid Groups Rmem Wmem Dump Locks Drops Inode\\n\")),\n- \"netstat\": newStaticProcInode(ctx, msrc, []byte(\"TcpExt: SyncookiesSent SyncookiesRecv SyncookiesFailed EmbryonicRsts PruneCalled RcvPruned OfoPruned OutOfWindowIcmps LockDroppedIcmps ArpFilter TW TWRecycled TWKilled PAWSPassive PAWSActive PAWSEstab DelayedACKs DelayedACKLocked DelayedACKLost ListenOverflows ListenDrops TCPPrequeued TCPDirectCopyFromBacklog TCPDirectCopyFromPrequeue TCPPrequeueDropped TCPHPHits TCPHPHitsToUser TCPPureAcks TCPHPAcks TCPRenoRecovery TCPSackRecovery TCPSACKReneging TCPFACKReorder TCPSACKReorder TCPRenoReorder TCPTSReorder TCPFullUndo TCPPartialUndo TCPDSACKUndo TCPLossUndo TCPLostRetransmit TCPRenoFailures TCPSackFailures TCPLossFailures TCPFastRetrans TCPForwardRetrans TCPSlowStartRetrans TCPTimeouts TCPLossProbes TCPLossProbeRecovery TCPRenoRecoveryFail TCPSackRecoveryFail TCPSchedulerFailed TCPRcvCollapsed TCPDSACKOldSent TCPDSACKOfoSent TCPDSACKRecv TCPDSACKOfoRecv TCPAbortOnData TCPAbortOnClose TCPAbortOnMemory TCPAbortOnTimeout TCPAbortOnLinger TCPAbortFailed TCPMemoryPressures TCPSACKDiscard TCPDSACKIgnoredOld TCPDSACKIgnoredNoUndo TCPSpuriousRTOs TCPMD5NotFound TCPMD5Unexpected TCPMD5Failure TCPSackShifted TCPSackMerged TCPSackShiftFallback TCPBacklogDrop TCPMinTTLDrop TCPDeferAcceptDrop IPReversePathFilter TCPTimeWaitOverflow TCPReqQFullDoCookies TCPReqQFullDrop TCPRetransFail TCPRcvCoalesce TCPOFOQueue TCPOFODrop TCPOFOMerge TCPChallengeACK TCPSYNChallenge TCPFastOpenActive TCPFastOpenActiveFail TCPFastOpenPassive TCPFastOpenPassiveFail TCPFastOpenListenOverflow TCPFastOpenCookieReqd TCPSpuriousRtxHostQueues BusyPollRxPackets TCPAutoCorking TCPFromZeroWindowAdv TCPToZeroWindowAdv TCPWantZeroWindowAdv TCPSynRetrans TCPOrigDataSent TCPHystartTrainDetect TCPHystartTrainCwnd TCPHystartDelayDetect TCPHystartDelayCwnd TCPACKSkippedSynRecv TCPACKSkippedPAWS TCPACKSkippedSeq TCPACKSkippedFinWait2 TCPACKSkippedTimeWait TCPACKSkippedChallenge TCPWinProbe TCPKeepAlive TCPMTUPFail TCPMTUPSuccess\\n\")),\n- \"packet\": newStaticProcInode(ctx, msrc, []byte(\"sk RefCnt Type Proto Iface R Rmem User Inode\\n\")),\n- \"protocols\": newStaticProcInode(ctx, msrc, []byte(\"protocol size sockets memory press maxhdr slab module cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\\n\")),\n+ \"netlink\": newStaticProcInode(t, msrc, []byte(\"sk Eth Pid Groups Rmem Wmem Dump Locks Drops Inode\\n\")),\n+ \"netstat\": newStaticProcInode(t, msrc, []byte(\"TcpExt: SyncookiesSent SyncookiesRecv SyncookiesFailed EmbryonicRsts PruneCalled RcvPruned OfoPruned OutOfWindowIcmps LockDroppedIcmps ArpFilter TW TWRecycled TWKilled PAWSPassive PAWSActive PAWSEstab DelayedACKs DelayedACKLocked DelayedACKLost ListenOverflows ListenDrops TCPPrequeued TCPDirectCopyFromBacklog TCPDirectCopyFromPrequeue TCPPrequeueDropped TCPHPHits TCPHPHitsToUser TCPPureAcks TCPHPAcks TCPRenoRecovery TCPSackRecovery TCPSACKReneging TCPFACKReorder TCPSACKReorder TCPRenoReorder TCPTSReorder TCPFullUndo TCPPartialUndo TCPDSACKUndo TCPLossUndo TCPLostRetransmit TCPRenoFailures TCPSackFailures TCPLossFailures TCPFastRetrans TCPForwardRetrans TCPSlowStartRetrans TCPTimeouts TCPLossProbes TCPLossProbeRecovery TCPRenoRecoveryFail TCPSackRecoveryFail TCPSchedulerFailed TCPRcvCollapsed TCPDSACKOldSent TCPDSACKOfoSent TCPDSACKRecv TCPDSACKOfoRecv TCPAbortOnData TCPAbortOnClose TCPAbortOnMemory TCPAbortOnTimeout TCPAbortOnLinger TCPAbortFailed TCPMemoryPressures TCPSACKDiscard TCPDSACKIgnoredOld TCPDSACKIgnoredNoUndo TCPSpuriousRTOs TCPMD5NotFound TCPMD5Unexpected TCPMD5Failure TCPSackShifted TCPSackMerged TCPSackShiftFallback TCPBacklogDrop TCPMinTTLDrop TCPDeferAcceptDrop IPReversePathFilter TCPTimeWaitOverflow TCPReqQFullDoCookies TCPReqQFullDrop TCPRetransFail TCPRcvCoalesce TCPOFOQueue TCPOFODrop TCPOFOMerge TCPChallengeACK TCPSYNChallenge TCPFastOpenActive TCPFastOpenActiveFail TCPFastOpenPassive TCPFastOpenPassiveFail TCPFastOpenListenOverflow TCPFastOpenCookieReqd TCPSpuriousRtxHostQueues BusyPollRxPackets TCPAutoCorking TCPFromZeroWindowAdv TCPToZeroWindowAdv TCPWantZeroWindowAdv TCPSynRetrans TCPOrigDataSent TCPHystartTrainDetect TCPHystartTrainCwnd TCPHystartDelayDetect TCPHystartDelayCwnd TCPACKSkippedSynRecv TCPACKSkippedPAWS TCPACKSkippedSeq TCPACKSkippedFinWait2 TCPACKSkippedTimeWait TCPACKSkippedChallenge TCPWinProbe TCPKeepAlive TCPMTUPFail TCPMTUPSuccess\\n\")),\n+ \"packet\": newStaticProcInode(t, msrc, []byte(\"sk RefCnt Type Proto Iface R Rmem User Inode\\n\")),\n+ \"protocols\": newStaticProcInode(t, msrc, []byte(\"protocol size sockets memory press maxhdr slab module cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\\n\")),\n// Linux sets psched values to: nsec per usec, psched\n// tick in ns, 1000000, high res timer ticks per sec\n// (ClockGetres returns 1ns resolution).\n- \"psched\": newStaticProcInode(ctx, msrc, []byte(fmt.Sprintf(\"%08x %08x %08x %08x\\n\", uint64(time.Microsecond/time.Nanosecond), 64, 1000000, uint64(time.Second/time.Nanosecond)))),\n- \"ptype\": newStaticProcInode(ctx, msrc, []byte(\"Type Device Function\\n\")),\n- \"route\": seqfile.NewSeqFileInode(ctx, &netRoute{s: s}, msrc),\n- \"tcp\": seqfile.NewSeqFileInode(ctx, &netTCP{k: k}, msrc),\n- \"udp\": seqfile.NewSeqFileInode(ctx, &netUDP{k: k}, msrc),\n- \"unix\": seqfile.NewSeqFileInode(ctx, &netUnix{k: k}, msrc),\n+ \"psched\": newStaticProcInode(t, msrc, []byte(fmt.Sprintf(\"%08x %08x %08x %08x\\n\", uint64(time.Microsecond/time.Nanosecond), 64, 1000000, uint64(time.Second/time.Nanosecond)))),\n+ \"ptype\": newStaticProcInode(t, msrc, []byte(\"Type Device Function\\n\")),\n+ \"route\": seqfile.NewSeqFileInode(t, &netRoute{s: s}, msrc),\n+ \"tcp\": seqfile.NewSeqFileInode(t, &netTCP{k: k}, msrc),\n+ \"udp\": seqfile.NewSeqFileInode(t, &netUDP{k: k}, msrc),\n+ \"unix\": seqfile.NewSeqFileInode(t, &netUnix{k: k}, msrc),\n}\nif s.SupportsIPv6() {\n- contents[\"if_inet6\"] = seqfile.NewSeqFileInode(ctx, &ifinet6{s: s}, msrc)\n- contents[\"ipv6_route\"] = newStaticProcInode(ctx, msrc, []byte(\"\"))\n- contents[\"tcp6\"] = seqfile.NewSeqFileInode(ctx, &netTCP6{k: k}, msrc)\n- contents[\"udp6\"] = newStaticProcInode(ctx, msrc, []byte(\" sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\\n\"))\n+ contents[\"if_inet6\"] = seqfile.NewSeqFileInode(t, &ifinet6{s: s}, msrc)\n+ contents[\"ipv6_route\"] = newStaticProcInode(t, msrc, []byte(\"\"))\n+ contents[\"tcp6\"] = seqfile.NewSeqFileInode(t, &netTCP6{k: k}, msrc)\n+ contents[\"udp6\"] = newStaticProcInode(t, msrc, []byte(\" sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\\n\"))\n}\n}\n- d := ramfs.NewDir(ctx, contents, fs.RootOwner, fs.FilePermsFromMode(0555))\n- return newProcInode(ctx, d, msrc, fs.SpecialDirectory, nil)\n+ d := ramfs.NewDir(t, contents, fs.RootOwner, fs.FilePermsFromMode(0555))\n+ return newProcInode(t, d, msrc, fs.SpecialDirectory, t)\n}\n// ifinet6 implements seqfile.SeqSource for /proc/net/if_inet6.\n@@ -837,4 +838,4 @@ func (n *netUDP) ReadSeqFileData(ctx context.Context, h seqfile.SeqHandle) ([]se\nreturn data, 0\n}\n-// LINT.ThenChange(../../fsimpl/proc/tasks_net.go)\n+// LINT.ThenChange(../../fsimpl/proc/task_net.go)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/proc.go",
"new_path": "pkg/sentry/fs/proc/proc.go",
"diff": "@@ -70,6 +70,7 @@ func New(ctx context.Context, msrc *fs.MountSource, cgroupControllers map[string\n\"loadavg\": seqfile.NewSeqFileInode(ctx, &loadavgData{}, msrc),\n\"meminfo\": seqfile.NewSeqFileInode(ctx, &meminfoData{k}, msrc),\n\"mounts\": newProcInode(ctx, ramfs.NewSymlink(ctx, fs.RootOwner, \"self/mounts\"), msrc, fs.Symlink, nil),\n+ \"net\": newProcInode(ctx, ramfs.NewSymlink(ctx, fs.RootOwner, \"self/net\"), msrc, fs.Symlink, nil),\n\"self\": newSelf(ctx, pidns, msrc),\n\"stat\": seqfile.NewSeqFileInode(ctx, &statData{k}, msrc),\n\"thread-self\": newThreadSelf(ctx, pidns, msrc),\n@@ -86,7 +87,6 @@ func New(ctx context.Context, msrc *fs.MountSource, cgroupControllers map[string\n}\n// Add more contents that need proc to be initialized.\n- p.AddChild(ctx, \"net\", p.newNetDir(ctx, k, msrc))\np.AddChild(ctx, \"sys\", p.newSysDir(ctx, msrc))\nreturn newProcInode(ctx, p, msrc, fs.SpecialDirectory, nil), nil\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/task.go",
"new_path": "pkg/sentry/fs/proc/task.go",
"diff": "@@ -84,6 +84,7 @@ func (p *proc) newTaskDir(t *kernel.Task, msrc *fs.MountSource, isThreadGroup bo\n\"maps\": newMaps(t, msrc),\n\"mountinfo\": seqfile.NewSeqFileInode(t, &mountInfoFile{t: t}, msrc),\n\"mounts\": seqfile.NewSeqFileInode(t, &mountsFile{t: t}, msrc),\n+ \"net\": newNetDir(t, msrc),\n\"ns\": newNamespaceDir(t, msrc),\n\"oom_score\": newOOMScore(t, msrc),\n\"oom_score_adj\": newOOMScoreAdj(t, msrc),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/BUILD",
"new_path": "pkg/sentry/fsimpl/proc/BUILD",
"diff": "@@ -9,9 +9,9 @@ go_library(\n\"subtasks.go\",\n\"task.go\",\n\"task_files.go\",\n+ \"task_net.go\",\n\"tasks.go\",\n\"tasks_files.go\",\n- \"tasks_net.go\",\n\"tasks_sys.go\",\n],\nvisibility = [\"//pkg/sentry:internal\"],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/task.go",
"new_path": "pkg/sentry/fsimpl/proc/task.go",
"diff": "@@ -57,6 +57,7 @@ func newTaskInode(inoGen InoGenerator, task *kernel.Task, pidns *kernel.PIDNames\n\"maps\": newTaskOwnedFile(task, inoGen.NextIno(), 0444, &mapsData{task: task}),\n//\"mountinfo\": seqfile.NewSeqFileInode(t, &mountInfoFile{t: t}, msrc),\n//\"mounts\": seqfile.NewSeqFileInode(t, &mountsFile{t: t}, msrc),\n+ \"net\": newTaskNetDir(task, inoGen),\n\"ns\": newTaskOwnedDir(task, inoGen.NextIno(), 0511, map[string]*kernfs.Dentry{\n\"net\": newNamespaceSymlink(task, inoGen.NextIno(), \"net\"),\n\"pid\": newNamespaceSymlink(task, inoGen.NextIno(), \"pid\"),\n"
},
{
"change_type": "RENAME",
"old_path": "pkg/sentry/fsimpl/proc/tasks_net.go",
"new_path": "pkg/sentry/fsimpl/proc/task_net.go",
"diff": "@@ -37,12 +37,13 @@ import (\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n-func newNetDir(root *auth.Credentials, inoGen InoGenerator, k *kernel.Kernel) *kernfs.Dentry {\n+func newTaskNetDir(task *kernel.Task, inoGen InoGenerator) *kernfs.Dentry {\n+ k := task.Kernel()\n+ pidns := task.PIDNamespace()\n+ root := auth.NewRootCredentials(pidns.UserNamespace())\n+\nvar contents map[string]*kernfs.Dentry\n- // TODO(gvisor.dev/issue/1833): Support for using the network stack in the\n- // network namespace of the calling process. We should make this per-process,\n- // a.k.a. /proc/PID/net, and make /proc/net a symlink to /proc/self/net.\n- if stack := k.RootNetworkNamespace().Stack(); stack != nil {\n+ if stack := task.NetworkNamespace().Stack(); stack != nil {\nconst (\narp = \"IP address HW type Flags HW address Mask Device\\n\"\nnetlink = \"sk Eth Pid Groups Rmem Wmem Dump Locks Drops Inode\\n\"\n@@ -53,6 +54,8 @@ func newNetDir(root *auth.Credentials, inoGen InoGenerator, k *kernel.Kernel) *k\n)\npsched := fmt.Sprintf(\"%08x %08x %08x %08x\\n\", uint64(time.Microsecond/time.Nanosecond), 64, 1000000, uint64(time.Second/time.Nanosecond))\n+ // TODO(gvisor.dev/issue/1833): Make sure file contents reflect the task\n+ // network namespace.\ncontents = map[string]*kernfs.Dentry{\n\"dev\": newDentry(root, inoGen.NextIno(), 0444, &netDevData{stack: stack}),\n\"snmp\": newDentry(root, inoGen.NextIno(), 0444, &netSnmpData{stack: stack}),\n@@ -84,7 +87,7 @@ func newNetDir(root *auth.Credentials, inoGen InoGenerator, k *kernel.Kernel) *k\n}\n}\n- return kernfs.NewStaticDir(root, inoGen.NextIno(), 0555, contents)\n+ return newTaskOwnedDir(task, inoGen.NextIno(), 0555, contents)\n}\n// ifinet6 implements vfs.DynamicBytesSource for /proc/net/if_inet6.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/tasks.go",
"new_path": "pkg/sentry/fsimpl/proc/tasks.go",
"diff": "@@ -72,7 +72,7 @@ func newTasksInode(inoGen InoGenerator, k *kernel.Kernel, pidns *kernel.PIDNames\n\"sys\": newSysDir(root, inoGen, k),\n\"meminfo\": newDentry(root, inoGen.NextIno(), 0444, &meminfoData{}),\n\"mounts\": kernfs.NewStaticSymlink(root, inoGen.NextIno(), \"self/mounts\"),\n- \"net\": newNetDir(root, inoGen, k),\n+ \"net\": kernfs.NewStaticSymlink(root, inoGen.NextIno(), \"self/net\"),\n\"stat\": newDentry(root, inoGen.NextIno(), 0444, &statData{k: k}),\n\"uptime\": newDentry(root, inoGen.NextIno(), 0444, &uptimeData{}),\n\"version\": newDentry(root, inoGen.NextIno(), 0444, &versionData{k: k}),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/tasks_test.go",
"new_path": "pkg/sentry/fsimpl/proc/tasks_test.go",
"diff": "@@ -50,7 +50,7 @@ var (\n\"loadavg\": linux.DT_REG,\n\"meminfo\": linux.DT_REG,\n\"mounts\": linux.DT_LNK,\n- \"net\": linux.DT_DIR,\n+ \"net\": linux.DT_LNK,\n\"self\": linux.DT_LNK,\n\"stat\": linux.DT_REG,\n\"sys\": linux.DT_DIR,\n@@ -71,6 +71,7 @@ var (\n\"gid_map\": linux.DT_REG,\n\"io\": linux.DT_REG,\n\"maps\": linux.DT_REG,\n+ \"net\": linux.DT_DIR,\n\"ns\": linux.DT_DIR,\n\"oom_score\": linux.DT_REG,\n\"oom_score_adj\": linux.DT_REG,\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/proc_net.cc",
"new_path": "test/syscalls/linux/proc_net.cc",
"diff": "@@ -33,6 +33,31 @@ namespace gvisor {\nnamespace testing {\nnamespace {\n+constexpr const char kProcNet[] = \"/proc/net\";\n+\n+TEST(ProcNetSymlinkTarget, FileMode) {\n+ struct stat s;\n+ ASSERT_THAT(stat(kProcNet, &s), SyscallSucceeds());\n+ EXPECT_EQ(s.st_mode & S_IFMT, S_IFDIR);\n+ EXPECT_EQ(s.st_mode & 0777, 0555);\n+}\n+\n+TEST(ProcNetSymlink, FileMode) {\n+ struct stat s;\n+ ASSERT_THAT(lstat(kProcNet, &s), SyscallSucceeds());\n+ EXPECT_EQ(s.st_mode & S_IFMT, S_IFLNK);\n+ EXPECT_EQ(s.st_mode & 0777, 0777);\n+}\n+\n+TEST(ProcNetSymlink, Contents) {\n+ char buf[40] = {};\n+ int n = readlink(kProcNet, buf, sizeof(buf));\n+ ASSERT_THAT(n, SyscallSucceeds());\n+\n+ buf[n] = 0;\n+ EXPECT_STREQ(buf, \"self/net\");\n+}\n+\nTEST(ProcNetIfInet6, Format) {\nauto ifinet6 = ASSERT_NO_ERRNO_AND_VALUE(GetContents(\"/proc/net/if_inet6\"));\nEXPECT_THAT(ifinet6,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Move /proc/net to /proc/PID/net, and make /proc/net -> /proc/self/net.
Issue #1833
PiperOrigin-RevId: 299998105 |
259,884 | 10.03.2020 13:58:27 | 25,200 | 0990ef7517236228f575f222ae639d375badec15 | Make checkpoint/restore e2e test less flaky | [
{
"change_type": "MODIFY",
"old_path": "test/e2e/integration_test.go",
"new_path": "test/e2e/integration_test.go",
"diff": "@@ -175,10 +175,8 @@ func TestCheckpointRestore(t *testing.T) {\nt.Fatal(err)\n}\n- // TODO(b/143498576): Remove after github.com/moby/moby/issues/38963 is fixed.\n- time.Sleep(1 * time.Second)\n-\n- if err := d.Restore(\"test\"); err != nil {\n+ // TODO(b/143498576): Remove Poll after github.com/moby/moby/issues/38963 is fixed.\n+ if err := testutil.Poll(func() error { return d.Restore(\"test\") }, 15*time.Second); err != nil {\nt.Fatal(\"docker restore failed:\", err)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Make checkpoint/restore e2e test less flaky
PiperOrigin-RevId: 300171916 |
259,884 | 30.01.2020 23:32:12 | 18,000 | 5f723ac601e8ea6eb3216f60fce49b771ef87e0a | Fix corrupted bazel install errors.
Previously /tmp/gvisor-website was used for the bazel output_user_root
but the host could delete a subset of the files under /tmp causing it to
become corrupted.
This commit updates the Makefile to use the bazel_user_root directory
under the repository root directory for caching bazel packages. | [
{
"change_type": "MODIFY",
"old_path": ".gitignore",
"new_path": ".gitignore",
"diff": "bin/\n+bazel_user_root/\npublic/\nresources/\nnode_modules/\n"
},
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -83,26 +83,24 @@ node_modules: package.json package-lock.json\n--entrypoint 'npm' \\\nnode ci\n-upstream/gvisor/bazel-bin/runsc/linux_amd64_pure_stripped/runsc: upstream-gvisor\n- mkdir -p /tmp/gvisor-website/build_output\n+bin/generate-syscall-docs: $(GEN_SOURCE)\n+ mkdir -p bin/\n+ go build -o bin/generate-syscall-docs gvisor.dev/website/cmd/generate-syscall-docs\n+\n+compatibility-docs: bin/generate-syscall-docs\n+ # bazel_user_root is used for caching bazel packages.\n+ mkdir -p bazel_user_root/\ndocker run \\\n--rm \\\n-v $(PWD)/upstream/gvisor:/workspace \\\n- -v /tmp/gvisor-website/build_output:/tmp/gvisor-website/build_output \\\n+ -v $(PWD)/bazel_user_root:/bazel_user_root \\\n-w /workspace \\\n--entrypoint 'sh' \\\nl.gcr.io/google/bazel \\\n-c '\\\ngroupadd --gid $(shell id -g) $(shell id -gn) && \\\nuseradd --uid $(shell id -u) --gid $(shell id -g) -ms /bin/bash $(USER) && \\\n- su $(USER) -c \"bazel --output_user_root=/tmp/gvisor-website/build_output build //runsc\"'\n-\n-bin/generate-syscall-docs: $(GEN_SOURCE)\n- mkdir -p bin/\n- go build -o bin/generate-syscall-docs gvisor.dev/website/cmd/generate-syscall-docs\n-\n-compatibility-docs: bin/generate-syscall-docs upstream/gvisor/bazel-bin/runsc/linux_amd64_pure_stripped/runsc\n- ./upstream/gvisor/bazel-bin/runsc/linux_amd64_pure_stripped/runsc help syscalls -o json | ./bin/generate-syscall-docs -out ./content/docs/user_guide/compatibility/\n+ su $(USER) -c \"bazel --output_user_root=/bazel_user_root run //runsc -- help syscalls -o json\"' | ./bin/generate-syscall-docs -out ./content/docs/user_guide/compatibility/\n.PHONY: compatibility-docs\ncheck: check-markdown check-html\n@@ -173,5 +171,8 @@ htmlproofer-docker-image:\n.PHONY: htmlproofer-docker-image\nclean:\n- rm -rf public/ resources/ node_modules/ upstream/ content/docs/user_guide/compatibility/linux/\n+ifneq (\"$(wildcard bazel_user_root/)\",\"\")\n+ chmod -R +w bazel_user_root/\n+endif\n+ rm -rf bazel_user_root/ public/ resources/ node_modules/ upstream/ content/docs/user_guide/compatibility/linux/\n.PHONY: clean\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix corrupted bazel install errors.
Previously /tmp/gvisor-website was used for the bazel output_user_root
but the host could delete a subset of the files under /tmp causing it to
become corrupted.
This commit updates the Makefile to use the bazel_user_root directory
under the repository root directory for caching bazel packages. |
259,884 | 21.12.2019 03:27:52 | 18,000 | 7a3048954a537b82f2dfd5cf81600585820ffd3a | Add note on nested virtualization | [
{
"change_type": "MODIFY",
"old_path": "content/docs/user_guide/platforms.md",
"new_path": "content/docs/user_guide/platforms.md",
"diff": "@@ -63,6 +63,11 @@ nested virtualization in several popular environments:\n* VirtualBox: [Nested Virtualization][nested-virtualbox]\n* KVM: [Nested Guests][nested-kvm]\n+***Note: nested virtualization will have poor performance and is historically a\n+cause of security issues (e.g.\n+[CVE-2018-12904](https://nvd.nist.gov/vuln/detail/CVE-2018-12904)). It is not\n+recommended for production.***\n+\n### Configuring Docker\nPer above, you will need to configure Docker to use `runsc` with the KVM\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add note on nested virtualization |
260,004 | 10.03.2020 17:50:47 | 25,200 | f56fe66b13b979f2ac96e8fce6fb0a5dec9a32e0 | Honour the link's MaxHeaderLength when forwarding
This change also updates where the IP packet buffer is held in an
outbound tcpip.PacketBuffer from Header to Data. This change removes
unncessary copying of the IP packet buffer when forwarding.
Test: stack_test.TestNICForwarding | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/packet_buffer.go",
"new_path": "pkg/tcpip/packet_buffer.go",
"diff": "@@ -39,8 +39,12 @@ type PacketBuffer struct {\n// payload.\nDataSize int\n- // Header holds the headers of outbound packets. As a packet is passed\n- // down the stack, each layer adds to Header.\n+ // Header holds the headers of outbound packets generated by the netstack. As\n+ // a packet is passed down the stack, each layer adds to Header.\n+ //\n+ // Note, if a packet is being forwarded at the IP layer, the headers for the\n+ // IP layer and above (transport) will be held in Data as the packet was not\n+ // passed down the stack it arrived at before being forwarded.\nHeader buffer.Prependable\n// These fields are used by both inbound and outbound packets. They\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/forwarder_test.go",
"new_path": "pkg/tcpip/stack/forwarder_test.go",
"diff": "@@ -473,7 +473,7 @@ func TestForwardingWithFakeResolverPartialTimeout(t *testing.T) {\nt.Fatal(\"packet not forwarded\")\n}\n- b := p.Pkt.Header.View()\n+ b := p.Pkt.Data.First()\nif b[0] != 3 {\nt.Fatalf(\"got b[0] = %d, want = 3\", b[0])\n}\n@@ -517,7 +517,7 @@ func TestForwardingWithFakeResolverTwoPackets(t *testing.T) {\nt.Fatal(\"packet not forwarded\")\n}\n- b := p.Pkt.Header.View()\n+ b := p.Pkt.Data.First()\nif b[0] != 3 {\nt.Fatalf(\"got b[0] = %d, want = 3\", b[0])\n}\n@@ -564,7 +564,7 @@ func TestForwardingWithFakeResolverManyPackets(t *testing.T) {\nt.Fatal(\"packet not forwarded\")\n}\n- b := p.Pkt.Header.View()\n+ b := p.Pkt.Data.First()\nif b[0] != 3 {\nt.Fatalf(\"got b[0] = %d, want = 3\", b[0])\n}\n@@ -619,7 +619,7 @@ func TestForwardingWithFakeResolverManyResolutions(t *testing.T) {\n// The first 5 packets (address 3 to 7) should not be forwarded\n// because their address resolutions are interrupted.\n- b := p.Pkt.Header.View()\n+ b := p.Pkt.Data.First()\nif b[0] < 8 {\nt.Fatalf(\"got b[0] = %d, want b[0] >= 8\", b[0])\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic.go",
"new_path": "pkg/tcpip/stack/nic.go",
"diff": "@@ -1246,10 +1246,10 @@ func (n *NIC) DeliverNetworkPacket(linkEP LinkEndpoint, remote, local tcpip.Link\n}\nfunc (n *NIC) forwardPacket(r *Route, protocol tcpip.NetworkProtocolNumber, pkt tcpip.PacketBuffer) {\n- // TODO(b/143425874) Decrease the TTL field in forwarded packets.\n- pkt.Header = buffer.NewPrependableFromView(pkt.Data.First())\n- pkt.Data.RemoveFirst()\n+ // TODO(b/143425874): Decrease the TTL field in forwarded packets.\n+ // pkt.Header should have enough capacity to hold the link's headers.\n+ pkt.Header = buffer.NewPrependable(int(n.linkEP.MaxHeaderLength()))\nif err := n.linkEP.WritePacket(r, nil /* gso */, protocol, pkt); err != nil {\nr.Stats().IP.OutgoingPacketErrors.Increment()\nreturn\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack_test.go",
"new_path": "pkg/tcpip/stack/stack_test.go",
"diff": "@@ -2240,57 +2240,85 @@ func TestNICStats(t *testing.T) {\n}\nfunc TestNICForwarding(t *testing.T) {\n- // Create a stack with the fake network protocol, two NICs, each with\n- // an address.\n+ const nicID1 = 1\n+ const nicID2 = 2\n+ const dstAddr = tcpip.Address(\"\\x03\")\n+\n+ tests := []struct {\n+ name string\n+ headerLen uint16\n+ }{\n+ {\n+ name: \"Zero header length\",\n+ },\n+ {\n+ name: \"Non-zero header length\",\n+ headerLen: 16,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\ns := stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},\n})\ns.SetForwarding(true)\nep1 := channel.New(10, defaultMTU, \"\")\n- if err := s.CreateNIC(1, ep1); err != nil {\n- t.Fatal(\"CreateNIC #1 failed:\", err)\n+ if err := s.CreateNIC(nicID1, ep1); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", nicID1, err)\n}\n- if err := s.AddAddress(1, fakeNetNumber, \"\\x01\"); err != nil {\n- t.Fatal(\"AddAddress #1 failed:\", err)\n+ if err := s.AddAddress(nicID1, fakeNetNumber, \"\\x01\"); err != nil {\n+ t.Fatalf(\"AddAddress(%d, %d, 0x01): %s\", nicID1, fakeNetNumber, err)\n}\n- ep2 := channel.New(10, defaultMTU, \"\")\n- if err := s.CreateNIC(2, ep2); err != nil {\n- t.Fatal(\"CreateNIC #2 failed:\", err)\n+ ep2 := channelLinkWithHeaderLength{\n+ Endpoint: channel.New(10, defaultMTU, \"\"),\n+ headerLength: test.headerLen,\n}\n- if err := s.AddAddress(2, fakeNetNumber, \"\\x02\"); err != nil {\n- t.Fatal(\"AddAddress #2 failed:\", err)\n+ if err := s.CreateNIC(nicID2, &ep2); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", nicID2, err)\n+ }\n+ if err := s.AddAddress(nicID2, fakeNetNumber, \"\\x02\"); err != nil {\n+ t.Fatalf(\"AddAddress(%d, %d, 0x02): %s\", nicID2, fakeNetNumber, err)\n}\n- // Route all packets to address 3 to NIC 2.\n+ // Route all packets to dstAddr to NIC 2.\n{\n- subnet, err := tcpip.NewSubnet(\"\\x03\", \"\\xff\")\n+ subnet, err := tcpip.NewSubnet(dstAddr, \"\\xff\")\nif err != nil {\nt.Fatal(err)\n}\n- s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: \"\\x00\", NIC: 2}})\n+ s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: \"\\x00\", NIC: nicID2}})\n}\n- // Send a packet to address 3.\n+ // Send a packet to dstAddr.\nbuf := buffer.NewView(30)\n- buf[0] = 3\n+ buf[0] = dstAddr[0]\nep1.InjectInbound(fakeNetNumber, tcpip.PacketBuffer{\nData: buf.ToVectorisedView(),\n})\n- if _, ok := ep2.Read(); !ok {\n- t.Fatal(\"Packet not forwarded\")\n+ pkt, ok := ep2.Read()\n+ if !ok {\n+ t.Fatal(\"packet not forwarded\")\n+ }\n+\n+ // Test that the link's MaxHeaderLength is honoured.\n+ if capacity, want := pkt.Pkt.Header.AvailableLength(), int(test.headerLen); capacity != want {\n+ t.Errorf(\"got Header.AvailableLength() = %d, want = %d\", capacity, want)\n}\n// Test that forwarding increments Tx stats correctly.\n- if got, want := s.NICInfo()[2].Stats.Tx.Packets.Value(), uint64(1); got != want {\n+ if got, want := s.NICInfo()[nicID2].Stats.Tx.Packets.Value(), uint64(1); got != want {\nt.Errorf(\"got Tx.Packets.Value() = %d, want = %d\", got, want)\n}\n- if got, want := s.NICInfo()[2].Stats.Tx.Bytes.Value(), uint64(len(buf)); got != want {\n+ if got, want := s.NICInfo()[nicID2].Stats.Tx.Bytes.Value(), uint64(len(buf)); got != want {\nt.Errorf(\"got Tx.Bytes.Value() = %d, want = %d\", got, want)\n}\n+ })\n+ }\n}\n// TestNICContextPreservation tests that you can read out via stack.NICInfo the\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/transport_test.go",
"new_path": "pkg/tcpip/stack/transport_test.go",
"diff": "@@ -641,10 +641,10 @@ func TestTransportForwarding(t *testing.T) {\nt.Fatal(\"Response packet not forwarded\")\n}\n- if dst := p.Pkt.Header.View()[0]; dst != 3 {\n+ if dst := p.Pkt.Data.First()[0]; dst != 3 {\nt.Errorf(\"Response packet has incorrect destination addresss: got = %d, want = 3\", dst)\n}\n- if src := p.Pkt.Header.View()[1]; src != 1 {\n+ if src := p.Pkt.Data.First()[1]; src != 1 {\nt.Errorf(\"Response packet has incorrect source addresss: got = %d, want = 3\", src)\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Honour the link's MaxHeaderLength when forwarding
This change also updates where the IP packet buffer is held in an
outbound tcpip.PacketBuffer from Header to Data. This change removes
unncessary copying of the IP packet buffer when forwarding.
Test: stack_test.TestNICForwarding
PiperOrigin-RevId: 300217972 |
259,884 | 10.03.2020 18:24:00 | 14,400 | 95535eca245cfa6de69c42a04a6f6b265f22e014 | Update tool compatibility. | [
{
"change_type": "MODIFY",
"old_path": "content/docs/user_guide/compatibility/_index.md",
"new_path": "content/docs/user_guide/compatibility/_index.md",
"diff": "@@ -62,24 +62,24 @@ Most common utilities work. Note that:\n| gdb | Working |\n| gosu | Working |\n| grep | Working (unless stdin is a pipe and stdout is /dev/null) |\n-| ifconfig | Works partially, like ip |\n-| ip | [In progress](https://github.com/google/gvisor/issues/769). Some subcommands work (e.g. addr, route) on alpine images. Not working on newest debian/ubuntu images. |\n+| ifconfig | Works partially, like ip. Full support [in progress](https://gvisor.dev/issue/578) |\n+| ip | Some subcommands work (e.g. addr, route). Full support [in progress](https://gvisor.dev/issue/578) |\n| less | Working |\n| ls | Working |\n| lsof | Working |\n| mount | Works in readonly mode. gVisor doesn't currently support creating new mounts at runtime |\n| nc | Working |\n| nmap | Not working |\n-| netstat | [In progress](https://github.com/google/gvisor/issues/506) |\n+| netstat | [In progress](https://gvisor.dev/issue/2112) |\n| nslookup | Working |\n| ping | Working |\n| ps | Working |\n-| route | [In progress](https://github.com/google/gvisor/issues/764) |\n-| ss | [In progress](https://github.com/google/gvisor/issues/506) |\n-| sshd | Partially working. Job control [in progress](https://github.com/google/gvisor/issues/154) |\n+| route | Working |\n+| ss | [In progress](https://gvisor.dev/issue/2114) |\n+| sshd | Partially working. Job control [in progress](https://gvisor.dev/issue/154) |\n| strace | Working |\n| tar | Working |\n-| tcpdump | Working |\n+| tcpdump | [In progress](https://gvisor.dev/issue/173) |\n| top | Working |\n| uptime | Working |\n| vim | Working |\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update tool compatibility. |
259,853 | 11.03.2020 11:44:27 | 25,200 | d3fa741fb539d16b271f1bed2bcd93e382b0b2e2 | runsc: Set asyncpreemptoff for the kvm platform
The asynchronous goroutine preemption is a new feature of Go 1.14.
When we switched to go 1.14 (cl/297915917) in the bazel config,
the kokoro syscall-kvm job started permanently failing. Lets
temporary set asyncpreemptoff for the kvm platform to unblock tests. | [
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -444,6 +444,12 @@ func (s *Sandbox) createSandboxProcess(conf *boot.Config, args *Args, startSyncF\nnextFD++\n}\n+ // TODO(b/151157106): syscall tests fail by timeout if asyncpreemptoff\n+ // isn't set.\n+ if conf.Platform == \"kvm\" {\n+ cmd.Env = append(cmd.Env, \"GODEBUG=asyncpreemptoff=1\")\n+ }\n+\n// The current process' stdio must be passed to the application via the\n// --stdio-fds flag. The stdio of the sandbox process itself must not\n// be connected to the same FDs, otherwise we risk leaking sandbox\n"
}
] | Go | Apache License 2.0 | google/gvisor | runsc: Set asyncpreemptoff for the kvm platform
The asynchronous goroutine preemption is a new feature of Go 1.14.
When we switched to go 1.14 (cl/297915917) in the bazel config,
the kokoro syscall-kvm job started permanently failing. Lets
temporary set asyncpreemptoff for the kvm platform to unblock tests.
PiperOrigin-RevId: 300372387 |
259,881 | 11.03.2020 14:38:04 | 25,200 | 5ee9bbb15d90b5f116d9482e932e0823cffd9f6e | Upgrade Kythe | [
{
"change_type": "MODIFY",
"old_path": "kokoro/kythe/generate_xrefs.sh",
"new_path": "kokoro/kythe/generate_xrefs.sh",
"diff": "@@ -23,7 +23,7 @@ bazel version\npython3 -V\n-readonly KYTHE_VERSION='v0.0.41'\n+readonly KYTHE_VERSION='v0.0.43'\nreadonly WORKDIR=\"$(mktemp -d)\"\nreadonly KYTHE_DIR=\"${WORKDIR}/kythe-${KYTHE_VERSION}\"\nif [[ -n \"$KOKORO_GIT_COMMIT\" ]]; then\n"
}
] | Go | Apache License 2.0 | google/gvisor | Upgrade Kythe
PiperOrigin-RevId: 300409401 |
259,891 | 09.03.2020 17:40:13 | 25,200 | 4054b021f05cb0902e9877ba82403978fd8d6405 | iptables: ready tests to be enabled in kokoro
Fixed flakes (tested via --runs_per_test=100) and added skips for
not-yet-implemented features. Once submitted, the iptables tests will be
ready to enable in kokoro. | [
{
"change_type": "MODIFY",
"old_path": "scripts/iptables_tests.sh",
"new_path": "scripts/iptables_tests.sh",
"diff": "@@ -19,9 +19,12 @@ source $(dirname $0)/common.sh\ninstall_runsc_for_test iptables\n# Build the docker image for the test.\n-run //test/iptables/runner-image --norun\n+run //test/iptables/runner:runner-image --norun\n-# TODO(gvisor.dev/issue/170): Also test this on runsc once iptables are better\n-# supported\n-test //test/iptables:iptables_test \"--test_arg=--runtime=runc\" \\\n+test //test/iptables:iptables_test \\\n+ \"--test_arg=--runtime=runc\" \\\n+ \"--test_arg=--image=bazel/test/iptables/runner:runner-image\"\n+\n+test //test/iptables:iptables_test \\\n+ \"--test_arg=--runtime=runsc\" \\\n\"--test_arg=--image=bazel/test/iptables/runner:runner-image\"\n"
},
{
"change_type": "MODIFY",
"old_path": "test/iptables/filter_input.go",
"new_path": "test/iptables/filter_input.go",
"diff": "@@ -106,7 +106,7 @@ func (FilterInputDropOnlyUDP) ContainerAction(ip net.IP) error {\nfunc (FilterInputDropOnlyUDP) LocalAction(ip net.IP) error {\n// Try to establish a TCP connection with the container, which should\n// succeed.\n- return connectTCP(ip, acceptPort, dropPort, sendloopDuration)\n+ return connectTCP(ip, acceptPort, sendloopDuration)\n}\n// FilterInputDropUDPPort tests that we can drop UDP traffic by port.\n@@ -192,7 +192,7 @@ func (FilterInputDropTCPDestPort) ContainerAction(ip net.IP) error {\n// LocalAction implements TestCase.LocalAction.\nfunc (FilterInputDropTCPDestPort) LocalAction(ip net.IP) error {\n- if err := connectTCP(ip, dropPort, acceptPort, sendloopDuration); err == nil {\n+ if err := connectTCP(ip, dropPort, sendloopDuration); err == nil {\nreturn fmt.Errorf(\"connection destined to port %d should not be accepted, but got accepted\", dropPort)\n}\n@@ -209,13 +209,14 @@ func (FilterInputDropTCPSrcPort) Name() string {\n// ContainerAction implements TestCase.ContainerAction.\nfunc (FilterInputDropTCPSrcPort) ContainerAction(ip net.IP) error {\n- if err := filterTable(\"-A\", \"INPUT\", \"-p\", \"tcp\", \"-m\", \"tcp\", \"--sport\", fmt.Sprintf(\"%d\", dropPort), \"-j\", \"DROP\"); err != nil {\n+ // Drop anything from an ephemeral port.\n+ if err := filterTable(\"-A\", \"INPUT\", \"-p\", \"tcp\", \"-m\", \"tcp\", \"--sport\", \"1024:65535\", \"-j\", \"DROP\"); err != nil {\nreturn err\n}\n// Listen for TCP packets on accept port.\nif err := listenTCP(acceptPort, sendloopDuration); err == nil {\n- return fmt.Errorf(\"connection destined to port %d should not be accepted, but got accepted\", dropPort)\n+ return fmt.Errorf(\"connection destined to port %d should not be accepted, but was\", dropPort)\n}\nreturn nil\n@@ -223,8 +224,8 @@ func (FilterInputDropTCPSrcPort) ContainerAction(ip net.IP) error {\n// LocalAction implements TestCase.LocalAction.\nfunc (FilterInputDropTCPSrcPort) LocalAction(ip net.IP) error {\n- if err := connectTCP(ip, acceptPort, dropPort, sendloopDuration); err == nil {\n- return fmt.Errorf(\"connection on port %d should not be acceptedi, but got accepted\", dropPort)\n+ if err := connectTCP(ip, acceptPort, sendloopDuration); err == nil {\n+ return fmt.Errorf(\"connection should not be accepted, but was\")\n}\nreturn nil\n"
},
{
"change_type": "MODIFY",
"old_path": "test/iptables/filter_output.go",
"new_path": "test/iptables/filter_output.go",
"diff": "@@ -24,7 +24,8 @@ func init() {\nRegisterTestCase(FilterOutputDropTCPSrcPort{})\n}\n-// FilterOutputDropTCPDestPort tests that connections are not accepted on specified source ports.\n+// FilterOutputDropTCPDestPort tests that connections are not accepted on\n+// specified source ports.\ntype FilterOutputDropTCPDestPort struct{}\n// Name implements TestCase.Name.\n@@ -48,14 +49,15 @@ func (FilterOutputDropTCPDestPort) ContainerAction(ip net.IP) error {\n// LocalAction implements TestCase.LocalAction.\nfunc (FilterOutputDropTCPDestPort) LocalAction(ip net.IP) error {\n- if err := connectTCP(ip, acceptPort, dropPort, sendloopDuration); err == nil {\n+ if err := connectTCP(ip, acceptPort, sendloopDuration); err == nil {\nreturn fmt.Errorf(\"connection on port %d should not be accepted, but got accepted\", dropPort)\n}\nreturn nil\n}\n-// FilterOutputDropTCPSrcPort tests that connections are not accepted on specified source ports.\n+// FilterOutputDropTCPSrcPort tests that connections are not accepted on\n+// specified source ports.\ntype FilterOutputDropTCPSrcPort struct{}\n// Name implements TestCase.Name.\n@@ -79,7 +81,7 @@ func (FilterOutputDropTCPSrcPort) ContainerAction(ip net.IP) error {\n// LocalAction implements TestCase.LocalAction.\nfunc (FilterOutputDropTCPSrcPort) LocalAction(ip net.IP) error {\n- if err := connectTCP(ip, dropPort, acceptPort, sendloopDuration); err == nil {\n+ if err := connectTCP(ip, dropPort, sendloopDuration); err == nil {\nreturn fmt.Errorf(\"connection destined to port %d should not be accepted, but got accepted\", dropPort)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/iptables/iptables_test.go",
"new_path": "test/iptables/iptables_test.go",
"diff": "@@ -191,24 +191,28 @@ func TestFilterInputDropOnlyUDP(t *testing.T) {\n}\nfunc TestNATRedirectUDPPort(t *testing.T) {\n+ t.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATRedirectUDPPort{}); err != nil {\nt.Fatal(err)\n}\n}\nfunc TestNATRedirectTCPPort(t *testing.T) {\n+ t.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATRedirectTCPPort{}); err != nil {\nt.Fatal(err)\n}\n}\nfunc TestNATDropUDP(t *testing.T) {\n+ t.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATDropUDP{}); err != nil {\nt.Fatal(err)\n}\n}\nfunc TestNATAcceptAll(t *testing.T) {\n+ t.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATAcceptAll{}); err != nil {\nt.Fatal(err)\n}\n@@ -251,12 +255,14 @@ func TestFilterInputReturnUnderflow(t *testing.T) {\n}\nfunc TestFilterOutputDropTCPDestPort(t *testing.T) {\n+ t.Skip(\"filter OUTPUT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(FilterOutputDropTCPDestPort{}); err != nil {\nt.Fatal(err)\n}\n}\nfunc TestFilterOutputDropTCPSrcPort(t *testing.T) {\n+ t.Skip(\"filter OUTPUT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(FilterOutputDropTCPSrcPort{}); err != nil {\nt.Fatal(err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/iptables/iptables_util.go",
"new_path": "test/iptables/iptables_util.go",
"diff": "@@ -125,26 +125,23 @@ func listenTCP(port int, timeout time.Duration) error {\nreturn nil\n}\n-// connectTCP connects the TCP server over specified local port, server IP and remote/server port.\n-func connectTCP(ip net.IP, remotePort, localPort int, timeout time.Duration) error {\n+// connectTCP connects to the given IP and port from an ephemeral local address.\n+func connectTCP(ip net.IP, port int, timeout time.Duration) error {\ncontAddr := net.TCPAddr{\nIP: ip,\n- Port: remotePort,\n+ Port: port,\n}\n// The container may not be listening when we first connect, so retry\n// upon error.\ncallback := func() error {\n- localAddr := net.TCPAddr{\n- Port: localPort,\n- }\n- conn, err := net.DialTCP(\"tcp4\", &localAddr, &contAddr)\n+ conn, err := net.DialTCP(\"tcp4\", nil, &contAddr)\nif conn != nil {\nconn.Close()\n}\nreturn err\n}\nif err := testutil.Poll(callback, timeout); err != nil {\n- return fmt.Errorf(\"timed out waiting to send IP, most recent error: %v\", err)\n+ return fmt.Errorf(\"timed out waiting to connect IP, most recent error: %v\", err)\n}\nreturn nil\n"
},
{
"change_type": "MODIFY",
"old_path": "test/iptables/nat.go",
"new_path": "test/iptables/nat.go",
"diff": "@@ -76,7 +76,7 @@ func (NATRedirectTCPPort) ContainerAction(ip net.IP) error {\n// LocalAction implements TestCase.LocalAction.\nfunc (NATRedirectTCPPort) LocalAction(ip net.IP) error {\n- return connectTCP(ip, dropPort, acceptPort, sendloopDuration)\n+ return connectTCP(ip, dropPort, sendloopDuration)\n}\n// NATDropUDP tests that packets are not received in ports other than redirect port.\n"
}
] | Go | Apache License 2.0 | google/gvisor | iptables: ready tests to be enabled in kokoro
Fixed flakes (tested via --runs_per_test=100) and added skips for
not-yet-implemented features. Once submitted, the iptables tests will be
ready to enable in kokoro. |
260,003 | 12.03.2020 14:34:16 | 25,200 | bbf86003bfd2a7547744b89c72e1cd06e9385e66 | Remove flaky network namespace test that uses clone(). | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -3707,11 +3707,10 @@ cc_binary(\n\":socket_test_util\",\ngtest,\n\"//test/util:capability_util\",\n- \"//test/util:memory_util\",\n+ \"//test/util:posix_error\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n\"//test/util:thread_util\",\n- \"@com_google_absl//absl/synchronization\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/network_namespace.cc",
"new_path": "test/syscalls/linux/network_namespace.cc",
"diff": "#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n-#include \"absl/synchronization/notification.h\"\n#include \"test/syscalls/linux/socket_test_util.h\"\n#include \"test/util/capability_util.h\"\n-#include \"test/util/memory_util.h\"\n+#include \"test/util/posix_error.h\"\n#include \"test/util/test_util.h\"\n#include \"test/util/thread_util.h\"\nnamespace gvisor {\nnamespace testing {\n-\nnamespace {\n-using TestFunc = std::function<PosixError()>;\n-using RunFunc = std::function<PosixError(TestFunc)>;\n-\n-struct NamespaceStrategy {\n- RunFunc run;\n-\n- static NamespaceStrategy Of(RunFunc run) {\n- NamespaceStrategy s;\n- s.run = run;\n- return s;\n- }\n-};\n+TEST(NetworkNamespaceTest, LoopbackExists) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_ADMIN)));\n-PosixError RunWithUnshare(TestFunc fn) {\n- PosixError err = PosixError(-1, \"function did not return a value\");\nScopedThread t([&] {\n- if (unshare(CLONE_NEWNET) != 0) {\n- err = PosixError(errno);\n- return;\n- }\n- err = fn();\n- });\n- t.Join();\n- return err;\n-}\n-\n-PosixError RunWithClone(TestFunc fn) {\n- struct Args {\n- absl::Notification n;\n- TestFunc fn;\n- PosixError err;\n- };\n- Args args;\n- args.fn = fn;\n- args.err = PosixError(-1, \"function did not return a value\");\n-\n- ASSIGN_OR_RETURN_ERRNO(\n- Mapping child_stack,\n- MmapAnon(kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE));\n- pid_t child = clone(\n- +[](void *arg) {\n- Args *args = reinterpret_cast<Args *>(arg);\n- args->err = args->fn();\n- args->n.Notify();\n- syscall(SYS_exit, 0); // Exit manually. No return address on stack.\n- return 0;\n- },\n- reinterpret_cast<void *>(child_stack.addr() + kPageSize),\n- CLONE_NEWNET | CLONE_THREAD | CLONE_SIGHAND | CLONE_VM, &args);\n- if (child < 0) {\n- return PosixError(errno, \"clone() failed\");\n- }\n- args.n.WaitForNotification();\n- return args.err;\n-}\n-\n-class NetworkNamespaceTest\n- : public ::testing::TestWithParam<NamespaceStrategy> {};\n-\n-TEST_P(NetworkNamespaceTest, LoopbackExists) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_ADMIN)));\n+ ASSERT_THAT(unshare(CLONE_NEWNET), SyscallSucceedsWithValue(0));\n- EXPECT_NO_ERRNO(GetParam().run([]() {\n// TODO(gvisor.dev/issue/1833): Update this to test that only \"lo\" exists.\n// Check loopback device exists.\nint sock = socket(AF_INET, SOCK_DGRAM, 0);\n- if (sock < 0) {\n- return PosixError(errno, \"socket() failed\");\n- }\n+ ASSERT_THAT(sock, SyscallSucceeds());\nstruct ifreq ifr;\n- snprintf(ifr.ifr_name, IFNAMSIZ, \"lo\");\n- if (ioctl(sock, SIOCGIFINDEX, &ifr) < 0) {\n- return PosixError(errno, \"ioctl() failed, lo cannot be found\");\n- }\n- return NoError();\n- }));\n+ strncpy(ifr.ifr_name, \"lo\", IFNAMSIZ);\n+ EXPECT_THAT(ioctl(sock, SIOCGIFINDEX, &ifr), SyscallSucceeds())\n+ << \"lo cannot be found\";\n+ });\n}\n-INSTANTIATE_TEST_SUITE_P(\n- AllNetworkNamespaceTest, NetworkNamespaceTest,\n- ::testing::Values(NamespaceStrategy::Of(RunWithUnshare),\n- NamespaceStrategy::Of(RunWithClone)));\n-\n} // namespace\n-\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove flaky network namespace test that uses clone().
PiperOrigin-RevId: 300626011 |
259,884 | 12.03.2020 18:14:31 | 14,400 | 14c1917b70a513ae71191c7fa7f24be62b1789a9 | Fix grammar mistake in Performance Guide
Fixes | [
{
"change_type": "MODIFY",
"old_path": "content/docs/architecture_guide/performance.md",
"new_path": "content/docs/architecture_guide/performance.md",
"diff": "@@ -25,9 +25,9 @@ Second, as gVisor is an independent implementation of the system call surface,\nmany of the subsystems or specific calls are not as optimized as more mature\nimplementations. A good example here is the network stack, which is continuing\nto evolve but does not support all the advanced recovery mechanisms offered by\n-other stacks and is less CPU efficient. This an **implementation cost** and is\n-distinct from **structural costs**. Improvements here are ongoing and driven by\n-the workloads that matter to gVisor users and contributors.\n+other stacks and is less CPU efficient. This is an **implementation cost** and\n+is distinct from **structural costs**. Improvements here are ongoing and driven\n+by the workloads that matter to gVisor users and contributors.\nThis page provides a guide for understanding baseline performance, and calls out\ndistint **structural costs** and **implementation costs**, highlighting where\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix grammar mistake in Performance Guide
Fixes #147 |
259,972 | 12.03.2020 18:38:41 | 25,200 | f693e1334b6fd0bea26fad770dfec3aa7e03c59a | Clarify comments about IHL in ipv4.go. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/ipv4.go",
"new_path": "pkg/tcpip/header/ipv4.go",
"diff": "@@ -38,7 +38,8 @@ const (\n// IPv4Fields contains the fields of an IPv4 packet. It is used to describe the\n// fields of a packet that needs to be encoded.\ntype IPv4Fields struct {\n- // IHL is the \"internet header length\" field of an IPv4 packet.\n+ // IHL is the \"internet header length\" field of an IPv4 packet. The value\n+ // is in bytes.\nIHL uint8\n// TOS is the \"type of service\" field of an IPv4 packet.\n@@ -138,7 +139,7 @@ func IPVersion(b []byte) int {\n}\n// HeaderLength returns the value of the \"header length\" field of the ipv4\n-// header.\n+// header. The length returned is in bytes.\nfunc (b IPv4) HeaderLength() uint8 {\nreturn (b[versIHL] & 0xf) * 4\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Clarify comments about IHL in ipv4.go.
PiperOrigin-RevId: 300668506 |
259,974 | 13.03.2020 03:02:26 | 0 | 333b74dc288357e192dbd86f6d0732be5ea7df64 | Enable syscall seccomp test on arm64. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/seccomp.cc",
"new_path": "test/syscalls/linux/seccomp.cc",
"diff": "@@ -72,8 +72,15 @@ void ApplySeccompFilter(uint32_t sysno, uint32_t filtered_result,\nstruct sock_filter filter[] = {\n// A = seccomp_data.arch\nBPF_STMT(BPF_LD | BPF_ABS | BPF_W, 4),\n+#if defined(__x86_64__)\n// if (A != AUDIT_ARCH_X86_64) goto kill\nBPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AUDIT_ARCH_X86_64, 0, 4),\n+#elif defined(__aarch64__)\n+ // if (A != AUDIT_ARCH_AARCH64) goto kill\n+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AUDIT_ARCH_AARCH64, 0, 4),\n+#else\n+#error \"Unknown architecture\"\n+#endif\n// A = seccomp_data.nr\nBPF_STMT(BPF_LD | BPF_ABS | BPF_W, 0),\n// if (A != sysno) goto allow\n@@ -179,9 +186,12 @@ TEST(SeccompTest, RetTrapCausesSIGSYS) {\nTEST_CHECK(info->si_errno == kTrapValue);\nTEST_CHECK(info->si_call_addr != nullptr);\nTEST_CHECK(info->si_syscall == kFilteredSyscall);\n-#ifdef __x86_64__\n+#if defined(__x86_64__)\nTEST_CHECK(info->si_arch == AUDIT_ARCH_X86_64);\nTEST_CHECK(uc->uc_mcontext.gregs[REG_RAX] == kFilteredSyscall);\n+#elif defined(__aarch64__)\n+ TEST_CHECK(info->si_arch == AUDIT_ARCH_AARCH64);\n+ TEST_CHECK(uc->uc_mcontext.regs[8] == kFilteredSyscall);\n#endif // defined(__x86_64__)\n_exit(0);\n});\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enable syscall seccomp test on arm64.
Signed-off-by: Haibo Xu <[email protected]>
Change-Id: Ibc926c917d98b31fc92bbf8d82d6818c39b0f93c |
259,992 | 13.03.2020 08:56:47 | 25,200 | 8f8f16efafd48da3c5e4db329a90bb76620b2324 | Add support for mount flags
Plumbs MS_NOEXEC and MS_RDONLY. Others are TODO.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsbridge/vfs.go",
"new_path": "pkg/sentry/fsbridge/vfs.go",
"diff": "@@ -115,8 +115,6 @@ func NewVFSLookup(mntns *vfs.MountNamespace, root, workingDir vfs.VirtualDentry)\n//\n// remainingTraversals is not configurable in VFS2, all callers are using the\n// default anyways.\n-//\n-// TODO(gvisor.dev/issue/1623): Check mount has read and exec permission.\nfunc (l *vfsLookup) OpenPath(ctx context.Context, pathname string, opts vfs.OpenOptions, _ *uint, resolveFinal bool) (File, error) {\nvfsObj := l.mntns.Root().Mount().Filesystem().VirtualFilesystem()\ncreds := auth.CredentialsFromContext(ctx)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/mount.go",
"new_path": "pkg/sentry/vfs/mount.go",
"diff": "@@ -74,6 +74,10 @@ type Mount struct {\n// umounted is true. umounted is protected by VirtualFilesystem.mountMu.\numounted bool\n+ // flags contains settings as specified for mount(2), e.g. MS_NOEXEC, except\n+ // for MS_RDONLY which is tracked in \"writers\".\n+ flags MountFlags\n+\n// The lower 63 bits of writers is the number of calls to\n// Mount.CheckBeginWrite() that have not yet been paired with a call to\n// Mount.EndWrite(). The MSB of writers is set if MS_RDONLY is in effect.\n@@ -81,6 +85,21 @@ type Mount struct {\nwriters int64\n}\n+func newMount(vfs *VirtualFilesystem, fs *Filesystem, root *Dentry, mntns *MountNamespace, opts *MountOptions) *Mount {\n+ mnt := &Mount{\n+ vfs: vfs,\n+ fs: fs,\n+ root: root,\n+ flags: opts.Flags,\n+ ns: mntns,\n+ refs: 1,\n+ }\n+ if opts.ReadOnly {\n+ mnt.setReadOnlyLocked(true)\n+ }\n+ return mnt\n+}\n+\n// A MountNamespace is a collection of Mounts.\n//\n// MountNamespaces are reference-counted. Unless otherwise specified, all\n@@ -129,13 +148,7 @@ func (vfs *VirtualFilesystem) NewMountNamespace(ctx context.Context, creds *auth\nrefs: 1,\nmountpoints: make(map[*Dentry]uint32),\n}\n- mntns.root = &Mount{\n- vfs: vfs,\n- fs: fs,\n- root: root,\n- ns: mntns,\n- refs: 1,\n- }\n+ mntns.root = newMount(vfs, fs, root, mntns, &MountOptions{})\nreturn mntns, nil\n}\n@@ -148,12 +161,7 @@ func (vfs *VirtualFilesystem) NewDisconnectedMount(fs *Filesystem, root *Dentry,\nif root != nil {\nroot.IncRef()\n}\n- return &Mount{\n- vfs: vfs,\n- fs: fs,\n- root: root,\n- refs: 1,\n- }, nil\n+ return newMount(vfs, fs, root, nil /* mntns */, opts), nil\n}\n// MountAt creates and mounts a Filesystem configured by the given arguments.\n@@ -218,13 +226,7 @@ func (vfs *VirtualFilesystem) MountAt(ctx context.Context, creds *auth.Credentia\n// are directories, or neither are, and returns ENOTDIR if this is not the\n// case.\nmntns := vd.mount.ns\n- mnt := &Mount{\n- vfs: vfs,\n- fs: fs,\n- root: root,\n- ns: mntns,\n- refs: 1,\n- }\n+ mnt := newMount(vfs, fs, root, mntns, opts)\nvfs.mounts.seq.BeginWrite()\nvfs.connectLocked(mnt, vd, mntns)\nvfs.mounts.seq.EndWrite()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/options.go",
"new_path": "pkg/sentry/vfs/options.go",
"diff": "@@ -46,8 +46,21 @@ type MknodOptions struct {\nDevMinor uint32\n}\n+// MountFlags contains flags as specified for mount(2), e.g. MS_NOEXEC.\n+// MS_RDONLY is not part of MountFlags because it's tracked in Mount.writers.\n+type MountFlags struct {\n+ // NoExec is equivalent to MS_NOEXEC.\n+ NoExec bool\n+}\n+\n// MountOptions contains options to VirtualFilesystem.MountAt().\ntype MountOptions struct {\n+ // Flags contains flags as specified for mount(2), e.g. MS_NOEXEC.\n+ Flags MountFlags\n+\n+ // ReadOnly is equivalent to MS_RDONLY.\n+ ReadOnly bool\n+\n// GetFilesystemOptions contains options to FilesystemType.GetFilesystem().\nGetFilesystemOptions GetFilesystemOptions\n@@ -75,7 +88,8 @@ type OpenOptions struct {\n// FileExec is set when the file is being opened to be executed.\n// VirtualFilesystem.OpenAt() checks that the caller has execute permissions\n- // on the file, and that the file is a regular file.\n+ // on the file, that the file is a regular file, and that the mount doesn't\n+ // have MS_NOEXEC set.\nFileExec bool\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/vfs.go",
"new_path": "pkg/sentry/vfs/vfs.go",
"diff": "@@ -388,6 +388,11 @@ func (vfs *VirtualFilesystem) OpenAt(ctx context.Context, creds *auth.Credential\n// TODO(gvisor.dev/issue/1193): Move inside fsimpl to avoid another call\n// to FileDescription.Stat().\nif opts.FileExec {\n+ if fd.Mount().flags.NoExec {\n+ fd.DecRef()\n+ return nil, syserror.EACCES\n+ }\n+\n// Only a regular file can be executed.\nstat, err := fd.Stat(ctx, StatOptions{Mask: linux.STATX_TYPE})\nif err != nil {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add support for mount flags
Plumbs MS_NOEXEC and MS_RDONLY. Others are TODO.
Updates #1623 #1193
PiperOrigin-RevId: 300764669 |
260,004 | 13.03.2020 10:43:09 | 25,200 | 28d26d2c4f231c447a10bcbcfb8223a804c9d8bc | Honour the link's MaxHeaderLength when forwarding
LinkEndpoints may expect/assume that the a tcpip.PacketBuffer's Header
has enough capacity for its own headers, as per documentation for
LinkEndpoint.MaxHeaderLength.
Test: stack_test.TestNICForwarding | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic.go",
"new_path": "pkg/tcpip/stack/nic.go",
"diff": "package stack\nimport (\n+ \"fmt\"\n\"log\"\n\"reflect\"\n\"sort\"\n@@ -1259,9 +1260,24 @@ func (n *NIC) DeliverNetworkPacket(linkEP LinkEndpoint, remote, local tcpip.Link\nfunc (n *NIC) forwardPacket(r *Route, protocol tcpip.NetworkProtocolNumber, pkt tcpip.PacketBuffer) {\n// TODO(b/143425874) Decrease the TTL field in forwarded packets.\n- pkt.Header = buffer.NewPrependableFromView(pkt.Data.First())\n+\n+ firstData := pkt.Data.First()\npkt.Data.RemoveFirst()\n+ if linkHeaderLen := int(n.linkEP.MaxHeaderLength()); linkHeaderLen == 0 {\n+ pkt.Header = buffer.NewPrependableFromView(firstData)\n+ } else {\n+ firstDataLen := len(firstData)\n+\n+ // pkt.Header should have enough capacity to hold n.linkEP's headers.\n+ pkt.Header = buffer.NewPrependable(firstDataLen + linkHeaderLen)\n+\n+ // TODO(b/151227689): avoid copying the packet when forwarding\n+ if n := copy(pkt.Header.Prepend(firstDataLen), firstData); n != firstDataLen {\n+ panic(fmt.Sprintf(\"copied %d bytes, expected %d\", n, firstDataLen))\n+ }\n+ }\n+\nif err := n.linkEP.WritePacket(r, nil /* gso */, protocol, pkt); err != nil {\nr.Stats().IP.OutgoingPacketErrors.Increment()\nreturn\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack_test.go",
"new_path": "pkg/tcpip/stack/stack_test.go",
"diff": "@@ -2240,57 +2240,85 @@ func TestNICStats(t *testing.T) {\n}\nfunc TestNICForwarding(t *testing.T) {\n- // Create a stack with the fake network protocol, two NICs, each with\n- // an address.\n+ const nicID1 = 1\n+ const nicID2 = 2\n+ const dstAddr = tcpip.Address(\"\\x03\")\n+\n+ tests := []struct {\n+ name string\n+ headerLen uint16\n+ }{\n+ {\n+ name: \"Zero header length\",\n+ },\n+ {\n+ name: \"Non-zero header length\",\n+ headerLen: 16,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\ns := stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},\n})\ns.SetForwarding(true)\nep1 := channel.New(10, defaultMTU, \"\")\n- if err := s.CreateNIC(1, ep1); err != nil {\n- t.Fatal(\"CreateNIC #1 failed:\", err)\n+ if err := s.CreateNIC(nicID1, ep1); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", nicID1, err)\n}\n- if err := s.AddAddress(1, fakeNetNumber, \"\\x01\"); err != nil {\n- t.Fatal(\"AddAddress #1 failed:\", err)\n+ if err := s.AddAddress(nicID1, fakeNetNumber, \"\\x01\"); err != nil {\n+ t.Fatalf(\"AddAddress(%d, %d, 0x01): %s\", nicID1, fakeNetNumber, err)\n}\n- ep2 := channel.New(10, defaultMTU, \"\")\n- if err := s.CreateNIC(2, ep2); err != nil {\n- t.Fatal(\"CreateNIC #2 failed:\", err)\n+ ep2 := channelLinkWithHeaderLength{\n+ Endpoint: channel.New(10, defaultMTU, \"\"),\n+ headerLength: test.headerLen,\n}\n- if err := s.AddAddress(2, fakeNetNumber, \"\\x02\"); err != nil {\n- t.Fatal(\"AddAddress #2 failed:\", err)\n+ if err := s.CreateNIC(nicID2, &ep2); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", nicID2, err)\n+ }\n+ if err := s.AddAddress(nicID2, fakeNetNumber, \"\\x02\"); err != nil {\n+ t.Fatalf(\"AddAddress(%d, %d, 0x02): %s\", nicID2, fakeNetNumber, err)\n}\n- // Route all packets to address 3 to NIC 2.\n+ // Route all packets to dstAddr to NIC 2.\n{\n- subnet, err := tcpip.NewSubnet(\"\\x03\", \"\\xff\")\n+ subnet, err := tcpip.NewSubnet(dstAddr, \"\\xff\")\nif err != nil {\nt.Fatal(err)\n}\n- s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: \"\\x00\", NIC: 2}})\n+ s.SetRouteTable([]tcpip.Route{{Destination: subnet, Gateway: \"\\x00\", NIC: nicID2}})\n}\n- // Send a packet to address 3.\n+ // Send a packet to dstAddr.\nbuf := buffer.NewView(30)\n- buf[0] = 3\n+ buf[0] = dstAddr[0]\nep1.InjectInbound(fakeNetNumber, tcpip.PacketBuffer{\nData: buf.ToVectorisedView(),\n})\n- if _, ok := ep2.Read(); !ok {\n- t.Fatal(\"Packet not forwarded\")\n+ pkt, ok := ep2.Read()\n+ if !ok {\n+ t.Fatal(\"packet not forwarded\")\n+ }\n+\n+ // Test that the link's MaxHeaderLength is honoured.\n+ if capacity, want := pkt.Pkt.Header.AvailableLength(), int(test.headerLen); capacity != want {\n+ t.Errorf(\"got Header.AvailableLength() = %d, want = %d\", capacity, want)\n}\n// Test that forwarding increments Tx stats correctly.\n- if got, want := s.NICInfo()[2].Stats.Tx.Packets.Value(), uint64(1); got != want {\n+ if got, want := s.NICInfo()[nicID2].Stats.Tx.Packets.Value(), uint64(1); got != want {\nt.Errorf(\"got Tx.Packets.Value() = %d, want = %d\", got, want)\n}\n- if got, want := s.NICInfo()[2].Stats.Tx.Bytes.Value(), uint64(len(buf)); got != want {\n+ if got, want := s.NICInfo()[nicID2].Stats.Tx.Bytes.Value(), uint64(len(buf)); got != want {\nt.Errorf(\"got Tx.Bytes.Value() = %d, want = %d\", got, want)\n}\n+ })\n+ }\n}\n// TestNICContextPreservation tests that you can read out via stack.NICInfo the\n"
}
] | Go | Apache License 2.0 | google/gvisor | Honour the link's MaxHeaderLength when forwarding
LinkEndpoints may expect/assume that the a tcpip.PacketBuffer's Header
has enough capacity for its own headers, as per documentation for
LinkEndpoint.MaxHeaderLength.
Test: stack_test.TestNICForwarding
PiperOrigin-RevId: 300784192 |
260,003 | 13.03.2020 11:25:49 | 25,200 | f458a325e9b6aecf2ee198de19063505c48a14d7 | Fix "application exiting with {Code:0 Signo:27}" during boot.
skips SIGURG, but later code expects
the sigchans array contains consecutive signal numbers. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/sighandling/sighandling.go",
"new_path": "pkg/sentry/sighandling/sighandling.go",
"diff": "@@ -83,12 +83,13 @@ func StartSignalForwarding(handler func(linux.Signal)) func() {\n// for their handling.\nvar sigchans []chan os.Signal\nfor sig := 1; sig <= numSignals+1; sig++ {\n+ sigchan := make(chan os.Signal, 1)\n+ sigchans = append(sigchans, sigchan)\n+\n// SIGURG is used by Go's runtime scheduler.\nif sig == int(linux.SIGURG) {\ncontinue\n}\n- sigchan := make(chan os.Signal, 1)\n- sigchans = append(sigchans, sigchan)\nsignal.Notify(sigchan, syscall.Signal(sig))\n}\n// Start up our listener.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix "application exiting with {Code:0 Signo:27}" during boot.
2aa9514a06a5e34894e606d508ac2df53b082c74 skips SIGURG, but later code expects
the sigchans array contains consecutive signal numbers.
PiperOrigin-RevId: 300793450 |
259,975 | 13.03.2020 11:50:30 | 25,200 | b8fda7f34f7e9629629bb0cdf7f7e72c7efdace9 | Run "startup" benchmark in Kokoro benchmark job. | [
{
"change_type": "MODIFY",
"old_path": "scripts/benchmark.sh",
"new_path": "scripts/benchmark.sh",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-# Run in the root of the repo.\n-cd \"$(dirname \"$0\")\"\n+source $(dirname $0)/common.sh\n+# Exporting for subprocesses as GCP APIs and tools check this environmental\n+# variable for authentication.\nexport GOOGLE_APPLICATION_CREDENTIALS=\"${KOKORO_KEYSTORE_DIR}/${GCLOUD_CREDENTIALS}\"\n-gcloud auth activate-service-account --key-file \"${GOOGLE_APPLICATION_CREDENTIALS}\"\n+gcloud auth activate-service-account \\\n+ --key-file \"${GOOGLE_APPLICATION_CREDENTIALS}\"\n-gcloud compute instances list\n-\n-bq show gvisor-benchmarks:test.test\n+bazel run //benchmarks:benchmarks -- \\\n+ --verbose \\\n+ run-gcp \\\n+ startup \\\n+ --runtime=runc \\\n+ --runtime=runsc \\\n+ --installers=head\n"
}
] | Go | Apache License 2.0 | google/gvisor | Run "startup" benchmark in Kokoro benchmark job.
PiperOrigin-RevId: 300798423 |
259,992 | 13.03.2020 12:09:58 | 25,200 | 722abdd8339f1df515beae0ad5272c8c2b2cfed0 | Skip process if it has exited | [
{
"change_type": "MODIFY",
"old_path": "test/root/runsc_test.go",
"new_path": "test/root/runsc_test.go",
"diff": "@@ -18,6 +18,7 @@ import (\n\"bytes\"\n\"fmt\"\n\"io/ioutil\"\n+ \"os\"\n\"os/exec\"\n\"path/filepath\"\n\"strconv\"\n@@ -117,6 +118,10 @@ func sandboxPid(pid int) (int, error) {\ncmdline, err := ioutil.ReadFile(filepath.Join(\"/proc\", line, \"cmdline\"))\nif err != nil {\n+ if os.IsNotExist(err) {\n+ // Raced with process exit.\n+ continue\n+ }\nreturn 0, err\n}\nargs := strings.SplitN(string(cmdline), \"\\x00\", 2)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Skip process if it has exited
PiperOrigin-RevId: 300802159 |
259,885 | 13.03.2020 12:16:59 | 25,200 | b78cee3bae142eb5c602d51874d0cbad274777e2 | Fix lock recursion in kernel.ProcessGroup.SendSignal(). | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/sessions.go",
"new_path": "pkg/sentry/kernel/sessions.go",
"diff": "@@ -246,7 +246,7 @@ func (pg *ProcessGroup) SendSignal(info *arch.SignalInfo) error {\nvar lastErr error\nfor tg := range tasks.Root.tgids {\n- if tg.ProcessGroup() == pg {\n+ if tg.processGroup == pg {\ntg.signalHandlers.mu.Lock()\ninfoCopy := *info\nif err := tg.leader.sendSignalLocked(&infoCopy, true /*group*/); err != nil {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix lock recursion in kernel.ProcessGroup.SendSignal().
PiperOrigin-RevId: 300803515 |
259,885 | 13.03.2020 13:17:59 | 25,200 | 1c0535297067179a822ba2dd9a6fe13a8be5a666 | Fix oom_score_adj.
Make oomScoreAdj a ThreadGroup field (Linux: signal_struct::oom_score_adj).
Avoid deadlock caused by Task.OOMScoreAdj()/SetOOMScoreAdj() locking Task.mu
and TaskSet.mu in the wrong order (via Task.ExitState()). | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/task.go",
"new_path": "pkg/sentry/fs/proc/task.go",
"diff": "@@ -853,15 +853,15 @@ func (o *oomScoreAdj) GetFile(ctx context.Context, dirent *fs.Dirent, flags fs.F\n// Read implements fs.FileOperations.Read.\nfunc (f *oomScoreAdjFile) Read(ctx context.Context, _ *fs.File, dst usermem.IOSequence, offset int64) (int64, error) {\n- if offset != 0 {\n- return 0, io.EOF\n+ if f.t.ExitState() == kernel.TaskExitDead {\n+ return 0, syserror.ESRCH\n}\n- adj, err := f.t.OOMScoreAdj()\n- if err != nil {\n- return 0, err\n+ var buf bytes.Buffer\n+ fmt.Fprintf(&buf, \"%d\\n\", f.t.OOMScoreAdj())\n+ if offset >= int64(buf.Len()) {\n+ return 0, io.EOF\n}\n- adjBytes := []byte(strconv.FormatInt(int64(adj), 10) + \"\\n\")\n- n, err := dst.CopyOut(ctx, adjBytes)\n+ n, err := dst.CopyOut(ctx, buf.Bytes()[offset:])\nreturn int64(n), err\n}\n@@ -880,6 +880,9 @@ func (f *oomScoreAdjFile) Write(ctx context.Context, _ *fs.File, src usermem.IOS\nreturn 0, err\n}\n+ if f.t.ExitState() == kernel.TaskExitDead {\n+ return 0, syserror.ESRCH\n+ }\nif err := f.t.SetOOMScoreAdj(v); err != nil {\nreturn 0, err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/task_files.go",
"new_path": "pkg/sentry/fsimpl/proc/task_files.go",
"diff": "@@ -539,11 +539,10 @@ var _ vfs.WritableDynamicBytesSource = (*oomScoreAdj)(nil)\n// Generate implements vfs.DynamicBytesSource.Generate.\nfunc (o *oomScoreAdj) Generate(ctx context.Context, buf *bytes.Buffer) error {\n- adj, err := o.task.OOMScoreAdj()\n- if err != nil {\n- return err\n+ if o.task.ExitState() == kernel.TaskExitDead {\n+ return syserror.ESRCH\n}\n- fmt.Fprintf(buf, \"%d\\n\", adj)\n+ fmt.Fprintf(buf, \"%d\\n\", o.task.OOMScoreAdj())\nreturn nil\n}\n@@ -562,6 +561,9 @@ func (o *oomScoreAdj) Write(ctx context.Context, src usermem.IOSequence, offset\nreturn 0, err\n}\n+ if o.task.ExitState() == kernel.TaskExitDead {\n+ return 0, syserror.ESRCH\n+ }\nif err := o.task.SetOOMScoreAdj(v); err != nil {\nreturn 0, err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task.go",
"new_path": "pkg/sentry/kernel/task.go",
"diff": "@@ -555,13 +555,6 @@ type Task struct {\n//\n// startTime is protected by mu.\nstartTime ktime.Time\n-\n- // oomScoreAdj is the task's OOM score adjustment. This is currently not\n- // used but is maintained for consistency.\n- // TODO(gvisor.dev/issue/1967)\n- //\n- // oomScoreAdj is protected by mu, and is owned by the task goroutine.\n- oomScoreAdj int32\n}\nfunc (t *Task) savePtraceTracer() *Task {\n@@ -856,27 +849,17 @@ func (t *Task) ContainerID() string {\nreturn t.containerID\n}\n-// OOMScoreAdj gets the task's OOM score adjustment.\n-func (t *Task) OOMScoreAdj() (int32, error) {\n- t.mu.Lock()\n- defer t.mu.Unlock()\n- if t.ExitState() == TaskExitDead {\n- return 0, syserror.ESRCH\n- }\n- return t.oomScoreAdj, nil\n+// OOMScoreAdj gets the task's thread group's OOM score adjustment.\n+func (t *Task) OOMScoreAdj() int32 {\n+ return atomic.LoadInt32(&t.tg.oomScoreAdj)\n}\n-// SetOOMScoreAdj sets the task's OOM score adjustment. The value should be\n-// between -1000 and 1000 inclusive.\n+// SetOOMScoreAdj sets the task's thread group's OOM score adjustment. The\n+// value should be between -1000 and 1000 inclusive.\nfunc (t *Task) SetOOMScoreAdj(adj int32) error {\n- t.mu.Lock()\n- defer t.mu.Unlock()\n- if t.ExitState() == TaskExitDead {\n- return syserror.ESRCH\n- }\nif adj > 1000 || adj < -1000 {\nreturn syserror.EINVAL\n}\n- t.oomScoreAdj = adj\n+ atomic.StoreInt32(&t.tg.oomScoreAdj, adj)\nreturn nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_clone.go",
"new_path": "pkg/sentry/kernel/task_clone.go",
"diff": "package kernel\nimport (\n+ \"sync/atomic\"\n+\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/bpf\"\n\"gvisor.dev/gvisor/pkg/sentry/inet\"\n@@ -260,15 +262,11 @@ func (t *Task) Clone(opts *CloneOptions) (ThreadID, *SyscallControl, error) {\nsh = sh.Fork()\n}\ntg = t.k.NewThreadGroup(tg.mounts, pidns, sh, opts.TerminationSignal, tg.limits.GetCopy())\n+ tg.oomScoreAdj = atomic.LoadInt32(&t.tg.oomScoreAdj)\nrseqAddr = t.rseqAddr\nrseqSignature = t.rseqSignature\n}\n- adj, err := t.OOMScoreAdj()\n- if err != nil {\n- return 0, nil, err\n- }\n-\ncfg := &TaskConfig{\nKernel: t.k,\nThreadGroup: tg,\n@@ -287,7 +285,6 @@ func (t *Task) Clone(opts *CloneOptions) (ThreadID, *SyscallControl, error) {\nRSeqAddr: rseqAddr,\nRSeqSignature: rseqSignature,\nContainerID: t.ContainerID(),\n- OOMScoreAdj: adj,\n}\nif opts.NewThreadGroup {\ncfg.Parent = t\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_start.go",
"new_path": "pkg/sentry/kernel/task_start.go",
"diff": "@@ -93,9 +93,6 @@ type TaskConfig struct {\n// ContainerID is the container the new task belongs to.\nContainerID string\n-\n- // oomScoreAdj is the task's OOM score adjustment.\n- OOMScoreAdj int32\n}\n// NewTask creates a new task defined by cfg.\n@@ -146,7 +143,6 @@ func (ts *TaskSet) newTask(cfg *TaskConfig) (*Task, error) {\nrseqSignature: cfg.RSeqSignature,\nfutexWaiter: futex.NewWaiter(),\ncontainerID: cfg.ContainerID,\n- oomScoreAdj: cfg.OOMScoreAdj,\n}\nt.creds.Store(cfg.Credentials)\nt.endStopCond.L = &t.tg.signalHandlers.mu\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/thread_group.go",
"new_path": "pkg/sentry/kernel/thread_group.go",
"diff": "@@ -254,6 +254,13 @@ type ThreadGroup struct {\n//\n// tty is protected by the signal mutex.\ntty *TTY\n+\n+ // oomScoreAdj is the thread group's OOM score adjustment. This is\n+ // currently not used but is maintained for consistency.\n+ // TODO(gvisor.dev/issue/1967)\n+ //\n+ // oomScoreAdj is accessed using atomic memory operations.\n+ oomScoreAdj int32\n}\n// NewThreadGroup returns a new, empty thread group in PID namespace pidns. The\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix oom_score_adj.
- Make oomScoreAdj a ThreadGroup field (Linux: signal_struct::oom_score_adj).
- Avoid deadlock caused by Task.OOMScoreAdj()/SetOOMScoreAdj() locking Task.mu
and TaskSet.mu in the wrong order (via Task.ExitState()).
PiperOrigin-RevId: 300814698 |
259,885 | 13.03.2020 16:08:06 | 25,200 | b0f2c3e7646df603156f1b8e8b3382f33353eb04 | Fix infinite loop in semaphore.sem.wakeWaiters(). | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/semaphore/semaphore.go",
"new_path": "pkg/sentry/kernel/semaphore/semaphore.go",
"diff": "@@ -554,6 +554,7 @@ func (s *sem) wakeWaiters() {\nfor w := s.waiters.Front(); w != nil; {\nif s.value < w.value {\n// Still blocked, skip it.\n+ w = w.Next()\ncontinue\n}\nw.ch <- struct{}{}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix infinite loop in semaphore.sem.wakeWaiters().
PiperOrigin-RevId: 300845134 |
259,992 | 13.03.2020 17:16:59 | 25,200 | 829beebf0b67e20e50dd5ec4a5030636e38cc576 | Panic if file in FDTable has been destroyed
This will give more information about the file to
identify where possibly the extra DecRef()
would be. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/fd_table.go",
"new_path": "pkg/sentry/kernel/fd_table.go",
"diff": "@@ -195,6 +195,8 @@ func (f *FDTable) Size() int {\n//\n// It is the caller's responsibility to acquire an appropriate lock.\nfunc (f *FDTable) forEach(fn func(fd int32, file *fs.File, fileVFS2 *vfs.FileDescription, flags FDFlags)) {\n+ // retries tracks the number of failed TryIncRef attempts for the same FD.\n+ retries := 0\nfd := int32(0)\nfor {\nfile, fileVFS2, flags, ok := f.getAll(fd)\n@@ -204,17 +206,26 @@ func (f *FDTable) forEach(fn func(fd int32, file *fs.File, fileVFS2 *vfs.FileDes\nswitch {\ncase file != nil:\nif !file.TryIncRef() {\n+ retries++\n+ if retries > 1000 {\n+ panic(fmt.Sprintf(\"File in FD table has been destroyed. FD: %d, File: %+v, FileOps: %+v\", fd, file, file.FileOperations))\n+ }\ncontinue // Race caught.\n}\nfn(fd, file, nil, flags)\nfile.DecRef()\ncase fileVFS2 != nil:\nif !fileVFS2.TryIncRef() {\n+ retries++\n+ if retries > 1000 {\n+ panic(fmt.Sprintf(\"File in FD table has been destroyed. FD: %d, File: %+v, Impl: %+v\", fd, fileVFS2, fileVFS2.Impl()))\n+ }\ncontinue // Race caught.\n}\nfn(fd, nil, fileVFS2, flags)\nfileVFS2.DecRef()\n}\n+ retries = 0\nfd++\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Panic if file in FDTable has been destroyed
This will give more information about the file to
identify where possibly the extra DecRef()
would be.
PiperOrigin-RevId: 300855874 |
259,992 | 14.03.2020 13:46:55 | 25,200 | 97127750289b49dd5e29f8ddb4209137e47fe52d | Disallow kernfs.Inode.SetStat for readonly inodes
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/dynamic_bytes_file.go",
"new_path": "pkg/sentry/fsimpl/kernfs/dynamic_bytes_file.go",
"diff": "@@ -61,9 +61,10 @@ func (f *DynamicBytesFile) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vf\nreturn &fd.vfsfd, nil\n}\n-// SetStat implements Inode.SetStat.\n-func (f *DynamicBytesFile) SetStat(*vfs.Filesystem, vfs.SetStatOptions) error {\n- // DynamicBytesFiles are immutable.\n+// SetStat implements Inode.SetStat. By default DynamicBytesFile doesn't allow\n+// inode attributes to be changed. Override SetStat() making it call\n+// f.InodeAttrs to allow it.\n+func (*DynamicBytesFile) SetStat(*vfs.Filesystem, vfs.SetStatOptions) error {\nreturn syserror.EPERM\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go",
"new_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go",
"diff": "@@ -228,7 +228,7 @@ func (a *InodeAttrs) Stat(*vfs.Filesystem, vfs.StatOptions) (linux.Statx, error)\nstat.GID = atomic.LoadUint32(&a.gid)\nstat.Nlink = atomic.LoadUint32(&a.nlink)\n- // TODO: Implement other stat fields like timestamps.\n+ // TODO(gvisor.dev/issue/1193): Implement other stat fields like timestamps.\nreturn stat, nil\n}\n@@ -256,7 +256,7 @@ func (a *InodeAttrs) SetStat(_ *vfs.Filesystem, opts vfs.SetStatOptions) error {\n// Note that not all fields are modifiable. For example, the file type and\n// inode numbers are immutable after node creation.\n- // TODO: Implement other stat fields like timestamps.\n+ // TODO(gvisor.dev/issue/1193): Implement other stat fields like timestamps.\nreturn nil\n}\n@@ -555,6 +555,11 @@ func (s *StaticDirectory) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vfs\nreturn fd.VFSFileDescription(), nil\n}\n+// SetStat implements Inode.SetStat not allowing inode attributes to be changed.\n+func (*StaticDirectory) SetStat(*vfs.Filesystem, vfs.SetStatOptions) error {\n+ return syserror.EPERM\n+}\n+\n// AlwaysValid partially implements kernfs.inodeDynamicLookup.\ntype AlwaysValid struct{}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/symlink.go",
"new_path": "pkg/sentry/fsimpl/kernfs/symlink.go",
"diff": "@@ -18,6 +18,8 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n)\n// StaticSymlink provides an Inode implementation for symlinks that point to\n@@ -52,3 +54,8 @@ func (s *StaticSymlink) Init(creds *auth.Credentials, ino uint64, target string)\nfunc (s *StaticSymlink) Readlink(_ context.Context) (string, error) {\nreturn s.target, nil\n}\n+\n+// SetStat implements Inode.SetStat not allowing inode attributes to be changed.\n+func (*StaticSymlink) SetStat(*vfs.Filesystem, vfs.SetStatOptions) error {\n+ return syserror.EPERM\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/subtasks.go",
"new_path": "pkg/sentry/fsimpl/proc/subtasks.go",
"diff": "@@ -127,3 +127,8 @@ func (i *subtasksInode) Stat(vsfs *vfs.Filesystem, opts vfs.StatOptions) (linux.\n}\nreturn stat, nil\n}\n+\n+// SetStat implements Inode.SetStat not allowing inode attributes to be changed.\n+func (*subtasksInode) SetStat(*vfs.Filesystem, vfs.SetStatOptions) error {\n+ return syserror.EPERM\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/task.go",
"new_path": "pkg/sentry/fsimpl/proc/task.go",
"diff": "@@ -107,14 +107,10 @@ func (i *taskInode) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vfs.OpenO\nreturn fd.VFSFileDescription(), nil\n}\n-// SetStat implements kernfs.Inode.\n-func (i *taskInode) SetStat(_ *vfs.Filesystem, opts vfs.SetStatOptions) error {\n- stat := opts.Stat\n- if stat.Mask&linux.STATX_MODE != 0 {\n+// SetStat implements Inode.SetStat not allowing inode attributes to be changed.\n+func (*taskInode) SetStat(*vfs.Filesystem, vfs.SetStatOptions) error {\nreturn syserror.EPERM\n}\n- return nil\n-}\n// taskOwnedInode implements kernfs.Inode and overrides inode owner with task\n// effective user and group.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/tasks.go",
"new_path": "pkg/sentry/fsimpl/proc/tasks.go",
"diff": "@@ -67,7 +67,7 @@ var _ kernfs.Inode = (*tasksInode)(nil)\nfunc newTasksInode(inoGen InoGenerator, k *kernel.Kernel, pidns *kernel.PIDNamespace, cgroupControllers map[string]string) (*tasksInode, *kernfs.Dentry) {\nroot := auth.NewRootCredentials(pidns.UserNamespace())\ncontents := map[string]*kernfs.Dentry{\n- \"cpuinfo\": newDentry(root, inoGen.NextIno(), 0444, newStaticFile(cpuInfoData(k))),\n+ \"cpuinfo\": newDentry(root, inoGen.NextIno(), 0444, newStaticFileSetStat(cpuInfoData(k))),\n\"filesystems\": newDentry(root, inoGen.NextIno(), 0444, &filesystemsData{}),\n\"loadavg\": newDentry(root, inoGen.NextIno(), 0444, &loadavgData{}),\n\"sys\": newSysDir(root, inoGen, k),\n@@ -225,6 +225,20 @@ func (i *tasksInode) Stat(vsfs *vfs.Filesystem, opts vfs.StatOptions) (linux.Sta\nreturn stat, nil\n}\n+// staticFileSetStat implements a special static file that allows inode\n+// attributes to be set. This is to support /proc files that are readonly, but\n+// allow attributes to be set.\n+type staticFileSetStat struct {\n+ dynamicBytesFileSetAttr\n+ vfs.StaticData\n+}\n+\n+var _ dynamicInode = (*staticFileSetStat)(nil)\n+\n+func newStaticFileSetStat(data string) *staticFileSetStat {\n+ return &staticFileSetStat{StaticData: vfs.StaticData{Data: data}}\n+}\n+\nfunc cpuInfoData(k *kernel.Kernel) string {\nfeatures := k.FeatureSet()\nif features == nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/tasks_files.go",
"new_path": "pkg/sentry/fsimpl/proc/tasks_files.go",
"diff": "@@ -26,6 +26,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n\"gvisor.dev/gvisor/pkg/sentry/usage\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n@@ -62,6 +63,11 @@ func (s *selfSymlink) Readlink(ctx context.Context) (string, error) {\nreturn strconv.FormatUint(uint64(tgid), 10), nil\n}\n+// SetStat implements Inode.SetStat not allowing inode attributes to be changed.\n+func (*selfSymlink) SetStat(*vfs.Filesystem, vfs.SetStatOptions) error {\n+ return syserror.EPERM\n+}\n+\ntype threadSelfSymlink struct {\nkernfs.InodeAttrs\nkernfs.InodeNoopRefCount\n@@ -95,6 +101,23 @@ func (s *threadSelfSymlink) Readlink(ctx context.Context) (string, error) {\nreturn fmt.Sprintf(\"%d/task/%d\", tgid, tid), nil\n}\n+// SetStat implements Inode.SetStat not allowing inode attributes to be changed.\n+func (*threadSelfSymlink) SetStat(*vfs.Filesystem, vfs.SetStatOptions) error {\n+ return syserror.EPERM\n+}\n+\n+// dynamicBytesFileSetAttr implements a special file that allows inode\n+// attributes to be set. This is to support /proc files that are readonly, but\n+// allow attributes to be set.\n+type dynamicBytesFileSetAttr struct {\n+ kernfs.DynamicBytesFile\n+}\n+\n+// SetStat implements Inode.SetStat.\n+func (d *dynamicBytesFileSetAttr) SetStat(fs *vfs.Filesystem, opts vfs.SetStatOptions) error {\n+ return d.DynamicBytesFile.InodeAttrs.SetStat(fs, opts)\n+}\n+\n// cpuStats contains the breakdown of CPU time for /proc/stat.\ntype cpuStats struct {\n// user is time spent in userspace tasks with non-positive niceness.\n@@ -137,7 +160,7 @@ func (c cpuStats) String() string {\n//\n// +stateify savable\ntype statData struct {\n- kernfs.DynamicBytesFile\n+ dynamicBytesFileSetAttr\n}\nvar _ dynamicInode = (*statData)(nil)\n@@ -201,7 +224,7 @@ func (*statData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n//\n// +stateify savable\ntype loadavgData struct {\n- kernfs.DynamicBytesFile\n+ dynamicBytesFileSetAttr\n}\nvar _ dynamicInode = (*loadavgData)(nil)\n@@ -220,7 +243,7 @@ func (*loadavgData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n//\n// +stateify savable\ntype meminfoData struct {\n- kernfs.DynamicBytesFile\n+ dynamicBytesFileSetAttr\n}\nvar _ dynamicInode = (*meminfoData)(nil)\n@@ -271,7 +294,7 @@ func (*meminfoData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n//\n// +stateify savable\ntype uptimeData struct {\n- kernfs.DynamicBytesFile\n+ dynamicBytesFileSetAttr\n}\nvar _ dynamicInode = (*uptimeData)(nil)\n@@ -290,7 +313,7 @@ func (*uptimeData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n//\n// +stateify savable\ntype versionData struct {\n- kernfs.DynamicBytesFile\n+ dynamicBytesFileSetAttr\n}\nvar _ dynamicInode = (*versionData)(nil)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/sys/sys.go",
"new_path": "pkg/sentry/fsimpl/sys/sys.go",
"diff": "@@ -94,15 +94,17 @@ func (fs *filesystem) newDir(creds *auth.Credentials, mode linux.FileMode, conte\nreturn &d.dentry\n}\n-// SetStat implements kernfs.Inode.SetStat.\n-func (d *dir) SetStat(fs *vfs.Filesystem, opts vfs.SetStatOptions) error {\n+// SetStat implements Inode.SetStat not allowing inode attributes to be changed.\n+func (*dir) SetStat(*vfs.Filesystem, vfs.SetStatOptions) error {\nreturn syserror.EPERM\n}\n// Open implements kernfs.Inode.Open.\nfunc (d *dir) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\nfd := &kernfs.GenericDirectoryFD{}\n- fd.Init(rp.Mount(), vfsd, &d.OrderedChildren, &opts)\n+ if err := fd.Init(rp.Mount(), vfsd, &d.OrderedChildren, &opts); err != nil {\n+ return nil, err\n+ }\nreturn fd.VFSFileDescription(), nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Disallow kernfs.Inode.SetStat for readonly inodes
Updates #1195, #1193
PiperOrigin-RevId: 300950993 |
259,884 | 12.03.2020 18:10:13 | 14,400 | e024f8fa560c1420039f8e29b601f30b1bb233e5 | Add FAQ to website for Kernel bug issue. | [
{
"change_type": "MODIFY",
"old_path": "content/docs/user_guide/FAQ.md",
"new_path": "content/docs/user_guide/FAQ.md",
"diff": "@@ -78,6 +78,18 @@ sudo chown root:root /usr/local/bin/runsc\nsudo chmod 0755 /usr/local/bin/runsc\n```\n+### I'm getting an error like `mount submount \"/etc/hostname\": creating mount with source \".../hostname\": input/output error: unknown.`\n+\n+There is a bug in Linux kernel versions 5.1 to 5.3.15, 5.4.2, and 5.5. Upgrade to a newer kernel or add the following to `/lib/systemd/system/containerd.service` as a workaround.\n+\n+```\n+LimitMEMLOCK=infinity\n+```\n+\n+And run `systemctl daemon-reload && systemctl restart containerd` to restart containerd.\n+\n+See [issue #1765](https://gvisor.dev/issue/1765) for more details.\n+\n### My container cannot resolve another container's name when using Docker user defined bridge\nThis is normally indicated by errors like `bad address 'container-name'` when\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add FAQ to website for Kernel bug issue.
https://github.com/google/gvisor/issues/1765 |
259,962 | 16.03.2020 08:02:05 | 25,200 | 52758e16e0d1e67b3cdd56e04abfce663607ac42 | Prevent vnetHdr from escaping in WritePacket. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/endpoint.go",
"new_path": "pkg/tcpip/link/fdbased/endpoint.go",
"diff": "@@ -407,7 +407,6 @@ func (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, protocol tcpip.Ne\nif e.Capabilities()&stack.CapabilityHardwareGSO != 0 {\nvnetHdr := virtioNetHdr{}\n- vnetHdrBuf := vnetHdrToByteSlice(&vnetHdr)\nif gso != nil {\nvnetHdr.hdrLen = uint16(pkt.Header.UsedLength())\nif gso.NeedsCsum {\n@@ -428,6 +427,7 @@ func (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, protocol tcpip.Ne\n}\n}\n+ vnetHdrBuf := vnetHdrToByteSlice(&vnetHdr)\nreturn rawfile.NonBlockingWrite3(e.fds[0], vnetHdrBuf, pkt.Header.View(), pkt.Data.ToView())\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/endpoint_unsafe.go",
"new_path": "pkg/tcpip/link/fdbased/endpoint_unsafe.go",
"diff": "@@ -24,9 +24,10 @@ import (\nconst virtioNetHdrSize = int(unsafe.Sizeof(virtioNetHdr{}))\nfunc vnetHdrToByteSlice(hdr *virtioNetHdr) (slice []byte) {\n- sh := (*reflect.SliceHeader)(unsafe.Pointer(&slice))\n- sh.Data = uintptr(unsafe.Pointer(hdr))\n- sh.Len = virtioNetHdrSize\n- sh.Cap = virtioNetHdrSize\n+ *(*reflect.SliceHeader)(unsafe.Pointer(&slice)) = reflect.SliceHeader{\n+ Data: uintptr((unsafe.Pointer(hdr))),\n+ Len: virtioNetHdrSize,\n+ Cap: virtioNetHdrSize,\n+ }\nreturn\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Prevent vnetHdr from escaping in WritePacket.
PiperOrigin-RevId: 301157950 |
260,003 | 16.03.2020 12:02:33 | 25,200 | 69da42885aff9371fd53227583a546df914de02b | Enable ARP resolution in TAP devices. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/tun/device.go",
"new_path": "pkg/tcpip/link/tun/device.go",
"diff": "@@ -98,7 +98,12 @@ func (d *Device) SetIff(s *stack.Stack, name string, flags uint16) error {\nprefix = \"tap\"\n}\n- endpoint, err := attachOrCreateNIC(s, name, prefix)\n+ linkCaps := stack.CapabilityNone\n+ if isTap {\n+ linkCaps |= stack.CapabilityResolutionRequired\n+ }\n+\n+ endpoint, err := attachOrCreateNIC(s, name, prefix, linkCaps)\nif err != nil {\nreturn syserror.EINVAL\n}\n@@ -109,7 +114,7 @@ func (d *Device) SetIff(s *stack.Stack, name string, flags uint16) error {\nreturn nil\n}\n-func attachOrCreateNIC(s *stack.Stack, name, prefix string) (*tunEndpoint, error) {\n+func attachOrCreateNIC(s *stack.Stack, name, prefix string, linkCaps stack.LinkEndpointCapabilities) (*tunEndpoint, error) {\nfor {\n// 1. Try to attach to an existing NIC.\nif name != \"\" {\n@@ -135,6 +140,7 @@ func attachOrCreateNIC(s *stack.Stack, name, prefix string) (*tunEndpoint, error\nnicID: id,\nname: name,\n}\n+ endpoint.Endpoint.LinkEPCapabilities = linkCaps\nif endpoint.name == \"\" {\nendpoint.name = fmt.Sprintf(\"%s%d\", prefix, id)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/tuntap.cc",
"new_path": "test/syscalls/linux/tuntap.cc",
"diff": "@@ -256,50 +256,59 @@ TEST_F(TuntapTest, WriteToDownDevice) {\nEXPECT_THAT(write(fd.get(), buf, sizeof(buf)), SyscallFailsWithErrno(EIO));\n}\n-// This test sets up a TAP device and pings kernel by sending ICMP echo request.\n-//\n-// It works as the following:\n-// * Open /dev/net/tun, and create kTapName interface.\n-// * Use rtnetlink to do initial setup of the interface:\n-// * Assign IP address 10.0.0.1/24 to kernel.\n-// * MAC address: kMacA\n-// * Bring up the interface.\n-// * Send an ICMP echo reqest (ping) packet from 10.0.0.2 (kMacB) to kernel.\n-// * Loop to receive packets from TAP device/fd:\n-// * If packet is an ICMP echo reply, it stops and passes the test.\n-// * If packet is an ARP request, it responds with canned reply and resends\n-// the\n-// ICMP request packet.\n-TEST_F(TuntapTest, PingKernel) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_ADMIN)));\n-\n+PosixErrorOr<FileDescriptor> OpenAndAttachTap(\n+ const std::string& dev_name, const std::string& dev_ipv4_addr) {\n// Interface creation.\n- FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(kDevNetTun, O_RDWR));\n+ ASSIGN_OR_RETURN_ERRNO(FileDescriptor fd, Open(kDevNetTun, O_RDWR));\nstruct ifreq ifr_set = {};\nifr_set.ifr_flags = IFF_TAP;\n- strncpy(ifr_set.ifr_name, kTapName, IFNAMSIZ);\n- EXPECT_THAT(ioctl(fd.get(), TUNSETIFF, &ifr_set),\n- SyscallSucceedsWithValue(0));\n+ strncpy(ifr_set.ifr_name, dev_name.c_str(), IFNAMSIZ);\n+ if (ioctl(fd.get(), TUNSETIFF, &ifr_set) < 0) {\n+ return PosixError(errno);\n+ }\n- absl::optional<Link> link =\n- ASSERT_NO_ERRNO_AND_VALUE(GetLinkByName(kTapName));\n- ASSERT_TRUE(link.has_value());\n+ ASSIGN_OR_RETURN_ERRNO(absl::optional<Link> link, GetLinkByName(dev_name));\n+ if (!link.has_value()) {\n+ return PosixError(ENOENT, \"no link\");\n+ }\n// Interface setup.\nstruct in_addr addr;\n- inet_pton(AF_INET, \"10.0.0.1\", &addr);\n+ inet_pton(AF_INET, dev_ipv4_addr.c_str(), &addr);\nEXPECT_NO_ERRNO(LinkAddLocalAddr(link->index, AF_INET, /*prefixlen=*/24,\n&addr, sizeof(addr)));\nif (!IsRunningOnGvisor()) {\n// FIXME: gVisor doesn't support setting MAC address on interfaces yet.\n- EXPECT_NO_ERRNO(LinkSetMacAddr(link->index, kMacA, sizeof(kMacA)));\n+ RETURN_IF_ERRNO(LinkSetMacAddr(link->index, kMacA, sizeof(kMacA)));\n// FIXME: gVisor always creates enabled/up'd interfaces.\n- EXPECT_NO_ERRNO(LinkChangeFlags(link->index, IFF_UP, IFF_UP));\n+ RETURN_IF_ERRNO(LinkChangeFlags(link->index, IFF_UP, IFF_UP));\n}\n+ return fd;\n+}\n+\n+// This test sets up a TAP device and pings kernel by sending ICMP echo request.\n+//\n+// It works as the following:\n+// * Open /dev/net/tun, and create kTapName interface.\n+// * Use rtnetlink to do initial setup of the interface:\n+// * Assign IP address 10.0.0.1/24 to kernel.\n+// * MAC address: kMacA\n+// * Bring up the interface.\n+// * Send an ICMP echo reqest (ping) packet from 10.0.0.2 (kMacB) to kernel.\n+// * Loop to receive packets from TAP device/fd:\n+// * If packet is an ICMP echo reply, it stops and passes the test.\n+// * If packet is an ARP request, it responds with canned reply and resends\n+// the\n+// ICMP request packet.\n+TEST_F(TuntapTest, PingKernel) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_ADMIN)));\n+\n+ FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(OpenAndAttachTap(kTapName, \"10.0.0.1\"));\nping_pkt ping_req = CreatePingPacket(kMacB, \"10.0.0.2\", kMacA, \"10.0.0.1\");\nstd::string arp_rep = CreateArpPacket(kMacB, \"10.0.0.2\", kMacA, \"10.0.0.1\");\n@@ -349,5 +358,47 @@ TEST_F(TuntapTest, PingKernel) {\n}\n}\n+TEST_F(TuntapTest, SendUdpTriggersArpResolution) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_ADMIN)));\n+\n+ FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(OpenAndAttachTap(kTapName, \"10.0.0.1\"));\n+\n+ // Send a UDP packet to remote.\n+ int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);\n+ ASSERT_THAT(sock, SyscallSucceeds());\n+\n+ struct sockaddr_in remote = {};\n+ remote.sin_family = AF_INET;\n+ remote.sin_port = htons(42);\n+ inet_pton(AF_INET, \"10.0.0.2\", &remote.sin_addr);\n+ int ret = sendto(sock, \"hello\", 5, 0, reinterpret_cast<sockaddr*>(&remote),\n+ sizeof(remote));\n+ ASSERT_THAT(ret, ::testing::AnyOf(SyscallSucceeds(),\n+ SyscallFailsWithErrno(EHOSTDOWN)));\n+\n+ struct inpkt {\n+ union {\n+ pihdr pi;\n+ arp_pkt arp;\n+ };\n+ };\n+ while (1) {\n+ inpkt r = {};\n+ int n = read(fd.get(), &r, sizeof(r));\n+ EXPECT_THAT(n, SyscallSucceeds());\n+\n+ if (n < sizeof(pihdr)) {\n+ std::cerr << \"Ignored packet, protocol: \" << r.pi.pi_protocol\n+ << \" len: \" << n << std::endl;\n+ continue;\n+ }\n+\n+ if (n >= sizeof(arp_pkt) && r.pi.pi_protocol == htons(ETH_P_ARP)) {\n+ break;\n+ }\n+ }\n+}\n+\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enable ARP resolution in TAP devices.
PiperOrigin-RevId: 301208471 |
259,992 | 16.03.2020 13:28:00 | 25,200 | 0f60799a4f8c3db567973574147370fc900df55f | Add calls to vfs.CheckSetStat to fsimpls
Only gofer filesystem was calling vfs.CheckSetStat for
vfs.FilesystemImpl.SetStatAt and vfs.FileDescriptionImpl.SetStat.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/host/host.go",
"new_path": "pkg/sentry/fsimpl/host/host.go",
"diff": "@@ -114,7 +114,8 @@ type inode struct {\nino uint64\n// mu protects the inode metadata below.\n- mu sync.Mutex\n+ // TODO(gvisor.dev/issue/1672): actually protect fields below.\n+ //mu sync.Mutex\n// mode is the file mode of this inode. Note that this value may become out\n// of date if the mode is changed on the host, e.g. with chmod.\n@@ -269,16 +270,20 @@ func (i *inode) fstat(opts vfs.StatOptions) (linux.Statx, error) {\n}\n// SetStat implements kernfs.Inode.\n-func (i *inode) SetStat(_ *vfs.Filesystem, opts vfs.SetStatOptions) error {\n+func (i *inode) SetStat(fs *vfs.Filesystem, creds *auth.Credentials, opts vfs.SetStatOptions) error {\ns := opts.Stat\nm := s.Mask\nif m == 0 {\nreturn nil\n}\n- if m&(linux.STATX_UID|linux.STATX_GID) != 0 {\n+ if m&^(linux.STATX_MODE|linux.STATX_SIZE|linux.STATX_ATIME|linux.STATX_MTIME) != 0 {\nreturn syserror.EPERM\n}\n+ if err := vfs.CheckSetStat(creds, &s, uint16(i.Mode().Permissions()), i.uid, i.gid); err != nil {\n+ return err\n+ }\n+\nif m&linux.STATX_MODE != 0 {\nif err := syscall.Fchmod(i.hostFD, uint32(s.Mode)); err != nil {\nreturn err\n@@ -375,8 +380,9 @@ type fileDescription struct {\n}\n// SetStat implements vfs.FileDescriptionImpl.\n-func (f *fileDescription) SetStat(_ context.Context, opts vfs.SetStatOptions) error {\n- return f.inode.SetStat(nil, opts)\n+func (f *fileDescription) SetStat(ctx context.Context, opts vfs.SetStatOptions) error {\n+ creds := auth.CredentialsFromContext(ctx)\n+ return f.inode.SetStat(nil, creds, opts)\n}\n// Stat implements vfs.FileDescriptionImpl.\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": "@@ -64,7 +64,7 @@ func (f *DynamicBytesFile) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vf\n// SetStat implements Inode.SetStat. By default DynamicBytesFile doesn't allow\n// inode attributes to be changed. Override SetStat() making it call\n// f.InodeAttrs to allow it.\n-func (*DynamicBytesFile) SetStat(*vfs.Filesystem, vfs.SetStatOptions) error {\n+func (*DynamicBytesFile) SetStat(*vfs.Filesystem, *auth.Credentials, vfs.SetStatOptions) error {\nreturn syserror.EPERM\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": "@@ -17,6 +17,7 @@ package kernfs\nimport (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/memmap\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n@@ -206,6 +207,7 @@ func (fd *GenericDirectoryFD) Stat(ctx context.Context, opts vfs.StatOptions) (l\n// SetStat implements vfs.FileDescriptionImpl.SetStat.\nfunc (fd *GenericDirectoryFD) SetStat(ctx context.Context, opts vfs.SetStatOptions) error {\nfs := fd.filesystem()\n+ creds := auth.CredentialsFromContext(ctx)\ninode := fd.vfsfd.VirtualDentry().Dentry().Impl().(*Dentry).inode\n- return inode.SetStat(fs, opts)\n+ return inode.SetStat(fs, creds, opts)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go",
"diff": "@@ -636,7 +636,7 @@ func (fs *Filesystem) SetStatAt(ctx context.Context, rp *vfs.ResolvingPath, opts\nif opts.Stat.Mask == 0 {\nreturn nil\n}\n- return inode.SetStat(fs.VFSFilesystem(), opts)\n+ return inode.SetStat(fs.VFSFilesystem(), rp.Credentials(), opts)\n}\n// StatAt implements vfs.FilesystemImpl.StatAt.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go",
"new_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go",
"diff": "@@ -234,7 +234,17 @@ func (a *InodeAttrs) Stat(*vfs.Filesystem, vfs.StatOptions) (linux.Statx, error)\n}\n// SetStat implements Inode.SetStat.\n-func (a *InodeAttrs) SetStat(_ *vfs.Filesystem, opts vfs.SetStatOptions) error {\n+func (a *InodeAttrs) SetStat(fs *vfs.Filesystem, creds *auth.Credentials, opts vfs.SetStatOptions) error {\n+ if opts.Stat.Mask == 0 {\n+ return nil\n+ }\n+ if opts.Stat.Mask&^(linux.STATX_MODE|linux.STATX_UID|linux.STATX_GID) != 0 {\n+ return syserror.EPERM\n+ }\n+ if err := vfs.CheckSetStat(creds, &opts.Stat, uint16(a.Mode().Permissions()), auth.KUID(atomic.LoadUint32(&a.uid)), auth.KGID(atomic.LoadUint32(&a.gid))); err != nil {\n+ return err\n+ }\n+\nstat := opts.Stat\nif stat.Mask&linux.STATX_MODE != 0 {\nfor {\n@@ -556,7 +566,7 @@ func (s *StaticDirectory) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vfs\n}\n// SetStat implements Inode.SetStat not allowing inode attributes to be changed.\n-func (*StaticDirectory) SetStat(*vfs.Filesystem, vfs.SetStatOptions) error {\n+func (*StaticDirectory) SetStat(*vfs.Filesystem, *auth.Credentials, vfs.SetStatOptions) error {\nreturn syserror.EPERM\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/kernfs.go",
"new_path": "pkg/sentry/fsimpl/kernfs/kernfs.go",
"diff": "@@ -330,8 +330,10 @@ type inodeMetadata interface {\nStat(fs *vfs.Filesystem, opts vfs.StatOptions) (linux.Statx, error)\n// SetStat updates the metadata for this inode. This corresponds to\n- // vfs.FilesystemImpl.SetStatAt.\n- SetStat(fs *vfs.Filesystem, opts vfs.SetStatOptions) error\n+ // vfs.FilesystemImpl.SetStatAt. Implementations are responsible for checking\n+ // if the operation can be performed (see vfs.CheckSetStat() for common\n+ // checks).\n+ SetStat(fs *vfs.Filesystem, creds *auth.Credentials, opts vfs.SetStatOptions) error\n}\n// Precondition: All methods in this interface may only be called on directory\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/kernfs_test.go",
"new_path": "pkg/sentry/fsimpl/kernfs/kernfs_test.go",
"diff": "@@ -91,7 +91,7 @@ type attrs struct {\nkernfs.InodeAttrs\n}\n-func (a *attrs) SetStat(fs *vfs.Filesystem, opt vfs.SetStatOptions) error {\n+func (*attrs) SetStat(*vfs.Filesystem, *auth.Credentials, vfs.SetStatOptions) error {\nreturn syserror.EPERM\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/symlink.go",
"new_path": "pkg/sentry/fsimpl/kernfs/symlink.go",
"diff": "@@ -56,6 +56,6 @@ func (s *StaticSymlink) Readlink(_ context.Context) (string, error) {\n}\n// SetStat implements Inode.SetStat not allowing inode attributes to be changed.\n-func (*StaticSymlink) SetStat(*vfs.Filesystem, vfs.SetStatOptions) error {\n+func (*StaticSymlink) SetStat(*vfs.Filesystem, *auth.Credentials, vfs.SetStatOptions) error {\nreturn syserror.EPERM\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/subtasks.go",
"new_path": "pkg/sentry/fsimpl/proc/subtasks.go",
"diff": "@@ -22,6 +22,7 @@ import (\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n)\n@@ -129,6 +130,6 @@ func (i *subtasksInode) Stat(vsfs *vfs.Filesystem, opts vfs.StatOptions) (linux.\n}\n// SetStat implements Inode.SetStat not allowing inode attributes to be changed.\n-func (*subtasksInode) SetStat(*vfs.Filesystem, vfs.SetStatOptions) error {\n+func (*subtasksInode) SetStat(*vfs.Filesystem, *auth.Credentials, vfs.SetStatOptions) error {\nreturn syserror.EPERM\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/task.go",
"new_path": "pkg/sentry/fsimpl/proc/task.go",
"diff": "@@ -108,7 +108,7 @@ func (i *taskInode) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vfs.OpenO\n}\n// SetStat implements Inode.SetStat not allowing inode attributes to be changed.\n-func (*taskInode) SetStat(*vfs.Filesystem, vfs.SetStatOptions) error {\n+func (*taskInode) SetStat(*vfs.Filesystem, *auth.Credentials, vfs.SetStatOptions) error {\nreturn syserror.EPERM\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/tasks_files.go",
"new_path": "pkg/sentry/fsimpl/proc/tasks_files.go",
"diff": "@@ -64,7 +64,7 @@ func (s *selfSymlink) Readlink(ctx context.Context) (string, error) {\n}\n// SetStat implements Inode.SetStat not allowing inode attributes to be changed.\n-func (*selfSymlink) SetStat(*vfs.Filesystem, vfs.SetStatOptions) error {\n+func (*selfSymlink) SetStat(*vfs.Filesystem, *auth.Credentials, vfs.SetStatOptions) error {\nreturn syserror.EPERM\n}\n@@ -102,7 +102,7 @@ func (s *threadSelfSymlink) Readlink(ctx context.Context) (string, error) {\n}\n// SetStat implements Inode.SetStat not allowing inode attributes to be changed.\n-func (*threadSelfSymlink) SetStat(*vfs.Filesystem, vfs.SetStatOptions) error {\n+func (*threadSelfSymlink) SetStat(*vfs.Filesystem, *auth.Credentials, vfs.SetStatOptions) error {\nreturn syserror.EPERM\n}\n@@ -114,8 +114,8 @@ type dynamicBytesFileSetAttr struct {\n}\n// SetStat implements Inode.SetStat.\n-func (d *dynamicBytesFileSetAttr) SetStat(fs *vfs.Filesystem, opts vfs.SetStatOptions) error {\n- return d.DynamicBytesFile.InodeAttrs.SetStat(fs, opts)\n+func (d *dynamicBytesFileSetAttr) SetStat(fs *vfs.Filesystem, creds *auth.Credentials, opts vfs.SetStatOptions) error {\n+ return d.DynamicBytesFile.InodeAttrs.SetStat(fs, creds, opts)\n}\n// cpuStats contains the breakdown of CPU time for /proc/stat.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/sys/sys.go",
"new_path": "pkg/sentry/fsimpl/sys/sys.go",
"diff": "@@ -95,7 +95,7 @@ func (fs *filesystem) newDir(creds *auth.Credentials, mode linux.FileMode, conte\n}\n// SetStat implements Inode.SetStat not allowing inode attributes to be changed.\n-func (*dir) SetStat(*vfs.Filesystem, vfs.SetStatOptions) error {\n+func (*dir) SetStat(*vfs.Filesystem, *auth.Credentials, vfs.SetStatOptions) error {\nreturn syserror.EPERM\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go",
"diff": "@@ -575,7 +575,7 @@ func (fs *filesystem) SetStatAt(ctx context.Context, rp *vfs.ResolvingPath, opts\nif err != nil {\nreturn err\n}\n- return d.inode.setStat(opts.Stat)\n+ return d.inode.setStat(rp.Credentials(), &opts.Stat)\n}\n// StatAt implements vfs.FilesystemImpl.StatAt.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"diff": "@@ -299,10 +299,16 @@ func (i *inode) statTo(stat *linux.Statx) {\n}\n}\n-func (i *inode) setStat(stat linux.Statx) error {\n+func (i *inode) setStat(creds *auth.Credentials, stat *linux.Statx) error {\nif stat.Mask == 0 {\nreturn nil\n}\n+ if stat.Mask&^(linux.STATX_MODE|linux.STATX_UID|linux.STATX_GID|linux.STATX_ATIME|linux.STATX_MTIME|linux.STATX_CTIME|linux.STATX_SIZE) != 0 {\n+ return syserror.EPERM\n+ }\n+ if err := vfs.CheckSetStat(creds, stat, uint16(atomic.LoadUint32(&i.mode))&^linux.S_IFMT, auth.KUID(atomic.LoadUint32(&i.uid)), auth.KGID(atomic.LoadUint32(&i.gid))); err != nil {\n+ return err\n+ }\ni.mu.Lock()\nvar (\nneedsMtimeBump bool\n@@ -457,5 +463,6 @@ func (fd *fileDescription) Stat(ctx context.Context, opts vfs.StatOptions) (linu\n// SetStat implements vfs.FileDescriptionImpl.SetStat.\nfunc (fd *fileDescription) SetStat(ctx context.Context, opts vfs.SetStatOptions) error {\n- return fd.inode().setStat(opts.Stat)\n+ creds := auth.CredentialsFromContext(ctx)\n+ return fd.inode().setStat(creds, &opts.Stat)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/file_description.go",
"new_path": "pkg/sentry/vfs/file_description.go",
"diff": "@@ -286,7 +286,8 @@ type FileDescriptionImpl interface {\nStat(ctx context.Context, opts StatOptions) (linux.Statx, error)\n// SetStat updates metadata for the file represented by the\n- // FileDescription.\n+ // FileDescription. Implementations are responsible for checking if the\n+ // operation can be performed (see vfs.CheckSetStat() for common checks).\nSetStat(ctx context.Context, opts SetStatOptions) error\n// StatFS returns metadata for the filesystem containing the file\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/filesystem.go",
"new_path": "pkg/sentry/vfs/filesystem.go",
"diff": "@@ -366,7 +366,9 @@ type FilesystemImpl interface {\n// ResolvingPath.Resolve*(), then !rp.Done().\nRmdirAt(ctx context.Context, rp *ResolvingPath) error\n- // SetStatAt updates metadata for the file at the given path.\n+ // SetStatAt updates metadata for the file at the given path. Implementations\n+ // are responsible for checking if the operation can be performed\n+ // (see vfs.CheckSetStat() for common checks).\n//\n// Errors:\n//\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add calls to vfs.CheckSetStat to fsimpls
Only gofer filesystem was calling vfs.CheckSetStat for
vfs.FilesystemImpl.SetStatAt and vfs.FileDescriptionImpl.SetStat.
Updates #1193, #1672, #1197
PiperOrigin-RevId: 301226522 |
259,853 | 16.03.2020 18:28:29 | 25,200 | b55f0e5d40c17cadf68d6238564d675ed12f8f49 | fdtable: don't try to zap fdtable entry if close is called for non-existing fd
FDTable.setAll is used to zap entries, but it grows the table up to
a specified fd.
Reported-by: | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/fd_table.go",
"new_path": "pkg/sentry/kernel/fd_table.go",
"diff": "@@ -536,7 +536,9 @@ func (f *FDTable) Remove(fd int32) (*fs.File, *vfs.FileDescription) {\ncase orig2 != nil:\norig2.IncRef()\n}\n+ if orig != nil || orig2 != nil {\nf.setAll(fd, nil, nil, FDFlags{}) // Zap entry.\n+ }\nreturn orig, orig2\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | fdtable: don't try to zap fdtable entry if close is called for non-existing fd
FDTable.setAll is used to zap entries, but it grows the table up to
a specified fd.
Reported-by: [email protected]
PiperOrigin-RevId: 301280000 |
259,891 | 17.03.2020 16:21:36 | 25,200 | 1cc5a71a0e2100c89c97ffd12a38143907b33630 | iptables: fix type in script name, mark some new tests as skipped | [
{
"change_type": "MODIFY",
"old_path": "kokoro/iptables_tests.cfg",
"new_path": "kokoro/iptables_tests.cfg",
"diff": "-build_file: \"repo/scripts/iptables_test.sh\"\n+build_file: \"repo/scripts/iptables_tests.sh\"\naction {\ndefine_artifacts {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/iptables/iptables_test.go",
"new_path": "test/iptables/iptables_test.go",
"diff": "@@ -191,6 +191,7 @@ func TestFilterInputDropOnlyUDP(t *testing.T) {\n}\nfunc TestNATRedirectUDPPort(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\nt.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATRedirectUDPPort{}); err != nil {\nt.Fatal(err)\n@@ -198,6 +199,7 @@ func TestNATRedirectUDPPort(t *testing.T) {\n}\nfunc TestNATRedirectTCPPort(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\nt.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATRedirectTCPPort{}); err != nil {\nt.Fatal(err)\n@@ -205,6 +207,7 @@ func TestNATRedirectTCPPort(t *testing.T) {\n}\nfunc TestNATDropUDP(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\nt.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATDropUDP{}); err != nil {\nt.Fatal(err)\n@@ -212,6 +215,7 @@ func TestNATDropUDP(t *testing.T) {\n}\nfunc TestNATAcceptAll(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\nt.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATAcceptAll{}); err != nil {\nt.Fatal(err)\n@@ -255,6 +259,7 @@ func TestFilterInputReturnUnderflow(t *testing.T) {\n}\nfunc TestFilterOutputDropTCPDestPort(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\nt.Skip(\"filter OUTPUT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(FilterOutputDropTCPDestPort{}); err != nil {\nt.Fatal(err)\n@@ -262,6 +267,7 @@ func TestFilterOutputDropTCPDestPort(t *testing.T) {\n}\nfunc TestFilterOutputDropTCPSrcPort(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\nt.Skip(\"filter OUTPUT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(FilterOutputDropTCPSrcPort{}); err != nil {\nt.Fatal(err)\n@@ -329,42 +335,56 @@ func TestOutputInvertDestination(t *testing.T) {\n}\nfunc TestNATOutRedirectIP(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\n+ t.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATOutRedirectIP{}); err != nil {\nt.Fatal(err)\n}\n}\nfunc TestNATOutDontRedirectIP(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\n+ t.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATOutDontRedirectIP{}); err != nil {\nt.Fatal(err)\n}\n}\nfunc TestNATOutRedirectInvert(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\n+ t.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATOutRedirectInvert{}); err != nil {\nt.Fatal(err)\n}\n}\nfunc TestNATPreRedirectIP(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\n+ t.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATPreRedirectIP{}); err != nil {\nt.Fatal(err)\n}\n}\nfunc TestNATPreDontRedirectIP(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\n+ t.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATPreDontRedirectIP{}); err != nil {\nt.Fatal(err)\n}\n}\nfunc TestNATPreRedirectInvert(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\n+ t.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATPreRedirectInvert{}); err != nil {\nt.Fatal(err)\n}\n}\nfunc TestNATRedirectRequiresProtocol(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\n+ t.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATRedirectRequiresProtocol{}); err != nil {\nt.Fatal(err)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | iptables: fix type in script name, mark some new tests as skipped
PiperOrigin-RevId: 301476456 |
259,974 | 11.03.2020 09:55:07 | 0 | 9c35d7eb1f96f12207f78b94722f0e8b778b5af3 | Enable syscall sysret_test on arm64.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -3336,10 +3336,7 @@ cc_binary(\ncc_binary(\nname = \"sysret_test\",\ntestonly = 1,\n- srcs = select_arch(\n- amd64 = [\"sysret.cc\"],\n- arm64 = [],\n- ),\n+ srcs = [\"sysret.cc\"],\nlinkstatic = 1,\ndeps = [\ngtest,\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/sysret.cc",
"new_path": "test/syscalls/linux/sysret.cc",
"diff": "// Tests to verify that the behavior of linux and gvisor matches when\n// 'sysret' returns to bad (aka non-canonical) %rip or %rsp.\n+\n+#include <linux/elf.h>\n#include <sys/ptrace.h>\n#include <sys/user.h>\n@@ -32,6 +34,7 @@ constexpr uint64_t kNonCanonicalRsp = 0xFFFF000000000000;\nclass SysretTest : public ::testing::Test {\nprotected:\nstruct user_regs_struct regs_;\n+ struct iovec iov;\npid_t child_;\nvoid SetUp() override {\n@@ -48,10 +51,14 @@ class SysretTest : public ::testing::Test {\n// Parent.\nint status;\n+ memset(&iov, 0, sizeof(iov));\nASSERT_THAT(pid, SyscallSucceeds()); // Might still be < 0.\nASSERT_THAT(waitpid(pid, &status, 0), SyscallSucceedsWithValue(pid));\nEXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP);\n- ASSERT_THAT(ptrace(PTRACE_GETREGS, pid, 0, ®s_), SyscallSucceeds());\n+\n+ iov.iov_base = ®s_;\n+ iov.iov_len = sizeof(regs_);\n+ ASSERT_THAT(ptrace(PTRACE_GETREGSET, pid, NT_PRSTATUS, &iov), SyscallSucceeds());\nchild_ = pid;\n}\n@@ -61,13 +68,25 @@ class SysretTest : public ::testing::Test {\n}\nvoid SetRip(uint64_t newrip) {\n+#if defined(__x86_64__)\nregs_.rip = newrip;\n- ASSERT_THAT(ptrace(PTRACE_SETREGS, child_, 0, ®s_), SyscallSucceeds());\n+#elif defined(__aarch64__)\n+ regs_.pc = newrip;\n+#else\n+#error \"Unknown architecture\"\n+#endif\n+ ASSERT_THAT(ptrace(PTRACE_SETREGSET, child_, NT_PRSTATUS, &iov), SyscallSucceeds());\n}\nvoid SetRsp(uint64_t newrsp) {\n+#if defined(__x86_64__)\nregs_.rsp = newrsp;\n- ASSERT_THAT(ptrace(PTRACE_SETREGS, child_, 0, ®s_), SyscallSucceeds());\n+#elif defined(__aarch64__)\n+ regs_.sp = newrsp;\n+#else\n+#error \"Unknown architecture\"\n+#endif\n+ ASSERT_THAT(ptrace(PTRACE_SETREGSET, child_, NT_PRSTATUS, &iov), SyscallSucceeds());\n}\n// Wait waits for the child pid and returns the exit status.\n@@ -104,8 +123,15 @@ TEST_F(SysretTest, BadRsp) {\nSetRsp(kNonCanonicalRsp);\nDetach();\nint status = Wait();\n+#if defined(__x86_64__)\nEXPECT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGBUS)\n<< \"status = \" << status;\n+#elif defined(__aarch64__)\n+ EXPECT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGSEGV)\n+ << \"status = \" << status;\n+#else\n+#error \"Unknown architecture\"\n+#endif\n}\n} // namespace\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enable syscall sysret_test on arm64.
Fixes #2058
Signed-off-by: Haibo Xu <[email protected]>
Change-Id: I05750d238a6425d3a47fae15720901f4dd924a32 |
259,992 | 18.03.2020 15:12:11 | 25,200 | f1d1af2a4ad35dd20a7c56bd9e842e347b126c31 | Fix FDTable.NewFDVFS2
It was looking at VFS1 table to determine where to
allocate the next FD from.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/fd_table.go",
"new_path": "pkg/sentry/kernel/fd_table.go",
"diff": "@@ -338,7 +338,7 @@ func (f *FDTable) NewFDVFS2(ctx context.Context, minfd int32, file *vfs.FileDesc\nfd = f.next\n}\nfor fd < end {\n- if d, _, _ := f.get(fd); d == nil {\n+ if d, _, _ := f.getVFS2(fd); d == nil {\nf.setVFS2(fd, file, flags)\nif fd == f.next {\n// Update next search start position.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix FDTable.NewFDVFS2
It was looking at VFS1 table to determine where to
allocate the next FD from.
Updates #1035
PiperOrigin-RevId: 301678858 |
259,891 | 18.03.2020 15:51:36 | 25,200 | b5ea65c07c29cbc894e9f879796eed816696d042 | iptables: skip tests for not-yet-supported features | [
{
"change_type": "MODIFY",
"old_path": "test/iptables/iptables_test.go",
"new_path": "test/iptables/iptables_test.go",
"diff": "@@ -191,6 +191,7 @@ func TestFilterInputDropOnlyUDP(t *testing.T) {\n}\nfunc TestNATRedirectUDPPort(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\nt.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATRedirectUDPPort{}); err != nil {\nt.Fatal(err)\n@@ -198,6 +199,7 @@ func TestNATRedirectUDPPort(t *testing.T) {\n}\nfunc TestNATRedirectTCPPort(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\nt.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATRedirectTCPPort{}); err != nil {\nt.Fatal(err)\n@@ -205,6 +207,7 @@ func TestNATRedirectTCPPort(t *testing.T) {\n}\nfunc TestNATDropUDP(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\nt.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATDropUDP{}); err != nil {\nt.Fatal(err)\n@@ -212,6 +215,7 @@ func TestNATDropUDP(t *testing.T) {\n}\nfunc TestNATAcceptAll(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\nt.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATAcceptAll{}); err != nil {\nt.Fatal(err)\n@@ -255,6 +259,7 @@ func TestFilterInputReturnUnderflow(t *testing.T) {\n}\nfunc TestFilterOutputDropTCPDestPort(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\nt.Skip(\"filter OUTPUT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(FilterOutputDropTCPDestPort{}); err != nil {\nt.Fatal(err)\n@@ -262,6 +267,7 @@ func TestFilterOutputDropTCPDestPort(t *testing.T) {\n}\nfunc TestFilterOutputDropTCPSrcPort(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\nt.Skip(\"filter OUTPUT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(FilterOutputDropTCPSrcPort{}); err != nil {\nt.Fatal(err)\n@@ -329,42 +335,56 @@ func TestOutputInvertDestination(t *testing.T) {\n}\nfunc TestNATOutRedirectIP(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\n+ t.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATOutRedirectIP{}); err != nil {\nt.Fatal(err)\n}\n}\nfunc TestNATOutDontRedirectIP(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\n+ t.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATOutDontRedirectIP{}); err != nil {\nt.Fatal(err)\n}\n}\nfunc TestNATOutRedirectInvert(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\n+ t.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATOutRedirectInvert{}); err != nil {\nt.Fatal(err)\n}\n}\nfunc TestNATPreRedirectIP(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\n+ t.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATPreRedirectIP{}); err != nil {\nt.Fatal(err)\n}\n}\nfunc TestNATPreDontRedirectIP(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\n+ t.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATPreDontRedirectIP{}); err != nil {\nt.Fatal(err)\n}\n}\nfunc TestNATPreRedirectInvert(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\n+ t.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATPreRedirectInvert{}); err != nil {\nt.Fatal(err)\n}\n}\nfunc TestNATRedirectRequiresProtocol(t *testing.T) {\n+ // TODO(gvisor.dev/issue/170): Enable when supported.\n+ t.Skip(\"NAT isn't supported yet (gvisor.dev/issue/170).\")\nif err := singleTest(NATRedirectRequiresProtocol{}); err != nil {\nt.Fatal(err)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | iptables: skip tests for not-yet-supported features
PiperOrigin-RevId: 301686266 |
259,854 | 18.03.2020 16:25:20 | 25,200 | 92a00ca91affab8564b8875387758914ddc9785b | Store segment transmit count.
This will aid in segment reordering detection.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/segment.go",
"new_path": "pkg/tcpip/transport/tcp/segment.go",
"diff": "@@ -56,9 +56,9 @@ type segment struct {\noptions []byte `state:\".([]byte)\"`\nhasNewSACKInfo bool\nrcvdTime time.Time `state:\".(unixTime)\"`\n- // xmitTime is the last transmit time of this segment. A zero value\n- // indicates that the segment has yet to be transmitted.\n+ // xmitTime is the last transmit time of this segment.\nxmitTime time.Time `state:\".(unixTime)\"`\n+ xmitCount uint32\n}\nfunc newSegment(r *stack.Route, id stack.TransportEndpointID, pkt tcpip.PacketBuffer) *segment {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/snd.go",
"new_path": "pkg/tcpip/transport/tcp/snd.go",
"diff": "@@ -1229,7 +1229,7 @@ func (s *sender) handleRcvdSegment(seg *segment) {\n// sendSegment sends the specified segment.\nfunc (s *sender) sendSegment(seg *segment) *tcpip.Error {\n- if !seg.xmitTime.IsZero() {\n+ if seg.xmitCount > 0 {\ns.ep.stack.Stats().TCP.Retransmits.Increment()\ns.ep.stats.SendErrors.Retransmits.Increment()\nif s.sndCwnd < s.sndSsthresh {\n@@ -1237,6 +1237,7 @@ func (s *sender) sendSegment(seg *segment) *tcpip.Error {\n}\n}\nseg.xmitTime = time.Now()\n+ seg.xmitCount++\nreturn s.sendSegmentFromView(seg.data, seg.flags, seg.sequenceNumber)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Store segment transmit count.
This will aid in segment reordering detection.
Updates #691
PiperOrigin-RevId: 301692638 |
259,853 | 18.03.2020 17:41:06 | 25,200 | c3cee7f5a433708a394cee4e89c223f80036f5d9 | Deflake third_party/gvisor/pkg/gate/gate_test
TestConcurrentAll executes 1000 goroutines which never sleep,
so they are not preempted by Go's runtime. In Go 1.14, async preemption
has been added, but the added runtime.Gosched() call will do nothing
wrong in this case too. | [
{
"change_type": "MODIFY",
"old_path": "pkg/gate/gate_test.go",
"new_path": "pkg/gate/gate_test.go",
"diff": "package gate_test\nimport (\n+ \"runtime\"\n\"testing\"\n\"time\"\n@@ -165,6 +166,8 @@ func worker(g *gate.Gate, done *sync.WaitGroup) {\nif !g.Enter() {\nbreak\n}\n+ // Golang before v1.14 doesn't preempt busyloops.\n+ runtime.Gosched()\ng.Leave()\n}\ndone.Done()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Deflake third_party/gvisor/pkg/gate/gate_test
TestConcurrentAll executes 1000 goroutines which never sleep,
so they are not preempted by Go's runtime. In Go 1.14, async preemption
has been added, but the added runtime.Gosched() call will do nothing
wrong in this case too.
PiperOrigin-RevId: 301705712 |
259,891 | 18.03.2020 14:44:56 | 25,200 | a8f9cc87989979b6d8bc3759e64bdd1b76329b64 | iptables: deflake DropTCP*Port tests
These tests could timeout because net.DialTCP didn't respect the
timeout. | [
{
"change_type": "MODIFY",
"old_path": "test/iptables/filter_input.go",
"new_path": "test/iptables/filter_input.go",
"diff": "@@ -194,8 +194,14 @@ func (FilterInputDropTCPDestPort) ContainerAction(ip net.IP) error {\n// LocalAction implements TestCase.LocalAction.\nfunc (FilterInputDropTCPDestPort) LocalAction(ip net.IP) error {\n- if err := connectTCP(ip, dropPort, sendloopDuration); err == nil {\n- return fmt.Errorf(\"connection destined to port %d should not be accepted, but got accepted\", dropPort)\n+ // After the container sets its DROP rule, we shouldn't be able to connect.\n+ // However, we may succeed in connecting if this runs before the container\n+ // sets the rule. To avoid this race, we retry connecting until\n+ // sendloopDuration has elapsed, ignoring whether the connect succeeds. The\n+ // test works becuase the container will error if a connection is\n+ // established after the rule is set.\n+ for start := time.Now(); time.Since(start) < sendloopDuration; {\n+ connectTCP(ip, dropPort, sendloopDuration-time.Since(start))\n}\nreturn nil\n@@ -226,8 +232,14 @@ func (FilterInputDropTCPSrcPort) ContainerAction(ip net.IP) error {\n// LocalAction implements TestCase.LocalAction.\nfunc (FilterInputDropTCPSrcPort) LocalAction(ip net.IP) error {\n- if err := connectTCP(ip, acceptPort, sendloopDuration); err == nil {\n- return fmt.Errorf(\"connection should not be accepted, but was\")\n+ // After the container sets its DROP rule, we shouldn't be able to connect.\n+ // However, we may succeed in connecting if this runs before the container\n+ // sets the rule. To avoid this race, we retry connecting until\n+ // sendloopDuration has elapsed, ignoring whether the connect succeeds. The\n+ // test works becuase the container will error if a connection is\n+ // established after the rule is set.\n+ for start := time.Now(); time.Since(start) < sendloopDuration; {\n+ connectTCP(ip, acceptPort, sendloopDuration-time.Since(start))\n}\nreturn nil\n"
},
{
"change_type": "MODIFY",
"old_path": "test/iptables/iptables_util.go",
"new_path": "test/iptables/iptables_util.go",
"diff": "@@ -144,7 +144,7 @@ func connectTCP(ip net.IP, port int, timeout time.Duration) error {\n// The container may not be listening when we first connect, so retry\n// upon error.\ncallback := func() error {\n- conn, err := net.DialTCP(\"tcp4\", nil, &contAddr)\n+ conn, err := net.DialTimeout(\"tcp\", contAddr.String(), timeout)\nif conn != nil {\nconn.Close()\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | iptables: deflake DropTCP*Port tests
These tests could timeout because net.DialTCP didn't respect the
timeout. |
259,962 | 19.03.2020 09:41:56 | 25,200 | fd27a917ef068a4e17cddbe3f671b59f52e6e030 | Address comments on workMu removal change.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/accept.go",
"new_path": "pkg/tcpip/transport/tcp/accept.go",
"diff": "@@ -420,7 +420,7 @@ func (e *endpoint) handleSynSegment(ctx *listenContext, s *segment, opts *header\n}\nfunc (e *endpoint) incSynRcvdCount() bool {\n- if e.synRcvdCount >= (cap(e.acceptedChan)) {\n+ if e.synRcvdCount >= cap(e.acceptedChan) {\nreturn false\n}\ne.synRcvdCount++\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"new_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"diff": "@@ -2236,12 +2236,13 @@ func TestSegmentMerging(t *testing.T) {\nc.CreateConnected(789, 30000, -1 /* epRcvBuf */)\n- // Send 10 1 byte segments to fill up InitialWindow but don't\n- // ACK. That should prevent anymore packets from going out.\n- for i := 0; i < 10; i++ {\n+ // Send tcp.InitialCwnd number of segments to fill up\n+ // InitialWindow but don't ACK. That should prevent\n+ // anymore packets from going out.\n+ for i := 0; i < tcp.InitialCwnd; i++ {\nview := buffer.NewViewFromBytes([]byte{0})\nif _, _, err := c.EP.Write(tcpip.SlicePayload(view), tcpip.WriteOptions{}); err != nil {\n- t.Fatalf(\"Write #%d failed: %v\", i+1, err)\n+ t.Fatalf(\"Write #%d failed: %s\", i+1, err)\n}\n}\n@@ -2256,8 +2257,8 @@ func TestSegmentMerging(t *testing.T) {\n}\n}\n- // Check that we get 10 packets of 1 byte each.\n- for i := 0; i < 10; i++ {\n+ // Check that we get tcp.InitialCwnd packets.\n+ for i := 0; i < tcp.InitialCwnd; i++ {\nb := c.GetPacket()\nchecker.IPv4(t, b,\nchecker.PayloadLen(header.TCPMinimumSize+1),\n"
}
] | Go | Apache License 2.0 | google/gvisor | Address comments on workMu removal change.
Updates #231, #357
PiperOrigin-RevId: 301833669 |
259,962 | 19.03.2020 09:59:21 | 25,200 | 3a37f6791745a26d38b69fbe9d4090f8fd0c7827 | Change SocketOperations.readMu to an RWMutex.
Also get rid of the readViewHasData as it's not required anymore.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/netstack.go",
"new_path": "pkg/sentry/socket/netstack/netstack.go",
"diff": "@@ -29,7 +29,6 @@ import (\n\"io\"\n\"math\"\n\"reflect\"\n- \"sync/atomic\"\n\"syscall\"\n\"time\"\n@@ -265,14 +264,8 @@ type SocketOperations struct {\nskType linux.SockType\nprotocol int\n- // readViewHasData is 1 iff readView has data to be read, 0 otherwise.\n- // Must be accessed using atomic operations. It must only be written\n- // with readMu held but can be read without holding readMu. The latter\n- // is required to avoid deadlocks in epoll Readiness checks.\n- readViewHasData uint32\n-\n// readMu protects access to the below fields.\n- readMu sync.Mutex `state:\"nosave\"`\n+ readMu sync.RWMutex `state:\"nosave\"`\n// readView contains the remaining payload from the last packet.\nreadView buffer.View\n// readCM holds control message information for the last packet read\n@@ -428,13 +421,11 @@ func (s *SocketOperations) fetchReadView() *syserr.Error {\nv, cms, err := s.Endpoint.Read(&s.sender)\nif err != nil {\n- atomic.StoreUint32(&s.readViewHasData, 0)\nreturn syserr.TranslateNetstackError(err)\n}\ns.readView = v\ns.readCM = cms\n- atomic.StoreUint32(&s.readViewHasData, 1)\nreturn nil\n}\n@@ -633,9 +624,11 @@ func (s *SocketOperations) Readiness(mask waiter.EventMask) waiter.EventMask {\n// Check our cached value iff the caller asked for readability and the\n// endpoint itself is currently not readable.\nif (mask & ^r & waiter.EventIn) != 0 {\n- if atomic.LoadUint32(&s.readViewHasData) == 1 {\n+ s.readMu.RLock()\n+ if len(s.readView) > 0 {\nr |= waiter.EventIn\n}\n+ s.readMu.RUnlock()\n}\nreturn r\n@@ -2342,9 +2335,6 @@ func (s *SocketOperations) coalescingRead(ctx context.Context, dst usermem.IOSeq\n}\ncopied += n\ns.readView.TrimFront(n)\n- if len(s.readView) == 0 {\n- atomic.StoreUint32(&s.readViewHasData, 0)\n- }\ndst = dst.DropFirst(n)\nif e != nil {\n@@ -2468,10 +2458,6 @@ func (s *SocketOperations) nonBlockingRead(ctx context.Context, dst usermem.IOSe\ns.readView.TrimFront(int(n))\n}\n- if len(s.readView) == 0 {\n- atomic.StoreUint32(&s.readViewHasData, 0)\n- }\n-\nvar flags int\nif msgLen > int(n) {\nflags |= linux.MSG_TRUNC\n"
}
] | Go | Apache License 2.0 | google/gvisor | Change SocketOperations.readMu to an RWMutex.
Also get rid of the readViewHasData as it's not required anymore.
Updates #231, #357
PiperOrigin-RevId: 301837227 |
259,972 | 19.03.2020 12:32:15 | 25,200 | e0fbcdcb7f8a3e18946ccd5d5b98ea3adadee5ba | Add packetimpact tests to presubmit and CI testing | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "kokoro/packetimpact_tests.cfg",
"diff": "+build_file: \"repo/scripts/packetimpact_tests.sh\"\n+\n+action {\n+ define_artifacts {\n+ regex: \"**/sponge_log.xml\"\n+ regex: \"**/sponge_log.log\"\n+ regex: \"**/outputs.zip\"\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/packetimpact_tests.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+source $(dirname $0)/common.sh\n+\n+install_runsc_for_test runsc-d\n+test_runsc $(bazel query \"attr(tags, packetimpact, tests(//test/packetimpact/...))\")\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/defs.bzl",
"new_path": "test/packetimpact/tests/defs.bzl",
"diff": "@@ -71,7 +71,7 @@ def packetimpact_linux_test(name, testbench_binary, **kwargs):\nname = name + \"_linux_test\",\ntestbench_binary = testbench_binary,\nflags = [\"--dut_platform\", \"linux\"],\n- tags = PACKETIMPACT_TAGS,\n+ tags = PACKETIMPACT_TAGS + [\"packetimpact\"],\n**kwargs\n)\n@@ -89,7 +89,7 @@ def packetimpact_netstack_test(name, testbench_binary, **kwargs):\n# This is the default runtime unless\n# \"--test_arg=--runtime=OTHER_RUNTIME\" is used to override the value.\nflags = [\"--dut_platform\", \"netstack\", \"--runtime=runsc-d\"],\n- tags = PACKETIMPACT_TAGS,\n+ tags = PACKETIMPACT_TAGS + [\"packetimpact\"],\n**kwargs\n)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add packetimpact tests to presubmit and CI testing
PiperOrigin-RevId: 301872161 |
259,975 | 19.03.2020 15:28:52 | 25,200 | 57d9bd922b4eff922d1a5185529fe5446249d592 | Remove the "frozen" bit from dirents.
Frozen was to lock down changes to the host filesystem
for hostFS. Now that hostFS is gone, it can be removed. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/dirent.go",
"new_path": "pkg/sentry/fs/dirent.go",
"diff": "@@ -17,7 +17,6 @@ package fs\nimport (\n\"fmt\"\n\"path\"\n- \"sort\"\n\"sync/atomic\"\n\"syscall\"\n@@ -121,9 +120,6 @@ type Dirent struct {\n// deleted may be set atomically when removed.\ndeleted int32\n- // frozen indicates this entry can't walk to unknown nodes.\n- frozen bool\n-\n// mounted is true if Dirent is a mount point, similar to include/linux/dcache.h:DCACHE_MOUNTED.\nmounted bool\n@@ -253,8 +249,7 @@ func (d *Dirent) IsNegative() bool {\nreturn d.Inode == nil\n}\n-// hashChild will hash child into the children list of its new parent d, carrying over\n-// any \"frozen\" state from d.\n+// hashChild will hash child into the children list of its new parent d.\n//\n// Returns (*WeakRef, true) if hashing child caused a Dirent to be unhashed. The caller must\n// validate the returned unhashed weak reference. Common cases:\n@@ -282,9 +277,6 @@ func (d *Dirent) hashChild(child *Dirent) (*refs.WeakRef, bool) {\nd.IncRef()\n}\n- // Carry over parent's frozen state.\n- child.frozen = d.frozen\n-\nreturn d.hashChildParentSet(child)\n}\n@@ -400,38 +392,6 @@ func (d *Dirent) MountRoot() *Dirent {\nreturn mountRoot\n}\n-// Freeze prevents this dirent from walking to more nodes. Freeze is applied\n-// recursively to all children.\n-//\n-// If this particular Dirent represents a Virtual node, then Walks and Creates\n-// may proceed as before.\n-//\n-// Freeze can only be called before the application starts running, otherwise\n-// the root it might be out of sync with the application root if modified by\n-// sys_chroot.\n-func (d *Dirent) Freeze() {\n- d.mu.Lock()\n- defer d.mu.Unlock()\n- if d.frozen {\n- // Already frozen.\n- return\n- }\n- d.frozen = true\n-\n- // Take a reference when freezing.\n- for _, w := range d.children {\n- if child := w.Get(); child != nil {\n- // NOTE: We would normally drop the reference here. But\n- // instead we're hanging on to it.\n- ch := child.(*Dirent)\n- ch.Freeze()\n- }\n- }\n-\n- // Drop all expired weak references.\n- d.flush()\n-}\n-\n// descendantOf returns true if the receiver dirent is equal to, or a\n// descendant of, the argument dirent.\n//\n@@ -524,11 +484,6 @@ func (d *Dirent) walk(ctx context.Context, root *Dirent, name string, walkMayUnl\nw.Drop()\n}\n- // Are we allowed to do the lookup?\n- if d.frozen && !d.Inode.IsVirtual() {\n- return nil, syscall.ENOENT\n- }\n-\n// Slow path: load the InodeOperations into memory. Since this is a hot path and the lookup may be\n// expensive, if possible release the lock and re-acquire it.\nif walkMayUnlock {\n@@ -659,11 +614,6 @@ func (d *Dirent) Create(ctx context.Context, root *Dirent, name string, flags Fi\nreturn nil, syscall.EEXIST\n}\n- // Are we frozen?\n- if d.frozen && !d.Inode.IsVirtual() {\n- return nil, syscall.ENOENT\n- }\n-\n// Try the create. We need to trust the file system to return EEXIST (or something\n// that will translate to EEXIST) if name already exists.\nfile, err := d.Inode.Create(ctx, d, name, flags, perms)\n@@ -727,11 +677,6 @@ func (d *Dirent) genericCreate(ctx context.Context, root *Dirent, name string, c\nreturn syscall.EEXIST\n}\n- // Are we frozen?\n- if d.frozen && !d.Inode.IsVirtual() {\n- return syscall.ENOENT\n- }\n-\n// Remove any negative Dirent. We've already asserted above with d.exists\n// that the only thing remaining here can be a negative Dirent.\nif w, ok := d.children[name]; ok {\n@@ -862,49 +807,6 @@ func (d *Dirent) GetDotAttrs(root *Dirent) (DentAttr, DentAttr) {\nreturn dot, dot\n}\n-// readdirFrozen returns readdir results based solely on the frozen children.\n-func (d *Dirent) readdirFrozen(root *Dirent, offset int64, dirCtx *DirCtx) (int64, error) {\n- // Collect attrs for \".\" and \"..\".\n- attrs := make(map[string]DentAttr)\n- names := []string{\".\", \"..\"}\n- attrs[\".\"], attrs[\"..\"] = d.GetDotAttrs(root)\n-\n- // Get info from all children.\n- d.mu.Lock()\n- defer d.mu.Unlock()\n- for name, w := range d.children {\n- if child := w.Get(); child != nil {\n- defer child.DecRef()\n-\n- // Skip negative children.\n- if child.(*Dirent).IsNegative() {\n- continue\n- }\n-\n- sattr := child.(*Dirent).Inode.StableAttr\n- attrs[name] = DentAttr{\n- Type: sattr.Type,\n- InodeID: sattr.InodeID,\n- }\n- names = append(names, name)\n- }\n- }\n-\n- sort.Strings(names)\n-\n- if int(offset) >= len(names) {\n- return offset, nil\n- }\n- names = names[int(offset):]\n- for _, name := range names {\n- if err := dirCtx.DirEmit(name, attrs[name]); err != nil {\n- return offset, err\n- }\n- offset++\n- }\n- return offset, nil\n-}\n-\n// DirIterator is an open directory containing directory entries that can be read.\ntype DirIterator interface {\n// IterateDir emits directory entries by calling dirCtx.EmitDir, beginning\n@@ -964,10 +866,6 @@ func direntReaddir(ctx context.Context, d *Dirent, it DirIterator, root *Dirent,\nreturn offset, nil\n}\n- if d.frozen {\n- return d.readdirFrozen(root, offset, dirCtx)\n- }\n-\n// Collect attrs for \".\" and \"..\".\ndot, dotdot := d.GetDotAttrs(root)\n@@ -1068,11 +966,6 @@ func (d *Dirent) mount(ctx context.Context, inode *Inode) (newChild *Dirent, err\nreturn nil, syserror.EINVAL\n}\n- // Are we frozen?\n- if d.parent.frozen && !d.parent.Inode.IsVirtual() {\n- return nil, syserror.ENOENT\n- }\n-\n// Dirent that'll replace d.\n//\n// Note that NewDirent returns with one reference taken; the reference\n@@ -1101,11 +994,6 @@ func (d *Dirent) unmount(ctx context.Context, replacement *Dirent) error {\nreturn syserror.ENOENT\n}\n- // Are we frozen?\n- if d.parent.frozen && !d.parent.Inode.IsVirtual() {\n- return syserror.ENOENT\n- }\n-\n// Remount our former child in its place.\n//\n// As replacement used to be our child, it must already have the right\n@@ -1135,11 +1023,6 @@ func (d *Dirent) Remove(ctx context.Context, root *Dirent, name string, dirPath\nunlock := d.lockDirectory()\ndefer unlock()\n- // Are we frozen?\n- if d.frozen && !d.Inode.IsVirtual() {\n- return syscall.ENOENT\n- }\n-\n// Try to walk to the node.\nchild, err := d.walk(ctx, root, name, false /* may unlock */)\nif err != nil {\n@@ -1201,11 +1084,6 @@ func (d *Dirent) RemoveDirectory(ctx context.Context, root *Dirent, name string)\nunlock := d.lockDirectory()\ndefer unlock()\n- // Are we frozen?\n- if d.frozen && !d.Inode.IsVirtual() {\n- return syscall.ENOENT\n- }\n-\n// Check for dots.\nif name == \".\" {\n// Rejected as the last component by rmdir(2).\n@@ -1519,15 +1397,6 @@ func Rename(ctx context.Context, root *Dirent, oldParent *Dirent, oldName string\nreturn err\n}\n- // Are we frozen?\n- // TODO(jamieliu): Is this the right errno?\n- if oldParent.frozen && !oldParent.Inode.IsVirtual() {\n- return syscall.ENOENT\n- }\n- if newParent.frozen && !newParent.Inode.IsVirtual() {\n- return syscall.ENOENT\n- }\n-\n// Do we have general permission to remove from oldParent and\n// create/replace in newParent?\nif err := oldParent.Inode.CheckPermission(ctx, PermMask{Write: true, Execute: true}); err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/file_overlay_test.go",
"new_path": "pkg/sentry/fs/file_overlay_test.go",
"diff": "@@ -175,90 +175,6 @@ func TestReaddirRevalidation(t *testing.T) {\n}\n}\n-// TestReaddirOverlayFrozen tests that calling Readdir on an overlay file with\n-// a frozen dirent tree does not make Readdir calls to the underlying files.\n-// This is a regression test for b/114808269.\n-func TestReaddirOverlayFrozen(t *testing.T) {\n- ctx := contexttest.Context(t)\n-\n- // Create an overlay with two directories, each with two files.\n- upper := newTestRamfsDir(ctx, []dirContent{{name: \"upper-file1\"}, {name: \"upper-file2\"}}, nil)\n- lower := newTestRamfsDir(ctx, []dirContent{{name: \"lower-file1\"}, {name: \"lower-file2\"}}, nil)\n- overlayInode := fs.NewTestOverlayDir(ctx, upper, lower, false)\n-\n- // Set that overlay as the root.\n- root := fs.NewDirent(ctx, overlayInode, \"root\")\n- ctx = &rootContext{\n- Context: ctx,\n- root: root,\n- }\n-\n- // Check that calling Readdir on the root now returns all 4 files (2\n- // from each layer in the overlay).\n- rootFile, err := root.Inode.GetFile(ctx, root, fs.FileFlags{Read: true})\n- if err != nil {\n- t.Fatalf(\"root.Inode.GetFile failed: %v\", err)\n- }\n- defer rootFile.DecRef()\n- ser := &fs.CollectEntriesSerializer{}\n- if err := rootFile.Readdir(ctx, ser); err != nil {\n- t.Fatalf(\"rootFile.Readdir failed: %v\", err)\n- }\n- if got, want := ser.Order, []string{\".\", \"..\", \"lower-file1\", \"lower-file2\", \"upper-file1\", \"upper-file2\"}; !reflect.DeepEqual(got, want) {\n- t.Errorf(\"Readdir got names %v, want %v\", got, want)\n- }\n-\n- // Readdir should have been called on upper and lower.\n- upperDir := upper.InodeOperations.(*dir)\n- lowerDir := lower.InodeOperations.(*dir)\n- if !upperDir.ReaddirCalled {\n- t.Errorf(\"upperDir.ReaddirCalled got %v, want true\", upperDir.ReaddirCalled)\n- }\n- if !lowerDir.ReaddirCalled {\n- t.Errorf(\"lowerDir.ReaddirCalled got %v, want true\", lowerDir.ReaddirCalled)\n- }\n-\n- // Reset.\n- upperDir.ReaddirCalled = false\n- lowerDir.ReaddirCalled = false\n-\n- // Take references on \"upper-file1\" and \"lower-file1\", pinning them in\n- // the dirent tree.\n- for _, name := range []string{\"upper-file1\", \"lower-file1\"} {\n- if _, err := root.Walk(ctx, root, name); err != nil {\n- t.Fatalf(\"root.Walk(%q) failed: %v\", name, err)\n- }\n- // Don't drop a reference on the returned dirent so that it\n- // will stay in the tree.\n- }\n-\n- // Freeze the dirent tree.\n- root.Freeze()\n-\n- // Seek back to the beginning of the file.\n- if _, err := rootFile.Seek(ctx, fs.SeekSet, 0); err != nil {\n- t.Fatalf(\"error seeking to beginning of directory: %v\", err)\n- }\n-\n- // Calling Readdir on the root now will return only the pinned\n- // children.\n- ser = &fs.CollectEntriesSerializer{}\n- if err := rootFile.Readdir(ctx, ser); err != nil {\n- t.Fatalf(\"rootFile.Readdir failed: %v\", err)\n- }\n- if got, want := ser.Order, []string{\".\", \"..\", \"lower-file1\", \"upper-file1\"}; !reflect.DeepEqual(got, want) {\n- t.Errorf(\"Readdir got names %v, want %v\", got, want)\n- }\n-\n- // Readdir should NOT have been called on upper or lower.\n- if upperDir.ReaddirCalled {\n- t.Errorf(\"upperDir.ReaddirCalled got %v, want false\", upperDir.ReaddirCalled)\n- }\n- if lowerDir.ReaddirCalled {\n- t.Errorf(\"lowerDir.ReaddirCalled got %v, want false\", lowerDir.ReaddirCalled)\n- }\n-}\n-\ntype rootContext struct {\ncontext.Context\nroot *fs.Dirent\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/mounts.go",
"new_path": "pkg/sentry/fs/mounts.go",
"diff": "@@ -273,19 +273,6 @@ func (mns *MountNamespace) DecRef() {\nmns.DecRefWithDestructor(mns.destroy)\n}\n-// Freeze freezes the entire mount tree.\n-func (mns *MountNamespace) Freeze() {\n- mns.mu.Lock()\n- defer mns.mu.Unlock()\n-\n- // We only want to freeze Dirents with active references, not Dirents referenced\n- // by a mount's MountSource.\n- mns.flushMountSourceRefsLocked()\n-\n- // Freeze the entire shebang.\n- mns.root.Freeze()\n-}\n-\n// withMountLocked prevents further walks to `node`, because `node` is about to\n// be a mount point.\nfunc (mns *MountNamespace) withMountLocked(node *Dirent, fn func() error) error {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove the "frozen" bit from dirents.
Frozen was to lock down changes to the host filesystem
for hostFS. Now that hostFS is gone, it can be removed.
PiperOrigin-RevId: 301907923 |
259,975 | 19.03.2020 16:05:52 | 25,200 | b9210b285566acd72d0820b42c1a330ba56a1ad0 | Fix bm-tools to run on bazel.
Fixes random stuff that is broken on bazel/kokoro.
random output coming back as "bytes" object instead of str
missed syntax error in bazel
a flag is missing in the version of gcloud on kokoro | [
{
"change_type": "MODIFY",
"old_path": "benchmarks/harness/machine_producers/gcloud_producer.py",
"new_path": "benchmarks/harness/machine_producers/gcloud_producer.py",
"diff": "@@ -168,7 +168,9 @@ class GCloudProducer(machine_producer.MachineProducer):\ncmd.append(\"--zone=\" + self.zone)\ncmd.append(\"--machine-type=\" + self.machine_type)\nres = self._run_command(cmd)\n- return json.loads(res.stdout)\n+ data = res.stdout\n+ data = str(data, \"utf-8\") if isinstance(data, (bytes, bytearray)) else data\n+ return json.loads(data)\ndef _add_ssh_key_to_instances(self, names: List[str]) -> None:\n\"\"\"Adds ssh key to instances by calling gcloud ssh command.\n@@ -186,11 +188,11 @@ class GCloudProducer(machine_producer.MachineProducer):\nTimeoutError: when 3 unsuccessful tries to ssh into the host return 255.\n\"\"\"\nfor name in names:\n- cmd = \"gcloud compute ssh {name}\".format(name=name).split(\" \")\n+ cmd = \"gcloud compute ssh {user}@{name}\".format(\n+ user=self.ssh_user, name=name).split(\" \")\ncmd.append(\"--ssh-key-file={key}\".format(key=self.ssh_key_file))\ncmd.append(\"--zone={zone}\".format(zone=self.zone))\ncmd.append(\"--command=uname\")\n- cmd.append(\"--ssh-key-expire-after=60m\")\ntimeout = datetime.timedelta(seconds=5 * 60)\nstart = datetime.datetime.now()\nwhile datetime.datetime.now() <= timeout + start:\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/images/BUILD",
"new_path": "tools/images/BUILD",
"diff": "@@ -9,7 +9,7 @@ package(\ngenrule(\nname = \"zone\",\nouts = [\"zone.txt\"],\n- cmd = \"gcloud config get-value compute/zone > $@\",\n+ cmd = \"gcloud config get-value compute/zone > \\\"$@\\\"\",\ntags = [\n\"local\",\n\"manual\",\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix bm-tools to run on bazel.
Fixes random stuff that is broken on bazel/kokoro.
- random output coming back as "bytes" object instead of str
- missed syntax error in bazel
- a flag is missing in the version of gcloud on kokoro
PiperOrigin-RevId: 301915289 |
259,992 | 19.03.2020 20:17:03 | 25,200 | 069f1edbe42ebd91800f9b35e8724babc4081613 | Improve error message when pivot_root fails | [
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/chroot.go",
"new_path": "runsc/cmd/chroot.go",
"diff": "@@ -50,7 +50,7 @@ func pivotRoot(root string) error {\n// new_root, so after umounting the old_root, we will see only\n// the new_root in \"/\".\nif err := syscall.PivotRoot(\".\", \".\"); err != nil {\n- return fmt.Errorf(\"error changing root filesystem: %v\", err)\n+ return fmt.Errorf(\"pivot_root failed, make sure that the root mount has a parent: %v\", err)\n}\nif err := syscall.Unmount(\".\", syscall.MNT_DETACH); err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/gofer.go",
"new_path": "runsc/cmd/gofer.go",
"diff": "@@ -335,7 +335,7 @@ func setupRootFS(spec *specs.Spec, conf *boot.Config) error {\nif !conf.TestOnlyAllowRunAsCurrentUserWithoutChroot {\nif err := pivotRoot(\"/proc\"); err != nil {\n- Fatalf(\"faild to change the root file system: %v\", err)\n+ Fatalf(\"failed to change the root file system: %v\", err)\n}\nif err := os.Chdir(\"/\"); err != nil {\nFatalf(\"failed to change working directory\")\n"
}
] | Go | Apache License 2.0 | google/gvisor | Improve error message when pivot_root fails
PiperOrigin-RevId: 301949722 |
259,860 | 19.03.2020 23:29:15 | 25,200 | 248e46f320525704da917e148a8f69d9b74671a0 | Whitelist utimensat(2).
utimensat is used by hostfs for setting timestamps on imported fds. Previously,
this would crash the sandbox since utimensat was not allowed.
Correct the VFS2 version of hostfs to match the call in VFS1. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/host/BUILD",
"new_path": "pkg/sentry/fsimpl/host/BUILD",
"diff": "@@ -9,6 +9,7 @@ go_library(\n\"ioctl_unsafe.go\",\n\"tty.go\",\n\"util.go\",\n+ \"util_unsafe.go\",\n],\nvisibility = [\"//pkg/sentry:internal\"],\ndeps = [\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/host/host.go",
"new_path": "pkg/sentry/fsimpl/host/host.go",
"diff": "@@ -322,11 +322,11 @@ func (i *inode) SetStat(ctx context.Context, fs *vfs.Filesystem, creds *auth.Cre\n}\n}\nif m&(linux.STATX_ATIME|linux.STATX_MTIME) != 0 {\n- timestamps := []unix.Timespec{\n+ ts := [2]syscall.Timespec{\ntoTimespec(s.Atime, m&linux.STATX_ATIME == 0),\ntoTimespec(s.Mtime, m&linux.STATX_MTIME == 0),\n}\n- if err := unix.UtimesNanoAt(i.hostFD, \"\", timestamps, unix.AT_EMPTY_PATH); err != nil {\n+ if err := setTimestamps(i.hostFD, &ts); err != nil {\nreturn err\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/host/util.go",
"new_path": "pkg/sentry/fsimpl/host/util.go",
"diff": "@@ -22,15 +22,15 @@ import (\n\"gvisor.dev/gvisor/pkg/syserror\"\n)\n-func toTimespec(ts linux.StatxTimestamp, omit bool) unix.Timespec {\n+func toTimespec(ts linux.StatxTimestamp, omit bool) syscall.Timespec {\nif omit {\n- return unix.Timespec{\n+ return syscall.Timespec{\nSec: 0,\nNsec: unix.UTIME_OMIT,\n}\n}\n- return unix.Timespec{\n- Sec: int64(ts.Sec),\n+ return syscall.Timespec{\n+ Sec: ts.Sec,\nNsec: int64(ts.Nsec),\n}\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fsimpl/host/util_unsafe.go",
"diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package host\n+\n+import (\n+ \"syscall\"\n+ \"unsafe\"\n+)\n+\n+func setTimestamps(fd int, ts *[2]syscall.Timespec) error {\n+ _, _, errno := syscall.Syscall6(\n+ syscall.SYS_UTIMENSAT,\n+ uintptr(fd),\n+ 0, /* path */\n+ uintptr(unsafe.Pointer(ts)),\n+ 0, /* flags */\n+ 0, 0)\n+ if errno != 0 {\n+ return errno\n+ }\n+ return nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/filter/config.go",
"new_path": "runsc/boot/filter/config.go",
"diff": "@@ -291,6 +291,14 @@ var allowedSyscalls = seccomp.SyscallRules{\nseccomp.AllowValue(uint64(os.Getpid())),\n},\n},\n+ syscall.SYS_UTIMENSAT: []seccomp.Rule{\n+ {\n+ seccomp.AllowAny{},\n+ seccomp.AllowValue(0), /* null pathname */\n+ seccomp.AllowAny{},\n+ seccomp.AllowValue(0), /* flags */\n+ },\n+ },\nsyscall.SYS_WRITE: {},\n// The only user in rawfile.NonBlockingWrite3 always passes iovcnt with\n// values 2 or 3. Three iovec-s are passed, when the PACKET_VNET_HDR\n"
}
] | Go | Apache License 2.0 | google/gvisor | Whitelist utimensat(2).
utimensat is used by hostfs for setting timestamps on imported fds. Previously,
this would crash the sandbox since utimensat was not allowed.
Correct the VFS2 version of hostfs to match the call in VFS1.
PiperOrigin-RevId: 301970121 |
260,003 | 20.03.2020 15:24:00 | 25,200 | 49aef9cee70d111f6c3e1a6b04430bbe414a6c1e | Remove unused variable `sndNxtList`. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/connect.go",
"new_path": "pkg/tcpip/transport/tcp/connect.go",
"diff": "@@ -878,7 +878,6 @@ func (e *endpoint) handleWrite() *tcpip.Error {\nfirst := e.sndQueue.Front()\nif first != nil {\ne.snd.writeList.PushBackList(&e.sndQueue)\n- e.snd.sndNxtList.UpdateForward(e.sndBufInQueue)\ne.sndBufInQueue = 0\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/snd.go",
"new_path": "pkg/tcpip/transport/tcp/snd.go",
"diff": "@@ -126,10 +126,6 @@ type sender struct {\n// sndNxt is the sequence number of the next segment to be sent.\nsndNxt seqnum.Value\n- // sndNxtList is the sequence number of the next segment to be added to\n- // the send list.\n- sndNxtList seqnum.Value\n-\n// rttMeasureSeqNum is the sequence number being used for the latest RTT\n// measurement.\nrttMeasureSeqNum seqnum.Value\n@@ -229,7 +225,6 @@ func newSender(ep *endpoint, iss, irs seqnum.Value, sndWnd seqnum.Size, mss uint\nsndWnd: sndWnd,\nsndUna: iss + 1,\nsndNxt: iss + 1,\n- sndNxtList: iss + 1,\nrto: 1 * time.Second,\nrttMeasureSeqNum: iss + 1,\nlastSendTime: time.Now(),\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove unused variable `sndNxtList`.
PiperOrigin-RevId: 302110328 |
259,962 | 20.03.2020 17:00:55 | 25,200 | 1bf2e52bdb5f366b397cb887d4cbdb91dd5e3213 | Actually wrap rand.Reader in bufio.Reader.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/rand/rand_linux.go",
"new_path": "pkg/rand/rand_linux.go",
"diff": "package rand\nimport (\n+ \"bufio\"\n\"crypto/rand\"\n\"io\"\n@@ -45,8 +46,22 @@ func (r *reader) Read(p []byte) (int, error) {\nreturn rand.Read(p)\n}\n+// bufferedReader implements a threadsafe buffered io.Reader.\n+type bufferedReader struct {\n+ mu sync.Mutex\n+ r *bufio.Reader\n+}\n+\n+// Read implements io.Reader.Read.\n+func (b *bufferedReader) Read(p []byte) (int, error) {\n+ b.mu.Lock()\n+ n, err := b.r.Read(p)\n+ b.mu.Unlock()\n+ return n, err\n+}\n+\n// Reader is the default reader.\n-var Reader io.Reader = &reader{}\n+var Reader io.Reader = &bufferedReader{r: bufio.NewReader(&reader{})}\n// Read reads from the default reader.\nfunc Read(b []byte) (int, error) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Actually wrap rand.Reader in bufio.Reader.
Updates #231
PiperOrigin-RevId: 302127697 |
259,972 | 20.03.2020 18:22:49 | 25,200 | fed59953aad40d89730ebfc6f33b17116c42abcf | Statically link libpthread for static c++ binaries.
The posix_server works fine when run in locally or in docker but fails in the
kokoro GCP build environment. Linking libpthread statically fixes it. | [
{
"change_type": "MODIFY",
"old_path": "tools/bazeldefs/defs.bzl",
"new_path": "tools/bazeldefs/defs.bzl",
"diff": "@@ -65,10 +65,17 @@ def cc_binary(name, static = False, **kwargs):\n**kwargs: the rest of the args.\n\"\"\"\nif static:\n- if \"linkopts\" in kwargs:\n- kwargs[\"linkopts\"] += [\"-static\", \"-lstdc++\"]\n- else:\n- kwargs[\"linkopts\"] = [\"-static\", \"-lstdc++\"]\n+ # How to statically link a c++ program that uses threads, like for gRPC:\n+ # https://gcc.gnu.org/legacy-ml/gcc-help/2010-05/msg00029.html\n+ if \"linkopts\" not in kwargs:\n+ kwargs[\"linkopts\"] = []\n+ kwargs[\"linkopts\"] += [\n+ \"-static\",\n+ \"-lstdc++\",\n+ \"-Wl,--whole-archive\",\n+ \"-lpthread\",\n+ \"-Wl,--no-whole-archive\",\n+ ]\n_cc_binary(\nname = name,\n**kwargs\n"
}
] | Go | Apache License 2.0 | google/gvisor | Statically link libpthread for static c++ binaries.
The posix_server works fine when run in locally or in docker but fails in the
kokoro GCP build environment. Linking libpthread statically fixes it.
PiperOrigin-RevId: 302139082 |
259,860 | 23.03.2020 14:32:05 | 25,200 | 6eebaea94936ffefd3603ff16ad2225856313fa3 | Correctly release taskPathOperation for accessAt. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/stat.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/stat.go",
"diff": "@@ -272,6 +272,7 @@ func accessAt(t *kernel.Task, dirfd int32, pathAddr usermem.Addr, mode uint) err\nif err != nil {\nreturn err\n}\n+ defer tpop.Release()\n// access(2) and faccessat(2) check permissions using real\n// UID/GID, not effective UID/GID.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Correctly release taskPathOperation for accessAt.
PiperOrigin-RevId: 302518924 |
259,962 | 23.03.2020 16:05:29 | 25,200 | 369cf38bd7186da97e134538cd4839a8a4d1aa2c | Fix data race in SetSockOpt. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/netstack.go",
"new_path": "pkg/sentry/socket/netstack/netstack.go",
"diff": "@@ -2382,9 +2382,9 @@ func (s *SocketOperations) nonBlockingRead(ctx context.Context, dst usermem.IOSe\n// caller-supplied buffer.\ns.readMu.Lock()\nn, err := s.coalescingRead(ctx, dst, trunc)\n- s.readMu.Unlock()\ncmsg := s.controlMessages()\ns.fillCmsgInq(&cmsg)\n+ s.readMu.Unlock()\nreturn n, 0, nil, 0, cmsg, err\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix data race in SetSockOpt.
PiperOrigin-RevId: 302539171 |
259,884 | 23.03.2020 16:11:37 | 25,200 | a730d74b3230fb32181b9a940c07b61338222874 | Support basic /proc/net/dev metrics for netstack
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/stack.go",
"new_path": "pkg/sentry/socket/netstack/stack.go",
"diff": "@@ -200,36 +200,66 @@ func (s *Stack) SetTCPSACKEnabled(enabled bool) error {\n// Statistics implements inet.Stack.Statistics.\nfunc (s *Stack) Statistics(stat interface{}, arg string) error {\nswitch stats := stat.(type) {\n+ case *inet.StatDev:\n+ for _, ni := range s.Stack.NICInfo() {\n+ if ni.Name != arg {\n+ continue\n+ }\n+ // TODO(gvisor.dev/issue/2103) Support stubbed stats.\n+ *stats = inet.StatDev{\n+ // Receive section.\n+ ni.Stats.Rx.Bytes.Value(), // bytes.\n+ ni.Stats.Rx.Packets.Value(), // packets.\n+ 0, // errs.\n+ 0, // drop.\n+ 0, // fifo.\n+ 0, // frame.\n+ 0, // compressed.\n+ 0, // multicast.\n+ // Transmit section.\n+ ni.Stats.Tx.Bytes.Value(), // bytes.\n+ ni.Stats.Tx.Packets.Value(), // packets.\n+ 0, // errs.\n+ 0, // drop.\n+ 0, // fifo.\n+ 0, // colls.\n+ 0, // carrier.\n+ 0, // compressed.\n+ }\n+ break\n+ }\ncase *inet.StatSNMPIP:\nip := Metrics.IP\n+ // TODO(gvisor.dev/issue/969) Support stubbed stats.\n*stats = inet.StatSNMPIP{\n- 0, // TODO(gvisor.dev/issue/969): Support Ip/Forwarding.\n- 0, // TODO(gvisor.dev/issue/969): Support Ip/DefaultTTL.\n+ 0, // Ip/Forwarding.\n+ 0, // Ip/DefaultTTL.\nip.PacketsReceived.Value(), // InReceives.\n- 0, // TODO(gvisor.dev/issue/969): Support Ip/InHdrErrors.\n+ 0, // Ip/InHdrErrors.\nip.InvalidDestinationAddressesReceived.Value(), // InAddrErrors.\n- 0, // TODO(gvisor.dev/issue/969): Support Ip/ForwDatagrams.\n- 0, // TODO(gvisor.dev/issue/969): Support Ip/InUnknownProtos.\n- 0, // TODO(gvisor.dev/issue/969): Support Ip/InDiscards.\n+ 0, // Ip/ForwDatagrams.\n+ 0, // Ip/InUnknownProtos.\n+ 0, // Ip/InDiscards.\nip.PacketsDelivered.Value(), // InDelivers.\nip.PacketsSent.Value(), // OutRequests.\nip.OutgoingPacketErrors.Value(), // OutDiscards.\n- 0, // TODO(gvisor.dev/issue/969): Support Ip/OutNoRoutes.\n- 0, // TODO(gvisor.dev/issue/969): Support Ip/ReasmTimeout.\n- 0, // TODO(gvisor.dev/issue/969): Support Ip/ReasmReqds.\n- 0, // TODO(gvisor.dev/issue/969): Support Ip/ReasmOKs.\n- 0, // TODO(gvisor.dev/issue/969): Support Ip/ReasmFails.\n- 0, // TODO(gvisor.dev/issue/969): Support Ip/FragOKs.\n- 0, // TODO(gvisor.dev/issue/969): Support Ip/FragFails.\n- 0, // TODO(gvisor.dev/issue/969): Support Ip/FragCreates.\n+ 0, // Ip/OutNoRoutes.\n+ 0, // Support Ip/ReasmTimeout.\n+ 0, // Support Ip/ReasmReqds.\n+ 0, // Support Ip/ReasmOKs.\n+ 0, // Support Ip/ReasmFails.\n+ 0, // Support Ip/FragOKs.\n+ 0, // Support Ip/FragFails.\n+ 0, // Support Ip/FragCreates.\n}\ncase *inet.StatSNMPICMP:\nin := Metrics.ICMP.V4PacketsReceived.ICMPv4PacketStats\nout := Metrics.ICMP.V4PacketsSent.ICMPv4PacketStats\n+ // TODO(gvisor.dev/issue/969) Support stubbed stats.\n*stats = inet.StatSNMPICMP{\n- 0, // TODO(gvisor.dev/issue/969): Support Icmp/InMsgs.\n+ 0, // Icmp/InMsgs.\nMetrics.ICMP.V4PacketsSent.Dropped.Value(), // InErrors.\n- 0, // TODO(gvisor.dev/issue/969): Support Icmp/InCsumErrors.\n+ 0, // Icmp/InCsumErrors.\nin.DstUnreachable.Value(), // InDestUnreachs.\nin.TimeExceeded.Value(), // InTimeExcds.\nin.ParamProblem.Value(), // InParmProbs.\n@@ -241,7 +271,7 @@ func (s *Stack) Statistics(stat interface{}, arg string) error {\nin.TimestampReply.Value(), // InTimestampReps.\nin.InfoRequest.Value(), // InAddrMasks.\nin.InfoReply.Value(), // InAddrMaskReps.\n- 0, // TODO(gvisor.dev/issue/969): Support Icmp/OutMsgs.\n+ 0, // Icmp/OutMsgs.\nMetrics.ICMP.V4PacketsReceived.Invalid.Value(), // OutErrors.\nout.DstUnreachable.Value(), // OutDestUnreachs.\nout.TimeExceeded.Value(), // OutTimeExcds.\n@@ -277,15 +307,16 @@ func (s *Stack) Statistics(stat interface{}, arg string) error {\n}\ncase *inet.StatSNMPUDP:\nudp := Metrics.UDP\n+ // TODO(gvisor.dev/issue/969) Support stubbed stats.\n*stats = inet.StatSNMPUDP{\nudp.PacketsReceived.Value(), // InDatagrams.\nudp.UnknownPortErrors.Value(), // NoPorts.\n- 0, // TODO(gvisor.dev/issue/969): Support Udp/InErrors.\n+ 0, // Udp/InErrors.\nudp.PacketsSent.Value(), // OutDatagrams.\nudp.ReceiveBufferErrors.Value(), // RcvbufErrors.\n- 0, // TODO(gvisor.dev/issue/969): Support Udp/SndbufErrors.\n- 0, // TODO(gvisor.dev/issue/969): Support Udp/InCsumErrors.\n- 0, // TODO(gvisor.dev/issue/969): Support Udp/IgnoredMulti.\n+ 0, // Udp/SndbufErrors.\n+ 0, // Udp/InCsumErrors.\n+ 0, // Udp/IgnoredMulti.\n}\ndefault:\nreturn syserr.ErrEndpointOperation.ToError()\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/proc_net.cc",
"new_path": "test/syscalls/linux/proc_net.cc",
"diff": "@@ -92,6 +92,59 @@ TEST(ProcSysNetIpv4Sack, CanReadAndWrite) {\nEXPECT_EQ(buf, to_write);\n}\n+// DeviceEntry is an entry in /proc/net/dev\n+struct DeviceEntry {\n+ std::string name;\n+ uint64_t stats[16];\n+};\n+\n+PosixErrorOr<std::vector<DeviceEntry>> GetDeviceMetricsFromProc(\n+ const std::string dev) {\n+ std::vector<std::string> lines = absl::StrSplit(dev, '\\n');\n+ std::vector<DeviceEntry> entries;\n+\n+ // /proc/net/dev prints 2 lines of headers followed by a line of metrics for\n+ // each network interface.\n+ for (unsigned i = 2; i < lines.size(); i++) {\n+ // Ignore empty lines.\n+ if (lines[i].empty()) {\n+ continue;\n+ }\n+\n+ std::vector<std::string> values =\n+ absl::StrSplit(lines[i], ' ', absl::SkipWhitespace());\n+\n+ // Interface name + 16 values.\n+ if (values.size() != 17) {\n+ return PosixError(EINVAL, \"invalid line: \" + lines[i]);\n+ }\n+\n+ DeviceEntry entry;\n+ entry.name = values[0];\n+ // Skip the interface name and read only the values.\n+ for (unsigned j = 1; j < 17; j++) {\n+ uint64_t num;\n+ if (!absl::SimpleAtoi(values[j], &num)) {\n+ return PosixError(EINVAL, \"invalid value: \" + values[j]);\n+ }\n+ entry.stats[j - 1] = num;\n+ }\n+\n+ entries.push_back(entry);\n+ }\n+\n+ return entries;\n+}\n+\n+// TEST(ProcNetDev, Format) tests that /proc/net/dev is parsable and\n+// contains at least one entry.\n+TEST(ProcNetDev, Format) {\n+ auto dev = ASSERT_NO_ERRNO_AND_VALUE(GetContents(\"/proc/net/dev\"));\n+ auto entries = ASSERT_NO_ERRNO_AND_VALUE(GetDeviceMetricsFromProc(dev));\n+\n+ EXPECT_GT(entries.size(), 0);\n+}\n+\nPosixErrorOr<uint64_t> GetSNMPMetricFromProc(const std::string snmp,\nconst std::string& type,\nconst std::string& item) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Support basic /proc/net/dev metrics for netstack
Fixes #506
PiperOrigin-RevId: 302540404 |
259,962 | 24.03.2020 15:33:16 | 25,200 | c8eeedcc1d6b1ee25532ae630a7efd7aa4656bdc | Add support for setting TCP segment hash.
This allows the link layer endpoints to consistenly hash a TCP
segment to a single underlying queue in case a link layer endpoint
does support multiple underlying queues.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/endpoint.go",
"new_path": "pkg/tcpip/link/fdbased/endpoint.go",
"diff": "@@ -405,6 +405,7 @@ func (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, protocol tcpip.Ne\neth.Encode(ethHdr)\n}\n+ fd := e.fds[pkt.Hash%uint32(len(e.fds))]\nif e.Capabilities()&stack.CapabilityHardwareGSO != 0 {\nvnetHdr := virtioNetHdr{}\nif gso != nil {\n@@ -428,14 +429,14 @@ func (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, protocol tcpip.Ne\n}\nvnetHdrBuf := vnetHdrToByteSlice(&vnetHdr)\n- return rawfile.NonBlockingWrite3(e.fds[0], vnetHdrBuf, pkt.Header.View(), pkt.Data.ToView())\n+ return rawfile.NonBlockingWrite3(fd, vnetHdrBuf, pkt.Header.View(), pkt.Data.ToView())\n}\nif pkt.Data.Size() == 0 {\n- return rawfile.NonBlockingWrite(e.fds[0], pkt.Header.View())\n+ return rawfile.NonBlockingWrite(fd, pkt.Header.View())\n}\n- return rawfile.NonBlockingWrite3(e.fds[0], pkt.Header.View(), pkt.Data.ToView(), nil)\n+ return rawfile.NonBlockingWrite3(fd, pkt.Header.View(), pkt.Data.ToView(), nil)\n}\n// WritePackets writes outbound packets to the file descriptor. If it is not\n@@ -551,7 +552,8 @@ func (e *endpoint) WritePackets(r *stack.Route, gso *stack.GSO, pkts []stack.Pac\npackets := 0\nfor packets < n {\n- sent, err := rawfile.NonBlockingSendMMsg(e.fds[0], mmsgHdrs)\n+ fd := e.fds[pkts[packets].Hash%uint32(len(e.fds))]\n+ sent, err := rawfile.NonBlockingSendMMsg(fd, mmsgHdrs)\nif err != nil {\nreturn packets, err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/endpoint_test.go",
"new_path": "pkg/tcpip/link/fdbased/endpoint_test.go",
"diff": "@@ -50,24 +50,29 @@ type packetInfo struct {\ntype context struct {\nt *testing.T\n- fds [2]int\n+ readFDs []int\n+ writeFDs []int\nep stack.LinkEndpoint\nch chan packetInfo\ndone chan struct{}\n}\nfunc newContext(t *testing.T, opt *Options) *context {\n- fds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_SEQPACKET, 0)\n+ firstFDPair, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_SEQPACKET, 0)\n+ if err != nil {\n+ t.Fatalf(\"Socketpair failed: %v\", err)\n+ }\n+ secondFDPair, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_SEQPACKET, 0)\nif err != nil {\nt.Fatalf(\"Socketpair failed: %v\", err)\n}\n- done := make(chan struct{}, 1)\n+ done := make(chan struct{}, 2)\nopt.ClosedFunc = func(*tcpip.Error) {\ndone <- struct{}{}\n}\n- opt.FDs = []int{fds[1]}\n+ opt.FDs = []int{firstFDPair[1], secondFDPair[1]}\nep, err := New(opt)\nif err != nil {\nt.Fatalf(\"Failed to create FD endpoint: %v\", err)\n@@ -75,7 +80,8 @@ func newContext(t *testing.T, opt *Options) *context {\nc := &context{\nt: t,\n- fds: fds,\n+ readFDs: []int{firstFDPair[0], secondFDPair[0]},\n+ writeFDs: opt.FDs,\nep: ep,\nch: make(chan packetInfo, 100),\ndone: done,\n@@ -87,9 +93,14 @@ func newContext(t *testing.T, opt *Options) *context {\n}\nfunc (c *context) cleanup() {\n- syscall.Close(c.fds[0])\n+ for _, fd := range c.readFDs {\n+ syscall.Close(fd)\n+ }\n+ <-c.done\n<-c.done\n- syscall.Close(c.fds[1])\n+ for _, fd := range c.writeFDs {\n+ syscall.Close(fd)\n+ }\n}\nfunc (c *context) DeliverNetworkPacket(linkEP stack.LinkEndpoint, remote tcpip.LinkAddress, local tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, pkt stack.PacketBuffer) {\n@@ -136,7 +147,7 @@ func TestAddress(t *testing.T) {\n}\n}\n-func testWritePacket(t *testing.T, plen int, eth bool, gsoMaxSize uint32) {\n+func testWritePacket(t *testing.T, plen int, eth bool, gsoMaxSize uint32, hash uint32) {\nc := newContext(t, &Options{Address: laddr, MTU: mtu, EthernetHeader: eth, GSOMaxSize: gsoMaxSize})\ndefer c.cleanup()\n@@ -171,13 +182,15 @@ func testWritePacket(t *testing.T, plen int, eth bool, gsoMaxSize uint32) {\nif err := c.ep.WritePacket(r, gso, proto, stack.PacketBuffer{\nHeader: hdr,\nData: payload.ToVectorisedView(),\n+ Hash: hash,\n}); err != nil {\nt.Fatalf(\"WritePacket failed: %v\", err)\n}\n- // Read from fd, then compare with what we wrote.\n+ // Read from the corresponding FD, then compare with what we wrote.\nb = make([]byte, mtu)\n- n, err := syscall.Read(c.fds[0], b)\n+ fd := c.readFDs[hash%uint32(len(c.readFDs))]\n+ n, err := syscall.Read(fd, b)\nif err != nil {\nt.Fatalf(\"Read failed: %v\", err)\n}\n@@ -238,13 +251,34 @@ func TestWritePacket(t *testing.T) {\nt.Run(\nfmt.Sprintf(\"Eth=%v,PayloadLen=%v,GSOMaxSize=%v\", eth, plen, gso),\nfunc(t *testing.T) {\n- testWritePacket(t, plen, eth, gso)\n+ testWritePacket(t, plen, eth, gso, 0)\n+ },\n+ )\n+ }\n+ }\n+ }\n+}\n+\n+func TestHashedWritePacket(t *testing.T) {\n+ lengths := []int{0, 100, 1000}\n+ eths := []bool{true, false}\n+ gsos := []uint32{0, 32768}\n+ hashes := []uint32{0, 1}\n+ for _, eth := range eths {\n+ for _, plen := range lengths {\n+ for _, gso := range gsos {\n+ for _, hash := range hashes {\n+ t.Run(\n+ fmt.Sprintf(\"Eth=%v,PayloadLen=%v,GSOMaxSize=%v,Hash=%d\", eth, plen, gso, hash),\n+ func(t *testing.T) {\n+ testWritePacket(t, plen, eth, gso, hash)\n},\n)\n}\n}\n}\n}\n+}\nfunc TestPreserveSrcAddress(t *testing.T) {\nbaddr := tcpip.LinkAddress(\"\\xcc\\xbb\\xaa\\x77\\x88\\x99\")\n@@ -270,7 +304,7 @@ func TestPreserveSrcAddress(t *testing.T) {\n// Read from the FD, then compare with what we wrote.\nb := make([]byte, mtu)\n- n, err := syscall.Read(c.fds[0], b)\n+ n, err := syscall.Read(c.readFDs[0], b)\nif err != nil {\nt.Fatalf(\"Read failed: %v\", err)\n}\n@@ -314,7 +348,7 @@ func TestDeliverPacket(t *testing.T) {\n}\n// Write packet via the file descriptor.\n- if _, err := syscall.Write(c.fds[0], all); err != nil {\n+ if _, err := syscall.Write(c.readFDs[0], all); err != nil {\nt.Fatalf(\"Write failed: %v\", err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/BUILD",
"new_path": "pkg/tcpip/stack/BUILD",
"diff": "@@ -30,6 +30,7 @@ go_library(\n\"nic.go\",\n\"packet_buffer.go\",\n\"packet_buffer_state.go\",\n+ \"rand.go\",\n\"registration.go\",\n\"route.go\",\n\"stack.go\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/packet_buffer.go",
"new_path": "pkg/tcpip/stack/packet_buffer.go",
"diff": "// 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+\npackage stack\nimport \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n@@ -54,6 +55,10 @@ type PacketBuffer struct {\nLinkHeader buffer.View\nNetworkHeader buffer.View\nTransportHeader buffer.View\n+\n+ // Hash is the transport layer hash of this packet. A value of zero\n+ // indicates no valid hash has been set.\n+ Hash uint32\n}\n// Clone makes a copy of pk. It clones the Data field, which creates a new\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/packet_buffer_state.go",
"new_path": "pkg/tcpip/stack/packet_buffer_state.go",
"diff": "// 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+\npackage stack\nimport \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/tcpip/stack/rand.go",
"diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package stack\n+\n+import (\n+ mathrand \"math/rand\"\n+\n+ \"gvisor.dev/gvisor/pkg/sync\"\n+)\n+\n+// lockedRandomSource provides a threadsafe rand.Source.\n+type lockedRandomSource struct {\n+ mu sync.Mutex\n+ src mathrand.Source\n+}\n+\n+func (r *lockedRandomSource) Int63() (n int64) {\n+ r.mu.Lock()\n+ n = r.src.Int63()\n+ r.mu.Unlock()\n+ return n\n+}\n+\n+func (r *lockedRandomSource) Seed(seed int64) {\n+ r.mu.Lock()\n+ r.src.Seed(seed)\n+ r.mu.Unlock()\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "package stack\nimport (\n+ \"bytes\"\n\"encoding/binary\"\n+ mathrand \"math/rand\"\n\"sync/atomic\"\n\"time\"\n@@ -465,6 +467,10 @@ type Stack struct {\n// forwarder holds the packets that wait for their link-address resolutions\n// to complete, and forwards them when each resolution is done.\nforwarder *forwardQueue\n+\n+ // randomGenerator is an injectable pseudo random generator that can be\n+ // used when a random number is required.\n+ randomGenerator *mathrand.Rand\n}\n// UniqueID is an abstract generator of unique identifiers.\n@@ -525,9 +531,16 @@ type Options struct {\n// this is non-nil.\nRawFactory RawFactory\n- // OpaqueIIDOpts hold the options for generating opaque interface identifiers\n- // (IIDs) as outlined by RFC 7217.\n+ // OpaqueIIDOpts hold the options for generating opaque interface\n+ // identifiers (IIDs) as outlined by RFC 7217.\nOpaqueIIDOpts OpaqueInterfaceIdentifierOptions\n+\n+ // RandSource is an optional source to use to generate random\n+ // numbers. If omitted it defaults to a Source seeded by the data\n+ // returned by rand.Read().\n+ //\n+ // RandSource must be thread-safe.\n+ RandSource mathrand.Source\n}\n// TransportEndpointInfo holds useful information about a transport endpoint\n@@ -623,6 +636,13 @@ func New(opts Options) *Stack {\nopts.UniqueID = new(uniqueIDGenerator)\n}\n+ randSrc := opts.RandSource\n+ if randSrc == nil {\n+ // Source provided by mathrand.NewSource is not thread-safe so\n+ // we wrap it in a simple thread-safe version.\n+ randSrc = &lockedRandomSource{src: mathrand.NewSource(generateRandInt64())}\n+ }\n+\n// Make sure opts.NDPConfigs contains valid values only.\nopts.NDPConfigs.validate()\n@@ -645,6 +665,7 @@ func New(opts Options) *Stack {\nndpDisp: opts.NDPDisp,\nopaqueIIDOpts: opts.OpaqueIIDOpts,\nforwarder: newForwardQueue(),\n+ randomGenerator: mathrand.New(randSrc),\n}\n// Add specified network protocols.\n@@ -1818,6 +1839,12 @@ func (s *Stack) Seed() uint32 {\nreturn s.seed\n}\n+// Rand returns a reference to a pseudo random generator that can be used\n+// to generate random numbers as required.\n+func (s *Stack) Rand() *mathrand.Rand {\n+ return s.randomGenerator\n+}\n+\nfunc generateRandUint32() uint32 {\nb := make([]byte, 4)\nif _, err := rand.Read(b); err != nil {\n@@ -1825,3 +1852,16 @@ func generateRandUint32() uint32 {\n}\nreturn binary.LittleEndian.Uint32(b)\n}\n+\n+func generateRandInt64() int64 {\n+ b := make([]byte, 8)\n+ if _, err := rand.Read(b); err != nil {\n+ panic(err)\n+ }\n+ buf := bytes.NewReader(b)\n+ var v int64\n+ if err := binary.Read(buf, binary.LittleEndian, &v); err != nil {\n+ panic(err)\n+ }\n+ return v\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/accept.go",
"new_path": "pkg/tcpip/transport/tcp/accept.go",
"diff": "@@ -445,7 +445,15 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) {\n// RFC 793 section 3.4 page 35 (figure 12) outlines that a RST\n// must be sent in response to a SYN-ACK while in the listen\n// state to prevent completing a handshake from an old SYN.\n- e.sendTCP(&s.route, s.id, buffer.VectorisedView{}, e.ttl, e.sendTOS, header.TCPFlagRst, s.ackNumber, 0, 0, nil, nil)\n+ e.sendTCP(&s.route, tcpFields{\n+ id: s.id,\n+ ttl: e.ttl,\n+ tos: e.sendTOS,\n+ flags: header.TCPFlagRst,\n+ seq: s.ackNumber,\n+ ack: 0,\n+ rcvWnd: 0,\n+ }, buffer.VectorisedView{}, nil)\nreturn\n}\n@@ -493,7 +501,15 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) {\nTSEcr: opts.TSVal,\nMSS: mssForRoute(&s.route),\n}\n- e.sendSynTCP(&s.route, s.id, e.ttl, e.sendTOS, header.TCPFlagSyn|header.TCPFlagAck, cookie, s.sequenceNumber+1, ctx.rcvWnd, synOpts)\n+ e.sendSynTCP(&s.route, tcpFields{\n+ id: s.id,\n+ ttl: e.ttl,\n+ tos: e.sendTOS,\n+ flags: header.TCPFlagSyn | header.TCPFlagAck,\n+ seq: cookie,\n+ ack: s.sequenceNumber + 1,\n+ rcvWnd: ctx.rcvWnd,\n+ }, synOpts)\ne.stack.Stats().TCP.ListenOverflowSynCookieSent.Increment()\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/connect.go",
"new_path": "pkg/tcpip/transport/tcp/connect.go",
"diff": "@@ -308,7 +308,15 @@ func (h *handshake) synSentState(s *segment) *tcpip.Error {\nif ttl == 0 {\nttl = s.route.DefaultTTL()\n}\n- h.ep.sendSynTCP(&s.route, h.ep.ID, ttl, h.ep.sendTOS, h.flags, h.iss, h.ackNum, h.rcvWnd, synOpts)\n+ h.ep.sendSynTCP(&s.route, tcpFields{\n+ id: h.ep.ID,\n+ ttl: ttl,\n+ tos: h.ep.sendTOS,\n+ flags: h.flags,\n+ seq: h.iss,\n+ ack: h.ackNum,\n+ rcvWnd: h.rcvWnd,\n+ }, synOpts)\nreturn nil\n}\n@@ -361,7 +369,15 @@ func (h *handshake) synRcvdState(s *segment) *tcpip.Error {\nSACKPermitted: h.ep.sackPermitted,\nMSS: h.ep.amss,\n}\n- h.ep.sendSynTCP(&s.route, h.ep.ID, h.ep.ttl, h.ep.sendTOS, h.flags, h.iss, h.ackNum, h.rcvWnd, synOpts)\n+ h.ep.sendSynTCP(&s.route, tcpFields{\n+ id: h.ep.ID,\n+ ttl: h.ep.ttl,\n+ tos: h.ep.sendTOS,\n+ flags: h.flags,\n+ seq: h.iss,\n+ ack: h.ackNum,\n+ rcvWnd: h.rcvWnd,\n+ }, synOpts)\nreturn nil\n}\n@@ -550,7 +566,16 @@ func (h *handshake) execute() *tcpip.Error {\nsynOpts.WS = -1\n}\n}\n- h.ep.sendSynTCP(&h.ep.route, h.ep.ID, h.ep.ttl, h.ep.sendTOS, h.flags, h.iss, h.ackNum, h.rcvWnd, synOpts)\n+\n+ h.ep.sendSynTCP(&h.ep.route, tcpFields{\n+ id: h.ep.ID,\n+ ttl: h.ep.ttl,\n+ tos: h.ep.sendTOS,\n+ flags: h.flags,\n+ seq: h.iss,\n+ ack: h.ackNum,\n+ rcvWnd: h.rcvWnd,\n+ }, synOpts)\nfor h.state != handshakeCompleted {\nh.ep.mu.Unlock()\n@@ -573,7 +598,15 @@ func (h *handshake) execute() *tcpip.Error {\n// the connection with another ACK or data (as ACKs are never\n// retransmitted on their own).\nif h.active || !h.acked || h.deferAccept != 0 && time.Since(h.startTime) > h.deferAccept {\n- h.ep.sendSynTCP(&h.ep.route, h.ep.ID, h.ep.ttl, h.ep.sendTOS, h.flags, h.iss, h.ackNum, h.rcvWnd, synOpts)\n+ h.ep.sendSynTCP(&h.ep.route, tcpFields{\n+ id: h.ep.ID,\n+ ttl: h.ep.ttl,\n+ tos: h.ep.sendTOS,\n+ flags: h.flags,\n+ seq: h.iss,\n+ ack: h.ackNum,\n+ rcvWnd: h.rcvWnd,\n+ }, synOpts)\n}\ncase wakerForNotification:\n@@ -686,18 +719,33 @@ func makeSynOptions(opts header.TCPSynOptions) []byte {\nreturn options[:offset]\n}\n-func (e *endpoint) sendSynTCP(r *stack.Route, id stack.TransportEndpointID, ttl, tos uint8, flags byte, seq, ack seqnum.Value, rcvWnd seqnum.Size, opts header.TCPSynOptions) *tcpip.Error {\n- options := makeSynOptions(opts)\n+// tcpFields is a struct to carry different parameters required by the\n+// send*TCP variant functions below.\n+type tcpFields struct {\n+ id stack.TransportEndpointID\n+ ttl uint8\n+ tos uint8\n+ flags byte\n+ seq seqnum.Value\n+ ack seqnum.Value\n+ rcvWnd seqnum.Size\n+ opts []byte\n+ txHash uint32\n+}\n+\n+func (e *endpoint) sendSynTCP(r *stack.Route, tf tcpFields, opts header.TCPSynOptions) *tcpip.Error {\n+ tf.opts = makeSynOptions(opts)\n// We ignore SYN send errors and let the callers re-attempt send.\n- if err := e.sendTCP(r, id, buffer.VectorisedView{}, ttl, tos, flags, seq, ack, rcvWnd, options, nil); err != nil {\n+ if err := e.sendTCP(r, tf, buffer.VectorisedView{}, nil); err != nil {\ne.stats.SendErrors.SynSendToNetworkFailed.Increment()\n}\n- putOptions(options)\n+ putOptions(tf.opts)\nreturn nil\n}\n-func (e *endpoint) sendTCP(r *stack.Route, id stack.TransportEndpointID, data buffer.VectorisedView, ttl, tos uint8, flags byte, seq, ack seqnum.Value, rcvWnd seqnum.Size, opts []byte, gso *stack.GSO) *tcpip.Error {\n- if err := sendTCP(r, id, data, ttl, tos, flags, seq, ack, rcvWnd, opts, gso); err != nil {\n+func (e *endpoint) sendTCP(r *stack.Route, tf tcpFields, data buffer.VectorisedView, gso *stack.GSO) *tcpip.Error {\n+ tf.txHash = e.txHash\n+ if err := sendTCP(r, tf, data, gso); err != nil {\ne.stats.SendErrors.SegmentSendToNetworkFailed.Increment()\nreturn err\n}\n@@ -705,8 +753,8 @@ func (e *endpoint) sendTCP(r *stack.Route, id stack.TransportEndpointID, data bu\nreturn nil\n}\n-func buildTCPHdr(r *stack.Route, id stack.TransportEndpointID, pkt *stack.PacketBuffer, flags byte, seq, ack seqnum.Value, rcvWnd seqnum.Size, opts []byte, gso *stack.GSO) {\n- optLen := len(opts)\n+func buildTCPHdr(r *stack.Route, tf tcpFields, pkt *stack.PacketBuffer, gso *stack.GSO) {\n+ optLen := len(tf.opts)\nhdr := &pkt.Header\npacketSize := pkt.DataSize\noff := pkt.DataOffset\n@@ -714,15 +762,15 @@ func buildTCPHdr(r *stack.Route, id stack.TransportEndpointID, pkt *stack.Packet\ntcp := header.TCP(hdr.Prepend(header.TCPMinimumSize + optLen))\npkt.TransportHeader = buffer.View(tcp)\ntcp.Encode(&header.TCPFields{\n- SrcPort: id.LocalPort,\n- DstPort: id.RemotePort,\n- SeqNum: uint32(seq),\n- AckNum: uint32(ack),\n+ SrcPort: tf.id.LocalPort,\n+ DstPort: tf.id.RemotePort,\n+ SeqNum: uint32(tf.seq),\n+ AckNum: uint32(tf.ack),\nDataOffset: uint8(header.TCPMinimumSize + optLen),\n- Flags: flags,\n- WindowSize: uint16(rcvWnd),\n+ Flags: tf.flags,\n+ WindowSize: uint16(tf.rcvWnd),\n})\n- copy(tcp[header.TCPMinimumSize:], opts)\n+ copy(tcp[header.TCPMinimumSize:], tf.opts)\nlength := uint16(hdr.UsedLength() + packetSize)\nxsum := r.PseudoHeaderChecksum(ProtocolNumber, length)\n@@ -737,13 +785,12 @@ func buildTCPHdr(r *stack.Route, id stack.TransportEndpointID, pkt *stack.Packet\nxsum = header.ChecksumVVWithOffset(pkt.Data, xsum, off, packetSize)\ntcp.SetChecksum(^tcp.CalculateChecksum(xsum))\n}\n-\n}\n-func sendTCPBatch(r *stack.Route, id stack.TransportEndpointID, data buffer.VectorisedView, ttl, tos uint8, flags byte, seq, ack seqnum.Value, rcvWnd seqnum.Size, opts []byte, gso *stack.GSO) *tcpip.Error {\n- optLen := len(opts)\n- if rcvWnd > 0xffff {\n- rcvWnd = 0xffff\n+func sendTCPBatch(r *stack.Route, tf tcpFields, data buffer.VectorisedView, gso *stack.GSO) *tcpip.Error {\n+ optLen := len(tf.opts)\n+ if tf.rcvWnd > 0xffff {\n+ tf.rcvWnd = 0xffff\n}\nmss := int(gso.MSS)\n@@ -768,14 +815,15 @@ func sendTCPBatch(r *stack.Route, id stack.TransportEndpointID, data buffer.Vect\npkts[i].DataOffset = off\npkts[i].DataSize = packetSize\npkts[i].Data = data\n- buildTCPHdr(r, id, &pkts[i], flags, seq, ack, rcvWnd, opts, gso)\n+ pkts[i].Hash = tf.txHash\n+ buildTCPHdr(r, tf, &pkts[i], gso)\noff += packetSize\n- seq = seq.Add(seqnum.Size(packetSize))\n+ tf.seq = tf.seq.Add(seqnum.Size(packetSize))\n}\n- if ttl == 0 {\n- ttl = r.DefaultTTL()\n+ if tf.ttl == 0 {\n+ tf.ttl = r.DefaultTTL()\n}\n- sent, err := r.WritePackets(gso, pkts, stack.NetworkHeaderParams{Protocol: ProtocolNumber, TTL: ttl, TOS: tos})\n+ sent, err := r.WritePackets(gso, pkts, stack.NetworkHeaderParams{Protocol: ProtocolNumber, TTL: tf.ttl, TOS: tf.tos})\nif err != nil {\nr.Stats().TCP.SegmentSendErrors.IncrementBy(uint64(n - sent))\n}\n@@ -785,14 +833,14 @@ func sendTCPBatch(r *stack.Route, id stack.TransportEndpointID, data buffer.Vect\n// sendTCP sends a TCP segment with the provided options via the provided\n// network endpoint and under the provided identity.\n-func sendTCP(r *stack.Route, id stack.TransportEndpointID, data buffer.VectorisedView, ttl, tos uint8, flags byte, seq, ack seqnum.Value, rcvWnd seqnum.Size, opts []byte, gso *stack.GSO) *tcpip.Error {\n- optLen := len(opts)\n- if rcvWnd > 0xffff {\n- rcvWnd = 0xffff\n+func sendTCP(r *stack.Route, tf tcpFields, data buffer.VectorisedView, gso *stack.GSO) *tcpip.Error {\n+ optLen := len(tf.opts)\n+ if tf.rcvWnd > 0xffff {\n+ tf.rcvWnd = 0xffff\n}\nif r.Loop&stack.PacketLoop == 0 && gso != nil && gso.Type == stack.GSOSW && int(gso.MSS) < data.Size() {\n- return sendTCPBatch(r, id, data, ttl, tos, flags, seq, ack, rcvWnd, opts, gso)\n+ return sendTCPBatch(r, tf, data, gso)\n}\npkt := stack.PacketBuffer{\n@@ -800,18 +848,19 @@ func sendTCP(r *stack.Route, id stack.TransportEndpointID, data buffer.Vectorise\nDataOffset: 0,\nDataSize: data.Size(),\nData: data,\n+ Hash: tf.txHash,\n}\n- buildTCPHdr(r, id, &pkt, flags, seq, ack, rcvWnd, opts, gso)\n+ buildTCPHdr(r, tf, &pkt, gso)\n- if ttl == 0 {\n- ttl = r.DefaultTTL()\n+ if tf.ttl == 0 {\n+ tf.ttl = r.DefaultTTL()\n}\n- if err := r.WritePacket(gso, stack.NetworkHeaderParams{Protocol: ProtocolNumber, TTL: ttl, TOS: tos}, pkt); err != nil {\n+ if err := r.WritePacket(gso, stack.NetworkHeaderParams{Protocol: ProtocolNumber, TTL: tf.ttl, TOS: tf.tos}, pkt); err != nil {\nr.Stats().TCP.SegmentSendErrors.Increment()\nreturn err\n}\nr.Stats().TCP.SegmentsSent.Increment()\n- if (flags & header.TCPFlagRst) != 0 {\n+ if (tf.flags & header.TCPFlagRst) != 0 {\nr.Stats().TCP.ResetsSent.Increment()\n}\nreturn nil\n@@ -863,7 +912,16 @@ func (e *endpoint) sendRaw(data buffer.VectorisedView, flags byte, seq, ack seqn\nsackBlocks = e.sack.Blocks[:e.sack.NumBlocks]\n}\noptions := e.makeOptions(sackBlocks)\n- err := e.sendTCP(&e.route, e.ID, data, e.ttl, e.sendTOS, flags, seq, ack, rcvWnd, options, e.gso)\n+ err := e.sendTCP(&e.route, tcpFields{\n+ id: e.ID,\n+ ttl: e.ttl,\n+ tos: e.sendTOS,\n+ flags: flags,\n+ seq: seq,\n+ ack: ack,\n+ rcvWnd: rcvWnd,\n+ opts: options,\n+ }, data, e.gso)\nputOptions(options)\nreturn err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -581,6 +581,10 @@ type endpoint struct {\n// endpoint and at this point the endpoint is only around\n// to complete the TCP shutdown.\nclosed bool\n+\n+ // txHash is the transport layer hash to be set on outbound packets\n+ // emitted by this endpoint.\n+ txHash uint32\n}\n// UniqueID implements stack.TransportEndpoint.UniqueID.\n@@ -771,6 +775,7 @@ func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, waiterQue\ncount: 9,\n},\nuniqueID: s.UniqueID(),\n+ txHash: s.Rand().Uint32(),\n}\nvar ss SendBufferSizeOption\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/protocol.go",
"new_path": "pkg/tcpip/transport/tcp/protocol.go",
"diff": "@@ -191,7 +191,15 @@ func replyWithReset(s *segment) {\nflags |= header.TCPFlagAck\nack = s.sequenceNumber.Add(s.logicalLen())\n}\n- sendTCP(&s.route, s.id, buffer.VectorisedView{}, s.route.DefaultTTL(), stack.DefaultTOS, flags, seq, ack, 0 /* rcvWnd */, nil /* options */, nil /* gso */)\n+ sendTCP(&s.route, tcpFields{\n+ id: s.id,\n+ ttl: s.route.DefaultTTL(),\n+ tos: stack.DefaultTOS,\n+ flags: flags,\n+ seq: seq,\n+ ack: ack,\n+ rcvWnd: 0,\n+ }, buffer.VectorisedView{}, nil /* gso */)\n}\n// SetOption implements stack.TransportProtocol.SetOption.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add support for setting TCP segment hash.
This allows the link layer endpoints to consistenly hash a TCP
segment to a single underlying queue in case a link layer endpoint
does support multiple underlying queues.
Updates #231
PiperOrigin-RevId: 302760664 |
259,884 | 25.03.2020 08:28:24 | -32,400 | 8fbf811f79d611dd55355734736265dfec20b73f | Updated e2e tests on travis
* Updated e2e tests on travis
Updated tests to run using Go 1.14
Added test for containerd 1.3
Updated release of runsc to test
* Fix release downloading in e2e tests
* Fix test targets
* Update to using Ubuntu bionic in travis tests | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "-dist: trusty\n+dist: bionic\nsudo: required\nlanguage: go\n-go: \"1.12.x\"\n+go: \"1.14.x\"\nenv:\n- - GO111MODULE=on CONTAINERD_VERSION=1.1.5 RUNSC_VERSION=2019-08-06 TEST=untrusted-workload\n- - GO111MODULE=on CONTAINERD_VERSION=1.2.1 RUNSC_VERSION=2019-08-06 TEST=untrusted-workload\n- - GO111MODULE=on CONTAINERD_VERSION=1.2.1 RUNSC_VERSION=2019-08-06 TEST=runtime-handler\n- - GO111MODULE=on CONTAINERD_VERSION=1.2.1 RUNSC_VERSION=2019-08-06 TEST=runtime-handler-shim-v2\n-\n+ - CONTAINERD_VERSION=1.1.8 RUNSC_VERSION=release/20200219.0 TEST=untrusted-workload\n+ - CONTAINERD_VERSION=1.2.13 RUNSC_VERSION=release/20200219.0 TEST=untrusted-workload\n+ - CONTAINERD_VERSION=1.2.13 RUNSC_VERSION=release/20200219.0 TEST=runtime-handler\n+ - CONTAINERD_VERSION=1.2.13 RUNSC_VERSION=release/20200219.0 TEST=runtime-handler-shim-v2\n+ - CONTAINERD_VERSION=1.3.3 RUNSC_VERSION=release/20200219.0 TEST=runtime-handler\n+ - CONTAINERD_VERSION=1.3.3 RUNSC_VERSION=release/20200219.0 TEST=runtime-handler-shim-v2\ngo_import_path: github.com/google/gvisor-containerd-shim\n@@ -18,11 +19,10 @@ addons:\n- socat\n- conntrack\n- ipset\n+ - libseccomp-dev\nbefore_install:\n- uname -r\n- - sudo apt-get -q update\n- - sudo apt-get install -y libseccomp-dev/trusty-backports\nscript:\n- make test\n"
},
{
"change_type": "MODIFY",
"old_path": "test/e2e/containerd-install.sh",
"new_path": "test/e2e/containerd-install.sh",
"diff": "@@ -10,6 +10,13 @@ sudo mkdir -p /etc/containerd /etc/cni/net.d /opt/cni/bin\nsudo tar -xvf cni-plugins-amd64-v0.7.0.tgz -C /opt/cni/bin/\nsudo tar -xvf containerd-${CONTAINERD_VERSION}.linux-amd64.tar.gz -C /\n+cat <<EOF | sudo tee /etc/containerd/config.toml\n+disabled_plugins = [\"restart\"]\n+# Set to avoid port overlap on older versions of containerd where default is 10010.\n+[plugins.cri]\n+ stream_server_port = \"10011\"\n+EOF\n+\ncat <<EOF | sudo tee /etc/cni/net.d/10-bridge.conf\n{\n\"cniVersion\": \"0.3.1\",\n@@ -35,4 +42,3 @@ cat <<EOF | sudo tee /etc/cni/net.d/99-loopback.conf\nEOF\nsudo PATH=$PATH containerd -log-level debug &>/tmp/containerd-cri.log &\n-\n"
},
{
"change_type": "MODIFY",
"old_path": "test/e2e/runsc-install.sh",
"new_path": "test/e2e/runsc-install.sh",
"diff": "# Sample script to install runsc\nwget -q --https-only \\\n- https://storage.googleapis.com/gvisor/releases/nightly/${RUNSC_VERSION}/runsc\n+ https://storage.googleapis.com/gvisor/releases/${RUNSC_VERSION}/runsc\nchmod +x runsc\nsudo mv runsc /usr/local/bin/\n"
},
{
"change_type": "MODIFY",
"old_path": "test/e2e/untrusted-workload/install.sh",
"new_path": "test/e2e/untrusted-workload/install.sh",
"diff": "@@ -11,6 +11,9 @@ disabled_plugins = [\"restart\"]\n[plugins.linux]\nshim = \"/usr/local/bin/gvisor-containerd-shim\"\nshim_debug = true\n+# Set to avoid port overlap on older versions of containerd where default is 10010.\n+[plugins.cri]\n+ stream_server_port = \"10011\"\n[plugins.cri.containerd.untrusted_workload_runtime]\nruntime_type = \"io.containerd.runtime.v1.linux\"\nruntime_engine = \"/usr/local/bin/runsc\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | Updated e2e tests on travis (#53)
* Updated e2e tests on travis
- Updated tests to run using Go 1.14
- Added test for containerd 1.3
- Updated release of runsc to test
* Fix release downloading in e2e tests
* Fix test targets
* Update to using Ubuntu bionic in travis tests |
259,962 | 25.03.2020 10:54:19 | 25,200 | d04adebaab86ac30aca463b06528fc22430598ac | Fix data-race in endpoint.Readiness | [
{
"change_type": "MODIFY",
"old_path": "pkg/sync/aliases.go",
"new_path": "pkg/sync/aliases.go",
"diff": "@@ -29,3 +29,8 @@ type (\n// Map is an alias of sync.Map.\nMap = sync.Map\n)\n+\n+// NewCond is a wrapper around sync.NewCond.\n+func NewCond(l Locker) *Cond {\n+ return sync.NewCond(l)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/accept.go",
"new_path": "pkg/tcpip/transport/tcp/accept.go",
"diff": "@@ -365,21 +365,29 @@ func (l *listenContext) closeAllPendingEndpoints() {\n}\n// deliverAccepted delivers the newly-accepted endpoint to the listener. If the\n-// endpoint has transitioned out of the listen state, the new endpoint is closed\n-// instead.\n+// endpoint has transitioned out of the listen state (acceptedChan is nil),\n+// the new endpoint is closed instead.\nfunc (e *endpoint) deliverAccepted(n *endpoint) {\ne.mu.Lock()\n- state := e.EndpointState()\ne.pendingAccepted.Add(1)\n- defer e.pendingAccepted.Done()\n- acceptedChan := e.acceptedChan\ne.mu.Unlock()\n+ defer e.pendingAccepted.Done()\n- if state == StateListen {\n- acceptedChan <- n\n- e.waiterQueue.Notify(waiter.EventIn)\n- } else {\n+ e.acceptMu.Lock()\n+ for {\n+ if e.acceptedChan == nil {\n+ e.acceptMu.Unlock()\nn.Close()\n+ return\n+ }\n+ select {\n+ case e.acceptedChan <- n:\n+ e.acceptMu.Unlock()\n+ e.waiterQueue.Notify(waiter.EventIn)\n+ return\n+ default:\n+ e.acceptCond.Wait()\n+ }\n}\n}\n@@ -420,11 +428,13 @@ func (e *endpoint) handleSynSegment(ctx *listenContext, s *segment, opts *header\n}\nfunc (e *endpoint) incSynRcvdCount() bool {\n- if e.synRcvdCount >= cap(e.acceptedChan) {\n- return false\n- }\n+ e.acceptMu.Lock()\n+ canInc := e.synRcvdCount < cap(e.acceptedChan)\n+ e.acceptMu.Unlock()\n+ if canInc {\ne.synRcvdCount++\n- return true\n+ }\n+ return canInc\n}\nfunc (e *endpoint) decSynRcvdCount() {\n@@ -432,10 +442,10 @@ func (e *endpoint) decSynRcvdCount() {\n}\nfunc (e *endpoint) acceptQueueIsFull() bool {\n- if l, c := len(e.acceptedChan)+e.synRcvdCount, cap(e.acceptedChan); l >= c {\n- return true\n- }\n- return false\n+ e.acceptMu.Lock()\n+ full := len(e.acceptedChan)+e.synRcvdCount >= cap(e.acceptedChan)\n+ e.acceptMu.Unlock()\n+ return full\n}\n// handleListenSegment is called when a listening endpoint receives a segment\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -291,6 +291,7 @@ func (*EndpointInfo) IsEndpointInfo() {}\n// The following three mutexes can be acquired independent of e.mu but if\n// acquired with e.mu then e.mu must be acquired first.\n//\n+// e.acceptMu -> protects acceptedChan.\n// e.rcvListMu -> Protects the rcvList and associated fields.\n// e.sndBufMu -> Protects the sndQueue and associated fields.\n// e.lastErrorMu -> Protects the lastError field.\n@@ -533,6 +534,23 @@ type endpoint struct {\n// to the acceptedChan below terminate before we close acceptedChan.\npendingAccepted sync.WaitGroup `state:\"nosave\"`\n+ // acceptMu protects acceptedChan.\n+ acceptMu sync.Mutex `state:\"nosave\"`\n+\n+ // acceptCond is a condition variable that can be used to block on when\n+ // acceptedChan is full and an endpoint is ready to be delivered.\n+ //\n+ // This condition variable is required because just blocking on sending\n+ // to acceptedChan does not work in cases where endpoint.Listen is\n+ // called twice with different backlog values. In such cases the channel\n+ // is closed and a new one created. Any pending goroutines blocking on\n+ // the write to the channel will panic.\n+ //\n+ // We use this condition variable to block/unblock goroutines which\n+ // tried to deliver an endpoint but couldn't because accept backlog was\n+ // full ( See: endpoint.deliverAccepted ).\n+ acceptCond *sync.Cond `state:\"nosave\"`\n+\n// acceptedChan is used by a listening endpoint protocol goroutine to\n// send newly accepted connections to the endpoint so that they can be\n// read by Accept() calls.\n@@ -814,6 +832,7 @@ func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, waiterQue\ne.segmentQueue.setLimit(MaxUnprocessedSegments)\ne.tsOffset = timeStampOffset()\n+ e.acceptCond = sync.NewCond(&e.acceptMu)\nreturn e\n}\n@@ -834,9 +853,11 @@ func (e *endpoint) Readiness(mask waiter.EventMask) waiter.EventMask {\ncase StateListen:\n// Check if there's anything in the accepted channel.\nif (mask & waiter.EventIn) != 0 {\n+ e.acceptMu.Lock()\nif len(e.acceptedChan) > 0 {\nresult |= waiter.EventIn\n}\n+ e.acceptMu.Unlock()\n}\n}\nif e.EndpointState().connected() {\n@@ -981,29 +1002,19 @@ func (e *endpoint) closeNoShutdownLocked() {\n// closePendingAcceptableConnections closes all connections that have completed\n// handshake but not yet been delivered to the application.\nfunc (e *endpoint) closePendingAcceptableConnectionsLocked() {\n- done := make(chan struct{})\n- // Spin a goroutine up as ranging on e.acceptedChan will just block when\n- // there are no more connections in the channel. Using a non-blocking\n- // select does not work as it can potentially select the default case\n- // even when there are pending writes but that are not yet written to\n- // the channel.\n- go func() {\n- defer close(done)\n- for n := range e.acceptedChan {\n- n.notifyProtocolGoroutine(notifyReset)\n- // close all connections that have completed but\n- // not accepted by the application.\n- n.Close()\n- }\n- }()\n- // pendingAccepted(see endpoint.deliverAccepted) tracks the number of\n- // endpoints which have completed handshake but are not yet written to\n- // the e.acceptedChan. We wait here till the goroutine above can drain\n- // all such connections from e.acceptedChan.\n- e.pendingAccepted.Wait()\n+ e.acceptMu.Lock()\n+ if e.acceptedChan == nil {\n+ e.acceptMu.Unlock()\n+ return\n+ }\n+\nclose(e.acceptedChan)\n- <-done\ne.acceptedChan = nil\n+ e.acceptCond.Broadcast()\n+ e.acceptMu.Unlock()\n+\n+ // Wait for all pending endpoints to close.\n+ e.pendingAccepted.Wait()\n}\n// cleanupLocked frees all resources associated with the endpoint. It is called\n@@ -1012,9 +1023,7 @@ func (e *endpoint) closePendingAcceptableConnectionsLocked() {\nfunc (e *endpoint) cleanupLocked() {\n// Close all endpoints that might have been accepted by TCP but not by\n// the client.\n- if e.acceptedChan != nil {\ne.closePendingAcceptableConnectionsLocked()\n- }\ne.workerCleanup = false\n@@ -2204,6 +2213,8 @@ func (e *endpoint) listen(backlog int) *tcpip.Error {\nif e.EndpointState() == StateListen && !e.workerCleanup {\n// Adjust the size of the channel iff we can fix existing\n// pending connections into the new one.\n+ e.acceptMu.Lock()\n+ defer e.acceptMu.Unlock()\nif len(e.acceptedChan) > backlog {\nreturn tcpip.ErrInvalidEndpointState\n}\n@@ -2216,6 +2227,11 @@ func (e *endpoint) listen(backlog int) *tcpip.Error {\nfor ep := range origChan {\ne.acceptedChan <- ep\n}\n+\n+ // Notify any blocked goroutines that they can attempt to\n+ // deliver endpoints again.\n+ e.acceptCond.Broadcast()\n+\nreturn nil\n}\n@@ -2245,9 +2261,12 @@ func (e *endpoint) listen(backlog int) *tcpip.Error {\n// The channel may be non-nil when we're restoring the endpoint, and it\n// may be pre-populated with some previously accepted (but not Accepted)\n// endpoints.\n+ e.acceptMu.Lock()\nif e.acceptedChan == nil {\ne.acceptedChan = make(chan *endpoint, backlog)\n}\n+ e.acceptMu.Unlock()\n+\ne.workerRunning = true\ngo e.protocolListenLoop( // S/R-SAFE: drained on save.\nseqnum.Size(e.receiveBufferAvailable()))\n@@ -2276,9 +2295,12 @@ func (e *endpoint) Accept() (tcpip.Endpoint, *waiter.Queue, *tcpip.Error) {\n}\n// Get the new accepted endpoint.\n+ e.acceptMu.Lock()\n+ defer e.acceptMu.Unlock()\nvar n *endpoint\nselect {\ncase n = <-e.acceptedChan:\n+ e.acceptCond.Signal()\ndefault:\nreturn nil, nil, tcpip.ErrWouldBlock\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint_state.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint_state.go",
"diff": "@@ -173,6 +173,9 @@ func (e *endpoint) afterLoad() {\n// Restore the endpoint to InitialState as it will be moved to\n// its origEndpointState during Resume.\ne.state = StateInitial\n+ // Condition variables and mutexs are not S/R'ed so reinitialize\n+ // acceptCond with e.acceptMu.\n+ e.acceptCond = sync.NewCond(&e.acceptMu)\nstack.StackFromEnv.RegisterRestoredEndpoint(e)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix data-race in endpoint.Readiness
PiperOrigin-RevId: 302924789 |
259,853 | 25.03.2020 11:20:24 | 25,200 | 2e09f2bdce11d5f303333c68af4272abb62b7885 | travis: exclude copybara branches
When copybara migrates changes, it creates a new branch and then creates a
pull-requests which is based on this branch. In this case, travis-ci
triggers build twice for the branch and for the pull-request. | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -17,3 +17,7 @@ matrix:\nscript:\n- uname -a\n- make DOCKER_RUN_OPTIONS=\"\" BAZEL_OPTIONS=\"build runsc:runsc\" bazel && $RUNSC_PATH --alsologtostderr --network none --debug --TESTONLY-unsafe-nonroot=true --rootless do ls\n+branches:\n+ except:\n+ # Skip copybara branches.\n+ - /^test\\/cl.*$/\n"
}
] | Go | Apache License 2.0 | google/gvisor | travis: exclude copybara branches
When copybara migrates changes, it creates a new branch and then creates a
pull-requests which is based on this branch. In this case, travis-ci
triggers build twice for the branch and for the pull-request.
PiperOrigin-RevId: 302930634 |
259,992 | 25.03.2020 14:44:18 | 25,200 | c7f5673529af758c9f7c95523535174c7929dab5 | Set file mode and type to attribute
Makes less error prone to find file type.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/device_file.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/device_file.go",
"diff": "package tmpfs\nimport (\n+ \"fmt\"\n+\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n@@ -33,6 +35,14 @@ func (fs *filesystem) newDeviceFile(creds *auth.Credentials, mode linux.FileMode\nmajor: major,\nminor: minor,\n}\n+ switch kind {\n+ case vfs.BlockDevice:\n+ mode |= linux.S_IFBLK\n+ case vfs.CharDevice:\n+ mode |= linux.S_IFCHR\n+ default:\n+ panic(fmt.Sprintf(\"invalid DeviceKind: %v\", kind))\n+ }\nfile.inode.init(file, fs, creds, mode)\nfile.inode.nlink = 1 // from parent directory\nreturn &file.inode\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/directory.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/directory.go",
"diff": "@@ -34,16 +34,11 @@ type directory struct {\nfunc (fs *filesystem) newDirectory(creds *auth.Credentials, mode linux.FileMode) *inode {\ndir := &directory{}\n- dir.inode.init(dir, fs, creds, mode)\n+ dir.inode.init(dir, fs, creds, linux.S_IFDIR|mode)\ndir.inode.nlink = 2 // from \".\" and parent directory or \"..\" for root\nreturn &dir.inode\n}\n-func (i *inode) isDir() bool {\n- _, ok := i.impl.(*directory)\n- return ok\n-}\n-\ntype directoryFD struct {\nfileDescription\nvfs.DirectoryFileDescriptionDefaultImpl\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/named_pipe.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/named_pipe.go",
"diff": "@@ -34,7 +34,7 @@ type namedPipe struct {\n// * rp.Mount().CheckBeginWrite() has been called successfully.\nfunc (fs *filesystem) newNamedPipe(creds *auth.Credentials, mode linux.FileMode) *inode {\nfile := &namedPipe{pipe: pipe.NewVFSPipe(pipe.DefaultPipeSize, usermem.PageSize)}\n- file.inode.init(file, fs, creds, mode)\n+ file.inode.init(file, fs, creds, linux.S_IFIFO|mode)\nfile.inode.nlink = 1 // Only the parent has a link.\nreturn &file.inode\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go",
"diff": "@@ -89,7 +89,7 @@ func (fs *filesystem) newRegularFile(creds *auth.Credentials, mode linux.FileMod\nfile := ®ularFile{\nmemFile: fs.memFile,\n}\n- file.inode.init(file, fs, creds, mode)\n+ file.inode.init(file, fs, creds, linux.S_IFREG|mode)\nfile.inode.nlink = 1 // from parent directory\nreturn &file.inode\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/symlink.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/symlink.go",
"diff": "package tmpfs\nimport (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n)\n@@ -27,7 +28,7 @@ func (fs *filesystem) newSymlink(creds *auth.Credentials, target string) *inode\nlink := &symlink{\ntarget: target,\n}\n- link.inode.init(link, fs, creds, 0777)\n+ link.inode.init(link, fs, creds, linux.S_IFLNK|0777)\nlink.inode.nlink = 1 // from parent directory\nreturn &link.inode\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"diff": "@@ -144,7 +144,7 @@ type inode struct {\n// Inode metadata. Writing multiple fields atomically requires holding\n// mu, othewise atomic operations can be used.\nmu sync.Mutex\n- mode uint32 // excluding file type bits, which are based on impl\n+ mode uint32 // file type and mode\nnlink uint32 // protected by filesystem.mu instead of inode.mu\nuid uint32 // auth.KUID, but stored as raw uint32 for sync/atomic\ngid uint32 // auth.KGID, but ...\n@@ -168,6 +168,9 @@ type inode struct {\nconst maxLinks = math.MaxUint32\nfunc (i *inode) init(impl interface{}, fs *filesystem, creds *auth.Credentials, mode linux.FileMode) {\n+ if mode.FileType() == 0 {\n+ panic(\"file type is required in FileMode\")\n+ }\ni.clock = fs.clock\ni.refs = 1\ni.mode = uint32(mode)\n@@ -269,31 +272,21 @@ func (i *inode) statTo(stat *linux.Statx) {\n// TODO(gvisor.dev/issues/1197): Device number.\nswitch impl := i.impl.(type) {\ncase *regularFile:\n- stat.Mode |= linux.S_IFREG\nstat.Mask |= linux.STATX_SIZE | linux.STATX_BLOCKS\nstat.Size = uint64(atomic.LoadUint64(&impl.size))\n// In tmpfs, this will be FileRangeSet.Span() / 512 (but also cached in\n// a uint64 accessed using atomic memory operations to avoid taking\n// locks).\nstat.Blocks = allocatedBlocksForSize(stat.Size)\n- case *directory:\n- stat.Mode |= linux.S_IFDIR\ncase *symlink:\n- stat.Mode |= linux.S_IFLNK\nstat.Mask |= linux.STATX_SIZE | linux.STATX_BLOCKS\nstat.Size = uint64(len(impl.target))\nstat.Blocks = allocatedBlocksForSize(stat.Size)\n- case *namedPipe:\n- stat.Mode |= linux.S_IFIFO\ncase *deviceFile:\n- switch impl.kind {\n- case vfs.BlockDevice:\n- stat.Mode |= linux.S_IFBLK\n- case vfs.CharDevice:\n- stat.Mode |= linux.S_IFCHR\n- }\nstat.RdevMajor = impl.major\nstat.RdevMinor = impl.minor\n+ case *directory, *namedPipe:\n+ // Nothing to do.\ndefault:\npanic(fmt.Sprintf(\"unknown inode type: %T\", i.impl))\n}\n@@ -316,7 +309,8 @@ func (i *inode) setStat(ctx context.Context, creds *auth.Credentials, stat *linu\n)\nmask := stat.Mask\nif mask&linux.STATX_MODE != 0 {\n- atomic.StoreUint32(&i.mode, uint32(stat.Mode))\n+ ft := atomic.LoadUint32(&i.mode) & linux.S_IFMT\n+ atomic.StoreUint32(&i.mode, ft|uint32(stat.Mode&^linux.S_IFMT))\nneedsCtimeBump = true\n}\nif mask&linux.STATX_UID != 0 {\n@@ -439,6 +433,10 @@ func (i *inode) direntType() uint8 {\n}\n}\n+func (i *inode) isDir() bool {\n+ return linux.FileMode(i.mode).FileType() == linux.S_IFDIR\n+}\n+\n// fileDescription is embedded by tmpfs implementations of\n// vfs.FileDescriptionImpl.\ntype fileDescription struct {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Set file mode and type to attribute
Makes less error prone to find file type.
Updates #1197
PiperOrigin-RevId: 302974244 |
259,992 | 25.03.2020 14:54:10 | 25,200 | e541ebec2fdb5b29209cb3fc8235b77edcaebb6a | Misc fixes to make stat_test pass (almost)
The only test failing now requires socket which is not
available in VFS2 yet.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/bits/bits_template.go",
"new_path": "pkg/bits/bits_template.go",
"diff": "@@ -42,3 +42,11 @@ func Mask(is ...int) T {\nfunc MaskOf(i int) T {\nreturn T(1) << T(i)\n}\n+\n+// IsPowerOfTwo returns true if v is power of 2.\n+func IsPowerOfTwo(v T) bool {\n+ if v == 0 {\n+ return false\n+ }\n+ return v&(v-1) == 0\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/bits/uint64_test.go",
"new_path": "pkg/bits/uint64_test.go",
"diff": "@@ -114,3 +114,21 @@ func TestIsOn(t *testing.T) {\n}\n}\n}\n+\n+func TestIsPowerOfTwo(t *testing.T) {\n+ for _, tc := range []struct {\n+ v uint64\n+ want bool\n+ }{\n+ {v: 0, want: false},\n+ {v: 1, want: true},\n+ {v: 2, want: true},\n+ {v: 3, want: false},\n+ {v: 4, want: true},\n+ {v: 5, want: false},\n+ } {\n+ if got := IsPowerOfTwo64(tc.v); got != tc.want {\n+ t.Errorf(\"IsPowerOfTwo(%d) = %t, want: %t\", tc.v, got, tc.want)\n+ }\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"new_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"diff": "@@ -454,6 +454,9 @@ func (fs *filesystem) unlinkAt(ctx context.Context, rp *vfs.ResolvingPath, dir b\n}\nif fs.opts.interop != InteropModeShared {\nparent.touchCMtime(ctx)\n+ if dir {\n+ parent.decLinks()\n+ }\nparent.cacheNegativeChildLocked(name)\nparent.dirents = nil\n}\n@@ -569,8 +572,13 @@ func (fs *filesystem) LinkAt(ctx context.Context, rp *vfs.ResolvingPath, vd vfs.\nfunc (fs *filesystem) MkdirAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.MkdirOptions) error {\nreturn fs.doCreateAt(ctx, rp, true /* dir */, func(parent *dentry, name string) error {\ncreds := rp.Credentials()\n- _, err := parent.file.mkdir(ctx, name, (p9.FileMode)(opts.Mode), (p9.UID)(creds.EffectiveKUID), (p9.GID)(creds.EffectiveKGID))\n+ if _, err := parent.file.mkdir(ctx, name, (p9.FileMode)(opts.Mode), (p9.UID)(creds.EffectiveKUID), (p9.GID)(creds.EffectiveKGID)); err != nil {\nreturn err\n+ }\n+ if fs.opts.interop != InteropModeShared {\n+ parent.incLinks()\n+ }\n+ return nil\n})\n}\n@@ -962,6 +970,10 @@ func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\noldParent.dirents = nil\ndelete(newParent.negativeChildren, newName)\nnewParent.dirents = nil\n+ if renamed.isDir() {\n+ oldParent.decLinks()\n+ newParent.incLinks()\n+ }\n}\nvfsObj.CommitRenameReplaceDentry(&renamed.vfsd, &newParent.vfsd, newName, replacedVFSD)\nreturn nil\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"diff": "@@ -485,6 +485,11 @@ type dentry struct {\n// locked to mutate it).\nsize uint64\n+ // nlink counts the number of hard links to this dentry. It's updated and\n+ // accessed using atomic operations. It's not protected by metadataMu like the\n+ // other metadata fields.\n+ nlink uint32\n+\nmapsMu sync.Mutex\n// If this dentry represents a regular file, mappings tracks mappings of\n@@ -604,6 +609,9 @@ func (fs *filesystem) newDentry(ctx context.Context, file p9file, qid p9.QID, ma\nif mask.BTime {\nd.btime = dentryTimestampFromP9(attr.BTimeSeconds, attr.BTimeNanoSeconds)\n}\n+ if mask.NLink {\n+ d.nlink = uint32(attr.NLink)\n+ }\nd.vfsd.Init(d)\nfs.syncMu.Lock()\n@@ -645,6 +653,9 @@ func (d *dentry) updateFromP9Attrs(mask p9.AttrMask, attr *p9.Attr) {\nif mask.BTime {\natomic.StoreInt64(&d.btime, dentryTimestampFromP9(attr.BTimeSeconds, attr.BTimeNanoSeconds))\n}\n+ if mask.NLink {\n+ atomic.StoreUint32(&d.nlink, uint32(attr.NLink))\n+ }\nif mask.Size {\nd.dataMu.Lock()\natomic.StoreUint64(&d.size, attr.Size)\n@@ -687,10 +698,7 @@ func (d *dentry) fileType() uint32 {\nfunc (d *dentry) statTo(stat *linux.Statx) {\nstat.Mask = linux.STATX_TYPE | linux.STATX_MODE | linux.STATX_NLINK | linux.STATX_UID | linux.STATX_GID | linux.STATX_ATIME | linux.STATX_MTIME | linux.STATX_CTIME | linux.STATX_INO | linux.STATX_SIZE | linux.STATX_BLOCKS | linux.STATX_BTIME\nstat.Blksize = atomic.LoadUint32(&d.blockSize)\n- stat.Nlink = 1\n- if d.isDir() {\n- stat.Nlink = 2\n- }\n+ stat.Nlink = atomic.LoadUint32(&d.nlink)\nstat.UID = atomic.LoadUint32(&d.uid)\nstat.GID = atomic.LoadUint32(&d.gid)\nstat.Mode = uint16(atomic.LoadUint32(&d.mode))\n@@ -703,7 +711,7 @@ func (d *dentry) statTo(stat *linux.Statx) {\nstat.Btime = statxTimestampFromDentry(atomic.LoadInt64(&d.btime))\nstat.Ctime = statxTimestampFromDentry(atomic.LoadInt64(&d.ctime))\nstat.Mtime = statxTimestampFromDentry(atomic.LoadInt64(&d.mtime))\n- // TODO(jamieliu): device number\n+ // TODO(gvisor.dev/issue/1198): device number\n}\nfunc (d *dentry) setStat(ctx context.Context, creds *auth.Credentials, stat *linux.Statx, mnt *vfs.Mount) error {\n@@ -1094,6 +1102,26 @@ func (d *dentry) ensureSharedHandle(ctx context.Context, read, write, trunc bool\nreturn nil\n}\n+// incLinks increments link count.\n+//\n+// Preconditions: d.nlink != 0 && d.nlink < math.MaxUint32.\n+func (d *dentry) incLinks() {\n+ v := atomic.AddUint32(&d.nlink, 1)\n+ if v < 2 {\n+ panic(fmt.Sprintf(\"dentry.nlink is invalid (was 0 or overflowed): %d\", v))\n+ }\n+}\n+\n+// decLinks decrements link count.\n+//\n+// Preconditions: d.nlink > 1.\n+func (d *dentry) decLinks() {\n+ v := atomic.AddUint32(&d.nlink, ^uint32(0))\n+ if v == 0 {\n+ panic(fmt.Sprintf(\"dentry.nlink must be greater than 0: %d\", v))\n+ }\n+}\n+\n// fileDescription is embedded by gofer implementations of\n// vfs.FileDescriptionImpl.\ntype fileDescription struct {\n@@ -1112,7 +1140,8 @@ func (fd *fileDescription) dentry() *dentry {\n// Stat implements vfs.FileDescriptionImpl.Stat.\nfunc (fd *fileDescription) Stat(ctx context.Context, opts vfs.StatOptions) (linux.Statx, error) {\nd := fd.dentry()\n- if d.fs.opts.interop == InteropModeShared && opts.Mask&(linux.STATX_MODE|linux.STATX_UID|linux.STATX_GID|linux.STATX_ATIME|linux.STATX_MTIME|linux.STATX_CTIME|linux.STATX_SIZE|linux.STATX_BLOCKS|linux.STATX_BTIME) != 0 && opts.Sync != linux.AT_STATX_DONT_SYNC {\n+ const validMask = uint32(linux.STATX_MODE | linux.STATX_UID | linux.STATX_GID | linux.STATX_ATIME | linux.STATX_MTIME | linux.STATX_CTIME | linux.STATX_SIZE | linux.STATX_BLOCKS | linux.STATX_BTIME)\n+ if d.fs.opts.interop == InteropModeShared && opts.Mask&(validMask) != 0 && opts.Sync != linux.AT_STATX_DONT_SYNC {\n// TODO(jamieliu): Use specialFileFD.handle.file for the getattr if\n// available?\nif err := d.updateFromGetattr(ctx); err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/BUILD",
"new_path": "pkg/sentry/syscalls/linux/vfs2/BUILD",
"diff": "@@ -31,6 +31,7 @@ go_library(\nvisibility = [\"//:sandbox\"],\ndeps = [\n\"//pkg/abi/linux\",\n+ \"//pkg/bits\",\n\"//pkg/fspath\",\n\"//pkg/gohacks\",\n\"//pkg/sentry/arch\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/filesystem.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/filesystem.go",
"diff": "@@ -250,7 +250,7 @@ func rmdirat(t *kernel.Task, dirfd int32, pathAddr usermem.Addr) error {\nif err != nil {\nreturn err\n}\n- tpop, err := getTaskPathOperation(t, dirfd, path, disallowEmptyPath, followFinalSymlink)\n+ tpop, err := getTaskPathOperation(t, dirfd, path, disallowEmptyPath, nofollowFinalSymlink)\nif err != nil {\nreturn err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/getdents.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/getdents.go",
"diff": "@@ -97,7 +97,7 @@ func (cb *getdentsCallback) Handle(dirent vfs.Dirent) error {\n// char d_name[]; /* Filename (null-terminated) */\n// };\nsize := 8 + 8 + 2 + 1 + 1 + len(dirent.Name)\n- if size < cb.remaining {\n+ if size > cb.remaining {\nreturn syserror.EINVAL\n}\nbuf = cb.t.CopyScratchBuffer(size)\n@@ -125,7 +125,7 @@ func (cb *getdentsCallback) Handle(dirent vfs.Dirent) error {\npanic(fmt.Sprintf(\"unsupported sizeof(unsigned long): %d\", cb.t.Arch().Width()))\n}\nsize := 8 + 8 + 2 + 1 + 1 + 1 + len(dirent.Name)\n- if size < cb.remaining {\n+ if size > cb.remaining {\nreturn syserror.EINVAL\n}\nbuf = cb.t.CopyScratchBuffer(size)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/stat.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/stat.go",
"diff": "@@ -16,6 +16,7 @@ package vfs2\nimport (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/bits\"\n\"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/gohacks\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n@@ -153,7 +154,11 @@ func Statx(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\nif flags&^(linux.AT_EMPTY_PATH|linux.AT_SYMLINK_NOFOLLOW|linux.AT_STATX_SYNC_TYPE) != 0 {\nreturn 0, nil, syserror.EINVAL\n}\n-\n+ // Make sure that only one sync type option is set.\n+ syncType := uint32(flags & linux.AT_STATX_SYNC_TYPE)\n+ if syncType != 0 && !bits.IsPowerOfTwo32(syncType) {\n+ return 0, nil, syserror.EINVAL\n+ }\nif mask&linux.STATX__RESERVED != 0 {\nreturn 0, nil, syserror.EINVAL\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/resolving_path.go",
"new_path": "pkg/sentry/vfs/resolving_path.go",
"diff": "@@ -329,10 +329,22 @@ func (rp *ResolvingPath) ResolveComponent(d *Dentry) (*Dentry, error) {\n// component in pcs represents a symbolic link, the symbolic link should be\n// followed.\n//\n+// If path is terminated with '/', the '/' is considered the last element and\n+// any symlink before that is followed:\n+// - For most non-creating walks, the last path component is handled by\n+// fs/namei.c:lookup_last(), which sets LOOKUP_FOLLOW if the first byte\n+// after the path component is non-NULL (which is only possible if it's '/')\n+// and the path component is of type LAST_NORM.\n+//\n+// - For open/openat/openat2 without O_CREAT, the last path component is\n+// handled by fs/namei.c:do_last(), which does the same, though without the\n+// LAST_NORM check.\n+//\n// Preconditions: !rp.Done().\nfunc (rp *ResolvingPath) ShouldFollowSymlink() bool {\n- // Non-final symlinks are always followed.\n- return rp.flags&rpflagsFollowFinalSymlink != 0 || !rp.Final()\n+ // Non-final symlinks are always followed. Paths terminated with '/' are also\n+ // always followed.\n+ return rp.flags&rpflagsFollowFinalSymlink != 0 || !rp.Final() || rp.MustBeDir()\n}\n// HandleSymlink is called when the current path component is a symbolic link\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/stat.cc",
"new_path": "test/syscalls/linux/stat.cc",
"diff": "#include \"test/util/temp_path.h\"\n#include \"test/util/test_util.h\"\n+#ifndef AT_STATX_FORCE_SYNC\n+#define AT_STATX_FORCE_SYNC 0x2000\n+#endif\n+#ifndef AT_STATX_DONT_SYNC\n+#define AT_STATX_DONT_SYNC 0x4000\n+#endif\n+\nnamespace gvisor {\nnamespace testing {\n@@ -700,8 +707,10 @@ TEST_F(StatTest, StatxInvalidFlags) {\nstruct kernel_statx stx;\nEXPECT_THAT(statx(AT_FDCWD, test_file_name_.c_str(), 12345, 0, &stx),\nSyscallFailsWithErrno(EINVAL));\n+\n+ // Sync flags are mutually exclusive.\nEXPECT_THAT(statx(AT_FDCWD, test_file_name_.c_str(),\n- 0x6000 /* AT_STATX_SYNC_TYPE */, 0, &stx),\n+ AT_STATX_FORCE_SYNC | AT_STATX_DONT_SYNC, 0, &stx),\nSyscallFailsWithErrno(EINVAL));\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Misc fixes to make stat_test pass (almost)
The only test failing now requires socket which is not
available in VFS2 yet.
Updates #1198
PiperOrigin-RevId: 302976572 |
259,992 | 25.03.2020 15:23:48 | 25,200 | f2eba940159b4ed55359f99a3422ad899a8647ee | Remove TODO to push down exec permission check
Pushing it down requires all implementation to check for
exec individualy which is not maintanable. Making it part
of GenericCheckPermissions add extra cost to everyone that
calls it. So it's better to keep is in
VirtualFilesystem.OpenAt.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/vfs.go",
"new_path": "pkg/sentry/vfs/vfs.go",
"diff": "@@ -402,8 +402,6 @@ func (vfs *VirtualFilesystem) OpenAt(ctx context.Context, creds *auth.Credential\nif err == nil {\nvfs.putResolvingPath(rp)\n- // TODO(gvisor.dev/issue/1193): Move inside fsimpl to avoid another call\n- // to FileDescription.Stat().\nif opts.FileExec {\nif fd.Mount().flags.NoExec {\nfd.DecRef()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove TODO to push down exec permission check
Pushing it down requires all implementation to check for
exec individualy which is not maintanable. Making it part
of GenericCheckPermissions add extra cost to everyone that
calls it. So it's better to keep is in
VirtualFilesystem.OpenAt.
Updates #1193
PiperOrigin-RevId: 302982993 |
259,992 | 25.03.2020 15:38:38 | 25,200 | 5f03dca5227e4f2e7aa472ad40d421d4623c9f72 | Fix race in TestRunEnvHasHome
It's possible to execute the command that checks user's
$HOME dir before the user is created. Move the code that
creates the user inside exec so it can be serialized. | [
{
"change_type": "MODIFY",
"old_path": "test/e2e/exec_test.go",
"new_path": "test/e2e/exec_test.go",
"diff": "@@ -240,17 +240,7 @@ func TestExecEnvHasHome(t *testing.T) {\n}\nd := dockerutil.MakeDocker(\"exec-env-home-test\")\n- // We will check that HOME is set for root user, and also for a new\n- // non-root user we will create.\n- newUID := 1234\n- newHome := \"/foo/bar\"\n-\n- // Create a new user with a home directory, and then sleep.\n- script := fmt.Sprintf(`\n- mkdir -p -m 777 %s && \\\n- adduser foo -D -u %d -h %s && \\\n- sleep 1000`, newHome, newUID, newHome)\n- if err := d.Run(\"alpine\", \"/bin/sh\", \"-c\", script); err != nil {\n+ if err := d.Run(\"alpine\", \"sleep\", \"1000\"); err != nil {\nt.Fatalf(\"docker run failed: %v\", err)\n}\ndefer d.CleanUp()\n@@ -264,7 +254,15 @@ func TestExecEnvHasHome(t *testing.T) {\nt.Errorf(\"wanted exec output to contain %q, got %q\", want, got)\n}\n- // Execute the same as uid 123 and expect newHome.\n+ // Create a new user with a home directory.\n+ newUID := 1234\n+ newHome := \"/foo/bar\"\n+ cmd := fmt.Sprintf(\"mkdir -p -m 777 %q && adduser foo -D -u %d -h %q\", newHome, newUID, newHome)\n+ if _, err := d.Exec(\"/bin/sh\", \"-c\", cmd); err != nil {\n+ t.Fatalf(\"docker exec failed: %v\", err)\n+ }\n+\n+ // Execute the same as the new user and expect newHome.\ngot, err = d.ExecAsUser(strconv.Itoa(newUID), \"/bin/sh\", \"-c\", \"echo $HOME\")\nif err != nil {\nt.Fatalf(\"docker exec failed: %v\", err)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix race in TestRunEnvHasHome
It's possible to execute the command that checks user's
$HOME dir before the user is created. Move the code that
creates the user inside exec so it can be serialized.
PiperOrigin-RevId: 302986184 |
259,858 | 28.02.2020 18:01:21 | 28,800 | d440fe0613a3b8fec75d33aff36ebada220106b0 | Fix go_marshal Example name.
There is a canonical naming convention for Examples, which are checked
by analyzers. This must be fixed since adding exceptions for generated
code will be more challenging. | [
{
"change_type": "MODIFY",
"old_path": "tools/go_marshal/gomarshal/generator.go",
"new_path": "tools/go_marshal/gomarshal/generator.go",
"diff": "@@ -413,7 +413,7 @@ func (g *Generator) writeTests(ts []*testGenerator) error {\n// empty example instead.\nif len(ts) == 0 {\nb.reset()\n- b.emit(\"func ExampleEmptyTestSuite() {\\n\")\n+ b.emit(\"func Example() {\\n\")\nb.inIndent(func() {\nb.emit(\"// This example is intentionally empty to ensure this file contains at least\\n\")\nb.emit(\"// one testable entity. go-marshal is forced to emit a test file if a package\\n\")\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix go_marshal Example name.
There is a canonical naming convention for Examples, which are checked
by analyzers. This must be fixed since adding exceptions for generated
code will be more challenging. |
259,858 | 04.10.2019 19:03:07 | 25,200 | 882ed330e6e7761f482f9bfa771cc6693e0f8008 | nogo: enable sanitizers.
This enables all relevant santizers (though most analyzers will not find
much, it will prevent instances from creeping in), and codifies existing
exceptions in tools/nogo.js to be fixed. | [
{
"change_type": "MODIFY",
"old_path": "BUILD",
"new_path": "BUILD",
"diff": "@@ -49,10 +49,31 @@ gazelle(name = \"gazelle\")\n# live in the tools subdirectory (unless they are standard).\nnogo(\nname = \"nogo\",\n- config = \"//tools:nogo.js\",\n+ config = \"//tools:nogo.json\",\nvisibility = [\"//visibility:public\"],\ndeps = [\n\"//tools/checkunsafe\",\n+ \"@org_golang_x_tools//go/analysis/passes/asmdecl:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/assign:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/atomic:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/atomicalign:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/bools:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/buildtag:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/cgocall:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/copylock:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/deepequalerrors:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/loopclosure:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/lostcancel:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/nilfunc:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/nilness:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/printf:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/shift:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/stdmethods:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/structtag:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/tests:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/unmarshal:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/unsafeptr:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/unusedresult:go_tool_library\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/BUILD",
"new_path": "tools/BUILD",
"diff": "package(licenses = [\"notice\"])\n-exports_files([\"nogo.js\"])\n+exports_files([\"nogo.json\"])\n"
},
{
"change_type": "DELETE",
"old_path": "tools/nogo.js",
"new_path": null,
"diff": "-{\n- \"checkunsafe\": {\n- \"exclude_files\": {\n- \"/external/\": \"not subject to constraint\"\n- }\n- }\n-}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tools/nogo.json",
"diff": "+{\n+ \"assign\": {\n+ \"exclude_files\": {\n+ \"/external/bazel_gazelle/walk/walk.go\": \"allowed: false positive\"\n+ }\n+ },\n+ \"checkunsafe\": {\n+ \"exclude_files\": {\n+ \"/external/\": \"allowed: not subject to unsafe naming rules\"\n+ }\n+ },\n+ \"copylocks\": {\n+ \"exclude_files\": {\n+ \".*_state_autogen.go\": \"fix: m.Failf copies by value\",\n+ \"/pkg/log/json.go\": \"fix: Emit passes lock by value: gvisor.dev/gvisor/pkg/log.JSONEmitter contains gvisor.dev/gvisor/pkg/log.Writer contains gvisor.dev/gvisor/pkg/sync.Mutex\",\n+ \"/pkg/log/log_test.go\": \"fix: call of fmt.Printf copies lock value: gvisor.dev/gvisor/pkg/log.Writer contains gvisor.dev/gvisor/pkg/sync.Mutex\",\n+ \"/pkg/sentry/fs/host/socket_test.go\": \"fix: call of t.Errorf copies lock value: gvisor.dev/gvisor/pkg/sentry/fs/host.ConnectedEndpoint contains gvisor.dev/gvisor/pkg/refs.AtomicRefCount contains gvisor.dev/gvisor/pkg/sync.Mutex\",\n+ \"/pkg/sentry/fs/proc/sys_net.go\": \"fix: Truncate passes lock by value: gvisor.dev/gvisor/pkg/sentry/fs/proc.tcpMemInode contains gvisor.dev/gvisor/pkg/sentry/fs/fsutil.SimpleFileInode contains gvisor.dev/gvisor/pkg/sentry/fs/fsutil.InodeSimpleAttributes contains gvisor.dev/gvisor/pkg/sync.RWMutex\",\n+ \"/pkg/sentry/fs/proc/sys_net.go\": \"fix: Truncate passes lock by value: gvisor.dev/gvisor/pkg/sentry/fs/proc.tcpSack contains gvisor.dev/gvisor/pkg/sentry/fs/fsutil.SimpleFileInode contains gvisor.dev/gvisor/pkg/sentry/fs/fsutil.InodeSimpleAttributes contains gvisor.dev/gvisor/pkg/sync.RWMutex\",\n+ \"/pkg/sentry/fs/tty/slave.go\": \"fix: Truncate passes lock by value: gvisor.dev/gvisor/pkg/sentry/fs/tty.slaveInodeOperations contains gvisor.dev/gvisor/pkg/sentry/fs/fsutil.SimpleFileInode contains gvisor.dev/gvisor/pkg/sentry/fs/fsutil.InodeSimpleAttributes contains gvisor.dev/gvisor/pkg/sync.RWMutex\",\n+ \"/pkg/sentry/kernel/time/time.go\": \"fix: Readiness passes lock by value: gvisor.dev/gvisor/pkg/sentry/kernel/time.ClockEventsQueue contains gvisor.dev/gvisor/pkg/waiter.Queue contains gvisor.dev/gvisor/pkg/sync.RWMutex\",\n+ \"/pkg/sentry/kernel/syscalls_state.go\": \"fix: assignment copies lock value to *s: gvisor.dev/gvisor/pkg/sentry/kernel.SyscallTable contains gvisor.dev/gvisor/pkg/sentry/kernel.SyscallFlagsTable contains gvisor.dev/gvisor/pkg/sync.Mutex\"\n+ }\n+ },\n+ \"lostcancel\": {\n+ \"exclude_files\": {\n+ \"/pkg/tcpip/network/arp/arp_test.go\": \"fix: the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak\",\n+ \"/pkg/tcpip/stack/ndp_test.go\": \"fix: the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak\",\n+ \"/pkg/tcpip/transport/udp/udp_test.go\": \"fix: the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak\",\n+ \"/pkg/tcpip/transport/tcp/testing/context/context.go\": \"fix: the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak\"\n+ }\n+ },\n+ \"nilness\": {\n+ \"exclude_files\": {\n+ \"/com_github_vishvananda_netlink/route_linux.go\": \"allowed: false positive\",\n+ \"/external/bazel_gazelle/cmd/gazelle/.*\": \"allowed: false positive\",\n+ \"/org_golang_x_tools/go/packages/golist.go\": \"allowed: runtime internals\",\n+ \"/pkg/sentry/platform/kvm/kvm_test.go\": \"allowed: intentional\"\n+ }\n+ },\n+ \"printf\": {\n+ \"exclude_files\": {\n+ \".*_abi_autogen_test.go\": \"fix: Sprintf format has insufficient args\",\n+ \"/pkg/segment/test/segment_test.go\": \"fix: Errorf format %d arg seg.Start is a func value, not called\",\n+ \"/pkg/tcpip/tcpip_test.go\": \"fix: Error call has possible formatting directive %q\",\n+ \"/pkg/tcpip/header/eth_test.go\": \"fix: Fatalf format %s reads arg #3, but call has 2 args\",\n+ \"/pkg/tcpip/header/ndp_test.go\": \"fix: Errorf format %d reads arg #1, but call has 0 args\",\n+ \"/pkg/eventchannel/event_test.go\": \"fix: Fatal call has possible formatting directive %v\",\n+ \"/pkg/tcpip/stack/ndp.go\": \"fix: Fatalf format %s has arg protocolAddr of wrong type gvisor.dev/gvisor/pkg/tcpip.ProtocolAddress\",\n+ \"/pkg/sentry/fs/fdpipe/pipe_test.go\": \"fix: Errorf format %s has arg flags of wrong type gvisor.dev/gvisor/pkg/sentry/fs.FileFlags\",\n+ \"/pkg/sentry/fs/fdpipe/pipe_test.go\": \"fix: Errorf format %d arg f.FD is a func value, not called\",\n+ \"/pkg/tcpip/link/fdbased/endpoint.go\": \"fix: Sprintf format %v with arg p causes recursive String method call\",\n+ \"/pkg/tcpip/transport/udp/udp_test.go\": \"fix: Fatalf format %s has arg h.srcAddr of wrong type gvisor.dev/gvisor/pkg/tcpip.FullAddress\",\n+ \"/pkg/tcpip/transport/tcp/tcp_test.go\": \"fix: Fatalf format %s has arg tcpTW of wrong type gvisor.dev/gvisor/pkg/tcpip.TCPTimeWaitTimeoutOption\",\n+ \"/pkg/tcpip/transport/tcp/tcp_test.go\": \"fix: Errorf call needs 1 arg but has 2 args\",\n+ \"/pkg/tcpip/stack/ndp_test.go\": \"fix: Errorf format %s reads arg #3, but call has 2 args\",\n+ \"/pkg/tcpip/stack/ndp_test.go\": \"fix: Fatalf format %s reads arg #5, but call has 4 args\",\n+ \"/pkg/tcpip/stack/stack_test.go\": \"fix: Fatalf format %s has arg protoAddr of wrong type gvisor.dev/gvisor/pkg/tcpip.ProtocolAddress\",\n+ \"/pkg/tcpip/stack/stack_test.go\": \"fix: Fatalf format %s has arg nic1ProtoAddr of wrong type gvisor.dev/gvisor/pkg/tcpip.ProtocolAddress\",\n+ \"/pkg/tcpip/stack/stack_test.go\": \"fix: Fatalf format %s has arg nic2ProtoAddr of wrong type gvisor.dev/gvisor/pkg/tcpip.ProtocolAddress\",\n+ \"/pkg/tcpip/stack/stack_test.go\": \"fix: Fatal call has possible formatting directive %t\",\n+ \"/pkg/tcpip/stack/stack_test.go\": \"fix: Fatalf call has arguments but no formatting directives\",\n+ \"/pkg/tcpip/link/fdbased/endpoint.go\": \"fix: Sprintf format %v with arg p causes recursive String method call\",\n+ \"/pkg/sentry/fsimpl/tmpfs/stat_test.go\": \"fix: Errorf format %v reads arg #1, but call has 0 args\",\n+ \"/runsc/container/test_app/test_app.go\": \"fix: Fatal call has possible formatting directive %q\",\n+ \"/test/root/cgroup_test.go\": \"fix: Errorf format %s has arg gots of wrong type []int\",\n+ \"/test/root/cgroup_test.go\": \"fix: Fatalf format %v reads arg #3, but call has 2 args\",\n+ \"/test/runtimes/runner.go\": \"fix: Skip call has possible formatting directive %q\",\n+ \"/test/runtimes/blacklist_test.go\": \"fix: Errorf format %q has arg blacklistFile of wrong type *string\"\n+ }\n+ },\n+ \"structtag\": {\n+ \"exclude_files\": {\n+ \"/external/\": \"allowed: may use arbitrary tags\"\n+ }\n+ },\n+ \"unsafeptr\": {\n+ \"exclude_files\": {\n+ \".*_test.go\": \"allowed: exclude tests\",\n+ \"/pkg/flipcall/flipcall_unsafe.go\": \"allowed: special case\",\n+ \"/pkg/gohacks/gohacks_unsafe.go\": \"allowed: special case\",\n+ \"/pkg/sentry/fs/fsutil/host_file_mapper_unsafe.go\": \"allowed: special case\",\n+ \"/pkg/sentry/platform/kvm/(bluepill|machine)_unsafe.go\": \"allowed: special case\",\n+ \"/pkg/sentry/platform/ring0/pagetables/allocator_unsafe.go\": \"allowed: special case\",\n+ \"/pkg/sentry/platform/safecopy/safecopy_unsafe.go\": \"allowed: special case\",\n+ \"/pkg/sentry/vfs/mount_unsafe.go\": \"allowed: special case\"\n+ }\n+ },\n+ \"unusedresult\": {\n+ \"exclude_files\": {\n+ \"/pkg/sentry/fsimpl/proc/task_net.go\": \"fix: result of fmt.Sprintf call not used\",\n+ \"/pkg/sentry/fsimpl/proc/tasks_net.go\": \"fix: result of fmt.Sprintf call not used\"\n+ }\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | nogo: enable sanitizers.
This enables all relevant santizers (though most analyzers will not find
much, it will prevent instances from creeping in), and codifies existing
exceptions in tools/nogo.js to be fixed. |
259,891 | 25.03.2020 18:55:19 | 25,200 | 4f374da60cb0c39ed862518e5b7524cb86ec96db | iptable: fix tests timeouts
Tests were run assuming a runtime of "runsc" was present, and did not
have --net-raw enabled. | [
{
"change_type": "MODIFY",
"old_path": "scripts/iptables_tests.sh",
"new_path": "scripts/iptables_tests.sh",
"diff": "source $(dirname $0)/common.sh\n-install_runsc_for_test iptables\n+install_runsc_for_test iptables --net-raw\n# Build the docker image for the test.\nrun //test/iptables/runner:runner-image --norun\n@@ -26,5 +26,5 @@ test //test/iptables:iptables_test \\\n\"--test_arg=--image=bazel/test/iptables/runner:runner-image\"\ntest //test/iptables:iptables_test \\\n- \"--test_arg=--runtime=runsc\" \\\n+ \"--test_arg=--runtime=${RUNTIME}\" \\\n\"--test_arg=--image=bazel/test/iptables/runner:runner-image\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | iptable: fix tests timeouts
Tests were run assuming a runtime of "runsc" was present, and did not
have --net-raw enabled. |
259,992 | 25.03.2020 19:12:25 | 25,200 | de694e5484502d53166d70b36141e62fcdf07803 | Combine file mode and isDir arguments
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/file.go",
"new_path": "pkg/abi/linux/file.go",
"diff": "@@ -287,6 +287,11 @@ func (m FileMode) ExtraBits() FileMode {\nreturn m &^ (PermissionsMask | FileTypeMask)\n}\n+// IsDir returns true if file type represents a directory.\n+func (m FileMode) IsDir() bool {\n+ return m.FileType() == S_IFDIR\n+}\n+\n// String returns a string representation of m.\nfunc (m FileMode) String() string {\nvar s []string\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/ext/inode.go",
"new_path": "pkg/sentry/fsimpl/ext/inode.go",
"diff": "@@ -186,7 +186,7 @@ func (in *inode) open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts *vfs.OpenOpt\n}\nfunc (in *inode) checkPermissions(creds *auth.Credentials, ats vfs.AccessTypes) error {\n- return vfs.GenericCheckPermissions(creds, ats, in.isDir(), uint16(in.diskInode.Mode()), in.diskInode.UID(), in.diskInode.GID())\n+ return vfs.GenericCheckPermissions(creds, ats, in.diskInode.Mode(), in.diskInode.UID(), in.diskInode.GID())\n}\n// statTo writes the statx fields to the output parameter.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"new_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"diff": "@@ -119,7 +119,7 @@ func (fs *filesystem) stepLocked(ctx context.Context, rp *vfs.ResolvingPath, d *\nif !d.isDir() {\nreturn nil, syserror.ENOTDIR\n}\n- if err := d.checkPermissions(rp.Credentials(), vfs.MayExec, true); err != nil {\n+ if err := d.checkPermissions(rp.Credentials(), vfs.MayExec); err != nil {\nreturn nil, err\n}\nafterSymlink:\n@@ -314,7 +314,7 @@ func (fs *filesystem) doCreateAt(ctx context.Context, rp *vfs.ResolvingPath, dir\nif err != nil {\nreturn err\n}\n- if err := parent.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec, true); err != nil {\n+ if err := parent.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec); err != nil {\nreturn err\n}\nif parent.isDeleted() {\n@@ -378,7 +378,7 @@ func (fs *filesystem) unlinkAt(ctx context.Context, rp *vfs.ResolvingPath, dir b\nif err != nil {\nreturn err\n}\n- if err := parent.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec, true); err != nil {\n+ if err := parent.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec); err != nil {\nreturn err\n}\nif err := rp.Mount().CheckBeginWrite(); err != nil {\n@@ -512,7 +512,7 @@ func (fs *filesystem) AccessAt(ctx context.Context, rp *vfs.ResolvingPath, creds\nif err != nil {\nreturn err\n}\n- return d.checkPermissions(creds, ats, d.isDir())\n+ return d.checkPermissions(creds, ats)\n}\n// GetDentryAt implements vfs.FilesystemImpl.GetDentryAt.\n@@ -528,7 +528,7 @@ func (fs *filesystem) GetDentryAt(ctx context.Context, rp *vfs.ResolvingPath, op\nif !d.isDir() {\nreturn nil, syserror.ENOTDIR\n}\n- if err := d.checkPermissions(rp.Credentials(), vfs.MayExec, true); err != nil {\n+ if err := d.checkPermissions(rp.Credentials(), vfs.MayExec); err != nil {\nreturn nil, err\n}\n}\n@@ -624,7 +624,7 @@ afterTrailingSymlink:\nreturn nil, err\n}\n// Check for search permission in the parent directory.\n- if err := parent.checkPermissions(rp.Credentials(), vfs.MayExec, true); err != nil {\n+ if err := parent.checkPermissions(rp.Credentials(), vfs.MayExec); err != nil {\nreturn nil, err\n}\n// Determine whether or not we need to create a file.\n@@ -661,7 +661,7 @@ afterTrailingSymlink:\n// Preconditions: fs.renameMu must be locked.\nfunc (d *dentry) openLocked(ctx context.Context, rp *vfs.ResolvingPath, opts *vfs.OpenOptions) (*vfs.FileDescription, error) {\nats := vfs.AccessTypesForOpenFlags(opts)\n- if err := d.checkPermissions(rp.Credentials(), ats, d.isDir()); err != nil {\n+ if err := d.checkPermissions(rp.Credentials(), ats); err != nil {\nreturn nil, err\n}\nmnt := rp.Mount()\n@@ -722,7 +722,7 @@ func (d *dentry) openLocked(ctx context.Context, rp *vfs.ResolvingPath, opts *vf\n// Preconditions: d.fs.renameMu must be locked. d.dirMu must be locked.\nfunc (d *dentry) createAndOpenChildLocked(ctx context.Context, rp *vfs.ResolvingPath, opts *vfs.OpenOptions) (*vfs.FileDescription, error) {\n- if err := d.checkPermissions(rp.Credentials(), vfs.MayWrite, true); err != nil {\n+ if err := d.checkPermissions(rp.Credentials(), vfs.MayWrite); err != nil {\nreturn nil, err\n}\nif d.isDeleted() {\n@@ -884,7 +884,7 @@ func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\nreturn err\n}\n}\n- if err := oldParent.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec, true); err != nil {\n+ if err := oldParent.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec); err != nil {\nreturn err\n}\nvfsObj := rp.VirtualFilesystem()\n@@ -904,7 +904,7 @@ func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\nreturn syserror.EINVAL\n}\nif oldParent != newParent {\n- if err := renamed.checkPermissions(rp.Credentials(), vfs.MayWrite, true); err != nil {\n+ if err := renamed.checkPermissions(rp.Credentials(), vfs.MayWrite); err != nil {\nreturn err\n}\n}\n@@ -915,7 +915,7 @@ func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\n}\nif oldParent != newParent {\n- if err := newParent.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec, true); err != nil {\n+ if err := newParent.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec); err != nil {\nreturn err\n}\nnewParent.dirMu.Lock()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"diff": "@@ -721,7 +721,8 @@ func (d *dentry) setStat(ctx context.Context, creds *auth.Credentials, stat *lin\nif stat.Mask&^(linux.STATX_MODE|linux.STATX_UID|linux.STATX_GID|linux.STATX_ATIME|linux.STATX_MTIME|linux.STATX_SIZE) != 0 {\nreturn syserror.EPERM\n}\n- if err := vfs.CheckSetStat(ctx, creds, stat, uint16(atomic.LoadUint32(&d.mode))&^linux.S_IFMT, auth.KUID(atomic.LoadUint32(&d.uid)), auth.KGID(atomic.LoadUint32(&d.gid))); err != nil {\n+ mode := linux.FileMode(atomic.LoadUint32(&d.mode))\n+ if err := vfs.CheckSetStat(ctx, creds, stat, mode, auth.KUID(atomic.LoadUint32(&d.uid)), auth.KGID(atomic.LoadUint32(&d.gid))); err != nil {\nreturn err\n}\nif err := mnt.CheckBeginWrite(); err != nil {\n@@ -843,8 +844,8 @@ func (d *dentry) setStat(ctx context.Context, creds *auth.Credentials, stat *lin\nreturn nil\n}\n-func (d *dentry) checkPermissions(creds *auth.Credentials, ats vfs.AccessTypes, isDir bool) error {\n- return vfs.GenericCheckPermissions(creds, ats, isDir, uint16(atomic.LoadUint32(&d.mode))&0777, auth.KUID(atomic.LoadUint32(&d.uid)), auth.KGID(atomic.LoadUint32(&d.gid)))\n+func (d *dentry) checkPermissions(creds *auth.Credentials, ats vfs.AccessTypes) error {\n+ return vfs.GenericCheckPermissions(creds, ats, linux.FileMode(atomic.LoadUint32(&d.mode)), auth.KUID(atomic.LoadUint32(&d.uid)), auth.KGID(atomic.LoadUint32(&d.gid)))\n}\n// IncRef implements vfs.DentryImpl.IncRef.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/host/host.go",
"new_path": "pkg/sentry/fsimpl/host/host.go",
"diff": "@@ -167,8 +167,8 @@ func fileFlagsFromHostFD(fd int) (int, error) {\n}\n// CheckPermissions implements kernfs.Inode.\n-func (i *inode) CheckPermissions(ctx context.Context, creds *auth.Credentials, atx vfs.AccessTypes) error {\n- return vfs.GenericCheckPermissions(creds, atx, false /* isDir */, uint16(i.mode), i.uid, i.gid)\n+func (i *inode) CheckPermissions(ctx context.Context, creds *auth.Credentials, ats vfs.AccessTypes) error {\n+ return vfs.GenericCheckPermissions(creds, ats, i.mode, i.uid, i.gid)\n}\n// Mode implements kernfs.Inode.\n@@ -306,7 +306,7 @@ func (i *inode) SetStat(ctx context.Context, fs *vfs.Filesystem, creds *auth.Cre\nif m&^(linux.STATX_MODE|linux.STATX_SIZE|linux.STATX_ATIME|linux.STATX_MTIME) != 0 {\nreturn syserror.EPERM\n}\n- if err := vfs.CheckSetStat(ctx, creds, &s, uint16(i.Mode().Permissions()), i.uid, i.gid); err != nil {\n+ if err := vfs.CheckSetStat(ctx, creds, &s, i.Mode(), i.uid, i.gid); err != nil {\nreturn err\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": "@@ -206,8 +206,7 @@ func (fd *GenericDirectoryFD) Stat(ctx context.Context, opts vfs.StatOptions) (l\n// SetStat implements vfs.FileDescriptionImpl.SetStat.\nfunc (fd *GenericDirectoryFD) SetStat(ctx context.Context, opts vfs.SetStatOptions) error {\n- fs := fd.filesystem()\ncreds := auth.CredentialsFromContext(ctx)\ninode := fd.vfsfd.VirtualDentry().Dentry().Impl().(*Dentry).inode\n- return inode.SetStat(ctx, fs, creds, opts)\n+ return inode.SetStat(ctx, fd.filesystem(), creds, opts)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go",
"new_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go",
"diff": "@@ -241,7 +241,7 @@ func (a *InodeAttrs) SetStat(ctx context.Context, fs *vfs.Filesystem, creds *aut\nif opts.Stat.Mask&^(linux.STATX_MODE|linux.STATX_UID|linux.STATX_GID) != 0 {\nreturn syserror.EPERM\n}\n- if err := vfs.CheckSetStat(ctx, creds, &opts.Stat, uint16(a.Mode().Permissions()), auth.KUID(atomic.LoadUint32(&a.uid)), auth.KGID(atomic.LoadUint32(&a.gid))); err != nil {\n+ if err := vfs.CheckSetStat(ctx, creds, &opts.Stat, a.Mode(), auth.KUID(atomic.LoadUint32(&a.uid)), auth.KGID(atomic.LoadUint32(&a.gid))); err != nil {\nreturn err\n}\n@@ -273,12 +273,10 @@ func (a *InodeAttrs) SetStat(ctx context.Context, fs *vfs.Filesystem, creds *aut\n// CheckPermissions implements Inode.CheckPermissions.\nfunc (a *InodeAttrs) CheckPermissions(_ context.Context, creds *auth.Credentials, ats vfs.AccessTypes) error {\n- mode := a.Mode()\nreturn vfs.GenericCheckPermissions(\ncreds,\nats,\n- mode.FileType() == linux.ModeDirectory,\n- uint16(mode),\n+ a.Mode(),\nauth.KUID(atomic.LoadUint32(&a.uid)),\nauth.KGID(atomic.LoadUint32(&a.gid)),\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/task.go",
"new_path": "pkg/sentry/fsimpl/proc/task.go",
"diff": "@@ -172,14 +172,7 @@ func (i *taskOwnedInode) Stat(fs *vfs.Filesystem, opts vfs.StatOptions) (linux.S\nfunc (i *taskOwnedInode) CheckPermissions(_ context.Context, creds *auth.Credentials, ats vfs.AccessTypes) error {\nmode := i.Mode()\nuid, gid := i.getOwner(mode)\n- return vfs.GenericCheckPermissions(\n- creds,\n- ats,\n- mode.FileType() == linux.ModeDirectory,\n- uint16(mode),\n- uid,\n- gid,\n- )\n+ return vfs.GenericCheckPermissions(creds, ats, mode, uid, gid)\n}\nfunc (i *taskOwnedInode) getOwner(mode linux.FileMode) (auth.KUID, auth.KGID) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go",
"diff": "@@ -41,7 +41,7 @@ func stepLocked(rp *vfs.ResolvingPath, d *dentry) (*dentry, error) {\nif !d.inode.isDir() {\nreturn nil, syserror.ENOTDIR\n}\n- if err := d.inode.checkPermissions(rp.Credentials(), vfs.MayExec, true); err != nil {\n+ if err := d.inode.checkPermissions(rp.Credentials(), vfs.MayExec); err != nil {\nreturn nil, err\n}\nafterSymlink:\n@@ -125,7 +125,7 @@ func (fs *filesystem) doCreateAt(rp *vfs.ResolvingPath, dir bool, create func(pa\nif err != nil {\nreturn err\n}\n- if err := parent.inode.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec, true /* isDir */); err != nil {\n+ if err := parent.inode.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec); err != nil {\nreturn err\n}\nname := rp.Component()\n@@ -163,7 +163,7 @@ func (fs *filesystem) AccessAt(ctx context.Context, rp *vfs.ResolvingPath, creds\nif err != nil {\nreturn err\n}\n- return d.inode.checkPermissions(creds, ats, d.inode.isDir())\n+ return d.inode.checkPermissions(creds, ats)\n}\n// GetDentryAt implements vfs.FilesystemImpl.GetDentryAt.\n@@ -178,7 +178,7 @@ func (fs *filesystem) GetDentryAt(ctx context.Context, rp *vfs.ResolvingPath, op\nif !d.inode.isDir() {\nreturn nil, syserror.ENOTDIR\n}\n- if err := d.inode.checkPermissions(rp.Credentials(), vfs.MayExec, true /* isDir */); err != nil {\n+ if err := d.inode.checkPermissions(rp.Credentials(), vfs.MayExec); err != nil {\nreturn nil, err\n}\n}\n@@ -301,7 +301,7 @@ afterTrailingSymlink:\nreturn nil, err\n}\n// Check for search permission in the parent directory.\n- if err := parent.inode.checkPermissions(rp.Credentials(), vfs.MayExec, true); err != nil {\n+ if err := parent.inode.checkPermissions(rp.Credentials(), vfs.MayExec); err != nil {\nreturn nil, err\n}\n// Reject attempts to open directories with O_CREAT.\n@@ -316,7 +316,7 @@ afterTrailingSymlink:\nchild, err := stepLocked(rp, parent)\nif err == syserror.ENOENT {\n// Already checked for searchability above; now check for writability.\n- if err := parent.inode.checkPermissions(rp.Credentials(), vfs.MayWrite, true); err != nil {\n+ if err := parent.inode.checkPermissions(rp.Credentials(), vfs.MayWrite); err != nil {\nreturn nil, err\n}\nif err := rp.Mount().CheckBeginWrite(); err != nil {\n@@ -347,7 +347,7 @@ afterTrailingSymlink:\nfunc (d *dentry) open(ctx context.Context, rp *vfs.ResolvingPath, opts *vfs.OpenOptions, afterCreate bool) (*vfs.FileDescription, error) {\nats := vfs.AccessTypesForOpenFlags(opts)\nif !afterCreate {\n- if err := d.inode.checkPermissions(rp.Credentials(), ats, d.inode.isDir()); err != nil {\n+ if err := d.inode.checkPermissions(rp.Credentials(), ats); err != nil {\nreturn nil, err\n}\n}\n@@ -428,7 +428,7 @@ func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\ndefer mnt.EndWrite()\noldParent := oldParentVD.Dentry().Impl().(*dentry)\n- if err := oldParent.inode.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec, true /* isDir */); err != nil {\n+ if err := oldParent.inode.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec); err != nil {\nreturn err\n}\n// Call vfs.Dentry.Child() instead of stepLocked() or rp.ResolveChild(),\n@@ -445,7 +445,7 @@ func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\n}\nif oldParent != newParent {\n// Writability is needed to change renamed's \"..\".\n- if err := renamed.inode.checkPermissions(rp.Credentials(), vfs.MayWrite, true /* isDir */); err != nil {\n+ if err := renamed.inode.checkPermissions(rp.Credentials(), vfs.MayWrite); err != nil {\nreturn err\n}\n}\n@@ -455,7 +455,7 @@ func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\n}\n}\n- if err := newParent.inode.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec, true /* isDir */); err != nil {\n+ if err := newParent.inode.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec); err != nil {\nreturn err\n}\nreplacedVFSD := newParent.vfsd.Child(newName)\n@@ -528,7 +528,7 @@ func (fs *filesystem) RmdirAt(ctx context.Context, rp *vfs.ResolvingPath) error\nif err != nil {\nreturn err\n}\n- if err := parent.inode.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec, true /* isDir */); err != nil {\n+ if err := parent.inode.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec); err != nil {\nreturn err\n}\nname := rp.Component()\n@@ -621,7 +621,7 @@ func (fs *filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\nif err != nil {\nreturn err\n}\n- if err := parent.inode.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec, true /* isDir */); err != nil {\n+ if err := parent.inode.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec); err != nil {\nreturn err\n}\nname := rp.Component()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"diff": "@@ -245,8 +245,9 @@ func (i *inode) decRef() {\n}\n}\n-func (i *inode) checkPermissions(creds *auth.Credentials, ats vfs.AccessTypes, isDir bool) error {\n- return vfs.GenericCheckPermissions(creds, ats, isDir, uint16(atomic.LoadUint32(&i.mode)), auth.KUID(atomic.LoadUint32(&i.uid)), auth.KGID(atomic.LoadUint32(&i.gid)))\n+func (i *inode) checkPermissions(creds *auth.Credentials, ats vfs.AccessTypes) error {\n+ mode := linux.FileMode(atomic.LoadUint32(&i.mode))\n+ return vfs.GenericCheckPermissions(creds, ats, mode, auth.KUID(atomic.LoadUint32(&i.uid)), auth.KGID(atomic.LoadUint32(&i.gid)))\n}\n// Go won't inline this function, and returning linux.Statx (which is quite\n@@ -299,7 +300,8 @@ func (i *inode) setStat(ctx context.Context, creds *auth.Credentials, stat *linu\nif stat.Mask&^(linux.STATX_MODE|linux.STATX_UID|linux.STATX_GID|linux.STATX_ATIME|linux.STATX_MTIME|linux.STATX_CTIME|linux.STATX_SIZE) != 0 {\nreturn syserror.EPERM\n}\n- if err := vfs.CheckSetStat(ctx, creds, stat, uint16(atomic.LoadUint32(&i.mode))&^linux.S_IFMT, auth.KUID(atomic.LoadUint32(&i.uid)), auth.KGID(atomic.LoadUint32(&i.gid))); err != nil {\n+ mode := linux.FileMode(atomic.LoadUint32(&i.mode))\n+ if err := vfs.CheckSetStat(ctx, creds, stat, mode, auth.KUID(atomic.LoadUint32(&i.uid)), auth.KGID(atomic.LoadUint32(&i.gid))); err != nil {\nreturn err\n}\ni.mu.Lock()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/anonfs.go",
"new_path": "pkg/sentry/vfs/anonfs.go",
"diff": "@@ -83,7 +83,7 @@ func (fs *anonFilesystem) AccessAt(ctx context.Context, rp *ResolvingPath, creds\nif !rp.Done() {\nreturn syserror.ENOTDIR\n}\n- return GenericCheckPermissions(creds, ats, false /* isDir */, anonFileMode, anonFileUID, anonFileGID)\n+ return GenericCheckPermissions(creds, ats, anonFileMode, anonFileUID, anonFileGID)\n}\n// GetDentryAt implements FilesystemImpl.GetDentryAt.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/permissions.go",
"new_path": "pkg/sentry/vfs/permissions.go",
"diff": "@@ -29,9 +29,9 @@ type AccessTypes uint16\n// Bits in AccessTypes.\nconst (\n+ MayExec AccessTypes = 1\n+ MayWrite AccessTypes = 2\nMayRead AccessTypes = 4\n- MayWrite = 2\n- MayExec = 1\n)\n// OnlyRead returns true if access _only_ allows read.\n@@ -56,16 +56,17 @@ func (a AccessTypes) MayExec() bool {\n// GenericCheckPermissions checks that creds has the given access rights on a\n// file with the given permissions, UID, and GID, subject to the rules of\n-// fs/namei.c:generic_permission(). isDir is true if the file is a directory.\n-func GenericCheckPermissions(creds *auth.Credentials, ats AccessTypes, isDir bool, mode uint16, kuid auth.KUID, kgid auth.KGID) error {\n+// fs/namei.c:generic_permission().\n+func GenericCheckPermissions(creds *auth.Credentials, ats AccessTypes, mode linux.FileMode, kuid auth.KUID, kgid auth.KGID) error {\n// Check permission bits.\n- perms := mode\n+ perms := uint16(mode.Permissions())\nif creds.EffectiveKUID == kuid {\nperms >>= 6\n} else if creds.InGroup(kgid) {\nperms >>= 3\n}\nif uint16(ats)&perms == uint16(ats) {\n+ // All permission bits match, access granted.\nreturn nil\n}\n@@ -77,7 +78,7 @@ func GenericCheckPermissions(creds *auth.Credentials, ats AccessTypes, isDir boo\n}\n// CAP_DAC_READ_SEARCH allows the caller to read and search arbitrary\n// directories, and read arbitrary non-directory files.\n- if (isDir && !ats.MayWrite()) || ats.OnlyRead() {\n+ if (mode.IsDir() && !ats.MayWrite()) || ats.OnlyRead() {\nif creds.HasCapability(linux.CAP_DAC_READ_SEARCH) {\nreturn nil\n}\n@@ -85,7 +86,7 @@ func GenericCheckPermissions(creds *auth.Credentials, ats AccessTypes, isDir boo\n// CAP_DAC_OVERRIDE allows arbitrary access to directories, read/write\n// access to non-directory files, and execute access to non-directory files\n// for which at least one execute bit is set.\n- if isDir || !ats.MayExec() || (mode&0111 != 0) {\n+ if mode.IsDir() || !ats.MayExec() || (mode.Permissions()&0111 != 0) {\nif creds.HasCapability(linux.CAP_DAC_OVERRIDE) {\nreturn nil\n}\n@@ -151,7 +152,7 @@ func MayWriteFileWithOpenFlags(flags uint32) bool {\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(ctx context.Context, creds *auth.Credentials, stat *linux.Statx, mode uint16, kuid auth.KUID, kgid auth.KGID) error {\n+func CheckSetStat(ctx context.Context, creds *auth.Credentials, stat *linux.Statx, mode linux.FileMode, kuid auth.KUID, kgid auth.KGID) error {\nif stat.Mask&linux.STATX_SIZE != 0 {\nlimit, err := CheckLimit(ctx, 0, int64(stat.Size))\nif err != nil {\n@@ -190,11 +191,7 @@ func CheckSetStat(ctx context.Context, creds *auth.Credentials, stat *linux.Stat\n(stat.Mask&linux.STATX_CTIME != 0 && stat.Ctime.Nsec != linux.UTIME_NOW) {\nreturn 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+ if err := GenericCheckPermissions(creds, MayWrite, mode, kuid, kgid); err != nil {\nreturn err\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Combine file mode and isDir arguments
Updates #1035
PiperOrigin-RevId: 303021328 |
259,891 | 26.03.2020 10:46:47 | 25,200 | bc3def43c3c30ccde6577a0af213d13e4fd17e1e | Check error in DropTCP*Port tests and fix comment. | [
{
"change_type": "MODIFY",
"old_path": "test/iptables/filter_input.go",
"new_path": "test/iptables/filter_input.go",
"diff": "@@ -194,14 +194,11 @@ func (FilterInputDropTCPDestPort) ContainerAction(ip net.IP) error {\n// LocalAction implements TestCase.LocalAction.\nfunc (FilterInputDropTCPDestPort) LocalAction(ip net.IP) error {\n- // After the container sets its DROP rule, we shouldn't be able to connect.\n- // However, we may succeed in connecting if this runs before the container\n- // sets the rule. To avoid this race, we retry connecting until\n- // sendloopDuration has elapsed, ignoring whether the connect succeeds. The\n- // test works becuase the container will error if a connection is\n- // established after the rule is set.\n+ // Ensure we cannot connect to the container.\nfor start := time.Now(); time.Since(start) < sendloopDuration; {\n- connectTCP(ip, dropPort, sendloopDuration-time.Since(start))\n+ if err := connectTCP(ip, dropPort, sendloopDuration-time.Since(start)); err == nil {\n+ return fmt.Errorf(\"expected not to connect, but was able to connect on port %d\", dropPort)\n+ }\n}\nreturn nil\n@@ -232,14 +229,11 @@ func (FilterInputDropTCPSrcPort) ContainerAction(ip net.IP) error {\n// LocalAction implements TestCase.LocalAction.\nfunc (FilterInputDropTCPSrcPort) LocalAction(ip net.IP) error {\n- // After the container sets its DROP rule, we shouldn't be able to connect.\n- // However, we may succeed in connecting if this runs before the container\n- // sets the rule. To avoid this race, we retry connecting until\n- // sendloopDuration has elapsed, ignoring whether the connect succeeds. The\n- // test works becuase the container will error if a connection is\n- // established after the rule is set.\n+ // Ensure we cannot connect to the container.\nfor start := time.Now(); time.Since(start) < sendloopDuration; {\n- connectTCP(ip, acceptPort, sendloopDuration-time.Since(start))\n+ if err := connectTCP(ip, acceptPort, sendloopDuration-time.Since(start)); err == nil {\n+ return fmt.Errorf(\"expected not to connect, but was able to connect on port %d\", acceptPort)\n+ }\n}\nreturn nil\n"
}
] | Go | Apache License 2.0 | google/gvisor | Check error in DropTCP*Port tests and fix comment.
PiperOrigin-RevId: 303147253 |
259,858 | 26.03.2020 12:29:14 | 25,200 | a5742f177af1758d9e7b65bfbf11af297960817b | Add nogo exemption for machine_arm64_unsafe.go | [
{
"change_type": "MODIFY",
"old_path": "tools/nogo.json",
"new_path": "tools/nogo.json",
"diff": "\"/pkg/gohacks/gohacks_unsafe.go\": \"allowed: special case\",\n\"/pkg/sentry/fs/fsutil/host_file_mapper_unsafe.go\": \"allowed: special case\",\n\"/pkg/sentry/platform/kvm/(bluepill|machine)_unsafe.go\": \"allowed: special case\",\n+ \"/pkg/sentry/platform/kvm/machine_arm64_unsafe.go\": \"fix: gvisor.dev/issue/22464\",\n\"/pkg/sentry/platform/ring0/pagetables/allocator_unsafe.go\": \"allowed: special case\",\n\"/pkg/sentry/platform/safecopy/safecopy_unsafe.go\": \"allowed: special case\",\n\"/pkg/sentry/vfs/mount_unsafe.go\": \"allowed: special case\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add nogo exemption for machine_arm64_unsafe.go |
260,004 | 26.03.2020 15:59:41 | 25,200 | edc3c049eb553fcbf32f4a6b515141a26c5609d4 | Use panic instead of log.Fatalf | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/icmp.go",
"new_path": "pkg/tcpip/network/ipv6/icmp.go",
"diff": "package ipv6\nimport (\n- \"log\"\n+ \"fmt\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n@@ -199,7 +199,7 @@ func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, pkt stack.P\nopt, done, err := it.Next()\nif err != nil {\n// This should never happen as Iter(true) above did not return an error.\n- log.Fatalf(\"unexpected error when iterating over NDP options: %s\", err)\n+ panic(fmt.Sprintf(\"unexpected error when iterating over NDP options: %s\", err))\n}\nif done {\nbreak\n@@ -306,7 +306,7 @@ func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, pkt stack.P\nopt, done, err := it.Next()\nif err != nil {\n// This should never happen as Iter(true) above did not return an error.\n- log.Fatalf(\"unexpected error when iterating over NDP options: %s\", err)\n+ panic(fmt.Sprintf(\"unexpected error when iterating over NDP options: %s\", err))\n}\nif done {\nbreak\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/ndp.go",
"new_path": "pkg/tcpip/stack/ndp.go",
"diff": "package stack\nimport (\n+ \"fmt\"\n\"log\"\n\"math/rand\"\n\"time\"\n@@ -428,7 +429,7 @@ func (ndp *ndpState) startDuplicateAddressDetection(addr tcpip.Address, ref *ref\nif ref.getKind() != permanentTentative {\n// The endpoint should be marked as tentative since we are starting DAD.\n- log.Fatalf(\"ndpdad: addr %s is not tentative on NIC(%d)\", addr, ndp.nic.ID())\n+ panic(fmt.Sprintf(\"ndpdad: addr %s is not tentative on NIC(%d)\", addr, ndp.nic.ID()))\n}\n// Should not attempt to perform DAD on an address that is currently in the\n@@ -440,7 +441,7 @@ func (ndp *ndpState) startDuplicateAddressDetection(addr tcpip.Address, ref *ref\n// address, or its reference count would have been increased without doing\n// the work that would have been done for an address that was brand new.\n// See NIC.addAddressLocked.\n- log.Fatalf(\"ndpdad: already performing DAD for addr %s on NIC(%d)\", addr, ndp.nic.ID())\n+ panic(fmt.Sprintf(\"ndpdad: already performing DAD for addr %s on NIC(%d)\", addr, ndp.nic.ID()))\n}\nremaining := ndp.configs.DupAddrDetectTransmits\n@@ -476,7 +477,7 @@ func (ndp *ndpState) startDuplicateAddressDetection(addr tcpip.Address, ref *ref\nif ref.getKind() != permanentTentative {\n// The endpoint should still be marked as tentative since we are still\n// performing DAD on it.\n- log.Fatalf(\"ndpdad: addr %s is no longer tentative on NIC(%d)\", addr, ndp.nic.ID())\n+ panic(fmt.Sprintf(\"ndpdad: addr %s is no longer tentative on NIC(%d)\", addr, ndp.nic.ID()))\n}\ndadDone := remaining == 0\n@@ -546,9 +547,9 @@ func (ndp *ndpState) sendDADPacket(addr tcpip.Address) *tcpip.Error {\n// Route should resolve immediately since snmc is a multicast address so a\n// remote link address can be calculated without a resolution process.\nif c, err := r.Resolve(nil); err != nil {\n- log.Fatalf(\"ndp: error when resolving route to send NDP NS for DAD (%s -> %s on NIC(%d)): %s\", header.IPv6Any, snmc, ndp.nic.ID(), err)\n+ panic(fmt.Sprintf(\"ndp: error when resolving route to send NDP NS for DAD (%s -> %s on NIC(%d)): %s\", header.IPv6Any, snmc, ndp.nic.ID(), err))\n} else if c != nil {\n- log.Fatalf(\"ndp: route resolution not immediate for route to send NDP NS for DAD (%s -> %s on NIC(%d))\", header.IPv6Any, snmc, ndp.nic.ID())\n+ panic(fmt.Sprintf(\"ndp: route resolution not immediate for route to send NDP NS for DAD (%s -> %s on NIC(%d))\", header.IPv6Any, snmc, ndp.nic.ID()))\n}\nhdr := buffer.NewPrependable(int(r.MaxHeaderLength()) + header.ICMPv6NeighborSolicitMinimumSize)\n@@ -949,7 +950,7 @@ func (ndp *ndpState) doSLAAC(prefix tcpip.Subnet, pl, vl time.Duration) {\ndeprecationTimer: tcpip.MakeCancellableTimer(&ndp.nic.mu, func() {\nprefixState, ok := ndp.slaacPrefixes[prefix]\nif !ok {\n- log.Fatalf(\"ndp: must have a slaacPrefixes entry for the SLAAC prefix %s\", prefix)\n+ panic(fmt.Sprintf(\"ndp: must have a slaacPrefixes entry for the SLAAC prefix %s\", prefix))\n}\nndp.deprecateSLAACAddress(prefixState.ref)\n@@ -1029,7 +1030,7 @@ func (ndp *ndpState) addSLAACAddr(prefix tcpip.Subnet, deprecated bool) *referen\nref, err := ndp.nic.addAddressLocked(generatedAddr, FirstPrimaryEndpoint, permanent, slaac, deprecated)\nif err != nil {\n- log.Fatalf(\"ndp: error when adding address %+v: %s\", generatedAddr, err)\n+ panic(fmt.Sprintf(\"ndp: error when adding address %+v: %s\", generatedAddr, err))\n}\nreturn ref\n@@ -1043,7 +1044,7 @@ func (ndp *ndpState) addSLAACAddr(prefix tcpip.Subnet, deprecated bool) *referen\nfunc (ndp *ndpState) refreshSLAACPrefixLifetimes(prefix tcpip.Subnet, pl, vl time.Duration) {\nprefixState, ok := ndp.slaacPrefixes[prefix]\nif !ok {\n- log.Fatalf(\"ndp: SLAAC prefix state not found to refresh lifetimes for %s\", prefix)\n+ panic(fmt.Sprintf(\"ndp: SLAAC prefix state not found to refresh lifetimes for %s\", prefix))\n}\ndefer func() { ndp.slaacPrefixes[prefix] = prefixState }()\n@@ -1144,7 +1145,7 @@ func (ndp *ndpState) invalidateSLAACPrefix(prefix tcpip.Subnet, removeAddr bool)\nif removeAddr {\nif err := ndp.nic.removePermanentAddressLocked(addr); err != nil {\n- log.Fatalf(\"ndp: removePermanentAddressLocked(%s): %s\", addr, err)\n+ panic(fmt.Sprintf(\"ndp: removePermanentAddressLocked(%s): %s\", addr, err))\n}\n}\n@@ -1193,7 +1194,7 @@ func (ndp *ndpState) cleanupState(hostOnly bool) {\n}\nif got := len(ndp.slaacPrefixes); got != linkLocalPrefixes {\n- log.Fatalf(\"ndp: still have non-linklocal SLAAC prefixes after cleaning up; found = %d prefixes, of which %d are link-local\", got, linkLocalPrefixes)\n+ panic(fmt.Sprintf(\"ndp: still have non-linklocal SLAAC prefixes after cleaning up; found = %d prefixes, of which %d are link-local\", got, linkLocalPrefixes))\n}\nfor prefix := range ndp.onLinkPrefixes {\n@@ -1201,7 +1202,7 @@ func (ndp *ndpState) cleanupState(hostOnly bool) {\n}\nif got := len(ndp.onLinkPrefixes); got != 0 {\n- log.Fatalf(\"ndp: still have discovered on-link prefixes after cleaning up; found = %d\", got)\n+ panic(fmt.Sprintf(\"ndp: still have discovered on-link prefixes after cleaning up; found = %d\", got))\n}\nfor router := range ndp.defaultRouters {\n@@ -1209,7 +1210,7 @@ func (ndp *ndpState) cleanupState(hostOnly bool) {\n}\nif got := len(ndp.defaultRouters); got != 0 {\n- log.Fatalf(\"ndp: still have discovered default routers after cleaning up; found = %d\", got)\n+ panic(fmt.Sprintf(\"ndp: still have discovered default routers after cleaning up; found = %d\", got))\n}\n}\n@@ -1251,9 +1252,9 @@ func (ndp *ndpState) startSolicitingRouters() {\n// header.IPv6AllRoutersMulticastAddress is a multicast address so a\n// remote link address can be calculated without a resolution process.\nif c, err := r.Resolve(nil); err != nil {\n- log.Fatalf(\"ndp: error when resolving route to send NDP RS (%s -> %s on NIC(%d)): %s\", header.IPv6Any, header.IPv6AllRoutersMulticastAddress, ndp.nic.ID(), err)\n+ panic(fmt.Sprintf(\"ndp: error when resolving route to send NDP RS (%s -> %s on NIC(%d)): %s\", header.IPv6Any, header.IPv6AllRoutersMulticastAddress, ndp.nic.ID(), err))\n} else if c != nil {\n- log.Fatalf(\"ndp: route resolution not immediate for route to send NDP RS (%s -> %s on NIC(%d))\", header.IPv6Any, header.IPv6AllRoutersMulticastAddress, ndp.nic.ID())\n+ panic(fmt.Sprintf(\"ndp: route resolution not immediate for route to send NDP RS (%s -> %s on NIC(%d))\", header.IPv6Any, header.IPv6AllRoutersMulticastAddress, ndp.nic.ID()))\n}\n// As per RFC 4861 section 4.1, an NDP RS SHOULD include the source\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic.go",
"new_path": "pkg/tcpip/stack/nic.go",
"diff": "@@ -16,7 +16,6 @@ package stack\nimport (\n\"fmt\"\n- \"log\"\n\"reflect\"\n\"sort\"\n\"strings\"\n@@ -480,7 +479,7 @@ func (n *NIC) primaryIPv6Endpoint(remoteAddr tcpip.Address) *referencedNetworkEn\n// Should never happen as we got r from the primary IPv6 endpoint list and\n// ScopeForIPv6Address only returns an error if addr is not an IPv6\n// address.\n- log.Fatalf(\"header.ScopeForIPv6Address(%s): %s\", addr, err)\n+ panic(fmt.Sprintf(\"header.ScopeForIPv6Address(%s): %s\", addr, err))\n}\ncs = append(cs, ipv6AddrCandidate{\n@@ -492,7 +491,7 @@ func (n *NIC) primaryIPv6Endpoint(remoteAddr tcpip.Address) *referencedNetworkEn\nremoteScope, err := header.ScopeForIPv6Address(remoteAddr)\nif err != nil {\n// primaryIPv6Endpoint should never be called with an invalid IPv6 address.\n- log.Fatalf(\"header.ScopeForIPv6Address(%s): %s\", remoteAddr, err)\n+ panic(fmt.Sprintf(\"header.ScopeForIPv6Address(%s): %s\", remoteAddr, err))\n}\n// Sort the addresses as per RFC 6724 section 5 rules 1-3.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use panic instead of log.Fatalf
PiperOrigin-RevId: 303212189 |
259,860 | 26.03.2020 21:47:46 | 25,200 | 76a7ace751bfd4b16411edbc0a2b06d0308b8832 | Add BoundEndpointAt filesystem operation.
BoundEndpointAt() is needed to support Unix sockets bound at a
file path, corresponding to BoundEndpoint() in VFS1.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/ext/BUILD",
"new_path": "pkg/sentry/fsimpl/ext/BUILD",
"diff": "@@ -45,6 +45,7 @@ go_library(\n\"//pkg/sentry/fsimpl/ext/disklayout\",\n\"//pkg/sentry/kernel/auth\",\n\"//pkg/sentry/memmap\",\n+ \"//pkg/sentry/socket/unix/transport\",\n\"//pkg/sentry/syscalls/linux\",\n\"//pkg/sentry/vfs\",\n\"//pkg/sync\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/ext/filesystem.go",
"new_path": "pkg/sentry/fsimpl/ext/filesystem.go",
"diff": "@@ -23,6 +23,7 @@ import (\n\"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/ext/disklayout\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n@@ -463,6 +464,17 @@ func (fs *filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\nreturn syserror.EROFS\n}\n+// BoundEndpointAt implements FilesystemImpl.BoundEndpointAt.\n+func (fs *filesystem) BoundEndpointAt(ctx context.Context, rp *vfs.ResolvingPath) (transport.BoundEndpoint, error) {\n+ _, _, err := fs.walk(rp, false)\n+ if err != nil {\n+ return nil, err\n+ }\n+\n+ // TODO(b/134676337): Support sockets.\n+ return nil, syserror.ECONNREFUSED\n+}\n+\n// ListxattrAt implements vfs.FilesystemImpl.ListxattrAt.\nfunc (fs *filesystem) ListxattrAt(ctx context.Context, rp *vfs.ResolvingPath) ([]string, error) {\n_, _, err := fs.walk(rp, false)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/BUILD",
"new_path": "pkg/sentry/fsimpl/gofer/BUILD",
"diff": "@@ -46,6 +46,7 @@ go_library(\n\"//pkg/sentry/memmap\",\n\"//pkg/sentry/pgalloc\",\n\"//pkg/sentry/platform\",\n+ \"//pkg/sentry/socket/unix/transport\",\n\"//pkg/sentry/usage\",\n\"//pkg/sentry/vfs\",\n\"//pkg/syserror\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"new_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"diff": "@@ -22,6 +22,7 @@ import (\n\"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/p9\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n)\n@@ -1059,6 +1060,13 @@ func (fs *filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\nreturn fs.unlinkAt(ctx, rp, false /* dir */)\n}\n+// BoundEndpointAt implements FilesystemImpl.BoundEndpointAt.\n+//\n+// TODO(gvisor.dev/issue/1476): Implement BoundEndpointAt.\n+func (fs *filesystem) BoundEndpointAt(ctx context.Context, rp *vfs.ResolvingPath) (transport.BoundEndpoint, error) {\n+ return nil, syserror.ECONNREFUSED\n+}\n+\n// ListxattrAt implements vfs.FilesystemImpl.ListxattrAt.\nfunc (fs *filesystem) ListxattrAt(ctx context.Context, rp *vfs.ResolvingPath) ([]string, error) {\nvar ds *[]*dentry\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/BUILD",
"new_path": "pkg/sentry/fsimpl/kernfs/BUILD",
"diff": "@@ -35,6 +35,7 @@ go_library(\n\"//pkg/refs\",\n\"//pkg/sentry/kernel/auth\",\n\"//pkg/sentry/memmap\",\n+ \"//pkg/sentry/socket/unix/transport\",\n\"//pkg/sentry/vfs\",\n\"//pkg/sync\",\n\"//pkg/syserror\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go",
"diff": "@@ -23,6 +23,7 @@ import (\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n)\n@@ -728,6 +729,18 @@ func (fs *Filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\nreturn nil\n}\n+// BoundEndpointAt implements FilesystemImpl.BoundEndpointAt.\n+func (fs *Filesystem) BoundEndpointAt(ctx context.Context, rp *vfs.ResolvingPath) (transport.BoundEndpoint, 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+ return nil, syserror.ECONNREFUSED\n+}\n+\n// ListxattrAt implements vfs.FilesystemImpl.ListxattrAt.\nfunc (fs *Filesystem) ListxattrAt(ctx context.Context, rp *vfs.ResolvingPath) ([]string, error) {\nfs.mu.RLock()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/BUILD",
"new_path": "pkg/sentry/fsimpl/tmpfs/BUILD",
"diff": "@@ -46,6 +46,7 @@ go_library(\n\"//pkg/sentry/memmap\",\n\"//pkg/sentry/pgalloc\",\n\"//pkg/sentry/platform\",\n+ \"//pkg/sentry/socket/unix/transport\",\n\"//pkg/sentry/usage\",\n\"//pkg/sentry/vfs\",\n\"//pkg/sentry/vfs/lock\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go",
"diff": "@@ -21,6 +21,7 @@ import (\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n)\n@@ -656,6 +657,13 @@ func (fs *filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\nreturn nil\n}\n+// BoundEndpointAt implements FilesystemImpl.BoundEndpointAt.\n+//\n+// TODO(gvisor.dev/issue/1476): Implement BoundEndpointAt.\n+func (fs *filesystem) BoundEndpointAt(ctx context.Context, rp *vfs.ResolvingPath) (transport.BoundEndpoint, error) {\n+ return nil, syserror.ECONNREFUSED\n+}\n+\n// ListxattrAt implements vfs.FilesystemImpl.ListxattrAt.\nfunc (fs *filesystem) ListxattrAt(ctx context.Context, rp *vfs.ResolvingPath) ([]string, error) {\nfs.mu.RLock()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/BUILD",
"new_path": "pkg/sentry/vfs/BUILD",
"diff": "@@ -53,6 +53,7 @@ go_library(\n\"//pkg/sentry/kernel/auth\",\n\"//pkg/sentry/limits\",\n\"//pkg/sentry/memmap\",\n+ \"//pkg/sentry/socket/unix/transport\",\n\"//pkg/sync\",\n\"//pkg/syserror\",\n\"//pkg/usermem\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/anonfs.go",
"new_path": "pkg/sentry/vfs/anonfs.go",
"diff": "@@ -21,6 +21,7 @@ import (\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n@@ -222,6 +223,14 @@ func (fs *anonFilesystem) UnlinkAt(ctx context.Context, rp *ResolvingPath) error\nreturn syserror.EPERM\n}\n+// BoundEndpointAt implements FilesystemImpl.BoundEndpointAt.\n+func (fs *anonFilesystem) BoundEndpointAt(ctx context.Context, rp *ResolvingPath) (transport.BoundEndpoint, error) {\n+ if !rp.Final() {\n+ return nil, syserror.ENOTDIR\n+ }\n+ return nil, syserror.ECONNREFUSED\n+}\n+\n// ListxattrAt implements FilesystemImpl.ListxattrAt.\nfunc (fs *anonFilesystem) ListxattrAt(ctx context.Context, rp *ResolvingPath) ([]string, error) {\nif !rp.Done() {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/filesystem.go",
"new_path": "pkg/sentry/vfs/filesystem.go",
"diff": "@@ -21,6 +21,7 @@ import (\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport\"\n)\n// A Filesystem is a tree of nodes represented by Dentries, which forms part of\n@@ -460,6 +461,11 @@ type FilesystemImpl interface {\n// RemovexattrAt returns ENOTSUP.\nRemovexattrAt(ctx context.Context, rp *ResolvingPath, name string) error\n+ // BoundEndpointAt returns the Unix socket endpoint bound at the path rp.\n+ //\n+ // - If a non-socket file exists at rp, then BoundEndpointAt returns ECONNREFUSED.\n+ BoundEndpointAt(ctx context.Context, rp *ResolvingPath) (transport.BoundEndpoint, 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@@ -482,7 +488,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: inotify_add_watch(); bind()\n+ // TODO: inotify_add_watch()\n}\n// PrependPathAtVFSRootError is returned by implementations of\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/vfs.go",
"new_path": "pkg/sentry/vfs/vfs.go",
"diff": "@@ -38,6 +38,7 @@ import (\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport\"\n\"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n)\n@@ -230,7 +231,7 @@ func (vfs *VirtualFilesystem) getParentDirAndName(ctx context.Context, creds *au\n}\nif checkInvariants {\nif rp.canHandleError(err) && rp.Done() {\n- panic(fmt.Sprintf(\"%T.GetParentDentryAt() consumed all path components and returned %T\", rp.mount.fs.impl, err))\n+ panic(fmt.Sprintf(\"%T.GetParentDentryAt() consumed all path components and returned %v\", rp.mount.fs.impl, err))\n}\n}\nif !rp.handleError(err) {\n@@ -271,7 +272,7 @@ func (vfs *VirtualFilesystem) LinkAt(ctx context.Context, creds *auth.Credential\n}\nif checkInvariants {\nif rp.canHandleError(err) && rp.Done() {\n- panic(fmt.Sprintf(\"%T.LinkAt() consumed all path components and returned %T\", rp.mount.fs.impl, err))\n+ panic(fmt.Sprintf(\"%T.LinkAt() consumed all path components and returned %v\", rp.mount.fs.impl, err))\n}\n}\nif !rp.handleError(err) {\n@@ -307,7 +308,7 @@ func (vfs *VirtualFilesystem) MkdirAt(ctx context.Context, creds *auth.Credentia\n}\nif checkInvariants {\nif rp.canHandleError(err) && rp.Done() {\n- panic(fmt.Sprintf(\"%T.MkdirAt() consumed all path components and returned %T\", rp.mount.fs.impl, err))\n+ panic(fmt.Sprintf(\"%T.MkdirAt() consumed all path components and returned %v\", rp.mount.fs.impl, err))\n}\n}\nif !rp.handleError(err) {\n@@ -340,7 +341,7 @@ func (vfs *VirtualFilesystem) MknodAt(ctx context.Context, creds *auth.Credentia\n}\nif checkInvariants {\nif rp.canHandleError(err) && rp.Done() {\n- panic(fmt.Sprintf(\"%T.MknodAt() consumed all path components and returned %T\", rp.mount.fs.impl, err))\n+ panic(fmt.Sprintf(\"%T.MknodAt() consumed all path components and returned %v\", rp.mount.fs.impl, err))\n}\n}\nif !rp.handleError(err) {\n@@ -350,6 +351,33 @@ func (vfs *VirtualFilesystem) MknodAt(ctx context.Context, creds *auth.Credentia\n}\n}\n+// BoundEndpointAt gets the bound endpoint at the given path, if one exists.\n+func (vfs *VirtualFilesystem) BoundEndpointAt(ctx context.Context, creds *auth.Credentials, pop *PathOperation) (transport.BoundEndpoint, error) {\n+ if !pop.Path.Begin.Ok() {\n+ if pop.Path.Absolute {\n+ return nil, syserror.ECONNREFUSED\n+ }\n+ return nil, syserror.ENOENT\n+ }\n+ rp := vfs.getResolvingPath(creds, pop)\n+ for {\n+ bep, err := rp.mount.fs.impl.BoundEndpointAt(ctx, rp)\n+ if err == nil {\n+ vfs.putResolvingPath(rp)\n+ return bep, nil\n+ }\n+ if checkInvariants {\n+ if rp.canHandleError(err) && rp.Done() {\n+ panic(fmt.Sprintf(\"%T.BoundEndpointAt() consumed all path components and returned %v\", rp.mount.fs.impl, err))\n+ }\n+ }\n+ if !rp.handleError(err) {\n+ vfs.putResolvingPath(rp)\n+ return nil, err\n+ }\n+ }\n+}\n+\n// OpenAt returns a FileDescription providing access to the file at the given\n// path. A reference is taken on the returned FileDescription.\nfunc (vfs *VirtualFilesystem) OpenAt(ctx context.Context, creds *auth.Credentials, pop *PathOperation, opts *OpenOptions) (*FileDescription, error) {\n@@ -494,7 +522,7 @@ func (vfs *VirtualFilesystem) RenameAt(ctx context.Context, creds *auth.Credenti\n}\nif checkInvariants {\nif rp.canHandleError(err) && rp.Done() {\n- panic(fmt.Sprintf(\"%T.RenameAt() consumed all path components and returned %T\", rp.mount.fs.impl, err))\n+ panic(fmt.Sprintf(\"%T.RenameAt() consumed all path components and returned %v\", rp.mount.fs.impl, err))\n}\n}\nif !rp.handleError(err) {\n@@ -527,7 +555,7 @@ func (vfs *VirtualFilesystem) RmdirAt(ctx context.Context, creds *auth.Credentia\n}\nif checkInvariants {\nif rp.canHandleError(err) && rp.Done() {\n- panic(fmt.Sprintf(\"%T.RmdirAt() consumed all path components and returned %T\", rp.mount.fs.impl, err))\n+ panic(fmt.Sprintf(\"%T.RmdirAt() consumed all path components and returned %v\", rp.mount.fs.impl, err))\n}\n}\nif !rp.handleError(err) {\n@@ -608,7 +636,7 @@ func (vfs *VirtualFilesystem) SymlinkAt(ctx context.Context, creds *auth.Credent\n}\nif checkInvariants {\nif rp.canHandleError(err) && rp.Done() {\n- panic(fmt.Sprintf(\"%T.SymlinkAt() consumed all path components and returned %T\", rp.mount.fs.impl, err))\n+ panic(fmt.Sprintf(\"%T.SymlinkAt() consumed all path components and returned %v\", rp.mount.fs.impl, err))\n}\n}\nif !rp.handleError(err) {\n@@ -640,7 +668,7 @@ func (vfs *VirtualFilesystem) UnlinkAt(ctx context.Context, creds *auth.Credenti\n}\nif checkInvariants {\nif rp.canHandleError(err) && rp.Done() {\n- panic(fmt.Sprintf(\"%T.UnlinkAt() consumed all path components and returned %T\", rp.mount.fs.impl, err))\n+ panic(fmt.Sprintf(\"%T.UnlinkAt() consumed all path components and returned %v\", rp.mount.fs.impl, err))\n}\n}\nif !rp.handleError(err) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/syserror/syserror.go",
"new_path": "pkg/syserror/syserror.go",
"diff": "@@ -27,6 +27,7 @@ import (\nvar (\nE2BIG = error(syscall.E2BIG)\nEACCES = error(syscall.EACCES)\n+ EADDRINUSE = error(syscall.EADDRINUSE)\nEAGAIN = error(syscall.EAGAIN)\nEBADF = error(syscall.EBADF)\nEBADFD = error(syscall.EBADFD)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add BoundEndpointAt filesystem operation.
BoundEndpointAt() is needed to support Unix sockets bound at a
file path, corresponding to BoundEndpoint() in VFS1.
Updates #1476.
PiperOrigin-RevId: 303258251 |
259,884 | 26.03.2020 19:03:47 | 14,400 | 4b0eaecb71c65465d5df39ac4bcadbe5a501c550 | Added FAQ redirect | [
{
"change_type": "MODIFY",
"old_path": "cmd/gvisor-website/main.go",
"new_path": "cmd/gvisor-website/main.go",
"diff": "@@ -30,11 +30,15 @@ import (\n)\nvar redirects = map[string]string{\n+ // Github redirects\n\"/change\": \"https://github.com/google/gvisor\",\n\"/issue\": \"https://github.com/google/gvisor/issues\",\n\"/issue/new\": \"https://github.com/google/gvisor/issues/new\",\n\"/pr\": \"https://github.com/google/gvisor/pulls\",\n+ // For links\n+ \"/faq\": \"/docs/user_guide/faq/\",\n+\n// Redirects to compatibility docs.\n\"/c\": \"/docs/user_guide/compatibility/\",\n\"/c/linux/amd64\": \"/docs/user_guide/compatibility/linux/amd64/\",\n"
}
] | Go | Apache License 2.0 | google/gvisor | Added FAQ redirect |
259,884 | 26.03.2020 20:27:48 | 14,400 | 2c352437734f17e1c051a7a801e501a302635db2 | Updated custom header ids | [
{
"change_type": "MODIFY",
"old_path": "content/docs/user_guide/FAQ.md",
"new_path": "content/docs/user_guide/FAQ.md",
"diff": "@@ -7,7 +7,7 @@ weight = 1000\ngVisor requires Linux {{< required_linux >}} ([older Linux][old-linux]).\n-### What CPU architectures are supported? {#supported-cpu}\n+### What CPU architectures are supported? {#supported-cpus}\ngVisor currently supports [x86_64/AMD64](https://en.wikipedia.org/wiki/X86-64)\ncompatible processors.\n@@ -16,7 +16,7 @@ compatible processors.\nNo. gVisor is capable of running unmodified Linux binaries.\n-### What binary formats does gVisor support? {#supported-binary}\n+### What binary formats does gVisor support? {#supported-binaries}\ngVisor supports Linux\n[ELF](https://en.wikipedia.org/wiki/Executable_and_Linkable_Format) binaries.\n@@ -50,7 +50,7 @@ gVisor requires Linux {{< required_linux >}} ([older Linux][old-linux]).\nThis is tracked in [bug #268](https://gvisor.dev/issue/268).\n-### When I run my container, docker fails with: `flag provided but not defined: -console` {#docker-old}\n+### When I run my container, docker fails with: `flag provided but not defined: -console` {#old-docker}\nYou're using an old version of Docker. See [Docker Quick Start][docker].\n"
}
] | Go | Apache License 2.0 | google/gvisor | Updated custom header ids |
259,885 | 27.03.2020 16:54:45 | 25,200 | f6e4daa67ad5f07ac1bcff33476b4d13f49a69bc | Add vfs.PathnameReachable().
/proc/[pid]/mount* omit mounts whose mount point is outside the chroot, which
is checked (indirectly) via __d_path(). | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/pathname.go",
"new_path": "pkg/sentry/vfs/pathname.go",
"diff": "@@ -90,6 +90,49 @@ loop:\nreturn b.String(), nil\n}\n+// PathnameReachable returns an absolute pathname to vd, consistent with\n+// Linux's __d_path() (as used by seq_path_root()). If vfsroot.Ok() and vd is\n+// not reachable from vfsroot, such that seq_path_root() would return SEQ_SKIP\n+// (causing the entire containing entry to be skipped), PathnameReachable\n+// returns (\"\", nil).\n+func (vfs *VirtualFilesystem) PathnameReachable(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+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+ return \"\", nil\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+ return \"\", nil\n+ default:\n+ return \"\", err\n+ }\n+ }\n+ b.PrependByte('/')\n+ return b.String(), nil\n+}\n+\n// PathnameForGetcwd returns an absolute pathname to vd, consistent with\n// Linux's sys_getcwd().\nfunc (vfs *VirtualFilesystem) PathnameForGetcwd(ctx context.Context, vfsroot, vd VirtualDentry) (string, error) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add vfs.PathnameReachable().
/proc/[pid]/mount* omit mounts whose mount point is outside the chroot, which
is checked (indirectly) via __d_path().
PiperOrigin-RevId: 303434226 |
259,858 | 30.03.2020 12:36:30 | 25,200 | 3fac85da951f9f56d0232718ea7584250cf11f31 | kvm: handle exit reasons even under EINTR.
In the case of other signals (preemption), inject a normal bounce and
defer the signal until the vCPU has been returned from guest mode. | [
{
"change_type": "MODIFY",
"old_path": "pkg/atomicbitops/atomicbitops_noasm.go",
"new_path": "pkg/atomicbitops/atomicbitops_noasm.go",
"diff": "@@ -20,6 +20,7 @@ import (\n\"sync/atomic\"\n)\n+//go:nosplit\nfunc AndUint32(addr *uint32, val uint32) {\nfor {\no := atomic.LoadUint32(addr)\n@@ -30,6 +31,7 @@ func AndUint32(addr *uint32, val uint32) {\n}\n}\n+//go:nosplit\nfunc OrUint32(addr *uint32, val uint32) {\nfor {\no := atomic.LoadUint32(addr)\n@@ -40,6 +42,7 @@ func OrUint32(addr *uint32, val uint32) {\n}\n}\n+//go:nosplit\nfunc XorUint32(addr *uint32, val uint32) {\nfor {\no := atomic.LoadUint32(addr)\n@@ -50,6 +53,7 @@ func XorUint32(addr *uint32, val uint32) {\n}\n}\n+//go:nosplit\nfunc CompareAndSwapUint32(addr *uint32, old, new uint32) (prev uint32) {\nfor {\nprev = atomic.LoadUint32(addr)\n@@ -62,6 +66,7 @@ func CompareAndSwapUint32(addr *uint32, old, new uint32) (prev uint32) {\n}\n}\n+//go:nosplit\nfunc AndUint64(addr *uint64, val uint64) {\nfor {\no := atomic.LoadUint64(addr)\n@@ -72,6 +77,7 @@ func AndUint64(addr *uint64, val uint64) {\n}\n}\n+//go:nosplit\nfunc OrUint64(addr *uint64, val uint64) {\nfor {\no := atomic.LoadUint64(addr)\n@@ -82,6 +88,7 @@ func OrUint64(addr *uint64, val uint64) {\n}\n}\n+//go:nosplit\nfunc XorUint64(addr *uint64, val uint64) {\nfor {\no := atomic.LoadUint64(addr)\n@@ -92,6 +99,7 @@ func XorUint64(addr *uint64, val uint64) {\n}\n}\n+//go:nosplit\nfunc CompareAndSwapUint64(addr *uint64, old, new uint64) (prev uint64) {\nfor {\nprev = atomic.LoadUint64(addr)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/safecopy/safecopy.go",
"new_path": "pkg/safecopy/safecopy.go",
"diff": "@@ -127,10 +127,10 @@ func initializeAddresses() {\nfunc init() {\ninitializeAddresses()\n- if err := ReplaceSignalHandler(syscall.SIGSEGV, reflect.ValueOf(signalHandler).Pointer(), &savedSigSegVHandler); err != nil {\n+ if err := ReplaceSignalHandler(syscall.SIGSEGV, reflect.ValueOf(signalHandler).Pointer(), &savedSigSegVHandler, 0); err != nil {\npanic(fmt.Sprintf(\"Unable to set handler for SIGSEGV: %v\", err))\n}\n- if err := ReplaceSignalHandler(syscall.SIGBUS, reflect.ValueOf(signalHandler).Pointer(), &savedSigBusHandler); err != nil {\n+ if err := ReplaceSignalHandler(syscall.SIGBUS, reflect.ValueOf(signalHandler).Pointer(), &savedSigBusHandler, 0); err != nil {\npanic(fmt.Sprintf(\"Unable to set handler for SIGBUS: %v\", err))\n}\nsyserror.AddErrorUnwrapper(func(e error) (syscall.Errno, bool) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/safecopy/safecopy_unsafe.go",
"new_path": "pkg/safecopy/safecopy_unsafe.go",
"diff": "@@ -324,11 +324,13 @@ func errorFromFaultSignal(addr uintptr, sig int32) error {\n//\n// It stores the value of the previously set handler in previous.\n//\n+// The extraMask parameter is OR'ed into the existing signal handler mask.\n+//\n// This function will be called on initialization in order to install safecopy\n// handlers for appropriate signals. These handlers will call the previous\n// handler however, and if this is function is being used externally then the\n// same courtesy is expected.\n-func ReplaceSignalHandler(sig syscall.Signal, handler uintptr, previous *uintptr) error {\n+func ReplaceSignalHandler(sig syscall.Signal, handler uintptr, previous *uintptr, extraMask uint64) error {\nvar sa struct {\nhandler uintptr\nflags uint64\n@@ -348,10 +350,10 @@ func ReplaceSignalHandler(sig syscall.Signal, handler uintptr, previous *uintptr\nif sa.handler == 0 {\nreturn fmt.Errorf(\"previous handler for signal %x isn't set\", sig)\n}\n-\n*previous = sa.handler\n// Install our own handler.\n+ sa.mask |= extraMask\nsa.handler = handler\nif _, _, e := syscall.RawSyscall6(syscall.SYS_RT_SIGACTION, uintptr(sig), uintptr(unsafe.Pointer(&sa)), 0, maskLen, 0, 0); e != 0 {\nreturn e\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/BUILD",
"new_path": "pkg/sentry/platform/kvm/BUILD",
"diff": "@@ -70,6 +70,7 @@ go_test(\n\"requires-kvm\",\n],\ndeps = [\n+ \"//pkg/procid\",\n\"//pkg/sentry/arch\",\n\"//pkg/sentry/platform\",\n\"//pkg/sentry/platform/kvm/testutil\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/bluepill.go",
"new_path": "pkg/sentry/platform/kvm/bluepill.go",
"diff": "@@ -46,6 +46,14 @@ var (\n// bounceSignalMask has only bounceSignal set.\nbounceSignalMask = uint64(1 << (uint64(bounceSignal) - 1))\n+ // otherSignalsMask includes all other signals that will be cause the\n+ // vCPU to exit during execution.\n+ //\n+ // Currently, this includes the preemption signal and the profiling\n+ // signal. In general, these should be signals whose delivery actually\n+ // influences the way the program executes as the switch can be costly.\n+ otherSignalsMask = uint64(1<<(uint64(syscall.SIGURG)-1)) | uint64(1<<(uint64(syscall.SIGPROF)-1))\n+\n// bounce is the interrupt vector used to return to the kernel.\nbounce = uint32(ring0.VirtualizationException)\n@@ -86,8 +94,8 @@ func (c *vCPU) die(context *arch.SignalContext64, msg string) {\n}\nfunc init() {\n- // Install the handler.\n- if err := safecopy.ReplaceSignalHandler(bluepillSignal, reflect.ValueOf(sighandler).Pointer(), &savedHandler); err != nil {\n+ // Install the handler, masking all signals.\n+ if err := safecopy.ReplaceSignalHandler(bluepillSignal, reflect.ValueOf(sighandler).Pointer(), &savedHandler, ^uint64(0)); err != nil {\npanic(fmt.Sprintf(\"Unable to set handler for signal %d: %v\", bluepillSignal, err))\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/bluepill_unsafe.go",
"new_path": "pkg/sentry/platform/kvm/bluepill_unsafe.go",
"diff": "@@ -24,6 +24,7 @@ import (\n\"syscall\"\n\"unsafe\"\n+ \"gvisor.dev/gvisor/pkg/atomicbitops\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n)\n@@ -58,6 +59,19 @@ func bluepillArchContext(context unsafe.Pointer) *arch.SignalContext64 {\nreturn &((*arch.UContext64)(context).MContext)\n}\n+// injectInterrupt is a helper to inject an interrupt.\n+//\n+//go:nosplit\n+func injectInterrupt(c *vCPU) {\n+ if _, _, errno := syscall.RawSyscall(\n+ syscall.SYS_IOCTL,\n+ uintptr(c.fd),\n+ _KVM_INTERRUPT,\n+ uintptr(unsafe.Pointer(&bounce))); errno != 0 {\n+ throw(\"interrupt injection failed\")\n+ }\n+}\n+\n// bluepillHandler is called from the signal stub.\n//\n// The world may be stopped while this is executing, and it executes on the\n@@ -69,6 +83,9 @@ func bluepillHandler(context unsafe.Pointer) {\n// Sanitize the registers; interrupts must always be disabled.\nc := bluepillArchEnter(bluepillArchContext(context))\n+ // Enable preemption.\n+ c.setSignalMask(true)\n+\n// Increment the number of switches.\natomic.AddUint32(&c.switches, 1)\n@@ -89,6 +106,9 @@ func bluepillHandler(context unsafe.Pointer) {\n// interrupted KVM. Since we're in a signal handler\n// currently, all signals are masked and the signal\n// must have been delivered directly to this thread.\n+ //\n+ // We will not be able to actually do subsequent\n+ // KVM_RUNs until this signal is processed.\ntimeout := syscall.Timespec{}\nsig, _, errno := syscall.RawSyscall6(\nsyscall.SYS_RT_SIGTIMEDWAIT,\n@@ -98,12 +118,24 @@ func bluepillHandler(context unsafe.Pointer) {\n8, // sigset size.\n0, 0)\nif errno == syscall.EAGAIN {\n- continue\n- }\n- if errno != 0 {\n+ // If weren't able to process this signal, then\n+ // it must not have been in the bounceMask. By\n+ // elimination, it must have been the\n+ // preemption signal. We can't process this\n+ // signal right now, so we need to disable\n+ // preemption until the interrupt is actually\n+ // handled.\n+ c.setSignalMask(false)\n+ // Note that there is a waiter for this vCPU.\n+ // This will cause the vCPU to exit at some\n+ // point in the future (releasing the user lock\n+ // and guest mode).\n+ atomicbitops.OrUint32(&c.state, vCPUWaiter)\n+ } else if errno != 0 {\n+ // We only expect success or a timeout.\nthrow(\"error waiting for pending signal\")\n- }\n- if sig != uintptr(bounceSignal) {\n+ } else if sig != uintptr(bounceSignal) {\n+ // Only the bounce should be processed.\nthrow(\"unexpected signal\")\n}\n@@ -114,11 +146,10 @@ func bluepillHandler(context unsafe.Pointer) {\n// ready.\nif c.runData.readyForInterruptInjection == 0 {\nc.runData.requestInterruptWindow = 1\n- continue // Rerun vCPU.\n} else {\n- // Force injection below; the vCPU is ready.\n- c.runData.exitReason = _KVM_EXIT_IRQ_WINDOW_OPEN\n+ injectInterrupt(c)\n}\n+ continue // Rerun vCPU.\ncase syscall.EFAULT:\n// If a fault is not serviceable due to the host\n// backing pages having page permissions, instead of an\n@@ -137,6 +168,30 @@ func bluepillHandler(context unsafe.Pointer) {\n}\nswitch c.runData.exitReason {\n+ case _KVM_EXIT_HLT:\n+ // Copy out registers.\n+ bluepillArchExit(c, bluepillArchContext(context))\n+\n+ // Return to the vCPUReady state; notify any waiters.\n+ user := atomic.LoadUint32(&c.state) & vCPUUser\n+ switch atomic.SwapUint32(&c.state, user) {\n+ case user | vCPUGuest: // Expected case.\n+ case user | vCPUGuest | vCPUWaiter:\n+ c.notify()\n+ default:\n+ throw(\"invalid state\")\n+ }\n+ return\n+ case _KVM_EXIT_IRQ_WINDOW_OPEN:\n+ // Inject an interrupt now.\n+ injectInterrupt(c)\n+ // Clear previous injection request.\n+ c.runData.requestInterruptWindow = 0\n+ case _KVM_EXIT_INTR:\n+ // This is fine, it is the normal exit reason during\n+ // signal delivery. However, we still need to handle\n+ // other potential exit reasons *combined* with EINTR,\n+ // so this switch must be hit even after the above.\ncase _KVM_EXIT_EXCEPTION:\nc.die(bluepillArchContext(context), \"exception\")\nreturn\n@@ -155,20 +210,6 @@ func bluepillHandler(context unsafe.Pointer) {\ncase _KVM_EXIT_DEBUG:\nc.die(bluepillArchContext(context), \"debug\")\nreturn\n- case _KVM_EXIT_HLT:\n- // Copy out registers.\n- bluepillArchExit(c, bluepillArchContext(context))\n-\n- // Return to the vCPUReady state; notify any waiters.\n- user := atomic.LoadUint32(&c.state) & vCPUUser\n- switch atomic.SwapUint32(&c.state, user) {\n- case user | vCPUGuest: // Expected case.\n- case user | vCPUGuest | vCPUWaiter:\n- c.notify()\n- default:\n- throw(\"invalid state\")\n- }\n- return\ncase _KVM_EXIT_MMIO:\n// Increment the fault count.\natomic.AddUint32(&c.faults, 1)\n@@ -200,18 +241,6 @@ func bluepillHandler(context unsafe.Pointer) {\ndata[i] = *b\n}\n}\n- case _KVM_EXIT_IRQ_WINDOW_OPEN:\n- // Interrupt: we must have requested an interrupt\n- // window; set the interrupt line.\n- if _, _, errno := syscall.RawSyscall(\n- syscall.SYS_IOCTL,\n- uintptr(c.fd),\n- _KVM_INTERRUPT,\n- uintptr(unsafe.Pointer(&bounce))); errno != 0 {\n- throw(\"interrupt injection failed\")\n- }\n- // Clear previous injection request.\n- c.runData.requestInterruptWindow = 0\ncase _KVM_EXIT_SHUTDOWN:\nc.die(bluepillArchContext(context), \"shutdown\")\nreturn\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/kvm_const.go",
"new_path": "pkg/sentry/platform/kvm/kvm_const.go",
"diff": "@@ -48,6 +48,7 @@ const (\n_KVM_EXIT_IRQ_WINDOW_OPEN = 0x7\n_KVM_EXIT_SHUTDOWN = 0x8\n_KVM_EXIT_FAIL_ENTRY = 0x9\n+ _KVM_EXIT_INTR = 0xa\n_KVM_EXIT_INTERNAL_ERROR = 0x11\n_KVM_EXIT_SYSTEM_EVENT = 0x18\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/kvm_test.go",
"new_path": "pkg/sentry/platform/kvm/kvm_test.go",
"diff": "@@ -16,12 +16,15 @@ package kvm\nimport (\n\"math/rand\"\n+ \"os\"\n\"reflect\"\n+ \"runtime\"\n\"sync/atomic\"\n\"syscall\"\n\"testing\"\n\"time\"\n+ \"gvisor.dev/gvisor/pkg/procid\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/platform\"\n\"gvisor.dev/gvisor/pkg/sentry/platform/kvm/testutil\"\n@@ -320,15 +323,18 @@ func TestBounce(t *testing.T) {\n})\n}\n-func TestBounceStress(t *testing.T) {\n- applicationTest(t, true, testutil.SpinLoop, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {\n- randomSleep := func() {\n- // O(hundreds of microseconds) is appropriate to ensure\n- // different overlaps and different schedules.\n+// randomSleep is used by some race tests below.\n+//\n+// O(hundreds of microseconds) is appropriate to ensure different overlaps and\n+// different schedules.\n+func randomSleep() {\nif n := rand.Intn(1000); n > 100 {\ntime.Sleep(time.Duration(n) * time.Microsecond)\n}\n}\n+\n+func TestBounceStress(t *testing.T) {\n+ applicationTest(t, true, testutil.SpinLoop, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {\nfor i := 0; i < 1000; i++ {\n// Start an asynchronously executing goroutine that\n// calls Bounce at pseudo-random point in time.\n@@ -355,6 +361,50 @@ func TestBounceStress(t *testing.T) {\n})\n}\n+func TestPreemption(t *testing.T) {\n+ applicationTest(t, true, testutil.SpinLoop, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {\n+ // Lock the main vCPU thread.\n+ runtime.LockOSThread()\n+ pid := os.Getpid()\n+ tid := procid.Current()\n+ running := uint32(1)\n+ defer atomic.StoreUint32(&running, 0)\n+\n+ // Start generating \"preemptions\".\n+ go func() {\n+ for atomic.LoadUint32(&running) != 0 {\n+ // Kick via a preemption: best effort.\n+ syscall.Tgkill(pid, int(tid), syscall.SIGURG)\n+ randomSleep()\n+ }\n+ }()\n+\n+ for i := 0; i < 1000; i++ {\n+ randomSleep()\n+ var si arch.SignalInfo\n+ if _, err := c.SwitchToUser(ring0.SwitchOpts{\n+ Registers: regs,\n+ FloatingPointState: dummyFPState,\n+ PageTables: pt,\n+ }, &si); err != platform.ErrContextInterrupt {\n+ t.Errorf(\"application partial restore: got %v, wanted %v\", err, platform.ErrContextInterrupt)\n+ }\n+ // Was this caused by a preemption signal?\n+ if got := atomic.LoadUint32(&c.state); got&vCPUGuest != 0 && got&vCPUWaiter == 0 {\n+ continue\n+ }\n+ c.unlock()\n+ // Should have dropped from guest mode, processed preemption.\n+ if got := atomic.LoadUint32(&c.state); got != vCPUReady {\n+ t.Errorf(\"vCPU not in ready state: got %v\", got)\n+ }\n+ randomSleep()\n+ c.lock()\n+ }\n+ return false\n+ })\n+}\n+\nfunc TestInvalidate(t *testing.T) {\nvar data uintptr // Used below.\napplicationTest(t, true, testutil.Touch, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine.go",
"new_path": "pkg/sentry/platform/kvm/machine.go",
"diff": "@@ -108,6 +108,9 @@ type vCPU struct {\n// This is a bitmask of the three fields (vCPU*) described above.\nstate uint32\n+ // signalMask is the vCPU signal mask.\n+ signalMask uint64\n+\n// runData for this vCPU.\nrunData *runData\n@@ -121,6 +124,7 @@ type vCPU struct {\n// vCPUArchState is the architecture-specific state.\nvCPUArchState\n+ // dieState is the temporary state associated with throwing exceptions.\ndieState dieState\n}\n@@ -153,11 +157,6 @@ func (m *machine) newVCPU() *vCPU {\nc.CPU.Init(&m.kernel, c)\nm.vCPUsByID[c.id] = c\n- // Ensure the signal mask is correct.\n- if err := c.setSignalMask(); err != nil {\n- panic(fmt.Sprintf(\"error setting signal mask: %v\", err))\n- }\n-\n// Map the run data.\nrunData, err := mapRunData(int(fd))\nif err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine_amd64_unsafe.go",
"new_path": "pkg/sentry/platform/kvm/machine_amd64_unsafe.go",
"diff": "@@ -111,31 +111,6 @@ func (c *vCPU) setSystemTime() error {\nreturn nil\n}\n-// setSignalMask sets the vCPU signal mask.\n-//\n-// This must be called prior to running the vCPU.\n-func (c *vCPU) setSignalMask() error {\n- // The layout of this structure implies that it will not necessarily be\n- // the same layout chosen by the Go compiler. It gets fudged here.\n- var data struct {\n- length uint32\n- mask1 uint32\n- mask2 uint32\n- _ uint32\n- }\n- data.length = 8 // Fixed sigset size.\n- data.mask1 = ^uint32(bounceSignalMask & 0xffffffff)\n- data.mask2 = ^uint32(bounceSignalMask >> 32)\n- if _, _, errno := syscall.RawSyscall(\n- syscall.SYS_IOCTL,\n- uintptr(c.fd),\n- _KVM_SET_SIGNAL_MASK,\n- uintptr(unsafe.Pointer(&data))); errno != 0 {\n- return fmt.Errorf(\"error setting signal mask: %v\", errno)\n- }\n- return nil\n-}\n-\n// setUserRegisters sets user registers in the vCPU.\nfunc (c *vCPU) setUserRegisters(uregs *userRegs) error {\nif _, _, errno := syscall.RawSyscall(\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine_arm64_unsafe.go",
"new_path": "pkg/sentry/platform/kvm/machine_arm64_unsafe.go",
"diff": "@@ -268,32 +268,6 @@ func (c *vCPU) setSystemTime() error {\nreturn nil\n}\n-// setSignalMask sets the vCPU signal mask.\n-//\n-// This must be called prior to running the vCPU.\n-func (c *vCPU) setSignalMask() error {\n- // The layout of this structure implies that it will not necessarily be\n- // the same layout chosen by the Go compiler. It gets fudged here.\n- var data struct {\n- length uint32\n- mask1 uint32\n- mask2 uint32\n- _ uint32\n- }\n- data.length = 8 // Fixed sigset size.\n- data.mask1 = ^uint32(bounceSignalMask & 0xffffffff)\n- data.mask2 = ^uint32(bounceSignalMask >> 32)\n- if _, _, errno := syscall.RawSyscall(\n- syscall.SYS_IOCTL,\n- uintptr(c.fd),\n- _KVM_SET_SIGNAL_MASK,\n- uintptr(unsafe.Pointer(&data))); errno != 0 {\n- return fmt.Errorf(\"error setting signal mask: %v\", errno)\n- }\n-\n- return nil\n-}\n-\n// SwitchToUser unpacks architectural-details.\nfunc (c *vCPU) SwitchToUser(switchOpts ring0.SwitchOpts, info *arch.SignalInfo) (usermem.AccessType, error) {\n// Check for canonical addresses.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine_unsafe.go",
"new_path": "pkg/sentry/platform/kvm/machine_unsafe.go",
"diff": "@@ -87,6 +87,47 @@ func unmapRunData(r *runData) error {\nreturn nil\n}\n+// setSignalMask sets the vCPU signal mask.\n+//\n+// This will be called from the bluepill handler, and therefore must not\n+// perform any allocation.\n+//\n+//go:nosplit\n+func (c *vCPU) setSignalMask(enableOthers bool) {\n+ // The signal mask is either:\n+ // *) Only the bounce signal, which we need to use to execute the\n+ // machine state up until the bounce interrupt can be processed.\n+ // or\n+ // *) All signals, which is the default state unless we need to\n+ // continue execution to exit guest mode (the case above).\n+ mask := bounceSignalMask\n+ if enableOthers {\n+ mask |= otherSignalsMask\n+ }\n+ if c.signalMask == mask {\n+ return // Already set.\n+ }\n+\n+ // The layout of this structure implies that it will not necessarily be\n+ // the same layout chosen by the Go compiler. It gets fudged here.\n+ var data struct {\n+ length uint32\n+ mask1 uint32\n+ mask2 uint32\n+ _ uint32\n+ }\n+ data.length = 8 // Fixed sigset size.\n+ data.mask1 = ^uint32(mask & 0xffffffff)\n+ data.mask2 = ^uint32(mask >> 32)\n+ if _, _, errno := syscall.RawSyscall(\n+ syscall.SYS_IOCTL,\n+ uintptr(c.fd),\n+ _KVM_SET_SIGNAL_MASK,\n+ uintptr(unsafe.Pointer(&data))); errno != 0 {\n+ throw(\"setSignal mask failed\")\n+ }\n+}\n+\n// atomicAddressSpace is an atomic address space pointer.\ntype atomicAddressSpace struct {\npointer unsafe.Pointer\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -444,12 +444,6 @@ func (s *Sandbox) createSandboxProcess(conf *boot.Config, args *Args, startSyncF\nnextFD++\n}\n- // TODO(b/151157106): syscall tests fail by timeout if asyncpreemptoff\n- // isn't set.\n- if conf.Platform == \"kvm\" {\n- cmd.Env = append(cmd.Env, \"GODEBUG=asyncpreemptoff=1\")\n- }\n-\n// The current process' stdio must be passed to the application via the\n// --stdio-fds flag. The stdio of the sandbox process itself must not\n// be connected to the same FDs, otherwise we risk leaking sandbox\n"
}
] | Go | Apache License 2.0 | google/gvisor | kvm: handle exit reasons even under EINTR.
In the case of other signals (preemption), inject a normal bounce and
defer the signal until the vCPU has been returned from guest mode.
PiperOrigin-RevId: 303799678 |
259,975 | 30.03.2020 13:04:44 | 25,200 | e36eccc4b18676e2cb441380d0e4e46f038f638e | BigQuery schema for benchmark-tools dashboard. | [
{
"change_type": "MODIFY",
"old_path": "WORKSPACE",
"new_path": "WORKSPACE",
"diff": "@@ -386,6 +386,49 @@ go_repository(\nversion = \"v1.0.0\",\n)\n+go_repository(\n+ name = \"com_google_cloud_go_bigquery\",\n+ importpath = \"cloud.google.com/go/bigquery\",\n+ sum = \"h1:K2NyuHRuv15ku6eUpe0DQk5ZykPMnSOnvuVf6IHcjaE=\",\n+ version = \"v1.5.0\",\n+)\n+\n+go_repository(\n+ name = \"org_golang_google_api\",\n+ importpath = \"google.golang.org/api\",\n+ sum = \"h1:jz2KixHX7EcCPiQrySzPdnYT7DbINAypCqKZ1Z7GM40=\",\n+ version = \"v0.20.0\",\n+)\n+\n+# BigQuery Dependencies for Benchmarks\n+go_repository(\n+ name = \"com_google_cloud_go\",\n+ importpath = \"cloud.google.com/go\",\n+ sum = \"h1:eoz/lYxKSL4CNAiaUJ0ZfD1J3bfMYbU5B3rwM1C1EIU=\",\n+ version = \"v0.55.0\",\n+)\n+\n+go_repository(\n+ name = \"com_github_googleapis_gax_go_v2\",\n+ importpath = \"github.com/googleapis/gax-go/v2\",\n+ sum = \"h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM=\",\n+ version = \"v2.0.5\",\n+)\n+\n+go_repository(\n+ name = \"io_opencensus_go\",\n+ importpath = \"go.opencensus.io\",\n+ sum = \"h1:8sGtKOrtQqkN1bp2AtX+misvLIlOmsEsNd+9NIcPEm8=\",\n+ version = \"v0.22.3\",\n+)\n+\n+go_repository(\n+ name = \"com_github_golang_groupcache\",\n+ importpath = \"github.com/golang/groupcache\",\n+ sum = \"h1:1r7pUrabqp18hOBcwBwiTsbnFeTZHV9eER/QT5JVZxY=\",\n+ version = \"v0.0.0-20200121045136-8c9f03a8e57e\",\n+)\n+\n# System Call test dependencies.\nhttp_archive(\nname = \"com_google_absl\",\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tools/bigquery/BUILD",
"diff": "+load(\"//tools:defs.bzl\", \"go_library\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_library(\n+ name = \"bigquery\",\n+ testonly = 1,\n+ srcs = [\"bigquery.go\"],\n+ deps = [\"@com_google_cloud_go_bigquery//:go_default_library\"],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tools/bigquery/bigquery.go",
"diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// Package bigquery defines a BigQuery schema for benchmarks.\n+//\n+// This package contains a schema for BigQuery and methods for publishing\n+// benchmark data into tables.\n+package bigquery\n+\n+import (\n+ \"context\"\n+ \"fmt\"\n+ \"strings\"\n+ \"time\"\n+\n+ bq \"cloud.google.com/go/bigquery\"\n+)\n+\n+// Benchmark is the top level structure of recorded benchmark data. BigQuery\n+// will infer the schema from this.\n+type Benchmark struct {\n+ Name string `bq:\"name\"`\n+ Timestamp time.Time `bq:\"timestamp\"`\n+ Official bool `bq:\"official\"`\n+ Metric []*Metric `bq:\"metric\"`\n+ Metadata *Metadata `bq:\"metadata\"`\n+}\n+\n+// Metric holds the actual metric data and unit information for this benchmark.\n+type Metric struct {\n+ Name string `bq:\"name\"`\n+ Unit string `bq:\"unit\"`\n+ Sample float64 `bq:\"sample\"`\n+}\n+\n+// Metadata about this benchmark.\n+type Metadata struct {\n+ CL string `bq:\"changelist\"`\n+ IterationID string `bq:\"iteration_id\"`\n+ PendingCL string `bq:\"pending_cl\"`\n+ Workflow string `bq:\"workflow\"`\n+ Platform string `bq:\"platform\"`\n+ Gofer string `bq:\"gofer\"`\n+}\n+\n+// InitBigQuery initializes a BigQuery dataset/table in the project. If the dataset/table already exists, it is not duplicated.\n+func InitBigQuery(ctx context.Context, projectID, datasetID, tableID string) error {\n+ client, err := bq.NewClient(ctx, projectID)\n+ if err != nil {\n+ return fmt.Errorf(\"failed to initialize client on project %s: %v\", projectID, err)\n+ }\n+ defer client.Close()\n+\n+ dataset := client.Dataset(datasetID)\n+ if err := dataset.Create(ctx, nil); err != nil && !checkDuplicateError(err) {\n+ return fmt.Errorf(\"failed to create dataset: %s: %v\", datasetID, err)\n+ }\n+\n+ table := dataset.Table(tableID)\n+ schema, err := bq.InferSchema(Benchmark{})\n+ if err != nil {\n+ return fmt.Errorf(\"failed to infer schema: %v\", err)\n+ }\n+\n+ if err := table.Create(ctx, &bq.TableMetadata{Schema: schema}); err != nil && !checkDuplicateError(err) {\n+ return fmt.Errorf(\"failed to create table: %s: %v\", tableID, err)\n+ }\n+ return nil\n+}\n+\n+// AddMetric adds a metric to an existing Benchmark.\n+func (bm *Benchmark) AddMetric(metricName, unit string, sample float64) {\n+ m := &Metric{\n+ Name: metricName,\n+ Unit: unit,\n+ Sample: sample,\n+ }\n+ bm.Metric = append(bm.Metric, m)\n+}\n+\n+// NewBenchmark initializes a new benchmark.\n+func NewBenchmark(name string, official bool) *Benchmark {\n+ return &Benchmark{\n+ Name: name,\n+ Timestamp: time.Now().UTC(),\n+ Official: official,\n+ Metric: make([]*Metric, 0),\n+ }\n+}\n+\n+// SendBenchmarks sends the slice of benchmarks to the BigQuery dataset/table.\n+func SendBenchmarks(ctx context.Context, benchmarks []*Benchmark, projectID, datasetID, tableID string) error {\n+ client, err := bq.NewClient(ctx, projectID)\n+ if err != nil {\n+ return fmt.Errorf(\"Failed to initialize client on project: %s: %v\", projectID, err)\n+ }\n+ defer client.Close()\n+\n+ uploader := client.Dataset(datasetID).Table(tableID).Uploader()\n+ if err = uploader.Put(ctx, benchmarks); err != nil {\n+ return fmt.Errorf(\"failed to upload benchmarks to proejct %s, table %s.%s: %v\", projectID, datasetID, tableID, err)\n+ }\n+\n+ return nil\n+}\n+\n+// BigQuery will error \"409\" for duplicate tables and datasets.\n+func checkDuplicateError(err error) bool {\n+ return strings.Contains(err.Error(), \"googleapi: Error 409: Already Exists\")\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/nogo.json",
"new_path": "tools/nogo.json",
"diff": "\"/com_github_vishvananda_netlink/route_linux.go\": \"allowed: false positive\",\n\"/external/bazel_gazelle/cmd/gazelle/.*\": \"allowed: false positive\",\n\"/org_golang_x_tools/go/packages/golist.go\": \"allowed: runtime internals\",\n- \"/pkg/sentry/platform/kvm/kvm_test.go\": \"allowed: intentional\"\n+ \"/pkg/sentry/platform/kvm/kvm_test.go\": \"allowed: intentional\",\n+ \"/tools/bigquery/bigquery.go\": \"allowed: false positive\",\n+ \"/external/io_opencensus_go/tag/map_codec.go\": \"allowed: false positive\"\n}\n},\n\"printf\": {\n"
}
] | Go | Apache License 2.0 | google/gvisor | BigQuery schema for benchmark-tools dashboard.
PiperOrigin-RevId: 303805784 |
259,881 | 30.03.2020 14:37:17 | 25,200 | 32a133537e61bbceb6a0a16c95815495d8f17a35 | Add AMD Rome CPUID flag.
This flag is set on Rome CPUs, but it is not documented. | [
{
"change_type": "MODIFY",
"old_path": "pkg/cpuid/cpuid_x86.go",
"new_path": "pkg/cpuid/cpuid_x86.go",
"diff": "@@ -235,7 +235,9 @@ const (\nX86FeaturePERFCTR_TSC\nX86FeaturePERFCTR_LLC\nX86FeatureMWAITX\n- // ECX[31:30] are reserved.\n+ // TODO(b/152776797): Some CPUs set this but it is not documented anywhere.\n+ X86FeatureBlock5Bit30\n+ _ // ecx bit 31 is reserved.\n)\n// Block 6 constants are the extended feature bits in\n@@ -438,6 +440,9 @@ var x86FeatureParseOnlyStrings = map[Feature]string{\n// Block 3.\nX86FeaturePREFETCHWT1: \"prefetchwt1\",\n+\n+ // Block 5.\n+ X86FeatureBlock5Bit30: \"block5_bit30\",\n}\n// intelCacheDescriptors describe the caches and TLBs on the system. They are\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add AMD Rome CPUID flag.
This flag is set on Rome CPUs, but it is not documented.
PiperOrigin-RevId: 303825532 |
259,974 | 20.03.2020 08:45:07 | 0 | 8ce5b569714351f9f2f7fc48b0ff0bebbdb018ee | Cleanup for syscall tests on arm64. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/getrandom.cc",
"new_path": "test/syscalls/linux/getrandom.cc",
"diff": "@@ -29,6 +29,8 @@ namespace {\n#define SYS_getrandom 318\n#elif defined(__i386__)\n#define SYS_getrandom 355\n+#elif defined(__aarch64__)\n+#define SYS_getrandom 278\n#else\n#error \"Unknown architecture\"\n#endif\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/lseek.cc",
"new_path": "test/syscalls/linux/lseek.cc",
"diff": "@@ -53,7 +53,7 @@ TEST(LseekTest, NegativeOffset) {\n// A 32-bit off_t is not large enough to represent an offset larger than\n// maximum file size on standard file systems, so it isn't possible to cause\n// overflow.\n-#ifdef __x86_64__\n+#if defined(__x86_64__) || defined(__aarch64__)\nTEST(LseekTest, Overflow) {\n// HA! Classic Linux. We really should have an EOVERFLOW\n// here, since we're seeking to something that cannot be\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/mlock.cc",
"new_path": "test/syscalls/linux/mlock.cc",
"diff": "@@ -199,8 +199,10 @@ TEST(MunlockallTest, Basic) {\n}\n#ifndef SYS_mlock2\n-#ifdef __x86_64__\n+#if defined(__x86_64__)\n#define SYS_mlock2 325\n+#elif defined(__aarch64__)\n+#define SYS_mlock2 284\n#endif\n#endif\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/mmap.cc",
"new_path": "test/syscalls/linux/mmap.cc",
"diff": "@@ -361,7 +361,7 @@ TEST_F(MMapTest, MapFixed) {\n}\n// 64-bit addresses work too\n-#ifdef __x86_64__\n+#if defined(__x86_64__) || defined(__aarch64__)\nTEST_F(MMapTest, MapFixed64) {\nEXPECT_THAT(Map(0x300000000000, kPageSize, PROT_NONE,\nMAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0),\n@@ -571,6 +571,12 @@ const uint8_t machine_code[] = {\n0xb8, 0x2a, 0x00, 0x00, 0x00, // movl $42, %eax\n0xc3, // retq\n};\n+#elif defined(__aarch64__)\n+const uint8_t machine_code[] = {\n+ 0x40, 0x05, 0x80, 0x52, // mov w0, #42\n+ 0xc0, 0x03, 0x5f, 0xd6, // ret\n+};\n+#endif\n// PROT_EXEC allows code execution\nTEST_F(MMapTest, ProtExec) {\n@@ -605,7 +611,6 @@ TEST_F(MMapTest, NoProtExecDeath) {\nEXPECT_EXIT(func(), ::testing::KilledBySignal(SIGSEGV), \"\");\n}\n-#endif\nTEST_F(MMapTest, NoExceedLimitData) {\nvoid* prevbrk;\n@@ -1644,6 +1649,7 @@ TEST(MMapNoFixtureTest, MapReadOnlyAfterCreateWriteOnly) {\n}\n// Conditional on MAP_32BIT.\n+// This flag is supported only on x86-64, for 64-bit programs.\n#ifdef __x86_64__\nTEST(MMapNoFixtureTest, Map32Bit) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Cleanup for syscall tests on arm64.
Signed-off-by: Haibo Xu <[email protected]>
Change-Id: I8008c0375fc7e23225a21026f359e78e691729e5 |
259,975 | 31.03.2020 16:16:45 | 25,200 | 57e67e32b59a30365a79f6dceb3e0cb772407029 | Debug script issues on Kokoro. | [
{
"change_type": "MODIFY",
"old_path": "scripts/benchmark.sh",
"new_path": "scripts/benchmark.sh",
"diff": "@@ -20,6 +20,8 @@ source $(dirname $0)/common.sh\n# variable for authentication.\nexport GOOGLE_APPLICATION_CREDENTIALS=\"${KOKORO_KEYSTORE_DIR}/${GCLOUD_CREDENTIALS}\"\n+which gcloud\n+\ngcloud auth activate-service-account \\\n--key-file \"${GOOGLE_APPLICATION_CREDENTIALS}\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | Debug script issues on Kokoro.
PiperOrigin-RevId: 304068950 |
259,974 | 28.02.2020 09:14:57 | 0 | c71e97784cfc57a0664a07cb798aca3d39d6bb11 | Enable rseq syscall test on arm64. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/rseq/BUILD",
"new_path": "test/syscalls/linux/rseq/BUILD",
"diff": "# This package contains a standalone rseq test binary. This binary must not\n# depend on libc, which might use rseq itself.\n-load(\"//tools:defs.bzl\", \"cc_flags_supplier\", \"cc_library\", \"cc_toolchain\")\n+load(\"//tools:defs.bzl\", \"cc_flags_supplier\", \"cc_library\", \"cc_toolchain\", \"select_arch\")\npackage(licenses = [\"notice\"])\n@@ -9,32 +9,35 @@ genrule(\nname = \"rseq_binary\",\nsrcs = [\n\"critical.h\",\n- \"critical.S\",\n+ \"critical_amd64.S\",\n+ \"critical_arm64.S\",\n\"rseq.cc\",\n\"syscalls.h\",\n- \"start.S\",\n+ \"start_amd64.S\",\n+ \"start_arm64.S\",\n\"test.h\",\n\"types.h\",\n\"uapi.h\",\n],\nouts = [\"rseq\"],\n- cmd = \" \".join([\n- \"$(CC)\",\n- \"$(CC_FLAGS) \",\n- \"-I.\",\n- \"-Wall\",\n- \"-Werror\",\n- \"-O2\",\n- \"-std=c++17\",\n- \"-static\",\n- \"-nostdlib\",\n- \"-ffreestanding\",\n- \"-o\",\n- \"$(location rseq)\",\n- \"$(location critical.S)\",\n+ cmd = \"$(CC) \" +\n+ \"$(CC_FLAGS) \" +\n+ \"-I. \" +\n+ \"-Wall \" +\n+ \"-Werror \" +\n+ \"-O2 \" +\n+ \"-std=c++17 \" +\n+ \"-static \" +\n+ \"-nostdlib \" +\n+ \"-ffreestanding \" +\n+ \"-o \" +\n+ \"$(location rseq) \" +\n+ select_arch(\n+ amd64 = \"$(location critical_amd64.S) $(location start_amd64.S) \",\n+ arm64 = \"$(location critical_arm64.S) $(location start_arm64.S) \",\n+ no_match_error = \"unsupported architecture\",\n+ ) +\n\"$(location rseq.cc)\",\n- \"$(location start.S)\",\n- ]),\ntoolchains = [\ncc_toolchain,\n\":no_pie_cc_flags\",\n"
},
{
"change_type": "RENAME",
"old_path": "test/syscalls/linux/rseq/critical.S",
"new_path": "test/syscalls/linux/rseq/critical_amd64.S",
"diff": ""
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/rseq/critical_arm64.S",
"diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// Restartable sequences critical sections.\n+\n+// Loops continuously until aborted.\n+//\n+// void rseq_loop(struct rseq* r, struct rseq_cs* cs)\n+\n+ .text\n+ .globl rseq_loop\n+ .type rseq_loop, @function\n+\n+rseq_loop:\n+ b begin\n+\n+ // Abort block before the critical section.\n+ // Abort signature.\n+ .byte 0x90, 0x90, 0x90, 0x90\n+ .globl rseq_loop_early_abort\n+rseq_loop_early_abort:\n+ ret\n+\n+begin:\n+ // r->rseq_cs = cs\n+ str x1, [x0, #8]\n+\n+ // N.B. rseq_cs will be cleared by any preempt, even outside the critical\n+ // section. Thus it must be set in or immediately before the critical section\n+ // to ensure it is not cleared before the section begins.\n+ .globl rseq_loop_start\n+rseq_loop_start:\n+ b rseq_loop_start\n+\n+ // \"Pre-commit\": extra instructions inside the critical section. These are\n+ // used as the abort point in TestAbortPreCommit, which is not valid.\n+ .globl rseq_loop_pre_commit\n+rseq_loop_pre_commit:\n+ // Extra abort signature + nop for TestAbortPostCommit.\n+ .byte 0x90, 0x90, 0x90, 0x90\n+ nop\n+\n+ // \"Post-commit\": never reached in this case.\n+ .globl rseq_loop_post_commit\n+rseq_loop_post_commit:\n+\n+ // Abort signature.\n+ .byte 0x90, 0x90, 0x90, 0x90\n+\n+ .globl rseq_loop_abort\n+rseq_loop_abort:\n+ ret\n+\n+ .size rseq_loop,.-rseq_loop\n+ .section .note.GNU-stack,\"\",@progbits\n"
},
{
"change_type": "RENAME",
"old_path": "test/syscalls/linux/rseq/start.S",
"new_path": "test/syscalls/linux/rseq/start_amd64.S",
"diff": ""
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/rseq/start_arm64.S",
"diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+\n+ .text\n+ .align 4\n+ .type _start,@function\n+ .globl _start\n+\n+_start:\n+ mov x29, sp\n+ bl __init\n+ wfi\n+\n+ .size _start,.-_start\n+ .section .note.GNU-stack,\"\",@progbits\n+\n+ .text\n+ .globl raw_syscall\n+ .type raw_syscall, @function\n+\n+raw_syscall:\n+ mov x8,x0 // syscall #\n+ mov x0,x1 // arg0\n+ mov x1,x2 // arg1\n+ mov x2,x3 // arg2\n+ mov x3,x4 // arg3\n+ mov x4,x5 // arg4\n+ mov x5,x6 // arg5\n+ svc #0\n+ ret\n+\n+ .size raw_syscall,.-raw_syscall\n+ .section .note.GNU-stack,\"\",@progbits\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/rseq/syscalls.h",
"new_path": "test/syscalls/linux/rseq/syscalls.h",
"diff": "#include \"test/syscalls/linux/rseq/types.h\"\n-#ifdef __x86_64__\n// Syscall numbers.\n+#if defined(__x86_64__)\nconstexpr int kGetpid = 39;\nconstexpr int kExitGroup = 231;\n+#elif defined(__aarch64__)\n+constexpr int kGetpid = 172;\n+constexpr int kExitGroup = 94;\n#else\n#error \"Unknown architecture\"\n#endif\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/rseq/uapi.h",
"new_path": "test/syscalls/linux/rseq/uapi.h",
"diff": "// User-kernel ABI for restartable sequences.\n-#ifdef __x86_64__\n// Syscall numbers.\n+#if defined(__x86_64__)\nconstexpr int kRseqSyscall = 334;\n+#elif defined(__aarch64__)\n+constexpr int kRseqSyscall = 293;\n#else\n#error \"Unknown architecture\"\n#endif // __x86_64__\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enable rseq syscall test on arm64.
Signed-off-by: Haibo Xu <[email protected]>
Change-Id: If30154a2d73e98f211cfe589853b232019b9e130 |
259,860 | 31.03.2020 19:15:55 | 25,200 | 639d94f9f71b43e86320a6e9157c932f5d7936a7 | Add socket filesystem and global disconnected socket mount for VFS2.
A socket mount where anonymous sockets will reside is added to the
VirtualFilesystem. Socketfs is built on top of kernfs.
Updates | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fsimpl/sockfs/BUILD",
"diff": "+load(\"//tools:defs.bzl\", \"go_library\")\n+\n+licenses([\"notice\"])\n+\n+go_library(\n+ name = \"sockfs\",\n+ srcs = [\"sockfs.go\"],\n+ visibility = [\"//pkg/sentry:internal\"],\n+ deps = [\n+ \"//pkg/context\",\n+ \"//pkg/sentry/fsimpl/kernfs\",\n+ \"//pkg/sentry/kernel/auth\",\n+ \"//pkg/sentry/vfs\",\n+ \"//pkg/syserror\",\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fsimpl/sockfs/sockfs.go",
"diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// Package sockfs provides a filesystem implementation for anonymous sockets.\n+package sockfs\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+)\n+\n+// NewFilesystem creates a new sockfs filesystem.\n+//\n+// Note that there should only ever be one instance of sockfs.Filesystem,\n+// backing a global socket mount.\n+func NewFilesystem(vfsObj *vfs.VirtualFilesystem) *vfs.Filesystem {\n+ fs, _, err := filesystemType{}.GetFilesystem(nil, vfsObj, nil, \"\", vfs.GetFilesystemOptions{})\n+ if err != nil {\n+ panic(\"failed to create sockfs filesystem\")\n+ }\n+ return fs\n+}\n+\n+// filesystemType implements vfs.FilesystemType.\n+type filesystemType struct{}\n+\n+// GetFilesystem implements FilesystemType.GetFilesystem.\n+func (fsType filesystemType) GetFilesystem(_ context.Context, vfsObj *vfs.VirtualFilesystem, _ *auth.Credentials, _ string, _ vfs.GetFilesystemOptions) (*vfs.Filesystem, *vfs.Dentry, error) {\n+ fs := &filesystem{}\n+ fs.Init(vfsObj, fsType)\n+ return fs.VFSFilesystem(), nil, nil\n+}\n+\n+// Name implements FilesystemType.Name.\n+//\n+// Note that registering sockfs is unnecessary, except for the fact that it\n+// will not show up under /proc/filesystems as a result. This is a very minor\n+// discrepancy from Linux.\n+func (filesystemType) Name() string {\n+ return \"sockfs\"\n+}\n+\n+// filesystem implements vfs.FilesystemImpl.\n+type filesystem struct {\n+ kernfs.Filesystem\n+}\n+\n+// inode implements kernfs.Inode.\n+type inode struct {\n+ kernfs.InodeNotDirectory\n+ kernfs.InodeNotSymlink\n+ kernfs.InodeAttrs\n+ kernfs.InodeNoopRefCount\n+}\n+\n+// Open implements kernfs.Inode.Open.\n+func (i *inode) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n+ return nil, syserror.ENXIO\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/BUILD",
"new_path": "pkg/sentry/kernel/BUILD",
"diff": "@@ -169,6 +169,7 @@ go_library(\n\"//pkg/sentry/fs/lock\",\n\"//pkg/sentry/fs/timerfd\",\n\"//pkg/sentry/fsbridge\",\n+ \"//pkg/sentry/fsimpl/sockfs\",\n\"//pkg/sentry/hostcpu\",\n\"//pkg/sentry/inet\",\n\"//pkg/sentry/kernel/auth\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/kernel.go",
"new_path": "pkg/sentry/kernel/kernel.go",
"diff": "@@ -50,6 +50,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n\"gvisor.dev/gvisor/pkg/sentry/fs/timerfd\"\n\"gvisor.dev/gvisor/pkg/sentry/fsbridge\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/sockfs\"\n\"gvisor.dev/gvisor/pkg/sentry/hostcpu\"\n\"gvisor.dev/gvisor/pkg/sentry/inet\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n@@ -225,6 +226,11 @@ type Kernel struct {\n// by extMu.\nnextSocketEntry uint64\n+ // socketMount is a disconnected vfs.Mount, not included in k.vfs,\n+ // representing a sockfs.filesystem. socketMount is used to back\n+ // VirtualDentries representing anonymous sockets.\n+ socketMount *vfs.Mount\n+\n// deviceRegistry is used to save/restore device.SimpleDevices.\ndeviceRegistry struct{} `state:\".(*device.Registry)\"`\n@@ -348,6 +354,19 @@ func (k *Kernel) Init(args InitKernelArgs) error {\nk.monotonicClock = &timekeeperClock{tk: args.Timekeeper, c: sentrytime.Monotonic}\nk.futexes = futex.NewManager()\nk.netlinkPorts = port.New()\n+ if VFS2Enabled {\n+ if err := k.vfs.Init(); err != nil {\n+ return fmt.Errorf(\"failed to initialize VFS: %v\", err)\n+ }\n+ fs := sockfs.NewFilesystem(&k.vfs)\n+ // NewDisconnectedMount will take an additional reference on fs.\n+ defer fs.DecRef()\n+ sm, err := k.vfs.NewDisconnectedMount(fs, nil, &vfs.MountOptions{})\n+ if err != nil {\n+ return fmt.Errorf(\"failed to initialize socket mount: %v\", err)\n+ }\n+ k.socketMount = sm\n+ }\nreturn nil\n}\n@@ -1452,6 +1471,11 @@ func (k *Kernel) ListSockets() []*SocketEntry {\nreturn socks\n}\n+// SocketMount returns the global socket mount.\n+func (k *Kernel) SocketMount() *vfs.Mount {\n+ return k.socketMount\n+}\n+\n// supervisorContext is a privileged context.\ntype supervisorContext struct {\ncontext.NoopSleeper\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_unix.cc",
"new_path": "test/syscalls/linux/socket_unix.cc",
"diff": "@@ -257,6 +257,8 @@ TEST_P(UnixSocketPairTest, ShutdownWrite) {\nTEST_P(UnixSocketPairTest, SocketReopenFromProcfs) {\n// TODO(b/122310852): We should be returning ENXIO and NOT EIO.\n+ // TODO(github.dev/issue/1624): This should be resolved in VFS2. Verify\n+ // that this is the case and delete the SKIP_IF once we delete VFS1.\nSKIP_IF(IsRunningOnGvisor());\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add socket filesystem and global disconnected socket mount for VFS2.
A socket mount where anonymous sockets will reside is added to the
VirtualFilesystem. Socketfs is built on top of kernfs.
Updates #1476, #1478, #1484, #1485.
PiperOrigin-RevId: 304095251 |
259,860 | 01.04.2020 07:56:05 | 25,200 | d01a8ca3473bfbc7a5eb8da5ea662925e5f2673d | Add FileDescription interface for socket files.
Refactor the existing socket interface to share methods between VFS1 and VFS2.
The method signatures do not contain anything filesystem-related, so they don't
need to be re-defined for VFS2.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/BUILD",
"new_path": "pkg/sentry/socket/BUILD",
"diff": "@@ -16,6 +16,7 @@ go_library(\n\"//pkg/sentry/kernel\",\n\"//pkg/sentry/kernel/time\",\n\"//pkg/sentry/socket/unix/transport\",\n+ \"//pkg/sentry/vfs\",\n\"//pkg/syserr\",\n\"//pkg/tcpip\",\n\"//pkg/usermem\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/socket.go",
"new_path": "pkg/sentry/socket/socket.go",
"diff": "@@ -31,6 +31,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\nktime \"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserr\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n@@ -48,11 +49,25 @@ func (c *ControlMessages) Release() {\nc.Unix.Release()\n}\n-// Socket is the interface containing socket syscalls used by the syscall layer\n-// to redirect them to the appropriate implementation.\n+// Socket is an interface combining fs.FileOperations and SocketOps,\n+// representing a VFS1 socket file.\ntype Socket interface {\nfs.FileOperations\n+ SocketOps\n+}\n+\n+// SocketVFS2 is an interface combining vfs.FileDescription and SocketOps,\n+// representing a VFS2 socket file.\n+type SocketVFS2 interface {\n+ vfs.FileDescriptionImpl\n+ SocketOps\n+}\n+// SocketOps is the interface containing socket syscalls used by the syscall\n+// layer to redirect them to the appropriate implementation.\n+//\n+// It is implemented by both Socket and SocketVFS2.\n+type SocketOps interface {\n// Connect implements the connect(2) linux syscall.\nConnect(t *kernel.Task, sockaddr []byte, blocking bool) *syserr.Error\n@@ -153,6 +168,8 @@ var families = make(map[int][]Provider)\n// RegisterProvider registers the provider of a given address family so that\n// sockets of that type can be created via socket() and/or socketpair()\n// syscalls.\n+//\n+// This should only be called during the initialization of the address family.\nfunc RegisterProvider(family int, provider Provider) {\nfamilies[family] = append(families[family], provider)\n}\n@@ -216,6 +233,72 @@ func NewDirent(ctx context.Context, d *device.Device) *fs.Dirent {\nreturn fs.NewDirent(ctx, inode, fmt.Sprintf(\"socket:[%d]\", ino))\n}\n+// ProviderVFS2 is the vfs2 interface implemented by providers of sockets for\n+// specific address families (e.g., AF_INET).\n+type ProviderVFS2 interface {\n+ // Socket creates a new socket.\n+ //\n+ // If a nil Socket _and_ a nil error is returned, it means that the\n+ // protocol is not supported. A non-nil error should only be returned\n+ // if the protocol is supported, but an error occurs during creation.\n+ Socket(t *kernel.Task, stype linux.SockType, protocol int) (*vfs.FileDescription, *syserr.Error)\n+\n+ // Pair creates a pair of connected sockets.\n+ //\n+ // See Socket for error information.\n+ Pair(t *kernel.Task, stype linux.SockType, protocol int) (*vfs.FileDescription, *vfs.FileDescription, *syserr.Error)\n+}\n+\n+// familiesVFS2 holds a map of all known address families and their providers.\n+var familiesVFS2 = make(map[int][]ProviderVFS2)\n+\n+// RegisterProviderVFS2 registers the provider of a given address family so that\n+// sockets of that type can be created via socket() and/or socketpair()\n+// syscalls.\n+//\n+// This should only be called during the initialization of the address family.\n+func RegisterProviderVFS2(family int, provider ProviderVFS2) {\n+ familiesVFS2[family] = append(familiesVFS2[family], provider)\n+}\n+\n+// NewVFS2 creates a new socket with the given family, type and protocol.\n+func NewVFS2(t *kernel.Task, family int, stype linux.SockType, protocol int) (*vfs.FileDescription, *syserr.Error) {\n+ for _, p := range familiesVFS2[family] {\n+ s, err := p.Socket(t, stype, protocol)\n+ if err != nil {\n+ return nil, err\n+ }\n+ if s != nil {\n+ // TODO: Add vfs2 sockets to global socket table.\n+ return s, nil\n+ }\n+ }\n+\n+ return nil, syserr.ErrAddressFamilyNotSupported\n+}\n+\n+// PairVFS2 creates a new connected socket pair with the given family, type and\n+// protocol.\n+func PairVFS2(t *kernel.Task, family int, stype linux.SockType, protocol int) (*vfs.FileDescription, *vfs.FileDescription, *syserr.Error) {\n+ providers, ok := familiesVFS2[family]\n+ if !ok {\n+ return nil, nil, syserr.ErrAddressFamilyNotSupported\n+ }\n+\n+ for _, p := range providers {\n+ s1, s2, err := p.Pair(t, stype, protocol)\n+ if err != nil {\n+ return nil, nil, err\n+ }\n+ if s1 != nil && s2 != nil {\n+ // TODO: Add vfs2 sockets to global socket table.\n+ return s1, s2, nil\n+ }\n+ }\n+\n+ return nil, nil, syserr.ErrSocketNotSupported\n+}\n+\n// SendReceiveTimeout stores timeouts for send and receive calls.\n//\n// It is meant to be embedded into Socket implementations to help satisfy the\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add FileDescription interface for socket files.
Refactor the existing socket interface to share methods between VFS1 and VFS2.
The method signatures do not contain anything filesystem-related, so they don't
need to be re-defined for VFS2.
Updates #1476, #1478, #1484, #1485.
PiperOrigin-RevId: 304184545 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.