author
int64
658
755k
date
stringlengths
19
19
timezone
int64
-46,800
43.2k
hash
stringlengths
40
40
message
stringlengths
5
490
mods
list
language
stringclasses
20 values
license
stringclasses
3 values
repo
stringlengths
5
68
original_message
stringlengths
12
491
259,974
20.02.2019 15:09:50
28,800
15d3189884c2e8050992381ff2a1f0521eae0ba2
Make some ptrace commands x86-only
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/BUILD", "new_path": "pkg/sentry/kernel/BUILD", "diff": "@@ -95,6 +95,8 @@ go_library(\n\"posixtimer.go\",\n\"process_group_list.go\",\n\"ptrace.go\",\n+ \"ptrace_amd64.go\",\n+ \"ptrace_arm64.go\",\n\"rseq.go\",\n\"seccomp.go\",\n\"seqatomic_taskgoroutineschedinfo.go\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/ptrace.go", "new_path": "pkg/sentry/kernel/ptrace.go", "diff": "@@ -863,42 +863,6 @@ func (t *Task) Ptrace(req int64, pid ThreadID, addr, data usermem.Addr) error {\n})\nreturn err\n- case linux.PTRACE_PEEKUSR: // aka PTRACE_PEEKUSER\n- n, err := target.Arch().PtracePeekUser(uintptr(addr))\n- if err != nil {\n- return err\n- }\n- _, err = t.CopyOut(data, n)\n- return err\n-\n- case linux.PTRACE_POKEUSR: // aka PTRACE_POKEUSER\n- return target.Arch().PtracePokeUser(uintptr(addr), uintptr(data))\n-\n- case linux.PTRACE_GETREGS:\n- // \"Copy the tracee's general-purpose ... registers ... to the address\n- // data in the tracer. ... (addr is ignored.) Note that SPARC systems\n- // have the meaning of data and addr reversed ...\"\n- _, err := target.Arch().PtraceGetRegs(&usermem.IOReadWriter{\n- Ctx: t,\n- IO: t.MemoryManager(),\n- Addr: data,\n- Opts: usermem.IOOpts{\n- AddressSpaceActive: true,\n- },\n- })\n- return err\n-\n- case linux.PTRACE_GETFPREGS:\n- _, err := target.Arch().PtraceGetFPRegs(&usermem.IOReadWriter{\n- Ctx: t,\n- IO: t.MemoryManager(),\n- Addr: data,\n- Opts: usermem.IOOpts{\n- AddressSpaceActive: true,\n- },\n- })\n- return err\n-\ncase linux.PTRACE_GETREGSET:\n// \"Read the tracee's registers. addr specifies, in an\n// architecture-dependent way, the type of registers to be read. ...\n@@ -930,28 +894,6 @@ func (t *Task) Ptrace(req int64, pid ThreadID, addr, data usermem.Addr) error {\nar.End = end\nreturn t.CopyOutIovecs(data, usermem.AddrRangeSeqOf(ar))\n- case linux.PTRACE_SETREGS:\n- _, err := target.Arch().PtraceSetRegs(&usermem.IOReadWriter{\n- Ctx: t,\n- IO: t.MemoryManager(),\n- Addr: data,\n- Opts: usermem.IOOpts{\n- AddressSpaceActive: true,\n- },\n- })\n- return err\n-\n- case linux.PTRACE_SETFPREGS:\n- _, err := target.Arch().PtraceSetFPRegs(&usermem.IOReadWriter{\n- Ctx: t,\n- IO: t.MemoryManager(),\n- Addr: data,\n- Opts: usermem.IOOpts{\n- AddressSpaceActive: true,\n- },\n- })\n- return err\n-\ncase linux.PTRACE_SETREGSET:\nars, err := t.CopyInIovecs(data, 1)\nif err != nil {\n@@ -1047,8 +989,9 @@ func (t *Task) Ptrace(req int64, pid ThreadID, addr, data usermem.Addr) error {\n_, err := t.CopyOut(usermem.Addr(data), target.ptraceEventMsg)\nreturn err\n- default:\n// PEEKSIGINFO is unimplemented but seems to have no users anywhere.\n- return syserror.EIO\n+\n+ default:\n+ return t.ptraceArch(target, req, addr, data)\n}\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/kernel/ptrace_amd64.go", "diff": "+// Copyright 2019 Google Inc.\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 amd64\n+\n+package kernel\n+\n+import (\n+ \"gvisor.googlesource.com/gvisor/pkg/abi/linux\"\n+ \"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\"\n+ \"gvisor.googlesource.com/gvisor/pkg/syserror\"\n+)\n+\n+// ptraceArch implements arch-specific ptrace commands.\n+func (t *Task) ptraceArch(target *Task, req int64, addr, data usermem.Addr) error {\n+ switch req {\n+ case linux.PTRACE_PEEKUSR: // aka PTRACE_PEEKUSER\n+ n, err := target.Arch().PtracePeekUser(uintptr(addr))\n+ if err != nil {\n+ return err\n+ }\n+ _, err = t.CopyOut(data, n)\n+ return err\n+\n+ case linux.PTRACE_POKEUSR: // aka PTRACE_POKEUSER\n+ return target.Arch().PtracePokeUser(uintptr(addr), uintptr(data))\n+\n+ case linux.PTRACE_GETREGS:\n+ // \"Copy the tracee's general-purpose ... registers ... to the address\n+ // data in the tracer. ... (addr is ignored.) Note that SPARC systems\n+ // have the meaning of data and addr reversed ...\"\n+ _, err := target.Arch().PtraceGetRegs(&usermem.IOReadWriter{\n+ Ctx: t,\n+ IO: t.MemoryManager(),\n+ Addr: data,\n+ Opts: usermem.IOOpts{\n+ AddressSpaceActive: true,\n+ },\n+ })\n+ return err\n+\n+ case linux.PTRACE_GETFPREGS:\n+ _, err := target.Arch().PtraceGetFPRegs(&usermem.IOReadWriter{\n+ Ctx: t,\n+ IO: t.MemoryManager(),\n+ Addr: data,\n+ Opts: usermem.IOOpts{\n+ AddressSpaceActive: true,\n+ },\n+ })\n+ return err\n+\n+ case linux.PTRACE_SETREGS:\n+ _, err := target.Arch().PtraceSetRegs(&usermem.IOReadWriter{\n+ Ctx: t,\n+ IO: t.MemoryManager(),\n+ Addr: data,\n+ Opts: usermem.IOOpts{\n+ AddressSpaceActive: true,\n+ },\n+ })\n+ return err\n+\n+ case linux.PTRACE_SETFPREGS:\n+ _, err := target.Arch().PtraceSetFPRegs(&usermem.IOReadWriter{\n+ Ctx: t,\n+ IO: t.MemoryManager(),\n+ Addr: data,\n+ Opts: usermem.IOOpts{\n+ AddressSpaceActive: true,\n+ },\n+ })\n+ return err\n+\n+ default:\n+ return syserror.EIO\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/kernel/ptrace_arm64.go", "diff": "+// Copyright 2019 Google Inc.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// +build arm64\n+\n+package kernel\n+\n+import (\n+ \"gvisor.googlesource.com/gvisor/pkg/abi/linux\"\n+ \"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\"\n+ \"gvisor.googlesource.com/gvisor/pkg/syserror\"\n+)\n+\n+// ptraceArch implements arch-specific ptrace commands.\n+func (t *Task) ptraceArch(target *Task, req int64, addr, data usermem.Addr) error {\n+ return syserror.EIO\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Make some ptrace commands x86-only Signed-off-by: Haibo Xu <[email protected]> Change-Id: I9751f859332d433ca772d6b9733f5a5a64398ec7 PiperOrigin-RevId: 234877624
259,891
22.02.2019 13:33:49
28,800
b75aa515044367094e762985a4b1a1f0580e3ad6
Rename ping endpoints to icmp endpoints.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/arp/BUILD", "new_path": "pkg/tcpip/network/arp/BUILD", "diff": "@@ -30,6 +30,6 @@ go_test(\n\"//pkg/tcpip/link/sniffer\",\n\"//pkg/tcpip/network/ipv4\",\n\"//pkg/tcpip/stack\",\n- \"//pkg/tcpip/transport/ping\",\n+ \"//pkg/tcpip/transport/icmp\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/arp/arp_test.go", "new_path": "pkg/tcpip/network/arp/arp_test.go", "diff": "@@ -26,7 +26,7 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/tcpip/network/arp\"\n\"gvisor.googlesource.com/gvisor/pkg/tcpip/network/ipv4\"\n\"gvisor.googlesource.com/gvisor/pkg/tcpip/stack\"\n- \"gvisor.googlesource.com/gvisor/pkg/tcpip/transport/ping\"\n+ \"gvisor.googlesource.com/gvisor/pkg/tcpip/transport/icmp\"\n)\nconst (\n@@ -43,7 +43,7 @@ type testContext struct {\n}\nfunc newTestContext(t *testing.T) *testContext {\n- s := stack.New([]string{ipv4.ProtocolName, arp.ProtocolName}, []string{ping.ProtocolName4}, stack.Options{})\n+ s := stack.New([]string{ipv4.ProtocolName, arp.ProtocolName}, []string{icmp.ProtocolName4}, stack.Options{})\nconst defaultMTU = 65536\nid, linkEP := channel.New(256, defaultMTU, stackLinkAddr)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/BUILD", "new_path": "pkg/tcpip/network/ipv6/BUILD", "diff": "@@ -32,7 +32,7 @@ go_test(\n\"//pkg/tcpip/link/channel\",\n\"//pkg/tcpip/link/sniffer\",\n\"//pkg/tcpip/stack\",\n- \"//pkg/tcpip/transport/ping\",\n+ \"//pkg/tcpip/transport/icmp\",\n\"//pkg/waiter\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp_test.go", "new_path": "pkg/tcpip/network/ipv6/icmp_test.go", "diff": "@@ -27,7 +27,7 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/tcpip/link/channel\"\n\"gvisor.googlesource.com/gvisor/pkg/tcpip/link/sniffer\"\n\"gvisor.googlesource.com/gvisor/pkg/tcpip/stack\"\n- \"gvisor.googlesource.com/gvisor/pkg/tcpip/transport/ping\"\n+ \"gvisor.googlesource.com/gvisor/pkg/tcpip/transport/icmp\"\n\"gvisor.googlesource.com/gvisor/pkg/waiter\"\n)\n@@ -68,8 +68,8 @@ func (e endpointWithResolutionCapability) Capabilities() stack.LinkEndpointCapab\nfunc newTestContext(t *testing.T) *testContext {\nc := &testContext{\nt: t,\n- s0: stack.New([]string{ProtocolName}, []string{ping.ProtocolName6}, stack.Options{}),\n- s1: stack.New([]string{ProtocolName}, []string{ping.ProtocolName6}, stack.Options{}),\n+ s0: stack.New([]string{ProtocolName}, []string{icmp.ProtocolName6}, stack.Options{}),\n+ s1: stack.New([]string{ProtocolName}, []string{icmp.ProtocolName6}, stack.Options{}),\nicmpCh: make(chan icmpInfo, 10),\n}\n" }, { "change_type": "RENAME", "old_path": "pkg/tcpip/transport/ping/BUILD", "new_path": "pkg/tcpip/transport/icmp/BUILD", "diff": "@@ -4,26 +4,26 @@ load(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\nload(\"//tools/go_stateify:defs.bzl\", \"go_library\")\ngo_template_instance(\n- name = \"ping_packet_list\",\n- out = \"ping_packet_list.go\",\n- package = \"ping\",\n- prefix = \"pingPacket\",\n+ name = \"icmp_packet_list\",\n+ out = \"icmp_packet_list.go\",\n+ package = \"icmp\",\n+ prefix = \"icmpPacket\",\ntemplate = \"//pkg/ilist:generic_list\",\ntypes = {\n- \"Element\": \"*pingPacket\",\n- \"Linker\": \"*pingPacket\",\n+ \"Element\": \"*icmpPacket\",\n+ \"Linker\": \"*icmpPacket\",\n},\n)\ngo_library(\n- name = \"ping\",\n+ name = \"icmp\",\nsrcs = [\n\"endpoint.go\",\n\"endpoint_state.go\",\n- \"ping_packet_list.go\",\n+ \"icmp_packet_list.go\",\n\"protocol.go\",\n],\n- importpath = \"gvisor.googlesource.com/gvisor/pkg/tcpip/transport/ping\",\n+ importpath = \"gvisor.googlesource.com/gvisor/pkg/tcpip/transport/icmp\",\nimports = [\"gvisor.googlesource.com/gvisor/pkg/tcpip/buffer\"],\nvisibility = [\"//visibility:public\"],\ndeps = [\n@@ -39,7 +39,7 @@ go_library(\nfilegroup(\nname = \"autogen\",\nsrcs = [\n- \"ping_packet_list.go\",\n+ \"icmp_packet_list.go\",\n],\nvisibility = [\"//:sandbox\"],\n)\n" }, { "change_type": "RENAME", "old_path": "pkg/tcpip/transport/ping/endpoint.go", "new_path": "pkg/tcpip/transport/icmp/endpoint.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-package ping\n+package icmp\nimport (\n\"encoding/binary\"\n@@ -27,8 +27,8 @@ import (\n)\n// +stateify savable\n-type pingPacket struct {\n- pingPacketEntry\n+type icmpPacket struct {\n+ icmpPacketEntry\nsenderAddress tcpip.FullAddress\ndata buffer.VectorisedView `state:\".(buffer.VectorisedView)\"`\ntimestamp int64\n@@ -46,10 +46,10 @@ const (\nstateClosed\n)\n-// endpoint represents a ping endpoint. This struct serves as the interface\n-// between users of the endpoint and the protocol implementation; it is legal to\n-// have concurrent goroutines make calls into the endpoint, they are properly\n-// synchronized.\n+// endpoint represents an ICMP (ping) endpoint. This struct serves as the\n+// interface between users of the endpoint and the protocol implementation; it\n+// is legal to have concurrent goroutines make calls into the endpoint, they\n+// are properly synchronized.\ntype endpoint struct {\n// The following fields are initialized at creation time and do not\n// change throughout the lifetime of the endpoint.\n@@ -62,7 +62,7 @@ type endpoint struct {\n// protected by rcvMu.\nrcvMu sync.Mutex `state:\"nosave\"`\nrcvReady bool\n- rcvList pingPacketList\n+ rcvList icmpPacketList\nrcvBufSizeMax int `state:\".(int)\"`\nrcvBufSize int\nrcvClosed bool\n@@ -669,7 +669,7 @@ func (e *endpoint) HandlePacket(r *stack.Route, id stack.TransportEndpointID, vv\nwasEmpty := e.rcvBufSize == 0\n// Push new packet into receive list and increment the buffer size.\n- pkt := &pingPacket{\n+ pkt := &icmpPacket{\nsenderAddress: tcpip.FullAddress{\nNIC: r.NICID(),\nAddr: id.RemoteAddress,\n" }, { "change_type": "RENAME", "old_path": "pkg/tcpip/transport/ping/endpoint_state.go", "new_path": "pkg/tcpip/transport/icmp/endpoint_state.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-package ping\n+package icmp\nimport (\n\"gvisor.googlesource.com/gvisor/pkg/tcpip\"\n@@ -20,15 +20,15 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/tcpip/stack\"\n)\n-// saveData saves pingPacket.data field.\n-func (p *pingPacket) saveData() buffer.VectorisedView {\n+// saveData saves icmpPacket.data field.\n+func (p *icmpPacket) saveData() buffer.VectorisedView {\n// We cannot save p.data directly as p.data.views may alias to p.views,\n// which is not allowed by state framework (in-struct pointer).\nreturn p.data.Clone(nil)\n}\n-// loadData loads pingPacket.data field.\n-func (p *pingPacket) loadData(data buffer.VectorisedView) {\n+// loadData loads icmpPacket.data field.\n+func (p *icmpPacket) loadData(data buffer.VectorisedView) {\n// NOTE: We cannot do the p.data = data.Clone(p.views[:]) optimization\n// here because data.views is not guaranteed to be loaded by now. Plus,\n// data.views will be allocated anyway so there really is little point\n" }, { "change_type": "RENAME", "old_path": "pkg/tcpip/transport/ping/protocol.go", "new_path": "pkg/tcpip/transport/icmp/protocol.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// Package ping contains the implementation of the ICMP and IPv6-ICMP transport\n+// Package icmp contains the implementation of the ICMP and IPv6-ICMP transport\n// protocols for use in ping. To use it in the networking stack, this package\n// must be added to the project, and\n-// activated on the stack by passing ping.ProtocolName (or \"ping\") and/or\n-// ping.ProtocolName6 (or \"ping6\") as one of the transport protocols when\n+// activated on the stack by passing icmp.ProtocolName (or \"icmp\") and/or\n+// icmp.ProtocolName6 (or \"icmp6\") as one of the transport protocols when\n// calling stack.New(). Then endpoints can be created by passing\n-// ping.ProtocolNumber or ping.ProtocolNumber6 as the transport protocol number\n+// icmp.ProtocolNumber or icmp.ProtocolNumber6 as the transport protocol number\n// when calling Stack.NewEndpoint().\n-package ping\n+package icmp\nimport (\n\"encoding/binary\"\n@@ -34,14 +34,14 @@ import (\n)\nconst (\n- // ProtocolName4 is the string representation of the ping protocol name.\n- ProtocolName4 = \"ping4\"\n+ // ProtocolName4 is the string representation of the icmp protocol name.\n+ ProtocolName4 = \"icmp4\"\n// ProtocolNumber4 is the ICMP protocol number.\nProtocolNumber4 = header.ICMPv4ProtocolNumber\n- // ProtocolName6 is the string representation of the ping protocol name.\n- ProtocolName6 = \"ping6\"\n+ // ProtocolName6 is the string representation of the icmp protocol name.\n+ ProtocolName6 = \"icmp6\"\n// ProtocolNumber6 is the IPv6-ICMP protocol number.\nProtocolNumber6 = header.ICMPv6ProtocolNumber\n@@ -66,7 +66,7 @@ func (p *protocol) netProto() tcpip.NetworkProtocolNumber {\npanic(fmt.Sprint(\"unknown protocol number: \", p.number))\n}\n-// NewEndpoint creates a new ping endpoint.\n+// NewEndpoint creates a new icmp endpoint.\nfunc (p *protocol) NewEndpoint(stack *stack.Stack, netProto tcpip.NetworkProtocolNumber, waiterQueue *waiter.Queue) (tcpip.Endpoint, *tcpip.Error) {\nif netProto != p.netProto() {\nreturn nil, tcpip.ErrUnknownProtocol\n@@ -74,7 +74,7 @@ func (p *protocol) NewEndpoint(stack *stack.Stack, netProto tcpip.NetworkProtoco\nreturn newEndpoint(stack, netProto, p.number, waiterQueue), nil\n}\n-// MinimumPacketSize returns the minimum valid ping packet size.\n+// MinimumPacketSize returns the minimum valid icmp packet size.\nfunc (p *protocol) MinimumPacketSize() int {\nswitch p.number {\ncase ProtocolNumber4:\n@@ -85,7 +85,7 @@ func (p *protocol) MinimumPacketSize() int {\npanic(fmt.Sprint(\"unknown protocol number: \", p.number))\n}\n-// ParsePorts returns the source and destination ports stored in the given ping\n+// ParsePorts returns the source and destination ports stored in the given icmp\n// packet.\nfunc (p *protocol) ParsePorts(v buffer.View) (src, dst uint16, err *tcpip.Error) {\nswitch p.number {\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/BUILD", "new_path": "runsc/boot/BUILD", "diff": "@@ -75,7 +75,7 @@ go_library(\n\"//pkg/tcpip/network/ipv4\",\n\"//pkg/tcpip/network/ipv6\",\n\"//pkg/tcpip/stack\",\n- \"//pkg/tcpip/transport/ping\",\n+ \"//pkg/tcpip/transport/icmp\",\n\"//pkg/tcpip/transport/tcp\",\n\"//pkg/tcpip/transport/udp\",\n\"//pkg/urpc\",\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/loader.go", "new_path": "runsc/boot/loader.go", "diff": "@@ -51,7 +51,7 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/tcpip/network/ipv4\"\n\"gvisor.googlesource.com/gvisor/pkg/tcpip/network/ipv6\"\n\"gvisor.googlesource.com/gvisor/pkg/tcpip/stack\"\n- \"gvisor.googlesource.com/gvisor/pkg/tcpip/transport/ping\"\n+ \"gvisor.googlesource.com/gvisor/pkg/tcpip/transport/icmp\"\n\"gvisor.googlesource.com/gvisor/pkg/tcpip/transport/tcp\"\n\"gvisor.googlesource.com/gvisor/pkg/tcpip/transport/udp\"\n\"gvisor.googlesource.com/gvisor/runsc/boot/filter\"\n@@ -766,7 +766,7 @@ func newEmptyNetworkStack(conf *Config, clock tcpip.Clock) (inet.Stack, error) {\ncase NetworkNone, NetworkSandbox:\n// NetworkNone sets up loopback using netstack.\nnetProtos := []string{ipv4.ProtocolName, ipv6.ProtocolName, arp.ProtocolName}\n- protoNames := []string{tcp.ProtocolName, udp.ProtocolName, ping.ProtocolName4}\n+ protoNames := []string{tcp.ProtocolName, udp.ProtocolName, icmp.ProtocolName4}\ns := epsocket.Stack{stack.New(netProtos, protoNames, stack.Options{\nClock: clock,\nStats: epsocket.Metrics,\n" } ]
Go
Apache License 2.0
google/gvisor
Rename ping endpoints to icmp endpoints. PiperOrigin-RevId: 235248572 Change-Id: I5b0538b6feb365a98712c2a2d56d856fe80a8a09
259,933
25.02.2019 10:01:25
28,800
c14a1a161869804af5ae2f1f73fd8eeb135ff043
Fix race condition in NIC.DeliverNetworkPacket cl/234850781 introduced a race condition in NIC.DeliverNetworkPacket by failing to hold a lock. This change fixes this regressesion by acquiring a read lock before iterating through n.endpoints, and then releasing the lock once iteration is complete.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -403,14 +403,19 @@ func (n *NIC) DeliverNetworkPacket(linkEP LinkEndpoint, remote, _ tcpip.LinkAddr\n// route to each IPv4 network endpoint and let each endpoint handle the\n// packet.\nif dst == header.IPv4Broadcast {\n+ // n.endpoints is mutex protected so acquire lock.\n+ n.mu.RLock()\nfor _, ref := range n.endpoints {\n+ n.mu.RUnlock()\nif ref.protocol == header.IPv4ProtocolNumber && ref.tryIncRef() {\nr := makeRoute(protocol, dst, src, linkEP.LinkAddress(), ref)\nr.RemoteLinkAddress = remote\nref.ep.HandlePacket(&r, vv)\nref.decRef()\n}\n+ n.mu.RLock()\n}\n+ n.mu.RUnlock()\nreturn\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix race condition in NIC.DeliverNetworkPacket cl/234850781 introduced a race condition in NIC.DeliverNetworkPacket by failing to hold a lock. This change fixes this regressesion by acquiring a read lock before iterating through n.endpoints, and then releasing the lock once iteration is complete. PiperOrigin-RevId: 235549770 Change-Id: Ib0133288be512d478cf759c3314dc95ec3205d4b
259,992
25.02.2019 12:16:44
28,800
10426e0f31e427e90e69fee83f199ea521b8fe3d
Handle invalid offset in sendfile(2)
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_file.go", "new_path": "pkg/sentry/syscalls/linux/sys_file.go", "diff": "@@ -2022,7 +2022,6 @@ func Sendfile(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\n}\n// Setup for sending data.\n- var offset uint64\nvar n int64\nvar err error\nw := &fs.FileWriter{t, outFile}\n@@ -2034,14 +2033,18 @@ func Sendfile(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\nreturn 0, nil, syserror.ESPIPE\n}\n// Copy in the offset.\n+ var offset int64\nif _, err := t.CopyIn(offsetAddr, &offset); err != nil {\nreturn 0, nil, err\n}\n+ if offset < 0 {\n+ return 0, nil, syserror.EINVAL\n+ }\n// Send data using Preadv.\n- r := io.NewSectionReader(&fs.FileReader{t, inFile}, int64(offset), count)\n+ r := io.NewSectionReader(&fs.FileReader{t, inFile}, offset, count)\nn, err = io.Copy(w, r)\n// Copy out the new offset.\n- if _, err := t.CopyOut(offsetAddr, n+int64(offset)); err != nil {\n+ if _, err := t.CopyOut(offsetAddr, n+offset); err != nil {\nreturn 0, nil, err\n}\n// If we don't have a provided offset.\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/sendfile.cc", "new_path": "test/syscalls/linux/sendfile.cc", "diff": "@@ -46,6 +46,25 @@ TEST(SendFileTest, SendZeroBytes) {\nSyscallSucceedsWithValue(0));\n}\n+TEST(SendFileTest, InvalidOffset) {\n+ // Create temp files.\n+ const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n+ const TempPath out_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n+\n+ // Open the input file as read only.\n+ const FileDescriptor inf =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDONLY));\n+\n+ // Open the output file as write only.\n+ const FileDescriptor outf =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(out_file.path(), O_WRONLY));\n+\n+ // Send data and verify that sendfile returns the correct value.\n+ off_t offset = -1;\n+ EXPECT_THAT(sendfile(outf.get(), inf.get(), &offset, 0),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\nTEST(SendFileTest, SendTrivially) {\n// Create temp files.\nconstexpr char kData[] = \"To be, or not to be, that is the question:\";\n" } ]
Go
Apache License 2.0
google/gvisor
Handle invalid offset in sendfile(2) PiperOrigin-RevId: 235578698 Change-Id: I608ff5e25eac97f6e1bda058511c1f82b0e3b736
259,885
25.02.2019 13:02:56
28,800
41167e6c508240a127f96bfa519b909c16ee0933
Don't call WalkGetAttr for walk(names=[]).
[ { "change_type": "MODIFY", "old_path": "pkg/p9/handlers.go", "new_path": "pkg/p9/handlers.go", "diff": "@@ -237,7 +237,7 @@ func (t *Tattach) handle(cs *connState) message {\n// We want the same traversal checks to apply on attach, so always\n// attach at the root and use the regular walk paths.\nnames := strings.Split(t.Auth.AttachName, \"/\")\n- _, newRef, _, attr, err := doWalk(cs, root, names)\n+ _, newRef, _, _, err := doWalk(cs, root, names, false)\nif err != nil {\nreturn newErr(err)\n}\n@@ -996,26 +996,40 @@ func (t *Tflushf) handle(cs *connState) message {\n// walkOne walks zero or one path elements.\n//\n// The slice passed as qids is append and returned.\n-func walkOne(qids []QID, from File, names []string) ([]QID, File, AttrMask, Attr, error) {\n+func walkOne(qids []QID, from File, names []string, getattr bool) ([]QID, File, AttrMask, Attr, error) {\nif len(names) > 1 {\n// We require exactly zero or one elements.\nreturn nil, nil, AttrMask{}, Attr{}, syscall.EINVAL\n}\n- var localQIDs []QID\n- localQIDs, sf, valid, attr, err := from.WalkGetAttr(names)\n- if err == syscall.ENOSYS {\n+ var (\n+ localQIDs []QID\n+ sf File\n+ valid AttrMask\n+ attr Attr\n+ err error\n+ )\n+ switch {\n+ case getattr:\n+ localQIDs, sf, valid, attr, err = from.WalkGetAttr(names)\n+ // Can't put fallthrough in the if because Go.\n+ if err != syscall.ENOSYS {\n+ break\n+ }\n+ fallthrough\n+ default:\nlocalQIDs, sf, err = from.Walk(names)\nif err != nil {\n// No way to walk this element.\n- return nil, nil, AttrMask{}, Attr{}, err\n+ break\n}\n- // Need a manual getattr.\n+ if getattr {\n_, valid, attr, err = sf.GetAttr(AttrMaskAll())\nif err != nil {\n// Don't leak the file.\nsf.Close()\n}\n}\n+ }\nif err != nil {\n// Error walking, don't return anything.\nreturn nil, nil, AttrMask{}, Attr{}, err\n@@ -1033,7 +1047,7 @@ func walkOne(qids []QID, from File, names []string) ([]QID, File, AttrMask, Attr\n// This enforces that all intermediate nodes are walkable (directories). The\n// fidRef returned (newRef) has a reference associated with it that is now\n// owned by the caller and must be handled appropriately.\n-func doWalk(cs *connState, ref *fidRef, names []string) (qids []QID, newRef *fidRef, valid AttrMask, attr Attr, err error) {\n+func doWalk(cs *connState, ref *fidRef, names []string, getattr bool) (qids []QID, newRef *fidRef, valid AttrMask, attr Attr, err error) {\n// Check the names.\nfor _, name := range names {\nerr = checkSafeName(name)\n@@ -1054,7 +1068,7 @@ func doWalk(cs *connState, ref *fidRef, names []string) (qids []QID, newRef *fid\nvar sf File // Temporary.\nif err := ref.maybeParent().safelyRead(func() (err error) {\n// Clone the single element.\n- qids, sf, valid, attr, err = walkOne(nil, ref.file, nil)\n+ qids, sf, valid, attr, err = walkOne(nil, ref.file, nil, getattr)\nif err != nil {\nreturn err\n}\n@@ -1101,7 +1115,9 @@ func doWalk(cs *connState, ref *fidRef, names []string) (qids []QID, newRef *fid\nvar sf File // Temporary.\nif err := walkRef.safelyRead(func() (err error) {\n- qids, sf, valid, attr, err = walkOne(qids, walkRef.file, names[i:i+1])\n+ // Pass getattr = true to walkOne since we need the file type for\n+ // newRef.\n+ qids, sf, valid, attr, err = walkOne(qids, walkRef.file, names[i:i+1], true)\nif err != nil {\nreturn err\n}\n@@ -1146,7 +1162,7 @@ func (t *Twalk) handle(cs *connState) message {\ndefer ref.DecRef()\n// Do the walk.\n- qids, newRef, _, _, err := doWalk(cs, ref, t.Names)\n+ qids, newRef, _, _, err := doWalk(cs, ref, t.Names, false)\nif err != nil {\nreturn newErr(err)\n}\n@@ -1167,7 +1183,7 @@ func (t *Twalkgetattr) handle(cs *connState) message {\ndefer ref.DecRef()\n// Do the walk.\n- qids, newRef, valid, attr, err := doWalk(cs, ref, t.Names)\n+ qids, newRef, valid, attr, err := doWalk(cs, ref, t.Names, true)\nif err != nil {\nreturn newErr(err)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Don't call WalkGetAttr for walk(names=[]). PiperOrigin-RevId: 235587729 Change-Id: I37074416b10a30ca3a00d11bcde338d8d979beaf
259,992
25.02.2019 19:20:52
28,800
52a2abfca43cffdb9cafb91a4266dacf51525470
Fix cgroup when path is relative This can happen when 'docker run --cgroup-parent=' flag is set.
[ { "change_type": "MODIFY", "old_path": "runsc/cgroup/cgroup.go", "new_path": "runsc/cgroup/cgroup.go", "diff": "@@ -161,20 +161,59 @@ func countCpuset(cpuset string) (int, error) {\nreturn count, nil\n}\n+// LoadPaths loads cgroup paths for given 'pid', may be set to 'self'.\n+func LoadPaths(pid string) (map[string]string, error) {\n+ f, err := os.Open(filepath.Join(\"/proc\", pid, \"cgroup\"))\n+ if err != nil {\n+ return nil, err\n+ }\n+ defer f.Close()\n+\n+ paths := make(map[string]string)\n+ scanner := bufio.NewScanner(f)\n+ for scanner.Scan() {\n+ // Format: ID:controller1,controller2:path\n+ // Example: 2:cpu,cpuacct:/user.slice\n+ tokens := strings.Split(scanner.Text(), \":\")\n+ if len(tokens) != 3 {\n+ return nil, fmt.Errorf(\"invalid cgroups file, line: %q\", scanner.Text())\n+ }\n+ for _, ctrlr := range strings.Split(tokens[1], \",\") {\n+ paths[ctrlr] = tokens[2]\n+ }\n+ }\n+ if err := scanner.Err(); err != nil {\n+ return nil, err\n+ }\n+ return paths, nil\n+}\n+\n// Cgroup represents a group inside all controllers. For example: Name='/foo/bar'\n// maps to /sys/fs/cgroup/<controller>/foo/bar on all controllers.\ntype Cgroup struct {\nName string `json:\"name\"`\n+ Parents map[string]string `json:\"parents\"`\nOwn bool `json:\"own\"`\n}\n// New creates a new Cgroup instance if the spec includes a cgroup path.\n// Returns nil otherwise.\n-func New(spec *specs.Spec) *Cgroup {\n+func New(spec *specs.Spec) (*Cgroup, error) {\nif spec.Linux == nil || spec.Linux.CgroupsPath == \"\" {\n- return nil\n+ return nil, nil\n+ }\n+ var parents map[string]string\n+ if !filepath.IsAbs(spec.Linux.CgroupsPath) {\n+ var err error\n+ parents, err = LoadPaths(\"self\")\n+ if err != nil {\n+ return nil, fmt.Errorf(\"finding current cgroups: %v\", err)\n}\n- return &Cgroup{Name: spec.Linux.CgroupsPath}\n+ }\n+ return &Cgroup{\n+ Name: spec.Linux.CgroupsPath,\n+ Parents: parents,\n+ }, nil\n}\n// Install creates and configures cgroups according to 'res'. If cgroup path\n@@ -188,9 +227,11 @@ func (c *Cgroup) Install(res *specs.LinuxResources) error {\nreturn nil\n}\n- // Mark that cgroup resources are owned by me.\nlog.Debugf(\"Creating cgroup %q\", c.Name)\n+\n+ // Mark that cgroup resources are owned by me.\nc.Own = true\n+\n// The Cleanup object cleans up partially created cgroups when an error occurs.\n// Errors occuring during cleanup itself are ignored.\nclean := specutils.MakeCleanup(func() { _ = c.Uninstall() })\n@@ -247,32 +288,19 @@ func (c *Cgroup) Uninstall() error {\nfunc (c *Cgroup) Join() (func(), error) {\n// First save the current state so it can be restored.\nundo := func() {}\n- f, err := os.Open(\"/proc/self/cgroup\")\n+ paths, err := LoadPaths(\"self\")\nif err != nil {\nreturn undo, err\n}\n- defer f.Close()\n-\nvar undoPaths []string\n- scanner := bufio.NewScanner(f)\n- for scanner.Scan() {\n- // Format: ID:controller1,controller2:path\n- // Example: 2:cpu,cpuacct:/user.slice\n- tokens := strings.Split(scanner.Text(), \":\")\n- if len(tokens) != 3 {\n- return undo, fmt.Errorf(\"formatting cgroups file, line: %q\", scanner.Text())\n- }\n- for _, ctrlr := range strings.Split(tokens[1], \",\") {\n+ for ctrlr, path := range paths {\n// Skip controllers we don't handle.\nif _, ok := controllers[ctrlr]; ok {\n- undoPaths = append(undoPaths, filepath.Join(cgroupRoot, ctrlr, tokens[2]))\n+ fullPath := filepath.Join(cgroupRoot, ctrlr, path)\n+ undoPaths = append(undoPaths, fullPath)\nbreak\n}\n}\n- }\n- if err := scanner.Err(); err != nil {\n- return undo, err\n- }\n// Replace empty undo with the real thing before changes are made to cgroups.\nundo = func() {\n@@ -316,7 +344,11 @@ func (c *Cgroup) MemoryLimit() (uint64, error) {\n}\nfunc (c *Cgroup) makePath(controllerName string) string {\n- return filepath.Join(cgroupRoot, controllerName, c.Name)\n+ path := c.Name\n+ if parent, ok := c.Parents[controllerName]; ok {\n+ path = filepath.Join(parent, c.Name)\n+ }\n+ return filepath.Join(cgroupRoot, controllerName, path)\n}\ntype controller interface {\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/container.go", "new_path": "runsc/container/container.go", "diff": "@@ -295,7 +295,10 @@ func Create(id string, spec *specs.Spec, conf *boot.Config, bundleDir, consoleSo\n// Create and join cgroup before processes are created to ensure they are\n// part of the cgroup from the start (and all tneir children processes).\n- cg := cgroup.New(spec)\n+ cg, err := cgroup.New(spec)\n+ if err != nil {\n+ return nil, err\n+ }\nif cg != nil {\n// If there is cgroup config, install it before creating sandbox process.\nif err := cg.Install(spec.Linux.Resources); err != nil {\n" }, { "change_type": "MODIFY", "old_path": "runsc/test/root/BUILD", "new_path": "runsc/test/root/BUILD", "diff": "@@ -24,6 +24,7 @@ go_test(\n\"local\",\n],\ndeps = [\n+ \"//runsc/cgroup\",\n\"//runsc/specutils\",\n\"//runsc/test/root/testdata\",\n\"//runsc/test/testutil\",\n" }, { "change_type": "MODIFY", "old_path": "runsc/test/root/cgroup_test.go", "new_path": "runsc/test/root/cgroup_test.go", "diff": "package root\nimport (\n+ \"bufio\"\n+ \"fmt\"\n\"io/ioutil\"\n\"os\"\n+ \"os/exec\"\n\"path/filepath\"\n\"strconv\"\n\"strings\"\n\"testing\"\n+ \"gvisor.googlesource.com/gvisor/runsc/cgroup\"\n\"gvisor.googlesource.com/gvisor/runsc/test/testutil\"\n)\n+func verifyPid(pid int, path string) error {\n+ f, err := os.Open(path)\n+ if err != nil {\n+ return err\n+ }\n+ defer f.Close()\n+\n+ var gots []int\n+ scanner := bufio.NewScanner(f)\n+ for scanner.Scan() {\n+ got, err := strconv.Atoi(scanner.Text())\n+ if err != nil {\n+ return err\n+ }\n+ if got == pid {\n+ return nil\n+ }\n+ gots = append(gots, got)\n+ }\n+ if scanner.Err() != nil {\n+ return scanner.Err()\n+ }\n+ return fmt.Errorf(\"got: %s, want: %d\", gots, pid)\n+}\n+\n// TestCgroup sets cgroup options and checks that cgroup was properly configured.\nfunc TestCgroup(t *testing.T) {\nif err := testutil.Pull(\"alpine\"); err != nil {\n@@ -161,12 +190,48 @@ func TestCgroup(t *testing.T) {\n}\nfor _, ctrl := range controllers {\npath := filepath.Join(\"/sys/fs/cgroup\", ctrl, \"docker\", gid, \"cgroup.procs\")\n- out, err := ioutil.ReadFile(path)\n+ if err := verifyPid(pid, path); err != nil {\n+ t.Errorf(\"cgroup control %q processes: %v\", ctrl, err)\n+ }\n+ }\n+}\n+\n+func TestCgroupParent(t *testing.T) {\n+ if err := testutil.Pull(\"alpine\"); err != nil {\n+ t.Fatal(\"docker pull failed:\", err)\n+ }\n+ d := testutil.MakeDocker(\"cgroup-test\")\n+\n+ parent := testutil.RandomName(\"runsc\")\n+ if err := d.Run(\"--cgroup-parent\", parent, \"alpine\", \"sleep\", \"10000\"); err != nil {\n+ t.Fatal(\"docker create failed:\", err)\n+ }\n+ defer d.CleanUp()\n+ gid, err := d.ID()\nif err != nil {\n- t.Fatalf(\"failed to read %q: %v\", path, err)\n+ t.Fatalf(\"Docker.ID() failed: %v\", err)\n+ }\n+ t.Logf(\"cgroup ID: %s\", gid)\n+\n+ // Check that sandbox is inside cgroup.\n+ pid, err := d.SandboxPid()\n+ if err != nil {\n+ t.Fatalf(\"SandboxPid: %v\", err)\n}\n- if got := string(out); !strings.Contains(got, strconv.Itoa(pid)) {\n- t.Errorf(\"cgroup control %s processes, got: %q, want: %q\", ctrl, got, pid)\n+\n+ // Finds cgroup for the sandbox's parent process to check that cgroup is\n+ // created in the right location relative to the parent.\n+ cmd := fmt.Sprintf(\"grep PPid: /proc/%d/status | sed 's/PPid:\\\\s//'\", pid)\n+ ppid, err := exec.Command(\"bash\", \"-c\", cmd).CombinedOutput()\n+ if err != nil {\n+ t.Fatalf(\"Executing %q: %v\", cmd, err)\n+ }\n+ cgroups, err := cgroup.LoadPaths(strings.TrimSpace(string(ppid)))\n+ if err != nil {\n+ t.Fatalf(\"cgroup.LoadPath(%s): %v\", ppid, err)\n}\n+ path := filepath.Join(\"/sys/fs/cgroup/memory\", cgroups[\"memory\"], parent, gid, \"cgroup.procs\")\n+ if err := verifyPid(pid, path); err != nil {\n+ t.Errorf(\"cgroup control %q processes: %v\", \"memory\", err)\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/test/testutil/docker.go", "new_path": "runsc/test/testutil/docker.go", "diff": "@@ -18,7 +18,6 @@ import (\n\"fmt\"\n\"io/ioutil\"\n\"log\"\n- \"math/rand\"\n\"os\"\n\"os/exec\"\n\"path\"\n@@ -31,10 +30,6 @@ import (\n\"github.com/kr/pty\"\n)\n-func init() {\n- rand.Seed(time.Now().UnixNano())\n-}\n-\nfunc getRuntime() string {\nr := os.Getenv(\"RUNSC_RUNTIME\")\nif r == \"\" {\n@@ -162,8 +157,7 @@ type Docker struct {\n// MakeDocker sets up the struct for a Docker container.\n// Names of containers will be unique.\nfunc MakeDocker(namePrefix string) Docker {\n- suffix := fmt.Sprintf(\"-%06d\", rand.Int())[:7]\n- return Docker{Name: namePrefix + suffix, Runtime: getRuntime()}\n+ return Docker{Name: RandomName(namePrefix), Runtime: getRuntime()}\n}\n// Create calls 'docker create' with the arguments provided.\n" }, { "change_type": "MODIFY", "old_path": "runsc/test/testutil/testutil.go", "new_path": "runsc/test/testutil/testutil.go", "diff": "@@ -461,3 +461,8 @@ func WriteTmpFile(pattern, text string) (string, error) {\n}\nreturn file.Name(), nil\n}\n+\n+// RandomName create a name with a 6 digit random number appended to it.\n+func RandomName(prefix string) string {\n+ return fmt.Sprintf(\"%s-%06d\", prefix, rand.Int31n(1000000))\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix cgroup when path is relative This can happen when 'docker run --cgroup-parent=' flag is set. PiperOrigin-RevId: 235645559 Change-Id: Ieea3ae66939abadab621053551bf7d62d412e7ee
259,992
26.02.2019 09:32:20
28,800
23fe059761a470d7724b462ad8ead09356ec21b7
Lazily allocate inotify map on inode
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/inode_inotify.go", "new_path": "pkg/sentry/fs/inode_inotify.go", "diff": "@@ -39,9 +39,7 @@ type Watches struct {\n}\nfunc newWatches() *Watches {\n- return &Watches{\n- ws: make(map[uint64]*Watch),\n- }\n+ return &Watches{}\n}\n// MarkUnlinked indicates the target for this set of watches to be unlinked.\n@@ -78,6 +76,9 @@ func (w *Watches) Add(watch *Watch) {\nif _, exists := w.ws[watch.ID()]; exists {\npanic(fmt.Sprintf(\"Watch collision with ID %+v\", watch.ID()))\n}\n+ if w.ws == nil {\n+ w.ws = make(map[uint64]*Watch)\n+ }\nw.ws[watch.ID()] = watch\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Lazily allocate inotify map on inode PiperOrigin-RevId: 235735865 Change-Id: I84223eb18eb51da1fa9768feaae80387ff6bfed0
259,940
26.02.2019 11:47:42
28,800
a2b794b30dd952793f4d99a9423cef7efdc7843f
FPE_INTOVF (integer overflow) should be 2 refer to Linux.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/machine_amd64.go", "new_path": "pkg/sentry/platform/kvm/machine_amd64.go", "diff": "@@ -290,7 +290,7 @@ func (c *vCPU) SwitchToUser(switchOpts ring0.SwitchOpts, info *arch.SignalInfo)\ncase ring0.Overflow:\n*info = arch.SignalInfo{\nSigno: int32(syscall.SIGFPE),\n- Code: 1, // FPE_INTOVF (integer overflow).\n+ Code: 2, // FPE_INTOVF (integer overflow).\n}\ninfo.SetAddr(switchOpts.Registers.Rip) // Include address.\nreturn usermem.AccessType{}, platform.ErrContextSignal\n" } ]
Go
Apache License 2.0
google/gvisor
FPE_INTOVF (integer overflow) should be 2 refer to Linux. Signed-off-by: Ruidong Cao <[email protected]> Change-Id: I03f8ab25cf29257b31f145cf43304525a93f3300 PiperOrigin-RevId: 235763203
260,013
26.02.2019 15:46:39
28,800
aeb7283a9106319db598a908708e80875fcb5c3d
Improve PosixErrorOr messages using gtest matchers. There was a minor bug whth IsPosixErrorOkAndHoldsMatcher where it wouldn't display the actual value contained. This fixes that and adds a few other minor improvements.
[ { "change_type": "MODIFY", "old_path": "test/util/posix_error.cc", "new_path": "test/util/posix_error.cc", "diff": "@@ -74,15 +74,10 @@ bool PosixErrorIsMatcherCommonImpl::MatchAndExplain(\ninner_listener.Clear();\nif (!code_matcher_.MatchAndExplain(error.errno_value(), &inner_listener)) {\n- *result_listener << (inner_listener.str().empty()\n- ? \"whose errno value is wrong\"\n- : \"which has a errno value \" +\n- inner_listener.str());\nreturn false;\n}\nif (!message_matcher_.Matches(error.error_message())) {\n- *result_listener << \"whose error message is wrong\";\nreturn false;\n}\n" }, { "change_type": "MODIFY", "old_path": "test/util/posix_error.h", "new_path": "test/util/posix_error.h", "diff": "@@ -74,6 +74,7 @@ class ABSL_MUST_USE_RESULT PosixError {\ntemplate <typename T>\nclass ABSL_MUST_USE_RESULT PosixErrorOr {\npublic:\n+ // A PosixErrorOr will check fail if it is constructed with NoError().\nPosixErrorOr(const PosixError& error);\nPosixErrorOr(const T& value);\nPosixErrorOr(T&& value);\n@@ -99,7 +100,7 @@ class ABSL_MUST_USE_RESULT PosixErrorOr {\n// Returns this->error().error_message();\nconst std::string error_message() const;\n- // Returns this->error().ok()\n+ // Returns true if this PosixErrorOr contains some T.\nbool ok() const;\n// Returns a reference to our current value, or CHECK-fails if !this->ok().\n@@ -121,7 +122,11 @@ class ABSL_MUST_USE_RESULT PosixErrorOr {\n};\ntemplate <typename T>\n-PosixErrorOr<T>::PosixErrorOr(const PosixError& error) : value_(error) {}\n+PosixErrorOr<T>::PosixErrorOr(const PosixError& error) : value_(error) {\n+ TEST_CHECK_MSG(\n+ !error.ok(),\n+ \"Constructing PosixErrorOr with NoError, eg. errno 0 is not allowed.\");\n+}\ntemplate <typename T>\nPosixErrorOr<T>::PosixErrorOr(const T& value) : value_(value) {}\n@@ -177,7 +182,7 @@ const std::string PosixErrorOr<T>::error_message() const {\ntemplate <typename T>\nbool PosixErrorOr<T>::ok() const {\n- return error().ok();\n+ return absl::holds_alternative<T>(value_);\n}\ntemplate <typename T>\n@@ -265,8 +270,8 @@ class IsPosixErrorOkAndHoldsMatcherImpl\nbool MatchAndExplain(\nPosixErrorOrType actual_value,\n::testing::MatchResultListener* listener) const override {\n+ // We can't extract the value if it doesn't contain one.\nif (!actual_value.ok()) {\n- *listener << \"which has error value \" << actual_value.error();\nreturn false;\n}\n@@ -274,10 +279,11 @@ class IsPosixErrorOkAndHoldsMatcherImpl\nconst bool matches = inner_matcher_.MatchAndExplain(\nactual_value.ValueOrDie(), &inner_listener);\nconst std::string inner_explanation = inner_listener.str();\n+ *listener << \"has a value \"\n+ << ::testing::PrintToString(actual_value.ValueOrDie());\n+\nif (!inner_explanation.empty()) {\n- *listener << \"which contains value \"\n- << ::testing::PrintToString(actual_value.ValueOrDie()) << \", \"\n- << inner_explanation;\n+ *listener << \" \" << inner_explanation;\n}\nreturn matches;\n}\n@@ -325,6 +331,18 @@ class PosixErrorIsMatcherCommonImpl {\nbool MatchAndExplain(const PosixError& error,\n::testing::MatchResultListener* result_listener) const;\n+ template <typename T>\n+ bool MatchAndExplain(const PosixErrorOr<T>& error_or,\n+ ::testing::MatchResultListener* result_listener) const {\n+ if (error_or.ok()) {\n+ *result_listener << \"has a value \"\n+ << ::testing::PrintToString(error_or.ValueOrDie());\n+ return false;\n+ }\n+\n+ return MatchAndExplain(error_or.error(), result_listener);\n+ }\n+\nprivate:\nconst ::testing::Matcher<int> code_matcher_;\nconst ::testing::Matcher<const std::string&> message_matcher_;\n@@ -350,7 +368,7 @@ class MonoPosixErrorIsMatcherImpl : public ::testing::MatcherInterface<T> {\nbool MatchAndExplain(\nT actual_value,\n::testing::MatchResultListener* result_listener) const override {\n- return common_impl_.MatchAndExplain(actual_value.error(), result_listener);\n+ return common_impl_.MatchAndExplain(actual_value, result_listener);\n}\nprivate:\n" }, { "change_type": "MODIFY", "old_path": "test/util/posix_error_test.cc", "new_path": "test/util/posix_error_test.cc", "diff": "@@ -35,7 +35,7 @@ TEST(PosixErrorTest, PosixErrorOrPosixError) {\nTEST(PosixErrorTest, PosixErrorOrNullptr) {\nauto err = PosixErrorOr<std::nullptr_t>(nullptr);\n- EXPECT_THAT(err, PosixErrorIs(0, \"\"));\n+ EXPECT_TRUE(err.ok());\nEXPECT_NO_ERRNO(err);\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Improve PosixErrorOr messages using gtest matchers. There was a minor bug whth IsPosixErrorOkAndHoldsMatcher where it wouldn't display the actual value contained. This fixes that and adds a few other minor improvements. PiperOrigin-RevId: 235809065 Change-Id: I487e5072e9569eb06104522963e9a1b34204daaf
259,992
27.02.2019 10:05:46
28,800
6df212b831dcc3350b7677423ec7835ed40b3f22
Don't log twice to debug log when --log isn't set
[ { "change_type": "MODIFY", "old_path": "runsc/main.go", "new_path": "runsc/main.go", "diff": "@@ -192,7 +192,13 @@ func main() {\ncmd.Fatalf(\"error dup'ing fd %d to stderr: %v\", f.Fd(), err)\n}\n+ if logFile == os.Stderr {\n+ // Suppress logging to stderr when debug log is enabled. Otherwise all\n+ // messages will be duplicated in the debug log (see Dup2() call above).\n+ e = newEmitter(*debugLogFormat, f)\n+ } else {\ne = log.MultiEmitter{e, newEmitter(*debugLogFormat, f)}\n+ }\n} else if *debugLog != \"\" {\nf, err := specutils.DebugLogFile(*debugLog, subcommand)\nif err != nil {\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/syscall_test_runner.go", "new_path": "test/syscalls/syscall_test_runner.go", "diff": "@@ -202,6 +202,11 @@ func runTestCaseRunsc(testBin string, tc gtest.TestCase, t *testing.T) {\ndebugLogDir += \"/\"\nlog.Infof(\"runsc logs: %s\", debugLogDir)\nargs = append(args, \"-debug-log\", debugLogDir)\n+\n+ // Default -log sends messages to stderr which makes reading the test log\n+ // difficult. Instead, drop them when debug log is enabled given it's a\n+ // better place for these messages.\n+ args = append(args, \"-log=/dev/null\")\n}\n// Current process doesn't have CAP_SYS_ADMIN, create user namespace and run\n" } ]
Go
Apache License 2.0
google/gvisor
Don't log twice to debug log when --log isn't set PiperOrigin-RevId: 235940853 Change-Id: I9c5b4cf18b199fb74044a5edb131bfff59dec945
259,885
28.02.2019 13:13:38
28,800
05d721f9eec3ad0a430906b968a2876bf37c44a7
Hold dataMu for writing in CachingInodeOperations.WriteOut. fsutil.SyncDirtyAll mutates the DirtySet.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/fsutil/inode_cached.go", "new_path": "pkg/sentry/fs/fsutil/inode_cached.go", "diff": "@@ -322,9 +322,9 @@ func (c *CachingInodeOperations) WriteOut(ctx context.Context, inode *fs.Inode)\nc.attrMu.Lock()\n// Write dirty pages back.\n- c.dataMu.RLock()\n+ c.dataMu.Lock()\nerr := SyncDirtyAll(ctx, &c.cache, &c.dirty, uint64(c.attr.Size), c.platform.Memory(), c.backingFile.WriteFromBlocksAt)\n- c.dataMu.RUnlock()\n+ c.dataMu.Unlock()\nif err != nil {\nc.attrMu.Unlock()\nreturn err\n" } ]
Go
Apache License 2.0
google/gvisor
Hold dataMu for writing in CachingInodeOperations.WriteOut. fsutil.SyncDirtyAll mutates the DirtySet. PiperOrigin-RevId: 236183349 Change-Id: I7e809d5b406ac843407e61eff17d81259a819b4f
259,992
28.02.2019 18:37:34
28,800
3b44377eda93137212e6e437b62dcb216566b858
Fix "-c dbg" build break Remove allocation from vCPU.die() to save stack space. Closes
[ { "change_type": "MODIFY", "old_path": "kokoro/run_tests.sh", "new_path": "kokoro/run_tests.sh", "diff": "@@ -71,11 +71,13 @@ BAZEL_BUILD_RBE_FLAGS=(\n####################\nbuild_everything() {\n+ FLAVOR=\"${1}\"\n+\ncd ${WORKSPACE_DIR}\nbazel \\\n\"${BAZEL_RBE_FLAGS[@]}\" \\\nbuild \\\n- \"${BAZEL_BUILD_RBE_FLAGS[@]}\" \\\n+ -c \"${FLAVOR}\" \"${BAZEL_BUILD_RBE_FLAGS[@]}\" \\\n\"${BUILD_PACKAGES[@]}\"\n}\n@@ -217,7 +219,7 @@ main() {\ntrap finish EXIT\n# Build and run the simple tests.\n- build_everything\n+ build_everything opt\nrun_simple_tests\n# So far so good. Install more deps and run the integration tests.\n@@ -228,6 +230,9 @@ main() {\nrun_syscall_tests\n+ # Build other flavors too.\n+ build_everything dbg\n+\n# No need to call \"finish\" here, it will happen at exit.\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/bluepill.go", "new_path": "pkg/sentry/platform/kvm/bluepill.go", "diff": "@@ -49,7 +49,7 @@ var (\n//\n//go:nosplit\nfunc dieHandler(c *vCPU) {\n- throw(c.dieMessage)\n+ throw(c.dieState.message)\n}\n// die is called to set the vCPU up to panic.\n@@ -59,17 +59,16 @@ func dieHandler(c *vCPU) {\n//go:nosplit\nfunc (c *vCPU) die(context *arch.SignalContext64, msg string) {\n// Save the death message, which will be thrown.\n- c.dieMessage = msg\n+ c.dieState.message = msg\n// Reload all registers to have an accurate stack trace when we return\n// to host mode. This means that the stack should be unwound correctly.\n- var guestRegs userRegs\n- if errno := c.getUserRegisters(&guestRegs); errno != 0 {\n+ if errno := c.getUserRegisters(&c.dieState.guestRegs); errno != 0 {\nthrow(msg)\n}\n// Setup the trampoline.\n- dieArchSetup(c, context, &guestRegs)\n+ dieArchSetup(c, context, &c.dieState.guestRegs)\n}\nfunc init() {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/machine.go", "new_path": "pkg/sentry/platform/kvm/machine.go", "diff": "@@ -121,8 +121,16 @@ type vCPU struct {\n// vCPUArchState is the architecture-specific state.\nvCPUArchState\n- // dieMessage is thrown from die.\n- dieMessage string\n+ dieState dieState\n+}\n+\n+type dieState struct {\n+ // message is thrown from die.\n+ message string\n+\n+ // guestRegs is used to store register state during vCPU.die() to prevent\n+ // allocation inside nosplit function.\n+ guestRegs userRegs\n}\n// newVCPU creates a returns a new vCPU.\n" } ]
Go
Apache License 2.0
google/gvisor
Fix "-c dbg" build break Remove allocation from vCPU.die() to save stack space. Closes #131 PiperOrigin-RevId: 236238102 Change-Id: Iafca27a1a3a472d4cb11dcda9a2060e585139d11
259,992
01.03.2019 10:55:22
28,800
3dbd4a16f8ae4da967f69fd93870462d1b3554f5
Add semctl(GETPID) syscall Also added unimplemented notification for semctl(2) commands.
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/sem.go", "new_path": "pkg/abi/linux/sem.go", "diff": "@@ -29,6 +29,7 @@ const (\nconst (\nSEM_STAT = 18\nSEM_INFO = 19\n+ SEM_STAT_ANY = 20\n)\nconst SEM_UNDO = 0x1000\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/semaphore/semaphore.go", "new_path": "pkg/sentry/kernel/semaphore/semaphore.go", "diff": "@@ -92,6 +92,7 @@ type Set struct {\ntype sem struct {\nvalue int16\nwaiters waiterList `state:\"zerovalue\"`\n+ pid int32\n}\n// waiter represents a caller that is waiting for the semaphore value to\n@@ -283,7 +284,7 @@ func (s *Set) Change(ctx context.Context, creds *auth.Credentials, owner fs.File\n}\n// SetVal overrides a semaphore value, waking up waiters as needed.\n-func (s *Set) SetVal(ctx context.Context, num int32, val int16, creds *auth.Credentials) error {\n+func (s *Set) SetVal(ctx context.Context, num int32, val int16, creds *auth.Credentials, pid int32) error {\nif val < 0 || val > valueMax {\nreturn syserror.ERANGE\n}\n@@ -303,15 +304,17 @@ func (s *Set) SetVal(ctx context.Context, num int32, val int16, creds *auth.Cred\n// TODO: Clear undo entries in all processes\nsem.value = val\n+ sem.pid = pid\ns.changeTime = ktime.NowFromContext(ctx)\nsem.wakeWaiters()\nreturn nil\n}\n-// SetValAll overrides all semaphores values, waking up waiters as needed.\n+// SetValAll overrides all semaphores values, waking up waiters as needed. It also\n+// sets semaphore's PID which was fixed in Linux 4.6.\n//\n// 'len(vals)' must be equal to 's.Size()'.\n-func (s *Set) SetValAll(ctx context.Context, vals []uint16, creds *auth.Credentials) error {\n+func (s *Set) SetValAll(ctx context.Context, vals []uint16, creds *auth.Credentials, pid int32) error {\nif len(vals) != s.Size() {\npanic(fmt.Sprintf(\"vals length (%d) different that Set.Size() (%d)\", len(vals), s.Size()))\n}\n@@ -335,6 +338,7 @@ func (s *Set) SetValAll(ctx context.Context, vals []uint16, creds *auth.Credenti\n// TODO: Clear undo entries in all processes\nsem.value = int16(val)\n+ sem.pid = pid\nsem.wakeWaiters()\n}\ns.changeTime = ktime.NowFromContext(ctx)\n@@ -375,12 +379,29 @@ func (s *Set) GetValAll(creds *auth.Credentials) ([]uint16, error) {\nreturn vals, nil\n}\n+// GetPID returns the PID set when performing operations in the semaphore.\n+func (s *Set) GetPID(num int32, creds *auth.Credentials) (int32, 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+ return sem.pid, 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// On failure, it may return an error (retries are hopeless) or it may return\n// a channel that can be waited on before attempting again.\n-func (s *Set) ExecuteOps(ctx context.Context, ops []linux.Sembuf, creds *auth.Credentials) (chan struct{}, int32, error) {\n+func (s *Set) ExecuteOps(ctx context.Context, ops []linux.Sembuf, creds *auth.Credentials, pid int32) (chan struct{}, int32, error) {\ns.mu.Lock()\ndefer s.mu.Unlock()\n@@ -404,14 +425,14 @@ func (s *Set) ExecuteOps(ctx context.Context, ops []linux.Sembuf, creds *auth.Cr\nreturn nil, 0, syserror.EACCES\n}\n- ch, num, err := s.executeOps(ctx, ops)\n+ ch, num, err := s.executeOps(ctx, ops, pid)\nif err != nil {\nreturn nil, 0, err\n}\nreturn ch, num, nil\n}\n-func (s *Set) executeOps(ctx context.Context, ops []linux.Sembuf) (chan struct{}, int32, error) {\n+func (s *Set) executeOps(ctx context.Context, ops []linux.Sembuf, pid int32) (chan struct{}, int32, error) {\n// Changes to semaphores go to this slice temporarily until they all succeed.\ntmpVals := make([]int16, len(s.sems))\nfor i := range s.sems {\n@@ -464,6 +485,7 @@ func (s *Set) executeOps(ctx context.Context, ops []linux.Sembuf) (chan struct{}\nfor i, v := range tmpVals {\ns.sems[i].value = v\ns.sems[i].wakeWaiters()\n+ s.sems[i].pid = pid\n}\ns.opTime = ktime.NowFromContext(ctx)\nreturn nil, 0, nil\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/semaphore/semaphore_test.go", "new_path": "pkg/sentry/kernel/semaphore/semaphore_test.go", "diff": "@@ -25,7 +25,7 @@ import (\n)\nfunc executeOps(ctx context.Context, t *testing.T, set *Set, ops []linux.Sembuf, block bool) chan struct{} {\n- ch, _, err := set.executeOps(ctx, ops)\n+ ch, _, err := set.executeOps(ctx, ops, 123)\nif err != nil {\nt.Fatalf(\"ExecuteOps(ops) failed, err: %v, ops: %+v\", err, ops)\n}\n@@ -123,13 +123,13 @@ func TestNoWait(t *testing.T) {\nops[0].SemOp = -2\nops[0].SemFlg = linux.IPC_NOWAIT\n- if _, _, err := set.executeOps(ctx, ops); err != syserror.ErrWouldBlock {\n+ if _, _, err := set.executeOps(ctx, ops, 123); err != syserror.ErrWouldBlock {\nt.Fatalf(\"ExecuteOps(ops) wrong result, got: %v, expected: %v\", err, syserror.ErrWouldBlock)\n}\nops[0].SemOp = 0\nops[0].SemFlg = linux.IPC_NOWAIT\n- if _, _, err := set.executeOps(ctx, ops); err != syserror.ErrWouldBlock {\n+ if _, _, err := set.executeOps(ctx, ops, 123); err != syserror.ErrWouldBlock {\nt.Fatalf(\"ExecuteOps(ops) wrong result, got: %v, expected: %v\", err, syserror.ErrWouldBlock)\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_sem.go", "new_path": "pkg/sentry/syscalls/linux/sys_sem.go", "diff": "@@ -71,8 +71,9 @@ func Semop(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\n}\ncreds := auth.CredentialsFromContext(t)\n+ pid := t.Kernel().GlobalInit().PIDNamespace().IDOfThreadGroup(t.ThreadGroup())\nfor {\n- ch, num, err := set.ExecuteOps(t, ops, creds)\n+ ch, num, err := set.ExecuteOps(t, ops, creds, int32(pid))\nif ch == nil || err != nil {\n// We're done (either on success or a failure).\nreturn 0, nil, err\n@@ -123,6 +124,21 @@ func Semctl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\nperms := fs.FilePermsFromMode(linux.FileMode(s.SemPerm.Mode & 0777))\nreturn 0, nil, ipcSet(t, id, auth.UID(s.SemPerm.UID), auth.GID(s.SemPerm.GID), perms)\n+ case linux.GETPID:\n+ v, err := getPID(t, id, num)\n+ return uintptr(v), nil, err\n+\n+ case linux.IPC_INFO,\n+ linux.SEM_INFO,\n+ linux.IPC_STAT,\n+ linux.SEM_STAT,\n+ linux.SEM_STAT_ANY,\n+ linux.GETNCNT,\n+ linux.GETZCNT:\n+\n+ t.Kernel().EmitUnimplementedEvent(t)\n+ fallthrough\n+\ndefault:\nreturn 0, nil, syserror.EINVAL\n}\n@@ -161,7 +177,8 @@ func setVal(t *kernel.Task, id int32, num int32, val int16) error {\nreturn syserror.EINVAL\n}\ncreds := auth.CredentialsFromContext(t)\n- return set.SetVal(t, num, val, creds)\n+ pid := t.Kernel().GlobalInit().PIDNamespace().IDOfThreadGroup(t.ThreadGroup())\n+ return set.SetVal(t, num, val, creds, int32(pid))\n}\nfunc setValAll(t *kernel.Task, id int32, array usermem.Addr) error {\n@@ -175,7 +192,8 @@ func setValAll(t *kernel.Task, id int32, array usermem.Addr) error {\nreturn err\n}\ncreds := auth.CredentialsFromContext(t)\n- return set.SetValAll(t, vals, creds)\n+ pid := t.Kernel().GlobalInit().PIDNamespace().IDOfThreadGroup(t.ThreadGroup())\n+ return set.SetValAll(t, vals, creds, int32(pid))\n}\nfunc getVal(t *kernel.Task, id int32, num int32) (int16, error) {\n@@ -202,3 +220,22 @@ func getValAll(t *kernel.Task, id int32, array usermem.Addr) error {\n_, err = t.CopyOut(array, vals)\nreturn err\n}\n+\n+func getPID(t *kernel.Task, id int32, num int32) (int32, 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+ gpid, err := set.GetPID(num, creds)\n+ if err != nil {\n+ return 0, err\n+ }\n+ // Convert pid from init namespace to the caller's namespace.\n+ tg := t.PIDNamespace().ThreadGroupWithID(kernel.ThreadID(gpid))\n+ if tg == nil {\n+ return 0, nil\n+ }\n+ return int32(tg.ID()), nil\n+}\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/compat.go", "new_path": "runsc/boot/compat.go", "diff": "@@ -100,6 +100,10 @@ func (c *compatEmitter) Emit(msg proto.Message) (hangup bool, err error) {\n// args: fd, level, name, ...\ntr = newArgsTracker(1, 2)\n+ case syscall.SYS_SEMCTL:\n+ // args: semid, semnum, cmd, ...\n+ tr = newArgsTracker(2)\n+\ndefault:\ntr = &onceTracker{}\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/semaphore.cc", "new_path": "test/syscalls/linux/semaphore.cc", "diff": "@@ -431,6 +431,35 @@ TEST(SemaphoreTest, SemCtlValAll) {\nSyscallFailsWithErrno(EFAULT));\n}\n+TEST(SemaphoreTest, SemCtlGetPid) {\n+ AutoSem sem(semget(IPC_PRIVATE, 1, 0600 | IPC_CREAT));\n+ ASSERT_THAT(sem.get(), SyscallSucceeds());\n+\n+ ASSERT_THAT(semctl(sem.get(), 0, SETVAL, 1), SyscallSucceeds());\n+ EXPECT_THAT(semctl(sem.get(), 0, GETPID), SyscallSucceedsWithValue(getpid()));\n+}\n+\n+TEST(SemaphoreTest, SemCtlGetPidFork) {\n+ AutoSem sem(semget(IPC_PRIVATE, 1, 0600 | IPC_CREAT));\n+ ASSERT_THAT(sem.get(), SyscallSucceeds());\n+\n+ const pid_t child_pid = fork();\n+ if (child_pid == 0) {\n+ ASSERT_THAT(semctl(sem.get(), 0, SETVAL, 1), SyscallSucceeds());\n+ ASSERT_THAT(semctl(sem.get(), 0, GETPID),\n+ SyscallSucceedsWithValue(getpid()));\n+\n+ _exit(0);\n+ }\n+ ASSERT_THAT(child_pid, SyscallSucceeds());\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+ << \" status \" << status;\n+}\n+\nTEST(SemaphoreTest, SemIpcSet) {\n// Drop CAP_IPC_OWNER which allows us to bypass semaphore permissions.\nASSERT_NO_ERRNO(SetCapability(CAP_IPC_OWNER, false));\n" } ]
Go
Apache License 2.0
google/gvisor
Add semctl(GETPID) syscall Also added unimplemented notification for semctl(2) commands. PiperOrigin-RevId: 236340672 Change-Id: I0795e3bd2e6d41d7936fabb731884df426a42478
259,881
01.03.2019 14:37:18
28,800
96226f9a473c0c55e0b632f9fbe883b078a234ea
Mark socket_ipv4_udp_unbound_loopback flaky To do so, we must add the ability to add tags to the syscall tests.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/BUILD", "new_path": "test/syscalls/BUILD", "diff": "@@ -363,7 +363,11 @@ syscall_test(\ntest = \"//test/syscalls/linux:socket_ip_udp_loopback_test\",\n)\n-syscall_test(test = \"//test/syscalls/linux:socket_ipv4_udp_unbound_loopback_test\")\n+syscall_test(\n+ # FIXME\n+ tags = [\"flaky\"],\n+ test = \"//test/syscalls/linux:socket_ipv4_udp_unbound_loopback_test\",\n+)\nsyscall_test(test = \"//test/syscalls/linux:socket_netdevice_test\")\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/build_defs.bzl", "new_path": "test/syscalls/build_defs.bzl", "diff": "# syscall_test is a macro that will create targets to run the given test target\n# on the host (native) and runsc.\n-def syscall_test(test, shard_count = 1, size = \"small\", use_tmpfs = False):\n- _syscall_test(test, shard_count, size, \"native\", False)\n- _syscall_test(test, shard_count, size, \"kvm\", use_tmpfs)\n- _syscall_test(test, shard_count, size, \"ptrace\", use_tmpfs)\n+def syscall_test(\n+ test,\n+ shard_count = 1,\n+ size = \"small\",\n+ use_tmpfs = False,\n+ tags = None):\n+ _syscall_test(\n+ test = test,\n+ shard_count = shard_count,\n+ size = size,\n+ platform = \"native\",\n+ use_tmpfs = False,\n+ tags = tags,\n+ )\n+\n+ _syscall_test(\n+ test = test,\n+ shard_count = shard_count,\n+ size = size,\n+ platform = \"kvm\",\n+ use_tmpfs = use_tmpfs,\n+ tags = tags,\n+ )\n+\n+ _syscall_test(\n+ test = test,\n+ shard_count = shard_count,\n+ size = size,\n+ platform = \"ptrace\",\n+ use_tmpfs = use_tmpfs,\n+ tags = tags,\n+ )\n+\nif not use_tmpfs:\n- _syscall_test(test, shard_count, size, \"ptrace\", use_tmpfs, \"shared\")\n+ # Also test shared gofer access.\n+ _syscall_test(\n+ test = test,\n+ shard_count = shard_count,\n+ size = size,\n+ platform = \"ptrace\",\n+ use_tmpfs = use_tmpfs,\n+ tags = tags,\n+ file_access = \"shared\",\n+ )\n-def _syscall_test(test, shard_count, size, platform, use_tmpfs, file_access = \"exclusive\"):\n+def _syscall_test(\n+ test,\n+ shard_count,\n+ size,\n+ platform,\n+ use_tmpfs,\n+ tags,\n+ file_access = \"exclusive\"):\ntest_name = test.split(\":\")[1]\n# Prepend \"runsc\" to non-native platform names.\n@@ -19,9 +64,12 @@ def _syscall_test(test, shard_count, size, platform, use_tmpfs, file_access = \"e\nif file_access == \"shared\":\nname += \"_shared\"\n+ if tags == None:\n+ tags = []\n+\n# Add the full_platform and file access in a tag to make it easier to run\n# all the tests on a specific flavor. Use --test_tag_filters=ptrace,file_shared.\n- tags = [full_platform, \"file_\" + file_access]\n+ tags += [full_platform, \"file_\" + file_access]\n# Add tag to prevent the tests from running in a Bazel sandbox.\n# TODO: Make the tests run without this tag.\n" } ]
Go
Apache License 2.0
google/gvisor
Mark socket_ipv4_udp_unbound_loopback flaky To do so, we must add the ability to add tags to the syscall tests. PiperOrigin-RevId: 236380371 Change-Id: I76d15feb2700f20115b27aab362a88cebe8c7a6a
259,858
01.03.2019 15:04:15
28,800
d811c1016d090ea88a687bd9bef4951dc08b391d
ptrace: drop old FIXME The globalPool uses a sync.Once mechanism for initialization, and no cleanup is strictly required. It's not really feasible to have the platform implement a full creation -> destruction cycle (due to the way filters are assumed to be installed), so drop the FIXME.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ptrace/ptrace.go", "new_path": "pkg/sentry/platform/ptrace/ptrace.go", "diff": "// The requested operation is performed in the traced subprocess thread\n// (e.g. set registers, execute, return).\n//\n-// FIXME: This package is currently sloppy with cleanup.\n-//\n// Lock order:\n//\n// subprocess.mu\n" } ]
Go
Apache License 2.0
google/gvisor
ptrace: drop old FIXME The globalPool uses a sync.Once mechanism for initialization, and no cleanup is strictly required. It's not really feasible to have the platform implement a full creation -> destruction cycle (due to the way filters are assumed to be installed), so drop the FIXME. PiperOrigin-RevId: 236385278 Change-Id: I98ac660ed58cc688d8a07147d16074a3e8181314
259,881
05.03.2019 13:53:36
28,800
bd46185e24e03b93ac551a5ddfffb06975f157c8
Add NoRandomSave to tests with correctness DisableSave Tests using DisableSave because a portion of the test is *incompatible* with S/R clearly cannot use random S/R, as the saves may occur in the DisableSave critical section. Most such tests already have NoRandomSave. Add it to the rest.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/flock.cc", "new_path": "test/syscalls/linux/flock.cc", "diff": "@@ -431,7 +431,7 @@ TEST_F(FlockTest, TestDupFdFollowedByLock) {\n// NOTE: These blocking tests are not perfect. Unfortunantely it's very hard to\n// determine if a thread was actually blocked in the kernel so we're forced\n// to use timing.\n-TEST_F(FlockTest, BlockingLockNoBlockingForSharedLocks) {\n+TEST_F(FlockTest, BlockingLockNoBlockingForSharedLocks_NoRandomSave) {\n// This test will verify that although LOCK_NB isn't specified\n// two different fds can obtain shared locks without blocking.\nASSERT_THAT(flock(test_file_fd_.get(), LOCK_SH), SyscallSucceeds());\n@@ -471,7 +471,7 @@ TEST_F(FlockTest, BlockingLockNoBlockingForSharedLocks) {\nEXPECT_THAT(flock(test_file_fd_.get(), LOCK_UN), SyscallSucceeds());\n}\n-TEST_F(FlockTest, BlockingLockFirstSharedSecondExclusive) {\n+TEST_F(FlockTest, BlockingLockFirstSharedSecondExclusive_NoRandomSave) {\n// This test will verify that if someone holds a shared lock any attempt to\n// obtain an exclusive lock will result in blocking.\nASSERT_THAT(flock(test_file_fd_.get(), LOCK_SH), SyscallSucceeds());\n@@ -508,7 +508,7 @@ TEST_F(FlockTest, BlockingLockFirstSharedSecondExclusive) {\nEXPECT_THAT(flock(test_file_fd_.get(), LOCK_UN), SyscallSucceeds());\n}\n-TEST_F(FlockTest, BlockingLockFirstExclusiveSecondShared) {\n+TEST_F(FlockTest, BlockingLockFirstExclusiveSecondShared_NoRandomSave) {\n// This test will verify that if someone holds an exclusive lock any attempt\n// to obtain a shared lock will result in blocking.\nASSERT_THAT(flock(test_file_fd_.get(), LOCK_EX), SyscallSucceeds());\n@@ -545,7 +545,7 @@ TEST_F(FlockTest, BlockingLockFirstExclusiveSecondShared) {\nEXPECT_THAT(flock(test_file_fd_.get(), LOCK_UN), SyscallSucceeds());\n}\n-TEST_F(FlockTest, BlockingLockFirstExclusiveSecondExclusive) {\n+TEST_F(FlockTest, BlockingLockFirstExclusiveSecondExclusive_NoRandomSave) {\n// This test will verify that if someone holds an exclusive lock any attempt\n// to obtain another exclusive lock will result in blocking.\nASSERT_THAT(flock(test_file_fd_.get(), LOCK_EX), SyscallSucceeds());\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/inotify.cc", "new_path": "test/syscalls/linux/inotify.cc", "diff": "@@ -1072,7 +1072,7 @@ TEST(Inotify, ChmodGeneratesAttribEvent_NoRandomSave) {\n};\n// Don't do cooperative S/R tests for any of the {f}chmod* syscalls below, the\n- // test will always fail because nodes cannot be saved when they have stricted\n+ // test will always fail because nodes cannot be saved when they have stricter\n// permissions than the original host node.\nconst DisableSave ds;\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/open.cc", "new_path": "test/syscalls/linux/open.cc", "diff": "@@ -293,7 +293,7 @@ TEST_F(OpenTest, CanTruncateReadOnly) {\n// If we don't have read permission on the file, opening with\n// O_TRUNC should fail.\n-TEST_F(OpenTest, CanTruncateReadOnlyNoWritePermission) {\n+TEST_F(OpenTest, CanTruncateReadOnlyNoWritePermission_NoRandomSave) {\n// Drop capabilities that allow us to override file permissions.\nASSERT_NO_ERRNO(SetCapability(CAP_DAC_OVERRIDE, false));\n@@ -314,7 +314,7 @@ TEST_F(OpenTest, CanTruncateReadOnlyNoWritePermission) {\n// If we don't have read permission but have write permission, opening O_WRONLY\n// and O_TRUNC should succeed.\n-TEST_F(OpenTest, CanTruncateWriteOnlyNoReadPermission) {\n+TEST_F(OpenTest, CanTruncateWriteOnlyNoReadPermission_NoRandomSave) {\nconst DisableSave ds; // Permissions are dropped.\nEXPECT_THAT(fchmod(test_file_fd_.get(), S_IWUSR | S_IWGRP),\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/stat.cc", "new_path": "test/syscalls/linux/stat.cc", "diff": "@@ -278,7 +278,7 @@ TEST_F(StatTest, LinkCountsWithRegularFileChild) {\n// This test verifies that inodes remain around when there is an open fd\n// after link count hits 0.\n-TEST_F(StatTest, ZeroLinksOpenFdRegularFileChild) {\n+TEST_F(StatTest, ZeroLinksOpenFdRegularFileChild_NoRandomSave) {\n// Setting the enviornment variable GVISOR_GOFER_UNCACHED to any value\n// will prevent this test from running, see the tmpfs lifecycle.\n//\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/unlink.cc", "new_path": "test/syscalls/linux/unlink.cc", "diff": "@@ -160,7 +160,7 @@ TEST(UnlinkTest, AtFile) {\nEXPECT_THAT(unlinkat(dirfd, \"UnlinkAtFile\", 0), SyscallSucceeds());\n}\n-TEST(UnlinkTest, OpenFile) {\n+TEST(UnlinkTest, OpenFile_NoRandomSave) {\n// We can't save unlinked file unless they are on tmpfs.\nconst DisableSave ds;\nauto file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n" } ]
Go
Apache License 2.0
google/gvisor
Add NoRandomSave to tests with correctness DisableSave Tests using DisableSave because a portion of the test is *incompatible* with S/R clearly cannot use random S/R, as the saves may occur in the DisableSave critical section. Most such tests already have NoRandomSave. Add it to the rest. PiperOrigin-RevId: 236914708 Change-Id: Iee1cf044cfa7cb8d5aba21ddc130926218210c48
259,962
05.03.2019 16:40:40
28,800
1718fdd1a8e16f36433b069a0f5d88ea7bdb65f5
Add new retransmissions and recovery related metrics.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/epsocket/epsocket.go", "new_path": "pkg/sentry/socket/epsocket/epsocket.go", "diff": "@@ -82,6 +82,12 @@ var Metrics = tcpip.Stats{\nSegmentsSent: mustCreateMetric(\"/netstack/tcp/segments_sent\", \"Number of TCP segments sent.\"),\nResetsSent: mustCreateMetric(\"/netstack/tcp/resets_sent\", \"Number of TCP resets sent.\"),\nResetsReceived: mustCreateMetric(\"/netstack/tcp/resets_received\", \"Number of TCP resets received.\"),\n+ Retransmits: mustCreateMetric(\"/netstack/tcp/retransmits\", \"Number of TCP segments retransmitted.\"),\n+ FastRecovery: mustCreateMetric(\"/netstack/tcp/fast_recovery\", \"Number of times fast recovery was used to recover from packet loss.\"),\n+ SACKRecovery: mustCreateMetric(\"/netstack/tcp/sack_recovery\", \"Number of times SACK recovery was used to recover from packet loss.\"),\n+ SlowStartRetransmits: mustCreateMetric(\"/netstack/tcp/slow_start_retransmits\", \"Number of segments retransmitted in slow start mode.\"),\n+ FastRetransmit: mustCreateMetric(\"/netstack/tcp/fast_retransmit\", \"Number of TCP segments which were fast retransmitted.\"),\n+ Timeouts: mustCreateMetric(\"/netstack/tcp/timeouts\", \"Number of times RTO expired.\"),\n},\nUDP: tcpip.UDPStats{\nPacketsReceived: mustCreateMetric(\"/netstack/udp/packets_received\", \"Number of UDP datagrams received via HandlePacket.\"),\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -628,6 +628,28 @@ type TCPStats struct {\n// ResetsReceived is the number of TCP resets received.\nResetsReceived *StatCounter\n+\n+ // Retransmits is the number of TCP segments retransmitted.\n+ Retransmits *StatCounter\n+\n+ // FastRecovery is the number of times Fast Recovery was used to\n+ // recover from packet loss.\n+ FastRecovery *StatCounter\n+\n+ // SACKRecovery is the number of times SACK Recovery was used to\n+ // recover from packet loss.\n+ SACKRecovery *StatCounter\n+\n+ // SlowStartRetransmits is the number of segments retransmitted in slow\n+ // start.\n+ SlowStartRetransmits *StatCounter\n+\n+ // FastRetransmit is the number of segments retransmitted in fast\n+ // recovery.\n+ FastRetransmit *StatCounter\n+\n+ // Timeouts is the number of times the RTO expired.\n+ Timeouts *StatCounter\n}\n// UDPStats collects UDP-specific stats.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/segment.go", "new_path": "pkg/tcpip/transport/tcp/segment.go", "diff": "@@ -61,6 +61,9 @@ type segment struct {\noptions []byte `state:\".([]byte)\"`\nhasNewSACKInfo bool\nrcvdTime time.Time `state:\".(unixTime)\"`\n+ // xmitTime is the last transmit time of this segment. A zero value\n+ // indicates that the segment has yet to be transmitted.\n+ xmitTime time.Time `state:\".(unixTime)\"`\n}\nfunc newSegment(r *stack.Route, id stack.TransportEndpointID, vv buffer.VectorisedView) *segment {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/segment_state.go", "new_path": "pkg/tcpip/transport/tcp/segment_state.go", "diff": "@@ -70,3 +70,13 @@ func (s *segment) saveRcvdTime() unixTime {\nfunc (s *segment) loadRcvdTime(unix unixTime) {\ns.rcvdTime = time.Unix(unix.second, unix.nano)\n}\n+\n+// saveXmitTime is invoked by stateify.\n+func (s *segment) saveXmitTime() unixTime {\n+ return unixTime{s.rcvdTime.Unix(), s.rcvdTime.UnixNano()}\n+}\n+\n+// loadXmitTime is invoked by stateify.\n+func (s *segment) loadXmitTime(unix unixTime) {\n+ s.rcvdTime = time.Unix(unix.second, unix.nano)\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/snd.go", "new_path": "pkg/tcpip/transport/tcp/snd.go", "diff": "@@ -338,6 +338,8 @@ func (s *sender) resendSegment() {\n// Resend the segment.\nif seg := s.writeList.Front(); seg != nil {\ns.sendSegment(seg.data, seg.flags, seg.sequenceNumber)\n+ s.ep.stack.Stats().TCP.FastRetransmit.Increment()\n+ s.ep.stack.Stats().TCP.Retransmits.Increment()\n}\n}\n@@ -352,6 +354,8 @@ func (s *sender) retransmitTimerExpired() bool {\nreturn true\n}\n+ s.ep.stack.Stats().TCP.Timeouts.Increment()\n+\n// Give up if we've waited more than a minute since the last resend.\nif s.rto >= 60*time.Second {\nreturn false\n@@ -422,7 +426,6 @@ func (s *sender) sendData() {\nend := s.sndUna.Add(s.sndWnd)\nvar dataSent bool\nfor ; seg != nil && s.outstanding < s.sndCwnd; seg = seg.Next() {\n-\n// We abuse the flags field to determine if we have already\n// assigned a sequence number to this segment.\nif seg.flags == 0 {\n@@ -524,6 +527,15 @@ func (s *sender) sendData() {\n// ensure that no keepalives are sent while there is pending data.\ns.ep.disableKeepaliveTimer()\n}\n+\n+ if !seg.xmitTime.IsZero() {\n+ s.ep.stack.Stats().TCP.Retransmits.Increment()\n+ if s.sndCwnd < s.sndSsthresh {\n+ s.ep.stack.Stats().TCP.SlowStartRetransmits.Increment()\n+ }\n+ }\n+\n+ seg.xmitTime = time.Now()\ns.sendSegment(seg.data, seg.flags, seg.sequenceNumber)\n// Update sndNxt if we actually sent new data (as opposed to\n@@ -556,6 +568,7 @@ func (s *sender) enterFastRecovery() {\ns.fr.first = s.sndUna\ns.fr.last = s.sndNxt - 1\ns.fr.maxCwnd = s.sndCwnd + s.outstanding\n+ s.ep.stack.Stats().TCP.FastRecovery.Increment()\n}\nfunc (s *sender) leaveFastRecovery() {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/tcp_test.go", "new_path": "pkg/tcpip/transport/tcp/tcp_test.go", "diff": "@@ -2669,6 +2669,18 @@ func TestFastRecovery(t *testing.T) {\n// Receive the retransmitted packet.\nc.ReceiveAndCheckPacket(data, rtxOffset, maxPayload)\n+ if got, want := c.Stack().Stats().TCP.FastRetransmit.Value(), uint64(1); got != want {\n+ t.Errorf(\"got stats.TCP.FastRetransmit.Value = %v, want = %v\", got, want)\n+ }\n+\n+ if got, want := c.Stack().Stats().TCP.Retransmits.Value(), uint64(1); got != want {\n+ t.Errorf(\"got stats.TCP.Retransmit.Value = %v, want = %v\", got, want)\n+ }\n+\n+ if got, want := c.Stack().Stats().TCP.FastRecovery.Value(), uint64(1); got != want {\n+ t.Errorf(\"got stats.TCP.FastRecovery.Value = %v, want = %v\", got, want)\n+ }\n+\n// Now send 7 mode duplicate acks. Each of these should cause a window\n// inflation by 1 and cause the sender to send an extra packet.\nfor i := 0; i < 7; i++ {\n@@ -2688,6 +2700,14 @@ func TestFastRecovery(t *testing.T) {\n// Receive the retransmit due to partial ack.\nc.ReceiveAndCheckPacket(data, rtxOffset, maxPayload)\n+ if got, want := c.Stack().Stats().TCP.FastRetransmit.Value(), uint64(2); got != want {\n+ t.Errorf(\"got stats.TCP.FastRetransmit.Value = %v, want = %v\", got, want)\n+ }\n+\n+ if got, want := c.Stack().Stats().TCP.Retransmits.Value(), uint64(2); got != want {\n+ t.Errorf(\"got stats.TCP.Retransmit.Value = %v, want = %v\", got, want)\n+ }\n+\n// Receive the 10 extra packets that should have been released due to\n// the congestion window inflation in recovery.\nfor i := 0; i < 10; i++ {\n@@ -2799,6 +2819,18 @@ func TestRetransmit(t *testing.T) {\nrtxOffset := bytesRead - maxPayload*expected\nc.ReceiveAndCheckPacket(data, rtxOffset, maxPayload)\n+ if got, want := c.Stack().Stats().TCP.Timeouts.Value(), uint64(1); got != want {\n+ t.Errorf(\"got stats.TCP.Timeouts.Value = %v, want = %v\", got, want)\n+ }\n+\n+ if got, want := c.Stack().Stats().TCP.Retransmits.Value(), uint64(1); got != want {\n+ t.Errorf(\"got stats.TCP.Retransmit.Value = %v, want = %v\", got, want)\n+ }\n+\n+ if got, want := c.Stack().Stats().TCP.SlowStartRetransmits.Value(), uint64(1); got != want {\n+ t.Errorf(\"got stats.TCP.SlowStartRetransmits.Value = %v, want = %v\", got, want)\n+ }\n+\n// Acknowledge half of the pending data.\nrtxOffset = bytesRead - expected*maxPayload/2\nc.SendAck(790, rtxOffset)\n" } ]
Go
Apache License 2.0
google/gvisor
Add new retransmissions and recovery related metrics. PiperOrigin-RevId: 236945145 Change-Id: I051760d95154ea5574c8bb6aea526f488af5e07b
259,992
05.03.2019 22:19:23
28,800
fcba4e8f040ab4b40e04b9315d718d7e5aa44635
Add uncaught signal message to the user log This help troubleshoot cases where the container is killed and the app logs don't show the reason.
[ { "change_type": "MODIFY", "old_path": "runsc/boot/BUILD", "new_path": "runsc/boot/BUILD", "diff": "@@ -46,6 +46,7 @@ go_library(\n\"//pkg/sentry/fs/tty\",\n\"//pkg/sentry/inet\",\n\"//pkg/sentry/kernel\",\n+ \"//pkg/sentry/kernel:uncaught_signal_go_proto\",\n\"//pkg/sentry/kernel/auth\",\n\"//pkg/sentry/kernel/kdefs\",\n\"//pkg/sentry/limits\",\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/compat.go", "new_path": "runsc/boot/compat.go", "diff": "@@ -26,6 +26,7 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/log\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/arch\"\nrpb \"gvisor.googlesource.com/gvisor/pkg/sentry/arch/registers_go_proto\"\n+ ucspb \"gvisor.googlesource.com/gvisor/pkg/sentry/kernel/uncaught_signal_go_proto\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/strace\"\nspb \"gvisor.googlesource.com/gvisor/pkg/sentry/unimpl/unimplemented_syscall_go_proto\"\n)\n@@ -73,12 +74,18 @@ func newCompatEmitter(logFD int) (*compatEmitter, error) {\n}\n// Emit implements eventchannel.Emitter.\n-func (c *compatEmitter) Emit(msg proto.Message) (hangup bool, err error) {\n- // Only interested in UnimplementedSyscall, skip the rest.\n- us, ok := msg.(*spb.UnimplementedSyscall)\n- if !ok {\n+func (c *compatEmitter) Emit(msg proto.Message) (bool, error) {\n+ switch m := msg.(type) {\n+ case *spb.UnimplementedSyscall:\n+ c.emitUnimplementedSyscall(m)\n+ case *ucspb.UncaughtSignal:\n+ c.emitUncaughtSignal(m)\n+ }\n+\nreturn false, nil\n}\n+\n+func (c *compatEmitter) emitUnimplementedSyscall(us *spb.UnimplementedSyscall) {\nregs := us.Registers.GetArch().(*rpb.Registers_Amd64).Amd64\nc.mu.Lock()\n@@ -113,7 +120,13 @@ func (c *compatEmitter) Emit(msg proto.Message) (hangup bool, err error) {\nc.sink.Infof(\"Unsupported syscall: %s, regs: %+v\", c.nameMap.Name(uintptr(sysnr)), regs)\ntr.onReported(regs)\n}\n- return false, nil\n+}\n+\n+func (c *compatEmitter) emitUncaughtSignal(msg *ucspb.UncaughtSignal) {\n+ sig := syscall.Signal(msg.SignalNumber)\n+ c.sink.Infof(\n+ \"Uncaught signal: %q (%d), PID: %d, TID: %d, fault addr: %#x\",\n+ sig, msg.SignalNumber, msg.Pid, msg.Tid, msg.FaultAddr)\n}\n// Close implements eventchannel.Emitter.\n" } ]
Go
Apache License 2.0
google/gvisor
Add uncaught signal message to the user log This help troubleshoot cases where the container is killed and the app logs don't show the reason. PiperOrigin-RevId: 236982883 Change-Id: I361892856a146cea5b04abaa3aedbf805e123724
259,881
06.03.2019 12:54:45
28,800
54ac76c305935b12b78ab6b464111dd227acdcbf
Remove unsafe ScopedSigaction ScopedSigaction is not async-signal-safe, so it cannot be used after fork. Replace it with plain sigaction, which is safe. This is in a unique child anyways, so it doesn't need any cleanup.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/kill.cc", "new_path": "test/syscalls/linux/kill.cc", "diff": "@@ -70,7 +70,8 @@ TEST(KillTest, CanKillAllPIDs) {\nsa.sa_sigaction = SigHandler;\nsigfillset(&sa.sa_mask);\nsa.sa_flags = SA_SIGINFO;\n- auto cleanup = ScopedSigaction(SIGWINCH, sa).ValueOrDie();\n+ TEST_PCHECK(sigaction(SIGWINCH, &sa, nullptr) == 0);\n+ MaybeSave();\n// Indicate to the parent that we're ready.\nwrite_fd.reset();\n" } ]
Go
Apache License 2.0
google/gvisor
Remove unsafe ScopedSigaction ScopedSigaction is not async-signal-safe, so it cannot be used after fork. Replace it with plain sigaction, which is safe. This is in a unique child anyways, so it doesn't need any cleanup. PiperOrigin-RevId: 237102411 Change-Id: I5c6ea373bbac67b9c4db204ceb1db62d338d9178
259,881
06.03.2019 13:18:25
28,800
cdd63375d39e92c6964df0487dcf7d8ff013c9e7
Increase ipv4_udp_unbound_loopback size to medium Now that tests aren't running in parallel, this test occassionally takes too long and times out.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/BUILD", "new_path": "test/syscalls/BUILD", "diff": "@@ -364,6 +364,7 @@ syscall_test(\n)\nsyscall_test(\n+ size = \"medium\",\n# Multicast packets can be received by the wrong test if run in parallel.\nparallel = False,\ntest = \"//test/syscalls/linux:socket_ipv4_udp_unbound_loopback_test\",\n" } ]
Go
Apache License 2.0
google/gvisor
Increase ipv4_udp_unbound_loopback size to medium Now that tests aren't running in parallel, this test occassionally takes too long and times out. PiperOrigin-RevId: 237106971 Change-Id: I195a4b77315c9f5511c9e8ffadddb7aaa78beafd
259,853
08.03.2019 13:32:37
28,800
832589cb076a638ca53076ebb66afb9fac4597d1
Fix tests which fail in kokoro * open_create_test_runsc_ptrace_shared doesn't expect the write access to / * exec_test_runsc_ptrace_shared could not find /usr/share/zoneinfo/ * clock_gettime_test_runsc_ptrace_shared didn't expect that a thread cpu time can be zero. * affinity_test_runsc_ptrace_shared expected minimum 3 cpus
[ { "change_type": "MODIFY", "old_path": "kokoro/run_tests.sh", "new_path": "kokoro/run_tests.sh", "diff": "@@ -177,16 +177,10 @@ run_root_tests() {\n# Run syscall unit tests.\nrun_syscall_tests() {\ncd ${WORKSPACE_DIR}\n- # TODO: Exclude tests which fail.\nbazel \\\n\"${BAZEL_RBE_FLAGS[@]}\" \\\ntest \"${BAZEL_BUILD_RBE_FLAGS[@]}\" \\\n- `bazel query //test/syscalls/... |\n- grep runsc_ptrace |\n- grep -v affinity_test_runsc_ptrace |\n- grep -v exec_test_runsc_ptrace |\n- grep -v open_create_test_runsc_ptrace |\n- grep -v clock_gettime_test_runsc_ptrace`\n+ --test_tag_filters=runsc_ptrace //test/syscalls/...\n}\n# Find and rename all test xml and log files so that Sponge can pick them up.\n" }, { "change_type": "MODIFY", "old_path": "test/BUILD", "new_path": "test/BUILD", "diff": "@@ -34,10 +34,6 @@ platform(\nname: \"dockerPrivileged\"\nvalue: \"true\"\n}\n- properties: {\n- name: \"dockerRunAsRoot\"\n- value: \"true\"\n- }\n\"\"\",\n)\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/BUILD", "new_path": "test/syscalls/BUILD", "diff": "@@ -49,7 +49,10 @@ syscall_test(test = \"//test/syscalls/linux:chroot_test\")\nsyscall_test(test = \"//test/syscalls/linux:clock_getres_test\")\n-syscall_test(test = \"//test/syscalls/linux:clock_gettime_test\")\n+syscall_test(\n+ size = \"medium\",\n+ test = \"//test/syscalls/linux:clock_gettime_test\",\n+)\nsyscall_test(test = \"//test/syscalls/linux:clock_nanosleep_test\")\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/affinity.cc", "new_path": "test/syscalls/linux/affinity.cc", "diff": "@@ -155,6 +155,7 @@ TEST_F(AffinityTest, Sanity) {\n}\nTEST_F(AffinityTest, NewThread) {\n+ SKIP_IF(CPU_COUNT(&mask_) < 3);\nASSERT_NO_ERRNO(ClearLowestBit());\nASSERT_NO_ERRNO(ClearLowestBit());\nEXPECT_THAT(sched_setaffinity(/*pid=*/0, sizeof(cpu_set_t), &mask_),\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/clock_gettime.cc", "new_path": "test/syscalls/linux/clock_gettime.cc", "diff": "@@ -87,7 +87,12 @@ TEST(ClockGettime, JavaThreadTime) {\nASSERT_EQ(0, pthread_getcpuclockid(pthread_self(), &clockid));\nstruct timespec tp;\nASSERT_THAT(clock_getres(clockid, &tp), SyscallSucceeds());\n+ EXPECT_TRUE(tp.tv_sec > 0 || tp.tv_nsec > 0);\n+ // A thread cputime is updated each 10msec and there is no approximation\n+ // if a task is running.\n+ do {\nASSERT_THAT(clock_gettime(clockid, &tp), SyscallSucceeds());\n+ } while (tp.tv_sec == 0 && tp.tv_nsec == 0);\nEXPECT_TRUE(tp.tv_sec > 0 || tp.tv_nsec > 0);\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/exec.cc", "new_path": "test/syscalls/linux/exec.cc", "diff": "@@ -476,8 +476,10 @@ TEST(ProcSelfExe, ChangesAcrossExecve) {\n}\nTEST(ExecTest, CloexecNormalFile) {\n- const FileDescriptor fd_closed_on_exec = ASSERT_NO_ERRNO_AND_VALUE(\n- Open(\"/usr/share/zoneinfo\", O_RDONLY | O_CLOEXEC));\n+ TempPath tempFile = ASSERT_NO_ERRNO_AND_VALUE(\n+ TempPath::CreateFileWith(GetAbsoluteTestTmpdir(), \"bar\", 0755));\n+ const FileDescriptor fd_closed_on_exec =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(tempFile.path(), O_RDONLY | O_CLOEXEC));\nCheckOutput(WorkloadPath(kAssertClosedWorkload),\n{WorkloadPath(kAssertClosedWorkload),\n@@ -487,7 +489,7 @@ TEST(ExecTest, CloexecNormalFile) {\n// The assert closed workload exits with code 2 if the file still exists. We\n// can use this to do a negative test.\nconst FileDescriptor fd_open_on_exec =\n- ASSERT_NO_ERRNO_AND_VALUE(Open(\"/usr/share/zoneinfo\", O_RDONLY));\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(tempFile.path(), O_RDONLY));\nCheckOutput(WorkloadPath(kAssertClosedWorkload),\n{WorkloadPath(kAssertClosedWorkload),\n" } ]
Go
Apache License 2.0
google/gvisor
Fix tests which fail in kokoro * open_create_test_runsc_ptrace_shared doesn't expect the write access to / * exec_test_runsc_ptrace_shared could not find /usr/share/zoneinfo/ * clock_gettime_test_runsc_ptrace_shared didn't expect that a thread cpu time can be zero. * affinity_test_runsc_ptrace_shared expected minimum 3 cpus PiperOrigin-RevId: 237509429 Change-Id: I477937e5d2cdf3f8720836bfa972abd35d8220a3
259,944
08.03.2019 17:53:36
28,800
b7015c1a46fbea47ad8e7985583b30bd918ddc4b
Put the gvisor user log into sandbox log directory.
[ { "change_type": "MODIFY", "old_path": "pkg/go-runsc/utils.go", "new_path": "pkg/go-runsc/utils.go", "diff": "@@ -39,18 +39,8 @@ func putBuf(b *bytes.Buffer) {\n}\n// FormatLogPath parses runsc config, and fill in %ID% in the log path.\n-// * For debug-log, it fills in the id in place;\n-// * For user-log, it fills in the id, returns the user log path, and deletes\n-// the `user-log` entry from the config, because it will only be added to runsc\n-// calls that create a new sandbox.\n-func FormatLogPath(id string, config map[string]string) string {\n+func FormatLogPath(id string, config map[string]string) {\nif path, ok := config[\"debug-log\"]; ok {\nconfig[\"debug-log\"] = strings.Replace(path, \"%ID%\", id, -1)\n}\n- var userLog string\n- if path, ok := config[\"user-log\"]; ok {\n- userLog = strings.Replace(path, \"%ID%\", id, -1)\n- delete(config, \"user-log\")\n- }\n- return userLog\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/v1/shim/service.go", "new_path": "pkg/v1/shim/service.go", "diff": "@@ -551,7 +551,7 @@ func newInit(ctx context.Context, path, workDir, runtimeRoot, namespace string,\nif err != nil {\nreturn nil, errors.Wrap(err, \"read oci spec\")\n}\n- userLog := runsc.FormatLogPath(r.ID, config)\n+ runsc.FormatLogPath(r.ID, config)\nrootfs := filepath.Join(path, \"rootfs\")\nruntime := proc.NewRunsc(runtimeRoot, path, namespace, r.Runtime, config)\np := proc.New(r.ID, runtime, rproc.Stdio{\n@@ -567,7 +567,7 @@ func newInit(ctx context.Context, path, workDir, runtimeRoot, namespace string,\np.IoUID = int(options.IoUid)\np.IoGID = int(options.IoGid)\np.Sandbox = utils.IsSandbox(spec)\n- p.UserLog = userLog\n+ p.UserLog = utils.UserLogPath(spec)\np.Monitor = shim.Default\nreturn p, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/v1/utils/utils.go", "new_path": "pkg/v1/utils/utils.go", "diff": "@@ -48,3 +48,12 @@ func IsSandbox(spec *specs.Spec) bool {\nt, ok := spec.Annotations[annotations.ContainerType]\nreturn !ok || t == annotations.ContainerTypeSandbox\n}\n+\n+// UserLogPath gets user log path from OCI annotation.\n+func UserLogPath(spec *specs.Spec) string {\n+ sandboxLogDir := spec.Annotations[annotations.SandboxLogDir]\n+ if sandboxLogDir == \"\" {\n+ return \"\"\n+ }\n+ return filepath.Join(sandboxLogDir, \"gvisor.log\")\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/v2/service.go", "new_path": "pkg/v2/service.go", "diff": "@@ -696,7 +696,7 @@ func newInit(ctx context.Context, path, workDir, namespace string, platform rpro\nif err != nil {\nreturn nil, errors.Wrap(err, \"read oci spec\")\n}\n- userLog := runsc.FormatLogPath(r.ID, options.RunscConfig)\n+ runsc.FormatLogPath(r.ID, options.RunscConfig)\nrootfs := filepath.Join(path, \"rootfs\")\nruntime := proc.NewRunsc(options.Root, path, namespace, options.BinaryName, options.RunscConfig)\np := proc.New(r.ID, runtime, rproc.Stdio{\n@@ -712,7 +712,7 @@ func newInit(ctx context.Context, path, workDir, namespace string, platform rpro\np.IoUID = int(options.IoUid)\np.IoGID = int(options.IoGid)\np.Sandbox = utils.IsSandbox(spec)\n- p.UserLog = userLog\n+ p.UserLog = utils.UserLogPath(spec)\np.Monitor = shim.Default\nreturn p, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "vendor.conf", "new_path": "vendor.conf", "diff": "@@ -2,7 +2,7 @@ github.com/BurntSushi/toml v0.3.0\ngithub.com/containerd/cgroups 5e610833b72089b37d0e615de9a92dfc043757c2\ngithub.com/containerd/console c12b1e7919c14469339a5d38f2f8ed9b64a9de23\ngithub.com/containerd/containerd v1.2.2\n-github.com/containerd/cri 4dd6735020f5596dd41738f8c4f5cb07fa804c5e\n+github.com/containerd/cri 8a0bd84b9a4c988a3098fca8fedcb9c0f14d9d08\ngithub.com/containerd/fifo 3d5202aec260678c48179c56f40e6f38a095738c\ngithub.com/containerd/go-runc 5a6d9f37cfa36b15efba46dc7ea349fa9b7143c3\ngithub.com/containerd/ttrpc 2a805f71863501300ae1976d29f0454ae003e85a\n" }, { "change_type": "MODIFY", "old_path": "vendor/github.com/containerd/cri/README.md", "new_path": "vendor/github.com/containerd/cri/README.md", "diff": "@@ -39,6 +39,17 @@ See [test dashboard](https://k8s-testgrid.appspot.com/sig-node-containerd)\n| | v1.2 | 1.10+ | v1alpha2 |\n| | HEAD | 1.10+ | v1alpha2 |\n+**Note:** The support table above specifies the Kubernetes Version that was supported at time of release of the containerd - cri integration.\n+\n+The following is the current support table for containerd CRI integration taking into account that Kubernetes only supports n-3 minor release versions and 1.10 is now end-of-life.\n+\n+| Containerd Version | Kubernetes Version | CRI Version |\n+|:------------------:|:------------------:|:-----------:|\n+| v1.1 | 1.11+ | v1alpha2 |\n+| v1.2 | 1.11+ | v1alpha2 |\n+| HEAD | 1.11+ | v1alpha2 |\n+\n+\n## Production Quality Cluster on GCE\nFor a production quality cluster on GCE brought up with `kube-up.sh` refer [here](docs/kube-up.md).\n## Installing with Ansible and Kubeadm\n" }, { "change_type": "MODIFY", "old_path": "vendor/github.com/containerd/cri/pkg/annotations/annotations.go", "new_path": "vendor/github.com/containerd/cri/pkg/annotations/annotations.go", "diff": "@@ -32,6 +32,15 @@ const (\n// SandboxID is the sandbox ID annotation\nSandboxID = \"io.kubernetes.cri.sandbox-id\"\n+ // SandboxLogDir is the pod log directory annotation.\n+ // If the sandbox needs to generate any log, it will put it into this directory.\n+ // Kubelet will be responsible for:\n+ // 1) Monitoring the disk usage of the log, and including it as part of the pod\n+ // ephemeral storage usage.\n+ // 2) Cleaning up the logs when the pod is deleted.\n+ // NOTE: Kubelet is not responsible for rotating the logs.\n+ SandboxLogDir = \"io.kubernetes.cri.sandbox-log-directory\"\n+\n// UntrustedWorkload is the sandbox annotation for untrusted workload. Untrusted\n// workload can only run on dedicated runtime for untrusted workload.\nUntrustedWorkload = \"io.kubernetes.cri.untrusted-workload\"\n" }, { "change_type": "MODIFY", "old_path": "vendor/github.com/containerd/cri/vendor.conf", "new_path": "vendor/github.com/containerd/cri/vendor.conf", "diff": "github.com/beorn7/perks 4c0e84591b9aa9e6dcfdf3e020114cd81f89d5f9\ngithub.com/blang/semver v3.1.0\ngithub.com/BurntSushi/toml a368813c5e648fee92e5f6c30e3944ff9d5e8895\n-github.com/containerd/cgroups 5e610833b72089b37d0e615de9a92dfc043757c2\n+github.com/containerd/cgroups 1152b960fcee041f50df15cdc67c29dbccf801ef\ngithub.com/containerd/console c12b1e7919c14469339a5d38f2f8ed9b64a9de23\n-github.com/containerd/containerd 6937c5a3ba8280edff9e9030767e3b0cb742581c\n+github.com/containerd/containerd 4543e32a8b29e691e523ddc142f0c9068917df54\ngithub.com/containerd/continuity bd77b46c8352f74eb12c85bdc01f4b90f69d66b4\ngithub.com/containerd/fifo 3d5202aec260678c48179c56f40e6f38a095738c\ngithub.com/containerd/go-cni 40bcf8ec8acd7372be1d77031d585d5d8e561c90\ngithub.com/containerd/go-runc 5a6d9f37cfa36b15efba46dc7ea349fa9b7143c3\n-github.com/containerd/ttrpc 2a805f71863501300ae1976d29f0454ae003e85a\n+github.com/containerd/ttrpc f02858b1457c5ca3aaec3a0803eb0d59f96e41d6\ngithub.com/containerd/typeurl a93fcdb778cd272c6e9b3028b2f42d813e785d40\ngithub.com/containernetworking/cni v0.6.0\ngithub.com/containernetworking/plugins v0.7.0\ngithub.com/coreos/go-systemd v14\ngithub.com/davecgh/go-spew v1.1.0\n-github.com/docker/distribution b38e5838b7b2f2ad48e06ec4b500011976080621\n+github.com/docker/distribution 0d3efadf0154c2b8a4e7b6621fff9809655cc580\ngithub.com/docker/docker 86f080cff0914e9694068ed78d503701667c4c00\ngithub.com/docker/go-events 9461782956ad83b30282bf90e31fa6a70c255ba9\ngithub.com/docker/go-metrics 4ea375f7759c82740c893fc030bc37088d2ec098\n@@ -32,12 +32,12 @@ github.com/hashicorp/go-multierror ed905158d87462226a13fe39ddf685ea65f1c11f\ngithub.com/json-iterator/go 1.1.5\ngithub.com/matttproud/golang_protobuf_extensions v1.0.0\ngithub.com/Microsoft/go-winio v0.4.11\n-github.com/Microsoft/hcsshim v0.8.2\n+github.com/Microsoft/hcsshim v0.8.5\ngithub.com/modern-go/concurrent 1.0.3\ngithub.com/modern-go/reflect2 1.0.1\ngithub.com/opencontainers/go-digest c9281466c8b2f606084ac71339773efd177436e7\ngithub.com/opencontainers/image-spec v1.0.1\n-github.com/opencontainers/runc v1.0.0-rc6\n+github.com/opencontainers/runc 12f6a991201fdb8f82579582d5e00e28fba06d0a\ngithub.com/opencontainers/runtime-spec eba862dc2470385a233c7507392675cbeadf7353\ngithub.com/opencontainers/runtime-tools fb101d5d42ab9c040f7d0a004e78336e5d5cb197\ngithub.com/opencontainers/selinux b6fa367ed7f534f9ba25391cc2d467085dbb445a\n@@ -60,7 +60,7 @@ go.etcd.io/bbolt v1.3.1-etcd.8\ngolang.org/x/crypto 49796115aa4b964c318aad4f3084fdb41e9aa067\ngolang.org/x/net b3756b4b77d7b13260a0a2ec658753cf48922eac\ngolang.org/x/oauth2 a6bd8cefa1811bd24b86f8902872e4e8225f74c4\n-golang.org/x/sync 450f422ab23cf9881c94e2db30cac0eb1b7cf80c\n+golang.org/x/sync 42b317875d0fa942474b76e1b46a6060d720ae6e\ngolang.org/x/sys 1b2967e3c290b7c545b3db0deeda16e9be4f98a2 https://github.com/golang/sys\ngolang.org/x/text 19e51611da83d6be54ddafce4a4af510cb3e9ea4\ngolang.org/x/time f51c12702a4d776e4c1fa9b0fabab841babae631\n@@ -68,11 +68,11 @@ google.golang.org/genproto d80a6e20e776b0b17a324d0ba1ab50a39c8e8944\ngoogle.golang.org/grpc v1.12.0\ngopkg.in/inf.v0 3887ee99ecf07df5b447e9b00d9c0b2adaa9f3e4\ngopkg.in/yaml.v2 v2.2.1\n-k8s.io/api kubernetes-1.13.0\n-k8s.io/apimachinery kubernetes-1.13.0\n-k8s.io/apiserver kubernetes-1.13.0\n-k8s.io/client-go kubernetes-1.13.0\n-k8s.io/klog 8139d8cb77af419532b33dfa7dd09fbc5f1d344f\n-k8s.io/kubernetes v1.13.0\n-k8s.io/utils 0d26856f57b32ec3398579285e5c8a2bfe8c5243\n+k8s.io/api kubernetes-1.15.0-alpha.0\n+k8s.io/apimachinery kubernetes-1.15.0-alpha.0\n+k8s.io/apiserver kubernetes-1.15.0-alpha.0\n+k8s.io/client-go kubernetes-1.15.0-alpha.0\n+k8s.io/klog 8145543d67ada0bd556af97faeeb8a65a2651c98\n+k8s.io/kubernetes v1.15.0-alpha.0\n+k8s.io/utils c2654d5206da6b7b6ace12841e8f359bb89b443c\nsigs.k8s.io/yaml v1.1.0\n" } ]
Go
Apache License 2.0
google/gvisor
Put the gvisor user log into sandbox log directory. (#17) Signed-off-by: Lantao Liu <[email protected]>
259,854
08.03.2019 19:04:29
28,800
86036f979b34855f0c945056f908961ccb804c1e
Validate multicast addresses in multicast group operations.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/endpoint.go", "new_path": "pkg/tcpip/transport/udp/endpoint.go", "diff": "@@ -459,6 +459,10 @@ func (e *endpoint) SetSockOpt(opt interface{}) *tcpip.Error {\ne.multicastAddr = addr\ncase tcpip.AddMembershipOption:\n+ if !header.IsV4MulticastAddress(v.MulticastAddr) && !header.IsV6MulticastAddress(v.MulticastAddr) {\n+ return tcpip.ErrInvalidOptionValue\n+ }\n+\nnicID := v.NIC\nif v.InterfaceAddr == header.IPv4Any {\nif nicID == 0 {\n@@ -475,7 +479,6 @@ func (e *endpoint) SetSockOpt(opt interface{}) *tcpip.Error {\nreturn tcpip.ErrUnknownDevice\n}\n- // TODO: check that v.MulticastAddr is a multicast address.\nif err := e.stack.JoinGroup(e.netProto, nicID, v.MulticastAddr); err != nil {\nreturn err\n}\n@@ -486,6 +489,10 @@ func (e *endpoint) SetSockOpt(opt interface{}) *tcpip.Error {\ne.multicastMemberships = append(e.multicastMemberships, multicastMembership{nicID, v.MulticastAddr})\ncase tcpip.RemoveMembershipOption:\n+ if !header.IsV4MulticastAddress(v.MulticastAddr) && !header.IsV6MulticastAddress(v.MulticastAddr) {\n+ return tcpip.ErrInvalidOptionValue\n+ }\n+\nnicID := v.NIC\nif v.InterfaceAddr == header.IPv4Any {\nif nicID == 0 {\n@@ -502,7 +509,6 @@ func (e *endpoint) SetSockOpt(opt interface{}) *tcpip.Error {\nreturn tcpip.ErrUnknownDevice\n}\n- // TODO: check that v.MulticastAddr is a multicast address.\nif err := e.stack.LeaveGroup(e.netProto, nicID, v.MulticastAddr); err != nil {\nreturn err\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_ip_udp_generic.cc", "new_path": "test/syscalls/linux/socket_ip_udp_generic.cc", "diff": "@@ -121,14 +121,9 @@ TEST_P(UDPSocketPairTest, SetEmptyIPAddMembership) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\nstruct ip_mreqn req = {};\n- int ret = setsockopt(sockets->first_fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &req,\n- sizeof(req));\n- // FIXME: gVisor returns the incorrect errno.\n- if (IsRunningOnGvisor()) {\n- EXPECT_THAT(ret, SyscallFails());\n- } else {\n- EXPECT_THAT(ret, SyscallFailsWithErrno(EINVAL));\n- }\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP,\n+ &req, sizeof(req)),\n+ SyscallFailsWithErrno(EINVAL));\n}\n} // namespace testing\n" } ]
Go
Apache License 2.0
google/gvisor
Validate multicast addresses in multicast group operations. PiperOrigin-RevId: 237559843 Change-Id: I93a9d83a08cd3d49d5fc7fcad5b0710d0aa04aaa
259,854
08.03.2019 20:26:55
28,800
281092e842445cfb9ff474aae81c169954b469cb
Make IP_MULTICAST_LOOP and IP_MULTICAST_TTL allow setting int or char. This is the correct Linux behavior, and at least PHP depends on it.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/epsocket/epsocket.go", "new_path": "pkg/sentry/socket/epsocket/epsocket.go", "diff": "@@ -1193,24 +1193,30 @@ func copyInMulticastRequest(optVal []byte) (linux.InetMulticastRequestWithNIC, *\nreturn req, nil\n}\n-// reduceToByte ORs all of the bytes in the input.\n-func reduceToByte(buf []byte) byte {\n- var out byte\n- for _, b := range buf {\n- out |= b\n+// parseIntOrChar copies either a 32-bit int or an 8-bit uint out of buf.\n+//\n+// net/ipv4/ip_sockglue.c:do_ip_setsockopt does this for its socket options.\n+func parseIntOrChar(buf []byte) (int32, *syserr.Error) {\n+ if len(buf) == 0 {\n+ return 0, syserr.ErrInvalidArgument\n}\n- return out\n+\n+ if len(buf) >= sizeOfInt32 {\n+ return int32(usermem.ByteOrder.Uint32(buf)), nil\n+ }\n+\n+ return int32(buf[0]), nil\n}\n// setSockOptIP implements SetSockOpt when level is SOL_IP.\nfunc setSockOptIP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *syserr.Error {\nswitch name {\ncase linux.IP_MULTICAST_TTL:\n- if len(optVal) < sizeOfInt32 {\n- return syserr.ErrInvalidArgument\n+ v, err := parseIntOrChar(optVal)\n+ if err != nil {\n+ return err\n}\n- v := int32(usermem.ByteOrder.Uint32(optVal))\nif v == -1 {\n// Linux translates -1 to 1.\nv = 1\n@@ -1260,15 +1266,13 @@ func setSockOptIP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *s\n}))\ncase linux.IP_MULTICAST_LOOP:\n- if len(optVal) < 1 {\n- return syserr.ErrInvalidArgument\n- }\n- if len(optVal) > sizeOfInt32 {\n- optVal = optVal[:sizeOfInt32]\n+ v, err := parseIntOrChar(optVal)\n+ if err != nil {\n+ return err\n}\nreturn syserr.TranslateNetstackError(ep.SetSockOpt(\n- tcpip.MulticastLoopOption(reduceToByte(optVal) != 0),\n+ tcpip.MulticastLoopOption(v != 0),\n))\ncase linux.MCAST_JOIN_GROUP:\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_ip_udp_generic.cc", "new_path": "test/syscalls/linux/socket_ip_udp_generic.cc", "diff": "@@ -117,6 +117,23 @@ TEST_P(UDPSocketPairTest, SetUDPMulticastTTLAboveMax) {\nSyscallFailsWithErrno(EINVAL));\n}\n+TEST_P(UDPSocketPairTest, SetUDPMulticastTTLChar) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ constexpr char kArbitrary = 6;\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_TTL,\n+ &kArbitrary, sizeof(kArbitrary)),\n+ SyscallSucceeds());\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ EXPECT_THAT(getsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_TTL,\n+ &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, kArbitrary);\n+}\n+\nTEST_P(UDPSocketPairTest, SetEmptyIPAddMembership) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n@@ -126,5 +143,72 @@ TEST_P(UDPSocketPairTest, SetEmptyIPAddMembership) {\nSyscallFailsWithErrno(EINVAL));\n}\n+TEST_P(UDPSocketPairTest, MulticastLoopDefault) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ EXPECT_THAT(getsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_LOOP,\n+ &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, kSockOptOn);\n+}\n+\n+TEST_P(UDPSocketPairTest, SetMulticastLoop) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ ASSERT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_LOOP,\n+ &kSockOptOff, sizeof(kSockOptOff)),\n+ SyscallSucceeds());\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ EXPECT_THAT(getsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_LOOP,\n+ &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, kSockOptOff);\n+\n+ ASSERT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_LOOP,\n+ &kSockOptOn, sizeof(kSockOptOn)),\n+ SyscallSucceeds());\n+\n+ EXPECT_THAT(getsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_LOOP,\n+ &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, kSockOptOn);\n+}\n+\n+TEST_P(UDPSocketPairTest, SetMulticastLoopChar) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ constexpr char kSockOptOnChar = kSockOptOn;\n+ constexpr char kSockOptOffChar = kSockOptOff;\n+\n+ ASSERT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_LOOP,\n+ &kSockOptOffChar, sizeof(kSockOptOffChar)),\n+ SyscallSucceeds());\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ EXPECT_THAT(getsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_LOOP,\n+ &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, kSockOptOff);\n+\n+ ASSERT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_LOOP,\n+ &kSockOptOnChar, sizeof(kSockOptOnChar)),\n+ SyscallSucceeds());\n+\n+ EXPECT_THAT(getsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_LOOP,\n+ &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, kSockOptOn);\n+}\n+\n} // namespace testing\n} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Make IP_MULTICAST_LOOP and IP_MULTICAST_TTL allow setting int or char. This is the correct Linux behavior, and at least PHP depends on it. PiperOrigin-RevId: 237565639 Change-Id: I931af09c8ed99a842cf70d22bfe0b65e330c4137
259,854
09.03.2019 11:39:41
28,800
71d53382bfb3a6f05e90e31df8f39d22c0131040
Fix getsockopt(IP_MULTICAST_IF). getsockopt(IP_MULTICAST_IF) only supports struct in_addr. Also adds support for setsockopt(IP_MULTICAST_IF) with struct in_addr.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/epsocket/epsocket.go", "new_path": "pkg/sentry/socket/epsocket/epsocket.go", "diff": "@@ -888,7 +888,7 @@ func getSockOptIP(t *kernel.Task, ep commonEndpoint, name, outLen int) (interfac\nreturn int32(v), nil\ncase linux.IP_MULTICAST_IF:\n- if outLen < inetMulticastRequestSize {\n+ if outLen < len(linux.InetAddr{}) {\nreturn nil, syserr.ErrInvalidArgument\n}\n@@ -899,17 +899,7 @@ func getSockOptIP(t *kernel.Task, ep commonEndpoint, name, outLen int) (interfac\na, _ := ConvertAddress(linux.AF_INET, tcpip.FullAddress{Addr: v.InterfaceAddr})\n- rv := linux.InetMulticastRequestWithNIC{\n- linux.InetMulticastRequest{\n- InterfaceAddr: a.(linux.SockAddrInet).Addr,\n- },\n- int32(v.NIC),\n- }\n-\n- if outLen >= inetMulticastRequestWithNICSize {\n- return rv, nil\n- }\n- return rv.InetMulticastRequest, nil\n+ return a.(linux.SockAddrInet).Addr, nil\ncase linux.IP_MULTICAST_LOOP:\nif outLen < sizeOfInt32 {\n@@ -1179,17 +1169,34 @@ var (\ninetMulticastRequestWithNICSize = int(binary.Size(linux.InetMulticastRequestWithNIC{}))\n)\n-func copyInMulticastRequest(optVal []byte) (linux.InetMulticastRequestWithNIC, *syserr.Error) {\n+// copyInMulticastRequest copies in a variable-size multicast request. The\n+// kernel determines which structure was passed by its length. IP_MULTICAST_IF\n+// supports ip_mreqn, ip_mreq and in_addr, while IP_ADD_MEMBERSHIP and\n+// IP_DROP_MEMBERSHIP only support ip_mreqn and ip_mreq. To handle this,\n+// allowAddr controls whether in_addr is accepted or rejected.\n+func copyInMulticastRequest(optVal []byte, allowAddr bool) (linux.InetMulticastRequestWithNIC, *syserr.Error) {\n+ if len(optVal) < len(linux.InetAddr{}) {\n+ return linux.InetMulticastRequestWithNIC{}, syserr.ErrInvalidArgument\n+ }\n+\nif len(optVal) < inetMulticastRequestSize {\n+ if !allowAddr {\nreturn linux.InetMulticastRequestWithNIC{}, syserr.ErrInvalidArgument\n}\nvar req linux.InetMulticastRequestWithNIC\n+ copy(req.InterfaceAddr[:], optVal)\n+ return req, nil\n+ }\n+\nif len(optVal) >= inetMulticastRequestWithNICSize {\n+ var req linux.InetMulticastRequestWithNIC\nbinary.Unmarshal(optVal[:inetMulticastRequestWithNICSize], usermem.ByteOrder, &req)\n- } else {\n- binary.Unmarshal(optVal[:inetMulticastRequestSize], usermem.ByteOrder, &req.InetMulticastRequest)\n+ return req, nil\n}\n+\n+ var req linux.InetMulticastRequestWithNIC\n+ binary.Unmarshal(optVal[:inetMulticastRequestSize], usermem.ByteOrder, &req.InetMulticastRequest)\nreturn req, nil\n}\n@@ -1227,7 +1234,7 @@ func setSockOptIP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *s\nreturn syserr.TranslateNetstackError(ep.SetSockOpt(tcpip.MulticastTTLOption(v)))\ncase linux.IP_ADD_MEMBERSHIP:\n- req, err := copyInMulticastRequest(optVal)\n+ req, err := copyInMulticastRequest(optVal, false /* allowAddr */)\nif err != nil {\nreturn err\n}\n@@ -1241,7 +1248,7 @@ func setSockOptIP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *s\n}))\ncase linux.IP_DROP_MEMBERSHIP:\n- req, err := copyInMulticastRequest(optVal)\n+ req, err := copyInMulticastRequest(optVal, false /* allowAddr */)\nif err != nil {\nreturn err\n}\n@@ -1255,7 +1262,7 @@ func setSockOptIP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *s\n}))\ncase linux.IP_MULTICAST_IF:\n- req, err := copyInMulticastRequest(optVal)\n+ req, err := copyInMulticastRequest(optVal, true /* allowAddr */)\nif err != nil {\nreturn err\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_ipv4_udp_unbound.cc", "new_path": "test/syscalls/linux/socket_ipv4_udp_unbound.cc", "diff": "@@ -893,7 +893,7 @@ TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastDropAddr) {\nreceiver_addr.addr_len),\nSyscallSucceeds());\nsocklen_t receiver_addr_len = receiver_addr.addr_len;\n- EXPECT_THAT(getsockname(sockets->second_fd(),\n+ ASSERT_THAT(getsockname(sockets->second_fd(),\nreinterpret_cast<sockaddr*>(&receiver_addr.addr),\n&receiver_addr_len),\nSyscallSucceeds());\n@@ -951,7 +951,7 @@ TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastDropNic) {\nreceiver_addr.addr_len),\nSyscallSucceeds());\nsocklen_t receiver_addr_len = receiver_addr.addr_len;\n- EXPECT_THAT(getsockname(sockets->second_fd(),\n+ ASSERT_THAT(getsockname(sockets->second_fd(),\nreinterpret_cast<sockaddr*>(&receiver_addr.addr),\n&receiver_addr_len),\nSyscallSucceeds());\n@@ -1016,6 +1016,176 @@ TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastIfInvalidAddr) {\nSyscallFailsWithErrno(EADDRNOTAVAIL));\n}\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastIfSetShort) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ // Create a valid full-sized request.\n+ ip_mreqn iface = {};\n+ iface.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+\n+ // Send an optlen of 1 to check that optlen is enforced.\n+ EXPECT_THAT(\n+ setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF, &iface, 1),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastIfDefault) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ in_addr get = {};\n+ socklen_t size = sizeof(get);\n+ ASSERT_THAT(\n+ getsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF, &get, &size),\n+ SyscallSucceeds());\n+ EXPECT_EQ(size, sizeof(get));\n+ EXPECT_EQ(get.s_addr, 0);\n+}\n+\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastIfDefaultReqn) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ ip_mreqn get = {};\n+ socklen_t size = sizeof(get);\n+ ASSERT_THAT(\n+ getsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF, &get, &size),\n+ SyscallSucceeds());\n+\n+ // getsockopt(IP_MULTICAST_IF) can only return an in_addr, so it treats the\n+ // first sizeof(struct in_addr) bytes of struct ip_mreqn as a struct in_addr.\n+ // Conveniently, this corresponds to the field ip_mreqn::imr_multiaddr.\n+ EXPECT_EQ(size, sizeof(in_addr));\n+\n+ // getsockopt(IP_MULTICAST_IF) will only return the interface address which\n+ // hasn't been set.\n+ EXPECT_EQ(get.imr_multiaddr.s_addr, 0);\n+ EXPECT_EQ(get.imr_address.s_addr, 0);\n+ EXPECT_EQ(get.imr_ifindex, 0);\n+}\n+\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastIfSetAddrGetReqn) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ in_addr set = {};\n+ set.s_addr = htonl(INADDR_LOOPBACK);\n+ ASSERT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF, &set,\n+ sizeof(set)),\n+ SyscallSucceeds());\n+\n+ ip_mreqn get = {};\n+ socklen_t size = sizeof(get);\n+ ASSERT_THAT(\n+ getsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF, &get, &size),\n+ SyscallSucceeds());\n+\n+ // getsockopt(IP_MULTICAST_IF) can only return an in_addr, so it treats the\n+ // first sizeof(struct in_addr) bytes of struct ip_mreqn as a struct in_addr.\n+ // Conveniently, this corresponds to the field ip_mreqn::imr_multiaddr.\n+ EXPECT_EQ(size, sizeof(in_addr));\n+ EXPECT_EQ(get.imr_multiaddr.s_addr, set.s_addr);\n+ EXPECT_EQ(get.imr_address.s_addr, 0);\n+ EXPECT_EQ(get.imr_ifindex, 0);\n+}\n+\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastIfSetReqAddrGetReqn) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ ip_mreq set = {};\n+ set.imr_interface.s_addr = htonl(INADDR_LOOPBACK);\n+ ASSERT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF, &set,\n+ sizeof(set)),\n+ SyscallSucceeds());\n+\n+ ip_mreqn get = {};\n+ socklen_t size = sizeof(get);\n+ ASSERT_THAT(\n+ getsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF, &get, &size),\n+ SyscallSucceeds());\n+\n+ // getsockopt(IP_MULTICAST_IF) can only return an in_addr, so it treats the\n+ // first sizeof(struct in_addr) bytes of struct ip_mreqn as a struct in_addr.\n+ // Conveniently, this corresponds to the field ip_mreqn::imr_multiaddr.\n+ EXPECT_EQ(size, sizeof(in_addr));\n+ EXPECT_EQ(get.imr_multiaddr.s_addr, set.imr_interface.s_addr);\n+ EXPECT_EQ(get.imr_address.s_addr, 0);\n+ EXPECT_EQ(get.imr_ifindex, 0);\n+}\n+\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastIfSetNicGetReqn) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ ip_mreqn set = {};\n+ set.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ ASSERT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF, &set,\n+ sizeof(set)),\n+ SyscallSucceeds());\n+\n+ ip_mreqn get = {};\n+ socklen_t size = sizeof(get);\n+ ASSERT_THAT(\n+ getsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF, &get, &size),\n+ SyscallSucceeds());\n+ EXPECT_EQ(size, sizeof(in_addr));\n+ EXPECT_EQ(get.imr_multiaddr.s_addr, 0);\n+ EXPECT_EQ(get.imr_address.s_addr, 0);\n+ EXPECT_EQ(get.imr_ifindex, 0);\n+}\n+\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastIfSetAddr) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ in_addr set = {};\n+ set.s_addr = htonl(INADDR_LOOPBACK);\n+ ASSERT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF, &set,\n+ sizeof(set)),\n+ SyscallSucceeds());\n+\n+ in_addr get = {};\n+ socklen_t size = sizeof(get);\n+ ASSERT_THAT(\n+ getsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF, &get, &size),\n+ SyscallSucceeds());\n+\n+ EXPECT_EQ(size, sizeof(get));\n+ EXPECT_EQ(get.s_addr, set.s_addr);\n+}\n+\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastIfSetReqAddr) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ ip_mreq set = {};\n+ set.imr_interface.s_addr = htonl(INADDR_LOOPBACK);\n+ ASSERT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF, &set,\n+ sizeof(set)),\n+ SyscallSucceeds());\n+\n+ in_addr get = {};\n+ socklen_t size = sizeof(get);\n+ ASSERT_THAT(\n+ getsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF, &get, &size),\n+ SyscallSucceeds());\n+\n+ EXPECT_EQ(size, sizeof(get));\n+ EXPECT_EQ(get.s_addr, set.imr_interface.s_addr);\n+}\n+\n+TEST_P(IPv4UDPUnboundSocketPairTest, IpMulticastIfSetNic) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ ip_mreqn set = {};\n+ set.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ ASSERT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF, &set,\n+ sizeof(set)),\n+ SyscallSucceeds());\n+\n+ in_addr get = {};\n+ socklen_t size = sizeof(get);\n+ ASSERT_THAT(\n+ getsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF, &get, &size),\n+ SyscallSucceeds());\n+ EXPECT_EQ(size, sizeof(get));\n+ EXPECT_EQ(get.s_addr, 0);\n+}\n+\nTEST_P(IPv4UDPUnboundSocketPairTest, TestJoinGroupNoIf) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n" } ]
Go
Apache License 2.0
google/gvisor
Fix getsockopt(IP_MULTICAST_IF). getsockopt(IP_MULTICAST_IF) only supports struct in_addr. Also adds support for setsockopt(IP_MULTICAST_IF) with struct in_addr. PiperOrigin-RevId: 237620230 Change-Id: I75e7b5b3e08972164eb1906f43ddd67aedffc27c
259,992
11.03.2019 11:46:18
25,200
bc9b979b9412ad5852872c1a9bee462f73d2455e
Add profiling commands to runsc Example: runsc debug --root=<dir> \ --profile-heap=/tmp/heap.prof \ --profile-cpu=/tmp/cpu.prod --profile-delay=30 \ <container ID>
[ { "change_type": "MODIFY", "old_path": "pkg/seccomp/seccomp.go", "new_path": "pkg/seccomp/seccomp.go", "diff": "@@ -55,7 +55,7 @@ func Install(rules SyscallRules) error {\n}\n// Uncomment to get stack trace when there is a violation.\n- // defaultAction = uint32(linux.SECCOMP_RET_TRAP)\n+ // defaultAction = linux.BPFAction(linux.SECCOMP_RET_TRAP)\nlog.Infof(\"Installing seccomp filters for %d syscalls (action=%v)\", len(rules), defaultAction)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/control/BUILD", "new_path": "pkg/sentry/control/BUILD", "diff": "@@ -6,6 +6,7 @@ go_library(\nname = \"control\",\nsrcs = [\n\"control.go\",\n+ \"pprof.go\",\n\"proc.go\",\n\"state.go\",\n],\n@@ -15,6 +16,7 @@ go_library(\n],\ndeps = [\n\"//pkg/abi/linux\",\n+ \"//pkg/fd\",\n\"//pkg/log\",\n\"//pkg/sentry/fs\",\n\"//pkg/sentry/fs/host\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/control/pprof.go", "diff": "+// Copyright 2019 Google LLC\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 control\n+\n+import (\n+ \"errors\"\n+ \"runtime\"\n+ \"runtime/pprof\"\n+ \"sync\"\n+\n+ \"gvisor.googlesource.com/gvisor/pkg/fd\"\n+ \"gvisor.googlesource.com/gvisor/pkg/urpc\"\n+)\n+\n+var errNoOutput = errors.New(\"no output writer provided\")\n+\n+// ProfileOpts contains options for the StartCPUProfile/Goroutine RPC call.\n+type ProfileOpts struct {\n+ // File is the filesystem path for the profile.\n+ File string `json:\"path\"`\n+\n+ // FilePayload is the destination for the profiling output.\n+ urpc.FilePayload\n+}\n+\n+// Profile includes profile-related RPC stubs. It provides a way to\n+// control the built-in pprof facility in sentry via sentryctl.\n+//\n+// The following options to sentryctl are added:\n+//\n+// - collect CPU profile on-demand.\n+// sentryctl -pid <pid> pprof-cpu-start\n+// sentryctl -pid <pid> pprof-cpu-stop\n+//\n+// - dump out the stack trace of current go routines.\n+// sentryctl -pid <pid> pprof-goroutine\n+type Profile struct {\n+ // mu protects the fields below.\n+ mu sync.Mutex\n+\n+ // cpuFile is the current CPU profile output file.\n+ cpuFile *fd.FD\n+}\n+\n+// StartCPUProfile is an RPC stub which starts recording the CPU profile in a\n+// file.\n+func (p *Profile) StartCPUProfile(o *ProfileOpts, _ *struct{}) error {\n+ if len(o.FilePayload.Files) < 1 {\n+ return errNoOutput\n+ }\n+\n+ output, err := fd.NewFromFile(o.FilePayload.Files[0])\n+ if err != nil {\n+ return err\n+ }\n+\n+ p.mu.Lock()\n+ defer p.mu.Unlock()\n+\n+ // Returns an error if profiling is already started.\n+ if err := pprof.StartCPUProfile(output); err != nil {\n+ output.Close()\n+ return err\n+ }\n+\n+ p.cpuFile = output\n+ return nil\n+}\n+\n+// StopCPUProfile is an RPC stub which stops the CPU profiling and flush out the\n+// profile data. It takes no argument.\n+func (p *Profile) StopCPUProfile(_, _ *struct{}) error {\n+ p.mu.Lock()\n+ defer p.mu.Unlock()\n+\n+ if p.cpuFile == nil {\n+ return errors.New(\"CPU profiling not started\")\n+ }\n+\n+ pprof.StopCPUProfile()\n+ p.cpuFile.Close()\n+ p.cpuFile = nil\n+ return nil\n+}\n+\n+// HeapProfile generates a heap profile for the sentry.\n+func (p *Profile) HeapProfile(o *ProfileOpts, _ *struct{}) error {\n+ if len(o.FilePayload.Files) < 1 {\n+ return errNoOutput\n+ }\n+ output := o.FilePayload.Files[0]\n+ defer output.Close()\n+ runtime.GC() // Get up-to-date statistics.\n+ if err := pprof.WriteHeapProfile(output); err != nil {\n+ return err\n+ }\n+ return nil\n+}\n+\n+// Goroutine is an RPC stub which dumps out the stack trace for all running\n+// goroutines.\n+func (p *Profile) Goroutine(o *ProfileOpts, _ *struct{}) error {\n+ if len(o.FilePayload.Files) < 1 {\n+ return errNoOutput\n+ }\n+ output := o.FilePayload.Files[0]\n+ defer output.Close()\n+ if err := pprof.Lookup(\"goroutine\").WriteTo(output, 2); err != nil {\n+ return err\n+ }\n+ return nil\n+}\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/config.go", "new_path": "runsc/boot/config.go", "diff": "@@ -202,6 +202,9 @@ type Config struct {\n// SIGUSR2(12) to troubleshoot hangs. -1 disables it.\nPanicSignal int\n+ // ProfileEnable is set to prepare the sandbox to be profiled.\n+ ProfileEnable bool\n+\n// TestOnlyAllowRunAsCurrentUserWithoutChroot should only be used in\n// tests. It allows runsc to start the sandbox process as the current\n// user, and without chrooting the sandbox process. This can be\n@@ -228,6 +231,7 @@ func (c *Config) ToFlags() []string {\n\"--strace-log-size=\" + strconv.Itoa(int(c.StraceLogSize)),\n\"--watchdog-action=\" + c.WatchdogAction.String(),\n\"--panic-signal=\" + strconv.Itoa(c.PanicSignal),\n+ \"--profile=\" + strconv.FormatBool(c.ProfileEnable),\n}\nif c.TestOnlyAllowRunAsCurrentUserWithoutChroot {\n// Only include if set since it is never to be used by users.\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/controller.go", "new_path": "runsc/boot/controller.go", "diff": "@@ -95,6 +95,11 @@ const (\n// SandboxStacks collects sandbox stacks for debugging.\nSandboxStacks = \"debug.Stacks\"\n+\n+ // Profiling related commands (see pprof.go for more details).\n+ StartCPUProfile = \"Profile.StartCPUProfile\"\n+ StopCPUProfile = \"Profile.StopCPUProfile\"\n+ HeapProfile = \"Profile.HeapProfile\"\n)\n// ControlSocketAddr generates an abstract unix socket name for the given ID.\n@@ -135,6 +140,9 @@ func newController(fd int, l *Loader) (*controller, error) {\n}\nsrv.Register(&debug{})\n+ if l.conf.ProfileEnable {\n+ srv.Register(&control.Profile{})\n+ }\nreturn &controller{\nsrv: srv,\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/filter/config.go", "new_path": "runsc/boot/filter/config.go", "diff": "@@ -470,3 +470,16 @@ func controlServerFilters(fd int) seccomp.SyscallRules {\n},\n}\n}\n+\n+// profileFilters returns extra syscalls made by runtime/pprof package.\n+func profileFilters() seccomp.SyscallRules {\n+ return seccomp.SyscallRules{\n+ syscall.SYS_OPENAT: []seccomp.Rule{\n+ {\n+ seccomp.AllowAny{},\n+ seccomp.AllowAny{},\n+ seccomp.AllowValue(syscall.O_RDONLY | syscall.O_LARGEFILE | syscall.O_CLOEXEC),\n+ },\n+ },\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/filter/filter.go", "new_path": "runsc/boot/filter/filter.go", "diff": "@@ -31,6 +31,7 @@ import (\ntype Options struct {\nPlatform platform.Platform\nHostNetwork bool\n+ ProfileEnable bool\nControllerFD int\n}\n@@ -47,6 +48,10 @@ func Install(opt Options) error {\nReport(\"host networking enabled: syscall filters less restrictive!\")\ns.Merge(hostInetFilters())\n}\n+ if opt.ProfileEnable {\n+ Report(\"profile enabled: syscall filters less restrictive!\")\n+ s.Merge(profileFilters())\n+ }\nswitch p := opt.Platform.(type) {\ncase *ptrace.PTrace:\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/loader.go", "new_path": "runsc/boot/loader.go", "diff": "@@ -447,6 +447,7 @@ func (l *Loader) run() error {\nopts := filter.Options{\nPlatform: l.k.Platform,\nHostNetwork: l.conf.Network == NetworkHost,\n+ ProfileEnable: l.conf.ProfileEnable,\nControllerFD: l.ctrl.srv.FD(),\n}\nif err := filter.Install(opts); err != nil {\n" }, { "change_type": "MODIFY", "old_path": "runsc/cmd/debug.go", "new_path": "runsc/cmd/debug.go", "diff": "@@ -16,7 +16,9 @@ package cmd\nimport (\n\"context\"\n+ \"os\"\n\"syscall\"\n+ \"time\"\n\"flag\"\n\"github.com/google/subcommands\"\n@@ -30,6 +32,9 @@ type Debug struct {\npid int\nstacks bool\nsignal int\n+ profileHeap string\n+ profileCPU string\n+ profileDelay int\n}\n// Name implements subcommands.Command.\n@@ -51,6 +56,9 @@ func (*Debug) Usage() string {\nfunc (d *Debug) SetFlags(f *flag.FlagSet) {\nf.IntVar(&d.pid, \"pid\", 0, \"sandbox process ID. Container ID is not necessary if this is set\")\nf.BoolVar(&d.stacks, \"stacks\", false, \"if true, dumps all sandbox stacks to the log\")\n+ f.StringVar(&d.profileHeap, \"profile-heap\", \"\", \"writes heap profile to the given file.\")\n+ f.StringVar(&d.profileCPU, \"profile-cpu\", \"\", \"writes CPU profile to the given file.\")\n+ f.IntVar(&d.profileDelay, \"profile-delay\", 5, \"amount of time to wait before stoping CPU profile\")\nf.IntVar(&d.signal, \"signal\", -1, \"sends signal to the sandbox\")\n}\n@@ -114,5 +122,35 @@ func (d *Debug) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\n}\nlog.Infof(\" *** Stack dump ***\\n%s\", stacks)\n}\n+ if d.profileCPU != \"\" {\n+ f, err := os.Create(d.profileCPU)\n+ if err != nil {\n+ Fatalf(err.Error())\n+ }\n+ defer f.Close()\n+\n+ if err := c.Sandbox.StartCPUProfile(f); err != nil {\n+ Fatalf(err.Error())\n+ }\n+ log.Infof(\"CPU profile started for %d sec, writing to %q\", d.profileDelay, d.profileCPU)\n+ time.Sleep(time.Duration(d.profileDelay) * time.Second)\n+\n+ if err := c.Sandbox.StopCPUProfile(); err != nil {\n+ Fatalf(err.Error())\n+ }\n+ log.Infof(\"CPU profile written to %q\", d.profileCPU)\n+ }\n+ if d.profileHeap != \"\" {\n+ f, err := os.Create(d.profileHeap)\n+ if err != nil {\n+ Fatalf(err.Error())\n+ }\n+ defer f.Close()\n+\n+ if err := c.Sandbox.HeapProfile(f); err != nil {\n+ Fatalf(err.Error())\n+ }\n+ log.Infof(\"Heap profile written to %q\", d.profileHeap)\n+ }\nreturn subcommands.ExitSuccess\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/main.go", "new_path": "runsc/main.go", "diff": "@@ -63,6 +63,7 @@ var (\noverlay = flag.Bool(\"overlay\", false, \"wrap filesystem mounts with writable overlay. All modifications are stored in memory inside the sandbox.\")\nwatchdogAction = flag.String(\"watchdog-action\", \"log\", \"sets what action the watchdog takes when triggered: log (default), panic.\")\npanicSignal = flag.Int(\"panic-signal\", -1, \"register signal handling that panics. Usually set to SIGUSR2(12) to troubleshoot hangs. -1 disables it.\")\n+ profile = flag.Bool(\"profile\", false, \"prepares the sandbox to use Golang profiler. Note that enabling profiler loosens the seccomp protection added to the sandbox (DO NOT USE IN PRODUCTION).\")\ntestOnlyAllowRunAsCurrentUserWithoutChroot = flag.Bool(\"TESTONLY-unsafe-nonroot\", false, \"TEST ONLY; do not ever use! This skips many security measures that isolate the host from the sandbox.\")\n)\n@@ -146,6 +147,7 @@ func main() {\nStraceLogSize: *straceLogSize,\nWatchdogAction: wa,\nPanicSignal: *panicSignal,\n+ ProfileEnable: *profile,\nTestOnlyAllowRunAsCurrentUserWithoutChroot: *testOnlyAllowRunAsCurrentUserWithoutChroot,\n}\nif len(*straceSyscalls) != 0 {\n" }, { "change_type": "MODIFY", "old_path": "runsc/sandbox/sandbox.go", "new_path": "runsc/sandbox/sandbox.go", "diff": "@@ -825,6 +825,61 @@ func (s *Sandbox) Stacks() (string, error) {\nreturn stacks, nil\n}\n+// HeapProfile writes a heap profile to the given file.\n+func (s *Sandbox) HeapProfile(f *os.File) error {\n+ log.Debugf(\"Heap profile %q\", s.ID)\n+ conn, err := s.sandboxConnect()\n+ if err != nil {\n+ return err\n+ }\n+ defer conn.Close()\n+\n+ opts := control.ProfileOpts{\n+ FilePayload: urpc.FilePayload{\n+ Files: []*os.File{f},\n+ },\n+ }\n+ if err := conn.Call(boot.HeapProfile, &opts, nil); err != nil {\n+ return fmt.Errorf(\"getting sandbox %q heap profile: %v\", s.ID, err)\n+ }\n+ return nil\n+}\n+\n+// StartCPUProfile start CPU profile writing to the given file.\n+func (s *Sandbox) StartCPUProfile(f *os.File) error {\n+ log.Debugf(\"CPU profile start %q\", s.ID)\n+ conn, err := s.sandboxConnect()\n+ if err != nil {\n+ return err\n+ }\n+ defer conn.Close()\n+\n+ opts := control.ProfileOpts{\n+ FilePayload: urpc.FilePayload{\n+ Files: []*os.File{f},\n+ },\n+ }\n+ if err := conn.Call(boot.StartCPUProfile, &opts, nil); err != nil {\n+ return fmt.Errorf(\"starting sandbox %q CPU profile: %v\", s.ID, err)\n+ }\n+ return nil\n+}\n+\n+// StopCPUProfile stops a previously started CPU profile.\n+func (s *Sandbox) StopCPUProfile() error {\n+ log.Debugf(\"CPU profile stop %q\", s.ID)\n+ conn, err := s.sandboxConnect()\n+ if err != nil {\n+ return err\n+ }\n+ defer conn.Close()\n+\n+ if err := conn.Call(boot.StopCPUProfile, nil, nil); err != nil {\n+ return fmt.Errorf(\"stopping sandbox %q CPU profile: %v\", s.ID, err)\n+ }\n+ return nil\n+}\n+\n// DestroyContainer destroys the given container. If it is the root container,\n// then the entire sandbox is destroyed.\nfunc (s *Sandbox) DestroyContainer(cid string) error {\n" } ]
Go
Apache License 2.0
google/gvisor
Add profiling commands to runsc Example: runsc debug --root=<dir> \ --profile-heap=/tmp/heap.prof \ --profile-cpu=/tmp/cpu.prod --profile-delay=30 \ <container ID> PiperOrigin-RevId: 237848456 Change-Id: Icff3f20c1b157a84d0922599eaea327320dad773
259,853
11.03.2019 17:00:48
25,200
4a8062990f33f33b3972feb0a7f2abe55bae16c7
gvisor/kokoro: don't downgrade libseccomp It isn't required with a new vm image.
[ { "change_type": "MODIFY", "old_path": "kokoro/run_tests.sh", "new_path": "kokoro/run_tests.sh", "diff": "@@ -44,6 +44,9 @@ use_bazel.sh latest\nwhich bazel\nbazel version\n+# Load the kvm module\n+sudo -n -E modprobe kvm\n+\n# Bazel start-up flags for RBE.\nBAZEL_RBE_FLAGS=(\n\"--bazelrc=${WORKSPACE_DIR}/.bazelrc_rbe\"\n@@ -99,9 +102,7 @@ install_runtime() {\n# Install dependencies for the crictl tests.\ninstall_crictl_test_deps() {\n# Install containerd.\n- # libseccomp2 needs to be downgraded in order to install libseccomp-dev.\nsudo -n -E apt-get update\n- sudo -n -E apt-get install -y --force-yes libseccomp2=2.1.1-1ubuntu1~trusty5\nsudo -n -E apt-get install -y btrfs-tools libseccomp-dev\n# go get will exit with a status of 1 despite succeeding, so ignore errors.\ngo get -d github.com/containerd/containerd || true\n" } ]
Go
Apache License 2.0
google/gvisor
gvisor/kokoro: don't downgrade libseccomp It isn't required with a new vm image. PiperOrigin-RevId: 237915203 Change-Id: I813e7f1801d0766cec598413718e5ddd4c3d8cdf
259,858
11.03.2019 18:18:41
25,200
6e6dbf0e566270ae96a4db81d9d04275d0fffb00
kvm: minimum guest/host timekeeping delta.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/machine_amd64_unsafe.go", "new_path": "pkg/sentry/platform/kvm/machine_amd64_unsafe.go", "diff": "@@ -87,17 +87,26 @@ func (c *vCPU) setCPUID() error {\n// setSystemTime sets the TSC for the vCPU.\n//\n-// FIXME: This introduces a slight TSC offset between host and\n-// guest, which may vary per vCPU.\n+// This has to make the call many times in order to minimize the intrinstic\n+// error in the offset. Unfortunately KVM does not expose a relative offset via\n+// the API, so this is an approximation. We do this via an iterative algorithm.\n+// This has the advantage that it can generally deal with highly variable\n+// system call times and should converge on the correct offset.\nfunc (c *vCPU) setSystemTime() error {\n- const _MSR_IA32_TSC = 0x00000010\n+ const (\n+ _MSR_IA32_TSC = 0x00000010\n+ calibrateTries = 10\n+ )\nregisters := modelControlRegisters{\nnmsrs: 1,\n}\nregisters.entries[0] = modelControlRegister{\nindex: _MSR_IA32_TSC,\n- data: uint64(time.Rdtsc()),\n}\n+ target := uint64(^uint32(0))\n+ for done := 0; done < calibrateTries; {\n+ start := uint64(time.Rdtsc())\n+ registers.entries[0].data = start + target\nif _, _, errno := syscall.RawSyscall(\nsyscall.SYS_IOCTL,\nuintptr(c.fd),\n@@ -105,6 +114,24 @@ func (c *vCPU) setSystemTime() error {\nuintptr(unsafe.Pointer(&registers))); errno != 0 {\nreturn fmt.Errorf(\"error setting system time: %v\", errno)\n}\n+ // See if this is our new minimum call time. Note that this\n+ // serves two functions: one, we make sure that we are\n+ // accurately predicting the offset we need to set. Second, we\n+ // don't want to do the final set on a slow call, which could\n+ // produce a really bad result. So we only count attempts\n+ // within +/- 6.25% of our minimum as an attempt.\n+ end := uint64(time.Rdtsc())\n+ if end < start {\n+ continue // Totally bogus.\n+ }\n+ half := (end - start) / 2\n+ if half < target {\n+ target = half\n+ }\n+ if (half - target) < target/8 {\n+ done++\n+ }\n+ }\nreturn nil\n}\n" } ]
Go
Apache License 2.0
google/gvisor
kvm: minimum guest/host timekeeping delta. PiperOrigin-RevId: 237927368 Change-Id: I359badd1967bb118fe74eab3282c946c18937edc
259,901
12.03.2019 15:35:32
25,200
8003bd6a5c012784c0b2a2dad93cbec969fac3b0
Make gonet.PacketConn implement net.Conn. gonet.PacketConn now implements net.Conn, allowing it to be returned from net.Dial.Dialer functions.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/adapters/gonet/gonet.go", "new_path": "pkg/tcpip/adapters/gonet/gonet.go", "diff": "@@ -557,6 +557,21 @@ func (c *PacketConn) newRemoteOpError(op string, remote net.Addr, err error) *ne\n}\n}\n+// RemoteAddr implements net.Conn.RemoteAddr.\n+func (c *PacketConn) RemoteAddr() net.Addr {\n+ a, err := c.ep.GetRemoteAddress()\n+ if err != nil {\n+ return nil\n+ }\n+ return fullToTCPAddr(a)\n+}\n+\n+// Read implements net.Conn.Read\n+func (c *PacketConn) Read(b []byte) (int, error) {\n+ bytesRead, _, err := c.ReadFrom(b)\n+ return bytesRead, err\n+}\n+\n// ReadFrom implements net.PacketConn.ReadFrom.\nfunc (c *PacketConn) ReadFrom(b []byte) (int, net.Addr, error) {\ndeadline := c.readCancel()\n@@ -570,6 +585,10 @@ func (c *PacketConn) ReadFrom(b []byte) (int, net.Addr, error) {\nreturn copy(b, read), fullToUDPAddr(addr), nil\n}\n+func (c *PacketConn) Write(b []byte) (int, error) {\n+ return c.WriteTo(b, nil)\n+}\n+\n// WriteTo implements net.PacketConn.WriteTo.\nfunc (c *PacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {\ndeadline := c.writeCancel()\n@@ -581,13 +600,16 @@ func (c *PacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {\ndefault:\n}\n+ // If we're being called by Write, there is no addr\n+ wopts := tcpip.WriteOptions{}\n+ if addr != nil {\nua := addr.(*net.UDPAddr)\n- fullAddr := tcpip.FullAddress{Addr: tcpip.Address(ua.IP), Port: uint16(ua.Port)}\n+ wopts.To = &tcpip.FullAddress{Addr: tcpip.Address(ua.IP), Port: uint16(ua.Port)}\n+ }\nv := buffer.NewView(len(b))\ncopy(v, b)\n- wopts := tcpip.WriteOptions{To: &fullAddr}\nn, resCh, err := c.ep.Write(tcpip.SlicePayload(v), wopts)\nif resCh != nil {\nselect {\n" } ]
Go
Apache License 2.0
google/gvisor
Make gonet.PacketConn implement net.Conn. gonet.PacketConn now implements net.Conn, allowing it to be returned from net.Dial.Dialer functions. PiperOrigin-RevId: 238111980 Change-Id: I174884385ff4d9b8e9918fac7bbb5b93ca366ba7
259,992
13.03.2019 15:24:09
25,200
70d06134442843cd4355590c4155ee6594558c00
Reduce PACKET_RX_RING memory usage Previous memory allocation was excessive (80 MB). Changed it to use 2 MB instead. There is no drop in perfomance due to this change: ab -n 100 -c 10 ==> 10 MB file 80 MB: 178 MB/s 2 MB: 181 MB/s
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/fdbased/mmap_amd64_unsafe.go", "new_path": "pkg/tcpip/link/fdbased/mmap_amd64_unsafe.go", "diff": "@@ -40,11 +40,13 @@ const (\n// We overallocate the frame size to accommodate space for the\n// TPacketHdr+RawSockAddrLinkLayer+MAC header and any padding.\n//\n+// Memory allocated for the ring buffer: tpBlockSize * tpBlockNR = 2 MiB\n+//\n// NOTE: Frames need to be aligned at 16 byte boundaries.\nconst (\ntpFrameSize = 65536 + 128\n- tpBlockSize = tpFrameSize * 128\n- tpBlockNR = 10\n+ tpBlockSize = tpFrameSize * 32\n+ tpBlockNR = 1\ntpFrameNR = (tpBlockSize * tpBlockNR) / tpFrameSize\n)\n" } ]
Go
Apache License 2.0
google/gvisor
Reduce PACKET_RX_RING memory usage Previous memory allocation was excessive (80 MB). Changed it to use 2 MB instead. There is no drop in perfomance due to this change: ab -n 100 -c 10 http://server/latin10m.txt ==> 10 MB file 80 MB: 178 MB/s 2 MB: 181 MB/s PiperOrigin-RevId: 238321594 Change-Id: I1c8aed13cad5d75f4506d2b406b305117055fbe5
259,885
14.03.2019 07:42:13
25,200
fb9919881c7dc98eaf97cad2a70d187bd78f1566
Use WalkGetAttr in gofer.inodeOperations.Create. p9.Twalk.handle() with a non-empty path also stats the walked-to path anyway, so the preceding GetAttr is completely wasted.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/path.go", "new_path": "pkg/sentry/fs/gofer/path.go", "diff": "@@ -18,6 +18,7 @@ import (\n\"fmt\"\n\"syscall\"\n+ \"gvisor.googlesource.com/gvisor/pkg/log\"\n\"gvisor.googlesource.com/gvisor/pkg/p9\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/context\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/device\"\n@@ -101,20 +102,20 @@ func (i *inodeOperations) Create(ctx context.Context, dir *fs.Inode, name string\ni.touchModificationTime(ctx, dir)\n- // Get the attributes of the file.\n- qid, mask, p9attr, err := getattr(ctx, newFile)\n+ // Get an unopened p9.File for the file we created so that it can be cloned\n+ // and re-opened multiple times after creation, while also getting its\n+ // attributes. Both are required for inodeOperations.\n+ qids, unopened, mask, p9attr, err := i.fileState.file.walkGetAttr(ctx, []string{name})\nif err != nil {\nnewFile.close(ctx)\nreturn nil, err\n}\n-\n- // Get an unopened p9.File for the file we created so that it can be\n- // cloned and re-opened multiple times after creation.\n- _, unopened, err := i.fileState.file.walk(ctx, []string{name})\n- if err != nil {\n+ if len(qids) != 1 {\n+ log.Warningf(\"WalkGetAttr(%s) succeeded, but returned %d QIDs (%v), wanted 1\", name, len(qids), qids)\nnewFile.close(ctx)\n- return nil, err\n+ return nil, syserror.EIO\n}\n+ qid := qids[0]\n// Construct the InodeOperations.\nsattr, iops := newInodeOperations(ctx, i.fileState.s, unopened, qid, mask, p9attr, false)\n" } ]
Go
Apache License 2.0
google/gvisor
Use WalkGetAttr in gofer.inodeOperations.Create. p9.Twalk.handle() with a non-empty path also stats the walked-to path anyway, so the preceding GetAttr is completely wasted. PiperOrigin-RevId: 238440645 Change-Id: I7fbc7536f46b8157639d0d1f491e6aaa9ab688a3
259,891
14.03.2019 10:45:54
25,200
6ee3d6614b3616a62e177630dfd152ab61211ba2
Fix flaky RawPingAndSockets (and MultipleSocketsRecieve just in case).
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/raw_socket_ipv4.cc", "new_path": "test/syscalls/linux/raw_socket_ipv4.cc", "diff": "@@ -164,24 +164,46 @@ TEST_F(RawSocketTest, MultipleSocketReceive) {\nicmp.un.echo.id = 2018;\nASSERT_NO_FATAL_FAILURE(SendEmptyICMP(&icmp));\n- // Receive it on socket 1.\n- char recv_buf1[512];\n+ // Both sockets will receive the echo request and reply in indeterminate\n+ // order, so we'll need to read 2 packets from each.\n+\n+ // Receive on socket 1.\n+ constexpr int kBufSize = 256;\n+ std::vector<char[kBufSize]> recv_buf1(2);\nstruct sockaddr_in src;\n- ASSERT_NO_FATAL_FAILURE(ReceiveICMP(recv_buf1, ABSL_ARRAYSIZE(recv_buf1),\n+ for (int i = 0; i < 2; i++) {\n+ ASSERT_NO_FATAL_FAILURE(ReceiveICMP(recv_buf1[i],\n+ ABSL_ARRAYSIZE(recv_buf1[i]),\nsizeof(struct icmphdr), &src));\nEXPECT_EQ(memcmp(&src, &addr_, sizeof(sockaddr_in)), 0);\n+ }\n- // Receive it on socket 2.\n- char recv_buf2[512];\n- ASSERT_NO_FATAL_FAILURE(ReceiveICMPFrom(recv_buf2, ABSL_ARRAYSIZE(recv_buf2),\n- sizeof(struct icmphdr), &src,\n- s2.get()));\n+ // Receive on socket 2.\n+ std::vector<char[kBufSize]> recv_buf2(2);\n+ for (int i = 0; i < 2; i++) {\n+ ASSERT_NO_FATAL_FAILURE(\n+ ReceiveICMPFrom(recv_buf2[i], ABSL_ARRAYSIZE(recv_buf2[i]),\n+ sizeof(struct icmphdr), &src, s2.get()));\nEXPECT_EQ(memcmp(&src, &addr_, sizeof(sockaddr_in)), 0);\n+ }\n- EXPECT_EQ(memcmp(recv_buf1 + sizeof(struct iphdr),\n- recv_buf2 + sizeof(struct iphdr), sizeof(icmp)),\n+ // Ensure both sockets receive identical packets.\n+ int types[] = {ICMP_ECHO, ICMP_ECHOREPLY};\n+ for (int type : types) {\n+ auto match_type = [=](char buf[kBufSize]) {\n+ struct icmphdr *icmp =\n+ reinterpret_cast<struct icmphdr *>(buf + sizeof(struct iphdr));\n+ return icmp->type == type;\n+ };\n+ char *icmp1 = *std::find_if(recv_buf1.begin(), recv_buf1.end(), match_type);\n+ char *icmp2 = *std::find_if(recv_buf2.begin(), recv_buf2.end(), match_type);\n+ ASSERT_NE(icmp1, *recv_buf1.end());\n+ ASSERT_NE(icmp2, *recv_buf2.end());\n+ EXPECT_EQ(memcmp(icmp1 + sizeof(struct iphdr), icmp2 + sizeof(struct iphdr),\n+ sizeof(icmp)),\n0);\n}\n+}\n// A raw ICMP socket and ping socket should both receive the ICMP packets\n// indended for the ping socket.\n@@ -201,23 +223,47 @@ TEST_F(RawSocketTest, RawAndPingSockets) {\n(struct sockaddr *)&addr_, sizeof(addr_)),\nSyscallSucceedsWithValue(sizeof(icmp)));\n- // Receive the packet via raw socket.\n- char recv_buf[512];\n+ // Both sockets will receive the echo request and reply in indeterminate\n+ // order, so we'll need to read 2 packets from each.\n+\n+ // Receive on socket 1.\n+ constexpr int kBufSize = 256;\n+ std::vector<char[kBufSize]> recv_buf1(2);\nstruct sockaddr_in src;\n- ASSERT_NO_FATAL_FAILURE(ReceiveICMP(recv_buf, ABSL_ARRAYSIZE(recv_buf),\n- sizeof(struct icmphdr), &src));\n+ for (int i = 0; i < 2; i++) {\n+ ASSERT_NO_FATAL_FAILURE(\n+ ReceiveICMP(recv_buf1[i], kBufSize, sizeof(struct icmphdr), &src));\nEXPECT_EQ(memcmp(&src, &addr_, sizeof(sockaddr_in)), 0);\n+ }\n- // Receive the packet via ping socket.\n- struct icmphdr ping_header;\n- ASSERT_THAT(\n- RetryEINTR(recv)(ping_sock.get(), &ping_header, sizeof(ping_header), 0),\n- SyscallSucceedsWithValue(sizeof(ping_header)));\n+ // Receive on socket 2.\n+ std::vector<char[kBufSize]> recv_buf2(2);\n+ for (int i = 0; i < 2; i++) {\n+ ASSERT_THAT(RetryEINTR(recv)(ping_sock.get(), recv_buf2[i], kBufSize, 0),\n+ SyscallSucceedsWithValue(sizeof(struct icmphdr)));\n+ }\n- // Packets should be the same.\n- EXPECT_EQ(memcmp(recv_buf + sizeof(struct iphdr), &ping_header,\n- sizeof(struct icmphdr)),\n- 0);\n+ // Ensure both sockets receive identical packets.\n+ int types[] = {ICMP_ECHO, ICMP_ECHOREPLY};\n+ for (int type : types) {\n+ auto match_type_ping = [=](char buf[kBufSize]) {\n+ struct icmphdr *icmp = reinterpret_cast<struct icmphdr *>(buf);\n+ return icmp->type == type;\n+ };\n+ auto match_type_raw = [=](char buf[kBufSize]) {\n+ struct icmphdr *icmp =\n+ reinterpret_cast<struct icmphdr *>(buf + sizeof(struct iphdr));\n+ return icmp->type == type;\n+ };\n+\n+ char *icmp1 =\n+ *std::find_if(recv_buf1.begin(), recv_buf1.end(), match_type_raw);\n+ char *icmp2 =\n+ *std::find_if(recv_buf2.begin(), recv_buf2.end(), match_type_ping);\n+ ASSERT_NE(icmp1, *recv_buf1.end());\n+ ASSERT_NE(icmp2, *recv_buf2.end());\n+ EXPECT_EQ(memcmp(icmp1 + sizeof(struct iphdr), icmp2, sizeof(icmp)), 0);\n+ }\n}\nvoid RawSocketTest::SendEmptyICMP(struct icmphdr *icmp) {\n" } ]
Go
Apache License 2.0
google/gvisor
Fix flaky RawPingAndSockets (and MultipleSocketsRecieve just in case). PiperOrigin-RevId: 238474202 Change-Id: Ib8c431e973e8cf1e1c8ee2f8c1978ddb8e88b0b8
259,985
18.03.2019 10:47:59
25,200
cea1dd7d21b976ad5cb145b94be7b1bf879235be
Remove racy access to shm fields.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/shm/shm.go", "new_path": "pkg/sentry/kernel/shm/shm.go", "diff": "@@ -286,7 +286,7 @@ func (r *Registry) remove(s *Shm) {\ndefer s.mu.Unlock()\nif s.key != linux.IPC_PRIVATE {\n- panic(fmt.Sprintf(\"Attempted to remove shm segment %+v from the registry whose key is still associated\", s))\n+ panic(fmt.Sprintf(\"Attempted to remove shm segment %d (key=%d) from the registry whose key is still associated\", s.ID, s.key))\n}\ndelete(r.shms, s.ID)\n" } ]
Go
Apache License 2.0
google/gvisor
Remove racy access to shm fields. PiperOrigin-RevId: 239016776 Change-Id: Ia7af4258e7c69b16a4630a6f3278aa8e6b627746
259,891
18.03.2019 11:31:12
25,200
88d791c259cc2f81b18547ae7f7859c3508cef21
Replace use of ucontext with ucontext_t.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/sigaltstack.cc", "new_path": "test/syscalls/linux/sigaltstack.cc", "diff": "@@ -143,7 +143,7 @@ void badhandler(int sig, siginfo_t* siginfo, void* arg) {\nbadhandler_recursive_faults--;\nFault();\n}\n- FixupFault(reinterpret_cast<ucontext*>(arg));\n+ FixupFault(reinterpret_cast<ucontext_t*>(arg));\n}\nTEST(SigaltstackTest, WalksOffBottom) {\n@@ -215,7 +215,7 @@ void setonstack(int sig, siginfo_t* siginfo, void* arg) {\nstack.ss_size = SIGSTKSZ;\nsetonstack_retval = sigaltstack(&stack, nullptr);\nsetonstack_errno = errno;\n- FixupFault(reinterpret_cast<ucontext*>(arg));\n+ FixupFault(reinterpret_cast<ucontext_t*>(arg));\n}\nTEST(SigaltstackTest, SetWhileOnStack) {\n" }, { "change_type": "MODIFY", "old_path": "test/util/signal_util.h", "new_path": "test/util/signal_util.h", "diff": "@@ -78,7 +78,7 @@ inline void Fault() {\n}\n// FixupFault fixes up a fault generated by fault, above.\n-inline void FixupFault(ucontext* ctx) {\n+inline void FixupFault(ucontext_t* ctx) {\n// Skip the bad instruction above.\n//\n// The encoding is 0x48 0xab 0x00.\n" } ]
Go
Apache License 2.0
google/gvisor
Replace use of ucontext with ucontext_t. PiperOrigin-RevId: 239026571 Change-Id: Ifd01674855094f3abad497776f418023452033a1
259,942
19.03.2019 08:29:37
25,200
928809fa7d3b682c7e2e06c9f9b1f3fb5d75a0d6
Add layer 2 stats (tx, rx) X (packets, bytes) to netstack
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -42,6 +42,20 @@ type NIC struct {\nprimary map[tcpip.NetworkProtocolNumber]*ilist.List\nendpoints map[NetworkEndpointID]*referencedNetworkEndpoint\nsubnets []tcpip.Subnet\n+\n+ stats NICStats\n+}\n+\n+// NICStats includes transmitted and received stats.\n+type NICStats struct {\n+ Tx DirectionStats\n+ Rx DirectionStats\n+}\n+\n+// DirectionStats includes packet and byte counts.\n+type DirectionStats struct {\n+ Packets *tcpip.StatCounter\n+ Bytes *tcpip.StatCounter\n}\n// PrimaryEndpointBehavior is an enumeration of an endpoint's primacy behavior.\n@@ -73,6 +87,16 @@ func newNIC(stack *Stack, id tcpip.NICID, name string, ep LinkEndpoint, loopback\ndemux: newTransportDemuxer(stack),\nprimary: make(map[tcpip.NetworkProtocolNumber]*ilist.List),\nendpoints: make(map[NetworkEndpointID]*referencedNetworkEndpoint),\n+ stats: NICStats{\n+ Tx: DirectionStats{\n+ Packets: &tcpip.StatCounter{},\n+ Bytes: &tcpip.StatCounter{},\n+ },\n+ Rx: DirectionStats{\n+ Packets: &tcpip.StatCounter{},\n+ Bytes: &tcpip.StatCounter{},\n+ },\n+ },\n}\n}\n@@ -384,6 +408,9 @@ func (n *NIC) RemoveAddress(addr tcpip.Address) *tcpip.Error {\n// This rule applies only to the slice itself, not to the items of the slice;\n// the ownership of the items is not retained by the caller.\nfunc (n *NIC) DeliverNetworkPacket(linkEP LinkEndpoint, remote, _ tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, vv buffer.VectorisedView) {\n+ n.stats.Rx.Packets.Increment()\n+ n.stats.Rx.Bytes.IncrementBy(uint64(vv.Size()))\n+\nnetProto, ok := n.stack.networkProtocols[protocol]\nif !ok {\nn.stack.stats.UnknownProtocolRcvdPackets.Increment()\n@@ -457,7 +484,14 @@ func (n *NIC) DeliverNetworkPacket(linkEP LinkEndpoint, remote, _ tcpip.LinkAddr\n// Send the packet out of n.\nhdr := buffer.NewPrependableFromView(vv.First())\nvv.RemoveFirst()\n- n.linkEP.WritePacket(&r, hdr, vv, protocol)\n+\n+ // TODO: use route.WritePacket.\n+ if err := n.linkEP.WritePacket(&r, hdr, vv, protocol); err != nil {\n+ r.Stats().IP.OutgoingPacketErrors.Increment()\n+ } else {\n+ n.stats.Tx.Packets.Increment()\n+ n.stats.Tx.Bytes.IncrementBy(uint64(hdr.UsedLength() + vv.Size()))\n+ }\n}\nreturn\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/route.go", "new_path": "pkg/tcpip/stack/route.go", "diff": "@@ -146,8 +146,11 @@ func (r *Route) IsResolutionRequired() bool {\n// WritePacket writes the packet through the given route.\nfunc (r *Route) WritePacket(hdr buffer.Prependable, payload buffer.VectorisedView, protocol tcpip.TransportProtocolNumber, ttl uint8) *tcpip.Error {\nerr := r.ref.ep.WritePacket(r, hdr, payload, protocol, ttl, r.loop)\n- if err == tcpip.ErrNoRoute {\n+ if err != nil {\nr.Stats().IP.OutgoingPacketErrors.Increment()\n+ } else {\n+ r.ref.nic.stats.Tx.Packets.Increment()\n+ r.ref.nic.stats.Tx.Bytes.IncrementBy(uint64(hdr.UsedLength() + payload.Size()))\n}\nreturn err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack.go", "new_path": "pkg/tcpip/stack/stack.go", "diff": "@@ -627,6 +627,8 @@ type NICInfo struct {\n// MTU is the maximum transmission unit.\nMTU uint32\n+\n+ Stats NICStats\n}\n// NICInfo returns a map of NICIDs to their associated information.\n@@ -648,6 +650,7 @@ func (s *Stack) NICInfo() map[tcpip.NICID]NICInfo {\nProtocolAddresses: nic.Addresses(),\nFlags: flags,\nMTU: nic.linkEP.MTU(),\n+ Stats: nic.stats,\n}\n}\nreturn nics\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack_test.go", "new_path": "pkg/tcpip/stack/stack_test.go", "diff": "@@ -273,7 +273,7 @@ func TestNetworkReceive(t *testing.T) {\n}\n}\n-func sendTo(t *testing.T, s *stack.Stack, addr tcpip.Address) {\n+func sendTo(t *testing.T, s *stack.Stack, addr tcpip.Address, payload buffer.View) {\nr, err := s.FindRoute(0, \"\", addr, fakeNetNumber, false /* multicastLoop */)\nif err != nil {\nt.Fatalf(\"FindRoute failed: %v\", err)\n@@ -281,9 +281,8 @@ func sendTo(t *testing.T, s *stack.Stack, addr tcpip.Address) {\ndefer r.Release()\nhdr := buffer.NewPrependable(int(r.MaxHeaderLength()))\n- if err := r.WritePacket(hdr, buffer.VectorisedView{}, fakeTransNumber, 123); err != nil {\n+ if err := r.WritePacket(hdr, payload.ToVectorisedView(), fakeTransNumber, 123); err != nil {\nt.Errorf(\"WritePacket failed: %v\", err)\n- return\n}\n}\n@@ -304,7 +303,7 @@ func TestNetworkSend(t *testing.T) {\n}\n// Make sure that the link-layer endpoint received the outbound packet.\n- sendTo(t, s, \"\\x03\")\n+ sendTo(t, s, \"\\x03\", nil)\nif c := linkEP.Drain(); c != 1 {\nt.Errorf(\"packetCount = %d, want %d\", c, 1)\n}\n@@ -351,14 +350,14 @@ func TestNetworkSendMultiRoute(t *testing.T) {\n})\n// Send a packet to an odd destination.\n- sendTo(t, s, \"\\x05\")\n+ sendTo(t, s, \"\\x05\", nil)\nif c := linkEP1.Drain(); c != 1 {\nt.Errorf(\"packetCount = %d, want %d\", c, 1)\n}\n// Send a packet to an even destination.\n- sendTo(t, s, \"\\x06\")\n+ sendTo(t, s, \"\\x06\", nil)\nif c := linkEP2.Drain(); c != 1 {\nt.Errorf(\"packetCount = %d, want %d\", c, 1)\n@@ -1055,6 +1054,44 @@ func TestGetMainNICAddressAddRemove(t *testing.T) {\n}\n}\n+func TestNICStats(t *testing.T) {\n+ s := stack.New([]string{\"fakeNet\"}, nil, stack.Options{})\n+ id1, linkEP1 := channel.New(10, defaultMTU, \"\")\n+ if err := s.CreateNIC(1, id1); err != nil {\n+ t.Fatalf(\"CreateNIC failed: %v\", err)\n+ }\n+ if err := s.AddAddress(1, fakeNetNumber, \"\\x01\"); err != nil {\n+ t.Fatalf(\"AddAddress failed: %v\", err)\n+ }\n+ // Route all packets for address \\x01 to NIC 1.\n+ s.SetRouteTable([]tcpip.Route{\n+ {\"\\x01\", \"\\xff\", \"\\x00\", 1},\n+ })\n+\n+ // Send a packet to address 1.\n+ buf := buffer.NewView(30)\n+ linkEP1.Inject(fakeNetNumber, buf.ToVectorisedView())\n+ if got, want := s.NICInfo()[1].Stats.Rx.Packets.Value(), uint64(1); got != want {\n+ t.Errorf(\"got Rx.Packets.Value() = %d, want = %d\", got, want)\n+ }\n+\n+ if got, want := s.NICInfo()[1].Stats.Rx.Bytes.Value(), uint64(len(buf)); got != want {\n+ t.Errorf(\"got Rx.Bytes.Value() = %d, want = %d\", got, want)\n+ }\n+\n+ payload := buffer.NewView(10)\n+ // Write a packet out via the address for NIC 1\n+ sendTo(t, s, \"\\x01\", payload)\n+ want := uint64(linkEP1.Drain())\n+ if got := s.NICInfo()[1].Stats.Tx.Packets.Value(); got != want {\n+ t.Errorf(\"got Tx.Packets.Value() = %d, linkEP1.Drain() = %d\", got, want)\n+ }\n+\n+ if got, want := s.NICInfo()[1].Stats.Tx.Bytes.Value(), uint64(len(payload)); got != want {\n+ t.Errorf(\"got Tx.Bytes.Value() = %d, want = %d\", got, want)\n+ }\n+}\n+\nfunc TestNICForwarding(t *testing.T) {\n// Create a stack with the fake network protocol, two NICs, each with\n// an address.\n@@ -1092,6 +1129,15 @@ func TestNICForwarding(t *testing.T) {\ndefault:\nt.Fatal(\"Packet not forwarded\")\n}\n+\n+ // Test that forwarding increments Tx stats correctly.\n+ if got, want := s.NICInfo()[2].Stats.Tx.Packets.Value(), uint64(1); got != want {\n+ t.Errorf(\"got Tx.Packets.Value() = %d, want = %d\", got, want)\n+ }\n+\n+ if got, want := s.NICInfo()[2].Stats.Tx.Bytes.Value(), uint64(len(buf)); got != want {\n+ t.Errorf(\"got Tx.Bytes.Value() = %d, want = %d\", got, want)\n+ }\n}\nfunc init() {\n" } ]
Go
Apache License 2.0
google/gvisor
Add layer 2 stats (tx, rx) X (packets, bytes) to netstack PiperOrigin-RevId: 239194420 Change-Id: Ie193e8ac2b7a6db21195ac85824a335930483971
259,992
19.03.2019 10:37:46
25,200
7b33df68450bdb9519cf650a8d92fa4a81f37fa0
Fix data race in netlink send buffer size
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netlink/socket.go", "new_path": "pkg/sentry/socket/netlink/socket.go", "diff": "@@ -291,6 +291,8 @@ func (s *Socket) GetSockOpt(t *kernel.Task, level int, name int, outLen int) (in\nif outLen < sizeOfInt32 {\nreturn nil, syserr.ErrInvalidArgument\n}\n+ s.mu.Lock()\n+ defer s.mu.Unlock()\nreturn int32(s.sendBufferSize), nil\ncase linux.SO_RCVBUF:\n@@ -335,7 +337,9 @@ func (s *Socket) SetSockOpt(t *kernel.Task, level int, name int, opt []byte) *sy\n} else if size > maxSendBufferSize {\nsize = maxSendBufferSize\n}\n+ s.mu.Lock()\ns.sendBufferSize = size\n+ s.mu.Unlock()\nreturn nil\ncase linux.SO_RCVBUF:\nif len(opt) < sizeOfInt32 {\n" } ]
Go
Apache License 2.0
google/gvisor
Fix data race in netlink send buffer size PiperOrigin-RevId: 239221041 Change-Id: Icc19e32a00fa89167447ab2f45e90dcfd61bea04
259,853
19.03.2019 17:32:23
25,200
87cce0ec08b9d629a5e3a88be411b1721d767301
netstack: reduce MSS from SYN to account tcp options See:
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/proc/README.md", "new_path": "pkg/sentry/fs/proc/README.md", "diff": "@@ -11,7 +11,6 @@ inconsistency, please file a bug.\nThe following files are implemented:\n-\n| File /proc/ | Content |\n| :------------------------ | :---------------------------------------------------- |\n| [cpuinfo](#cpuinfo) | Info about the CPU |\n@@ -23,7 +22,6 @@ The following files are implemented:\n| [uptime](#uptime) | Wall clock since boot, combined idle time of all cpus |\n| [version](#version) | Kernel version |\n-\n### cpuinfo\n```bash\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint.go", "new_path": "pkg/tcpip/transport/tcp/endpoint.go", "diff": "@@ -1596,6 +1596,16 @@ func (e *endpoint) maybeEnableSACKPermitted(synOpts *header.TCPSynOptions) {\n}\n}\n+// maxOptionSize return the maximum size of TCP options.\n+func (e *endpoint) maxOptionSize() (size int) {\n+ var maxSackBlocks [header.TCPMaxSACKBlocks]header.SACKBlock\n+ options := e.makeOptions(maxSackBlocks[:])\n+ size = len(options)\n+ putOptions(options)\n+\n+ return size\n+}\n+\n// completeState makes a full copy of the endpoint and returns it. This is used\n// before invoking the probe. The state returned may not be fully consistent if\n// there are intervening syscalls when the state is being copied.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/snd.go", "new_path": "pkg/tcpip/transport/tcp/snd.go", "diff": "@@ -172,6 +172,11 @@ type fastRecovery struct {\n}\nfunc newSender(ep *endpoint, iss, irs seqnum.Value, sndWnd seqnum.Size, mss uint16, sndWndScale int) *sender {\n+ // The sender MUST reduce the TCP data length to account for any IP or\n+ // TCP options that it is including in the packets that it sends.\n+ // See: https://tools.ietf.org/html/rfc6691#section-2\n+ maxPayloadSize := int(mss) - ep.maxOptionSize()\n+\ns := &sender{\nep: ep,\nsndCwnd: InitialCwnd,\n@@ -183,7 +188,7 @@ func newSender(ep *endpoint, iss, irs seqnum.Value, sndWnd seqnum.Size, mss uint\nrto: 1 * time.Second,\nrttMeasureSeqNum: iss + 1,\nlastSendTime: time.Now(),\n- maxPayloadSize: int(mss),\n+ maxPayloadSize: maxPayloadSize,\nmaxSentAck: irs + 1,\nfr: fastRecovery{\n// See: https://tools.ietf.org/html/rfc6582#section-3.2 Step 1.\n@@ -226,11 +231,7 @@ func (s *sender) initCongestionControl(congestionControlName CongestionControlOp\nfunc (s *sender) updateMaxPayloadSize(mtu, count int) {\nm := mtu - header.TCPMinimumSize\n- // Calculate the maximum option size.\n- var maxSackBlocks [header.TCPMaxSACKBlocks]header.SACKBlock\n- options := s.ep.makeOptions(maxSackBlocks[:])\n- m -= len(options)\n- putOptions(options)\n+ m -= s.ep.maxOptionSize()\n// We don't adjust up for now.\nif m >= s.maxPayloadSize {\n" }, { "change_type": "MODIFY", "old_path": "runsc/test/README.md", "new_path": "runsc/test/README.md", "diff": "@@ -12,13 +12,11 @@ they may need extra setup in the test machine and extra configuration to run.\nThe following setup steps are required in order to run these tests:\n-\n`./runsc/test/install.sh [--runtime <name>]`\nThe tests expect the runtime name to be provided in the `RUNSC_RUNTIME`\nenvironment variable (default: `runsc-test`). To run the tests execute:\n-\n```\nbazel test --test_env=RUNSC_RUNTIME=runsc-test \\\n//runsc/test/image:image_test \\\n" }, { "change_type": "MODIFY", "old_path": "runsc/test/root/crictl_test.go", "new_path": "runsc/test/root/crictl_test.go", "diff": "@@ -36,6 +36,7 @@ import (\n// Tests for crictl have to be run as root (rather than in a user namespace)\n// because crictl creates named network namespaces in /var/run/netns/.\n+\nfunc TestCrictlSanity(t *testing.T) {\n// Setup containerd and crictl.\ncrictl, cleanup, err := setup(t)\n@@ -58,6 +59,7 @@ func TestCrictlSanity(t *testing.T) {\nt.Fatal(err)\n}\n}\n+\nfunc TestMountPaths(t *testing.T) {\n// Setup containerd and crictl.\ncrictl, cleanup, err := setup(t)\n@@ -80,6 +82,7 @@ func TestMountPaths(t *testing.T) {\nt.Fatal(err)\n}\n}\n+\nfunc TestMountOverSymlinks(t *testing.T) {\n// Setup containerd and crictl.\ncrictl, cleanup, err := setup(t)\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/exec.cc", "new_path": "test/syscalls/linux/exec.cc", "diff": "@@ -58,6 +58,7 @@ std::string WorkloadPath(absl::string_view binary) {\nif (test_src) {\nfull_path = JoinPath(test_src, \"__main__/test/syscalls/linux\", binary);\n}\n+\nTEST_CHECK(full_path.empty() == false);\nreturn full_path;\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/preadv.cc", "new_path": "test/syscalls/linux/preadv.cc", "diff": "@@ -37,6 +37,7 @@ namespace gvisor {\nnamespace testing {\nnamespace {\n+\nTEST(PreadvTest, MMConcurrencyStress) {\n// Fill a one-page file with zeroes (the contents don't really matter).\nconst auto f = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/proc.cc", "new_path": "test/syscalls/linux/proc.cc", "diff": "@@ -1258,6 +1258,7 @@ TEST(ProcPidSymlink, SubprocessRunning) {\nEXPECT_THAT(ReadlinkWhileRunning(\"ns/user\", buf, sizeof(buf)),\nSyscallSucceedsWithValue(sizeof(buf)));\n}\n+\n// FIXME: Inconsistent behavior between gVisor and linux\n// on proc files.\nTEST(ProcPidSymlink, SubprocessZombied) {\n@@ -1362,6 +1363,7 @@ TEST(ProcPidFile, SubprocessRunning) {\n// Test whether /proc/PID/ files can be read for a zombie process.\nTEST(ProcPidFile, SubprocessZombie) {\nchar buf[1];\n+\n// 4.17: Succeeds and returns 1\n// gVisor: Succeds and returns 0\nEXPECT_THAT(ReadWhileZombied(\"auxv\", buf, sizeof(buf)), SyscallSucceeds());\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/sigaltstack.cc", "new_path": "test/syscalls/linux/sigaltstack.cc", "diff": "@@ -101,6 +101,7 @@ TEST(SigaltstackTest, ResetByExecve) {\nif (test_src) {\nfull_path = JoinPath(test_src, \"../../linux/sigaltstack_check\");\n}\n+\nASSERT_FALSE(full_path.empty());\npid_t child_pid = -1;\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/time.cc", "new_path": "test/syscalls/linux/time.cc", "diff": "@@ -61,6 +61,7 @@ TEST(TimeTest, VsyscallTime_InvalidAddressSIGSEGV) {\nEXPECT_EXIT(vsyscall_time(reinterpret_cast<time_t*>(0x1)),\n::testing::KilledBySignal(SIGSEGV), \"\");\n}\n+\nint vsyscall_gettimeofday(struct timeval* tv, struct timezone* tz) {\nconstexpr uint64_t kVsyscallGettimeofdayEntry = 0xffffffffff600000;\nreturn reinterpret_cast<int (*)(struct timeval*, struct timezone*)>(\n" }, { "change_type": "MODIFY", "old_path": "test/util/temp_path.cc", "new_path": "test/util/temp_path.cc", "diff": "@@ -75,6 +75,7 @@ std::string NewTempRelPath() { return NextTempBasename(); }\nstd::string GetAbsoluteTestTmpdir() {\nchar* env_tmpdir = getenv(\"TEST_TMPDIR\");\nstd::string tmp_dir = env_tmpdir != nullptr ? std::string(env_tmpdir) : \"/tmp\";\n+\nreturn MakeAbsolute(tmp_dir, \"\").ValueOrDie();\n}\n" }, { "change_type": "MODIFY", "old_path": "test/util/test_util.cc", "new_path": "test/util/test_util.cc", "diff": "#include <ctime>\n#include <vector>\n+\n#include \"absl/base/attributes.h\"\n#include \"absl/strings/numbers.h\"\n#include \"absl/strings/str_cat.h\"\n@@ -234,6 +235,7 @@ bool Equivalent(uint64_t current, uint64_t target, double tolerance) {\nauto abs_diff = target > current ? target - current : current - target;\nreturn abs_diff <= static_cast<uint64_t>(tolerance * target);\n}\n+\nvoid TestInit(int* argc, char*** argv) {\n::testing::InitGoogleTest(argc, *argv);\n::gflags::ParseCommandLineFlags(argc, argv, true);\n" }, { "change_type": "MODIFY", "old_path": "test/util/test_util.h", "new_path": "test/util/test_util.h", "diff": "#include <thread> // NOLINT: using std::thread::hardware_concurrency().\n#include <utility>\n#include <vector>\n+\n#include <gflags/gflags.h>\n#include <glog/logging.h>\n#include \"gmock/gmock.h\"\n" } ]
Go
Apache License 2.0
google/gvisor
netstack: reduce MSS from SYN to account tcp options See: https://tools.ietf.org/html/rfc6691#section-2 PiperOrigin-RevId: 239305632 Change-Id: Ie8eb912a43332e6490045dc95570709c5b81855e
259,992
20.03.2019 10:35:13
25,200
c7877b0a14778af9165eb2b841513b6f7dfdcbee
Fail in case mount option is unknown
[ { "change_type": "MODIFY", "old_path": "runsc/specutils/fs.go", "new_path": "runsc/specutils/fs.go", "diff": "@@ -20,7 +20,6 @@ import (\n\"syscall\"\nspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n- \"gvisor.googlesource.com/gvisor/pkg/log\"\n)\ntype mapping struct {\n@@ -121,7 +120,7 @@ func validateMount(mnt *specs.Mount) error {\n_, ok1 := optionsMap[o]\n_, ok2 := propOptionsMap[o]\nif !ok1 && !ok2 {\n- log.Warningf(\"Ignoring unknown mount option %q\", o)\n+ return fmt.Errorf(\"unknown mount option %q\", o)\n}\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fail in case mount option is unknown PiperOrigin-RevId: 239425816 Change-Id: I3b1479c61b4222c3931a416c4efc909157044330
259,985
20.03.2019 14:30:00
25,200
81f4829d1195276d037f8bd23a2ef69e88f5ae6c
Record sockets created during accept(2) for all families. Track new sockets created during accept(2) in the socket table for all families. Previously we were only doing this for unix domain sockets.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/epsocket/epsocket.go", "new_path": "pkg/sentry/socket/epsocket/epsocket.go", "diff": "@@ -504,6 +504,8 @@ func (s *SocketOperations) Accept(t *kernel.Task, peerRequested bool, flags int,\n}\nfd, e := t.FDMap().NewFDFrom(0, ns, fdFlags, t.ThreadGroup().Limits())\n+ t.Kernel().RecordSocket(ns, s.family)\n+\nreturn fd, addr, addrLen, syserr.FromError(e)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/hostinet/socket.go", "new_path": "pkg/sentry/socket/hostinet/socket.go", "diff": "@@ -53,14 +53,15 @@ type socketOperations struct {\nfsutil.FileNoMMap `state:\"nosave\"`\nsocket.SendReceiveTimeout\n+ family int // Read-only.\nfd int // must be O_NONBLOCK\nqueue waiter.Queue\n}\nvar _ = socket.Socket(&socketOperations{})\n-func newSocketFile(ctx context.Context, fd int, nonblock bool) (*fs.File, *syserr.Error) {\n- s := &socketOperations{fd: fd}\n+func newSocketFile(ctx context.Context, family int, fd int, nonblock bool) (*fs.File, *syserr.Error) {\n+ s := &socketOperations{family: family, fd: fd}\nif err := fdnotifier.AddFD(int32(fd), &s.queue); err != nil {\nreturn nil, syserr.FromError(err)\n}\n@@ -218,7 +219,7 @@ func (s *socketOperations) Accept(t *kernel.Task, peerRequested bool, flags int,\nreturn 0, peerAddr, peerAddrlen, syserr.FromError(syscallErr)\n}\n- f, err := newSocketFile(t, fd, flags&syscall.SOCK_NONBLOCK != 0)\n+ f, err := newSocketFile(t, s.family, fd, flags&syscall.SOCK_NONBLOCK != 0)\nif err != nil {\nsyscall.Close(fd)\nreturn 0, nil, 0, err\n@@ -229,6 +230,7 @@ func (s *socketOperations) Accept(t *kernel.Task, peerRequested bool, flags int,\nCloseOnExec: flags&syscall.SOCK_CLOEXEC != 0,\n}\nkfd, kerr := t.FDMap().NewFDFrom(0, f, fdFlags, t.ThreadGroup().Limits())\n+ t.Kernel().RecordSocket(f, s.family)\nreturn kfd, peerAddr, peerAddrlen, syserr.FromError(kerr)\n}\n@@ -552,7 +554,7 @@ func (p *socketProvider) Socket(t *kernel.Task, stypeflags transport.SockType, p\nif err != nil {\nreturn nil, syserr.FromError(err)\n}\n- return newSocketFile(t, fd, stypeflags&syscall.SOCK_NONBLOCK != 0)\n+ return newSocketFile(t, p.family, fd, stypeflags&syscall.SOCK_NONBLOCK != 0)\n}\n// Pair implements socket.Provider.Pair.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/rpcinet/socket.go", "new_path": "pkg/sentry/socket/rpcinet/socket.go", "diff": "@@ -52,6 +52,7 @@ type socketOperations struct {\nfsutil.FileNoMMap `state:\"nosave\"`\nsocket.SendReceiveTimeout\n+ family int // Read-only.\nfd uint32 // must be O_NONBLOCK\nwq *waiter.Queue\nrpcConn *conn.RPCConnection\n@@ -83,6 +84,7 @@ func newSocketFile(ctx context.Context, stack *Stack, family int, skType int, pr\ndirent := socket.NewDirent(ctx, socketDevice)\ndefer dirent.DecRef()\nreturn fs.NewFile(ctx, dirent, fs.FileFlags{Read: true, Write: true}, &socketOperations{\n+ family: family,\nwq: &wq,\nfd: fd,\nrpcConn: stack.rpcConn,\n@@ -329,6 +331,7 @@ func (s *socketOperations) Accept(t *kernel.Task, peerRequested bool, flags int,\nif err != nil {\nreturn 0, nil, 0, syserr.FromError(err)\n}\n+ t.Kernel().RecordSocket(file, s.family)\nif peerRequested {\nreturn fd, payload.Address.Address, payload.Address.Length, nil\n" } ]
Go
Apache License 2.0
google/gvisor
Record sockets created during accept(2) for all families. Track new sockets created during accept(2) in the socket table for all families. Previously we were only doing this for unix domain sockets. PiperOrigin-RevId: 239475550 Change-Id: I16f009f24a06245bfd1d72ffd2175200f837c6ac
259,853
20.03.2019 18:39:57
25,200
064fda1a759fa3e73d25da3fd535d256ac8ccfb0
gvisor: don't allocate a new credential object on fork A credential object is immutable, so we don't need to copy it for a new task.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_clone.go", "new_path": "pkg/sentry/kernel/task_clone.go", "diff": "@@ -252,7 +252,7 @@ func (t *Task) Clone(opts *CloneOptions) (ThreadID, *SyscallControl, error) {\nTaskContext: tc,\nFSContext: fsc,\nFDMap: fds,\n- Credentials: creds.Fork(),\n+ Credentials: creds,\nNiceness: t.Niceness(),\nNetworkNamespaced: t.netns,\nAllowedCPUMask: t.CPUMask(),\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_identity.go", "new_path": "pkg/sentry/kernel/task_identity.go", "diff": "@@ -372,6 +372,7 @@ func (t *Task) DropBoundingCapability(cp linux.Capability) error {\nif !t.creds.HasCapability(linux.CAP_SETPCAP) {\nreturn syserror.EPERM\n}\n+ t.creds = t.creds.Fork() // See doc for creds.\nt.creds.BoundingCaps &^= auth.CapabilitySetOf(cp)\nreturn nil\n}\n" } ]
Go
Apache License 2.0
google/gvisor
gvisor: don't allocate a new credential object on fork A credential object is immutable, so we don't need to copy it for a new task. PiperOrigin-RevId: 239519266 Change-Id: I0632f641fdea9554779ac25d84bee4231d0d18f2
259,891
21.03.2019 11:53:11
25,200
ba937d74f9a69893cde8c7e8cb9c2d1cdadb2b70
Address typos from github.
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -157,8 +157,8 @@ There are several factors influencing performance. The platform choice has the\nlargest direct impact that varies depending on the specific workload. There is\nno best platform: Ptrace works universally, including on VM instances, but\napplications may perform at a fraction of their original levels. Beyond the\n-platform choice, passthrough modes may be useful for improving perfomance at the\n-cost of some isolation.\n+platform choice, passthrough modes may be useful for improving performance at\n+the cost of some isolation.\n## Installation\n" } ]
Go
Apache License 2.0
google/gvisor
Address typos from github. https://github.com/google/gvisor/pull/132 PiperOrigin-RevId: 239641377 Change-Id: I7ba6b57730800cc98496c83cb643e70ec902ed3d
259,854
21.03.2019 13:18:00
25,200
ba828233b9e934992ac024232e5018ce9971f334
Clear msghdr flags on successful recvmsg. .net sets these flags to -1 and then uses their result, especting it to be zero. Does not set actual flags (e.g. MSG_TRUNC), but setting to zero is more correct than what we did before.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_socket.go", "new_path": "pkg/sentry/syscalls/linux/sys_socket.go", "diff": "@@ -57,6 +57,10 @@ const nameLenOffset = 8\n// to the ControlLen field.\nconst controlLenOffset = 40\n+// flagsOffset is the offset form the start of the MessageHeader64 struct\n+// to the Flags field.\n+const flagsOffset = 48\n+\n// messageHeader64Len is the length of a MessageHeader64 struct.\nvar messageHeader64Len = uint64(binary.Size(MessageHeader64{}))\n@@ -743,6 +747,16 @@ func recvSingleMsg(t *kernel.Task, s socket.Socket, msgPtr usermem.Addr, flags i\nreturn 0, syserror.ConvertIntr(err.ToError(), kernel.ERESTARTSYS)\n}\ncms.Unix.Release()\n+\n+ if msg.Flags != 0 {\n+ // Copy out the flags to the caller.\n+ //\n+ // TODO: Plumb through actual flags.\n+ if _, err := t.CopyOut(msgPtr+flagsOffset, int32(0)); err != nil {\n+ return 0, err\n+ }\n+ }\n+\nreturn uintptr(n), nil\n}\n@@ -787,6 +801,13 @@ func recvSingleMsg(t *kernel.Task, s socket.Socket, msgPtr usermem.Addr, flags i\n}\n}\n+ // Copy out the flags to the caller.\n+ //\n+ // TODO: Plumb through actual flags.\n+ if _, err := t.CopyOut(msgPtr+flagsOffset, int32(0)); err != nil {\n+ return 0, err\n+ }\n+\nreturn uintptr(n), nil\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_generic.cc", "new_path": "test/syscalls/linux/socket_generic.cc", "diff": "@@ -183,6 +183,80 @@ TEST_P(AllSocketPairTest, SendmsgRecvmsg16KB) {\nmemcmp(sent_data.data(), received_data.data(), sent_data.size()));\n}\n+TEST_P(AllSocketPairTest, RecvmsgMsghdrFlagsNotClearedOnFailure) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ char received_data[10] = {};\n+\n+ struct iovec iov;\n+ iov.iov_base = received_data;\n+ iov.iov_len = sizeof(received_data);\n+ struct msghdr msg = {};\n+ msg.msg_flags = -1;\n+ msg.msg_iov = &iov;\n+ msg.msg_iovlen = 1;\n+\n+ ASSERT_THAT(RetryEINTR(recvmsg)(sockets->second_fd(), &msg, MSG_DONTWAIT),\n+ SyscallFailsWithErrno(EAGAIN));\n+\n+ // Check that msghdr flags were not changed.\n+ EXPECT_EQ(msg.msg_flags, -1);\n+}\n+\n+TEST_P(AllSocketPairTest, RecvmsgMsghdrFlagsCleared) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ char sent_data[10];\n+ RandomizeBuffer(sent_data, sizeof(sent_data));\n+ ASSERT_THAT(\n+ RetryEINTR(send)(sockets->first_fd(), sent_data, sizeof(sent_data), 0),\n+ SyscallSucceedsWithValue(sizeof(sent_data)));\n+\n+ char received_data[sizeof(sent_data)] = {};\n+\n+ struct iovec iov;\n+ iov.iov_base = received_data;\n+ iov.iov_len = sizeof(received_data);\n+ struct msghdr msg = {};\n+ msg.msg_flags = -1;\n+ msg.msg_iov = &iov;\n+ msg.msg_iovlen = 1;\n+\n+ ASSERT_THAT(RetryEINTR(recvmsg)(sockets->second_fd(), &msg, 0),\n+ SyscallSucceedsWithValue(sizeof(sent_data)));\n+ EXPECT_EQ(0, memcmp(received_data, sent_data, sizeof(sent_data)));\n+\n+ // Check that msghdr flags were cleared.\n+ EXPECT_EQ(msg.msg_flags, 0);\n+}\n+\n+TEST_P(AllSocketPairTest, RecvmsgPeekMsghdrFlagsCleared) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ char sent_data[10];\n+ RandomizeBuffer(sent_data, sizeof(sent_data));\n+ ASSERT_THAT(\n+ RetryEINTR(send)(sockets->first_fd(), sent_data, sizeof(sent_data), 0),\n+ SyscallSucceedsWithValue(sizeof(sent_data)));\n+\n+ char received_data[sizeof(sent_data)] = {};\n+\n+ struct iovec iov;\n+ iov.iov_base = received_data;\n+ iov.iov_len = sizeof(received_data);\n+ struct msghdr msg = {};\n+ msg.msg_flags = -1;\n+ msg.msg_iov = &iov;\n+ msg.msg_iovlen = 1;\n+\n+ ASSERT_THAT(RetryEINTR(recvmsg)(sockets->second_fd(), &msg, MSG_PEEK),\n+ SyscallSucceedsWithValue(sizeof(sent_data)));\n+ EXPECT_EQ(0, memcmp(received_data, sent_data, sizeof(sent_data)));\n+\n+ // Check that msghdr flags were cleared.\n+ EXPECT_EQ(msg.msg_flags, 0);\n+}\n+\nTEST_P(AllSocketPairTest, RecvmmsgInvalidTimeout) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\nchar buf[10];\n" } ]
Go
Apache License 2.0
google/gvisor
Clear msghdr flags on successful recvmsg. .net sets these flags to -1 and then uses their result, especting it to be zero. Does not set actual flags (e.g. MSG_TRUNC), but setting to zero is more correct than what we did before. PiperOrigin-RevId: 239657951 Change-Id: I89c5f84bc9b94a2cd8ff84e8ecfea09e01142030
259,891
21.03.2019 18:03:49
25,200
0cd5f2004444b1c792ab3d4bd3b01699b11b9553
Replace manual pty copies to/from userspace with safemem operations. Also, changing queue.writeBuf from a buffer.Bytes to a [][]byte should reduce copying and reallocating of slices.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/tty/BUILD", "new_path": "pkg/sentry/fs/tty/BUILD", "diff": "@@ -24,6 +24,7 @@ go_library(\n\"//pkg/sentry/fs\",\n\"//pkg/sentry/fs/fsutil\",\n\"//pkg/sentry/kernel/auth\",\n+ \"//pkg/sentry/safemem\",\n\"//pkg/sentry/socket/unix/transport\",\n\"//pkg/sentry/unimpl\",\n\"//pkg/sentry/usermem\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/tty/line_discipline.go", "new_path": "pkg/sentry/fs/tty/line_discipline.go", "diff": "@@ -140,10 +140,10 @@ func (l *lineDiscipline) setTermios(ctx context.Context, io usermem.IO, args arc\n// buffer to its read buffer. Anything already in the read buffer is\n// now readable.\nif oldCanonEnabled && !l.termios.LEnabled(linux.ICANON) {\n- if n := l.inQueue.pushWaitBuf(l); n > 0 {\n+ l.inQueue.pushWaitBuf(l)\n+ l.inQueue.readable = true\nl.slaveWaiter.Notify(waiter.EventIn)\n}\n- }\nreturn 0, err\n}\n@@ -263,7 +263,7 @@ type outputQueueTransformer struct{}\n// transform does output processing for one end of the pty. See\n// drivers/tty/n_tty.c:do_output_char for an analogous kernel function.\n//\n-// Precondition:\n+// Preconditions:\n// * l.termiosMu must be held for reading.\n// * q.mu must be held.\nfunc (*outputQueueTransformer) transform(l *lineDiscipline, q *queue, buf []byte) int {\n@@ -271,11 +271,11 @@ func (*outputQueueTransformer) transform(l *lineDiscipline, q *queue, buf []byte\n// master termios never has ICANON set.\nif !l.termios.OEnabled(linux.OPOST) {\n- n, _ := q.readBuf.Write(buf)\n- if q.readBuf.Len() > 0 {\n+ q.readBuf = append(q.readBuf, buf...)\n+ if len(q.readBuf) > 0 {\nq.readable = true\n}\n- return n\n+ return len(buf)\n}\nvar ret int\n@@ -289,7 +289,7 @@ func (*outputQueueTransformer) transform(l *lineDiscipline, q *queue, buf []byte\nl.column = 0\n}\nif l.termios.OEnabled(linux.ONLCR) {\n- q.readBuf.Write([]byte{'\\r', '\\n'})\n+ q.readBuf = append(q.readBuf, '\\r', '\\n')\ncontinue\n}\ncase '\\r':\n@@ -308,7 +308,7 @@ func (*outputQueueTransformer) transform(l *lineDiscipline, q *queue, buf []byte\nspaces := spacesPerTab - l.column%spacesPerTab\nif l.termios.OutputFlags&linux.TABDLY == linux.XTABS {\nl.column += spaces\n- q.readBuf.Write(bytes.Repeat([]byte{' '}, spacesPerTab))\n+ q.readBuf = append(q.readBuf, bytes.Repeat([]byte{' '}, spacesPerTab)...)\ncontinue\n}\nl.column += spaces\n@@ -319,9 +319,12 @@ func (*outputQueueTransformer) transform(l *lineDiscipline, q *queue, buf []byte\ndefault:\nl.column++\n}\n- q.readBuf.WriteRune(c)\n+ // The compiler optimizes this by growing readBuf without\n+ // creating the intermediate slice.\n+ q.readBuf = append(q.readBuf, make([]byte, size)...)\n+ utf8.EncodeRune(q.readBuf[len(q.readBuf)-size:], c)\n}\n- if q.readBuf.Len() > 0 {\n+ if len(q.readBuf) > 0 {\nq.readable = true\n}\nreturn ret\n@@ -338,7 +341,7 @@ type inputQueueTransformer struct{}\n// drivers/tty/n_tty.c:n_tty_receive_char_special for an analogous kernel\n// function.\n//\n-// Precondition:\n+// Preconditions:\n// * l.termiosMu must be held for reading.\n// * q.mu must be held.\nfunc (*inputQueueTransformer) transform(l *lineDiscipline, q *queue, buf []byte) int {\n@@ -354,7 +357,7 @@ func (*inputQueueTransformer) transform(l *lineDiscipline, q *queue, buf []byte)\n}\nvar ret int\n- for len(buf) > 0 && q.readBuf.Len() < canonMaxBytes {\n+ for len(buf) > 0 && len(q.readBuf) < canonMaxBytes {\nc, size := l.peekRune(buf)\nswitch c {\ncase '\\r':\n@@ -381,7 +384,7 @@ func (*inputQueueTransformer) transform(l *lineDiscipline, q *queue, buf []byte)\n}\n// Stop if the buffer would be overfilled.\n- if q.readBuf.Len()+size > maxBytes {\n+ if len(q.readBuf)+size > maxBytes {\nbreak\n}\ncBytes := buf[:size]\n@@ -394,13 +397,16 @@ func (*inputQueueTransformer) transform(l *lineDiscipline, q *queue, buf []byte)\nbreak\n}\n- q.readBuf.WriteRune(c)\n+ // The compiler optimizes this by growing readBuf without\n+ // creating the intermediate slice.\n+ q.readBuf = append(q.readBuf, make([]byte, size)...)\n+ utf8.EncodeRune(q.readBuf[len(q.readBuf)-size:], c)\n+\n// Anything written to the readBuf will have to be echoed.\nif l.termios.LEnabled(linux.ECHO) {\n- if l.outQueue.writeBytes(cBytes, l) > 0 {\n+ l.outQueue.writeBytes(cBytes, l)\nl.masterWaiter.Notify(waiter.EventIn)\n}\n- }\n// If we finish a line, make it available for reading.\nif l.termios.LEnabled(linux.ICANON) && l.termios.IsTerminating(c) {\n@@ -410,7 +416,7 @@ func (*inputQueueTransformer) transform(l *lineDiscipline, q *queue, buf []byte)\n}\n// In noncanonical mode, everything is readable.\n- if !l.termios.LEnabled(linux.ICANON) && q.readBuf.Len() > 0 {\n+ if !l.termios.LEnabled(linux.ICANON) && len(q.readBuf) > 0 {\nq.readable = true\n}\n@@ -425,7 +431,7 @@ func (*inputQueueTransformer) transform(l *lineDiscipline, q *queue, buf []byte)\n// * l.termiosMu must be held for reading.\n// * q.mu must be held.\nfunc (l *lineDiscipline) shouldDiscard(q *queue, c rune) bool {\n- return l.termios.LEnabled(linux.ICANON) && q.readBuf.Len()+utf8.RuneLen(c) >= canonMaxBytes && !l.termios.IsTerminating(c)\n+ return l.termios.LEnabled(linux.ICANON) && len(q.readBuf)+utf8.RuneLen(c) >= canonMaxBytes && !l.termios.IsTerminating(c)\n}\n// peekRune returns the first rune from the byte array depending on whether\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/tty/queue.go", "new_path": "pkg/sentry/fs/tty/queue.go", "diff": "package tty\nimport (\n- \"bytes\"\n\"sync\"\n\"gvisor.googlesource.com/gvisor/pkg/abi/linux\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/arch\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/context\"\n+ \"gvisor.googlesource.com/gvisor/pkg/sentry/safemem\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\"\n\"gvisor.googlesource.com/gvisor/pkg/syserror\"\n\"gvisor.googlesource.com/gvisor/pkg/waiter\"\n)\n+// waitBufMaxBytes is the maximum size of a wait buffer. It is based on\n+// TTYB_DEFAULT_MEM_LIMIT.\n+const waitBufMaxBytes = 131072\n+\n// queue represents one of the input or output queues between a pty master and\n// slave. Bytes written to a queue are added to the read buffer until it is\n// full, at which point they are written to the wait buffer. Bytes are\n@@ -40,12 +44,13 @@ type queue struct {\n// readBuf is buffer of data ready to be read when readable is true.\n// This data has been processed.\n- readBuf bytes.Buffer `state:\".([]byte)\"`\n+ readBuf []byte\n// waitBuf contains data that can't fit into readBuf. It is put here\n// until it can be loaded into the read buffer. waitBuf contains data\n// that hasn't been processed.\n- waitBuf bytes.Buffer `state:\".([]byte)\"`\n+ waitBuf [][]byte\n+ waitBufLen uint64\n// readable indicates whether the read buffer can be read from. In\n// canonical mode, there can be an unterminated line in the read buffer,\n@@ -58,31 +63,54 @@ type queue struct {\ntransformer\n}\n-// saveReadBuf is invoked by stateify.\n-func (q *queue) saveReadBuf() []byte {\n- return append([]byte(nil), q.readBuf.Bytes()...)\n+// ReadToBlocks implements safemem.Reader.ReadToBlocks.\n+func (q *queue) ReadToBlocks(dst safemem.BlockSeq) (uint64, error) {\n+ src := safemem.BlockSeqOf(safemem.BlockFromSafeSlice(q.readBuf))\n+ n, err := safemem.CopySeq(dst, src)\n+ if err != nil {\n+ return 0, err\n+ }\n+ q.readBuf = q.readBuf[n:]\n+\n+ // If we read everything, this queue is no longer readable.\n+ if len(q.readBuf) == 0 {\n+ q.readable = false\n+ }\n+\n+ return n, nil\n}\n-// loadReadBuf is invoked by stateify.\n-func (q *queue) loadReadBuf(b []byte) {\n- q.readBuf.Write(b)\n+// WriteFromBlocks implements safemem.Writer.WriteFromBlocks.\n+func (q *queue) WriteFromBlocks(src safemem.BlockSeq) (uint64, error) {\n+ copyLen := src.NumBytes()\n+ room := waitBufMaxBytes - q.waitBufLen\n+ // If out of room, return EAGAIN.\n+ if room == 0 && copyLen > 0 {\n+ return 0, syserror.ErrWouldBlock\n+ }\n+ // Cap the size of the wait buffer.\n+ if copyLen > room {\n+ copyLen = room\n+ src = src.TakeFirst64(room)\n}\n+ buf := make([]byte, copyLen)\n-// saveWaitBuf is invoked by stateify.\n-func (q *queue) saveWaitBuf() []byte {\n- return append([]byte(nil), q.waitBuf.Bytes()...)\n+ // Copy the data into the wait buffer.\n+ dst := safemem.BlockSeqOf(safemem.BlockFromSafeSlice(buf))\n+ n, err := safemem.CopySeq(dst, src)\n+ if err != nil {\n+ return 0, err\n}\n+ q.waitBufAppend(buf)\n-// loadWaitBuf is invoked by stateify.\n-func (q *queue) loadWaitBuf(b []byte) {\n- q.waitBuf.Write(b)\n+ return n, nil\n}\n// readReadiness returns whether q is ready to be read from.\nfunc (q *queue) readReadiness(t *linux.KernelTermios) waiter.EventMask {\nq.mu.Lock()\ndefer q.mu.Unlock()\n- if q.readBuf.Len() > 0 && q.readable {\n+ if len(q.readBuf) > 0 && q.readable {\nreturn waiter.EventIn\n}\nreturn waiter.EventMask(0)\n@@ -90,9 +118,11 @@ func (q *queue) readReadiness(t *linux.KernelTermios) waiter.EventMask {\n// writeReadiness returns whether q is ready to be written to.\nfunc (q *queue) writeReadiness(t *linux.KernelTermios) waiter.EventMask {\n- // Like Linux, we don't impose a maximum size on what can be enqueued.\n+ if q.waitBufLen < waitBufMaxBytes {\nreturn waiter.EventOut\n}\n+ return waiter.EventMask(0)\n+}\n// readableSize writes the number of readable bytes to userspace.\nfunc (q *queue) readableSize(ctx context.Context, io usermem.IO, args arch.SyscallArguments) error {\n@@ -100,7 +130,7 @@ func (q *queue) readableSize(ctx context.Context, io usermem.IO, args arch.Sysca\ndefer q.mu.Unlock()\nvar size int32\nif q.readable {\n- size = int32(q.readBuf.Len())\n+ size = int32(len(q.readBuf))\n}\n_, err := usermem.CopyObjectOut(ctx, io, args[2].Pointer(), size, usermem.IOOpts{\n@@ -119,29 +149,19 @@ func (q *queue) readableSize(ctx context.Context, io usermem.IO, args arch.Sysca\nfunc (q *queue) read(ctx context.Context, dst usermem.IOSequence, l *lineDiscipline) (int64, bool, error) {\nq.mu.Lock()\ndefer q.mu.Unlock()\n+\nif !q.readable {\nreturn 0, false, syserror.ErrWouldBlock\n}\n- // Read out from the read buffer.\n- n := canonMaxBytes\n- if n > int(dst.NumBytes()) {\n- n = int(dst.NumBytes())\n+ if dst.NumBytes() > canonMaxBytes {\n+ dst = dst.TakeFirst(canonMaxBytes)\n}\n- if n > q.readBuf.Len() {\n- n = q.readBuf.Len()\n- }\n- n, err := dst.Writer(ctx).Write(q.readBuf.Bytes()[:n])\n+\n+ n, err := dst.CopyOutFrom(ctx, q)\nif err != nil {\nreturn 0, false, err\n}\n- // Discard bytes read out.\n- q.readBuf.Next(n)\n-\n- // If we read everything, this queue is no longer readable.\n- if q.readBuf.Len() == 0 {\n- q.readable = false\n- }\n// Move data from the queue's wait buffer to its read buffer.\nnPushed := q.pushWaitBufLocked(l)\n@@ -154,37 +174,32 @@ func (q *queue) read(ctx context.Context, dst usermem.IOSequence, l *lineDiscipl\n// Preconditions:\n// * l.termiosMu must be held for reading.\nfunc (q *queue) write(ctx context.Context, src usermem.IOSequence, l *lineDiscipline) (int64, error) {\n- // TODO: Use CopyInTo/safemem to avoid extra copying.\n- // Copy in the bytes to write from user-space.\n- b := make([]byte, src.NumBytes())\n- n, err := src.CopyIn(ctx, b)\n+ q.mu.Lock()\n+ defer q.mu.Unlock()\n+\n+ // Copy data into the wait buffer.\n+ n, err := src.CopyInTo(ctx, q)\nif err != nil {\nreturn 0, err\n}\n- b = b[:n]\n- // If state changed, notify any waiters. If we were unable to write\n- // anything, let the caller know we could block.\n- if c := q.writeBytes(b, l); c > 0 {\n- return c, nil\n- }\n- return 0, syserror.ErrWouldBlock\n+ // Push data from the wait to the read buffer.\n+ q.pushWaitBufLocked(l)\n+\n+ return n, nil\n}\n// writeBytes writes to q from b.\n//\n// Preconditions:\n// * l.termiosMu must be held for reading.\n-func (q *queue) writeBytes(b []byte, l *lineDiscipline) int64 {\n+func (q *queue) writeBytes(b []byte, l *lineDiscipline) {\nq.mu.Lock()\ndefer q.mu.Unlock()\n- // Write as much as possible to the read buffer.\n- n := q.transform(l, q, b)\n-\n- // Write remaining data to the wait buffer.\n- nWaiting, _ := q.waitBuf.Write(b[n:])\n- return int64(n + nWaiting)\n+ // Write to the wait buffer.\n+ q.waitBufAppend(b)\n+ q.pushWaitBufLocked(l)\n}\n// pushWaitBuf fills the queue's read buffer with data from the wait buffer.\n@@ -201,9 +216,32 @@ func (q *queue) pushWaitBuf(l *lineDiscipline) int {\n// * l.termiosMu must be held for reading.\n// * q.mu must be locked.\nfunc (q *queue) pushWaitBufLocked(l *lineDiscipline) int {\n- // Remove bytes from the wait buffer and move them to the read buffer.\n- n := q.transform(l, q, q.waitBuf.Bytes())\n- q.waitBuf.Next(n)\n+ if q.waitBufLen == 0 {\n+ return 0\n+ }\n+\n+ // Move data from the wait to the read buffer.\n+ var total int\n+ var i int\n+ for i = 0; i < len(q.waitBuf); i++ {\n+ n := q.transform(l, q, q.waitBuf[i])\n+ total += n\n+ if n != len(q.waitBuf[i]) {\n+ // The read buffer filled up without consuming the\n+ // entire buffer.\n+ q.waitBuf[i] = q.waitBuf[i][n:]\n+ break\n+ }\n+ }\n+\n+ // Update wait buffer based on consumed data.\n+ q.waitBuf = q.waitBuf[i:]\n+ q.waitBufLen -= uint64(total)\n+\n+ return total\n+}\n- return n\n+func (q *queue) waitBufAppend(b []byte) {\n+ q.waitBuf = append(q.waitBuf, b)\n+ q.waitBufLen += uint64(len(b))\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Replace manual pty copies to/from userspace with safemem operations. Also, changing queue.writeBuf from a buffer.Bytes to a [][]byte should reduce copying and reallocating of slices. PiperOrigin-RevId: 239713547 Change-Id: I6ee5ff19c3ee2662f1af5749cae7b73db0569e96
259,854
21.03.2019 18:10:13
25,200
125d3a19e3a0e8d5549dca061f3dec9e0f5aa9d4
Test TCP sockets with MSG_TRUNC|MSG_PEEK.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_ip_tcp_generic.cc", "new_path": "test/syscalls/linux/socket_ip_tcp_generic.cc", "diff": "@@ -538,5 +538,34 @@ TEST_P(TCPSocketPairTest, SetOOBInline) {\nEXPECT_EQ(get, kSockOptOn);\n}\n+TEST_P(TCPSocketPairTest, MsgTruncMsgPeek) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ char sent_data[512];\n+ RandomizeBuffer(sent_data, sizeof(sent_data));\n+ ASSERT_THAT(\n+ RetryEINTR(send)(sockets->first_fd(), sent_data, sizeof(sent_data), 0),\n+ SyscallSucceedsWithValue(sizeof(sent_data)));\n+\n+ // Read half of the data with MSG_TRUNC | MSG_PEEK. This way there will still\n+ // be some data left to read in the next step even if the data gets consumed.\n+ char received_data1[sizeof(sent_data) / 2] = {};\n+ ASSERT_THAT(RetryEINTR(recv)(sockets->second_fd(), received_data1,\n+ sizeof(received_data1), MSG_TRUNC | MSG_PEEK),\n+ SyscallSucceedsWithValue(sizeof(received_data1)));\n+\n+ // Check that we didn't get anything.\n+ char zeros[sizeof(received_data1)] = {};\n+ EXPECT_EQ(0, memcmp(zeros, received_data1, sizeof(received_data1)));\n+\n+ // Check that all of the data is still there.\n+ char received_data2[sizeof(sent_data)] = {};\n+ ASSERT_THAT(RetryEINTR(recv)(sockets->second_fd(), received_data2,\n+ sizeof(received_data2), 0),\n+ SyscallSucceedsWithValue(sizeof(sent_data)));\n+\n+ EXPECT_EQ(0, memcmp(received_data2, sent_data, sizeof(sent_data)));\n+}\n+\n} // namespace testing\n} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Test TCP sockets with MSG_TRUNC|MSG_PEEK. PiperOrigin-RevId: 239714368 Change-Id: I35860b880a1d8885eb8c2d4ff267caaf72d91088
259,854
21.03.2019 18:52:03
25,200
7d0227ff16f4397924fb008a7452f6ed3f8205e0
Add test for short recvmsg iovec length.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_generic.cc", "new_path": "test/syscalls/linux/socket_generic.cc", "diff": "@@ -257,6 +257,32 @@ TEST_P(AllSocketPairTest, RecvmsgPeekMsghdrFlagsCleared) {\nEXPECT_EQ(msg.msg_flags, 0);\n}\n+TEST_P(AllSocketPairTest, RecvmsgIovNotUpdated) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ char sent_data[10];\n+ RandomizeBuffer(sent_data, sizeof(sent_data));\n+ ASSERT_THAT(\n+ RetryEINTR(send)(sockets->first_fd(), sent_data, sizeof(sent_data), 0),\n+ SyscallSucceedsWithValue(sizeof(sent_data)));\n+\n+ char received_data[sizeof(sent_data) * 2] = {};\n+\n+ struct iovec iov;\n+ iov.iov_base = received_data;\n+ iov.iov_len = sizeof(received_data);\n+ struct msghdr msg = {};\n+ msg.msg_iov = &iov;\n+ msg.msg_iovlen = 1;\n+\n+ ASSERT_THAT(RetryEINTR(recvmsg)(sockets->second_fd(), &msg, 0),\n+ SyscallSucceedsWithValue(sizeof(sent_data)));\n+ EXPECT_EQ(0, memcmp(received_data, sent_data, sizeof(sent_data)));\n+\n+ // Check that the iovec length was not updated.\n+ EXPECT_EQ(msg.msg_iov->iov_len, sizeof(received_data));\n+}\n+\nTEST_P(AllSocketPairTest, RecvmmsgInvalidTimeout) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\nchar buf[10];\n" } ]
Go
Apache License 2.0
google/gvisor
Add test for short recvmsg iovec length. PiperOrigin-RevId: 239718991 Change-Id: Idc78557a8e9bfdd3cb7d8ec4db708364652640a4
259,872
21.03.2019 22:03:34
25,200
45ba52f8246a7060da48e250512a734a79187adf
Allow BP and OF can be called from user space Change the DPL from 0 to 3 for Breakpoint and Overflow, then user space could trigger Breakpoint and Overflow as excepected.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ring0/kernel_amd64.go", "new_path": "pkg/sentry/platform/ring0/kernel_amd64.go", "diff": "@@ -27,9 +27,15 @@ func (k *Kernel) init(opts KernelOpts) {\n// Setup the IDT, which is uniform.\nfor v, handler := range handlers {\n+ // Allow Breakpoint and Overflow to be called from all\n+ // privilege levels.\n+ dpl := 0\n+ if v == Breakpoint || v == Overflow {\n+ dpl = 3\n+ }\n// Note that we set all traps to use the interrupt stack, this\n// is defined below when setting up the TSS.\n- k.globalIDT[v].setInterrupt(Kcode, uint64(kernelFunc(handler)), 0 /* dpl */, 1 /* ist */)\n+ k.globalIDT[v].setInterrupt(Kcode, uint64(kernelFunc(handler)), dpl, 1 /* ist */)\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Allow BP and OF can be called from user space Change the DPL from 0 to 3 for Breakpoint and Overflow, then user space could trigger Breakpoint and Overflow as excepected. Change-Id: Ibead65fb8c98b32b7737f316db93b3a8d9dcd648 PiperOrigin-RevId: 239736648
259,853
26.03.2019 15:09:35
25,200
79aca14a0cd70720e8a8f8bd6c1499ab1ffbd8d3
Use toolchain configs from bazel_0.23.0 bazel 0.24.0 isn't compatible with bazel_0.20.0 configs: (10:32:27) ERROR: bazel_toolchains/configs/ubuntu16_04_clang/1.1/bazel_0.20.0/default/BUILD:57:1: no such attribute 'dynamic_runtime_libs' in 'cc_toolchain' rule
[ { "change_type": "MODIFY", "old_path": ".bazelrc_rbe", "new_path": ".bazelrc_rbe", "diff": "# limitations under the License.\n# Note for gVisor authors:\n-# This version is a derivative of: bazel-0.20.0.bazelrc\n+# This version is a derivative of: bazel-0.23.0.bazelrc\n# From: https://github.com/bazelbuild/bazel-toolchains/blob/master/bazelrc/bazel-0.20.0.bazelrc\n# This .bazelrc file contains all of the flags required for the toolchain,\n@@ -33,15 +33,15 @@ build:remote --jobs=50\n# Set several flags related to specifying the platform, toolchain and java\n# properties.\n# These flags are duplicated rather than imported from (for example)\n-# %workspace%/configs/ubuntu16_04_clang/1.1/toolchain.bazelrc to make this\n+# %workspace%/configs/ubuntu16_04_clang/1.2/toolchain.bazelrc to make this\n# bazelrc a standalone file that can be copied more easily.\n# These flags should only be used as is for the rbe-ubuntu16-04 container\n# and need to be adapted to work with other toolchain containers.\n-build:remote --host_javabase=@bazel_toolchains//configs/ubuntu16_04_clang/1.1:jdk8\n-build:remote --javabase=@bazel_toolchains//configs/ubuntu16_04_clang/1.1:jdk8\n+build:remote --host_javabase=@bazel_toolchains//configs/ubuntu16_04_clang/1.2:jdk8\n+build:remote --javabase=@bazel_toolchains//configs/ubuntu16_04_clang/1.2:jdk8\nbuild:remote --host_java_toolchain=@bazel_tools//tools/jdk:toolchain_hostjdk8\nbuild:remote --java_toolchain=@bazel_tools//tools/jdk:toolchain_hostjdk8\n-build:remote --crosstool_top=@bazel_toolchains//configs/ubuntu16_04_clang/1.1/bazel_0.20.0/default:toolchain\n+build:remote --crosstool_top=@bazel_toolchains//configs/ubuntu16_04_clang/1.2/bazel_0.23.0/default:toolchain\nbuild:remote --action_env=BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1\n# Platform flags:\n# The toolchain container used for execution is defined in the target indicated\n@@ -62,7 +62,7 @@ build:remote --platforms=//test:rbe_ubuntu1604\nbuild:remote --spawn_strategy=remote\nbuild:remote --strategy=Javac=remote\nbuild:remote --strategy=Closure=remote\n-build:remote --genrule_strategy=remote\n+build:remote --strategy=Genrule=remote\nbuild:remote --define=EXECUTOR=remote\n# Enable the remote cache so action results can be shared across machines,\n@@ -75,11 +75,6 @@ build:remote --remote_executor=remotebuildexecution.googleapis.com\n# Enable encryption.\nbuild:remote --tls_enabled=true\n-# Enforce stricter environment rules, which eliminates some non-hermetic\n-# behavior and therefore improves both the remote cache hit rate and the\n-# correctness and repeatability of the build.\n-build:remote --experimental_strict_action_env=true\n-\n# Set a higher timeout value, just in case.\nbuild:remote --remote_timeout=3600\n@@ -112,10 +107,9 @@ build:results-local --bes_results_url=\"https://source.cloud.google.com/results/i\n# across machines, developers, and workspaces.\nbuild:remote-cache --remote_cache=remotebuildexecution.googleapis.com\nbuild:remote-cache --tls_enabled=true\n-build:remote-cache --experimental_strict_action_env=true\nbuild:remote-cache --remote_timeout=3600\nbuild:remote-cache --auth_enabled=true\nbuild:remote-cache --spawn_strategy=standalone\nbuild:remote-cache --strategy=Javac=standalone\nbuild:remote-cache --strategy=Closure=standalone\n-build:remote-cache --genrule_strategy=standalone\n+build:remote-cache --strategy=Genrule=standalone\n" }, { "change_type": "MODIFY", "old_path": "WORKSPACE", "new_path": "WORKSPACE", "diff": "@@ -21,12 +21,12 @@ gazelle_dependencies()\n# See releases at https://releases.bazel.build/bazel-toolchains.html\nhttp_archive(\nname = \"bazel_toolchains\",\n+ sha256 = \"4b1468b254a572dbe134cc1fd7c6eab1618a72acd339749ea343bd8f55c3b7eb\",\n+ strip_prefix = \"bazel-toolchains-d665ccfa3e9c90fa789671bf4ef5f7c19c5715c4\",\nurls = [\n- \"https://mirror.bazel.build/github.com/bazelbuild/bazel-toolchains/archive/31b5dc8c4e9c7fd3f5f4d04c6714f2ce87b126c1.tar.gz\",\n- \"https://github.com/bazelbuild/bazel-toolchains/archive/31b5dc8c4e9c7fd3f5f4d04c6714f2ce87b126c1.tar.gz\",\n+ \"https://mirror.bazel.build/github.com/bazelbuild/bazel-toolchains/archive/d665ccfa3e9c90fa789671bf4ef5f7c19c5715c4.tar.gz\",\n+ \"https://github.com/bazelbuild/bazel-toolchains/archive/d665ccfa3e9c90fa789671bf4ef5f7c19c5715c4.tar.gz\",\n],\n- strip_prefix = \"bazel-toolchains-31b5dc8c4e9c7fd3f5f4d04c6714f2ce87b126c1\",\n- sha256 = \"07a81ee03f5feae354c9f98c884e8e886914856fb2b6a63cba4619ef10aaaf0b\",\n)\n# External repositories, in sorted order.\n" }, { "change_type": "MODIFY", "old_path": "test/BUILD", "new_path": "test/BUILD", "diff": "@@ -24,7 +24,7 @@ platform(\nremote_execution_properties = \"\"\"\nproperties: {\nname: \"container-image\"\n- value:\"docker://gcr.io/cloud-marketplace/google/rbe-ubuntu16-04@sha256:f3120a030a19d67626ababdac79cc787e699a1aa924081431285118f87e7b375\"\n+ value:\"docker://gcr.io/cloud-marketplace/google/rbe-ubuntu16-04@sha256:69c9f1652941d64a46f6f7358a44c1718f25caa5cb1ced4a58ccc5281cd183b5\"\n}\nproperties: {\nname: \"dockerAddCapabilities\"\n@@ -43,6 +43,6 @@ toolchain(\n],\ntarget_compatible_with = [\n],\n- toolchain = \"@bazel_toolchains//configs/ubuntu16_04_clang/1.1/bazel_0.20.0/default:cc-compiler-k8\",\n+ toolchain = \"@bazel_toolchains//configs/ubuntu16_04_clang/1.2/bazel_0.23.0/default:cc-compiler-k8\",\ntoolchain_type = \"@bazel_tools//tools/cpp:toolchain_type\",\n)\n" } ]
Go
Apache License 2.0
google/gvisor
Use toolchain configs from bazel_0.23.0 bazel 0.24.0 isn't compatible with bazel_0.20.0 configs: (10:32:27) ERROR: bazel_toolchains/configs/ubuntu16_04_clang/1.1/bazel_0.20.0/default/BUILD:57:1: no such attribute 'dynamic_runtime_libs' in 'cc_toolchain' rule PiperOrigin-RevId: 240436868 Change-Id: Iee68c9b79d907ca2bdd124386aaa77c786e089ce
259,853
26.03.2019 17:14:04
25,200
654e878abba174d8f7d588f38ecfd5a020bf581e
netstack: Don't exclude length when a pseudo-header checksum is calculated This is a preparation for GSO changes (cl/234508902). RELNOTES[gofers]: Refactor checksum code to include length, which it already did, but in a convoluted way. Should be a no-op.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/checksum.go", "new_path": "pkg/tcpip/header/checksum.go", "diff": "package header\nimport (\n+ \"encoding/binary\"\n+\n\"gvisor.googlesource.com/gvisor/pkg/tcpip\"\n\"gvisor.googlesource.com/gvisor/pkg/tcpip/buffer\"\n)\n@@ -76,12 +78,17 @@ func ChecksumCombine(a, b uint16) uint16 {\nreturn uint16(v + v>>16)\n}\n-// PseudoHeaderChecksum calculates the pseudo-header checksum for the\n-// given destination protocol and network address, ignoring the length\n-// field. Pseudo-headers are needed by transport layers when calculating\n-// their own checksum.\n-func PseudoHeaderChecksum(protocol tcpip.TransportProtocolNumber, srcAddr tcpip.Address, dstAddr tcpip.Address) uint16 {\n+// PseudoHeaderChecksum calculates the pseudo-header checksum for the given\n+// destination protocol and network address. Pseudo-headers are needed by\n+// transport layers when calculating their own checksum.\n+func PseudoHeaderChecksum(protocol tcpip.TransportProtocolNumber, srcAddr tcpip.Address, dstAddr tcpip.Address, totalLen uint16) uint16 {\nxsum := Checksum([]byte(srcAddr), 0)\nxsum = Checksum([]byte(dstAddr), xsum)\n+\n+ // Add the length portion of the checksum to the pseudo-checksum.\n+ tmp := make([]byte, 2)\n+ binary.BigEndian.PutUint16(tmp, totalLen)\n+ xsum = Checksum(tmp, xsum)\n+\nreturn Checksum([]byte{0, uint8(protocol)}, xsum)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/tcp.go", "new_path": "pkg/tcpip/header/tcp.go", "diff": "@@ -231,19 +231,12 @@ func (b TCP) SetChecksum(checksum uint16) {\nbinary.BigEndian.PutUint16(b[tcpChecksum:], checksum)\n}\n-// CalculateChecksum calculates the checksum of the tcp segment given\n-// the totalLen and partialChecksum(descriptions below)\n-// totalLen is the total length of the segment\n+// CalculateChecksum calculates the checksum of the tcp segment.\n// partialChecksum is the checksum of the network-layer pseudo-header\n-// (excluding the total length) and the checksum of the segment data.\n-func (b TCP) CalculateChecksum(partialChecksum uint16, totalLen uint16) uint16 {\n- // Add the length portion of the checksum to the pseudo-checksum.\n- tmp := make([]byte, 2)\n- binary.BigEndian.PutUint16(tmp, totalLen)\n- checksum := Checksum(tmp, partialChecksum)\n-\n+// and the checksum of the segment data.\n+func (b TCP) CalculateChecksum(partialChecksum uint16) uint16 {\n// Calculate the rest of the checksum.\n- return Checksum(b[:b.DataOffset()], checksum)\n+ return Checksum(b[:b.DataOffset()], partialChecksum)\n}\n// Options returns a slice that holds the unparsed TCP options in the segment.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/udp.go", "new_path": "pkg/tcpip/header/udp.go", "diff": "@@ -94,17 +94,11 @@ func (b UDP) SetChecksum(checksum uint16) {\nbinary.BigEndian.PutUint16(b[udpChecksum:], checksum)\n}\n-// CalculateChecksum calculates the checksum of the udp packet, given the total\n-// length of the packet and the checksum of the network-layer pseudo-header\n-// (excluding the total length) and the checksum of the payload.\n-func (b UDP) CalculateChecksum(partialChecksum uint16, totalLen uint16) uint16 {\n- // Add the length portion of the checksum to the pseudo-checksum.\n- tmp := make([]byte, 2)\n- binary.BigEndian.PutUint16(tmp, totalLen)\n- checksum := Checksum(tmp, partialChecksum)\n-\n+// CalculateChecksum calculates the checksum of the udp packet, given the\n+// checksum of the network-layer pseudo-header and the checksum of the payload.\n+func (b UDP) CalculateChecksum(partialChecksum uint16) uint16 {\n// Calculate the rest of the checksum.\n- return Checksum(b[:UDPMinimumSize], checksum)\n+ return Checksum(b[:UDPMinimumSize], partialChecksum)\n}\n// Encode encodes all the fields of the udp header.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/route.go", "new_path": "pkg/tcpip/stack/route.go", "diff": "@@ -88,8 +88,8 @@ func (r *Route) Stats() tcpip.Stats {\n// PseudoHeaderChecksum forwards the call to the network endpoint's\n// implementation.\n-func (r *Route) PseudoHeaderChecksum(protocol tcpip.TransportProtocolNumber) uint16 {\n- return header.PseudoHeaderChecksum(protocol, r.LocalAddress, r.RemoteAddress)\n+func (r *Route) PseudoHeaderChecksum(protocol tcpip.TransportProtocolNumber, totalLen uint16) uint16 {\n+ return header.PseudoHeaderChecksum(protocol, r.LocalAddress, r.RemoteAddress, totalLen)\n}\n// Capabilities returns the link-layer capabilities of the route.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/connect.go", "new_path": "pkg/tcpip/transport/tcp/connect.go", "diff": "@@ -589,10 +589,10 @@ func sendTCP(r *stack.Route, id stack.TransportEndpointID, data buffer.Vectorise\n// Only calculate the checksum if offloading isn't supported.\nif r.Capabilities()&stack.CapabilityChecksumOffload == 0 {\nlength := uint16(hdr.UsedLength() + data.Size())\n- xsum := r.PseudoHeaderChecksum(ProtocolNumber)\n+ xsum := r.PseudoHeaderChecksum(ProtocolNumber, length)\nxsum = header.ChecksumVV(data, xsum)\n- tcp.SetChecksum(^tcp.CalculateChecksum(xsum, length))\n+ tcp.SetChecksum(^tcp.CalculateChecksum(xsum))\n}\nr.Stats().TCP.SegmentsSent.Increment()\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": "@@ -332,9 +332,8 @@ func (c *Context) BuildSegment(payload []byte, h *Headers) buffer.VectorisedView\nxsum = header.Checksum([]byte{0, uint8(tcp.ProtocolNumber)}, xsum)\n// Calculate the TCP checksum and set it.\n- length := uint16(header.TCPMinimumSize + len(h.TCPOpts) + len(payload))\nxsum = header.Checksum(payload, xsum)\n- t.SetChecksum(^t.CalculateChecksum(xsum, length))\n+ t.SetChecksum(^t.CalculateChecksum(xsum))\n// Inject packet.\nreturn buf.ToVectorisedView()\n@@ -487,9 +486,8 @@ func (c *Context) SendV6Packet(payload []byte, h *Headers) {\nxsum = header.Checksum([]byte{0, uint8(tcp.ProtocolNumber)}, xsum)\n// Calculate the TCP checksum and set it.\n- length := uint16(header.TCPMinimumSize + len(payload))\nxsum = header.Checksum(payload, xsum)\n- t.SetChecksum(^t.CalculateChecksum(xsum, length))\n+ t.SetChecksum(^t.CalculateChecksum(xsum))\n// Inject packet.\nc.linkEP.Inject(ipv6.ProtocolNumber, buf.ToVectorisedView())\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/endpoint.go", "new_path": "pkg/tcpip/transport/udp/endpoint.go", "diff": "@@ -641,11 +641,11 @@ func sendUDP(r *stack.Route, data buffer.VectorisedView, localPort, remotePort u\n// Only calculate the checksum if offloading isn't supported.\nif r.Capabilities()&stack.CapabilityChecksumOffload == 0 {\n- xsum := r.PseudoHeaderChecksum(ProtocolNumber)\n+ xsum := r.PseudoHeaderChecksum(ProtocolNumber, length)\nfor _, v := range data.Views() {\nxsum = header.Checksum(v, xsum)\n}\n- udp.SetChecksum(^udp.CalculateChecksum(xsum, length))\n+ udp.SetChecksum(^udp.CalculateChecksum(xsum))\n}\n// Track count of packets sent.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/udp_test.go", "new_path": "pkg/tcpip/transport/udp/udp_test.go", "diff": "@@ -200,9 +200,8 @@ func (c *testContext) sendV6Packet(payload []byte, h *headers) {\nxsum = header.Checksum([]byte{0, uint8(udp.ProtocolNumber)}, xsum)\n// Calculate the UDP checksum and set it.\n- length := uint16(header.UDPMinimumSize + len(payload))\nxsum = header.Checksum(payload, xsum)\n- u.SetChecksum(^u.CalculateChecksum(xsum, length))\n+ u.SetChecksum(^u.CalculateChecksum(xsum))\n// Inject packet.\nc.linkEP.Inject(ipv6.ProtocolNumber, buf.ToVectorisedView())\n@@ -239,9 +238,8 @@ func (c *testContext) sendPacket(payload []byte, h *headers) {\nxsum = header.Checksum([]byte{0, uint8(udp.ProtocolNumber)}, xsum)\n// Calculate the UDP checksum and set it.\n- length := uint16(header.UDPMinimumSize + len(payload))\nxsum = header.Checksum(payload, xsum)\n- u.SetChecksum(^u.CalculateChecksum(xsum, length))\n+ u.SetChecksum(^u.CalculateChecksum(xsum))\n// Inject packet.\nc.linkEP.Inject(ipv4.ProtocolNumber, buf.ToVectorisedView())\n" } ]
Go
Apache License 2.0
google/gvisor
netstack: Don't exclude length when a pseudo-header checksum is calculated This is a preparation for GSO changes (cl/234508902). RELNOTES[gofers]: Refactor checksum code to include length, which it already did, but in a convoluted way. Should be a no-op. PiperOrigin-RevId: 240460794 Change-Id: I537381bc670b5a9f5d70a87aa3eb7252e8f5ace2
259,885
27.03.2019 10:45:17
25,200
26583e413e40666f70170025cd4c5224f45fdfa3
Convert []byte to string without copying in usermem.CopyStringIn. This is the same technique used by Go's strings.Builder (https://golang.org/src/strings/builder.go#L45), and for the same reason. (We can't just use strings.Builder because there's no way to get the underlying []byte to pass to usermem.IO.CopyIn.)
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/usermem/BUILD", "new_path": "pkg/sentry/usermem/BUILD", "diff": "@@ -25,6 +25,7 @@ go_library(\n\"bytes_io_unsafe.go\",\n\"usermem.go\",\n\"usermem_arm64.go\",\n+ \"usermem_unsafe.go\",\n\"usermem_x86.go\",\n],\nimportpath = \"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/usermem/usermem.go", "new_path": "pkg/sentry/usermem/usermem.go", "diff": "@@ -37,6 +37,8 @@ type IO interface {\n//\n// Preconditions: The caller must not hold mm.MemoryManager.mappingMu or\n// any following locks in the lock order.\n+ //\n+ // Postconditions: CopyOut does not retain src.\nCopyOut(ctx context.Context, addr Addr, src []byte, opts IOOpts) (int, error)\n// CopyIn copies len(dst) bytes from the memory mapped at addr to dst.\n@@ -45,6 +47,8 @@ type IO interface {\n//\n// Preconditions: The caller must not hold mm.MemoryManager.mappingMu or\n// any following locks in the lock order.\n+ //\n+ // Postconditions: CopyIn does not retain dst.\nCopyIn(ctx context.Context, addr Addr, dst []byte, opts IOOpts) (int, error)\n// ZeroOut sets toZero bytes to 0, starting at addr. It returns the number\n@@ -237,7 +241,7 @@ func CopyStringIn(ctx context.Context, uio IO, addr Addr, maxlen int, opts IOOpt\nif !ok {\n// Last page of kernel memory. The application can't use this\n// anyway.\n- return string(buf[:done]), syserror.EFAULT\n+ return stringFromImmutableBytes(buf[:done]), syserror.EFAULT\n}\n// Read up to copyStringIncrement bytes at a time.\nreadlen := copyStringIncrement\n@@ -246,7 +250,7 @@ func CopyStringIn(ctx context.Context, uio IO, addr Addr, maxlen int, opts IOOpt\n}\nend, ok := start.AddLength(uint64(readlen))\nif !ok {\n- return string(buf[:done]), syserror.EFAULT\n+ return stringFromImmutableBytes(buf[:done]), syserror.EFAULT\n}\n// Shorten the read to avoid crossing page boundaries, since faulting\n// in a page unnecessarily is expensive. This also ensures that partial\n@@ -259,15 +263,15 @@ func CopyStringIn(ctx context.Context, uio IO, addr Addr, maxlen int, opts IOOpt\n// hitting err.\nfor i, c := range buf[done : done+n] {\nif c == 0 {\n- return string(buf[:done+i]), nil\n+ return stringFromImmutableBytes(buf[:done+i]), nil\n}\n}\ndone += n\nif err != nil {\n- return string(buf[:done]), err\n+ return stringFromImmutableBytes(buf[:done]), err\n}\n}\n- return string(buf), syserror.ENAMETOOLONG\n+ return stringFromImmutableBytes(buf), syserror.ENAMETOOLONG\n}\n// CopyOutVec copies bytes from src to the memory mapped at ars in uio. The\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/usermem/usermem_unsafe.go", "diff": "+// Copyright 2019 Google LLC\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 usermem\n+\n+import (\n+ \"unsafe\"\n+)\n+\n+// stringFromImmutableBytes is equivalent to string(bs), except that it never\n+// copies even if escape analysis can't prove that bs does not escape. This is\n+// only valid if bs is never mutated after stringFromImmutableBytes returns.\n+func stringFromImmutableBytes(bs []byte) string {\n+ // Compare strings.Builder.String().\n+ return *(*string)(unsafe.Pointer(&bs))\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Convert []byte to string without copying in usermem.CopyStringIn. This is the same technique used by Go's strings.Builder (https://golang.org/src/strings/builder.go#L45), and for the same reason. (We can't just use strings.Builder because there's no way to get the underlying []byte to pass to usermem.IO.CopyIn.) PiperOrigin-RevId: 240594892 Change-Id: Ic070e7e480aee53a71289c7c120850991358c52c
259,853
27.03.2019 11:08:33
25,200
5d94c893ae38f09f5132ab43d48204ab49121960
gvisor/runsc: address typos from github Fixes: Fixes
[ { "change_type": "MODIFY", "old_path": "runsc/cmd/list.go", "new_path": "runsc/cmd/list.go", "diff": "@@ -42,7 +42,7 @@ func (*List) Name() string {\n// Synopsis implements subcommands.Command.Synopsis.\nfunc (*List) Synopsis() string {\n- return \"list contaners started by runsc with the given root\"\n+ return \"list containers started by runsc with the given root\"\n}\n// Usage implements subcommands.Command.Usage.\n" } ]
Go
Apache License 2.0
google/gvisor
gvisor/runsc: address typos from github Fixes: https://github.com/google/gvisor/issues/143 Fixes #143 PiperOrigin-RevId: 240600719 Change-Id: Id1731b9969f98e32e52e144a6643e12b0b70f168
259,962
28.03.2019 18:17:40
25,200
cc0e96a4bd3348ecc2a636fd90118b8e5cce672c
Fix Panic in SACKScoreboard.Delete. The panic was caused by modifying the tree while iterating which invalidated the iterator. Also fixes another bug in SACKScoreboard.Insert() which was causing blocks to be merged incorrectly.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/sack_scoreboard.go", "new_path": "pkg/tcpip/transport/tcp/sack_scoreboard.go", "diff": "@@ -77,7 +77,7 @@ func (s *SACKScoreboard) Insert(r header.SACKBlock) {\nsacked := i.(header.SACKBlock)\n// There is a hole between these two SACK blocks, so we can't\n// merge anymore.\n- if r.End.LessThan(r.Start) {\n+ if r.End.LessThan(sacked.Start) {\nreturn false\n}\n// There is some overlap at this point, merge the blocks and\n@@ -167,7 +167,11 @@ func (s *SACKScoreboard) String() string {\n// Delete removes all SACK information prior to seq.\nfunc (s *SACKScoreboard) Delete(seq seqnum.Value) {\n+ if s.Empty() {\n+ return\n+ }\ntoDelete := []btree.Item{}\n+ toInsert := []btree.Item{}\nr := header.SACKBlock{seq, seq.Add(1)}\ns.ranges.DescendLessOrEqual(r, func(i btree.Item) bool {\nif i == r {\n@@ -179,13 +183,16 @@ func (s *SACKScoreboard) Delete(seq seqnum.Value) {\ns.sacked -= sb.Start.Size(sb.End)\n} else {\nnewSB := header.SACKBlock{seq, sb.End}\n- s.ranges.ReplaceOrInsert(newSB)\n+ toInsert = append(toInsert, newSB)\ns.sacked -= sb.Start.Size(seq)\n}\nreturn true\n})\n- for _, i := range toDelete {\n- s.ranges.Delete(i)\n+ for _, sb := range toDelete {\n+ s.ranges.Delete(sb)\n+ }\n+ for _, sb := range toInsert {\n+ s.ranges.ReplaceOrInsert(sb)\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/sack_scoreboard_test.go", "new_path": "pkg/tcpip/transport/tcp/sack_scoreboard_test.go", "diff": "@@ -77,6 +77,15 @@ func TestSACKScoreboardIsSACKED(t *testing.T) {\n},\n4294254144,\n},\n+ {\n+ \"Test disjoint SACKBlocks out of order\",\n+ []header.SACKBlock{{827450276, 827454536}, {827426028, 827428868}},\n+ []blockTest{\n+ {header.SACKBlock{827426028, 827428867}, true},\n+ {header.SACKBlock{827450168, 827450275}, false},\n+ },\n+ 827426000,\n+ },\n}\nfor _, tc := range testCases {\nsb := initScoreboard(tc.scoreboardBlocks, tc.iss)\n" } ]
Go
Apache License 2.0
google/gvisor
Fix Panic in SACKScoreboard.Delete. The panic was caused by modifying the tree while iterating which invalidated the iterator. Also fixes another bug in SACKScoreboard.Insert() which was causing blocks to be merged incorrectly. PiperOrigin-RevId: 240895053 Change-Id: Ia72b8244297962df5c04283346da5226434740af
259,962
29.03.2019 12:04:42
25,200
45c54b1f4e2bb6fcad14b8b7734d6a1847329901
Fix incorrect checksums in TCP and UDP tests.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/testing/context/context.go", "new_path": "pkg/tcpip/transport/tcp/testing/context/context.go", "diff": "@@ -327,9 +327,7 @@ func (c *Context) BuildSegment(payload []byte, h *Headers) buffer.VectorisedView\n})\n// Calculate the TCP pseudo-header checksum.\n- xsum := header.Checksum([]byte(TestAddr), 0)\n- xsum = header.Checksum([]byte(StackAddr), xsum)\n- xsum = header.Checksum([]byte{0, uint8(tcp.ProtocolNumber)}, xsum)\n+ xsum := header.PseudoHeaderChecksum(tcp.ProtocolNumber, TestAddr, StackAddr, uint16(len(t)))\n// Calculate the TCP checksum and set it.\nxsum = header.Checksum(payload, xsum)\n@@ -481,9 +479,7 @@ func (c *Context) SendV6Packet(payload []byte, h *Headers) {\n})\n// Calculate the TCP pseudo-header checksum.\n- xsum := header.Checksum([]byte(TestV6Addr), 0)\n- xsum = header.Checksum([]byte(StackV6Addr), xsum)\n- xsum = header.Checksum([]byte{0, uint8(tcp.ProtocolNumber)}, xsum)\n+ xsum := header.PseudoHeaderChecksum(tcp.ProtocolNumber, TestV6Addr, StackV6Addr, uint16(len(t)))\n// Calculate the TCP checksum and set it.\nxsum = header.Checksum(payload, xsum)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/udp_test.go", "new_path": "pkg/tcpip/transport/udp/udp_test.go", "diff": "@@ -195,9 +195,7 @@ func (c *testContext) sendV6Packet(payload []byte, h *headers) {\n})\n// Calculate the UDP pseudo-header checksum.\n- xsum := header.Checksum([]byte(testV6Addr), 0)\n- xsum = header.Checksum([]byte(stackV6Addr), xsum)\n- xsum = header.Checksum([]byte{0, uint8(udp.ProtocolNumber)}, xsum)\n+ xsum := header.PseudoHeaderChecksum(udp.ProtocolNumber, testV6Addr, stackV6Addr, uint16(len(u)))\n// Calculate the UDP checksum and set it.\nxsum = header.Checksum(payload, xsum)\n@@ -233,9 +231,7 @@ func (c *testContext) sendPacket(payload []byte, h *headers) {\n})\n// Calculate the UDP pseudo-header checksum.\n- xsum := header.Checksum([]byte(testAddr), 0)\n- xsum = header.Checksum([]byte(stackAddr), xsum)\n- xsum = header.Checksum([]byte{0, uint8(udp.ProtocolNumber)}, xsum)\n+ xsum := header.PseudoHeaderChecksum(udp.ProtocolNumber, testAddr, stackAddr, uint16(len(u)))\n// Calculate the UDP checksum and set it.\nxsum = header.Checksum(payload, xsum)\n" } ]
Go
Apache License 2.0
google/gvisor
Fix incorrect checksums in TCP and UDP tests. PiperOrigin-RevId: 241025361 Change-Id: I292e7aea9a4b294b11e4f736e107010d9524586b
259,885
29.03.2019 13:15:49
25,200
69afd0438e3213b8bf6d74bdf9c288772f81e834
Return srclen in proc.idMapFileOperations.Write.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/proc/uid_gid_map.go", "new_path": "pkg/sentry/fs/proc/uid_gid_map.go", "diff": "@@ -169,5 +169,8 @@ func (imfo *idMapFileOperations) Write(ctx context.Context, file *fs.File, src u\nif err != nil {\nreturn 0, err\n}\n- return int64(len(b)), nil\n+\n+ // On success, Linux's kernel/user_namespace.c:map_write() always returns\n+ // count, even if fewer bytes were used.\n+ return int64(srclen), nil\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/proc_pid_uid_gid_map.cc", "new_path": "test/syscalls/linux/proc_pid_uid_gid_map.cc", "diff": "@@ -129,6 +129,23 @@ TEST_P(ProcSelfUidGidMapTest, IdentityMapOwnID) {\nIsPosixErrorOkAndHolds(0));\n}\n+TEST_P(ProcSelfUidGidMapTest, TrailingNewlineAndNULIgnored) {\n+ // This is identical to IdentityMapOwnID, except that a trailing newline, NUL,\n+ // and an invalid (incomplete) map entry are appended to the valid entry. The\n+ // newline should be accepted, and everything after the NUL should be ignored.\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(CanCreateUserNamespace()));\n+ uint32_t id = CurrentID();\n+ std::string line = absl::StrCat(id, \" \", id, \" 1\\n\\0 4 3\");\n+ EXPECT_THAT(\n+ InNewUserNamespaceWithMapFD([&](int fd) {\n+ DenySelfSetgroups();\n+ // The write should return the full size of the write, even though\n+ // characters after the NUL were ignored.\n+ TEST_PCHECK(write(fd, line.c_str(), line.size()) == line.size());\n+ }),\n+ IsPosixErrorOkAndHolds(0));\n+}\n+\nTEST_P(ProcSelfUidGidMapTest, NonIdentityMapOwnID) {\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(CanCreateUserNamespace()));\nSKIP_IF(ASSERT_NO_ERRNO_AND_VALUE(HaveSetIDCapability()));\n" } ]
Go
Apache License 2.0
google/gvisor
Return srclen in proc.idMapFileOperations.Write. PiperOrigin-RevId: 241037926 Change-Id: I4b0381ac1c7575e8b861291b068d3da22bc03850
259,885
29.03.2019 16:24:29
25,200
26e8d9981fcf6d08199a9fd9c609d9715c3cf37e
Use kernel.Task.CopyScratchBuffer in syscalls/linux where possible.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task.go", "new_path": "pkg/sentry/kernel/task.go", "diff": "@@ -550,17 +550,16 @@ func (t *Task) afterLoad() {\nt.futexWaiter = futex.NewWaiter()\n}\n-// copyScratchBufferLen is the length of the copyScratchBuffer field of the Task\n-// struct.\n-const copyScratchBufferLen = 52\n+// copyScratchBufferLen is the length of Task.copyScratchBuffer.\n+const copyScratchBufferLen = 144 // sizeof(struct stat)\n// CopyScratchBuffer returns a scratch buffer to be used in CopyIn/CopyOut\n// functions. It must only be used within those functions and can only be used\n// by the task goroutine; it exists to improve performance and thus\n// intentionally lacks any synchronization.\n//\n-// Callers should pass a constant value as an argument, which will allow the\n-// compiler to inline and optimize out the if statement below.\n+// Callers should pass a constant value as an argument if possible, which will\n+// allow the compiler to inline and optimize out the if statement below.\nfunc (t *Task) CopyScratchBuffer(size int) []byte {\nif size > copyScratchBufferLen {\nreturn make([]byte, size)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_prctl.go", "new_path": "pkg/sentry/syscalls/linux/sys_prctl.go", "diff": "@@ -75,7 +75,7 @@ func Prctl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\ncase linux.PR_GET_NAME:\naddr := args[1].Pointer()\n- buf := make([]byte, linux.TASK_COMM_LEN)\n+ buf := t.CopyScratchBuffer(linux.TASK_COMM_LEN)\nlen := copy(buf, t.Name())\nif len < linux.TASK_COMM_LEN {\nbuf[len] = 0\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_socket.go", "new_path": "pkg/sentry/syscalls/linux/sys_socket.go", "diff": "@@ -516,7 +516,7 @@ func SetSockOpt(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sy\nif optLen > maxOptLen {\nreturn 0, nil, syscall.EINVAL\n}\n- buf := make([]byte, optLen)\n+ buf := t.CopyScratchBuffer(int(optLen))\nif _, err := t.CopyIn(optValAddr, &buf); err != nil {\nreturn 0, nil, err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_stat.go", "new_path": "pkg/sentry/syscalls/linux/sys_stat.go", "diff": "@@ -133,7 +133,7 @@ func stat(t *kernel.Task, d *fs.Dirent, dirPath bool, statAddr usermem.Addr) err\n// common syscall for many applications, and t.CopyObjectOut has\n// noticeable performance impact due to its many slice allocations and\n// use of reflection.\n- b := make([]byte, 0, linux.SizeOfStat)\n+ b := t.CopyScratchBuffer(int(linux.SizeOfStat))[:0]\n// Dev (uint64)\nb = binary.AppendUint64(b, usermem.ByteOrder, uint64(d.Inode.StableAttr.DeviceID))\n" } ]
Go
Apache License 2.0
google/gvisor
Use kernel.Task.CopyScratchBuffer in syscalls/linux where possible. PiperOrigin-RevId: 241072126 Change-Id: Ib4d9f58f550732ac4c5153d3cf159a5b1a9749da
259,885
01.04.2019 10:17:28
25,200
60efd53822fe8bb6b737a1e9a722d8317807ee9a
Fix MemfdTest_OtherProcessCanOpenFromProcfs. Make the body of InForkedProcess async-signal-safe. Pass the correct path to open().
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/memfd.cc", "new_path": "test/syscalls/linux/memfd.cc", "diff": "@@ -485,10 +485,12 @@ TEST(MemfdTest, CanOpenFromProcfs) {\nTEST(MemfdTest, OtherProcessCanOpenFromProcfs) {\nconst FileDescriptor memfd =\nASSERT_NO_ERRNO_AND_VALUE(MemfdCreate(kMemfdName, MFD_ALLOW_SEALING));\n- pid_t pid = getpid();\n+ const auto memfd_path =\n+ absl::StrFormat(\"/proc/%d/fd/%d\", getpid(), memfd.get());\nconst auto rest = [&] {\n- ASSERT_NO_ERRNO(\n- Open(absl::StrFormat(\"/proc/self/%d/%d\", pid, memfd.get()), O_RDWR));\n+ int fd = open(memfd_path.c_str(), O_RDWR);\n+ TEST_PCHECK(fd >= 0);\n+ TEST_PCHECK(close(fd) >= 0);\n};\nEXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0));\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix MemfdTest_OtherProcessCanOpenFromProcfs. - Make the body of InForkedProcess async-signal-safe. - Pass the correct path to open(). PiperOrigin-RevId: 241348774 Change-Id: I753dfa36e4fb05521e659c173e3b7db0c7fc159b
259,853
01.04.2019 12:52:19
25,200
a4b34e26372528ef60140acef0b7c1ab1934f82a
gvisor: convert ilist to ilist:generic_list ilist:generic_list works faster (cl/240185278) and the code looks cleaner without type casting.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/BUILD", "new_path": "pkg/sentry/fs/BUILD", "diff": "@@ -14,6 +14,7 @@ go_library(\n\"dirent_cache.go\",\n\"dirent_list.go\",\n\"dirent_state.go\",\n+ \"event_list.go\",\n\"file.go\",\n\"file_operations.go\",\n\"file_overlay.go\",\n@@ -46,7 +47,6 @@ go_library(\ndeps = [\n\"//pkg/abi/linux\",\n\"//pkg/amutex\",\n- \"//pkg/ilist\",\n\"//pkg/log\",\n\"//pkg/metric\",\n\"//pkg/p9\",\n@@ -83,6 +83,18 @@ go_template_instance(\n},\n)\n+go_template_instance(\n+ name = \"event_list\",\n+ out = \"event_list.go\",\n+ package = \"fs\",\n+ prefix = \"event\",\n+ template = \"//pkg/ilist:generic_list\",\n+ types = {\n+ \"Linker\": \"*Event\",\n+ \"Element\": \"*Event\",\n+ },\n+)\n+\ngo_test(\nname = \"fs_x_test\",\nsize = \"small\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/inotify.go", "new_path": "pkg/sentry/fs/inotify.go", "diff": "@@ -19,7 +19,6 @@ import (\n\"sync/atomic\"\n\"gvisor.googlesource.com/gvisor/pkg/abi/linux\"\n- \"gvisor.googlesource.com/gvisor/pkg/ilist\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/arch\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/context\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/memmap\"\n@@ -51,7 +50,7 @@ type Inotify struct {\nevMu sync.Mutex `state:\"nosave\"`\n// A list of pending events for this inotify instance. Protected by evMu.\n- events ilist.List\n+ events eventList\n// A scratch buffer, use to serialize inotify events. Use allocate this\n// ahead of time and reuse performance. Protected by evMu.\n@@ -143,9 +142,7 @@ func (i *Inotify) Read(ctx context.Context, _ *File, dst usermem.IOSequence, _ i\n}\nvar writeLen int64\n- for e := i.events.Front(); e != nil; e = e.Next() {\n- event := e.(*Event)\n-\n+ for event := i.events.Front(); event != nil; event = event.Next() {\n// Does the buffer have enough remaining space to hold the event we're\n// about to write out?\nif dst.NumBytes() < int64(event.sizeOf()) {\n@@ -160,7 +157,7 @@ func (i *Inotify) Read(ctx context.Context, _ *File, dst usermem.IOSequence, _ i\n// Linux always dequeues an available event as long as there's enough\n// buffer space to copy it out, even if the copy below fails. Emulate\n// this behaviour.\n- i.events.Remove(e)\n+ i.events.Remove(event)\n// Buffer has enough space, copy event to the read buffer.\nn, err := event.CopyTo(ctx, i.scratch, dst)\n@@ -197,8 +194,7 @@ func (i *Inotify) Ioctl(ctx context.Context, io usermem.IO, args arch.SyscallArg\ndefer i.evMu.Unlock()\nvar n uint32\nfor e := i.events.Front(); e != nil; e = e.Next() {\n- event := e.(*Event)\n- n += uint32(event.sizeOf())\n+ n += uint32(e.sizeOf())\n}\nvar buf [4]byte\nusermem.ByteOrder.PutUint32(buf[:], n)\n@@ -216,7 +212,7 @@ func (i *Inotify) queueEvent(ev *Event) {\n// Check if we should coalesce the event we're about to queue with the last\n// one currently in the queue. Events are coalesced if they are identical.\nif last := i.events.Back(); last != nil {\n- if ev.equals(last.(*Event)) {\n+ if ev.equals(last) {\n// \"Coalesce\" the two events by simply not queuing the new one. We\n// don't need to raise a waiter.EventIn notification because no new\n// data is available for reading.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/inotify_event.go", "new_path": "pkg/sentry/fs/inotify_event.go", "diff": "@@ -18,7 +18,6 @@ import (\n\"bytes\"\n\"fmt\"\n- \"gvisor.googlesource.com/gvisor/pkg/ilist\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/context\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\"\n)\n@@ -31,7 +30,7 @@ const inotifyEventBaseSize = 16\n//\n// +stateify savable\ntype Event struct {\n- ilist.Entry\n+ eventEntry\nwd int32\nmask uint32\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/pipe/BUILD", "new_path": "pkg/sentry/kernel/pipe/BUILD", "diff": "package(licenses = [\"notice\"])\n+load(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\nload(\"//tools/go_stateify:defs.bzl\", \"go_library\", \"go_test\")\n+go_template_instance(\n+ name = \"buffer_list\",\n+ out = \"buffer_list.go\",\n+ package = \"pipe\",\n+ prefix = \"buffer\",\n+ template = \"//pkg/ilist:generic_list\",\n+ types = {\n+ \"Element\": \"*Buffer\",\n+ \"Linker\": \"*Buffer\",\n+ },\n+)\n+\ngo_library(\nname = \"pipe\",\nsrcs = [\n+ \"buffer_list.go\",\n\"buffers.go\",\n\"device.go\",\n\"node.go\",\n@@ -18,7 +32,6 @@ go_library(\ndeps = [\n\"//pkg/abi/linux\",\n\"//pkg/amutex\",\n- \"//pkg/ilist\",\n\"//pkg/sentry/arch\",\n\"//pkg/sentry/context\",\n\"//pkg/sentry/device\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/pipe/buffers.go", "new_path": "pkg/sentry/kernel/pipe/buffers.go", "diff": "package pipe\n-import (\n- \"gvisor.googlesource.com/gvisor/pkg/ilist\"\n-)\n-\n// Buffer encapsulates a queueable byte buffer that can\n// easily be truncated. It is designed only for use with pipes.\n//\n// +stateify savable\ntype Buffer struct {\n- ilist.Entry\n+ bufferEntry\ndata []byte\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/pipe/pipe.go", "new_path": "pkg/sentry/kernel/pipe/pipe.go", "diff": "@@ -25,7 +25,6 @@ import (\n\"sync/atomic\"\n\"syscall\"\n- \"gvisor.googlesource.com/gvisor/pkg/ilist\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/context\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/fs\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/usermem\"\n@@ -51,7 +50,7 @@ type Pipe struct {\nDirent *fs.Dirent\n// The buffered byte queue.\n- data ilist.List\n+ data bufferList\n// Max size of the pipe in bytes. When this max has been reached,\n// writers will get EWOULDBLOCK.\n@@ -170,13 +169,12 @@ func (p *Pipe) read(ctx context.Context, dst usermem.IOSequence) (int64, error)\nreturn 0, syserror.ErrWouldBlock\n}\nvar n int64\n- for b := p.data.Front(); b != nil; b = p.data.Front() {\n- buffer := b.(*Buffer)\n+ for buffer := p.data.Front(); buffer != nil; buffer = p.data.Front() {\nn0, err := dst.CopyOut(ctx, buffer.bytes())\nn += int64(n0)\np.size -= n0\nif buffer.truncate(n0) == 0 {\n- p.data.Remove(b)\n+ p.data.Remove(buffer)\n}\ndst = dst.DropFirst(n0)\nif dst.NumBytes() == 0 || err != nil {\n" }, { "change_type": "MODIFY", "old_path": "pkg/waiter/BUILD", "new_path": "pkg/waiter/BUILD", "diff": "package(licenses = [\"notice\"])\n+load(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\nload(\"//tools/go_stateify:defs.bzl\", \"go_library\", \"go_test\")\n+go_template_instance(\n+ name = \"waiter_list\",\n+ out = \"waiter_list.go\",\n+ package = \"waiter\",\n+ prefix = \"waiter\",\n+ template = \"//pkg/ilist:generic_list\",\n+ types = {\n+ \"Element\": \"*Entry\",\n+ \"Linker\": \"*Entry\",\n+ },\n+)\n+\ngo_library(\nname = \"waiter\",\n- srcs = [\"waiter.go\"],\n+ srcs = [\n+ \"waiter.go\",\n+ \"waiter_list.go\",\n+ ],\nimportpath = \"gvisor.googlesource.com/gvisor/pkg/waiter\",\nvisibility = [\"//visibility:public\"],\n- deps = [\"//pkg/ilist\"],\n)\ngo_test(\n@@ -18,3 +33,11 @@ go_test(\n],\nembed = [\":waiter\"],\n)\n+\n+filegroup(\n+ name = \"autogen\",\n+ srcs = [\n+ \"waiter_list.go\",\n+ ],\n+ visibility = [\"//:sandbox\"],\n+)\n" }, { "change_type": "MODIFY", "old_path": "pkg/waiter/waiter.go", "new_path": "pkg/waiter/waiter.go", "diff": "@@ -59,8 +59,6 @@ package waiter\nimport (\n\"sync\"\n-\n- \"gvisor.googlesource.com/gvisor/pkg/ilist\"\n)\n// EventMask represents io events as used in the poll() syscall.\n@@ -127,7 +125,7 @@ type Entry struct {\n// The following fields are protected by the queue lock.\nmask EventMask\n- ilist.Entry\n+ waiterEntry\n}\ntype channelCallback struct{}\n@@ -162,7 +160,7 @@ func NewChannelEntry(c chan struct{}) (Entry, chan struct{}) {\n//\n// +stateify savable\ntype Queue struct {\n- list ilist.List `state:\"zerovalue\"`\n+ list waiterList `state:\"zerovalue\"`\nmu sync.RWMutex `state:\"nosave\"`\n}\n@@ -186,8 +184,7 @@ func (q *Queue) EventUnregister(e *Entry) {\n// in common with the notification mask.\nfunc (q *Queue) Notify(mask EventMask) {\nq.mu.RLock()\n- for it := q.list.Front(); it != nil; it = it.Next() {\n- e := it.(*Entry)\n+ for e := q.list.Front(); e != nil; e = e.Next() {\nif mask&e.mask != 0 {\ne.Callback.Callback(e)\n}\n@@ -201,8 +198,7 @@ func (q *Queue) Events() EventMask {\nret := EventMask(0)\nq.mu.RLock()\n- for it := q.list.Front(); it != nil; it = it.Next() {\n- e := it.(*Entry)\n+ for e := q.list.Front(); e != nil; e = e.Next() {\nret |= e.mask\n}\nq.mu.RUnlock()\n" } ]
Go
Apache License 2.0
google/gvisor
gvisor: convert ilist to ilist:generic_list ilist:generic_list works faster (cl/240185278) and the code looks cleaner without type casting. PiperOrigin-RevId: 241381175 Change-Id: I8487ab1d73637b3e9733c253c56dce9e79f0d35f
259,885
01.04.2019 14:46:28
25,200
b4006686d2752857b406c6c7e53a112efca826ff
Don't expand COW-break on executable VMAs.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/mm/pma.go", "new_path": "pkg/sentry/mm/pma.go", "diff": "@@ -318,7 +318,23 @@ func (mm *MemoryManager) getPMAsInternalLocked(ctx context.Context, vseg vmaIter\npanic(fmt.Sprintf(\"pma %v needs to be copied for writing, but is not readable: %v\", pseg.Range(), oldpma))\n}\n}\n- copyAR := pseg.Range().Intersect(maskAR)\n+ // The majority of copy-on-write breaks on executable pages\n+ // come from:\n+ //\n+ // - The ELF loader, which must zero out bytes on the last\n+ // page of each segment after the end of the segment.\n+ //\n+ // - gdb's use of ptrace to insert breakpoints.\n+ //\n+ // Neither of these cases has enough spatial locality to\n+ // benefit from copying nearby pages, so if the vma is\n+ // executable, only copy the pages required.\n+ var copyAR usermem.AddrRange\n+ if vseg.ValuePtr().effectivePerms.Execute {\n+ copyAR = pseg.Range().Intersect(ar)\n+ } else {\n+ copyAR = pseg.Range().Intersect(maskAR)\n+ }\n// Get internal mappings from the pma to copy from.\nif err := pseg.getInternalMappingsLocked(); err != nil {\nreturn pstart, pseg.PrevGap(), err\n" } ]
Go
Apache License 2.0
google/gvisor
Don't expand COW-break on executable VMAs. PiperOrigin-RevId: 241403847 Change-Id: I4631ca05734142da6e80cdfa1a1d63ed68aa05cc
259,985
01.04.2019 15:38:08
25,200
7cff746ef2bbe5351e5985bebc88efc9e0881c78
Save/restore simple devices. We weren't saving simple devices' last allocated inode numbers, which caused inode number reuse across S/R.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/device/BUILD", "new_path": "pkg/sentry/device/BUILD", "diff": "-load(\"//tools/go_stateify:defs.bzl\", \"go_library\", \"go_test\")\n-\npackage(licenses = [\"notice\"])\n+load(\"//tools/go_stateify:defs.bzl\", \"go_library\", \"go_test\")\n+\ngo_library(\nname = \"device\",\nsrcs = [\"device.go\"],\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/device/device.go", "new_path": "pkg/sentry/device/device.go", "diff": "// Package device defines reserved virtual kernel devices and structures\n// for managing them.\n-//\n-// Saving and restoring devices is not necessary if the devices are initialized\n-// as package global variables. Package initialization happens in a single goroutine\n-// and in a deterministic order, so minor device numbers will be assigned in the\n-// same order as packages are loaded.\npackage device\nimport (\n@@ -30,7 +25,83 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/abi/linux\"\n)\n+// Registry tracks all simple devices and related state on the system for\n+// save/restore.\n+//\n+// The set of devices across save/restore must remain consistent. That is, no\n+// devices may be created or removed on restore relative to the saved\n+// system. Practically, this means do not create new devices specifically as\n+// part of restore.\n+//\n+// +stateify savable\n+type Registry struct {\n+ // lastAnonDeviceMinor is the last minor device number used for an anonymous\n+ // device. Must be accessed atomically.\n+ lastAnonDeviceMinor uint64\n+\n+ // mu protects the fields below.\n+ mu sync.Mutex `state:\"nosave\"`\n+\n+ devices map[ID]*Device\n+}\n+\n+// SimpleDevices is the system-wide simple device registry. This is\n+// saved/restored by kernel.Kernel, but defined here to allow access without\n+// depending on the kernel package. See kernel.Kernel.deviceRegistry.\n+var SimpleDevices = newRegistry()\n+\n+func newRegistry() *Registry {\n+ return &Registry{\n+ devices: make(map[ID]*Device),\n+ }\n+}\n+\n+// newAnonID assigns a major and minor number to an anonymous device ID.\n+func (r *Registry) newAnonID() ID {\n+ return ID{\n+ // Anon devices always have a major number of 0.\n+ Major: 0,\n+ // Use the next minor number.\n+ Minor: atomic.AddUint64(&r.lastAnonDeviceMinor, 1),\n+ }\n+}\n+\n+// newAnonDevice allocates a new anonymous device with a unique minor device\n+// number, and registers it with r.\n+func (r *Registry) newAnonDevice() *Device {\n+ r.mu.Lock()\n+ defer r.mu.Unlock()\n+ d := &Device{\n+ ID: r.newAnonID(),\n+ }\n+ r.devices[d.ID] = d\n+ return d\n+}\n+\n+// LoadFrom initializes the internal state of all devices in r from other. The\n+// set of devices in both registries must match. Devices may not be created or\n+// destroyed across save/restore.\n+func (r *Registry) LoadFrom(other *Registry) {\n+ r.mu.Lock()\n+ defer r.mu.Unlock()\n+ other.mu.Lock()\n+ defer other.mu.Unlock()\n+ if len(r.devices) != len(other.devices) {\n+ panic(fmt.Sprintf(\"Devices were added or removed when restoring the registry:\\nnew:\\n%+v\\nold:\\n%+v\", r.devices, other.devices))\n+ }\n+ for id, otherD := range other.devices {\n+ ourD, ok := r.devices[id]\n+ if !ok {\n+ panic(fmt.Sprintf(\"Device %+v could not be restored as it wasn't defined in the new registry\", otherD))\n+ }\n+ ourD.loadFrom(otherD)\n+ }\n+ atomic.StoreUint64(&r.lastAnonDeviceMinor, atomic.LoadUint64(&other.lastAnonDeviceMinor))\n+}\n+\n// ID identifies a device.\n+//\n+// +stateify savable\ntype ID struct {\nMajor uint64\nMinor uint64\n@@ -41,18 +112,12 @@ func (i *ID) DeviceID() uint64 {\nreturn uint64(linux.MakeDeviceID(uint16(i.Major), uint32(i.Minor)))\n}\n-// nextAnonDeviceMinor is the next minor number for a new anonymous device.\n-// Must be accessed atomically.\n-var nextAnonDeviceMinor uint64\n-\n// NewAnonDevice creates a new anonymous device. Packages that require an anonymous\n// device should initialize the device in a global variable in a file called device.go:\n//\n// var myDevice = device.NewAnonDevice()\nfunc NewAnonDevice() *Device {\n- return &Device{\n- ID: newAnonID(),\n- }\n+ return SimpleDevices.newAnonDevice()\n}\n// NewAnonMultiDevice creates a new multi-keyed anonymous device. Packages that require\n@@ -62,21 +127,13 @@ func NewAnonDevice() *Device {\n// var myDevice = device.NewAnonMultiDevice()\nfunc NewAnonMultiDevice() *MultiDevice {\nreturn &MultiDevice{\n- ID: newAnonID(),\n- }\n-}\n-\n-// newAnonID assigns a major and minor number to an anonymous device ID.\n-func newAnonID() ID {\n- return ID{\n- // Anon devices always have a major number of 0.\n- Major: 0,\n- // Use the next minor number.\n- Minor: atomic.AddUint64(&nextAnonDeviceMinor, 1),\n+ ID: SimpleDevices.newAnonID(),\n}\n}\n// Device is a simple virtual kernel device.\n+//\n+// +stateify savable\ntype Device struct {\nID\n@@ -84,6 +141,14 @@ type Device struct {\nlast uint64\n}\n+// loadFrom initializes d from other. The IDs of both devices must match.\n+func (d *Device) loadFrom(other *Device) {\n+ if d.ID != other.ID {\n+ panic(fmt.Sprintf(\"Attempting to initialize a device %+v from %+v, but device IDs don't match\", d, other))\n+ }\n+ atomic.StoreUint64(&d.last, atomic.LoadUint64(&other.last))\n+}\n+\n// NextIno generates a new inode number\nfunc (d *Device) NextIno() uint64 {\nreturn atomic.AddUint64(&d.last, 1)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/BUILD", "new_path": "pkg/sentry/kernel/BUILD", "diff": "@@ -137,6 +137,7 @@ go_library(\nimportpath = \"gvisor.googlesource.com/gvisor/pkg/sentry/kernel\",\nimports = [\n\"gvisor.googlesource.com/gvisor/pkg/bpf\",\n+ \"gvisor.googlesource.com/gvisor/pkg/sentry/device\",\n\"gvisor.googlesource.com/gvisor/pkg/tcpip\",\n],\nvisibility = [\"//:sandbox\"],\n@@ -156,6 +157,7 @@ go_library(\n\"//pkg/secio\",\n\"//pkg/sentry/arch\",\n\"//pkg/sentry/context\",\n+ \"//pkg/sentry/device\",\n\"//pkg/sentry/fs\",\n\"//pkg/sentry/fs/lock\",\n\"//pkg/sentry/fs/timerfd\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/kernel.go", "new_path": "pkg/sentry/kernel/kernel.go", "diff": "@@ -185,6 +185,9 @@ type Kernel struct {\n// socketTable is used to track all sockets on the system. Protected by\n// extMu.\nsocketTable map[int]map[*refs.WeakRef]struct{}\n+\n+ // deviceRegistry is used to save/restore device.SimpleDevices.\n+ deviceRegistry struct{} `state:\".(*device.Registry)\"`\n}\n// InitKernelArgs holds arguments to Init.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/kernel_state.go", "new_path": "pkg/sentry/kernel/kernel_state.go", "diff": "package kernel\nimport (\n+ \"gvisor.googlesource.com/gvisor/pkg/sentry/device\"\n\"gvisor.googlesource.com/gvisor/pkg/tcpip\"\n)\n@@ -29,3 +30,13 @@ func (k *Kernel) loadDanglingEndpoints(es []tcpip.Endpoint) {\ntcpip.AddDanglingEndpoint(e)\n}\n}\n+\n+// saveDeviceRegistry is invoked by stateify.\n+func (k *Kernel) saveDeviceRegistry() *device.Registry {\n+ return device.SimpleDevices\n+}\n+\n+// loadDeviceRegistry is invoked by stateify.\n+func (k *Kernel) loadDeviceRegistry(r *device.Registry) {\n+ device.SimpleDevices.LoadFrom(r)\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/stat.cc", "new_path": "test/syscalls/linux/stat.cc", "diff": "@@ -429,6 +429,39 @@ TEST_F(StatTest, LstatELOOPPath) {\nASSERT_THAT(lstat(path.c_str(), &s), SyscallFailsWithErrno(ELOOP));\n}\n+// Ensure that inode allocation for anonymous devices work correctly across\n+// save/restore. In particular, inode numbers should be unique across S/R.\n+TEST(SimpleStatTest, AnonDeviceAllocatesUniqueInodesAcrossSaveRestore) {\n+ // Use sockets as a convenient way to create inodes on an anonymous device.\n+ int fd;\n+ ASSERT_THAT(fd = socket(AF_UNIX, SOCK_STREAM, 0), SyscallSucceeds());\n+ FileDescriptor fd1(fd);\n+ MaybeSave();\n+ ASSERT_THAT(fd = socket(AF_UNIX, SOCK_STREAM, 0), SyscallSucceeds());\n+ FileDescriptor fd2(fd);\n+\n+ struct stat st1;\n+ struct stat st2;\n+ ASSERT_THAT(fstat(fd1.get(), &st1), SyscallSucceeds());\n+ ASSERT_THAT(fstat(fd2.get(), &st2), SyscallSucceeds());\n+\n+ // The two fds should have different inode numbers. Specifically, since fd2\n+ // was created later, it should have a higher inode number.\n+ EXPECT_GT(st2.st_ino, st1.st_ino);\n+\n+ // Verify again after another S/R cycle. The inode numbers should remain the\n+ // same.\n+ MaybeSave();\n+\n+ struct stat st1_after;\n+ struct stat st2_after;\n+ ASSERT_THAT(fstat(fd1.get(), &st1_after), SyscallSucceeds());\n+ ASSERT_THAT(fstat(fd2.get(), &st2_after), SyscallSucceeds());\n+\n+ EXPECT_EQ(st1_after.st_ino, st1.st_ino);\n+ EXPECT_EQ(st2_after.st_ino, st2.st_ino);\n+}\n+\n} // namespace\n} // namespace testing\n" } ]
Go
Apache License 2.0
google/gvisor
Save/restore simple devices. We weren't saving simple devices' last allocated inode numbers, which caused inode number reuse across S/R. PiperOrigin-RevId: 241414245 Change-Id: I964289978841ef0a57d2fa48daf8eab7633c1284
259,858
01.04.2019 16:17:40
25,200
7543e9ec2043af7d071373aeec04b92a98051087
Add release hook and version flag
[ { "change_type": "MODIFY", "old_path": "runsc/BUILD", "new_path": "runsc/BUILD", "diff": "@@ -6,12 +6,13 @@ go_binary(\nname = \"runsc\",\nsrcs = [\n\"main.go\",\n+ \"version.go\",\n],\npure = \"on\",\nvisibility = [\n\"//visibility:public\",\n],\n- x_defs = {\"main.gitRevision\": \"{GIT_REVISION}\"},\n+ x_defs = {\"main.version\": \"{VERSION}\"},\ndeps = [\n\"//pkg/log\",\n\"//runsc/boot\",\n@@ -36,12 +37,13 @@ go_binary(\nname = \"runsc-race\",\nsrcs = [\n\"main.go\",\n+ \"version.go\",\n],\nstatic = \"on\",\nvisibility = [\n\"//visibility:public\",\n],\n- x_defs = {\"main.gitRevision\": \"{GIT_REVISION}\"},\n+ x_defs = {\"main.version\": \"{VERSION}\"},\ndeps = [\n\"//pkg/log\",\n\"//runsc/boot\",\n" }, { "change_type": "MODIFY", "old_path": "runsc/main.go", "new_path": "runsc/main.go", "diff": "@@ -18,6 +18,7 @@ package main\nimport (\n\"context\"\n+ \"fmt\"\n\"io\"\n\"os\"\n\"path/filepath\"\n@@ -40,6 +41,7 @@ var (\nlogFilename = flag.String(\"log\", \"\", \"file path where internal debug information is written, default is stdout\")\nlogFormat = flag.String(\"log-format\", \"text\", \"log format: text (default), json, or json-k8s\")\ndebug = flag.Bool(\"debug\", false, \"enable debug logging\")\n+ showVersion = flag.Bool(\"version\", false, \"show version and exit\")\n// These flags are unique to runsc, and are used to configure parts of the\n// system that are not covered by the runtime spec.\n@@ -69,9 +71,6 @@ var (\ntestOnlyAllowRunAsCurrentUserWithoutChroot = flag.Bool(\"TESTONLY-unsafe-nonroot\", false, \"TEST ONLY; do not ever use! This skips many security measures that isolate the host from the sandbox.\")\n)\n-// gitRevision is set during linking.\n-var gitRevision = \"\"\n-\nfunc main() {\n// Help and flags commands are generated automatically.\nsubcommands.Register(subcommands.HelpCommand(), \"\")\n@@ -107,6 +106,14 @@ func main() {\n// All subcommands must be registered before flag parsing.\nflag.Parse()\n+ // Are we showing the version?\n+ if *showVersion {\n+ // The format here is the same as runc.\n+ fmt.Fprintf(os.Stdout, \"runsc version %s\\n\", version)\n+ fmt.Fprintf(os.Stdout, \"spec: %s\\n\", specutils.Version)\n+ os.Exit(0)\n+ }\n+\nplatformType, err := boot.MakePlatformType(*platform)\nif err != nil {\ncmd.Fatalf(\"%v\", err)\n@@ -215,7 +222,7 @@ func main() {\nlog.Infof(\"***************************\")\nlog.Infof(\"Args: %s\", os.Args)\n- log.Infof(\"Git Revision: %s\", gitRevision)\n+ log.Infof(\"Version %s\", version)\nlog.Infof(\"PID: %d\", os.Getpid())\nlog.Infof(\"UID: %d, GID: %d\", os.Getuid(), os.Getgid())\nlog.Infof(\"Configuration:\")\n" }, { "change_type": "MODIFY", "old_path": "runsc/specutils/specutils.go", "new_path": "runsc/specutils/specutils.go", "diff": "@@ -38,6 +38,9 @@ import (\n// changed in tests that aren't linked in the same binary.\nvar ExePath = \"/proc/self/exe\"\n+// Version is the supported spec version.\n+var Version = specs.Version\n+\n// LogSpec logs the spec in a human-friendly way.\nfunc LogSpec(spec *specs.Spec) {\nlog.Debugf(\"Spec: %+v\", spec)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "runsc/version.go", "diff": "+// Copyright 2019 Google LLC\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 main\n+\n+// version is set during linking.\n+var version = \"\"\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/tag_release.sh", "diff": "+#!/bin/bash\n+\n+# Copyright 2019 Google LLC\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+# This script will optionally map a PiperOrigin-RevId to a given commit,\n+# validate a provided release name, create a tag and push it. It must be\n+# run manually when a release is created.\n+\n+set -euxo pipefail\n+\n+# Check arguments.\n+if [ \"$#\" -ne 2 ]; then\n+ echo \"usage: $0 <commit|revid> <release.rc>\"\n+ exit 1\n+fi\n+\n+commit=$1\n+release=$2\n+\n+# Is the passed identifier a sha commit?\n+if ! git show \"${commit}\" &> /dev/null; then\n+ # Extract the commit given a piper ID.\n+ commit=$(git log|grep -E \"(^commit |^ PiperOrigin-RevId:)\" |grep -B1 \"RevId: ${commit}\"| head -n1|cut -d\" \" -f2)\n+fi\n+if ! git show \"${commit}\" &> /dev/null; then\n+ echo \"unknown commit: ${commit}\"\n+ exit 1\n+fi\n+\n+# Is the release name sane? Must be a date with patch/rc.\n+if ! [[ \"${release}\" =~ ^20[0-9]{6}\\.[0-9]+$ ]]; then\n+ expected=$(date +%Y%m%d.0) # Use today's date.\n+ echo \"unexpected release format: ${release}\"\n+ echo \" ... expected like ${expected}\"\n+ exit 1\n+fi\n+\n+# Tag the given commit.\n+tag=\"release-${release}\"\n+(git tag \"${tag}\" \"${commit}\" && git push origin tag \"${tag}\") || \\\n+ (git tag -d \"${tag}\" && false)\n" }, { "change_type": "MODIFY", "old_path": "tools/workspace_status.sh", "new_path": "tools/workspace_status.sh", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-echo GIT_REVISION $(git describe --always --abbrev=40 --dirty)\n+echo VERSION $(git describe --always --tags --abbrev=12 --dirty)\n" } ]
Go
Apache License 2.0
google/gvisor
Add release hook and version flag PiperOrigin-RevId: 241421671 Change-Id: Ic0cebfe3efd458dc42c49f7f812c13318705199a
259,858
01.04.2019 16:54:43
25,200
b19b7f3e46ce57bec4b70c7f7ef748295dec558b
Drop godoc handling.
[ { "change_type": "MODIFY", "old_path": "cmd/gvisor-website/app.yaml", "new_path": "cmd/gvisor-website/app.yaml", "diff": "runtime: go111\nhandlers:\n+ - url: /(change|cl||issue)(/.*)?\n+ secure: always\n+ script: auto\n- url: /.*\nsecure: always\nscript: auto\n- # TODO: remove this when published\n+ # TODO: remove this when published.\nlogin: admin\n- # - url: /(change|cl|godoc|issue)(/.*)?\n- # secure: always\n- # script: auto\n- # - url: /(.*)\n- # secure: always\n- # redirect_http_response_code: 301\n- # static_files: static/\\1\n- # upload: static/.*\n" }, { "change_type": "MODIFY", "old_path": "cmd/gvisor-website/main.go", "new_path": "cmd/gvisor-website/main.go", "diff": "@@ -28,7 +28,6 @@ import (\nvar redirects = map[string]string{\n\"/change\": \"https://gvisor.googlesource.com/gvisor/\",\n\"/cl\": \"https://gvisor-review.googlesource.com/\",\n- \"/godoc\": \"https://godoc.org/github.com/google/gvisor\",\n\"/issue\": \"https://github.com/google/gvisor/issues\",\n\"/issue/new\": \"https://github.com/google/gvisor/issues/new\",\n}\n@@ -36,9 +35,7 @@ var redirects = map[string]string{\nvar prefixHelpers = map[string]string{\n\"cl\": \"https://gvisor-review.googlesource.com/c/gvisor/+/%s\",\n\"change\": \"https://gvisor.googlesource.com/gvisor/+/%s\",\n- \"godoc\": \"https://godoc.org/github.com/google/gvisor/%s\",\n\"issue\": \"https://github.com/google/gvisor/issues/%s\",\n- \"syscall\": \"/docs/user_guide/compatibility/syscall_reference/#%s\",\n}\nvar validId = regexp.MustCompile(`^[A-Za-z0-9-]*/?$`)\n" } ]
Go
Apache License 2.0
google/gvisor
Drop godoc handling.
259,854
02.04.2019 10:25:24
25,200
27a8830ca2021406f1232a257a8c971f83f793f2
Fix governance link on community page.
[ { "change_type": "MODIFY", "old_path": "content/docs/community/_index.md", "new_path": "content/docs/community/_index.md", "diff": "@@ -18,7 +18,7 @@ collaborate.\n<iframe src=\"https://calendar.google.com/calendar/b/1/embed?showTitle=0&amp;height=600&amp;wkst=1&amp;bgcolor=%23FFFFFF&amp;src=bd6f4k210u3ukmlj9b8vl053fk%40group.calendar.google.com&amp;color=%23AB8B00&amp;ctz=America%2FLos_Angeles\" style=\"border-width:0\" width=\"800\" height=\"600\" frameborder=\"0\" scrolling=\"no\"></iframe>\n[community]: https://gvisor.googlesource.com/community\n-[goverance]: https://gvisor.googlesource.com/community/+/refs/heads/master/README.md\n+[governance]: https://gvisor.googlesource.com/community/+/refs/heads/master/README.md\n[gvisor-dev]: https://groups.google.com/forum/#!forum/gvisor-dev\n[gvisor-users]: https://groups.google.com/forum/#!forum/gvisor-users\n[codeofconduct]: https://gvisor.googlesource.com/community/+/refs/heads/master/CODE_OF_CONDUCT.md\n" } ]
Go
Apache License 2.0
google/gvisor
Fix governance link on community page. (#2)
259,854
02.04.2019 10:26:01
25,200
cf172c7ab4e8e8d3c95be7be88e14fae0e8c11c6
Tweaks to architecture guide
[ { "change_type": "MODIFY", "old_path": "content/docs/architecture_guide/overview.md", "new_path": "content/docs/architecture_guide/overview.md", "diff": "title = \"Overview & Platforms\"\nweight = 10\n+++\n-gVisor sandbox consists of multiple processes when running. These sandboxes\n+A gVisor sandbox consists of multiple processes when running. These processes\ncollectively comprise a shared environment in which one or more containers can\nbe run.\n@@ -28,7 +28,7 @@ the [OCI runtime spec][runtime-spec] for more information on filesystem bundles.\n`runsc` implements multiple commands that perform various functions such as\nstarting, stopping, listing, and querying the status of containers.\n-## The Sentry\n+## Sentry\nThe Sentry is the largest component of gVisor. It can be thought of as a\nuserspace OS kernel. The Sentry implements all the kernel functionality needed\n@@ -37,33 +37,33 @@ signal delivery, memory management and page faulting logic, the threading\nmodel, and more.\nWhen the untrusted application makes a system call, the currently used platform\n-redirects to the Sentry, which will do the necessary work to service the system\n-call. It is important to note that the Sentry will not simply pass through\n-system calls to the host kernel. As a userspace application, the Sentry will\n-make some host system calls to support its operation, but it will not allow the\n+redirects the call to the Sentry, which will do the necessary work to service\n+it. It is important to note that the Sentry will not simply pass through system\n+calls to the host kernel. As a userspace application, the Sentry will make some\n+host system calls to support its operation, but it will not allow the\napplication to directly control the system calls it makes.\nThe Sentry aims to present an equivalent environment to (upstream) Linux v4.4.\n-I/O operations that extend beyond the sandbox (not internal /proc files, pipes,\n-etc) are sent to the Gofer, described below.\n+File system operations that extend beyond the sandbox (not internal /proc\n+files, pipes, etc) are sent to the Gofer, described below.\n## Platforms\n-gVisor requires a platform to implement interruption of syscalls, basic context\n+gVisor requires a platform to implement interception of syscalls, basic context\nswitching, and memory mapping functionality.\n### ptrace\n-The ptrace platform uses `PTRACE_SYSEMU` to execute user code without executing\n-host system calls. This platform can run anywhere that ptrace works (even VMs\n-without nested virtualization).\n+The ptrace platform uses `PTRACE_SYSEMU` to execute user code without allowing\n+it to execute host system calls. This platform can run anywhere that ptrace\n+works (even VMs without nested virtualization).\n### KVM (experimental)\nThe KVM platform allows the Sentry to act as both guest OS and VMM, switching\nback and forth between the two worlds seamlessly. The KVM platform can run on\n-bare-metal or on a VM with nested virtualization enabled. While there is no\n+bare-metal or in a VM with nested virtualization enabled. While there is no\nvirtualized hardware layer -- the sandbox retains a process model -- gVisor\nleverages virtualization extensions available on modern processors in order to\nimprove isolation and performance of address space switches.\n@@ -73,12 +73,12 @@ improve isolation and performance of address space switches.\nThe Gofer is a normal host Linux process. The Gofer is started with each sandbox\nand connected to the Sentry. The Sentry process is started in a restricted\nseccomp container without access to file system resources. The Gofer provides\n-access to file system resources to the Sentry via the 9P protocol and provides\n-an additional level of isolation.\n+the Sentry access to file system resources via the 9P protocol and provides an\n+additional level of isolation.\n## Application\n-The application (aka, the untrusted application) is a normal Linux binary\n+The application (aka the untrusted application) is a normal Linux binary\nprovided to gVisor in an OCI runtime bundle. gVisor aims to provide an\nenvironment equivalent to Linux v4.4, so applications should be able to run\nunmodified. However, gVisor does not presently implement every system call,\n" } ]
Go
Apache License 2.0
google/gvisor
Tweaks to architecture guide (#4)
259,891
02.04.2019 11:26:47
25,200
a40ee4f4b8a6874157759723583d6489bbac7f23
Change bug number for duplicate bug.
[ { "change_type": "MODIFY", "old_path": "runsc/boot/controller.go", "new_path": "runsc/boot/controller.go", "diff": "@@ -232,7 +232,7 @@ func (cm *containerManager) Start(args *StartArgs, _ *struct{}) error {\n}\n// Prevent CIDs containing \"..\" from confusing the sentry when creating\n// /containers/<cid> directory.\n- // TODO: Once we have multiple independant roots, this\n+ // TODO: Once we have multiple independent roots, this\n// check won't be necessary.\nif path.Clean(args.CID) != args.CID {\nreturn fmt.Errorf(\"container ID shouldn't contain directory traversals such as \\\"..\\\": %q\", args.CID)\n" } ]
Go
Apache License 2.0
google/gvisor
Change bug number for duplicate bug. PiperOrigin-RevId: 241567897 Change-Id: I580eac04f52bb15f4aab7df9822c4aa92e743021
259,881
02.04.2019 11:35:32
25,200
b11221fe7ce7a3620c8145de2d4219ab2b8625b7
Reword to remove duplicate "Linux" "Linux x86_64 Linux 3.17+" is wordy. Reword to mention Linux only once.
[ { "change_type": "MODIFY", "old_path": "content/docs/includes/install_gvisor.md", "new_path": "content/docs/includes/install_gvisor.md", "diff": "-> Note: gVisor requires Linux x86\\_64 Linux 3.17+.\n+> Note: gVisor supports only x86\\_64 and requires Linux 3.17+.\nThe easiest way to get `runsc` is from the [latest nightly\nbuild][latest-nightly]. After you download the binary, check it against the\n" } ]
Go
Apache License 2.0
google/gvisor
Reword to remove duplicate "Linux" (#6) "Linux x86_64 Linux 3.17+" is wordy. Reword to mention Linux only once.
259,854
02.04.2019 10:10:39
25,200
882a3a914ea8fb48f15e29f24fc0ed6a56fa84f6
Capitalize "the" after colon in title
[ { "change_type": "MODIFY", "old_path": "content/docs/architecture_guide/security.md", "new_path": "content/docs/architecture_guide/security.md", "diff": "@@ -7,7 +7,7 @@ exploitation of kernel bugs when running untrusted code. In order to understand\nhow gVisor achieves this goal, it is first necessary to understand the basic\nthreat model.\n-## Threats: the Anatomy of an Exploit\n+## Threats: The Anatomy of an Exploit\nAn exploit takes advantage of a software or hardware bug in order to escalate\nprivileges, gain access to privileged data, or disrupt services. All of the\n" } ]
Go
Apache License 2.0
google/gvisor
Capitalize "the" after colon in title https://blog.apastyle.org/apastyle/2011/06/capitalization-after-colons.html
259,854
02.04.2019 10:48:18
25,200
0d1c1d94eec097edd8a53e44bff25e479f85bb10
Remove duplicate word not
[ { "change_type": "MODIFY", "old_path": "content/docs/architecture_guide/security.md", "new_path": "content/docs/architecture_guide/security.md", "diff": "@@ -138,7 +138,7 @@ We allow a sandbox to do the following.\nfiles. The calls include duplication and closing of file descriptors,\nsynchronization, timers and signal management.\n1. Read and write packets to a virtual ethernet device. This is not required if\n- not host networking is enabled.\n+ host networking is enabled.\n## Principles: Defense-in-Depth\n" } ]
Go
Apache License 2.0
google/gvisor
Remove duplicate word not
259,854
02.04.2019 10:49:24
25,200
f419ffb46d34654e69e8dba3174bba3bc192f5c4
Add that veth is not required if networking is disabled.
[ { "change_type": "MODIFY", "old_path": "content/docs/architecture_guide/security.md", "new_path": "content/docs/architecture_guide/security.md", "diff": "@@ -138,7 +138,7 @@ We allow a sandbox to do the following.\nfiles. The calls include duplication and closing of file descriptors,\nsynchronization, timers and signal management.\n1. Read and write packets to a virtual ethernet device. This is not required if\n- host networking is enabled.\n+ host networking is enabled (or networking is disabled).\n## Principles: Defense-in-Depth\n" } ]
Go
Apache License 2.0
google/gvisor
Add that veth is not required if networking is disabled.
259,854
02.04.2019 10:53:24
25,200
dacb87a938986fa937c682062fa035f36566dea8
Replace distinct with independent. I think this is clearer.
[ { "change_type": "MODIFY", "old_path": "content/docs/architecture_guide/security.md", "new_path": "content/docs/architecture_guide/security.md", "diff": "@@ -146,8 +146,8 @@ For gVisor development, there are several engineering principles that are\nemployed in order to ensure that the system meets its design goals.\n1. No system call is passed through directly to the host. Every supported call\n- has a distinct implementation in the Sentry, that is unlikely to suffer from\n- identical vulnerabilities that may appear in the host. This has the\n+ has an independent implementation in the Sentry, that is unlikely to suffer\n+ from identical vulnerabilities that may appear in the host. This has the\nconsequence that all kernel features used by applications require an\nimplementation within the Sentry.\n1. Only common, universal functionality is implemented. Some filesystems,\n" } ]
Go
Apache License 2.0
google/gvisor
Replace distinct with independent. I think this is clearer.
259,858
02.04.2019 13:42:14
25,200
ff7f193073fdc075f47d1d8f0a450ec5fd130097
Use a top-level docs link
[ { "change_type": "MODIFY", "old_path": "content/_index.html", "new_path": "content/_index.html", "diff": "@@ -37,7 +37,7 @@ Capable of running most Linux applications unmodified, with zero configuration.\n{{< blocks/section color=\"white\" >}}\n{{% blocks/feature icon=\"fas fa-book\" title=\"Read the Docs\" %}}\n-Read the [documentation](./docs/user_guide/) to understand gVisor, its architecture and trade-offs, and how to use it.\n+Read the [documentation](./docs/) to understand gVisor, its architecture and trade-offs, and how to use it.\n{{% /blocks/feature %}}\n{{% blocks/feature icon=\"fas fa-code-branch\" title=\"Contribute to gVisor\" %}}\n" } ]
Go
Apache License 2.0
google/gvisor
Use a top-level docs link
259,884
02.04.2019 03:27:24
14,400
4c7a3ecacd432f16287be8a2dc144a2bb50ad163
Fix edit links in documentation
[ { "change_type": "MODIFY", "old_path": "layouts/partials/page-meta-links.html", "new_path": "layouts/partials/page-meta-links.html", "diff": "{{ $gh_repo := ($.Param \"github_repo\") }}\n{{ if $gh_repo }}\n<div class=\"td-page-meta ml-2 pb-1 pt-2 mb-0\">\n-{{ $editURL := printf \"%s/edit/master/content/%s/%s\" $gh_repo ($.Site.Language.Lang) .Path }}\n+{{ $editURL := printf \"%s/edit/master/content/%s\" $gh_repo .Path }}\n{{ $issuesURL := printf \"%s/issues/new?title=%s\" $gh_repo (htmlEscape $.Title )}}\n<a href=\"{{ $editURL }}\" target=\"_blank\" rel=\"noopener\"><i class=\"fa fa-edit fa-fw\"></i> {{ T \"post_edit_this\" }}</a>\n<a href=\"{{ $issuesURL }}\" target=\"_blank\" rel=\"noopener\"><i class=\"fab fa-github fa-fw\"></i> {{ T \"post_create_issue\" }}</a>\n" } ]
Go
Apache License 2.0
google/gvisor
Fix edit links in documentation
259,884
29.03.2019 23:53:20
14,400
009f45da3bc2d6c66e597e56f02aa32f4ffb8d2b
Remove superfluous section from compatibility top
[ { "change_type": "MODIFY", "old_path": "content/docs/user_guide/compatibility/_index.md", "new_path": "content/docs/user_guide/compatibility/_index.md", "diff": "@@ -36,8 +36,3 @@ The following applications/images have been tested:\n* wordpress\n[bug]: https://github.com/google/gvisor/issues\n-\n-## Syscall Reference\n-\n-This section contains an architecture-specific syscall reference guide. These\n-tables are automatically generated from source-level annotations.\n" } ]
Go
Apache License 2.0
google/gvisor
Remove superfluous section from compatibility top
259,884
30.03.2019 00:02:19
14,400
0fa497a567ba0b387f4b42035a3894dca37018f5
Update syscall ref doc generator
[ { "change_type": "MODIFY", "old_path": "cmd/parse-syscall-annotations/main.go", "new_path": "cmd/parse-syscall-annotations/main.go", "diff": "@@ -59,14 +59,14 @@ var (\nr2 *regexp.Regexp\nmdTemplate = template.Must(template.New(\"name\").Parse(`+++\n-title = \"Syscall Reference\"\n-description = \"Syscall Compatibility Reference Documentation\"\n+title = \"AMD64\"\n+description = \"Syscall Compatibility Reference Documentation for AMD64\"\nweight = 10\n+++\n-This table is a reference of Linux syscalls and their compatibility status in\n-gVisor. gVisor does not support all syscalls and some syscalls may have a\n-partial implementation.\n+This table is a reference of Linux syscalls for the AMD64 architecture and\n+their compatibility status in gVisor. gVisor does not support all syscalls and\n+some syscalls may have a partial implementation.\nOf {{ .Total }} syscalls, {{ .Implemented }} syscalls have a full or partial\nimplementation. There are currently {{ .Unimplemented }} unimplemented\n" }, { "change_type": "MODIFY", "old_path": "content/docs/user_guide/compatibility/amd64.md", "new_path": "content/docs/user_guide/compatibility/amd64.md", "diff": "+++\ntitle = \"AMD64\"\n+description = \"Syscall Compatibility Reference Documentation for AMD64\"\nweight = 10\n+++\n-This table is a reference of Linux syscalls for AMD64 and their compatibility\n-status in gVisor. gVisor does not support all syscalls and some syscalls may\n-have a partial implementation.\n-Of 329 syscalls, 47 syscalls have a full or partial implementation. There are\n-currently 51 unimplemented syscalls. 231 syscalls are not yet documented.\n+This table is a reference of Linux syscalls for the AMD64 architecture and\n+their compatibility status in gVisor. gVisor does not support all syscalls and\n+some syscalls may have a partial implementation.\n+\n+Of 329 syscalls, 47 syscalls have a full or partial\n+implementation. There are currently 51 unimplemented\n+syscalls. 231 syscalls are not yet documented.\n<table>\n<thead>\n" } ]
Go
Apache License 2.0
google/gvisor
Update syscall ref doc generator
259,884
30.03.2019 00:43:21
14,400
96dedf5dd6c42125b3c6f976a1447de96e804600
Removed link to filesystem page
[ { "change_type": "MODIFY", "old_path": "content/docs/user_guide/FAQ.md", "new_path": "content/docs/user_guide/FAQ.md", "diff": "@@ -26,7 +26,6 @@ Note that `kubectl cp` works because it does the copy by exec'ing inside the\nsandbox, and thus gVisor cache is aware of the new files and dirs.\nThere are also different filesystem modes that can be used to avoid this issue.\n-See [Filesystem](../filesystem/).\n### What's the security model?\n" } ]
Go
Apache License 2.0
google/gvisor
Removed link to filesystem page
259,884
31.03.2019 20:18:04
14,400
0803a82bffccdd609db03743d145c3d6656f220e
Updated style for top page cover
[ { "change_type": "ADD", "old_path": null, "new_path": "assets/scss/_custom_styles.scss", "diff": "+// Custom styles.\n+\n+// The table anchor for syscall references so that entries referenced\n+// directly by an anchor aren't buried underneath the header.\n+a.doc-table-anchor {\n+ display: block;\n+ position: relative;\n+ top: -75px;\n+ visibility: hidden;\n+}\n+\n+// Adjust the width of the svg logo in the header. For smaller svg\n+// files the width is too large.\n+.td-navbar .navbar-brand .navbar-logo svg {\n+ width: auto;\n+}\n+\n+.td-navbar-cover .navbar-brand {\n+ display: none;\n+}\n+.td-navbar-cover.navbar-bg-onscroll .navbar-brand {\n+ display: inherit;\n+}\n+\n+// Cover block.\n+.td-default main section.td-cover-block h1 {\n+ padding-bottom: 6rem;\n+}\n+\n+.td-default main section.td-cover-block {\n+ padding-top: 4rem;\n+ padding-bottom: 8rem;\n+}\n+\n+.td-default main section.td-cover-block p.lead {\n+ width: 50%;\n+ font-size: 2rem;\n+}\n+\n+.td-default main section.td-cover-block p.lead strong {\n+ font-weight: bold;\n+}\n+\n" }, { "change_type": "MODIFY", "old_path": "assets/scss/_variables_project.scss", "new_path": "assets/scss/_variables_project.scss", "diff": "$primary: #262362;\n$secondary: #ffffff;\n-// Custom styles.\n-a.doc-table-anchor {\n- display: block;\n- position: relative;\n- top: -75px;\n- visibility: hidden;\n-}\n-\n-.td-navbar {\n- .navbar-brand {\n- .navbar-logo {\n- svg {\n- width: auto;\n- }\n- }\n- }\n-}\n-\n// Fonts.\n$google_font_name: \"Roboto\";\n$google_font_family: \"Roboto\";\n" }, { "change_type": "ADD", "old_path": null, "new_path": "assets/scss/main.scss", "diff": "+@import \"support/functions\";\n+@import \"variables_project\";\n+@import \"variables\";\n+@import \"support/mixins\";\n+\n+@import \"../vendor/bootstrap/scss/bootstrap\";\n+\n+@import \"../vendor/Font-Awesome//web-fonts-with-css/scss/fontawesome.scss\";\n+@import \"../vendor/Font-Awesome//web-fonts-with-css/scss/fa-solid.scss\";\n+@import \"../vendor/Font-Awesome//web-fonts-with-css/scss/fa-brands.scss\";\n+\n+@import \"support/utilities\";\n+@import \"colors\";\n+@import \"boxes\";\n+@import \"blog\";\n+@import \"code\";\n+@import \"nav\";\n+@import \"sidebar-tree\";\n+@import \"sidebar-toc\";\n+@import \"buttons\";\n+@import \"breadcrumb\";\n+@import \"alerts\";\n+@import \"content\";\n+@import \"search\";\n+@import \"main-container\";\n+@import \"blocks/blocks\";\n+\n+@if $td-enable-google-fonts {\n+ @import url($web-font-path);\n+}\n+\n+footer {\n+ min-height: 150px;\n+\n+ @include media-breakpoint-down(md) {\n+ min-height: 200px;\n+ }\n+}\n+\n+// Adjust anchors vs the fixed menu.\n+@include media-breakpoint-up(md) {\n+ .td-offset-anchor:target {\n+ display: block;\n+ position: relative;\n+ top: -4rem;\n+ visibility: hidden;\n+ }\n+\n+ h2[id]:before, h3[id]:before, h4[id]:before, h5[id]:before {\n+ display: block;\n+ content: \" \";\n+ margin-top: -5rem;\n+ height: 5rem;\n+ visibility: hidden;\n+ }\n+}\n+\n+@import \"custom_styles\";\n" }, { "change_type": "MODIFY", "old_path": "content/_index.html", "new_path": "content/_index.html", "diff": "@@ -5,9 +5,9 @@ description = \"A container sandbox runtime focused on security, efficiency, and\n+++\n{{< blocks/cover image_anchor=\"top\" height=\"auto\" color=\"primary\" title=\"gVisor\" >}}\n-<div class=\"mx-auto\" style=\"margin-bottom: 8rem !important;\">\n- <p class=\"lead\" style=\"font-size: 1.6rem\">A container sandbox runtime focused on <strong>security</strong>, <strong>efficiency</strong>, and <strong>ease of use</strong>.</p>\n- <a class=\"btn btn-lg btn-secondary mr-3 mb-4\" href=\"./docs/user_guide/docker/\">Quick Start<i class=\"fas fa-arrow-alt-circle-right ml-2\"></i></a>\n+<div class=\"mx-auto\">\n+ <p class=\"lead\">A container sandbox runtime focused on <strong>security</strong>, <strong>efficiency</strong>, and <strong>ease of use</strong>.</p>\n+ <a class=\"btn btn-lg btn-primary mr-3 mb-4\" href=\"./docs/user_guide/docker/\" >Quick Start<i class=\"fas fa-arrow-alt-circle-right ml-2\"></i></a>\n<a class=\"btn btn-lg btn-secondary mr-3 mb-4\" href=\"https://github.com/google/gvisor\" rel=\"noopener\">GitHub <i class=\"fab fa-github ml-2\"></i></a>\n</div>\n{{< /blocks/cover >}}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "layouts/shortcodes/blocks/cover.html", "diff": "+{{ $blockID := printf \"td-cover-block-%d\" .Ordinal }}\n+{{ $promo_image := (.Page.Resources.ByType \"image\").GetMatch \"**background*\" }}\n+{{ $logo_image := (.Page.Resources.ByType \"image\").GetMatch \"**logo*\" }}\n+{{ $col_id := .Get \"color\" | default \"dark\" }}\n+{{ $image_anchor := .Get \"image_anchor\" | default \"smart\" }}\n+{{ $logo_anchor := .Get \"logo_anchor\" | default \"smart\" }}\n+{{/* Height can be one of: auto, min, med, max, full. */}}\n+{{ $height := .Get \"height\" | default \"max\" }}\n+{{ with $promo_image }}\n+{{ $promo_image_big := (.Fill (printf \"1920x1080 %s\" $image_anchor)) }}\n+{{ $promo_image_small := (.Fill (printf \"960x540 %s\" $image_anchor)) }}\n+<link rel=\"preload\" as=\"image\" href=\"{{ $promo_image_small.RelPermalink }}\" media=\"(max-width: 1200px)\">\n+<link rel=\"preload\" as=\"image\" href=\"{{ $promo_image_big.RelPermalink }}\" media=\"(min-width: 1200px)\">\n+<style>\n+#{{ $blockID }} {\n+ background-image: url({{ $promo_image_small.RelPermalink }});\n+}\n+@media only screen and (min-width: 1200px) {\n+ #{{ $blockID }} {\n+ background-image: url({{ $promo_image_big.RelPermalink }});\n+ }\n+}\n+</style>\n+{{ end }}\n+<section id=\"{{ $blockID }}\" class=\"row td-cover-block td-cover-block--height-{{ $height }} js-td-cover td-overlay td-overlay--dark -bg-{{ $col_id }}\">\n+ <div class=\"container td-overlay__inner\">\n+ <div class=\"row\">\n+ <div class=\"col-12\">\n+ {{ with .Get \"title\" }}<h1 class=\"display-1 mt-0 mt-md-5\">{{ $title := . }}{{ with $logo_image }}{{ $logo_image_resized := (.Fit (printf \"70x70 %s\" $logo_anchor)) }}<img class=\"td-cover-logo\" src=\"{{ $logo_image_resized.RelPermalink }}\" alt=\"{{ $title | html }} Logo\">{{ end }}{{ $title | html }}</h1>{{ end }}\n+ {{ with .Get \"subtitle\" }}<p class=\"display-2 text-uppercase mb-0\">{{ . | html }}</p>{{ end }}\n+ <div class=\"pt-3 lead\">\n+ {{ .Inner }}\n+ </div>\n+ </div>\n+ </div>\n+ </div>\n+</section>\n" } ]
Go
Apache License 2.0
google/gvisor
Updated style for top page cover
259,884
31.03.2019 20:26:11
14,400
9288f50ee371b6bfc96c5ca7ef208be955e7314c
Convert background from png to jpg jpeg is much smaller for the background image. 2.5mb -> 86.7kb
[ { "change_type": "RENAME", "old_path": "content/background.png", "new_path": "assets/backgrounds/background.png", "diff": "" }, { "change_type": "RENAME", "old_path": "content/background.svg", "new_path": "assets/backgrounds/background.svg", "diff": "" }, { "change_type": "ADD", "old_path": "content/background.jpg", "new_path": "content/background.jpg", "diff": "Binary files /dev/null and b/content/background.jpg differ\n" } ]
Go
Apache License 2.0
google/gvisor
Convert background from png to jpg jpeg is much smaller for the background image. 2.5mb -> 86.7kb
259,884
31.03.2019 20:57:11
14,400
d37053976470412c4895ca30c370d80e3ea42d76
Adjust link color to improve accessibility.
[ { "change_type": "MODIFY", "old_path": "assets/scss/_styles_project.scss", "new_path": "assets/scss/_styles_project.scss", "diff": "// Custom styles.\n+// Apply the link-color to blocks with white background to improve\n+// accessibility.\n+a, .td-box--secondary p > a, .td-box--white p > a {\n+ color: $link-color;\n+}\n+\n// The table anchor for syscall references so that entries referenced\n// directly by an anchor aren't buried underneath the header.\na.doc-table-anchor {\n@@ -15,6 +21,7 @@ a.doc-table-anchor {\nwidth: auto;\n}\n+// Only show the logo in the header after scrolling down the page.\n.td-navbar-cover .navbar-brand {\ndisplay: none;\n}\n@@ -22,22 +29,18 @@ a.doc-table-anchor {\ndisplay: inherit;\n}\n-// Cover block.\n+// Left align the cover block and increase text size.\n.td-default main section.td-cover-block h1 {\npadding-bottom: 6rem;\n}\n-\n.td-default main section.td-cover-block {\npadding-top: 4rem;\npadding-bottom: 8rem;\n}\n-\n.td-default main section.td-cover-block p.lead {\nwidth: 50%;\nfont-size: 2rem;\n}\n-\n.td-default main section.td-cover-block p.lead strong {\nfont-weight: bold;\n}\n-\n" }, { "change_type": "MODIFY", "old_path": "assets/scss/_variables_project.scss", "new_path": "assets/scss/_variables_project.scss", "diff": "// Colors.\n$primary: #262362;\n$secondary: #ffffff;\n+$link-color: #286FD7;\n// Fonts.\n$google_font_name: \"Roboto\";\n" } ]
Go
Apache License 2.0
google/gvisor
Adjust link color to improve accessibility.
259,884
31.03.2019 20:59:43
14,400
8a30257ad9eb5f38b11732c6cfa93d0f6adf9624
Adjust bottom padding for title/logo
[ { "change_type": "MODIFY", "old_path": "assets/scss/_styles_project.scss", "new_path": "assets/scss/_styles_project.scss", "diff": "@@ -31,7 +31,7 @@ a.doc-table-anchor {\n// Left align the cover block and increase text size.\n.td-default main section.td-cover-block h1 {\n- padding-bottom: 6rem;\n+ padding-bottom: 5rem;\n}\n.td-default main section.td-cover-block {\npadding-top: 4rem;\n" } ]
Go
Apache License 2.0
google/gvisor
Adjust bottom padding for title/logo
259,884
31.03.2019 21:05:39
14,400
025a0a7999724afdb3e3214172ef565da572dc92
Center the cover block for mobile devices
[ { "change_type": "MODIFY", "old_path": "assets/scss/_styles_project.scss", "new_path": "assets/scss/_styles_project.scss", "diff": "@@ -30,6 +30,11 @@ a.doc-table-anchor {\n}\n// Left align the cover block and increase text size.\n+.td-default main section.td-cover-block {\n+ @media (max-width: 768px) {\n+ text-align: center;\n+ }\n+}\n.td-default main section.td-cover-block h1 {\npadding-bottom: 5rem;\n}\n@@ -38,7 +43,9 @@ a.doc-table-anchor {\npadding-bottom: 8rem;\n}\n.td-default main section.td-cover-block p.lead {\n+ @media (min-width: 768px) {\nwidth: 50%;\n+ }\nfont-size: 2rem;\n}\n.td-default main section.td-cover-block p.lead strong {\n" } ]
Go
Apache License 2.0
google/gvisor
Center the cover block for mobile devices
259,884
31.03.2019 22:19:43
14,400
0e99ceece3bfb6103c6a81d480b6bd85247a4f1c
Update cover to match layout from designers
[ { "change_type": "MODIFY", "old_path": "assets/scss/_styles_project.scss", "new_path": "assets/scss/_styles_project.scss", "diff": "@@ -21,26 +21,47 @@ a.doc-table-anchor {\nwidth: auto;\n}\n-// Only show the logo in the header after scrolling down the page.\n+// Only show the navbar after scrolling down the page.\n.td-navbar-cover .navbar-brand {\ndisplay: none;\n}\n-.td-navbar-cover.navbar-bg-onscroll .navbar-brand {\n- display: inherit;\n+.td-navbar-cover .td-navbar-nav-scroll {\n+ @media (min-width: 768px) {\n+ display: none;\n+ }\n+}\n+.td-navbar-cover.navbar-bg-onscroll .navbar-brand, .td-navbar-cover.navbar-bg-onscroll .td-navbar-nav-scroll {\n+ @media (min-width: 768px) {\n+ display: block;\n+ }\n}\n+// Show an inner navbar as part of the cover block\n+.cover-content nav {\n+ @media (max-width: 767px) {\n+ display: none;\n+ }\n+ padding: 0;\n+ margin-top: 3rem;\n+ float: right;\n+}\n// Left align the cover block and increase text size.\n.td-default main section.td-cover-block {\n- @media (max-width: 768px) {\n+ @media (max-width: 767px) {\ntext-align: center;\n}\n}\n.td-default main section.td-cover-block h1 {\n- padding-bottom: 5rem;\n+ @media (min-width: 768px) {\n+ padding-top: 0.5rem; // match padding for .nav-link\n+ padding-bottom: 8rem;\n+ }\n}\n.td-default main section.td-cover-block {\n- padding-top: 4rem;\n- padding-bottom: 8rem;\n+ @media (min-width: 768px) {\n+ padding-top: 0;\n+ padding-bottom: 10rem;\n+ }\n}\n.td-default main section.td-cover-block p.lead {\n@media (min-width: 768px) {\n" }, { "change_type": "MODIFY", "old_path": "layouts/shortcodes/blocks/cover.html", "new_path": "layouts/shortcodes/blocks/cover.html", "diff": "<section id=\"{{ $blockID }}\" class=\"row td-cover-block td-cover-block--height-{{ $height }} js-td-cover td-overlay td-overlay--dark -bg-{{ $col_id }}\">\n<div class=\"container td-overlay__inner\">\n<div class=\"row\">\n- <div class=\"col-12\">\n+ <div class=\"cover-content col-12\">\n+ <nav class=\"navbar navbar-expand navbar-dark flex-column flex-md-row\">\n+ <div class=\"td-navbar-nav-scroll ml-md-auto\" id=\"main_navbar\">\n+ <ul class=\"navbar-nav mt-2 mt-lg-0\">\n+ {{ $p := . }}\n+ {{ range .Site.Menus.main }}\n+ <li class=\"nav-item mr-4 mb-2 mb-lg-0\">\n+ <a class=\"nav-link\" href=\"{{ with .Page }}{{ .RelPermalink }}{{ else }}{{ .URL | relLangURL }}{{ end }}\"><span>{{ .Name }}</span></a>\n+ </li>\n+ {{ end }}\n+ {{ if (gt (len .Site.Home.Translations) 0) }}\n+ <li class=\"nav-item dropdown d-none d-lg-block\">\n+ {{ partial \"navbar-lang-selector.html\" . }}\n+ </li>\n+ {{ end }}\n+ </ul>\n+ </div>\n+ <div class=\"navbar-nav d-none d-lg-block\">{{ partial \"search-input.html\" . }}</div>\n+ </nav>\n+\n{{ with .Get \"title\" }}<h1 class=\"display-1 mt-0 mt-md-5\">{{ $title := . }}{{ with $logo_image }}{{ $logo_image_resized := (.Fit (printf \"70x70 %s\" $logo_anchor)) }}<img class=\"td-cover-logo\" src=\"{{ $logo_image_resized.RelPermalink }}\" alt=\"{{ $title | html }} Logo\">{{ end }}{{ $title | html }}</h1>{{ end }}\n{{ with .Get \"subtitle\" }}<p class=\"display-2 text-uppercase mb-0\">{{ . | html }}</p>{{ end }}\n<div class=\"pt-3 lead\">\n" } ]
Go
Apache License 2.0
google/gvisor
Update cover to match layout from designers
259,858
02.04.2019 16:14:53
25,200
d81ea7a799cd39fa23ff7b26a3bc0c8a0d894dc1
Drop performance guide until complete
[ { "change_type": "MODIFY", "old_path": "content/docs/user_guide/FAQ.md", "new_path": "content/docs/user_guide/FAQ.md", "diff": "@@ -30,7 +30,3 @@ There are also different filesystem modes that can be used to avoid this issue.\n### What's the security model?\nSee the [Security Model](../../architecture_guide/security/).\n-\n-### What's the expected performance?\n-\n-See the [Performance Guide](../../architecture_guide/performance/).\n" } ]
Go
Apache License 2.0
google/gvisor
Drop performance guide until complete
259,858
02.04.2019 16:19:47
25,200
63d5bb5a161a7231f0cc2b8a9a3005210b4157f1
Update the conditional deploy
[ { "change_type": "MODIFY", "old_path": "cloudbuild.yaml", "new_path": "cloudbuild.yaml", "diff": "# limitations under the License.\nsteps:\n- # Generate the website\n+ # Generate the website.\n- name: 'gcr.io/gvisor-website/hugo:0.53'\nargs: [\"make\"]\n- # Test the HTML for issues\n+ # Test the HTML for issues.\n- name: 'gcr.io/gvisor-website/html-proofer:3.10.2'\nargs: [\"htmlproofer\", \"--disable-external\", \"public/static\"]\n- # Deploy to App Engine only for master branch\n+ # Deploy to App Engine only for master branch.\n- name: 'gcr.io/cloud-builders/gcloud'\nentrypoint: 'bash'\nargs:\n- '-c'\n- |\n- [[ \"$BRANCH_NAME\" == \"master\" ]] && gcloud app deploy public/app.yaml\n+ [[ \"$BRANCH_NAME\" == \"master\" ]] && gcloud app deploy public/app.yaml || return 0\n" } ]
Go
Apache License 2.0
google/gvisor
Update the conditional deploy
259,985
02.04.2019 16:45:27
25,200
d14a7de65865e14383e3c4e68400446189b2e5e8
Fix more data races in shm debug messages.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/shm/shm.go", "new_path": "pkg/sentry/kernel/shm/shm.go", "diff": "@@ -286,7 +286,7 @@ func (r *Registry) remove(s *Shm) {\ndefer s.mu.Unlock()\nif s.key != linux.IPC_PRIVATE {\n- panic(fmt.Sprintf(\"Attempted to remove shm segment %d (key=%d) from the registry whose key is still associated\", s.ID, s.key))\n+ panic(fmt.Sprintf(\"Attempted to remove %s from the registry whose key is still associated\", s.debugLocked()))\n}\ndelete(r.shms, s.ID)\n@@ -370,6 +370,12 @@ type Shm struct {\npendingDestruction bool\n}\n+// Precondition: Caller must hold s.mu.\n+func (s *Shm) debugLocked() string {\n+ return fmt.Sprintf(\"Shm{id: %d, key: %d, size: %d bytes, refs: %d, destroyed: %v}\",\n+ s.ID, s.key, s.size, s.ReadRefs(), s.pendingDestruction)\n+}\n+\n// MappedName implements memmap.MappingIdentity.MappedName.\nfunc (s *Shm) MappedName(ctx context.Context) string {\ns.mu.Lock()\n@@ -412,7 +418,7 @@ func (s *Shm) AddMapping(ctx context.Context, _ memmap.MappingSpace, _ usermem.A\n} else {\n// AddMapping is called during a syscall, so ctx should always be a task\n// context.\n- log.Warningf(\"Adding mapping to shm %+v but couldn't get the current pid; not updating the last attach pid\", s)\n+ log.Warningf(\"Adding mapping to %s but couldn't get the current pid; not updating the last attach pid\", s.debugLocked())\n}\nreturn nil\n}\n@@ -434,7 +440,7 @@ func (s *Shm) RemoveMapping(ctx context.Context, _ memmap.MappingSpace, _ userme\nif pid, ok := context.ThreadGroupIDFromContext(ctx); ok {\ns.lastAttachDetachPID = pid\n} else {\n- log.Debugf(\"Couldn't obtain pid when removing mapping to shm %+v, not updating the last detach pid.\", s)\n+ log.Debugf(\"Couldn't obtain pid when removing mapping to %s, not updating the last detach pid.\", s.debugLocked())\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix more data races in shm debug messages. PiperOrigin-RevId: 241630409 Change-Id: Ie0df5f5a2f20c2d32e615f16e2ba43c88f963181
259,858
02.04.2019 17:08:26
25,200
4ab738270aed18cf7aa111e2f53e9ca7f6a53a73
Substitute true for return
[ { "change_type": "MODIFY", "old_path": "cloudbuild.yaml", "new_path": "cloudbuild.yaml", "diff": "@@ -25,4 +25,4 @@ steps:\nargs:\n- '-c'\n- |\n- [[ \"$BRANCH_NAME\" == \"master\" ]] && gcloud app deploy public/app.yaml || return 0\n+ [[ \"$BRANCH_NAME\" == \"master\" ]] && gcloud app deploy public/app.yaml || true\n" } ]
Go
Apache License 2.0
google/gvisor
Substitute true for return
259,854
02.04.2019 14:27:54
25,200
da61580968c8a5862a28f29c5f95fe8a23fbd961
Update user guide platform description to match architecture section. syscall interception is an important part of the platform.
[ { "change_type": "MODIFY", "old_path": "content/docs/user_guide/platforms.md", "new_path": "content/docs/user_guide/platforms.md", "diff": "@@ -8,9 +8,9 @@ platform.\n## What is a Platform?\n-gVisor requires a *platform* to implement basic context switching and memory\n-mapping functionality. These are described in more depth in the [Architecture\n-Guide](../../architecture_guide/).\n+gVisor requires a *platform* to implement interception of syscalls, basic\n+context switching, and memory mapping functionality. These are described in\n+more depth in the [Architecture Guide](../../architecture_guide/).\n## Selecting a Platform\n" } ]
Go
Apache License 2.0
google/gvisor
Update user guide platform description to match architecture section. syscall interception is an important part of the platform.
259,858
02.04.2019 17:57:26
25,200
811de2bbe57ff863b50dec4a0f2494afd551a89e
Ensure exact match for project
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -69,7 +69,7 @@ account](https://cloud.google.com/cloud-build/docs/securing-builds/set-service-a\n```\n{\n- PROJECT_NUMBER=$(gcloud projects list --filter=gvisor-website --format=\"value(projectNumber)\")\n+ PROJECT_NUMBER=$(gcloud projects list --filter=projectId:gvisor-website --format=\"value(projectNumber)\")\ngcloud services enable appengine.googleapis.com\ngcloud projects add-iam-policy-binding gvisor-website \\\n--member=serviceAccount:${PROJECT_NUMBER}@cloudbuild.gserviceaccount.com \\\n" } ]
Go
Apache License 2.0
google/gvisor
Ensure exact match for project
259,854
02.04.2019 18:03:01
25,200
9549ed31f9617ec10f85595f152022f0e550605d
Add docs for disabling external networking. This is a useful feature for truly untrusted code.
[ { "change_type": "MODIFY", "old_path": "content/docs/user_guide/networking.md", "new_path": "content/docs/user_guide/networking.md", "diff": "@@ -33,4 +33,26 @@ Add the following `runtimeArgs` to your Docker configuration\n}\n```\n+## Disabling external networking\n+\n+To completely isolate the host and network from the sandbox, external\n+networking can be disabled. The sandbox will still contain a loopback provided\n+by netstack.\n+\n+Add the following `runtimeArgs` to your Docker configuration\n+(`/etc/docker/daemon.json`) and restart the Docker daemon:\n+\n+```json\n+{\n+ \"runtimes\": {\n+ \"runsc\": {\n+ \"path\": \"/usr/local/bin/runsc\",\n+ \"runtimeArgs\": [\n+ \"--network=none\"\n+ ]\n+ }\n+ }\n+}\n+```\n+\n[netstack]: https://github.com/google/netstack\n" } ]
Go
Apache License 2.0
google/gvisor
Add docs for disabling external networking. This is a useful feature for truly untrusted code.
259,884
03.04.2019 00:53:36
14,400
d369412917fdc2bb87037358b225b3897a515ee8
Remove parse-syscall-annotations tool for now Some more work needs to be done for generating syscall compatibility reference documentation.
[ { "change_type": "DELETE", "old_path": "cmd/parse-syscall-annotations/.gitignore", "new_path": null, "diff": "-parse-syscall-annotations\n" }, { "change_type": "DELETE", "old_path": "cmd/parse-syscall-annotations/main.go", "new_path": null, "diff": "-// Copyright 2018 Google LLC\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-// This program will take a single golang source file, or a directory containing\n-// many source files and produce a JSON output which represent any comments\n-// containing compatibility metadata.\n-\n-// Command parse-syscall-annotations parses syscall annotations from Godoc and\n-// generates a JSON file with the parsed syscall info.\n-//\n-// Annotations take the form:\n-// @Syscall(<name>, <arg>:<value>, ...)\n-//\n-// Supported args and values are:\n-// - arg: A syscall option. This entry only applies to the syscall when given this option.\n-// - support: Indicates support level\n-// - FULL: Full support\n-// - PARTIAL: Partial support. Details should be provided in note.\n-// - UNIMPLEMENTED: Unimplemented\n-// - returns: Indicates a known return value. Implies PARTIAL support. Values are syscall errors.\n-// This is treated as a string so you can use something like \"returns:EPERM or ENOSYS\".\n-// - issue: A GitHub issue number.\n-// - note: A note\n-\n-package main\n-\n-import (\n- \"encoding/json\"\n- \"flag\"\n- \"fmt\"\n- \"go/ast\"\n- \"go/parser\"\n- \"go/token\"\n- \"log\"\n- \"os\"\n- \"path/filepath\"\n- \"regexp\"\n- \"sort\"\n- \"strings\"\n- \"text/template\"\n-)\n-\n-var (\n- srcDir = flag.String(\"dir\", \"./\", \"The source directory\")\n- jsonOut = flag.Bool(\"json\", false, \"Output info as json\")\n-\n- r *regexp.Regexp\n- r2 *regexp.Regexp\n-\n- mdTemplate = template.Must(template.New(\"name\").Parse(`+++\n-title = \"AMD64\"\n-description = \"Syscall Compatibility Reference Documentation for AMD64\"\n-weight = 10\n-+++\n-\n-This table is a reference of Linux syscalls for the AMD64 architecture and\n-their compatibility status in gVisor. gVisor does not support all syscalls and\n-some syscalls may have a partial implementation.\n-\n-Of {{ .Total }} syscalls, {{ .Implemented }} syscalls have a full or partial\n-implementation. There are currently {{ .Unimplemented }} unimplemented\n-syscalls. {{ .Unknown }} syscalls are not yet documented.\n-\n-<table>\n- <thead>\n- <tr>\n- <th>#</th>\n- <th>Name</th>\n- <th>Support</th>\n- <th>GitHub Issue</th>\n- <th>Notes</th>\n- </tr>\n- </thead>\n- <tbody>{{ range .Syscalls }}{{ if ne .Support \"Unknown\" }}\n- <tr>\n- <td><a class=\"doc-table-anchor\" id=\"{{ .Name }}{{ if index .Metadata \"arg\" }}({{ index .Metadata \"arg\" }}){{ end }}\"></a>{{ .Number }}</td>\n- <td><a href=\"http://man7.org/linux/man-pages/man2/{{ .Name }}.2.html\" target=\"_blank\" rel=\"noopener\">{{ .Name }}{{ if index .Metadata \"arg\" }}({{ index .Metadata \"arg\" }}){{ end }}</a></td>\n- <td>{{ .Support }}</td>\n- <td>{{ if index .Metadata \"issue\" }}<a href=\"https://github.com/google/gvisor/issues/{{ index .Metadata \"issue\" }}\">#{{ index .Metadata \"issue\" }}</a>{{ end }}</td>\n- <td>{{ .Note }}</td>\n- </tr>{{ end }}{{ end }}\n- </tbody>\n-</table>\n-`))\n-)\n-\n-// Syscall represents a function implementation of a syscall.\n-type Syscall struct {\n- File string\n- Line int\n-\n- Number int\n- Name string\n-\n- Metadata map[string]string\n-}\n-\n-const (\n- UNKNOWN = iota\n- UNIMPLEMENTED\n- PARTIAL_SUPPORT\n- FULL_SUPPORT\n-)\n-\n-func (s *Syscall) SupportLevel() int {\n- supportLevel := UNKNOWN\n- switch strings.ToUpper(s.Metadata[\"support\"]) {\n- case \"FULL\":\n- supportLevel = FULL_SUPPORT\n- case \"PARTIAL\":\n- supportLevel = PARTIAL_SUPPORT\n- case \"UNIMPLEMENTED\":\n- supportLevel = UNIMPLEMENTED\n- }\n-\n- // If an arg or returns is specifed treat that as a partial implementation even if\n- // there is full support for the argument.\n- if s.Metadata[\"arg\"] != \"\" {\n- supportLevel = PARTIAL_SUPPORT\n- }\n- if s.Metadata[\"returns\"] != \"\" && supportLevel == UNKNOWN {\n- returns := strings.ToUpper(s.Metadata[\"returns\"])\n- // Default to PARTIAL support if only returns is specified\n- supportLevel = PARTIAL_SUPPORT\n-\n- // If ENOSYS is returned unequivically, treat it as unimplemented.\n- if returns == \"ENOSYS\" {\n- supportLevel = UNIMPLEMENTED\n- }\n- }\n-\n- return supportLevel\n-}\n-\n-func (s *Syscall) Support() string {\n- l := s.SupportLevel()\n- switch l {\n- case FULL_SUPPORT:\n- return \"Full\"\n- case PARTIAL_SUPPORT:\n- return \"Partial\"\n- case UNIMPLEMENTED:\n- return \"Unimplemented\"\n- default:\n- return \"Unknown\"\n- }\n-}\n-\n-func (s *Syscall) Note() string {\n- note := s.Metadata[\"note\"]\n- returns := s.Metadata[\"returns\"]\n- // Add \"Returns ENOSYS\" note by default if support:UNIMPLEMENTED\n- if returns == \"\" && s.SupportLevel() == UNIMPLEMENTED {\n- returns = \"ENOSYS\"\n- }\n- if returns != \"\" {\n- return_note := fmt.Sprintf(\"Returns %s\", returns)\n- if note != \"\" {\n- note = return_note + \"; \" + note\n- } else {\n- note = return_note\n- }\n- }\n- if note == \"\" && s.SupportLevel() == FULL_SUPPORT {\n- note = \"Full Support\"\n- }\n- return note\n-}\n-\n-type Report struct {\n- Implemented int\n- Unimplemented int\n- Unknown int\n- Total int\n- Syscalls []*Syscall\n-}\n-\n-func init() {\n- // Build a regex that will attempt to match all fields in tokens.\n-\n- // Regexp for matching syscall definitions\n- s := \"@Syscall\\\\(([^\\\\),]+)([^\\\\)]+)\\\\)\"\n- r = regexp.MustCompile(s)\n-\n- // Regexp for matching metadata\n- s2 := \"([^\\\\ ),]+):([^\\\\),]+)\"\n- r2 = regexp.MustCompile(s2)\n-\n- ReverseSyscallMap = make(map[string]int)\n- for no, name := range SyscallMap {\n- ReverseSyscallMap[name] = no\n- }\n-}\n-\n-// parseDoc parses all comments in a file and returns the parsed syscall\n-// information.\n-func parseDoc(fs *token.FileSet, f *ast.File) []*Syscall {\n- syscalls := []*Syscall{}\n- for _, cg := range f.Comments {\n- for _, line := range strings.Split(cg.Text(), \"\\n\") {\n- if syscall := parseLine(fs, line); syscall != nil {\n- pos := fs.Position(cg.Pos())\n- syscall.File = pos.Filename\n- syscall.Line = pos.Line\n-\n- syscalls = append(syscalls, syscall)\n- }\n- }\n- }\n- return syscalls\n-}\n-\n-// parseLine parses a single line of Godoc and returns the parsed syscall\n-// information. If no information is found, nil is returned.\n-// Syscall declarations take the form:\n-// @Syscall(<name>, <verb>:<value>, ...)\n-func parseLine(fs *token.FileSet, line string) *Syscall {\n- s := r.FindAllStringSubmatch(line, -1)\n- if len(s) > 0 {\n- name := strings.ToLower(s[0][1])\n- if n, ok := ReverseSyscallMap[name]; ok {\n- syscall := Syscall{}\n- syscall.Name = name\n- syscall.Number = n\n- syscall.Metadata = make(map[string]string)\n- s2 := r2.FindAllStringSubmatch(s[0][2], -1)\n- for _, match := range s2 {\n- syscall.Metadata[match[1]] = match[2]\n- }\n- return &syscall\n- } else {\n- log.Printf(\"Warning: unknown syscall %q\", name)\n- }\n- }\n- return nil\n-}\n-\n-func main() {\n- flag.Parse()\n-\n- var syscalls []*Syscall\n-\n- err := filepath.Walk(*srcDir, func(path string, info os.FileInfo, err error) error {\n- if info != nil && info.IsDir() {\n- fs := token.NewFileSet()\n- d, err := parser.ParseDir(fs, path, nil, parser.ParseComments)\n- if err != nil {\n- return err\n- }\n-\n- for _, p := range d {\n- for _, f := range p.Files {\n- s := parseDoc(fs, f)\n- syscalls = append(syscalls, s...)\n- }\n- }\n- }\n-\n- return nil\n- })\n-\n- if err != nil {\n- fmt.Printf(\"failed to walk dir %s: %v\", *srcDir, err)\n- os.Exit(1)\n- }\n-\n- var fullList []*Syscall\n- for no, name := range SyscallMap {\n- found := false\n- for _, s := range syscalls {\n- if s.Number == no {\n- fullList = append(fullList, s)\n- found = true\n- }\n- }\n- if !found {\n- fullList = append(fullList, &Syscall{\n- Name: name,\n- Number: no,\n- })\n- }\n- }\n-\n- // Sort the syscalls by number.\n- sort.Slice(fullList, func(i, j int) bool {\n- return fullList[i].Number < fullList[j].Number\n- })\n-\n- if *jsonOut {\n- j, err := json.Marshal(fullList)\n- if err != nil {\n- fmt.Printf(\"failed to marshal JSON: %v\", err)\n- os.Exit(1)\n- }\n- os.Stdout.Write(j)\n- return\n- }\n-\n- // Count syscalls and group by syscall number and support level\n- supportMap := map[int]int{}\n- for _, s := range fullList {\n- supportLevel := s.SupportLevel()\n-\n- // If we already have set a higher level of support\n- // keep the current value\n- if current, ok := supportMap[s.Number]; ok && supportLevel < current {\n- continue\n- }\n-\n- supportMap[s.Number] = supportLevel\n- }\n- report := Report{\n- Syscalls: fullList,\n- }\n- for _, s := range supportMap {\n- switch s {\n- case FULL_SUPPORT:\n- report.Implemented += 1\n- case PARTIAL_SUPPORT:\n- report.Implemented += 1\n- case UNIMPLEMENTED:\n- report.Unimplemented += 1\n- case UNKNOWN:\n- report.Unknown += 1\n- }\n- report.Total += 1\n- }\n-\n- err = mdTemplate.Execute(os.Stdout, report)\n- if err != nil {\n- fmt.Printf(\"failed to execute template: %v\", err)\n- os.Exit(1)\n- return\n- }\n-}\n" }, { "change_type": "DELETE", "old_path": "cmd/parse-syscall-annotations/syscall.go", "new_path": null, "diff": "-// Copyright 2018 Google LLC\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-// This program will take a single golang source file, or a directory containing\n-// many source files and produce a JSON output which represent any comments\n-// containing compatibility metadata.\n-\n-// Command parse-syscall-annotations parses syscall annotations from Godoc and\n-// generates a JSON file with the parsed syscall info.\n-\n-package main\n-\n-// ReverseSyscallMap is a map of syscall name (lowercase) to number\n-var ReverseSyscallMap map[string]int\n-\n-// SyscallMap is a map of syscall number to syscall name (lowercase)\n-var SyscallMap = map[int]string{\n- 0: \"read\",\n- 1: \"write\",\n- 2: \"open\",\n- 3: \"close\",\n- 4: \"stat\",\n- 5: \"fstat\",\n- 6: \"lstat\",\n- 7: \"poll\",\n- 8: \"lseek\",\n- 9: \"mmap\",\n- 10: \"mprotect\",\n- 11: \"munmap\",\n- 12: \"brk\",\n- 13: \"rtsigaction\",\n- 14: \"rtsigprocmask\",\n- 15: \"rtsigreturn\",\n- 16: \"ioctl\",\n- 17: \"pread64\",\n- 18: \"pwrite64\",\n- 19: \"readv\",\n- 20: \"writev\",\n- 21: \"access\",\n- 22: \"pipe\",\n- 23: \"select\",\n- 24: \"schedyield\",\n- 25: \"mremap\",\n- 26: \"msync\",\n- 27: \"mincore\",\n- 28: \"madvise\",\n- 29: \"shmget\",\n- 30: \"shmat\",\n- 31: \"shmctl\",\n- 32: \"dup\",\n- 33: \"dup2\",\n- 34: \"pause\",\n- 35: \"nanosleep\",\n- 36: \"getitimer\",\n- 37: \"alarm\",\n- 38: \"setitimer\",\n- 39: \"getpid\",\n- 40: \"sendfile\",\n- 41: \"socket\",\n- 42: \"connect\",\n- 43: \"accept\",\n- 44: \"sendto\",\n- 45: \"recvfrom\",\n- 46: \"sendmsg\",\n- 47: \"recvmsg\",\n- 48: \"shutdown\",\n- 49: \"bind\",\n- 50: \"listen\",\n- 51: \"getsockname\",\n- 52: \"getpeername\",\n- 53: \"socketpair\",\n- 54: \"setsockopt\",\n- 55: \"getsockopt\",\n- 56: \"clone\",\n- 57: \"fork\",\n- 58: \"vfork\",\n- 59: \"execve\",\n- 60: \"exit\",\n- 61: \"wait4\",\n- 62: \"kill\",\n- 63: \"uname\",\n- 64: \"semget\",\n- 65: \"semop\",\n- 66: \"semctl\",\n- 67: \"shmdt\",\n- 68: \"msgget\",\n- 69: \"msgsnd\",\n- 70: \"msgrcv\",\n- 71: \"msgctl\",\n- 72: \"fcntl\",\n- 73: \"flock\",\n- 74: \"fsync\",\n- 75: \"fdatasync\",\n- 76: \"truncate\",\n- 77: \"ftruncate\",\n- 78: \"getdents\",\n- 79: \"getcwd\",\n- 80: \"chdir\",\n- 81: \"fchdir\",\n- 82: \"rename\",\n- 83: \"mkdir\",\n- 84: \"rmdir\",\n- 85: \"creat\",\n- 86: \"link\",\n- 87: \"unlink\",\n- 88: \"symlink\",\n- 89: \"readlink\",\n- 90: \"chmod\",\n- 91: \"fchmod\",\n- 92: \"chown\",\n- 93: \"fchown\",\n- 94: \"lchown\",\n- 95: \"umask\",\n- 96: \"gettimeofday\",\n- 97: \"getrlimit\",\n- 98: \"getrusage\",\n- 99: \"sysinfo\",\n- 100: \"times\",\n- 101: \"ptrace\",\n- 102: \"getuid\",\n- 103: \"syslog\",\n- 104: \"getgid\",\n- 105: \"setuid\",\n- 106: \"setgid\",\n- 107: \"geteuid\",\n- 108: \"getegid\",\n- 109: \"setpgid\",\n- 110: \"getppid\",\n- 111: \"getpgrp\",\n- 112: \"setsid\",\n- 113: \"setreuid\",\n- 114: \"setregid\",\n- 115: \"getgroups\",\n- 116: \"setgroups\",\n- 117: \"setresuid\",\n- 118: \"getresuid\",\n- 119: \"setresgid\",\n- 120: \"getresgid\",\n- 121: \"getpgid\",\n- 122: \"setfsuid\",\n- 123: \"setfsgid\",\n- 124: \"getsid\",\n- 125: \"capget\",\n- 126: \"capset\",\n- 127: \"rtsigpending\",\n- 128: \"rtsigtimedwait\",\n- 129: \"rtsigqueueinfo\",\n- 130: \"rtsigsuspend\",\n- 131: \"sigaltstack\",\n- 132: \"utime\",\n- 133: \"mknod\",\n- 134: \"uselib\",\n- 135: \"setpersonality\",\n- 136: \"ustat\",\n- 137: \"statfs\",\n- 138: \"fstatfs\",\n- 139: \"sysfs\",\n- 140: \"getpriority\",\n- 141: \"setpriority\",\n- 142: \"schedsetparam\",\n- 143: \"schedgetparam\",\n- 144: \"schedsetscheduler\",\n- 145: \"schedgetscheduler\",\n- 146: \"schedgetprioritymax\",\n- 147: \"schedgetprioritymin\",\n- 148: \"schedrrgetinterval\",\n- 149: \"mlock\",\n- 150: \"munlock\",\n- 151: \"mlockall\",\n- 152: \"munlockall\",\n- 153: \"vhangup\",\n- 154: \"modifyldt\",\n- 155: \"pivotroot\",\n- 156: \"sysctl\",\n- 157: \"prctl\",\n- 158: \"archprctl\",\n- 159: \"adjtimex\",\n- 160: \"setrlimit\",\n- 161: \"chroot\",\n- 162: \"sync\",\n- 163: \"acct\",\n- 164: \"settimeofday\",\n- 165: \"mount\",\n- 166: \"umount2\",\n- 167: \"swapon\",\n- 168: \"swapoff\",\n- 169: \"reboot\",\n- 170: \"sethostname\",\n- 171: \"setdomainname\",\n- 172: \"iopl\",\n- 173: \"ioperm\",\n- 174: \"createmodule\",\n- 175: \"initmodule\",\n- 176: \"deletemodule\",\n- 177: \"getkernelsyms\",\n- 178: \"querymodule\",\n- 179: \"quotactl\",\n- 180: \"nfsservctl\",\n- 181: \"getpmsg\",\n- 182: \"putpmsg\",\n- 183: \"afssyscall\",\n- 184: \"tuxcall\",\n- 185: \"security\",\n- 186: \"gettid\",\n- 187: \"readahead\",\n- 188: \"setxattr\",\n- 189: \"lsetxattr\",\n- 190: \"fsetxattr\",\n- 191: \"getxattr\",\n- 192: \"lgetxattr\",\n- 193: \"fgetxattr\",\n- 194: \"listxattr\",\n- 195: \"llistxattr\",\n- 196: \"flistxattr\",\n- 197: \"removexattr\",\n- 198: \"lremovexattr\",\n- 199: \"fremovexattr\",\n- 200: \"tkill\",\n- 201: \"time\",\n- 202: \"futex\",\n- 203: \"schedsetaffinity\",\n- 204: \"schedgetaffinity\",\n- 205: \"setthreadarea\",\n- 206: \"iosetup\",\n- 207: \"iodestroy\",\n- 208: \"iogetevents\",\n- 209: \"iosubmit\",\n- 210: \"iocancel\",\n- 211: \"getthreadarea\",\n- 212: \"lookupdcookie\",\n- 213: \"epollcreate\",\n- 214: \"epollctlold\",\n- 215: \"epollwaitold\",\n- 216: \"remapfilepages\",\n- 217: \"getdents64\",\n- 218: \"settidaddress\",\n- 219: \"restartsyscall\",\n- 220: \"semtimedop\",\n- 221: \"fadvise64\",\n- 222: \"timercreate\",\n- 223: \"timersettime\",\n- 224: \"timergettime\",\n- 225: \"timergetoverrun\",\n- 226: \"timerdelete\",\n- 227: \"clocksettime\",\n- 228: \"clockgettime\",\n- 229: \"clockgetres\",\n- 230: \"clocknanosleep\",\n- 231: \"exitgroup\",\n- 232: \"epollwait\",\n- 233: \"epollctl\",\n- 234: \"tgkill\",\n- 235: \"utimes\",\n- 236: \"vserver\",\n- 237: \"mbind\",\n- 238: \"setmempolicy\",\n- 239: \"getmempolicy\",\n- 240: \"mqopen\",\n- 241: \"mqunlink\",\n- 242: \"mqtimedsend\",\n- 243: \"mqtimedreceive\",\n- 244: \"mqnotify\",\n- 245: \"mqgetsetattr\",\n- 246: \"kexec_load\",\n- 247: \"waitid\",\n- 248: \"addkey\",\n- 249: \"requestkey\",\n- 250: \"keyctl\",\n- 251: \"ioprioset\",\n- 252: \"ioprioget\",\n- 253: \"inotifyinit\",\n- 254: \"inotifyaddwatch\",\n- 255: \"inotifyrmwatch\",\n- 256: \"migratepages\",\n- 257: \"openat\",\n- 258: \"mkdirat\",\n- 259: \"mknodat\",\n- 260: \"fchownat\",\n- 261: \"futimesat\",\n- 262: \"fstatat\",\n- 263: \"unlinkat\",\n- 264: \"renameat\",\n- 265: \"linkat\",\n- 266: \"symlinkat\",\n- 267: \"readlinkat\",\n- 268: \"fchmodat\",\n- 269: \"faccessat\",\n- 270: \"pselect\",\n- 271: \"ppoll\",\n- 272: \"unshare\",\n- 273: \"setrobustlist\",\n- 274: \"getrobustlist\",\n- 275: \"splice\",\n- 276: \"tee\",\n- 277: \"syncfilerange\",\n- 278: \"vmsplice\",\n- 279: \"movepages\",\n- 280: \"utimensat\",\n- 281: \"epollpwait\",\n- 282: \"signalfd\",\n- 283: \"timerfdcreate\",\n- 284: \"eventfd\",\n- 285: \"fallocate\",\n- 286: \"timerfdsettime\",\n- 287: \"timerfdgettime\",\n- 288: \"accept4\",\n- 289: \"signalfd4\",\n- 290: \"eventfd2\",\n- 291: \"epollcreate1\",\n- 292: \"dup3\",\n- 293: \"pipe2\",\n- 294: \"inotifyinit1\",\n- 295: \"preadv\",\n- 296: \"pwritev\",\n- 297: \"rttgsigqueueinfo\",\n- 298: \"perfeventopen\",\n- 299: \"recvmmsg\",\n- 300: \"fanotifyinit\",\n- 301: \"fanotifymark\",\n- 302: \"prlimit64\",\n- 303: \"nametohandleat\",\n- 304: \"openbyhandleat\",\n- 305: \"clockadjtime\",\n- 306: \"syncfs\",\n- 307: \"sendmmsg\",\n- 308: \"setns\",\n- 309: \"getcpu\",\n- 310: \"processvmreadv\",\n- 311: \"processvmwritev\",\n- 312: \"kcmp\",\n- 313: \"finitmodule\",\n- 314: \"schedsetattr\",\n- 315: \"schedgetattr\",\n- 316: \"renameat2\",\n- 317: \"seccomp\",\n- 318: \"getrandom\",\n- 319: \"memfdcreate\",\n- 320: \"kexecfileload\",\n- 321: \"bpf\",\n- 322: \"execveat\",\n- 323: \"userfaultfd\",\n- 324: \"membarrier\",\n- 325: \"mlock2\",\n- // syscalls after 325 are \"backports\" from versions of linux after 4.4.\n- 326: \"copyfilerange\",\n- 327: \"preadv2\",\n- 328: \"pwritev2\",\n-}\n" } ]
Go
Apache License 2.0
google/gvisor
Remove parse-syscall-annotations tool for now Some more work needs to be done for generating syscall compatibility reference documentation.
259,884
03.04.2019 02:10:26
14,400
95e9f1e2d83a630cb7fe280a6c971b97bb31f1b0
Update Kubernetes doc page Add info on RuntimeClass Add section headers to clearly show content organization
[ { "change_type": "MODIFY", "old_path": "content/docs/user_guide/kubernetes.md", "new_path": "content/docs/user_guide/kubernetes.md", "diff": "title = \"Kubernetes\"\nweight = 30\n+++\n-gVisor can run sandboxed containers in a Kubernetes cluster with Minikube. After\n-the gVisor addon is enabled, pods with `io.kubernetes.cri.untrusted-workload`\n-set to true will execute with `runsc`. Follow [these instructions][minikube] to\n-enable gVisor addon.\n+gVisor can be used to run Kubernetes pods and has several integration points\n+with Kubernetes.\n-You can also setup Kubernetes nodes to run pods in gvisor using the `containerd`\n-CRI runtime and the `gvisor-containerd-shim`. Pods with the\n-`io.kubernetes.cri.untrusted-workload` annotation will execute with `runsc`. You\n-can find instructions [here][gvisor-containerd-shim].\n+## Using Minikube\n+gVisor can run sandboxed containers in a Kubernetes cluster with Minikube.\n+After the gVisor addon is enabled, pods with\n+`io.kubernetes.cri.untrusted-workload` set to true will execute with `runsc`.\n+Follow [these instructions][minikube] to enable gVisor addon.\n+\n+## Using Containerd\n+\n+You can also setup Kubernetes nodes to run pods in gvisor using the\n+[containerd][containerd] CRI runtime and the `gvisor-containerd-shim`. You can\n+use either the `io.kubernetes.cri.untrusted-workload` annotation or\n+[RuntimeClass][runtimeclass] to run Pods with `runsc`. You can find\n+instructions [here][gvisor-containerd-shim].\n+\n+[containerd]: https://containerd.io/\n[minikube]: https://github.com/kubernetes/minikube/blob/master/deploy/addons/gvisor/README.md\n[gvisor-containerd-shim]: https://github.com/google/gvisor-containerd-shim\n+[runtimeclass]: https://kubernetes.io/docs/concepts/containers/runtime-class/\n" } ]
Go
Apache License 2.0
google/gvisor
Update Kubernetes doc page - Add info on RuntimeClass - Add section headers to clearly show content organization
259,884
03.04.2019 01:48:18
14,400
5f7f96b50bf797cac2fb40262c7b69f8ad7025f9
Add a /syscall redirect to compatibility docs /syscall -> /docs/user_guide/compatibility/amd64 /syscall/amd64 -> /docs/user_guide/compatibility/amd64 /syscall/amd64/.* -> /docs/user_guide/compatibility/amd64/#%s
[ { "change_type": "MODIFY", "old_path": "cmd/gvisor-website/main.go", "new_path": "cmd/gvisor-website/main.go", "diff": "@@ -30,17 +30,24 @@ var redirects = map[string]string{\n\"/cl\": \"https://gvisor-review.googlesource.com/\",\n\"/issue\": \"https://github.com/google/gvisor/issues\",\n\"/issue/new\": \"https://github.com/google/gvisor/issues/new\",\n+\n+ // Redirects to compatibility docs.\n+ \"/c\": \"/docs/user_guide/compatibility\",\n+ \"/c/linux/amd64\": \"/docs/user_guide/compatibility/amd64\",\n}\nvar prefixHelpers = map[string]string{\n\"cl\": \"https://gvisor-review.googlesource.com/c/gvisor/+/%s\",\n\"change\": \"https://gvisor.googlesource.com/gvisor/+/%s\",\n\"issue\": \"https://github.com/google/gvisor/issues/%s\",\n+\n+ // Redirects to compatibility docs.\n+ \"c/linux/amd64\": \"/docs/user_guide/compatibility/amd64/#%s\",\n}\nvar validId = regexp.MustCompile(`^[A-Za-z0-9-]*/?$`)\n-// redirectWithQuery redirects to the given target url preserving query parameters\n+// redirectWithQuery redirects to the given target url preserving query parameters.\nfunc redirectWithQuery(w http.ResponseWriter, r *http.Request, target string) {\nurl := target\nif qs := r.URL.RawQuery; qs != \"\" {\n@@ -53,7 +60,7 @@ func redirectWithQuery(w http.ResponseWriter, r *http.Request, target string) {\nfunc prefixRedirectHandler(prefix, baseURL string) http.Handler {\nreturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\nif p := r.URL.Path; p == prefix {\n- // redirect /prefix/ to /prefix\n+ // Redirect /prefix/ to /prefix.\nhttp.Redirect(w, r, p[:len(p)-1], http.StatusFound)\nreturn\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add a /syscall redirect to compatibility docs /syscall -> /docs/user_guide/compatibility/amd64 /syscall/amd64 -> /docs/user_guide/compatibility/amd64 /syscall/amd64/.* -> /docs/user_guide/compatibility/amd64/#%s
259,858
03.04.2019 00:14:55
25,200
6eb84a20ba51d9725f79a9b2b47e0de1af450667
Update lead text The text fully-virtualized may be taken to mean virtualized hardware, so drop that.
[ { "change_type": "MODIFY", "old_path": "content/_index.html", "new_path": "content/_index.html", "diff": "@@ -13,7 +13,7 @@ description = \"A container sandbox runtime focused on security, efficiency, and\n{{< /blocks/cover >}}\n{{% blocks/lead color=\"secondary\" %}}\n-gVisor is an open-source, <a href=\"https://www.opencontainers.org/\" target=\"_blank\" rel=\"noopener\">OCI-compatible</a> sandbox runtime that provides a fully-virtualized container environment. It runs containers with a new <a href=\"https://en.wikipedia.org/wiki/User_space\" target=\"_blank\" rel=\"noopener\">user-space</a> kernel, delivering a low overhead container security solution for low I/O, highly scaled applications.\n+gVisor is an open-source, <a href=\"https://www.opencontainers.org/\" target=\"_blank\" rel=\"noopener\">OCI-compatible</a> sandbox runtime that provides a virtualized container environment. It runs containers with a new <a href=\"https://en.wikipedia.org/wiki/User_space\" target=\"_blank\" rel=\"noopener\">user-space</a> kernel, delivering a low overhead container security solution for high-density applications.\ngVisor integrates with <a href=\"https://www.docker.com/\" target=\"_blank\" rel=\"noopener\">Docker</a>, <a href=\"https://containerd.io/\" target=\"_blank\" rel=\"noopener\">containerd</a> and <a href=\"https://kubernetes.io/\" target=\"_blank\" rel=\"noopener\">Kubernetes</a>, making it easier to improve the security isolation of your containers while still using familiar tooling. Additionally, gVisor supports a variety of underlying mechanisms for intercepting application calls, allowing it to run in diverse host environments, including cloud-hosted virtual machines.\n{{% /blocks/lead %}}\n" } ]
Go
Apache License 2.0
google/gvisor
Update lead text The text fully-virtualized may be taken to mean virtualized hardware, so drop that.
259,891
03.04.2019 11:48:33
25,200
c79e81bd27cd9cccddb0cece30bf47efbfca41b7
Addresses data race in tty implementation. Also makes the safemem reading and writing inline, as it makes it easier to see what locks are held.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/tty/queue.go", "new_path": "pkg/sentry/fs/tty/queue.go", "diff": "@@ -63,49 +63,6 @@ type queue struct {\ntransformer\n}\n-// ReadToBlocks implements safemem.Reader.ReadToBlocks.\n-func (q *queue) ReadToBlocks(dst safemem.BlockSeq) (uint64, error) {\n- src := safemem.BlockSeqOf(safemem.BlockFromSafeSlice(q.readBuf))\n- n, err := safemem.CopySeq(dst, src)\n- if err != nil {\n- return 0, err\n- }\n- q.readBuf = q.readBuf[n:]\n-\n- // If we read everything, this queue is no longer readable.\n- if len(q.readBuf) == 0 {\n- q.readable = false\n- }\n-\n- return n, nil\n-}\n-\n-// WriteFromBlocks implements safemem.Writer.WriteFromBlocks.\n-func (q *queue) WriteFromBlocks(src safemem.BlockSeq) (uint64, error) {\n- copyLen := src.NumBytes()\n- room := waitBufMaxBytes - q.waitBufLen\n- // If out of room, return EAGAIN.\n- if room == 0 && copyLen > 0 {\n- return 0, syserror.ErrWouldBlock\n- }\n- // Cap the size of the wait buffer.\n- if copyLen > room {\n- copyLen = room\n- src = src.TakeFirst64(room)\n- }\n- buf := make([]byte, copyLen)\n-\n- // Copy the data into the wait buffer.\n- dst := safemem.BlockSeqOf(safemem.BlockFromSafeSlice(buf))\n- n, err := safemem.CopySeq(dst, src)\n- if err != nil {\n- return 0, err\n- }\n- q.waitBufAppend(buf)\n-\n- return n, nil\n-}\n-\n// readReadiness returns whether q is ready to be read from.\nfunc (q *queue) readReadiness(t *linux.KernelTermios) waiter.EventMask {\nq.mu.Lock()\n@@ -118,6 +75,8 @@ func (q *queue) readReadiness(t *linux.KernelTermios) waiter.EventMask {\n// writeReadiness returns whether q is ready to be written to.\nfunc (q *queue) writeReadiness(t *linux.KernelTermios) waiter.EventMask {\n+ q.mu.Lock()\n+ defer q.mu.Unlock()\nif q.waitBufLen < waitBufMaxBytes {\nreturn waiter.EventOut\n}\n@@ -158,7 +117,21 @@ func (q *queue) read(ctx context.Context, dst usermem.IOSequence, l *lineDiscipl\ndst = dst.TakeFirst(canonMaxBytes)\n}\n- n, err := dst.CopyOutFrom(ctx, q)\n+ n, err := dst.CopyOutFrom(ctx, safemem.ReaderFunc(func(dst safemem.BlockSeq) (uint64, error) {\n+ src := safemem.BlockSeqOf(safemem.BlockFromSafeSlice(q.readBuf))\n+ n, err := safemem.CopySeq(dst, src)\n+ if err != nil {\n+ return 0, err\n+ }\n+ q.readBuf = q.readBuf[n:]\n+\n+ // If we read everything, this queue is no longer readable.\n+ if len(q.readBuf) == 0 {\n+ q.readable = false\n+ }\n+\n+ return n, nil\n+ }))\nif err != nil {\nreturn 0, false, err\n}\n@@ -178,7 +151,30 @@ func (q *queue) write(ctx context.Context, src usermem.IOSequence, l *lineDiscip\ndefer q.mu.Unlock()\n// Copy data into the wait buffer.\n- n, err := src.CopyInTo(ctx, q)\n+ n, err := src.CopyInTo(ctx, safemem.WriterFunc(func(src safemem.BlockSeq) (uint64, error) {\n+ copyLen := src.NumBytes()\n+ room := waitBufMaxBytes - q.waitBufLen\n+ // If out of room, return EAGAIN.\n+ if room == 0 && copyLen > 0 {\n+ return 0, syserror.ErrWouldBlock\n+ }\n+ // Cap the size of the wait buffer.\n+ if copyLen > room {\n+ copyLen = room\n+ src = src.TakeFirst64(room)\n+ }\n+ buf := make([]byte, copyLen)\n+\n+ // Copy the data into the wait buffer.\n+ dst := safemem.BlockSeqOf(safemem.BlockFromSafeSlice(buf))\n+ n, err := safemem.CopySeq(dst, src)\n+ if err != nil {\n+ return 0, err\n+ }\n+ q.waitBufAppend(buf)\n+\n+ return n, nil\n+ }))\nif err != nil {\nreturn 0, err\n}\n@@ -241,6 +237,7 @@ func (q *queue) pushWaitBufLocked(l *lineDiscipline) int {\nreturn total\n}\n+// Precondition: q.mu must be locked.\nfunc (q *queue) waitBufAppend(b []byte) {\nq.waitBuf = append(q.waitBuf, b)\nq.waitBufLen += uint64(len(b))\n" } ]
Go
Apache License 2.0
google/gvisor
Addresses data race in tty implementation. Also makes the safemem reading and writing inline, as it makes it easier to see what locks are held. PiperOrigin-RevId: 241775201 Change-Id: Ib1072f246773ef2d08b5b9a042eb7e9e0284175c
259,891
03.04.2019 11:09:07
25,200
51bfff9f74e3e25a05d070bae19b89aef2187643
Remove unnecessary curly braces around bash commands.
[ { "change_type": "MODIFY", "old_path": "content/docs/includes/install_gvisor.md", "new_path": "content/docs/includes/install_gvisor.md", "diff": "@@ -16,13 +16,11 @@ user `nobody` to avoid unnecessary privileges. The `/usr/local/bin` directory is\na good place to put the `runsc` binary.\n```bash\n-{\nwget https://storage.googleapis.com/gvisor/releases/nightly/latest/runsc\nwget https://storage.googleapis.com/gvisor/releases/nightly/latest/runsc.sha512\nsha512sum -c runsc.sha512\nchmod a+x runsc\nsudo mv runsc /usr/local/bin\n-}\n```\n[latest-nightly]: https://storage.googleapis.com/gvisor/releases/nightly/latest/runsc\n" }, { "change_type": "MODIFY", "old_path": "content/docs/user_guide/oci.md", "new_path": "content/docs/user_guide/oci.md", "diff": "@@ -15,20 +15,16 @@ Now we will create an [OCI][oci] container bundle to run our container. First we\nwill create a root directory for our bundle.\n```bash\n-{\nmkdir bundle\ncd bundle\n-}\n```\nCreate a root file system for the container. We will use the Docker hello-world\nimage as the basis for our container.\n```bash\n-{\nmkdir rootfs\ndocker export $(docker create hello-world) | tar -xf - -C rootfs\n-}\n```\nNext, create an specification file called `config.json` that contains our\n@@ -36,10 +32,8 @@ container specification. We will update the default command it runs to `/hello`\nin the `hello-world` container.\n```bash\n-{\nrunsc spec\nsed -i 's;\"sh\";\"/hello\";' config.json\n-}\n```\nFinally run the container.\n" } ]
Go
Apache License 2.0
google/gvisor
Remove unnecessary curly braces around bash commands.
259,884
03.04.2019 03:37:27
14,400
0fa5356531014baa82606c15fcc401cd5012ef84
Only deploy if in the gvisor-website project
[ { "change_type": "MODIFY", "old_path": "cloudbuild.yaml", "new_path": "cloudbuild.yaml", "diff": "@@ -24,5 +24,4 @@ steps:\nentrypoint: 'bash'\nargs:\n- '-c'\n- - |\n- [[ \"$BRANCH_NAME\" == \"master\" ]] && gcloud app deploy public/app.yaml || true\n+ - 'if [[ \"$PROJECT_ID\" == \"gvisor-website\" && \"$BRANCH_NAME\" == \"master\" ]]; then gcloud app deploy public/app.yaml; fi'\n" } ]
Go
Apache License 2.0
google/gvisor
Only deploy if in the gvisor-website project
259,854
03.04.2019 10:51:34
25,200
6592608d3ca9353ded2c18b92969760a24a8a727
Add required version to Docker user guide.
[ { "change_type": "MODIFY", "old_path": "content/docs/user_guide/docker.md", "new_path": "content/docs/user_guide/docker.md", "diff": "@@ -11,8 +11,8 @@ gVisor with the default platform.\n## Configuring Docker\n-> Note: This guide requires Docker. Refer to the [Docker documentation][docker] for\n-> how to install it.\n+> Note: This guide requires Docker version 17.09.0 or greater. Refer to the\n+> [Docker documentation][docker] for how to install it.\nFirst you will need to configure Docker to use `runsc` by adding a runtime\nentry to your Docker configuration (`/etc/docker/daemon.json`). You may have to\n" } ]
Go
Apache License 2.0
google/gvisor
Add required version to Docker user guide.
259,881
03.04.2019 18:05:30
25,200
9cf33960fc61309140a67587748570a36e78fc75
Only CopyOut CPU when it changes This will save copies when preemption is not caused by a CPU migration.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/rseq.go", "new_path": "pkg/sentry/kernel/rseq.go", "diff": "@@ -88,6 +88,7 @@ func (t *Task) RSEQCPUAddr() usermem.Addr {\nfunc (t *Task) SetRSEQCPUAddr(addr usermem.Addr) error {\nt.rseqCPUAddr = addr\nif addr != 0 {\n+ t.rseqCPU = int32(hostcpu.GetCPU())\nif err := t.rseqCopyOutCPU(); err != nil {\nt.rseqCPUAddr = 0\nt.rseqCPU = -1\n@@ -102,7 +103,6 @@ func (t *Task) SetRSEQCPUAddr(addr usermem.Addr) error {\n// Preconditions: The caller must be running on the task goroutine. t's\n// AddressSpace must be active.\nfunc (t *Task) rseqCopyOutCPU() error {\n- t.rseqCPU = int32(hostcpu.GetCPU())\nbuf := t.CopyScratchBuffer(4)\nusermem.ByteOrder.PutUint32(buf, uint32(t.rseqCPU))\n_, err := t.CopyOutBytes(t.rseqCPUAddr, buf)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_run.go", "new_path": "pkg/sentry/kernel/task_run.go", "diff": "@@ -21,6 +21,7 @@ import (\n\"gvisor.googlesource.com/gvisor/pkg/abi/linux\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/arch\"\n+ \"gvisor.googlesource.com/gvisor/pkg/sentry/hostcpu\"\nktime \"gvisor.googlesource.com/gvisor/pkg/sentry/kernel/time\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/memmap\"\n\"gvisor.googlesource.com/gvisor/pkg/sentry/platform\"\n@@ -169,6 +170,9 @@ func (*runApp) execute(t *Task) taskRunState {\nif t.rseqPreempted {\nt.rseqPreempted = false\nif t.rseqCPUAddr != 0 {\n+ cpu := int32(hostcpu.GetCPU())\n+ if t.rseqCPU != cpu {\n+ t.rseqCPU = cpu\nif err := t.rseqCopyOutCPU(); err != nil {\nt.Warningf(\"Failed to copy CPU to %#x for RSEQ: %v\", t.rseqCPUAddr, err)\nt.forceSignal(linux.SIGSEGV, false)\n@@ -177,6 +181,7 @@ func (*runApp) execute(t *Task) taskRunState {\nreturn (*runApp)(nil)\n}\n}\n+ }\nt.rseqInterrupt()\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Only CopyOut CPU when it changes This will save copies when preemption is not caused by a CPU migration. PiperOrigin-RevId: 241844399 Change-Id: I2ba3b64aa377846ab763425bd59b61158f576851
259,992
03.04.2019 09:13:14
25,200
8f8fc33a874b16d529dfacecdd6b34a42c98d514
Update install_gvisor.md
[ { "change_type": "MODIFY", "old_path": "content/docs/includes/install_gvisor.md", "new_path": "content/docs/includes/install_gvisor.md", "diff": "@@ -11,7 +11,7 @@ With corresponding SHA512 checksums here:\n`https://storage.googleapis.com/gvisor/releases/nightly/${yyyy-mm-dd}/runsc.sha512`\n**It is important to copy this binary to a location that is accessible to all\n-users, and make sure it is executable to all users**, since `runsc` executes itself\n+users, and ensure it is executable by all users**, since `runsc` executes itself\nas user `nobody` to avoid unnecessary privileges. The `/usr/local/bin` directory is\na good place to put the `runsc` binary.\n" } ]
Go
Apache License 2.0
google/gvisor
Update install_gvisor.md
259,858
04.04.2019 14:22:32
25,200
e9508967b0a1c9a8398adf5f6c28be79353f8a1f
Format workspace
[ { "change_type": "MODIFY", "old_path": "WORKSPACE", "new_path": "WORKSPACE", "diff": "# Load go bazel rules and gazelle.\nload(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n+\nhttp_archive(\nname = \"io_bazel_rules_go\",\n- url = \"https://github.com/bazelbuild/rules_go/releases/download/0.18.1/rules_go-0.18.1.tar.gz\",\nsha256 = \"77dfd303492f2634de7a660445ee2d3de2960cbd52f97d8c0dffa9362d3ddef9\",\n+ url = \"https://github.com/bazelbuild/rules_go/releases/download/0.18.1/rules_go-0.18.1.tar.gz\",\n)\n+\nhttp_archive(\nname = \"bazel_gazelle\",\n- url = \"https://github.com/bazelbuild/bazel-gazelle/releases/download/0.17.0/bazel-gazelle-0.17.0.tar.gz\",\nsha256 = \"3c681998538231a2d24d0c07ed5a7658cb72bfb5fd4bf9911157c0e9ac6a2687\",\n+ url = \"https://github.com/bazelbuild/bazel-gazelle/releases/download/0.17.0/bazel-gazelle-0.17.0.tar.gz\",\n)\nload(\"@io_bazel_rules_go//go:deps.bzl\", \"go_rules_dependencies\", \"go_register_toolchains\")\n+\ngo_rules_dependencies()\n+\ngo_register_toolchains(go_version = \"1.12.1\")\n+\nload(\"@bazel_gazelle//:deps.bzl\", \"gazelle_dependencies\", \"go_repository\")\n+\ngazelle_dependencies()\n# Load bazel_toolchain to support Remote Build Execution.\n@@ -32,86 +38,86 @@ http_archive(\n# External repositories, in sorted order.\ngo_repository(\nname = \"com_github_cenkalti_backoff\",\n- importpath = \"github.com/cenkalti/backoff\",\ncommit = \"66e726b43552c0bab0539b28e640b89fd6862115\",\n+ importpath = \"github.com/cenkalti/backoff\",\n)\ngo_repository(\nname = \"com_github_gofrs_flock\",\n+ commit = \"886344bea0798d02ff3fae16a922be5f6b26cee0\",\nimportpath = \"github.com/gofrs/flock\",\n- commit = \"886344bea0798d02ff3fae16a922be5f6b26cee0\"\n)\ngo_repository(\nname = \"com_github_golang_mock\",\n- importpath = \"github.com/golang/mock\",\ncommit = \"600781dde9cca80734169b9e969d9054ccc57937\",\n+ importpath = \"github.com/golang/mock\",\n)\ngo_repository(\nname = \"com_github_google_go-cmp\",\n- importpath = \"github.com/google/go-cmp\",\ncommit = \"3af367b6b30c263d47e8895973edcca9a49cf029\",\n+ importpath = \"github.com/google/go-cmp\",\n)\ngo_repository(\nname = \"com_github_google_subcommands\",\n- importpath = \"github.com/google/subcommands\",\ncommit = \"ce3d4cfc062faac7115d44e5befec8b5a08c3faa\",\n+ importpath = \"github.com/google/subcommands\",\n)\ngo_repository(\nname = \"com_github_google_uuid\",\n- importpath = \"github.com/google/uuid\",\ncommit = \"dec09d789f3dba190787f8b4454c7d3c936fed9e\",\n+ importpath = \"github.com/google/uuid\",\n)\ngo_repository(\nname = \"com_github_kr_pty\",\n- importpath = \"github.com/kr/pty\",\ncommit = \"282ce0e5322c82529687d609ee670fac7c7d917c\",\n+ importpath = \"github.com/kr/pty\",\n)\ngo_repository(\nname = \"com_github_opencontainers_runtime-spec\",\n- importpath = \"github.com/opencontainers/runtime-spec\",\ncommit = \"b2d941ef6a780da2d9982c1fb28d77ad97f54fc7\",\n+ importpath = \"github.com/opencontainers/runtime-spec\",\n)\ngo_repository(\nname = \"com_github_syndtr_gocapability\",\n- importpath = \"github.com/syndtr/gocapability\",\ncommit = \"d98352740cb2c55f81556b63d4a1ec64c5a319c2\",\n+ importpath = \"github.com/syndtr/gocapability\",\n)\ngo_repository(\nname = \"com_github_vishvananda_netlink\",\n- importpath = \"github.com/vishvananda/netlink\",\ncommit = \"adb577d4a45e341da53c4d9196ad4222c9a23e69\",\n+ importpath = \"github.com/vishvananda/netlink\",\n)\ngo_repository(\nname = \"com_github_vishvananda_netns\",\n- importpath = \"github.com/vishvananda/netns\",\ncommit = \"be1fbeda19366dea804f00efff2dd73a1642fdcc\",\n+ importpath = \"github.com/vishvananda/netns\",\n)\ngo_repository(\nname = \"org_golang_x_net\",\n- importpath = \"golang.org/x/net\",\ncommit = \"b3c676e531a6dc479fa1b35ac961c13f5e2b4d2e\",\n+ importpath = \"golang.org/x/net\",\n)\ngo_repository(\nname = \"org_golang_x_sys\",\n- importpath = \"golang.org/x/sys\",\ncommit = \"0dd5e194bbf5eb84a39666eb4c98a4d007e4203a\",\n+ importpath = \"golang.org/x/sys\",\n)\ngo_repository(\nname = \"com_github_google_btree\",\n- importpath = \"github.com/google/btree\",\ncommit = \"4030bb1f1f0c35b30ca7009e9ebd06849dd45306\",\n+ importpath = \"github.com/google/btree\",\n)\n# System Call test dependencies.\n" } ]
Go
Apache License 2.0
google/gvisor
Format workspace Change-Id: Ibb77656c46942eb123cd6cff8b471a526468d2dd PiperOrigin-RevId: 242007583
259,858
04.04.2019 17:04:30
25,200
75c8ac38e0f6cc4eb3726c89aee41357cd592c4b
BUILD: Add useful go_path target
[ { "change_type": "MODIFY", "old_path": "BUILD", "new_path": "BUILD", "diff": "+package(licenses = [\"notice\"]) # Apache 2.0\n+\n+load(\"@io_bazel_rules_go//go:def.bzl\", \"go_path\")\n+\n# The sandbox filegroup is used for sandbox-internal dependencies.\npackage_group(\nname = \"sandbox\",\n@@ -5,3 +9,16 @@ package_group(\n\"//...\",\n],\n)\n+\n+# gopath defines a directory that is structured in a way that is compatible\n+# with standard Go tools. Things like godoc, editors and refactor tools should\n+# work as expected.\n+#\n+# The files in this tree are symlinks to the true sources.\n+go_path(\n+ name = \"gopath\",\n+ mode = \"link\",\n+ deps = [\n+ \"//runsc\",\n+ ],\n+)\n" }, { "change_type": "MODIFY", "old_path": "CONTRIBUTING.md", "new_path": "CONTRIBUTING.md", "diff": "@@ -12,6 +12,24 @@ You generally only need to submit a CLA once, so if you've already submitted one\n(even if it was for a different project), you probably don't need to do it\nagain.\n+### Using GOPATH\n+\n+Some editors may require the code to be structured in a `GOPATH` directory tree.\n+In this case, you may use the `:gopath` target to generate a directory tree with\n+symlinks to the original source files.\n+\n+```\n+bazel build :gopath\n+```\n+\n+You can then set the `GOPATH` in your editor to `bazel-bin/gopath`.\n+\n+If you use this mechanism, keep in mind that the generated tree is not the\n+canonical source. You will still need to build and test with `bazel`. New files\n+will need to be added to the appropriate `BUILD` files, and the `:gopath` target\n+will need to be re-run to generate appropriate symlinks in the `GOPATH`\n+directory tree.\n+\n### Coding Guidelines\nAll code should conform to the [Go style guidelines][gostyle].\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_utsname.go", "new_path": "pkg/sentry/syscalls/linux/sys_utsname.go", "diff": "@@ -35,7 +35,7 @@ func Uname(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\ncopy(u.Nodename[:], uts.HostName())\ncopy(u.Release[:], version.Release)\ncopy(u.Version[:], version.Version)\n- copy(u.Machine[:], \"x86_64\") // +build tag above.\n+ copy(u.Machine[:], \"x86_64\") // build tag above.\ncopy(u.Domainname[:], uts.DomainName())\n// Copy out the result.\n" } ]
Go
Apache License 2.0
google/gvisor
BUILD: Add useful go_path target Change-Id: Ibd6d8a1a63826af6e62a0f0669f8f0866c8091b4 PiperOrigin-RevId: 242037969
259,881
04.04.2019 17:13:31
25,200
75a5ccf5d98876c26305da0feff20e4a148027ec
Remove defer from trivial ThreadID methods In particular, ns.IDOfTask and tg.ID are used for gettid and getpid, respectively, where removing defer saves ~100ns. This may be a small improvement to application logging, which may call gettid/getpid frequently.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/threads.go", "new_path": "pkg/sentry/kernel/threads.go", "diff": "@@ -196,8 +196,9 @@ func (ns *PIDNamespace) NewChild(userns *auth.UserNamespace) *PIDNamespace {\n// task has that TID, TaskWithID returns nil.\nfunc (ns *PIDNamespace) TaskWithID(tid ThreadID) *Task {\nns.owner.mu.RLock()\n- defer ns.owner.mu.RUnlock()\n- return ns.tasks[tid]\n+ t := ns.tasks[tid]\n+ ns.owner.mu.RUnlock()\n+ return t\n}\n// ThreadGroupWithID returns the thread group lead by the task with thread ID\n@@ -224,16 +225,18 @@ func (ns *PIDNamespace) ThreadGroupWithID(tid ThreadID) *ThreadGroup {\n// 0.\nfunc (ns *PIDNamespace) IDOfTask(t *Task) ThreadID {\nns.owner.mu.RLock()\n- defer ns.owner.mu.RUnlock()\n- return ns.tids[t]\n+ id := ns.tids[t]\n+ ns.owner.mu.RUnlock()\n+ return id\n}\n// IDOfThreadGroup returns the TID assigned to tg's leader in PID namespace ns.\n// If the task is not visible in that namespace, IDOfThreadGroup returns 0.\nfunc (ns *PIDNamespace) IDOfThreadGroup(tg *ThreadGroup) ThreadID {\nns.owner.mu.RLock()\n- defer ns.owner.mu.RUnlock()\n- return ns.tgids[tg]\n+ id := ns.tgids[tg]\n+ ns.owner.mu.RUnlock()\n+ return id\n}\n// Tasks returns a snapshot of the tasks in ns.\n@@ -390,8 +393,9 @@ func (tg *ThreadGroup) MemberIDs(pidns *PIDNamespace) []ThreadID {\n// is dead, ID returns 0.\nfunc (tg *ThreadGroup) ID() ThreadID {\ntg.pidns.owner.mu.RLock()\n- defer tg.pidns.owner.mu.RUnlock()\n- return tg.pidns.tgids[tg]\n+ id := tg.pidns.tgids[tg]\n+ tg.pidns.owner.mu.RUnlock()\n+ return id\n}\n// A taskNode defines the relationship between a task and the rest of the\n" } ]
Go
Apache License 2.0
google/gvisor
Remove defer from trivial ThreadID methods In particular, ns.IDOfTask and tg.ID are used for gettid and getpid, respectively, where removing defer saves ~100ns. This may be a small improvement to application logging, which may call gettid/getpid frequently. PiperOrigin-RevId: 242039616 Change-Id: I860beb62db3fe077519835e6bafa7c74cba6ca80
259,853
04.04.2019 17:42:51
25,200
88409e983c463b6d9c8085e7fdbe7ff45b3c5184
gvisor: Add support for the MS_NOEXEC mount option
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/context.go", "new_path": "pkg/sentry/fs/context.go", "diff": "@@ -46,6 +46,11 @@ func ContextCanAccessFile(ctx context.Context, inode *Inode, reqPerms PermMask)\np = uattr.Perms.Group\n}\n+ // Do not allow programs to be executed if MS_NOEXEC is set.\n+ if IsFile(inode.StableAttr) && reqPerms.Execute && inode.MountSource.Flags.NoExec {\n+ return false\n+ }\n+\n// Are permissions satisfied without capability checks?\nif p.SupersetOf(reqPerms) {\nreturn true\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/filesystems.go", "new_path": "pkg/sentry/fs/filesystems.go", "diff": "@@ -140,6 +140,10 @@ type MountSourceFlags struct {\n// cache, even when the platform supports direct mapped I/O. This\n// doesn't correspond to any Linux mount options.\nForcePageCache bool\n+\n+ // NoExec corresponds to mount(2)'s \"MS_NOEXEC\" and indicates that\n+ // binaries from this file system can't be executed.\n+ NoExec bool\n}\n// GenericMountSourceOptions splits a string containing comma separated tokens of the\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/proc/mounts.go", "new_path": "pkg/sentry/fs/proc/mounts.go", "diff": "@@ -129,6 +129,9 @@ func (mif *mountInfoFile) ReadSeqFileData(ctx context.Context, handle seqfile.Se\nif m.Flags.NoAtime {\nopts += \",noatime\"\n}\n+ if m.Flags.NoExec {\n+ opts += \",noexec\"\n+ }\nfmt.Fprintf(&buf, \"%s \", opts)\n// (7) Optional fields: zero or more fields of the form \"tag[:value]\".\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_mount.go", "new_path": "pkg/sentry/syscalls/linux/sys_mount.go", "diff": "@@ -75,7 +75,7 @@ func Mount(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\n// Silently allow MS_NOSUID, since we don't implement set-id bits\n// anyway.\n- const unsupportedFlags = linux.MS_NODEV | linux.MS_NOEXEC |\n+ const unsupportedFlags = linux.MS_NODEV |\nlinux.MS_NODIRATIME | linux.MS_STRICTATIME\n// Linux just allows passing any flags to mount(2) - it won't fail when\n@@ -100,6 +100,9 @@ func Mount(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\nif flags&linux.MS_RDONLY == linux.MS_RDONLY {\nsuperFlags.ReadOnly = true\n}\n+ if flags&linux.MS_NOEXEC == linux.MS_NOEXEC {\n+ superFlags.NoExec = true\n+ }\nrootInode, err := rsys.Mount(t, sourcePath, superFlags, data, nil)\nif err != nil {\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/fs.go", "new_path": "runsc/boot/fs.go", "diff": "@@ -482,6 +482,8 @@ func mountFlags(opts []string) fs.MountSourceFlags {\nmf.ReadOnly = true\ncase \"noatime\":\nmf.NoAtime = true\n+ case \"noexec\":\n+ mf.NoExec = true\ndefault:\nlog.Warningf(\"ignoring unknown mount option %q\", o)\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/specutils/fs.go", "new_path": "runsc/specutils/fs.go", "diff": "@@ -39,6 +39,7 @@ var optionsMap = map[string]mapping{\n\"diratime\": {set: false, val: syscall.MS_NODIRATIME},\n\"dirsync\": {set: true, val: syscall.MS_DIRSYNC},\n\"exec\": {set: false, val: syscall.MS_NOEXEC},\n+ \"noexec\": {set: true, val: syscall.MS_NOEXEC},\n\"iversion\": {set: true, val: syscall.MS_I_VERSION},\n\"loud\": {set: false, val: syscall.MS_SILENT},\n\"mand\": {set: true, val: syscall.MS_MANDLOCK},\n@@ -76,9 +77,7 @@ var propOptionsMap = map[string]mapping{\n// invalidOptions list options not allowed.\n// - shared: sandbox must be isolated from the host. Propagating mount changes\n// from the sandbox to the host breaks the isolation.\n-// - noexec: not yet supported. Don't ignore it since it could break\n-// in-sandbox security.\n-var invalidOptions = []string{\"shared\", \"rshared\", \"noexec\"}\n+var invalidOptions = []string{\"shared\", \"rshared\"}\n// OptionsToFlags converts mount options to syscall flags.\nfunc OptionsToFlags(opts []string) uint32 {\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -1080,6 +1080,7 @@ cc_binary(\n\"//test/util:file_descriptor\",\n\"//test/util:fs_util\",\n\"//test/util:mount_util\",\n+ \"//test/util:multiprocess_util\",\n\"//test/util:posix_error\",\n\"//test/util:temp_path\",\n\"//test/util:test_main\",\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/mount.cc", "new_path": "test/syscalls/linux/mount.cc", "diff": "#include \"test/util/file_descriptor.h\"\n#include \"test/util/fs_util.h\"\n#include \"test/util/mount_util.h\"\n+#include \"test/util/multiprocess_util.h\"\n#include \"test/util/posix_error.h\"\n#include \"test/util/temp_path.h\"\n#include \"test/util/test_util.h\"\n@@ -277,6 +278,23 @@ TEST(MountTest, MountNoAtime) {\nEXPECT_EQ(before, after);\n}\n+TEST(MountTest, MountNoExec) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN)));\n+\n+ auto const dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ auto const mount = ASSERT_NO_ERRNO_AND_VALUE(\n+ Mount(\"\", dir.path(), \"tmpfs\", MS_NOEXEC, \"mode=0777\", 0));\n+\n+ std::string const contents = \"No no no, don't follow the instructions!\";\n+ auto const file = ASSERT_NO_ERRNO_AND_VALUE(\n+ TempPath::CreateFileWith(dir.path(), contents, 0777));\n+\n+ int execve_errno;\n+ ASSERT_NO_ERRNO_AND_VALUE(\n+ ForkAndExec(file.path(), {}, {}, nullptr, &execve_errno));\n+ EXPECT_EQ(execve_errno, EACCES);\n+}\n+\nTEST(MountTest, RenameRemoveMountPoint) {\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN)));\n" } ]
Go
Apache License 2.0
google/gvisor
gvisor: Add support for the MS_NOEXEC mount option https://github.com/google/gvisor/issues/145 PiperOrigin-RevId: 242044115 Change-Id: I8f140fe05e32ecd438b6be218e224e4b7fe05878