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
|
---|---|---|---|---|---|---|---|---|---|
260,001 | 24.10.2020 12:01:52 | 25,200 | 73a18635385d6a90942370e15fe2cbeb2a5a4386 | Implement Seek in verity fs | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/verity/filesystem.go",
"new_path": "pkg/sentry/fsimpl/verity/filesystem.go",
"diff": "@@ -365,6 +365,7 @@ func (fs *filesystem) verifyStat(ctx context.Context, d *dentry, stat linux.Stat\nd.mode = uint32(stat.Mode)\nd.uid = stat.UID\nd.gid = stat.GID\n+ d.size = uint32(size)\nreturn nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/verity/verity.go",
"new_path": "pkg/sentry/fsimpl/verity/verity.go",
"diff": "@@ -23,6 +23,7 @@ package verity\nimport (\n\"fmt\"\n+ \"math\"\n\"strconv\"\n\"sync/atomic\"\n@@ -290,11 +291,12 @@ type dentry struct {\n// fs is the owning filesystem. fs is immutable.\nfs *filesystem\n- // mode, uid and gid are the file mode, owner, and group of the file in\n- // the underlying file system.\n+ // mode, uid, gid and size are the file mode, owner, group, and size of\n+ // the file in the underlying file system.\nmode uint32\nuid uint32\ngid uint32\n+ size uint32\n// parent is the dentry corresponding to this dentry's parent directory.\n// name is this dentry's name in parent. If this dentry is a filesystem\n@@ -550,6 +552,32 @@ func (fd *fileDescription) SetStat(ctx context.Context, opts vfs.SetStatOptions)\nreturn syserror.EPERM\n}\n+// Seek implements vfs.FileDescriptionImpl.Seek.\n+func (fd *fileDescription) Seek(ctx context.Context, offset int64, whence int32) (int64, error) {\n+ fd.mu.Lock()\n+ defer fd.mu.Unlock()\n+ n := int64(0)\n+ switch whence {\n+ case linux.SEEK_SET:\n+ // use offset as specified\n+ case linux.SEEK_CUR:\n+ n = fd.off\n+ case linux.SEEK_END:\n+ n = int64(fd.d.size)\n+ default:\n+ return 0, syserror.EINVAL\n+ }\n+ if offset > math.MaxInt64-n {\n+ return 0, syserror.EINVAL\n+ }\n+ offset += n\n+ if offset < 0 {\n+ return 0, syserror.EINVAL\n+ }\n+ fd.off = offset\n+ return offset, nil\n+}\n+\n// generateMerkle generates a Merkle tree file for fd. If fd points to a file\n// /foo/bar, a Merkle tree file /foo/.merkle.verity.bar is generated. The hash\n// of the generated Merkle tree and the data size is returned. If fd points to\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement Seek in verity fs
PiperOrigin-RevId: 338847417 |
259,975 | 26.10.2020 10:27:25 | 25,200 | e2dce046037c30b585cc62db45d517f59d1a08fc | Add parser for open source benchmarks.
Add a parser binary for parsing files containing
Benchmark output and sending data to BigQuery. | [
{
"change_type": "MODIFY",
"old_path": "tools/bigquery/BUILD",
"new_path": "tools/bigquery/BUILD",
"diff": "@@ -9,5 +9,8 @@ go_library(\nvisibility = [\n\"//:sandbox\",\n],\n- deps = [\"@com_google_cloud_go_bigquery//:go_default_library\"],\n+ deps = [\n+ \"@com_google_cloud_go_bigquery//:go_default_library\",\n+ \"@org_golang_google_api//option:go_default_library\",\n+ ],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/bigquery/bigquery.go",
"new_path": "tools/bigquery/bigquery.go",
"diff": "@@ -25,22 +25,30 @@ import (\n\"time\"\nbq \"cloud.google.com/go/bigquery\"\n+ \"google.golang.org/api/option\"\n)\n-// Benchmark is the top level structure of recorded benchmark data. BigQuery\n+// Suite is the top level structure for a benchmark run. BigQuery\n// will infer the schema from this.\n+type Suite struct {\n+ Name string `bq:\"name\"`\n+ Conditions []*Condition `bq:\"conditions\"`\n+ Benchmarks []*Benchmark `bq:\"benchmarks\"`\n+ Official bool `bq:\"official\"`\n+ Timestamp time.Time `bq:\"timestamp\"`\n+}\n+\n+// Benchmark represents an individual benchmark in a suite.\ntype Benchmark struct {\nName string `bq:\"name\"`\nCondition []*Condition `bq:\"condition\"`\n- Timestamp time.Time `bq:\"timestamp\"`\n- Official bool `bq:\"official\"`\nMetric []*Metric `bq:\"metric\"`\n- Metadata *Metadata `bq:\"metadata\"`\n}\n-// Condition represents qualifiers for the benchmark. For example:\n+// Condition represents qualifiers for the benchmark or suite. For example:\n// Get_Pid/1/real_time would have Benchmark Name \"Get_Pid\" with \"1\"\n-// and \"real_time\" parameters as conditions.\n+// and \"real_time\" parameters as conditions. Suite conditions include\n+// information such as the CL number and platform name.\ntype Condition struct {\nName string `bq:\"name\"`\nValue string `bq:\"value\"`\n@@ -53,19 +61,9 @@ type Metric struct {\nSample float64 `bq:\"sample\"`\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+func InitBigQuery(ctx context.Context, projectID, datasetID, tableID string, opts []option.ClientOption) error {\n+ client, err := bq.NewClient(ctx, projectID, opts...)\nif err != nil {\nreturn fmt.Errorf(\"failed to initialize client on project %s: %v\", projectID, err)\n}\n@@ -77,7 +75,7 @@ func InitBigQuery(ctx context.Context, projectID, datasetID, tableID string) err\n}\ntable := dataset.Table(tableID)\n- schema, err := bq.InferSchema(Benchmark{})\n+ schema, err := bq.InferSchema(Suite{})\nif err != nil {\nreturn fmt.Errorf(\"failed to infer schema: %v\", err)\n}\n@@ -110,23 +108,31 @@ func (bm *Benchmark) AddMetric(metricName, unit string, sample float64) {\nfunc NewBenchmark(name string, iters int, official bool) *Benchmark {\nreturn &Benchmark{\nName: name,\n- Timestamp: time.Now().UTC(),\n- Official: official,\nMetric: make([]*Metric, 0),\n}\n}\n+// NewSuite initializes a new Suite.\n+func NewSuite(name string) *Suite {\n+ return &Suite{\n+ Name: name,\n+ Timestamp: time.Now().UTC(),\n+ Benchmarks: make([]*Benchmark, 0),\n+ Conditions: make([]*Condition, 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+func SendBenchmarks(ctx context.Context, suite *Suite, projectID, datasetID, tableID string, opts []option.ClientOption) error {\n+ client, err := bq.NewClient(ctx, projectID, opts...)\nif err != nil {\nreturn fmt.Errorf(\"failed to initialize client on project: %s: %v\", projectID, err)\n}\ndefer client.Close()\nuploader := 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+ if err = uploader.Put(ctx, suite); err != nil {\n+ return fmt.Errorf(\"failed to upload benchmarks %s to project %s, table %s.%s: %v\", suite.Name, projectID, datasetID, tableID, err)\n}\nreturn nil\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/parsers/BUILD",
"new_path": "tools/parsers/BUILD",
"diff": "-load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+load(\"//tools:defs.bzl\", \"go_binary\", \"go_library\", \"go_test\")\npackage(licenses = [\"notice\"])\n@@ -27,3 +27,15 @@ go_library(\n\"//tools/bigquery\",\n],\n)\n+\n+go_binary(\n+ name = \"parser\",\n+ testonly = 1,\n+ srcs = [\"parser_main.go\"],\n+ nogo = False,\n+ deps = [\n+ \":parsers\",\n+ \"//runsc/flag\",\n+ \"//tools/bigquery\",\n+ ],\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/parsers/go_parser.go",
"new_path": "tools/parsers/go_parser.go",
"diff": "@@ -27,20 +27,21 @@ import (\n\"gvisor.dev/gvisor/tools/bigquery\"\n)\n-// parseOutput expects golang benchmark output returns a Benchmark struct formatted for BigQuery.\n-func parseOutput(output string, metadata *bigquery.Metadata, official bool) ([]*bigquery.Benchmark, error) {\n- var benchmarks []*bigquery.Benchmark\n+// ParseOutput expects golang benchmark output and returns a struct formatted\n+// for BigQuery.\n+func ParseOutput(output string, name string, official bool) (*bigquery.Suite, error) {\n+ suite := bigquery.NewSuite(name)\nlines := strings.Split(output, \"\\n\")\nfor _, line := range lines {\n- bm, err := parseLine(line, metadata, official)\n+ bm, err := parseLine(line, official)\nif err != nil {\nreturn nil, fmt.Errorf(\"failed to parse line '%s': %v\", line, err)\n}\nif bm != nil {\n- benchmarks = append(benchmarks, bm)\n+ suite.Benchmarks = append(suite.Benchmarks, bm)\n}\n}\n- return benchmarks, nil\n+ return suite, nil\n}\n// parseLine handles parsing a benchmark line into a bigquery.Benchmark.\n@@ -58,9 +59,8 @@ func parseOutput(output string, metadata *bigquery.Metadata, official bool) ([]*\n// {Name: ns/op, Unit: ns/op, Sample: 1397875880}\n// {Name: requests_per_second, Unit: QPS, Sample: 140 }\n// }\n-// Metadata: metadata\n//}\n-func parseLine(line string, metadata *bigquery.Metadata, official bool) (*bigquery.Benchmark, error) {\n+func parseLine(line string, official bool) (*bigquery.Benchmark, error) {\nfields := strings.Fields(line)\n// Check if this line is a Benchmark line. Otherwise ignore the line.\n@@ -79,7 +79,6 @@ func parseLine(line string, metadata *bigquery.Metadata, official bool) (*bigque\n}\nbm := bigquery.NewBenchmark(name, iters, official)\n- bm.Metadata = metadata\nfor _, p := range params {\nbm.AddCondition(p.Name, p.Value)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/parsers/go_parser_test.go",
"new_path": "tools/parsers/go_parser_test.go",
"diff": "@@ -94,13 +94,11 @@ func TestParseLine(t *testing.T) {\nfor _, tc := range testCases {\nt.Run(tc.name, func(t *testing.T) {\n- got, err := parseLine(tc.data, nil, false)\n+ got, err := parseLine(tc.data, false)\nif err != nil {\nt.Fatalf(\"parseLine failed with: %v\", err)\n}\n- tc.want.Timestamp = got.Timestamp\n-\nif !cmp.Equal(tc.want, got, nil) {\nfor _, c := range got.Condition {\nt.Logf(\"Cond: %+v\", c)\n@@ -150,14 +148,14 @@ BenchmarkRuby/server_threads.5-6 1 1416003331 ns/op 0.00950 average_latency.s 46\nfor _, tc := range testCases {\nt.Run(tc.name, func(t *testing.T) {\n- bms, err := parseOutput(tc.data, nil, false)\n+ suite, err := ParseOutput(tc.data, \"\", false)\nif err != nil {\nt.Fatalf(\"parseOutput failed: %v\", err)\n- } else if len(bms) != tc.numBenchmarks {\n- t.Fatalf(\"NumBenchmarks failed want: %d got: %d %+v\", tc.numBenchmarks, len(bms), bms)\n+ } else if len(suite.Benchmarks) != tc.numBenchmarks {\n+ t.Fatalf(\"NumBenchmarks failed want: %d got: %d %+v\", tc.numBenchmarks, len(suite.Benchmarks), suite.Benchmarks)\n}\n- for _, bm := range bms {\n+ for _, bm := range suite.Benchmarks {\nif len(bm.Metric) != tc.numMetrics {\nt.Fatalf(\"NumMetrics failed want: %d got: %d %+v\", tc.numMetrics, len(bm.Metric), bm.Metric)\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tools/parsers/parser_main.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+// Binary parser parses Benchmark data from golang benchmarks,\n+// puts it into a Schema for BigQuery, and sends it to BigQuery.\n+// parser will also initialize a table with the Benchmarks BigQuery schema.\n+package main\n+\n+import (\n+ \"context\"\n+ \"fmt\"\n+ \"io/ioutil\"\n+ \"os\"\n+\n+ \"gvisor.dev/gvisor/runsc/flag\"\n+ bq \"gvisor.dev/gvisor/tools/bigquery\"\n+ \"gvisor.dev/gvisor/tools/parsers\"\n+)\n+\n+const (\n+ initString = \"init\"\n+ initDescription = \"initializes a new table with benchmarks schema\"\n+ parseString = \"parse\"\n+ parseDescription = \"parses given benchmarks file and sends it to BigQuery table.\"\n+)\n+\n+var (\n+ // The init command will create a new dataset/table in the given project and initialize\n+ // the table with the schema in //tools/bigquery/bigquery.go. If the table/dataset exists\n+ // or has been initialized, init has no effect and successfully returns.\n+ initCmd = flag.NewFlagSet(initString, flag.ContinueOnError)\n+ initProject = initCmd.String(\"project\", \"\", \"GCP project to send benchmarks.\")\n+ initDataset = initCmd.String(\"dataset\", \"\", \"dataset to send benchmarks data.\")\n+ initTable = initCmd.String(\"table\", \"\", \"table to send benchmarks data.\")\n+\n+ // The parse command parses benchmark data in `file` and sends it to the\n+ // requested table.\n+ parseCmd = flag.NewFlagSet(parseString, flag.ContinueOnError)\n+ file = parseCmd.String(\"file\", \"\", \"file to parse for benchmarks\")\n+ name = parseCmd.String(\"suite_name\", \"\", \"name of the benchmark suite\")\n+ clNumber = parseCmd.String(\"cl\", \"\", \"changelist number of this run\")\n+ gitCommit = parseCmd.String(\"git_commit\", \"\", \"git commit sha for this run\")\n+ parseProject = parseCmd.String(\"project\", \"\", \"GCP project to send benchmarks.\")\n+ parseDataset = parseCmd.String(\"dataset\", \"\", \"dataset to send benchmarks data.\")\n+ parseTable = parseCmd.String(\"table\", \"\", \"table to send benchmarks data.\")\n+ official = parseCmd.Bool(\"official\", false, \"mark input data as official.\")\n+)\n+\n+// initBenchmarks initializes a dataset/table in a BigQuery project.\n+func initBenchmarks(ctx context.Context) error {\n+ return bq.InitBigQuery(ctx, *initProject, *initDataset, *initTable, nil)\n+}\n+\n+// parseBenchmarks parses the given file into the BigQuery schema,\n+// adds some custom data for the commit, and sends the data to BigQuery.\n+func parseBenchmarks(ctx context.Context) error {\n+ data, err := ioutil.ReadFile(*file)\n+ if err != nil {\n+ return fmt.Errorf(\"failed to read file: %v\", err)\n+ }\n+ suite, err := parsers.ParseOutput(string(data), *name, *official)\n+ if err != nil {\n+ return fmt.Errorf(\"failed parse data: %v\", err)\n+ }\n+ extraConditions := []*bq.Condition{\n+ {\n+ Name: \"change_list\",\n+ Value: *clNumber,\n+ },\n+ {\n+ Name: \"commit\",\n+ Value: *gitCommit,\n+ },\n+ }\n+\n+ suite.Conditions = append(suite.Conditions, extraConditions...)\n+ return bq.SendBenchmarks(ctx, suite, *parseProject, *parseDataset, *parseTable, nil)\n+}\n+\n+func main() {\n+ ctx := context.Background()\n+ switch {\n+ // the \"init\" command\n+ case len(os.Args) >= 2 && os.Args[1] == initString:\n+ if err := initCmd.Parse(os.Args[2:]); err != nil {\n+ fmt.Fprintf(os.Stderr, \"failed parse flags: %v\", err)\n+ os.Exit(1)\n+ }\n+ if err := initBenchmarks(ctx); err != nil {\n+ failure := \"failed to initialize project: %s dataset: %s table: %s: %v\"\n+ fmt.Fprintf(os.Stderr, failure, *parseProject, *parseDataset, *parseTable, err)\n+ os.Exit(1)\n+ }\n+ // the \"parse\" command.\n+ case len(os.Args) >= 2 && os.Args[1] == parseString:\n+ if err := parseCmd.Parse(os.Args[2:]); err != nil {\n+ fmt.Fprintf(os.Stderr, \"failed parse flags: %v\", err)\n+ os.Exit(1)\n+ }\n+ if err := parseBenchmarks(ctx); err != nil {\n+ fmt.Fprintf(os.Stderr, \"failed parse benchmarks: %v\", err)\n+ os.Exit(1)\n+ }\n+ default:\n+ printUsage()\n+ }\n+}\n+\n+// printUsage prints the top level usage string.\n+func printUsage() {\n+ usage := `Usage: parser <command> <flags> ...\n+\n+Available commands:\n+ %s %s\n+ %s %s\n+`\n+ fmt.Fprintf(os.Stderr, usage, initCmd.Name(), initDescription, parseCmd.Name(), parseDescription)\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add parser for open source benchmarks.
Add a parser binary for parsing files containing
Benchmark output and sending data to BigQuery.
PiperOrigin-RevId: 339066396 |
259,860 | 26.10.2020 14:13:55 | 25,200 | 0bdcee38bdfa5c4585d28a0edd0c46e170cdc9b5 | Fix SCM Rights S/R reference leak.
Control messages collected when peeking into a socket were being leaked. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/transport/unix.go",
"new_path": "pkg/sentry/socket/unix/transport/unix.go",
"diff": "@@ -32,6 +32,8 @@ import (\nconst initialLimit = 16 * 1024\n// A RightsControlMessage is a control message containing FDs.\n+//\n+// +stateify savable\ntype RightsControlMessage interface {\n// Clone returns a copy of the RightsControlMessage.\nClone() RightsControlMessage\n@@ -336,7 +338,7 @@ type Receiver interface {\nRecvMaxQueueSize() int64\n// Release releases any resources owned by the Receiver. It should be\n- // called before droping all references to a Receiver.\n+ // called before dropping all references to a Receiver.\nRelease(ctx context.Context)\n}\n@@ -572,6 +574,12 @@ func (q *streamQueueReceiver) Recv(ctx context.Context, data [][]byte, wantCreds\nreturn copied, copied, c, cmTruncated, q.addr, notify, nil\n}\n+// Release implements Receiver.Release.\n+func (q *streamQueueReceiver) Release(ctx context.Context) {\n+ q.queueReceiver.Release(ctx)\n+ q.control.Release(ctx)\n+}\n+\n// A ConnectedEndpoint is an Endpoint that can be used to send Messages.\ntype ConnectedEndpoint interface {\n// Passcred implements Endpoint.Passcred.\n@@ -619,7 +627,7 @@ type ConnectedEndpoint interface {\nSendMaxQueueSize() int64\n// Release releases any resources owned by the ConnectedEndpoint. It should\n- // be called before droping all references to a ConnectedEndpoint.\n+ // be called before dropping all references to a ConnectedEndpoint.\nRelease(ctx context.Context)\n// CloseUnread sets the fact that this end is closed with unread data to\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_unix_cmsg.cc",
"new_path": "test/syscalls/linux/socket_unix_cmsg.cc",
"diff": "@@ -630,9 +630,7 @@ TEST_P(UnixSocketPairCmsgTest, FDPassNotCoalesced) {\nTransferTest(pair2->first_fd(), pair2->second_fd());\n}\n-// TODO(b/171425923): Enable random/cooperative save once fixed.\n-TEST_P(UnixSocketPairCmsgTest, FDPassPeek_NoRandomSave) {\n- const DisableSave ds;\n+TEST_P(UnixSocketPairCmsgTest, FDPassPeek) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\nchar sent_data[20];\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix SCM Rights S/R reference leak.
Control messages collected when peeking into a socket were being leaked.
PiperOrigin-RevId: 339114961 |
260,001 | 26.10.2020 16:49:54 | 25,200 | 528bc380222d1568fcbf95b449d0b19fd6dc0a00 | Add verity tests for deleted/renamed cases
Also change verity test to use a context with an active task. This is
required to delete/rename the file in the underlying file system. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/verity/BUILD",
"new_path": "pkg/sentry/fsimpl/verity/BUILD",
"diff": "@@ -40,10 +40,12 @@ go_test(\n\"//pkg/context\",\n\"//pkg/fspath\",\n\"//pkg/sentry/arch\",\n+ \"//pkg/sentry/fsimpl/testutil\",\n\"//pkg/sentry/fsimpl/tmpfs\",\n+ \"//pkg/sentry/kernel\",\n\"//pkg/sentry/kernel/auth\",\n- \"//pkg/sentry/kernel/contexttest\",\n\"//pkg/sentry/vfs\",\n+ \"//pkg/syserror\",\n\"//pkg/usermem\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/verity/verity_test.go",
"new_path": "pkg/sentry/fsimpl/verity/verity_test.go",
"diff": "@@ -25,10 +25,12 @@ import (\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/testutil\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/tmpfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n- \"gvisor.dev/gvisor/pkg/sentry/kernel/contexttest\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n@@ -41,11 +43,18 @@ const maxDataSize = 100000\n// newVerityRoot creates a new verity mount, and returns the root. The\n// underlying file system is tmpfs. If the error is not nil, then cleanup\n// should be called when the root is no longer needed.\n-func newVerityRoot(ctx context.Context, t *testing.T) (*vfs.VirtualFilesystem, vfs.VirtualDentry, error) {\n+func newVerityRoot(t *testing.T) (*vfs.VirtualFilesystem, vfs.VirtualDentry, *kernel.Task, error) {\n+ k, err := testutil.Boot()\n+ if err != nil {\n+ t.Fatalf(\"testutil.Boot: %v\", err)\n+ }\n+\n+ ctx := k.SupervisorContext()\n+\nrand.Seed(time.Now().UnixNano())\nvfsObj := &vfs.VirtualFilesystem{}\nif err := vfsObj.Init(ctx); err != nil {\n- return nil, vfs.VirtualDentry{}, fmt.Errorf(\"VFS init: %v\", err)\n+ return nil, vfs.VirtualDentry{}, nil, fmt.Errorf(\"VFS init: %v\", err)\n}\nvfsObj.MustRegisterFilesystemType(\"verity\", FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n@@ -67,16 +76,26 @@ func newVerityRoot(ctx context.Context, t *testing.T) (*vfs.VirtualFilesystem, v\n},\n})\nif err != nil {\n- return nil, vfs.VirtualDentry{}, fmt.Errorf(\"NewMountNamespace: %v\", err)\n+ return nil, vfs.VirtualDentry{}, nil, fmt.Errorf(\"NewMountNamespace: %v\", err)\n}\nroot := mntns.Root()\nroot.IncRef()\n+\n+ // Use lowerRoot in the task as we modify the lower file system\n+ // directly in many tests.\n+ lowerRoot := root.Dentry().Impl().(*dentry).lowerVD\n+ tc := k.NewThreadGroup(nil, k.RootPIDNamespace(), kernel.NewSignalHandlers(), linux.SIGCHLD, k.GlobalInit().Limits())\n+ task, err := testutil.CreateTask(ctx, \"name\", tc, mntns, lowerRoot, lowerRoot)\n+ if err != nil {\n+ t.Fatalf(\"testutil.CreateTask: %v\", err)\n+ }\n+\nt.Helper()\nt.Cleanup(func() {\nroot.DecRef(ctx)\nmntns.DecRef(ctx)\n})\n- return vfsObj, root, nil\n+ return vfsObj, root, task, nil\n}\n// newFileFD creates a new file in the verity mount, and returns the FD. The FD\n@@ -145,8 +164,7 @@ func corruptRandomBit(ctx context.Context, fd *vfs.FileDescription, size int) er\n// TestOpen ensures that when a file is created, the corresponding Merkle tree\n// file and the root Merkle tree file exist.\nfunc TestOpen(t *testing.T) {\n- ctx := contexttest.Context(t)\n- vfsObj, root, err := newVerityRoot(ctx, t)\n+ vfsObj, root, ctx, err := newVerityRoot(t)\nif err != nil {\nt.Fatalf(\"newVerityRoot: %v\", err)\n}\n@@ -183,8 +201,7 @@ func TestOpen(t *testing.T) {\n// TestPReadUnmodifiedFileSucceeds ensures that pread from an untouched verity\n// file succeeds after enabling verity for it.\nfunc TestPReadUnmodifiedFileSucceeds(t *testing.T) {\n- ctx := contexttest.Context(t)\n- vfsObj, root, err := newVerityRoot(ctx, t)\n+ vfsObj, root, ctx, err := newVerityRoot(t)\nif err != nil {\nt.Fatalf(\"newVerityRoot: %v\", err)\n}\n@@ -216,8 +233,7 @@ func TestPReadUnmodifiedFileSucceeds(t *testing.T) {\n// TestReadUnmodifiedFileSucceeds ensures that read from an untouched verity\n// file succeeds after enabling verity for it.\nfunc TestReadUnmodifiedFileSucceeds(t *testing.T) {\n- ctx := contexttest.Context(t)\n- vfsObj, root, err := newVerityRoot(ctx, t)\n+ vfsObj, root, ctx, err := newVerityRoot(t)\nif err != nil {\nt.Fatalf(\"newVerityRoot: %v\", err)\n}\n@@ -249,8 +265,7 @@ func TestReadUnmodifiedFileSucceeds(t *testing.T) {\n// TestReopenUnmodifiedFileSucceeds ensures that reopen an untouched verity file\n// succeeds after enabling verity for it.\nfunc TestReopenUnmodifiedFileSucceeds(t *testing.T) {\n- ctx := contexttest.Context(t)\n- vfsObj, root, err := newVerityRoot(ctx, t)\n+ vfsObj, root, ctx, err := newVerityRoot(t)\nif err != nil {\nt.Fatalf(\"newVerityRoot: %v\", err)\n}\n@@ -284,8 +299,7 @@ func TestReopenUnmodifiedFileSucceeds(t *testing.T) {\n// TestPReadModifiedFileFails ensures that read from a modified verity file\n// fails.\nfunc TestPReadModifiedFileFails(t *testing.T) {\n- ctx := contexttest.Context(t)\n- vfsObj, root, err := newVerityRoot(ctx, t)\n+ vfsObj, root, ctx, err := newVerityRoot(t)\nif err != nil {\nt.Fatalf(\"newVerityRoot: %v\", err)\n}\n@@ -330,8 +344,7 @@ func TestPReadModifiedFileFails(t *testing.T) {\n// TestReadModifiedFileFails ensures that read from a modified verity file\n// fails.\nfunc TestReadModifiedFileFails(t *testing.T) {\n- ctx := contexttest.Context(t)\n- vfsObj, root, err := newVerityRoot(ctx, t)\n+ vfsObj, root, ctx, err := newVerityRoot(t)\nif err != nil {\nt.Fatalf(\"newVerityRoot: %v\", err)\n}\n@@ -376,8 +389,7 @@ func TestReadModifiedFileFails(t *testing.T) {\n// TestModifiedMerkleFails ensures that read from a verity file fails if the\n// corresponding Merkle tree file is modified.\nfunc TestModifiedMerkleFails(t *testing.T) {\n- ctx := contexttest.Context(t)\n- vfsObj, root, err := newVerityRoot(ctx, t)\n+ vfsObj, root, ctx, err := newVerityRoot(t)\nif err != nil {\nt.Fatalf(\"newVerityRoot: %v\", err)\n}\n@@ -430,8 +442,7 @@ func TestModifiedMerkleFails(t *testing.T) {\n// verity enabled directory fails if the hashes related to the target file in\n// the parent Merkle tree file is modified.\nfunc TestModifiedParentMerkleFails(t *testing.T) {\n- ctx := contexttest.Context(t)\n- vfsObj, root, err := newVerityRoot(ctx, t)\n+ vfsObj, root, ctx, err := newVerityRoot(t)\nif err != nil {\nt.Fatalf(\"newVerityRoot: %v\", err)\n}\n@@ -508,8 +519,7 @@ func TestModifiedParentMerkleFails(t *testing.T) {\n// TestUnmodifiedStatSucceeds ensures that stat of an untouched verity file\n// succeeds after enabling verity for it.\nfunc TestUnmodifiedStatSucceeds(t *testing.T) {\n- ctx := contexttest.Context(t)\n- vfsObj, root, err := newVerityRoot(ctx, t)\n+ vfsObj, root, ctx, err := newVerityRoot(t)\nif err != nil {\nt.Fatalf(\"newVerityRoot: %v\", err)\n}\n@@ -535,8 +545,7 @@ func TestUnmodifiedStatSucceeds(t *testing.T) {\n// TestModifiedStatFails checks that getting stat for a file with modified stat\n// should fail.\nfunc TestModifiedStatFails(t *testing.T) {\n- ctx := contexttest.Context(t)\n- vfsObj, root, err := newVerityRoot(ctx, t)\n+ vfsObj, root, ctx, err := newVerityRoot(t)\nif err != nil {\nt.Fatalf(\"newVerityRoot: %v\", err)\n}\n@@ -569,3 +578,123 @@ func TestModifiedStatFails(t *testing.T) {\nt.Errorf(\"fd.Stat succeeded when it should fail\")\n}\n}\n+\n+// TestOpenDeletedOrRenamedFileFails ensures that opening a deleted/renamed\n+// verity enabled file or the corresponding Merkle tree file fails with the\n+// verify error.\n+func TestOpenDeletedFileFails(t *testing.T) {\n+ testCases := []struct {\n+ // Tests removing files is remove is true. Otherwise tests\n+ // renaming files.\n+ remove bool\n+ // The original file is removed/renamed if changeFile is true.\n+ changeFile bool\n+ // The Merkle tree file is removed/renamed if changeMerkleFile\n+ // is true.\n+ changeMerkleFile bool\n+ }{\n+ {\n+ remove: true,\n+ changeFile: true,\n+ changeMerkleFile: false,\n+ },\n+ {\n+ remove: true,\n+ changeFile: false,\n+ changeMerkleFile: true,\n+ },\n+ {\n+ remove: false,\n+ changeFile: true,\n+ changeMerkleFile: false,\n+ },\n+ {\n+ remove: false,\n+ changeFile: true,\n+ changeMerkleFile: false,\n+ },\n+ }\n+ for _, tc := range testCases {\n+ t.Run(fmt.Sprintf(\"remove:%t\", tc.remove), func(t *testing.T) {\n+ vfsObj, root, ctx, err := newVerityRoot(t)\n+ if err != nil {\n+ t.Fatalf(\"newVerityRoot: %v\", err)\n+ }\n+\n+ filename := \"verity-test-file\"\n+ fd, _, err := newFileFD(ctx, vfsObj, root, filename, 0644)\n+ if err != nil {\n+ t.Fatalf(\"newFileFD: %v\", err)\n+ }\n+\n+ // Enable verity on the file.\n+ var args arch.SyscallArguments\n+ args[1] = arch.SyscallArgument{Value: linux.FS_IOC_ENABLE_VERITY}\n+ if _, err := fd.Ioctl(ctx, nil /* uio */, args); err != nil {\n+ t.Fatalf(\"Ioctl: %v\", err)\n+ }\n+\n+ rootLowerVD := root.Dentry().Impl().(*dentry).lowerVD\n+ if tc.remove {\n+ if tc.changeFile {\n+ if err := vfsObj.UnlinkAt(ctx, auth.CredentialsFromContext(ctx), &vfs.PathOperation{\n+ Root: rootLowerVD,\n+ Start: rootLowerVD,\n+ Path: fspath.Parse(filename),\n+ }); err != nil {\n+ t.Fatalf(\"UnlinkAt: %v\", err)\n+ }\n+ }\n+ if tc.changeMerkleFile {\n+ if err := vfsObj.UnlinkAt(ctx, auth.CredentialsFromContext(ctx), &vfs.PathOperation{\n+ Root: rootLowerVD,\n+ Start: rootLowerVD,\n+ Path: fspath.Parse(merklePrefix + filename),\n+ }); err != nil {\n+ t.Fatalf(\"UnlinkAt: %v\", err)\n+ }\n+ }\n+ } else {\n+ newFilename := \"renamed-test-file\"\n+ if tc.changeFile {\n+ if err := vfsObj.RenameAt(ctx, auth.CredentialsFromContext(ctx), &vfs.PathOperation{\n+ Root: rootLowerVD,\n+ Start: rootLowerVD,\n+ Path: fspath.Parse(filename),\n+ }, &vfs.PathOperation{\n+ Root: rootLowerVD,\n+ Start: rootLowerVD,\n+ Path: fspath.Parse(newFilename),\n+ }, &vfs.RenameOptions{}); err != nil {\n+ t.Fatalf(\"RenameAt: %v\", err)\n+ }\n+ }\n+ if tc.changeMerkleFile {\n+ if err := vfsObj.RenameAt(ctx, auth.CredentialsFromContext(ctx), &vfs.PathOperation{\n+ Root: rootLowerVD,\n+ Start: rootLowerVD,\n+ Path: fspath.Parse(merklePrefix + filename),\n+ }, &vfs.PathOperation{\n+ Root: rootLowerVD,\n+ Start: rootLowerVD,\n+ Path: fspath.Parse(merklePrefix + newFilename),\n+ }, &vfs.RenameOptions{}); err != nil {\n+ t.Fatalf(\"UnlinkAt: %v\", err)\n+ }\n+ }\n+ }\n+\n+ // Ensure reopening the verity enabled file fails.\n+ if _, err = vfsObj.OpenAt(ctx, auth.CredentialsFromContext(ctx), &vfs.PathOperation{\n+ Root: root,\n+ Start: root,\n+ Path: fspath.Parse(filename),\n+ }, &vfs.OpenOptions{\n+ Flags: linux.O_RDONLY,\n+ Mode: linux.ModeRegular,\n+ }); err != syserror.EIO {\n+ t.Errorf(\"got OpenAt error: %v, expected EIO\", err)\n+ }\n+ })\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add verity tests for deleted/renamed cases
Also change verity test to use a context with an active task. This is
required to delete/rename the file in the underlying file system.
PiperOrigin-RevId: 339146445 |
259,990 | 26.10.2020 18:02:52 | 25,200 | 2b72da8bf95e3e1afb361f8984584bcf0524cff3 | Allow overriding mount options for /dev and /dev/pts
This is useful to optionally set /dev ro,noexec.
Treat /dev and /dev/pts the same as /proc and /sys.
Make sure the Type is right though. Many config.json snippets
on the Internet suggest /dev is tmpfs, not devtmpfs. | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/fs.go",
"new_path": "runsc/boot/fs.go",
"diff": "@@ -103,33 +103,28 @@ func addOverlay(ctx context.Context, conf *Config, lower *fs.Inode, name string,\n// mandatory mounts that are required by the OCI specification.\nfunc compileMounts(spec *specs.Spec) []specs.Mount {\n// Keep track of whether proc and sys were mounted.\n- var procMounted, sysMounted bool\n+ var procMounted, sysMounted, devMounted, devptsMounted bool\nvar mounts []specs.Mount\n- // Always mount /dev.\n- mounts = append(mounts, specs.Mount{\n- Type: devtmpfs.Name,\n- Destination: \"/dev\",\n- })\n-\n- mounts = append(mounts, specs.Mount{\n- Type: devpts.Name,\n- Destination: \"/dev/pts\",\n- })\n-\n// Mount all submounts from the spec.\nfor _, m := range spec.Mounts {\nif !specutils.IsSupportedDevMount(m) {\nlog.Warningf(\"ignoring dev mount at %q\", m.Destination)\ncontinue\n}\n- mounts = append(mounts, m)\nswitch filepath.Clean(m.Destination) {\ncase \"/proc\":\nprocMounted = true\ncase \"/sys\":\nsysMounted = true\n+ case \"/dev\":\n+ m.Type = devtmpfs.Name\n+ devMounted = true\n+ case \"/dev/pts\":\n+ m.Type = devpts.Name\n+ devptsMounted = true\n}\n+ mounts = append(mounts, m)\n}\n// Mount proc and sys even if the user did not ask for it, as the spec\n@@ -147,6 +142,18 @@ func compileMounts(spec *specs.Spec) []specs.Mount {\nDestination: \"/sys\",\n})\n}\n+ if !devMounted {\n+ mandatoryMounts = append(mandatoryMounts, specs.Mount{\n+ Type: devtmpfs.Name,\n+ Destination: \"/dev\",\n+ })\n+ }\n+ if !devptsMounted {\n+ mandatoryMounts = append(mandatoryMounts, specs.Mount{\n+ Type: devpts.Name,\n+ Destination: \"/dev/pts\",\n+ })\n+ }\n// The mandatory mounts should be ordered right after the root, in case\n// there are submounts of these mandatory mounts already in the spec.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/specutils/specutils.go",
"new_path": "runsc/specutils/specutils.go",
"diff": "@@ -334,15 +334,9 @@ func IsSupportedDevMount(m specs.Mount) bool {\nvar existingDevices = []string{\n\"/dev/fd\", \"/dev/stdin\", \"/dev/stdout\", \"/dev/stderr\",\n\"/dev/null\", \"/dev/zero\", \"/dev/full\", \"/dev/random\",\n- \"/dev/urandom\", \"/dev/shm\", \"/dev/pts\", \"/dev/ptmx\",\n+ \"/dev/urandom\", \"/dev/shm\", \"/dev/ptmx\",\n}\ndst := filepath.Clean(m.Destination)\n- if dst == \"/dev\" {\n- // OCI spec uses many different mounts for the things inside of '/dev'. We\n- // have a single mount at '/dev' that is always mounted, regardless of\n- // whether it was asked for, as the spec says we SHOULD.\n- return false\n- }\nfor _, dev := range existingDevices {\nif dst == dev || strings.HasPrefix(dst, dev+\"/\") {\nreturn false\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow overriding mount options for /dev and /dev/pts
This is useful to optionally set /dev ro,noexec.
Treat /dev and /dev/pts the same as /proc and /sys.
Make sure the Type is right though. Many config.json snippets
on the Internet suggest /dev is tmpfs, not devtmpfs. |
259,875 | 26.10.2020 19:24:28 | 25,200 | facb2fb9c39de72c2426849a972f7181e236e7ab | Implement command IPC_STAT for semctl. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/semaphore/semaphore.go",
"new_path": "pkg/sentry/kernel/semaphore/semaphore.go",
"diff": "@@ -283,6 +283,33 @@ func (s *Set) Change(ctx context.Context, creds *auth.Credentials, owner fs.File\nreturn nil\n}\n+// GetStat extracts semid_ds information from the set.\n+func (s *Set) GetStat(creds *auth.Credentials) (*linux.SemidDS, error) {\n+ s.mu.Lock()\n+ defer s.mu.Unlock()\n+\n+ // \"The calling process must have read permission on the semaphore set.\"\n+ if !s.checkPerms(creds, fs.PermMask{Read: true}) {\n+ return nil, syserror.EACCES\n+ }\n+\n+ ds := &linux.SemidDS{\n+ SemPerm: linux.IPCPerm{\n+ Key: uint32(s.key),\n+ UID: uint32(creds.UserNamespace.MapFromKUID(s.owner.UID)),\n+ GID: uint32(creds.UserNamespace.MapFromKGID(s.owner.GID)),\n+ CUID: uint32(creds.UserNamespace.MapFromKUID(s.creator.UID)),\n+ CGID: uint32(creds.UserNamespace.MapFromKGID(s.creator.GID)),\n+ Mode: uint16(s.perms.LinuxMode()),\n+ Seq: 0, // IPC sequence not supported.\n+ },\n+ SemOTime: s.opTime.TimeT(),\n+ SemCTime: s.changeTime.TimeT(),\n+ SemNSems: uint64(s.Size()),\n+ }\n+ return ds, nil\n+}\n+\n// SetVal overrides a semaphore value, waking up waiters as needed.\nfunc (s *Set) SetVal(ctx context.Context, num int32, val int16, creds *auth.Credentials, pid int32) error {\nif val < 0 || val > valueMax {\n@@ -320,7 +347,7 @@ func (s *Set) SetValAll(ctx context.Context, vals []uint16, creds *auth.Credenti\n}\nfor _, val := range vals {\n- if val < 0 || val > valueMax {\n+ if val > valueMax {\nreturn syserror.ERANGE\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/linux64.go",
"new_path": "pkg/sentry/syscalls/linux/linux64.go",
"diff": "@@ -118,7 +118,7 @@ var AMD64 = &kernel.SyscallTable{\n63: syscalls.Supported(\"uname\", Uname),\n64: syscalls.Supported(\"semget\", Semget),\n65: syscalls.PartiallySupported(\"semop\", Semop, \"Option SEM_UNDO not supported.\", nil),\n- 66: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options IPC_INFO, SEM_INFO, IPC_STAT, SEM_STAT, SEM_STAT_ANY, GETNCNT, GETZCNT not supported.\", nil),\n+ 66: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options IPC_INFO, SEM_INFO, SEM_STAT, SEM_STAT_ANY, GETNCNT, GETZCNT not supported.\", nil),\n67: syscalls.Supported(\"shmdt\", Shmdt),\n68: syscalls.ErrorWithEvent(\"msgget\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n69: syscalls.ErrorWithEvent(\"msgsnd\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n@@ -619,7 +619,7 @@ var ARM64 = &kernel.SyscallTable{\n188: syscalls.ErrorWithEvent(\"msgrcv\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n189: syscalls.ErrorWithEvent(\"msgsnd\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n190: syscalls.Supported(\"semget\", Semget),\n- 191: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options IPC_INFO, SEM_INFO, IPC_STAT, SEM_STAT, SEM_STAT_ANY, GETNCNT, GETZCNT not supported.\", nil),\n+ 191: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options IPC_INFO, SEM_INFO, SEM_STAT, SEM_STAT_ANY, GETNCNT, GETZCNT not supported.\", nil),\n192: syscalls.ErrorWithEvent(\"semtimedop\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/137\"}),\n193: syscalls.PartiallySupported(\"semop\", Semop, \"Option SEM_UNDO not supported.\", nil),\n194: syscalls.PartiallySupported(\"shmget\", Shmget, \"Option SHM_HUGETLB is not supported.\", nil),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_sem.go",
"new_path": "pkg/sentry/syscalls/linux/sys_sem.go",
"diff": "@@ -129,9 +129,17 @@ func Semctl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\nv, err := getPID(t, id, num)\nreturn uintptr(v), nil, err\n+ case linux.IPC_STAT:\n+ arg := args[3].Pointer()\n+ ds, err := ipcStat(t, id)\n+ if err == nil {\n+ _, err = ds.CopyOut(t, arg)\n+ }\n+\n+ return 0, nil, err\n+\ncase linux.IPC_INFO,\nlinux.SEM_INFO,\n- linux.IPC_STAT,\nlinux.SEM_STAT,\nlinux.SEM_STAT_ANY,\nlinux.GETNCNT,\n@@ -171,6 +179,16 @@ func ipcSet(t *kernel.Task, id int32, uid auth.UID, gid auth.GID, perms fs.FileP\nreturn set.Change(t, creds, owner, perms)\n}\n+func ipcStat(t *kernel.Task, id int32) (*linux.SemidDS, error) {\n+ r := t.IPCNamespace().SemaphoreRegistry()\n+ set := r.FindByID(id)\n+ if set == nil {\n+ return nil, syserror.EINVAL\n+ }\n+ creds := auth.CredentialsFromContext(t)\n+ return set.GetStat(creds)\n+}\n+\nfunc setVal(t *kernel.Task, id int32, num int32, val int16) error {\nr := t.IPCNamespace().SemaphoreRegistry()\nset := r.FindByID(id)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/semaphore.cc",
"new_path": "test/syscalls/linux/semaphore.cc",
"diff": "@@ -486,6 +486,62 @@ TEST(SemaphoreTest, SemIpcSet) {\nASSERT_THAT(semop(sem.get(), &buf, 1), SyscallFailsWithErrno(EACCES));\n}\n+TEST(SemaphoreTest, SemCtlIpcStat) {\n+ // Drop CAP_IPC_OWNER which allows us to bypass semaphore permissions.\n+ ASSERT_NO_ERRNO(SetCapability(CAP_IPC_OWNER, false));\n+ const uid_t kUid = getuid();\n+ const gid_t kGid = getgid();\n+ time_t start_time = time(nullptr);\n+\n+ AutoSem sem(semget(IPC_PRIVATE, 10, 0600 | IPC_CREAT));\n+ ASSERT_THAT(sem.get(), SyscallSucceeds());\n+\n+ struct semid_ds ds;\n+ EXPECT_THAT(semctl(sem.get(), 0, IPC_STAT, &ds), SyscallSucceeds());\n+\n+ EXPECT_EQ(ds.sem_perm.__key, IPC_PRIVATE);\n+ EXPECT_EQ(ds.sem_perm.uid, kUid);\n+ EXPECT_EQ(ds.sem_perm.gid, kGid);\n+ EXPECT_EQ(ds.sem_perm.cuid, kUid);\n+ EXPECT_EQ(ds.sem_perm.cgid, kGid);\n+ EXPECT_EQ(ds.sem_perm.mode, 0600);\n+ // Last semop time is not set on creation.\n+ EXPECT_EQ(ds.sem_otime, 0);\n+ EXPECT_GE(ds.sem_ctime, start_time);\n+ EXPECT_EQ(ds.sem_nsems, 10);\n+\n+ // The timestamps only have a resolution of seconds; slow down so we actually\n+ // see the timestamps change.\n+ absl::SleepFor(absl::Seconds(1));\n+\n+ // Set semid_ds structure of the set.\n+ auto last_ctime = ds.sem_ctime;\n+ start_time = time(nullptr);\n+ struct semid_ds semid_to_set = {};\n+ semid_to_set.sem_perm.uid = kUid;\n+ semid_to_set.sem_perm.gid = kGid;\n+ semid_to_set.sem_perm.mode = 0666;\n+ ASSERT_THAT(semctl(sem.get(), 0, IPC_SET, &semid_to_set), SyscallSucceeds());\n+ struct sembuf buf = {};\n+ buf.sem_op = 1;\n+ ASSERT_THAT(semop(sem.get(), &buf, 1), SyscallSucceeds());\n+\n+ EXPECT_THAT(semctl(sem.get(), 0, IPC_STAT, &ds), SyscallSucceeds());\n+ EXPECT_EQ(ds.sem_perm.mode, 0666);\n+ EXPECT_GE(ds.sem_otime, start_time);\n+ EXPECT_GT(ds.sem_ctime, last_ctime);\n+\n+ // An invalid semid fails the syscall with errno EINVAL.\n+ EXPECT_THAT(semctl(sem.get() + 1, 0, IPC_STAT, &ds),\n+ SyscallFailsWithErrno(EINVAL));\n+\n+ // Make semaphore not readable and check the signal fails.\n+ semid_to_set.sem_perm.mode = 0200;\n+ ASSERT_THAT(semctl(sem.get(), 0, IPC_SET, &semid_to_set), SyscallSucceeds());\n+ EXPECT_THAT(semctl(sem.get(), 0, IPC_STAT, &ds),\n+ SyscallFailsWithErrno(EACCES));\n+}\n+\n} // namespace\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement command IPC_STAT for semctl.
PiperOrigin-RevId: 339166854 |
259,884 | 26.10.2020 21:59:47 | 25,200 | 3bb5f7164eefc6d5f33e7c08f87e2ae6df1c4bff | Update latest install docs to install containerd shim | [
{
"change_type": "MODIFY",
"old_path": "g3doc/user_guide/install.md",
"new_path": "g3doc/user_guide/install.md",
"diff": "@@ -13,15 +13,19 @@ To download and install the latest release manually follow these steps:\n(\nset -e\nURL=https://storage.googleapis.com/gvisor/releases/release/latest\n- wget ${URL}/runsc ${URL}/runsc.sha512\n- sha512sum -c runsc.sha512\n- rm -f runsc.sha512\n- sudo mv runsc /usr/local/bin\n- sudo chmod a+rx /usr/local/bin/runsc\n+ wget ${URL}/runsc ${URL}/runsc.sha512 \\\n+ ${URL}/gvisor-containerd-shim ${URL}/gvisor-containerd-shim.sha512 \\\n+ ${URL}/containerd-shim-runsc-v1 ${URL}/containerd-shim-runsc-v1.sha512\n+ sha512sum -c runsc.sha512 \\\n+ -c gvisor-containerd-shim.sha512 \\\n+ -c containerd-shim-runsc-v1.sha512\n+ rm -f *.sha512\n+ chmod a+rx runsc gvisor-containerd-shim containerd-shim-runsc-v1\n+ sudo mv runsc gvisor-containerd-shim containerd-shim-runsc-v1 /usr/local/bin\n)\n```\n-To install gVisor with Docker, run the following commands:\n+To install gVisor as a Docker runtime, run the following commands:\n```bash\n/usr/local/bin/runsc install\n@@ -165,5 +169,6 @@ You can use this link with the steps described in\nNote that `apt` installation of a specific point release is not supported.\nAfter installation, try out `runsc` by following the\n-[Docker Quick Start](./quick_start/docker.md) or\n+[Docker Quick Start](./quick_start/docker.md),\n+[Containerd QuickStart](./containerd/quick_start.md), or\n[OCI Quick Start](./quick_start/oci.md).\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update latest install docs to install containerd shim
PiperOrigin-RevId: 339182137 |
259,884 | 26.10.2020 22:04:13 | 25,200 | ef9378711ba4a5d27f9e819ff4811d4b0c210cc5 | Fix platforms blog post permalink | [
{
"change_type": "MODIFY",
"old_path": "website/blog/BUILD",
"new_path": "website/blog/BUILD",
"diff": "@@ -46,7 +46,7 @@ doc(\n\"mpratt\",\n],\nlayout = \"post\",\n- permalink = \"/blog/2020/09/22/platform-portability/\",\n+ permalink = \"/blog/2020/10/22/platform-portability/\",\n)\ndocs(\n"
},
{
"change_type": "MODIFY",
"old_path": "website/cmd/server/main.go",
"new_path": "website/cmd/server/main.go",
"diff": "@@ -53,6 +53,8 @@ var redirects = map[string]string{\n\"/docs/user_guide/oci\": \"/docs/user_guide/quick_start/oci/\",\n\"/docs/user_guide/docker/\": \"/docs/user_guide/quick_start/docker/\",\n\"/docs/user_guide/docker\": \"/docs/user_guide/quick_start/docker/\",\n+ \"/blog/2020/09/22/platform-portability\": \"/blog/2020/10/22/platform-portability/\",\n+ \"/blog/2020/09/22/platform-portability/\": \"/blog/2020/10/22/platform-portability/\",\n// Deprecated, but links continue to work.\n\"/cl\": \"https://gvisor-review.googlesource.com\",\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix platforms blog post permalink
PiperOrigin-RevId: 339182848 |
259,884 | 27.10.2020 00:16:14 | 25,200 | 59e2c9f16a9a4cce2ecf8b6449a47316fdf76ca2 | Add basic address deletion to netlink
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/inet/inet.go",
"new_path": "pkg/sentry/inet/inet.go",
"diff": "@@ -32,9 +32,13 @@ type Stack interface {\nInterfaceAddrs() map[int32][]InterfaceAddr\n// AddInterfaceAddr adds an address to the network interface identified by\n- // index.\n+ // idx.\nAddInterfaceAddr(idx int32, addr InterfaceAddr) error\n+ // RemoveInterfaceAddr removes an address from the network interface\n+ // identified by idx.\n+ RemoveInterfaceAddr(idx int32, addr InterfaceAddr) error\n+\n// SupportsIPv6 returns true if the stack supports IPv6 connectivity.\nSupportsIPv6() bool\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/inet/test_stack.go",
"new_path": "pkg/sentry/inet/test_stack.go",
"diff": "package inet\nimport (\n+ \"bytes\"\n+ \"fmt\"\n+\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n)\n@@ -58,6 +61,24 @@ func (s *TestStack) AddInterfaceAddr(idx int32, addr InterfaceAddr) error {\nreturn nil\n}\n+// RemoveInterfaceAddr implements Stack.RemoveInterfaceAddr.\n+func (s *TestStack) RemoveInterfaceAddr(idx int32, addr InterfaceAddr) error {\n+ interfaceAddrs, ok := s.InterfaceAddrsMap[idx]\n+ if !ok {\n+ return fmt.Errorf(\"unknown idx: %d\", idx)\n+ }\n+\n+ var filteredAddrs []InterfaceAddr\n+ for _, interfaceAddr := range interfaceAddrs {\n+ if !bytes.Equal(interfaceAddr.Addr, addr.Addr) {\n+ filteredAddrs = append(filteredAddrs, addr)\n+ }\n+ }\n+ s.InterfaceAddrsMap[idx] = filteredAddrs\n+\n+ return nil\n+}\n+\n// SupportsIPv6 implements Stack.SupportsIPv6.\nfunc (s *TestStack) SupportsIPv6() bool {\nreturn s.SupportsIPv6Flag\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/hostinet/stack.go",
"new_path": "pkg/sentry/socket/hostinet/stack.go",
"diff": "@@ -324,7 +324,12 @@ func (s *Stack) InterfaceAddrs() map[int32][]inet.InterfaceAddr {\n}\n// AddInterfaceAddr implements inet.Stack.AddInterfaceAddr.\n-func (s *Stack) AddInterfaceAddr(idx int32, addr inet.InterfaceAddr) error {\n+func (s *Stack) AddInterfaceAddr(int32, inet.InterfaceAddr) error {\n+ return syserror.EACCES\n+}\n+\n+// RemoveInterfaceAddr implements inet.Stack.RemoveInterfaceAddr.\n+func (s *Stack) RemoveInterfaceAddr(int32, inet.InterfaceAddr) error {\nreturn syserror.EACCES\n}\n@@ -359,7 +364,7 @@ func (s *Stack) TCPSACKEnabled() (bool, error) {\n}\n// SetTCPSACKEnabled implements inet.Stack.SetTCPSACKEnabled.\n-func (s *Stack) SetTCPSACKEnabled(enabled bool) error {\n+func (s *Stack) SetTCPSACKEnabled(bool) error {\nreturn syserror.EACCES\n}\n@@ -369,7 +374,7 @@ func (s *Stack) TCPRecovery() (inet.TCPLossRecovery, error) {\n}\n// SetTCPRecovery implements inet.Stack.SetTCPRecovery.\n-func (s *Stack) SetTCPRecovery(recovery inet.TCPLossRecovery) error {\n+func (s *Stack) SetTCPRecovery(inet.TCPLossRecovery) error {\nreturn syserror.EACCES\n}\n@@ -495,6 +500,6 @@ func (s *Stack) Forwarding(protocol tcpip.NetworkProtocolNumber) bool {\n}\n// SetForwarding implements inet.Stack.SetForwarding.\n-func (s *Stack) SetForwarding(protocol tcpip.NetworkProtocolNumber, enable bool) error {\n+func (s *Stack) SetForwarding(tcpip.NetworkProtocolNumber, bool) error {\nreturn syserror.EACCES\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netlink/route/protocol.go",
"new_path": "pkg/sentry/socket/netlink/route/protocol.go",
"diff": "@@ -423,6 +423,11 @@ func (p *Protocol) newAddr(ctx context.Context, msg *netlink.Message, ms *netlin\n}\nattrs = rest\n+ // NOTE: A netlink message will contain multiple header attributes.\n+ // Both the IFA_ADDRESS and IFA_LOCAL attributes are typically sent\n+ // with IFA_ADDRESS being a prefix address and IFA_LOCAL being the\n+ // local interface address. We add the local interface address here\n+ // and ignore the IFA_ADDRESS.\nswitch ahdr.Type {\ncase linux.IFA_LOCAL:\nerr := stack.AddInterfaceAddr(int32(ifa.Index), inet.InterfaceAddr{\n@@ -439,8 +444,57 @@ func (p *Protocol) newAddr(ctx context.Context, msg *netlink.Message, ms *netlin\n} else if err != nil {\nreturn syserr.ErrInvalidArgument\n}\n+ case linux.IFA_ADDRESS:\n+ default:\n+ return syserr.ErrNotSupported\n+ }\n+ }\n+ return nil\n+}\n+\n+// delAddr handles RTM_DELADDR requests.\n+func (p *Protocol) delAddr(ctx context.Context, msg *netlink.Message, ms *netlink.MessageSet) *syserr.Error {\n+ stack := inet.StackFromContext(ctx)\n+ if stack == nil {\n+ // No network stack.\n+ return syserr.ErrProtocolNotSupported\n}\n+\n+ var ifa linux.InterfaceAddrMessage\n+ attrs, ok := msg.GetData(&ifa)\n+ if !ok {\n+ return syserr.ErrInvalidArgument\n}\n+\n+ for !attrs.Empty() {\n+ ahdr, value, rest, ok := attrs.ParseFirst()\n+ if !ok {\n+ return syserr.ErrInvalidArgument\n+ }\n+ attrs = rest\n+\n+ // NOTE: A netlink message will contain multiple header attributes.\n+ // Both the IFA_ADDRESS and IFA_LOCAL attributes are typically sent\n+ // with IFA_ADDRESS being a prefix address and IFA_LOCAL being the\n+ // local interface address. We use the local interface address to\n+ // remove the address and ignore the IFA_ADDRESS.\n+ switch ahdr.Type {\n+ case linux.IFA_LOCAL:\n+ err := stack.RemoveInterfaceAddr(int32(ifa.Index), inet.InterfaceAddr{\n+ Family: ifa.Family,\n+ PrefixLen: ifa.PrefixLen,\n+ Flags: ifa.Flags,\n+ Addr: value,\n+ })\n+ if err != nil {\n+ return syserr.ErrInvalidArgument\n+ }\n+ case linux.IFA_ADDRESS:\n+ default:\n+ return syserr.ErrNotSupported\n+ }\n+ }\n+\nreturn nil\n}\n@@ -485,6 +539,8 @@ func (p *Protocol) ProcessMessage(ctx context.Context, msg *netlink.Message, ms\nreturn p.dumpRoutes(ctx, msg, ms)\ncase linux.RTM_NEWADDR:\nreturn p.newAddr(ctx, msg, ms)\n+ case linux.RTM_DELADDR:\n+ return p.delAddr(ctx, msg, ms)\ndefault:\nreturn syserr.ErrNotSupported\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/stack.go",
"new_path": "pkg/sentry/socket/netstack/stack.go",
"diff": "@@ -100,56 +100,101 @@ func (s *Stack) InterfaceAddrs() map[int32][]inet.InterfaceAddr {\nreturn nicAddrs\n}\n-// AddInterfaceAddr implements inet.Stack.AddInterfaceAddr.\n-func (s *Stack) AddInterfaceAddr(idx int32, addr inet.InterfaceAddr) error {\n+// convertAddr converts an InterfaceAddr to a ProtocolAddress.\n+func convertAddr(addr inet.InterfaceAddr) (tcpip.ProtocolAddress, error) {\nvar (\nprotocol tcpip.NetworkProtocolNumber\naddress tcpip.Address\n+ protocolAddress tcpip.ProtocolAddress\n)\nswitch addr.Family {\ncase linux.AF_INET:\n- if len(addr.Addr) < header.IPv4AddressSize {\n- return syserror.EINVAL\n+ if len(addr.Addr) != header.IPv4AddressSize {\n+ return protocolAddress, syserror.EINVAL\n}\nif addr.PrefixLen > header.IPv4AddressSize*8 {\n- return syserror.EINVAL\n+ return protocolAddress, syserror.EINVAL\n}\nprotocol = ipv4.ProtocolNumber\n- address = tcpip.Address(addr.Addr[:header.IPv4AddressSize])\n-\n+ address = tcpip.Address(addr.Addr)\ncase linux.AF_INET6:\n- if len(addr.Addr) < header.IPv6AddressSize {\n- return syserror.EINVAL\n+ if len(addr.Addr) != header.IPv6AddressSize {\n+ return protocolAddress, syserror.EINVAL\n}\nif addr.PrefixLen > header.IPv6AddressSize*8 {\n- return syserror.EINVAL\n+ return protocolAddress, syserror.EINVAL\n}\nprotocol = ipv6.ProtocolNumber\n- address = tcpip.Address(addr.Addr[:header.IPv6AddressSize])\n-\n+ address = tcpip.Address(addr.Addr)\ndefault:\n- return syserror.ENOTSUP\n+ return protocolAddress, syserror.ENOTSUP\n}\n- protocolAddress := tcpip.ProtocolAddress{\n+ protocolAddress = tcpip.ProtocolAddress{\nProtocol: protocol,\nAddressWithPrefix: tcpip.AddressWithPrefix{\nAddress: address,\nPrefixLen: int(addr.PrefixLen),\n},\n}\n+ return protocolAddress, nil\n+}\n+\n+// AddInterfaceAddr implements inet.Stack.AddInterfaceAddr.\n+func (s *Stack) AddInterfaceAddr(idx int32, addr inet.InterfaceAddr) error {\n+ protocolAddress, err := convertAddr(addr)\n+ if err != nil {\n+ return err\n+ }\n// Attach address to interface.\n- if err := s.Stack.AddProtocolAddressWithOptions(tcpip.NICID(idx), protocolAddress, stack.CanBePrimaryEndpoint); err != nil {\n+ nicID := tcpip.NICID(idx)\n+ if err := s.Stack.AddProtocolAddressWithOptions(nicID, protocolAddress, stack.CanBePrimaryEndpoint); err != nil {\nreturn syserr.TranslateNetstackError(err).ToError()\n}\n- // Add route for local network.\n- s.Stack.AddRoute(tcpip.Route{\n+ // Add route for local network if it doesn't exist already.\n+ localRoute := tcpip.Route{\nDestination: protocolAddress.AddressWithPrefix.Subnet(),\nGateway: \"\", // No gateway for local network.\n- NIC: tcpip.NICID(idx),\n+ NIC: nicID,\n+ }\n+\n+ for _, rt := range s.Stack.GetRouteTable() {\n+ if rt.Equal(localRoute) {\n+ return nil\n+ }\n+ }\n+\n+ // Local route does not exist yet. Add it.\n+ s.Stack.AddRoute(localRoute)\n+\n+ return nil\n+}\n+\n+// RemoveInterfaceAddr implements inet.Stack.RemoveInterfaceAddr.\n+func (s *Stack) RemoveInterfaceAddr(idx int32, addr inet.InterfaceAddr) error {\n+ protocolAddress, err := convertAddr(addr)\n+ if err != nil {\n+ return err\n+ }\n+\n+ // Remove addresses matching the address and prefix.\n+ nicID := tcpip.NICID(idx)\n+ if err := s.Stack.RemoveAddress(nicID, protocolAddress.AddressWithPrefix.Address); err != nil {\n+ return syserr.TranslateNetstackError(err).ToError()\n+ }\n+\n+ // Remove the corresponding local network route if it exists.\n+ localRoute := tcpip.Route{\n+ Destination: protocolAddress.AddressWithPrefix.Subnet(),\n+ Gateway: \"\", // No gateway for local network.\n+ NIC: nicID,\n+ }\n+ s.Stack.RemoveRoutes(func(rt tcpip.Route) bool {\n+ return rt.Equal(localRoute)\n})\n+\nreturn nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -830,6 +830,20 @@ func (s *Stack) AddRoute(route tcpip.Route) {\ns.routeTable = append(s.routeTable, route)\n}\n+// RemoveRoutes removes matching routes from the route table.\n+func (s *Stack) RemoveRoutes(match func(tcpip.Route) bool) {\n+ s.mu.Lock()\n+ defer s.mu.Unlock()\n+\n+ var filteredRoutes []tcpip.Route\n+ for _, route := range s.routeTable {\n+ if !match(route) {\n+ filteredRoutes = append(filteredRoutes, route)\n+ }\n+ }\n+ s.routeTable = filteredRoutes\n+}\n+\n// NewEndpoint creates a new transport layer endpoint of the given protocol.\nfunc (s *Stack) NewEndpoint(transport tcpip.TransportProtocolNumber, network tcpip.NetworkProtocolNumber, waiterQueue *waiter.Queue) (tcpip.Endpoint, *tcpip.Error) {\nt, ok := s.transportProtocols[transport]\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack_test.go",
"new_path": "pkg/tcpip/stack/stack_test.go",
"diff": "@@ -3672,3 +3672,87 @@ func TestGetMainNICAddressWhenNICDisabled(t *testing.T) {\nt.Fatalf(\"got GetMainNICAddress(%d, %d) = %s, want = %s\", nicID, fakeNetNumber, gotAddr, protocolAddress.AddressWithPrefix)\n}\n}\n+\n+// TestAddRoute tests Stack.AddRoute\n+func TestAddRoute(t *testing.T) {\n+ const nicID = 1\n+\n+ s := stack.New(stack.Options{})\n+\n+ subnet1, err := tcpip.NewSubnet(\"\\x00\", \"\\x00\")\n+ if err != nil {\n+ t.Fatal(err)\n+ }\n+\n+ subnet2, err := tcpip.NewSubnet(\"\\x01\", \"\\x01\")\n+ if err != nil {\n+ t.Fatal(err)\n+ }\n+\n+ expected := []tcpip.Route{\n+ {Destination: subnet1, Gateway: \"\\x00\", NIC: 1},\n+ {Destination: subnet2, Gateway: \"\\x00\", NIC: 1},\n+ }\n+\n+ // Initialize the route table with one route.\n+ s.SetRouteTable([]tcpip.Route{expected[0]})\n+\n+ // Add another route.\n+ s.AddRoute(expected[1])\n+\n+ rt := s.GetRouteTable()\n+ if got, want := len(rt), len(expected); got != want {\n+ t.Fatalf(\"Unexpected route table length got = %d, want = %d\", got, want)\n+ }\n+ for i, route := range rt {\n+ if got, want := route, expected[i]; got != want {\n+ t.Fatalf(\"Unexpected route got = %#v, want = %#v\", got, want)\n+ }\n+ }\n+}\n+\n+// TestRemoveRoutes tests Stack.RemoveRoutes\n+func TestRemoveRoutes(t *testing.T) {\n+ const nicID = 1\n+\n+ s := stack.New(stack.Options{})\n+\n+ addressToRemove := tcpip.Address(\"\\x01\")\n+ subnet1, err := tcpip.NewSubnet(addressToRemove, \"\\x01\")\n+ if err != nil {\n+ t.Fatal(err)\n+ }\n+\n+ subnet2, err := tcpip.NewSubnet(addressToRemove, \"\\x01\")\n+ if err != nil {\n+ t.Fatal(err)\n+ }\n+\n+ subnet3, err := tcpip.NewSubnet(\"\\x02\", \"\\x02\")\n+ if err != nil {\n+ t.Fatal(err)\n+ }\n+\n+ // Initialize the route table with three routes.\n+ s.SetRouteTable([]tcpip.Route{\n+ {Destination: subnet1, Gateway: \"\\x00\", NIC: 1},\n+ {Destination: subnet2, Gateway: \"\\x00\", NIC: 1},\n+ {Destination: subnet3, Gateway: \"\\x00\", NIC: 1},\n+ })\n+\n+ // Remove routes with the specific address.\n+ s.RemoveRoutes(func(r tcpip.Route) bool {\n+ return r.Destination.ID() == addressToRemove\n+ })\n+\n+ expected := []tcpip.Route{{Destination: subnet3, Gateway: \"\\x00\", NIC: 1}}\n+ rt := s.GetRouteTable()\n+ if got, want := len(rt), len(expected); got != want {\n+ t.Fatalf(\"Unexpected route table length got = %d, want = %d\", got, want)\n+ }\n+ for i, route := range rt {\n+ if got, want := route, expected[i]; got != want {\n+ t.Fatalf(\"Unexpected route got = %#v, want = %#v\", got, want)\n+ }\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -356,10 +356,9 @@ func (s *Subnet) IsBroadcast(address Address) bool {\nreturn s.Prefix() <= 30 && s.Broadcast() == address\n}\n-// Equal returns true if s equals o.\n-//\n-// Needed to use cmp.Equal on Subnet as its fields are unexported.\n+// Equal returns true if this Subnet is equal to the given Subnet.\nfunc (s Subnet) Equal(o Subnet) bool {\n+ // If this changes, update Route.Equal accordingly.\nreturn s == o\n}\n@@ -1260,6 +1259,12 @@ func (r Route) String() string {\nreturn out.String()\n}\n+// Equal returns true if the given Route is equal to this Route.\n+func (r Route) Equal(to Route) bool {\n+ // NOTE: This relies on the fact that r.Destination == to.Destination\n+ return r == to\n+}\n+\n// TransportProtocolNumber is the number of a transport protocol.\ntype TransportProtocolNumber uint32\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ipv4_udp_unbound_netlink.cc",
"new_path": "test/syscalls/linux/socket_ipv4_udp_unbound_netlink.cc",
"diff": "@@ -40,17 +40,9 @@ TEST_P(IPv4UDPUnboundSocketNetlinkTest, JoinSubnet) {\n/*prefixlen=*/24, &addr, sizeof(addr)));\nCleanup defer_addr_removal = Cleanup(\n[loopback_link = std::move(loopback_link), addr = std::move(addr)] {\n- if (IsRunningOnGvisor()) {\n- // TODO(gvisor.dev/issue/3921): Remove this once deleting addresses\n- // via netlink is supported.\n- EXPECT_THAT(LinkDelLocalAddr(loopback_link.index, AF_INET,\n- /*prefixlen=*/24, &addr, sizeof(addr)),\n- PosixErrorIs(EOPNOTSUPP, ::testing::_));\n- } else {\nEXPECT_NO_ERRNO(LinkDelLocalAddr(loopback_link.index, AF_INET,\n/*prefixlen=*/24, &addr,\nsizeof(addr)));\n- }\n});\nauto snd_sock = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n@@ -124,17 +116,9 @@ TEST_P(IPv4UDPUnboundSocketNetlinkTest, ReuseAddrSubnetDirectedBroadcast) {\n24 /* prefixlen */, &addr, sizeof(addr)));\nCleanup defer_addr_removal = Cleanup(\n[loopback_link = std::move(loopback_link), addr = std::move(addr)] {\n- if (IsRunningOnGvisor()) {\n- // TODO(gvisor.dev/issue/3921): Remove this once deleting addresses\n- // via netlink is supported.\n- EXPECT_THAT(LinkDelLocalAddr(loopback_link.index, AF_INET,\n- /*prefixlen=*/24, &addr, sizeof(addr)),\n- PosixErrorIs(EOPNOTSUPP, ::testing::_));\n- } else {\nEXPECT_NO_ERRNO(LinkDelLocalAddr(loopback_link.index, AF_INET,\n/*prefixlen=*/24, &addr,\nsizeof(addr)));\n- }\n});\nTestAddress broadcast_address(\"SubnetBroadcastAddress\");\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_netlink_route.cc",
"new_path": "test/syscalls/linux/socket_netlink_route.cc",
"diff": "@@ -511,52 +511,41 @@ TEST(NetlinkRouteTest, LookupAll) {\nASSERT_GT(count, 0);\n}\n-TEST(NetlinkRouteTest, AddAddr) {\n+TEST(NetlinkRouteTest, AddAndRemoveAddr) {\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_ADMIN)));\n+ // Don't do cooperative save/restore because netstack state is not restored.\n+ // TODO(gvisor.dev/issue/4595): enable cooperative save tests.\n+ const DisableSave ds;\nLink loopback_link = ASSERT_NO_ERRNO_AND_VALUE(LoopbackLink());\n- FileDescriptor fd =\n- ASSERT_NO_ERRNO_AND_VALUE(NetlinkBoundSocket(NETLINK_ROUTE));\n-\n- struct request {\n- struct nlmsghdr hdr;\n- struct ifaddrmsg ifa;\n- struct rtattr rtattr;\nstruct in_addr addr;\n- char pad[NLMSG_ALIGNTO + RTA_ALIGNTO];\n- };\n-\n- struct request req = {};\n- req.hdr.nlmsg_type = RTM_NEWADDR;\n- req.hdr.nlmsg_seq = kSeq;\n- req.ifa.ifa_family = AF_INET;\n- req.ifa.ifa_prefixlen = 24;\n- req.ifa.ifa_flags = 0;\n- req.ifa.ifa_scope = 0;\n- req.ifa.ifa_index = loopback_link.index;\n- req.rtattr.rta_type = IFA_LOCAL;\n- req.rtattr.rta_len = RTA_LENGTH(sizeof(req.addr));\n- inet_pton(AF_INET, \"10.0.0.1\", &req.addr);\n- req.hdr.nlmsg_len =\n- NLMSG_LENGTH(sizeof(req.ifa)) + NLMSG_ALIGN(req.rtattr.rta_len);\n+ ASSERT_EQ(inet_pton(AF_INET, \"10.0.0.1\", &addr), 1);\n// Create should succeed, as no such address in kernel.\n- req.hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE | NLM_F_ACK;\n- EXPECT_NO_ERRNO(\n- NetlinkRequestAckOrError(fd, req.hdr.nlmsg_seq, &req, req.hdr.nlmsg_len));\n+ ASSERT_NO_ERRNO(LinkAddLocalAddr(loopback_link.index, AF_INET,\n+ /*prefixlen=*/24, &addr, sizeof(addr)));\n+\n+ Cleanup defer_addr_removal = Cleanup(\n+ [loopback_link = std::move(loopback_link), addr = std::move(addr)] {\n+ // First delete should succeed, as address exists.\n+ EXPECT_NO_ERRNO(LinkDelLocalAddr(loopback_link.index, AF_INET,\n+ /*prefixlen=*/24, &addr,\n+ sizeof(addr)));\n+\n+ // Second delete should fail, as address no longer exists.\n+ EXPECT_THAT(LinkDelLocalAddr(loopback_link.index, AF_INET,\n+ /*prefixlen=*/24, &addr, sizeof(addr)),\n+ PosixErrorIs(EINVAL, ::testing::_));\n+ });\n// Replace an existing address should succeed.\n- req.hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_REPLACE | NLM_F_ACK;\n- req.hdr.nlmsg_seq++;\n- EXPECT_NO_ERRNO(\n- NetlinkRequestAckOrError(fd, req.hdr.nlmsg_seq, &req, req.hdr.nlmsg_len));\n+ ASSERT_NO_ERRNO(LinkReplaceLocalAddr(loopback_link.index, AF_INET,\n+ /*prefixlen=*/24, &addr, sizeof(addr)));\n// Create exclusive should fail, as we created the address above.\n- req.hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL | NLM_F_ACK;\n- req.hdr.nlmsg_seq++;\n- EXPECT_THAT(\n- NetlinkRequestAckOrError(fd, req.hdr.nlmsg_seq, &req, req.hdr.nlmsg_len),\n+ EXPECT_THAT(LinkAddExclusiveLocalAddr(loopback_link.index, AF_INET,\n+ /*prefixlen=*/24, &addr, sizeof(addr)),\nPosixErrorIs(EEXIST, ::testing::_));\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_netlink_route_util.cc",
"new_path": "test/syscalls/linux/socket_netlink_route_util.cc",
"diff": "@@ -29,6 +29,8 @@ constexpr uint32_t kSeq = 12345;\n// Types of address modifications that may be performed on an interface.\nenum class LinkAddrModification {\nkAdd,\n+ kAddExclusive,\n+ kReplace,\nkDelete,\n};\n@@ -40,6 +42,14 @@ PosixError PopulateNlmsghdr(LinkAddrModification modification,\nhdr->nlmsg_type = RTM_NEWADDR;\nhdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;\nreturn NoError();\n+ case LinkAddrModification::kAddExclusive:\n+ hdr->nlmsg_type = RTM_NEWADDR;\n+ hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_EXCL | NLM_F_ACK;\n+ return NoError();\n+ case LinkAddrModification::kReplace:\n+ hdr->nlmsg_type = RTM_NEWADDR;\n+ hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_REPLACE | NLM_F_ACK;\n+ return NoError();\ncase LinkAddrModification::kDelete:\nhdr->nlmsg_type = RTM_DELADDR;\nhdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;\n@@ -144,6 +154,18 @@ PosixError LinkAddLocalAddr(int index, int family, int prefixlen,\nLinkAddrModification::kAdd);\n}\n+PosixError LinkAddExclusiveLocalAddr(int index, int family, int prefixlen,\n+ const void* addr, int addrlen) {\n+ return LinkModifyLocalAddr(index, family, prefixlen, addr, addrlen,\n+ LinkAddrModification::kAddExclusive);\n+}\n+\n+PosixError LinkReplaceLocalAddr(int index, int family, int prefixlen,\n+ const void* addr, int addrlen) {\n+ return LinkModifyLocalAddr(index, family, prefixlen, addr, addrlen,\n+ LinkAddrModification::kReplace);\n+}\n+\nPosixError LinkDelLocalAddr(int index, int family, int prefixlen,\nconst void* addr, int addrlen) {\nreturn LinkModifyLocalAddr(index, family, prefixlen, addr, addrlen,\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_netlink_route_util.h",
"new_path": "test/syscalls/linux/socket_netlink_route_util.h",
"diff": "@@ -39,10 +39,19 @@ PosixErrorOr<std::vector<Link>> DumpLinks();\n// Returns the loopback link on the system. ENOENT if not found.\nPosixErrorOr<Link> LoopbackLink();\n-// LinkAddLocalAddr sets IFA_LOCAL attribute on the interface.\n+// LinkAddLocalAddr adds a new IFA_LOCAL address to the interface.\nPosixError LinkAddLocalAddr(int index, int family, int prefixlen,\nconst void* addr, int addrlen);\n+// LinkAddExclusiveLocalAddr adds a new IFA_LOCAL address with NLM_F_EXCL flag\n+// to the interface.\n+PosixError LinkAddExclusiveLocalAddr(int index, int family, int prefixlen,\n+ const void* addr, int addrlen);\n+\n+// LinkReplaceLocalAddr replaces an IFA_LOCAL address on the interface.\n+PosixError LinkReplaceLocalAddr(int index, int family, int prefixlen,\n+ const void* addr, int addrlen);\n+\n// LinkDelLocalAddr removes IFA_LOCAL attribute on the interface.\nPosixError LinkDelLocalAddr(int index, int family, int prefixlen,\nconst void* addr, int addrlen);\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add basic address deletion to netlink
Updates #3921
PiperOrigin-RevId: 339195417 |
259,882 | 27.10.2020 18:05:16 | 25,200 | 1c2836da37261c47cb8372e3ae5a49adab369694 | Implement /proc/[pid]/mem
This PR implements /proc/[pid]/mem for `pkg/sentry/fs` (refer to and `pkg/sentry/fsimpl`.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/gvisor/pull/4060 from lnsp:proc-pid-mem | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/task.go",
"new_path": "pkg/sentry/fs/proc/task.go",
"diff": "@@ -92,6 +92,7 @@ func (p *proc) newTaskDir(t *kernel.Task, msrc *fs.MountSource, isThreadGroup bo\n\"gid_map\": newGIDMap(t, msrc),\n\"io\": newIO(t, msrc, isThreadGroup),\n\"maps\": newMaps(t, msrc),\n+ \"mem\": newMem(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@@ -399,6 +400,88 @@ func newNamespaceDir(t *kernel.Task, msrc *fs.MountSource) *fs.Inode {\nreturn newProcInode(t, d, msrc, fs.SpecialDirectory, t)\n}\n+// memData implements fs.Inode for /proc/[pid]/mem.\n+//\n+// +stateify savable\n+type memData struct {\n+ fsutil.SimpleFileInode\n+\n+ t *kernel.Task\n+}\n+\n+// memDataFile implements fs.FileOperations for /proc/[pid]/mem.\n+//\n+// +stateify savable\n+type memDataFile struct {\n+ fsutil.FileGenericSeek `state:\"nosave\"`\n+ fsutil.FileNoIoctl `state:\"nosave\"`\n+ fsutil.FileNoMMap `state:\"nosave\"`\n+ fsutil.FileNoWrite `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+func newMem(t *kernel.Task, msrc *fs.MountSource) *fs.Inode {\n+ inode := &memData{\n+ SimpleFileInode: *fsutil.NewSimpleFileInode(t, fs.RootOwner, fs.FilePermsFromMode(0400), linux.PROC_SUPER_MAGIC),\n+ t: t,\n+ }\n+ return newProcInode(t, inode, msrc, fs.SpecialFile, t)\n+}\n+\n+// Truncate implements fs.InodeOperations.Truncate.\n+func (m *memData) Truncate(context.Context, *fs.Inode, int64) error {\n+ return nil\n+}\n+\n+// GetFile implements fs.InodeOperations.GetFile.\n+func (m *memData) GetFile(ctx context.Context, dirent *fs.Dirent, flags fs.FileFlags) (*fs.File, error) {\n+ // TODO(gvisor.dev/issue/260): Add check for PTRACE_MODE_ATTACH_FSCREDS\n+ // Permission to read this file is governed by PTRACE_MODE_ATTACH_FSCREDS\n+ // Since we dont implement setfsuid/setfsgid we can just use PTRACE_MODE_ATTACH\n+ if !kernel.ContextCanTrace(ctx, m.t, true) {\n+ return nil, syserror.EACCES\n+ }\n+ if err := checkTaskState(m.t); err != nil {\n+ return nil, err\n+ }\n+ // Enable random access reads\n+ flags.Pread = true\n+ return fs.NewFile(ctx, dirent, flags, &memDataFile{t: m.t}), nil\n+}\n+\n+// Read implements fs.FileOperations.Read.\n+func (m *memDataFile) Read(ctx context.Context, _ *fs.File, dst usermem.IOSequence, offset int64) (int64, error) {\n+ if dst.NumBytes() == 0 {\n+ return 0, nil\n+ }\n+ mm, err := getTaskMM(m.t)\n+ if err != nil {\n+ return 0, nil\n+ }\n+ defer mm.DecUsers(ctx)\n+ // Buffer the read data because of MM locks\n+ buf := make([]byte, dst.NumBytes())\n+ n, readErr := mm.CopyIn(ctx, usermem.Addr(offset), buf, usermem.IOOpts{IgnorePermissions: true})\n+ if n > 0 {\n+ if _, err := dst.CopyOut(ctx, buf[:n]); err != nil {\n+ return 0, syserror.EFAULT\n+ }\n+ return int64(n), nil\n+ }\n+ if readErr != nil {\n+ return 0, syserror.EIO\n+ }\n+ return 0, nil\n+}\n+\n// mapsData implements seqfile.SeqSource for /proc/[pid]/maps.\n//\n// +stateify savable\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/task.go",
"new_path": "pkg/sentry/fsimpl/proc/task.go",
"diff": "@@ -64,6 +64,7 @@ func (fs *filesystem) newTaskInode(task *kernel.Task, pidns *kernel.PIDNamespace\n\"gid_map\": fs.newTaskOwnedInode(task, fs.NextIno(), 0644, &idMapData{task: task, gids: true}),\n\"io\": fs.newTaskOwnedInode(task, fs.NextIno(), 0400, newIO(task, isThreadGroup)),\n\"maps\": fs.newTaskOwnedInode(task, fs.NextIno(), 0444, &mapsData{task: task}),\n+ \"mem\": fs.newMemInode(task, fs.NextIno(), 0400),\n\"mountinfo\": fs.newTaskOwnedInode(task, fs.NextIno(), 0444, &mountInfoData{task: task}),\n\"mounts\": fs.newTaskOwnedInode(task, fs.NextIno(), 0444, &mountsData{task: task}),\n\"net\": fs.newTaskNetDir(task),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/task_files.go",
"new_path": "pkg/sentry/fsimpl/proc/task_files.go",
"diff": "@@ -31,6 +31,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/mm\"\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)\n@@ -366,6 +367,162 @@ func (d *idMapData) Write(ctx context.Context, src usermem.IOSequence, offset in\nreturn int64(srclen), nil\n}\n+var _ kernfs.Inode = (*memInode)(nil)\n+\n+// memInode implements kernfs.Inode for /proc/[pid]/mem.\n+//\n+// +stateify savable\n+type memInode struct {\n+ kernfs.InodeAttrs\n+ kernfs.InodeNoStatFS\n+ kernfs.InodeNoopRefCount\n+ kernfs.InodeNotDirectory\n+ kernfs.InodeNotSymlink\n+\n+ task *kernel.Task\n+ locks vfs.FileLocks\n+}\n+\n+func (fs *filesystem) newMemInode(task *kernel.Task, ino uint64, perm linux.FileMode) kernfs.Inode {\n+ // Note: credentials are overridden by taskOwnedInode.\n+ inode := &memInode{task: task}\n+ inode.init(task, task.Credentials(), linux.UNNAMED_MAJOR, fs.devMinor, ino, perm)\n+ return &taskOwnedInode{Inode: inode, owner: task}\n+}\n+\n+func (f *memInode) init(ctx context.Context, creds *auth.Credentials, devMajor, devMinor uint32, ino uint64, perm linux.FileMode) {\n+ if perm&^linux.PermissionsMask != 0 {\n+ panic(fmt.Sprintf(\"Only permission mask must be set: %x\", perm&linux.PermissionsMask))\n+ }\n+ f.InodeAttrs.Init(ctx, creds, devMajor, devMinor, ino, linux.ModeRegular|perm)\n+}\n+\n+// Open implements kernfs.Inode.Open.\n+func (f *memInode) Open(ctx context.Context, rp *vfs.ResolvingPath, d *kernfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n+ // TODO(gvisor.dev/issue/260): Add check for PTRACE_MODE_ATTACH_FSCREDS\n+ // Permission to read this file is governed by PTRACE_MODE_ATTACH_FSCREDS\n+ // Since we dont implement setfsuid/setfsgid we can just use PTRACE_MODE_ATTACH\n+ if !kernel.ContextCanTrace(ctx, f.task, true) {\n+ return nil, syserror.EACCES\n+ }\n+ if err := checkTaskState(f.task); err != nil {\n+ return nil, err\n+ }\n+ fd := &memFD{}\n+ if err := fd.Init(rp.Mount(), d, f, opts.Flags); err != nil {\n+ return nil, err\n+ }\n+ return &fd.vfsfd, nil\n+}\n+\n+// SetStat implements kernfs.Inode.SetStat.\n+func (*memInode) SetStat(context.Context, *vfs.Filesystem, *auth.Credentials, vfs.SetStatOptions) error {\n+ return syserror.EPERM\n+}\n+\n+var _ vfs.FileDescriptionImpl = (*memFD)(nil)\n+\n+// memFD implements vfs.FileDescriptionImpl for /proc/[pid]/mem.\n+//\n+// +stateify savable\n+type memFD struct {\n+ vfsfd vfs.FileDescription\n+ vfs.FileDescriptionDefaultImpl\n+ vfs.LockFD\n+\n+ inode *memInode\n+\n+ // mu guards the fields below.\n+ mu sync.Mutex `state:\"nosave\"`\n+ offset int64\n+}\n+\n+// Init initializes memFD.\n+func (fd *memFD) Init(m *vfs.Mount, d *kernfs.Dentry, inode *memInode, flags uint32) error {\n+ fd.LockFD.Init(&inode.locks)\n+ if err := fd.vfsfd.Init(fd, flags, m, d.VFSDentry(), &vfs.FileDescriptionOptions{}); err != nil {\n+ return err\n+ }\n+ fd.inode = inode\n+ return nil\n+}\n+\n+// Seek implements vfs.FileDescriptionImpl.Seek.\n+func (fd *memFD) Seek(ctx context.Context, offset int64, whence int32) (int64, error) {\n+ fd.mu.Lock()\n+ defer fd.mu.Unlock()\n+ switch whence {\n+ case linux.SEEK_SET:\n+ case linux.SEEK_CUR:\n+ offset += fd.offset\n+ default:\n+ return 0, syserror.EINVAL\n+ }\n+ if offset < 0 {\n+ return 0, syserror.EINVAL\n+ }\n+ fd.offset = offset\n+ return offset, nil\n+}\n+\n+// PRead implements vfs.FileDescriptionImpl.PRead.\n+func (fd *memFD) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts vfs.ReadOptions) (int64, error) {\n+ if dst.NumBytes() == 0 {\n+ return 0, nil\n+ }\n+ m, err := getMMIncRef(fd.inode.task)\n+ if err != nil {\n+ return 0, nil\n+ }\n+ defer m.DecUsers(ctx)\n+ // Buffer the read data because of MM locks\n+ buf := make([]byte, dst.NumBytes())\n+ n, readErr := m.CopyIn(ctx, usermem.Addr(offset), buf, usermem.IOOpts{IgnorePermissions: true})\n+ if n > 0 {\n+ if _, err := dst.CopyOut(ctx, buf[:n]); err != nil {\n+ return 0, syserror.EFAULT\n+ }\n+ return int64(n), nil\n+ }\n+ if readErr != nil {\n+ return 0, syserror.EIO\n+ }\n+ return 0, nil\n+}\n+\n+// Read implements vfs.FileDescriptionImpl.Read.\n+func (fd *memFD) Read(ctx context.Context, dst usermem.IOSequence, opts vfs.ReadOptions) (int64, error) {\n+ fd.mu.Lock()\n+ n, err := fd.PRead(ctx, dst, fd.offset, opts)\n+ fd.offset += n\n+ fd.mu.Unlock()\n+ return n, err\n+}\n+\n+// Stat implements vfs.FileDescriptionImpl.Stat.\n+func (fd *memFD) Stat(ctx context.Context, opts vfs.StatOptions) (linux.Statx, error) {\n+ fs := fd.vfsfd.VirtualDentry().Mount().Filesystem()\n+ return fd.inode.Stat(ctx, fs, opts)\n+}\n+\n+// SetStat implements vfs.FileDescriptionImpl.SetStat.\n+func (fd *memFD) SetStat(context.Context, vfs.SetStatOptions) error {\n+ return syserror.EPERM\n+}\n+\n+// Release implements vfs.FileDescriptionImpl.Release.\n+func (fd *memFD) Release(context.Context) {}\n+\n+// LockPOSIX implements vfs.FileDescriptionImpl.LockPOSIX.\n+func (fd *memFD) LockPOSIX(ctx context.Context, uid fslock.UniqueID, t fslock.LockType, start, length uint64, whence int16, block fslock.Blocker) error {\n+ return fd.Locks().LockPOSIX(ctx, &fd.vfsfd, uid, t, start, length, whence, block)\n+}\n+\n+// UnlockPOSIX implements vfs.FileDescriptionImpl.UnlockPOSIX.\n+func (fd *memFD) UnlockPOSIX(ctx context.Context, uid fslock.UniqueID, start, length uint64, whence int16) error {\n+ return fd.Locks().UnlockPOSIX(ctx, &fd.vfsfd, uid, start, length, whence)\n+}\n+\n// mapsData implements vfs.DynamicBytesSource for /proc/[pid]/maps.\n//\n// +stateify savable\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/tasks_test.go",
"new_path": "pkg/sentry/fsimpl/proc/tasks_test.go",
"diff": "@@ -77,6 +77,7 @@ var (\n\"gid_map\": linux.DT_REG,\n\"io\": linux.DT_REG,\n\"maps\": linux.DT_REG,\n+ \"mem\": linux.DT_REG,\n\"mountinfo\": linux.DT_REG,\n\"mounts\": linux.DT_REG,\n\"net\": linux.DT_DIR,\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/proc.cc",
"new_path": "test/syscalls/linux/proc.cc",
"diff": "#include <string.h>\n#include <sys/mman.h>\n#include <sys/prctl.h>\n+#include <sys/ptrace.h>\n#include <sys/stat.h>\n#include <sys/statfs.h>\n#include <sys/utsname.h>\n@@ -512,6 +513,414 @@ TEST(ProcSelfAuxv, EntryValues) {\nEXPECT_EQ(i, proc_auxv.size());\n}\n+// Just open and read a part of /proc/self/mem, check that we can read an item.\n+TEST(ProcPidMem, Read) {\n+ auto memfd = ASSERT_NO_ERRNO_AND_VALUE(Open(\"/proc/self/mem\", O_RDONLY));\n+ char input[] = \"hello-world\";\n+ char output[sizeof(input)];\n+ ASSERT_THAT(pread(memfd.get(), output, sizeof(output),\n+ reinterpret_cast<off_t>(input)),\n+ SyscallSucceedsWithValue(sizeof(input)));\n+ ASSERT_STREQ(input, output);\n+}\n+\n+// Perform read on an unmapped region.\n+TEST(ProcPidMem, Unmapped) {\n+ // Strategy: map then unmap, so we have a guaranteed unmapped region\n+ auto memfd = ASSERT_NO_ERRNO_AND_VALUE(Open(\"/proc/self/mem\", O_RDONLY));\n+ Mapping mapping = ASSERT_NO_ERRNO_AND_VALUE(\n+ MmapAnon(kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE));\n+ // Fill it with things\n+ memset(mapping.ptr(), 'x', mapping.len());\n+ char expected = 'x', output;\n+ ASSERT_THAT(pread(memfd.get(), &output, sizeof(output),\n+ reinterpret_cast<off_t>(mapping.ptr())),\n+ SyscallSucceedsWithValue(sizeof(output)));\n+ ASSERT_EQ(expected, output);\n+\n+ // Unmap region again\n+ ASSERT_THAT(munmap(mapping.ptr(), mapping.len()), SyscallSucceeds());\n+\n+ // Now we want EIO error\n+ ASSERT_THAT(pread(memfd.get(), &output, sizeof(output),\n+ reinterpret_cast<off_t>(mapping.ptr())),\n+ SyscallFailsWithErrno(EIO));\n+}\n+\n+// Perform read repeatedly to verify offset change.\n+TEST(ProcPidMem, RepeatedRead) {\n+ auto const num_reads = 3;\n+ char expected[] = \"01234567890abcdefghijkl\";\n+ char output[sizeof(expected) / num_reads];\n+\n+ auto memfd = ASSERT_NO_ERRNO_AND_VALUE(Open(\"/proc/self/mem\", O_RDONLY));\n+ ASSERT_THAT(lseek(memfd.get(), reinterpret_cast<off_t>(&expected), SEEK_SET),\n+ SyscallSucceedsWithValue(reinterpret_cast<off_t>(&expected)));\n+ for (auto i = 0; i < num_reads; i++) {\n+ ASSERT_THAT(read(memfd.get(), &output, sizeof(output)),\n+ SyscallSucceedsWithValue(sizeof(output)));\n+ ASSERT_EQ(strncmp(&expected[i * sizeof(output)], output, sizeof(output)),\n+ 0);\n+ }\n+}\n+\n+// Perform seek operations repeatedly.\n+TEST(ProcPidMem, RepeatedSeek) {\n+ auto const num_reads = 3;\n+ char expected[] = \"01234567890abcdefghijkl\";\n+ char output[sizeof(expected) / num_reads];\n+\n+ auto memfd = ASSERT_NO_ERRNO_AND_VALUE(Open(\"/proc/self/mem\", O_RDONLY));\n+ ASSERT_THAT(lseek(memfd.get(), reinterpret_cast<off_t>(&expected), SEEK_SET),\n+ SyscallSucceedsWithValue(reinterpret_cast<off_t>(&expected)));\n+ // Read from start\n+ ASSERT_THAT(read(memfd.get(), &output, sizeof(output)),\n+ SyscallSucceedsWithValue(sizeof(output)));\n+ ASSERT_EQ(strncmp(&expected[0 * sizeof(output)], output, sizeof(output)), 0);\n+ // Skip ahead one read\n+ ASSERT_THAT(lseek(memfd.get(), sizeof(output), SEEK_CUR),\n+ SyscallSucceedsWithValue(reinterpret_cast<off_t>(&expected) +\n+ sizeof(output) * 2));\n+ // Do read again\n+ ASSERT_THAT(read(memfd.get(), &output, sizeof(output)),\n+ SyscallSucceedsWithValue(sizeof(output)));\n+ ASSERT_EQ(strncmp(&expected[2 * sizeof(output)], output, sizeof(output)), 0);\n+ // Skip back three reads\n+ ASSERT_THAT(lseek(memfd.get(), -3 * sizeof(output), SEEK_CUR),\n+ SyscallSucceedsWithValue(reinterpret_cast<off_t>(&expected)));\n+ // Do read again\n+ ASSERT_THAT(read(memfd.get(), &output, sizeof(output)),\n+ SyscallSucceedsWithValue(sizeof(output)));\n+ ASSERT_EQ(strncmp(&expected[0 * sizeof(output)], output, sizeof(output)), 0);\n+ // Check that SEEK_END does not work\n+ ASSERT_THAT(lseek(memfd.get(), 0, SEEK_END), SyscallFailsWithErrno(EINVAL));\n+}\n+\n+// Perform read past an allocated memory region.\n+TEST(ProcPidMem, PartialRead) {\n+ // Strategy: map large region, then do unmap and remap smaller region\n+ auto memfd = ASSERT_NO_ERRNO_AND_VALUE(Open(\"/proc/self/mem\", O_RDONLY));\n+\n+ Mapping mapping = ASSERT_NO_ERRNO_AND_VALUE(\n+ MmapAnon(2 * kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE));\n+ ASSERT_THAT(munmap(mapping.ptr(), mapping.len()), SyscallSucceeds());\n+ Mapping smaller_mapping = ASSERT_NO_ERRNO_AND_VALUE(\n+ Mmap(mapping.ptr(), kPageSize, PROT_READ | PROT_WRITE,\n+ MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));\n+\n+ // Fill it with things\n+ memset(smaller_mapping.ptr(), 'x', smaller_mapping.len());\n+\n+ // Now we want no error\n+ char expected[] = {'x'};\n+ std::unique_ptr<char[]> output(new char[kPageSize]);\n+ off_t read_offset =\n+ reinterpret_cast<off_t>(smaller_mapping.ptr()) + kPageSize - 1;\n+ ASSERT_THAT(\n+ pread(memfd.get(), output.get(), sizeof(output.get()), read_offset),\n+ SyscallSucceedsWithValue(sizeof(expected)));\n+ // Since output is larger, than expected we have to do manual compare\n+ ASSERT_EQ(expected[0], (output).get()[0]);\n+}\n+\n+// Perform read on /proc/[pid]/mem after exit.\n+TEST(ProcPidMem, AfterExit) {\n+ int pfd1[2] = {};\n+ int pfd2[2] = {};\n+\n+ char expected[] = \"hello-world\";\n+\n+ ASSERT_THAT(pipe(pfd1), SyscallSucceeds());\n+ ASSERT_THAT(pipe(pfd2), SyscallSucceeds());\n+\n+ // Create child process\n+ pid_t const child_pid = fork();\n+ if (child_pid == 0) {\n+ // Close reading end of first pipe\n+ close(pfd1[0]);\n+\n+ // Tell parent about location of input\n+ char ok = 1;\n+ TEST_CHECK(WriteFd(pfd1[1], &ok, sizeof(ok)) == sizeof(ok));\n+ TEST_PCHECK(close(pfd1[1]) == 0);\n+\n+ // Close writing end of second pipe\n+ TEST_PCHECK(close(pfd2[1]) == 0);\n+\n+ // Await parent OK to die\n+ ok = 0;\n+ TEST_CHECK(ReadFd(pfd2[0], &ok, sizeof(ok)) == sizeof(ok));\n+\n+ // Close rest pipes\n+ TEST_PCHECK(close(pfd2[0]) == 0);\n+ _exit(0);\n+ }\n+\n+ // In parent process.\n+ ASSERT_THAT(child_pid, SyscallSucceeds());\n+\n+ // Close writing end of first pipe\n+ EXPECT_THAT(close(pfd1[1]), SyscallSucceeds());\n+\n+ // Wait for child to be alive and well\n+ char ok = 0;\n+ EXPECT_THAT(ReadFd(pfd1[0], &ok, sizeof(ok)),\n+ SyscallSucceedsWithValue(sizeof(ok)));\n+ // Close reading end of first pipe\n+ EXPECT_THAT(close(pfd1[0]), SyscallSucceeds());\n+\n+ // Open /proc/pid/mem fd\n+ std::string mempath = absl::StrCat(\"/proc/\", child_pid, \"/mem\");\n+ auto memfd = ASSERT_NO_ERRNO_AND_VALUE(Open(mempath, O_RDONLY));\n+\n+ // Expect that we can read\n+ char output[sizeof(expected)];\n+ EXPECT_THAT(pread(memfd.get(), &output, sizeof(output),\n+ reinterpret_cast<off_t>(&expected)),\n+ SyscallSucceedsWithValue(sizeof(output)));\n+ EXPECT_STREQ(expected, output);\n+\n+ // Tell proc its ok to go\n+ EXPECT_THAT(close(pfd2[0]), SyscallSucceeds());\n+ ok = 1;\n+ EXPECT_THAT(WriteFd(pfd2[1], &ok, sizeof(ok)),\n+ SyscallSucceedsWithValue(sizeof(ok)));\n+ EXPECT_THAT(close(pfd2[1]), SyscallSucceeds());\n+\n+ // Expect termination\n+ int status;\n+ ASSERT_THAT(waitpid(child_pid, &status, 0), SyscallSucceeds());\n+\n+ // Expect that we can't read anymore\n+ EXPECT_THAT(pread(memfd.get(), &output, sizeof(output),\n+ reinterpret_cast<off_t>(&expected)),\n+ SyscallSucceedsWithValue(0));\n+}\n+\n+// Read from /proc/[pid]/mem with different UID/GID and attached state.\n+TEST(ProcPidMem, DifferentUserAttached) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SETUID)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_DAC_OVERRIDE)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_PTRACE)));\n+\n+ int pfd1[2] = {};\n+ int pfd2[2] = {};\n+\n+ ASSERT_THAT(pipe(pfd1), SyscallSucceeds());\n+ ASSERT_THAT(pipe(pfd2), SyscallSucceeds());\n+\n+ // Create child process\n+ pid_t const child_pid = fork();\n+ if (child_pid == 0) {\n+ // Close reading end of first pipe\n+ close(pfd1[0]);\n+\n+ // Tell parent about location of input\n+ char input[] = \"hello-world\";\n+ off_t input_location = reinterpret_cast<off_t>(input);\n+ TEST_CHECK(WriteFd(pfd1[1], &input_location, sizeof(input_location)) ==\n+ sizeof(input_location));\n+ TEST_PCHECK(close(pfd1[1]) == 0);\n+\n+ // Close writing end of second pipe\n+ TEST_PCHECK(close(pfd2[1]) == 0);\n+\n+ // Await parent OK to die\n+ char ok = 0;\n+ TEST_CHECK(ReadFd(pfd2[0], &ok, sizeof(ok)) == sizeof(ok));\n+\n+ // Close rest pipes\n+ TEST_PCHECK(close(pfd2[0]) == 0);\n+ _exit(0);\n+ }\n+\n+ // In parent process.\n+ ASSERT_THAT(child_pid, SyscallSucceeds());\n+\n+ // Close writing end of first pipe\n+ EXPECT_THAT(close(pfd1[1]), SyscallSucceeds());\n+\n+ // Read target location from child\n+ off_t target_location;\n+ EXPECT_THAT(ReadFd(pfd1[0], &target_location, sizeof(target_location)),\n+ SyscallSucceedsWithValue(sizeof(target_location)));\n+ // Close reading end of first pipe\n+ EXPECT_THAT(close(pfd1[0]), SyscallSucceeds());\n+\n+ ScopedThread([&] {\n+ // Attach to child subprocess without stopping it\n+ EXPECT_THAT(ptrace(PTRACE_SEIZE, child_pid, NULL, NULL), SyscallSucceeds());\n+\n+ // Keep capabilities after setuid\n+ EXPECT_THAT(prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0), SyscallSucceeds());\n+ constexpr int kNobody = 65534;\n+ EXPECT_THAT(syscall(SYS_setuid, kNobody), SyscallSucceeds());\n+\n+ // Only restore CAP_SYS_PTRACE and CAP_DAC_OVERRIDE\n+ EXPECT_NO_ERRNO(SetCapability(CAP_SYS_PTRACE, true));\n+ EXPECT_NO_ERRNO(SetCapability(CAP_DAC_OVERRIDE, true));\n+\n+ // Open /proc/pid/mem fd\n+ std::string mempath = absl::StrCat(\"/proc/\", child_pid, \"/mem\");\n+ auto memfd = ASSERT_NO_ERRNO_AND_VALUE(Open(mempath, O_RDONLY));\n+ char expected[] = \"hello-world\";\n+ char output[sizeof(expected)];\n+ EXPECT_THAT(pread(memfd.get(), output, sizeof(output),\n+ reinterpret_cast<off_t>(target_location)),\n+ SyscallSucceedsWithValue(sizeof(output)));\n+ EXPECT_STREQ(expected, output);\n+\n+ // Tell proc its ok to go\n+ EXPECT_THAT(close(pfd2[0]), SyscallSucceeds());\n+ char ok = 1;\n+ EXPECT_THAT(WriteFd(pfd2[1], &ok, sizeof(ok)),\n+ SyscallSucceedsWithValue(sizeof(ok)));\n+ EXPECT_THAT(close(pfd2[1]), SyscallSucceeds());\n+\n+ // Expect termination\n+ int status;\n+ ASSERT_THAT(waitpid(child_pid, &status, 0), SyscallSucceeds());\n+ EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)\n+ << \" status \" << status;\n+ });\n+}\n+\n+// Attempt to read from /proc/[pid]/mem with different UID/GID.\n+TEST(ProcPidMem, DifferentUser) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SETUID)));\n+\n+ int pfd1[2] = {};\n+ int pfd2[2] = {};\n+\n+ ASSERT_THAT(pipe(pfd1), SyscallSucceeds());\n+ ASSERT_THAT(pipe(pfd2), SyscallSucceeds());\n+\n+ // Create child process\n+ pid_t const child_pid = fork();\n+ if (child_pid == 0) {\n+ // Close reading end of first pipe\n+ close(pfd1[0]);\n+\n+ // Tell parent about location of input\n+ char input[] = \"hello-world\";\n+ off_t input_location = reinterpret_cast<off_t>(input);\n+ TEST_CHECK(WriteFd(pfd1[1], &input_location, sizeof(input_location)) ==\n+ sizeof(input_location));\n+ TEST_PCHECK(close(pfd1[1]) == 0);\n+\n+ // Close writing end of second pipe\n+ TEST_PCHECK(close(pfd2[1]) == 0);\n+\n+ // Await parent OK to die\n+ char ok = 0;\n+ TEST_CHECK(ReadFd(pfd2[0], &ok, sizeof(ok)) == sizeof(ok));\n+\n+ // Close rest pipes\n+ TEST_PCHECK(close(pfd2[0]) == 0);\n+ _exit(0);\n+ }\n+\n+ // In parent process.\n+ ASSERT_THAT(child_pid, SyscallSucceeds());\n+\n+ // Close writing end of first pipe\n+ EXPECT_THAT(close(pfd1[1]), SyscallSucceeds());\n+\n+ // Read target location from child\n+ off_t target_location;\n+ EXPECT_THAT(ReadFd(pfd1[0], &target_location, sizeof(target_location)),\n+ SyscallSucceedsWithValue(sizeof(target_location)));\n+ // Close reading end of first pipe\n+ EXPECT_THAT(close(pfd1[0]), SyscallSucceeds());\n+\n+ ScopedThread([&] {\n+ constexpr int kNobody = 65534;\n+ EXPECT_THAT(syscall(SYS_setuid, kNobody), SyscallSucceeds());\n+\n+ // Attempt to open /proc/[child_pid]/mem\n+ std::string mempath = absl::StrCat(\"/proc/\", child_pid, \"/mem\");\n+ EXPECT_THAT(open(mempath.c_str(), O_RDONLY), SyscallFailsWithErrno(EACCES));\n+\n+ // Tell proc its ok to go\n+ EXPECT_THAT(close(pfd2[0]), SyscallSucceeds());\n+ char ok = 1;\n+ EXPECT_THAT(WriteFd(pfd2[1], &ok, sizeof(ok)),\n+ SyscallSucceedsWithValue(sizeof(ok)));\n+ EXPECT_THAT(close(pfd2[1]), SyscallSucceeds());\n+\n+ // Expect termination\n+ int status;\n+ ASSERT_THAT(waitpid(child_pid, &status, 0), SyscallSucceeds());\n+ });\n+}\n+\n+// Perform read on /proc/[pid]/mem with same UID/GID.\n+TEST(ProcPidMem, SameUser) {\n+ int pfd1[2] = {};\n+ int pfd2[2] = {};\n+\n+ ASSERT_THAT(pipe(pfd1), SyscallSucceeds());\n+ ASSERT_THAT(pipe(pfd2), SyscallSucceeds());\n+\n+ // Create child process\n+ pid_t const child_pid = fork();\n+ if (child_pid == 0) {\n+ // Close reading end of first pipe\n+ close(pfd1[0]);\n+\n+ // Tell parent about location of input\n+ char input[] = \"hello-world\";\n+ off_t input_location = reinterpret_cast<off_t>(input);\n+ TEST_CHECK(WriteFd(pfd1[1], &input_location, sizeof(input_location)) ==\n+ sizeof(input_location));\n+ TEST_PCHECK(close(pfd1[1]) == 0);\n+\n+ // Close writing end of second pipe\n+ TEST_PCHECK(close(pfd2[1]) == 0);\n+\n+ // Await parent OK to die\n+ char ok = 0;\n+ TEST_CHECK(ReadFd(pfd2[0], &ok, sizeof(ok)) == sizeof(ok));\n+\n+ // Close rest pipes\n+ TEST_PCHECK(close(pfd2[0]) == 0);\n+ _exit(0);\n+ }\n+ // In parent process.\n+ ASSERT_THAT(child_pid, SyscallSucceeds());\n+\n+ // Close writing end of first pipe\n+ EXPECT_THAT(close(pfd1[1]), SyscallSucceeds());\n+\n+ // Read target location from child\n+ off_t target_location;\n+ EXPECT_THAT(ReadFd(pfd1[0], &target_location, sizeof(target_location)),\n+ SyscallSucceedsWithValue(sizeof(target_location)));\n+ // Close reading end of first pipe\n+ EXPECT_THAT(close(pfd1[0]), SyscallSucceeds());\n+\n+ // Open /proc/pid/mem fd\n+ std::string mempath = absl::StrCat(\"/proc/\", child_pid, \"/mem\");\n+ auto memfd = ASSERT_NO_ERRNO_AND_VALUE(Open(mempath, O_RDONLY));\n+ char expected[] = \"hello-world\";\n+ char output[sizeof(expected)];\n+ EXPECT_THAT(pread(memfd.get(), output, sizeof(output),\n+ reinterpret_cast<off_t>(target_location)),\n+ SyscallSucceedsWithValue(sizeof(output)));\n+ EXPECT_STREQ(expected, output);\n+\n+ // Tell proc its ok to go\n+ EXPECT_THAT(close(pfd2[0]), SyscallSucceeds());\n+ char ok = 1;\n+ EXPECT_THAT(WriteFd(pfd2[1], &ok, sizeof(ok)),\n+ SyscallSucceedsWithValue(sizeof(ok)));\n+ EXPECT_THAT(close(pfd2[1]), SyscallSucceeds());\n+\n+ // Expect termination\n+ int status;\n+ ASSERT_THAT(waitpid(child_pid, &status, 0), SyscallSucceeds());\n+}\n+\n// Just open and read /proc/self/maps, check that we can find [stack]\nTEST(ProcSelfMaps, Basic) {\nauto proc_self_maps =\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement /proc/[pid]/mem
This PR implements /proc/[pid]/mem for `pkg/sentry/fs` (refer to #2716) and `pkg/sentry/fsimpl`.
@majek
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/gvisor/pull/4060 from lnsp:proc-pid-mem 2caf9021254646f441be618a9bb5528610e44d43
PiperOrigin-RevId: 339369629 |
260,001 | 27.10.2020 19:10:32 | 25,200 | bc91ae17f682d2a0a6062101707e2707f965a9b2 | Add SHA512 to merkle tree library | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/ioctl.go",
"new_path": "pkg/abi/linux/ioctl.go",
"diff": "@@ -121,6 +121,9 @@ const (\n// Constants from uapi/linux/fsverity.h.\nconst (\n+ FS_VERITY_HASH_ALG_SHA256 = 1\n+ FS_VERITY_HASH_ALG_SHA512 = 2\n+\nFS_IOC_ENABLE_VERITY = 1082156677\nFS_IOC_MEASURE_VERITY = 3221513862\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/merkletree/BUILD",
"new_path": "pkg/merkletree/BUILD",
"diff": "@@ -6,12 +6,18 @@ go_library(\nname = \"merkletree\",\nsrcs = [\"merkletree.go\"],\nvisibility = [\"//pkg/sentry:internal\"],\n- deps = [\"//pkg/usermem\"],\n+ deps = [\n+ \"//pkg/abi/linux\",\n+ \"//pkg/usermem\",\n+ ],\n)\ngo_test(\nname = \"merkletree_test\",\nsrcs = [\"merkletree_test.go\"],\nlibrary = \":merkletree\",\n- deps = [\"//pkg/usermem\"],\n+ deps = [\n+ \"//pkg/abi/linux\",\n+ \"//pkg/usermem\",\n+ ],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/merkletree/merkletree.go",
"new_path": "pkg/merkletree/merkletree.go",
"diff": "@@ -18,21 +18,32 @@ package merkletree\nimport (\n\"bytes\"\n\"crypto/sha256\"\n+ \"crypto/sha512\"\n\"fmt\"\n\"io\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\nconst (\n// sha256DigestSize specifies the digest size of a SHA256 hash.\nsha256DigestSize = 32\n+ // sha512DigestSize specifies the digest size of a SHA512 hash.\n+ sha512DigestSize = 64\n)\n// DigestSize returns the size (in bytes) of a digest.\n-// TODO(b/156980949): Allow config other hash methods (SHA384/SHA512).\n-func DigestSize() int {\n+// TODO(b/156980949): Allow config SHA384.\n+func DigestSize(hashAlgorithm int) int {\n+ switch hashAlgorithm {\n+ case linux.FS_VERITY_HASH_ALG_SHA256:\nreturn sha256DigestSize\n+ case linux.FS_VERITY_HASH_ALG_SHA512:\n+ return sha512DigestSize\n+ default:\n+ return -1\n+ }\n}\n// Layout defines the scale of a Merkle tree.\n@@ -51,11 +62,19 @@ type Layout struct {\n// InitLayout initializes and returns a new Layout object describing the structure\n// of a tree. dataSize specifies the size of input data in bytes.\n-func InitLayout(dataSize int64, dataAndTreeInSameFile bool) Layout {\n+func InitLayout(dataSize int64, hashAlgorithms int, dataAndTreeInSameFile bool) (Layout, error) {\nlayout := Layout{\nblockSize: usermem.PageSize,\n- // TODO(b/156980949): Allow config other hash methods (SHA384/SHA512).\n- digestSize: sha256DigestSize,\n+ }\n+\n+ // TODO(b/156980949): Allow config SHA384.\n+ switch hashAlgorithms {\n+ case linux.FS_VERITY_HASH_ALG_SHA256:\n+ layout.digestSize = sha256DigestSize\n+ case linux.FS_VERITY_HASH_ALG_SHA512:\n+ layout.digestSize = sha512DigestSize\n+ default:\n+ return Layout{}, fmt.Errorf(\"unexpected hash algorithms\")\n}\n// treeStart is the offset (in bytes) of the first level of the tree in\n@@ -88,7 +107,7 @@ func InitLayout(dataSize int64, dataAndTreeInSameFile bool) Layout {\n}\nlayout.levelOffset = append(layout.levelOffset, treeStart+offset*layout.blockSize)\n- return layout\n+ return layout, nil\n}\n// hashesPerBlock() returns the number of digests in each block. For example,\n@@ -139,12 +158,33 @@ func (d *VerityDescriptor) String() string {\n}\n// verify generates a hash from d, and compares it with expected.\n-func (d *VerityDescriptor) verify(expected []byte) error {\n- h := sha256.Sum256([]byte(d.String()))\n+func (d *VerityDescriptor) verify(expected []byte, hashAlgorithms int) error {\n+ h, err := hashData([]byte(d.String()), hashAlgorithms)\n+ if err != nil {\n+ return err\n+ }\nif !bytes.Equal(h[:], expected) {\nreturn fmt.Errorf(\"unexpected root hash\")\n}\nreturn nil\n+\n+}\n+\n+// hashData hashes data and returns the result hash based on the hash\n+// algorithms.\n+func hashData(data []byte, hashAlgorithms int) ([]byte, error) {\n+ var digest []byte\n+ switch hashAlgorithms {\n+ case linux.FS_VERITY_HASH_ALG_SHA256:\n+ digestArray := sha256.Sum256(data)\n+ digest = digestArray[:]\n+ case linux.FS_VERITY_HASH_ALG_SHA512:\n+ digestArray := sha512.Sum512(data)\n+ digest = digestArray[:]\n+ default:\n+ return nil, fmt.Errorf(\"unexpected hash algorithms\")\n+ }\n+ return digest, nil\n}\n// GenerateParams contains the parameters used to generate a Merkle tree.\n@@ -161,6 +201,8 @@ type GenerateParams struct {\nUID uint32\n// GID is the group ID of the target file.\nGID uint32\n+ // HashAlgorithms is the algorithms used to hash data.\n+ HashAlgorithms int\n// TreeReader is a reader for the Merkle tree.\nTreeReader io.ReaderAt\n// TreeWriter is a writer for the Merkle tree.\n@@ -176,7 +218,10 @@ type GenerateParams struct {\n// Generate returns a hash of a VerityDescriptor, which contains the file\n// metadata and the hash from file content.\nfunc Generate(params *GenerateParams) ([]byte, error) {\n- layout := InitLayout(params.Size, params.DataAndTreeInSameFile)\n+ layout, err := InitLayout(params.Size, params.HashAlgorithms, params.DataAndTreeInSameFile)\n+ if err != nil {\n+ return nil, err\n+ }\nnumBlocks := (params.Size + layout.blockSize - 1) / layout.blockSize\n@@ -218,10 +263,13 @@ func Generate(params *GenerateParams) ([]byte, error) {\nreturn nil, err\n}\n// Hash the bytes in buf.\n- digest := sha256.Sum256(buf)\n+ digest, err := hashData(buf, params.HashAlgorithms)\n+ if err != nil {\n+ return nil, err\n+ }\nif level == layout.rootLevel() {\n- root = digest[:]\n+ root = digest\n}\n// Write the generated hash to the end of the tree file.\n@@ -246,8 +294,7 @@ func Generate(params *GenerateParams) ([]byte, error) {\nGID: params.GID,\nRootHash: root,\n}\n- ret := sha256.Sum256([]byte(descriptor.String()))\n- return ret[:], nil\n+ return hashData([]byte(descriptor.String()), params.HashAlgorithms)\n}\n// VerifyParams contains the params used to verify a portion of a file against\n@@ -269,6 +316,8 @@ type VerifyParams struct {\nUID uint32\n// GID is the group ID of the target file.\nGID uint32\n+ // HashAlgorithms is the algorithms used to hash data.\n+ HashAlgorithms int\n// ReadOffset is the offset of the data range to be verified.\nReadOffset int64\n// ReadSize is the size of the data range to be verified.\n@@ -298,7 +347,7 @@ func verifyMetadata(params *VerifyParams, layout *Layout) error {\nGID: params.GID,\nRootHash: root,\n}\n- return descriptor.verify(params.Expected)\n+ return descriptor.verify(params.Expected, params.HashAlgorithms)\n}\n// Verify verifies the content read from data with offset. The content is\n@@ -313,7 +362,10 @@ func Verify(params *VerifyParams) (int64, error) {\nif params.ReadSize < 0 {\nreturn 0, fmt.Errorf(\"unexpected read size: %d\", params.ReadSize)\n}\n- layout := InitLayout(int64(params.Size), params.DataAndTreeInSameFile)\n+ layout, err := InitLayout(int64(params.Size), params.HashAlgorithms, params.DataAndTreeInSameFile)\n+ if err != nil {\n+ return 0, err\n+ }\nif params.ReadSize == 0 {\nreturn 0, verifyMetadata(params, &layout)\n}\n@@ -354,7 +406,7 @@ func Verify(params *VerifyParams) (int64, error) {\nUID: params.UID,\nGID: params.GID,\n}\n- if err := verifyBlock(params.Tree, &descriptor, &layout, buf, i, params.Expected); err != nil {\n+ if err := verifyBlock(params.Tree, &descriptor, &layout, buf, i, params.HashAlgorithms, params.Expected); err != nil {\nreturn 0, err\n}\n@@ -395,7 +447,7 @@ func Verify(params *VerifyParams) (int64, error) {\n// fails if the calculated hash from block is different from any level of\n// hashes stored in tree. And the final root hash is compared with\n// expected.\n-func verifyBlock(tree io.ReaderAt, descriptor *VerityDescriptor, layout *Layout, dataBlock []byte, blockIndex int64, expected []byte) error {\n+func verifyBlock(tree io.ReaderAt, descriptor *VerityDescriptor, layout *Layout, dataBlock []byte, blockIndex int64, hashAlgorithms int, expected []byte) error {\nif len(dataBlock) != int(layout.blockSize) {\nreturn fmt.Errorf(\"incorrect block size\")\n}\n@@ -406,8 +458,11 @@ func verifyBlock(tree io.ReaderAt, descriptor *VerityDescriptor, layout *Layout,\nfor level := 0; level < layout.numLevels(); level++ {\n// Calculate hash.\nif level == 0 {\n- digestArray := sha256.Sum256(dataBlock)\n- digest = digestArray[:]\n+ h, err := hashData(dataBlock, hashAlgorithms)\n+ if err != nil {\n+ return err\n+ }\n+ digest = h\n} else {\n// Read a block in previous level that contains the\n// hash we just generated, and generate a next level\n@@ -415,8 +470,11 @@ func verifyBlock(tree io.ReaderAt, descriptor *VerityDescriptor, layout *Layout,\nif _, err := tree.ReadAt(treeBlock, layout.blockOffset(level-1, blockIndex)); err != nil {\nreturn err\n}\n- digestArray := sha256.Sum256(treeBlock)\n- digest = digestArray[:]\n+ h, err := hashData(treeBlock, hashAlgorithms)\n+ if err != nil {\n+ return err\n+ }\n+ digest = h\n}\n// Read the digest for the current block and store in\n@@ -434,5 +492,5 @@ func verifyBlock(tree io.ReaderAt, descriptor *VerityDescriptor, layout *Layout,\n// Verification for the tree succeeded. Now hash the descriptor with\n// the root hash and compare it with expected.\ndescriptor.RootHash = digest\n- return descriptor.verify(expected)\n+ return descriptor.verify(expected, hashAlgorithms)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/merkletree/merkletree_test.go",
"new_path": "pkg/merkletree/merkletree_test.go",
"diff": "@@ -22,54 +22,114 @@ import (\n\"testing\"\n\"time\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\nfunc TestLayout(t *testing.T) {\ntestCases := []struct {\ndataSize int64\n+ hashAlgorithms int\ndataAndTreeInSameFile bool\n+ expectedDigestSize int64\nexpectedLevelOffset []int64\n}{\n{\ndataSize: 100,\n+ hashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA256,\ndataAndTreeInSameFile: false,\n+ expectedDigestSize: 32,\nexpectedLevelOffset: []int64{0},\n},\n{\ndataSize: 100,\n+ hashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA512,\n+ dataAndTreeInSameFile: false,\n+ expectedDigestSize: 64,\n+ expectedLevelOffset: []int64{0},\n+ },\n+ {\n+ dataSize: 100,\n+ hashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA256,\ndataAndTreeInSameFile: true,\n+ expectedDigestSize: 32,\n+ expectedLevelOffset: []int64{usermem.PageSize},\n+ },\n+ {\n+ dataSize: 100,\n+ hashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA512,\n+ dataAndTreeInSameFile: true,\n+ expectedDigestSize: 64,\nexpectedLevelOffset: []int64{usermem.PageSize},\n},\n{\ndataSize: 1000000,\n+ hashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA256,\ndataAndTreeInSameFile: false,\n+ expectedDigestSize: 32,\nexpectedLevelOffset: []int64{0, 2 * usermem.PageSize, 3 * usermem.PageSize},\n},\n{\ndataSize: 1000000,\n+ hashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA512,\n+ dataAndTreeInSameFile: false,\n+ expectedDigestSize: 64,\n+ expectedLevelOffset: []int64{0, 4 * usermem.PageSize, 5 * usermem.PageSize},\n+ },\n+ {\n+ dataSize: 1000000,\n+ hashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA256,\ndataAndTreeInSameFile: true,\n+ expectedDigestSize: 32,\nexpectedLevelOffset: []int64{245 * usermem.PageSize, 247 * usermem.PageSize, 248 * usermem.PageSize},\n},\n+ {\n+ dataSize: 1000000,\n+ hashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA512,\n+ dataAndTreeInSameFile: true,\n+ expectedDigestSize: 64,\n+ expectedLevelOffset: []int64{245 * usermem.PageSize, 249 * usermem.PageSize, 250 * usermem.PageSize},\n+ },\n{\ndataSize: 4096 * int64(usermem.PageSize),\n+ hashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA256,\ndataAndTreeInSameFile: false,\n+ expectedDigestSize: 32,\nexpectedLevelOffset: []int64{0, 32 * usermem.PageSize, 33 * usermem.PageSize},\n},\n{\ndataSize: 4096 * int64(usermem.PageSize),\n+ hashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA512,\n+ dataAndTreeInSameFile: false,\n+ expectedDigestSize: 64,\n+ expectedLevelOffset: []int64{0, 64 * usermem.PageSize, 65 * usermem.PageSize},\n+ },\n+ {\n+ dataSize: 4096 * int64(usermem.PageSize),\n+ hashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA256,\ndataAndTreeInSameFile: true,\n+ expectedDigestSize: 32,\nexpectedLevelOffset: []int64{4096 * usermem.PageSize, 4128 * usermem.PageSize, 4129 * usermem.PageSize},\n},\n+ {\n+ dataSize: 4096 * int64(usermem.PageSize),\n+ hashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA512,\n+ dataAndTreeInSameFile: true,\n+ expectedDigestSize: 64,\n+ expectedLevelOffset: []int64{4096 * usermem.PageSize, 4160 * usermem.PageSize, 4161 * usermem.PageSize},\n+ },\n}\nfor _, tc := range testCases {\nt.Run(fmt.Sprintf(\"%d\", tc.dataSize), func(t *testing.T) {\n- l := InitLayout(tc.dataSize, tc.dataAndTreeInSameFile)\n+ l, err := InitLayout(tc.dataSize, tc.hashAlgorithms, tc.dataAndTreeInSameFile)\n+ if err != nil {\n+ t.Fatalf(\"Failed to InitLayout: %v\", err)\n+ }\nif l.blockSize != int64(usermem.PageSize) {\nt.Errorf(\"Got blockSize %d, want %d\", l.blockSize, usermem.PageSize)\n}\n- if l.digestSize != sha256DigestSize {\n+ if l.digestSize != tc.expectedDigestSize {\nt.Errorf(\"Got digestSize %d, want %d\", l.digestSize, sha256DigestSize)\n}\nif l.numLevels() != len(tc.expectedLevelOffset) {\n@@ -119,24 +179,49 @@ func TestGenerate(t *testing.T) {\n// and all other bytes are zeroes.\ntestCases := []struct {\ndata []byte\n+ hashAlgorithms int\nexpectedHash []byte\n}{\n{\ndata: bytes.Repeat([]byte{0}, usermem.PageSize),\n+ hashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA256,\nexpectedHash: []byte{64, 253, 58, 72, 192, 131, 82, 184, 193, 33, 108, 142, 43, 46, 179, 134, 244, 21, 29, 190, 14, 39, 66, 129, 6, 46, 200, 211, 30, 247, 191, 252},\n},\n+ {\n+ data: bytes.Repeat([]byte{0}, usermem.PageSize),\n+ hashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA512,\n+ expectedHash: []byte{14, 27, 126, 158, 9, 94, 163, 51, 243, 162, 82, 167, 183, 127, 93, 121, 221, 23, 184, 59, 104, 166, 111, 49, 161, 195, 229, 111, 121, 201, 233, 68, 10, 154, 78, 142, 154, 236, 170, 156, 110, 167, 15, 144, 155, 97, 241, 235, 202, 233, 246, 217, 138, 88, 152, 179, 238, 46, 247, 185, 125, 20, 101, 201},\n+ },\n{\ndata: bytes.Repeat([]byte{0}, 128*usermem.PageSize+1),\n+ hashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA256,\nexpectedHash: []byte{182, 223, 218, 62, 65, 185, 160, 219, 93, 119, 186, 88, 205, 32, 122, 231, 173, 72, 78, 76, 65, 57, 177, 146, 159, 39, 44, 123, 230, 156, 97, 26},\n},\n+ {\n+ data: bytes.Repeat([]byte{0}, 128*usermem.PageSize+1),\n+ hashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA512,\n+ expectedHash: []byte{55, 204, 240, 1, 224, 252, 58, 131, 251, 174, 45, 140, 107, 57, 118, 11, 18, 236, 203, 204, 19, 59, 27, 196, 3, 78, 21, 7, 22, 98, 197, 128, 17, 128, 90, 122, 54, 83, 253, 108, 156, 67, 59, 229, 236, 241, 69, 88, 99, 44, 127, 109, 204, 183, 150, 232, 187, 57, 228, 137, 209, 235, 241, 172},\n+ },\n{\ndata: []byte{'a'},\n+ hashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA256,\nexpectedHash: []byte{28, 201, 8, 36, 150, 178, 111, 5, 193, 212, 129, 205, 206, 124, 211, 90, 224, 142, 81, 183, 72, 165, 243, 240, 242, 241, 76, 127, 101, 61, 63, 11},\n},\n+ {\n+ data: []byte{'a'},\n+ hashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA512,\n+ expectedHash: []byte{207, 233, 114, 94, 113, 212, 243, 160, 59, 232, 226, 77, 28, 81, 176, 61, 211, 213, 222, 190, 148, 196, 90, 166, 237, 56, 113, 148, 230, 154, 23, 105, 14, 97, 144, 211, 12, 122, 226, 207, 167, 203, 136, 193, 38, 249, 227, 187, 92, 238, 101, 97, 170, 255, 246, 209, 246, 98, 241, 150, 175, 253, 173, 206},\n+ },\n{\ndata: bytes.Repeat([]byte{'a'}, usermem.PageSize),\n+ hashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA256,\nexpectedHash: []byte{106, 58, 160, 152, 41, 68, 38, 108, 245, 74, 177, 84, 64, 193, 19, 176, 249, 86, 27, 193, 85, 164, 99, 240, 79, 104, 148, 222, 76, 46, 191, 79},\n},\n+ {\n+ data: bytes.Repeat([]byte{'a'}, usermem.PageSize),\n+ hashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA512,\n+ expectedHash: []byte{110, 103, 29, 250, 27, 211, 235, 119, 112, 65, 49, 156, 6, 92, 66, 105, 133, 1, 187, 172, 169, 13, 186, 34, 105, 72, 252, 131, 12, 159, 91, 188, 79, 184, 240, 227, 40, 164, 72, 193, 65, 31, 227, 153, 191, 6, 117, 42, 82, 122, 33, 255, 92, 215, 215, 249, 2, 131, 170, 134, 39, 192, 222, 33},\n+ },\n}\nfor _, tc := range testCases {\n@@ -149,6 +234,7 @@ func TestGenerate(t *testing.T) {\nMode: defaultMode,\nUID: defaultUID,\nGID: defaultGID,\n+ HashAlgorithms: tc.hashAlgorithms,\nTreeReader: &tree,\nTreeWriter: &tree,\nDataAndTreeInSameFile: dataAndTreeInSameFile,\n@@ -348,6 +434,7 @@ func TestVerify(t *testing.T) {\n// Generate random bytes in data.\nrand.Read(data)\n+ for _, hashAlgorithms := range []int{linux.FS_VERITY_HASH_ALG_SHA256, linux.FS_VERITY_HASH_ALG_SHA512} {\nfor _, dataAndTreeInSameFile := range []bool{false, true} {\nvar tree bytesReadWriter\ngenParams := GenerateParams{\n@@ -356,6 +443,7 @@ func TestVerify(t *testing.T) {\nMode: defaultMode,\nUID: defaultUID,\nGID: defaultGID,\n+ HashAlgorithms: hashAlgorithms,\nTreeReader: &tree,\nTreeWriter: &tree,\nDataAndTreeInSameFile: dataAndTreeInSameFile,\n@@ -385,6 +473,7 @@ func TestVerify(t *testing.T) {\nMode: defaultMode,\nUID: defaultUID,\nGID: defaultGID,\n+ HashAlgorithms: hashAlgorithms,\nReadOffset: tc.verifyStart,\nReadSize: tc.verifySize,\nExpected: hash,\n@@ -422,6 +511,7 @@ func TestVerify(t *testing.T) {\n}\n}\n}\n+ }\n})\n}\n}\n@@ -435,6 +525,7 @@ func TestVerifyRandom(t *testing.T) {\n// Generate random bytes in data.\nrand.Read(data)\n+ for _, hashAlgorithms := range []int{linux.FS_VERITY_HASH_ALG_SHA256, linux.FS_VERITY_HASH_ALG_SHA512} {\nfor _, dataAndTreeInSameFile := range []bool{false, true} {\nvar tree bytesReadWriter\ngenParams := GenerateParams{\n@@ -443,6 +534,7 @@ func TestVerifyRandom(t *testing.T) {\nMode: defaultMode,\nUID: defaultUID,\nGID: defaultGID,\n+ HashAlgorithms: hashAlgorithms,\nTreeReader: &tree,\nTreeWriter: &tree,\nDataAndTreeInSameFile: dataAndTreeInSameFile,\n@@ -475,6 +567,7 @@ func TestVerifyRandom(t *testing.T) {\nMode: defaultMode,\nUID: defaultUID,\nGID: defaultGID,\n+ HashAlgorithms: hashAlgorithms,\nReadOffset: start,\nReadSize: size,\nExpected: hash,\n@@ -519,3 +612,4 @@ func TestVerifyRandom(t *testing.T) {\n}\n}\n}\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/verity/filesystem.go",
"new_path": "pkg/sentry/fsimpl/verity/filesystem.go",
"diff": "@@ -275,8 +275,10 @@ func (fs *filesystem) verifyChild(ctx context.Context, parent *dentry, child *de\nMode: uint32(parentStat.Mode),\nUID: parentStat.UID,\nGID: parentStat.GID,\n+ //TODO(b/156980949): Support passing other hash algorithms.\n+ HashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA256,\nReadOffset: int64(offset),\n- ReadSize: int64(merkletree.DigestSize()),\n+ ReadSize: int64(merkletree.DigestSize(linux.FS_VERITY_HASH_ALG_SHA256)),\nExpected: parent.hash,\nDataAndTreeInSameFile: true,\n}); err != nil && err != io.EOF {\n@@ -349,6 +351,8 @@ func (fs *filesystem) verifyStat(ctx context.Context, d *dentry, stat linux.Stat\nMode: uint32(stat.Mode),\nUID: stat.UID,\nGID: stat.GID,\n+ //TODO(b/156980949): Support passing other hash algorithms.\n+ HashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA256,\nReadOffset: 0,\n// Set read size to 0 so only the metadata is verified.\nReadSize: 0,\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/verity/verity.go",
"new_path": "pkg/sentry/fsimpl/verity/verity.go",
"diff": "@@ -600,6 +600,8 @@ func (fd *fileDescription) generateMerkle(ctx context.Context) ([]byte, uint64,\nparams := &merkletree.GenerateParams{\nTreeReader: &merkleReader,\nTreeWriter: &merkleWriter,\n+ //TODO(b/156980949): Support passing other hash algorithms.\n+ HashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA256,\n}\nswitch atomic.LoadUint32(&fd.d.mode) & linux.S_IFMT {\n@@ -844,6 +846,8 @@ func (fd *fileDescription) PRead(ctx context.Context, dst usermem.IOSequence, of\nMode: fd.d.mode,\nUID: fd.d.uid,\nGID: fd.d.gid,\n+ //TODO(b/156980949): Support passing other hash algorithms.\n+ HashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA256,\nReadOffset: offset,\nReadSize: dst.NumBytes(),\nExpected: fd.d.hash,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add SHA512 to merkle tree library
PiperOrigin-RevId: 339377254 |
259,992 | 27.10.2020 19:44:41 | 25,200 | 93d2d37a93640328f01add7d4866bc107ff6a74e | Add more cgroup unit tests | [
{
"change_type": "MODIFY",
"old_path": "runsc/cgroup/cgroup.go",
"new_path": "runsc/cgroup/cgroup.go",
"diff": "@@ -21,6 +21,7 @@ import (\n\"context\"\n\"errors\"\n\"fmt\"\n+ \"io\"\n\"io/ioutil\"\n\"os\"\n\"path/filepath\"\n@@ -198,8 +199,13 @@ func LoadPaths(pid string) (map[string]string, error) {\n}\ndefer f.Close()\n+ return loadPathsHelper(f)\n+}\n+\n+func loadPathsHelper(cgroup io.Reader) (map[string]string, error) {\npaths := make(map[string]string)\n- scanner := bufio.NewScanner(f)\n+\n+ scanner := bufio.NewScanner(cgroup)\nfor scanner.Scan() {\n// Format: ID:[name=]controller1,controller2:path\n// Example: 2:cpu,cpuacct:/user.slice\n@@ -207,6 +213,9 @@ func LoadPaths(pid string) (map[string]string, error) {\nif len(tokens) != 3 {\nreturn nil, fmt.Errorf(\"invalid cgroups file, line: %q\", scanner.Text())\n}\n+ if len(tokens[1]) == 0 {\n+ continue\n+ }\nfor _, ctrlr := range strings.Split(tokens[1], \",\") {\n// Remove prefix for cgroups with no controller, eg. systemd.\nctrlr = strings.TrimPrefix(ctrlr, \"name=\")\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cgroup/cgroup_test.go",
"new_path": "runsc/cgroup/cgroup_test.go",
"diff": "@@ -647,3 +647,83 @@ func TestPids(t *testing.T) {\n})\n}\n}\n+\n+func TestLoadPaths(t *testing.T) {\n+ for _, tc := range []struct {\n+ name string\n+ cgroups string\n+ want map[string]string\n+ err string\n+ }{\n+ {\n+ name: \"abs-path\",\n+ cgroups: \"0:ctr:/path\",\n+ want: map[string]string{\"ctr\": \"/path\"},\n+ },\n+ {\n+ name: \"rel-path\",\n+ cgroups: \"0:ctr:rel-path\",\n+ want: map[string]string{\"ctr\": \"rel-path\"},\n+ },\n+ {\n+ name: \"non-controller\",\n+ cgroups: \"0:name=systemd:/path\",\n+ want: map[string]string{\"systemd\": \"/path\"},\n+ },\n+ {\n+ name: \"empty\",\n+ },\n+ {\n+ name: \"multiple\",\n+ cgroups: \"0:ctr0:/path0\\n\" +\n+ \"1:ctr1:/path1\\n\" +\n+ \"2::/empty\\n\",\n+ want: map[string]string{\n+ \"ctr0\": \"/path0\",\n+ \"ctr1\": \"/path1\",\n+ },\n+ },\n+ {\n+ name: \"missing-field\",\n+ cgroups: \"0:nopath\\n\",\n+ err: \"invalid cgroups file\",\n+ },\n+ {\n+ name: \"too-many-fields\",\n+ cgroups: \"0:ctr:/path:extra\\n\",\n+ err: \"invalid cgroups file\",\n+ },\n+ {\n+ name: \"multiple-malformed\",\n+ cgroups: \"0:ctr0:/path0\\n\" +\n+ \"1:ctr1:/path1\\n\" +\n+ \"2:\\n\",\n+ err: \"invalid cgroups file\",\n+ },\n+ } {\n+ t.Run(tc.name, func(t *testing.T) {\n+ r := strings.NewReader(tc.cgroups)\n+ got, err := loadPathsHelper(r)\n+ if len(tc.err) == 0 {\n+ if err != nil {\n+ t.Fatalf(\"Unexpected error: %v\", err)\n+ }\n+ } else if !strings.Contains(err.Error(), tc.err) {\n+ t.Fatalf(\"Wrong error message, want: *%s*, got: %v\", tc.err, err)\n+ }\n+ for key, vWant := range tc.want {\n+ vGot, ok := got[key]\n+ if !ok {\n+ t.Errorf(\"Missing controller %q\", key)\n+ }\n+ if vWant != vGot {\n+ t.Errorf(\"Wrong controller %q value, want: %q, got: %q\", key, vWant, vGot)\n+ }\n+ delete(got, key)\n+ }\n+ for k, v := range got {\n+ t.Errorf(\"Unexpected controller %q: %q\", k, v)\n+ }\n+ })\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add more cgroup unit tests
PiperOrigin-RevId: 339380431 |
260,003 | 28.10.2020 09:38:17 | 25,200 | 8fa18e8ecb3e3da2015e5c73db9e46494dcfeff7 | Bump honnef.co/go/tools to v0.0.1-2020.1.6 | [
{
"change_type": "MODIFY",
"old_path": "WORKSPACE",
"new_path": "WORKSPACE",
"diff": "@@ -482,8 +482,8 @@ go_repository(\ngo_repository(\nname = \"co_honnef_go_tools\",\nimportpath = \"honnef.co/go/tools\",\n- sum = \"h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM=\",\n- version = \"v0.0.1-2019.2.3\",\n+ sum = \"h1:W18jzjh8mfPez+AwGLxmOImucz/IFjpNlrKVnaj2YVc=\",\n+ version = \"v0.0.1-2020.1.6\",\n)\ngo_repository(\n"
},
{
"change_type": "MODIFY",
"old_path": "nogo.yaml",
"new_path": "nogo.yaml",
"diff": "@@ -32,6 +32,8 @@ global:\n# go_embed_data rules generate unicode literals.\n- \"string literal contains the Unicode format character\"\n- \"string literal contains the Unicode control character\"\n+ - \"string literal contains Unicode control characters\"\n+ - \"string literal contains Unicode format and control characters\"\n# Some external code will generate protov1\n# implementations. These should be ignored.\n- \"proto.* is deprecated\"\n@@ -101,6 +103,7 @@ global:\n- pkg/sentry/fs/dev/net_tun.go:63\n- pkg/sentry/fs/dev/null.go:97\n- pkg/sentry/fs/dirent_cache.go:64\n+ - pkg/sentry/fs/fdpipe/pipe_opener_test.go:366\n- pkg/sentry/fs/file_overlay.go:327\n- pkg/sentry/fs/file_overlay.go:524\n- pkg/sentry/fs/filetest/filetest.go:55\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/dut_client.go",
"new_path": "test/packetimpact/testbench/dut_client.go",
"diff": "@@ -19,7 +19,7 @@ import (\npb \"gvisor.dev/gvisor/test/packetimpact/proto/posix_server_go_proto\"\n)\n-// PosixClient is a gRPC client for the Posix service.\n+// POSIXClient is a gRPC client for the Posix service.\ntype POSIXClient pb.PosixClient\n// NewPOSIXClient makes a new gRPC client for the POSIX service.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Bump honnef.co/go/tools to v0.0.1-2020.1.6
PiperOrigin-RevId: 339476515 |
259,907 | 28.10.2020 11:46:18 | 25,200 | 4cc3894b27e8cfddb507b4c68b95695ec3979eba | [vfs] Refactor hostfs mmap into kernfs util. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/host/BUILD",
"new_path": "pkg/sentry/fsimpl/host/BUILD",
"diff": "@@ -33,7 +33,6 @@ go_library(\n\"host.go\",\n\"inode_refs.go\",\n\"ioctl_unsafe.go\",\n- \"mmap.go\",\n\"save_restore.go\",\n\"socket.go\",\n\"socket_iovec.go\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/host/host.go",
"new_path": "pkg/sentry/fsimpl/host/host.go",
"diff": "@@ -48,6 +48,7 @@ type inode struct {\nkernfs.InodeNoStatFS\nkernfs.InodeNotDirectory\nkernfs.InodeNotSymlink\n+ kernfs.CachedMappable\nkernfs.InodeTemporary // This holds no meaning as this inode can't be Looked up and is always valid.\nlocks vfs.FileLocks\n@@ -96,16 +97,6 @@ type inode struct {\n// Event queue for blocking operations.\nqueue waiter.Queue\n- // mapsMu protects mappings.\n- mapsMu sync.Mutex `state:\"nosave\"`\n-\n- // If this file is mmappable, mappings tracks mappings of hostFD into\n- // memmap.MappingSpaces.\n- mappings memmap.MappingSet\n-\n- // pf implements platform.File for mappings of hostFD.\n- pf inodePlatformFile\n-\n// If haveBuf is non-zero, hostFD represents a pipe, and buf contains data\n// read from the pipe from previous calls to inode.beforeSave(). haveBuf\n// and buf are protected by bufMu. haveBuf is accessed using atomic memory\n@@ -135,7 +126,7 @@ func newInode(ctx context.Context, fs *filesystem, hostFD int, savable bool, fil\nisTTY: isTTY,\nsavable: savable,\n}\n- i.pf.inode = i\n+ i.CachedMappable.Init(hostFD)\ni.EnableLeakCheck()\n// If the hostFD can return EWOULDBLOCK when set to non-blocking, do so and\n@@ -439,14 +430,7 @@ func (i *inode) SetStat(ctx context.Context, fs *vfs.Filesystem, creds *auth.Cre\noldpgend, _ := usermem.PageRoundUp(oldSize)\nnewpgend, _ := usermem.PageRoundUp(s.Size)\nif oldpgend != newpgend {\n- i.mapsMu.Lock()\n- i.mappings.Invalidate(memmap.MappableRange{newpgend, oldpgend}, memmap.InvalidateOpts{\n- // Compare Linux's mm/truncate.c:truncate_setsize() =>\n- // truncate_pagecache() =>\n- // mm/memory.c:unmap_mapping_range(evencows=1).\n- InvalidatePrivate: true,\n- })\n- i.mapsMu.Unlock()\n+ i.CachedMappable.InvalidateRange(memmap.MappableRange{newpgend, oldpgend})\n}\n}\n}\n@@ -797,7 +781,7 @@ func (f *fileDescription) ConfigureMMap(_ context.Context, opts *memmap.MMapOpts\nreturn syserror.ENODEV\n}\ni := f.inode\n- i.pf.fileMapperInitOnce.Do(i.pf.fileMapper.Init)\n+ i.CachedMappable.InitFileMapperOnce()\nreturn vfs.GenericConfigureMMap(&f.vfsfd, i, opts)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/host/save_restore.go",
"new_path": "pkg/sentry/fsimpl/host/save_restore.go",
"diff": "@@ -68,11 +68,3 @@ func (i *inode) afterLoad() {\n}\n}\n}\n-\n-// afterLoad is invoked by stateify.\n-func (i *inodePlatformFile) afterLoad() {\n- if i.fileMapper.IsInited() {\n- // Ensure that we don't call i.fileMapper.Init() again.\n- i.fileMapperInitOnce.Do(func() {})\n- }\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/BUILD",
"new_path": "pkg/sentry/fsimpl/kernfs/BUILD",
"diff": "@@ -92,6 +92,8 @@ go_library(\n\"fstree.go\",\n\"inode_impl_util.go\",\n\"kernfs.go\",\n+ \"mmap_util.go\",\n+ \"save_restore.go\",\n\"slot_list.go\",\n\"static_directory_refs.go\",\n\"symlink.go\",\n@@ -106,6 +108,7 @@ go_library(\n\"//pkg/log\",\n\"//pkg/refs\",\n\"//pkg/refsvfs2\",\n+ \"//pkg/safemem\",\n\"//pkg/sentry/fs/fsutil\",\n\"//pkg/sentry/fs/lock\",\n\"//pkg/sentry/kernel/auth\",\n"
},
{
"change_type": "RENAME",
"old_path": "pkg/sentry/fsimpl/host/mmap.go",
"new_path": "pkg/sentry/fsimpl/kernfs/mmap_util.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-package host\n+package kernfs\nimport (\n\"gvisor.dev/gvisor/pkg/context\"\n@@ -26,11 +26,14 @@ import (\n// inodePlatformFile implements memmap.File. It exists solely because inode\n// cannot implement both kernfs.Inode.IncRef and memmap.File.IncRef.\n//\n-// inodePlatformFile should only be used if inode.canMap is true.\n-//\n// +stateify savable\ntype inodePlatformFile struct {\n- *inode\n+ // hostFD contains the host fd that this file was originally created from,\n+ // which must be available at time of restore.\n+ //\n+ // This field is initialized at creation time and is immutable.\n+ // inodePlatformFile does not own hostFD and hence should not close it.\n+ hostFD int\n// fdRefsMu protects fdRefs.\nfdRefsMu sync.Mutex `state:\"nosave\"`\n@@ -46,9 +49,9 @@ type inodePlatformFile struct {\nfileMapperInitOnce sync.Once `state:\"nosave\"`\n}\n+var _ memmap.File = (*inodePlatformFile)(nil)\n+\n// IncRef implements memmap.File.IncRef.\n-//\n-// Precondition: i.inode.canMap must be true.\nfunc (i *inodePlatformFile) IncRef(fr memmap.FileRange) {\ni.fdRefsMu.Lock()\ni.fdRefs.IncRefAndAccount(fr)\n@@ -56,8 +59,6 @@ func (i *inodePlatformFile) IncRef(fr memmap.FileRange) {\n}\n// DecRef implements memmap.File.DecRef.\n-//\n-// Precondition: i.inode.canMap must be true.\nfunc (i *inodePlatformFile) DecRef(fr memmap.FileRange) {\ni.fdRefsMu.Lock()\ni.fdRefs.DecRefAndAccount(fr)\n@@ -65,8 +66,6 @@ func (i *inodePlatformFile) DecRef(fr memmap.FileRange) {\n}\n// MapInternal implements memmap.File.MapInternal.\n-//\n-// Precondition: i.inode.canMap must be true.\nfunc (i *inodePlatformFile) MapInternal(fr memmap.FileRange, at usermem.AccessType) (safemem.BlockSeq, error) {\nreturn i.fileMapper.MapInternal(fr, i.hostFD, at.Write)\n}\n@@ -76,10 +75,32 @@ func (i *inodePlatformFile) FD() int {\nreturn i.hostFD\n}\n-// AddMapping implements memmap.Mappable.AddMapping.\n+// CachedMappable implements memmap.Mappable. This utility can be embedded in a\n+// kernfs.Inode that represents a host file to make the inode mappable.\n+// CachedMappable caches the mappings of the host file. CachedMappable must be\n+// initialized (via Init) with a hostFD before use.\n//\n-// Precondition: i.inode.canMap must be true.\n-func (i *inode) AddMapping(ctx context.Context, ms memmap.MappingSpace, ar usermem.AddrRange, offset uint64, writable bool) error {\n+// +stateify savable\n+type CachedMappable struct {\n+ // mapsMu protects mappings.\n+ mapsMu sync.Mutex `state:\"nosave\"`\n+\n+ // mappings tracks mappings of hostFD into memmap.MappingSpaces.\n+ mappings memmap.MappingSet\n+\n+ // pf implements memmap.File for mappings backed by a host fd.\n+ pf inodePlatformFile\n+}\n+\n+var _ memmap.Mappable = (*CachedMappable)(nil)\n+\n+// Init initializes i.pf. This must be called before using CachedMappable.\n+func (i *CachedMappable) Init(hostFD int) {\n+ i.pf.hostFD = hostFD\n+}\n+\n+// AddMapping implements memmap.Mappable.AddMapping.\n+func (i *CachedMappable) AddMapping(ctx context.Context, ms memmap.MappingSpace, ar usermem.AddrRange, offset uint64, writable bool) error {\ni.mapsMu.Lock()\nmapped := i.mappings.AddMapping(ms, ar, offset, writable)\nfor _, r := range mapped {\n@@ -90,9 +111,7 @@ func (i *inode) AddMapping(ctx context.Context, ms memmap.MappingSpace, ar userm\n}\n// RemoveMapping implements memmap.Mappable.RemoveMapping.\n-//\n-// Precondition: i.inode.canMap must be true.\n-func (i *inode) RemoveMapping(ctx context.Context, ms memmap.MappingSpace, ar usermem.AddrRange, offset uint64, writable bool) {\n+func (i *CachedMappable) RemoveMapping(ctx context.Context, ms memmap.MappingSpace, ar usermem.AddrRange, offset uint64, writable bool) {\ni.mapsMu.Lock()\nunmapped := i.mappings.RemoveMapping(ms, ar, offset, writable)\nfor _, r := range unmapped {\n@@ -102,16 +121,12 @@ func (i *inode) RemoveMapping(ctx context.Context, ms memmap.MappingSpace, ar us\n}\n// CopyMapping implements memmap.Mappable.CopyMapping.\n-//\n-// Precondition: i.inode.canMap must be true.\n-func (i *inode) CopyMapping(ctx context.Context, ms memmap.MappingSpace, srcAR, dstAR usermem.AddrRange, offset uint64, writable bool) error {\n+func (i *CachedMappable) CopyMapping(ctx context.Context, ms memmap.MappingSpace, srcAR, dstAR usermem.AddrRange, offset uint64, writable bool) error {\nreturn i.AddMapping(ctx, ms, dstAR, offset, writable)\n}\n// Translate implements memmap.Mappable.Translate.\n-//\n-// Precondition: i.inode.canMap must be true.\n-func (i *inode) Translate(ctx context.Context, required, optional memmap.MappableRange, at usermem.AccessType) ([]memmap.Translation, error) {\n+func (i *CachedMappable) Translate(ctx context.Context, required, optional memmap.MappableRange, at usermem.AccessType) ([]memmap.Translation, error) {\nmr := optional\nreturn []memmap.Translation{\n{\n@@ -124,10 +139,26 @@ func (i *inode) Translate(ctx context.Context, required, optional memmap.Mappabl\n}\n// InvalidateUnsavable implements memmap.Mappable.InvalidateUnsavable.\n-//\n-// Precondition: i.inode.canMap must be true.\n-func (i *inode) InvalidateUnsavable(ctx context.Context) error {\n+func (i *CachedMappable) InvalidateUnsavable(ctx context.Context) error {\n// We expect the same host fd across save/restore, so all translations\n// should be valid.\nreturn nil\n}\n+\n+// InvalidateRange invalidates the passed range on i.mappings.\n+func (i *CachedMappable) InvalidateRange(r memmap.MappableRange) {\n+ i.mapsMu.Lock()\n+ i.mappings.Invalidate(r, memmap.InvalidateOpts{\n+ // Compare Linux's mm/truncate.c:truncate_setsize() =>\n+ // truncate_pagecache() =>\n+ // mm/memory.c:unmap_mapping_range(evencows=1).\n+ InvalidatePrivate: true,\n+ })\n+ i.mapsMu.Unlock()\n+}\n+\n+// InitFileMapperOnce initializes the host file mapper. It ensures that the\n+// file mapper is initialized just once.\n+func (i *CachedMappable) InitFileMapperOnce() {\n+ i.pf.fileMapperInitOnce.Do(i.pf.fileMapper.Init)\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fsimpl/kernfs/save_restore.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 kernfs\n+\n+// afterLoad is invoked by stateify.\n+func (i *inodePlatformFile) afterLoad() {\n+ if i.fileMapper.IsInited() {\n+ // Ensure that we don't call i.fileMapper.Init() again.\n+ i.fileMapperInitOnce.Do(func() {})\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | [vfs] Refactor hostfs mmap into kernfs util.
PiperOrigin-RevId: 339505487 |
259,885 | 28.10.2020 13:40:56 | 25,200 | 9907539d92f0233fa7a0daba22484085da44d1c4 | Invalidate overlay.dentry.dirents during open() file creation.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/overlay/filesystem.go",
"new_path": "pkg/sentry/fsimpl/overlay/filesystem.go",
"diff": "@@ -976,7 +976,10 @@ func (fs *filesystem) createAndOpenLocked(ctx context.Context, rp *vfs.Resolving\n}\nreturn nil, err\n}\n- // Finally construct the overlay FD.\n+ // Finally construct the overlay FD. Below this point, we don't perform\n+ // cleanup (the file was created successfully even if we can no longer open\n+ // it for some reason).\n+ parent.dirents = nil\nupperFlags := upperFD.StatusFlags()\nfd := ®ularFileFD{\ncopiedUp: true,\n@@ -987,8 +990,6 @@ func (fs *filesystem) createAndOpenLocked(ctx context.Context, rp *vfs.Resolving\nupperFDOpts := upperFD.Options()\nif err := fd.vfsfd.Init(fd, upperFlags, mnt, &child.vfsd, &upperFDOpts); err != nil {\nupperFD.DecRef(ctx)\n- // Don't bother with cleanup; the file was created successfully, we\n- // just can't open it anymore for some reason.\nreturn nil, err\n}\nparent.watches.Notify(ctx, childName, linux.IN_CREATE, 0 /* cookie */, vfs.PathEvent, false /* unlinked */)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Invalidate overlay.dentry.dirents during open() file creation.
Updates #1199
PiperOrigin-RevId: 339528827 |
259,858 | 28.10.2020 17:25:58 | 25,200 | b4b42a5fce4cdd134d7d28d96ae7d4862791d911 | Traversal embedded libraries, even for go_library rules. | [
{
"change_type": "MODIFY",
"old_path": "tools/bazeldefs/go.bzl",
"new_path": "tools/bazeldefs/go.bzl",
"diff": "@@ -94,10 +94,10 @@ def go_rule(rule, implementation, **kwargs):\ntoolchains = kwargs.get(\"toolchains\", []) + [\"@io_bazel_rules_go//go:toolchain\"]\nreturn rule(implementation, attrs = attrs, toolchains = toolchains, **kwargs)\n-def go_test_library(target):\n- if hasattr(target.attr, \"embed\") and len(target.attr.embed) > 0:\n- return target.attr.embed[0]\n- return None\n+def go_embed_libraries(target):\n+ if hasattr(target.attr, \"embed\"):\n+ return target.attr.embed\n+ return []\ndef go_context(ctx, goos = None, goarch = None, std = False):\n\"\"\"Extracts a standard Go context struct.\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/nogo/defs.bzl",
"new_path": "tools/nogo/defs.bzl",
"diff": "\"\"\"Nogo rules.\"\"\"\n-load(\"//tools/bazeldefs:go.bzl\", \"go_context\", \"go_importpath\", \"go_rule\", \"go_test_library\")\n+load(\"//tools/bazeldefs:go.bzl\", \"go_context\", \"go_embed_libraries\", \"go_importpath\", \"go_rule\")\nNogoConfigInfo = provider(\n\"information about a nogo configuration\",\n@@ -200,10 +200,8 @@ def _nogo_aspect_impl(target, ctx):\n# If we're using the \"library\" attribute, then we need to aggregate the\n# original library sources and dependencies into this target to perform\n# proper type analysis.\n- if ctx.rule.kind == \"go_test\":\n- library = go_test_library(ctx.rule)\n- if library != None:\n- info = library[NogoInfo]\n+ for embed in go_embed_libraries(ctx.rule):\n+ info = embed[NogoInfo]\nif hasattr(info, \"srcs\"):\nsrcs = srcs + info.srcs\nif hasattr(info, \"deps\"):\n"
}
] | Go | Apache License 2.0 | google/gvisor | Traversal embedded libraries, even for go_library rules.
PiperOrigin-RevId: 339570821 |
259,860 | 28.10.2020 18:16:30 | 25,200 | 3b4674ffe0e6ef1b016333ee726293ecf70c4e4e | Add logging option to leak checker.
Also refactor the template and CheckedObject interface to make this cleaner.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/refs/refcounter.go",
"new_path": "pkg/refs/refcounter.go",
"diff": "@@ -319,7 +319,8 @@ func makeStackKey(pcs []uintptr) stackKey {\nreturn key\n}\n-func recordStack() []uintptr {\n+// RecordStack constructs and returns the PCs on the current stack.\n+func RecordStack() []uintptr {\npcs := make([]uintptr, maxStackFrames)\nn := runtime.Callers(1, pcs)\nif n == 0 {\n@@ -342,7 +343,8 @@ func recordStack() []uintptr {\nreturn v\n}\n-func formatStack(pcs []uintptr) string {\n+// FormatStack converts the given stack into a readable format.\n+func FormatStack(pcs []uintptr) string {\nframes := runtime.CallersFrames(pcs)\nvar trace bytes.Buffer\nfor {\n@@ -367,7 +369,7 @@ func (r *AtomicRefCount) finalize() {\nif n := r.ReadRefs(); n != 0 {\nmsg := fmt.Sprintf(\"%sAtomicRefCount %p owned by %q garbage collected with ref count of %d (want 0)\", note, r, r.name, n)\nif len(r.stack) != 0 {\n- msg += \":\\nCaller:\\n\" + formatStack(r.stack)\n+ msg += \":\\nCaller:\\n\" + FormatStack(r.stack)\n} else {\nmsg += \" (enable trace logging to debug)\"\n}\n@@ -392,7 +394,7 @@ func (r *AtomicRefCount) EnableLeakCheck(name string) {\ncase NoLeakChecking:\nreturn\ncase LeaksLogTraces:\n- r.stack = recordStack()\n+ r.stack = RecordStack()\n}\nr.name = name\nruntime.SetFinalizer(r, (*AtomicRefCount).finalize)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/refsvfs2/BUILD",
"new_path": "pkg/refsvfs2/BUILD",
"diff": "@@ -8,6 +8,9 @@ go_template(\nsrcs = [\n\"refs_template.go\",\n],\n+ opt_consts = [\n+ \"logTrace\",\n+ ],\ntypes = [\n\"T\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/refsvfs2/refs_map.go",
"new_path": "pkg/refsvfs2/refs_map.go",
"diff": "@@ -37,24 +37,31 @@ var (\n// CheckedObject represents a reference-counted object with an informative\n// leak detection message.\ntype CheckedObject interface {\n+ // RefType is the type of the reference-counted object.\n+ RefType() string\n+\n// LeakMessage supplies a warning to be printed upon leak detection.\nLeakMessage() string\n+\n+ // LogRefs indicates whether reference-related events should be logged.\n+ LogRefs() bool\n}\nfunc init() {\nliveObjects = make(map[CheckedObject]struct{})\n}\n-// LeakCheckEnabled returns whether leak checking is enabled. The following\n+// leakCheckEnabled returns whether leak checking is enabled. The following\n// functions should only be called if it returns true.\n-func LeakCheckEnabled() bool {\n+func leakCheckEnabled() bool {\nreturn refs_vfs1.GetLeakMode() != refs_vfs1.NoLeakChecking\n}\n// Register adds obj to the live object map.\n-func Register(obj CheckedObject, typ string) {\n+func Register(obj CheckedObject) {\n+ if leakCheckEnabled() {\nfor _, str := range ignored {\n- if strings.Contains(typ, str) {\n+ if strings.Contains(obj.RefType(), str) {\nreturn\n}\n}\n@@ -64,27 +71,56 @@ func Register(obj CheckedObject, typ string) {\n}\nliveObjects[obj] = struct{}{}\nliveObjectsMu.Unlock()\n+ logEvent(obj, \"registered\")\n+ }\n}\n// Unregister removes obj from the live object map.\n-func Unregister(obj CheckedObject, typ string) {\n+func Unregister(obj CheckedObject) {\n+ if leakCheckEnabled() {\nliveObjectsMu.Lock()\ndefer liveObjectsMu.Unlock()\nif _, ok := liveObjects[obj]; !ok {\nfor _, str := range ignored {\n- if strings.Contains(typ, str) {\n+ if strings.Contains(obj.RefType(), str) {\nreturn\n}\n}\npanic(fmt.Sprintf(\"Expected to find entry in leak checking map for reference %p\", obj))\n}\ndelete(liveObjects, obj)\n+ logEvent(obj, \"unregistered\")\n+ }\n+}\n+\n+// LogIncRef logs a reference increment.\n+func LogIncRef(obj CheckedObject, refs int64) {\n+ logEvent(obj, fmt.Sprintf(\"IncRef to %d\", refs))\n+}\n+\n+// LogTryIncRef logs a successful TryIncRef call.\n+func LogTryIncRef(obj CheckedObject, refs int64) {\n+ logEvent(obj, fmt.Sprintf(\"TryIncRef to %d\", refs))\n+}\n+\n+// LogDecRef logs a reference decrement.\n+func LogDecRef(obj CheckedObject, refs int64) {\n+ logEvent(obj, fmt.Sprintf(\"DecRef to %d\", refs))\n+}\n+\n+// logEvent logs a message for the given reference-counted object.\n+func logEvent(obj CheckedObject, msg string) {\n+ if obj.LogRefs() {\n+ log.Infof(\"[%s %p] %s:\", obj.RefType(), obj, msg)\n+ log.Infof(refs_vfs1.FormatStack(refs_vfs1.RecordStack()))\n+ }\n}\n// DoLeakCheck iterates through the live object map and logs a message for each\n// object. It is called once no reference-counted objects should be reachable\n// anymore, at which point anything left in the map is considered a leak.\nfunc DoLeakCheck() {\n+ if leakCheckEnabled() {\nliveObjectsMu.Lock()\ndefer liveObjectsMu.Unlock()\nleaked := len(liveObjects)\n@@ -95,3 +131,4 @@ func DoLeakCheck() {\n}\n}\n}\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/refsvfs2/refs_template.go",
"new_path": "pkg/refsvfs2/refs_template.go",
"diff": "@@ -26,13 +26,19 @@ import (\n\"gvisor.dev/gvisor/pkg/refsvfs2\"\n)\n+// enableLogging indicates whether reference-related events should be logged (with\n+// stack traces). This is false by default and should only be set to true for\n+// debugging purposes, as it can generate an extremely large amount of output\n+// and drastically degrade performance.\n+const enableLogging = false\n+\n// T is the type of the reference counted object. It is only used to customize\n// debug output when leak checking.\ntype T interface{}\n-// ownerType is used to customize logging. Note that we use a pointer to T so\n-// that we do not copy the entire object when passed as a format parameter.\n-var ownerType *T\n+// obj is used to customize logging. Note that we use a pointer to T so that\n+// we do not copy the entire object when passed as a format parameter.\n+var obj *T\n// Refs implements refs.RefCounter. It keeps a reference count using atomic\n// operations and calls the destructor when the count reaches zero.\n@@ -52,16 +58,24 @@ type Refs struct {\nrefCount int64\n}\n-// EnableLeakCheck enables reference leak checking on r.\n-func (r *Refs) EnableLeakCheck() {\n- if refsvfs2.LeakCheckEnabled() {\n- refsvfs2.Register(r, fmt.Sprintf(\"%T\", ownerType))\n- }\n+// RefType implements refsvfs2.CheckedObject.RefType.\n+func (r *Refs) RefType() string {\n+ return fmt.Sprintf(\"%T\", obj)[1:]\n}\n// LeakMessage implements refsvfs2.CheckedObject.LeakMessage.\nfunc (r *Refs) LeakMessage() string {\n- return fmt.Sprintf(\"%T %p: reference count of %d instead of 0\", ownerType, r, r.ReadRefs())\n+ return fmt.Sprintf(\"[%s %p] reference count of %d instead of 0\", r.RefType(), r, r.ReadRefs())\n+}\n+\n+// LogRefs implements refsvfs2.CheckedObject.LogRefs.\n+func (r *Refs) LogRefs() bool {\n+ return enableLogging\n+}\n+\n+// EnableLeakCheck enables reference leak checking on r.\n+func (r *Refs) EnableLeakCheck() {\n+ refsvfs2.Register(r)\n}\n// ReadRefs returns the current number of references. The returned count is\n@@ -75,8 +89,10 @@ func (r *Refs) ReadRefs() int64 {\n//\n//go:nosplit\nfunc (r *Refs) IncRef() {\n- if v := atomic.AddInt64(&r.refCount, 1); v <= 0 {\n- panic(fmt.Sprintf(\"Incrementing non-positive count %p on %T\", r, ownerType))\n+ v := atomic.AddInt64(&r.refCount, 1)\n+ refsvfs2.LogIncRef(r, v+1)\n+ if v <= 0 {\n+ panic(fmt.Sprintf(\"Incrementing non-positive count %p on %s\", r, r.RefType()))\n}\n}\n@@ -89,15 +105,15 @@ func (r *Refs) IncRef() {\n//go:nosplit\nfunc (r *Refs) TryIncRef() bool {\nconst speculativeRef = 1 << 32\n- v := atomic.AddInt64(&r.refCount, speculativeRef)\n- if int32(v) < 0 {\n+ if v := atomic.AddInt64(&r.refCount, speculativeRef); int32(v) < 0 {\n// This object has already been freed.\natomic.AddInt64(&r.refCount, -speculativeRef)\nreturn false\n}\n// Turn into a real reference.\n- atomic.AddInt64(&r.refCount, -speculativeRef+1)\n+ v := atomic.AddInt64(&r.refCount, -speculativeRef+1)\n+ refsvfs2.LogTryIncRef(r, v+1)\nreturn true\n}\n@@ -114,14 +130,14 @@ func (r *Refs) TryIncRef() bool {\n//\n//go:nosplit\nfunc (r *Refs) DecRef(destroy func()) {\n- switch v := atomic.AddInt64(&r.refCount, -1); {\n+ v := atomic.AddInt64(&r.refCount, -1)\n+ refsvfs2.LogDecRef(r, v+1)\n+ switch {\ncase v < -1:\n- panic(fmt.Sprintf(\"Decrementing non-positive ref count %p, owned by %T\", r, ownerType))\n+ panic(fmt.Sprintf(\"Decrementing non-positive ref count %p, owned by %s\", r, r.RefType()))\ncase v == -1:\n- if refsvfs2.LeakCheckEnabled() {\n- refsvfs2.Unregister(r, fmt.Sprintf(\"%T\", ownerType))\n- }\n+ refsvfs2.Unregister(r)\n// Call the destructor.\nif destroy != nil {\ndestroy()\n@@ -130,7 +146,7 @@ func (r *Refs) DecRef(destroy func()) {\n}\nfunc (r *Refs) afterLoad() {\n- if refsvfs2.LeakCheckEnabled() && r.ReadRefs() > 0 {\n+ if r.ReadRefs() > 0 {\nr.EnableLeakCheck()\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/directory.go",
"new_path": "pkg/sentry/fsimpl/gofer/directory.go",
"diff": "@@ -101,9 +101,7 @@ func (d *dentry) createSyntheticChildLocked(opts *createSyntheticOpts) {\nhostFD: -1,\nnlink: uint32(2),\n}\n- if refsvfs2.LeakCheckEnabled() {\n- refsvfs2.Register(child, \"gofer.dentry\")\n- }\n+ refsvfs2.Register(child)\nswitch opts.mode.FileType() {\ncase linux.S_IFDIR:\n// Nothing else needs to be done.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"new_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"diff": "@@ -262,7 +262,7 @@ func (fs *filesystem) revalidateChildLocked(ctx context.Context, vfsObj *vfs.Vir\n// treat their invalidation as deletion.\nchild.setDeleted()\nparent.syntheticChildren--\n- child.decRefLocked()\n+ child.decRefNoCaching()\nparent.dirents = nil\n}\n*ds = appendDentry(*ds, child)\n@@ -631,7 +631,7 @@ func (fs *filesystem) unlinkAt(ctx context.Context, rp *vfs.ResolvingPath, dir b\nchild.setDeleted()\nif child.isSynthetic() {\nparent.syntheticChildren--\n- child.decRefLocked()\n+ child.decRefNoCaching()\n}\nds = appendDentry(ds, child)\n}\n@@ -1361,7 +1361,7 @@ func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\nreplaced.setDeleted()\nif replaced.isSynthetic() {\nnewParent.syntheticChildren--\n- replaced.decRefLocked()\n+ replaced.decRefNoCaching()\n}\nds = appendDentry(ds, replaced)\n}\n@@ -1370,7 +1370,7 @@ func (fs *filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\n// with reference counts and queue oldParent for checkCachingLocked if the\n// parent isn't actually changing.\nif oldParent != newParent {\n- oldParent.decRefLocked()\n+ oldParent.decRefNoCaching()\nds = appendDentry(ds, oldParent)\nnewParent.IncRef()\nif renamed.isSynthetic() {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"diff": "@@ -590,7 +590,7 @@ func (fs *filesystem) Release(ctx context.Context) {\n// Precondition: d.fs.renameMu is locked.\nfunc (d *dentry) releaseSyntheticRecursiveLocked(ctx context.Context) {\nif d.isSynthetic() {\n- d.decRefLocked()\n+ d.decRefNoCaching()\nd.checkCachingLocked(ctx)\n}\nif d.isDir() {\n@@ -860,10 +860,7 @@ func (fs *filesystem) newDentry(ctx context.Context, file p9file, qid p9.QID, ma\nd.nlink = uint32(attr.NLink)\n}\nd.vfsd.Init(d)\n- if refsvfs2.LeakCheckEnabled() {\n- refsvfs2.Register(d, \"gofer.dentry\")\n- }\n-\n+ refsvfs2.Register(d)\nfs.syncMu.Lock()\nfs.syncableDentries[d] = struct{}{}\nfs.syncMu.Unlock()\n@@ -1222,17 +1219,19 @@ func dentryGIDFromP9GID(gid p9.GID) uint32 {\nfunc (d *dentry) IncRef() {\n// d.refs may be 0 if d.fs.renameMu is locked, which serializes against\n// d.checkCachingLocked().\n- atomic.AddInt64(&d.refs, 1)\n+ r := atomic.AddInt64(&d.refs, 1)\n+ refsvfs2.LogIncRef(d, r)\n}\n// TryIncRef implements vfs.DentryImpl.TryIncRef.\nfunc (d *dentry) TryIncRef() bool {\nfor {\n- refs := atomic.LoadInt64(&d.refs)\n- if refs <= 0 {\n+ r := atomic.LoadInt64(&d.refs)\n+ if r <= 0 {\nreturn false\n}\n- if atomic.CompareAndSwapInt64(&d.refs, refs, refs+1) {\n+ if atomic.CompareAndSwapInt64(&d.refs, r, r+1) {\n+ refsvfs2.LogTryIncRef(d, r+1)\nreturn true\n}\n}\n@@ -1240,22 +1239,28 @@ func (d *dentry) TryIncRef() bool {\n// DecRef implements vfs.DentryImpl.DecRef.\nfunc (d *dentry) DecRef(ctx context.Context) {\n- if refs := atomic.AddInt64(&d.refs, -1); refs == 0 {\n+ if d.decRefNoCaching() == 0 {\nd.fs.renameMu.Lock()\nd.checkCachingLocked(ctx)\nd.fs.renameMu.Unlock()\n- } else if refs < 0 {\n- panic(\"gofer.dentry.DecRef() called without holding a reference\")\n}\n}\n-// decRefLocked decrements d's reference count without calling\n+// decRefNoCaching decrements d's reference count without calling\n// d.checkCachingLocked, even if d's reference count reaches 0; callers are\n// responsible for ensuring that d.checkCachingLocked will be called later.\n-func (d *dentry) decRefLocked() {\n- if refs := atomic.AddInt64(&d.refs, -1); refs < 0 {\n- panic(\"gofer.dentry.decRefLocked() called without holding a reference\")\n+func (d *dentry) decRefNoCaching() int64 {\n+ r := atomic.AddInt64(&d.refs, -1)\n+ refsvfs2.LogDecRef(d, r)\n+ if r < 0 {\n+ panic(\"gofer.dentry.decRefNoCaching() called without holding a reference\")\n}\n+ return r\n+}\n+\n+// RefType implements refsvfs2.CheckedObject.Type.\n+func (d *dentry) RefType() string {\n+ return \"gofer.dentry\"\n}\n// LeakMessage implements refsvfs2.CheckedObject.LeakMessage.\n@@ -1263,6 +1268,14 @@ func (d *dentry) LeakMessage() string {\nreturn fmt.Sprintf(\"[gofer.dentry %p] reference count of %d instead of -1\", d, atomic.LoadInt64(&d.refs))\n}\n+// LogRefs implements refsvfs2.CheckedObject.LogRefs.\n+//\n+// This should only be set to true for debugging purposes, as it can generate an\n+// extremely large amount of output and drastically degrade performance.\n+func (d *dentry) LogRefs() bool {\n+ return false\n+}\n+\n// InotifyWithParent implements vfs.DentryImpl.InotifyWithParent.\nfunc (d *dentry) InotifyWithParent(ctx context.Context, events, cookie uint32, et vfs.EventType) {\nif d.isDir() {\n@@ -1486,17 +1499,10 @@ func (d *dentry) destroyLocked(ctx context.Context) {\n// Drop the reference held by d on its parent without recursively locking\n// d.fs.renameMu.\n- if d.parent != nil {\n- if refs := atomic.AddInt64(&d.parent.refs, -1); refs == 0 {\n+ if d.parent != nil && d.parent.decRefNoCaching() == 0 {\nd.parent.checkCachingLocked(ctx)\n- } else if refs < 0 {\n- panic(\"gofer.dentry.DecRef() called without holding a reference\")\n- }\n- }\n-\n- if refsvfs2.LeakCheckEnabled() {\n- refsvfs2.Unregister(d, \"gofer.dentry\")\n}\n+ refsvfs2.Unregister(d)\n}\nfunc (d *dentry) isDeleted() bool {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/save_restore.go",
"new_path": "pkg/sentry/fsimpl/gofer/save_restore.go",
"diff": "@@ -140,8 +140,8 @@ func (d *dentry) beforeSave() {\n// afterLoad is invoked by stateify.\nfunc (d *dentry) afterLoad() {\nd.hostFD = -1\n- if refsvfs2.LeakCheckEnabled() && atomic.LoadInt64(&d.refs) != -1 {\n- refsvfs2.Register(d, \"gofer.dentry\")\n+ if atomic.LoadInt64(&d.refs) != -1 {\n+ refsvfs2.Register(d)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/overlay/BUILD",
"new_path": "pkg/sentry/fsimpl/overlay/BUILD",
"diff": "@@ -31,6 +31,7 @@ go_library(\n\"//pkg/context\",\n\"//pkg/fspath\",\n\"//pkg/log\",\n+ \"//pkg/refs\",\n\"//pkg/refsvfs2\",\n\"//pkg/sentry/arch\",\n\"//pkg/sentry/fs/lock\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/overlay/overlay.go",
"new_path": "pkg/sentry/fsimpl/overlay/overlay.go",
"diff": "@@ -505,9 +505,7 @@ func (fs *filesystem) newDentry() *dentry {\n}\nd.lowerVDs = d.inlineLowerVDs[:0]\nd.vfsd.Init(d)\n- if refsvfs2.LeakCheckEnabled() {\n- refsvfs2.Register(d, \"overlay.dentry\")\n- }\n+ refsvfs2.Register(d)\nreturn d\n}\n@@ -515,17 +513,19 @@ func (fs *filesystem) newDentry() *dentry {\nfunc (d *dentry) IncRef() {\n// d.refs may be 0 if d.fs.renameMu is locked, which serializes against\n// d.checkDropLocked().\n- atomic.AddInt64(&d.refs, 1)\n+ r := atomic.AddInt64(&d.refs, 1)\n+ refsvfs2.LogIncRef(d, r)\n}\n// TryIncRef implements vfs.DentryImpl.TryIncRef.\nfunc (d *dentry) TryIncRef() bool {\nfor {\n- refs := atomic.LoadInt64(&d.refs)\n- if refs <= 0 {\n+ r := atomic.LoadInt64(&d.refs)\n+ if r <= 0 {\nreturn false\n}\n- if atomic.CompareAndSwapInt64(&d.refs, refs, refs+1) {\n+ if atomic.CompareAndSwapInt64(&d.refs, r, r+1) {\n+ refsvfs2.LogTryIncRef(d, r+1)\nreturn true\n}\n}\n@@ -533,15 +533,27 @@ func (d *dentry) TryIncRef() bool {\n// DecRef implements vfs.DentryImpl.DecRef.\nfunc (d *dentry) DecRef(ctx context.Context) {\n- if refs := atomic.AddInt64(&d.refs, -1); refs == 0 {\n+ r := atomic.AddInt64(&d.refs, -1)\n+ refsvfs2.LogDecRef(d, r)\n+ if r == 0 {\nd.fs.renameMu.Lock()\nd.checkDropLocked(ctx)\nd.fs.renameMu.Unlock()\n- } else if refs < 0 {\n+ } else if r < 0 {\npanic(\"overlay.dentry.DecRef() called without holding a reference\")\n}\n}\n+func (d *dentry) decRefLocked(ctx context.Context) {\n+ r := atomic.AddInt64(&d.refs, -1)\n+ refsvfs2.LogDecRef(d, r)\n+ if r == 0 {\n+ d.checkDropLocked(ctx)\n+ } else if r < 0 {\n+ panic(\"overlay.dentry.decRefLocked() called without holding a reference\")\n+ }\n+}\n+\n// checkDropLocked should be called after d's reference count becomes 0 or it\n// becomes deleted.\n//\n@@ -601,15 +613,14 @@ func (d *dentry) destroyLocked(ctx context.Context) {\nd.parent.dirMu.Unlock()\n// Drop the reference held by d on its parent without recursively\n// locking d.fs.renameMu.\n- if refs := atomic.AddInt64(&d.parent.refs, -1); refs == 0 {\n- d.parent.checkDropLocked(ctx)\n- } else if refs < 0 {\n- panic(\"overlay.dentry.DecRef() called without holding a reference\")\n+ d.parent.decRefLocked(ctx)\n}\n+ refsvfs2.Unregister(d)\n}\n- if refsvfs2.LeakCheckEnabled() {\n- refsvfs2.Unregister(d, \"overlay.dentry\")\n- }\n+\n+// RefType implements refsvfs2.CheckedObject.Type.\n+func (d *dentry) RefType() string {\n+ return \"overlay.dentry\"\n}\n// LeakMessage implements refsvfs2.CheckedObject.LeakMessage.\n@@ -617,6 +628,14 @@ func (d *dentry) LeakMessage() string {\nreturn fmt.Sprintf(\"[overlay.dentry %p] reference count of %d instead of -1\", d, atomic.LoadInt64(&d.refs))\n}\n+// LogRefs implements refsvfs2.CheckedObject.LogRefs.\n+//\n+// This should only be set to true for debugging purposes, as it can generate an\n+// extremely large amount of output and drastically degrade performance.\n+func (d *dentry) LogRefs() bool {\n+ return false\n+}\n+\n// InotifyWithParent implements vfs.DentryImpl.InotifyWithParent.\nfunc (d *dentry) InotifyWithParent(ctx context.Context, events uint32, cookie uint32, et vfs.EventType) {\nif d.isDir() {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/overlay/save_restore.go",
"new_path": "pkg/sentry/fsimpl/overlay/save_restore.go",
"diff": "@@ -21,7 +21,7 @@ import (\n)\nfunc (d *dentry) afterLoad() {\n- if refsvfs2.LeakCheckEnabled() && atomic.LoadInt64(&d.refs) != -1 {\n- refsvfs2.Register(d, \"overlay.dentry\")\n+ if atomic.LoadInt64(&d.refs) != -1 {\n+ refsvfs2.Register(d)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/verity/save_restore.go",
"new_path": "pkg/sentry/fsimpl/verity/save_restore.go",
"diff": "@@ -21,7 +21,7 @@ import (\n)\nfunc (d *dentry) afterLoad() {\n- if refsvfs2.LeakCheckEnabled() && atomic.LoadInt64(&d.refs) != -1 {\n- refsvfs2.Register(d, \"verity.dentry\")\n+ if atomic.LoadInt64(&d.refs) != -1 {\n+ refsvfs2.Register(d)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/verity/verity.go",
"new_path": "pkg/sentry/fsimpl/verity/verity.go",
"diff": "@@ -43,32 +43,41 @@ import (\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n+const (\n// Name is the default filesystem name.\n-const Name = \"verity\"\n+ Name = \"verity\"\n// merklePrefix is the prefix of the Merkle tree files. For example, the Merkle\n// tree file for \"/foo\" is \"/.merkle.verity.foo\".\n-const merklePrefix = \".merkle.verity.\"\n+ merklePrefix = \".merkle.verity.\"\n-// merkleoffsetInParentXattr is the extended attribute name specifying the\n-// offset of child hash in its parent's Merkle tree.\n-const merkleOffsetInParentXattr = \"user.merkle.offset\"\n+ // merkleOffsetInParentXattr is the extended attribute name specifying the\n+ // offset of the child hash in its parent's Merkle tree.\n+ merkleOffsetInParentXattr = \"user.merkle.offset\"\n// merkleSizeXattr is the extended attribute name specifying the size of data\n-// hashed by the corresponding Merkle tree. For a file, it's the size of the\n-// whole file. For a directory, it's the size of all its children's hashes.\n-const merkleSizeXattr = \"user.merkle.size\"\n+ // hashed by the corresponding Merkle tree. For a regular file, this is the\n+ // file size. For a directory, this is the size of all its children's hashes.\n+ merkleSizeXattr = \"user.merkle.size\"\n// sizeOfStringInt32 is the size for a 32 bit integer stored as string in\n-// extended attributes. The maximum value of a 32 bit integer is 10 digits.\n-const sizeOfStringInt32 = 10\n+ // extended attributes. The maximum value of a 32 bit integer has 10 digits.\n+ sizeOfStringInt32 = 10\n+)\n+var (\n// noCrashOnVerificationFailure indicates whether the sandbox should panic\n// whenever verification fails. If true, an error is returned instead of\n// panicking. This should only be set for tests.\n-// TOOD(b/165661693): Decide whether to panic or return error based on this\n+ //\n+ // TODO(b/165661693): Decide whether to panic or return error based on this\n// flag.\n-var noCrashOnVerificationFailure bool\n+ noCrashOnVerificationFailure bool\n+\n+ // verityMu synchronizes concurrent operations that enable verity and perform\n+ // verification checks.\n+ verityMu sync.RWMutex\n+)\n// FilesystemType implements vfs.FilesystemType.\n//\n@@ -334,25 +343,25 @@ func (fs *filesystem) newDentry() *dentry {\nfs: fs,\n}\nd.vfsd.Init(d)\n- if refsvfs2.LeakCheckEnabled() {\n- refsvfs2.Register(d, \"verity.dentry\")\n- }\n+ refsvfs2.Register(d)\nreturn d\n}\n// IncRef implements vfs.DentryImpl.IncRef.\nfunc (d *dentry) IncRef() {\n- atomic.AddInt64(&d.refs, 1)\n+ r := atomic.AddInt64(&d.refs, 1)\n+ refsvfs2.LogIncRef(d, r)\n}\n// TryIncRef implements vfs.DentryImpl.TryIncRef.\nfunc (d *dentry) TryIncRef() bool {\nfor {\n- refs := atomic.LoadInt64(&d.refs)\n- if refs <= 0 {\n+ r := atomic.LoadInt64(&d.refs)\n+ if r <= 0 {\nreturn false\n}\n- if atomic.CompareAndSwapInt64(&d.refs, refs, refs+1) {\n+ if atomic.CompareAndSwapInt64(&d.refs, r, r+1) {\n+ refsvfs2.LogTryIncRef(d, r+1)\nreturn true\n}\n}\n@@ -360,15 +369,27 @@ func (d *dentry) TryIncRef() bool {\n// DecRef implements vfs.DentryImpl.DecRef.\nfunc (d *dentry) DecRef(ctx context.Context) {\n- if refs := atomic.AddInt64(&d.refs, -1); refs == 0 {\n+ r := atomic.AddInt64(&d.refs, -1)\n+ refsvfs2.LogDecRef(d, r)\n+ if r == 0 {\nd.fs.renameMu.Lock()\nd.checkDropLocked(ctx)\nd.fs.renameMu.Unlock()\n- } else if refs < 0 {\n+ } else if r < 0 {\npanic(\"verity.dentry.DecRef() called without holding a reference\")\n}\n}\n+func (d *dentry) decRefLocked(ctx context.Context) {\n+ r := atomic.AddInt64(&d.refs, -1)\n+ refsvfs2.LogDecRef(d, r)\n+ if r == 0 {\n+ d.checkDropLocked(ctx)\n+ } else if r < 0 {\n+ panic(\"verity.dentry.decRefLocked() called without holding a reference\")\n+ }\n+}\n+\n// checkDropLocked should be called after d's reference count becomes 0 or it\n// becomes deleted.\nfunc (d *dentry) checkDropLocked(ctx context.Context) {\n@@ -399,26 +420,23 @@ func (d *dentry) destroyLocked(ctx context.Context) {\nif d.lowerVD.Ok() {\nd.lowerVD.DecRef(ctx)\n}\n- if refsvfs2.LeakCheckEnabled() {\n- refsvfs2.Unregister(d, \"verity.dentry\")\n- }\n-\nif d.lowerMerkleVD.Ok() {\nd.lowerMerkleVD.DecRef(ctx)\n}\n-\nif d.parent != nil {\nd.parent.dirMu.Lock()\nif !d.vfsd.IsDead() {\ndelete(d.parent.children, d.name)\n}\nd.parent.dirMu.Unlock()\n- if refs := atomic.AddInt64(&d.parent.refs, -1); refs == 0 {\n- d.parent.checkDropLocked(ctx)\n- } else if refs < 0 {\n- panic(\"verity.dentry.DecRef() called without holding a reference\")\n+ d.parent.decRefLocked(ctx)\n}\n+ refsvfs2.Unregister(d)\n}\n+\n+// RefType implements refsvfs2.CheckedObject.Type.\n+func (d *dentry) RefType() string {\n+ return \"verity.dentry\"\n}\n// LeakMessage implements refsvfs2.CheckedObject.LeakMessage.\n@@ -426,6 +444,14 @@ func (d *dentry) LeakMessage() string {\nreturn fmt.Sprintf(\"[verity.dentry %p] reference count of %d instead of -1\", d, atomic.LoadInt64(&d.refs))\n}\n+// LogRefs implements refsvfs2.CheckedObject.LogRefs.\n+//\n+// This should only be set to true for debugging purposes, as it can generate an\n+// extremely large amount of output and drastically degrade performance.\n+func (d *dentry) LogRefs() bool {\n+ return false\n+}\n+\n// InotifyWithParent implements vfs.DentryImpl.InotifyWithParent.\nfunc (d *dentry) InotifyWithParent(ctx context.Context, events, cookie uint32, et vfs.EventType) {\n//TODO(b/159261227): Implement InotifyWithParent.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/mount.go",
"new_path": "pkg/sentry/vfs/mount.go",
"diff": "@@ -107,9 +107,7 @@ func newMount(vfs *VirtualFilesystem, fs *Filesystem, root *Dentry, mntns *Mount\nif opts.ReadOnly {\nmnt.setReadOnlyLocked(true)\n}\n- if refsvfs2.LeakCheckEnabled() {\n- refsvfs2.Register(mnt, \"vfs.Mount\")\n- }\n+ refsvfs2.Register(mnt)\nreturn mnt\n}\n@@ -474,11 +472,12 @@ func (vfs *VirtualFilesystem) disconnectLocked(mnt *Mount) VirtualDentry {\n// tryIncMountedRef does not require that a reference is held on mnt.\nfunc (mnt *Mount) tryIncMountedRef() bool {\nfor {\n- refs := atomic.LoadInt64(&mnt.refs)\n- if refs <= 0 { // refs < 0 => MSB set => eagerly unmounted\n+ r := atomic.LoadInt64(&mnt.refs)\n+ if r <= 0 { // r < 0 => MSB set => eagerly unmounted\nreturn false\n}\n- if atomic.CompareAndSwapInt64(&mnt.refs, refs, refs+1) {\n+ if atomic.CompareAndSwapInt64(&mnt.refs, r, r+1) {\n+ refsvfs2.LogTryIncRef(mnt, r+1)\nreturn true\n}\n}\n@@ -488,16 +487,15 @@ func (mnt *Mount) tryIncMountedRef() bool {\nfunc (mnt *Mount) IncRef() {\n// In general, negative values for mnt.refs are valid because the MSB is\n// the eager-unmount bit.\n- atomic.AddInt64(&mnt.refs, 1)\n+ r := atomic.AddInt64(&mnt.refs, 1)\n+ refsvfs2.LogIncRef(mnt, r)\n}\n// DecRef decrements mnt's reference count.\nfunc (mnt *Mount) DecRef(ctx context.Context) {\nr := atomic.AddInt64(&mnt.refs, -1)\nif r&^math.MinInt64 == 0 { // mask out MSB\n- if refsvfs2.LeakCheckEnabled() {\n- refsvfs2.Unregister(mnt, \"vfs.Mount\")\n- }\n+ refsvfs2.Unregister(mnt)\nmnt.destroy(ctx)\n}\n}\n@@ -520,11 +518,24 @@ func (mnt *Mount) destroy(ctx context.Context) {\n}\n}\n+// RefType implements refsvfs2.CheckedObject.Type.\n+func (mnt *Mount) RefType() string {\n+ return \"vfs.Mount\"\n+}\n+\n// LeakMessage implements refsvfs2.CheckedObject.LeakMessage.\nfunc (mnt *Mount) LeakMessage() string {\nreturn fmt.Sprintf(\"[vfs.Mount %p] reference count of %d instead of 0\", mnt, atomic.LoadInt64(&mnt.refs))\n}\n+// LogRefs implements refsvfs2.CheckedObject.LogRefs.\n+//\n+// This should only be set to true for debugging purposes, as it can generate an\n+// extremely large amount of output and drastically degrade performance.\n+func (mnt *Mount) LogRefs() bool {\n+ return false\n+}\n+\n// DecRef decrements mntns' reference count.\nfunc (mntns *MountNamespace) DecRef(ctx context.Context) {\nvfs := mntns.root.fs.VirtualFilesystem()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/save_restore.go",
"new_path": "pkg/sentry/vfs/save_restore.go",
"diff": "@@ -111,8 +111,8 @@ func (vfs *VirtualFilesystem) loadMounts(mounts []*Mount) {\n}\nfunc (mnt *Mount) afterLoad() {\n- if refsvfs2.LeakCheckEnabled() && atomic.LoadInt64(&mnt.refs) != 0 {\n- refsvfs2.Register(mnt, \"vfs.Mount\")\n+ if atomic.LoadInt64(&mnt.refs) != 0 {\n+ refsvfs2.Register(mnt)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader.go",
"new_path": "runsc/boot/loader.go",
"diff": "@@ -479,9 +479,7 @@ func (l *Loader) Destroy() {\n// All sentry-created resources should have been released at this point;\n// check for reference leaks.\n- if refsvfs2.LeakCheckEnabled() {\nrefsvfs2.DoLeakCheck()\n- }\n// In the success case, stdioFDs and goferFDs will only contain\n// released/closed FDs that ownership has been passed over to host FDs and\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add logging option to leak checker.
Also refactor the template and CheckedObject interface to make this cleaner.
Updates #1486.
PiperOrigin-RevId: 339577120 |
259,860 | 28.10.2020 19:00:01 | 25,200 | 265f1eb2c7abbbf924448ef6bbd8cddb13e66b9f | Add leak checking for kernfs.Dentry.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/refsvfs2/refs_map.go",
"new_path": "pkg/refsvfs2/refs_map.go",
"diff": "@@ -16,16 +16,12 @@ package refsvfs2\nimport (\n\"fmt\"\n- \"strings\"\n\"gvisor.dev/gvisor/pkg/log\"\nrefs_vfs1 \"gvisor.dev/gvisor/pkg/refs\"\n\"gvisor.dev/gvisor/pkg/sync\"\n)\n-// TODO(gvisor.dev/issue/1193): re-enable once kernfs refs are fixed.\n-var ignored []string = []string{\"kernfs.\", \"proc.\", \"sys.\", \"devpts.\", \"fuse.\"}\n-\nvar (\n// liveObjects is a global map of reference-counted objects. Objects are\n// inserted when leak check is enabled, and they are removed when they are\n@@ -60,11 +56,6 @@ func leakCheckEnabled() bool {\n// Register adds obj to the live object map.\nfunc Register(obj CheckedObject) {\nif leakCheckEnabled() {\n- for _, str := range ignored {\n- if strings.Contains(obj.RefType(), str) {\n- return\n- }\n- }\nliveObjectsMu.Lock()\nif _, ok := liveObjects[obj]; ok {\npanic(fmt.Sprintf(\"Unexpected entry in leak checking map: reference %p already added\", obj))\n@@ -81,11 +72,6 @@ func Unregister(obj CheckedObject) {\nliveObjectsMu.Lock()\ndefer liveObjectsMu.Unlock()\nif _, ok := liveObjects[obj]; !ok {\n- for _, str := range ignored {\n- if strings.Contains(obj.RefType(), str) {\n- return\n- }\n- }\npanic(fmt.Sprintf(\"Expected to find entry in leak checking map for reference %p\", obj))\n}\ndelete(liveObjects, obj)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/devpts/devpts.go",
"new_path": "pkg/sentry/fsimpl/devpts/devpts.go",
"diff": "@@ -113,7 +113,7 @@ func (fstype *FilesystemType) newFilesystem(ctx context.Context, vfsObj *vfs.Vir\nroot.EnableLeakCheck()\nvar rootD kernfs.Dentry\n- rootD.Init(&fs.Filesystem, root)\n+ rootD.InitRoot(&fs.Filesystem, root)\n// Construct the pts master inode and dentry. Linux always uses inode\n// id 2 for ptmx. See fs/devpts/inode.c:mknod_ptmx.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/fuse/fusefs.go",
"new_path": "pkg/sentry/fsimpl/fuse/fusefs.go",
"diff": "@@ -205,7 +205,7 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\n}\n// root is the fusefs root directory.\n- root := fs.newRootInode(ctx, creds, fsopts.rootMode)\n+ root := fs.newRoot(ctx, creds, fsopts.rootMode)\nreturn fs.VFSFilesystem(), root.VFSDentry(), nil\n}\n@@ -284,14 +284,14 @@ type inode struct {\nlink string\n}\n-func (fs *filesystem) newRootInode(ctx context.Context, creds *auth.Credentials, mode linux.FileMode) *kernfs.Dentry {\n+func (fs *filesystem) newRoot(ctx context.Context, creds *auth.Credentials, mode linux.FileMode) *kernfs.Dentry {\ni := &inode{fs: fs, nodeID: 1}\ni.InodeAttrs.Init(ctx, creds, linux.UNNAMED_MAJOR, fs.devMinor, 1, linux.ModeDirectory|0755)\ni.OrderedChildren.Init(kernfs.OrderedChildrenOptions{})\ni.EnableLeakCheck()\nvar d kernfs.Dentry\n- d.Init(&fs.Filesystem, i)\n+ d.InitRoot(&fs.Filesystem, i)\nreturn &d\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go",
"diff": "@@ -245,7 +245,41 @@ func checkDeleteLocked(ctx context.Context, rp *vfs.ResolvingPath, d *Dentry) er\n}\n// Release implements vfs.FilesystemImpl.Release.\n-func (fs *Filesystem) Release(context.Context) {\n+func (fs *Filesystem) Release(ctx context.Context) {\n+ root := fs.root\n+ if root == nil {\n+ return\n+ }\n+ fs.mu.Lock()\n+ root.releaseKeptDentriesLocked(ctx)\n+ for fs.cachedDentriesLen != 0 {\n+ fs.evictCachedDentryLocked(ctx)\n+ }\n+ fs.mu.Unlock()\n+ // Drop ref acquired in Dentry.InitRoot().\n+ root.DecRef(ctx)\n+}\n+\n+// releaseKeptDentriesLocked recursively drops all dentry references created by\n+// Lookup when Dentry.inode.Keep() is true.\n+//\n+// Precondition: Filesystem.mu is held.\n+func (d *Dentry) releaseKeptDentriesLocked(ctx context.Context) {\n+ if d.inode.Keep() {\n+ d.decRefLocked(ctx)\n+ }\n+\n+ if d.isDir() {\n+ var children []*Dentry\n+ d.dirMu.Lock()\n+ for _, child := range d.children {\n+ children = append(children, child)\n+ }\n+ d.dirMu.Unlock()\n+ for _, child := range children {\n+ child.releaseKeptDentriesLocked(ctx)\n+ }\n+ }\n}\n// Sync implements vfs.FilesystemImpl.Sync.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/kernfs.go",
"new_path": "pkg/sentry/fsimpl/kernfs/kernfs.go",
"diff": "@@ -61,6 +61,7 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/refsvfs2\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/sync\"\n@@ -118,6 +119,12 @@ type Filesystem struct {\n// MaxCachedDentries is the maximum size of cachedDentries. If not set,\n// defaults to 0 and kernfs does not cache any dentries. This is immutable.\nMaxCachedDentries uint64\n+\n+ // root is the root dentry of this filesystem. Note that root may be nil for\n+ // filesystems on a disconnected mount without a root (e.g. pipefs, sockfs,\n+ // hostfs). Filesystem holds an extra reference on root to prevent it from\n+ // being destroyed prematurely. This is immutable.\n+ root *Dentry\n}\n// deferDecRef defers dropping a dentry ref until the next call to\n@@ -214,17 +221,19 @@ type Dentry struct {\nfunc (d *Dentry) IncRef() {\n// d.refs may be 0 if d.fs.mu is locked, which serializes against\n// d.cacheLocked().\n- atomic.AddInt64(&d.refs, 1)\n+ r := atomic.AddInt64(&d.refs, 1)\n+ refsvfs2.LogIncRef(d, r)\n}\n// TryIncRef implements vfs.DentryImpl.TryIncRef.\nfunc (d *Dentry) TryIncRef() bool {\nfor {\n- refs := atomic.LoadInt64(&d.refs)\n- if refs <= 0 {\n+ r := atomic.LoadInt64(&d.refs)\n+ if r <= 0 {\nreturn false\n}\n- if atomic.CompareAndSwapInt64(&d.refs, refs, refs+1) {\n+ if atomic.CompareAndSwapInt64(&d.refs, r, r+1) {\n+ refsvfs2.LogTryIncRef(d, r+1)\nreturn true\n}\n}\n@@ -232,11 +241,23 @@ func (d *Dentry) TryIncRef() bool {\n// DecRef implements vfs.DentryImpl.DecRef.\nfunc (d *Dentry) DecRef(ctx context.Context) {\n- if refs := atomic.AddInt64(&d.refs, -1); refs == 0 {\n+ r := atomic.AddInt64(&d.refs, -1)\n+ refsvfs2.LogDecRef(d, r)\n+ if r == 0 {\nd.fs.mu.Lock()\nd.cacheLocked(ctx)\nd.fs.mu.Unlock()\n- } else if refs < 0 {\n+ } else if r < 0 {\n+ panic(\"kernfs.Dentry.DecRef() called without holding a reference\")\n+ }\n+}\n+\n+func (d *Dentry) decRefLocked(ctx context.Context) {\n+ r := atomic.AddInt64(&d.refs, -1)\n+ refsvfs2.LogDecRef(d, r)\n+ if r == 0 {\n+ d.cacheLocked(ctx)\n+ } else if r < 0 {\npanic(\"kernfs.Dentry.DecRef() called without holding a reference\")\n}\n}\n@@ -298,11 +319,20 @@ func (d *Dentry) cacheLocked(ctx context.Context) {\nif d.fs.cachedDentriesLen <= d.fs.MaxCachedDentries {\nreturn\n}\n+ d.fs.evictCachedDentryLocked(ctx)\n+ // Whether or not victim was destroyed, we brought fs.cachedDentriesLen\n+ // back down to fs.opts.maxCachedDentries, so we don't loop.\n+}\n+\n+// Preconditions:\n+// * fs.mu must be locked for writing.\n+// * fs.cachedDentriesLen != 0.\n+func (fs *Filesystem) evictCachedDentryLocked(ctx context.Context) {\n// Evict the least recently used dentry because cache size is greater than\n// max cache size (configured on mount).\n- victim := d.fs.cachedDentries.Back()\n- d.fs.cachedDentries.Remove(victim)\n- d.fs.cachedDentriesLen--\n+ victim := fs.cachedDentries.Back()\n+ fs.cachedDentries.Remove(victim)\n+ fs.cachedDentriesLen--\nvictim.cached = false\n// victim.refs may have become non-zero from an earlier path resolution\n// after it was inserted into fs.cachedDentries.\n@@ -311,7 +341,7 @@ func (d *Dentry) cacheLocked(ctx context.Context) {\nvictim.parent.dirMu.Lock()\n// Note that victim can't be a mount point (in any mount\n// namespace), since VFS holds references on mount points.\n- d.fs.vfsfs.VirtualFilesystem().InvalidateDentry(ctx, victim.VFSDentry())\n+ fs.vfsfs.VirtualFilesystem().InvalidateDentry(ctx, victim.VFSDentry())\ndelete(victim.parent.children, victim.name)\nvictim.parent.dirMu.Unlock()\n}\n@@ -330,7 +360,8 @@ func (d *Dentry) cacheLocked(ctx context.Context) {\n// by path traversal.\n// * d.vfsd.IsDead() is true.\nfunc (d *Dentry) destroyLocked(ctx context.Context) {\n- switch atomic.LoadInt64(&d.refs) {\n+ refs := atomic.LoadInt64(&d.refs)\n+ switch refs {\ncase 0:\n// Mark the dentry destroyed.\natomic.StoreInt64(&d.refs, -1)\n@@ -343,15 +374,42 @@ func (d *Dentry) destroyLocked(ctx context.Context) {\nd.inode.DecRef(ctx) // IncRef from Init.\nd.inode = nil\n- // Drop the reference held by d on its parent without recursively locking\n- // d.fs.mu.\nif d.parent != nil {\n- if refs := atomic.AddInt64(&d.parent.refs, -1); refs == 0 {\n- d.parent.cacheLocked(ctx)\n- } else if refs < 0 {\n- panic(\"kernfs.Dentry.DecRef() called without holding a reference\")\n+ d.parent.decRefLocked(ctx)\n}\n+\n+ refsvfs2.Unregister(d)\n+}\n+\n+// RefType implements refsvfs2.CheckedObject.Type.\n+func (d *Dentry) RefType() string {\n+ return \"kernfs.Dentry\"\n+}\n+\n+// LeakMessage implements refsvfs2.CheckedObject.LeakMessage.\n+func (d *Dentry) LeakMessage() string {\n+ return fmt.Sprintf(\"[kernfs.Dentry %p] reference count of %d instead of -1\", d, atomic.LoadInt64(&d.refs))\n+}\n+\n+// LogRefs implements refsvfs2.CheckedObject.LogRefs.\n+//\n+// This should only be set to true for debugging purposes, as it can generate an\n+// extremely large amount of output and drastically degrade performance.\n+func (d *Dentry) LogRefs() bool {\n+ return false\n}\n+\n+// InitRoot initializes this dentry as the root of the filesystem.\n+//\n+// Precondition: Caller must hold a reference on inode.\n+//\n+// Postcondition: Caller's reference on inode is transferred to the dentry.\n+func (d *Dentry) InitRoot(fs *Filesystem, inode Inode) {\n+ d.Init(fs, inode)\n+ fs.root = d\n+ // Hold an extra reference on the root dentry. It is held by fs to prevent the\n+ // root from being \"cached\" and subsequently evicted.\n+ d.IncRef()\n}\n// Init initializes this dentry.\n@@ -371,6 +429,7 @@ func (d *Dentry) Init(fs *Filesystem, inode Inode) {\nif ftype == linux.ModeSymlink {\nd.flags |= dflagsIsSymlink\n}\n+ refsvfs2.Register(d)\n}\n// VFSDentry returns the generic vfs dentry for this kernfs dentry.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/save_restore.go",
"new_path": "pkg/sentry/fsimpl/kernfs/save_restore.go",
"diff": "package kernfs\n+import (\n+ \"sync/atomic\"\n+\n+ \"gvisor.dev/gvisor/pkg/refsvfs2\"\n+)\n+\n+// afterLoad is invoked by stateify.\n+func (d *Dentry) afterLoad() {\n+ if atomic.LoadInt64(&d.refs) >= 0 {\n+ refsvfs2.Register(d)\n+ }\n+}\n+\n// afterLoad is invoked by stateify.\nfunc (i *inodePlatformFile) afterLoad() {\nif i.fileMapper.IsInited() {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/filesystem.go",
"new_path": "pkg/sentry/fsimpl/proc/filesystem.go",
"diff": "@@ -94,7 +94,7 @@ func (ft FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.VirtualF\ninode := procfs.newTasksInode(ctx, k, pidns, cgroups)\nvar dentry kernfs.Dentry\n- dentry.Init(&procfs.Filesystem, inode)\n+ dentry.InitRoot(&procfs.Filesystem, inode)\nreturn procfs.VFSFilesystem(), dentry.VFSDentry(), nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/sys/sys.go",
"new_path": "pkg/sentry/fsimpl/sys/sys.go",
"diff": "@@ -102,7 +102,7 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\n\"power\": fs.newDir(ctx, creds, defaultSysDirMode, nil),\n})\nvar rootD kernfs.Dentry\n- rootD.Init(&fs.Filesystem, root)\n+ rootD.InitRoot(&fs.Filesystem, root)\nreturn fs.VFSFilesystem(), rootD.VFSDentry(), nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add leak checking for kernfs.Dentry.
Updates #1486.
PiperOrigin-RevId: 339581879 |
259,884 | 28.10.2020 23:14:44 | 25,200 | b0b275449b215c59b1621d509b07277c46c506f4 | Add url option for blog authors | [
{
"change_type": "MODIFY",
"old_path": "website/_config.yml",
"new_path": "website/_config.yml",
"diff": "@@ -40,6 +40,7 @@ authors:\nianlewis:\nname: Ian Lewis\nemail: [email protected]\n+ url: https://twitter.com/IanMLewis\nmpratt:\nname: Michael Pratt\nemail: [email protected]\n"
},
{
"change_type": "MODIFY",
"old_path": "website/_includes/byline.html",
"new_path": "website/_includes/byline.html",
"diff": "@@ -5,7 +5,7 @@ By\n{% assign author_id=include.authors[i] %}\n{% assign author=site.authors[author_id] %}\n{% if author %}\n- <a href=\"mailto:{{ author.email }}\">{{ author.name }}</a>\n+ <a href=\"{% if author.url %}{{ author.url }}{% else %}mailto:{{ author.email }}{% endif %}\">{{ author.name }}</a>\n{% else %}\n{{ author_id }}\n{% endif %}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add url option for blog authors
PiperOrigin-RevId: 339608078 |
259,951 | 29.10.2020 10:42:39 | 25,200 | 337c4b9a19ea7b880383eb875c5dffddbc5bebde | Add support for bare IPv4 in packetimpact tests | [
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/connections.go",
"new_path": "test/packetimpact/testbench/connections.go",
"diff": "@@ -839,6 +839,61 @@ func (conn *TCPIPv4) Drain(t *testing.T) {\nconn.sniffer.Drain(t)\n}\n+// IPv4Conn maintains the state for all the layers in a IPv4 connection.\n+type IPv4Conn Connection\n+\n+// NewIPv4Conn creates a new IPv4Conn connection with reasonable defaults.\n+func NewIPv4Conn(t *testing.T, outgoingIPv4, incomingIPv4 IPv4) IPv4Conn {\n+ t.Helper()\n+\n+ etherState, err := newEtherState(Ether{}, Ether{})\n+ if err != nil {\n+ t.Fatalf(\"can't make EtherState: %s\", err)\n+ }\n+ ipv4State, err := newIPv4State(outgoingIPv4, incomingIPv4)\n+ if err != nil {\n+ t.Fatalf(\"can't make IPv4State: %s\", err)\n+ }\n+\n+ injector, err := NewInjector(t)\n+ if err != nil {\n+ t.Fatalf(\"can't make injector: %s\", err)\n+ }\n+ sniffer, err := NewSniffer(t)\n+ if err != nil {\n+ t.Fatalf(\"can't make sniffer: %s\", err)\n+ }\n+\n+ return IPv4Conn{\n+ layerStates: []layerState{etherState, ipv4State},\n+ injector: injector,\n+ sniffer: sniffer,\n+ }\n+}\n+\n+// Send sends a frame with ipv4 overriding the IPv4 layer defaults and\n+// additionalLayers added after it.\n+func (c *IPv4Conn) Send(t *testing.T, ipv4 IPv4, additionalLayers ...Layer) {\n+ t.Helper()\n+\n+ (*Connection)(c).send(t, Layers{&ipv4}, additionalLayers...)\n+}\n+\n+// Close cleans up any resources held.\n+func (c *IPv4Conn) Close(t *testing.T) {\n+ t.Helper()\n+\n+ (*Connection)(c).Close(t)\n+}\n+\n+// ExpectFrame expects a frame that matches the provided Layers within the\n+// timeout specified. If it doesn't arrive in time, an error is returned.\n+func (c *IPv4Conn) ExpectFrame(t *testing.T, frame Layers, timeout time.Duration) (Layers, error) {\n+ t.Helper()\n+\n+ return (*Connection)(c).ExpectFrame(t, frame, timeout)\n+}\n+\n// IPv6Conn maintains the state for all the layers in a IPv6 connection.\ntype IPv6Conn Connection\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add support for bare IPv4 in packetimpact tests
PiperOrigin-RevId: 339699771 |
260,003 | 29.10.2020 13:50:28 | 25,200 | b9f18fe2f1ad0c8547e2bd66d1cd3bbbddfbddda | Fix TCP wildcard bind failure when netstack is v6 only
TCP endpoint unconditionly binds to v4 even when the stack only supports v6. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/dual_stack_test.go",
"new_path": "pkg/tcpip/transport/tcp/dual_stack_test.go",
"diff": "@@ -236,6 +236,25 @@ func TestV6ConnectWhenBoundToWildcard(t *testing.T) {\ntestV6Connect(t, c)\n}\n+func TestStackV6OnlyConnectWhenBoundToWildcard(t *testing.T) {\n+ c := context.NewWithOpts(t, context.Options{\n+ EnableV6: true,\n+ MTU: defaultMTU,\n+ })\n+ defer c.Cleanup()\n+\n+ // Create a v6 endpoint but don't set the v6-only TCP option.\n+ c.CreateV6Endpoint(false)\n+\n+ // Bind to wildcard.\n+ if err := c.EP.Bind(tcpip.FullAddress{}); err != nil {\n+ t.Fatalf(\"Bind failed: %v\", err)\n+ }\n+\n+ // Test the connection request.\n+ testV6Connect(t, c)\n+}\n+\nfunc TestV6ConnectWhenBoundToLocalAddress(t *testing.T) {\nc := context.New(t, defaultMTU)\ndefer c.Cleanup()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -2690,14 +2690,16 @@ func (e *endpoint) bindLocked(addr tcpip.FullAddress) (err *tcpip.Error) {\nreturn err\n}\n- // Expand netProtos to include v4 and v6 if the caller is binding to a\n- // wildcard (empty) address, and this is an IPv6 endpoint with v6only\n- // set to false.\nnetProtos := []tcpip.NetworkProtocolNumber{netProto}\n- if netProto == header.IPv6ProtocolNumber && !e.v6only && addr.Addr == \"\" {\n- netProtos = []tcpip.NetworkProtocolNumber{\n- header.IPv6ProtocolNumber,\n- header.IPv4ProtocolNumber,\n+\n+ // Expand netProtos to include v4 and v6 under dual-stack if the caller is\n+ // binding to a wildcard (empty) address, and this is an IPv6 endpoint with\n+ // v6only set to false.\n+ if netProto == header.IPv6ProtocolNumber {\n+ stackHasV4 := e.stack.CheckNetworkProtocol(header.IPv4ProtocolNumber)\n+ alsoBindToV4 := !e.v6only && addr.Addr == \"\" && stackHasV4\n+ if alsoBindToV4 {\n+ netProtos = append(netProtos, header.IPv4ProtocolNumber)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/testing/context/context.go",
"new_path": "pkg/tcpip/transport/tcp/testing/context/context.go",
"diff": "@@ -112,6 +112,18 @@ type Headers struct {\nTCPOpts []byte\n}\n+// Options contains options for creating a new test context.\n+type Options struct {\n+ // EnableV4 indicates whether IPv4 should be enabled.\n+ EnableV4 bool\n+\n+ // EnableV6 indicates whether IPv4 should be enabled.\n+ EnableV6 bool\n+\n+ // MTU indicates the maximum transmission unit on the link layer.\n+ MTU uint32\n+}\n+\n// Context provides an initialized Network stack and a link layer endpoint\n// for use in TCP tests.\ntype Context struct {\n@@ -154,10 +166,30 @@ type Context struct {\n// New allocates and initializes a test context containing a new\n// stack and a link-layer endpoint.\nfunc New(t *testing.T, mtu uint32) *Context {\n- s := stack.New(stack.Options{\n- NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},\n- TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol},\n+ return NewWithOpts(t, Options{\n+ EnableV4: true,\n+ EnableV6: true,\n+ MTU: mtu,\n})\n+}\n+\n+// NewWithOpts allocates and initializes a test context containing a new\n+// stack and a link-layer endpoint with specific options.\n+func NewWithOpts(t *testing.T, opts Options) *Context {\n+ if opts.MTU == 0 {\n+ panic(\"MTU must be greater than 0\")\n+ }\n+\n+ stackOpts := stack.Options{\n+ TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol},\n+ }\n+ if opts.EnableV4 {\n+ stackOpts.NetworkProtocols = append(stackOpts.NetworkProtocols, ipv4.NewProtocol)\n+ }\n+ if opts.EnableV6 {\n+ stackOpts.NetworkProtocols = append(stackOpts.NetworkProtocols, ipv6.NewProtocol)\n+ }\n+ s := stack.New(stackOpts)\nconst sendBufferSize = 1 << 20 // 1 MiB\nconst recvBufferSize = 1 << 20 // 1 MiB\n@@ -182,24 +214,27 @@ func New(t *testing.T, mtu uint32) *Context {\n// Some of the congestion control tests send up to 640 packets, we so\n// set the channel size to 1000.\n- ep := channel.New(1000, mtu, \"\")\n+ ep := channel.New(1000, opts.MTU, \"\")\nwep := stack.LinkEndpoint(ep)\nif testing.Verbose() {\nwep = sniffer.New(ep)\n}\n- opts := stack.NICOptions{Name: \"nic1\"}\n- if err := s.CreateNICWithOptions(1, wep, opts); err != nil {\n+ nicOpts := stack.NICOptions{Name: \"nic1\"}\n+ if err := s.CreateNICWithOptions(1, wep, nicOpts); err != nil {\nt.Fatalf(\"CreateNICWithOptions(_, _, %+v) failed: %v\", opts, err)\n}\n- wep2 := stack.LinkEndpoint(channel.New(1000, mtu, \"\"))\n+ wep2 := stack.LinkEndpoint(channel.New(1000, opts.MTU, \"\"))\nif testing.Verbose() {\n- wep2 = sniffer.New(channel.New(1000, mtu, \"\"))\n+ wep2 = sniffer.New(channel.New(1000, opts.MTU, \"\"))\n}\nopts2 := stack.NICOptions{Name: \"nic2\"}\nif err := s.CreateNICWithOptions(2, wep2, opts2); err != nil {\nt.Fatalf(\"CreateNICWithOptions(_, _, %+v) failed: %v\", opts2, err)\n}\n+ var routeTable []tcpip.Route\n+\n+ if opts.EnableV4 {\nv4ProtocolAddr := tcpip.ProtocolAddress{\nProtocol: ipv4.ProtocolNumber,\nAddressWithPrefix: StackAddrWithPrefix,\n@@ -207,7 +242,13 @@ func New(t *testing.T, mtu uint32) *Context {\nif err := s.AddProtocolAddress(1, v4ProtocolAddr); err != nil {\nt.Fatalf(\"AddProtocolAddress(1, %#v): %s\", v4ProtocolAddr, err)\n}\n+ routeTable = append(routeTable, tcpip.Route{\n+ Destination: header.IPv4EmptySubnet,\n+ NIC: 1,\n+ })\n+ }\n+ if opts.EnableV6 {\nv6ProtocolAddr := tcpip.ProtocolAddress{\nProtocol: ipv6.ProtocolNumber,\nAddressWithPrefix: StackV6AddrWithPrefix,\n@@ -215,17 +256,13 @@ func New(t *testing.T, mtu uint32) *Context {\nif err := s.AddProtocolAddress(1, v6ProtocolAddr); err != nil {\nt.Fatalf(\"AddProtocolAddress(1, %#v): %s\", v6ProtocolAddr, err)\n}\n-\n- s.SetRouteTable([]tcpip.Route{\n- {\n- Destination: header.IPv4EmptySubnet,\n- NIC: 1,\n- },\n- {\n+ routeTable = append(routeTable, tcpip.Route{\nDestination: header.IPv6EmptySubnet,\nNIC: 1,\n- },\n})\n+ }\n+\n+ s.SetRouteTable(routeTable)\nreturn &Context{\nt: t,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix TCP wildcard bind failure when netstack is v6 only
TCP endpoint unconditionly binds to v4 even when the stack only supports v6.
PiperOrigin-RevId: 339739392 |
259,891 | 29.10.2020 14:26:48 | 25,200 | 181fea0b58f2e13a469a34eb0b921b169d292a9d | Make RedirectTarget thread safe
Fixes | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -210,6 +210,15 @@ iptables-tests: load-iptables\n@$(call submake,test-runtime RUNTIME=\"iptables\" TARGETS=\"//test/iptables:iptables_test\")\n.PHONY: iptables-tests\n+# Run the iptables tests with runsc only. Useful for developing to skip runc\n+# testing.\n+iptables-runsc-tests: load-iptables\n+ @sudo modprobe iptable_filter\n+ @sudo modprobe ip6table_filter\n+ @$(call submake,install-test-runtime RUNTIME=\"iptables\" ARGS=\"--net-raw\")\n+ @$(call submake,test-runtime RUNTIME=\"iptables\" TARGETS=\"//test/iptables:iptables_test\")\n+.PHONY: iptables-runsc-tests\n+\npacketdrill-tests: load-packetdrill\n@$(call submake,install-test-runtime RUNTIME=\"packetdrill\")\n@$(call submake,test-runtime RUNTIME=\"packetdrill\" TARGETS=\"$(shell $(MAKE) query TARGETS='attr(tags, packetdrill, tests(//...))')\")\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netfilter/netfilter.go",
"new_path": "pkg/sentry/socket/netfilter/netfilter.go",
"diff": "@@ -57,7 +57,7 @@ var nameToID = map[string]stack.TableID{\n}\n// DefaultLinuxTables returns the rules of stack.DefaultTables() wrapped for\n-// compatability with netfilter extensions.\n+// compatibility with netfilter extensions.\nfunc DefaultLinuxTables() *stack.IPTables {\ntables := stack.DefaultTables()\ntables.VisitTargets(func(oldTarget stack.Target) stack.Target {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netfilter/targets.go",
"new_path": "pkg/sentry/socket/netfilter/targets.go",
"diff": "@@ -118,6 +118,10 @@ func (rt *returnTarget) id() targetID {\ntype redirectTarget struct {\nstack.RedirectTarget\n+\n+ // addr must be (un)marshalled when reading and writing the target to\n+ // userspace, but does not affect behavior.\n+ addr tcpip.Address\n}\nfunc (rt *redirectTarget) id() targetID {\n@@ -296,7 +300,7 @@ func (*redirectTargetMaker) unmarshal(buf []byte, filter stack.IPHeaderFilter) (\nbinary.Unmarshal(buf, usermem.ByteOrder, &rt)\n// Copy linux.XTRedirectTarget to stack.RedirectTarget.\n- target := redirectTarget{stack.RedirectTarget{\n+ target := redirectTarget{RedirectTarget: stack.RedirectTarget{\nNetworkProtocol: filter.NetworkProtocol(),\n}}\n@@ -326,7 +330,7 @@ func (*redirectTargetMaker) unmarshal(buf []byte, filter stack.IPHeaderFilter) (\nreturn nil, syserr.ErrInvalidArgument\n}\n- target.Addr = tcpip.Address(nfRange.RangeIPV4.MinIP[:])\n+ target.addr = tcpip.Address(nfRange.RangeIPV4.MinIP[:])\ntarget.Port = ntohs(nfRange.RangeIPV4.MinPort)\nreturn &target, nil\n@@ -361,8 +365,8 @@ func (*nfNATTargetMaker) marshal(target target) []byte {\n},\n}\ncopy(nt.Target.Name[:], RedirectTargetName)\n- copy(nt.Range.MinAddr[:], rt.Addr)\n- copy(nt.Range.MaxAddr[:], rt.Addr)\n+ copy(nt.Range.MinAddr[:], rt.addr)\n+ copy(nt.Range.MaxAddr[:], rt.addr)\nnt.Range.MinProto = htons(rt.Port)\nnt.Range.MaxProto = nt.Range.MinProto\n@@ -403,11 +407,13 @@ func (*nfNATTargetMaker) unmarshal(buf []byte, filter stack.IPHeaderFilter) (tar\nreturn nil, syserr.ErrInvalidArgument\n}\n- target := redirectTarget{stack.RedirectTarget{\n+ target := redirectTarget{\n+ RedirectTarget: stack.RedirectTarget{\nNetworkProtocol: filter.NetworkProtocol(),\n- Addr: tcpip.Address(natRange.MinAddr[:]),\nPort: ntohs(natRange.MinProto),\n- }}\n+ },\n+ addr: tcpip.Address(natRange.MinAddr[:]),\n+ }\nreturn &target, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -269,7 +269,7 @@ func (ct *ConnTrack) connForTID(tid tupleID) (*conn, direction) {\nreturn nil, dirOriginal\n}\n-func (ct *ConnTrack) insertRedirectConn(pkt *PacketBuffer, hook Hook, rt *RedirectTarget) *conn {\n+func (ct *ConnTrack) insertRedirectConn(pkt *PacketBuffer, hook Hook, port uint16, address tcpip.Address) *conn {\ntid, err := packetToTupleID(pkt)\nif err != nil {\nreturn nil\n@@ -282,8 +282,8 @@ func (ct *ConnTrack) insertRedirectConn(pkt *PacketBuffer, hook Hook, rt *Redire\n// rule. This tuple will be used to manipulate the packet in\n// handlePacket.\nreplyTID := tid.reply()\n- replyTID.srcAddr = rt.Addr\n- replyTID.srcPort = rt.Port\n+ replyTID.srcAddr = address\n+ replyTID.srcPort = port\nvar manip manipType\nswitch hook {\ncase Prerouting:\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables.go",
"new_path": "pkg/tcpip/stack/iptables.go",
"diff": "@@ -25,7 +25,7 @@ import (\n// TableID identifies a specific table.\ntype TableID int\n-// Each value identifies a specfic table.\n+// Each value identifies a specific table.\nconst (\nNATID TableID = iota\nMangleID\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables_targets.go",
"new_path": "pkg/tcpip/stack/iptables_targets.go",
"diff": "package stack\nimport (\n+ \"fmt\"\n+\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n@@ -81,25 +83,34 @@ func (*ReturnTarget) Action(*PacketBuffer, *ConnTrack, Hook, *GSO, *Route, tcpip\nreturn RuleReturn, 0\n}\n-// RedirectTarget redirects the packet by modifying the destination port/IP.\n+// RedirectTarget redirects the packet to this machine by modifying the\n+// destination port/IP. Outgoing packets are redirected to the loopback device,\n+// and incoming packets are redirected to the incoming interface (rather than\n+// forwarded).\n+//\n// TODO(gvisor.dev/issue/170): Other flags need to be added after we support\n// them.\ntype RedirectTarget struct {\n- // Addr indicates address used to redirect.\n- Addr tcpip.Address\n-\n- // Port indicates port used to redirect.\n+ // Port indicates port used to redirect. It is immutable.\nPort uint16\n- // NetworkProtocol is the network protocol the target is used with.\n+ // NetworkProtocol is the network protocol the target is used with. It\n+ // is immutable.\nNetworkProtocol tcpip.NetworkProtocolNumber\n}\n// Action implements Target.Action.\n// TODO(gvisor.dev/issue/170): Parse headers without copying. The current\n-// implementation only works for PREROUTING and calls pkt.Clone(), neither\n+// implementation only works for Prerouting and calls pkt.Clone(), neither\n// of which should be the case.\nfunc (rt *RedirectTarget) Action(pkt *PacketBuffer, ct *ConnTrack, hook Hook, gso *GSO, r *Route, address tcpip.Address) (RuleVerdict, int) {\n+ // Sanity check.\n+ if rt.NetworkProtocol != pkt.NetworkProtocolNumber {\n+ panic(fmt.Sprintf(\n+ \"RedirectTarget.Action with NetworkProtocol %d called on packet with NetworkProtocolNumber %d\",\n+ rt.NetworkProtocol, pkt.NetworkProtocolNumber))\n+ }\n+\n// Packet is already manipulated.\nif pkt.NatDone {\nreturn RuleAccept, 0\n@@ -110,17 +121,17 @@ func (rt *RedirectTarget) Action(pkt *PacketBuffer, ct *ConnTrack, hook Hook, gs\nreturn RuleDrop, 0\n}\n- // Change the address to localhost (127.0.0.1 or ::1) in Output and to\n+ // Change the address to loopback (127.0.0.1 or ::1) in Output and to\n// the primary address of the incoming interface in Prerouting.\nswitch hook {\ncase Output:\nif pkt.NetworkProtocolNumber == header.IPv4ProtocolNumber {\n- rt.Addr = tcpip.Address([]byte{127, 0, 0, 1})\n+ address = tcpip.Address([]byte{127, 0, 0, 1})\n} else {\n- rt.Addr = header.IPv6Loopback\n+ address = header.IPv6Loopback\n}\ncase Prerouting:\n- rt.Addr = address\n+ // No-op, as address is already set correctly.\ndefault:\npanic(\"redirect target is supported only on output and prerouting hooks\")\n}\n@@ -148,7 +159,7 @@ func (rt *RedirectTarget) Action(pkt *PacketBuffer, ct *ConnTrack, hook Hook, gs\n}\n}\n- pkt.Network().SetDestinationAddress(rt.Addr)\n+ pkt.Network().SetDestinationAddress(address)\n// After modification, IPv4 packets need a valid checksum.\nif pkt.NetworkProtocolNumber == header.IPv4ProtocolNumber {\n@@ -165,7 +176,7 @@ func (rt *RedirectTarget) Action(pkt *PacketBuffer, ct *ConnTrack, hook Hook, gs\n// Set up conection for matching NAT rule. Only the first\n// packet of the connection comes here. Other packets will be\n// manipulated in connection tracking.\n- if conn := ct.insertRedirectConn(pkt, hook, rt); conn != nil {\n+ if conn := ct.insertRedirectConn(pkt, hook, rt.Port, address); conn != nil {\nct.handlePacket(pkt, hook, gso, r)\n}\ndefault:\n"
}
] | Go | Apache License 2.0 | google/gvisor | Make RedirectTarget thread safe
Fixes #4613.
PiperOrigin-RevId: 339746784 |
259,907 | 29.10.2020 15:04:56 | 25,200 | 52f1dd5e7270dd78ae4ae246d583f2f7c6df0ba5 | [infra] Deflake Go / generate (pull_request.
does not seem to work. Try this new approach. | [
{
"change_type": "MODIFY",
"old_path": "tools/go_branch.sh",
"new_path": "tools/go_branch.sh",
"diff": "@@ -61,14 +61,6 @@ go_branch=$( \\\n)\nreadonly go_branch\n-declare commit\n-commit=$(git rev-parse HEAD)\n-readonly commit\n-if [[ -n \"$(git branch --contains=\"${commit}\" go)\" ]]; then\n- # The go branch already has the commit.\n- exit 0\n-fi\n-\n# Clone the current repository to the temporary directory, and check out the\n# current go_branch directory. We move to the new repository for convenience.\ndeclare repo_orig\n@@ -130,7 +122,11 @@ find . -type f -exec chmod 0644 {} \\;\nfind . -type d -exec chmod 0755 {} \\;\n# Update the current working set and commit.\n-git add . && git commit -m \"Merge ${head} (automated)\"\n+# If the current working commit has already been committed to the remote go\n+# branch, then we have nothing to commit here. So allow empty commit. This can\n+# occur when this script is run parallely (via pull_request and push events)\n+# and the push workflow finishes before the pull_request workflow can run this.\n+git add . && git commit --allow-empty -m \"Merge ${head} (automated)\"\n# Push the branch back to the original repository.\ngit remote add orig \"${repo_orig}\" && git push -f orig go:go\n"
}
] | Go | Apache License 2.0 | google/gvisor | [infra] Deflake Go / generate (pull_request.
#4673 does not seem to work. Try this new approach.
PiperOrigin-RevId: 339754794 |
259,951 | 29.10.2020 16:20:44 | 25,200 | dd056112b72abde9f570a69ad7cfc2a0a6beed14 | Add IPv4 reassembly packetimpact test
The IPv6 reassembly test was also refactored to be easily extended with
more cases. | [
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/runner/defs.bzl",
"new_path": "test/packetimpact/runner/defs.bzl",
"diff": "@@ -251,6 +251,9 @@ ALL_TESTS = [\n# TODO(b/159928940): Fix netstack then remove the line below.\nexpect_netstack_failure = True,\n),\n+ PacketimpactTestInfo(\n+ name = \"ipv4_fragment_reassembly\",\n+ ),\nPacketimpactTestInfo(\nname = \"ipv6_fragment_reassembly\",\n),\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/BUILD",
"new_path": "test/packetimpact/tests/BUILD",
"diff": "@@ -297,6 +297,18 @@ packetimpact_testbench(\n],\n)\n+packetimpact_testbench(\n+ name = \"ipv4_fragment_reassembly\",\n+ srcs = [\"ipv4_fragment_reassembly_test.go\"],\n+ deps = [\n+ \"//pkg/tcpip/buffer\",\n+ \"//pkg/tcpip/header\",\n+ \"//test/packetimpact/testbench\",\n+ \"@com_github_google_go_cmp//cmp:go_default_library\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n+ ],\n+)\n+\npacketimpact_testbench(\nname = \"ipv6_fragment_reassembly\",\nsrcs = [\"ipv6_fragment_reassembly_test.go\"],\n@@ -305,6 +317,7 @@ packetimpact_testbench(\n\"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/header\",\n\"//test/packetimpact/testbench\",\n+ \"@com_github_google_go_cmp//cmp:go_default_library\",\n\"@org_golang_x_sys//unix:go_default_library\",\n],\n)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/packetimpact/tests/ipv4_fragment_reassembly_test.go",
"diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package ipv4_fragment_reassembly_test\n+\n+import (\n+ \"flag\"\n+ \"math/rand\"\n+ \"testing\"\n+ \"time\"\n+\n+ \"github.com/google/go-cmp/cmp\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/test/packetimpact/testbench\"\n+)\n+\n+func init() {\n+ testbench.RegisterFlags(flag.CommandLine)\n+}\n+\n+type fragmentInfo struct {\n+ offset uint16\n+ size uint16\n+ more uint8\n+}\n+\n+func TestIPv4FragmentReassembly(t *testing.T) {\n+ const fragmentID = 42\n+ icmpv4ProtoNum := uint8(header.ICMPv4ProtocolNumber)\n+\n+ tests := []struct {\n+ description string\n+ ipPayloadLen int\n+ fragments []fragmentInfo\n+ expectReply bool\n+ }{\n+ {\n+ description: \"basic reassembly\",\n+ ipPayloadLen: 2000,\n+ fragments: []fragmentInfo{\n+ {offset: 0, size: 1000, more: header.IPv4FlagMoreFragments},\n+ {offset: 1000, size: 1000, more: 0},\n+ },\n+ expectReply: true,\n+ },\n+ {\n+ description: \"out of order fragments\",\n+ ipPayloadLen: 2000,\n+ fragments: []fragmentInfo{\n+ {offset: 1000, size: 1000, more: 0},\n+ {offset: 0, size: 1000, more: header.IPv4FlagMoreFragments},\n+ },\n+ expectReply: true,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.description, func(t *testing.T) {\n+ dut := testbench.NewDUT(t)\n+ defer dut.TearDown()\n+ conn := testbench.NewIPv4Conn(t, testbench.IPv4{}, testbench.IPv4{})\n+ defer conn.Close(t)\n+\n+ data := make([]byte, test.ipPayloadLen)\n+ icmp := header.ICMPv4(data[:header.ICMPv4MinimumSize])\n+ icmp.SetType(header.ICMPv4Echo)\n+ icmp.SetCode(header.ICMPv4UnusedCode)\n+ icmp.SetChecksum(0)\n+ icmp.SetSequence(0)\n+ icmp.SetIdent(0)\n+ originalPayload := data[header.ICMPv4MinimumSize:]\n+ if _, err := rand.Read(originalPayload); err != nil {\n+ t.Fatalf(\"rand.Read: %s\", err)\n+ }\n+ cksum := header.ICMPv4Checksum(\n+ icmp,\n+ buffer.NewVectorisedView(len(originalPayload), []buffer.View{originalPayload}),\n+ )\n+ icmp.SetChecksum(cksum)\n+\n+ for _, fragment := range test.fragments {\n+ conn.Send(t,\n+ testbench.IPv4{\n+ Protocol: &icmpv4ProtoNum,\n+ FragmentOffset: testbench.Uint16(fragment.offset),\n+ Flags: testbench.Uint8(fragment.more),\n+ ID: testbench.Uint16(fragmentID),\n+ },\n+ &testbench.Payload{\n+ Bytes: data[fragment.offset:][:fragment.size],\n+ })\n+ }\n+\n+ var bytesReceived int\n+ reassembledPayload := make([]byte, test.ipPayloadLen)\n+ for {\n+ incomingFrame, err := conn.ExpectFrame(t, testbench.Layers{\n+ &testbench.Ether{},\n+ &testbench.IPv4{},\n+ &testbench.ICMPv4{},\n+ }, time.Second)\n+ if err != nil {\n+ // Either an unexpected frame was received, or none at all.\n+ if bytesReceived < test.ipPayloadLen {\n+ t.Fatalf(\"received %d bytes out of %d, then conn.ExpectFrame(_, _, time.Second) failed with %s\", bytesReceived, test.ipPayloadLen, err)\n+ }\n+ break\n+ }\n+ if !test.expectReply {\n+ t.Fatalf(\"unexpected reply received:\\n%s\", incomingFrame)\n+ }\n+ ipPayload, err := incomingFrame[2 /* ICMPv4 */].ToBytes()\n+ if err != nil {\n+ t.Fatalf(\"failed to parse ICMPv4 header: incomingPacket[2].ToBytes() = (_, %s)\", err)\n+ }\n+ offset := *incomingFrame[1 /* IPv4 */].(*testbench.IPv4).FragmentOffset\n+ if copied := copy(reassembledPayload[offset:], ipPayload); copied != len(ipPayload) {\n+ t.Fatalf(\"wrong number of bytes copied into reassembledPayload: got = %d, want = %d\", copied, len(ipPayload))\n+ }\n+ bytesReceived += len(ipPayload)\n+ }\n+\n+ if test.expectReply {\n+ if diff := cmp.Diff(originalPayload, reassembledPayload[header.ICMPv4MinimumSize:]); diff != \"\" {\n+ t.Fatalf(\"reassembledPayload mismatch (-want +got):\\n%s\", diff)\n+ }\n+ }\n+ })\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/ipv6_fragment_reassembly_test.go",
"new_path": "test/packetimpact/tests/ipv6_fragment_reassembly_test.go",
"diff": "package ipv6_fragment_reassembly_test\nimport (\n- \"bytes\"\n- \"encoding/binary\"\n- \"encoding/hex\"\n\"flag\"\n+ \"math/rand\"\n\"net\"\n\"testing\"\n\"time\"\n+ \"github.com/google/go-cmp/cmp\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/test/packetimpact/testbench\"\n)\n-const (\n- // The payload length for the first fragment we send. This number\n- // is a multiple of 8 near 750 (half of 1500).\n- firstPayloadLength = 752\n- // The ID field for our outgoing fragments.\n- fragmentID = 1\n- // A node must be able to accept a fragmented packet that,\n- // after reassembly, is as large as 1500 octets.\n- reassemblyCap = 1500\n-)\n-\nfunc init() {\ntestbench.RegisterFlags(flag.CommandLine)\n}\n+type fragmentInfo struct {\n+ offset uint16\n+ size uint16\n+ more bool\n+}\n+\nfunc TestIPv6FragmentReassembly(t *testing.T) {\n+ const fragmentID = 42\n+ icmpv6ProtoNum := header.IPv6ExtensionHeaderIdentifier(header.ICMPv6ProtocolNumber)\n+\n+ tests := []struct {\n+ description string\n+ ipPayloadLen int\n+ fragments []fragmentInfo\n+ expectReply bool\n+ }{\n+ {\n+ description: \"basic reassembly\",\n+ ipPayloadLen: 1500,\n+ fragments: []fragmentInfo{\n+ {offset: 0, size: 760, more: true},\n+ {offset: 760, size: 740, more: false},\n+ },\n+ expectReply: true,\n+ },\n+ {\n+ description: \"out of order fragments\",\n+ ipPayloadLen: 3000,\n+ fragments: []fragmentInfo{\n+ {offset: 0, size: 1024, more: true},\n+ {offset: 2048, size: 952, more: false},\n+ {offset: 1024, size: 1024, more: true},\n+ },\n+ expectReply: true,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.description, func(t *testing.T) {\ndut := testbench.NewDUT(t)\ndefer dut.TearDown()\nconn := testbench.NewIPv6Conn(t, testbench.IPv6{}, testbench.IPv6{})\ndefer conn.Close(t)\n- firstPayloadToSend := make([]byte, firstPayloadLength)\n- for i := range firstPayloadToSend {\n- firstPayloadToSend[i] = 'A'\n- }\n-\n- secondPayloadLength := reassemblyCap - firstPayloadLength - header.ICMPv6EchoMinimumSize\n- secondPayloadToSend := firstPayloadToSend[:secondPayloadLength]\n-\n- icmpv6EchoPayload := make([]byte, 4)\n- binary.BigEndian.PutUint16(icmpv6EchoPayload[0:], 0)\n- binary.BigEndian.PutUint16(icmpv6EchoPayload[2:], 0)\n- icmpv6EchoPayload = append(icmpv6EchoPayload, firstPayloadToSend...)\n-\nlIP := tcpip.Address(net.ParseIP(testbench.LocalIPv6).To16())\nrIP := tcpip.Address(net.ParseIP(testbench.RemoteIPv6).To16())\n- icmpv6 := testbench.ICMPv6{\n- Type: testbench.ICMPv6Type(header.ICMPv6EchoRequest),\n- Code: testbench.ICMPv6Code(header.ICMPv6UnusedCode),\n- Payload: icmpv6EchoPayload,\n- }\n- icmpv6Bytes, err := icmpv6.ToBytes()\n- if err != nil {\n- t.Fatalf(\"failed to serialize ICMPv6: %s\", err)\n+\n+ data := make([]byte, test.ipPayloadLen)\n+ icmp := header.ICMPv6(data[:header.ICMPv6HeaderSize])\n+ icmp.SetType(header.ICMPv6EchoRequest)\n+ icmp.SetCode(header.ICMPv6UnusedCode)\n+ icmp.SetChecksum(0)\n+ originalPayload := data[header.ICMPv6HeaderSize:]\n+ if _, err := rand.Read(originalPayload); err != nil {\n+ t.Fatalf(\"rand.Read: %s\", err)\n}\n+\ncksum := header.ICMPv6Checksum(\n- header.ICMPv6(icmpv6Bytes),\n+ icmp,\nlIP,\nrIP,\n- buffer.NewVectorisedView(len(secondPayloadToSend), []buffer.View{secondPayloadToSend}),\n+ buffer.NewVectorisedView(len(originalPayload), []buffer.View{originalPayload}),\n)\n+ icmp.SetChecksum(cksum)\n- conn.Send(t, testbench.IPv6{},\n- &testbench.IPv6FragmentExtHdr{\n- FragmentOffset: testbench.Uint16(0),\n- MoreFragments: testbench.Bool(true),\n- Identification: testbench.Uint32(fragmentID),\n- },\n- &testbench.ICMPv6{\n- Type: testbench.ICMPv6Type(header.ICMPv6EchoRequest),\n- Code: testbench.ICMPv6Code(header.ICMPv6UnusedCode),\n- Payload: icmpv6EchoPayload,\n- Checksum: &cksum,\n- })\n-\n- icmpv6ProtoNum := header.IPv6ExtensionHeaderIdentifier(header.ICMPv6ProtocolNumber)\n-\n+ for _, fragment := range test.fragments {\nconn.Send(t, testbench.IPv6{},\n&testbench.IPv6FragmentExtHdr{\nNextHeader: &icmpv6ProtoNum,\n- FragmentOffset: testbench.Uint16((firstPayloadLength + header.ICMPv6EchoMinimumSize) / 8),\n- MoreFragments: testbench.Bool(false),\n+ FragmentOffset: testbench.Uint16(fragment.offset / header.IPv6FragmentExtHdrFragmentOffsetBytesPerUnit),\n+ MoreFragments: testbench.Bool(fragment.more),\nIdentification: testbench.Uint32(fragmentID),\n},\n&testbench.Payload{\n- Bytes: secondPayloadToSend,\n+ Bytes: data[fragment.offset:][:fragment.size],\n})\n+ }\n- gotEchoReplyFirstPart, err := conn.ExpectFrame(t, testbench.Layers{\n+ var bytesReceived int\n+ reassembledPayload := make([]byte, test.ipPayloadLen)\n+ for {\n+ incomingFrame, err := conn.ExpectFrame(t, testbench.Layers{\n&testbench.Ether{},\n&testbench.IPv6{},\n- &testbench.IPv6FragmentExtHdr{\n- FragmentOffset: testbench.Uint16(0),\n- MoreFragments: testbench.Bool(true),\n- },\n- &testbench.ICMPv6{\n- Type: testbench.ICMPv6Type(header.ICMPv6EchoReply),\n- Code: testbench.ICMPv6Code(header.ICMPv6UnusedCode),\n- },\n+ &testbench.IPv6FragmentExtHdr{},\n+ &testbench.ICMPv6{},\n}, time.Second)\nif err != nil {\n- t.Fatalf(\"expected a fragmented ICMPv6 Echo Reply, but got none: %s\", err)\n+ // Either an unexpected frame was received, or none at all.\n+ if bytesReceived < test.ipPayloadLen {\n+ t.Fatalf(\"received %d bytes out of %d, then conn.ExpectFrame(_, _, time.Second) failed with %s\", bytesReceived, test.ipPayloadLen, err)\n}\n-\n- id := *gotEchoReplyFirstPart[2].(*testbench.IPv6FragmentExtHdr).Identification\n- gotFirstPayload, err := gotEchoReplyFirstPart[len(gotEchoReplyFirstPart)-1].ToBytes()\n+ break\n+ }\n+ if !test.expectReply {\n+ t.Fatalf(\"unexpected reply received:\\n%s\", incomingFrame)\n+ }\n+ ipPayload, err := incomingFrame[3 /* ICMPv6 */].ToBytes()\nif err != nil {\n- t.Fatalf(\"failed to serialize ICMPv6: %s\", err)\n+ t.Fatalf(\"failed to parse ICMPv6 header: incomingPacket[3].ToBytes() = (_, %s)\", err)\n}\n- icmpPayload := gotFirstPayload[header.ICMPv6EchoMinimumSize:]\n- receivedLen := len(icmpPayload)\n- wantSecondPayloadLen := reassemblyCap - header.ICMPv6EchoMinimumSize - receivedLen\n- wantFirstPayload := make([]byte, receivedLen)\n- for i := range wantFirstPayload {\n- wantFirstPayload[i] = 'A'\n+ offset := *incomingFrame[2 /* IPv6FragmentExtHdr */].(*testbench.IPv6FragmentExtHdr).FragmentOffset\n+ offset *= header.IPv6FragmentExtHdrFragmentOffsetBytesPerUnit\n+ if copied := copy(reassembledPayload[offset:], ipPayload); copied != len(ipPayload) {\n+ t.Fatalf(\"wrong number of bytes copied into reassembledPayload: got = %d, want = %d\", copied, len(ipPayload))\n}\n- wantSecondPayload := wantFirstPayload[:wantSecondPayloadLen]\n- if !bytes.Equal(icmpPayload, wantFirstPayload) {\n- t.Fatalf(\"received unexpected payload, got: %s, want: %s\",\n- hex.Dump(icmpPayload),\n- hex.Dump(wantFirstPayload))\n+ bytesReceived += len(ipPayload)\n}\n- gotEchoReplySecondPart, err := conn.ExpectFrame(t, testbench.Layers{\n- &testbench.Ether{},\n- &testbench.IPv6{},\n- &testbench.IPv6FragmentExtHdr{\n- NextHeader: &icmpv6ProtoNum,\n- FragmentOffset: testbench.Uint16(uint16((receivedLen + header.ICMPv6EchoMinimumSize) / 8)),\n- MoreFragments: testbench.Bool(false),\n- Identification: &id,\n- },\n- &testbench.ICMPv6{},\n- }, time.Second)\n- if err != nil {\n- t.Fatalf(\"expected the rest of ICMPv6 Echo Reply, but got none: %s\", err)\n+ if test.expectReply {\n+ if diff := cmp.Diff(originalPayload, reassembledPayload[header.ICMPv6HeaderSize:]); diff != \"\" {\n+ t.Fatalf(\"reassembledPayload mismatch (-want +got):\\n%s\", diff)\n}\n- secondPayload, err := gotEchoReplySecondPart[len(gotEchoReplySecondPart)-1].ToBytes()\n- if err != nil {\n- t.Fatalf(\"failed to serialize ICMPv6 Echo Reply: %s\", err)\n}\n- if !bytes.Equal(secondPayload, wantSecondPayload) {\n- t.Fatalf(\"received unexpected payload, got: %s, want: %s\",\n- hex.Dump(secondPayload),\n- hex.Dump(wantSecondPayload))\n+ })\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add IPv4 reassembly packetimpact test
The IPv6 reassembly test was also refactored to be easily extended with
more cases.
PiperOrigin-RevId: 339768605 |
259,858 | 30.10.2020 09:39:16 | 25,200 | 3a6f046ae8d852210ae2b82ba35e9a8c2e6757b9 | Avoid creating users if user is root already. | [
{
"change_type": "MODIFY",
"old_path": "tools/bazel.mk",
"new_path": "tools/bazel.mk",
"diff": "@@ -26,13 +26,13 @@ BRANCH_NAME := $(shell (git branch --show-current 2>/dev/null || \\\nBUILD_ROOTS := bazel-bin/ bazel-out/\n# Bazel container configuration (see below).\n-USER ?= gvisor\n-HASH ?= $(shell readlink -m $(CURDIR) | md5sum | cut -c1-8)\n+USER := $(shell whoami)\n+HASH := $(shell readlink -m $(CURDIR) | md5sum | cut -c1-8)\nBUILDER_BASE := gvisor.dev/images/default\nBUILDER_IMAGE := gvisor.dev/images/builder\n-BUILDER_NAME ?= gvisor-builder-$(HASH)\n-DOCKER_NAME ?= gvisor-bazel-$(HASH)\n-DOCKER_PRIVILEGED ?= --privileged\n+BUILDER_NAME := gvisor-builder-$(HASH)\n+DOCKER_NAME := gvisor-bazel-$(HASH)\n+DOCKER_PRIVILEGED := --privileged\nBAZEL_CACHE := $(shell readlink -m ~/.cache/bazel/)\nGCLOUD_CONFIG := $(shell readlink -m ~/.config/gcloud/)\nDOCKER_SOCKET := /var/run/docker.sock\n@@ -59,6 +59,25 @@ ifeq (true,$(shell [[ -t 0 ]] && echo true))\nFULL_DOCKER_EXEC_OPTIONS += --tty\nendif\n+# Add basic UID/GID options.\n+#\n+# Note that USERADD_DOCKER and GROUPADD_DOCKER are both defined as \"deferred\"\n+# variables in Make terminology, that is they will be expanded at time of use\n+# and may include other variables, including those defined below.\n+#\n+# NOTE: we pass -l to useradd below because otherwise you can hit a bug\n+# best described here:\n+# https://github.com/moby/moby/issues/5419#issuecomment-193876183\n+# TLDR; trying to add to /var/log/lastlog (sparse file) runs the machine out\n+# out of disk space.\n+ifneq ($(UID),0)\n+USERADD_DOCKER += useradd -l --uid $(UID) --non-unique --no-create-home \\\n+ --gid $(GID) $(USERADD_OPTIONS) -d $(HOME) $(USER) &&\n+endif\n+ifneq ($(GID),0)\n+GROUPADD_DOCKER += groupadd --gid $(GID) --non-unique $(USER) &&\n+endif\n+\n# Add docker passthrough options.\nifneq ($(DOCKER_PRIVILEGED),)\nFULL_DOCKER_RUN_OPTIONS += -v \"$(DOCKER_SOCKET):$(DOCKER_SOCKET)\"\n@@ -91,19 +110,12 @@ ifneq (,$(BAZEL_CONFIG))\nOPTIONS += --config=$(BAZEL_CONFIG)\nendif\n-# NOTE: we pass -l to useradd below because otherwise you can hit a bug\n-# best described here:\n-# https://github.com/moby/moby/issues/5419#issuecomment-193876183\n-# TLDR; trying to add to /var/log/lastlog (sparse file) runs the machine out\n-# out of disk space.\nbazel-image: load-default\n@if docker ps --all | grep $(BUILDER_NAME); then docker rm -f $(BUILDER_NAME); fi\ndocker run --user 0:0 --entrypoint \"\" --name $(BUILDER_NAME) \\\n$(BUILDER_BASE) \\\n- sh -c \"groupadd --gid $(GID) --non-unique $(USER) && \\\n- $(GROUPADD_DOCKER) \\\n- useradd -l --uid $(UID) --non-unique --no-create-home \\\n- --gid $(GID) $(USERADD_OPTIONS) -d $(HOME) $(USER) && \\\n+ sh -c \"$(GROUPADD_DOCKER) \\\n+ $(USERADD_DOCKER) \\\nif [[ -e /dev/kvm ]]; then chmod a+rw /dev/kvm; fi\"\ndocker commit $(BUILDER_NAME) $(BUILDER_IMAGE)\n@docker rm -f $(BUILDER_NAME)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Avoid creating users if user is root already.
PiperOrigin-RevId: 339886754 |
259,860 | 30.10.2020 17:40:28 | 25,200 | 1f25697cfe0484198784afc947ae3bdf4eb05e9b | Fix rename error handling for VFS2 kernfs.
The non-errno error was causing panics before. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go",
"new_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go",
"diff": "@@ -568,13 +568,6 @@ func (o *OrderedChildren) RmDir(ctx context.Context, name string, child Inode) e\nreturn o.Unlink(ctx, name, child)\n}\n-// +stateify savable\n-type renameAcrossDifferentImplementationsError struct{}\n-\n-func (renameAcrossDifferentImplementationsError) Error() string {\n- return \"rename across inodes with different implementations\"\n-}\n-\n// Rename implements Inode.Rename.\n//\n// Precondition: Rename may only be called across two directory inodes with\n@@ -587,7 +580,7 @@ func (renameAcrossDifferentImplementationsError) Error() string {\nfunc (o *OrderedChildren) Rename(ctx context.Context, oldname, newname string, child, dstDir Inode) error {\ndst, ok := dstDir.(interface{}).(*OrderedChildren)\nif !ok {\n- return renameAcrossDifferentImplementationsError{}\n+ return syserror.ENODEV\n}\nif !o.writable || !dst.writable {\nreturn syserror.EPERM\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix rename error handling for VFS2 kernfs.
The non-errno error was causing panics before.
PiperOrigin-RevId: 339969348 |
259,860 | 30.10.2020 19:37:29 | 25,200 | 4eb1c87e8033520981cce19dea7cde5f85f07737 | Adjust error handling in kernfs rename.
Read-only directories (e.g. under /sys, /proc) should return EPERM for rename. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go",
"new_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go",
"diff": "@@ -578,13 +578,18 @@ func (o *OrderedChildren) RmDir(ctx context.Context, name string, child Inode) e\n//\n// Postcondition: reference on any replaced dentry transferred to caller.\nfunc (o *OrderedChildren) Rename(ctx context.Context, oldname, newname string, child, dstDir Inode) error {\n+ if !o.writable {\n+ return syserror.EPERM\n+ }\n+\ndst, ok := dstDir.(interface{}).(*OrderedChildren)\nif !ok {\n- return syserror.ENODEV\n+ return syserror.EXDEV\n}\n- if !o.writable || !dst.writable {\n+ if !dst.writable {\nreturn syserror.EPERM\n}\n+\n// Note: There's a potential deadlock below if concurrent calls to Rename\n// refer to the same src and dst directories in reverse. We avoid any\n// ordering issues because the caller is required to serialize concurrent\n"
}
] | Go | Apache License 2.0 | google/gvisor | Adjust error handling in kernfs rename.
Read-only directories (e.g. under /sys, /proc) should return EPERM for rename.
PiperOrigin-RevId: 339979022 |
259,853 | 31.10.2020 01:17:29 | 25,200 | df88f223bb5474a462da65ede6f266eb52f1b2ef | net/tcpip: connect to unset loopback address has to return EADDRNOTAVAIL
In the docker container, the ipv6 loopback address is not set,
and connect("::1") has to return ENEADDRNOTAVAIL in this case.
Without this fix, it returns EHOSTUNREACH. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/ipv6.go",
"new_path": "pkg/tcpip/header/ipv6.go",
"diff": "@@ -375,6 +375,12 @@ func IsV6LinkLocalAddress(addr tcpip.Address) bool {\nreturn addr[0] == 0xfe && (addr[1]&0xc0) == 0x80\n}\n+// IsV6LoopbackAddress determines if the provided address is an IPv6 loopback\n+// address.\n+func IsV6LoopbackAddress(addr tcpip.Address) bool {\n+ return addr == IPv6Loopback\n+}\n+\n// IsV6LinkLocalMulticastAddress determines if the provided address is an IPv6\n// link-local multicast address.\nfunc IsV6LinkLocalMulticastAddress(addr tcpip.Address) bool {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -1210,7 +1210,9 @@ func (s *Stack) FindRoute(id tcpip.NICID, localAddr, remoteAddr tcpip.Address, n\nisLocalBroadcast := remoteAddr == header.IPv4Broadcast\nisMulticast := header.IsV4MulticastAddress(remoteAddr) || header.IsV6MulticastAddress(remoteAddr)\n- needRoute := !(isLocalBroadcast || isMulticast || header.IsV6LinkLocalAddress(remoteAddr))\n+ isLinkLocal := header.IsV6LinkLocalAddress(remoteAddr) || header.IsV6LinkLocalMulticastAddress(remoteAddr)\n+ IsLoopback := header.IsV4LoopbackAddress(remoteAddr) || header.IsV6LoopbackAddress(remoteAddr)\n+ needRoute := !(isLocalBroadcast || isMulticast || isLinkLocal || IsLoopback)\nif id != 0 && !needRoute {\nif nic, ok := s.nics[id]; ok && nic.Enabled() {\nif addressEndpoint := s.getAddressEP(nic, localAddr, remoteAddr, netProto); addressEndpoint != nil {\n@@ -1246,6 +1248,9 @@ func (s *Stack) FindRoute(id tcpip.NICID, localAddr, remoteAddr tcpip.Address, n\n}\nif !needRoute {\n+ if IsLoopback {\n+ return Route{}, tcpip.ErrBadLocalAddress\n+ }\nreturn Route{}, tcpip.ErrNetworkUnreachable\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/runtimes/exclude/python3.7.3.csv",
"new_path": "test/runtimes/exclude/python3.7.3.csv",
"diff": "@@ -4,7 +4,6 @@ test_asyncore,b/162973328,\ntest_epoll,b/162983393,\ntest_fcntl,b/162978767,fcntl invalid argument -- artificial test to make sure something works in 64 bit mode.\ntest_httplib,b/163000009,OSError: [Errno 98] Address already in use\n-test_imaplib,b/162979661,\ntest_logging,b/162980079,\ntest_multiprocessing_fork,,Flaky. Sometimes times out.\ntest_multiprocessing_forkserver,,Flaky. Sometimes times out.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -694,6 +694,10 @@ syscall_test(\ntest = \"//test/syscalls/linux:socket_ip_unbound_test\",\n)\n+syscall_test(\n+ test = \"//test/syscalls/linux:socket_ip_unbound_netlink_test\",\n+)\n+\nsyscall_test(\ntest = \"//test/syscalls/linux:socket_netdevice_test\",\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -2883,6 +2883,24 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"socket_ip_unbound_netlink_test\",\n+ testonly = 1,\n+ srcs = [\n+ \"socket_ip_unbound_netlink.cc\",\n+ ],\n+ linkstatic = 1,\n+ deps = [\n+ \":ip_socket_test_util\",\n+ \":socket_netlink_route_util\",\n+ \":socket_test_util\",\n+ \"//test/util:capability_util\",\n+ gtest,\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n+\ncc_binary(\nname = \"socket_domain_test\",\ntestonly = 1,\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ip_unbound.cc",
"new_path": "test/syscalls/linux/socket_ip_unbound.cc",
"diff": "@@ -454,23 +454,15 @@ TEST_P(IPUnboundSocketTest, SetReuseAddr) {\nINSTANTIATE_TEST_SUITE_P(\nIPUnboundSockets, IPUnboundSocketTest,\n- ::testing::ValuesIn(VecCat<SocketKind>(VecCat<SocketKind>(\n+ ::testing::ValuesIn(VecCat<SocketKind>(\nApplyVec<SocketKind>(IPv4UDPUnboundSocket,\n- AllBitwiseCombinations(List<int>{SOCK_DGRAM},\n- List<int>{0,\n- SOCK_NONBLOCK})),\n+ std::vector<int>{0, SOCK_NONBLOCK}),\nApplyVec<SocketKind>(IPv6UDPUnboundSocket,\n- AllBitwiseCombinations(List<int>{SOCK_DGRAM},\n- List<int>{0,\n- SOCK_NONBLOCK})),\n+ std::vector<int>{0, SOCK_NONBLOCK}),\nApplyVec<SocketKind>(IPv4TCPUnboundSocket,\n- AllBitwiseCombinations(List<int>{SOCK_STREAM},\n- List<int>{0,\n- SOCK_NONBLOCK})),\n+ std::vector{0, SOCK_NONBLOCK}),\nApplyVec<SocketKind>(IPv6TCPUnboundSocket,\n- AllBitwiseCombinations(List<int>{SOCK_STREAM},\n- List<int>{\n- 0, SOCK_NONBLOCK}))))));\n+ std::vector{0, SOCK_NONBLOCK}))));\n} // namespace testing\n} // namespace gvisor\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/socket_ip_unbound_netlink.cc",
"diff": "+// Copyright 2019 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <arpa/inet.h>\n+#include <netinet/in.h>\n+#include <sys/socket.h>\n+#include <sys/types.h>\n+#include <sys/un.h>\n+\n+#include <cstdio>\n+#include <cstring>\n+\n+#include \"gmock/gmock.h\"\n+#include \"gtest/gtest.h\"\n+#include \"test/syscalls/linux/ip_socket_test_util.h\"\n+#include \"test/syscalls/linux/socket_netlink_route_util.h\"\n+#include \"test/syscalls/linux/socket_test_util.h\"\n+#include \"test/util/capability_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+// Test fixture for tests that apply to pairs of IP sockets.\n+using IPv6UnboundSocketTest = SimpleSocketTest;\n+\n+TEST_P(IPv6UnboundSocketTest, ConnectToBadLocalAddress_NoRandomSave) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_ADMIN)));\n+\n+ // TODO(gvisor.dev/issue/4595): Addresses on net devices are not saved\n+ // across save/restore.\n+ DisableSave ds;\n+\n+ // Delete the loopback address from the loopback interface.\n+ Link loopback_link = ASSERT_NO_ERRNO_AND_VALUE(LoopbackLink());\n+ EXPECT_NO_ERRNO(LinkDelLocalAddr(loopback_link.index, AF_INET6,\n+ /*prefixlen=*/128, &in6addr_loopback,\n+ sizeof(in6addr_loopback)));\n+ Cleanup defer_addr_removal =\n+ Cleanup([loopback_link = std::move(loopback_link)] {\n+ EXPECT_NO_ERRNO(LinkAddLocalAddr(loopback_link.index, AF_INET6,\n+ /*prefixlen=*/128, &in6addr_loopback,\n+ sizeof(in6addr_loopback)));\n+ });\n+\n+ TestAddress addr = V6Loopback();\n+ reinterpret_cast<sockaddr_in6*>(&addr.addr)->sin6_port = 65535;\n+ auto sock = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n+ EXPECT_THAT(connect(sock->get(), reinterpret_cast<sockaddr*>(&addr.addr),\n+ addr.addr_len),\n+ SyscallFailsWithErrno(EADDRNOTAVAIL));\n+}\n+\n+INSTANTIATE_TEST_SUITE_P(IPUnboundSockets, IPv6UnboundSocketTest,\n+ ::testing::ValuesIn(std::vector<SocketKind>{\n+ IPv6UDPUnboundSocket(0),\n+ IPv6TCPUnboundSocket(0)}));\n+\n+using IPv4UnboundSocketTest = SimpleSocketTest;\n+\n+TEST_P(IPv4UnboundSocketTest, ConnectToBadLocalAddress_NoRandomSave) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_ADMIN)));\n+\n+ // TODO(gvisor.dev/issue/4595): Addresses on net devices are not saved\n+ // across save/restore.\n+ DisableSave ds;\n+\n+ // Delete the loopback address from the loopback interface.\n+ Link loopback_link = ASSERT_NO_ERRNO_AND_VALUE(LoopbackLink());\n+ struct in_addr laddr;\n+ laddr.s_addr = htonl(INADDR_LOOPBACK);\n+ EXPECT_NO_ERRNO(LinkDelLocalAddr(loopback_link.index, AF_INET,\n+ /*prefixlen=*/8, &laddr, sizeof(laddr)));\n+ Cleanup defer_addr_removal = Cleanup(\n+ [loopback_link = std::move(loopback_link), addr = std::move(laddr)] {\n+ EXPECT_NO_ERRNO(LinkAddLocalAddr(loopback_link.index, AF_INET,\n+ /*prefixlen=*/8, &addr, sizeof(addr)));\n+ });\n+ TestAddress addr = V4Loopback();\n+ reinterpret_cast<sockaddr_in*>(&addr.addr)->sin_port = 65535;\n+ auto sock = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n+ EXPECT_THAT(connect(sock->get(), reinterpret_cast<sockaddr*>(&addr.addr),\n+ addr.addr_len),\n+ SyscallFailsWithErrno(EADDRNOTAVAIL));\n+}\n+\n+INSTANTIATE_TEST_SUITE_P(IPUnboundSockets, IPv4UnboundSocketTest,\n+ ::testing::ValuesIn(std::vector<SocketKind>{\n+ IPv4UDPUnboundSocket(0),\n+ IPv4TCPUnboundSocket(0)}));\n+\n+} // namespace testing\n+} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | net/tcpip: connect to unset loopback address has to return EADDRNOTAVAIL
In the docker container, the ipv6 loopback address is not set,
and connect("::1") has to return ENEADDRNOTAVAIL in this case.
Without this fix, it returns EHOSTUNREACH.
PiperOrigin-RevId: 340002915 |
259,884 | 01.11.2020 18:01:57 | 28,800 | 5e606844df577936ebcd13225da85eda80317021 | Fix returned error when deleting non-existant address | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netlink/route/protocol.go",
"new_path": "pkg/sentry/socket/netlink/route/protocol.go",
"diff": "@@ -487,7 +487,7 @@ func (p *Protocol) delAddr(ctx context.Context, msg *netlink.Message, ms *netlin\nAddr: value,\n})\nif err != nil {\n- return syserr.ErrInvalidArgument\n+ return syserr.ErrBadLocalAddress\n}\ncase linux.IFA_ADDRESS:\ndefault:\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_netlink_route.cc",
"new_path": "test/syscalls/linux/socket_netlink_route.cc",
"diff": "@@ -536,7 +536,7 @@ TEST(NetlinkRouteTest, AddAndRemoveAddr) {\n// Second delete should fail, as address no longer exists.\nEXPECT_THAT(LinkDelLocalAddr(loopback_link.index, AF_INET,\n/*prefixlen=*/24, &addr, sizeof(addr)),\n- PosixErrorIs(EINVAL, ::testing::_));\n+ PosixErrorIs(EADDRNOTAVAIL, ::testing::_));\n});\n// Replace an existing address should succeed.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix returned error when deleting non-existant address
PiperOrigin-RevId: 340149214 |
259,857 | 13.08.2020 13:01:20 | -28,800 | 3425485b7c47861422c8bf285635d11911035383 | kvm: share upper halves among all pagtables
Fixes: | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/kvm.go",
"new_path": "pkg/sentry/platform/kvm/kvm.go",
"diff": "@@ -158,8 +158,7 @@ func (*KVM) MaxUserAddress() usermem.Addr {\n// NewAddressSpace returns a new pagetable root.\nfunc (k *KVM) NewAddressSpace(_ interface{}) (platform.AddressSpace, <-chan struct{}, error) {\n// Allocate page tables and install system mappings.\n- pageTables := pagetables.New(newAllocator())\n- k.machine.mapUpperHalf(pageTables)\n+ pageTables := pagetables.NewWithUpper(newAllocator(), k.machine.upperSharedPageTables, ring0.KernelStartAddress)\n// Return the new address space.\nreturn &addressSpace{\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine.go",
"new_path": "pkg/sentry/platform/kvm/machine.go",
"diff": "@@ -41,6 +41,9 @@ type machine struct {\n// slots are currently being updated, and the caller should retry.\nnextSlot uint32\n+ // upperSharedPageTables tracks the read-only shared upper of all the pagetables.\n+ upperSharedPageTables *pagetables.PageTables\n+\n// kernel is the set of global structures.\nkernel ring0.Kernel\n@@ -199,9 +202,7 @@ func newMachine(vm int) (*machine, error) {\nlog.Debugf(\"The maximum number of vCPUs is %d.\", m.maxVCPUs)\nm.vCPUsByTID = make(map[uint64]*vCPU)\nm.vCPUsByID = make([]*vCPU, m.maxVCPUs)\n- m.kernel.Init(ring0.KernelOpts{\n- PageTables: pagetables.New(newAllocator()),\n- }, m.maxVCPUs)\n+ m.kernel.Init(m.maxVCPUs)\n// Pull the maximum slots.\nmaxSlots, _, errno := syscall.RawSyscall(syscall.SYS_IOCTL, uintptr(m.fd), _KVM_CHECK_EXTENSION, _KVM_CAP_MAX_MEMSLOTS)\n@@ -213,6 +214,13 @@ func newMachine(vm int) (*machine, error) {\nlog.Debugf(\"The maximum number of slots is %d.\", m.maxSlots)\nm.usedSlots = make([]uintptr, m.maxSlots)\n+ // Create the upper shared pagetables and kernel(sentry) pagetables.\n+ m.upperSharedPageTables = pagetables.New(newAllocator())\n+ m.mapUpperHalf(m.upperSharedPageTables)\n+ m.upperSharedPageTables.Allocator.(*allocator).base.Drain()\n+ m.upperSharedPageTables.MarkReadOnlyShared()\n+ m.kernel.PageTables = pagetables.NewWithUpper(newAllocator(), m.upperSharedPageTables, ring0.KernelStartAddress)\n+\n// Apply the physical mappings. Note that these mappings may point to\n// guest physical addresses that are not actually available. These\n// physical pages are mapped on demand, see kernel_unsafe.go.\n@@ -226,7 +234,6 @@ func newMachine(vm int) (*machine, error) {\nreturn true // Keep iterating.\n})\n- m.mapUpperHalf(m.kernel.PageTables)\nvar physicalRegionsReadOnly []physicalRegion\nvar physicalRegionsAvailable []physicalRegion\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine_amd64.go",
"new_path": "pkg/sentry/platform/kvm/machine_amd64.go",
"diff": "@@ -432,23 +432,19 @@ func availableRegionsForSetMem() (phyRegions []physicalRegion) {\nreturn physicalRegions\n}\n-var execRegions = func() (regions []region) {\n+func (m *machine) mapUpperHalf(pageTable *pagetables.PageTables) {\n+ // Map all the executible regions so that all the entry functions\n+ // are mapped in the upper half.\napplyVirtualRegions(func(vr virtualRegion) {\nif excludeVirtualRegion(vr) || vr.filename == \"[vsyscall]\" {\nreturn\n}\n- if vr.accessType.Execute {\n- regions = append(regions, vr.region)\n- }\n- })\n- return\n-}()\n-func (m *machine) mapUpperHalf(pageTable *pagetables.PageTables) {\n- for _, r := range execRegions {\n+ if vr.accessType.Execute {\n+ r := vr.region\nphysical, length, ok := translateToPhysical(r.virtual)\nif !ok || length < r.length {\n- panic(\"impossilbe translation\")\n+ panic(\"impossible translation\")\n}\npageTable.Map(\nusermem.Addr(ring0.KernelStartAddress|r.virtual),\n@@ -456,6 +452,7 @@ func (m *machine) mapUpperHalf(pageTable *pagetables.PageTables) {\npagetables.MapOpts{AccessType: usermem.Execute},\nphysical)\n}\n+ })\nfor start, end := range m.kernel.EntryRegions() {\nregionLen := end - start\nphysical, length, ok := translateToPhysical(start)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/defs.go",
"new_path": "pkg/sentry/platform/ring0/defs.go",
"diff": "@@ -23,6 +23,9 @@ import (\n//\n// This contains global state, shared by multiple CPUs.\ntype Kernel struct {\n+ // PageTables are the kernel pagetables; this must be provided.\n+ PageTables *pagetables.PageTables\n+\nKernelArchState\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/defs_amd64.go",
"new_path": "pkg/sentry/platform/ring0/defs_amd64.go",
"diff": "@@ -66,17 +66,9 @@ var (\nKernelDataSegment SegmentDescriptor\n)\n-// KernelOpts has initialization options for the kernel.\n-type KernelOpts struct {\n- // PageTables are the kernel pagetables; this must be provided.\n- PageTables *pagetables.PageTables\n-}\n-\n// KernelArchState contains architecture-specific state.\ntype KernelArchState struct {\n- KernelOpts\n-\n- // cpuEntries is array of kernelEntry for all cpus\n+ // cpuEntries is array of kernelEntry for all cpus.\ncpuEntries []kernelEntry\n// globalIDT is our set of interrupt gates.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/defs_arm64.go",
"new_path": "pkg/sentry/platform/ring0/defs_arm64.go",
"diff": "@@ -32,15 +32,8 @@ var (\nKernelStartAddress = ^uintptr(0) - (UserspaceSize - 1)\n)\n-// KernelOpts has initialization options for the kernel.\n-type KernelOpts struct {\n- // PageTables are the kernel pagetables; this must be provided.\n- PageTables *pagetables.PageTables\n-}\n-\n// KernelArchState contains architecture-specific state.\ntype KernelArchState struct {\n- KernelOpts\n}\n// CPUArchState contains CPU-specific arch state.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/kernel.go",
"new_path": "pkg/sentry/platform/ring0/kernel.go",
"diff": "@@ -16,11 +16,9 @@ package ring0\n// Init initializes a new kernel.\n//\n-// N.B. that constraints on KernelOpts must be satisfied.\n-//\n//go:nosplit\n-func (k *Kernel) Init(opts KernelOpts, maxCPUs int) {\n- k.init(opts, maxCPUs)\n+func (k *Kernel) Init(maxCPUs int) {\n+ k.init(maxCPUs)\n}\n// Halt halts execution.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/kernel_amd64.go",
"new_path": "pkg/sentry/platform/ring0/kernel_amd64.go",
"diff": "@@ -24,10 +24,7 @@ import (\n)\n// init initializes architecture-specific state.\n-func (k *Kernel) init(opts KernelOpts, maxCPUs int) {\n- // Save the root page tables.\n- k.PageTables = opts.PageTables\n-\n+func (k *Kernel) init(maxCPUs int) {\nentrySize := reflect.TypeOf(kernelEntry{}).Size()\nvar (\nentries []kernelEntry\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/kernel_arm64.go",
"new_path": "pkg/sentry/platform/ring0/kernel_arm64.go",
"diff": "@@ -25,9 +25,7 @@ func HaltAndResume()\nfunc HaltEl1SvcAndResume()\n// init initializes architecture-specific state.\n-func (k *Kernel) init(opts KernelOpts, maxCPUs int) {\n- // Save the root page tables.\n- k.PageTables = opts.PageTables\n+func (k *Kernel) init(maxCPUs int) {\n}\n// init initializes architecture-specific state.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/pagetables/pagetables.go",
"new_path": "pkg/sentry/platform/ring0/pagetables/pagetables.go",
"diff": "@@ -30,6 +30,10 @@ type PageTables struct {\nAllocator Allocator\n// root is the pagetable root.\n+ //\n+ // For same archs such as amd64, the upper of the PTEs is cloned\n+ // from and owned by upperSharedPageTables which are shared among\n+ // many PageTables if upperSharedPageTables is not nil.\nroot *PTEs\n// rootPhysical is the cached physical address of the root.\n@@ -39,15 +43,52 @@ type PageTables struct {\n// archPageTables includes architecture-specific features.\narchPageTables\n+\n+ // upperSharedPageTables represents a read-only shared upper\n+ // of the Pagetable. When it is not nil, the upper is not\n+ // allowed to be modified.\n+ upperSharedPageTables *PageTables\n+\n+ // upperStart is the start address of the upper portion that\n+ // are shared from upperSharedPageTables\n+ upperStart uintptr\n+\n+ // readOnlyShared indicates the Pagetables are read-only and\n+ // own the ranges that are shared with other Pagetables.\n+ readOnlyShared bool\n}\n-// New returns new PageTables.\n-func New(a Allocator) *PageTables {\n+// NewWithUpper returns new PageTables.\n+//\n+// upperSharedPageTables are used for mapping the upper of addresses,\n+// starting at upperStart. These pageTables should not be touched (as\n+// invalidations may be incorrect) after they are passed as an\n+// upperSharedPageTables. Only when all dependent PageTables are gone\n+// may they be used. The intenteded use case is for kernel page tables,\n+// which are static and fixed.\n+//\n+// Precondition: upperStart must be between canonical ranges.\n+// Precondition: upperStart must be pgdSize aligned.\n+// precondition: upperSharedPageTables must be marked read-only shared.\n+func NewWithUpper(a Allocator, upperSharedPageTables *PageTables, upperStart uintptr) *PageTables {\np := new(PageTables)\np.Init(a)\n+ if upperSharedPageTables != nil {\n+ if !upperSharedPageTables.readOnlyShared {\n+ panic(\"Only read-only shared pagetables can be used as upper\")\n+ }\n+ p.upperSharedPageTables = upperSharedPageTables\n+ p.upperStart = upperStart\n+ p.cloneUpperShared()\n+ }\nreturn p\n}\n+// New returns new PageTables.\n+func New(a Allocator) *PageTables {\n+ return NewWithUpper(a, nil, 0)\n+}\n+\n// mapVisitor is used for map.\ntype mapVisitor struct {\ntarget uintptr // Input.\n@@ -90,6 +131,21 @@ func (*mapVisitor) requiresSplit() bool { return true }\n//\n//go:nosplit\nfunc (p *PageTables) Map(addr usermem.Addr, length uintptr, opts MapOpts, physical uintptr) bool {\n+ if p.readOnlyShared {\n+ panic(\"Should not modify read-only shared pagetables.\")\n+ }\n+ if uintptr(addr)+length < uintptr(addr) {\n+ panic(\"addr & length overflow\")\n+ }\n+ if p.upperSharedPageTables != nil {\n+ // ignore change to the read-only upper shared portion.\n+ if uintptr(addr) >= p.upperStart {\n+ return false\n+ }\n+ if uintptr(addr)+length > p.upperStart {\n+ length = p.upperStart - uintptr(addr)\n+ }\n+ }\nif !opts.AccessType.Any() {\nreturn p.Unmap(addr, length)\n}\n@@ -128,12 +184,27 @@ func (v *unmapVisitor) visit(start uintptr, pte *PTE, align uintptr) {\n//\n// True is returned iff there was a previous mapping in the range.\n//\n-// Precondition: addr & length must be page-aligned.\n+// Precondition: addr & length must be page-aligned, their sum must not overflow.\n//\n// +checkescape:hard,stack\n//\n//go:nosplit\nfunc (p *PageTables) Unmap(addr usermem.Addr, length uintptr) bool {\n+ if p.readOnlyShared {\n+ panic(\"Should not modify read-only shared pagetables.\")\n+ }\n+ if uintptr(addr)+length < uintptr(addr) {\n+ panic(\"addr & length overflow\")\n+ }\n+ if p.upperSharedPageTables != nil {\n+ // ignore change to the read-only upper shared portion.\n+ if uintptr(addr) >= p.upperStart {\n+ return false\n+ }\n+ if uintptr(addr)+length > p.upperStart {\n+ length = p.upperStart - uintptr(addr)\n+ }\n+ }\nw := unmapWalker{\npageTables: p,\nvisitor: unmapVisitor{\n@@ -218,3 +289,10 @@ func (p *PageTables) Lookup(addr usermem.Addr) (physical uintptr, opts MapOpts)\nw.iterateRange(uintptr(addr), uintptr(addr)+1)\nreturn w.visitor.physical + offset, w.visitor.opts\n}\n+\n+// MarkReadOnlyShared marks the pagetables read-only and can be shared.\n+//\n+// It is usually used on the pagetables that are used as the upper\n+func (p *PageTables) MarkReadOnlyShared() {\n+ p.readOnlyShared = true\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/pagetables/pagetables_aarch64.go",
"new_path": "pkg/sentry/platform/ring0/pagetables/pagetables_aarch64.go",
"diff": "@@ -24,14 +24,6 @@ import (\n// archPageTables is architecture-specific data.\ntype archPageTables struct {\n- // root is the pagetable root for kernel space.\n- root *PTEs\n-\n- // rootPhysical is the cached physical address of the root.\n- //\n- // This is saved only to prevent constant translation.\n- rootPhysical uintptr\n-\nasid uint16\n}\n@@ -46,7 +38,7 @@ func (p *PageTables) TTBR0_EL1(noFlush bool, asid uint16) uint64 {\n//\n//go:nosplit\nfunc (p *PageTables) TTBR1_EL1(noFlush bool, asid uint16) uint64 {\n- return uint64(p.archPageTables.rootPhysical) | (uint64(asid)&ttbrASIDMask)<<ttbrASIDOffset\n+ return uint64(p.upperSharedPageTables.rootPhysical) | (uint64(asid)&ttbrASIDMask)<<ttbrASIDOffset\n}\n// Bits in page table entries.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/pagetables/pagetables_amd64.go",
"new_path": "pkg/sentry/platform/ring0/pagetables/pagetables_amd64.go",
"diff": "@@ -50,5 +50,26 @@ func (p *PageTables) Init(allocator Allocator) {\np.rootPhysical = p.Allocator.PhysicalFor(p.root)\n}\n+func pgdIndex(upperStart uintptr) uintptr {\n+ if upperStart&(pgdSize-1) != 0 {\n+ panic(\"upperStart should be pgd size aligned\")\n+ }\n+ if upperStart >= upperBottom {\n+ return entriesPerPage/2 + (upperStart-upperBottom)/pgdSize\n+ }\n+ if upperStart < lowerTop {\n+ return upperStart / pgdSize\n+ }\n+ panic(\"upperStart should be in canonical range\")\n+}\n+\n+// cloneUpperShared clone the upper from the upper shared page tables.\n+//\n+//go:nosplit\n+func (p *PageTables) cloneUpperShared() {\n+ start := pgdIndex(p.upperStart)\n+ copy(p.root[start:entriesPerPage], p.upperSharedPageTables.root[start:entriesPerPage])\n+}\n+\n// PTEs is a collection of entries.\ntype PTEs [entriesPerPage]PTE\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/pagetables/pagetables_arm64.go",
"new_path": "pkg/sentry/platform/ring0/pagetables/pagetables_arm64.go",
"diff": "@@ -49,8 +49,17 @@ func (p *PageTables) Init(allocator Allocator) {\np.Allocator = allocator\np.root = p.Allocator.NewPTEs()\np.rootPhysical = p.Allocator.PhysicalFor(p.root)\n- p.archPageTables.root = p.Allocator.NewPTEs()\n- p.archPageTables.rootPhysical = p.Allocator.PhysicalFor(p.archPageTables.root)\n+}\n+\n+// cloneUpperShared clone the upper from the upper shared page tables.\n+//\n+//go:nosplit\n+func (p *PageTables) cloneUpperShared() {\n+ if p.upperStart != upperBottom {\n+ panic(\"upperStart should be the same as upperBottom\")\n+ }\n+\n+ // nothing to do for arm.\n}\n// PTEs is a collection of entries.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/pagetables/walker_arm64.go",
"new_path": "pkg/sentry/platform/ring0/pagetables/walker_arm64.go",
"diff": "@@ -116,7 +116,7 @@ func next(start uintptr, size uintptr) uintptr {\nfunc (w *Walker) iterateRangeCanonical(start, end uintptr) {\npgdEntryIndex := w.pageTables.root\nif start >= upperBottom {\n- pgdEntryIndex = w.pageTables.archPageTables.root\n+ pgdEntryIndex = w.pageTables.upperSharedPageTables.root\n}\nfor pgdIndex := (uint16((start & pgdMask) >> pgdShift)); start < end && pgdIndex < entriesPerPage; pgdIndex++ {\n"
}
] | Go | Apache License 2.0 | google/gvisor | kvm: share upper halves among all pagtables
Fixes: #509
Signed-off-by: Lai Jiangshan <[email protected]>
Signed-off-by: Lai Jiangshan <[email protected]> |
259,853 | 02.11.2020 10:39:33 | 28,800 | 73f980e97e2df13db736271ae8e8c3bfb1c1e1aa | Block external network for tests
And in this case, tests will run in separate network namespaces
and will not affect each other. | [
{
"change_type": "MODIFY",
"old_path": "test/runner/defs.bzl",
"new_path": "test/runner/defs.bzl",
"diff": "@@ -97,10 +97,10 @@ def _syscall_test(\n# we figure out how to request ipv4 sockets on Guitar machines.\nif network == \"host\":\ntags.append(\"noguitar\")\n- tags.append(\"block-network\")\n# Disable off-host networking.\ntags.append(\"requires-net:loopback\")\n+ tags.append(\"block-network\")\n# gotsan makes sense only if tests are running in gVisor.\nif platform == \"native\":\n"
}
] | Go | Apache License 2.0 | google/gvisor | Block external network for tests
And in this case, tests will run in separate network namespaces
and will not affect each other.
PiperOrigin-RevId: 340267734 |
260,001 | 02.11.2020 11:15:09 | 28,800 | ed4f8573435763f08971374243934d3dcf65c06a | Pass hashing algorithms in verity fs opts | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/verity/filesystem.go",
"new_path": "pkg/sentry/fsimpl/verity/filesystem.go",
"diff": "@@ -276,9 +276,9 @@ func (fs *filesystem) verifyChild(ctx context.Context, parent *dentry, child *de\nUID: parentStat.UID,\nGID: parentStat.GID,\n//TODO(b/156980949): Support passing other hash algorithms.\n- HashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA256,\n+ HashAlgorithms: fs.alg.toLinuxHashAlg(),\nReadOffset: int64(offset),\n- ReadSize: int64(merkletree.DigestSize(linux.FS_VERITY_HASH_ALG_SHA256)),\n+ ReadSize: int64(merkletree.DigestSize(fs.alg.toLinuxHashAlg())),\nExpected: parent.hash,\nDataAndTreeInSameFile: true,\n}); err != nil && err != io.EOF {\n@@ -352,7 +352,7 @@ func (fs *filesystem) verifyStat(ctx context.Context, d *dentry, stat linux.Stat\nUID: stat.UID,\nGID: stat.GID,\n//TODO(b/156980949): Support passing other hash algorithms.\n- HashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA256,\n+ HashAlgorithms: fs.alg.toLinuxHashAlg(),\nReadOffset: 0,\n// Set read size to 0 so only the metadata is verified.\nReadSize: 0,\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/verity/verity.go",
"new_path": "pkg/sentry/fsimpl/verity/verity.go",
"diff": "@@ -79,6 +79,27 @@ var (\nverityMu sync.RWMutex\n)\n+// HashAlgorithm is a type specifying the algorithm used to hash the file\n+// content.\n+type HashAlgorithm int\n+\n+// Currently supported hashing algorithms include SHA256 and SHA512.\n+const (\n+ SHA256 HashAlgorithm = iota\n+ SHA512\n+)\n+\n+func (alg HashAlgorithm) toLinuxHashAlg() int {\n+ switch alg {\n+ case SHA256:\n+ return linux.FS_VERITY_HASH_ALG_SHA256\n+ case SHA512:\n+ return linux.FS_VERITY_HASH_ALG_SHA512\n+ default:\n+ return 0\n+ }\n+}\n+\n// FilesystemType implements vfs.FilesystemType.\n//\n// +stateify savable\n@@ -108,6 +129,10 @@ type filesystem struct {\n// stores the root hash of the whole file system in bytes.\nrootDentry *dentry\n+ // alg is the algorithms used to hash the files in the verity file\n+ // system.\n+ alg HashAlgorithm\n+\n// renameMu synchronizes renaming with non-renaming operations in order\n// to ensure consistent lock ordering between dentry.dirMu in different\n// dentries.\n@@ -136,6 +161,10 @@ type InternalFilesystemOptions struct {\n// LowerName is the name of the filesystem wrapped by verity fs.\nLowerName string\n+ // Alg is the algorithms used to hash the files in the verity file\n+ // system.\n+ Alg HashAlgorithm\n+\n// RootHash is the root hash of the overall verity file system.\nRootHash []byte\n@@ -194,6 +223,7 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nfs := &filesystem{\ncreds: creds.Fork(),\n+ alg: iopts.Alg,\nlowerMount: mnt,\nallowRuntimeEnable: iopts.AllowRuntimeEnable,\n}\n@@ -627,7 +657,7 @@ func (fd *fileDescription) generateMerkle(ctx context.Context) ([]byte, uint64,\nTreeReader: &merkleReader,\nTreeWriter: &merkleWriter,\n//TODO(b/156980949): Support passing other hash algorithms.\n- HashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA256,\n+ HashAlgorithms: fd.d.fs.alg.toLinuxHashAlg(),\n}\nswitch atomic.LoadUint32(&fd.d.mode) & linux.S_IFMT {\n@@ -873,7 +903,7 @@ func (fd *fileDescription) PRead(ctx context.Context, dst usermem.IOSequence, of\nUID: fd.d.uid,\nGID: fd.d.gid,\n//TODO(b/156980949): Support passing other hash algorithms.\n- HashAlgorithms: linux.FS_VERITY_HASH_ALG_SHA256,\n+ HashAlgorithms: fd.d.fs.alg.toLinuxHashAlg(),\nReadOffset: offset,\nReadSize: dst.NumBytes(),\nExpected: fd.d.hash,\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/verity/verity_test.go",
"new_path": "pkg/sentry/fsimpl/verity/verity_test.go",
"diff": "@@ -43,7 +43,7 @@ const maxDataSize = 100000\n// newVerityRoot creates a new verity mount, and returns the root. The\n// underlying file system is tmpfs. If the error is not nil, then cleanup\n// should be called when the root is no longer needed.\n-func newVerityRoot(t *testing.T) (*vfs.VirtualFilesystem, vfs.VirtualDentry, *kernel.Task, error) {\n+func newVerityRoot(t *testing.T, hashAlg HashAlgorithm) (*vfs.VirtualFilesystem, vfs.VirtualDentry, *kernel.Task, error) {\nk, err := testutil.Boot()\nif err != nil {\nt.Fatalf(\"testutil.Boot: %v\", err)\n@@ -70,6 +70,7 @@ func newVerityRoot(t *testing.T) (*vfs.VirtualFilesystem, vfs.VirtualDentry, *ke\nInternalData: InternalFilesystemOptions{\nRootMerkleFileName: rootMerkleFilename,\nLowerName: \"tmpfs\",\n+ Alg: hashAlg,\nAllowRuntimeEnable: true,\nNoCrashOnVerificationFailure: true,\n},\n@@ -161,10 +162,13 @@ func corruptRandomBit(ctx context.Context, fd *vfs.FileDescription, size int) er\nreturn nil\n}\n+var hashAlgs = []HashAlgorithm{SHA256, SHA512}\n+\n// TestOpen ensures that when a file is created, the corresponding Merkle tree\n// file and the root Merkle tree file exist.\nfunc TestOpen(t *testing.T) {\n- vfsObj, root, ctx, err := newVerityRoot(t)\n+ for _, alg := range hashAlgs {\n+ vfsObj, root, ctx, err := newVerityRoot(t, alg)\nif err != nil {\nt.Fatalf(\"newVerityRoot: %v\", err)\n}\n@@ -197,11 +201,13 @@ func TestOpen(t *testing.T) {\nt.Errorf(\"OpenAt root Merkle tree file %s: %v\", merklePrefix+rootMerkleFilename, err)\n}\n}\n+}\n// TestPReadUnmodifiedFileSucceeds ensures that pread from an untouched verity\n// file succeeds after enabling verity for it.\nfunc TestPReadUnmodifiedFileSucceeds(t *testing.T) {\n- vfsObj, root, ctx, err := newVerityRoot(t)\n+ for _, alg := range hashAlgs {\n+ vfsObj, root, ctx, err := newVerityRoot(t, alg)\nif err != nil {\nt.Fatalf(\"newVerityRoot: %v\", err)\n}\n@@ -229,11 +235,13 @@ func TestPReadUnmodifiedFileSucceeds(t *testing.T) {\nt.Errorf(\"fd.PRead got read length %d, want %d\", n, size)\n}\n}\n+}\n// TestReadUnmodifiedFileSucceeds ensures that read from an untouched verity\n// file succeeds after enabling verity for it.\nfunc TestReadUnmodifiedFileSucceeds(t *testing.T) {\n- vfsObj, root, ctx, err := newVerityRoot(t)\n+ for _, alg := range hashAlgs {\n+ vfsObj, root, ctx, err := newVerityRoot(t, alg)\nif err != nil {\nt.Fatalf(\"newVerityRoot: %v\", err)\n}\n@@ -261,11 +269,13 @@ func TestReadUnmodifiedFileSucceeds(t *testing.T) {\nt.Errorf(\"fd.PRead got read length %d, want %d\", n, size)\n}\n}\n+}\n// TestReopenUnmodifiedFileSucceeds ensures that reopen an untouched verity file\n// succeeds after enabling verity for it.\nfunc TestReopenUnmodifiedFileSucceeds(t *testing.T) {\n- vfsObj, root, ctx, err := newVerityRoot(t)\n+ for _, alg := range hashAlgs {\n+ vfsObj, root, ctx, err := newVerityRoot(t, alg)\nif err != nil {\nt.Fatalf(\"newVerityRoot: %v\", err)\n}\n@@ -295,11 +305,13 @@ func TestReopenUnmodifiedFileSucceeds(t *testing.T) {\nt.Errorf(\"reopen enabled file failed: %v\", err)\n}\n}\n+}\n// TestPReadModifiedFileFails ensures that read from a modified verity file\n// fails.\nfunc TestPReadModifiedFileFails(t *testing.T) {\n- vfsObj, root, ctx, err := newVerityRoot(t)\n+ for _, alg := range hashAlgs {\n+ vfsObj, root, ctx, err := newVerityRoot(t, alg)\nif err != nil {\nt.Fatalf(\"newVerityRoot: %v\", err)\n}\n@@ -340,11 +352,13 @@ func TestPReadModifiedFileFails(t *testing.T) {\nt.Fatalf(\"fd.PRead succeeded, expected failure\")\n}\n}\n+}\n// TestReadModifiedFileFails ensures that read from a modified verity file\n// fails.\nfunc TestReadModifiedFileFails(t *testing.T) {\n- vfsObj, root, ctx, err := newVerityRoot(t)\n+ for _, alg := range hashAlgs {\n+ vfsObj, root, ctx, err := newVerityRoot(t, alg)\nif err != nil {\nt.Fatalf(\"newVerityRoot: %v\", err)\n}\n@@ -385,11 +399,13 @@ func TestReadModifiedFileFails(t *testing.T) {\nt.Fatalf(\"fd.Read succeeded, expected failure\")\n}\n}\n+}\n// TestModifiedMerkleFails ensures that read from a verity file fails if the\n// corresponding Merkle tree file is modified.\nfunc TestModifiedMerkleFails(t *testing.T) {\n- vfsObj, root, ctx, err := newVerityRoot(t)\n+ for _, alg := range hashAlgs {\n+ vfsObj, root, ctx, err := newVerityRoot(t, alg)\nif err != nil {\nt.Fatalf(\"newVerityRoot: %v\", err)\n}\n@@ -437,12 +453,14 @@ func TestModifiedMerkleFails(t *testing.T) {\nt.Fatalf(\"fd.PRead succeeded with modified Merkle file\")\n}\n}\n+}\n// TestModifiedParentMerkleFails ensures that open a verity enabled file in a\n// verity enabled directory fails if the hashes related to the target file in\n// the parent Merkle tree file is modified.\nfunc TestModifiedParentMerkleFails(t *testing.T) {\n- vfsObj, root, ctx, err := newVerityRoot(t)\n+ for _, alg := range hashAlgs {\n+ vfsObj, root, ctx, err := newVerityRoot(t, alg)\nif err != nil {\nt.Fatalf(\"newVerityRoot: %v\", err)\n}\n@@ -515,11 +533,13 @@ func TestModifiedParentMerkleFails(t *testing.T) {\nt.Errorf(\"OpenAt file with modified parent Merkle succeeded\")\n}\n}\n+}\n// TestUnmodifiedStatSucceeds ensures that stat of an untouched verity file\n// succeeds after enabling verity for it.\nfunc TestUnmodifiedStatSucceeds(t *testing.T) {\n- vfsObj, root, ctx, err := newVerityRoot(t)\n+ for _, alg := range hashAlgs {\n+ vfsObj, root, ctx, err := newVerityRoot(t, alg)\nif err != nil {\nt.Fatalf(\"newVerityRoot: %v\", err)\n}\n@@ -541,11 +561,13 @@ func TestUnmodifiedStatSucceeds(t *testing.T) {\nt.Errorf(\"fd.Stat: %v\", err)\n}\n}\n+}\n// TestModifiedStatFails checks that getting stat for a file with modified stat\n// should fail.\nfunc TestModifiedStatFails(t *testing.T) {\n- vfsObj, root, ctx, err := newVerityRoot(t)\n+ for _, alg := range hashAlgs {\n+ vfsObj, root, ctx, err := newVerityRoot(t, alg)\nif err != nil {\nt.Fatalf(\"newVerityRoot: %v\", err)\n}\n@@ -578,6 +600,7 @@ func TestModifiedStatFails(t *testing.T) {\nt.Errorf(\"fd.Stat succeeded when it should fail\")\n}\n}\n+}\n// TestOpenDeletedOrRenamedFileFails ensures that opening a deleted/renamed\n// verity enabled file or the corresponding Merkle tree file fails with the\n@@ -616,7 +639,8 @@ func TestOpenDeletedFileFails(t *testing.T) {\n}\nfor _, tc := range testCases {\nt.Run(fmt.Sprintf(\"remove:%t\", tc.remove), func(t *testing.T) {\n- vfsObj, root, ctx, err := newVerityRoot(t)\n+ for _, alg := range hashAlgs {\n+ vfsObj, root, ctx, err := newVerityRoot(t, alg)\nif err != nil {\nt.Fatalf(\"newVerityRoot: %v\", err)\n}\n@@ -695,6 +719,7 @@ func TestOpenDeletedFileFails(t *testing.T) {\n}); err != syserror.EIO {\nt.Errorf(\"got OpenAt error: %v, expected EIO\", err)\n}\n+ }\n})\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Pass hashing algorithms in verity fs opts
PiperOrigin-RevId: 340275942 |
259,853 | 02.11.2020 14:40:24 | 28,800 | 9efaf675187a2f22bb24492eb5b040e2ff8196a9 | Clean up the code of setupTimeWaitClose
The active_closefd has to be shutdown only for write,
otherwise the second poll will always return immediately.
The second poll should not be called from a separate thread. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_inet_loopback.cc",
"new_path": "test/syscalls/linux/socket_inet_loopback.cc",
"diff": "@@ -940,7 +940,7 @@ void setupTimeWaitClose(const TestAddress* listener,\n}\n// shutdown to trigger TIME_WAIT.\n- ASSERT_THAT(shutdown(active_closefd.get(), SHUT_RDWR), SyscallSucceeds());\n+ ASSERT_THAT(shutdown(active_closefd.get(), SHUT_WR), SyscallSucceeds());\n{\nconst int kTimeout = 10000;\nstruct pollfd pfd = {\n@@ -950,7 +950,8 @@ void setupTimeWaitClose(const TestAddress* listener,\nASSERT_THAT(poll(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1));\nASSERT_EQ(pfd.revents, POLLIN);\n}\n- ScopedThread t([&]() {\n+ ASSERT_THAT(shutdown(passive_closefd.get(), SHUT_WR), SyscallSucceeds());\n+ {\nconstexpr int kTimeout = 10000;\nconstexpr int16_t want_events = POLLHUP;\nstruct pollfd pfd = {\n@@ -958,11 +959,8 @@ void setupTimeWaitClose(const TestAddress* listener,\n.events = want_events,\n};\nASSERT_THAT(poll(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1));\n- });\n+ }\n- passive_closefd.reset();\n- t.Join();\n- active_closefd.reset();\n// This sleep is needed to reduce flake to ensure that the passive-close\n// ensures the state transitions to CLOSE from LAST_ACK.\nabsl::SleepFor(absl::Seconds(1));\n"
}
] | Go | Apache License 2.0 | google/gvisor | Clean up the code of setupTimeWaitClose
The active_closefd has to be shutdown only for write,
otherwise the second poll will always return immediately.
The second poll should not be called from a separate thread.
PiperOrigin-RevId: 340319071 |
259,860 | 02.11.2020 19:13:16 | 28,800 | 51b062f6cdfb59ef82d0a6fa2ca79cb00dd953d2 | Skip log.Sprintfs when leak check logging is not enabled. | [
{
"change_type": "MODIFY",
"old_path": "pkg/refsvfs2/refs_map.go",
"new_path": "pkg/refsvfs2/refs_map.go",
"diff": "@@ -62,9 +62,11 @@ func Register(obj CheckedObject) {\n}\nliveObjects[obj] = struct{}{}\nliveObjectsMu.Unlock()\n+ if leakCheckEnabled() && obj.LogRefs() {\nlogEvent(obj, \"registered\")\n}\n}\n+}\n// Unregister removes obj from the live object map.\nfunc Unregister(obj CheckedObject) {\n@@ -75,32 +77,41 @@ func Unregister(obj CheckedObject) {\npanic(fmt.Sprintf(\"Expected to find entry in leak checking map for reference %p\", obj))\n}\ndelete(liveObjects, obj)\n+ if leakCheckEnabled() && obj.LogRefs() {\nlogEvent(obj, \"unregistered\")\n}\n}\n+}\n// LogIncRef logs a reference increment.\nfunc LogIncRef(obj CheckedObject, refs int64) {\n+ if leakCheckEnabled() && obj.LogRefs() {\nlogEvent(obj, fmt.Sprintf(\"IncRef to %d\", refs))\n}\n+}\n// LogTryIncRef logs a successful TryIncRef call.\nfunc LogTryIncRef(obj CheckedObject, refs int64) {\n+ if leakCheckEnabled() && obj.LogRefs() {\nlogEvent(obj, fmt.Sprintf(\"TryIncRef to %d\", refs))\n}\n+}\n// LogDecRef logs a reference decrement.\nfunc LogDecRef(obj CheckedObject, refs int64) {\n+ if leakCheckEnabled() && obj.LogRefs() {\nlogEvent(obj, fmt.Sprintf(\"DecRef to %d\", refs))\n}\n+}\n// logEvent logs a message for the given reference-counted object.\n+//\n+// obj.LogRefs() should be checked before calling logEvent, in order to avoid\n+// calling any text processing needed to evaluate msg.\nfunc logEvent(obj CheckedObject, msg string) {\n- if obj.LogRefs() {\nlog.Infof(\"[%s %p] %s:\", obj.RefType(), obj, msg)\nlog.Infof(refs_vfs1.FormatStack(refs_vfs1.RecordStack()))\n}\n-}\n// DoLeakCheck iterates through the live object map and logs a message for each\n// object. It is called once no reference-counted objects should be reachable\n"
}
] | Go | Apache License 2.0 | google/gvisor | Skip log.Sprintfs when leak check logging is not enabled.
PiperOrigin-RevId: 340361998 |
259,860 | 02.11.2020 22:30:23 | 28,800 | 1321f837bd9f082e3c1b0a37831453b3637202c3 | [vfs2] Refactor kernfs checkCreateLocked.
Don't return the filename, since it can already be determined by the caller.
This was causing a panic in RenameAt, which relied on the name to be nonempty
even if the error was EEXIST.
Reported-by: | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go",
"diff": "@@ -207,24 +207,23 @@ func (fs *Filesystem) walkParentDirLocked(ctx context.Context, rp *vfs.Resolving\n// Preconditions:\n// * Filesystem.mu must be locked for at least reading.\n// * isDir(parentInode) == true.\n-func checkCreateLocked(ctx context.Context, rp *vfs.ResolvingPath, parent *Dentry) (string, error) {\n- if err := parent.inode.CheckPermissions(ctx, rp.Credentials(), vfs.MayWrite|vfs.MayExec); err != nil {\n- return \"\", err\n+func checkCreateLocked(ctx context.Context, creds *auth.Credentials, name string, parent *Dentry) error {\n+ if err := parent.inode.CheckPermissions(ctx, creds, vfs.MayWrite|vfs.MayExec); err != nil {\n+ return err\n}\n- pc := rp.Component()\n- if pc == \".\" || pc == \"..\" {\n- return \"\", syserror.EEXIST\n+ if name == \".\" || name == \"..\" {\n+ return syserror.EEXIST\n}\n- if len(pc) > linux.NAME_MAX {\n- return \"\", syserror.ENAMETOOLONG\n+ if len(name) > linux.NAME_MAX {\n+ return syserror.ENAMETOOLONG\n}\n- if _, ok := parent.children[pc]; ok {\n- return \"\", syserror.EEXIST\n+ if _, ok := parent.children[name]; ok {\n+ return syserror.EEXIST\n}\nif parent.VFSDentry().IsDead() {\n- return \"\", syserror.ENOENT\n+ return syserror.ENOENT\n}\n- return pc, nil\n+ return nil\n}\n// checkDeleteLocked checks that the file represented by vfsd may be deleted.\n@@ -352,8 +351,8 @@ func (fs *Filesystem) LinkAt(ctx context.Context, rp *vfs.ResolvingPath, vd vfs.\nparent.dirMu.Lock()\ndefer parent.dirMu.Unlock()\n- pc, err := checkCreateLocked(ctx, rp, parent)\n- if err != nil {\n+ pc := rp.Component()\n+ if err := checkCreateLocked(ctx, rp.Credentials(), pc, parent); err != nil {\nreturn err\n}\nif rp.Mount() != vd.Mount() {\n@@ -394,8 +393,8 @@ func (fs *Filesystem) MkdirAt(ctx context.Context, rp *vfs.ResolvingPath, opts v\nparent.dirMu.Lock()\ndefer parent.dirMu.Unlock()\n- pc, err := checkCreateLocked(ctx, rp, parent)\n- if err != nil {\n+ pc := rp.Component()\n+ if err := checkCreateLocked(ctx, rp.Credentials(), pc, parent); err != nil {\nreturn err\n}\nif err := rp.Mount().CheckBeginWrite(); err != nil {\n@@ -430,8 +429,8 @@ func (fs *Filesystem) MknodAt(ctx context.Context, rp *vfs.ResolvingPath, opts v\nparent.dirMu.Lock()\ndefer parent.dirMu.Unlock()\n- pc, err := checkCreateLocked(ctx, rp, parent)\n- if err != nil {\n+ pc := rp.Component()\n+ if err := checkCreateLocked(ctx, rp.Credentials(), pc, parent); err != nil {\nreturn err\n}\nif err := rp.Mount().CheckBeginWrite(); err != nil {\n@@ -657,8 +656,8 @@ func (fs *Filesystem) RenameAt(ctx context.Context, rp *vfs.ResolvingPath, oldPa\n// Can we create the dst dentry?\nvar dst *Dentry\n- pc, err := checkCreateLocked(ctx, rp, dstDir)\n- switch err {\n+ pc := rp.Component()\n+ switch err := checkCreateLocked(ctx, rp.Credentials(), pc, dstDir); err {\ncase nil:\n// Ok, continue with rename as replacement.\ncase syserror.EEXIST:\n@@ -822,8 +821,8 @@ func (fs *Filesystem) SymlinkAt(ctx context.Context, rp *vfs.ResolvingPath, targ\nparent.dirMu.Lock()\ndefer parent.dirMu.Unlock()\n- pc, err := checkCreateLocked(ctx, rp, parent)\n- if err != nil {\n+ pc := rp.Component()\n+ if err := checkCreateLocked(ctx, rp.Credentials(), pc, parent); err != nil {\nreturn err\n}\nif err := rp.Mount().CheckBeginWrite(); err != nil {\n"
}
] | Go | Apache License 2.0 | google/gvisor | [vfs2] Refactor kernfs checkCreateLocked.
Don't return the filename, since it can already be determined by the caller.
This was causing a panic in RenameAt, which relied on the name to be nonempty
even if the error was EEXIST.
Reported-by: [email protected]
PiperOrigin-RevId: 340381946 |
259,875 | 02.11.2020 23:56:29 | 28,800 | 1a3f417f4a329339d89fcf89262bd08c18c1f27e | Implement command GETZCNT for semctl. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/semaphore/semaphore.go",
"new_path": "pkg/sentry/kernel/semaphore/semaphore.go",
"diff": "@@ -423,6 +423,29 @@ func (s *Set) GetPID(num int32, creds *auth.Credentials) (int32, error) {\nreturn sem.pid, nil\n}\n+// GetZeroWaiters returns number of waiters waiting for the sem to go to zero.\n+func (s *Set) GetZeroWaiters(num int32, creds *auth.Credentials) (uint16, error) {\n+ s.mu.Lock()\n+ defer s.mu.Unlock()\n+\n+ // The calling process must have read permission on the semaphore set.\n+ if !s.checkPerms(creds, fs.PermMask{Read: true}) {\n+ return 0, syserror.EACCES\n+ }\n+\n+ sem := s.findSem(num)\n+ if sem == nil {\n+ return 0, syserror.ERANGE\n+ }\n+ var semzcnt uint16\n+ for w := sem.waiters.Front(); w != nil; w = w.Next() {\n+ if w.value == 0 {\n+ semzcnt++\n+ }\n+ }\n+ return semzcnt, nil\n+}\n+\n// ExecuteOps attempts to execute a list of operations to the set. It only\n// succeeds when all operations can be applied. No changes are made if it fails.\n//\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/linux64.go",
"new_path": "pkg/sentry/syscalls/linux/linux64.go",
"diff": "@@ -118,7 +118,7 @@ var AMD64 = &kernel.SyscallTable{\n63: syscalls.Supported(\"uname\", Uname),\n64: syscalls.Supported(\"semget\", Semget),\n65: syscalls.PartiallySupported(\"semop\", Semop, \"Option SEM_UNDO not supported.\", nil),\n- 66: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options IPC_INFO, SEM_INFO, SEM_STAT, SEM_STAT_ANY, GETNCNT, GETZCNT not supported.\", nil),\n+ 66: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options IPC_INFO, SEM_INFO, SEM_STAT, SEM_STAT_ANY, GETNCNT not supported.\", nil),\n67: syscalls.Supported(\"shmdt\", Shmdt),\n68: syscalls.ErrorWithEvent(\"msgget\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n69: syscalls.ErrorWithEvent(\"msgsnd\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n@@ -619,7 +619,7 @@ var ARM64 = &kernel.SyscallTable{\n188: syscalls.ErrorWithEvent(\"msgrcv\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n189: syscalls.ErrorWithEvent(\"msgsnd\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n190: syscalls.Supported(\"semget\", Semget),\n- 191: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options IPC_INFO, SEM_INFO, SEM_STAT, SEM_STAT_ANY, GETNCNT, GETZCNT not supported.\", nil),\n+ 191: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options IPC_INFO, SEM_INFO, SEM_STAT, SEM_STAT_ANY, GETNCNT not supported.\", nil),\n192: syscalls.ErrorWithEvent(\"semtimedop\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/137\"}),\n193: syscalls.PartiallySupported(\"semop\", Semop, \"Option SEM_UNDO not supported.\", nil),\n194: syscalls.PartiallySupported(\"shmget\", Shmget, \"Option SHM_HUGETLB is not supported.\", nil),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_sem.go",
"new_path": "pkg/sentry/syscalls/linux/sys_sem.go",
"diff": "@@ -138,12 +138,15 @@ func Semctl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\nreturn 0, nil, err\n+ case linux.GETZCNT:\n+ v, err := getSemzcnt(t, id, num)\n+ return uintptr(v), nil, err\n+\ncase linux.IPC_INFO,\nlinux.SEM_INFO,\nlinux.SEM_STAT,\nlinux.SEM_STAT_ANY,\n- linux.GETNCNT,\n- linux.GETZCNT:\n+ linux.GETNCNT:\nt.Kernel().EmitUnimplementedEvent(t)\nfallthrough\n@@ -258,3 +261,13 @@ func getPID(t *kernel.Task, id int32, num int32) (int32, error) {\n}\nreturn int32(tg.ID()), nil\n}\n+\n+func getSemzcnt(t *kernel.Task, id int32, num int32) (uint16, error) {\n+ r := t.IPCNamespace().SemaphoreRegistry()\n+ set := r.FindByID(id)\n+ if set == nil {\n+ return 0, syserror.EINVAL\n+ }\n+ creds := auth.CredentialsFromContext(t)\n+ return set.GetZeroWaiters(num, creds)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/semaphore.cc",
"new_path": "test/syscalls/linux/semaphore.cc",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n+#include <signal.h>\n#include <sys/ipc.h>\n#include <sys/sem.h>\n#include <sys/types.h>\n@@ -542,6 +543,120 @@ TEST(SemaphoreTest, SemCtlIpcStat) {\nSyscallFailsWithErrno(EACCES));\n}\n+// The funcion keeps calling semctl's GETZCNT command until\n+// the return value is not less than target.\n+int WaitSemzcnt(int semid, int target) {\n+ constexpr absl::Duration timeout = absl::Seconds(10);\n+ int semcnt = 0;\n+ for (auto start = absl::Now(); absl::Now() - start < timeout;) {\n+ semcnt = semctl(semid, 0, GETZCNT);\n+ if (semcnt >= target) {\n+ break;\n+ }\n+ absl::SleepFor(absl::Milliseconds(10));\n+ }\n+ return semcnt;\n+}\n+\n+TEST(SemaphoreTest, SemopGetzcnt) {\n+ // Drop CAP_IPC_OWNER which allows us to bypass semaphore permissions.\n+ ASSERT_NO_ERRNO(SetCapability(CAP_IPC_OWNER, false));\n+ // Create a write only semaphore set.\n+ AutoSem sem(semget(IPC_PRIVATE, 1, 0200 | IPC_CREAT));\n+ ASSERT_THAT(sem.get(), SyscallSucceeds());\n+\n+ // No read permission to retrieve semzcnt.\n+ EXPECT_THAT(semctl(sem.get(), 0, GETZCNT), SyscallFailsWithErrno(EACCES));\n+\n+ // Remove the calling thread's read permission.\n+ struct semid_ds ds = {};\n+ ds.sem_perm.uid = getuid();\n+ ds.sem_perm.gid = getgid();\n+ ds.sem_perm.mode = 0600;\n+ ASSERT_THAT(semctl(sem.get(), 0, IPC_SET, &ds), SyscallSucceeds());\n+\n+ std::vector<pid_t> children;\n+ ASSERT_THAT(semctl(sem.get(), 0, SETVAL, 1), SyscallSucceeds());\n+\n+ struct sembuf buf = {};\n+ buf.sem_num = 0;\n+ buf.sem_op = 0;\n+ constexpr size_t kLoops = 10;\n+ for (auto i = 0; i < kLoops; i++) {\n+ auto child_pid = fork();\n+ if (child_pid == 0) {\n+ ASSERT_THAT(RetryEINTR(semop)(sem.get(), &buf, 1), SyscallSucceeds());\n+ _exit(0);\n+ }\n+ children.push_back(child_pid);\n+ }\n+ EXPECT_THAT(WaitSemzcnt(sem.get(), kLoops), SyscallSucceedsWithValue(kLoops));\n+ // Set semval to 0, which wakes up children that sleep on the semop.\n+ ASSERT_THAT(semctl(sem.get(), 0, SETVAL, 0), SyscallSucceeds());\n+ for (const auto& child_pid : children) {\n+ int status;\n+ ASSERT_THAT(RetryEINTR(waitpid)(child_pid, &status, 0),\n+ SyscallSucceedsWithValue(child_pid));\n+ EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0);\n+ }\n+ EXPECT_EQ(semctl(sem.get(), 0, GETZCNT), 0);\n+}\n+\n+TEST(SemaphoreTest, SemopGetzcntOnSetRemoval) {\n+ auto semid = semget(IPC_PRIVATE, 1, 0600 | IPC_CREAT);\n+ ASSERT_THAT(semid, SyscallSucceeds());\n+ ASSERT_THAT(semctl(semid, 0, SETVAL, 1), SyscallSucceeds());\n+ ASSERT_EQ(semctl(semid, 0, GETZCNT), 0);\n+\n+ auto child_pid = fork();\n+ if (child_pid == 0) {\n+ struct sembuf buf = {};\n+ buf.sem_num = 0;\n+ buf.sem_op = 0;\n+\n+ ASSERT_THAT(RetryEINTR(semop)(semid, &buf, 1), SyscallFails());\n+ // Ensure that wait will only unblock when the semaphore is removed. On\n+ // EINTR retry it may race with deletion and return EINVAL.\n+ ASSERT_TRUE(errno == EIDRM || errno == EINVAL) << \"errno=\" << errno;\n+ _exit(0);\n+ }\n+\n+ EXPECT_THAT(WaitSemzcnt(semid, 1), SyscallSucceedsWithValue(1));\n+ // Remove the semaphore set, which fails the sleep semop.\n+ ASSERT_THAT(semctl(semid, 0, IPC_RMID), SyscallSucceeds());\n+ int status;\n+ ASSERT_THAT(RetryEINTR(waitpid)(child_pid, &status, 0),\n+ SyscallSucceedsWithValue(child_pid));\n+ EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0);\n+ EXPECT_THAT(semctl(semid, 0, GETZCNT), SyscallFailsWithErrno(EINVAL));\n+}\n+\n+TEST(SemaphoreTest, SemopGetzcntOnSignal) {\n+ AutoSem sem(semget(IPC_PRIVATE, 1, 0600 | IPC_CREAT));\n+ ASSERT_THAT(sem.get(), SyscallSucceeds());\n+ ASSERT_THAT(semctl(sem.get(), 0, SETVAL, 1), SyscallSucceeds());\n+ ASSERT_EQ(semctl(sem.get(), 0, GETZCNT), 0);\n+\n+ auto child_pid = fork();\n+ if (child_pid == 0) {\n+ signal(SIGHUP, [](int sig) -> void {});\n+ struct sembuf buf = {};\n+ buf.sem_num = 0;\n+ buf.sem_op = 0;\n+\n+ ASSERT_THAT(semop(sem.get(), &buf, 1), SyscallFailsWithErrno(EINTR));\n+ _exit(0);\n+ }\n+ EXPECT_THAT(WaitSemzcnt(sem.get(), 1), SyscallSucceedsWithValue(1));\n+ // Send a signal to the child, which fails the sleep semop.\n+ ASSERT_EQ(kill(child_pid, SIGHUP), 0);\n+ int status;\n+ ASSERT_THAT(RetryEINTR(waitpid)(child_pid, &status, 0),\n+ SyscallSucceedsWithValue(child_pid));\n+ EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0);\n+ EXPECT_EQ(semctl(sem.get(), 0, GETZCNT), 0);\n+}\n+\n} // namespace\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement command GETZCNT for semctl.
PiperOrigin-RevId: 340389884 |
259,914 | 03.11.2020 09:32:22 | 28,800 | 0e96f8065e7dc24aa5bc0a8cb14380c58ed6af13 | arm64 kvm: inject sError to trigger sigbus
Use an sErr injection to trigger sigbus when we receive EFAULT from the
run ioctl.
After applying this patch, mmap_test_runsc_kvm will be passed on
Arm64.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/gvisor/pull/4542 from lubinszARM:pr_kvm_mmap_1 | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/bluepill_amd64_unsafe.go",
"new_path": "pkg/sentry/platform/kvm/bluepill_amd64_unsafe.go",
"diff": "@@ -79,6 +79,18 @@ func bluepillStopGuest(c *vCPU) {\nc.runData.requestInterruptWindow = 0\n}\n+// bluepillSigBus is reponsible for injecting NMI to trigger sigbus.\n+//\n+//go:nosplit\n+func bluepillSigBus(c *vCPU) {\n+ if _, _, errno := syscall.RawSyscall( // escapes: no.\n+ syscall.SYS_IOCTL,\n+ uintptr(c.fd),\n+ _KVM_NMI, 0); errno != 0 {\n+ throw(\"NMI injection failed\")\n+ }\n+}\n+\n// bluepillReadyStopGuest checks whether the current vCPU is ready for interrupt injection.\n//\n//go:nosplit\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/bluepill_arm64.go",
"new_path": "pkg/sentry/platform/kvm/bluepill_arm64.go",
"diff": "@@ -27,15 +27,20 @@ var (\n// The action for bluepillSignal is changed by sigaction().\nbluepillSignal = syscall.SIGILL\n- // vcpuSErr is the event of system error.\n- vcpuSErr = kvmVcpuEvents{\n+ // vcpuSErrBounce is the event of system error for bouncing KVM.\n+ vcpuSErrBounce = kvmVcpuEvents{\nexception: exception{\nsErrPending: 1,\n- sErrHasEsr: 0,\n- pad: [6]uint8{0, 0, 0, 0, 0, 0},\n- sErrEsr: 1,\n},\n- rsvd: [12]uint32{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n+ }\n+\n+ // vcpuSErrNMI is the event of system error to trigger sigbus.\n+ vcpuSErrNMI = kvmVcpuEvents{\n+ exception: exception{\n+ sErrPending: 1,\n+ sErrHasEsr: 1,\n+ sErrEsr: _ESR_ELx_SERR_NMI,\n+ },\n}\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/bluepill_arm64_unsafe.go",
"new_path": "pkg/sentry/platform/kvm/bluepill_arm64_unsafe.go",
"diff": "@@ -80,11 +80,24 @@ func getHypercallID(addr uintptr) int {\n//\n//go:nosplit\nfunc bluepillStopGuest(c *vCPU) {\n- if _, _, errno := syscall.RawSyscall(\n+ if _, _, errno := syscall.RawSyscall( // escapes: no.\nsyscall.SYS_IOCTL,\nuintptr(c.fd),\n_KVM_SET_VCPU_EVENTS,\n- uintptr(unsafe.Pointer(&vcpuSErr))); errno != 0 {\n+ uintptr(unsafe.Pointer(&vcpuSErrBounce))); errno != 0 {\n+ throw(\"sErr injection failed\")\n+ }\n+}\n+\n+// bluepillSigBus is reponsible for injecting sError to trigger sigbus.\n+//\n+//go:nosplit\n+func bluepillSigBus(c *vCPU) {\n+ if _, _, errno := syscall.RawSyscall( // escapes: no.\n+ syscall.SYS_IOCTL,\n+ uintptr(c.fd),\n+ _KVM_SET_VCPU_EVENTS,\n+ uintptr(unsafe.Pointer(&vcpuSErrNMI))); errno != 0 {\nthrow(\"sErr injection failed\")\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/bluepill_unsafe.go",
"new_path": "pkg/sentry/platform/kvm/bluepill_unsafe.go",
"diff": "@@ -146,12 +146,7 @@ func bluepillHandler(context unsafe.Pointer) {\n// MMIO exit we receive EFAULT from the run ioctl. We\n// always inject an NMI here since we may be in kernel\n// mode and have interrupts disabled.\n- if _, _, errno := syscall.RawSyscall( // escapes: no.\n- syscall.SYS_IOCTL,\n- uintptr(c.fd),\n- _KVM_NMI, 0); errno != 0 {\n- throw(\"NMI injection failed\")\n- }\n+ bluepillSigBus(c)\ncontinue // Rerun vCPU.\ndefault:\nthrow(\"run failed\")\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/kvm_const_arm64.go",
"new_path": "pkg/sentry/platform/kvm/kvm_const_arm64.go",
"diff": "@@ -151,6 +151,9 @@ const (\n_ESR_SEGV_PEMERR_L1 = 0xd\n_ESR_SEGV_PEMERR_L2 = 0xe\n_ESR_SEGV_PEMERR_L3 = 0xf\n+\n+ // Custom ISS field definitions for system error.\n+ _ESR_ELx_SERR_NMI = 0x1\n)\n// Arm64: MMIO base address used to dispatch hypercalls.\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": "@@ -257,11 +257,13 @@ func (c *vCPU) SwitchToUser(switchOpts ring0.SwitchOpts, info *arch.SignalInfo)\ncase ring0.PageFault:\nreturn c.fault(int32(syscall.SIGSEGV), info)\n+ case ring0.El0ErrNMI:\n+ return c.fault(int32(syscall.SIGBUS), info)\ncase ring0.Vector(bounce): // ring0.VirtualizationException\nreturn usermem.NoAccess, platform.ErrContextInterrupt\n- case ring0.El0Sync_undef:\n+ case ring0.El0SyncUndef:\nreturn c.fault(int32(syscall.SIGILL), info)\n- case ring0.El1Sync_undef:\n+ case ring0.El1SyncUndef:\n*info = arch.SignalInfo{\nSigno: int32(syscall.SIGILL),\nCode: 1, // ILL_ILLOPC (illegal opcode).\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/aarch64.go",
"new_path": "pkg/sentry/platform/ring0/aarch64.go",
"diff": "@@ -58,46 +58,55 @@ type Vector uintptr\n// Exception vectors.\nconst (\n- El1SyncInvalid = iota\n- El1IrqInvalid\n- El1FiqInvalid\n- El1ErrorInvalid\n+ El1InvSync = iota\n+ El1InvIrq\n+ El1InvFiq\n+ El1InvError\n+\nEl1Sync\nEl1Irq\nEl1Fiq\n- El1Error\n+ El1Err\n+\nEl0Sync\nEl0Irq\nEl0Fiq\n- El0Error\n- El0Sync_invalid\n- El0Irq_invalid\n- El0Fiq_invalid\n- El0Error_invalid\n- El1Sync_da\n- El1Sync_ia\n- El1Sync_sp_pc\n- El1Sync_undef\n- El1Sync_dbg\n- El1Sync_inv\n- El0Sync_svc\n- El0Sync_da\n- El0Sync_ia\n- El0Sync_fpsimd_acc\n- El0Sync_sve_acc\n- El0Sync_sys\n- El0Sync_sp_pc\n- El0Sync_undef\n- El0Sync_dbg\n- El0Sync_inv\n+ El0Err\n+\n+ El0InvSync\n+ El0InvIrq\n+ El0InvFiq\n+ El0InvErr\n+\n+ El1SyncDa\n+ El1SyncIa\n+ El1SyncSpPc\n+ El1SyncUndef\n+ El1SyncDbg\n+ El1SyncInv\n+\n+ El0SyncSVC\n+ El0SyncDa\n+ El0SyncIa\n+ El0SyncFpsimdAcc\n+ El0SyncSveAcc\n+ El0SyncSys\n+ El0SyncSpPc\n+ El0SyncUndef\n+ El0SyncDbg\n+ El0SyncInv\n+\n+ El0ErrNMI\n+ El0ErrBounce\n+\n_NR_INTERRUPTS\n)\n// System call vectors.\nconst (\n- Syscall Vector = El0Sync_svc\n- PageFault Vector = El0Sync_da\n- VirtualizationException Vector = El0Error\n+ Syscall Vector = El0SyncSVC\n+ PageFault Vector = El0SyncDa\n+ VirtualizationException Vector = El0ErrBounce\n)\n// VirtualAddressBits returns the number bits available for virtual addresses.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/offsets_arm64.go",
"new_path": "pkg/sentry/platform/ring0/offsets_arm64.go",
"diff": "@@ -47,43 +47,36 @@ func Emit(w io.Writer) {\nfmt.Fprintf(w, \"#define _KERNEL_FLAGS 0x%02x\\n\", KernelFlagsSet)\nfmt.Fprintf(w, \"\\n// Vectors.\\n\")\n- fmt.Fprintf(w, \"#define El1SyncInvalid 0x%02x\\n\", El1SyncInvalid)\n- fmt.Fprintf(w, \"#define El1IrqInvalid 0x%02x\\n\", El1IrqInvalid)\n- fmt.Fprintf(w, \"#define El1FiqInvalid 0x%02x\\n\", El1FiqInvalid)\n- fmt.Fprintf(w, \"#define El1ErrorInvalid 0x%02x\\n\", El1ErrorInvalid)\nfmt.Fprintf(w, \"#define El1Sync 0x%02x\\n\", El1Sync)\nfmt.Fprintf(w, \"#define El1Irq 0x%02x\\n\", El1Irq)\nfmt.Fprintf(w, \"#define El1Fiq 0x%02x\\n\", El1Fiq)\n- fmt.Fprintf(w, \"#define El1Error 0x%02x\\n\", El1Error)\n+ fmt.Fprintf(w, \"#define El1Err 0x%02x\\n\", El1Err)\nfmt.Fprintf(w, \"#define El0Sync 0x%02x\\n\", El0Sync)\nfmt.Fprintf(w, \"#define El0Irq 0x%02x\\n\", El0Irq)\nfmt.Fprintf(w, \"#define El0Fiq 0x%02x\\n\", El0Fiq)\n- fmt.Fprintf(w, \"#define El0Error 0x%02x\\n\", El0Error)\n+ fmt.Fprintf(w, \"#define El0Err 0x%02x\\n\", El0Err)\n- fmt.Fprintf(w, \"#define El0Sync_invalid 0x%02x\\n\", El0Sync_invalid)\n- fmt.Fprintf(w, \"#define El0Irq_invalid 0x%02x\\n\", El0Irq_invalid)\n- fmt.Fprintf(w, \"#define El0Fiq_invalid 0x%02x\\n\", El0Fiq_invalid)\n- fmt.Fprintf(w, \"#define El0Error_invalid 0x%02x\\n\", El0Error_invalid)\n+ fmt.Fprintf(w, \"#define El1SyncDa 0x%02x\\n\", El1SyncDa)\n+ fmt.Fprintf(w, \"#define El1SyncIa 0x%02x\\n\", El1SyncIa)\n+ fmt.Fprintf(w, \"#define El1SyncSpPc 0x%02x\\n\", El1SyncSpPc)\n+ fmt.Fprintf(w, \"#define El1SyncUndef 0x%02x\\n\", El1SyncUndef)\n+ fmt.Fprintf(w, \"#define El1SyncDbg 0x%02x\\n\", El1SyncDbg)\n+ fmt.Fprintf(w, \"#define El1SyncInv 0x%02x\\n\", El1SyncInv)\n- fmt.Fprintf(w, \"#define El1Sync_da 0x%02x\\n\", El1Sync_da)\n- fmt.Fprintf(w, \"#define El1Sync_ia 0x%02x\\n\", El1Sync_ia)\n- fmt.Fprintf(w, \"#define El1Sync_sp_pc 0x%02x\\n\", El1Sync_sp_pc)\n- fmt.Fprintf(w, \"#define El1Sync_undef 0x%02x\\n\", El1Sync_undef)\n- fmt.Fprintf(w, \"#define El1Sync_dbg 0x%02x\\n\", El1Sync_dbg)\n- fmt.Fprintf(w, \"#define El1Sync_inv 0x%02x\\n\", El1Sync_inv)\n+ fmt.Fprintf(w, \"#define El0SyncSVC 0x%02x\\n\", El0SyncSVC)\n+ fmt.Fprintf(w, \"#define El0SyncDa 0x%02x\\n\", El0SyncDa)\n+ fmt.Fprintf(w, \"#define El0SyncIa 0x%02x\\n\", El0SyncIa)\n+ fmt.Fprintf(w, \"#define El0SyncFpsimdAcc 0x%02x\\n\", El0SyncFpsimdAcc)\n+ fmt.Fprintf(w, \"#define El0SyncSveAcc 0x%02x\\n\", El0SyncSveAcc)\n+ fmt.Fprintf(w, \"#define El0SyncSys 0x%02x\\n\", El0SyncSys)\n+ fmt.Fprintf(w, \"#define El0SyncSpPc 0x%02x\\n\", El0SyncSpPc)\n+ fmt.Fprintf(w, \"#define El0SyncUndef 0x%02x\\n\", El0SyncUndef)\n+ fmt.Fprintf(w, \"#define El0SyncDbg 0x%02x\\n\", El0SyncDbg)\n+ fmt.Fprintf(w, \"#define El0SyncInv 0x%02x\\n\", El0SyncInv)\n- fmt.Fprintf(w, \"#define El0Sync_svc 0x%02x\\n\", El0Sync_svc)\n- fmt.Fprintf(w, \"#define El0Sync_da 0x%02x\\n\", El0Sync_da)\n- fmt.Fprintf(w, \"#define El0Sync_ia 0x%02x\\n\", El0Sync_ia)\n- fmt.Fprintf(w, \"#define El0Sync_fpsimd_acc 0x%02x\\n\", El0Sync_fpsimd_acc)\n- fmt.Fprintf(w, \"#define El0Sync_sve_acc 0x%02x\\n\", El0Sync_sve_acc)\n- fmt.Fprintf(w, \"#define El0Sync_sys 0x%02x\\n\", El0Sync_sys)\n- fmt.Fprintf(w, \"#define El0Sync_sp_pc 0x%02x\\n\", El0Sync_sp_pc)\n- fmt.Fprintf(w, \"#define El0Sync_undef 0x%02x\\n\", El0Sync_undef)\n- fmt.Fprintf(w, \"#define El0Sync_dbg 0x%02x\\n\", El0Sync_dbg)\n- fmt.Fprintf(w, \"#define El0Sync_inv 0x%02x\\n\", El0Sync_inv)\n+ fmt.Fprintf(w, \"#define El0ErrNMI 0x%02x\\n\", El0ErrNMI)\nfmt.Fprintf(w, \"#define PageFault 0x%02x\\n\", PageFault)\nfmt.Fprintf(w, \"#define Syscall 0x%02x\\n\", Syscall)\n"
}
] | Go | Apache License 2.0 | google/gvisor | arm64 kvm: inject sError to trigger sigbus
Use an sErr injection to trigger sigbus when we receive EFAULT from the
run ioctl.
After applying this patch, mmap_test_runsc_kvm will be passed on
Arm64.
Signed-off-by: Bin Lu <[email protected]>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/gvisor/pull/4542 from lubinszARM:pr_kvm_mmap_1 f81bd42466d1d60a581e5fb34de18b78878c68c1
PiperOrigin-RevId: 340461239 |
259,860 | 03.11.2020 14:54:54 | 28,800 | 580bbb749747e8c8bbf4dfe60c15676c85065a6a | [vfs2] Do not drop inotify waiters across S/R.
The waits-for relationship between an epoll instance and an inotify fd should
be restored.
This fixes flaky inotify vfs2 tests. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/inotify.go",
"new_path": "pkg/sentry/vfs/inotify.go",
"diff": "@@ -65,7 +65,7 @@ type Inotify struct {\n// queue is used to notify interested parties when the inotify instance\n// becomes readable or writable.\n- queue waiter.Queue `state:\"nosave\"`\n+ queue waiter.Queue\n// evMu *only* protects the events list. We need a separate lock while\n// queuing events: using mu may violate lock ordering, since at that point\n"
}
] | Go | Apache License 2.0 | google/gvisor | [vfs2] Do not drop inotify waiters across S/R.
The waits-for relationship between an epoll instance and an inotify fd should
be restored.
This fixes flaky inotify vfs2 tests.
PiperOrigin-RevId: 340531367 |
259,898 | 04.11.2020 18:17:33 | 28,800 | e29972ec04f96fa9c560f864113599ce313e1240 | Make the regex for inet6Line in packetimpact/netdevs more accurate | [
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/netdevs/netdevs.go",
"new_path": "test/packetimpact/netdevs/netdevs.go",
"diff": "@@ -40,7 +40,7 @@ var (\ndeviceLine = regexp.MustCompile(`^\\s*(\\d+): (\\w+)`)\nlinkLine = regexp.MustCompile(`^\\s*link/\\w+ ([0-9a-fA-F:]+)`)\ninetLine = regexp.MustCompile(`^\\s*inet ([0-9./]+)`)\n- inet6Line = regexp.MustCompile(`^\\s*inet6 ([0-9a-fA-Z:/]+)`)\n+ inet6Line = regexp.MustCompile(`^\\s*inet6 ([0-9a-fA-F:/]+)`)\n)\n// ParseDevices parses the output from `ip addr show` into a map from device\n"
}
] | Go | Apache License 2.0 | google/gvisor | Make the regex for inet6Line in packetimpact/netdevs more accurate
PiperOrigin-RevId: 340763455 |
259,860 | 04.11.2020 22:44:48 | 28,800 | 771e9ce8e18021fc8015c77c67e57f66ff93ea10 | Unlock tcp endpoint mutex before blocking forever.
This was occasionally causing tests to get stuck due to races with the save
process, during which the same mutex is acquired. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/connect.go",
"new_path": "pkg/tcpip/transport/tcp/connect.go",
"diff": "@@ -1370,7 +1370,9 @@ func (e *endpoint) protocolMainLoop(handshake bool, wakerInitDone chan<- struct{\ndrained := e.drainDone != nil\nif drained {\nclose(e.drainDone)\n+ e.mu.Unlock()\n<-e.undrain\n+ e.mu.Lock()\n}\n// Set up the functions that will be called when the main protocol loop\n"
}
] | Go | Apache License 2.0 | google/gvisor | Unlock tcp endpoint mutex before blocking forever.
This was occasionally causing tests to get stuck due to races with the save
process, during which the same mutex is acquired.
PiperOrigin-RevId: 340789616 |
259,885 | 05.11.2020 12:05:36 | 28,800 | a00c5df98bb9a3df2eb1669c0f97778bb5067c92 | Deflake semaphore_test.
Disable saving in tests that wait for EINTR.
Do not execute async-signal-unsafe code after fork() (see fork(2)'s manpage,
"After a fork in a multithreaded program ...")
Check for errors returned by semctl(GETZCNT). | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/semaphore.cc",
"new_path": "test/syscalls/linux/semaphore.cc",
"diff": "@@ -543,13 +543,17 @@ TEST(SemaphoreTest, SemCtlIpcStat) {\nSyscallFailsWithErrno(EACCES));\n}\n-// The funcion keeps calling semctl's GETZCNT command until\n-// the return value is not less than target.\n-int WaitSemzcnt(int semid, int target) {\n+// Calls semctl(GETZCNT) until the returned value is >= target, an internal\n+// timeout expires, or semctl returns an error.\n+PosixErrorOr<int> WaitSemzcnt(int semid, int target) {\nconstexpr absl::Duration timeout = absl::Seconds(10);\n+ const auto deadline = absl::Now() + timeout;\nint semcnt = 0;\n- for (auto start = absl::Now(); absl::Now() - start < timeout;) {\n+ while (absl::Now() < deadline) {\nsemcnt = semctl(semid, 0, GETZCNT);\n+ if (semcnt < 0) {\n+ return PosixError(errno, \"semctl(GETZCNT) failed\");\n+ }\nif (semcnt >= target) {\nbreak;\n}\n@@ -585,12 +589,12 @@ TEST(SemaphoreTest, SemopGetzcnt) {\nfor (auto i = 0; i < kLoops; i++) {\nauto child_pid = fork();\nif (child_pid == 0) {\n- ASSERT_THAT(RetryEINTR(semop)(sem.get(), &buf, 1), SyscallSucceeds());\n+ TEST_PCHECK(RetryEINTR(semop)(sem.get(), &buf, 1) == 0);\n_exit(0);\n}\nchildren.push_back(child_pid);\n}\n- EXPECT_THAT(WaitSemzcnt(sem.get(), kLoops), SyscallSucceedsWithValue(kLoops));\n+ EXPECT_THAT(WaitSemzcnt(sem.get(), kLoops), IsPosixErrorOkAndHolds(kLoops));\n// Set semval to 0, which wakes up children that sleep on the semop.\nASSERT_THAT(semctl(sem.get(), 0, SETVAL, 0), SyscallSucceeds());\nfor (const auto& child_pid : children) {\n@@ -614,14 +618,14 @@ TEST(SemaphoreTest, SemopGetzcntOnSetRemoval) {\nbuf.sem_num = 0;\nbuf.sem_op = 0;\n- ASSERT_THAT(RetryEINTR(semop)(semid, &buf, 1), SyscallFails());\n// Ensure that wait will only unblock when the semaphore is removed. On\n// EINTR retry it may race with deletion and return EINVAL.\n- ASSERT_TRUE(errno == EIDRM || errno == EINVAL) << \"errno=\" << errno;\n+ TEST_PCHECK(RetryEINTR(semop)(semid, &buf, 1) < 0 &&\n+ (errno == EIDRM || errno == EINVAL));\n_exit(0);\n}\n- EXPECT_THAT(WaitSemzcnt(semid, 1), SyscallSucceedsWithValue(1));\n+ EXPECT_THAT(WaitSemzcnt(semid, 1), IsPosixErrorOkAndHolds(1));\n// Remove the semaphore set, which fails the sleep semop.\nASSERT_THAT(semctl(semid, 0, IPC_RMID), SyscallSucceeds());\nint status;\n@@ -631,25 +635,31 @@ TEST(SemaphoreTest, SemopGetzcntOnSetRemoval) {\nEXPECT_THAT(semctl(semid, 0, GETZCNT), SyscallFailsWithErrno(EINVAL));\n}\n-TEST(SemaphoreTest, SemopGetzcntOnSignal) {\n+TEST(SemaphoreTest, SemopGetzcntOnSignal_NoRandomSave) {\nAutoSem sem(semget(IPC_PRIVATE, 1, 0600 | IPC_CREAT));\nASSERT_THAT(sem.get(), SyscallSucceeds());\nASSERT_THAT(semctl(sem.get(), 0, SETVAL, 1), SyscallSucceeds());\nASSERT_EQ(semctl(sem.get(), 0, GETZCNT), 0);\n+ // Saving will cause semop() to be spuriously interrupted.\n+ DisableSave ds;\n+\nauto child_pid = fork();\nif (child_pid == 0) {\n- signal(SIGHUP, [](int sig) -> void {});\n+ TEST_PCHECK(signal(SIGHUP, [](int sig) -> void {}) != SIG_ERR);\nstruct sembuf buf = {};\nbuf.sem_num = 0;\nbuf.sem_op = 0;\n- ASSERT_THAT(semop(sem.get(), &buf, 1), SyscallFailsWithErrno(EINTR));\n+ TEST_PCHECK(semop(sem.get(), &buf, 1) < 0 && errno == EINTR);\n_exit(0);\n}\n- EXPECT_THAT(WaitSemzcnt(sem.get(), 1), SyscallSucceedsWithValue(1));\n+ EXPECT_THAT(WaitSemzcnt(sem.get(), 1), IsPosixErrorOkAndHolds(1));\n// Send a signal to the child, which fails the sleep semop.\nASSERT_EQ(kill(child_pid, SIGHUP), 0);\n+\n+ ds.reset();\n+\nint status;\nASSERT_THAT(RetryEINTR(waitpid)(child_pid, &status, 0),\nSyscallSucceedsWithValue(child_pid));\n"
}
] | Go | Apache License 2.0 | google/gvisor | Deflake semaphore_test.
- Disable saving in tests that wait for EINTR.
- Do not execute async-signal-unsafe code after fork() (see fork(2)'s manpage,
"After a fork in a multithreaded program ...")
- Check for errors returned by semctl(GETZCNT).
PiperOrigin-RevId: 340901353 |
259,907 | 05.11.2020 17:09:28 | 28,800 | f27edcc708e412b5c5bbeb0c274837af94c625cc | [runtime tests] Add partitions to runtime tests.
This will allow us to run massive runtime tests live java to run in parallel
across multiple jobs. | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -156,12 +156,24 @@ syscall-tests: ## Run all system call tests.\n@$(call submake,test TARGETS=\"test/syscalls/...\")\n%-runtime-tests: load-runtimes_%\n+ifeq ($(PARTITION),)\n+ @$(eval PARTITION := 1)\n+endif\n+ifeq ($(TOTAL_PARTITIONS),)\n+ @$(eval TOTAL_PARTITIONS := 1)\n+endif\n@$(call submake,install-test-runtime)\n- @$(call submake,test-runtime OPTIONS=\"--test_timeout=10800\" TARGETS=\"//test/runtimes:$*\")\n+ @$(call submake,test-runtime OPTIONS=\"--test_timeout=10800 --test_arg=--partition=$(PARTITION) --test_arg=--total_partitions=$(TOTAL_PARTITIONS)\" TARGETS=\"//test/runtimes:$*\")\n%-runtime-tests_vfs2: load-runtimes_%\n+ifeq ($(PARTITION),)\n+ @$(eval PARTITION := 1)\n+endif\n+ifeq ($(TOTAL_PARTITIONS),)\n+ @$(eval TOTAL_PARTITIONS := 1)\n+endif\n@$(call submake,install-test-runtime RUNTIME=\"vfs2\" ARGS=\"--vfs2\")\n- @$(call submake,test-runtime RUNTIME=\"vfs2\" OPTIONS=\"--test_timeout=10800\" TARGETS=\"//test/runtimes:$*\")\n+ @$(call submake,test-runtime RUNTIME=\"vfs2\" OPTIONS=\"--test_timeout=10800 --test_arg=--partition=$(PARTITION) --test_arg=--total_partitions=$(TOTAL_PARTITIONS)\" TARGETS=\"//test/runtimes:$*\")\ndo-tests: runsc\n@$(call submake,run TARGETS=\"//runsc\" ARGS=\"--rootless do true\")\n"
},
{
"change_type": "MODIFY",
"old_path": "test/runtimes/runner/lib/lib.go",
"new_path": "test/runtimes/runner/lib/lib.go",
"diff": "@@ -34,7 +34,12 @@ import (\n// RunTests is a helper that is called by main. It exists so that we can run\n// defered functions before exiting. It returns an exit code that should be\n// passed to os.Exit.\n-func RunTests(lang, image, excludeFile string, batchSize int, timeout time.Duration) int {\n+func RunTests(lang, image, excludeFile string, partitionNum, totalPartitions, batchSize int, timeout time.Duration) int {\n+ if partitionNum <= 0 || totalPartitions <= 0 || partitionNum > totalPartitions {\n+ fmt.Fprintf(os.Stderr, \"invalid partition %d of %d\", partitionNum, totalPartitions)\n+ return 1\n+ }\n+\n// Get tests to exclude..\nexcludes, err := getExcludes(excludeFile)\nif err != nil {\n@@ -55,7 +60,7 @@ func RunTests(lang, image, excludeFile string, batchSize int, timeout time.Durat\n// Get a slice of tests to run. This will also start a single Docker\n// container that will be used to run each test. The final test will\n// stop the Docker container.\n- tests, err := getTests(ctx, d, lang, image, batchSize, timeout, excludes)\n+ tests, err := getTests(ctx, d, lang, image, partitionNum, totalPartitions, batchSize, timeout, excludes)\nif err != nil {\nfmt.Fprintf(os.Stderr, \"%s\\n\", err.Error())\nreturn 1\n@@ -66,7 +71,7 @@ func RunTests(lang, image, excludeFile string, batchSize int, timeout time.Durat\n}\n// getTests executes all tests as table tests.\n-func getTests(ctx context.Context, d *dockerutil.Container, lang, image string, batchSize int, timeout time.Duration, excludes map[string]struct{}) ([]testing.InternalTest, error) {\n+func getTests(ctx context.Context, d *dockerutil.Container, lang, image string, partitionNum, totalPartitions, batchSize int, timeout time.Duration, excludes map[string]struct{}) ([]testing.InternalTest, error) {\n// Start the container.\nopts := dockerutil.RunOpts{\nImage: fmt.Sprintf(\"runtimes/%s\", image),\n@@ -86,6 +91,14 @@ func getTests(ctx context.Context, d *dockerutil.Container, lang, image string,\n// shard.\ntests := strings.Fields(list)\nsort.Strings(tests)\n+\n+ partitionSize := len(tests) / totalPartitions\n+ if partitionNum == totalPartitions {\n+ tests = tests[(partitionNum-1)*partitionSize:]\n+ } else {\n+ tests = tests[(partitionNum-1)*partitionSize : partitionNum*partitionSize]\n+ }\n+\nindices, err := testutil.TestIndicesForShard(len(tests))\nif err != nil {\nreturn nil, fmt.Errorf(\"TestsForShard() failed: %v\", err)\n@@ -116,8 +129,15 @@ func getTests(ctx context.Context, d *dockerutil.Container, lang, image string,\nerr error\n)\n+ state, err := d.Status(ctx)\n+ if err != nil {\n+ t.Fatalf(\"Could not find container status: %v\", err)\n+ }\n+ if !state.Running {\n+ t.Fatalf(\"container is not running: state = %s\", state.Status)\n+ }\n+\ngo func() {\n- fmt.Printf(\"RUNNING the following in a batch\\n%s\\n\", strings.Join(tcs, \"\\n\"))\noutput, err = d.Exec(ctx, dockerutil.ExecOpts{}, \"/proctor/proctor\", \"--runtime\", lang, \"--tests\", strings.Join(tcs, \",\"))\nclose(done)\n}()\n@@ -125,12 +145,12 @@ func getTests(ctx context.Context, d *dockerutil.Container, lang, image string,\nselect {\ncase <-done:\nif err == nil {\n- fmt.Printf(\"PASS: (%v)\\n\\n\", time.Since(now))\n+ fmt.Printf(\"PASS: (%v) %d tests passed\\n\", time.Since(now), len(tcs))\nreturn\n}\n- t.Errorf(\"FAIL: (%v):\\n%s\\n\", time.Since(now), output)\n+ t.Errorf(\"FAIL: (%v):\\nBatch:\\n%s\\nOutput:\\n%s\\n\", time.Since(now), strings.Join(tcs, \"\\n\"), output)\ncase <-time.After(timeout):\n- t.Errorf(\"TIMEOUT: (%v):\\n%s\\n\", time.Since(now), output)\n+ t.Errorf(\"TIMEOUT: (%v):\\nBatch:\\n%s\\nOutput:\\n%s\\n\", time.Since(now), strings.Join(tcs, \"\\n\"), output)\n}\n},\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "test/runtimes/runner/main.go",
"new_path": "test/runtimes/runner/main.go",
"diff": "@@ -28,6 +28,8 @@ var (\nlang = flag.String(\"lang\", \"\", \"language runtime to test\")\nimage = flag.String(\"image\", \"\", \"docker image with runtime tests\")\nexcludeFile = flag.String(\"exclude_file\", \"\", \"file containing list of tests to exclude, in CSV format with fields: test name, bug id, comment\")\n+ partition = flag.Int(\"partition\", 1, \"partition number, this is 1-indexed\")\n+ totalPartitions = flag.Int(\"total_partitions\", 1, \"total number of partitions\")\nbatchSize = flag.Int(\"batch\", 50, \"number of test cases run in one command\")\ntimeout = flag.Duration(\"timeout\", 90*time.Minute, \"batch timeout\")\n)\n@@ -38,5 +40,5 @@ func main() {\nfmt.Fprintf(os.Stderr, \"lang and image flags must not be empty\\n\")\nos.Exit(1)\n}\n- os.Exit(lib.RunTests(*lang, *image, *excludeFile, *batchSize, *timeout))\n+ os.Exit(lib.RunTests(*lang, *image, *excludeFile, *partition, *totalPartitions, *batchSize, *timeout))\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | [runtime tests] Add partitions to runtime tests.
This will allow us to run massive runtime tests live java to run in parallel
across multiple jobs.
PiperOrigin-RevId: 340956246 |
259,992 | 05.11.2020 18:16:11 | 28,800 | 62b0e845b7301da7d0c75eb812e9cd75ade05b74 | Return failure when `runsc events` queries a stopped container
This was causing gvisor-containerd-shim to crash because the command
suceeded, but there was no stat present. | [
{
"change_type": "MODIFY",
"old_path": "pkg/shim/runsc/BUILD",
"new_path": "pkg/shim/runsc/BUILD",
"diff": "@@ -10,6 +10,7 @@ go_library(\n],\nvisibility = [\"//:sandbox\"],\ndeps = [\n+ \"@com_github_containerd_containerd//log:go_default_library\",\n\"@com_github_containerd_go_runc//:go_default_library\",\n\"@com_github_opencontainers_runtime_spec//specs-go:go_default_library\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/shim/runsc/runsc.go",
"new_path": "pkg/shim/runsc/runsc.go",
"diff": "@@ -28,10 +28,12 @@ import (\n\"syscall\"\n\"time\"\n+ \"github.com/containerd/containerd/log\"\nrunc \"github.com/containerd/go-runc\"\nspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n)\n+// Monitor is the default process monitor to be used by runsc.\nvar Monitor runc.ProcessMonitor = runc.Monitor\n// DefaultCommand is the default command for Runsc.\n@@ -74,6 +76,7 @@ func (r *Runsc) State(context context.Context, id string) (*runc.Container, erro\nreturn &c, nil\n}\n+// CreateOpts is a set of options to Runsc.Create().\ntype CreateOpts struct {\nrunc.IO\nConsoleSocket runc.ConsoleSocket\n@@ -197,6 +200,7 @@ func (r *Runsc) Wait(context context.Context, id string) (int, error) {\nreturn res.ExitStatus, nil\n}\n+// ExecOpts is a set of options to runsc.Exec().\ntype ExecOpts struct {\nrunc.IO\nPidFile string\n@@ -301,6 +305,7 @@ func (r *Runsc) Run(context context.Context, id, bundle string, opts *CreateOpts\nreturn Monitor.Wait(cmd, ec)\n}\n+// DeleteOpts is a set of options to runsc.Delete().\ntype DeleteOpts struct {\nForce bool\n}\n@@ -367,6 +372,13 @@ func (r *Runsc) Stats(context context.Context, id string) (*runc.Stats, error) {\nif err := json.NewDecoder(rd).Decode(&e); err != nil {\nreturn nil, err\n}\n+ log.L.Debugf(\"Stats returned: %+v\", e.Stats)\n+ if e.Type != \"stats\" {\n+ return nil, fmt.Errorf(`unexpected event type %q, wanted \"stats\"`, e.Type)\n+ }\n+ if e.Stats == nil {\n+ return nil, fmt.Errorf(`\"runsc events -stat\" succeeded but no stat was provided`)\n+ }\nreturn e.Stats, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/events.go",
"new_path": "runsc/cmd/events.go",
"diff": "@@ -85,7 +85,12 @@ func (evs *Events) Execute(ctx context.Context, f *flag.FlagSet, args ...interfa\nev, err := c.Event()\nif err != nil {\nlog.Warningf(\"Error getting events for container: %v\", err)\n+ if evs.stats {\n+ return subcommands.ExitFailure\n}\n+ }\n+ log.Debugf(\"Events: %+v\", ev)\n+\n// err must be preserved because it is used below when breaking\n// out of the loop.\nb, err := json.Marshal(ev)\n@@ -101,11 +106,9 @@ func (evs *Events) Execute(ctx context.Context, f *flag.FlagSet, args ...interfa\nif err != nil {\nreturn subcommands.ExitFailure\n}\n- break\n+ return subcommands.ExitSuccess\n}\ntime.Sleep(time.Duration(evs.intervalSec) * time.Second)\n}\n-\n- return subcommands.ExitSuccess\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/container.go",
"new_path": "runsc/container/container.go",
"diff": "@@ -587,7 +587,12 @@ func (c *Container) SandboxPid() int {\n// and wait returns immediately.\nfunc (c *Container) Wait() (syscall.WaitStatus, error) {\nlog.Debugf(\"Wait on container, cid: %s\", c.ID)\n- return c.Sandbox.Wait(c.ID)\n+ ws, err := c.Sandbox.Wait(c.ID)\n+ if err == nil {\n+ // Wait succeeded, container is not running anymore.\n+ c.changeStatus(Stopped)\n+ }\n+ return ws, err\n}\n// WaitRootPID waits for process 'pid' in the sandbox's PID namespace and\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/multi_container_test.go",
"new_path": "runsc/container/multi_container_test.go",
"diff": "package container\nimport (\n+ \"encoding/json\"\n\"fmt\"\n\"io/ioutil\"\n\"math\"\n@@ -1766,3 +1767,72 @@ func TestMultiContainerHomeEnvDir(t *testing.T) {\n})\n}\n}\n+\n+func TestMultiContainerEvent(t *testing.T) {\n+ conf := testutil.TestConfig(t)\n+ rootDir, cleanup, err := testutil.SetupRootDir()\n+ if err != nil {\n+ t.Fatalf(\"error creating root dir: %v\", err)\n+ }\n+ defer cleanup()\n+ conf.RootDir = rootDir\n+\n+ // Setup the containers.\n+ sleep := []string{\"/bin/sleep\", \"100\"}\n+ quick := []string{\"/bin/true\"}\n+ podSpec, ids := createSpecs(sleep, sleep, quick)\n+ containers, cleanup, err := startContainers(conf, podSpec, ids)\n+ if err != nil {\n+ t.Fatalf(\"error starting containers: %v\", err)\n+ }\n+ defer cleanup()\n+\n+ for _, cont := range containers {\n+ t.Logf(\"Running containerd %s\", cont.ID)\n+ }\n+\n+ // Wait for last container to stabilize the process count that is checked\n+ // further below.\n+ if ws, err := containers[2].Wait(); err != nil || ws != 0 {\n+ t.Fatalf(\"Container.Wait, status: %v, err: %v\", ws, err)\n+ }\n+\n+ // Check events for running containers.\n+ for _, cont := range containers[:2] {\n+ evt, err := cont.Event()\n+ if err != nil {\n+ t.Errorf(\"Container.Events(): %v\", err)\n+ }\n+ if want := \"stats\"; evt.Type != want {\n+ t.Errorf(\"Wrong event type, want: %s, got :%s\", want, evt.Type)\n+ }\n+ if cont.ID != evt.ID {\n+ t.Errorf(\"Wrong container ID, want: %s, got :%s\", cont.ID, evt.ID)\n+ }\n+ // Event.Data is an interface, so it comes from the wire was\n+ // map[string]string. Marshal and unmarshall again to the correc type.\n+ data, err := json.Marshal(evt.Data)\n+ if err != nil {\n+ t.Fatalf(\"invalid event data: %v\", err)\n+ }\n+ var stats boot.Stats\n+ if err := json.Unmarshal(data, &stats); err != nil {\n+ t.Fatalf(\"invalid event data: %v\", err)\n+ }\n+ // One process per remaining container.\n+ if want := uint64(2); stats.Pids.Current != want {\n+ t.Errorf(\"Wrong number of PIDs, want: %d, got :%d\", want, stats.Pids.Current)\n+ }\n+ }\n+\n+ // Check that stop and destroyed containers return error.\n+ if err := containers[1].Destroy(); err != nil {\n+ t.Fatalf(\"container.Destroy: %v\", err)\n+ }\n+ for _, cont := range containers[1:] {\n+ _, err := cont.Event()\n+ if err == nil {\n+ t.Errorf(\"Container.Events() should have failed, cid:%s, state: %v\", cont.ID, cont.Status)\n+ }\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Return failure when `runsc events` queries a stopped container
This was causing gvisor-containerd-shim to crash because the command
suceeded, but there was no stat present.
PiperOrigin-RevId: 340964921 |
259,992 | 05.11.2020 19:04:28 | 28,800 | 0e8fdfd3885bda36c0cb9225a107f1ee30c6c65f | Re-add start/stop container tests
Due to a type doDestroyNotStartedTest was being tested
2x instead of doDestroyStartingTest. | [
{
"change_type": "MODIFY",
"old_path": "runsc/container/container_test.go",
"new_path": "runsc/container/container_test.go",
"diff": "@@ -1976,11 +1976,11 @@ func doDestroyNotStartedTest(t *testing.T, vfs2 bool) {\n// TestDestroyStarting attempts to force a race between start and destroy.\nfunc TestDestroyStarting(t *testing.T) {\n- doDestroyNotStartedTest(t, false)\n+ doDestroyStartingTest(t, false)\n}\nfunc TestDestroyStartedVFS2(t *testing.T) {\n- doDestroyNotStartedTest(t, true)\n+ doDestroyStartingTest(t, true)\n}\nfunc doDestroyStartingTest(t *testing.T, vfs2 bool) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Re-add start/stop container tests
Due to a type doDestroyNotStartedTest was being tested
2x instead of doDestroyStartingTest.
PiperOrigin-RevId: 340969797 |
259,962 | 05.11.2020 19:05:14 | 28,800 | 06e33cd737c59623ddcca60eacefb112fc1a0cd4 | Cache addressEndpoint.addr.Subnet() to avoid allocations.
This change adds a Subnet() method to AddressableEndpoint so that we
can avoid repeated calls to AddressableEndpoint.AddressWithPrefix().Subnet().
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4.go",
"diff": "@@ -692,7 +692,7 @@ func (e *endpoint) AcquireAssignedAddress(localAddr tcpip.Address, allowTemp boo\nloopback := e.nic.IsLoopback()\naddressEndpoint := e.mu.addressableEndpointState.ReadOnly().AddrOrMatching(localAddr, allowTemp, func(addressEndpoint stack.AddressEndpoint) bool {\n- subnet := addressEndpoint.AddressWithPrefix().Subnet()\n+ subnet := addressEndpoint.Subnet()\n// IPv4 has a notion of a subnet broadcast address and considers the\n// loopback interface bound to an address's whole subnet (on linux).\nreturn subnet.IsBroadcast(localAddr) || (loopback && subnet.Contains(localAddr))\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6.go",
"diff": "@@ -166,7 +166,7 @@ func (e *endpoint) dupTentativeAddrDetected(addr tcpip.Address) *tcpip.Error {\nreturn err\n}\n- prefix := addressEndpoint.AddressWithPrefix().Subnet()\n+ prefix := addressEndpoint.Subnet()\nswitch t := addressEndpoint.ConfigType(); t {\ncase stack.AddressConfigStatic:\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/addressable_endpoint_state.go",
"new_path": "pkg/tcpip/stack/addressable_endpoint_state.go",
"diff": "@@ -272,6 +272,9 @@ func (a *AddressableEndpointState) addAndAcquireAddressLocked(addr tcpip.Address\naddrState = &addressState{\naddressableEndpointState: a,\naddr: addr,\n+ // Cache the subnet in addrState to avoid calls to addr.Subnet() as that\n+ // results in allocations on every call.\n+ subnet: addr.Subnet(),\n}\na.mu.endpoints[addr.Address] = addrState\naddrState.mu.Lock()\n@@ -666,7 +669,7 @@ var _ AddressEndpoint = (*addressState)(nil)\ntype addressState struct {\naddressableEndpointState *AddressableEndpointState\naddr tcpip.AddressWithPrefix\n-\n+ subnet tcpip.Subnet\n// Lock ordering (from outer to inner lock ordering):\n//\n// AddressableEndpointState.mu\n@@ -686,6 +689,11 @@ func (a *addressState) AddressWithPrefix() tcpip.AddressWithPrefix {\nreturn a.addr\n}\n+// Subnet implements AddressEndpoint.\n+func (a *addressState) Subnet() tcpip.Subnet {\n+ return a.subnet\n+}\n+\n// GetKind implements AddressEndpoint.\nfunc (a *addressState) GetKind() AddressKind {\na.mu.RLock()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/registration.go",
"new_path": "pkg/tcpip/stack/registration.go",
"diff": "@@ -340,6 +340,9 @@ type AssignableAddressEndpoint interface {\n// AddressWithPrefix returns the endpoint's address.\nAddressWithPrefix() tcpip.AddressWithPrefix\n+ // Subnet returns the subnet of the endpoint's address.\n+ Subnet() tcpip.Subnet\n+\n// IsAssigned returns whether or not the endpoint is considered bound\n// to its NetworkEndpoint.\nIsAssigned(allowExpired bool) bool\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/route.go",
"new_path": "pkg/tcpip/stack/route.go",
"diff": "@@ -440,7 +440,7 @@ func (r *Route) isV4Broadcast(addr tcpip.Address) bool {\nreturn true\n}\n- subnet := r.localAddressEndpoint.AddressWithPrefix().Subnet()\n+ subnet := r.localAddressEndpoint.Subnet()\nreturn subnet.IsBroadcast(addr)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Cache addressEndpoint.addr.Subnet() to avoid allocations.
This change adds a Subnet() method to AddressableEndpoint so that we
can avoid repeated calls to AddressableEndpoint.AddressWithPrefix().Subnet().
Updates #231
PiperOrigin-RevId: 340969877 |
259,885 | 06.11.2020 00:18:34 | 28,800 | 29683f359822310d0f81a5c0f6ccaf98d6c284a3 | Cap iovec array length in //pkg/sentry/hostfd. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/hostfd/BUILD",
"new_path": "pkg/sentry/hostfd/BUILD",
"diff": "@@ -6,10 +6,12 @@ go_library(\nname = \"hostfd\",\nsrcs = [\n\"hostfd.go\",\n+ \"hostfd_linux.go\",\n\"hostfd_unsafe.go\",\n],\nvisibility = [\"//pkg/sentry:internal\"],\ndeps = [\n+ \"//pkg/log\",\n\"//pkg/safemem\",\n\"//pkg/sync\",\n\"@org_golang_x_sys//unix:go_default_library\",\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/hostfd/hostfd_linux.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 hostfd\n+\n+// maxIov is the maximum permitted size of a struct iovec array.\n+const maxIov = 1024 // UIO_MAXIOV\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/hostfd/hostfd_unsafe.go",
"new_path": "pkg/sentry/hostfd/hostfd_unsafe.go",
"diff": "@@ -20,6 +20,7 @@ import (\n\"unsafe\"\n\"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/safemem\"\n)\n@@ -44,6 +45,10 @@ func Preadv2(fd int32, dsts safemem.BlockSeq, offset int64, flags uint32) (uint6\n}\n} else {\niovs := safemem.IovecsFromBlockSeq(dsts)\n+ if len(iovs) > maxIov {\n+ log.Debugf(\"hostfd.Preadv2: truncating from %d iovecs to %d\", len(iovs), maxIov)\n+ iovs = iovs[:maxIov]\n+ }\nn, _, e = syscall.Syscall6(unix.SYS_PREADV2, uintptr(fd), uintptr((unsafe.Pointer)(&iovs[0])), uintptr(len(iovs)), uintptr(offset), 0 /* pos_h */, uintptr(flags))\n}\nif e != 0 {\n@@ -76,6 +81,10 @@ func Pwritev2(fd int32, srcs safemem.BlockSeq, offset int64, flags uint32) (uint\n}\n} else {\niovs := safemem.IovecsFromBlockSeq(srcs)\n+ if len(iovs) > maxIov {\n+ log.Debugf(\"hostfd.Preadv2: truncating from %d iovecs to %d\", len(iovs), maxIov)\n+ iovs = iovs[:maxIov]\n+ }\nn, _, e = syscall.Syscall6(unix.SYS_PWRITEV2, uintptr(fd), uintptr((unsafe.Pointer)(&iovs[0])), uintptr(len(iovs)), uintptr(offset), 0 /* pos_h */, uintptr(flags))\n}\nif e != 0 {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Cap iovec array length in //pkg/sentry/hostfd.
PiperOrigin-RevId: 341001328 |
260,004 | 06.11.2020 01:45:12 | 28,800 | 955e09dfbdb8a4cdae0a0b625001a567f6f15758 | Do not send to the zero port
Port 0 is not meant to identify any remote port so attempting to send
a packet to it should return an error. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -487,6 +487,11 @@ func (e *endpoint) write(p tcpip.Payloader, opts tcpip.WriteOptions) (int64, <-c\nnicID = e.BindNICID\n}\n+ if to.Port == 0 {\n+ // Port 0 is an invalid port to send to.\n+ return 0, nil, tcpip.ErrInvalidEndpointState\n+ }\n+\ndst, netProto, err := e.checkV4MappedLocked(*to)\nif err != nil {\nreturn 0, nil, err\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/udp_socket.cc",
"new_path": "test/syscalls/linux/udp_socket.cc",
"diff": "@@ -1887,6 +1887,22 @@ TEST_P(UdpSocketTest, GetSocketDetachFilter) {\nSyscallFailsWithErrno(ENOPROTOOPT));\n}\n+TEST_P(UdpSocketTest, SendToZeroPort) {\n+ char buf[8];\n+ struct sockaddr_storage addr = InetLoopbackAddr();\n+\n+ // Sending to an invalid port should fail.\n+ SetPort(&addr, 0);\n+ EXPECT_THAT(sendto(sock_.get(), buf, sizeof(buf), 0,\n+ reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)),\n+ SyscallFailsWithErrno(EINVAL));\n+\n+ SetPort(&addr, 1234);\n+ EXPECT_THAT(sendto(sock_.get(), buf, sizeof(buf), 0,\n+ reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)),\n+ SyscallSucceedsWithValue(sizeof(buf)));\n+}\n+\nINSTANTIATE_TEST_SUITE_P(AllInetTests, UdpSocketTest,\n::testing::Values(AddressFamily::kIpv4,\nAddressFamily::kIpv6,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Do not send to the zero port
Port 0 is not meant to identify any remote port so attempting to send
a packet to it should return an error.
PiperOrigin-RevId: 341009528 |
259,860 | 06.11.2020 12:59:44 | 28,800 | bcd883f095d62ef790889e5516adc4f437512726 | Avoid extra DecRef on kernfs root for "kept" dentries.
The root dentry was not created through Inode.Lookup, so we should not
release a reference even if inode.Keep() is true. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go",
"diff": "@@ -264,7 +264,7 @@ func (fs *Filesystem) Release(ctx context.Context) {\n//\n// Precondition: Filesystem.mu is held.\nfunc (d *Dentry) releaseKeptDentriesLocked(ctx context.Context) {\n- if d.inode.Keep() {\n+ if d.inode.Keep() && d != d.fs.root {\nd.decRefLocked(ctx)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Avoid extra DecRef on kernfs root for "kept" dentries.
The root dentry was not created through Inode.Lookup, so we should not
release a reference even if inode.Keep() is true.
PiperOrigin-RevId: 341103220 |
259,962 | 06.11.2020 13:53:21 | 28,800 | 9e82747d62e57ee7498c8f3f54c313917891273a | Return early in walkSACK if segment has no SACK blocks.
This avoids a needless allocation.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/snd.go",
"new_path": "pkg/tcpip/transport/tcp/snd.go",
"diff": "@@ -1285,6 +1285,10 @@ func (s *sender) checkDuplicateAck(seg *segment) (rtx bool) {\n// See: https://tools.ietf.org/html/draft-ietf-tcpm-rack-08#section-7.2\n// steps 2 and 3.\nfunc (s *sender) walkSACK(rcvdSeg *segment) {\n+ if len(rcvdSeg.parsedOptions.SACKBlocks) == 0 {\n+ return\n+ }\n+\n// Sort the SACK blocks. The first block is the most recent unacked\n// block. The following blocks can be in arbitrary order.\nsackBlocks := make([]header.SACKBlock, len(rcvdSeg.parsedOptions.SACKBlocks))\n"
}
] | Go | Apache License 2.0 | google/gvisor | Return early in walkSACK if segment has no SACK blocks.
This avoids a needless allocation.
Updates #231
PiperOrigin-RevId: 341113160 |
259,975 | 06.11.2020 15:44:38 | 28,800 | 6c93dc970f0acc110ae4f941574defa4aa113116 | Add pull image statment to benchmarks rule. | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -291,7 +291,7 @@ init-benchmark-table: ## Initializes a BigQuery table with the benchmark schema\n--dataset=$(BENCHMARKS_DATASET) --table=$(BENCHMARKS_TABLE)\")\n.PHONY: init-benchmark-table\n-benchmark-platforms: ## Runs benchmarks for runc and all given platforms in BENCHMARK_PLATFORMS.\n+benchmark-platforms: load-benchmarks-images ## Runs benchmarks for runc and all given platforms in BENCHMARK_PLATFORMS.\n$(call submake, run-benchmark RUNTIME=\"runc\")\n$(foreach PLATFORM,$(BENCHMARKS_PLATFORMS),\\\n$(call submake,benchmark-platform RUNTIME=\"$(PLATFORM)\" RUNTIME_ARGS=\"--platform=$(PLATFORM) --net-raw --vfs2\") && \\\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add pull image statment to benchmarks rule.
PiperOrigin-RevId: 341132662 |
260,004 | 06.11.2020 15:59:02 | 28,800 | 5288e194156a72a3efae7794e46e44f1dd0d7427 | Trim link headers from buffer clone when sniffing | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/sniffer/sniffer.go",
"new_path": "pkg/tcpip/link/sniffer/sniffer.go",
"diff": "@@ -205,7 +205,12 @@ func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, pkt *stack.P\n//\n// We don't clone the original packet buffer so that the new packet buffer\n// does not have any of its headers set.\n- pkt = stack.NewPacketBuffer(stack.PacketBufferOptions{Data: buffer.NewVectorisedView(pkt.Size(), pkt.Views())})\n+ //\n+ // We trim the link headers from the cloned buffer as the sniffer doesn't\n+ // handle link headers.\n+ vv := buffer.NewVectorisedView(pkt.Size(), pkt.Views())\n+ vv.TrimFront(len(pkt.LinkHeader().View()))\n+ pkt = stack.NewPacketBuffer(stack.PacketBufferOptions{Data: vv})\nswitch protocol {\ncase header.IPv4ProtocolNumber:\nif ok := parse.IPv4(pkt); !ok {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Trim link headers from buffer clone when sniffing
PiperOrigin-RevId: 341135083 |
259,875 | 06.11.2020 18:36:03 | 28,800 | 3ac00fe9c3396f07a1416ff7fc855f6f9a3c4304 | Implement command GETNCNT for semctl. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/semaphore/semaphore.go",
"new_path": "pkg/sentry/kernel/semaphore/semaphore.go",
"diff": "@@ -103,6 +103,7 @@ type waiter struct {\nwaiterEntry\n// value represents how much resource the waiter needs to wake up.\n+ // The value is either 0 or negative.\nvalue int16\nch chan struct{}\n}\n@@ -423,8 +424,7 @@ func (s *Set) GetPID(num int32, creds *auth.Credentials) (int32, error) {\nreturn sem.pid, nil\n}\n-// GetZeroWaiters returns number of waiters waiting for the sem to go to zero.\n-func (s *Set) GetZeroWaiters(num int32, creds *auth.Credentials) (uint16, error) {\n+func (s *Set) countWaiters(num int32, creds *auth.Credentials, pred func(w *waiter) bool) (uint16, error) {\ns.mu.Lock()\ndefer s.mu.Unlock()\n@@ -437,13 +437,27 @@ func (s *Set) GetZeroWaiters(num int32, creds *auth.Credentials) (uint16, error)\nif sem == nil {\nreturn 0, syserror.ERANGE\n}\n- var semzcnt uint16\n+ var cnt uint16\nfor w := sem.waiters.Front(); w != nil; w = w.Next() {\n- if w.value == 0 {\n- semzcnt++\n+ if pred(w) {\n+ cnt++\n}\n}\n- return semzcnt, nil\n+ return cnt, nil\n+}\n+\n+// CountZeroWaiters returns number of waiters waiting for the sem's value to increase.\n+func (s *Set) CountZeroWaiters(num int32, creds *auth.Credentials) (uint16, error) {\n+ return s.countWaiters(num, creds, func(w *waiter) bool {\n+ return w.value == 0\n+ })\n+}\n+\n+// CountNegativeWaiters returns number of waiters waiting for the sem to go to zero.\n+func (s *Set) CountNegativeWaiters(num int32, creds *auth.Credentials) (uint16, error) {\n+ return s.countWaiters(num, creds, func(w *waiter) bool {\n+ return w.value < 0\n+ })\n}\n// ExecuteOps attempts to execute a list of operations to the set. It only\n@@ -598,11 +612,18 @@ func (s *Set) destroy() {\n}\n}\n+func abs(val int16) int16 {\n+ if val < 0 {\n+ return -val\n+ }\n+ return val\n+}\n+\n// wakeWaiters goes over all waiters and checks which of them can be notified.\nfunc (s *sem) wakeWaiters() {\n// Note that this will release all waiters waiting for 0 too.\nfor w := s.waiters.Front(); w != nil; {\n- if s.value < w.value {\n+ if s.value < abs(w.value) {\n// Still blocked, skip it.\nw = w.Next()\ncontinue\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/linux64.go",
"new_path": "pkg/sentry/syscalls/linux/linux64.go",
"diff": "@@ -118,7 +118,7 @@ var AMD64 = &kernel.SyscallTable{\n63: syscalls.Supported(\"uname\", Uname),\n64: syscalls.Supported(\"semget\", Semget),\n65: syscalls.PartiallySupported(\"semop\", Semop, \"Option SEM_UNDO not supported.\", nil),\n- 66: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options IPC_INFO, SEM_INFO, SEM_STAT, SEM_STAT_ANY, GETNCNT not supported.\", nil),\n+ 66: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options IPC_INFO, SEM_INFO, SEM_STAT, SEM_STAT_ANY not supported.\", nil),\n67: syscalls.Supported(\"shmdt\", Shmdt),\n68: syscalls.ErrorWithEvent(\"msgget\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n69: syscalls.ErrorWithEvent(\"msgsnd\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n@@ -619,7 +619,7 @@ var ARM64 = &kernel.SyscallTable{\n188: syscalls.ErrorWithEvent(\"msgrcv\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n189: syscalls.ErrorWithEvent(\"msgsnd\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n190: syscalls.Supported(\"semget\", Semget),\n- 191: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options IPC_INFO, SEM_INFO, SEM_STAT, SEM_STAT_ANY, GETNCNT not supported.\", nil),\n+ 191: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options IPC_INFO, SEM_INFO, SEM_STAT, SEM_STAT_ANY not supported.\", nil),\n192: syscalls.ErrorWithEvent(\"semtimedop\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/137\"}),\n193: syscalls.PartiallySupported(\"semop\", Semop, \"Option SEM_UNDO not supported.\", nil),\n194: syscalls.PartiallySupported(\"shmget\", Shmget, \"Option SHM_HUGETLB is not supported.\", nil),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_sem.go",
"new_path": "pkg/sentry/syscalls/linux/sys_sem.go",
"diff": "@@ -139,14 +139,17 @@ func Semctl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\nreturn 0, nil, err\ncase linux.GETZCNT:\n- v, err := getSemzcnt(t, id, num)\n+ v, err := getZCnt(t, id, num)\n+ return uintptr(v), nil, err\n+\n+ case linux.GETNCNT:\n+ v, err := getNCnt(t, id, num)\nreturn uintptr(v), nil, err\ncase linux.IPC_INFO,\nlinux.SEM_INFO,\nlinux.SEM_STAT,\n- linux.SEM_STAT_ANY,\n- linux.GETNCNT:\n+ linux.SEM_STAT_ANY:\nt.Kernel().EmitUnimplementedEvent(t)\nfallthrough\n@@ -262,12 +265,22 @@ func getPID(t *kernel.Task, id int32, num int32) (int32, error) {\nreturn int32(tg.ID()), nil\n}\n-func getSemzcnt(t *kernel.Task, id int32, num int32) (uint16, error) {\n+func getZCnt(t *kernel.Task, id int32, num int32) (uint16, error) {\n+ r := t.IPCNamespace().SemaphoreRegistry()\n+ set := r.FindByID(id)\n+ if set == nil {\n+ return 0, syserror.EINVAL\n+ }\n+ creds := auth.CredentialsFromContext(t)\n+ return set.CountZeroWaiters(num, creds)\n+}\n+\n+func getNCnt(t *kernel.Task, id int32, num int32) (uint16, error) {\nr := t.IPCNamespace().SemaphoreRegistry()\nset := r.FindByID(id)\nif set == nil {\nreturn 0, syserror.EINVAL\n}\ncreds := auth.CredentialsFromContext(t)\n- return set.GetZeroWaiters(num, creds)\n+ return set.CountNegativeWaiters(num, creds)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/semaphore.cc",
"new_path": "test/syscalls/linux/semaphore.cc",
"diff": "@@ -543,14 +543,14 @@ TEST(SemaphoreTest, SemCtlIpcStat) {\nSyscallFailsWithErrno(EACCES));\n}\n-// Calls semctl(GETZCNT) until the returned value is >= target, an internal\n-// timeout expires, or semctl returns an error.\n-PosixErrorOr<int> WaitSemzcnt(int semid, int target) {\n+// Calls semctl(semid, 0, cmd) until the returned value is >= target, an\n+// internal timeout expires, or semctl returns an error.\n+PosixErrorOr<int> WaitSemctl(int semid, int target, int cmd) {\nconstexpr absl::Duration timeout = absl::Seconds(10);\nconst auto deadline = absl::Now() + timeout;\nint semcnt = 0;\nwhile (absl::Now() < deadline) {\n- semcnt = semctl(semid, 0, GETZCNT);\n+ semcnt = semctl(semid, 0, cmd);\nif (semcnt < 0) {\nreturn PosixError(errno, \"semctl(GETZCNT) failed\");\n}\n@@ -594,7 +594,9 @@ TEST(SemaphoreTest, SemopGetzcnt) {\n}\nchildren.push_back(child_pid);\n}\n- EXPECT_THAT(WaitSemzcnt(sem.get(), kLoops), IsPosixErrorOkAndHolds(kLoops));\n+\n+ EXPECT_THAT(WaitSemctl(sem.get(), kLoops, GETZCNT),\n+ IsPosixErrorOkAndHolds(kLoops));\n// Set semval to 0, which wakes up children that sleep on the semop.\nASSERT_THAT(semctl(sem.get(), 0, SETVAL, 0), SyscallSucceeds());\nfor (const auto& child_pid : children) {\n@@ -625,7 +627,7 @@ TEST(SemaphoreTest, SemopGetzcntOnSetRemoval) {\n_exit(0);\n}\n- EXPECT_THAT(WaitSemzcnt(semid, 1), IsPosixErrorOkAndHolds(1));\n+ EXPECT_THAT(WaitSemctl(semid, 1, GETZCNT), IsPosixErrorOkAndHolds(1));\n// Remove the semaphore set, which fails the sleep semop.\nASSERT_THAT(semctl(semid, 0, IPC_RMID), SyscallSucceeds());\nint status;\n@@ -654,7 +656,8 @@ TEST(SemaphoreTest, SemopGetzcntOnSignal_NoRandomSave) {\nTEST_PCHECK(semop(sem.get(), &buf, 1) < 0 && errno == EINTR);\n_exit(0);\n}\n- EXPECT_THAT(WaitSemzcnt(sem.get(), 1), IsPosixErrorOkAndHolds(1));\n+\n+ EXPECT_THAT(WaitSemctl(sem.get(), 1, GETZCNT), IsPosixErrorOkAndHolds(1));\n// Send a signal to the child, which fails the sleep semop.\nASSERT_EQ(kill(child_pid, SIGHUP), 0);\n@@ -667,6 +670,109 @@ TEST(SemaphoreTest, SemopGetzcntOnSignal_NoRandomSave) {\nEXPECT_EQ(semctl(sem.get(), 0, GETZCNT), 0);\n}\n+TEST(SemaphoreTest, SemopGetncnt) {\n+ // Drop CAP_IPC_OWNER which allows us to bypass semaphore permissions.\n+ ASSERT_NO_ERRNO(SetCapability(CAP_IPC_OWNER, false));\n+ // Create a write only semaphore set.\n+ AutoSem sem(semget(IPC_PRIVATE, 1, 0200 | IPC_CREAT));\n+ ASSERT_THAT(sem.get(), SyscallSucceeds());\n+\n+ // No read permission to retrieve semzcnt.\n+ EXPECT_THAT(semctl(sem.get(), 0, GETNCNT), SyscallFailsWithErrno(EACCES));\n+\n+ // Remove the calling thread's read permission.\n+ struct semid_ds ds = {};\n+ ds.sem_perm.uid = getuid();\n+ ds.sem_perm.gid = getgid();\n+ ds.sem_perm.mode = 0600;\n+ ASSERT_THAT(semctl(sem.get(), 0, IPC_SET, &ds), SyscallSucceeds());\n+\n+ std::vector<pid_t> children;\n+\n+ struct sembuf buf = {};\n+ buf.sem_num = 0;\n+ buf.sem_op = -1;\n+ constexpr size_t kLoops = 10;\n+ for (auto i = 0; i < kLoops; i++) {\n+ auto child_pid = fork();\n+ if (child_pid == 0) {\n+ TEST_PCHECK(RetryEINTR(semop)(sem.get(), &buf, 1) == 0);\n+ _exit(0);\n+ }\n+ children.push_back(child_pid);\n+ }\n+ EXPECT_THAT(WaitSemctl(sem.get(), kLoops, GETNCNT),\n+ IsPosixErrorOkAndHolds(kLoops));\n+ // Set semval to 1, which wakes up children that sleep on the semop.\n+ ASSERT_THAT(semctl(sem.get(), 0, SETVAL, kLoops), SyscallSucceeds());\n+ for (const auto& child_pid : children) {\n+ int status;\n+ ASSERT_THAT(RetryEINTR(waitpid)(child_pid, &status, 0),\n+ SyscallSucceedsWithValue(child_pid));\n+ EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0);\n+ }\n+ EXPECT_EQ(semctl(sem.get(), 0, GETNCNT), 0);\n+}\n+\n+TEST(SemaphoreTest, SemopGetncntOnSetRemoval) {\n+ auto semid = semget(IPC_PRIVATE, 1, 0600 | IPC_CREAT);\n+ ASSERT_THAT(semid, SyscallSucceeds());\n+ ASSERT_EQ(semctl(semid, 0, GETNCNT), 0);\n+\n+ auto child_pid = fork();\n+ if (child_pid == 0) {\n+ struct sembuf buf = {};\n+ buf.sem_num = 0;\n+ buf.sem_op = -1;\n+\n+ // Ensure that wait will only unblock when the semaphore is removed. On\n+ // EINTR retry it may race with deletion and return EINVAL\n+ TEST_PCHECK(RetryEINTR(semop)(semid, &buf, 1) < 0 &&\n+ (errno == EIDRM || errno == EINVAL));\n+ _exit(0);\n+ }\n+\n+ EXPECT_THAT(WaitSemctl(semid, 1, GETNCNT), IsPosixErrorOkAndHolds(1));\n+ // Remove the semaphore set, which fails the sleep semop.\n+ ASSERT_THAT(semctl(semid, 0, IPC_RMID), SyscallSucceeds());\n+ int status;\n+ ASSERT_THAT(RetryEINTR(waitpid)(child_pid, &status, 0),\n+ SyscallSucceedsWithValue(child_pid));\n+ EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0);\n+ EXPECT_THAT(semctl(semid, 0, GETNCNT), SyscallFailsWithErrno(EINVAL));\n+}\n+\n+TEST(SemaphoreTest, SemopGetncntOnSignal_NoRandomSave) {\n+ AutoSem sem(semget(IPC_PRIVATE, 1, 0600 | IPC_CREAT));\n+ ASSERT_THAT(sem.get(), SyscallSucceeds());\n+ ASSERT_EQ(semctl(sem.get(), 0, GETNCNT), 0);\n+\n+ // Saving will cause semop() to be spuriously interrupted.\n+ DisableSave ds;\n+\n+ auto child_pid = fork();\n+ if (child_pid == 0) {\n+ TEST_PCHECK(signal(SIGHUP, [](int sig) -> void {}) != SIG_ERR);\n+ struct sembuf buf = {};\n+ buf.sem_num = 0;\n+ buf.sem_op = -1;\n+\n+ TEST_PCHECK(semop(sem.get(), &buf, 1) < 0 && errno == EINTR);\n+ _exit(0);\n+ }\n+ EXPECT_THAT(WaitSemctl(sem.get(), 1, GETNCNT), IsPosixErrorOkAndHolds(1));\n+ // Send a signal to the child, which fails the sleep semop.\n+ ASSERT_EQ(kill(child_pid, SIGHUP), 0);\n+\n+ ds.reset();\n+\n+ int status;\n+ ASSERT_THAT(RetryEINTR(waitpid)(child_pid, &status, 0),\n+ SyscallSucceedsWithValue(child_pid));\n+ EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0);\n+ EXPECT_EQ(semctl(sem.get(), 0, GETNCNT), 0);\n+}\n+\n} // namespace\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement command GETNCNT for semctl.
PiperOrigin-RevId: 341154192 |
259,907 | 06.11.2020 18:50:33 | 28,800 | fe9442d3270d14c095932d917e4e53e706866217 | [vfs] Return EEXIST when file already exists and rp.MustBeDir() is true.
This is consistent with what Linux does. This was causing a PHP runtime test
failure. Fixed it for VFS2. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"new_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"diff": "@@ -371,9 +371,6 @@ func (fs *filesystem) doCreateAt(ctx context.Context, rp *vfs.ResolvingPath, dir\nif len(name) > maxFilenameLen {\nreturn syserror.ENAMETOOLONG\n}\n- if !dir && rp.MustBeDir() {\n- return syserror.ENOENT\n- }\nif parent.isDeleted() {\nreturn syserror.ENOENT\n}\n@@ -388,6 +385,9 @@ func (fs *filesystem) doCreateAt(ctx context.Context, rp *vfs.ResolvingPath, dir\nif child := parent.children[name]; child != nil {\nreturn syserror.EEXIST\n}\n+ if !dir && rp.MustBeDir() {\n+ return syserror.ENOENT\n+ }\nif createInSyntheticDir == nil {\nreturn syserror.EPERM\n}\n@@ -407,6 +407,9 @@ func (fs *filesystem) doCreateAt(ctx context.Context, rp *vfs.ResolvingPath, dir\nif child := parent.children[name]; child != nil && child.isSynthetic() {\nreturn syserror.EEXIST\n}\n+ if !dir && rp.MustBeDir() {\n+ return syserror.ENOENT\n+ }\n// The existence of a non-synthetic dentry at name would be inconclusive\n// because the file it represents may have been deleted from the remote\n// filesystem, so we would need to make an RPC to revalidate the dentry.\n@@ -427,6 +430,9 @@ func (fs *filesystem) doCreateAt(ctx context.Context, rp *vfs.ResolvingPath, dir\nif child := parent.children[name]; child != nil {\nreturn syserror.EEXIST\n}\n+ if !dir && rp.MustBeDir() {\n+ return syserror.ENOENT\n+ }\n// No cached dentry exists; however, there might still be an existing file\n// at name. As above, we attempt the file creation RPC anyway.\nif err := createInRemoteDir(parent, name, &ds); err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go",
"diff": "@@ -355,6 +355,9 @@ func (fs *Filesystem) LinkAt(ctx context.Context, rp *vfs.ResolvingPath, vd vfs.\nif err := checkCreateLocked(ctx, rp.Credentials(), pc, parent); err != nil {\nreturn err\n}\n+ if rp.MustBeDir() {\n+ return syserror.ENOENT\n+ }\nif rp.Mount() != vd.Mount() {\nreturn syserror.EXDEV\n}\n@@ -433,6 +436,9 @@ func (fs *Filesystem) MknodAt(ctx context.Context, rp *vfs.ResolvingPath, opts v\nif err := checkCreateLocked(ctx, rp.Credentials(), pc, parent); err != nil {\nreturn err\n}\n+ if rp.MustBeDir() {\n+ return syserror.ENOENT\n+ }\nif err := rp.Mount().CheckBeginWrite(); err != nil {\nreturn err\n}\n@@ -825,6 +831,9 @@ func (fs *Filesystem) SymlinkAt(ctx context.Context, rp *vfs.ResolvingPath, targ\nif err := checkCreateLocked(ctx, rp.Credentials(), pc, parent); err != nil {\nreturn err\n}\n+ if rp.MustBeDir() {\n+ return syserror.ENOENT\n+ }\nif err := rp.Mount().CheckBeginWrite(); err != nil {\nreturn err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/overlay/filesystem.go",
"new_path": "pkg/sentry/fsimpl/overlay/filesystem.go",
"diff": "@@ -477,9 +477,6 @@ func (fs *filesystem) doCreateAt(ctx context.Context, rp *vfs.ResolvingPath, dir\nif name == \".\" || name == \"..\" {\nreturn syserror.EEXIST\n}\n- if !dir && rp.MustBeDir() {\n- return syserror.ENOENT\n- }\nif parent.vfsd.IsDead() {\nreturn syserror.ENOENT\n}\n@@ -503,6 +500,10 @@ func (fs *filesystem) doCreateAt(ctx context.Context, rp *vfs.ResolvingPath, dir\nreturn syserror.EEXIST\n}\n+ if !dir && rp.MustBeDir() {\n+ return syserror.ENOENT\n+ }\n+\n// Ensure that the parent directory is copied-up so that we can create the\n// new file in the upper layer.\nif err := parent.copyUpLocked(ctx); err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/runtimes/exclude/php7.3.6.csv",
"new_path": "test/runtimes/exclude/php7.3.6.csv",
"diff": "@@ -30,7 +30,7 @@ ext/standard/tests/file/php_fd_wrapper_04.phpt,,\next/standard/tests/file/realpath_bug77484.phpt,b/162894969,VFS1 only failure\next/standard/tests/file/rename_variation.phpt,b/68717309,\next/standard/tests/file/symlink_link_linkinfo_is_link_variation4.phpt,b/162895341,\n-ext/standard/tests/file/symlink_link_linkinfo_is_link_variation8.phpt,b/162896223,\n+ext/standard/tests/file/symlink_link_linkinfo_is_link_variation8.phpt,b/162896223,VFS1 only failure\next/standard/tests/general_functions/escapeshellarg_bug71270.phpt,,\next/standard/tests/general_functions/escapeshellcmd_bug71270.phpt,,\next/standard/tests/streams/proc_open_bug60120.phpt,,Flaky until php-src 3852a35fdbcb\n"
},
{
"change_type": "MODIFY",
"old_path": "test/runtimes/runner/lib/lib.go",
"new_path": "test/runtimes/runner/lib/lib.go",
"diff": "@@ -40,7 +40,10 @@ func RunTests(lang, image, excludeFile string, partitionNum, totalPartitions, ba\nreturn 1\n}\n- // Get tests to exclude..\n+ // TODO(gvisor.dev/issue/1624): Remove those tests from all exclude lists\n+ // that only fail with VFS1.\n+\n+ // Get tests to exclude.\nexcludes, err := getExcludes(excludeFile)\nif err != nil {\nfmt.Fprintf(os.Stderr, \"Error getting exclude list: %s\\n\", err.Error())\n"
}
] | Go | Apache License 2.0 | google/gvisor | [vfs] Return EEXIST when file already exists and rp.MustBeDir() is true.
This is consistent with what Linux does. This was causing a PHP runtime test
failure. Fixed it for VFS2.
PiperOrigin-RevId: 341155209 |
259,885 | 06.11.2020 23:20:08 | 28,800 | 78cce3a46b953cab00731f8afacf7e9e7f4dc751 | Allow VFS2 gofer.dentries to have separate read and write FDs.
This is necessary to allow writes to files opened with O_WRONLY to go through
host FDs. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/directory.go",
"new_path": "pkg/sentry/fsimpl/gofer/directory.go",
"diff": "@@ -98,7 +98,9 @@ func (d *dentry) createSyntheticChildLocked(opts *createSyntheticOpts) {\nuid: uint32(opts.kuid),\ngid: uint32(opts.kgid),\nblockSize: usermem.PageSize, // arbitrary\n- hostFD: -1,\n+ readFD: -1,\n+ writeFD: -1,\n+ mmapFD: -1,\nnlink: uint32(2),\n}\nrefsvfs2.Register(child)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"new_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"diff": "@@ -1167,18 +1167,21 @@ func (d *dentry) createAndOpenChildLocked(ctx context.Context, rp *vfs.Resolving\n// Incorporate the fid that was opened by lcreate.\nuseRegularFileFD := child.fileType() == linux.S_IFREG && !d.fs.opts.regularFilesUseSpecialFileFD\nif useRegularFileFD {\n+ openFD := int32(-1)\n+ if fdobj != nil {\n+ openFD = int32(fdobj.Release())\n+ }\nchild.handleMu.Lock()\nif vfs.MayReadFileWithOpenFlags(opts.Flags) {\nchild.readFile = openFile\nif fdobj != nil {\n- child.hostFD = int32(fdobj.Release())\n+ child.readFD = openFD\n+ child.mmapFD = openFD\n}\n- } else if fdobj != nil {\n- // Can't use fdobj if it's not readable.\n- fdobj.Close()\n}\nif vfs.MayWriteFileWithOpenFlags(opts.Flags) {\nchild.writeFile = openFile\n+ child.writeFD = openFD\n}\nchild.handleMu.Unlock()\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"diff": "@@ -548,11 +548,16 @@ func (fs *filesystem) Release(ctx context.Context) {\nd.cache.DropAll(mf)\nd.dirty.RemoveAll()\nd.dataMu.Unlock()\n- // Close the host fd if one exists.\n- if d.hostFD >= 0 {\n- syscall.Close(int(d.hostFD))\n- d.hostFD = -1\n+ // Close host FDs if they exist.\n+ if d.readFD >= 0 {\n+ syscall.Close(int(d.readFD))\n}\n+ if d.writeFD >= 0 && d.readFD != d.writeFD {\n+ syscall.Close(int(d.writeFD))\n+ }\n+ d.readFD = -1\n+ d.writeFD = -1\n+ d.mmapFD = -1\nd.handleMu.Unlock()\n}\n// There can't be any specialFileFDs still using fs, since each such\n@@ -726,15 +731,17 @@ type dentry struct {\n// - If this dentry represents a regular file or directory, readFile is the\n// p9.File used for reads by all regularFileFDs/directoryFDs representing\n- // this dentry.\n+ // this dentry, and readFD (if not -1) is a host FD equivalent to readFile\n+ // used as a faster alternative.\n//\n// - If this dentry represents a regular file, writeFile is the p9.File\n- // used for writes by all regularFileFDs representing this dentry.\n+ // used for writes by all regularFileFDs representing this dentry, and\n+ // writeFD (if not -1) is a host FD equivalent to writeFile used as a\n+ // faster alternative.\n//\n- // - If this dentry represents a regular file, hostFD is the host FD used\n- // for memory mappings and I/O (when applicable) in preference to readFile\n- // and writeFile. hostFD is always readable; if !writeFile.isNil(), it must\n- // also be writable. If hostFD is -1, no such host FD is available.\n+ // - If this dentry represents a regular file, mmapFD is the host FD used\n+ // for memory mappings. If mmapFD is -1, no such FD is available, and the\n+ // internal page cache implementation is used for memory mappings instead.\n//\n// These fields are protected by handleMu.\n//\n@@ -742,10 +749,17 @@ type dentry struct {\n// either p9.File transitions from closed (isNil() == true) to open\n// (isNil() == false), it may be mutated with handleMu locked, but cannot\n// be closed until the dentry is destroyed.\n+ //\n+ // readFD and writeFD may or may not be the same file descriptor. mmapFD is\n+ // always either -1 or equal to readFD; if !writeFile.isNil() (the file has\n+ // been opened for writing), it is additionally either -1 or equal to\n+ // writeFD.\nhandleMu sync.RWMutex `state:\"nosave\"`\nreadFile p9file `state:\"nosave\"`\nwriteFile p9file `state:\"nosave\"`\n- hostFD int32 `state:\"nosave\"`\n+ readFD int32 `state:\"nosave\"`\n+ writeFD int32 `state:\"nosave\"`\n+ mmapFD int32 `state:\"nosave\"`\ndataMu sync.RWMutex `state:\"nosave\"`\n@@ -829,7 +843,9 @@ func (fs *filesystem) newDentry(ctx context.Context, file p9file, qid p9.QID, ma\nuid: uint32(fs.opts.dfltuid),\ngid: uint32(fs.opts.dfltgid),\nblockSize: usermem.PageSize,\n- hostFD: -1,\n+ readFD: -1,\n+ writeFD: -1,\n+ mmapFD: -1,\n}\nd.pf.dentry = d\nif mask.UID {\n@@ -1469,10 +1485,15 @@ func (d *dentry) destroyLocked(ctx context.Context) {\n}\nd.readFile = p9file{}\nd.writeFile = p9file{}\n- if d.hostFD >= 0 {\n- syscall.Close(int(d.hostFD))\n- d.hostFD = -1\n+ if d.readFD >= 0 {\n+ syscall.Close(int(d.readFD))\n}\n+ if d.writeFD >= 0 && d.readFD != d.writeFD {\n+ syscall.Close(int(d.writeFD))\n+ }\n+ d.readFD = -1\n+ d.writeFD = -1\n+ d.mmapFD = -1\nd.handleMu.Unlock()\nif !d.file.isNil() {\n@@ -1584,7 +1605,8 @@ func (d *dentry) ensureSharedHandle(ctx context.Context, read, write, trunc bool\nd.handleMu.RUnlock()\n}\n- fdToClose := int32(-1)\n+ var fdsToCloseArr [2]int32\n+ fdsToClose := fdsToCloseArr[:0]\ninvalidateTranslations := false\nd.handleMu.Lock()\nif (read && d.readFile.isNil()) || (write && d.writeFile.isNil()) || trunc {\n@@ -1615,56 +1637,88 @@ func (d *dentry) ensureSharedHandle(ctx context.Context, read, write, trunc bool\nreturn err\n}\n- if d.hostFD < 0 && h.fd >= 0 && openReadable && (d.writeFile.isNil() || openWritable) {\n- // We have no existing FD, and the new FD meets the requirements\n- // for d.hostFD, so start using it.\n- d.hostFD = h.fd\n- } else if d.hostFD >= 0 && d.writeFile.isNil() && openWritable {\n- // We have an existing read-only FD, but the file has just been\n- // opened for writing, so we need to start supporting writable memory\n- // mappings. This may race with callers of d.pf.FD() using the existing\n- // FD, so in most cases we need to delay closing the old FD until after\n- // invalidating memmap.Translations that might have observed it.\n- if !openReadable || h.fd < 0 {\n- // We don't have a read/write FD, so we have no FD that can be\n- // used to create writable memory mappings. Switch to using the\n- // internal page cache.\n- invalidateTranslations = true\n- fdToClose = d.hostFD\n- d.hostFD = -1\n- } else if d.fs.opts.overlayfsStaleRead {\n- // We do have a read/write FD, but it may not be coherent with\n- // the existing read-only FD, so we must switch to mappings of\n- // the new FD in both the application and sentry.\n+ // Update d.readFD and d.writeFD.\n+ if h.fd >= 0 {\n+ if openReadable && openWritable && (d.readFD < 0 || d.writeFD < 0 || d.readFD != d.writeFD) {\n+ // Replace existing FDs with this one.\n+ if d.readFD >= 0 {\n+ // We already have a readable FD that may be in use by\n+ // concurrent callers of d.pf.FD().\n+ if d.fs.opts.overlayfsStaleRead {\n+ // If overlayfsStaleRead is in effect, then the new FD\n+ // may not be coherent with the existing one, so we\n+ // have no choice but to switch to mappings of the new\n+ // FD in both the application and sentry.\nif err := d.pf.hostFileMapper.RegenerateMappings(int(h.fd)); err != nil {\nd.handleMu.Unlock()\nctx.Warningf(\"gofer.dentry.ensureSharedHandle: failed to replace sentry mappings of old FD with mappings of new FD: %v\", err)\nh.close(ctx)\nreturn err\n}\n+ fdsToClose = append(fdsToClose, d.readFD)\ninvalidateTranslations = true\n- fdToClose = d.hostFD\n- d.hostFD = h.fd\n+ d.readFD = h.fd\n} else {\n- // We do have a read/write FD. To avoid invalidating existing\n- // memmap.Translations (which is expensive), use dup3 to make\n- // the old file descriptor refer to the new file description,\n- // then close the new file descriptor (which is no longer\n- // needed). Racing callers of d.pf.FD() may use the old or new\n- // file description, but this doesn't matter since they refer\n- // to the same file, and any racing mappings must be read-only.\n- if err := syscall.Dup3(int(h.fd), int(d.hostFD), syscall.O_CLOEXEC); err != nil {\n- oldHostFD := d.hostFD\n+ // Otherwise, we want to avoid invalidating existing\n+ // memmap.Translations (which is expensive); instead, use\n+ // dup3 to make the old file descriptor refer to the new\n+ // file description, then close the new file descriptor\n+ // (which is no longer needed). Racing callers of d.pf.FD()\n+ // may use the old or new file description, but this\n+ // doesn't matter since they refer to the same file, and\n+ // any racing mappings must be read-only.\n+ if err := syscall.Dup3(int(h.fd), int(d.readFD), syscall.O_CLOEXEC); err != nil {\n+ oldFD := d.readFD\nd.handleMu.Unlock()\n- ctx.Warningf(\"gofer.dentry.ensureSharedHandle: failed to dup fd %d to fd %d: %v\", h.fd, oldHostFD, err)\n+ ctx.Warningf(\"gofer.dentry.ensureSharedHandle: failed to dup fd %d to fd %d: %v\", h.fd, oldFD, err)\nh.close(ctx)\nreturn err\n}\n- fdToClose = h.fd\n+ fdsToClose = append(fdsToClose, h.fd)\n+ h.fd = d.readFD\n+ }\n+ } else {\n+ d.readFD = h.fd\n+ }\n+ if d.writeFD != h.fd && d.writeFD >= 0 {\n+ fdsToClose = append(fdsToClose, d.writeFD)\n+ }\n+ d.writeFD = h.fd\n+ d.mmapFD = h.fd\n+ } else if openReadable && d.readFD < 0 {\n+ d.readFD = h.fd\n+ // If the file has not been opened for writing, the new FD may\n+ // be used for read-only memory mappings. If the file was\n+ // previously opened for reading (without an FD), then existing\n+ // translations of the file may use the internal page cache;\n+ // invalidate those mappings.\n+ if d.writeFile.isNil() {\n+ invalidateTranslations = !d.readFile.isNil()\n+ d.mmapFD = h.fd\n+ }\n+ } else if openWritable && d.writeFD < 0 {\n+ d.writeFD = h.fd\n+ if d.readFD >= 0 {\n+ // We have an existing read-only FD, but the file has just\n+ // been opened for writing, so we need to start supporting\n+ // writable memory mappings. However, the new FD is not\n+ // readable, so we have no FD that can be used to create\n+ // writable memory mappings. Switch to using the internal\n+ // page cache.\n+ invalidateTranslations = true\n+ d.mmapFD = -1\n}\n} else {\n- // h.fd is not useful.\n- fdToClose = h.fd\n+ // The new FD is not useful.\n+ fdsToClose = append(fdsToClose, h.fd)\n+ }\n+ } else if openWritable && d.writeFD < 0 && d.mmapFD >= 0 {\n+ // We have an existing read-only FD, but the file has just been\n+ // opened for writing, so we need to start supporting writable\n+ // memory mappings. However, we have no writable host FD. Switch to\n+ // using the internal page cache.\n+ invalidateTranslations = true\n+ d.mmapFD = -1\n}\n// Switch to new fids.\n@@ -1698,8 +1752,8 @@ func (d *dentry) ensureSharedHandle(ctx context.Context, read, write, trunc bool\nd.mappings.InvalidateAll(memmap.InvalidateOpts{})\nd.mapsMu.Unlock()\n}\n- if fdToClose >= 0 {\n- syscall.Close(int(fdToClose))\n+ for _, fd := range fdsToClose {\n+ syscall.Close(int(fd))\n}\nreturn nil\n@@ -1709,7 +1763,7 @@ func (d *dentry) ensureSharedHandle(ctx context.Context, read, write, trunc bool\nfunc (d *dentry) readHandleLocked() handle {\nreturn handle{\nfile: d.readFile,\n- fd: d.hostFD,\n+ fd: d.readFD,\n}\n}\n@@ -1717,7 +1771,7 @@ func (d *dentry) readHandleLocked() handle {\nfunc (d *dentry) writeHandleLocked() handle {\nreturn handle{\nfile: d.writeFile,\n- fd: d.hostFD,\n+ fd: d.writeFD,\n}\n}\n@@ -1730,16 +1784,24 @@ func (d *dentry) syncRemoteFile(ctx context.Context) error {\n// Preconditions: d.handleMu must be locked.\nfunc (d *dentry) syncRemoteFileLocked(ctx context.Context) error {\n// If we have a host FD, fsyncing it is likely to be faster than an fsync\n- // RPC.\n- if d.hostFD >= 0 {\n+ // RPC. Prefer syncing write handles over read handles, since some remote\n+ // filesystem implementations may not sync changes made through write\n+ // handles otherwise.\n+ if d.writeFD >= 0 {\nctx.UninterruptibleSleepStart(false)\n- err := syscall.Fsync(int(d.hostFD))\n+ err := syscall.Fsync(int(d.writeFD))\nctx.UninterruptibleSleepFinish(false)\nreturn err\n}\nif !d.writeFile.isNil() {\nreturn d.writeFile.fsync(ctx)\n}\n+ if d.readFD >= 0 {\n+ ctx.UninterruptibleSleepStart(false)\n+ err := syscall.Fsync(int(d.readFD))\n+ ctx.UninterruptibleSleepFinish(false)\n+ return err\n+ }\nif !d.readFile.isNil() {\nreturn d.readFile.fsync(ctx)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/regular_file.go",
"new_path": "pkg/sentry/fsimpl/gofer/regular_file.go",
"diff": "@@ -326,7 +326,7 @@ func (rw *dentryReadWriter) ReadToBlocks(dsts safemem.BlockSeq) (uint64, error)\n// dentry.readHandleLocked() without locking dentry.dataMu.\nrw.d.handleMu.RLock()\nh := rw.d.readHandleLocked()\n- if (rw.d.hostFD >= 0 && !rw.d.fs.opts.forcePageCache) || rw.d.fs.opts.interop == InteropModeShared || rw.direct {\n+ if (rw.d.mmapFD >= 0 && !rw.d.fs.opts.forcePageCache) || rw.d.fs.opts.interop == InteropModeShared || rw.direct {\nn, err := h.readToBlocksAt(rw.ctx, dsts, rw.off)\nrw.d.handleMu.RUnlock()\nrw.off += n\n@@ -446,7 +446,7 @@ func (rw *dentryReadWriter) WriteFromBlocks(srcs safemem.BlockSeq) (uint64, erro\n// without locking dentry.dataMu.\nrw.d.handleMu.RLock()\nh := rw.d.writeHandleLocked()\n- if (rw.d.hostFD >= 0 && !rw.d.fs.opts.forcePageCache) || rw.d.fs.opts.interop == InteropModeShared || rw.direct {\n+ if (rw.d.mmapFD >= 0 && !rw.d.fs.opts.forcePageCache) || rw.d.fs.opts.interop == InteropModeShared || rw.direct {\nn, err := h.writeFromBlocksAt(rw.ctx, srcs, rw.off)\nrw.off += n\nrw.d.dataMu.Lock()\n@@ -648,7 +648,7 @@ func (fd *regularFileFD) ConfigureMMap(ctx context.Context, opts *memmap.MMapOpt\nreturn syserror.ENODEV\n}\nd.handleMu.RLock()\n- haveFD := d.hostFD >= 0\n+ haveFD := d.mmapFD >= 0\nd.handleMu.RUnlock()\nif !haveFD {\nreturn syserror.ENODEV\n@@ -669,7 +669,7 @@ func (d *dentry) mayCachePages() bool {\nreturn true\n}\nd.handleMu.RLock()\n- haveFD := d.hostFD >= 0\n+ haveFD := d.mmapFD >= 0\nd.handleMu.RUnlock()\nreturn haveFD\n}\n@@ -727,7 +727,7 @@ func (d *dentry) CopyMapping(ctx context.Context, ms memmap.MappingSpace, srcAR,\n// Translate implements memmap.Mappable.Translate.\nfunc (d *dentry) Translate(ctx context.Context, required, optional memmap.MappableRange, at usermem.AccessType) ([]memmap.Translation, error) {\nd.handleMu.RLock()\n- if d.hostFD >= 0 && !d.fs.opts.forcePageCache {\n+ if d.mmapFD >= 0 && !d.fs.opts.forcePageCache {\nd.handleMu.RUnlock()\nmr := optional\nif d.fs.opts.limitHostFDTranslation {\n@@ -881,7 +881,7 @@ func (d *dentry) Evict(ctx context.Context, er pgalloc.EvictableRange) {\n// cannot implement both vfs.DentryImpl.IncRef and memmap.File.IncRef.\n//\n// dentryPlatformFile is only used when a host FD representing the remote file\n-// is available (i.e. dentry.hostFD >= 0), and that FD is used for application\n+// is available (i.e. dentry.mmapFD >= 0), and that FD is used for application\n// memory mappings (i.e. !filesystem.opts.forcePageCache).\n//\n// +stateify savable\n@@ -892,8 +892,8 @@ type dentryPlatformFile struct {\n// by dentry.dataMu.\nfdRefs fsutil.FrameRefSet\n- // If this dentry represents a regular file, and dentry.hostFD >= 0,\n- // hostFileMapper caches mappings of dentry.hostFD.\n+ // If this dentry represents a regular file, and dentry.mmapFD >= 0,\n+ // hostFileMapper caches mappings of dentry.mmapFD.\nhostFileMapper fsutil.HostFileMapper\n// hostFileMapperInitOnce is used to lazily initialize hostFileMapper.\n@@ -918,12 +918,12 @@ func (d *dentryPlatformFile) DecRef(fr memmap.FileRange) {\nfunc (d *dentryPlatformFile) MapInternal(fr memmap.FileRange, at usermem.AccessType) (safemem.BlockSeq, error) {\nd.handleMu.RLock()\ndefer d.handleMu.RUnlock()\n- return d.hostFileMapper.MapInternal(fr, int(d.hostFD), at.Write)\n+ return d.hostFileMapper.MapInternal(fr, int(d.mmapFD), at.Write)\n}\n// FD implements memmap.File.FD.\nfunc (d *dentryPlatformFile) FD() int {\nd.handleMu.RLock()\ndefer d.handleMu.RUnlock()\n- return int(d.hostFD)\n+ return int(d.mmapFD)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/save_restore.go",
"new_path": "pkg/sentry/fsimpl/gofer/save_restore.go",
"diff": "@@ -139,7 +139,9 @@ func (d *dentry) beforeSave() {\n// afterLoad is invoked by stateify.\nfunc (d *dentry) afterLoad() {\n- d.hostFD = -1\n+ d.readFD = -1\n+ d.writeFD = -1\n+ d.mmapFD = -1\nif atomic.LoadInt64(&d.refs) != -1 {\nrefsvfs2.Register(d)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow VFS2 gofer.dentries to have separate read and write FDs.
This is necessary to allow writes to files opened with O_WRONLY to go through
host FDs.
PiperOrigin-RevId: 341174509 |
259,891 | 09.11.2020 10:48:16 | 28,800 | 16caaf79f8f85233c6921d1ee953f365007d7a68 | iptables: add documentation about enabing docker ipv6 | [
{
"change_type": "MODIFY",
"old_path": "test/iptables/README.md",
"new_path": "test/iptables/README.md",
"diff": "iptables tests are run via `make iptables-tests`.\n-iptables requires raw socket support, so you must add the `--net-raw=true` flag\n-to `/etc/docker/daemon.json` in order to use it.\n+iptables require some extra Docker configuration to work. Enable IPv6 in\n+`/etc/docker/daemon.json` (make sure to restart Docker if you change this file):\n+\n+```json\n+{\n+ \"experimental\": true,\n+ \"fixed-cidr-v6\": \"2001:db8:1::/64\",\n+ \"ipv6\": true,\n+ // Runtimes and other Docker config...\n+}\n+```\n+\n+And if you're running manually (i.e. not using the `make` target), you'll need\n+to:\n+\n+* Enable iptables via `modprobe iptables_filter && modprobe ip6table_filter`.\n+* Enable `--net-raw` in your chosen runtime in `/etc/docker/daemon.json` (make\n+ sure to restart Docker if you change this file).\n+\n+The resulting runtime should look something like this:\n+\n+```json\n+\"runsc\": {\n+ \"path\": \"/tmp/iptables/runsc\",\n+ \"runtimeArgs\": [\n+ \"--debug-log\",\n+ \"/tmp/iptables/logs/runsc.log.%TEST%.%TIMESTAMP%.%COMMAND%\",\n+ \"--net-raw\"\n+ ]\n+},\n+// ...\n+```\n## Test Structure\n"
}
] | Go | Apache License 2.0 | google/gvisor | iptables: add documentation about enabing docker ipv6
PiperOrigin-RevId: 341439435 |
259,853 | 09.11.2020 12:13:13 | 28,800 | cbca5b2edde0920309029a0c591f28ce65cdad70 | Print a debug message if /sys/kernel/debug/kcov is available
This will help to debug: | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/sys/sys.go",
"new_path": "pkg/sentry/fsimpl/sys/sys.go",
"diff": "@@ -23,6 +23,7 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/coverage\"\n+ \"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n@@ -126,6 +127,7 @@ func kernelDir(ctx context.Context, fs *filesystem, creds *auth.Credentials) ker\n// keep it in sys.\nvar children map[string]kernfs.Inode\nif coverage.KcovAvailable() {\n+ log.Debugf(\"Set up /sys/kernel/debug/kcov\")\nchildren = map[string]kernfs.Inode{\n\"debug\": fs.newDir(ctx, creds, linux.FileMode(0700), map[string]kernfs.Inode{\n\"kcov\": fs.newKcovFile(ctx, creds),\n"
}
] | Go | Apache License 2.0 | google/gvisor | Print a debug message if /sys/kernel/debug/kcov is available
This will help to debug:
https://syzkaller.appspot.com/bug?id=0d717bd7028dceeb4b38f09aab2841c398b41d81
PiperOrigin-RevId: 341458715 |
259,898 | 09.11.2020 13:14:23 | 28,800 | c59bdd18d521ebb3c8dedf03a6adfa56dd6245c7 | parameterize regexp in netdevs.ParseDevices | [
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/netdevs/netdevs.go",
"new_path": "test/packetimpact/netdevs/netdevs.go",
"diff": "@@ -43,14 +43,10 @@ var (\ninet6Line = regexp.MustCompile(`^\\s*inet6 ([0-9a-fA-F:/]+)`)\n)\n-// ParseDevices parses the output from `ip addr show` into a map from device\n-// name to information about the device.\n-//\n-// Note: if multiple IPv6 addresses are assigned to a device, the last address\n-// displayed by `ip addr show` will be used. This is fine for packetimpact\n-// because we will always only have at most one IPv6 address assigned to each\n-// device.\n-func ParseDevices(cmdOutput string) (map[string]DeviceInfo, error) {\n+// ParseDevicesWithRegex will parse the output with the given regexps to produce\n+// a map from device name to device information. It is assumed that deviceLine\n+// contains both a name and an ID.\n+func ParseDevicesWithRegex(cmdOutput string, deviceLine, linkLine, inetLine, inet6Line *regexp.Regexp) (map[string]DeviceInfo, error) {\nvar currentDevice string\nvar currentInfo DeviceInfo\ndeviceInfos := make(map[string]DeviceInfo)\n@@ -93,6 +89,17 @@ func ParseDevices(cmdOutput string) (map[string]DeviceInfo, error) {\nreturn deviceInfos, nil\n}\n+// ParseDevices parses the output from `ip addr show` into a map from device\n+// name to information about the device.\n+//\n+// Note: if multiple IPv6 addresses are assigned to a device, the last address\n+// displayed by `ip addr show` will be used. This is fine for packetimpact\n+// because we will always only have at most one IPv6 address assigned to each\n+// device.\n+func ParseDevices(cmdOutput string) (map[string]DeviceInfo, error) {\n+ return ParseDevicesWithRegex(cmdOutput, deviceLine, linkLine, inetLine, inet6Line)\n+}\n+\n// MACToIP converts the MAC address to an IPv6 link local address as described\n// in RFC 4291 page 20: https://tools.ietf.org/html/rfc4291#page-20\nfunc MACToIP(mac net.HardwareAddr) net.IP {\n"
}
] | Go | Apache License 2.0 | google/gvisor | parameterize regexp in netdevs.ParseDevices
PiperOrigin-RevId: 341470647 |
259,853 | 09.11.2020 13:55:28 | 28,800 | 2fcca60a7bf084a28e878941d9dcb47e11268cbd | net: connect to the ipv4 localhost returns ENETUNREACH if the address isn't set
cl/340002915 modified the code to return EADDRNOTAVAIL if connect
is called for a localhost address which isn't set.
But actually, Linux returns EADDRNOTAVAIL for ipv6 addresses and ENETUNREACH
for ipv4 addresses.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -1418,7 +1418,7 @@ func (s *Stack) FindRoute(id tcpip.NICID, localAddr, remoteAddr tcpip.Address, n\nif needRoute {\nreturn Route{}, tcpip.ErrNoRoute\n}\n- if isLoopback {\n+ if header.IsV6LoopbackAddress(remoteAddr) {\nreturn Route{}, tcpip.ErrBadLocalAddress\n}\nreturn Route{}, tcpip.ErrNetworkUnreachable\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ip_unbound_netlink.cc",
"new_path": "test/syscalls/linux/socket_ip_unbound_netlink.cc",
"diff": "@@ -92,7 +92,7 @@ TEST_P(IPv4UnboundSocketTest, ConnectToBadLocalAddress_NoRandomSave) {\nauto sock = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\nEXPECT_THAT(connect(sock->get(), reinterpret_cast<sockaddr*>(&addr.addr),\naddr.addr_len),\n- SyscallFailsWithErrno(EADDRNOTAVAIL));\n+ SyscallFailsWithErrno(ENETUNREACH));\n}\nINSTANTIATE_TEST_SUITE_P(IPUnboundSockets, IPv4UnboundSocketTest,\n"
}
] | Go | Apache License 2.0 | google/gvisor | net: connect to the ipv4 localhost returns ENETUNREACH if the address isn't set
cl/340002915 modified the code to return EADDRNOTAVAIL if connect
is called for a localhost address which isn't set.
But actually, Linux returns EADDRNOTAVAIL for ipv6 addresses and ENETUNREACH
for ipv4 addresses.
Updates #4735
PiperOrigin-RevId: 341479129 |
259,858 | 09.11.2020 19:11:12 | 28,800 | b2d5b71ecdf7a7e07210b74610b5432b6f93f38d | Evaluate T as a shell variable, not a Make variable. | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -276,7 +276,6 @@ containerd-tests: containerd-test-1.4.0-beta.0\n## BENCHMARKS_OFFICIAL - marks the data as official.\n## BENCHMARKS_PLATFORMS - platforms to run benchmarks (e.g. ptrace kvm).\n##\n-RUNTIME_ARGS := --net-raw --platform=ptrace\nBENCHMARKS_PROJECT := gvisor-benchmarks\nBENCHMARKS_DATASET := kokoro\nBENCHMARKS_TABLE := benchmarks\n@@ -284,6 +283,8 @@ BENCHMARKS_SUITE := start\nBENCHMARKS_UPLOAD := false\nBENCHMARKS_OFFICIAL := false\nBENCHMARKS_PLATFORMS := ptrace\n+BENCHMARKS_TARGETS := //test/benchmarks/base:base_test\n+BENCHMARKS_ARGS := -test.bench=.\ninit-benchmark-table: ## Initializes a BigQuery table with the benchmark schema\n## (see //tools/bigquery/bigquery.go). If the table alread exists, this is a noop.\n@@ -294,25 +295,25 @@ init-benchmark-table: ## Initializes a BigQuery table with the benchmark schema\nbenchmark-platforms: load-benchmarks-images ## Runs benchmarks for runc and all given platforms in BENCHMARK_PLATFORMS.\n$(call submake, run-benchmark RUNTIME=\"runc\")\n$(foreach PLATFORM,$(BENCHMARKS_PLATFORMS), \\\n- $(call submake,benchmark-platform RUNTIME=\"$(PLATFORM)\" RUNTIME_ARGS=\"--platform=$(PLATFORM) --net-raw --vfs2\") && \\\n- $(call submake,benchmark-platform RUNTIME=\"$(PLATFORM)_vfs1\" RUNTIME_ARGS=\"--platform=$(PLATFORM) --net-raw\"))\n+ $(call submake,install-runtime RUNTIME=\"$(PLATFORM)\" ARGS=\"--platform=$(PLATFORM) --vfs2\") && \\\n+ $(call submake,run-benchmark RUNTIME=\"$(PLATFORM)\") && \\\n+ $(call submake,install-runtime RUNTIME=\"$(PLATFORM)_vfs1\" ARGS=\"--platform=$(PLATFORM)\") && \\\n+ $(call submake,run-benchmark RUNTIME=\"$(PLATFORM)_vfs1\") && \\\n+ ) \\\n+ true\n.PHONY: benchmark-platforms\n-benchmark-platform: ## Installs a runtime with the given platform args.\n- @$(call submake,install-test-runtime ARGS=\"$(RUNTIME_ARGS)\")\n- @$(call submake, run-benchmark)\n-.PHONY: benchmark-platform\n-\nrun-benchmark: ## Runs single benchmark and optionally sends data to BigQuery.\n- $(eval T := $(shell mktemp /tmp/logs.$(RUNTIME).XXXXXX))\n- $(call submake,sudo TARGETS=\"$(TARGETS)\" ARGS=\"--runtime=$(RUNTIME) $(ARGS)\" | tee $(T))\n- @if [[ \"$(BENCHMARKS_UPLOAD)\" == \"true\" ]]; then \\\n- @$(call submake,run TARGETS=tools/parsers:parser ARGS=\"parse --file=$(T) \\\n+ @T=$$(mktemp logs.$(RUNTIME).XXXXXX); \\\n+ $(call submake,sudo TARGETS=\"$(BENCHMARKS_TARGETS)\" ARGS=\"--runtime=$(RUNTIME) $(BENCHMARKS_ARGS) | tee $$T\"); \\\n+ rc=$$?; \\\n+ if [[ \"$(BENCHMARKS_UPLOAD)\" == \"true\" ]]; then \\\n+ $(call submake,run TARGETS=tools/parsers:parser ARGS=\"parse --file=$$T \\\n--runtime=$(RUNTIME) --suite_name=$(BENCHMARKS_SUITE) \\\n--project=$(BENCHMARKS_PROJECT) --dataset=$(BENCHMARKS_DATASET) \\\n--table=$(BENCHMARKS_TABLE) --official=$(BENCHMARKS_OFFICIAL)\"); \\\n- fi;\n- rm -rf $T\n+ fi; \\\n+ rm -rf $$T; exit $$rc\n.PHONY: run-benchmark\n##\n@@ -427,13 +428,13 @@ dev: ## Installs a set of local runtimes. Requires sudo.\n@sudo systemctl restart docker\n.PHONY: dev\n-refresh: ## Refreshes the runtime binary (for development only). Must have called 'dev' or 'install-test-runtime' first.\n+refresh: ## Refreshes the runtime binary (for development only). Must have called 'dev' or 'install-runtime' first.\n@mkdir -p \"$(RUNTIME_DIR)\"\n@$(call submake,copy TARGETS=runsc DESTINATION=\"$(RUNTIME_BIN)\")\n.PHONY: refresh\n-install-test-runtime: ## Installs the runtime for testing. Requires sudo.\n- @$(call submake,refresh ARGS=\"--net-raw --TESTONLY-test-name-env=RUNSC_TEST_NAME --debug --strace --log-packets $(ARGS)\")\n+install-runtime: ## Installs the runtime for testing. Requires sudo.\n+ @$(call submake,refresh ARGS=\"--net-raw --TESTONLY-test-name-env=RUNSC_TEST_NAME $(ARGS)\")\n@$(call submake,configure RUNTIME_NAME=runsc)\n@$(call submake,configure RUNTIME_NAME=\"$(RUNTIME)\")\n@sudo systemctl restart docker\n@@ -441,9 +442,13 @@ install-test-runtime: ## Installs the runtime for testing. Requires sudo.\nsudo chmod 0755 /etc/docker && \\\nsudo chmod 0644 /etc/docker/daemon.json; \\\nfi\n+.PHONY: install-runtime\n+\n+install-test-runtime: ## Installs the runtime for testing with default args. Requires sudo.\n+ @$(call submake,install-runtime ARGS=\"--debug --strace --log-packets $(ARGS)\")\n.PHONY: install-test-runtime\n-configure: ## Configures a single runtime. Requires sudo. Typically called from dev or install-test-runtime.\n+configure: ## Configures a single runtime. Requires sudo. Typically called from dev or install-runtime.\n@sudo sudo \"$(RUNTIME_BIN)\" install --experimental=true --runtime=\"$(RUNTIME_NAME)\" -- --debug-log \"$(RUNTIME_LOGS)\" $(ARGS)\n@echo -e \"$(INFO) Installed runtime \\\"$(RUNTIME)\\\" @ $(RUNTIME_BIN)\"\n@echo -e \"$(INFO) Logs are in: $(RUNTIME_LOG_DIR)\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | Evaluate T as a shell variable, not a Make variable.
PiperOrigin-RevId: 341531230 |
260,024 | 09.11.2020 21:57:30 | 28,800 | 3b353ff0ef09caf53037a68a055418c7028557e7 | Additions to ICMP and IPv4 parsers
Teach ICMP.Parser/ToBytes to handle some non echo ICMP packets.
Teach IPv4.Parser that fragments only have a payload, not an upper layer.
Fix IPv4 and IPv6 reassembly tests to handle the change.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/layers.go",
"new_path": "test/packetimpact/testbench/layers.go",
"diff": "@@ -402,6 +402,10 @@ func parseIPv4(b []byte) (Layer, layerParser) {\nDstAddr: Address(h.DestinationAddress()),\n}\nvar nextParser layerParser\n+ // If it is a fragment, don't treat it as having a transport protocol.\n+ if h.FragmentOffset() != 0 || h.More() {\n+ return &ipv4, parsePayload\n+ }\nswitch h.TransportProtocol() {\ncase header.TCPProtocolNumber:\nnextParser = parseTCP\n@@ -709,12 +713,17 @@ func parseIPv6FragmentExtHdr(b []byte) (Layer, layerParser) {\nnextHeader := b[0]\nvar extHdr header.IPv6FragmentExtHdr\ncopy(extHdr[:], b[2:])\n- return &IPv6FragmentExtHdr{\n+ fragLayer := IPv6FragmentExtHdr{\nNextHeader: IPv6ExtHdrIdent(header.IPv6ExtensionHeaderIdentifier(nextHeader)),\nFragmentOffset: Uint16(extHdr.FragmentOffset()),\nMoreFragments: Bool(extHdr.More()),\nIdentification: Uint32(extHdr.ID()),\n- }, nextIPv6PayloadParser(nextHeader)\n+ }\n+ // If it is a fragment, we can't interpret it.\n+ if extHdr.FragmentOffset() != 0 || extHdr.More() {\n+ return &fragLayer, parsePayload\n+ }\n+ return &fragLayer, nextIPv6PayloadParser(nextHeader)\n}\nfunc (l *IPv6HopByHopOptionsExtHdr) length() int {\n@@ -861,26 +870,15 @@ func (l *ICMPv6) merge(other Layer) error {\nreturn mergeLayer(l, other)\n}\n-// ICMPv4Type is a helper routine that allocates a new header.ICMPv4Type value\n-// to store t and returns a pointer to it.\n-func ICMPv4Type(t header.ICMPv4Type) *header.ICMPv4Type {\n- return &t\n-}\n-\n-// ICMPv4Code is a helper routine that allocates a new header.ICMPv4Code value\n-// to store t and returns a pointer to it.\n-func ICMPv4Code(t header.ICMPv4Code) *header.ICMPv4Code {\n- return &t\n-}\n-\n// ICMPv4 can construct and match an ICMPv4 encapsulation.\ntype ICMPv4 struct {\nLayerBase\nType *header.ICMPv4Type\nCode *header.ICMPv4Code\nChecksum *uint16\n- Ident *uint16\n- Sequence *uint16\n+ Ident *uint16 // Only in Echo Request/Reply.\n+ Sequence *uint16 // Only in Echo Request/Reply.\n+ Pointer *uint8 // Only in Parameter Problem.\nPayload []byte\n}\n@@ -888,6 +886,18 @@ func (l *ICMPv4) String() string {\nreturn stringLayer(l)\n}\n+// ICMPv4Type is a helper routine that allocates a new header.ICMPv4Type value\n+// to store t and returns a pointer to it.\n+func ICMPv4Type(t header.ICMPv4Type) *header.ICMPv4Type {\n+ return &t\n+}\n+\n+// ICMPv4Code is a helper routine that allocates a new header.ICMPv4Code value\n+// to store t and returns a pointer to it.\n+func ICMPv4Code(t header.ICMPv4Code) *header.ICMPv4Code {\n+ return &t\n+}\n+\n// ToBytes implements Layer.ToBytes.\nfunc (l *ICMPv4) ToBytes() ([]byte, error) {\nb := make([]byte, header.ICMPv4MinimumSize+len(l.Payload))\n@@ -901,12 +911,20 @@ func (l *ICMPv4) ToBytes() ([]byte, error) {\nif copied := copy(h.Payload(), l.Payload); copied != len(l.Payload) {\npanic(fmt.Sprintf(\"wrong number of bytes copied into h.Payload(): got = %d, want = %d\", len(h.Payload()), len(l.Payload)))\n}\n+ typ := h.Type()\n+ switch typ {\n+ case header.ICMPv4EchoReply, header.ICMPv4Echo:\nif l.Ident != nil {\nh.SetIdent(*l.Ident)\n}\nif l.Sequence != nil {\nh.SetSequence(*l.Sequence)\n}\n+ case header.ICMPv4ParamProblem:\n+ if l.Pointer != nil {\n+ h.SetPointer(*l.Pointer)\n+ }\n+ }\n// The checksum must be handled last because the ICMPv4 header fields are\n// included in the computation.\n@@ -932,14 +950,21 @@ func (l *ICMPv4) ToBytes() ([]byte, error) {\n// parser for the encapsulated payload.\nfunc parseICMPv4(b []byte) (Layer, layerParser) {\nh := header.ICMPv4(b)\n+\n+ msgType := h.Type()\nicmpv4 := ICMPv4{\n- Type: ICMPv4Type(h.Type()),\n+ Type: ICMPv4Type(msgType),\nCode: ICMPv4Code(h.Code()),\nChecksum: Uint16(h.Checksum()),\n- Ident: Uint16(h.Ident()),\n- Sequence: Uint16(h.Sequence()),\nPayload: h.Payload(),\n}\n+ switch msgType {\n+ case header.ICMPv4EchoReply, header.ICMPv4Echo:\n+ icmpv4.Ident = Uint16(h.Ident())\n+ icmpv4.Sequence = Uint16(h.Sequence())\n+ case header.ICMPv4ParamProblem:\n+ icmpv4.Pointer = Uint8(h.Pointer())\n+ }\nreturn &icmpv4, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/ipv4_fragment_reassembly_test.go",
"new_path": "test/packetimpact/tests/ipv4_fragment_reassembly_test.go",
"diff": "@@ -105,11 +105,13 @@ func TestIPv4FragmentReassembly(t *testing.T) {\nvar bytesReceived int\nreassembledPayload := make([]byte, test.ipPayloadLen)\n+ // We are sending a packet fragmented into smaller parts but the\n+ // response may also be large enough to require fragmentation.\n+ // Therefore we only look for payload for an IPv4 packet not ICMP.\nfor {\nincomingFrame, err := conn.ExpectFrame(t, testbench.Layers{\n&testbench.Ether{},\n&testbench.IPv4{},\n- &testbench.ICMPv4{},\n}, time.Second)\nif err != nil {\n// Either an unexpected frame was received, or none at all.\n@@ -121,9 +123,10 @@ func TestIPv4FragmentReassembly(t *testing.T) {\nif !test.expectReply {\nt.Fatalf(\"unexpected reply received:\\n%s\", incomingFrame)\n}\n- ipPayload, err := incomingFrame[2 /* ICMPv4 */].ToBytes()\n+ // We only asked for Ethernet and IPv4 so the rest should be payload.\n+ ipPayload, err := incomingFrame[2 /* Payload */].ToBytes()\nif err != nil {\n- t.Fatalf(\"failed to parse ICMPv4 header: incomingPacket[2].ToBytes() = (_, %s)\", err)\n+ t.Fatalf(\"failed to parse payload: incomingPacket[2].ToBytes() = (_, %s)\", err)\n}\noffset := *incomingFrame[1 /* IPv4 */].(*testbench.IPv4).FragmentOffset\nif copied := copy(reassembledPayload[offset:], ipPayload); copied != len(ipPayload) {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/ipv6_fragment_reassembly_test.go",
"new_path": "test/packetimpact/tests/ipv6_fragment_reassembly_test.go",
"diff": "@@ -117,7 +117,6 @@ func TestIPv6FragmentReassembly(t *testing.T) {\n&testbench.Ether{},\n&testbench.IPv6{},\n&testbench.IPv6FragmentExtHdr{},\n- &testbench.ICMPv6{},\n}, time.Second)\nif err != nil {\n// Either an unexpected frame was received, or none at all.\n@@ -129,7 +128,7 @@ func TestIPv6FragmentReassembly(t *testing.T) {\nif !test.expectReply {\nt.Fatalf(\"unexpected reply received:\\n%s\", incomingFrame)\n}\n- ipPayload, err := incomingFrame[3 /* ICMPv6 */].ToBytes()\n+ ipPayload, err := incomingFrame[3 /* Payload */].ToBytes()\nif err != nil {\nt.Fatalf(\"failed to parse ICMPv6 header: incomingPacket[3].ToBytes() = (_, %s)\", err)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Additions to ICMP and IPv4 parsers
Teach ICMP.Parser/ToBytes to handle some non echo ICMP packets.
Teach IPv4.Parser that fragments only have a payload, not an upper layer.
Fix IPv4 and IPv6 reassembly tests to handle the change.
Fixes #4758
PiperOrigin-RevId: 341549665 |
259,860 | 10.11.2020 09:55:46 | 28,800 | e998b9904f35cca5df468e11a7da7c2d7de5f0e7 | Add logging to internal gvisor when checking for kcov.
May help with debugging | [
{
"change_type": "MODIFY",
"old_path": "pkg/coverage/BUILD",
"new_path": "pkg/coverage/BUILD",
"diff": "@@ -7,6 +7,7 @@ go_library(\nsrcs = [\"coverage.go\"],\nvisibility = [\"//:sandbox\"],\ndeps = [\n+ \"//pkg/log\",\n\"//pkg/sync\",\n\"//pkg/usermem\",\n\"@io_bazel_rules_go//go/tools/coverdata\",\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add logging to internal gvisor when checking for kcov.
May help with debugging
https://syzkaller.appspot.com/bug?id=0d717bd7028dceeb4b38f09aab2841c398b41d81
PiperOrigin-RevId: 341640485 |
259,975 | 10.11.2020 11:25:17 | 28,800 | 267d18408461350e41d914467608dfc418e61f05 | Add all base and fs tests to Continuous Tests. | [
{
"change_type": "MODIFY",
"old_path": "BUILD",
"new_path": "BUILD",
"diff": "@@ -64,9 +64,12 @@ build_test(\n\"//test/e2e:integration_test\",\n\"//test/image:image_test\",\n\"//test/root:root_test\",\n- \"//test/benchmarks/base:base_test\",\n+ \"//test/benchmarks/base:startup_test\",\n+ \"//test/benchmarks/base:size_test\",\n+ \"//test/benchmarks/base:sysbench_test\",\n\"//test/benchmarks/database:database_test\",\n- \"//test/benchmarks/fs:fs_test\",\n+ \"//test/benchmarks/fs:bazel_test\",\n+ \"//test/benchmarks/fs:fio_test\",\n\"//test/benchmarks/media:media_test\",\n\"//test/benchmarks/ml:ml_test\",\n\"//test/benchmarks/network:network_test\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/base/BUILD",
"new_path": "test/benchmarks/base/BUILD",
"diff": "@@ -8,23 +8,41 @@ go_library(\nsrcs = [\n\"base.go\",\n],\n- deps = [\"//test/benchmarks/harness\"],\n+ deps = [\n+ \"//pkg/test/dockerutil\",\n+ \"//test/benchmarks/harness\",\n+ ],\n)\ngo_test(\n- name = \"base_test\",\n+ name = \"startup_test\",\nsize = \"enormous\",\n- srcs = [\n- \"size_test.go\",\n- \"startup_test.go\",\n- \"sysbench_test.go\",\n+ srcs = [\"startup_test.go\"],\n+ visibility = [\"//:sandbox\"],\n+ deps = [\n+ \"//pkg/test/dockerutil\",\n+ \"//test/benchmarks/base\",\n+ \"//test/benchmarks/harness\",\n],\n- library = \":base\",\n- tags = [\n- # Requires docker and runsc to be configured before test runs.\n- \"manual\",\n- \"local\",\n+)\n+\n+go_test(\n+ name = \"size_test\",\n+ size = \"enormous\",\n+ srcs = [\"size_test.go\"],\n+ visibility = [\"//:sandbox\"],\n+ deps = [\n+ \"//pkg/test/dockerutil\",\n+ \"//test/benchmarks/base\",\n+ \"//test/benchmarks/harness\",\n+ \"//test/benchmarks/tools\",\n],\n+)\n+\n+go_test(\n+ name = \"sysbench_test\",\n+ size = \"enormous\",\n+ srcs = [\"sysbench_test.go\"],\nvisibility = [\"//:sandbox\"],\ndeps = [\n\"//pkg/test/dockerutil\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/base/base.go",
"new_path": "test/benchmarks/base/base.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// Package base holds base performance benchmarks.\n+// Package base holds utility methods common to the base tests.\npackage base\nimport (\n- \"os\"\n+ \"context\"\n+ \"net\"\n\"testing\"\n+ \"time\"\n+ \"gvisor.dev/gvisor/pkg/test/dockerutil\"\n\"gvisor.dev/gvisor/test/benchmarks/harness\"\n)\n-var testHarness harness.Harness\n+// ServerArgs wraps args for startServers and runServerWorkload.\n+type ServerArgs struct {\n+ Machine harness.Machine\n+ Port int\n+ RunOpts dockerutil.RunOpts\n+ Cmd []string\n+}\n+\n+// StartServers starts b.N containers defined by 'runOpts' and 'cmd' and uses\n+// 'machine' to check that each is up.\n+func StartServers(ctx context.Context, b *testing.B, args ServerArgs) []*dockerutil.Container {\n+ b.Helper()\n+ servers := make([]*dockerutil.Container, 0, b.N)\n+\n+ // Create N servers and wait until each of them is serving.\n+ for i := 0; i < b.N; i++ {\n+ server := args.Machine.GetContainer(ctx, b)\n+ servers = append(servers, server)\n+ if err := server.Spawn(ctx, args.RunOpts, args.Cmd...); err != nil {\n+ CleanUpContainers(ctx, servers)\n+ b.Fatalf(\"failed to spawn node instance: %v\", err)\n+ }\n+\n+ // Get the container IP.\n+ servingIP, err := server.FindIP(ctx, false)\n+ if err != nil {\n+ CleanUpContainers(ctx, servers)\n+ b.Fatalf(\"failed to get ip from server: %v\", err)\n+ }\n+\n+ // Wait until the server is up.\n+ if err := harness.WaitUntilServing(ctx, args.Machine, servingIP, args.Port); err != nil {\n+ CleanUpContainers(ctx, servers)\n+ b.Fatalf(\"failed to wait for serving\")\n+ }\n+ }\n+ return servers\n+}\n+\n+// CleanUpContainers cleans up a slice of containers.\n+func CleanUpContainers(ctx context.Context, containers []*dockerutil.Container) {\n+ for _, c := range containers {\n+ if c != nil {\n+ c.CleanUp(ctx)\n+ }\n+ }\n+}\n-// TestMain is the main method for package network.\n-func TestMain(m *testing.M) {\n- testHarness.Init()\n- os.Exit(m.Run())\n+// RedisInstance returns a Redis container and its reachable IP.\n+func RedisInstance(ctx context.Context, b *testing.B, machine harness.Machine) (*dockerutil.Container, net.IP) {\n+ b.Helper()\n+ // Spawn a redis instance for the app to use.\n+ redis := machine.GetNativeContainer(ctx, b)\n+ if err := redis.Spawn(ctx, dockerutil.RunOpts{\n+ Image: \"benchmarks/redis\",\n+ }); err != nil {\n+ redis.CleanUp(ctx)\n+ b.Fatalf(\"failed to spwan redis instance: %v\", err)\n+ }\n+\n+ if out, err := redis.WaitForOutput(ctx, \"Ready to accept connections\", 3*time.Second); err != nil {\n+ redis.CleanUp(ctx)\n+ b.Fatalf(\"failed to start redis server: %v %s\", err, out)\n+ }\n+ redisIP, err := redis.FindIP(ctx, false)\n+ if err != nil {\n+ redis.CleanUp(ctx)\n+ b.Fatalf(\"failed to get IP from redis instance: %v\", err)\n+ }\n+ return redis, redisIP\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/base/size_test.go",
"new_path": "test/benchmarks/base/size_test.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-package base\n+package size_test\nimport (\n\"context\"\n+ \"os\"\n\"testing\"\n\"time\"\n\"gvisor.dev/gvisor/pkg/test/dockerutil\"\n+ \"gvisor.dev/gvisor/test/benchmarks/base\"\n\"gvisor.dev/gvisor/test/benchmarks/harness\"\n\"gvisor.dev/gvisor/test/benchmarks/tools\"\n)\n+var testHarness harness.Harness\n+\n// BenchmarkSizeEmpty creates N empty containers and reads memory usage from\n// /proc/meminfo.\nfunc BenchmarkSizeEmpty(b *testing.B) {\n@@ -53,11 +57,11 @@ func BenchmarkSizeEmpty(b *testing.B) {\nif err := container.Spawn(ctx, dockerutil.RunOpts{\nImage: \"benchmarks/alpine\",\n}, \"sh\", \"-c\", \"echo Hello && sleep 1000\"); err != nil {\n- cleanUpContainers(ctx, containers)\n+ base.CleanUpContainers(ctx, containers)\nb.Fatalf(\"failed to run container: %v\", err)\n}\nif _, err := container.WaitForOutputSubmatch(ctx, \"Hello\", 5*time.Second); err != nil {\n- cleanUpContainers(ctx, containers)\n+ base.CleanUpContainers(ctx, containers)\nb.Fatalf(\"failed to read container output: %v\", err)\n}\n}\n@@ -67,7 +71,7 @@ func BenchmarkSizeEmpty(b *testing.B) {\n// Check available memory after containers are up.\nafter, err := machine.RunCommand(cmd, args...)\n- cleanUpContainers(ctx, containers)\n+ base.CleanUpContainers(ctx, containers)\nif err != nil {\nb.Fatalf(\"failed to get meminfo: %v\", err)\n}\n@@ -100,14 +104,14 @@ func BenchmarkSizeNginx(b *testing.B) {\nImage: \"benchmarks/nginx\",\n}\nconst port = 80\n- servers := startServers(ctx, b,\n- serverArgs{\n- machine: machine,\n- port: port,\n- runOpts: runOpts,\n- cmd: []string{\"nginx\", \"-c\", \"/etc/nginx/nginx_gofer.conf\"},\n+ servers := base.StartServers(ctx, b,\n+ base.ServerArgs{\n+ Machine: machine,\n+ Port: port,\n+ RunOpts: runOpts,\n+ Cmd: []string{\"nginx\", \"-c\", \"/etc/nginx/nginx_gofer.conf\"},\n})\n- defer cleanUpContainers(ctx, servers)\n+ defer base.CleanUpContainers(ctx, servers)\n// DropCaches after servers are created.\nharness.DropCaches(machine)\n@@ -130,7 +134,7 @@ func BenchmarkSizeNode(b *testing.B) {\n// Make a redis instance for Node to connect.\nctx := context.Background()\n- redis, redisIP := redisInstance(ctx, b, machine)\n+ redis, redisIP := base.RedisInstance(ctx, b, machine)\ndefer redis.CleanUp(ctx)\n// DropCaches after redis is created.\n@@ -152,14 +156,14 @@ func BenchmarkSizeNode(b *testing.B) {\n}\nnodeCmd := []string{\"node\", \"index.js\", redisIP.String()}\nconst port = 8080\n- servers := startServers(ctx, b,\n- serverArgs{\n- machine: machine,\n- port: port,\n- runOpts: runOpts,\n- cmd: nodeCmd,\n+ servers := base.StartServers(ctx, b,\n+ base.ServerArgs{\n+ Machine: machine,\n+ Port: port,\n+ RunOpts: runOpts,\n+ Cmd: nodeCmd,\n})\n- defer cleanUpContainers(ctx, servers)\n+ defer base.CleanUpContainers(ctx, servers)\n// DropCaches after servers are created.\nharness.DropCaches(machine)\n@@ -172,50 +176,8 @@ func BenchmarkSizeNode(b *testing.B) {\nmeminfo.Report(b, before, after)\n}\n-// serverArgs wraps args for startServers and runServerWorkload.\n-type serverArgs struct {\n- machine harness.Machine\n- port int\n- runOpts dockerutil.RunOpts\n- cmd []string\n-}\n-\n-// startServers starts b.N containers defined by 'runOpts' and 'cmd' and uses\n-// 'machine' to check that each is up.\n-func startServers(ctx context.Context, b *testing.B, args serverArgs) []*dockerutil.Container {\n- b.Helper()\n- servers := make([]*dockerutil.Container, 0, b.N)\n-\n- // Create N servers and wait until each of them is serving.\n- for i := 0; i < b.N; i++ {\n- server := args.machine.GetContainer(ctx, b)\n- servers = append(servers, server)\n- if err := server.Spawn(ctx, args.runOpts, args.cmd...); err != nil {\n- cleanUpContainers(ctx, servers)\n- b.Fatalf(\"failed to spawn node instance: %v\", err)\n- }\n-\n- // Get the container IP.\n- servingIP, err := server.FindIP(ctx, false)\n- if err != nil {\n- cleanUpContainers(ctx, servers)\n- b.Fatalf(\"failed to get ip from server: %v\", err)\n- }\n-\n- // Wait until the server is up.\n- if err := harness.WaitUntilServing(ctx, args.machine, servingIP, args.port); err != nil {\n- cleanUpContainers(ctx, servers)\n- b.Fatalf(\"failed to wait for serving\")\n- }\n- }\n- return servers\n-}\n-\n-// cleanUpContainers cleans up a slice of containers.\n-func cleanUpContainers(ctx context.Context, containers []*dockerutil.Container) {\n- for _, c := range containers {\n- if c != nil {\n- c.CleanUp(ctx)\n- }\n- }\n+// TestMain is the main method for package network.\n+func TestMain(m *testing.M) {\n+ testHarness.Init()\n+ os.Exit(m.Run())\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/base/startup_test.go",
"new_path": "test/benchmarks/base/startup_test.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-package base\n+package startup_test\nimport (\n\"context\"\n\"fmt\"\n- \"net\"\n+ \"os\"\n\"testing\"\n- \"time\"\n\"gvisor.dev/gvisor/pkg/test/dockerutil\"\n+ \"gvisor.dev/gvisor/test/benchmarks/base\"\n\"gvisor.dev/gvisor/test/benchmarks/harness\"\n)\n+var testHarness harness.Harness\n+\n// BenchmarkStartEmpty times startup time for an empty container.\nfunc BenchmarkStartupEmpty(b *testing.B) {\nmachine, err := testHarness.GetMachine()\n@@ -60,11 +62,11 @@ func BenchmarkStartupNginx(b *testing.B) {\nImage: \"benchmarks/nginx\",\n}\nrunServerWorkload(ctx, b,\n- serverArgs{\n- machine: machine,\n- runOpts: runOpts,\n- port: 80,\n- cmd: []string{\"nginx\", \"-c\", \"/etc/nginx/nginx_gofer.conf\"},\n+ base.ServerArgs{\n+ Machine: machine,\n+ RunOpts: runOpts,\n+ Port: 80,\n+ Cmd: []string{\"nginx\", \"-c\", \"/etc/nginx/nginx_gofer.conf\"},\n})\n}\n@@ -79,7 +81,7 @@ func BenchmarkStartupNode(b *testing.B) {\ndefer machine.CleanUp()\nctx := context.Background()\n- redis, redisIP := redisInstance(ctx, b, machine)\n+ redis, redisIP := base.RedisInstance(ctx, b, machine)\ndefer redis.CleanUp(ctx)\nrunOpts := dockerutil.RunOpts{\nImage: \"benchmarks/node\",\n@@ -89,52 +91,28 @@ func BenchmarkStartupNode(b *testing.B) {\ncmd := []string{\"node\", \"index.js\", redisIP.String()}\nrunServerWorkload(ctx, b,\n- serverArgs{\n- machine: machine,\n- port: 8080,\n- runOpts: runOpts,\n- cmd: cmd,\n+ base.ServerArgs{\n+ Machine: machine,\n+ Port: 8080,\n+ RunOpts: runOpts,\n+ Cmd: cmd,\n})\n}\n-// redisInstance returns a Redis container and its reachable IP.\n-func redisInstance(ctx context.Context, b *testing.B, machine harness.Machine) (*dockerutil.Container, net.IP) {\n- b.Helper()\n- // Spawn a redis instance for the app to use.\n- redis := machine.GetNativeContainer(ctx, b)\n- if err := redis.Spawn(ctx, dockerutil.RunOpts{\n- Image: \"benchmarks/redis\",\n- }); err != nil {\n- redis.CleanUp(ctx)\n- b.Fatalf(\"failed to spwan redis instance: %v\", err)\n- }\n-\n- if out, err := redis.WaitForOutput(ctx, \"Ready to accept connections\", 3*time.Second); err != nil {\n- redis.CleanUp(ctx)\n- b.Fatalf(\"failed to start redis server: %v %s\", err, out)\n- }\n- redisIP, err := redis.FindIP(ctx, false)\n- if err != nil {\n- redis.CleanUp(ctx)\n- b.Fatalf(\"failed to get IP from redis instance: %v\", err)\n- }\n- return redis, redisIP\n-}\n-\n// runServerWorkload runs a server workload defined by 'runOpts' and 'cmd'.\n// 'clientMachine' is used to connect to the server on 'serverMachine'.\n-func runServerWorkload(ctx context.Context, b *testing.B, args serverArgs) {\n+func runServerWorkload(ctx context.Context, b *testing.B, args base.ServerArgs) {\nb.ResetTimer()\nfor i := 0; i < b.N; i++ {\nif err := func() error {\n- server := args.machine.GetContainer(ctx, b)\n+ server := args.Machine.GetContainer(ctx, b)\ndefer func() {\nb.StopTimer()\n// Cleanup servers as we run so that we can go indefinitely.\nserver.CleanUp(ctx)\nb.StartTimer()\n}()\n- if err := server.Spawn(ctx, args.runOpts, args.cmd...); err != nil {\n+ if err := server.Spawn(ctx, args.RunOpts, args.Cmd...); err != nil {\nreturn fmt.Errorf(\"failed to spawn node instance: %v\", err)\n}\n@@ -144,7 +122,7 @@ func runServerWorkload(ctx context.Context, b *testing.B, args serverArgs) {\n}\n// Wait until the Client sees the server as up.\n- if err := harness.WaitUntilServing(ctx, args.machine, servingIP, args.port); err != nil {\n+ if err := harness.WaitUntilServing(ctx, args.Machine, servingIP, args.Port); err != nil {\nreturn fmt.Errorf(\"failed to wait for serving: %v\", err)\n}\nreturn nil\n@@ -153,3 +131,9 @@ func runServerWorkload(ctx context.Context, b *testing.B, args serverArgs) {\n}\n}\n}\n+\n+// TestMain is the main method for package network.\n+func TestMain(m *testing.M) {\n+ testHarness.Init()\n+ os.Exit(m.Run())\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/base/sysbench_test.go",
"new_path": "test/benchmarks/base/sysbench_test.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-package base\n+package sysbench_test\nimport (\n\"context\"\n\"testing\"\n\"gvisor.dev/gvisor/pkg/test/dockerutil\"\n+ \"gvisor.dev/gvisor/test/benchmarks/harness\"\n\"gvisor.dev/gvisor/test/benchmarks/tools\"\n)\n+var testHarness harness.Harness\n+\ntype testCase struct {\nname string\ntest tools.Sysbench\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/fs/BUILD",
"new_path": "test/benchmarks/fs/BUILD",
"diff": "-load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+load(\"//tools:defs.bzl\", \"go_test\")\npackage(licenses = [\"notice\"])\n-go_library(\n- name = \"fs\",\n- testonly = 1,\n- srcs = [\"fs.go\"],\n- deps = [\"//test/benchmarks/harness\"],\n+go_test(\n+ name = \"bazel_test\",\n+ size = \"enormous\",\n+ srcs = [\"bazel_test.go\"],\n+ visibility = [\"//:sandbox\"],\n+ deps = [\n+ \"//pkg/test/dockerutil\",\n+ \"//test/benchmarks/harness\",\n+ \"//test/benchmarks/tools\",\n+ ],\n)\ngo_test(\n- name = \"fs_test\",\n- size = \"large\",\n- srcs = [\n- \"bazel_test.go\",\n- \"fio_test.go\",\n- ],\n- library = \":fs\",\n- tags = [\n- # Requires docker and runsc to be configured before test runs.\n- \"local\",\n- \"manual\",\n- ],\n+ name = \"fio_test\",\n+ size = \"enormous\",\n+ srcs = [\"fio_test.go\"],\nvisibility = [\"//:sandbox\"],\ndeps = [\n\"//pkg/test/dockerutil\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/fs/bazel_test.go",
"new_path": "test/benchmarks/fs/bazel_test.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-package fs\n+package bazel_test\nimport (\n\"context\"\n\"fmt\"\n+ \"os\"\n\"strings\"\n\"testing\"\n@@ -24,6 +25,8 @@ import (\n\"gvisor.dev/gvisor/test/benchmarks/tools\"\n)\n+var h harness.Harness\n+\n// Note: CleanCache versions of this test require running with root permissions.\nfunc BenchmarkBuildABSL(b *testing.B) {\nrunBuildBenchmark(b, \"benchmarks/absl\", \"/abseil-cpp\", \"absl/base/...\")\n@@ -138,3 +141,9 @@ func runBuildBenchmark(b *testing.B, image, workdir, target string) {\n})\n}\n}\n+\n+// TestMain is the main method for package fs.\n+func TestMain(m *testing.M) {\n+ h.Init()\n+ os.Exit(m.Run())\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/fs/fio_test.go",
"new_path": "test/benchmarks/fs/fio_test.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-package fs\n+package fio_test\nimport (\n\"context\"\n\"fmt\"\n+ \"os\"\n\"path/filepath\"\n\"strings\"\n\"testing\"\n@@ -26,6 +27,8 @@ import (\n\"gvisor.dev/gvisor/test/benchmarks/tools\"\n)\n+var h harness.Harness\n+\n// BenchmarkFio runs fio on the runtime under test. There are 4 basic test\n// cases each run on a tmpfs mount and a bind mount. Fio requires root so that\n// caches can be dropped.\n@@ -179,3 +182,9 @@ func makeMount(machine harness.Machine, mountType mount.Type, target string) (mo\nreturn mount.Mount{}, func() {}, fmt.Errorf(\"illegal mount time not supported: %v\", mountType)\n}\n}\n+\n+// TestMain is the main method for package fs.\n+func TestMain(m *testing.M) {\n+ h.Init()\n+ os.Exit(m.Run())\n+}\n"
},
{
"change_type": "DELETE",
"old_path": "test/benchmarks/fs/fs.go",
"new_path": null,
"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 fs holds benchmarks around filesystem performance.\n-package fs\n-\n-import (\n- \"os\"\n- \"testing\"\n-\n- \"gvisor.dev/gvisor/test/benchmarks/harness\"\n-)\n-\n-var h harness.Harness\n-\n-// TestMain is the main method for package fs.\n-func TestMain(m *testing.M) {\n- h.Init()\n- os.Exit(m.Run())\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/harness/harness.go",
"new_path": "test/benchmarks/harness/harness.go",
"diff": "@@ -17,17 +17,31 @@ package harness\nimport (\n\"flag\"\n+ \"fmt\"\n+ \"os\"\n\"gvisor.dev/gvisor/pkg/test/dockerutil\"\n)\n+var (\n+ help = flag.Bool(\"help\", false, \"print this usage message\")\n+)\n+\n// Harness is a handle for managing state in benchmark runs.\ntype Harness struct {\n}\n// Init performs any harness initilialization before runs.\nfunc (h *Harness) Init() error {\n+ flag.Usage = func() {\n+ fmt.Fprintf(os.Stderr, \"Usage: %s -- --test.bench=<regex>\\n\", os.Args[0])\n+ flag.PrintDefaults()\n+ }\nflag.Parse()\n+ if flag.NFlag() == 0 || *help {\n+ flag.Usage()\n+ os.Exit(0)\n+ }\ndockerutil.EnsureSupportedDockerVersion()\nreturn nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add all base and fs tests to Continuous Tests.
PiperOrigin-RevId: 341660511 |
259,858 | 10.11.2020 11:59:15 | 28,800 | a0e2966df502360067b45c24c90951efaf4a942c | Show run-benchmark output. | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -304,16 +304,15 @@ benchmark-platforms: load-benchmarks-images ## Runs benchmarks for runc and all\n.PHONY: benchmark-platforms\nrun-benchmark: ## Runs single benchmark and optionally sends data to BigQuery.\n- @T=$$(mktemp logs.$(RUNTIME).XXXXXX); \\\n- $(call submake,sudo TARGETS=\"$(BENCHMARKS_TARGETS)\" ARGS=\"--runtime=$(RUNTIME) $(BENCHMARKS_ARGS) | tee $$T\"); \\\n- rc=$$?; \\\n+ @set -xeuo pipefail; T=$$(mktemp --tmpdir logs.$(RUNTIME).XXXXXX); \\\n+ $(call submake,sudo TARGETS=\"$(BENCHMARKS_TARGETS)\" ARGS=\"--runtime=$(RUNTIME) $(BENCHMARKS_ARGS)\") | tee $$T; \\\nif [[ \"$(BENCHMARKS_UPLOAD)\" == \"true\" ]]; then \\\n$(call submake,run TARGETS=tools/parsers:parser ARGS=\"parse --file=$$T \\\n--runtime=$(RUNTIME) --suite_name=$(BENCHMARKS_SUITE) \\\n--project=$(BENCHMARKS_PROJECT) --dataset=$(BENCHMARKS_DATASET) \\\n--table=$(BENCHMARKS_TABLE) --official=$(BENCHMARKS_OFFICIAL)\"); \\\nfi; \\\n- rm -rf $$T; exit $$rc\n+ rm -rf $$T\n.PHONY: run-benchmark\n##\n@@ -369,8 +368,8 @@ RELEASE_NOTES :=\nGPG_TEST_OPTIONS := $(shell if gpg --pinentry-mode loopback --version >/dev/null 2>&1; then echo --pinentry-mode loopback; fi)\n$(RELEASE_KEY):\n@echo \"WARNING: Generating a key for testing ($@); don't use this.\"\n- T=$$(mktemp /tmp/keyring.XXXXXX); \\\n- C=$$(mktemp /tmp/config.XXXXXX); \\\n+ T=$$(mktemp --tmpdir keyring.XXXXXX); \\\n+ C=$$(mktemp --tmpdir config.XXXXXX); \\\necho Key-Type: DSA >> $$C && \\\necho Key-Length: 1024 >> $$C && \\\necho Name-Real: Test >> $$C && \\\n@@ -383,7 +382,7 @@ $(RELEASE_KEY):\nrelease: $(RELEASE_KEY) ## Builds a release.\n@mkdir -p $(RELEASE_ROOT)\n- @T=$$(mktemp -d /tmp/release.XXXXXX); \\\n+ @T=$$(mktemp -d --tmpdir release.XXXXXX); \\\n$(call submake,copy TARGETS=\"//runsc:runsc\" DESTINATION=$$T) && \\\n$(call submake,copy TARGETS=\"//shim/v1:gvisor-containerd-shim\" DESTINATION=$$T) && \\\n$(call submake,copy TARGETS=\"//shim/v2:containerd-shim-runsc-v1\" DESTINATION=$$T) && \\\n"
}
] | Go | Apache License 2.0 | google/gvisor | Show run-benchmark output.
PiperOrigin-RevId: 341667792 |
259,975 | 10.11.2020 21:18:57 | 28,800 | 792cbc06de41f226f76f55a828dfcfad9b8fb16e | Add debug logs to startup benchmark. | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -283,7 +283,7 @@ BENCHMARKS_SUITE := start\nBENCHMARKS_UPLOAD := false\nBENCHMARKS_OFFICIAL := false\nBENCHMARKS_PLATFORMS := ptrace\n-BENCHMARKS_TARGETS := //test/benchmarks/base:base_test\n+BENCHMARKS_TARGETS := //test/benchmarks/base:startup_test\nBENCHMARKS_ARGS := -test.bench=.\ninit-benchmark-table: ## Initializes a BigQuery table with the benchmark schema\n@@ -305,9 +305,9 @@ benchmark-platforms: load-benchmarks-images ## Runs benchmarks for runc and all\nrun-benchmark: ## Runs single benchmark and optionally sends data to BigQuery.\n@set -xeuo pipefail; T=$$(mktemp --tmpdir logs.$(RUNTIME).XXXXXX); \\\n- $(call submake,sudo TARGETS=\"$(BENCHMARKS_TARGETS)\" ARGS=\"--runtime=$(RUNTIME) $(BENCHMARKS_ARGS)\") | tee $$T; \\\n+ $(call submake,sudo TARGETS=\"$(BENCHMARKS_TARGETS)\" ARGS=\"--runtime=$(RUNTIME) $(BENCHMARKS_ARGS)\" | tee $$T); \\\nif [[ \"$(BENCHMARKS_UPLOAD)\" == \"true\" ]]; then \\\n- $(call submake,run TARGETS=tools/parsers:parser ARGS=\"parse --file=$$T \\\n+ $(call submake,run TARGETS=tools/parsers:parser ARGS=\"parse --debug --file=$$T \\\n--runtime=$(RUNTIME) --suite_name=$(BENCHMARKS_SUITE) \\\n--project=$(BENCHMARKS_PROJECT) --dataset=$(BENCHMARKS_DATASET) \\\n--table=$(BENCHMARKS_TABLE) --official=$(BENCHMARKS_OFFICIAL)\"); \\\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/base/startup_test.go",
"new_path": "test/benchmarks/base/startup_test.go",
"diff": "@@ -37,6 +37,7 @@ func BenchmarkStartupEmpty(b *testing.B) {\nctx := context.Background()\nfor i := 0; i < b.N; i++ {\n+ harness.DebugLog(b, \"Running container: %d\", i)\ncontainer := machine.GetContainer(ctx, b)\ndefer container.CleanUp(ctx)\nif _, err := container.Run(ctx, dockerutil.RunOpts{\n@@ -44,6 +45,7 @@ func BenchmarkStartupEmpty(b *testing.B) {\n}, \"true\"); err != nil {\nb.Fatalf(\"failed to run container: %v\", err)\n}\n+ harness.DebugLog(b, \"Ran container: %d\", i)\n}\n}\n@@ -104,6 +106,7 @@ func BenchmarkStartupNode(b *testing.B) {\nfunc runServerWorkload(ctx context.Context, b *testing.B, args base.ServerArgs) {\nb.ResetTimer()\nfor i := 0; i < b.N; i++ {\n+ harness.DebugLog(b, \"Running iteration: %d\", i)\nif err := func() error {\nserver := args.Machine.GetContainer(ctx, b)\ndefer func() {\n@@ -112,15 +115,18 @@ func runServerWorkload(ctx context.Context, b *testing.B, args base.ServerArgs)\nserver.CleanUp(ctx)\nb.StartTimer()\n}()\n+ harness.DebugLog(b, \"Spawning container: %s\", args.RunOpts.Image)\nif err := server.Spawn(ctx, args.RunOpts, args.Cmd...); err != nil {\nreturn fmt.Errorf(\"failed to spawn node instance: %v\", err)\n}\n+ harness.DebugLog(b, \"Finding Container IP\")\nservingIP, err := server.FindIP(ctx, false)\nif err != nil {\nreturn fmt.Errorf(\"failed to get ip from server: %v\", err)\n}\n+ harness.DebugLog(b, \"Waiting for container to start.\")\n// Wait until the Client sees the server as up.\nif err := harness.WaitUntilServing(ctx, args.Machine, servingIP, args.Port); err != nil {\nreturn fmt.Errorf(\"failed to wait for serving: %v\", err)\n@@ -129,6 +135,7 @@ func runServerWorkload(ctx context.Context, b *testing.B, args base.ServerArgs)\n}(); err != nil {\nb.Fatal(err)\n}\n+ harness.DebugLog(b, \"Ran iteration: %d\", i)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/harness/harness.go",
"new_path": "test/benchmarks/harness/harness.go",
"diff": "@@ -25,6 +25,7 @@ import (\nvar (\nhelp = flag.Bool(\"help\", false, \"print this usage message\")\n+ debug = flag.Bool(\"debug\", false, \"turns on debug messages for individual benchmarks\")\n)\n// Harness is a handle for managing state in benchmark runs.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/harness/util.go",
"new_path": "test/benchmarks/harness/util.go",
"diff": "@@ -18,6 +18,7 @@ import (\n\"context\"\n\"fmt\"\n\"net\"\n+ \"testing\"\n\"gvisor.dev/gvisor/pkg/test/dockerutil\"\n\"gvisor.dev/gvisor/pkg/test/testutil\"\n@@ -46,3 +47,11 @@ func DropCaches(machine Machine) error {\n}\nreturn nil\n}\n+\n+// DebugLog prints debug messages if the debug flag is set.\n+func DebugLog(b *testing.B, msg string, args ...interface{}) {\n+ b.Helper()\n+ if *debug {\n+ b.Logf(msg, args...)\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/parsers/parser_main.go",
"new_path": "tools/parsers/parser_main.go",
"diff": "@@ -21,6 +21,7 @@ import (\n\"context\"\n\"fmt\"\n\"io/ioutil\"\n+ \"log\"\n\"os\"\n\"gvisor.dev/gvisor/runsc/flag\"\n@@ -54,6 +55,7 @@ var (\nparseTable = parseCmd.String(\"table\", \"\", \"table to send benchmarks data.\")\nofficial = parseCmd.Bool(\"official\", false, \"mark input data as official.\")\nruntime = parseCmd.String(\"runtime\", \"\", \"runtime used to run the benchmark\")\n+ debug = parseCmd.Bool(\"debug\", false, \"print debug logs\")\n)\n// initBenchmarks initializes a dataset/table in a BigQuery project.\n@@ -64,14 +66,17 @@ func initBenchmarks(ctx context.Context) error {\n// parseBenchmarks parses the given file into the BigQuery schema,\n// adds some custom data for the commit, and sends the data to BigQuery.\nfunc parseBenchmarks(ctx context.Context) error {\n+ debugLog(\"Reading file: %s\", *file)\ndata, err := ioutil.ReadFile(*file)\nif err != nil {\nreturn fmt.Errorf(\"failed to read file %s: %v\", *file, err)\n}\n+ debugLog(\"Parsing output: %s\", string(data))\nsuite, err := parsers.ParseOutput(string(data), *name, *official)\nif err != nil {\nreturn fmt.Errorf(\"failed parse data: %v\", err)\n}\n+ debugLog(\"Parsed benchmarks: %d\", len(suite.Benchmarks))\nif len(suite.Benchmarks) < 1 {\nfmt.Fprintf(os.Stderr, \"Failed to find benchmarks for file: %s\", *file)\nreturn nil\n@@ -90,6 +95,7 @@ func parseBenchmarks(ctx context.Context) error {\nsuite.Official = *official\nsuite.Conditions = append(suite.Conditions, extraConditions...)\n+ debugLog(\"Sending benchmarks\")\nreturn bq.SendBenchmarks(ctx, suite, *parseProject, *parseDataset, *parseTable, nil)\n}\n@@ -99,22 +105,22 @@ func main() {\n// the \"init\" command\ncase len(os.Args) >= 2 && os.Args[1] == initString:\nif err := initCmd.Parse(os.Args[2:]); err != nil {\n- fmt.Fprintf(os.Stderr, \"failed parse flags: %v\\n\", err)\n+ log.Fatalf(\"Failed parse flags: %v\\n\", err)\nos.Exit(1)\n}\nif err := initBenchmarks(ctx); err != nil {\nfailure := \"failed to initialize project: %s dataset: %s table: %s: %v\\n\"\n- fmt.Fprintf(os.Stderr, failure, *parseProject, *parseDataset, *parseTable, err)\n+ log.Fatalf(failure, *parseProject, *parseDataset, *parseTable, err)\nos.Exit(1)\n}\n// the \"parse\" command.\ncase len(os.Args) >= 2 && os.Args[1] == parseString:\nif err := parseCmd.Parse(os.Args[2:]); err != nil {\n- fmt.Fprintf(os.Stderr, \"failed parse flags: %v\\n\", err)\n+ log.Fatalf(\"Failed parse flags: %v\\n\", err)\nos.Exit(1)\n}\nif err := parseBenchmarks(ctx); err != nil {\n- fmt.Fprintf(os.Stderr, \"failed parse benchmarks: %v\\n\", err)\n+ log.Fatalf(\"Failed parse benchmarks: %v\\n\", err)\nos.Exit(1)\n}\ndefault:\n@@ -131,5 +137,11 @@ Available commands:\n%s %s\n%s %s\n`\n- fmt.Fprintf(os.Stderr, usage, initCmd.Name(), initDescription, parseCmd.Name(), parseDescription)\n+ log.Printf(usage, initCmd.Name(), initDescription, parseCmd.Name(), parseDescription)\n+}\n+\n+func debugLog(msg string, args ...interface{}) {\n+ if *debug {\n+ log.Printf(msg, args...)\n+ }\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add debug logs to startup benchmark.
PiperOrigin-RevId: 341757694 |
260,019 | 12.11.2020 03:52:30 | 0 | b7de12fc03c6abde6d39b8bb326fc97cbc455901 | kvm-test: adjust the check logic in TestWrongVCPU case | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/kvm_test.go",
"new_path": "pkg/sentry/platform/kvm/kvm_test.go",
"diff": "@@ -412,9 +412,10 @@ func TestWrongVCPU(t *testing.T) {\n// Basic test, one then the other.\nbluepill(c1)\nbluepill(c2)\n- if c2.guestExits == 0 {\n+ if c1.guestExits == 0 {\n+ // Check: vCPU1 will exit due to redpill() in bluepill(c2).\n// Don't allow the test to proceed if this fails.\n- t.Fatalf(\"wrong vCPU#2 exits: vCPU1=%+v,vCPU2=%+v\", c1, c2)\n+ t.Fatalf(\"wrong vCPU#1 exits: vCPU1=%+v,vCPU2=%+v\", c1, c2)\n}\n// Alternate vCPUs; we expect to need to trigger the\n"
}
] | Go | Apache License 2.0 | google/gvisor | kvm-test: adjust the check logic in TestWrongVCPU case
Signed-off-by: Robin Luk <[email protected]> |
259,885 | 11.11.2020 22:43:33 | 28,800 | ac62743e380c90255fbca6b76d899c3b7cf70877 | Read fsimpl/tmpfs timestamps atomically. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"diff": "@@ -478,9 +478,9 @@ func (i *inode) statTo(stat *linux.Statx) {\nstat.GID = atomic.LoadUint32(&i.gid)\nstat.Mode = uint16(atomic.LoadUint32(&i.mode))\nstat.Ino = i.ino\n- stat.Atime = linux.NsecToStatxTimestamp(i.atime)\n- stat.Ctime = linux.NsecToStatxTimestamp(i.ctime)\n- stat.Mtime = linux.NsecToStatxTimestamp(i.mtime)\n+ stat.Atime = linux.NsecToStatxTimestamp(atomic.LoadInt64(&i.atime))\n+ stat.Ctime = linux.NsecToStatxTimestamp(atomic.LoadInt64(&i.ctime))\n+ stat.Mtime = linux.NsecToStatxTimestamp(atomic.LoadInt64(&i.mtime))\nstat.DevMajor = linux.UNNAMED_MAJOR\nstat.DevMinor = i.fs.devMinor\nswitch impl := i.impl.(type) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Read fsimpl/tmpfs timestamps atomically.
PiperOrigin-RevId: 341982672 |
259,907 | 12.11.2020 16:28:17 | 28,800 | 2a1974b07613420cb95845052815afb51187fc85 | [infra] Do not use debug flags for testing.
This causes some networking related tests to take a very long time.
Upon failure, tests can be manually run with debug flags to debug. As is the
strace logs are not available from a test run. | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -162,7 +162,7 @@ endif\nifeq ($(TOTAL_PARTITIONS),)\n@$(eval TOTAL_PARTITIONS := 1)\nendif\n- @$(call submake,install-test-runtime)\n+ @$(call submake,install-runtime)\n@$(call submake,test-runtime OPTIONS=\"--test_timeout=10800 --test_arg=--partition=$(PARTITION) --test_arg=--total_partitions=$(TOTAL_PARTITIONS)\" TARGETS=\"//test/runtimes:$*\")\n%-runtime-tests_vfs2: load-runtimes_%\n@@ -172,7 +172,7 @@ endif\nifeq ($(TOTAL_PARTITIONS),)\n@$(eval TOTAL_PARTITIONS := 1)\nendif\n- @$(call submake,install-test-runtime RUNTIME=\"vfs2\" ARGS=\"--vfs2\")\n+ @$(call submake,install-runtime RUNTIME=\"vfs2\" ARGS=\"--vfs2\")\n@$(call submake,test-runtime RUNTIME=\"vfs2\" OPTIONS=\"--test_timeout=10800 --test_arg=--partition=$(PARTITION) --test_arg=--total_partitions=$(TOTAL_PARTITIONS)\" TARGETS=\"//test/runtimes:$*\")\ndo-tests: runsc\n@@ -185,24 +185,24 @@ simple-tests: unit-tests # Compatibility target.\n.PHONY: simple-tests\ndocker-tests: load-basic-images\n- @$(call submake,install-test-runtime RUNTIME=\"vfs1\")\n+ @$(call submake,install-runtime RUNTIME=\"vfs1\")\n@$(call submake,test-runtime RUNTIME=\"vfs1\" TARGETS=\"$(INTEGRATION_TARGETS)\")\n- @$(call submake,install-test-runtime RUNTIME=\"vfs2\" ARGS=\"--vfs2\")\n+ @$(call submake,install-runtime RUNTIME=\"vfs2\" ARGS=\"--vfs2\")\n@$(call submake,test-runtime RUNTIME=\"vfs2\" TARGETS=\"$(INTEGRATION_TARGETS)\")\n.PHONY: docker-tests\noverlay-tests: load-basic-images\n- @$(call submake,install-test-runtime RUNTIME=\"overlay\" ARGS=\"--overlay\")\n+ @$(call submake,install-runtime RUNTIME=\"overlay\" ARGS=\"--overlay\")\n@$(call submake,test-runtime RUNTIME=\"overlay\" TARGETS=\"$(INTEGRATION_TARGETS)\")\n.PHONY: overlay-tests\nswgso-tests: load-basic-images\n- @$(call submake,install-test-runtime RUNTIME=\"swgso\" ARGS=\"--software-gso=true --gso=false\")\n+ @$(call submake,install-runtime RUNTIME=\"swgso\" ARGS=\"--software-gso=true --gso=false\")\n@$(call submake,test-runtime RUNTIME=\"swgso\" TARGETS=\"$(INTEGRATION_TARGETS)\")\n.PHONY: swgso-tests\nhostnet-tests: load-basic-images\n- @$(call submake,install-test-runtime RUNTIME=\"hostnet\" ARGS=\"--network=host\")\n+ @$(call submake,install-runtime RUNTIME=\"hostnet\" ARGS=\"--network=host\")\n@$(call submake,test-runtime RUNTIME=\"hostnet\" OPTIONS=\"--test_arg=-checkpoint=false\" TARGETS=\"$(INTEGRATION_TARGETS)\")\n.PHONY: hostnet-tests\n@@ -210,7 +210,7 @@ kvm-tests: load-basic-images\n@(lsmod | grep -E '^(kvm_intel|kvm_amd)') || sudo modprobe kvm\n@if ! [[ -w /dev/kvm ]]; then sudo chmod a+rw /dev/kvm; fi\n@$(call submake,test TARGETS=\"//pkg/sentry/platform/kvm:kvm_test\")\n- @$(call submake,install-test-runtime RUNTIME=\"kvm\" ARGS=\"--platform=kvm\")\n+ @$(call submake,install-runtime RUNTIME=\"kvm\" ARGS=\"--platform=kvm\")\n@$(call submake,test-runtime RUNTIME=\"kvm\" TARGETS=\"$(INTEGRATION_TARGETS)\")\n.PHONY: kvm-tests\n@@ -218,7 +218,7 @@ iptables-tests: load-iptables\n@sudo modprobe iptable_filter\n@sudo modprobe ip6table_filter\n@$(call submake,test-runtime RUNTIME=\"runc\" TARGETS=\"//test/iptables:iptables_test\")\n- @$(call submake,install-test-runtime RUNTIME=\"iptables\" ARGS=\"--net-raw\")\n+ @$(call submake,install-runtime RUNTIME=\"iptables\" ARGS=\"--net-raw\")\n@$(call submake,test-runtime RUNTIME=\"iptables\" TARGETS=\"//test/iptables:iptables_test\")\n.PHONY: iptables-tests\n@@ -227,25 +227,25 @@ iptables-tests: load-iptables\niptables-runsc-tests: load-iptables\n@sudo modprobe iptable_filter\n@sudo modprobe ip6table_filter\n- @$(call submake,install-test-runtime RUNTIME=\"iptables\" ARGS=\"--net-raw\")\n+ @$(call submake,install-runtime RUNTIME=\"iptables\" ARGS=\"--net-raw\")\n@$(call submake,test-runtime RUNTIME=\"iptables\" TARGETS=\"//test/iptables:iptables_test\")\n.PHONY: iptables-runsc-tests\npacketdrill-tests: load-packetdrill\n- @$(call submake,install-test-runtime RUNTIME=\"packetdrill\")\n+ @$(call submake,install-runtime RUNTIME=\"packetdrill\")\n@$(call submake,test-runtime RUNTIME=\"packetdrill\" TARGETS=\"$(shell $(MAKE) query TARGETS='attr(tags, packetdrill, tests(//...))')\")\n.PHONY: packetdrill-tests\npacketimpact-tests: load-packetimpact\n@sudo modprobe iptable_filter\n@sudo modprobe ip6table_filter\n- @$(call submake,install-test-runtime RUNTIME=\"packetimpact\")\n+ @$(call submake,install-runtime RUNTIME=\"packetimpact\")\n@$(call submake,test-runtime OPTIONS=\"--jobs=HOST_CPUS*3 --local_test_jobs=HOST_CPUS*3\" RUNTIME=\"packetimpact\" TARGETS=\"$(shell $(MAKE) query TARGETS='attr(tags, packetimpact, tests(//...))')\")\n.PHONY: packetimpact-tests\n# Specific containerd version tests.\ncontainerd-test-%: load-basic_alpine load-basic_python load-basic_busybox load-basic_resolv load-basic_httpd load-basic_ubuntu\n- @$(call submake,install-test-runtime RUNTIME=\"root\")\n+ @$(call submake,install-runtime RUNTIME=\"root\")\n@CONTAINERD_VERSION=$* $(MAKE) sudo TARGETS=\"tools/installers:containerd\"\n@$(MAKE) sudo TARGETS=\"tools/installers:shim\"\n@$(MAKE) sudo TARGETS=\"test/root:root_test\" ARGS=\"--runtime=root -test.v\"\n@@ -443,9 +443,9 @@ install-runtime: ## Installs the runtime for testing. Requires sudo.\nfi\n.PHONY: install-runtime\n-install-test-runtime: ## Installs the runtime for testing with default args. Requires sudo.\n+install-debug-runtime: ## Installs the runtime for debugging. Requires sudo.\n@$(call submake,install-runtime ARGS=\"--debug --strace --log-packets $(ARGS)\")\n-.PHONY: install-test-runtime\n+.PHONY: install-debug-runtime\nconfigure: ## Configures a single runtime. Requires sudo. Typically called from dev or install-runtime.\n@sudo sudo \"$(RUNTIME_BIN)\" install --experimental=true --runtime=\"$(RUNTIME_NAME)\" -- --debug-log \"$(RUNTIME_LOGS)\" $(ARGS)\n"
}
] | Go | Apache License 2.0 | google/gvisor | [infra] Do not use debug flags for testing.
This causes some networking related tests to take a very long time.
Upon failure, tests can be manually run with debug flags to debug. As is the
strace logs are not available from a test run.
PiperOrigin-RevId: 342156294 |
259,885 | 12.11.2020 16:54:22 | 28,800 | ae7ab0a330aaa1676d1fe066e3f5ac5fe805ec1c | Filter dentries with non-zero refs in VFS2 gofer/overlay checks. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"new_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"diff": "@@ -114,6 +114,51 @@ func putDentrySlice(ds *[]*dentry) {\ndentrySlicePool.Put(ds)\n}\n+// renameMuRUnlockAndCheckCaching calls fs.renameMu.RUnlock(), then calls\n+// dentry.checkCachingLocked on all dentries in *dsp with fs.renameMu locked\n+// for writing.\n+//\n+// dsp is a pointer-to-pointer since defer evaluates its arguments immediately,\n+// but dentry slices are allocated lazily, and it's much easier to say \"defer\n+// fs.renameMuRUnlockAndCheckCaching(&ds)\" than \"defer func() {\n+// fs.renameMuRUnlockAndCheckCaching(ds) }()\" to work around this.\n+func (fs *filesystem) renameMuRUnlockAndCheckCaching(ctx context.Context, dsp **[]*dentry) {\n+ fs.renameMu.RUnlock()\n+ if *dsp == nil {\n+ return\n+ }\n+ ds := **dsp\n+ // Only go through calling dentry.checkCachingLocked() (which requires\n+ // re-locking renameMu) if we actually have any dentries with zero refs.\n+ checkAny := false\n+ for i := range ds {\n+ if atomic.LoadInt64(&ds[i].refs) == 0 {\n+ checkAny = true\n+ break\n+ }\n+ }\n+ if checkAny {\n+ fs.renameMu.Lock()\n+ for _, d := range ds {\n+ d.checkCachingLocked(ctx)\n+ }\n+ fs.renameMu.Unlock()\n+ }\n+ putDentrySlice(*dsp)\n+}\n+\n+func (fs *filesystem) renameMuUnlockAndCheckCaching(ctx context.Context, ds **[]*dentry) {\n+ if *ds == nil {\n+ fs.renameMu.Unlock()\n+ return\n+ }\n+ for _, d := range **ds {\n+ d.checkCachingLocked(ctx)\n+ }\n+ fs.renameMu.Unlock()\n+ putDentrySlice(*ds)\n+}\n+\n// stepLocked resolves rp.Component() to an existing file, starting from the\n// given directory.\n//\n@@ -651,41 +696,6 @@ func (fs *filesystem) unlinkAt(ctx context.Context, rp *vfs.ResolvingPath, dir b\nreturn nil\n}\n-// renameMuRUnlockAndCheckCaching calls fs.renameMu.RUnlock(), then calls\n-// dentry.checkCachingLocked on all dentries in *ds with fs.renameMu locked for\n-// writing.\n-//\n-// ds is a pointer-to-pointer since defer evaluates its arguments immediately,\n-// but dentry slices are allocated lazily, and it's much easier to say \"defer\n-// fs.renameMuRUnlockAndCheckCaching(&ds)\" than \"defer func() {\n-// fs.renameMuRUnlockAndCheckCaching(ds) }()\" to work around this.\n-func (fs *filesystem) renameMuRUnlockAndCheckCaching(ctx context.Context, ds **[]*dentry) {\n- fs.renameMu.RUnlock()\n- if *ds == nil {\n- return\n- }\n- if len(**ds) != 0 {\n- fs.renameMu.Lock()\n- for _, d := range **ds {\n- d.checkCachingLocked(ctx)\n- }\n- fs.renameMu.Unlock()\n- }\n- putDentrySlice(*ds)\n-}\n-\n-func (fs *filesystem) renameMuUnlockAndCheckCaching(ctx context.Context, ds **[]*dentry) {\n- if *ds == nil {\n- fs.renameMu.Unlock()\n- return\n- }\n- for _, d := range **ds {\n- d.checkCachingLocked(ctx)\n- }\n- fs.renameMu.Unlock()\n- putDentrySlice(*ds)\n-}\n-\n// AccessAt implements vfs.Filesystem.Impl.AccessAt.\nfunc (fs *filesystem) AccessAt(ctx context.Context, rp *vfs.ResolvingPath, creds *auth.Credentials, ats vfs.AccessTypes) error {\nvar ds *[]*dentry\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"diff": "@@ -1352,6 +1352,11 @@ func (d *dentry) checkCachingLocked(ctx context.Context) {\n}\nif refs > 0 {\nif d.cached {\n+ // This isn't strictly necessary (fs.cachedDentries is permitted to\n+ // contain dentries with non-zero refs, which are skipped by\n+ // fs.evictCachedDentryLocked() upon reaching the end of the LRU),\n+ // but since we are already holding fs.renameMu for writing we may\n+ // as well.\nd.fs.cachedDentries.Remove(d)\nd.fs.cachedDentriesLen--\nd.cached = false\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/overlay/filesystem.go",
"new_path": "pkg/sentry/fsimpl/overlay/filesystem.go",
"diff": "@@ -78,26 +78,36 @@ func putDentrySlice(ds *[]*dentry) {\n}\n// renameMuRUnlockAndCheckDrop calls fs.renameMu.RUnlock(), then calls\n-// dentry.checkDropLocked on all dentries in *ds with fs.renameMu locked for\n+// dentry.checkDropLocked on all dentries in *dsp with fs.renameMu locked for\n// writing.\n//\n-// ds is a pointer-to-pointer since defer evaluates its arguments immediately,\n+// dsp is a pointer-to-pointer since defer evaluates its arguments immediately,\n// but dentry slices are allocated lazily, and it's much easier to say \"defer\n// fs.renameMuRUnlockAndCheckDrop(&ds)\" than \"defer func() {\n// fs.renameMuRUnlockAndCheckDrop(ds) }()\" to work around this.\n-func (fs *filesystem) renameMuRUnlockAndCheckDrop(ctx context.Context, ds **[]*dentry) {\n+func (fs *filesystem) renameMuRUnlockAndCheckDrop(ctx context.Context, dsp **[]*dentry) {\nfs.renameMu.RUnlock()\n- if *ds == nil {\n+ if *dsp == nil {\nreturn\n}\n- if len(**ds) != 0 {\n+ ds := **dsp\n+ // Only go through calling dentry.checkDropLocked() (which requires\n+ // re-locking renameMu) if we actually have any dentries with zero refs.\n+ checkAny := false\n+ for i := range ds {\n+ if atomic.LoadInt64(&ds[i].refs) == 0 {\n+ checkAny = true\n+ break\n+ }\n+ }\n+ if checkAny {\nfs.renameMu.Lock()\n- for _, d := range **ds {\n+ for _, d := range ds {\nd.checkDropLocked(ctx)\n}\nfs.renameMu.Unlock()\n}\n- putDentrySlice(*ds)\n+ putDentrySlice(*dsp)\n}\nfunc (fs *filesystem) renameMuUnlockAndCheckDrop(ctx context.Context, ds **[]*dentry) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Filter dentries with non-zero refs in VFS2 gofer/overlay checks.
PiperOrigin-RevId: 342161204 |
259,992 | 12.11.2020 17:42:45 | 28,800 | 74be0dd0d59d468a9ebdcdf52f68eda78f4ea42a | Remove TESTONLY tag from vfs2 flag
Updates | [
{
"change_type": "MODIFY",
"old_path": "runsc/config/flags.go",
"new_path": "runsc/config/flags.go",
"diff": "@@ -71,7 +71,7 @@ func RegisterFlags() {\nflag.Bool(\"overlay\", false, \"wrap filesystem mounts with writable overlay. All modifications are stored in memory inside the sandbox.\")\nflag.Bool(\"overlayfs-stale-read\", true, \"assume root mount is an overlay filesystem\")\nflag.Bool(\"fsgofer-host-uds\", false, \"allow the gofer to mount Unix Domain Sockets.\")\n- flag.Bool(\"vfs2\", false, \"TEST ONLY; use while VFSv2 is landing. This uses the new experimental VFS layer.\")\n+ flag.Bool(\"vfs2\", false, \"enables VFSv2. This uses the new VFS layer that is faster than the previous one.\")\nflag.Bool(\"fuse\", false, \"TEST ONLY; use while FUSE in VFSv2 is landing. This allows the use of the new experimental FUSE filesystem.\")\n// Flags that control sandbox runtime behavior: network related.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove TESTONLY tag from vfs2 flag
Updates #1035
PiperOrigin-RevId: 342168926 |
260,024 | 12.11.2020 17:46:37 | 28,800 | d700ba22abb9e5f29749cc3843991c31dc00384d | Pad with a loop rather than a copy from an allocation.
Add a unit test for ipv4.Encode and a round trip test. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/ipv4.go",
"new_path": "pkg/tcpip/header/ipv4.go",
"diff": "@@ -374,8 +374,14 @@ func (b IPv4) Encode(i *IPv4Fields) {\nif hdrLen > len(b) {\npanic(fmt.Sprintf(\"encode received %d bytes, wanted >= %d\", len(b), hdrLen))\n}\n- if aLen != copy(b[options:], i.Options) {\n- _ = copy(b[options+len(i.Options):options+aLen], []byte{0, 0, 0, 0})\n+ opts := b[options:]\n+ // This avoids bounds checks on the next line(s) which would happen even\n+ // if there's no work to do.\n+ if n := copy(opts, i.Options); n != aLen {\n+ padding := opts[n:][:aLen-n]\n+ for i := range padding {\n+ padding[i] = 0\n+ }\n}\n}\nb.SetHeaderLength(uint8(hdrLen))\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4_test.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4_test.go",
"diff": "@@ -103,6 +103,105 @@ func TestExcludeBroadcast(t *testing.T) {\n})\n}\n+// TestIPv4Encode checks that ipv4.Encode correctly fills out the requested\n+// fields when options are supplied.\n+func TestIPv4EncodeOptions(t *testing.T) {\n+ tests := []struct {\n+ name string\n+ options header.IPv4Options\n+ encodedOptions header.IPv4Options // reply should look like this\n+ wantIHL int\n+ }{\n+ {\n+ name: \"valid no options\",\n+ wantIHL: header.IPv4MinimumSize,\n+ },\n+ {\n+ name: \"one byte options\",\n+ options: header.IPv4Options{1},\n+ encodedOptions: header.IPv4Options{1, 0, 0, 0},\n+ wantIHL: header.IPv4MinimumSize + 4,\n+ },\n+ {\n+ name: \"two byte options\",\n+ options: header.IPv4Options{1, 1},\n+ encodedOptions: header.IPv4Options{1, 1, 0, 0},\n+ wantIHL: header.IPv4MinimumSize + 4,\n+ },\n+ {\n+ name: \"three byte options\",\n+ options: header.IPv4Options{1, 1, 1},\n+ encodedOptions: header.IPv4Options{1, 1, 1, 0},\n+ wantIHL: header.IPv4MinimumSize + 4,\n+ },\n+ {\n+ name: \"four byte options\",\n+ options: header.IPv4Options{1, 1, 1, 1},\n+ encodedOptions: header.IPv4Options{1, 1, 1, 1},\n+ wantIHL: header.IPv4MinimumSize + 4,\n+ },\n+ {\n+ name: \"five byte options\",\n+ options: header.IPv4Options{1, 1, 1, 1, 1},\n+ encodedOptions: header.IPv4Options{1, 1, 1, 1, 1, 0, 0, 0},\n+ wantIHL: header.IPv4MinimumSize + 8,\n+ },\n+ {\n+ name: \"thirty nine byte options\",\n+ options: header.IPv4Options{\n+ 1, 2, 3, 4, 5, 6, 7, 8,\n+ 9, 10, 11, 12, 13, 14, 15, 16,\n+ 17, 18, 19, 20, 21, 22, 23, 24,\n+ 25, 26, 27, 28, 29, 30, 31, 32,\n+ 33, 34, 35, 36, 37, 38, 39,\n+ },\n+ encodedOptions: header.IPv4Options{\n+ 1, 2, 3, 4, 5, 6, 7, 8,\n+ 9, 10, 11, 12, 13, 14, 15, 16,\n+ 17, 18, 19, 20, 21, 22, 23, 24,\n+ 25, 26, 27, 28, 29, 30, 31, 32,\n+ 33, 34, 35, 36, 37, 38, 39, 0,\n+ },\n+ wantIHL: header.IPv4MinimumSize + 40,\n+ },\n+ }\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ paddedOptionLength := test.options.AllocationSize()\n+ ipHeaderLength := header.IPv4MinimumSize + paddedOptionLength\n+ if ipHeaderLength > header.IPv4MaximumHeaderSize {\n+ t.Fatalf(\"IP header length too large: got = %d, want <= %d \", ipHeaderLength, header.IPv4MaximumHeaderSize)\n+ }\n+ totalLen := uint16(ipHeaderLength)\n+ hdr := buffer.NewPrependable(int(totalLen))\n+ ip := header.IPv4(hdr.Prepend(ipHeaderLength))\n+ // To check the padding works, poison the last byte of the options space.\n+ if paddedOptionLength != len(test.options) {\n+ ip.SetHeaderLength(uint8(ipHeaderLength))\n+ ip.Options()[paddedOptionLength-1] = 0xff\n+ ip.SetHeaderLength(0)\n+ }\n+ ip.Encode(&header.IPv4Fields{\n+ Options: test.options,\n+ })\n+ options := ip.Options()\n+ wantOptions := test.encodedOptions\n+ if got, want := int(ip.HeaderLength()), test.wantIHL; got != want {\n+ t.Errorf(\"got IHL of %d, want %d\", got, want)\n+ }\n+\n+ // cmp.Diff does not consider nil slices equal to empty slices, but we do.\n+ if len(wantOptions) == 0 && len(options) == 0 {\n+ return\n+ }\n+\n+ if diff := cmp.Diff(wantOptions, options); diff != \"\" {\n+ t.Errorf(\"options mismatch (-want +got):\\n%s\", diff)\n+ }\n+ })\n+ }\n+}\n+\n// TestIPv4Sanity sends IP/ICMP packets with various problems to the stack and\n// checks the response.\nfunc TestIPv4Sanity(t *testing.T) {\n@@ -196,6 +295,14 @@ func TestIPv4Sanity(t *testing.T) {\noptions: header.IPv4Options{1, 1, 0, 0},\nreplyOptions: header.IPv4Options{1, 1, 0, 0},\n},\n+ {\n+ name: \"Check option padding\",\n+ maxTotalLength: ipv4.MaxTotalSize,\n+ transportProtocol: uint8(header.ICMPv4ProtocolNumber),\n+ TTL: ttl,\n+ options: header.IPv4Options{1, 1, 1},\n+ replyOptions: header.IPv4Options{1, 1, 1, 0},\n+ },\n{\nname: \"bad header length\",\nheaderLength: header.IPv4MinimumSize - 1,\n@@ -599,9 +706,10 @@ func TestIPv4Sanity(t *testing.T) {\n},\n})\n- ipHeaderLength := header.IPv4MinimumSize + test.options.AllocationSize()\n+ paddedOptionLength := test.options.AllocationSize()\n+ ipHeaderLength := header.IPv4MinimumSize + paddedOptionLength\nif ipHeaderLength > header.IPv4MaximumHeaderSize {\n- t.Fatalf(\"too many bytes in options: got = %d, want <= %d \", ipHeaderLength, header.IPv4MaximumHeaderSize)\n+ t.Fatalf(\"IP header length too large: got = %d, want <= %d \", ipHeaderLength, header.IPv4MaximumHeaderSize)\n}\ntotalLen := uint16(ipHeaderLength + header.ICMPv4MinimumSize)\nhdr := buffer.NewPrependable(int(totalLen))\n@@ -618,6 +726,12 @@ func TestIPv4Sanity(t *testing.T) {\nif test.maxTotalLength < totalLen {\ntotalLen = test.maxTotalLength\n}\n+ // To check the padding works, poison the options space.\n+ if paddedOptionLength != len(test.options) {\n+ ip.SetHeaderLength(uint8(ipHeaderLength))\n+ ip.Options()[paddedOptionLength-1] = 0x01\n+ }\n+\nip.Encode(&header.IPv4Fields{\nTotalLength: totalLen,\nProtocol: test.transportProtocol,\n@@ -732,7 +846,7 @@ func TestIPv4Sanity(t *testing.T) {\n}\n// If the IP options change size then the packet will change size, so\n// some IP header fields will need to be adjusted for the checks.\n- sizeChange := len(test.replyOptions) - len(test.options)\n+ sizeChange := len(test.replyOptions) - paddedOptionLength\nchecker.IPv4(t, replyIPHeader,\nchecker.IPv4HeaderLength(ipHeaderLength+sizeChange),\n"
}
] | Go | Apache License 2.0 | google/gvisor | Pad with a loop rather than a copy from an allocation.
Add a unit test for ipv4.Encode and a round trip test.
PiperOrigin-RevId: 342169517 |
260,024 | 12.11.2020 18:36:45 | 28,800 | 638d64c6337d05b91f0bde81de8e1c8d6d9908d8 | Change AllocationSize to SizeWithPadding as requested
RELNOTES: n/a | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/ipv4.go",
"new_path": "pkg/tcpip/header/ipv4.go",
"diff": "@@ -275,12 +275,12 @@ func (b IPv4) DestinationAddress() tcpip.Address {\n// IPv4Options is a buffer that holds all the raw IP options.\ntype IPv4Options []byte\n-// AllocationSize implements stack.NetOptions.\n+// SizeWithPadding implements stack.NetOptions.\n// It reports the size to allocate for the Options. RFC 791 page 23 (end of\n// section 3.1) says of the padding at the end of the options:\n// The internet header padding is used to ensure that the internet\n// header ends on a 32 bit boundary.\n-func (o IPv4Options) AllocationSize() int {\n+func (o IPv4Options) SizeWithPadding() int {\nreturn (len(o) + IPv4IHLStride - 1) & ^(IPv4IHLStride - 1)\n}\n@@ -368,8 +368,8 @@ func (b IPv4) Encode(i *IPv4Fields) {\n// worth a bit of optimisation here to keep the copy out of the fast path.\nhdrLen := IPv4MinimumSize\nif len(i.Options) != 0 {\n- // AllocationSize is always >= len(i.Options).\n- aLen := i.Options.AllocationSize()\n+ // SizeWithPadding is always >= len(i.Options).\n+ aLen := i.Options.SizeWithPadding()\nhdrLen += aLen\nif hdrLen > len(b) {\npanic(fmt.Sprintf(\"encode received %d bytes, wanted >= %d\", len(b), hdrLen))\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ip_test.go",
"new_path": "pkg/tcpip/network/ip_test.go",
"diff": "@@ -1227,7 +1227,7 @@ func TestWriteHeaderIncludedPacket(t *testing.T) {\nnicAddr: localIPv4Addr,\nremoteAddr: remoteIPv4Addr,\npktGen: func(t *testing.T, src tcpip.Address) buffer.VectorisedView {\n- ipHdrLen := header.IPv4MinimumSize + ipv4Options.AllocationSize()\n+ ipHdrLen := header.IPv4MinimumSize + ipv4Options.SizeWithPadding()\ntotalLen := ipHdrLen + len(data)\nhdr := buffer.NewPrependable(totalLen)\nif n := copy(hdr.Prepend(len(data)), data); n != len(data) {\n@@ -1272,7 +1272,7 @@ func TestWriteHeaderIncludedPacket(t *testing.T) {\nnicAddr: localIPv4Addr,\nremoteAddr: remoteIPv4Addr,\npktGen: func(t *testing.T, src tcpip.Address) buffer.VectorisedView {\n- ip := header.IPv4(make([]byte, header.IPv4MinimumSize+ipv4Options.AllocationSize()))\n+ ip := header.IPv4(make([]byte, header.IPv4MinimumSize+ipv4Options.SizeWithPadding()))\nip.Encode(&header.IPv4Fields{\nProtocol: transportProto,\nTTL: ipv4.DefaultTTL,\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4.go",
"diff": "@@ -206,12 +206,12 @@ func (e *endpoint) addIPHeader(r *stack.Route, pkt *stack.PacketBuffer, params s\nif opts, ok = params.Options.(header.IPv4Options); !ok {\npanic(fmt.Sprintf(\"want IPv4Options, got %T\", params.Options))\n}\n- hdrLen += opts.AllocationSize()\n+ hdrLen += opts.SizeWithPadding()\nif hdrLen > header.IPv4MaximumHeaderSize {\n// Since we have no way to report an error we must either panic or create\n// a packet which is different to what was requested. Choose panic as this\n// would be a programming error that should be caught in testing.\n- panic(fmt.Sprintf(\"IPv4 Options %d bytes, Max %d\", params.Options.AllocationSize(), header.IPv4MaximumOptionsSize))\n+ panic(fmt.Sprintf(\"IPv4 Options %d bytes, Max %d\", params.Options.SizeWithPadding(), header.IPv4MaximumOptionsSize))\n}\n}\nip := header.IPv4(pkt.NetworkHeader().Push(hdrLen))\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4_test.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4_test.go",
"diff": "@@ -167,7 +167,7 @@ func TestIPv4EncodeOptions(t *testing.T) {\n}\nfor _, test := range tests {\nt.Run(test.name, func(t *testing.T) {\n- paddedOptionLength := test.options.AllocationSize()\n+ paddedOptionLength := test.options.SizeWithPadding()\nipHeaderLength := header.IPv4MinimumSize + paddedOptionLength\nif ipHeaderLength > header.IPv4MaximumHeaderSize {\nt.Fatalf(\"IP header length too large: got = %d, want <= %d \", ipHeaderLength, header.IPv4MaximumHeaderSize)\n@@ -706,7 +706,7 @@ func TestIPv4Sanity(t *testing.T) {\n},\n})\n- paddedOptionLength := test.options.AllocationSize()\n+ paddedOptionLength := test.options.SizeWithPadding()\nipHeaderLength := header.IPv4MinimumSize + paddedOptionLength\nif ipHeaderLength > header.IPv4MaximumHeaderSize {\nt.Fatalf(\"IP header length too large: got = %d, want <= %d \", ipHeaderLength, header.IPv4MaximumHeaderSize)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/registration.go",
"new_path": "pkg/tcpip/stack/registration.go",
"diff": "@@ -262,10 +262,10 @@ const (\n// NetOptions is an interface that allows us to pass network protocol specific\n// options through the Stack layer code.\ntype NetOptions interface {\n- // AllocationSize returns the amount of memory that must be allocated to\n+ // SizeWithPadding returns the amount of memory that must be allocated to\n// hold the options given that the value must be rounded up to the next\n// multiple of 4 bytes.\n- AllocationSize() int\n+ SizeWithPadding() int\n}\n// NetworkHeaderParams are the header parameters given as input by the\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/layers.go",
"new_path": "test/packetimpact/testbench/layers.go",
"diff": "@@ -298,7 +298,7 @@ func (l *IPv4) ToBytes() ([]byte, error) {\n// An IPv4 header is variable length depending on the size of the Options.\nhdrLen := header.IPv4MinimumSize\nif l.Options != nil {\n- hdrLen += l.Options.AllocationSize()\n+ hdrLen += l.Options.SizeWithPadding()\nif hdrLen > header.IPv4MaximumHeaderSize {\n// While ToBytes can be called on packets that were received as well\n// as packets locally generated, it is physically impossible for a\n"
}
] | Go | Apache License 2.0 | google/gvisor | Change AllocationSize to SizeWithPadding as requested
RELNOTES: n/a
PiperOrigin-RevId: 342176296 |
259,885 | 12.11.2020 19:10:01 | 28,800 | bf392dcc7d7b1f256acfe8acd2758a77db3fc8a2 | Allow goid.Get() to be used outside of race builds. | [
{
"change_type": "MODIFY",
"old_path": "pkg/goid/BUILD",
"new_path": "pkg/goid/BUILD",
"diff": "@@ -8,8 +8,6 @@ go_library(\n\"goid.go\",\n\"goid_amd64.s\",\n\"goid_arm64.s\",\n- \"goid_race.go\",\n- \"goid_unsafe.go\",\n],\nvisibility = [\"//visibility:public\"],\n)\n@@ -18,7 +16,6 @@ go_test(\nname = \"goid_test\",\nsize = \"small\",\nsrcs = [\n- \"empty_test.go\",\n\"goid_test.go\",\n],\nlibrary = \":goid\",\n"
},
{
"change_type": "DELETE",
"old_path": "pkg/goid/empty_test.go",
"new_path": null,
"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 !race\n-\n-package goid\n-\n-import \"testing\"\n-\n-// TestNothing exists to make the build system happy.\n-func TestNothing(t *testing.T) {}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/goid/goid.go",
"new_path": "pkg/goid/goid.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build !race\n+// +build go1.12\n+// +build !go1.17\n-// Package goid provides access to the ID of the current goroutine in\n-// race/gotsan builds.\n+// Check type signatures when updating Go version.\n+\n+// Package goid provides the Get function.\npackage goid\n// Get returns the ID of the current goroutine.\nfunc Get() int64 {\n- panic(\"unimplemented for non-race builds\")\n+ return getg().goid\n+}\n+\n+// Structs from Go runtime. These may change in the future and require\n+// updating. These structs are currently the same on both AMD64 and ARM64,\n+// but may diverge in the future.\n+\n+type stack struct {\n+ lo uintptr\n+ hi uintptr\n+}\n+\n+type gobuf struct {\n+ sp uintptr\n+ pc uintptr\n+ g uintptr\n+ ctxt uintptr\n+ ret uint64\n+ lr uintptr\n+ bp uintptr\n}\n+\n+type g struct {\n+ stack stack\n+ stackguard0 uintptr\n+ stackguard1 uintptr\n+\n+ _panic uintptr\n+ _defer uintptr\n+ m uintptr\n+ sched gobuf\n+ syscallsp uintptr\n+ syscallpc uintptr\n+ stktopsp uintptr\n+ param uintptr\n+ atomicstatus uint32\n+ stackLock uint32\n+ goid int64\n+\n+ // More fields...\n+ //\n+ // We only use goid and the fields before it are only listed to\n+ // calculate the correct offset.\n+}\n+\n+// Defined in assembly. This can't use go:linkname since runtime.getg() isn't a\n+// real function, it's a compiler intrinsic.\n+func getg() *g\n"
},
{
"change_type": "DELETE",
"old_path": "pkg/goid/goid_race.go",
"new_path": null,
"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-// Only available in race/gotsan builds.\n-// +build race\n-\n-// Package goid provides access to the ID of the current goroutine in\n-// race/gotsan builds.\n-package goid\n-\n-// Get returns the ID of the current goroutine.\n-func Get() int64 {\n- return goid()\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/goid/goid_test.go",
"new_path": "pkg/goid/goid_test.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build race\n-\npackage goid\nimport (\n\"runtime\"\n\"sync\"\n\"testing\"\n+ \"time\"\n)\n-func TestInitialGoID(t *testing.T) {\n- const max = 10000\n- if id := goid(); id < 0 || id > max {\n- t.Errorf(\"got goid = %d, want 0 < goid <= %d\", id, max)\n- }\n-}\n-\n-// TestGoIDSquence verifies that goid returns values which could plausibly be\n-// goroutine IDs. If this test breaks or becomes flaky, the structs in\n-// goid_unsafe.go may need to be updated.\n-func TestGoIDSquence(t *testing.T) {\n- // Goroutine IDs are cached by each P.\n- runtime.GOMAXPROCS(1)\n+func TestUniquenessAndConsistency(t *testing.T) {\n+ const (\n+ numGoroutines = 5000\n- // Fill any holes in lower range.\n- for i := 0; i < 50; i++ {\n- var wg sync.WaitGroup\n- wg.Add(1)\n- go func() {\n- wg.Done()\n-\n- // Leak the goroutine to prevent the ID from being\n- // reused.\n- select {}\n- }()\n- wg.Wait()\n- }\n+ // maxID is not an intrinsic property of goroutine IDs; it is only a\n+ // property of how the Go runtime currently assigns them. Future\n+ // changes to the Go runtime may require that maxID be raised, or that\n+ // assertions regarding it be removed entirely.\n+ maxID = numGoroutines + 1000\n+ )\n- id := goid()\n- for i := 0; i < 100; i++ {\nvar (\n- newID int64\n- wg sync.WaitGroup\n+ goidsMu sync.Mutex\n+ goids = make(map[int64]struct{})\n+ checkedWG sync.WaitGroup\n+ exitCh = make(chan struct{})\n)\n- wg.Add(1)\n+ for i := 0; i < numGoroutines; i++ {\n+ checkedWG.Add(1)\ngo func() {\n- newID = goid()\n- wg.Done()\n-\n- // Leak the goroutine to prevent the ID from being\n- // reused.\n- select {}\n- }()\n- wg.Wait()\n- if max := id + 100; newID <= id || newID > max {\n- t.Errorf(\"unexpected goroutine ID pattern, got goid = %d, want %d < goid <= %d (previous = %d)\", newID, id, max, id)\n+ id := Get()\n+ if id > maxID {\n+ t.Errorf(\"observed unexpectedly large goroutine ID %d\", id)\n+ }\n+ goidsMu.Lock()\n+ if _, dup := goids[id]; dup {\n+ t.Errorf(\"observed duplicate goroutine ID %d\", id)\n}\n- id = newID\n+ goids[id] = struct{}{}\n+ goidsMu.Unlock()\n+ checkedWG.Done()\n+ for {\n+ if curID := Get(); curID != id {\n+ t.Errorf(\"goroutine ID changed from %d to %d\", id, curID)\n+ // Don't spam logs by repeating the check; wait quietly for\n+ // the test to finish.\n+ <-exitCh\n+ return\n+ }\n+ // Check if the test is over.\n+ select {\n+ case <-exitCh:\n+ return\n+ default:\n+ }\n+ // Yield to other goroutines, and possibly migrate to another P.\n+ runtime.Gosched()\n+ }\n+ }()\n}\n+ // Wait for all goroutines to perform uniqueness checks.\n+ checkedWG.Wait()\n+ // Wait for an additional second to allow goroutines to spin checking for\n+ // ID consistency.\n+ time.Sleep(time.Second)\n+ // Request that all goroutines exit.\n+ close(exitCh)\n}\n"
},
{
"change_type": "DELETE",
"old_path": "pkg/goid/goid_unsafe.go",
"new_path": null,
"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 goid\n-\n-// Structs from Go runtime. These may change in the future and require\n-// updating. These structs are currently the same on both AMD64 and ARM64,\n-// but may diverge in the future.\n-\n-type stack struct {\n- lo uintptr\n- hi uintptr\n-}\n-\n-type gobuf struct {\n- sp uintptr\n- pc uintptr\n- g uintptr\n- ctxt uintptr\n- ret uint64\n- lr uintptr\n- bp uintptr\n-}\n-\n-type g struct {\n- stack stack\n- stackguard0 uintptr\n- stackguard1 uintptr\n-\n- _panic uintptr\n- _defer uintptr\n- m uintptr\n- sched gobuf\n- syscallsp uintptr\n- syscallpc uintptr\n- stktopsp uintptr\n- param uintptr\n- atomicstatus uint32\n- stackLock uint32\n- goid int64\n-\n- // More fields...\n- //\n- // We only use goid and the fields before it are only listed to\n- // calculate the correct offset.\n-}\n-\n-func getg() *g\n-\n-// goid returns the ID of the current goroutine.\n-func goid() int64 {\n- return getg().goid\n-}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow goid.Get() to be used outside of race builds.
PiperOrigin-RevId: 342179912 |
260,023 | 12.11.2020 23:02:15 | 28,800 | 8e6963491c7bc9b98fc7bcff5024089726a9c204 | Deflake tcp_socket test.
Increase the wait time for the thread to be blocked on read/write
syscall. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/tcp_socket.cc",
"new_path": "test/syscalls/linux/tcp_socket.cc",
"diff": "@@ -467,7 +467,7 @@ TEST_P(TcpSocketTest, PollWithFullBufferBlocks) {\nTEST_P(TcpSocketTest, ClosedWriteBlockingSocket) {\nFillSocketBuffers(first_fd, second_fd);\n- constexpr int timeout = 2;\n+ constexpr int timeout = 10;\nstruct timeval tv = {.tv_sec = timeout, .tv_usec = 0};\nEXPECT_THAT(setsockopt(first_fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)),\nSyscallSucceeds());\n@@ -485,7 +485,7 @@ TEST_P(TcpSocketTest, ClosedWriteBlockingSocket) {\n});\n// Wait for the thread to be blocked on write.\n- absl::SleepFor(absl::Milliseconds(50));\n+ absl::SleepFor(absl::Milliseconds(250));\n// Socket close does not have any effect on a blocked write.\nASSERT_THAT(close(first_fd), SyscallSucceeds());\n// Indicate to the cleanup routine that we are already closed.\n@@ -518,7 +518,7 @@ TEST_P(TcpSocketTest, ClosedReadBlockingSocket) {\n});\n// Wait for the thread to be blocked on read.\n- absl::SleepFor(absl::Milliseconds(50));\n+ absl::SleepFor(absl::Milliseconds(250));\n// Socket close does not have any effect on a blocked read.\nASSERT_THAT(close(first_fd), SyscallSucceeds());\n// Indicate to the cleanup routine that we are already closed.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Deflake tcp_socket test.
Increase the wait time for the thread to be blocked on read/write
syscall.
PiperOrigin-RevId: 342204627 |
259,853 | 13.11.2020 00:46:16 | 28,800 | cc1b20590cf4505e04b8c221d1d950e45110f5f0 | fs/tmpfs: use atomic operations to access inode.mode | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"diff": "@@ -631,7 +631,8 @@ func (i *inode) direntType() uint8 {\n}\nfunc (i *inode) isDir() bool {\n- return linux.FileMode(i.mode).FileType() == linux.S_IFDIR\n+ mode := linux.FileMode(atomic.LoadUint32(&i.mode))\n+ return mode.FileType() == linux.S_IFDIR\n}\nfunc (i *inode) touchAtime(mnt *vfs.Mount) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | fs/tmpfs: use atomic operations to access inode.mode
PiperOrigin-RevId: 342214859 |
259,853 | 13.11.2020 01:49:36 | 28,800 | e869e2c7cddca0337b6dfb28584b05ee1b225a7f | fs/tmpfs: change regularFile.size atomically | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go",
"diff": "@@ -565,7 +565,7 @@ func (rw *regularFileReadWriter) ReadToBlocks(dsts safemem.BlockSeq) (uint64, er\n// WriteFromBlocks implements safemem.Writer.WriteFromBlocks.\n//\n-// Preconditions: inode.mu must be held.\n+// Preconditions: rw.file.inode.mu must be held.\nfunc (rw *regularFileReadWriter) WriteFromBlocks(srcs safemem.BlockSeq) (uint64, error) {\n// Hold dataMu so we can modify size.\nrw.file.dataMu.Lock()\n@@ -657,7 +657,7 @@ exitLoop:\n// If the write ends beyond the file's previous size, it causes the\n// file to grow.\nif rw.off > rw.file.size {\n- rw.file.size = rw.off\n+ atomic.StoreUint64(&rw.file.size, rw.off)\n}\nreturn done, retErr\n"
}
] | Go | Apache License 2.0 | google/gvisor | fs/tmpfs: change regularFile.size atomically
PiperOrigin-RevId: 342221309 |
259,885 | 13.11.2020 01:52:59 | 28,800 | 280cf46874cd8f4bd4fa16125aa6c0914b888deb | Minor fdchannel fixes.
Don't close fdchannel.Endpoint.sockfd in Shutdown(), while it still may be in
use.
Don't call runtime.enter/exitsyscall from RecvFDNonblock(). | [
{
"change_type": "MODIFY",
"old_path": "pkg/fdchannel/fdchannel_unsafe.go",
"new_path": "pkg/fdchannel/fdchannel_unsafe.go",
"diff": "@@ -21,7 +21,6 @@ package fdchannel\nimport (\n\"fmt\"\n\"reflect\"\n- \"sync/atomic\"\n\"syscall\"\n\"unsafe\"\n)\n@@ -41,7 +40,7 @@ func NewConnectedSockets() ([2]int, error) {\n//\n// Endpoint is not copyable or movable by value.\ntype Endpoint struct {\n- sockfd int32 // accessed using atomic memory operations\n+ sockfd int32\nmsghdr syscall.Msghdr\ncmsg *syscall.Cmsghdr // followed by sizeofInt32 bytes of data\n}\n@@ -54,10 +53,10 @@ func (ep *Endpoint) Init(sockfd int) {\n// sendmsg+recvmsg for a zero-length datagram is slightly faster than\n// sendmsg+recvmsg for a single byte over a stream socket.\ncmsgSlice := make([]byte, syscall.CmsgSpace(sizeofInt32))\n- cmsgReflect := (*reflect.SliceHeader)((unsafe.Pointer)(&cmsgSlice))\n+ cmsgReflect := (*reflect.SliceHeader)(unsafe.Pointer(&cmsgSlice))\nep.sockfd = int32(sockfd)\n- ep.msghdr.Control = (*byte)((unsafe.Pointer)(cmsgReflect.Data))\n- ep.cmsg = (*syscall.Cmsghdr)((unsafe.Pointer)(cmsgReflect.Data))\n+ ep.msghdr.Control = (*byte)(unsafe.Pointer(cmsgReflect.Data))\n+ ep.cmsg = (*syscall.Cmsghdr)(unsafe.Pointer(cmsgReflect.Data))\n// ep.msghdr.Controllen and ep.cmsg.* are mutated by recvmsg(2), so they're\n// set before calling sendmsg/recvmsg.\n}\n@@ -73,13 +72,9 @@ func NewEndpoint(sockfd int) *Endpoint {\n// Destroy releases resources owned by ep. No other Endpoint methods may be\n// called after Destroy.\nfunc (ep *Endpoint) Destroy() {\n- // These need not use sync/atomic since there must not be any concurrent\n- // calls to Endpoint methods.\n- if ep.sockfd >= 0 {\nsyscall.Close(int(ep.sockfd))\nep.sockfd = -1\n}\n-}\n// Shutdown causes concurrent and future calls to ep.SendFD(), ep.RecvFD(), and\n// ep.RecvFDNonblock(), as well as the same calls in the connected Endpoint, to\n@@ -88,10 +83,7 @@ func (ep *Endpoint) Destroy() {\n// Shutdown is the only Endpoint method that may be called concurrently with\n// other methods.\nfunc (ep *Endpoint) Shutdown() {\n- if sockfd := int(atomic.SwapInt32(&ep.sockfd, -1)); sockfd >= 0 {\n- syscall.Shutdown(sockfd, syscall.SHUT_RDWR)\n- syscall.Close(sockfd)\n- }\n+ syscall.Shutdown(int(ep.sockfd), syscall.SHUT_RDWR)\n}\n// SendFD sends the open file description represented by the given file\n@@ -103,7 +95,7 @@ func (ep *Endpoint) SendFD(fd int) error {\nep.cmsg.SetLen(cmsgLen)\n*ep.cmsgData() = int32(fd)\nep.msghdr.SetControllen(cmsgLen)\n- _, _, e := syscall.Syscall(syscall.SYS_SENDMSG, uintptr(atomic.LoadInt32(&ep.sockfd)), uintptr((unsafe.Pointer)(&ep.msghdr)), 0)\n+ _, _, e := syscall.Syscall(syscall.SYS_SENDMSG, uintptr(ep.sockfd), uintptr(unsafe.Pointer(&ep.msghdr)), 0)\nif e != 0 {\nreturn e\n}\n@@ -113,7 +105,7 @@ func (ep *Endpoint) SendFD(fd int) error {\n// RecvFD receives an open file description from the connected Endpoint and\n// returns a file descriptor representing it, owned by the caller.\nfunc (ep *Endpoint) RecvFD() (int, error) {\n- return ep.recvFD(0)\n+ return ep.recvFD(false)\n}\n// RecvFDNonblock receives an open file description from the connected Endpoint\n@@ -121,13 +113,18 @@ func (ep *Endpoint) RecvFD() (int, error) {\n// are no pending receivable open file descriptions, RecvFDNonblock returns\n// (<unspecified>, EAGAIN or EWOULDBLOCK).\nfunc (ep *Endpoint) RecvFDNonblock() (int, error) {\n- return ep.recvFD(syscall.MSG_DONTWAIT)\n+ return ep.recvFD(true)\n}\n-func (ep *Endpoint) recvFD(flags uintptr) (int, error) {\n+func (ep *Endpoint) recvFD(nonblock bool) (int, error) {\ncmsgLen := syscall.CmsgLen(sizeofInt32)\nep.msghdr.SetControllen(cmsgLen)\n- _, _, e := syscall.Syscall(syscall.SYS_RECVMSG, uintptr(atomic.LoadInt32(&ep.sockfd)), uintptr((unsafe.Pointer)(&ep.msghdr)), flags|syscall.MSG_TRUNC)\n+ var e syscall.Errno\n+ if nonblock {\n+ _, _, e = syscall.RawSyscall(syscall.SYS_RECVMSG, uintptr(ep.sockfd), uintptr(unsafe.Pointer(&ep.msghdr)), syscall.MSG_TRUNC|syscall.MSG_DONTWAIT)\n+ } else {\n+ _, _, e = syscall.Syscall(syscall.SYS_RECVMSG, uintptr(ep.sockfd), uintptr(unsafe.Pointer(&ep.msghdr)), syscall.MSG_TRUNC)\n+ }\nif e != 0 {\nreturn -1, e\n}\n@@ -142,5 +139,5 @@ func (ep *Endpoint) recvFD(flags uintptr) (int, error) {\nfunc (ep *Endpoint) cmsgData() *int32 {\n// syscall.CmsgLen(0) == syscall.cmsgAlignOf(syscall.SizeofCmsghdr)\n- return (*int32)((unsafe.Pointer)(uintptr((unsafe.Pointer)(ep.cmsg)) + uintptr(syscall.CmsgLen(0))))\n+ return (*int32)(unsafe.Pointer(uintptr(unsafe.Pointer(ep.cmsg)) + uintptr(syscall.CmsgLen(0))))\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Minor fdchannel fixes.
- Don't close fdchannel.Endpoint.sockfd in Shutdown(), while it still may be in
use.
- Don't call runtime.enter/exitsyscall from RecvFDNonblock().
PiperOrigin-RevId: 342221770 |
259,885 | 13.11.2020 12:22:38 | 28,800 | d5e17d2dbc2809c6d70153f0d4c996eff899e69d | Disable save/restore in PartialBadBufferTest.SendMsgTCP. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/partial_bad_buffer.cc",
"new_path": "test/syscalls/linux/partial_bad_buffer.cc",
"diff": "@@ -320,7 +320,10 @@ PosixErrorOr<sockaddr_storage> InetLoopbackAddr(int family) {\n// EFAULT. It also verifies that passing a buffer which is made up of 2\n// pages one valid and one guard page succeeds as long as the write is\n// for exactly the size of 1 page.\n-TEST_F(PartialBadBufferTest, SendMsgTCP) {\n+TEST_F(PartialBadBufferTest, SendMsgTCP_NoRandomSave) {\n+ // FIXME(b/171436815): Netstack save/restore is broken.\n+ const DisableSave ds;\n+\nauto listen_socket =\nASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP));\n"
}
] | Go | Apache License 2.0 | google/gvisor | Disable save/restore in PartialBadBufferTest.SendMsgTCP.
PiperOrigin-RevId: 342314586 |
260,004 | 13.11.2020 13:10:51 | 28,800 | 6c0f53002a7f3a518befbe667d308c3d64cc9a59 | Decrement TTL/Hop Limit when forwarding IP packets
If the packet must no longer be forwarded because its TTL/Hop Limit
reaches 0, send an ICMP Time Exceeded error to the source.
Required as per relevant RFCs. See comments in code for RFC references.
Fixes
Tests:
- ipv4_test.TestForwarding
- ipv6.TestForwarding | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/checker/checker.go",
"new_path": "pkg/tcpip/checker/checker.go",
"diff": "@@ -904,6 +904,12 @@ func ICMPv4Payload(want []byte) TransportChecker {\nt.Fatalf(\"unexpected transport header passed to checker, got = %T, want = header.ICMPv4\", h)\n}\npayload := icmpv4.Payload()\n+\n+ // cmp.Diff does not consider nil slices equal to empty slices, but we do.\n+ if len(want) == 0 && len(payload) == 0 {\n+ return\n+ }\n+\nif diff := cmp.Diff(want, payload); diff != \"\" {\nt.Errorf(\"ICMP payload mismatch (-want +got):\\n%s\", diff)\n}\n@@ -994,6 +1000,12 @@ func ICMPv6Payload(want []byte) TransportChecker {\nt.Fatalf(\"unexpected transport header passed to checker, got = %T, want = header.ICMPv6\", h)\n}\npayload := icmpv6.Payload()\n+\n+ // cmp.Diff does not consider nil slices equal to empty slices, but we do.\n+ if len(want) == 0 && len(payload) == 0 {\n+ return\n+ }\n+\nif diff := cmp.Diff(want, payload); diff != \"\" {\nt.Errorf(\"ICMP payload mismatch (-want +got):\\n%s\", diff)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/ipv6.go",
"new_path": "pkg/tcpip/header/ipv6.go",
"diff": "@@ -54,7 +54,7 @@ type IPv6Fields struct {\n// NextHeader is the \"next header\" field of an IPv6 packet.\nNextHeader uint8\n- // HopLimit is the \"hop limit\" field of an IPv6 packet.\n+ // HopLimit is the \"Hop Limit\" field of an IPv6 packet.\nHopLimit uint8\n// SrcAddr is the \"source ip address\" of an IPv6 packet.\n@@ -171,7 +171,7 @@ func (b IPv6) PayloadLength() uint16 {\nreturn binary.BigEndian.Uint16(b[IPv6PayloadLenOffset:])\n}\n-// HopLimit returns the value of the \"hop limit\" field of the ipv6 header.\n+// HopLimit returns the value of the \"Hop Limit\" field of the ipv6 header.\nfunc (b IPv6) HopLimit() uint8 {\nreturn b[hopLimit]\n}\n@@ -236,6 +236,11 @@ func (b IPv6) SetDestinationAddress(addr tcpip.Address) {\ncopy(b[v6DstAddr:][:IPv6AddressSize], addr)\n}\n+// SetHopLimit sets the value of the \"Hop Limit\" field.\n+func (b IPv6) SetHopLimit(v uint8) {\n+ b[hopLimit] = v\n+}\n+\n// SetNextHeader sets the value of the \"next header\" field of the ipv6 header.\nfunc (b IPv6) SetNextHeader(v uint8) {\nb[IPv6NextHeaderOffset] = v\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/icmp.go",
"new_path": "pkg/tcpip/network/ipv4/icmp.go",
"diff": "@@ -290,6 +290,13 @@ type icmpReasonProtoUnreachable struct{}\nfunc (*icmpReasonProtoUnreachable) isICMPReason() {}\n+// icmpReasonTTLExceeded is an error where a packet's time to live exceeded in\n+// transit to its final destination, as per RFC 792 page 6, Time Exceeded\n+// Message.\n+type icmpReasonTTLExceeded struct{}\n+\n+func (*icmpReasonTTLExceeded) isICMPReason() {}\n+\n// icmpReasonReassemblyTimeout is an error where insufficient fragments are\n// received to complete reassembly of a packet within a configured time after\n// the reception of the first-arriving fragment of that packet.\n@@ -342,11 +349,31 @@ func (p *protocol) returnError(reason icmpReason, pkt *stack.PacketBuffer) *tcpi\nreturn nil\n}\n+ // If we hit a TTL Exceeded error, then we know we are operating as a router.\n+ // As per RFC 792 page 6, Time Exceeded Message,\n+ //\n+ // If the gateway processing a datagram finds the time to live field\n+ // is zero it must discard the datagram. The gateway may also notify\n+ // the source host via the time exceeded message.\n+ //\n+ // ...\n+ //\n+ // Code 0 may be received from a gateway. ...\n+ //\n+ // Note, Code 0 is the TTL exceeded error.\n+ //\n+ // If we are operating as a router/gateway, don't use the packet's destination\n+ // address as the response's source address as we should not not own the\n+ // destination address of a packet we are forwarding.\n+ localAddr := origIPHdrDst\n+ if _, ok := reason.(*icmpReasonTTLExceeded); ok {\n+ localAddr = \"\"\n+ }\n// Even if we were able to receive a packet from some remote, we may not have\n// a route to it - the remote may be blocked via routing rules. We must always\n// consult our routing table and find a route to the remote before sending any\n// packet.\n- route, err := p.stack.FindRoute(pkt.NICID, origIPHdrDst, origIPHdrSrc, ProtocolNumber, false /* multicastLoop */)\n+ route, err := p.stack.FindRoute(pkt.NICID, localAddr, origIPHdrSrc, ProtocolNumber, false /* multicastLoop */)\nif err != nil {\nreturn err\n}\n@@ -454,6 +481,10 @@ func (p *protocol) returnError(reason icmpReason, pkt *stack.PacketBuffer) *tcpi\nicmpHdr.SetType(header.ICMPv4DstUnreachable)\nicmpHdr.SetCode(header.ICMPv4ProtoUnreachable)\ncounter = sent.DstUnreachable\n+ case *icmpReasonTTLExceeded:\n+ icmpHdr.SetType(header.ICMPv4TimeExceeded)\n+ icmpHdr.SetCode(header.ICMPv4TTLExceeded)\n+ counter = sent.TimeExceeded\ncase *icmpReasonReassemblyTimeout:\nicmpHdr.SetType(header.ICMPv4TimeExceeded)\nicmpHdr.SetCode(header.ICMPv4ReassemblyTimeout)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4.go",
"diff": "@@ -485,6 +485,16 @@ func (e *endpoint) WriteHeaderIncludedPacket(r *stack.Route, pkt *stack.PacketBu\n// forwardPacket attempts to forward a packet to its final destination.\nfunc (e *endpoint) forwardPacket(pkt *stack.PacketBuffer) *tcpip.Error {\nh := header.IPv4(pkt.NetworkHeader().View())\n+ ttl := h.TTL()\n+ if ttl == 0 {\n+ // As per RFC 792 page 6, Time Exceeded Message,\n+ //\n+ // If the gateway processing a datagram finds the time to live field\n+ // is zero it must discard the datagram. The gateway may also notify\n+ // the source host via the time exceeded message.\n+ return e.protocol.returnError(&icmpReasonTTLExceeded{}, pkt)\n+ }\n+\ndstAddr := h.DestinationAddress()\n// Check if the destination is owned by the stack.\n@@ -503,13 +513,22 @@ func (e *endpoint) forwardPacket(pkt *stack.PacketBuffer) *tcpip.Error {\n}\ndefer r.Release()\n- // TODO(b/143425874) Decrease the TTL field in forwarded packets.\n- return r.WriteHeaderIncludedPacket(stack.NewPacketBuffer(stack.PacketBufferOptions{\n- ReserveHeaderBytes: int(r.MaxHeaderLength()),\n// We need to do a deep copy of the IP packet because\n// WriteHeaderIncludedPacket takes ownership of the packet buffer, but we do\n// not own it.\n- Data: stack.PayloadSince(pkt.NetworkHeader()).ToVectorisedView(),\n+ newHdr := header.IPv4(stack.PayloadSince(pkt.NetworkHeader()))\n+\n+ // As per RFC 791 page 30, Time to Live,\n+ //\n+ // This field must be decreased at each point that the internet header\n+ // is processed to reflect the time spent processing the datagram.\n+ // Even if no local information is available on the time actually\n+ // spent, the field must be decremented by 1.\n+ newHdr.SetTTL(ttl - 1)\n+\n+ return r.WriteHeaderIncludedPacket(stack.NewPacketBuffer(stack.PacketBufferOptions{\n+ ReserveHeaderBytes: int(r.MaxHeaderLength()),\n+ Data: buffer.View(newHdr).ToVectorisedView(),\n}))\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4_test.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4_test.go",
"diff": "@@ -202,6 +202,163 @@ func TestIPv4EncodeOptions(t *testing.T) {\n}\n}\n+func TestForwarding(t *testing.T) {\n+ const (\n+ nicID1 = 1\n+ nicID2 = 2\n+ randomSequence = 123\n+ randomIdent = 42\n+ )\n+\n+ ipv4Addr1 := tcpip.AddressWithPrefix{\n+ Address: tcpip.Address(net.ParseIP(\"10.0.0.1\").To4()),\n+ PrefixLen: 8,\n+ }\n+ ipv4Addr2 := tcpip.AddressWithPrefix{\n+ Address: tcpip.Address(net.ParseIP(\"11.0.0.1\").To4()),\n+ PrefixLen: 8,\n+ }\n+ remoteIPv4Addr1 := tcpip.Address(net.ParseIP(\"10.0.0.2\").To4())\n+ remoteIPv4Addr2 := tcpip.Address(net.ParseIP(\"11.0.0.2\").To4())\n+\n+ tests := []struct {\n+ name string\n+ TTL uint8\n+ expectErrorICMP bool\n+ }{\n+ {\n+ name: \"TTL of zero\",\n+ TTL: 0,\n+ expectErrorICMP: true,\n+ },\n+ {\n+ name: \"TTL of one\",\n+ TTL: 1,\n+ expectErrorICMP: false,\n+ },\n+ {\n+ name: \"TTL of two\",\n+ TTL: 2,\n+ expectErrorICMP: false,\n+ },\n+ {\n+ name: \"Max TTL\",\n+ TTL: math.MaxUint8,\n+ expectErrorICMP: false,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol},\n+ TransportProtocols: []stack.TransportProtocolFactory{icmp.NewProtocol4},\n+ })\n+ // We expect at most a single packet in response to our ICMP Echo Request.\n+ e1 := channel.New(1, ipv4.MaxTotalSize, \"\")\n+ if err := s.CreateNIC(nicID1, e1); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", nicID1, err)\n+ }\n+ ipv4ProtoAddr1 := tcpip.ProtocolAddress{Protocol: header.IPv4ProtocolNumber, AddressWithPrefix: ipv4Addr1}\n+ if err := s.AddProtocolAddress(nicID1, ipv4ProtoAddr1); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %#v): %s\", nicID1, ipv4ProtoAddr1, err)\n+ }\n+\n+ e2 := channel.New(1, ipv4.MaxTotalSize, \"\")\n+ if err := s.CreateNIC(nicID2, e2); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", nicID2, err)\n+ }\n+ ipv4ProtoAddr2 := tcpip.ProtocolAddress{Protocol: header.IPv4ProtocolNumber, AddressWithPrefix: ipv4Addr2}\n+ if err := s.AddProtocolAddress(nicID2, ipv4ProtoAddr2); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %#v): %s\", nicID2, ipv4ProtoAddr2, err)\n+ }\n+\n+ s.SetRouteTable([]tcpip.Route{\n+ {\n+ Destination: ipv4Addr1.Subnet(),\n+ NIC: nicID1,\n+ },\n+ {\n+ Destination: ipv4Addr2.Subnet(),\n+ NIC: nicID2,\n+ },\n+ })\n+\n+ if err := s.SetForwarding(header.IPv4ProtocolNumber, true); err != nil {\n+ t.Fatalf(\"SetForwarding(%d, true): %s\", header.IPv4ProtocolNumber, err)\n+ }\n+\n+ totalLen := uint16(header.IPv4MinimumSize + header.ICMPv4MinimumSize)\n+ hdr := buffer.NewPrependable(int(totalLen))\n+ icmp := header.ICMPv4(hdr.Prepend(header.ICMPv4MinimumSize))\n+ icmp.SetIdent(randomIdent)\n+ icmp.SetSequence(randomSequence)\n+ icmp.SetType(header.ICMPv4Echo)\n+ icmp.SetCode(header.ICMPv4UnusedCode)\n+ icmp.SetChecksum(0)\n+ icmp.SetChecksum(^header.Checksum(icmp, 0))\n+ ip := header.IPv4(hdr.Prepend(header.IPv4MinimumSize))\n+ ip.Encode(&header.IPv4Fields{\n+ TotalLength: totalLen,\n+ Protocol: uint8(header.ICMPv4ProtocolNumber),\n+ TTL: test.TTL,\n+ SrcAddr: remoteIPv4Addr1,\n+ DstAddr: remoteIPv4Addr2,\n+ })\n+ ip.SetChecksum(0)\n+ ip.SetChecksum(^ip.CalculateChecksum())\n+ requestPkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n+ Data: hdr.View().ToVectorisedView(),\n+ })\n+ e1.InjectInbound(header.IPv4ProtocolNumber, requestPkt)\n+\n+ if test.expectErrorICMP {\n+ reply, ok := e1.Read()\n+ if !ok {\n+ t.Fatal(\"expected ICMP TTL Exceeded packet through incoming NIC\")\n+ }\n+\n+ checker.IPv4(t, header.IPv4(stack.PayloadSince(reply.Pkt.NetworkHeader())),\n+ checker.SrcAddr(ipv4Addr1.Address),\n+ checker.DstAddr(remoteIPv4Addr1),\n+ checker.TTL(ipv4.DefaultTTL),\n+ checker.ICMPv4(\n+ checker.ICMPv4Checksum(),\n+ checker.ICMPv4Type(header.ICMPv4TimeExceeded),\n+ checker.ICMPv4Code(header.ICMPv4TTLExceeded),\n+ checker.ICMPv4Payload([]byte(hdr.View())),\n+ ),\n+ )\n+\n+ if n := e2.Drain(); n != 0 {\n+ t.Fatalf(\"got e2.Drain() = %d, want = 0\", n)\n+ }\n+ } else {\n+ reply, ok := e2.Read()\n+ if !ok {\n+ t.Fatal(\"expected ICMP Echo packet through outgoing NIC\")\n+ }\n+\n+ checker.IPv4(t, header.IPv4(stack.PayloadSince(reply.Pkt.NetworkHeader())),\n+ checker.SrcAddr(remoteIPv4Addr1),\n+ checker.DstAddr(remoteIPv4Addr2),\n+ checker.TTL(test.TTL-1),\n+ checker.ICMPv4(\n+ checker.ICMPv4Checksum(),\n+ checker.ICMPv4Type(header.ICMPv4Echo),\n+ checker.ICMPv4Code(header.ICMPv4UnusedCode),\n+ checker.ICMPv4Payload(nil),\n+ ),\n+ )\n+\n+ if n := e1.Drain(); n != 0 {\n+ t.Fatalf(\"got e1.Drain() = %d, want = 0\", n)\n+ }\n+ }\n+ })\n+ }\n+}\n+\n// TestIPv4Sanity sends IP/ICMP packets with various problems to the stack and\n// checks the response.\nfunc TestIPv4Sanity(t *testing.T) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/icmp.go",
"new_path": "pkg/tcpip/network/ipv6/icmp.go",
"diff": "@@ -750,6 +750,12 @@ type icmpReasonPortUnreachable struct{}\nfunc (*icmpReasonPortUnreachable) isICMPReason() {}\n+// icmpReasonHopLimitExceeded is an error where a packet's hop limit exceeded in\n+// transit to its final destination, as per RFC 4443 section 3.3.\n+type icmpReasonHopLimitExceeded struct{}\n+\n+func (*icmpReasonHopLimitExceeded) isICMPReason() {}\n+\n// icmpReasonReassemblyTimeout is an error where insufficient fragments are\n// received to complete reassembly of a packet within a configured time after\n// the reception of the first-arriving fragment of that packet.\n@@ -794,11 +800,27 @@ func (p *protocol) returnError(reason icmpReason, pkt *stack.PacketBuffer) *tcpi\nreturn nil\n}\n+ // If we hit a Hop Limit Exceeded error, then we know we are operating as a\n+ // router. As per RFC 4443 section 3.3:\n+ //\n+ // If a router receives a packet with a Hop Limit of zero, or if a\n+ // router decrements a packet's Hop Limit to zero, it MUST discard the\n+ // packet and originate an ICMPv6 Time Exceeded message with Code 0 to\n+ // the source of the packet. This indicates either a routing loop or\n+ // too small an initial Hop Limit value.\n+ //\n+ // If we are operating as a router, do not use the packet's destination\n+ // address as the response's source address as we should not own the\n+ // destination address of a packet we are forwarding.\n+ localAddr := origIPHdrDst\n+ if _, ok := reason.(*icmpReasonHopLimitExceeded); ok {\n+ localAddr = \"\"\n+ }\n// Even if we were able to receive a packet from some remote, we may not have\n// a route to it - the remote may be blocked via routing rules. We must always\n// consult our routing table and find a route to the remote before sending any\n// packet.\n- route, err := p.stack.FindRoute(pkt.NICID, origIPHdrDst, origIPHdrSrc, ProtocolNumber, false /* multicastLoop */)\n+ route, err := p.stack.FindRoute(pkt.NICID, localAddr, origIPHdrSrc, ProtocolNumber, false /* multicastLoop */)\nif err != nil {\nreturn err\n}\n@@ -811,8 +833,6 @@ func (p *protocol) returnError(reason icmpReason, pkt *stack.PacketBuffer) *tcpi\nreturn nil\n}\n- network, transport := pkt.NetworkHeader().View(), pkt.TransportHeader().View()\n-\nif pkt.TransportProtocolNumber == header.ICMPv6ProtocolNumber {\n// TODO(gvisor.dev/issues/3810): Sort this out when ICMP headers are stored.\n// Unfortunately at this time ICMP Packets do not have a transport\n@@ -830,6 +850,8 @@ func (p *protocol) returnError(reason icmpReason, pkt *stack.PacketBuffer) *tcpi\n}\n}\n+ network, transport := pkt.NetworkHeader().View(), pkt.TransportHeader().View()\n+\n// As per RFC 4443 section 2.4\n//\n// (c) Every ICMPv6 error message (type < 128) MUST include\n@@ -873,6 +895,10 @@ func (p *protocol) returnError(reason icmpReason, pkt *stack.PacketBuffer) *tcpi\nicmpHdr.SetType(header.ICMPv6DstUnreachable)\nicmpHdr.SetCode(header.ICMPv6PortUnreachable)\ncounter = sent.DstUnreachable\n+ case *icmpReasonHopLimitExceeded:\n+ icmpHdr.SetType(header.ICMPv6TimeExceeded)\n+ icmpHdr.SetCode(header.ICMPv6HopLimitExceeded)\n+ counter = sent.TimeExceeded\ncase *icmpReasonReassemblyTimeout:\nicmpHdr.SetType(header.ICMPv6TimeExceeded)\nicmpHdr.SetCode(header.ICMPv6ReassemblyTimeout)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6.go",
"diff": "@@ -645,6 +645,18 @@ func (e *endpoint) WriteHeaderIncludedPacket(r *stack.Route, pkt *stack.PacketBu\n// forwardPacket attempts to forward a packet to its final destination.\nfunc (e *endpoint) forwardPacket(pkt *stack.PacketBuffer) *tcpip.Error {\nh := header.IPv6(pkt.NetworkHeader().View())\n+ hopLimit := h.HopLimit()\n+ if hopLimit <= 1 {\n+ // As per RFC 4443 section 3.3,\n+ //\n+ // If a router receives a packet with a Hop Limit of zero, or if a\n+ // router decrements a packet's Hop Limit to zero, it MUST discard the\n+ // packet and originate an ICMPv6 Time Exceeded message with Code 0 to\n+ // the source of the packet. This indicates either a routing loop or\n+ // too small an initial Hop Limit value.\n+ return e.protocol.returnError(&icmpReasonHopLimitExceeded{}, pkt)\n+ }\n+\ndstAddr := h.DestinationAddress()\n// Check if the destination is owned by the stack.\n@@ -663,13 +675,20 @@ func (e *endpoint) forwardPacket(pkt *stack.PacketBuffer) *tcpip.Error {\n}\ndefer r.Release()\n- // TODO(b/143425874) Decrease the TTL field in forwarded packets.\n- return r.WriteHeaderIncludedPacket(stack.NewPacketBuffer(stack.PacketBufferOptions{\n- ReserveHeaderBytes: int(r.MaxHeaderLength()),\n// We need to do a deep copy of the IP packet because\n// WriteHeaderIncludedPacket takes ownership of the packet buffer, but we do\n// not own it.\n- Data: stack.PayloadSince(pkt.NetworkHeader()).ToVectorisedView(),\n+ newHdr := header.IPv6(stack.PayloadSince(pkt.NetworkHeader()))\n+\n+ // As per RFC 8200 section 3,\n+ //\n+ // Hop Limit 8-bit unsigned integer. Decremented by 1 by\n+ // each node that forwards the packet.\n+ newHdr.SetHopLimit(hopLimit - 1)\n+\n+ return r.WriteHeaderIncludedPacket(stack.NewPacketBuffer(stack.PacketBufferOptions{\n+ ReserveHeaderBytes: int(r.MaxHeaderLength()),\n+ Data: buffer.View(newHdr).ToVectorisedView(),\n}))\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6_test.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6_test.go",
"diff": "@@ -18,6 +18,7 @@ import (\n\"encoding/hex\"\n\"fmt\"\n\"math\"\n+ \"net\"\n\"testing\"\n\"github.com/google/go-cmp/cmp\"\n@@ -2821,3 +2822,160 @@ func TestFragmentationErrors(t *testing.T) {\n})\n}\n}\n+\n+func TestForwarding(t *testing.T) {\n+ const (\n+ nicID1 = 1\n+ nicID2 = 2\n+ randomSequence = 123\n+ randomIdent = 42\n+ )\n+\n+ ipv6Addr1 := tcpip.AddressWithPrefix{\n+ Address: tcpip.Address(net.ParseIP(\"10::1\").To16()),\n+ PrefixLen: 64,\n+ }\n+ ipv6Addr2 := tcpip.AddressWithPrefix{\n+ Address: tcpip.Address(net.ParseIP(\"11::1\").To16()),\n+ PrefixLen: 64,\n+ }\n+ remoteIPv6Addr1 := tcpip.Address(net.ParseIP(\"10::2\").To16())\n+ remoteIPv6Addr2 := tcpip.Address(net.ParseIP(\"11::2\").To16())\n+\n+ tests := []struct {\n+ name string\n+ TTL uint8\n+ expectErrorICMP bool\n+ }{\n+ {\n+ name: \"TTL of zero\",\n+ TTL: 0,\n+ expectErrorICMP: true,\n+ },\n+ {\n+ name: \"TTL of one\",\n+ TTL: 1,\n+ expectErrorICMP: true,\n+ },\n+ {\n+ name: \"TTL of two\",\n+ TTL: 2,\n+ expectErrorICMP: false,\n+ },\n+ {\n+ name: \"TTL of three\",\n+ TTL: 3,\n+ expectErrorICMP: false,\n+ },\n+ {\n+ name: \"Max TTL\",\n+ TTL: math.MaxUint8,\n+ expectErrorICMP: false,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{NewProtocol},\n+ TransportProtocols: []stack.TransportProtocolFactory{icmp.NewProtocol6},\n+ })\n+ // We expect at most a single packet in response to our ICMP Echo Request.\n+ e1 := channel.New(1, header.IPv6MinimumMTU, \"\")\n+ if err := s.CreateNIC(nicID1, e1); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", nicID1, err)\n+ }\n+ ipv6ProtoAddr1 := tcpip.ProtocolAddress{Protocol: ProtocolNumber, AddressWithPrefix: ipv6Addr1}\n+ if err := s.AddProtocolAddress(nicID1, ipv6ProtoAddr1); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %#v): %s\", nicID1, ipv6ProtoAddr1, err)\n+ }\n+\n+ e2 := channel.New(1, header.IPv6MinimumMTU, \"\")\n+ if err := s.CreateNIC(nicID2, e2); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", nicID2, err)\n+ }\n+ ipv6ProtoAddr2 := tcpip.ProtocolAddress{Protocol: ProtocolNumber, AddressWithPrefix: ipv6Addr2}\n+ if err := s.AddProtocolAddress(nicID2, ipv6ProtoAddr2); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %#v): %s\", nicID2, ipv6ProtoAddr2, err)\n+ }\n+\n+ s.SetRouteTable([]tcpip.Route{\n+ {\n+ Destination: ipv6Addr1.Subnet(),\n+ NIC: nicID1,\n+ },\n+ {\n+ Destination: ipv6Addr2.Subnet(),\n+ NIC: nicID2,\n+ },\n+ })\n+\n+ if err := s.SetForwarding(ProtocolNumber, true); err != nil {\n+ t.Fatalf(\"SetForwarding(%d, true): %s\", ProtocolNumber, err)\n+ }\n+\n+ hdr := buffer.NewPrependable(header.IPv6MinimumSize + header.ICMPv6MinimumSize)\n+ icmp := header.ICMPv6(hdr.Prepend(header.ICMPv6MinimumSize))\n+ icmp.SetIdent(randomIdent)\n+ icmp.SetSequence(randomSequence)\n+ icmp.SetType(header.ICMPv6EchoRequest)\n+ icmp.SetCode(header.ICMPv6UnusedCode)\n+ icmp.SetChecksum(0)\n+ icmp.SetChecksum(header.ICMPv6Checksum(icmp, remoteIPv6Addr1, remoteIPv6Addr2, buffer.VectorisedView{}))\n+ ip := header.IPv6(hdr.Prepend(header.IPv6MinimumSize))\n+ ip.Encode(&header.IPv6Fields{\n+ PayloadLength: header.ICMPv6MinimumSize,\n+ NextHeader: uint8(header.ICMPv6ProtocolNumber),\n+ HopLimit: test.TTL,\n+ SrcAddr: remoteIPv6Addr1,\n+ DstAddr: remoteIPv6Addr2,\n+ })\n+ requestPkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n+ Data: hdr.View().ToVectorisedView(),\n+ })\n+ e1.InjectInbound(ProtocolNumber, requestPkt)\n+\n+ if test.expectErrorICMP {\n+ reply, ok := e1.Read()\n+ if !ok {\n+ t.Fatal(\"expected ICMP Hop Limit Exceeded packet through incoming NIC\")\n+ }\n+\n+ checker.IPv6(t, header.IPv6(stack.PayloadSince(reply.Pkt.NetworkHeader())),\n+ checker.SrcAddr(ipv6Addr1.Address),\n+ checker.DstAddr(remoteIPv6Addr1),\n+ checker.TTL(DefaultTTL),\n+ checker.ICMPv6(\n+ checker.ICMPv6Type(header.ICMPv6TimeExceeded),\n+ checker.ICMPv6Code(header.ICMPv6HopLimitExceeded),\n+ checker.ICMPv6Payload([]byte(hdr.View())),\n+ ),\n+ )\n+\n+ if n := e2.Drain(); n != 0 {\n+ t.Fatalf(\"got e2.Drain() = %d, want = 0\", n)\n+ }\n+ } else {\n+ reply, ok := e2.Read()\n+ if !ok {\n+ t.Fatal(\"expected ICMP Echo Request packet through outgoing NIC\")\n+ }\n+\n+ checker.IPv6(t, header.IPv6(stack.PayloadSince(reply.Pkt.NetworkHeader())),\n+ checker.SrcAddr(remoteIPv6Addr1),\n+ checker.DstAddr(remoteIPv6Addr2),\n+ checker.TTL(test.TTL-1),\n+ checker.ICMPv6(\n+ checker.ICMPv6Type(header.ICMPv6EchoRequest),\n+ checker.ICMPv6Code(header.ICMPv6UnusedCode),\n+ checker.ICMPv6Payload(nil),\n+ ),\n+ )\n+\n+ if n := e1.Drain(); n != 0 {\n+ t.Fatalf(\"got e1.Drain() = %d, want = 0\", n)\n+ }\n+ }\n+ })\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Decrement TTL/Hop Limit when forwarding IP packets
If the packet must no longer be forwarded because its TTL/Hop Limit
reaches 0, send an ICMP Time Exceeded error to the source.
Required as per relevant RFCs. See comments in code for RFC references.
Fixes #1085
Tests:
- ipv4_test.TestForwarding
- ipv6.TestForwarding
PiperOrigin-RevId: 342323610 |
259,896 | 13.11.2020 13:57:02 | 28,800 | 839dd97008bacf526c05afa542e67c94f8b399ea | RACK: Detect DSACK
Detect if the ACK is a duplicate and update in RACK. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -82,6 +82,7 @@ type TCPRACKState struct {\nFACK seqnum.Value\nRTT time.Duration\nReord bool\n+ DSACKSeen bool\n}\n// TCPEndpointID is the unique 4 tuple that identifies a given endpoint.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -3051,6 +3051,7 @@ func (e *endpoint) completeState() stack.TCPEndpointState {\nFACK: rc.fack,\nRTT: rc.rtt,\nReord: rc.reorderSeen,\n+ DSACKSeen: rc.dsackSeen,\n}\nreturn s\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/rack.go",
"new_path": "pkg/tcpip/transport/tcp/rack.go",
"diff": "@@ -29,12 +29,12 @@ import (\n//\n// +stateify savable\ntype rackControl struct {\n+ // dsackSeen indicates if the connection has seen a DSACK.\n+ dsackSeen bool\n+\n// endSequence is the ending TCP sequence number of rackControl.seg.\nendSequence seqnum.Value\n- // dsack indicates if the connection has seen a DSACK.\n- dsack bool\n-\n// fack is the highest selectively or cumulatively acknowledged\n// sequence.\nfack seqnum.Value\n@@ -122,3 +122,8 @@ func (rc *rackControl) detectReorder(seg *segment) {\nrc.reorderSeen = true\n}\n}\n+\n+// setDSACKSeen updates rack control if duplicate SACK is seen by the connection.\n+func (rc *rackControl) setDSACKSeen() {\n+ rc.dsackSeen = true\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/snd.go",
"new_path": "pkg/tcpip/transport/tcp/snd.go",
"diff": "@@ -1182,25 +1182,29 @@ func (s *sender) detectLoss(seg *segment) (fastRetransmit bool) {\n// See: https://tools.ietf.org/html/draft-ietf-tcpm-rack-08#section-7.2\n// steps 2 and 3.\nfunc (s *sender) walkSACK(rcvdSeg *segment) {\n- if len(rcvdSeg.parsedOptions.SACKBlocks) == 0 {\n+ // Look for DSACK block.\n+ idx := 0\n+ n := len(rcvdSeg.parsedOptions.SACKBlocks)\n+ if s.checkDSACK(rcvdSeg) {\n+ s.rc.setDSACKSeen()\n+ idx = 1\n+ n--\n+ }\n+\n+ if n == 0 {\nreturn\n}\n// Sort the SACK blocks. The first block is the most recent unacked\n// block. The following blocks can be in arbitrary order.\n- sackBlocks := make([]header.SACKBlock, len(rcvdSeg.parsedOptions.SACKBlocks))\n- copy(sackBlocks, rcvdSeg.parsedOptions.SACKBlocks)\n+ sackBlocks := make([]header.SACKBlock, n)\n+ copy(sackBlocks, rcvdSeg.parsedOptions.SACKBlocks[idx:])\nsort.Slice(sackBlocks, func(i, j int) bool {\nreturn sackBlocks[j].Start.LessThan(sackBlocks[i].Start)\n})\nseg := s.writeList.Front()\nfor _, sb := range sackBlocks {\n- // This check excludes DSACK blocks.\n- if sb.Start.LessThanEq(rcvdSeg.ackNumber) || sb.Start.LessThanEq(s.sndUna) || s.sndNxt.LessThan(sb.End) {\n- continue\n- }\n-\nfor seg != nil && seg.sequenceNumber.LessThan(sb.End) && seg.xmitCount != 0 {\nif sb.Start.LessThanEq(seg.sequenceNumber) && !seg.acked {\ns.rc.update(seg, rcvdSeg, s.ep.tsOffset)\n@@ -1212,6 +1216,50 @@ func (s *sender) walkSACK(rcvdSeg *segment) {\n}\n}\n+// checkDSACK checks if a DSACK is reported and updates it in RACK.\n+func (s *sender) checkDSACK(rcvdSeg *segment) bool {\n+ n := len(rcvdSeg.parsedOptions.SACKBlocks)\n+ if n == 0 {\n+ return false\n+ }\n+\n+ sb := rcvdSeg.parsedOptions.SACKBlocks[0]\n+ // Check if SACK block is invalid.\n+ if sb.End.LessThan(sb.Start) {\n+ return false\n+ }\n+\n+ // See: https://tools.ietf.org/html/rfc2883#section-5 DSACK is sent in\n+ // at most one SACK block. DSACK is detected in the below two cases:\n+ // * If the SACK sequence space is less than this cumulative ACK, it is\n+ // an indication that the segment identified by the SACK block has\n+ // been received more than once by the receiver.\n+ // * If the sequence space in the first SACK block is greater than the\n+ // cumulative ACK, then the sender next compares the sequence space\n+ // in the first SACK block with the sequence space in the second SACK\n+ // block, if there is one. This comparison can determine if the first\n+ // SACK block is reporting duplicate data that lies above the\n+ // cumulative ACK.\n+ if sb.Start.LessThan(rcvdSeg.ackNumber) {\n+ return true\n+ }\n+\n+ if n > 1 {\n+ sb1 := rcvdSeg.parsedOptions.SACKBlocks[1]\n+ if sb1.End.LessThan(sb1.Start) {\n+ return false\n+ }\n+\n+ // If the first SACK block is fully covered by second SACK\n+ // block, then the first block is a DSACK block.\n+ if sb.End.LessThanEq(sb1.End) && sb1.Start.LessThanEq(sb.Start) {\n+ return true\n+ }\n+ }\n+\n+ return false\n+}\n+\n// handleRcvdSegment is called when a segment is received; it is responsible for\n// updating the send-related state.\nfunc (s *sender) handleRcvdSegment(rcvdSeg *segment) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/tcp_rack_test.go",
"new_path": "pkg/tcpip/transport/tcp/tcp_rack_test.go",
"diff": "@@ -30,15 +30,17 @@ const (\nmaxPayload = 10\ntsOptionSize = 12\nmaxTCPOptionSize = 40\n+ mtu = header.TCPMinimumSize + header.IPv4MinimumSize + maxTCPOptionSize + maxPayload\n)\n// TestRACKUpdate tests the RACK related fields are updated when an ACK is\n// received on a SACK enabled connection.\nfunc TestRACKUpdate(t *testing.T) {\n- c := context.New(t, uint32(header.TCPMinimumSize+header.IPv4MinimumSize+maxTCPOptionSize+maxPayload))\n+ c := context.New(t, uint32(mtu))\ndefer c.Cleanup()\nvar xmitTime time.Time\n+ probeDone := make(chan struct{})\nc.Stack().AddTCPProbe(func(state stack.TCPEndpointState) {\n// Validate that the endpoint Sender.RACKState is what we expect.\nif state.Sender.RACKState.XmitTime.Before(xmitTime) {\n@@ -54,6 +56,7 @@ func TestRACKUpdate(t *testing.T) {\nif state.Sender.RACKState.RTT == 0 {\nt.Fatalf(\"RACK RTT failed to update when an ACK is received, got RACKState.RTT == 0 want != 0\")\n}\n+ close(probeDone)\n})\nsetStackSACKPermitted(t, c, true)\ncreateConnectedWithSACKAndTS(c)\n@@ -73,18 +76,20 @@ func TestRACKUpdate(t *testing.T) {\nc.ReceiveAndCheckPacketWithOptions(data, bytesRead, maxPayload, tsOptionSize)\nbytesRead += maxPayload\nc.SendAck(seqnum.Value(context.TestInitialSequenceNumber).Add(1), bytesRead)\n- time.Sleep(200 * time.Millisecond)\n+\n+ // Wait for the probe function to finish processing the ACK before the\n+ // test completes.\n+ <-probeDone\n}\n// TestRACKDetectReorder tests that RACK detects packet reordering.\nfunc TestRACKDetectReorder(t *testing.T) {\n- c := context.New(t, uint32(header.TCPMinimumSize+header.IPv4MinimumSize+maxTCPOptionSize+maxPayload))\n+ c := context.New(t, uint32(mtu))\ndefer c.Cleanup()\n- const ackNum = 2\n-\nvar n int\n- ch := make(chan struct{})\n+ const ackNumToVerify = 2\n+ probeDone := make(chan struct{})\nc.Stack().AddTCPProbe(func(state stack.TCPEndpointState) {\ngotSeq := state.Sender.RACKState.FACK\nwantSeq := state.Sender.SndNxt\n@@ -95,7 +100,7 @@ func TestRACKDetectReorder(t *testing.T) {\n}\nn++\n- if n < ackNum {\n+ if n < ackNumToVerify {\nif state.Sender.RACKState.Reord {\nt.Fatalf(\"RACK reorder detected when there is no reordering\")\n}\n@@ -105,11 +110,11 @@ func TestRACKDetectReorder(t *testing.T) {\nif state.Sender.RACKState.Reord == false {\nt.Fatalf(\"RACK reorder detection failed\")\n}\n- close(ch)\n+ close(probeDone)\n})\nsetStackSACKPermitted(t, c, true)\ncreateConnectedWithSACKAndTS(c)\n- data := buffer.NewView(ackNum * maxPayload)\n+ data := buffer.NewView(ackNumToVerify * maxPayload)\nfor i := range data {\ndata[i] = byte(i)\n}\n@@ -120,7 +125,7 @@ func TestRACKDetectReorder(t *testing.T) {\n}\nbytesRead := 0\n- for i := 0; i < ackNum; i++ {\n+ for i := 0; i < ackNumToVerify; i++ {\nc.ReceiveAndCheckPacketWithOptions(data, bytesRead, maxPayload, tsOptionSize)\nbytesRead += maxPayload\n}\n@@ -133,5 +138,393 @@ func TestRACKDetectReorder(t *testing.T) {\n// Wait for the probe function to finish processing the ACK before the\n// test completes.\n- <-ch\n+ <-probeDone\n+}\n+\n+func sendAndReceive(t *testing.T, c *context.Context, numPackets int) buffer.View {\n+ setStackSACKPermitted(t, c, true)\n+ createConnectedWithSACKAndTS(c)\n+\n+ data := buffer.NewView(numPackets * maxPayload)\n+ for i := range data {\n+ data[i] = byte(i)\n+ }\n+\n+ // Write the data.\n+ if _, _, err := c.EP.Write(tcpip.SlicePayload(data), tcpip.WriteOptions{}); err != nil {\n+ t.Fatalf(\"Write failed: %s\", err)\n+ }\n+\n+ bytesRead := 0\n+ for i := 0; i < numPackets; i++ {\n+ c.ReceiveAndCheckPacketWithOptions(data, bytesRead, maxPayload, tsOptionSize)\n+ bytesRead += maxPayload\n+ }\n+\n+ return data\n+}\n+\n+const (\n+ validDSACKDetected = 1\n+ failedToDetectDSACK = 2\n+ invalidDSACKDetected = 3\n+)\n+\n+func addDSACKSeenCheckerProbe(t *testing.T, c *context.Context, numACK int, probeDone chan int) {\n+ var n int\n+ c.Stack().AddTCPProbe(func(state stack.TCPEndpointState) {\n+ // Validate that RACK detects DSACK.\n+ n++\n+ if n < numACK {\n+ if state.Sender.RACKState.DSACKSeen {\n+ probeDone <- invalidDSACKDetected\n+ }\n+ return\n+ }\n+\n+ if !state.Sender.RACKState.DSACKSeen {\n+ probeDone <- failedToDetectDSACK\n+ return\n+ }\n+ probeDone <- validDSACKDetected\n+ })\n+}\n+\n+// TestRACKDetectDSACK tests that RACK detects DSACK with duplicate segments.\n+// See: https://tools.ietf.org/html/rfc2883#section-4.1.1.\n+func TestRACKDetectDSACK(t *testing.T) {\n+ c := context.New(t, uint32(mtu))\n+ defer c.Cleanup()\n+\n+ probeDone := make(chan int)\n+ const ackNumToVerify = 2\n+ addDSACKSeenCheckerProbe(t, c, ackNumToVerify, probeDone)\n+\n+ numPackets := 8\n+ data := sendAndReceive(t, c, numPackets)\n+\n+ // Cumulative ACK for [1-5] packets.\n+ seq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n+ bytesRead := 5 * maxPayload\n+ c.SendAck(seq, bytesRead)\n+\n+ // Expect retransmission of #6 packet.\n+ c.ReceiveAndCheckPacketWithOptions(data, bytesRead, maxPayload, tsOptionSize)\n+\n+ // Send DSACK block for #6 packet indicating both\n+ // initial and retransmitted packet are received and\n+ // packets [1-7] are received.\n+ start := c.IRS.Add(seqnum.Size(bytesRead))\n+ end := start.Add(maxPayload)\n+ bytesRead += 2 * maxPayload\n+ c.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{start, end}})\n+\n+ // Wait for the probe function to finish processing the\n+ // ACK before the test completes.\n+ err := <-probeDone\n+ switch err {\n+ case failedToDetectDSACK:\n+ t.Fatalf(\"RACK DSACK detection failed\")\n+ case invalidDSACKDetected:\n+ t.Fatalf(\"RACK DSACK detected when there is no duplicate SACK\")\n+ }\n+}\n+\n+// TestRACKDetectDSACKWithOutOfOrder tests that RACK detects DSACK with out of\n+// order segments.\n+// See: https://tools.ietf.org/html/rfc2883#section-4.1.2.\n+func TestRACKDetectDSACKWithOutOfOrder(t *testing.T) {\n+ c := context.New(t, uint32(mtu))\n+ defer c.Cleanup()\n+\n+ probeDone := make(chan int)\n+ const ackNumToVerify = 2\n+ addDSACKSeenCheckerProbe(t, c, ackNumToVerify, probeDone)\n+\n+ numPackets := 10\n+ data := sendAndReceive(t, c, numPackets)\n+\n+ // Cumulative ACK for [1-5] packets.\n+ seq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n+ bytesRead := 5 * maxPayload\n+ c.SendAck(seq, bytesRead)\n+\n+ // Expect retransmission of #6 packet.\n+ c.ReceiveAndCheckPacketWithOptions(data, bytesRead, maxPayload, tsOptionSize)\n+\n+ // Send DSACK block for #6 packet indicating both\n+ // initial and retransmitted packet are received and\n+ // packets [1-7] are received.\n+ start := c.IRS.Add(seqnum.Size(bytesRead))\n+ end := start.Add(maxPayload)\n+ bytesRead += 2 * maxPayload\n+ // Send DSACK block for #6 along with out of\n+ // order #9 packet is received.\n+ start1 := c.IRS.Add(seqnum.Size(bytesRead) + maxPayload)\n+ end1 := start1.Add(maxPayload)\n+ c.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{start, end}, {start1, end1}})\n+\n+ // Wait for the probe function to finish processing the\n+ // ACK before the test completes.\n+ err := <-probeDone\n+ switch err {\n+ case failedToDetectDSACK:\n+ t.Fatalf(\"RACK DSACK detection failed\")\n+ case invalidDSACKDetected:\n+ t.Fatalf(\"RACK DSACK detected when there is no duplicate SACK\")\n+ }\n+}\n+\n+// TestRACKDetectDSACKWithOutOfOrderDup tests that DSACK is detected on a\n+// duplicate of out of order packet.\n+// See: https://tools.ietf.org/html/rfc2883#section-4.1.3\n+func TestRACKDetectDSACKWithOutOfOrderDup(t *testing.T) {\n+ c := context.New(t, uint32(mtu))\n+ defer c.Cleanup()\n+\n+ probeDone := make(chan int)\n+ const ackNumToVerify = 4\n+ addDSACKSeenCheckerProbe(t, c, ackNumToVerify, probeDone)\n+\n+ numPackets := 10\n+ sendAndReceive(t, c, numPackets)\n+\n+ // ACK [1-5] packets.\n+ seq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n+ bytesRead := 5 * maxPayload\n+ c.SendAck(seq, bytesRead)\n+\n+ // Send SACK indicating #6 packet is missing and received #7 packet.\n+ offset := seqnum.Size(bytesRead + maxPayload)\n+ start := c.IRS.Add(1 + offset)\n+ end := start.Add(maxPayload)\n+ c.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{start, end}})\n+\n+ // Send SACK with #6 packet is missing and received [7-8] packets.\n+ end = start.Add(2 * maxPayload)\n+ c.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{start, end}})\n+\n+ // Consider #8 packet is duplicated on the network and send DSACK.\n+ dsackStart := c.IRS.Add(1 + offset + maxPayload)\n+ dsackEnd := dsackStart.Add(maxPayload)\n+ c.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{dsackStart, dsackEnd}, {start, end}})\n+\n+ // Wait for the probe function to finish processing the ACK before the\n+ // test completes.\n+ err := <-probeDone\n+ switch err {\n+ case failedToDetectDSACK:\n+ t.Fatalf(\"RACK DSACK detection failed\")\n+ case invalidDSACKDetected:\n+ t.Fatalf(\"RACK DSACK detected when there is no duplicate SACK\")\n+ }\n+}\n+\n+// TestRACKDetectDSACKSingleDup tests DSACK for a single duplicate subsegment.\n+// See: https://tools.ietf.org/html/rfc2883#section-4.2.1.\n+func TestRACKDetectDSACKSingleDup(t *testing.T) {\n+ c := context.New(t, uint32(mtu))\n+ defer c.Cleanup()\n+\n+ probeDone := make(chan int)\n+ const ackNumToVerify = 4\n+ addDSACKSeenCheckerProbe(t, c, ackNumToVerify, probeDone)\n+\n+ numPackets := 4\n+ data := sendAndReceive(t, c, numPackets)\n+\n+ // Send ACK for #1 packet.\n+ bytesRead := maxPayload\n+ seq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n+ c.SendAck(seq, bytesRead)\n+\n+ // Missing [2-3] packets and received #4 packet.\n+ seq = seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n+ start := c.IRS.Add(1 + seqnum.Size(3*maxPayload))\n+ end := start.Add(seqnum.Size(maxPayload))\n+ c.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{start, end}})\n+\n+ // Expect retransmission of #2 packet.\n+ c.ReceiveAndCheckPacketWithOptions(data, bytesRead, maxPayload, tsOptionSize)\n+\n+ // ACK for retransmitted #2 packet.\n+ bytesRead += maxPayload\n+ c.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{start, end}})\n+\n+ // Simulate receving delayed subsegment of #2 packet and delayed #3 packet by\n+ // sending DSACK block for the subsegment.\n+ dsackStart := c.IRS.Add(1 + seqnum.Size(bytesRead))\n+ dsackEnd := dsackStart.Add(seqnum.Size(maxPayload / 2))\n+ c.SendAckWithSACK(seq, numPackets*maxPayload, []header.SACKBlock{{dsackStart, dsackEnd}})\n+\n+ // Wait for the probe function to finish processing the ACK before the\n+ // test completes.\n+ err := <-probeDone\n+ switch err {\n+ case failedToDetectDSACK:\n+ t.Fatalf(\"RACK DSACK detection failed\")\n+ case invalidDSACKDetected:\n+ t.Fatalf(\"RACK DSACK detected when there is no duplicate SACK\")\n+ }\n+}\n+\n+// TestRACKDetectDSACKDupWithCumulativeACK tests DSACK for two non-contiguous\n+// duplicate subsegments covered by the cumulative acknowledgement.\n+// See: https://tools.ietf.org/html/rfc2883#section-4.2.2.\n+func TestRACKDetectDSACKDupWithCumulativeACK(t *testing.T) {\n+ c := context.New(t, uint32(mtu))\n+ defer c.Cleanup()\n+\n+ probeDone := make(chan int)\n+ const ackNumToVerify = 5\n+ addDSACKSeenCheckerProbe(t, c, ackNumToVerify, probeDone)\n+\n+ numPackets := 6\n+ data := sendAndReceive(t, c, numPackets)\n+\n+ // Send ACK for #1 packet.\n+ bytesRead := maxPayload\n+ seq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n+ c.SendAck(seq, bytesRead)\n+\n+ // Missing [2-5] packets and received #6 packet.\n+ seq = seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n+ start := c.IRS.Add(1 + seqnum.Size(5*maxPayload))\n+ end := start.Add(seqnum.Size(maxPayload))\n+ c.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{start, end}})\n+\n+ // Expect retransmission of #2 packet.\n+ c.ReceiveAndCheckPacketWithOptions(data, bytesRead, maxPayload, tsOptionSize)\n+\n+ // Received delayed #2 packet.\n+ bytesRead += maxPayload\n+ c.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{start, end}})\n+\n+ // Received delayed #4 packet.\n+ start1 := c.IRS.Add(1 + seqnum.Size(3*maxPayload))\n+ end1 := start1.Add(seqnum.Size(maxPayload))\n+ c.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{start1, end1}, {start, end}})\n+\n+ // Simulate receiving retransmitted subsegment for #2 packet and delayed #3\n+ // packet by sending DSACK block for #2 packet.\n+ dsackStart := c.IRS.Add(1 + seqnum.Size(maxPayload))\n+ dsackEnd := dsackStart.Add(seqnum.Size(maxPayload / 2))\n+ c.SendAckWithSACK(seq, 4*maxPayload, []header.SACKBlock{{dsackStart, dsackEnd}, {start, end}})\n+\n+ // Wait for the probe function to finish processing the ACK before the\n+ // test completes.\n+ err := <-probeDone\n+ switch err {\n+ case failedToDetectDSACK:\n+ t.Fatalf(\"RACK DSACK detection failed\")\n+ case invalidDSACKDetected:\n+ t.Fatalf(\"RACK DSACK detected when there is no duplicate SACK\")\n+ }\n+}\n+\n+// TestRACKDetectDSACKDup tests two non-contiguous duplicate subsegments not\n+// covered by the cumulative acknowledgement.\n+// See: https://tools.ietf.org/html/rfc2883#section-4.2.3.\n+func TestRACKDetectDSACKDup(t *testing.T) {\n+ c := context.New(t, uint32(mtu))\n+ defer c.Cleanup()\n+\n+ probeDone := make(chan int)\n+ const ackNumToVerify = 5\n+ addDSACKSeenCheckerProbe(t, c, ackNumToVerify, probeDone)\n+\n+ numPackets := 7\n+ data := sendAndReceive(t, c, numPackets)\n+\n+ // Send ACK for #1 packet.\n+ bytesRead := maxPayload\n+ seq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n+ c.SendAck(seq, bytesRead)\n+\n+ // Missing [2-6] packets and SACK #7 packet.\n+ seq = seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n+ start := c.IRS.Add(1 + seqnum.Size(6*maxPayload))\n+ end := start.Add(seqnum.Size(maxPayload))\n+ c.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{start, end}})\n+\n+ // Received delayed #3 packet.\n+ start1 := c.IRS.Add(1 + seqnum.Size(2*maxPayload))\n+ end1 := start1.Add(seqnum.Size(maxPayload))\n+ c.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{start1, end1}, {start, end}})\n+\n+ // Expect retransmission of #2 packet.\n+ c.ReceiveAndCheckPacketWithOptions(data, bytesRead, maxPayload, tsOptionSize)\n+\n+ // Consider #2 packet has been dropped and SACK #4 packet.\n+ start2 := c.IRS.Add(1 + seqnum.Size(3*maxPayload))\n+ end2 := start2.Add(seqnum.Size(maxPayload))\n+ c.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{start2, end2}, {start1, end1}, {start, end}})\n+\n+ // Simulate receiving retransmitted subsegment for #3 packet and delayed #5\n+ // packet by sending DSACK block for the subsegment.\n+ dsackStart := c.IRS.Add(1 + seqnum.Size(2*maxPayload))\n+ dsackEnd := dsackStart.Add(seqnum.Size(maxPayload / 2))\n+ end1 = end1.Add(seqnum.Size(2 * maxPayload))\n+ c.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{dsackStart, dsackEnd}, {start1, end1}})\n+\n+ // Wait for the probe function to finish processing the ACK before the\n+ // test completes.\n+ err := <-probeDone\n+ switch err {\n+ case failedToDetectDSACK:\n+ t.Fatalf(\"RACK DSACK detection failed\")\n+ case invalidDSACKDetected:\n+ t.Fatalf(\"RACK DSACK detected when there is no duplicate SACK\")\n+ }\n+}\n+\n+// TestRACKWithInvalidDSACKBlock tests that DSACK is not detected when DSACK\n+// is not the first SACK block.\n+func TestRACKWithInvalidDSACKBlock(t *testing.T) {\n+ c := context.New(t, uint32(mtu))\n+ defer c.Cleanup()\n+\n+ probeDone := make(chan struct{})\n+ const ackNumToVerify = 2\n+ var n int\n+ c.Stack().AddTCPProbe(func(state stack.TCPEndpointState) {\n+ // Validate that RACK does not detect DSACK when DSACK block is\n+ // not the first SACK block.\n+ n++\n+ t.Helper()\n+ if state.Sender.RACKState.DSACKSeen {\n+ t.Fatalf(\"RACK DSACK detected when there is no duplicate SACK\")\n+ }\n+\n+ if n == ackNumToVerify {\n+ close(probeDone)\n+ }\n+ })\n+\n+ numPackets := 10\n+ data := sendAndReceive(t, c, numPackets)\n+\n+ // Cumulative ACK for [1-5] packets.\n+ seq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n+ bytesRead := 5 * maxPayload\n+ c.SendAck(seq, bytesRead)\n+\n+ // Expect retransmission of #6 packet.\n+ c.ReceiveAndCheckPacketWithOptions(data, bytesRead, maxPayload, tsOptionSize)\n+\n+ // Send DSACK block for #6 packet indicating both\n+ // initial and retransmitted packet are received and\n+ // packets [1-7] are received.\n+ start := c.IRS.Add(seqnum.Size(bytesRead))\n+ end := start.Add(maxPayload)\n+ bytesRead += 2 * maxPayload\n+\n+ // Send DSACK block as second block.\n+ start1 := c.IRS.Add(seqnum.Size(bytesRead) + maxPayload)\n+ end1 := start1.Add(maxPayload)\n+ c.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{start1, end1}, {start, end}})\n+\n+ // Wait for the probe function to finish processing the\n+ // ACK before the test completes.\n+ <-probeDone\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | RACK: Detect DSACK
Detect if the ACK is a duplicate and update in RACK.
PiperOrigin-RevId: 342332569 |
259,885 | 13.11.2020 14:29:47 | 28,800 | 89517eca414a311598aa6e64a229c7acc5e3a22f | Have fuse.DeviceFD hold reference on fuse.filesystem.
This is actually just b/168751672 again; cl/332394146 was incorrectly reverted
by cl/341411151. Document the reference holder to reduce the likelihood that
this happens again.
Also document a few other bugs observed in the process. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/fuse/connection.go",
"new_path": "pkg/sentry/fsimpl/fuse/connection.go",
"diff": "@@ -21,7 +21,6 @@ import (\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n- \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n@@ -193,11 +192,12 @@ func (conn *connection) loadInitializedChan(closed bool) {\n}\n}\n-// newFUSEConnection creates a FUSE connection to fd.\n-func newFUSEConnection(_ context.Context, fd *vfs.FileDescription, opts *filesystemOptions) (*connection, error) {\n- // Mark the device as ready so it can be used. /dev/fuse can only be used if the FD was used to\n- // mount a FUSE filesystem.\n- fuseFD := fd.Impl().(*DeviceFD)\n+// newFUSEConnection creates a FUSE connection to fuseFD.\n+func newFUSEConnection(_ context.Context, fuseFD *DeviceFD, opts *filesystemOptions) (*connection, error) {\n+ // Mark the device as ready so it can be used.\n+ // FIXME(gvisor.dev/issue/4813): fuseFD's fields are accessed without\n+ // synchronization and without checking if fuseFD has already been used to\n+ // mount another filesystem.\n// Create the writeBuf for the header to be stored in.\nhdrLen := uint32((*linux.FUSEHeaderOut)(nil).SizeBytes())\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/fuse/connection_control.go",
"new_path": "pkg/sentry/fsimpl/fuse/connection_control.go",
"diff": "@@ -198,7 +198,6 @@ func (conn *connection) Abort(ctx context.Context) {\nif !conn.connected {\nconn.asyncMu.Unlock()\nconn.mu.Unlock()\n- conn.fd.mu.Unlock()\nreturn\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/fuse/dev.go",
"new_path": "pkg/sentry/fsimpl/fuse/dev.go",
"diff": "@@ -94,7 +94,8 @@ type DeviceFD struct {\n// unprocessed in-flight requests.\nfullQueueCh chan struct{} `state:\".(int)\"`\n- // fs is the FUSE filesystem that this FD is being used for.\n+ // fs is the FUSE filesystem that this FD is being used for. A reference is\n+ // held on fs.\nfs *filesystem\n}\n@@ -135,12 +136,6 @@ func (fd *DeviceFD) Read(ctx context.Context, dst usermem.IOSequence, opts vfs.R\nreturn 0, syserror.EPERM\n}\n- // Return ENODEV if the filesystem is umounted.\n- if fd.fs.umounted {\n- // TODO(gvisor.dev/issue/3525): return ECONNABORTED if aborted via fuse control fs.\n- return 0, syserror.ENODEV\n- }\n-\n// We require that any Read done on this filesystem have a sane minimum\n// read buffer. It must have the capacity for the fixed parts of any request\n// header (Linux uses the request header and the FUSEWriteIn header for this\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/fuse/fusefs.go",
"new_path": "pkg/sentry/fsimpl/fuse/fusefs.go",
"diff": "@@ -127,7 +127,13 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nlog.Warningf(\"%s.GetFilesystem: couldn't get kernel task from context\", fsType.Name())\nreturn nil, nil, syserror.EINVAL\n}\n- fuseFd := kernelTask.GetFileVFS2(int32(deviceDescriptor))\n+ fuseFDGeneric := kernelTask.GetFileVFS2(int32(deviceDescriptor))\n+ defer fuseFDGeneric.DecRef(ctx)\n+ fuseFD, ok := fuseFDGeneric.Impl().(*DeviceFD)\n+ if !ok {\n+ log.Warningf(\"%s.GetFilesystem: device FD is %T, not a FUSE device\", fsType.Name, fuseFDGeneric)\n+ return nil, nil, syserror.EINVAL\n+ }\n// Parse and set all the other supported FUSE mount options.\n// TODO(gVisor.dev/issue/3229): Expand the supported mount options.\n@@ -189,18 +195,17 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\n}\n// Create a new FUSE filesystem.\n- fs, err := newFUSEFilesystem(ctx, devMinor, &fsopts, fuseFd)\n+ fs, err := newFUSEFilesystem(ctx, vfsObj, &fsType, fuseFD, devMinor, &fsopts)\nif err != nil {\nlog.Warningf(\"%s.NewFUSEFilesystem: failed with error: %v\", fsType.Name(), err)\nreturn nil, nil, err\n}\n- fs.VFSFilesystem().Init(vfsObj, &fsType, fs)\n-\n// Send a FUSE_INIT request to the FUSE daemon server before returning.\n// This call is not blocking.\nif err := fs.conn.InitSend(creds, uint32(kernelTask.ThreadID())); err != nil {\nlog.Warningf(\"%s.InitSend: failed with error: %v\", fsType.Name(), err)\n+ fs.VFSFilesystem().DecRef(ctx) // returned by newFUSEFilesystem\nreturn nil, nil, err\n}\n@@ -211,20 +216,28 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\n}\n// newFUSEFilesystem creates a new FUSE filesystem.\n-func newFUSEFilesystem(ctx context.Context, devMinor uint32, opts *filesystemOptions, device *vfs.FileDescription) (*filesystem, error) {\n- conn, err := newFUSEConnection(ctx, device, opts)\n+func newFUSEFilesystem(ctx context.Context, vfsObj *vfs.VirtualFilesystem, fsType *FilesystemType, fuseFD *DeviceFD, devMinor uint32, opts *filesystemOptions) (*filesystem, error) {\n+ conn, err := newFUSEConnection(ctx, fuseFD, opts)\nif err != nil {\nlog.Warningf(\"fuse.NewFUSEFilesystem: NewFUSEConnection failed with error: %v\", err)\nreturn nil, syserror.EINVAL\n}\n- fuseFD := device.Impl().(*DeviceFD)\nfs := &filesystem{\ndevMinor: devMinor,\nopts: opts,\nconn: conn,\n}\n+ fs.VFSFilesystem().Init(vfsObj, fsType, fs)\n+\n+ // FIXME(gvisor.dev/issue/4813): Doesn't conn or fs need to hold a\n+ // reference on fuseFD, since conn uses fuseFD for communication with the\n+ // server? Wouldn't doing so create a circular reference?\n+ fs.VFSFilesystem().IncRef() // for fuseFD.fs\n+ // FIXME(gvisor.dev/issue/4813): fuseFD.fs is accessed without\n+ // synchronization.\nfuseFD.fs = fs\n+\nreturn fs, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/fuse/utils_test.go",
"new_path": "pkg/sentry/fsimpl/fuse/utils_test.go",
"diff": "@@ -52,28 +52,21 @@ func setup(t *testing.T) *testutil.System {\n// newTestConnection creates a fuse connection that the sentry can communicate with\n// and the FD for the server to communicate with.\nfunc newTestConnection(system *testutil.System, k *kernel.Kernel, maxActiveRequests uint64) (*connection, *vfs.FileDescription, error) {\n- vfsObj := &vfs.VirtualFilesystem{}\nfuseDev := &DeviceFD{}\n- if err := vfsObj.Init(system.Ctx); err != nil {\n- return nil, nil, err\n- }\n-\n- vd := vfsObj.NewAnonVirtualDentry(\"genCountFD\")\n+ vd := system.VFS.NewAnonVirtualDentry(\"fuse\")\ndefer vd.DecRef(system.Ctx)\n- if err := fuseDev.vfsfd.Init(fuseDev, linux.O_RDWR|linux.O_CREAT, vd.Mount(), vd.Dentry(), &vfs.FileDescriptionOptions{}); err != nil {\n+ if err := fuseDev.vfsfd.Init(fuseDev, linux.O_RDWR, vd.Mount(), vd.Dentry(), &vfs.FileDescriptionOptions{}); err != nil {\nreturn nil, nil, err\n}\nfsopts := filesystemOptions{\nmaxActiveRequests: maxActiveRequests,\n}\n- fs, err := newFUSEFilesystem(system.Ctx, 0, &fsopts, &fuseDev.vfsfd)\n+ fs, err := newFUSEFilesystem(system.Ctx, system.VFS, &FilesystemType{}, fuseDev, 0, &fsopts)\nif err != nil {\nreturn nil, nil, err\n}\n- fs.VFSFilesystem().Init(vfsObj, nil, fs)\n-\nreturn fs.conn, &fuseDev.vfsfd, nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Have fuse.DeviceFD hold reference on fuse.filesystem.
This is actually just b/168751672 again; cl/332394146 was incorrectly reverted
by cl/341411151. Document the reference holder to reduce the likelihood that
this happens again.
Also document a few other bugs observed in the process.
PiperOrigin-RevId: 342339144 |
260,024 | 13.11.2020 17:11:12 | 28,800 | 0fee59c8c84bff0185e681b4550ba077a65739f2 | Requested Comment/Message wording changes | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/ipv4.go",
"new_path": "pkg/tcpip/header/ipv4.go",
"diff": "@@ -89,7 +89,17 @@ type IPv4Fields struct {\n// DstAddr is the \"destination ip address\" of an IPv4 packet.\nDstAddr tcpip.Address\n- // Options is between 0 and 40 bytes or nil if empty.\n+ // Options must be 40 bytes or less as they must fit along with the\n+ // rest of the IPv4 header into the maximum size describable in the\n+ // IHL field. RFC 791 section 3.1 says:\n+ // IHL: 4 bits\n+ //\n+ // Internet Header Length is the length of the internet header in 32\n+ // bit words, and thus points to the beginning of the data. Note that\n+ // the minimum value for a correct header is 5.\n+ //\n+ // That leaves ten 32 bit (4 byte) fields for options. An attempt to encode\n+ // more will fail.\nOptions IPv4Options\n}\n@@ -284,14 +294,11 @@ func (o IPv4Options) SizeWithPadding() int {\nreturn (len(o) + IPv4IHLStride - 1) & ^(IPv4IHLStride - 1)\n}\n-// Options returns a buffer holding the options or nil.\n+// Options returns a buffer holding the options.\nfunc (b IPv4) Options() IPv4Options {\nhdrLen := b.HeaderLength()\n- if hdrLen > IPv4MinimumSize {\nreturn IPv4Options(b[options:hdrLen:hdrLen])\n}\n- return nil\n-}\n// TransportProtocol implements Network.TransportProtocol.\nfunc (b IPv4) TransportProtocol() tcpip.TransportProtocolNumber {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/icmp.go",
"new_path": "pkg/tcpip/network/ipv4/icmp.go",
"diff": "@@ -90,7 +90,7 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer) {\niph := header.IPv4(pkt.NetworkHeader().View())\nvar newOptions header.IPv4Options\n- if len(iph) > header.IPv4MinimumSize {\n+ if opts := iph.Options(); len(opts) != 0 {\n// RFC 1122 section 3.2.2.6 (page 43) (and similar for other round trip\n// type ICMP packets):\n// If a Record Route and/or Time Stamp option is received in an\n@@ -106,7 +106,7 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer) {\n} else {\nop = &optionUsageReceive{}\n}\n- aux, tmp, err := e.processIPOptions(pkt, iph.Options(), op)\n+ aux, tmp, err := e.processIPOptions(pkt, opts, op)\nif err != nil {\nswitch {\ncase\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4.go",
"diff": "@@ -713,11 +713,11 @@ func (e *endpoint) handlePacket(pkt *stack.PacketBuffer) {\ne.handleICMP(pkt)\nreturn\n}\n- if len(h.Options()) != 0 {\n+ if opts := h.Options(); len(opts) != 0 {\n// TODO(gvisor.dev/issue/4586):\n// When we add forwarding support we should use the verified options\n// rather than just throwing them away.\n- aux, _, err := e.processIPOptions(pkt, h.Options(), &optionUsageReceive{})\n+ aux, _, err := e.processIPOptions(pkt, opts, &optionUsageReceive{})\nif err != nil {\nswitch {\ncase\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/connections.go",
"new_path": "test/packetimpact/testbench/connections.go",
"diff": "@@ -72,7 +72,7 @@ func pickPort(domain, typ int) (fd int, port uint16, err error) {\n}\nsa, err = unix.Getsockname(fd)\nif err != nil {\n- return -1, 0, fmt.Errorf(\"fail in Getsocketname(%d): %w\", fd, err)\n+ return -1, 0, fmt.Errorf(\"unix.Getsocketname(%d): %w\", fd, err)\n}\nport, err = portFromSockaddr(sa)\nif err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/layers.go",
"new_path": "test/packetimpact/testbench/layers.go",
"diff": "@@ -410,13 +410,7 @@ func Address(v tcpip.Address) *tcpip.Address {\n// continues parsing further encapsulations.\nfunc parseIPv4(b []byte) (Layer, layerParser) {\nh := header.IPv4(b)\n- hdrLen := h.HeaderLength()\n- // Even if there are no options, we set an empty options field instead of nil\n- // so that the decision to compare is up to the caller of that comparison.\n- var options header.IPv4Options\n- if hdrLen > header.IPv4MinimumSize {\n- options = append(options, h.Options()...)\n- }\n+ options := h.Options()\ntos, _ := h.TOS()\nipv4 := IPv4{\nIHL: Uint8(h.HeaderLength()),\n"
}
] | Go | Apache License 2.0 | google/gvisor | Requested Comment/Message wording changes
PiperOrigin-RevId: 342366891 |
259,885 | 13.11.2020 18:09:15 | 28,800 | 182c126013a28f19594ff61326f1f9a2c481f1b4 | Log task goroutine IDs in the sentry watchdog. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_run.go",
"new_path": "pkg/sentry/kernel/task_run.go",
"diff": "@@ -390,6 +390,11 @@ func (t *Task) assertTaskGoroutine() {\n}\n}\n+// GoroutineID returns the ID of t's task goroutine.\n+func (t *Task) GoroutineID() int64 {\n+ return atomic.LoadInt64(&t.goid)\n+}\n+\n// waitGoroutineStoppedOrExited blocks until t's task goroutine stops or exits.\nfunc (t *Task) waitGoroutineStoppedOrExited() {\nt.goroutineStopped.Wait()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/watchdog/watchdog.go",
"new_path": "pkg/sentry/watchdog/watchdog.go",
"diff": "@@ -336,11 +336,9 @@ func (w *Watchdog) report(offenders map[*kernel.Task]*offender, newTaskFound boo\nbuf.WriteString(fmt.Sprintf(\"Sentry detected %d stuck task(s):\\n\", len(offenders)))\nfor t, o := range offenders {\ntid := w.k.TaskSet().Root.IDOfTask(t)\n- buf.WriteString(fmt.Sprintf(\"\\tTask tid: %v (%#x), entered RunSys state %v ago.\\n\", tid, uint64(tid), now.Sub(o.lastUpdateTime)))\n+ buf.WriteString(fmt.Sprintf(\"\\tTask tid: %v (goroutine %d), entered RunSys state %v ago.\\n\", tid, t.GoroutineID(), now.Sub(o.lastUpdateTime)))\n}\n- buf.WriteString(\"Search for '(*Task).run(0x..., 0x<tid>)' in the stack dump to find the offending goroutine\")\n-\n// Force stack dump only if a new task is detected.\nw.doAction(w.TaskTimeoutAction, newTaskFound, &buf)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Log task goroutine IDs in the sentry watchdog.
PiperOrigin-RevId: 342373580 |
259,884 | 16.11.2020 00:04:07 | 28,800 | 43dd7a200569cb04c778b83df4b9007c76091756 | Fix labels on issue templates | [
{
"change_type": "MODIFY",
"old_path": ".github/ISSUE_TEMPLATE/bug_report.md",
"new_path": ".github/ISSUE_TEMPLATE/bug_report.md",
"diff": "name: Bug report\nabout: Create a bug report to help us improve\ntitle:\n-labels:\n- - 'type: bug'\n+labels: 'type: bug'\nassignees: ''\n---\n"
},
{
"change_type": "MODIFY",
"old_path": ".github/ISSUE_TEMPLATE/feature_request.md",
"new_path": ".github/ISSUE_TEMPLATE/feature_request.md",
"diff": "name: Feature request\nabout: Suggest an idea or improvement\ntitle: ''\n-labels:\n- - 'type: enhancement'\n+labels: 'type: enhancement'\nassignees: ''\n---\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix labels on issue templates
PiperOrigin-RevId: 342577869 |
259,992 | 16.11.2020 10:12:07 | 28,800 | 39f712f1d8a53db9d1ccbf7a894d9190edab076d | Add new shim debug options to docs | [
{
"change_type": "MODIFY",
"old_path": "g3doc/user_guide/containerd/configuration.md",
"new_path": "g3doc/user_guide/containerd/configuration.md",
"diff": "@@ -4,41 +4,56 @@ This document describes how to configure runtime options for\n`containerd-shim-runsc-v1`. This follows the\n[Containerd Quick Start](./quick_start.md) and requires containerd 1.2 or later.\n-### Update `/etc/containerd/config.toml` to point to a configuration file for `containerd-shim-runsc-v1`.\n+## Shim Configuration\n-`containerd-shim-runsc-v1` supports a few different configuration options based\n-on the version of containerd that is used. For versions >= 1.3, it supports a\n-configurable `ConfigPath` in the containerd runtime configuration.\n+The shim can be provided with a configuration file containing options to the\n+shim itself as well as a set of flags to runsc. Here is a quick example:\n+\n+```shell\n+cat <<EOF | sudo tee /etc/containerd/runsc.toml\n+option = \"value\"\n+[runsc_config]\n+ flag = \"value\"\n+```\n+\n+The set of options that can be configured can be found in\n+[options.go](https://github.com/google/gvisor/blob/master/pkg/shim/v2/options.go).\n+Values under `[runsc_config]` can be used to set arbitrary flags to runsc.\n+`flag = \"value\"` is converted to `--flag=\"value\"` when runsc is invoked. Run\n+`runsc flags` so see which flags are available\n+\n+Next, containerd needs to be configured to send the configuration file to the\n+shim.\n+\n+### Containerd 1.3+\n+\n+Starting in 1.3, containerd supports a configurable `ConfigPath` in the runtime\n+configuration. Here is an example:\n```shell\ncat <<EOF | sudo tee /etc/containerd/config.toml\ndisabled_plugins = [\"restart\"]\n-[plugins.linux]\n- shim_debug = true\n[plugins.cri.containerd.runtimes.runsc]\nruntime_type = \"io.containerd.runsc.v1\"\n[plugins.cri.containerd.runtimes.runsc.options]\nTypeUrl = \"io.containerd.runsc.v1.options\"\n- # containerd 1.3 only!\nConfigPath = \"/etc/containerd/runsc.toml\"\nEOF\n```\n-When you are done restart containerd to pick up the new configuration files.\n+When you are done, restart containerd to pick up the changes.\n```shell\nsudo systemctl restart containerd\n```\n-### Configure `/etc/containerd/runsc.toml`\n+### Containerd 1.2\n-> Note: For containerd 1.2, the config file should named `config.toml` and\n-> located in the runtime root. By default, this is `/run/containerd/runsc`.\n+For containerd 1.2, the config file is not configurable. It should be named\n+`config.toml` and located in the runtime root. By default, this is\n+`/run/containerd/runsc`.\n-The set of options that can be configured can be found in\n-[options.go](https://github.com/google/gvisor/blob/master/pkg/shim/v2/options.go).\n-\n-#### Example: Enable the KVM platform\n+### Example: Enable the KVM platform\ngVisor enables the use of a number of platforms. This example shows how to\nconfigure `containerd-shim-runsc-v1` to use gvisor with the KVM platform.\n@@ -53,7 +68,38 @@ platform = \"kvm\"\nEOF\n```\n-### Example: Enable gVisor debug logging\n+## Debug\n+\n+When `shim_debug` is enabled in `/etc/containerd/config.toml`, containerd will\n+forward shim logs to its own log. You can additionally set `level = \"debug\"` to\n+enable debug logs. To see the logs run `sudo journalctl -u containerd`. Here is\n+a containerd configuration file that enables both options:\n+\n+```shell\n+cat <<EOF | sudo tee /etc/containerd/config.toml\n+disabled_plugins = [\"restart\"]\n+[debug]\n+ level = \"debug\"\n+[plugins.linux]\n+ shim_debug = true\n+[plugins.cri.containerd.runtimes.runsc]\n+ runtime_type = \"io.containerd.runsc.v1\"\n+[plugins.cri.containerd.runtimes.runsc.options]\n+ TypeUrl = \"io.containerd.runsc.v1.options\"\n+ ConfigPath = \"/etc/containerd/runsc.toml\"\n+EOF\n+```\n+\n+It can be hard to separate containerd messages from the shim's though. To create\n+a log file dedicated to the shim, you can set the `log_path` and `log_level`\n+values in the shim configuration file:\n+\n+- `log_path` is the directory where the shim logs will be created. `%ID%` is\n+ the path is replaced with the container ID.\n+- `log_level` sets the logs level. It is normally set to \"debug\" as there is\n+ not much interesting happening with other log levels.\n+\n+### Example: Enable shim and gVisor debug logging\ngVisor debug logging can be enabled by setting the `debug` and `debug-log` flag.\nThe shim will replace \"%ID%\" with the container ID, and \"%COMMAND%\" with the\n@@ -63,8 +109,9 @@ Find out more about debugging in the [debugging guide](../debugging.md).\n```shell\ncat <<EOF | sudo tee /etc/containerd/runsc.toml\n+log_path = \"/var/log/runsc/%ID%/shim.log\"\n+log_level = \"debug\"\n[runsc_config]\n- debug=true\n- debug-log=/var/log/%ID%/gvisor.%COMMAND%.log\n-EOF\n+ debug = \"true\"\n+ debug-log = \"/var/log/runsc/%ID%/gvisor.%COMMAND%.log\"\n```\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add new shim debug options to docs
PiperOrigin-RevId: 342662753 |
259,964 | 16.11.2020 13:05:01 | 28,800 | 758e45618f3d663a092b31baf29f24b3e4dc4d54 | Clean up fragmentation.Process
Pass a PacketBuffer directly instead of releaseCB
No longer pass a VectorisedView, which is included in the PacketBuffer
Make it an error if data size is not equal to (last - first + 1)
Set the callback for the reassembly timeout on NewFragmentation | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/parse/parse.go",
"new_path": "pkg/tcpip/header/parse/parse.go",
"diff": "@@ -109,6 +109,9 @@ traverseExtensions:\nfragOffset = extHdr.FragmentOffset()\nfragMore = extHdr.More()\n}\n+ rawPayload := it.AsRawHeader(true /* consume */)\n+ extensionsSize = dataClone.Size() - rawPayload.Buf.Size()\n+ break traverseExtensions\ncase header.IPv6RawPayloadHeader:\n// We've found the payload after any extensions.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/fragmentation/BUILD",
"new_path": "pkg/tcpip/network/fragmentation/BUILD",
"diff": "@@ -47,6 +47,7 @@ go_test(\n\"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/faketime\",\n\"//pkg/tcpip/network/testutil\",\n+ \"//pkg/tcpip/stack\",\n\"@com_github_google_go_cmp//cmp:go_default_library\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/fragmentation/fragmentation.go",
"new_path": "pkg/tcpip/network/fragmentation/fragmentation.go",
"diff": "@@ -81,6 +81,15 @@ type Fragmentation struct {\nblockSize uint16\nclock tcpip.Clock\nreleaseJob *tcpip.Job\n+ timeoutHandler TimeoutHandler\n+}\n+\n+// TimeoutHandler is consulted if a packet reassembly has timed out.\n+type TimeoutHandler interface {\n+ // OnReassemblyTimeout will be called with the first fragment (or nil, if the\n+ // first fragment has not been received) of a packet whose reassembly has\n+ // timed out.\n+ OnReassemblyTimeout(pkt *stack.PacketBuffer)\n}\n// NewFragmentation creates a new Fragmentation.\n@@ -97,7 +106,7 @@ type Fragmentation struct {\n// reassemblingTimeout specifies the maximum time allowed to reassemble a packet.\n// Fragments are lazily evicted only when a new a packet with an\n// already existing fragmentation-id arrives after the timeout.\n-func NewFragmentation(blockSize uint16, highMemoryLimit, lowMemoryLimit int, reassemblingTimeout time.Duration, clock tcpip.Clock) *Fragmentation {\n+func NewFragmentation(blockSize uint16, highMemoryLimit, lowMemoryLimit int, reassemblingTimeout time.Duration, clock tcpip.Clock, timeoutHandler TimeoutHandler) *Fragmentation {\nif lowMemoryLimit >= highMemoryLimit {\nlowMemoryLimit = highMemoryLimit\n}\n@@ -117,6 +126,7 @@ func NewFragmentation(blockSize uint16, highMemoryLimit, lowMemoryLimit int, rea\ntimeout: reassemblingTimeout,\nblockSize: blockSize,\nclock: clock,\n+ timeoutHandler: timeoutHandler,\n}\nf.releaseJob = tcpip.NewJob(f.clock, &f.mu, f.releaseReassemblersLocked)\n@@ -136,16 +146,8 @@ func NewFragmentation(blockSize uint16, highMemoryLimit, lowMemoryLimit int, rea\n// proto is the protocol number marked in the fragment being processed. It has\n// to be given here outside of the FragmentID struct because IPv6 should not use\n// the protocol to identify a fragment.\n-//\n-// releaseCB is a callback that will run when the fragment reassembly of a\n-// packet is complete or cancelled. releaseCB take a a boolean argument which is\n-// true iff the reassembly is cancelled due to timeout. releaseCB should be\n-// passed only with the first fragment of a packet. If more than one releaseCB\n-// are passed for the same packet, only the first releaseCB will be saved for\n-// the packet and the succeeding ones will be dropped by running them\n-// immediately with a false argument.\nfunc (f *Fragmentation) Process(\n- id FragmentID, first, last uint16, more bool, proto uint8, vv buffer.VectorisedView, releaseCB func(bool)) (\n+ id FragmentID, first, last uint16, more bool, proto uint8, pkt *stack.PacketBuffer) (\nbuffer.VectorisedView, uint8, bool, error) {\nif first > last {\nreturn buffer.VectorisedView{}, 0, false, fmt.Errorf(\"first=%d is greater than last=%d: %w\", first, last, ErrInvalidArgs)\n@@ -160,10 +162,9 @@ func (f *Fragmentation) Process(\nreturn buffer.VectorisedView{}, 0, false, fmt.Errorf(\"fragment size=%d bytes is not a multiple of block size=%d on non-final fragment: %w\", fragmentSize, f.blockSize, ErrInvalidArgs)\n}\n- if l := vv.Size(); l < int(fragmentSize) {\n- return buffer.VectorisedView{}, 0, false, fmt.Errorf(\"got fragment size=%d bytes less than the expected fragment size=%d bytes (first=%d last=%d): %w\", l, fragmentSize, first, last, ErrInvalidArgs)\n+ if l := pkt.Data.Size(); l != int(fragmentSize) {\n+ return buffer.VectorisedView{}, 0, false, fmt.Errorf(\"got fragment size=%d bytes not equal to the expected fragment size=%d bytes (first=%d last=%d): %w\", l, fragmentSize, first, last, ErrInvalidArgs)\n}\n- vv.CapLength(int(fragmentSize))\nf.mu.Lock()\nr, ok := f.reassemblers[id]\n@@ -179,15 +180,9 @@ func (f *Fragmentation) Process(\nf.releaseReassemblersLocked()\n}\n}\n- if releaseCB != nil {\n- if !r.setCallback(releaseCB) {\n- // We got a duplicate callback. Release it immediately.\n- releaseCB(false /* timedOut */)\n- }\n- }\nf.mu.Unlock()\n- res, firstFragmentProto, done, consumed, err := r.process(first, last, more, proto, vv)\n+ res, firstFragmentProto, done, consumed, err := r.process(first, last, more, proto, pkt)\nif err != nil {\n// We probably got an invalid sequence of fragments. Just\n// discard the reassembler and move on.\n@@ -231,7 +226,9 @@ func (f *Fragmentation) release(r *reassembler, timedOut bool) {\nf.size = 0\n}\n- r.release(timedOut) // releaseCB may run.\n+ if h := f.timeoutHandler; timedOut && h != nil {\n+ h.OnReassemblyTimeout(r.pkt)\n+ }\n}\n// releaseReassemblersLocked releases already-expired reassemblers, then\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/fragmentation/fragmentation_test.go",
"new_path": "pkg/tcpip/network/fragmentation/fragmentation_test.go",
"diff": "@@ -24,6 +24,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/faketime\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/testutil\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/stack\"\n)\n// reassembleTimeout is dummy timeout used for testing, where the clock never\n@@ -40,13 +41,19 @@ func vv(size int, pieces ...string) buffer.VectorisedView {\nreturn buffer.NewVectorisedView(size, views)\n}\n+func pkt(size int, pieces ...string) *stack.PacketBuffer {\n+ return stack.NewPacketBuffer(stack.PacketBufferOptions{\n+ Data: vv(size, pieces...),\n+ })\n+}\n+\ntype processInput struct {\nid FragmentID\nfirst uint16\nlast uint16\nmore bool\nproto uint8\n- vv buffer.VectorisedView\n+ pkt *stack.PacketBuffer\n}\ntype processOutput struct {\n@@ -63,8 +70,8 @@ var processTestCases = []struct {\n{\ncomment: \"One ID\",\nin: []processInput{\n- {id: FragmentID{ID: 0}, first: 0, last: 1, more: true, vv: vv(2, \"01\")},\n- {id: FragmentID{ID: 0}, first: 2, last: 3, more: false, vv: vv(2, \"23\")},\n+ {id: FragmentID{ID: 0}, first: 0, last: 1, more: true, pkt: pkt(2, \"01\")},\n+ {id: FragmentID{ID: 0}, first: 2, last: 3, more: false, pkt: pkt(2, \"23\")},\n},\nout: []processOutput{\n{vv: buffer.VectorisedView{}, done: false},\n@@ -74,8 +81,8 @@ var processTestCases = []struct {\n{\ncomment: \"Next Header protocol mismatch\",\nin: []processInput{\n- {id: FragmentID{ID: 0}, first: 0, last: 1, more: true, proto: 6, vv: vv(2, \"01\")},\n- {id: FragmentID{ID: 0}, first: 2, last: 3, more: false, proto: 17, vv: vv(2, \"23\")},\n+ {id: FragmentID{ID: 0}, first: 0, last: 1, more: true, proto: 6, pkt: pkt(2, \"01\")},\n+ {id: FragmentID{ID: 0}, first: 2, last: 3, more: false, proto: 17, pkt: pkt(2, \"23\")},\n},\nout: []processOutput{\n{vv: buffer.VectorisedView{}, done: false},\n@@ -85,10 +92,10 @@ var processTestCases = []struct {\n{\ncomment: \"Two IDs\",\nin: []processInput{\n- {id: FragmentID{ID: 0}, first: 0, last: 1, more: true, vv: vv(2, \"01\")},\n- {id: FragmentID{ID: 1}, first: 0, last: 1, more: true, vv: vv(2, \"ab\")},\n- {id: FragmentID{ID: 1}, first: 2, last: 3, more: false, vv: vv(2, \"cd\")},\n- {id: FragmentID{ID: 0}, first: 2, last: 3, more: false, vv: vv(2, \"23\")},\n+ {id: FragmentID{ID: 0}, first: 0, last: 1, more: true, pkt: pkt(2, \"01\")},\n+ {id: FragmentID{ID: 1}, first: 0, last: 1, more: true, pkt: pkt(2, \"ab\")},\n+ {id: FragmentID{ID: 1}, first: 2, last: 3, more: false, pkt: pkt(2, \"cd\")},\n+ {id: FragmentID{ID: 0}, first: 2, last: 3, more: false, pkt: pkt(2, \"23\")},\n},\nout: []processOutput{\n{vv: buffer.VectorisedView{}, done: false},\n@@ -102,17 +109,17 @@ var processTestCases = []struct {\nfunc TestFragmentationProcess(t *testing.T) {\nfor _, c := range processTestCases {\nt.Run(c.comment, func(t *testing.T) {\n- f := NewFragmentation(minBlockSize, 1024, 512, reassembleTimeout, &faketime.NullClock{})\n+ f := NewFragmentation(minBlockSize, 1024, 512, reassembleTimeout, &faketime.NullClock{}, nil)\nfirstFragmentProto := c.in[0].proto\nfor i, in := range c.in {\n- vv, proto, done, err := f.Process(in.id, in.first, in.last, in.more, in.proto, in.vv, nil)\n+ vv, proto, done, err := f.Process(in.id, in.first, in.last, in.more, in.proto, in.pkt)\nif err != nil {\n- t.Fatalf(\"f.Process(%+v, %d, %d, %t, %d, %X) failed: %s\",\n- in.id, in.first, in.last, in.more, in.proto, in.vv.ToView(), err)\n+ t.Fatalf(\"f.Process(%+v, %d, %d, %t, %d, %#v) failed: %s\",\n+ in.id, in.first, in.last, in.more, in.proto, in.pkt, err)\n}\nif !reflect.DeepEqual(vv, c.out[i].vv) {\n- t.Errorf(\"got Process(%+v, %d, %d, %t, %d, %X) = (%X, _, _, _), want = (%X, _, _, _)\",\n- in.id, in.first, in.last, in.more, in.proto, in.vv.ToView(), vv.ToView(), c.out[i].vv.ToView())\n+ t.Errorf(\"got Process(%+v, %d, %d, %t, %d, %#v) = (%X, _, _, _), want = (%X, _, _, _)\",\n+ in.id, in.first, in.last, in.more, in.proto, in.pkt, vv.ToView(), c.out[i].vv.ToView())\n}\nif done != c.out[i].done {\nt.Errorf(\"got Process(%+v, %d, %d, %t, %d, _) = (_, _, %t, _), want = (_, _, %t, _)\",\n@@ -236,11 +243,11 @@ func TestReassemblingTimeout(t *testing.T) {\nfor _, test := range tests {\nt.Run(test.name, func(t *testing.T) {\nclock := faketime.NewManualClock()\n- f := NewFragmentation(minBlockSize, HighFragThreshold, LowFragThreshold, reassemblyTimeout, clock)\n+ f := NewFragmentation(minBlockSize, HighFragThreshold, LowFragThreshold, reassemblyTimeout, clock, nil)\nfor _, event := range test.events {\nclock.Advance(event.clockAdvance)\nif frag := event.fragment; frag != nil {\n- _, _, done, err := f.Process(FragmentID{}, frag.first, frag.last, frag.more, protocol, vv(len(frag.data), frag.data), nil)\n+ _, _, done, err := f.Process(FragmentID{}, frag.first, frag.last, frag.more, protocol, pkt(len(frag.data), frag.data))\nif err != nil {\nt.Fatalf(\"%s: f.Process failed: %s\", event.name, err)\n}\n@@ -257,17 +264,17 @@ func TestReassemblingTimeout(t *testing.T) {\n}\nfunc TestMemoryLimits(t *testing.T) {\n- f := NewFragmentation(minBlockSize, 3, 1, reassembleTimeout, &faketime.NullClock{})\n+ f := NewFragmentation(minBlockSize, 3, 1, reassembleTimeout, &faketime.NullClock{}, nil)\n// Send first fragment with id = 0.\n- f.Process(FragmentID{ID: 0}, 0, 0, true, 0xFF, vv(1, \"0\"), nil)\n+ f.Process(FragmentID{ID: 0}, 0, 0, true, 0xFF, pkt(1, \"0\"))\n// Send first fragment with id = 1.\n- f.Process(FragmentID{ID: 1}, 0, 0, true, 0xFF, vv(1, \"1\"), nil)\n+ f.Process(FragmentID{ID: 1}, 0, 0, true, 0xFF, pkt(1, \"1\"))\n// Send first fragment with id = 2.\n- f.Process(FragmentID{ID: 2}, 0, 0, true, 0xFF, vv(1, \"2\"), nil)\n+ f.Process(FragmentID{ID: 2}, 0, 0, true, 0xFF, pkt(1, \"2\"))\n// Send first fragment with id = 3. This should caused id = 0 and id = 1 to be\n// evicted.\n- f.Process(FragmentID{ID: 3}, 0, 0, true, 0xFF, vv(1, \"3\"), nil)\n+ f.Process(FragmentID{ID: 3}, 0, 0, true, 0xFF, pkt(1, \"3\"))\nif _, ok := f.reassemblers[FragmentID{ID: 0}]; ok {\nt.Errorf(\"Memory limits are not respected: id=0 has not been evicted.\")\n@@ -281,11 +288,11 @@ func TestMemoryLimits(t *testing.T) {\n}\nfunc TestMemoryLimitsIgnoresDuplicates(t *testing.T) {\n- f := NewFragmentation(minBlockSize, 1, 0, reassembleTimeout, &faketime.NullClock{})\n+ f := NewFragmentation(minBlockSize, 1, 0, reassembleTimeout, &faketime.NullClock{}, nil)\n// Send first fragment with id = 0.\n- f.Process(FragmentID{}, 0, 0, true, 0xFF, vv(1, \"0\"), nil)\n+ f.Process(FragmentID{}, 0, 0, true, 0xFF, pkt(1, \"0\"))\n// Send the same packet again.\n- f.Process(FragmentID{}, 0, 0, true, 0xFF, vv(1, \"0\"), nil)\n+ f.Process(FragmentID{}, 0, 0, true, 0xFF, pkt(1, \"0\"))\ngot := f.size\nwant := 1\n@@ -327,6 +334,7 @@ func TestErrors(t *testing.T) {\nlast: 3,\nmore: true,\ndata: \"012\",\n+ err: ErrInvalidArgs,\n},\n{\nname: \"exact block size with more and too little data\",\n@@ -376,8 +384,8 @@ func TestErrors(t *testing.T) {\nfor _, test := range tests {\nt.Run(test.name, func(t *testing.T) {\n- f := NewFragmentation(test.blockSize, HighFragThreshold, LowFragThreshold, reassembleTimeout, &faketime.NullClock{})\n- _, _, done, err := f.Process(FragmentID{}, test.first, test.last, test.more, 0, vv(len(test.data), test.data), nil)\n+ f := NewFragmentation(test.blockSize, HighFragThreshold, LowFragThreshold, reassembleTimeout, &faketime.NullClock{}, nil)\n+ _, _, done, err := f.Process(FragmentID{}, test.first, test.last, test.more, 0, pkt(len(test.data), test.data))\nif !errors.Is(err, test.err) {\nt.Errorf(\"got Process(_, %d, %d, %t, _, %q) = (_, _, _, %v), want = (_, _, _, %v)\", test.first, test.last, test.more, test.data, err, test.err)\n}\n@@ -498,57 +506,92 @@ func TestPacketFragmenter(t *testing.T) {\n}\n}\n-func TestReleaseCallback(t *testing.T) {\n+type testTimeoutHandler struct {\n+ pkt *stack.PacketBuffer\n+}\n+\n+func (h *testTimeoutHandler) OnReassemblyTimeout(pkt *stack.PacketBuffer) {\n+ h.pkt = pkt\n+}\n+\n+func TestTimeoutHandler(t *testing.T) {\nconst (\nproto = 99\n)\n- var result int\n- var callbackReasonIsTimeout bool\n- cb1 := func(timedOut bool) { result = 1; callbackReasonIsTimeout = timedOut }\n- cb2 := func(timedOut bool) { result = 2; callbackReasonIsTimeout = timedOut }\n+ pk1 := pkt(1, \"1\")\n+ pk2 := pkt(1, \"2\")\n+\n+ type processParam struct {\n+ first uint16\n+ last uint16\n+ more bool\n+ pkt *stack.PacketBuffer\n+ }\ntests := []struct {\nname string\n- callbacks []func(bool)\n- timeout bool\n- wantResult int\n- wantCallbackReasonIsTimeout bool\n+ params []processParam\n+ wantError bool\n+ wantPkt *stack.PacketBuffer\n}{\n{\n- name: \"callback runs on release\",\n- callbacks: []func(bool){cb1},\n- timeout: false,\n- wantResult: 1,\n- wantCallbackReasonIsTimeout: false,\n+ name: \"onTimeout runs\",\n+ params: []processParam{\n+ {\n+ first: 0,\n+ last: 0,\n+ more: true,\n+ pkt: pk1,\n+ },\n+ },\n+ wantError: false,\n+ wantPkt: pk1,\n},\n{\n- name: \"first callback is nil\",\n- callbacks: []func(bool){nil, cb2},\n- timeout: false,\n- wantResult: 2,\n- wantCallbackReasonIsTimeout: false,\n+ name: \"no first fragment\",\n+ params: []processParam{\n+ {\n+ first: 1,\n+ last: 1,\n+ more: true,\n+ pkt: pk1,\n+ },\n},\n+ wantError: false,\n+ wantPkt: nil,\n+ },\n+ {\n+ name: \"second pkt is ignored\",\n+ params: []processParam{\n{\n- name: \"two callbacks - first one is set\",\n- callbacks: []func(bool){cb1, cb2},\n- timeout: false,\n- wantResult: 1,\n- wantCallbackReasonIsTimeout: false,\n+ first: 0,\n+ last: 0,\n+ more: true,\n+ pkt: pk1,\n},\n{\n- name: \"callback runs on timeout\",\n- callbacks: []func(bool){cb1},\n- timeout: true,\n- wantResult: 1,\n- wantCallbackReasonIsTimeout: true,\n+ first: 0,\n+ last: 0,\n+ more: true,\n+ pkt: pk2,\n+ },\n+ },\n+ wantError: false,\n+ wantPkt: pk1,\n},\n{\n- name: \"no callbacks\",\n- callbacks: []func(bool){nil},\n- timeout: false,\n- wantResult: 0,\n- wantCallbackReasonIsTimeout: false,\n+ name: \"invalid args - first is greater than last\",\n+ params: []processParam{\n+ {\n+ first: 1,\n+ last: 0,\n+ more: true,\n+ pkt: pk1,\n+ },\n+ },\n+ wantError: true,\n+ wantPkt: nil,\n},\n}\n@@ -556,29 +599,31 @@ func TestReleaseCallback(t *testing.T) {\nfor _, test := range tests {\nt.Run(test.name, func(t *testing.T) {\n- result = 0\n- callbackReasonIsTimeout = false\n+ handler := &testTimeoutHandler{pkt: nil}\n- f := NewFragmentation(minBlockSize, HighFragThreshold, LowFragThreshold, reassembleTimeout, &faketime.NullClock{})\n+ f := NewFragmentation(minBlockSize, HighFragThreshold, LowFragThreshold, reassembleTimeout, &faketime.NullClock{}, handler)\n- for i, cb := range test.callbacks {\n- _, _, _, err := f.Process(id, uint16(i), uint16(i), true, proto, vv(1, \"0\"), cb)\n- if err != nil {\n+ for _, p := range test.params {\n+ if _, _, _, err := f.Process(id, p.first, p.last, p.more, proto, p.pkt); err != nil && !test.wantError {\nt.Errorf(\"f.Process error = %s\", err)\n}\n}\n-\n+ if !test.wantError {\nr, ok := f.reassemblers[id]\nif !ok {\n- t.Fatalf(\"Reassemberr not found\")\n+ t.Fatal(\"Reassembler not found\")\n}\n- f.release(r, test.timeout)\n-\n- if result != test.wantResult {\n- t.Errorf(\"got result = %d, want = %d\", result, test.wantResult)\n+ f.release(r, true)\n+ }\n+ switch {\n+ case handler.pkt != nil && test.wantPkt == nil:\n+ t.Errorf(\"got handler.pkt = not nil (pkt.Data = %x), want = nil\", handler.pkt.Data.ToView())\n+ case handler.pkt == nil && test.wantPkt != nil:\n+ t.Errorf(\"got handler.pkt = nil, want = not nil (pkt.Data = %x)\", test.wantPkt.Data.ToView())\n+ case handler.pkt != nil && test.wantPkt != nil:\n+ if diff := cmp.Diff(test.wantPkt.Data.ToView(), handler.pkt.Data.ToView()); diff != \"\" {\n+ t.Errorf(\"pkt.Data mismatch (-want, +got):\\n%s\", diff)\n}\n- if callbackReasonIsTimeout != test.wantCallbackReasonIsTimeout {\n- t.Errorf(\"got callbackReasonIsTimeout = %t, want = %t\", callbackReasonIsTimeout, test.wantCallbackReasonIsTimeout)\n}\n})\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/fragmentation/reassembler.go",
"new_path": "pkg/tcpip/network/fragmentation/reassembler.go",
"diff": "@@ -22,6 +22,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/stack\"\n)\ntype hole struct {\n@@ -41,7 +42,7 @@ type reassembler struct {\nheap fragHeap\ndone bool\ncreationTime int64\n- callback func(bool)\n+ pkt *stack.PacketBuffer\n}\nfunc newReassembler(id FragmentID, clock tcpip.Clock) *reassembler {\n@@ -79,7 +80,7 @@ func (r *reassembler) updateHoles(first, last uint16, more bool) bool {\nreturn used\n}\n-func (r *reassembler) process(first, last uint16, more bool, proto uint8, vv buffer.VectorisedView) (buffer.VectorisedView, uint8, bool, int, error) {\n+func (r *reassembler) process(first, last uint16, more bool, proto uint8, pkt *stack.PacketBuffer) (buffer.VectorisedView, uint8, bool, int, error) {\nr.mu.Lock()\ndefer r.mu.Unlock()\nconsumed := 0\n@@ -89,18 +90,20 @@ func (r *reassembler) process(first, last uint16, more bool, proto uint8, vv buf\n// was waiting on the mutex. We don't have to do anything in this case.\nreturn buffer.VectorisedView{}, 0, false, consumed, nil\n}\n+ if r.updateHoles(first, last, more) {\n// For IPv6, it is possible to have different Protocol values between\n// fragments of a packet (because, unlike IPv4, the Protocol is not used to\n// identify a fragment). In this case, only the Protocol of the first\n// fragment must be used as per RFC 8200 Section 4.5.\n//\n- // TODO(gvisor.dev/issue/3648): The entire first IP header should be recorded\n- // here (instead of just the protocol) because most IP options should be\n- // derived from the first fragment.\n+ // TODO(gvisor.dev/issue/3648): During reassembly of an IPv6 packet, IP\n+ // options received in the first fragment should be used - and they should\n+ // override options from following fragments.\nif first == 0 {\n+ r.pkt = pkt\nr.proto = proto\n}\n- if r.updateHoles(first, last, more) {\n+ vv := pkt.Data\n// We store the incoming packet only if it filled some holes.\nheap.Push(&r.heap, fragment{offset: first, vv: vv.Clone(nil)})\nconsumed = vv.Size()\n@@ -124,24 +127,3 @@ func (r *reassembler) checkDoneOrMark() bool {\nr.mu.Unlock()\nreturn prev\n}\n-\n-func (r *reassembler) setCallback(c func(bool)) bool {\n- r.mu.Lock()\n- defer r.mu.Unlock()\n- if r.callback != nil {\n- return false\n- }\n- r.callback = c\n- return true\n-}\n-\n-func (r *reassembler) release(timedOut bool) {\n- r.mu.Lock()\n- callback := r.callback\n- r.callback = nil\n- r.mu.Unlock()\n-\n- if callback != nil {\n- callback(timedOut)\n- }\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/fragmentation/reassembler_test.go",
"new_path": "pkg/tcpip/network/fragmentation/reassembler_test.go",
"diff": "@@ -105,26 +105,3 @@ func TestUpdateHoles(t *testing.T) {\n}\n}\n}\n-\n-func TestSetCallback(t *testing.T) {\n- result := 0\n- reasonTimeout := false\n-\n- cb1 := func(timedOut bool) { result = 1; reasonTimeout = timedOut }\n- cb2 := func(timedOut bool) { result = 2; reasonTimeout = timedOut }\n-\n- r := newReassembler(FragmentID{}, &faketime.NullClock{})\n- if !r.setCallback(cb1) {\n- t.Errorf(\"setCallback failed\")\n- }\n- if r.setCallback(cb2) {\n- t.Errorf(\"setCallback should fail if one is already set\")\n- }\n- r.release(true)\n- if result != 1 {\n- t.Errorf(\"got result = %d, want = 1\", result)\n- }\n- if !reasonTimeout {\n- t.Errorf(\"got reasonTimeout = %t, want = true\", reasonTimeout)\n- }\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/icmp.go",
"new_path": "pkg/tcpip/network/ipv4/icmp.go",
"diff": "@@ -514,3 +514,18 @@ func (p *protocol) returnError(reason icmpReason, pkt *stack.PacketBuffer) *tcpi\ncounter.Increment()\nreturn nil\n}\n+\n+// OnReassemblyTimeout implements fragmentation.TimeoutHandler.\n+func (p *protocol) OnReassemblyTimeout(pkt *stack.PacketBuffer) {\n+ // OnReassemblyTimeout sends a Time Exceeded Message, as per RFC 792:\n+ //\n+ // If a host reassembling a fragmented datagram cannot complete the\n+ // reassembly due to missing fragments within its time limit it discards the\n+ // datagram, and it may send a time exceeded message.\n+ //\n+ // If fragment zero is not available then no time exceeded need be sent at\n+ // all.\n+ if pkt != nil {\n+ p.returnError(&icmpReasonReassemblyTimeout{}, pkt)\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4.go",
"diff": "@@ -650,29 +650,8 @@ func (e *endpoint) handlePacket(pkt *stack.PacketBuffer) {\nreturn\n}\n- // Set up a callback in case we need to send a Time Exceeded Message, as per\n- // RFC 792:\n- //\n- // If a host reassembling a fragmented datagram cannot complete the\n- // reassembly due to missing fragments within its time limit it discards\n- // the datagram, and it may send a time exceeded message.\n- //\n- // If fragment zero is not available then no time exceeded need be sent at\n- // all.\n- var releaseCB func(bool)\n- if start == 0 {\n- pkt := pkt.Clone()\n- releaseCB = func(timedOut bool) {\n- if timedOut {\n- _ = e.protocol.returnError(&icmpReasonReassemblyTimeout{}, pkt)\n- }\n- }\n- }\n-\n- var ready bool\n- var err error\nproto := h.Protocol()\n- pkt.Data, _, ready, err = e.protocol.fragmentation.Process(\n+ data, _, ready, err := e.protocol.fragmentation.Process(\n// As per RFC 791 section 2.3, the identification value is unique\n// for a source-destination pair and protocol.\nfragmentation.FragmentID{\n@@ -685,8 +664,7 @@ func (e *endpoint) handlePacket(pkt *stack.PacketBuffer) {\nstart+uint16(pkt.Data.Size())-1,\nh.More(),\nproto,\n- pkt.Data,\n- releaseCB,\n+ pkt,\n)\nif err != nil {\nstats.IP.MalformedPacketsReceived.Increment()\n@@ -696,6 +674,7 @@ func (e *endpoint) handlePacket(pkt *stack.PacketBuffer) {\nif !ready {\nreturn\n}\n+ pkt.Data = data\n// The reassembler doesn't take care of fixing up the header, so we need\n// to do it here.\n@@ -863,6 +842,7 @@ func (e *endpoint) IsInGroup(addr tcpip.Address) bool {\nvar _ stack.ForwardingNetworkProtocol = (*protocol)(nil)\nvar _ stack.NetworkProtocol = (*protocol)(nil)\n+var _ fragmentation.TimeoutHandler = (*protocol)(nil)\ntype protocol struct {\nstack *stack.Stack\n@@ -1027,13 +1007,14 @@ func NewProtocol(s *stack.Stack) stack.NetworkProtocol {\n}\nhashIV := r[buckets]\n- return &protocol{\n+ p := &protocol{\nstack: s,\nids: ids,\nhashIV: hashIV,\ndefaultTTL: DefaultTTL,\n- fragmentation: fragmentation.NewFragmentation(fragmentblockSize, fragmentation.HighFragThreshold, fragmentation.LowFragThreshold, ReassembleTimeout, s.Clock()),\n}\n+ p.fragmentation = fragmentation.NewFragmentation(fragmentblockSize, fragmentation.HighFragThreshold, fragmentation.LowFragThreshold, ReassembleTimeout, s.Clock(), p)\n+ return p\n}\nfunc buildNextFragment(pf *fragmentation.PacketFragmenter, originalIPHeader header.IPv4) (*stack.PacketBuffer, bool) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/icmp.go",
"new_path": "pkg/tcpip/network/ipv6/icmp.go",
"diff": "@@ -922,3 +922,16 @@ func (p *protocol) returnError(reason icmpReason, pkt *stack.PacketBuffer) *tcpi\ncounter.Increment()\nreturn nil\n}\n+\n+// OnReassemblyTimeout implements fragmentation.TimeoutHandler.\n+func (p *protocol) OnReassemblyTimeout(pkt *stack.PacketBuffer) {\n+ // OnReassemblyTimeout sends a Time Exceeded Message as per RFC 2460 Section\n+ // 4.5:\n+ //\n+ // If the first fragment (i.e., the one with a Fragment Offset of zero) has\n+ // been received, an ICMP Time Exceeded -- Fragment Reassembly Time Exceeded\n+ // message should be sent to the source of that fragment.\n+ if pkt != nil {\n+ p.returnError(&icmpReasonReassemblyTimeout{}, pkt)\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6.go",
"diff": "@@ -967,18 +967,6 @@ func (e *endpoint) handlePacket(pkt *stack.PacketBuffer) {\nreturn\n}\n- // Set up a callback in case we need to send a Time Exceeded Message as\n- // per RFC 2460 Section 4.5.\n- var releaseCB func(bool)\n- if start == 0 {\n- pkt := pkt.Clone()\n- releaseCB = func(timedOut bool) {\n- if timedOut {\n- _ = e.protocol.returnError(&icmpReasonReassemblyTimeout{}, pkt)\n- }\n- }\n- }\n-\n// Note that pkt doesn't have its transport header set after reassembly,\n// and won't until DeliverNetworkPacket sets it.\ndata, proto, ready, err := e.protocol.fragmentation.Process(\n@@ -993,17 +981,17 @@ func (e *endpoint) handlePacket(pkt *stack.PacketBuffer) {\nstart+uint16(fragmentPayloadLen)-1,\nextHdr.More(),\nuint8(rawPayload.Identifier),\n- rawPayload.Buf,\n- releaseCB,\n+ pkt,\n)\nif err != nil {\nstats.IP.MalformedPacketsReceived.Increment()\nstats.IP.MalformedFragmentsReceived.Increment()\nreturn\n}\n- pkt.Data = data\nif ready {\n+ pkt.Data = data\n+\n// We create a new iterator with the reassembled packet because we could\n// have more extension headers in the reassembled payload, as per RFC\n// 8200 section 4.5. We also use the NextHeader value from the first\n@@ -1414,6 +1402,7 @@ func (e *endpoint) IsInGroup(addr tcpip.Address) bool {\nvar _ stack.ForwardingNetworkProtocol = (*protocol)(nil)\nvar _ stack.NetworkProtocol = (*protocol)(nil)\n+var _ fragmentation.TimeoutHandler = (*protocol)(nil)\ntype protocol struct {\nstack *stack.Stack\n@@ -1670,7 +1659,6 @@ func NewProtocolWithOptions(opts Options) stack.NetworkProtocolFactory {\nreturn func(s *stack.Stack) stack.NetworkProtocol {\np := &protocol{\nstack: s,\n- fragmentation: fragmentation.NewFragmentation(header.IPv6FragmentExtHdrFragmentOffsetBytesPerUnit, fragmentation.HighFragThreshold, fragmentation.LowFragThreshold, ReassembleTimeout, s.Clock()),\nids: ids,\nhashIV: hashIV,\n@@ -1680,6 +1668,7 @@ func NewProtocolWithOptions(opts Options) stack.NetworkProtocolFactory {\ntempIIDSeed: opts.TempIIDSeed,\nautoGenIPv6LinkLocal: opts.AutoGenIPv6LinkLocal,\n}\n+ p.fragmentation = fragmentation.NewFragmentation(header.IPv6FragmentExtHdrFragmentOffsetBytesPerUnit, fragmentation.HighFragThreshold, fragmentation.LowFragThreshold, ReassembleTimeout, s.Clock(), p)\np.mu.eps = make(map[*endpoint]struct{})\np.SetDefaultTTL(DefaultTTL)\nreturn p\n"
}
] | Go | Apache License 2.0 | google/gvisor | Clean up fragmentation.Process
- Pass a PacketBuffer directly instead of releaseCB
- No longer pass a VectorisedView, which is included in the PacketBuffer
- Make it an error if data size is not equal to (last - first + 1)
- Set the callback for the reassembly timeout on NewFragmentation
PiperOrigin-RevId: 342702432 |
259,964 | 16.11.2020 13:11:36 | 28,800 | 373fd8310032ef19e05f8cc77a1eeb6fcb438da8 | Add packetimpact tests for ICMPv6 Error message for fragment
Updates | [
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/runner/defs.bzl",
"new_path": "test/packetimpact/runner/defs.bzl",
"diff": "@@ -257,6 +257,9 @@ ALL_TESTS = [\nPacketimpactTestInfo(\nname = \"ipv6_fragment_reassembly\",\n),\n+ PacketimpactTestInfo(\n+ name = \"ipv6_fragment_icmp_error\",\n+ ),\nPacketimpactTestInfo(\nname = \"udp_send_recv_dgram\",\n),\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/BUILD",
"new_path": "test/packetimpact/tests/BUILD",
"diff": "@@ -322,6 +322,20 @@ packetimpact_testbench(\n],\n)\n+packetimpact_testbench(\n+ name = \"ipv6_fragment_icmp_error\",\n+ srcs = [\"ipv6_fragment_icmp_error_test.go\"],\n+ deps = [\n+ \"//pkg/tcpip\",\n+ \"//pkg/tcpip/buffer\",\n+ \"//pkg/tcpip/header\",\n+ \"//pkg/tcpip/network/ipv6\",\n+ \"//test/packetimpact/testbench\",\n+ \"@com_github_google_go_cmp//cmp:go_default_library\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n+ ],\n+)\n+\npacketimpact_testbench(\nname = \"udp_send_recv_dgram\",\nsrcs = [\"udp_send_recv_dgram_test.go\"],\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/packetimpact/tests/ipv6_fragment_icmp_error_test.go",
"diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package ipv6_fragment_icmp_error_test\n+\n+import (\n+ \"flag\"\n+ \"net\"\n+ \"testing\"\n+ \"time\"\n+\n+ \"github.com/google/go-cmp/cmp\"\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/network/ipv6\"\n+ \"gvisor.dev/gvisor/test/packetimpact/testbench\"\n+)\n+\n+const (\n+ data = \"IPV6_PROTOCOL_TESTER_FOR_FRAGMENT\"\n+ fragmentID = 1\n+ reassemblyTimeout = ipv6.ReassembleTimeout + 5*time.Second\n+)\n+\n+func init() {\n+ testbench.RegisterFlags(flag.CommandLine)\n+}\n+\n+func fragmentedICMPEchoRequest(t *testing.T, conn *testbench.Connection, firstPayloadLength uint16, payload []byte, secondFragmentOffset uint16) ([]testbench.Layers, [][]byte) {\n+ t.Helper()\n+\n+ icmpv6Header := header.ICMPv6(make([]byte, header.ICMPv6EchoMinimumSize))\n+ icmpv6Header.SetType(header.ICMPv6EchoRequest)\n+ icmpv6Header.SetCode(header.ICMPv6UnusedCode)\n+ icmpv6Header.SetIdent(0)\n+ icmpv6Header.SetSequence(0)\n+ cksum := header.ICMPv6Checksum(\n+ icmpv6Header,\n+ tcpip.Address(net.ParseIP(testbench.LocalIPv6).To16()),\n+ tcpip.Address(net.ParseIP(testbench.RemoteIPv6).To16()),\n+ buffer.NewVectorisedView(len(payload), []buffer.View{payload}),\n+ )\n+ icmpv6Header.SetChecksum(cksum)\n+ icmpv6Bytes := append([]byte(icmpv6Header), payload...)\n+\n+ icmpv6ProtoNum := header.IPv6ExtensionHeaderIdentifier(header.ICMPv6ProtocolNumber)\n+\n+ firstFragment := conn.CreateFrame(t, testbench.Layers{&testbench.IPv6{}},\n+ &testbench.IPv6FragmentExtHdr{\n+ NextHeader: &icmpv6ProtoNum,\n+ FragmentOffset: testbench.Uint16(0),\n+ MoreFragments: testbench.Bool(true),\n+ Identification: testbench.Uint32(fragmentID),\n+ },\n+ &testbench.Payload{\n+ Bytes: icmpv6Bytes[:header.ICMPv6PayloadOffset+firstPayloadLength],\n+ },\n+ )\n+ firstIPv6 := firstFragment[1:]\n+ firstIPv6Bytes, err := firstIPv6.ToBytes()\n+ if err != nil {\n+ t.Fatalf(\"failed to convert first %s to bytes: %s\", firstIPv6, err)\n+ }\n+\n+ secondFragment := conn.CreateFrame(t, testbench.Layers{&testbench.IPv6{}},\n+ &testbench.IPv6FragmentExtHdr{\n+ NextHeader: &icmpv6ProtoNum,\n+ FragmentOffset: testbench.Uint16(secondFragmentOffset),\n+ MoreFragments: testbench.Bool(false),\n+ Identification: testbench.Uint32(fragmentID),\n+ },\n+ &testbench.Payload{\n+ Bytes: icmpv6Bytes[header.ICMPv6PayloadOffset+firstPayloadLength:],\n+ },\n+ )\n+ secondIPv6 := secondFragment[1:]\n+ secondIPv6Bytes, err := secondIPv6.ToBytes()\n+ if err != nil {\n+ t.Fatalf(\"failed to convert second %s to bytes: %s\", secondIPv6, err)\n+ }\n+\n+ return []testbench.Layers{firstFragment, secondFragment}, [][]byte{firstIPv6Bytes, secondIPv6Bytes}\n+}\n+\n+func TestIPv6ICMPEchoRequestFragmentReassembly(t *testing.T) {\n+ tests := []struct {\n+ name string\n+ firstPayloadLength uint16\n+ payload []byte\n+ secondFragmentOffset uint16\n+ sendFrameOrder []int\n+ }{\n+ {\n+ name: \"reassemble two fragments\",\n+ firstPayloadLength: 8,\n+ payload: []byte(data)[:20],\n+ secondFragmentOffset: (header.ICMPv6EchoMinimumSize + 8) / 8,\n+ sendFrameOrder: []int{1, 2},\n+ },\n+ {\n+ name: \"reassemble two fragments in reverse order\",\n+ firstPayloadLength: 8,\n+ payload: []byte(data)[:20],\n+ secondFragmentOffset: (header.ICMPv6EchoMinimumSize + 8) / 8,\n+ sendFrameOrder: []int{2, 1},\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ dut := testbench.NewDUT(t)\n+ defer dut.TearDown()\n+ ipv6Conn := testbench.NewIPv6Conn(t, testbench.IPv6{}, testbench.IPv6{})\n+ conn := (*testbench.Connection)(&ipv6Conn)\n+ defer ipv6Conn.Close(t)\n+\n+ fragments, _ := fragmentedICMPEchoRequest(t, conn, test.firstPayloadLength, test.payload, test.secondFragmentOffset)\n+\n+ for _, i := range test.sendFrameOrder {\n+ conn.SendFrame(t, fragments[i-1])\n+ }\n+\n+ gotEchoReply, err := ipv6Conn.ExpectFrame(t, testbench.Layers{\n+ &testbench.Ether{},\n+ &testbench.IPv6{},\n+ &testbench.ICMPv6{\n+ Type: testbench.ICMPv6Type(header.ICMPv6EchoReply),\n+ Code: testbench.ICMPv6Code(header.ICMPv6UnusedCode),\n+ },\n+ }, time.Second)\n+ if err != nil {\n+ t.Fatalf(\"didn't receive an ICMPv6 Echo Reply: %s\", err)\n+ }\n+ gotPayload, err := gotEchoReply[len(gotEchoReply)-1].ToBytes()\n+ if err != nil {\n+ t.Fatalf(\"failed to convert ICMPv6 to bytes: %s\", err)\n+ }\n+ icmpPayload := gotPayload[header.ICMPv6EchoMinimumSize:]\n+ wantPayload := test.payload\n+ if diff := cmp.Diff(wantPayload, icmpPayload); diff != \"\" {\n+ t.Fatalf(\"payload mismatch (-want +got):\\n%s\", diff)\n+ }\n+ })\n+ }\n+}\n+\n+func TestIPv6FragmentReassemblyTimeout(t *testing.T) {\n+ type icmpFramePattern struct {\n+ typ header.ICMPv6Type\n+ code header.ICMPv6Code\n+ }\n+\n+ type icmpReassemblyTimeoutDetail struct {\n+ payloadFragment int // 1: first fragment, 2: second fragnemt.\n+ }\n+\n+ tests := []struct {\n+ name string\n+ firstPayloadLength uint16\n+ payload []byte\n+ secondFragmentOffset uint16\n+ sendFrameOrder []int\n+ replyFilter icmpFramePattern\n+ expectErrorReply bool\n+ expectICMPReassemblyTimeout icmpReassemblyTimeoutDetail\n+ }{\n+ {\n+ name: \"reassembly timeout (first fragment only)\",\n+ firstPayloadLength: 8,\n+ payload: []byte(data)[:20],\n+ secondFragmentOffset: (header.ICMPv6EchoMinimumSize + 8) / 8,\n+ sendFrameOrder: []int{1},\n+ replyFilter: icmpFramePattern{\n+ typ: header.ICMPv6TimeExceeded,\n+ code: header.ICMPv6ReassemblyTimeout,\n+ },\n+ expectErrorReply: true,\n+ expectICMPReassemblyTimeout: icmpReassemblyTimeoutDetail{\n+ payloadFragment: 1,\n+ },\n+ },\n+ {\n+ name: \"reassembly timeout (second fragment only)\",\n+ firstPayloadLength: 8,\n+ payload: []byte(data)[:20],\n+ secondFragmentOffset: (header.ICMPv6EchoMinimumSize + 8) / 8,\n+ sendFrameOrder: []int{2},\n+ replyFilter: icmpFramePattern{\n+ typ: header.ICMPv6TimeExceeded,\n+ code: header.ICMPv6ReassemblyTimeout,\n+ },\n+ expectErrorReply: false,\n+ },\n+ {\n+ name: \"reassembly timeout (two fragments with a gap)\",\n+ firstPayloadLength: 8,\n+ payload: []byte(data)[:20],\n+ secondFragmentOffset: (header.ICMPv6EchoMinimumSize + 16) / 8,\n+ sendFrameOrder: []int{1, 2},\n+ replyFilter: icmpFramePattern{\n+ typ: header.ICMPv6TimeExceeded,\n+ code: header.ICMPv6ReassemblyTimeout,\n+ },\n+ expectErrorReply: true,\n+ expectICMPReassemblyTimeout: icmpReassemblyTimeoutDetail{\n+ payloadFragment: 1,\n+ },\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ dut := testbench.NewDUT(t)\n+ defer dut.TearDown()\n+ ipv6Conn := testbench.NewIPv6Conn(t, testbench.IPv6{}, testbench.IPv6{})\n+ conn := (*testbench.Connection)(&ipv6Conn)\n+ defer ipv6Conn.Close(t)\n+\n+ fragments, ipv6Bytes := fragmentedICMPEchoRequest(t, conn, test.firstPayloadLength, test.payload, test.secondFragmentOffset)\n+\n+ for _, i := range test.sendFrameOrder {\n+ conn.SendFrame(t, fragments[i-1])\n+ }\n+\n+ gotErrorMessage, err := ipv6Conn.ExpectFrame(t, testbench.Layers{\n+ &testbench.Ether{},\n+ &testbench.IPv6{},\n+ &testbench.ICMPv6{\n+ Type: testbench.ICMPv6Type(test.replyFilter.typ),\n+ Code: testbench.ICMPv6Code(test.replyFilter.code),\n+ },\n+ }, reassemblyTimeout)\n+ if !test.expectErrorReply {\n+ if err == nil {\n+ t.Fatalf(\"shouldn't receive an ICMPv6 Error Message with type=%d and code=%d\", test.replyFilter.typ, test.replyFilter.code)\n+ }\n+ return\n+ }\n+ if err != nil {\n+ t.Fatalf(\"didn't receive an ICMPv6 Error Message with type=%d and code=%d: err\", test.replyFilter.typ, test.replyFilter.code, err)\n+ }\n+ gotPayload, err := gotErrorMessage[len(gotErrorMessage)-1].ToBytes()\n+ if err != nil {\n+ t.Fatalf(\"failed to convert ICMPv6 to bytes: %s\", err)\n+ }\n+ icmpPayload := gotPayload[header.ICMPv6ErrorHeaderSize:]\n+ wantPayload := ipv6Bytes[test.expectICMPReassemblyTimeout.payloadFragment-1]\n+ if diff := cmp.Diff(wantPayload, icmpPayload); diff != \"\" {\n+ t.Fatalf(\"payload mismatch (-want +got):\\n%s\", diff)\n+ }\n+ })\n+ }\n+}\n+\n+func TestIPv6FragmentParamProblem(t *testing.T) {\n+ type icmpFramePattern struct {\n+ typ header.ICMPv6Type\n+ code header.ICMPv6Code\n+ }\n+\n+ type icmpParamProblemDetail struct {\n+ pointer uint32\n+ payloadFragment int // 1: first fragment, 2: second fragnemt.\n+ }\n+\n+ tests := []struct {\n+ name string\n+ firstPayloadLength uint16\n+ payload []byte\n+ secondFragmentOffset uint16\n+ sendFrameOrder []int\n+ replyFilter icmpFramePattern\n+ expectICMPParamProblem icmpParamProblemDetail\n+ }{\n+ {\n+ name: \"payload size not a multiple of 8\",\n+ firstPayloadLength: 9,\n+ payload: []byte(data)[:20],\n+ secondFragmentOffset: (header.ICMPv6EchoMinimumSize + 8) / 8,\n+ sendFrameOrder: []int{1},\n+ replyFilter: icmpFramePattern{\n+ typ: header.ICMPv6ParamProblem,\n+ code: header.ICMPv6ErroneousHeader,\n+ },\n+ expectICMPParamProblem: icmpParamProblemDetail{\n+ pointer: 4,\n+ payloadFragment: 1,\n+ },\n+ },\n+ {\n+ name: \"payload length error\",\n+ firstPayloadLength: 16,\n+ payload: []byte(data)[:33],\n+ secondFragmentOffset: 65520 / 8,\n+ sendFrameOrder: []int{1, 2},\n+ replyFilter: icmpFramePattern{\n+ typ: header.ICMPv6ParamProblem,\n+ code: header.ICMPv6ErroneousHeader,\n+ },\n+ expectICMPParamProblem: icmpParamProblemDetail{\n+ pointer: 42,\n+ payloadFragment: 2,\n+ },\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ dut := testbench.NewDUT(t)\n+ defer dut.TearDown()\n+ ipv6Conn := testbench.NewIPv6Conn(t, testbench.IPv6{}, testbench.IPv6{})\n+ conn := (*testbench.Connection)(&ipv6Conn)\n+ defer ipv6Conn.Close(t)\n+\n+ fragments, ipv6Bytes := fragmentedICMPEchoRequest(t, conn, test.firstPayloadLength, test.payload, test.secondFragmentOffset)\n+\n+ for _, i := range test.sendFrameOrder {\n+ conn.SendFrame(t, fragments[i-1])\n+ }\n+\n+ gotErrorMessage, err := ipv6Conn.ExpectFrame(t, testbench.Layers{\n+ &testbench.Ether{},\n+ &testbench.IPv6{},\n+ &testbench.ICMPv6{\n+ Type: testbench.ICMPv6Type(test.replyFilter.typ),\n+ Code: testbench.ICMPv6Code(test.replyFilter.code),\n+ },\n+ }, time.Second)\n+ if err != nil {\n+ t.Fatalf(\"didn't receive an ICMPv6 Error Message with type=%d and code=%d: err\", test.replyFilter.typ, test.replyFilter.code, err)\n+ }\n+ gotPayload, err := gotErrorMessage[len(gotErrorMessage)-1].ToBytes()\n+ if err != nil {\n+ t.Fatalf(\"failed to convert ICMPv6 to bytes: %s\", err)\n+ }\n+ gotPointer := header.ICMPv6(gotPayload).TypeSpecific()\n+ wantPointer := test.expectICMPParamProblem.pointer\n+ if gotPointer != wantPointer {\n+ t.Fatalf(\"got pointer = %d, want = %d\", gotPointer, wantPointer)\n+ }\n+ icmpPayload := gotPayload[header.ICMPv6ErrorHeaderSize:]\n+ wantPayload := ipv6Bytes[test.expectICMPParamProblem.payloadFragment-1]\n+ if diff := cmp.Diff(wantPayload, icmpPayload); diff != \"\" {\n+ t.Fatalf(\"payload mismatch (-want +got):\\n%s\", diff)\n+ }\n+ })\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add packetimpact tests for ICMPv6 Error message for fragment
Updates #4427
PiperOrigin-RevId: 342703931 |
259,992 | 16.11.2020 16:29:16 | 28,800 | d48610795d94f4d1a1782bd5372cbb8e0a76931c | Allow RLIMIT_RSS to be set
Closes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_rlimit.go",
"new_path": "pkg/sentry/syscalls/linux/sys_rlimit.go",
"diff": "@@ -90,6 +90,9 @@ var setableLimits = map[limits.LimitType]struct{}{\nlimits.FileSize: {},\nlimits.MemoryLocked: {},\nlimits.Stack: {},\n+ // RSS can be set, but it's not enforced because Linux doesn't enforce it\n+ // either: \"This limit has effect only in Linux 2.4.x, x < 30\"\n+ limits.Rss: {},\n// These are not enforced, but we include them here to avoid returning\n// EPERM, since some apps expect them to succeed.\nlimits.Core: {},\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow RLIMIT_RSS to be set
Closes #4746
PiperOrigin-RevId: 342747165 |
259,885 | 16.11.2020 18:52:20 | 28,800 | 267560d159b299a17f626029d7091ab923afeef6 | Reset watchdog timer between sendfile() iterations.
As part of this, change Task.interrupted() to not drain Task.interruptChan, and
do so explicitly using new function Task.unsetInterrupted() instead. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_block.go",
"new_path": "pkg/sentry/kernel/task_block.go",
"diff": "@@ -177,19 +177,23 @@ func (t *Task) SleepStart() <-chan struct{} {\n// SleepFinish implements context.ChannelSleeper.SleepFinish.\nfunc (t *Task) SleepFinish(success bool) {\nif !success {\n- // The interrupted notification is consumed only at the top-level\n- // (Run). Therefore we attempt to reset the pending notification.\n- // This will also elide our next entry back into the task, so we\n- // will process signals, state changes, etc.\n+ // Our caller received from t.interruptChan; we need to re-send to it\n+ // to ensure that t.interrupted() is still true.\nt.interruptSelf()\n}\nt.accountTaskGoroutineLeave(TaskGoroutineBlockedInterruptible)\nt.Activate()\n}\n-// Interrupted implements amutex.Sleeper.Interrupted\n+// Interrupted implements context.ChannelSleeper.Interrupted.\nfunc (t *Task) Interrupted() bool {\n- return len(t.interruptChan) != 0\n+ if t.interrupted() {\n+ return true\n+ }\n+ // Indicate that t's task goroutine is still responsive (i.e. reset the\n+ // watchdog timer).\n+ t.accountTaskGoroutineRunning()\n+ return false\n}\n// UninterruptibleSleepStart implements context.Context.UninterruptibleSleepStart.\n@@ -210,13 +214,17 @@ func (t *Task) UninterruptibleSleepFinish(activate bool) {\n}\n// interrupted returns true if interrupt or interruptSelf has been called at\n-// least once since the last call to interrupted.\n+// least once since the last call to unsetInterrupted.\nfunc (t *Task) interrupted() bool {\n+ return len(t.interruptChan) != 0\n+}\n+\n+// unsetInterrupted causes interrupted to return false until the next call to\n+// interrupt or interruptSelf.\n+func (t *Task) unsetInterrupted() {\nselect {\ncase <-t.interruptChan:\n- return true\ndefault:\n- return false\n}\n}\n@@ -232,9 +240,7 @@ func (t *Task) interrupt() {\nfunc (t *Task) interruptSelf() {\nselect {\ncase t.interruptChan <- struct{}{}:\n- t.Debugf(\"Interrupt queued\")\ndefault:\n- t.Debugf(\"Dropping duplicate interrupt\")\n}\n// platform.Context.Interrupt() is unnecessary since a task goroutine\n// calling interruptSelf() cannot also be blocked in\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_sched.go",
"new_path": "pkg/sentry/kernel/task_sched.go",
"diff": "@@ -157,6 +157,18 @@ func (t *Task) accountTaskGoroutineLeave(state TaskGoroutineState) {\nt.goschedSeq.EndWrite()\n}\n+// Preconditions: The caller must be running on the task goroutine.\n+func (t *Task) accountTaskGoroutineRunning() {\n+ now := t.k.CPUClockNow()\n+ if t.gosched.State != TaskGoroutineRunningSys {\n+ panic(fmt.Sprintf(\"Task goroutine in state %v (expected %v)\", t.gosched.State, TaskGoroutineRunningSys))\n+ }\n+ t.goschedSeq.BeginWrite()\n+ t.gosched.SysTicks += now - t.gosched.Timestamp\n+ t.gosched.Timestamp = now\n+ t.goschedSeq.EndWrite()\n+}\n+\n// TaskGoroutineSchedInfo returns a copy of t's task goroutine scheduling info.\n// Most clients should use t.CPUStats() instead.\nfunc (t *Task) TaskGoroutineSchedInfo() TaskGoroutineSchedInfo {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_signals.go",
"new_path": "pkg/sentry/kernel/task_signals.go",
"diff": "@@ -619,9 +619,6 @@ func (t *Task) setSignalMaskLocked(mask linux.SignalSet) {\nreturn\n}\n})\n- // We have to re-issue the interrupt consumed by t.interrupted() since\n- // it might have been for a different reason.\n- t.interruptSelf()\n}\n// Conversely, if the new mask unblocks any signals that were blocked by\n@@ -931,10 +928,10 @@ func (t *Task) signalStop(target *Task, code int32, status int32) {\ntype runInterrupt struct{}\nfunc (*runInterrupt) execute(t *Task) taskRunState {\n- // Interrupts are de-duplicated (if t is interrupted twice before\n- // t.interrupted() is called, t.interrupted() will only return true once),\n- // so early exits from this function must re-enter the runInterrupt state\n- // to check for more interrupt-signaled conditions.\n+ // Interrupts are de-duplicated (t.unsetInterrupted() will undo the effect\n+ // of all previous calls to t.interrupted() regardless of how many such\n+ // calls there have been), so early exits from this function must re-enter\n+ // the runInterrupt state to check for more interrupt-signaled conditions.\nt.tg.signalHandlers.mu.Lock()\n@@ -1080,6 +1077,7 @@ func (*runInterrupt) execute(t *Task) taskRunState {\nreturn t.deliverSignal(info, act)\n}\n+ t.unsetInterrupted()\nt.tg.signalHandlers.mu.Unlock()\nreturn (*runApp)(nil)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/splice.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/splice.go",
"diff": "@@ -343,7 +343,7 @@ func Sendfile(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\n// Copy data.\nvar (\n- n int64\n+ total int64\nerr error\n)\ndw := dualWaiter{\n@@ -357,13 +357,20 @@ func Sendfile(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\n// can block.\nnonBlock := outFile.StatusFlags()&linux.O_NONBLOCK != 0\nif outIsPipe {\n- for n < count {\n- var spliceN int64\n- spliceN, err = outPipeFD.SpliceFromNonPipe(t, inFile, offset, count)\n+ for {\n+ var n int64\n+ n, err = outPipeFD.SpliceFromNonPipe(t, inFile, offset, count-total)\nif offset != -1 {\n- offset += spliceN\n+ offset += n\n+ }\n+ total += n\n+ if total == count {\n+ break\n+ }\n+ if err == nil && t.Interrupted() {\n+ err = syserror.ErrInterrupted\n+ break\n}\n- n += spliceN\nif err == syserror.ErrWouldBlock && !nonBlock {\nerr = dw.waitForBoth(t)\n}\n@@ -374,7 +381,7 @@ func Sendfile(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\n} else {\n// Read inFile to buffer, then write the contents to outFile.\nbuf := make([]byte, count)\n- for n < count {\n+ for {\nvar readN int64\nif offset != -1 {\nreadN, err = inFile.PRead(t, usermem.BytesIOSequence(buf), offset, vfs.ReadOptions{})\n@@ -382,7 +389,6 @@ func Sendfile(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\n} else {\nreadN, err = inFile.Read(t, usermem.BytesIOSequence(buf), vfs.ReadOptions{})\n}\n- n += readN\n// Write all of the bytes that we read. This may need\n// multiple write calls to complete.\n@@ -398,7 +404,7 @@ func Sendfile(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\n// We didn't complete the write. Only report the bytes that were actually\n// written, and rewind offsets as needed.\nnotWritten := int64(len(wbuf))\n- n -= notWritten\n+ readN -= notWritten\nif offset == -1 {\n// We modified the offset of the input file itself during the read\n// operation. Rewind it.\n@@ -415,6 +421,16 @@ func Sendfile(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\nbreak\n}\n}\n+\n+ total += readN\n+ buf = buf[readN:]\n+ if total == count {\n+ break\n+ }\n+ if err == nil && t.Interrupted() {\n+ err = syserror.ErrInterrupted\n+ break\n+ }\nif err == syserror.ErrWouldBlock && !nonBlock {\nerr = dw.waitForBoth(t)\n}\n@@ -432,7 +448,7 @@ func Sendfile(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\n}\n}\n- if n != 0 {\n+ if total != 0 {\ninFile.Dentry().InotifyWithParent(t, linux.IN_ACCESS, 0, vfs.PathEvent)\noutFile.Dentry().InotifyWithParent(t, linux.IN_MODIFY, 0, vfs.PathEvent)\n@@ -445,7 +461,7 @@ func Sendfile(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\n// We can only pass a single file to handleIOError, so pick inFile arbitrarily.\n// This is used only for debugging purposes.\n- return uintptr(n), nil, slinux.HandleIOErrorVFS2(t, n != 0, err, syserror.ERESTARTSYS, \"sendfile\", inFile)\n+ return uintptr(total), nil, slinux.HandleIOErrorVFS2(t, total != 0, err, syserror.ERESTARTSYS, \"sendfile\", inFile)\n}\n// dualWaiter is used to wait on one or both vfs.FileDescriptions. It is not\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/sendfile.cc",
"new_path": "test/syscalls/linux/sendfile.cc",
"diff": "@@ -631,6 +631,24 @@ TEST(SendFileTest, SendFileToPipe) {\nSyscallSucceedsWithValue(kDataSize));\n}\n+TEST(SendFileTest, SendFileToSelf_NoRandomSave) {\n+ int rawfd;\n+ ASSERT_THAT(rawfd = memfd_create(\"memfd\", 0), SyscallSucceeds());\n+ const FileDescriptor fd(rawfd);\n+\n+ char c = 0x01;\n+ ASSERT_THAT(WriteFd(fd.get(), &c, 1), SyscallSucceedsWithValue(1));\n+\n+ // Arbitrarily chosen to make sendfile() take long enough that the sentry\n+ // watchdog usually fires unless it's reset by sendfile() between iterations\n+ // of the buffered copy. See b/172076632.\n+ constexpr size_t kSendfileSize = 0xa00000;\n+\n+ off_t offset = 0;\n+ ASSERT_THAT(sendfile(fd.get(), fd.get(), &offset, kSendfileSize),\n+ SyscallSucceedsWithValue(kSendfileSize));\n+}\n+\nstatic volatile int signaled = 0;\nvoid SigUsr1Handler(int sig, siginfo_t* info, void* context) { signaled = 1; }\n"
}
] | Go | Apache License 2.0 | google/gvisor | Reset watchdog timer between sendfile() iterations.
As part of this, change Task.interrupted() to not drain Task.interruptChan, and
do so explicitly using new function Task.unsetInterrupted() instead.
PiperOrigin-RevId: 342768365 |
259,885 | 16.11.2020 18:53:32 | 28,800 | 938aabeecb935771ab5be5eca5acff0bd19ebc97 | Minor flipcall refactoring. | [
{
"change_type": "MODIFY",
"old_path": "pkg/flipcall/ctrl_futex.go",
"new_path": "pkg/flipcall/ctrl_futex.go",
"diff": "@@ -40,71 +40,104 @@ func (ep *Endpoint) ctrlInit(opts ...EndpointOption) error {\nreturn nil\n}\n-type ctrlHandshakeRequest struct{}\n-\n-type ctrlHandshakeResponse struct{}\n-\nfunc (ep *Endpoint) ctrlConnect() error {\nif err := ep.enterFutexWait(); err != nil {\nreturn err\n}\n- _, err := ep.futexConnect(&ctrlHandshakeRequest{})\n- ep.exitFutexWait()\n+ defer ep.exitFutexWait()\n+\n+ // Write the connection request.\n+ w := ep.NewWriter()\n+ if err := json.NewEncoder(w).Encode(struct{}{}); err != nil {\n+ return fmt.Errorf(\"error writing connection request: %v\", err)\n+ }\n+ *ep.dataLen() = w.Len()\n+\n+ // Exchange control with the server.\n+ if err := ep.futexSetPeerActive(); err != nil {\n+ return err\n+ }\n+ if err := ep.futexWakePeer(); err != nil {\n+ return err\n+ }\n+ if err := ep.futexWaitUntilActive(); err != nil {\nreturn err\n}\n+ // Read the connection response.\n+ var resp struct{}\n+ respLen := atomic.LoadUint32(ep.dataLen())\n+ if respLen > ep.dataCap {\n+ return fmt.Errorf(\"invalid connection response length %d (maximum %d)\", respLen, ep.dataCap)\n+ }\n+ if err := json.NewDecoder(ep.NewReader(respLen)).Decode(&resp); err != nil {\n+ return fmt.Errorf(\"error reading connection response: %v\", err)\n+ }\n+\n+ return nil\n+}\n+\nfunc (ep *Endpoint) ctrlWaitFirst() error {\nif err := ep.enterFutexWait(); err != nil {\nreturn err\n}\ndefer ep.exitFutexWait()\n- // Wait for the handshake request.\n- if err := ep.futexSwitchFromPeer(); err != nil {\n+ // Wait for the connection request.\n+ if err := ep.futexWaitUntilActive(); err != nil {\nreturn err\n}\n- // Read the handshake request.\n+ // Read the connection request.\nreqLen := atomic.LoadUint32(ep.dataLen())\nif reqLen > ep.dataCap {\n- return fmt.Errorf(\"invalid handshake request length %d (maximum %d)\", reqLen, ep.dataCap)\n+ return fmt.Errorf(\"invalid connection request length %d (maximum %d)\", reqLen, ep.dataCap)\n}\n- var req ctrlHandshakeRequest\n+ var req struct{}\nif err := json.NewDecoder(ep.NewReader(reqLen)).Decode(&req); err != nil {\n- return fmt.Errorf(\"error reading handshake request: %v\", err)\n+ return fmt.Errorf(\"error reading connection request: %v\", err)\n}\n- // Write the handshake response.\n+ // Write the connection response.\nw := ep.NewWriter()\n- if err := json.NewEncoder(w).Encode(ctrlHandshakeResponse{}); err != nil {\n- return fmt.Errorf(\"error writing handshake response: %v\", err)\n+ if err := json.NewEncoder(w).Encode(struct{}{}); err != nil {\n+ return fmt.Errorf(\"error writing connection response: %v\", err)\n}\n*ep.dataLen() = w.Len()\n// Return control to the client.\nraceBecomeInactive()\n- if err := ep.futexSwitchToPeer(); err != nil {\n+ if err := ep.futexSetPeerActive(); err != nil {\n+ return err\n+ }\n+ if err := ep.futexWakePeer(); err != nil {\nreturn err\n}\n- // Wait for the first non-handshake message.\n- return ep.futexSwitchFromPeer()\n+ // Wait for the first non-connection message.\n+ return ep.futexWaitUntilActive()\n}\nfunc (ep *Endpoint) ctrlRoundTrip() error {\n- if err := ep.futexSwitchToPeer(); err != nil {\n+ if err := ep.enterFutexWait(); err != nil {\nreturn err\n}\n- if err := ep.enterFutexWait(); err != nil {\n+ defer ep.exitFutexWait()\n+\n+ if err := ep.futexSetPeerActive(); err != nil {\nreturn err\n}\n- err := ep.futexSwitchFromPeer()\n- ep.exitFutexWait()\n+ if err := ep.futexWakePeer(); err != nil {\nreturn err\n}\n+ return ep.futexWaitUntilActive()\n+}\nfunc (ep *Endpoint) ctrlWakeLast() error {\n- return ep.futexSwitchToPeer()\n+ if err := ep.futexSetPeerActive(); err != nil {\n+ return err\n+ }\n+ return ep.futexWakePeer()\n}\nfunc (ep *Endpoint) enterFutexWait() error {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/flipcall/flipcall_unsafe.go",
"new_path": "pkg/flipcall/flipcall_unsafe.go",
"diff": "@@ -41,11 +41,11 @@ const (\n)\nfunc (ep *Endpoint) connState() *uint32 {\n- return (*uint32)((unsafe.Pointer)(ep.packet))\n+ return (*uint32)(unsafe.Pointer(ep.packet))\n}\nfunc (ep *Endpoint) dataLen() *uint32 {\n- return (*uint32)((unsafe.Pointer)(ep.packet + 4))\n+ return (*uint32)(unsafe.Pointer(ep.packet + 4))\n}\n// Data returns the datagram part of ep's packet window as a byte slice.\n@@ -63,7 +63,7 @@ func (ep *Endpoint) dataLen() *uint32 {\n// all.\nfunc (ep *Endpoint) Data() []byte {\nvar bs []byte\n- bsReflect := (*reflect.SliceHeader)((unsafe.Pointer)(&bs))\n+ bsReflect := (*reflect.SliceHeader)(unsafe.Pointer(&bs))\nbsReflect.Data = ep.packet + PacketHeaderBytes\nbsReflect.Len = int(ep.dataCap)\nbsReflect.Cap = int(ep.dataCap)\n@@ -76,12 +76,12 @@ var ioSync int64\nfunc raceBecomeActive() {\nif sync.RaceEnabled {\n- sync.RaceAcquire((unsafe.Pointer)(&ioSync))\n+ sync.RaceAcquire(unsafe.Pointer(&ioSync))\n}\n}\nfunc raceBecomeInactive() {\nif sync.RaceEnabled {\n- sync.RaceReleaseMerge((unsafe.Pointer)(&ioSync))\n+ sync.RaceReleaseMerge(unsafe.Pointer(&ioSync))\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/flipcall/futex_linux.go",
"new_path": "pkg/flipcall/futex_linux.go",
"diff": "package flipcall\nimport (\n- \"encoding/json\"\n\"fmt\"\n\"runtime\"\n\"sync/atomic\"\n@@ -26,39 +25,10 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n)\n-func (ep *Endpoint) futexConnect(req *ctrlHandshakeRequest) (ctrlHandshakeResponse, error) {\n- var resp ctrlHandshakeResponse\n-\n- // Write the handshake request.\n- w := ep.NewWriter()\n- if err := json.NewEncoder(w).Encode(req); err != nil {\n- return resp, fmt.Errorf(\"error writing handshake request: %v\", err)\n- }\n- *ep.dataLen() = w.Len()\n-\n- // Exchange control with the server.\n- if err := ep.futexSwitchToPeer(); err != nil {\n- return resp, err\n- }\n- if err := ep.futexSwitchFromPeer(); err != nil {\n- return resp, err\n- }\n-\n- // Read the handshake response.\n- respLen := atomic.LoadUint32(ep.dataLen())\n- if respLen > ep.dataCap {\n- return resp, fmt.Errorf(\"invalid handshake response length %d (maximum %d)\", respLen, ep.dataCap)\n- }\n- if err := json.NewDecoder(ep.NewReader(respLen)).Decode(&resp); err != nil {\n- return resp, fmt.Errorf(\"error reading handshake response: %v\", err)\n- }\n-\n- return resp, nil\n+func (ep *Endpoint) futexSetPeerActive() error {\n+ if atomic.CompareAndSwapUint32(ep.connState(), ep.activeState, ep.inactiveState) {\n+ return nil\n}\n-\n-func (ep *Endpoint) futexSwitchToPeer() error {\n- // Update connection state to indicate that the peer should be active.\n- if !atomic.CompareAndSwapUint32(ep.connState(), ep.activeState, ep.inactiveState) {\nswitch cs := atomic.LoadUint32(ep.connState()); cs {\ncase csShutdown:\nreturn ShutdownError{}\n@@ -67,14 +37,14 @@ func (ep *Endpoint) futexSwitchToPeer() error {\n}\n}\n- // Wake the peer's Endpoint.futexSwitchFromPeer().\n+func (ep *Endpoint) futexWakePeer() error {\nif err := ep.futexWakeConnState(1); err != nil {\nreturn fmt.Errorf(\"failed to FUTEX_WAKE peer Endpoint: %v\", err)\n}\nreturn nil\n}\n-func (ep *Endpoint) futexSwitchFromPeer() error {\n+func (ep *Endpoint) futexWaitUntilActive() error {\nfor {\nswitch cs := atomic.LoadUint32(ep.connState()); cs {\ncase ep.activeState:\n"
}
] | Go | Apache License 2.0 | google/gvisor | Minor flipcall refactoring.
PiperOrigin-RevId: 342768550 |
260,019 | 17.11.2020 14:53:50 | -28,800 | 170b5842225176d3fa981e7d8628c1dda4a4f504 | arm64 kvm: add the processing functions for all el0/el1 exceptions
I added 2 unified processing functions for all exceptions of el/el0 | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine_arm64_unsafe.go",
"new_path": "pkg/sentry/platform/kvm/machine_arm64_unsafe.go",
"diff": "@@ -263,13 +263,6 @@ func (c *vCPU) SwitchToUser(switchOpts ring0.SwitchOpts, info *arch.SignalInfo)\nreturn usermem.NoAccess, platform.ErrContextInterrupt\ncase ring0.El0SyncUndef:\nreturn c.fault(int32(syscall.SIGILL), info)\n- case ring0.El1SyncUndef:\n- *info = arch.SignalInfo{\n- Signo: int32(syscall.SIGILL),\n- Code: 1, // ILL_ILLOPC (illegal opcode).\n- }\n- info.SetAddr(switchOpts.Registers.Pc) // Include address.\n- return usermem.AccessType{}, platform.ErrContextSignal\ndefault:\npanic(fmt.Sprintf(\"unexpected vector: 0x%x\", vector))\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/aarch64.go",
"new_path": "pkg/sentry/platform/ring0/aarch64.go",
"diff": "@@ -90,6 +90,7 @@ const (\nEl0SyncIa\nEl0SyncFpsimdAcc\nEl0SyncSveAcc\n+ El0SyncFpsimdExc\nEl0SyncSys\nEl0SyncSpPc\nEl0SyncUndef\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/kernel_arm64.go",
"new_path": "pkg/sentry/platform/ring0/kernel_arm64.go",
"diff": "@@ -24,6 +24,10 @@ func HaltAndResume()\n//go:nosplit\nfunc HaltEl1SvcAndResume()\n+// HaltEl1ExceptionAndResume calls Hooks.KernelException and resume.\n+//go:nosplit\n+func HaltEl1ExceptionAndResume()\n+\n// init initializes architecture-specific state.\nfunc (k *Kernel) init(maxCPUs int) {\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/offsets_arm64.go",
"new_path": "pkg/sentry/platform/ring0/offsets_arm64.go",
"diff": "@@ -70,6 +70,7 @@ func Emit(w io.Writer) {\nfmt.Fprintf(w, \"#define El0SyncIa 0x%02x\\n\", El0SyncIa)\nfmt.Fprintf(w, \"#define El0SyncFpsimdAcc 0x%02x\\n\", El0SyncFpsimdAcc)\nfmt.Fprintf(w, \"#define El0SyncSveAcc 0x%02x\\n\", El0SyncSveAcc)\n+ fmt.Fprintf(w, \"#define El0SyncFpsimdExc 0x%02x\\n\", El0SyncFpsimdExc)\nfmt.Fprintf(w, \"#define El0SyncSys 0x%02x\\n\", El0SyncSys)\nfmt.Fprintf(w, \"#define El0SyncSpPc 0x%02x\\n\", El0SyncSpPc)\nfmt.Fprintf(w, \"#define El0SyncUndef 0x%02x\\n\", El0SyncUndef)\n"
}
] | Go | Apache License 2.0 | google/gvisor | arm64 kvm: add the processing functions for all el0/el1 exceptions
I added 2 unified processing functions for all exceptions of el/el0
Signed-off-by: Robin Luk <[email protected]> |
260,019 | 17.11.2020 16:05:12 | -28,800 | 05d5e3cb2baaa9c91397b802c0cace45384b91fc | arm64 kvm: optimize all fpsimd related code
Optimize and bug fix all fpsimd related code. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/kernel_arm64.go",
"new_path": "pkg/sentry/platform/ring0/kernel_arm64.go",
"diff": "@@ -61,11 +61,13 @@ func (c *CPU) SwitchToUser(switchOpts SwitchOpts) (vector Vector) {\nregs.Pstate &= ^uint64(PsrFlagsClear)\nregs.Pstate |= UserFlagsSet\n+ EnableVFP()\nLoadFloatingPoint(switchOpts.FloatingPointState)\nkernelExitToEl0()\nSaveFloatingPoint(switchOpts.FloatingPointState)\n+ DisableVFP()\nvector = c.vecCode\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ring0/lib_arm64.go",
"new_path": "pkg/sentry/platform/ring0/lib_arm64.go",
"diff": "@@ -53,6 +53,12 @@ func LoadFloatingPoint(*byte)\n// SaveFloatingPoint saves floating point state.\nfunc SaveFloatingPoint(*byte)\n+// EnableVFP enables fpsimd.\n+func EnableVFP()\n+\n+// DisableVFP disables fpsimd.\n+func DisableVFP()\n+\n// Init sets function pointers based on architectural features.\n//\n// This must be called prior to using ring0.\n"
}
] | Go | Apache License 2.0 | google/gvisor | arm64 kvm: optimize all fpsimd related code
Optimize and bug fix all fpsimd related code.
Signed-off-by: Robin Luk <[email protected]> |
260,001 | 17.11.2020 14:26:52 | 28,800 | 2d89f234029d9e020bc12b78c29ce1abd58fb4c7 | Add consistent precondition formatting for verity
Also add the lock order for verity fs, and add a lock to protect dentry
hash. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/verity/filesystem.go",
"new_path": "pkg/sentry/fsimpl/verity/filesystem.go",
"diff": "@@ -107,8 +107,10 @@ func (fs *filesystem) renameMuUnlockAndCheckDrop(ctx context.Context, ds **[]*de\n// Dentries which may have a reference count of zero, and which therefore\n// should be dropped once traversal is complete, are appended to ds.\n//\n-// Preconditions: fs.renameMu must be locked. d.dirMu must be locked.\n-// !rp.Done().\n+// Preconditions:\n+// * fs.renameMu must be locked.\n+// * d.dirMu must be locked.\n+// * !rp.Done().\nfunc (fs *filesystem) stepLocked(ctx context.Context, rp *vfs.ResolvingPath, d *dentry, mayFollowSymlinks bool, ds **[]*dentry) (*dentry, error) {\nif !d.isDir() {\nreturn nil, syserror.ENOTDIR\n@@ -158,15 +160,19 @@ afterSymlink:\nreturn child, nil\n}\n-// verifyChild verifies the hash of child against the already verified hash of\n-// the parent to ensure the child is expected. verifyChild triggers a sentry\n-// panic if unexpected modifications to the file system are detected. In\n+// verifyChildLocked verifies the hash of child against the already verified\n+// hash of the parent to ensure the child is expected. verifyChild triggers a\n+// sentry panic if unexpected modifications to the file system are detected. In\n// noCrashOnVerificationFailure mode it returns a syserror instead.\n-// Preconditions: fs.renameMu must be locked. d.dirMu must be locked.\n+//\n+// Preconditions:\n+// * fs.renameMu must be locked.\n+// * d.dirMu must be locked.\n+//\n// TODO(b/166474175): Investigate all possible errors returned in this\n// function, and make sure we differentiate all errors that indicate unexpected\n// modifications to the file system from the ones that are not harmful.\n-func (fs *filesystem) verifyChild(ctx context.Context, parent *dentry, child *dentry) (*dentry, error) {\n+func (fs *filesystem) verifyChildLocked(ctx context.Context, parent *dentry, child *dentry) (*dentry, error) {\nvfsObj := fs.vfsfs.VirtualFilesystem()\n// Get the path to the child dentry. This is only used to provide path\n@@ -268,7 +274,8 @@ func (fs *filesystem) verifyChild(ctx context.Context, parent *dentry, child *de\n// contain the hash of the children in the parent Merkle tree when\n// Verify returns with success.\nvar buf bytes.Buffer\n- if _, err := merkletree.Verify(&merkletree.VerifyParams{\n+ parent.hashMu.RLock()\n+ _, err = merkletree.Verify(&merkletree.VerifyParams{\nOut: &buf,\nFile: &fdReader,\nTree: &fdReader,\n@@ -284,21 +291,27 @@ func (fs *filesystem) verifyChild(ctx context.Context, parent *dentry, child *de\nReadSize: int64(merkletree.DigestSize(fs.alg.toLinuxHashAlg())),\nExpected: parent.hash,\nDataAndTreeInSameFile: true,\n- }); err != nil && err != io.EOF {\n+ })\n+ parent.hashMu.RUnlock()\n+ if err != nil && err != io.EOF {\nreturn nil, alertIntegrityViolation(fmt.Sprintf(\"Verification for %s failed: %v\", childPath, err))\n}\n// Cache child hash when it's verified the first time.\n+ child.hashMu.Lock()\nif len(child.hash) == 0 {\nchild.hash = buf.Bytes()\n}\n+ child.hashMu.Unlock()\nreturn child, nil\n}\n-// verifyStatAndChildren verifies the stat and children names against the\n+// verifyStatAndChildrenLocked verifies the stat and children names against the\n// verified hash. The mode/uid/gid and childrenNames of the file is cached\n// after verified.\n-func (fs *filesystem) verifyStatAndChildren(ctx context.Context, d *dentry, stat linux.Statx) error {\n+//\n+// Preconditions: d.dirMu must be locked.\n+func (fs *filesystem) verifyStatAndChildrenLocked(ctx context.Context, d *dentry, stat linux.Statx) error {\nvfsObj := fs.vfsfs.VirtualFilesystem()\n// Get the path to the child dentry. This is only used to provide path\n@@ -390,6 +403,7 @@ func (fs *filesystem) verifyStatAndChildren(ctx context.Context, d *dentry, stat\n}\nvar buf bytes.Buffer\n+ d.hashMu.RLock()\nparams := &merkletree.VerifyParams{\nOut: &buf,\nTree: &fdReader,\n@@ -407,6 +421,7 @@ func (fs *filesystem) verifyStatAndChildren(ctx context.Context, d *dentry, stat\nExpected: d.hash,\nDataAndTreeInSameFile: false,\n}\n+ d.hashMu.RUnlock()\nif atomic.LoadUint32(&d.mode)&linux.S_IFMT == linux.S_IFDIR {\nparams.DataAndTreeInSameFile = true\n}\n@@ -421,7 +436,9 @@ func (fs *filesystem) verifyStatAndChildren(ctx context.Context, d *dentry, stat\nreturn nil\n}\n-// Preconditions: fs.renameMu must be locked. d.dirMu must be locked.\n+// Preconditions:\n+// * fs.renameMu must be locked.\n+// * parent.dirMu must be locked.\nfunc (fs *filesystem) getChildLocked(ctx context.Context, parent *dentry, name string, ds **[]*dentry) (*dentry, error) {\nif child, ok := parent.children[name]; ok {\n// If verity is enabled on child, we should check again whether\n@@ -470,7 +487,7 @@ func (fs *filesystem) getChildLocked(ctx context.Context, parent *dentry, name s\n// be cached before enabled.\nif fs.allowRuntimeEnable {\nif parent.verityEnabled() {\n- if _, err := fs.verifyChild(ctx, parent, child); err != nil {\n+ if _, err := fs.verifyChildLocked(ctx, parent, child); err != nil {\nreturn nil, err\n}\n}\n@@ -486,7 +503,7 @@ func (fs *filesystem) getChildLocked(ctx context.Context, parent *dentry, name s\nif err != nil {\nreturn nil, err\n}\n- if err := fs.verifyStatAndChildren(ctx, child, stat); err != nil {\n+ if err := fs.verifyStatAndChildrenLocked(ctx, child, stat); err != nil {\nreturn nil, err\n}\n}\n@@ -506,7 +523,9 @@ func (fs *filesystem) getChildLocked(ctx context.Context, parent *dentry, name s\nreturn child, nil\n}\n-// Preconditions: fs.renameMu must be locked. parent.dirMu must be locked.\n+// Preconditions:\n+// * fs.renameMu must be locked.\n+// * parent.dirMu must be locked.\nfunc (fs *filesystem) lookupAndVerifyLocked(ctx context.Context, parent *dentry, name string) (*dentry, error) {\nvfsObj := fs.vfsfs.VirtualFilesystem()\n@@ -597,13 +616,13 @@ func (fs *filesystem) lookupAndVerifyLocked(ctx context.Context, parent *dentry,\n// allowRuntimeEnable mode and the parent directory hasn't been enabled\n// yet.\nif parent.verityEnabled() {\n- if _, err := fs.verifyChild(ctx, parent, child); err != nil {\n+ if _, err := fs.verifyChildLocked(ctx, parent, child); err != nil {\nchild.destroyLocked(ctx)\nreturn nil, err\n}\n}\nif child.verityEnabled() {\n- if err := fs.verifyStatAndChildren(ctx, child, stat); err != nil {\n+ if err := fs.verifyStatAndChildrenLocked(ctx, child, stat); err != nil {\nchild.destroyLocked(ctx)\nreturn nil, err\n}\n@@ -617,7 +636,9 @@ func (fs *filesystem) lookupAndVerifyLocked(ctx context.Context, parent *dentry,\n// rp.Start().Impl().(*dentry)). It does not check that the returned directory\n// is searchable by the provider of rp.\n//\n-// Preconditions: fs.renameMu must be locked. !rp.Done().\n+// Preconditions:\n+// * fs.renameMu must be locked.\n+// * !rp.Done().\nfunc (fs *filesystem) walkParentDirLocked(ctx context.Context, rp *vfs.ResolvingPath, d *dentry, ds **[]*dentry) (*dentry, error) {\nfor !rp.Final() {\nd.dirMu.Lock()\n@@ -958,11 +979,13 @@ func (fs *filesystem) StatAt(ctx context.Context, rp *vfs.ResolvingPath, opts vf\nif err != nil {\nreturn linux.Statx{}, err\n}\n+ d.dirMu.Lock()\nif d.verityEnabled() {\n- if err := fs.verifyStatAndChildren(ctx, d, stat); err != nil {\n+ if err := fs.verifyStatAndChildrenLocked(ctx, d, stat); err != nil {\nreturn linux.Statx{}, err\n}\n}\n+ d.dirMu.Unlock()\nreturn stat, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/verity/verity.go",
"new_path": "pkg/sentry/fsimpl/verity/verity.go",
"diff": "// The verity file system is read-only, except for one case: when\n// allowRuntimeEnable is true, additional Merkle files can be generated using\n// the FS_IOC_ENABLE_VERITY ioctl.\n+//\n+// Lock order:\n+//\n+// filesystem.renameMu\n+// dentry.dirMu\n+// fileDescription.mu\n+// filesystem.verityMu\n+// dentry.hashMu\n+//\n+// Locking dentry.dirMu in multiple dentries requires that parent dentries are\n+// locked before child dentries, and that filesystem.renameMu is locked to\n+// stabilize this relationship.\npackage verity\nimport (\n@@ -372,12 +384,14 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nreturn nil, nil, alertIntegrityViolation(fmt.Sprintf(\"Failed to deserialize childrenNames: %v\", err))\n}\n- if err := fs.verifyStatAndChildren(ctx, d, stat); err != nil {\n+ if err := fs.verifyStatAndChildrenLocked(ctx, d, stat); err != nil {\nreturn nil, nil, err\n}\n}\n+ d.hashMu.Lock()\ncopy(d.hash, iopts.RootHash)\n+ d.hashMu.Unlock()\nd.vfsd.Init(d)\nfs.rootDentry = d\n@@ -402,7 +416,8 @@ type dentry struct {\nfs *filesystem\n// mode, uid, gid and size are the file mode, owner, group, and size of\n- // the file in the underlying file system.\n+ // the file in the underlying file system. They are set when a dentry\n+ // is initialized, and never modified.\nmode uint32\nuid uint32\ngid uint32\n@@ -425,17 +440,21 @@ type dentry struct {\n// childrenNames stores the name of all children of the dentry. This is\n// used by verity to check whether a child is expected. This is only\n- // populated by enableVerity.\n+ // populated by enableVerity. childrenNames is also protected by dirMu.\nchildrenNames map[string]struct{}\n- // lowerVD is the VirtualDentry in the underlying file system.\n+ // lowerVD is the VirtualDentry in the underlying file system. It is\n+ // never modified after initialized.\nlowerVD vfs.VirtualDentry\n// lowerMerkleVD is the VirtualDentry of the corresponding Merkle tree\n- // in the underlying file system.\n+ // in the underlying file system. It is never modified after\n+ // initialized.\nlowerMerkleVD vfs.VirtualDentry\n- // hash is the calculated hash for the current file or directory.\n+ // hash is the calculated hash for the current file or directory. hash\n+ // is protected by hashMu.\n+ hashMu sync.RWMutex `state:\"nosave\"`\nhash []byte\n}\n@@ -519,7 +538,9 @@ func (d *dentry) checkDropLocked(ctx context.Context) {\n// destroyLocked destroys the dentry.\n//\n-// Preconditions: d.fs.renameMu must be locked for writing. d.refs == 0.\n+// Preconditions:\n+// * d.fs.renameMu must be locked for writing.\n+// * d.refs == 0.\nfunc (d *dentry) destroyLocked(ctx context.Context) {\nswitch atomic.LoadInt64(&d.refs) {\ncase 0:\n@@ -599,6 +620,8 @@ func (d *dentry) checkPermissions(creds *auth.Credentials, ats vfs.AccessTypes)\n// mode, it returns true if the target has been enabled with\n// ioctl(FS_IOC_ENABLE_VERITY).\nfunc (d *dentry) verityEnabled() bool {\n+ d.hashMu.RLock()\n+ defer d.hashMu.RUnlock()\nreturn !d.fs.allowRuntimeEnable || len(d.hash) != 0\n}\n@@ -678,11 +701,13 @@ func (fd *fileDescription) Stat(ctx context.Context, opts vfs.StatOptions) (linu\nif err != nil {\nreturn linux.Statx{}, err\n}\n+ fd.d.dirMu.Lock()\nif fd.d.verityEnabled() {\n- if err := fd.d.fs.verifyStatAndChildren(ctx, fd.d, stat); err != nil {\n+ if err := fd.d.fs.verifyStatAndChildrenLocked(ctx, fd.d, stat); err != nil {\nreturn linux.Statx{}, err\n}\n}\n+ fd.d.dirMu.Unlock()\nreturn stat, nil\n}\n@@ -718,13 +743,15 @@ func (fd *fileDescription) Seek(ctx context.Context, offset int64, whence int32)\nreturn offset, nil\n}\n-// generateMerkle generates a Merkle tree file for fd. If fd points to a file\n-// /foo/bar, a Merkle tree file /foo/.merkle.verity.bar is generated. The hash\n-// of the generated Merkle tree and the data size is returned. If fd points to\n-// a regular file, the data is the content of the file. If fd points to a\n-// directory, the data is all hahes of its children, written to the Merkle tree\n-// file.\n-func (fd *fileDescription) generateMerkle(ctx context.Context) ([]byte, uint64, error) {\n+// generateMerkleLocked generates a Merkle tree file for fd. If fd points to a\n+// file /foo/bar, a Merkle tree file /foo/.merkle.verity.bar is generated. The\n+// hash of the generated Merkle tree and the data size is returned. If fd\n+// points to a regular file, the data is the content of the file. If fd points\n+// to a directory, the data is all hahes of its children, written to the Merkle\n+// tree file.\n+//\n+// Preconditions: fd.d.fs.verityMu must be locked.\n+func (fd *fileDescription) generateMerkleLocked(ctx context.Context) ([]byte, uint64, error) {\nfdReader := vfs.FileReadWriteSeeker{\nFD: fd.lowerFD,\nCtx: ctx,\n@@ -793,11 +820,14 @@ func (fd *fileDescription) generateMerkle(ctx context.Context) ([]byte, uint64,\nreturn hash, uint64(params.Size), err\n}\n-// recordChildren writes the names of fd's children into the corresponding\n-// Merkle tree file, and saves the offset/size of the map into xattrs.\n+// recordChildrenLocked writes the names of fd's children into the\n+// corresponding Merkle tree file, and saves the offset/size of the map into\n+// xattrs.\n//\n-// Preconditions: fd.d.isDir() == true\n-func (fd *fileDescription) recordChildren(ctx context.Context) error {\n+// Preconditions:\n+// * fd.d.fs.verityMu must be locked.\n+// * fd.d.isDir() == true.\n+func (fd *fileDescription) recordChildrenLocked(ctx context.Context) error {\n// Record the children names in the Merkle tree file.\nchildrenNames, err := json.Marshal(fd.d.childrenNames)\nif err != nil {\n@@ -847,7 +877,7 @@ func (fd *fileDescription) enableVerity(ctx context.Context) (uintptr, error) {\nreturn 0, alertIntegrityViolation(\"Unexpected verity fd: missing expected underlying fds\")\n}\n- hash, dataSize, err := fd.generateMerkle(ctx)\n+ hash, dataSize, err := fd.generateMerkleLocked(ctx)\nif err != nil {\nreturn 0, err\n}\n@@ -888,11 +918,13 @@ func (fd *fileDescription) enableVerity(ctx context.Context) (uintptr, error) {\n}\nif fd.d.isDir() {\n- if err := fd.recordChildren(ctx); err != nil {\n+ if err := fd.recordChildrenLocked(ctx); err != nil {\nreturn 0, err\n}\n}\n- fd.d.hash = append(fd.d.hash, hash...)\n+ fd.d.hashMu.Lock()\n+ fd.d.hash = hash\n+ fd.d.hashMu.Unlock()\nreturn 0, nil\n}\n@@ -904,6 +936,9 @@ func (fd *fileDescription) measureVerity(ctx context.Context, verityDigest userm\n}\nvar metadata linux.DigestMetadata\n+ fd.d.hashMu.RLock()\n+ defer fd.d.hashMu.RUnlock()\n+\n// If allowRuntimeEnable is true, an empty fd.d.hash indicates that\n// verity is not enabled for the file. If allowRuntimeEnable is false,\n// this is an integrity violation because all files should have verity\n@@ -940,11 +975,13 @@ func (fd *fileDescription) measureVerity(ctx context.Context, verityDigest userm\nfunc (fd *fileDescription) verityFlags(ctx context.Context, flags usermem.Addr) (uintptr, error) {\nf := int32(0)\n+ fd.d.hashMu.RLock()\n// All enabled files should store a hash. This flag is not settable via\n// FS_IOC_SETFLAGS.\nif len(fd.d.hash) != 0 {\nf |= linux.FS_VERITY_FL\n}\n+ fd.d.hashMu.RUnlock()\nt := kernel.TaskFromContext(ctx)\nif t == nil {\n@@ -1023,6 +1060,7 @@ func (fd *fileDescription) PRead(ctx context.Context, dst usermem.IOSequence, of\nCtx: ctx,\n}\n+ fd.d.hashMu.RLock()\nn, err := merkletree.Verify(&merkletree.VerifyParams{\nOut: dst.Writer(ctx),\nFile: &dataReader,\n@@ -1040,6 +1078,7 @@ func (fd *fileDescription) PRead(ctx context.Context, dst usermem.IOSequence, of\nExpected: fd.d.hash,\nDataAndTreeInSameFile: false,\n})\n+ fd.d.hashMu.RUnlock()\nif err != nil {\nreturn 0, alertIntegrityViolation(fmt.Sprintf(\"Verification failed: %v\", err))\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add consistent precondition formatting for verity
Also add the lock order for verity fs, and add a lock to protect dentry
hash.
PiperOrigin-RevId: 342946537 |
259,927 | 17.11.2020 14:43:45 | 28,800 | 7492ed6bd63cd4f3b7c81a45b13b053b840f6d50 | Add per-sniffer instance log prefix
A prefix associated with a sniffer instance can help debug situations where
more than one NIC (i.e. more than one sniffer) exists. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/sniffer/sniffer.go",
"new_path": "pkg/tcpip/link/sniffer/sniffer.go",
"diff": "@@ -53,16 +53,35 @@ type endpoint struct {\nnested.Endpoint\nwriter io.Writer\nmaxPCAPLen uint32\n+ logPrefix string\n}\nvar _ stack.GSOEndpoint = (*endpoint)(nil)\nvar _ stack.LinkEndpoint = (*endpoint)(nil)\nvar _ stack.NetworkDispatcher = (*endpoint)(nil)\n+type direction int\n+\n+const (\n+ directionSend = iota\n+ directionRecv\n+)\n+\n// New creates a new sniffer link-layer endpoint. It wraps around another\n// endpoint and logs packets and they traverse the endpoint.\nfunc New(lower stack.LinkEndpoint) stack.LinkEndpoint {\n- sniffer := &endpoint{}\n+ return NewWithPrefix(lower, \"\")\n+}\n+\n+// NewWithPrefix creates a new sniffer link-layer endpoint. It wraps around\n+// another endpoint and logs packets prefixed with logPrefix as they traverse\n+// the endpoint.\n+//\n+// logPrefix is prepended to the log line without any separators.\n+// E.g. logPrefix = \"NIC:en0/\" will produce log lines like\n+// \"NIC:en0/send udp [...]\".\n+func NewWithPrefix(lower stack.LinkEndpoint, logPrefix string) stack.LinkEndpoint {\n+ sniffer := &endpoint{logPrefix: logPrefix}\nsniffer.Endpoint.Init(lower, sniffer)\nreturn sniffer\n}\n@@ -120,7 +139,7 @@ func NewWithWriter(lower stack.LinkEndpoint, writer io.Writer, snapLen uint32) (\n// called by the link-layer endpoint being wrapped when a packet arrives, and\n// logs the packet before forwarding to the actual dispatcher.\nfunc (e *endpoint) DeliverNetworkPacket(remote, local tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) {\n- e.dumpPacket(\"recv\", nil, protocol, pkt)\n+ e.dumpPacket(directionRecv, nil, protocol, pkt)\ne.Endpoint.DeliverNetworkPacket(remote, local, protocol, pkt)\n}\n@@ -129,10 +148,10 @@ func (e *endpoint) DeliverOutboundPacket(remote, local tcpip.LinkAddress, protoc\ne.Endpoint.DeliverOutboundPacket(remote, local, protocol, pkt)\n}\n-func (e *endpoint) dumpPacket(prefix string, gso *stack.GSO, protocol tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) {\n+func (e *endpoint) dumpPacket(dir direction, gso *stack.GSO, protocol tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) {\nwriter := e.writer\nif writer == nil && atomic.LoadUint32(&LogPackets) == 1 {\n- logPacket(prefix, protocol, pkt, gso)\n+ logPacket(e.logPrefix, dir, protocol, pkt, gso)\n}\nif writer != nil && atomic.LoadUint32(&LogPacketsToPCAP) == 1 {\ntotalLength := pkt.Size()\n@@ -169,7 +188,7 @@ func (e *endpoint) dumpPacket(prefix string, gso *stack.GSO, protocol tcpip.Netw\n// higher-level protocols to write packets; it just logs the packet and\n// forwards the request to the lower endpoint.\nfunc (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, protocol tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) *tcpip.Error {\n- e.dumpPacket(\"send\", gso, protocol, pkt)\n+ e.dumpPacket(directionSend, gso, protocol, pkt)\nreturn e.Endpoint.WritePacket(r, gso, protocol, pkt)\n}\n@@ -178,20 +197,20 @@ func (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, protocol tcpip.Ne\n// forwards the request to the lower endpoint.\nfunc (e *endpoint) WritePackets(r *stack.Route, gso *stack.GSO, pkts stack.PacketBufferList, protocol tcpip.NetworkProtocolNumber) (int, *tcpip.Error) {\nfor pkt := pkts.Front(); pkt != nil; pkt = pkt.Next() {\n- e.dumpPacket(\"send\", gso, protocol, pkt)\n+ e.dumpPacket(directionSend, gso, protocol, pkt)\n}\nreturn e.Endpoint.WritePackets(r, gso, pkts, protocol)\n}\n// WriteRawPacket implements stack.LinkEndpoint.WriteRawPacket.\nfunc (e *endpoint) WriteRawPacket(vv buffer.VectorisedView) *tcpip.Error {\n- e.dumpPacket(\"send\", nil, 0, stack.NewPacketBuffer(stack.PacketBufferOptions{\n+ e.dumpPacket(directionSend, nil, 0, stack.NewPacketBuffer(stack.PacketBufferOptions{\nData: vv,\n}))\nreturn e.Endpoint.WriteRawPacket(vv)\n}\n-func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer, gso *stack.GSO) {\n+func logPacket(prefix string, dir direction, protocol tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer, gso *stack.GSO) {\n// Figure out the network layer info.\nvar transProto uint8\nsrc := tcpip.Address(\"unknown\")\n@@ -201,6 +220,16 @@ func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, pkt *stack.P\nvar fragmentOffset uint16\nvar moreFragments bool\n+ var directionPrefix string\n+ switch dir {\n+ case directionSend:\n+ directionPrefix = \"send\"\n+ case directionRecv:\n+ directionPrefix = \"recv\"\n+ default:\n+ panic(fmt.Sprintf(\"unrecognized direction: %d\", dir))\n+ }\n+\n// Clone the packet buffer to not modify the original.\n//\n// We don't clone the original packet buffer so that the new packet buffer\n@@ -248,15 +277,16 @@ func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, pkt *stack.P\narp := header.ARP(pkt.NetworkHeader().View())\nlog.Infof(\n- \"%s arp %s (%s) -> %s (%s) valid:%t\",\n+ \"%s%s arp %s (%s) -> %s (%s) valid:%t\",\nprefix,\n+ directionPrefix,\ntcpip.Address(arp.ProtocolAddressSender()), tcpip.LinkAddress(arp.HardwareAddressSender()),\ntcpip.Address(arp.ProtocolAddressTarget()), tcpip.LinkAddress(arp.HardwareAddressTarget()),\narp.IsValid(),\n)\nreturn\ndefault:\n- log.Infof(\"%s unknown network protocol\", prefix)\n+ log.Infof(\"%s%s unknown network protocol\", prefix, directionPrefix)\nreturn\n}\n@@ -300,7 +330,7 @@ func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, pkt *stack.P\nicmpType = \"info reply\"\n}\n}\n- log.Infof(\"%s %s %s -> %s %s len:%d id:%04x code:%d\", prefix, transName, src, dst, icmpType, size, id, icmp.Code())\n+ log.Infof(\"%s%s %s %s -> %s %s len:%d id:%04x code:%d\", prefix, directionPrefix, transName, src, dst, icmpType, size, id, icmp.Code())\nreturn\ncase header.ICMPv6ProtocolNumber:\n@@ -335,7 +365,7 @@ func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, pkt *stack.P\ncase header.ICMPv6RedirectMsg:\nicmpType = \"redirect message\"\n}\n- log.Infof(\"%s %s %s -> %s %s len:%d id:%04x code:%d\", prefix, transName, src, dst, icmpType, size, id, icmp.Code())\n+ log.Infof(\"%s%s %s %s -> %s %s len:%d id:%04x code:%d\", prefix, directionPrefix, transName, src, dst, icmpType, size, id, icmp.Code())\nreturn\ncase header.UDPProtocolNumber:\n@@ -391,7 +421,7 @@ func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, pkt *stack.P\n}\ndefault:\n- log.Infof(\"%s %s -> %s unknown transport protocol: %d\", prefix, src, dst, transProto)\n+ log.Infof(\"%s%s %s -> %s unknown transport protocol: %d\", prefix, directionPrefix, src, dst, transProto)\nreturn\n}\n@@ -399,5 +429,5 @@ func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, pkt *stack.P\ndetails += fmt.Sprintf(\" gso: %+v\", gso)\n}\n- log.Infof(\"%s %s %s:%d -> %s:%d len:%d id:%04x %s\", prefix, transName, src, srcPort, dst, dstPort, size, id, details)\n+ log.Infof(\"%s%s %s %s:%d -> %s:%d len:%d id:%04x %s\", prefix, directionPrefix, transName, src, srcPort, dst, dstPort, size, id, details)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add per-sniffer instance log prefix
A prefix associated with a sniffer instance can help debug situations where
more than one NIC (i.e. more than one sniffer) exists.
PiperOrigin-RevId: 342950027 |
259,853 | 17.11.2020 14:53:06 | 28,800 | 10ba578c018294bb037a7eb90010491cdda270a7 | tmpfs: make sure that a dentry will not be destroyed before the open() call
If we don't hold a reference, the dentry can be destroyed by another thread.
Reported-by: | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go",
"diff": "@@ -381,6 +381,8 @@ afterTrailingSymlink:\ncreds := rp.Credentials()\nchild := fs.newDentry(fs.newRegularFile(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode))\nparentDir.insertChildLocked(child, name)\n+ child.IncRef()\n+ defer child.DecRef(ctx)\nunlock()\nfd, err := child.open(ctx, rp, &opts, true)\nif err != nil {\n"
}
] | Go | Apache License 2.0 | google/gvisor | tmpfs: make sure that a dentry will not be destroyed before the open() call
If we don't hold a reference, the dentry can be destroyed by another thread.
Reported-by: [email protected]
PiperOrigin-RevId: 342951940 |
259,853 | 17.11.2020 19:00:36 | 28,800 | 05223889bd74faf0f3967e58fa11e3bdf1a518d7 | fs/fuse: don't dereference fuse.DeviceFD.fs if it is nil | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/fuse/dev.go",
"new_path": "pkg/sentry/fsimpl/fuse/dev.go",
"diff": "@@ -363,7 +363,7 @@ func (fd *DeviceFD) Readiness(mask waiter.EventMask) waiter.EventMask {\nfunc (fd *DeviceFD) readinessLocked(mask waiter.EventMask) waiter.EventMask {\nvar ready waiter.EventMask\n- if fd.fs.umounted {\n+ if fd.fs == nil || fd.fs.umounted {\nready |= waiter.EventErr\nreturn ready & mask\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | fs/fuse: don't dereference fuse.DeviceFD.fs if it is nil
PiperOrigin-RevId: 342992936 |
259,962 | 17.11.2020 22:56:44 | 28,800 | 0e32d98f3a5d4f81459635efcaa53898f43996b9 | Fix endpoint.Read() when endpoint is in StateError.
If the endpoint is in StateError but e.hardErrorLocked() returns
nil then return ErrClosedForRecieve.
This can happen if a concurrent write on the same endpoint was in progress
when the endpoint transitioned to an error state. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -1330,7 +1330,10 @@ func (e *endpoint) Read(*tcpip.FullAddress) (buffer.View, tcpip.ControlMessages,\nif s := e.EndpointState(); !s.connected() && s != StateClose && bufUsed == 0 {\ne.rcvListMu.Unlock()\nif s == StateError {\n- return buffer.View{}, tcpip.ControlMessages{}, e.hardErrorLocked()\n+ if err := e.hardErrorLocked(); err != nil {\n+ return buffer.View{}, tcpip.ControlMessages{}, err\n+ }\n+ return buffer.View{}, tcpip.ControlMessages{}, tcpip.ErrClosedForReceive\n}\ne.stats.ReadErrors.NotConnected.Increment()\nreturn buffer.View{}, tcpip.ControlMessages{}, tcpip.ErrNotConnected\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix endpoint.Read() when endpoint is in StateError.
If the endpoint is in StateError but e.hardErrorLocked() returns
nil then return ErrClosedForRecieve.
This can happen if a concurrent write on the same endpoint was in progress
when the endpoint transitioned to an error state.
PiperOrigin-RevId: 343018257 |
259,962 | 17.11.2020 23:31:49 | 28,800 | a5e3fd1b29e14083cd558def8c0f7f283a33fa9e | Remove sniffer from gonet_test.
This was added by mistake in cl/342868552. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/adapters/gonet/BUILD",
"new_path": "pkg/tcpip/adapters/gonet/BUILD",
"diff": "@@ -26,7 +26,6 @@ go_test(\n\"//pkg/tcpip\",\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/link/loopback\",\n- \"//pkg/tcpip/link/sniffer\",\n\"//pkg/tcpip/network/ipv4\",\n\"//pkg/tcpip/network/ipv6\",\n\"//pkg/tcpip/stack\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/adapters/gonet/gonet_test.go",
"new_path": "pkg/tcpip/adapters/gonet/gonet_test.go",
"diff": "@@ -28,7 +28,6 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/loopback\"\n- \"gvisor.dev/gvisor/pkg/tcpip/link/sniffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv4\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv6\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n@@ -66,7 +65,7 @@ func newLoopbackStack() (*stack.Stack, *tcpip.Error) {\nTransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol, udp.NewProtocol},\n})\n- if err := s.CreateNIC(NICID, sniffer.New(loopback.New())); err != nil {\n+ if err := s.CreateNIC(NICID, loopback.New()); err != nil {\nreturn nil, err\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove sniffer from gonet_test.
This was added by mistake in cl/342868552.
PiperOrigin-RevId: 343021431 |
259,860 | 18.11.2020 09:40:59 | 28,800 | 87ed61ea055dde0a11b3394c2d2aa4db3f7db5c6 | Remove outdated nogo exception. | [
{
"change_type": "MODIFY",
"old_path": "nogo.yaml",
"new_path": "nogo.yaml",
"diff": "@@ -74,7 +74,6 @@ global:\n- pkg/pool/pool.go:15\n- pkg/refs/refcounter.go:510\n- pkg/refs/refcounter_test.go:169\n- - pkg/refs_vfs2/refs.go:16\n- pkg/safemem/block_unsafe.go:89\n- pkg/seccomp/seccomp.go:82\n- pkg/segment/test/set_functions.go:15\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove outdated nogo exception.
PiperOrigin-RevId: 343096420 |
259,868 | 18.11.2020 11:44:44 | 28,800 | d6e788a8d1a3941108e127ac8b7e14d00def35c6 | Add a few syslog messages. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/syslog.go",
"new_path": "pkg/sentry/kernel/syslog.go",
"diff": "@@ -75,6 +75,12 @@ func (s *syslog) Log() []byte {\n\"Checking naughty and nice process list...\", // Check it up to twice.\n\"Granting licence to kill(2)...\", // British spelling for British movie.\n\"Letting the watchdogs out...\",\n+ \"Conjuring /dev/null black hole...\",\n+ \"Adversarially training Redcode AI...\",\n+ \"Singleplexing /dev/ptmx...\",\n+ \"Recruiting cron-ies...\",\n+ \"Verifying that no non-zero bytes made their way into /dev/zero...\",\n+ \"Accelerating teletypewriter to 9600 baud...\",\n}\nselectMessage := func() string {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add a few syslog messages.
PiperOrigin-RevId: 343123278 |
260,004 | 18.11.2020 12:43:51 | 28,800 | 60b97bfda6b5a2730c3016c8d243d521a89b6272 | Fix loopback subnet routing error
Packets should be properly routed when sending packets to addresses
in the loopback subnet which are not explicitly assigned to the loopback
interface.
Tests:
integration_test.TestLoopbackAcceptAllInSubnetUDP
integration_test.TestLoopbackAcceptAllInSubnetTCP | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/route.go",
"new_path": "pkg/tcpip/stack/route.go",
"diff": "@@ -71,22 +71,24 @@ type Route struct {\n// ownership of the provided local address.\n//\n// Returns an empty route if validation fails.\n-func constructAndValidateRoute(netProto tcpip.NetworkProtocolNumber, addressEndpoint AssignableAddressEndpoint, localAddressNIC, outgoingNIC *NIC, gateway, remoteAddr tcpip.Address, handleLocal, multicastLoop bool) Route {\n- addrWithPrefix := addressEndpoint.AddressWithPrefix()\n+func constructAndValidateRoute(netProto tcpip.NetworkProtocolNumber, addressEndpoint AssignableAddressEndpoint, localAddressNIC, outgoingNIC *NIC, gateway, localAddr, remoteAddr tcpip.Address, handleLocal, multicastLoop bool) Route {\n+ if len(localAddr) == 0 {\n+ localAddr = addressEndpoint.AddressWithPrefix().Address\n+ }\n- if localAddressNIC != outgoingNIC && header.IsV6LinkLocalAddress(addrWithPrefix.Address) {\n+ if localAddressNIC != outgoingNIC && header.IsV6LinkLocalAddress(localAddr) {\naddressEndpoint.DecRef()\nreturn Route{}\n}\n// If no remote address is provided, use the local address.\nif len(remoteAddr) == 0 {\n- remoteAddr = addrWithPrefix.Address\n+ remoteAddr = localAddr\n}\nr := makeRoute(\nnetProto,\n- addrWithPrefix.Address,\n+ localAddr,\nremoteAddr,\noutgoingNIC,\nlocalAddressNIC,\n@@ -99,7 +101,7 @@ func constructAndValidateRoute(netProto tcpip.NetworkProtocolNumber, addressEndp\n// broadcast it.\nif len(gateway) > 0 {\nr.NextHop = gateway\n- } else if subnet := addrWithPrefix.Subnet(); subnet.IsBroadcast(remoteAddr) {\n+ } else if subnet := addressEndpoint.Subnet(); subnet.IsBroadcast(remoteAddr) {\nr.RemoteLinkAddress = header.EthernetBroadcastAddress\n}\n@@ -113,6 +115,10 @@ func makeRoute(netProto tcpip.NetworkProtocolNumber, localAddr, remoteAddr tcpip\npanic(fmt.Sprintf(\"cannot create a route with NICs from different stacks\"))\n}\n+ if len(localAddr) == 0 {\n+ localAddr = localAddressEndpoint.AddressWithPrefix().Address\n+ }\n+\nloop := PacketOut\n// TODO(gvisor.dev/issue/4689): Loopback interface loops back packets at the\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -1240,7 +1240,7 @@ func (s *Stack) findLocalRouteFromNICRLocked(localAddressNIC *NIC, localAddr, re\nr := makeLocalRoute(\nnetProto,\n- localAddressEndpoint.AddressWithPrefix().Address,\n+ localAddr,\nremoteAddr,\noutgoingNIC,\nlocalAddressNIC,\n@@ -1317,7 +1317,7 @@ func (s *Stack) FindRoute(id tcpip.NICID, localAddr, remoteAddr tcpip.Address, n\nif addressEndpoint := s.getAddressEP(nic, localAddr, remoteAddr, netProto); addressEndpoint != nil {\nreturn makeRoute(\nnetProto,\n- addressEndpoint.AddressWithPrefix().Address,\n+ localAddr,\nremoteAddr,\nnic, /* outboundNIC */\nnic, /* localAddressNIC*/\n@@ -1354,7 +1354,7 @@ func (s *Stack) FindRoute(id tcpip.NICID, localAddr, remoteAddr tcpip.Address, n\nif needRoute {\ngateway = route.Gateway\n}\n- r := constructAndValidateRoute(netProto, addressEndpoint, nic /* outgoingNIC */, nic /* outgoingNIC */, gateway, remoteAddr, s.handleLocal, multicastLoop)\n+ r := constructAndValidateRoute(netProto, addressEndpoint, nic /* outgoingNIC */, nic /* outgoingNIC */, gateway, localAddr, remoteAddr, s.handleLocal, multicastLoop)\nif r == (Route{}) {\npanic(fmt.Sprintf(\"non-forwarding route validation failed with route table entry = %#v, id = %d, localAddr = %s, remoteAddr = %s\", route, id, localAddr, remoteAddr))\n}\n@@ -1391,7 +1391,7 @@ func (s *Stack) FindRoute(id tcpip.NICID, localAddr, remoteAddr tcpip.Address, n\nif id != 0 {\nif aNIC, ok := s.nics[id]; ok {\nif addressEndpoint := s.getAddressEP(aNIC, localAddr, remoteAddr, netProto); addressEndpoint != nil {\n- if r := constructAndValidateRoute(netProto, addressEndpoint, aNIC /* localAddressNIC */, nic /* outgoingNIC */, gateway, remoteAddr, s.handleLocal, multicastLoop); r != (Route{}) {\n+ if r := constructAndValidateRoute(netProto, addressEndpoint, aNIC /* localAddressNIC */, nic /* outgoingNIC */, gateway, localAddr, remoteAddr, s.handleLocal, multicastLoop); r != (Route{}) {\nreturn r, nil\n}\n}\n@@ -1409,7 +1409,7 @@ func (s *Stack) FindRoute(id tcpip.NICID, localAddr, remoteAddr tcpip.Address, n\ncontinue\n}\n- if r := constructAndValidateRoute(netProto, addressEndpoint, aNIC /* localAddressNIC */, nic /* outgoingNIC */, gateway, remoteAddr, s.handleLocal, multicastLoop); r != (Route{}) {\n+ if r := constructAndValidateRoute(netProto, addressEndpoint, aNIC /* localAddressNIC */, nic /* outgoingNIC */, gateway, localAddr, remoteAddr, s.handleLocal, multicastLoop); r != (Route{}) {\nreturn r, nil\n}\n}\n@@ -2130,3 +2130,43 @@ func (s *Stack) networkProtocolNumbers() []tcpip.NetworkProtocolNumber {\n}\nreturn protos\n}\n+\n+func isSubnetBroadcastOnNIC(nic *NIC, protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) bool {\n+ addressEndpoint := nic.getAddressOrCreateTempInner(protocol, addr, false /* createTemp */, NeverPrimaryEndpoint)\n+ if addressEndpoint == nil {\n+ return false\n+ }\n+\n+ subnet := addressEndpoint.Subnet()\n+ addressEndpoint.DecRef()\n+ return subnet.IsBroadcast(addr)\n+}\n+\n+// IsSubnetBroadcast returns true if the provided address is a subnet-local\n+// broadcast address on the specified NIC and protocol.\n+//\n+// Returns false if the NIC is unknown or if the protocol is unknown or does\n+// not support addressing.\n+//\n+// If the NIC is not specified, the stack will check all NICs.\n+func (s *Stack) IsSubnetBroadcast(nicID tcpip.NICID, protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) bool {\n+ s.mu.RLock()\n+ defer s.mu.RUnlock()\n+\n+ if nicID != 0 {\n+ nic, ok := s.nics[nicID]\n+ if !ok {\n+ return false\n+ }\n+\n+ return isSubnetBroadcastOnNIC(nic, protocol, addr)\n+ }\n+\n+ for _, nic := range s.nics {\n+ if isSubnetBroadcastOnNIC(nic, protocol, addr) {\n+ return true\n+ }\n+ }\n+\n+ return false\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/integration/BUILD",
"new_path": "pkg/tcpip/tests/integration/BUILD",
"diff": "@@ -25,6 +25,7 @@ go_test(\n\"//pkg/tcpip/network/ipv6\",\n\"//pkg/tcpip/stack\",\n\"//pkg/tcpip/transport/icmp\",\n+ \"//pkg/tcpip/transport/tcp\",\n\"//pkg/tcpip/transport/udp\",\n\"//pkg/waiter\",\n\"@com_github_google_go_cmp//cmp:go_default_library\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/integration/loopback_test.go",
"new_path": "pkg/tcpip/tests/integration/loopback_test.go",
"diff": "@@ -26,6 +26,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv4\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv6\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/transport/tcp\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/udp\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n@@ -93,9 +94,10 @@ func TestInitialLoopbackAddresses(t *testing.T) {\n}\n}\n-// TestLoopbackAcceptAllInSubnet tests that a loopback interface considers\n-// itself bound to all addresses in the subnet of an assigned address.\n-func TestLoopbackAcceptAllInSubnet(t *testing.T) {\n+// TestLoopbackAcceptAllInSubnetUDP tests that a loopback interface considers\n+// itself bound to all addresses in the subnet of an assigned address and UDP\n+// traffic is sent/received correctly.\n+func TestLoopbackAcceptAllInSubnetUDP(t *testing.T) {\nconst (\nnicID = 1\nlocalPort = 80\n@@ -107,7 +109,7 @@ func TestLoopbackAcceptAllInSubnet(t *testing.T) {\nProtocol: header.IPv4ProtocolNumber,\nAddressWithPrefix: ipv4Addr,\n}\n- ipv4Bytes := []byte(ipv4Addr.Address)\n+ ipv4Bytes := []byte(ipv4ProtocolAddress.AddressWithPrefix.Address)\nipv4Bytes[len(ipv4Bytes)-1]++\notherIPv4Address := tcpip.Address(ipv4Bytes)\n@@ -129,7 +131,7 @@ func TestLoopbackAcceptAllInSubnet(t *testing.T) {\n{\nname: \"IPv4 bind to wildcard and send to assigned address\",\naddAddress: ipv4ProtocolAddress,\n- dstAddr: ipv4Addr.Address,\n+ dstAddr: ipv4ProtocolAddress.AddressWithPrefix.Address,\nexpectRx: true,\n},\n{\n@@ -148,7 +150,7 @@ func TestLoopbackAcceptAllInSubnet(t *testing.T) {\nname: \"IPv4 bind to other subnet-local address and send to assigned address\",\naddAddress: ipv4ProtocolAddress,\nbindAddr: otherIPv4Address,\n- dstAddr: ipv4Addr.Address,\n+ dstAddr: ipv4ProtocolAddress.AddressWithPrefix.Address,\nexpectRx: false,\n},\n{\n@@ -161,7 +163,7 @@ func TestLoopbackAcceptAllInSubnet(t *testing.T) {\n{\nname: \"IPv4 bind to assigned address and send to other subnet-local address\",\naddAddress: ipv4ProtocolAddress,\n- bindAddr: ipv4Addr.Address,\n+ bindAddr: ipv4ProtocolAddress.AddressWithPrefix.Address,\ndstAddr: otherIPv4Address,\nexpectRx: false,\n},\n@@ -236,13 +238,17 @@ func TestLoopbackAcceptAllInSubnet(t *testing.T) {\nt.Fatalf(\"got sep.Write(_, _) = (%d, _, nil), want = (%d, _, nil)\", n, want)\n}\n- if gotPayload, _, err := rep.Read(nil); test.expectRx {\n+ var addr tcpip.FullAddress\n+ if gotPayload, _, err := rep.Read(&addr); test.expectRx {\nif err != nil {\n- t.Fatalf(\"reep.Read(nil): %s\", err)\n+ t.Fatalf(\"reep.Read(_): %s\", err)\n}\nif diff := cmp.Diff(buffer.View(data), gotPayload); diff != \"\" {\nt.Errorf(\"got UDP payload mismatch (-want +got):\\n%s\", diff)\n}\n+ if addr.Addr != test.addAddress.AddressWithPrefix.Address {\n+ t.Errorf(\"got addr.Addr = %s, want = %s\", addr.Addr, test.addAddress.AddressWithPrefix.Address)\n+ }\n} else {\nif err != tcpip.ErrWouldBlock {\nt.Fatalf(\"got rep.Read(nil) = (%x, _, %s), want = (_, _, %s)\", gotPayload, err, tcpip.ErrWouldBlock)\n@@ -312,3 +318,168 @@ func TestLoopbackSubnetLifetimeBoundToAddr(t *testing.T) {\nt.Fatalf(\"got r.WritePacket(nil, %#v, _) = %s, want = %s\", params, err, tcpip.ErrInvalidEndpointState)\n}\n}\n+\n+// TestLoopbackAcceptAllInSubnetTCP tests that a loopback interface considers\n+// itself bound to all addresses in the subnet of an assigned address and TCP\n+// traffic is sent/received correctly.\n+func TestLoopbackAcceptAllInSubnetTCP(t *testing.T) {\n+ const (\n+ nicID = 1\n+ localPort = 80\n+ )\n+\n+ ipv4ProtocolAddress := tcpip.ProtocolAddress{\n+ Protocol: header.IPv4ProtocolNumber,\n+ AddressWithPrefix: ipv4Addr,\n+ }\n+ ipv4ProtocolAddress.AddressWithPrefix.PrefixLen = 8\n+ ipv4Bytes := []byte(ipv4ProtocolAddress.AddressWithPrefix.Address)\n+ ipv4Bytes[len(ipv4Bytes)-1]++\n+ otherIPv4Address := tcpip.Address(ipv4Bytes)\n+\n+ ipv6ProtocolAddress := tcpip.ProtocolAddress{\n+ Protocol: header.IPv6ProtocolNumber,\n+ AddressWithPrefix: ipv6Addr,\n+ }\n+ ipv6Bytes := []byte(ipv6Addr.Address)\n+ ipv6Bytes[len(ipv6Bytes)-1]++\n+ otherIPv6Address := tcpip.Address(ipv6Bytes)\n+\n+ tests := []struct {\n+ name string\n+ addAddress tcpip.ProtocolAddress\n+ bindAddr tcpip.Address\n+ dstAddr tcpip.Address\n+ expectAccept bool\n+ }{\n+ {\n+ name: \"IPv4 bind to wildcard and send to assigned address\",\n+ addAddress: ipv4ProtocolAddress,\n+ dstAddr: ipv4ProtocolAddress.AddressWithPrefix.Address,\n+ expectAccept: true,\n+ },\n+ {\n+ name: \"IPv4 bind to wildcard and send to other subnet-local address\",\n+ addAddress: ipv4ProtocolAddress,\n+ dstAddr: otherIPv4Address,\n+ expectAccept: true,\n+ },\n+ {\n+ name: \"IPv4 bind to wildcard send to other address\",\n+ addAddress: ipv4ProtocolAddress,\n+ dstAddr: remoteIPv4Addr,\n+ expectAccept: false,\n+ },\n+ {\n+ name: \"IPv4 bind to other subnet-local address and send to assigned address\",\n+ addAddress: ipv4ProtocolAddress,\n+ bindAddr: otherIPv4Address,\n+ dstAddr: ipv4ProtocolAddress.AddressWithPrefix.Address,\n+ expectAccept: false,\n+ },\n+ {\n+ name: \"IPv4 bind and send to other subnet-local address\",\n+ addAddress: ipv4ProtocolAddress,\n+ bindAddr: otherIPv4Address,\n+ dstAddr: otherIPv4Address,\n+ expectAccept: true,\n+ },\n+ {\n+ name: \"IPv4 bind to assigned address and send to other subnet-local address\",\n+ addAddress: ipv4ProtocolAddress,\n+ bindAddr: ipv4ProtocolAddress.AddressWithPrefix.Address,\n+ dstAddr: otherIPv4Address,\n+ expectAccept: false,\n+ },\n+\n+ {\n+ name: \"IPv6 bind and send to assigned address\",\n+ addAddress: ipv6ProtocolAddress,\n+ bindAddr: ipv6Addr.Address,\n+ dstAddr: ipv6Addr.Address,\n+ expectAccept: true,\n+ },\n+ {\n+ name: \"IPv6 bind to wildcard and send to other subnet-local address\",\n+ addAddress: ipv6ProtocolAddress,\n+ dstAddr: otherIPv6Address,\n+ expectAccept: false,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},\n+ TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol},\n+ })\n+ if err := s.CreateNIC(nicID, loopback.New()); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", nicID, err)\n+ }\n+ if err := s.AddProtocolAddress(nicID, test.addAddress); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %#v): %s\", nicID, test.addAddress, err)\n+ }\n+ s.SetRouteTable([]tcpip.Route{\n+ tcpip.Route{\n+ Destination: header.IPv4EmptySubnet,\n+ NIC: nicID,\n+ },\n+ tcpip.Route{\n+ Destination: header.IPv6EmptySubnet,\n+ NIC: nicID,\n+ },\n+ })\n+\n+ var wq waiter.Queue\n+ we, ch := waiter.NewChannelEntry(nil)\n+ wq.EventRegister(&we, waiter.EventIn)\n+ defer wq.EventUnregister(&we)\n+ listeningEndpoint, err := s.NewEndpoint(tcp.ProtocolNumber, test.addAddress.Protocol, &wq)\n+ if err != nil {\n+ t.Fatalf(\"NewEndpoint(%d, %d, _): %s\", udp.ProtocolNumber, test.addAddress.Protocol, err)\n+ }\n+ defer listeningEndpoint.Close()\n+\n+ bindAddr := tcpip.FullAddress{Addr: test.bindAddr, Port: localPort}\n+ if err := listeningEndpoint.Bind(bindAddr); err != nil {\n+ t.Fatalf(\"listeningEndpoint.Bind(%#v): %s\", bindAddr, err)\n+ }\n+\n+ if err := listeningEndpoint.Listen(1); err != nil {\n+ t.Fatalf(\"listeningEndpoint.Listen(1): %s\", err)\n+ }\n+\n+ connectingEndpoint, err := s.NewEndpoint(tcp.ProtocolNumber, test.addAddress.Protocol, &wq)\n+ if err != nil {\n+ t.Fatalf(\"s.NewEndpoint(%d, %d, _): %s\", udp.ProtocolNumber, test.addAddress.Protocol, err)\n+ }\n+ defer connectingEndpoint.Close()\n+\n+ connectAddr := tcpip.FullAddress{\n+ Addr: test.dstAddr,\n+ Port: localPort,\n+ }\n+ if err := connectingEndpoint.Connect(connectAddr); err != tcpip.ErrConnectStarted {\n+ t.Fatalf(\"connectingEndpoint.Connect(%#v): %s\", connectAddr, err)\n+ }\n+\n+ if !test.expectAccept {\n+ if _, _, err := listeningEndpoint.Accept(nil); err != tcpip.ErrWouldBlock {\n+ t.Fatalf(\"got listeningEndpoint.Accept(nil) = %s, want = %s\", err, tcpip.ErrWouldBlock)\n+ }\n+ return\n+ }\n+\n+ // Wait for the listening endpoint to be \"readable\". That is, wait for a\n+ // new connection.\n+ <-ch\n+ var addr tcpip.FullAddress\n+ if _, _, err := listeningEndpoint.Accept(&addr); err != nil {\n+ t.Fatalf(\"listeningEndpoint.Accept(nil): %s\", err)\n+ }\n+ if addr.Addr != test.addAddress.AddressWithPrefix.Address {\n+ t.Errorf(\"got addr.Addr = %s, want = %s\", addr.Addr, test.addAddress.AddressWithPrefix.Address)\n+ }\n+ })\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -369,7 +369,7 @@ func (e *endpoint) prepareForWrite(to *tcpip.FullAddress) (retry bool, err *tcpi\n// specified address is a multicast address.\nfunc (e *endpoint) connectRoute(nicID tcpip.NICID, addr tcpip.FullAddress, netProto tcpip.NetworkProtocolNumber) (stack.Route, tcpip.NICID, *tcpip.Error) {\nlocalAddr := e.ID.LocalAddress\n- if isBroadcastOrMulticast(localAddr) {\n+ if e.isBroadcastOrMulticast(nicID, netProto, localAddr) {\n// A packet can only originate from a unicast address (i.e., an interface).\nlocalAddr = \"\"\n}\n@@ -1290,7 +1290,7 @@ func (e *endpoint) bindLocked(addr tcpip.FullAddress) *tcpip.Error {\n}\nnicID := addr.NIC\n- if len(addr.Addr) != 0 && !isBroadcastOrMulticast(addr.Addr) {\n+ if len(addr.Addr) != 0 && !e.isBroadcastOrMulticast(addr.NIC, netProto, addr.Addr) {\n// A local unicast address was specified, verify that it's valid.\nnicID = e.stack.CheckLocalAddress(addr.NIC, netProto, addr.Addr)\nif nicID == 0 {\n@@ -1531,8 +1531,8 @@ func (e *endpoint) Stats() tcpip.EndpointStats {\n// Wait implements tcpip.Endpoint.Wait.\nfunc (*endpoint) Wait() {}\n-func isBroadcastOrMulticast(a tcpip.Address) bool {\n- return a == header.IPv4Broadcast || header.IsV4MulticastAddress(a) || header.IsV6MulticastAddress(a)\n+func (e *endpoint) isBroadcastOrMulticast(nicID tcpip.NICID, netProto tcpip.NetworkProtocolNumber, addr tcpip.Address) bool {\n+ return addr == header.IPv4Broadcast || header.IsV4MulticastAddress(addr) || header.IsV6MulticastAddress(addr) || e.stack.IsSubnetBroadcast(nicID, netProto, addr)\n}\n// SetOwner implements tcpip.Endpoint.SetOwner.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint_state.go",
"new_path": "pkg/tcpip/transport/udp/endpoint_state.go",
"diff": "@@ -118,7 +118,7 @@ func (e *endpoint) Resume(s *stack.Stack) {\nif err != nil {\npanic(err)\n}\n- } else if len(e.ID.LocalAddress) != 0 && !isBroadcastOrMulticast(e.ID.LocalAddress) { // stateBound\n+ } else if len(e.ID.LocalAddress) != 0 && !e.isBroadcastOrMulticast(e.RegisterNICID, netProto, e.ID.LocalAddress) { // stateBound\n// A local unicast address is specified, verify that it's valid.\nif e.stack.CheckLocalAddress(e.RegisterNICID, netProto, e.ID.LocalAddress) == 0 {\npanic(tcpip.ErrBadLocalAddress)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix loopback subnet routing error
Packets should be properly routed when sending packets to addresses
in the loopback subnet which are not explicitly assigned to the loopback
interface.
Tests:
- integration_test.TestLoopbackAcceptAllInSubnetUDP
- integration_test.TestLoopbackAcceptAllInSubnetTCP
PiperOrigin-RevId: 343135643 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.