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,966 | 04.04.2022 10:46:16 | 25,200 | 47fbf57a832139af24d3caa485ec531ad33a23b1 | Add option to enable multicast forwarding
Setting this newly added option to "true" will currently be a no-op. Full
support for multicast routing will be added in subsequent CLs.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4.go",
"diff": "@@ -72,6 +72,7 @@ var ipv4BroadcastAddr = header.IPv4Broadcast.WithPrefix()\nvar _ stack.LinkResolvableNetworkEndpoint = (*endpoint)(nil)\nvar _ stack.ForwardingNetworkEndpoint = (*endpoint)(nil)\n+var _ stack.MulticastForwardingNetworkEndpoint = (*endpoint)(nil)\nvar _ stack.GroupAddressableEndpoint = (*endpoint)(nil)\nvar _ stack.AddressableEndpoint = (*endpoint)(nil)\nvar _ stack.NetworkEndpoint = (*endpoint)(nil)\n@@ -94,6 +95,15 @@ type endpoint struct {\n// +checkatomic\nforwarding uint32\n+ // multicastForwarding is set to forwardingEnabled when the endpoint has\n+ // forwarding enabled and forwardingDisabled when it is disabled.\n+ //\n+ // TODO(https://gvisor.dev/issue/7338): Implement support for multicast\n+ //forwarding. Currently, setting this value to true is a no-op.\n+ //\n+ // +checkatomic\n+ multicastForwarding uint32\n+\n// mu protects below.\nmu sync.RWMutex\n@@ -236,6 +246,24 @@ func (e *endpoint) SetForwarding(forwarding bool) bool {\nreturn prevForwarding\n}\n+// MulticastForwarding implements stack.MulticastForwardingNetworkEndpoint.\n+func (e *endpoint) MulticastForwarding() bool {\n+ return atomic.LoadUint32(&e.multicastForwarding) == forwardingEnabled\n+}\n+\n+// SetMulticastForwarding implements stack.MulticastForwardingNetworkEndpoint.\n+func (e *endpoint) SetMulticastForwarding(forwarding bool) bool {\n+ e.mu.Lock()\n+ defer e.mu.Unlock()\n+\n+ updatedForwarding := uint32(forwardingDisabled)\n+ if forwarding {\n+ updatedForwarding = forwardingEnabled\n+ }\n+\n+ return atomic.SwapUint32(&e.multicastForwarding, updatedForwarding) != forwardingDisabled\n+}\n+\n// Enable implements stack.NetworkEndpoint.\nfunc (e *endpoint) Enable() tcpip.Error {\ne.mu.Lock()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6.go",
"diff": "@@ -174,6 +174,7 @@ var _ stack.DuplicateAddressDetector = (*endpoint)(nil)\nvar _ stack.LinkAddressResolver = (*endpoint)(nil)\nvar _ stack.LinkResolvableNetworkEndpoint = (*endpoint)(nil)\nvar _ stack.ForwardingNetworkEndpoint = (*endpoint)(nil)\n+var _ stack.MulticastForwardingNetworkEndpoint = (*endpoint)(nil)\nvar _ stack.GroupAddressableEndpoint = (*endpoint)(nil)\nvar _ stack.AddressableEndpoint = (*endpoint)(nil)\nvar _ stack.NetworkEndpoint = (*endpoint)(nil)\n@@ -198,6 +199,15 @@ type endpoint struct {\n// Must be accessed using atomic operations.\nforwarding uint32\n+ // multicastForwarding is set to forwardingEnabled when the endpoint has\n+ // forwarding enabled and forwardingDisabled when it is disabled.\n+ //\n+ // TODO(https://gvisor.dev/issue/7338): Implement support for multicast\n+ // forwarding. Currently, setting this value to true is a no-op.\n+ //\n+ // Must be accessed using atomic operations.\n+ multicastForwarding uint32\n+\nmu struct {\nsync.RWMutex\n@@ -505,6 +515,24 @@ func (e *endpoint) SetForwarding(forwarding bool) bool {\nreturn prevForwarding\n}\n+// MulticastForwarding implements stack.MulticastForwardingNetworkEndpoint.\n+func (e *endpoint) MulticastForwarding() bool {\n+ return atomic.LoadUint32(&e.multicastForwarding) == forwardingEnabled\n+}\n+\n+// SetMulticastForwarding implements stack.MulticastForwardingNetworkEndpoint.\n+func (e *endpoint) SetMulticastForwarding(forwarding bool) bool {\n+ e.mu.Lock()\n+ defer e.mu.Unlock()\n+\n+ updatedForwarding := uint32(forwardingDisabled)\n+ if forwarding {\n+ updatedForwarding = forwardingEnabled\n+ }\n+\n+ return atomic.SwapUint32(&e.multicastForwarding, updatedForwarding) != forwardingDisabled\n+}\n+\n// Enable implements stack.NetworkEndpoint.\nfunc (e *endpoint) Enable() tcpip.Error {\ne.mu.Lock()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic.go",
"new_path": "pkg/tcpip/stack/nic.go",
"diff": "@@ -1040,3 +1040,35 @@ func (n *nic) forwarding(protocol tcpip.NetworkProtocolNumber) (bool, tcpip.Erro\nreturn forwardingEP.Forwarding(), nil\n}\n+\n+func (n *nic) multicastForwardingEndpoint(protocol tcpip.NetworkProtocolNumber) (MulticastForwardingNetworkEndpoint, tcpip.Error) {\n+ ep := n.getNetworkEndpoint(protocol)\n+ if ep == nil {\n+ return nil, &tcpip.ErrUnknownProtocol{}\n+ }\n+\n+ forwardingEP, ok := ep.(MulticastForwardingNetworkEndpoint)\n+ if !ok {\n+ return nil, &tcpip.ErrNotSupported{}\n+ }\n+\n+ return forwardingEP, nil\n+}\n+\n+func (n *nic) setMulticastForwarding(protocol tcpip.NetworkProtocolNumber, enable bool) (bool, tcpip.Error) {\n+ ep, err := n.multicastForwardingEndpoint(protocol)\n+ if err != nil {\n+ return false, err\n+ }\n+\n+ return ep.SetMulticastForwarding(enable), nil\n+}\n+\n+func (n *nic) multicastForwarding(protocol tcpip.NetworkProtocolNumber) (bool, tcpip.Error) {\n+ ep, err := n.multicastForwardingEndpoint(protocol)\n+ if err != nil {\n+ return false, err\n+ }\n+\n+ return ep.MulticastForwarding(), nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/registration.go",
"new_path": "pkg/tcpip/stack/registration.go",
"diff": "@@ -691,6 +691,21 @@ type ForwardingNetworkEndpoint interface {\nSetForwarding(bool) bool\n}\n+// MulticastForwardingNetworkEndpoint is a network endpoint that may forward\n+// multicast packets.\n+type MulticastForwardingNetworkEndpoint interface {\n+ ForwardingNetworkEndpoint\n+\n+ // MulticastForwarding returns true if multicast forwarding is enabled.\n+ // Otherwise, returns false.\n+ MulticastForwarding() bool\n+\n+ // SetMulticastForwarding sets the multicast forwarding configuration.\n+ //\n+ // Returns the previous forwarding configuration.\n+ SetMulticastForwarding(bool) bool\n+}\n+\n// NetworkProtocol is the interface that needs to be implemented by network\n// protocols (e.g., ipv4, ipv6) that want to be part of the networking stack.\ntype NetworkProtocol interface {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -563,6 +563,40 @@ func (s *Stack) SetForwardingDefaultAndAllNICs(protocol tcpip.NetworkProtocolNum\nreturn nil\n}\n+// SetNICMulticastForwarding enables or disables multicast packet forwarding on\n+// the specified NIC for the passed protocol.\n+//\n+// Returns the previous configuration on the NIC.\n+//\n+// TODO(https://gvisor.dev/issue/7338): Implement support for multicast\n+// forwarding. Currently, setting this value is a no-op and is not ready for\n+// use.\n+func (s *Stack) SetNICMulticastForwarding(id tcpip.NICID, protocol tcpip.NetworkProtocolNumber, enable bool) (bool, tcpip.Error) {\n+ s.mu.RLock()\n+ defer s.mu.RUnlock()\n+\n+ nic, ok := s.nics[id]\n+ if !ok {\n+ return false, &tcpip.ErrUnknownNICID{}\n+ }\n+\n+ return nic.setMulticastForwarding(protocol, enable)\n+}\n+\n+// NICMulticastForwarding returns the multicast forwarding configuration for\n+// the specified NIC.\n+func (s *Stack) NICMulticastForwarding(id tcpip.NICID, protocol tcpip.NetworkProtocolNumber) (bool, tcpip.Error) {\n+ s.mu.RLock()\n+ defer s.mu.RUnlock()\n+\n+ nic, ok := s.nics[id]\n+ if !ok {\n+ return false, &tcpip.ErrUnknownNICID{}\n+ }\n+\n+ return nic.multicastForwarding(protocol)\n+}\n+\n// PortRange returns the UDP and TCP inclusive range of ephemeral ports used in\n// both IPv4 and IPv6.\nfunc (s *Stack) PortRange() (uint16, uint16) {\n@@ -843,6 +877,10 @@ type NICInfo struct {\n// Forwarding holds the forwarding status for each network endpoint that\n// supports forwarding.\nForwarding map[tcpip.NetworkProtocolNumber]bool\n+\n+ // MulticastForwarding holds the forwarding status for each network endpoint\n+ // that supports multicast forwarding.\n+ MulticastForwarding map[tcpip.NetworkProtocolNumber]bool\n}\n// HasNIC returns true if the NICID is defined in the stack.\n@@ -858,6 +896,21 @@ func (s *Stack) NICInfo() map[tcpip.NICID]NICInfo {\ns.mu.RLock()\ndefer s.mu.RUnlock()\n+ type forwardingFn func(tcpip.NetworkProtocolNumber) (bool, tcpip.Error)\n+ forwardingValue := func(forwardingFn forwardingFn, proto tcpip.NetworkProtocolNumber, nicID tcpip.NICID, fnName string) (forward bool, ok bool) {\n+ switch forwarding, err := forwardingFn(proto); err.(type) {\n+ case nil:\n+ return forwarding, true\n+ case *tcpip.ErrUnknownProtocol:\n+ panic(fmt.Sprintf(\"expected network protocol %d to be available on NIC %d\", proto, nicID))\n+ case *tcpip.ErrNotSupported:\n+ // Not all network protocols support forwarding.\n+ default:\n+ panic(fmt.Sprintf(\"nic(id=%d).%s(%d): %s\", nicID, fnName, proto, err))\n+ }\n+ return false, false\n+ }\n+\nnics := make(map[tcpip.NICID]NICInfo)\nfor id, nic := range s.nics {\nflags := NICStateFlags{\n@@ -883,18 +936,16 @@ func (s *Stack) NICInfo() map[tcpip.NICID]NICInfo {\nContext: nic.context,\nARPHardwareType: nic.NetworkLinkEndpoint.ARPHardwareType(),\nForwarding: make(map[tcpip.NetworkProtocolNumber]bool),\n+ MulticastForwarding: make(map[tcpip.NetworkProtocolNumber]bool),\n}\nfor proto := range s.networkProtocols {\n- switch forwarding, err := nic.forwarding(proto); err.(type) {\n- case nil:\n+ if forwarding, ok := forwardingValue(nic.forwarding, proto, id, \"forwarding\"); ok {\ninfo.Forwarding[proto] = forwarding\n- case *tcpip.ErrUnknownProtocol:\n- panic(fmt.Sprintf(\"expected network protocol %d to be available on NIC %d\", proto, nic.ID()))\n- case *tcpip.ErrNotSupported:\n- // Not all network protocols support forwarding.\n- default:\n- panic(fmt.Sprintf(\"nic(id=%d).forwarding(%d): %s\", nic.ID(), proto, err))\n+ }\n+\n+ if multicastForwarding, ok := forwardingValue(nic.multicastForwarding, proto, id, \"multicastForwarding\"); ok {\n+ info.MulticastForwarding[proto] = multicastForwarding\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack_test.go",
"new_path": "pkg/tcpip/stack/stack_test.go",
"diff": "@@ -86,6 +86,7 @@ type fakeNetworkEndpoint struct {\nenabled bool\nforwarding bool\n+ multicastForwarding bool\n}\nnic stack.NetworkInterface\n@@ -313,6 +314,22 @@ func (f *fakeNetworkEndpoint) SetForwarding(v bool) bool {\nreturn prev\n}\n+// MulticastForwarding implements stack.MulticastForwardingNetworkEndpoint.\n+func (f *fakeNetworkEndpoint) MulticastForwarding() bool {\n+ f.mu.RLock()\n+ defer f.mu.RUnlock()\n+ return f.mu.multicastForwarding\n+}\n+\n+// SetMulticastForwarding implements stack.MulticastForwardingNetworkEndpoint.\n+func (f *fakeNetworkEndpoint) SetMulticastForwarding(v bool) bool {\n+ f.mu.Lock()\n+ defer f.mu.Unlock()\n+ prev := f.mu.multicastForwarding\n+ f.mu.multicastForwarding = v\n+ return prev\n+}\n+\nfunc fakeNetFactory(s *stack.Stack) stack.NetworkProtocol {\nreturn &fakeNetworkProtocol{stack: s}\n}\n@@ -4670,8 +4687,39 @@ func TestNICForwarding(t *testing.T) {\n},\n}\n+ subTests := []struct {\n+ name string\n+ getForwardingFunc func(*stack.Stack, tcpip.NICID, tcpip.NetworkProtocolNumber) (bool, tcpip.Error)\n+ getForwardingFuncName string\n+ setForwardingFunc func(*stack.Stack, tcpip.NICID, tcpip.NetworkProtocolNumber, bool) (bool, tcpip.Error)\n+ setForwardingFuncName string\n+ getNicInfoForwardingMap func(stack.NICInfo) map[tcpip.NetworkProtocolNumber]bool\n+ nicInfoForwardingMapName string\n+ }{\n+ {\n+ name: \"unicast\",\n+ getForwardingFunc: (*stack.Stack).NICForwarding,\n+ getForwardingFuncName: \"NICForwarding\",\n+ setForwardingFunc: (*stack.Stack).SetNICForwarding,\n+ setForwardingFuncName: \"SetNICForwarding\",\n+ getNicInfoForwardingMap: func(info stack.NICInfo) map[tcpip.NetworkProtocolNumber]bool { return info.Forwarding },\n+ nicInfoForwardingMapName: \"Forwarding\",\n+ },\n+ {\n+ name: \"multicast\",\n+ getForwardingFunc: (*stack.Stack).NICMulticastForwarding,\n+ getForwardingFuncName: \"NICMulticastForwarding\",\n+ setForwardingFunc: (*stack.Stack).SetNICMulticastForwarding,\n+ setForwardingFuncName: \"SetNICMulticastForwarding\",\n+ getNicInfoForwardingMap: func(info stack.NICInfo) map[tcpip.NetworkProtocolNumber]bool { return info.MulticastForwarding },\n+ nicInfoForwardingMapName: \"MulticastForwarding\",\n+ },\n+ }\n+\nfor _, test := range tests {\nt.Run(test.name, func(t *testing.T) {\n+ for _, subTest := range subTests {\n+ t.Run(subTest.name, func(t *testing.T) {\ns := stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocolFactory{test.factory},\n})\n@@ -4680,40 +4728,69 @@ func TestNICForwarding(t *testing.T) {\n}\n// Forwarding should initially be disabled.\n- if forwarding, err := s.NICForwarding(nicID, test.netProto); err != nil {\n- t.Fatalf(\"s.NICForwarding(%d, %d): %s\", nicID, test.netProto, err)\n+ if forwarding, err := subTest.getForwardingFunc(s, nicID, test.netProto); err != nil {\n+ t.Fatalf(\"s.%s(%d, %d): %s\", subTest.getForwardingFuncName, nicID, test.netProto, err)\n} else if forwarding {\n- t.Errorf(\"got s.NICForwarding(%d, %d) = true, want = false\", nicID, test.netProto)\n+ t.Errorf(\"got s.%s(%d, %d) = true, want = false\", subTest.getForwardingFuncName, nicID, test.netProto)\n}\n// Setting forwarding to be enabled should return the previous\n- // configuration of false. Enabling it a second time should be a no-op.\n+ // configuration of false. Enabling it a second time should be a\n+ // no-op.\nfor _, wantPrevForwarding := range [...]bool{false, true} {\n- if prevForwarding, err := s.SetNICForwarding(nicID, test.netProto, true); err != nil {\n- t.Fatalf(\"s.SetNICForwarding(%d, %d, true): %s\", nicID, test.netProto, err)\n+ if prevForwarding, err := subTest.setForwardingFunc(s, nicID, test.netProto, true); err != nil {\n+ t.Fatalf(\"s.%s(%d, %d, true): %s\", subTest.setForwardingFuncName, nicID, test.netProto, err)\n} else if prevForwarding != wantPrevForwarding {\n- t.Errorf(\"got s.SetNICForwarding(%d, %d, true) = %t, want = %t\", nicID, test.netProto, prevForwarding, wantPrevForwarding)\n+ t.Errorf(\"got s.%s(%d, %d, true) = %t, want = %t\", subTest.setForwardingFuncName, nicID, test.netProto, prevForwarding, wantPrevForwarding)\n}\n- if forwarding, err := s.NICForwarding(nicID, test.netProto); err != nil {\n- t.Fatalf(\"s.NICForwarding(%d, %d): %s\", nicID, test.netProto, err)\n+ if forwarding, err := subTest.getForwardingFunc(s, nicID, test.netProto); err != nil {\n+ t.Fatalf(\"s.%s(%d, %d): %s\", subTest.getForwardingFuncName, nicID, test.netProto, err)\n} else if !forwarding {\n- t.Errorf(\"got s.NICForwarding(%d, %d) = false, want = true\", nicID, test.netProto)\n+ t.Errorf(\"got s.%s(%d, %d) = false, want = true\", subTest.getForwardingFuncName, nicID, test.netProto)\n+ }\n+ // Verify that the NICInfo also contains the expected value.\n+ allNICInfo := s.NICInfo()\n+ if info, ok := allNICInfo[nicID]; !ok {\n+ t.Fatalf(\"entry for %d missing from allNICInfo = %+v\", nicID, allNICInfo)\n+ } else {\n+ forwardingMap := subTest.getNicInfoForwardingMap(info)\n+ if forward, ok := forwardingMap[test.netProto]; !ok {\n+ t.Fatalf(\"entry for %d missing from info.%s = %+v\", test.netProto, subTest.nicInfoForwardingMapName, forwardingMap)\n+ } else if !forward {\n+ t.Errorf(\"got info.%s[%d] = %t, want = true\", subTest.nicInfoForwardingMapName, test.netProto, forward)\n+ }\n}\n}\n// Setting forwarding to be disabled should return the previous\n- // configuration of true. Disabling it a second time should be a no-op.\n+ // configuration of true. Disabling it a second time should be a\n+ // no-op.\nfor _, wantPrevForwarding := range [...]bool{true, false} {\n- if prevForwarding, err := s.SetNICForwarding(nicID, test.netProto, false); err != nil {\n- t.Fatalf(\"s.SetNICForwarding(%d, %d, false): %s\", nicID, test.netProto, err)\n+ if prevForwarding, err := subTest.setForwardingFunc(s, nicID, test.netProto, false); err != nil {\n+ t.Fatalf(\"s.%s(%d, %d, false): %s\", subTest.setForwardingFuncName, nicID, test.netProto, err)\n} else if prevForwarding != wantPrevForwarding {\n- t.Errorf(\"got s.SetNICForwarding(%d, %d, false) = %t, want = %t\", nicID, test.netProto, prevForwarding, wantPrevForwarding)\n+ t.Errorf(\"got s.%s(%d, %d, false) = %t, want = %t\", subTest.setForwardingFuncName, nicID, test.netProto, prevForwarding, wantPrevForwarding)\n}\n- if forwarding, err := s.NICForwarding(nicID, test.netProto); err != nil {\n- t.Fatalf(\"s.NICForwarding(%d, %d): %s\", nicID, test.netProto, err)\n+ if forwarding, err := subTest.getForwardingFunc(s, nicID, test.netProto); err != nil {\n+ t.Fatalf(\"s.%s(%d, %d): %s\", subTest.getForwardingFuncName, nicID, test.netProto, err)\n} else if forwarding {\n- t.Errorf(\"got s.NICForwarding(%d, %d) = true, want = false\", nicID, test.netProto)\n+ t.Errorf(\"got s.%s(%d, %d) = true, want = false\", subTest.getForwardingFuncName, nicID, test.netProto)\n}\n+ // Verify that the NICInfo also contains the expected value.\n+ allNICInfo := s.NICInfo()\n+ if info, ok := allNICInfo[nicID]; !ok {\n+ t.Fatalf(\"entry for %d missing from allNICInfo = %+v\", nicID, allNICInfo)\n+ } else {\n+ forwardingMap := subTest.getNicInfoForwardingMap(info)\n+ if forward, ok := forwardingMap[test.netProto]; !ok {\n+ t.Fatalf(\"entry for %d missing from info.%s = %+v\", test.netProto, subTest.nicInfoForwardingMapName, forwardingMap)\n+ } else if forward {\n+ t.Errorf(\"got info.%s[%d] = %t, want = false\", subTest.nicInfoForwardingMapName, test.netProto, forward)\n+ }\n+ }\n+ }\n+\n+ })\n}\n})\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add option to enable multicast forwarding
Setting this newly added option to "true" will currently be a no-op. Full
support for multicast routing will be added in subsequent CLs.
Updates #7338.
PiperOrigin-RevId: 439356271 |
259,962 | 04.04.2022 13:50:47 | 25,200 | 399199e4b7c89ff9d670e37ed8ae93bbca0defb4 | Call ConfirmReachable only once per batch of packets.
ConfirmReachable does not need to be called on every packet processed
as we process packets in batches. Its more efficient to do so once
for every batch in handleSegmentsLocked. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/connect.go",
"new_path": "pkg/tcpip/transport/tcp/connect.go",
"diff": "@@ -1142,6 +1142,7 @@ func (e *endpoint) handleReset(s *segment) (ok bool, err tcpip.Error) {\n// +checklocksalias:e.snd.ep.mu=e.mu\nfunc (e *endpoint) handleSegmentsLocked(fastPath bool) tcpip.Error {\ncheckRequeue := true\n+ sndUna := e.snd.SndUna\nfor i := 0; i < maxSegmentsPerWake; i++ {\nif state := e.EndpointState(); state.closed() || state == StateTimeWait {\nreturn nil\n@@ -1162,6 +1163,16 @@ func (e *endpoint) handleSegmentsLocked(fastPath bool) tcpip.Error {\n}\n}\n+ // The remote ACK-ing at least 1 byte is an indication that we have a\n+ // full-duplex connection to the remote as the only way we will receive an\n+ // ACK is if the remote received data that we previously sent.\n+ //\n+ // As of writing, Linux seems to only confirm a route as reachable when\n+ // forward progress is made which is indicated by an ACK that removes data\n+ // from the retransmit queue, i.e. sender makes forward progress.\n+ if sndUna.LessThan(e.snd.SndUna) {\n+ e.route.ConfirmReachable()\n+ }\n// When fastPath is true we don't want to wake up the worker\n// goroutine. If the endpoint has more segments to process the\n// dispatcher will call handleSegments again anyway.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/snd.go",
"new_path": "pkg/tcpip/transport/tcp/snd.go",
"diff": "@@ -1496,18 +1496,6 @@ func (s *sender) handleRcvdSegment(rcvdSeg *segment) {\n// Remove all acknowledged data from the write list.\nacked := s.SndUna.Size(ack)\ns.SndUna = ack\n-\n- // The remote ACK-ing at least 1 byte is an indication that we have a\n- // full-duplex connection to the remote as the only way we will receive an\n- // ACK is if the remote received data that we previously sent.\n- //\n- // As of writing, linux seems to only confirm a route as reachable when\n- // forward progress is made which is indicated by an ACK that removes data\n- // from the retransmit queue.\n- if acked > 0 {\n- s.ep.route.ConfirmReachable()\n- }\n-\nackLeft := acked\noriginalOutstanding := s.Outstanding\nfor ackLeft > 0 {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Call ConfirmReachable only once per batch of packets.
ConfirmReachable does not need to be called on every packet processed
as we process packets in batches. Its more efficient to do so once
for every batch in handleSegmentsLocked.
PiperOrigin-RevId: 439402884 |
259,966 | 05.04.2022 12:43:01 | 25,200 | bfd3f716ab34dee81050276369527f1c870821c3 | Remove unnecessary locks from SetMulticastForwarding | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4.go",
"diff": "@@ -253,9 +253,6 @@ func (e *endpoint) MulticastForwarding() bool {\n// SetMulticastForwarding implements stack.MulticastForwardingNetworkEndpoint.\nfunc (e *endpoint) SetMulticastForwarding(forwarding bool) bool {\n- e.mu.Lock()\n- defer e.mu.Unlock()\n-\nupdatedForwarding := uint32(forwardingDisabled)\nif forwarding {\nupdatedForwarding = forwardingEnabled\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6.go",
"diff": "@@ -522,9 +522,6 @@ func (e *endpoint) MulticastForwarding() bool {\n// SetMulticastForwarding implements stack.MulticastForwardingNetworkEndpoint.\nfunc (e *endpoint) SetMulticastForwarding(forwarding bool) bool {\n- e.mu.Lock()\n- defer e.mu.Unlock()\n-\nupdatedForwarding := uint32(forwardingDisabled)\nif forwarding {\nupdatedForwarding = forwardingEnabled\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove unnecessary locks from SetMulticastForwarding
PiperOrigin-RevId: 439650199 |
259,853 | 06.04.2022 14:18:09 | 25,200 | e8ee6e81252850255cffc982e9867d48207ed659 | Remove unused ring0.RestoreKernelFPState. | [
{
"change_type": "MODIFY",
"old_path": "pkg/ring0/kernel_amd64.go",
"new_path": "pkg/ring0/kernel_amd64.go",
"diff": "@@ -338,21 +338,3 @@ func SetCPUIDFaulting(on bool) bool {\nfunc ReadCR2() uintptr {\nreturn readCR2()\n}\n-\n-// kernelMXCSR is the value of the mxcsr register in the Sentry.\n-//\n-// The MXCSR control configuration is initialized once and never changed. Look\n-// at src/cmd/compile/abi-internal.md in the golang sources for more details.\n-var kernelMXCSR uint32\n-\n-// RestoreKernelFPState restores the Sentry floating point state.\n-//\n-//go:nosplit\n-func RestoreKernelFPState() {\n- // Restore the MXCSR control configuration.\n- ldmxcsr(&kernelMXCSR)\n-}\n-\n-func init() {\n- stmxcsr(&kernelMXCSR)\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/ring0/kernel_arm64.go",
"new_path": "pkg/ring0/kernel_arm64.go",
"diff": "@@ -90,9 +90,3 @@ func (c *CPU) SwitchToUser(switchOpts SwitchOpts) (vector Vector) {\nreturn\n}\n-\n-// RestoreKernelFPState restores the Sentry floating point state.\n-//\n-//go:nosplit\n-func RestoreKernelFPState() {\n-}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove unused ring0.RestoreKernelFPState.
PiperOrigin-RevId: 439933401 |
259,992 | 07.04.2022 12:01:35 | 25,200 | 90ef5d086970c647d47211236971c78e26725acc | Take direct dependency on Any proto | [
{
"change_type": "MODIFY",
"old_path": "pkg/eventchannel/BUILD",
"new_path": "pkg/eventchannel/BUILD",
"diff": "@@ -6,7 +6,6 @@ go_library(\nname = \"eventchannel\",\nsrcs = [\n\"event.go\",\n- \"event_any.go\",\n\"processor.go\",\n\"rate.go\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/eventchannel/event.go",
"new_path": "pkg/eventchannel/event.go",
"diff": "@@ -25,6 +25,7 @@ import (\n\"google.golang.org/protobuf/encoding/prototext\"\n\"google.golang.org/protobuf/proto\"\n+ \"google.golang.org/protobuf/types/known/anypb\"\n\"gvisor.dev/gvisor/pkg/errors/linuxerr\"\npb \"gvisor.dev/gvisor/pkg/eventchannel/eventchannel_go_proto\"\n\"gvisor.dev/gvisor/pkg/log\"\n@@ -139,7 +140,7 @@ func SocketEmitter(fd int) (Emitter, error) {\n// Emit implements Emitter.Emit.\nfunc (s *socketEmitter) Emit(msg proto.Message) (bool, error) {\n- any, err := newAny(msg)\n+ any, err := anypb.New(msg)\nif err != nil {\nreturn false, err\n}\n"
},
{
"change_type": "DELETE",
"old_path": "pkg/eventchannel/event_any.go",
"new_path": null,
"diff": "-// Copyright 2018 The gVisor Authors.\n-//\n-// Licensed under the Apache License, Version 2.0 (the \"License\");\n-// you may not use this file except in compliance with the License.\n-// You may obtain a copy of the License at\n-//\n-// http://www.apache.org/licenses/LICENSE-2.0\n-//\n-// Unless required by applicable law or agreed to in writing, software\n-// distributed under the License is distributed on an \"AS IS\" BASIS,\n-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-// See the License for the specific language governing permissions and\n-// limitations under the License.\n-\n-//go:build go1.1\n-// +build go1.1\n-\n-package eventchannel\n-\n-import (\n- \"google.golang.org/protobuf/types/known/anypb\"\n-\n- \"google.golang.org/protobuf/proto\"\n-)\n-\n-func newAny(m proto.Message) (*anypb.Any, error) {\n- return anypb.New(m)\n-}\n-\n-func emptyAny() *anypb.Any {\n- var any anypb.Any\n- return &any\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/eventchannel/processor.go",
"new_path": "pkg/eventchannel/processor.go",
"diff": "@@ -22,6 +22,7 @@ import (\n\"time\"\n\"google.golang.org/protobuf/proto\"\n+ \"google.golang.org/protobuf/types/known/anypb\"\npb \"gvisor.dev/gvisor/pkg/eventchannel/eventchannel_go_proto\"\n)\n@@ -76,13 +77,13 @@ func (e *eventProcessor) processOne(src io.Reader, out *os.File) error {\n// Unmarshal the payload into an \"Any\" protobuf, which encodes the actual\n// event.\n- encodedEv := emptyAny()\n- if err := proto.Unmarshal(buf, encodedEv); err != nil {\n+ encodedEv := anypb.Any{}\n+ if err := proto.Unmarshal(buf, &encodedEv); err != nil {\nreturn fmt.Errorf(\"failed to unmarshal 'any' protobuf message: %v\", err)\n}\nvar ev pb.DebugEvent\n- if err := (encodedEv).UnmarshalTo(&ev); err != nil {\n+ if err := encodedEv.UnmarshalTo(&ev); err != nil {\nreturn fmt.Errorf(\"failed to decode 'any' protobuf message: %v\", err)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Take direct dependency on Any proto
PiperOrigin-RevId: 440166317 |
259,985 | 07.04.2022 14:20:05 | 25,200 | 9219adb83cdff5f8dee51ae0e183e62bf5d5e1b8 | cgroupfs: Mkdir should honour file mode. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/base.go",
"new_path": "pkg/sentry/fsimpl/cgroupfs/base.go",
"diff": "@@ -163,7 +163,7 @@ type cgroupInode struct {\nvar _ kernel.CgroupImpl = (*cgroupInode)(nil)\n-func (fs *filesystem) newCgroupInode(ctx context.Context, creds *auth.Credentials, parent *cgroupInode) kernfs.Inode {\n+func (fs *filesystem) newCgroupInode(ctx context.Context, creds *auth.Credentials, parent *cgroupInode, mode linux.FileMode) kernfs.Inode {\nc := &cgroupInode{\ndir: dir{fs: fs},\nts: make(map[*kernel.Task]struct{}),\n@@ -190,7 +190,7 @@ func (fs *filesystem) newCgroupInode(ctx context.Context, creds *auth.Credential\n}\n}\n- c.dir.InodeAttrs.Init(ctx, creds, linux.UNNAMED_MAJOR, fs.devMinor, fs.NextIno(), linux.ModeDirectory|linux.FileMode(0555))\n+ c.dir.InodeAttrs.Init(ctx, creds, linux.UNNAMED_MAJOR, fs.devMinor, fs.NextIno(), mode)\nc.dir.OrderedChildren.Init(kernfs.OrderedChildrenOptions{Writable: true})\nc.dir.IncLinks(c.dir.OrderedChildren.Populate(contents))\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/cgroupfs.go",
"new_path": "pkg/sentry/fsimpl/cgroupfs/cgroupfs.go",
"diff": "@@ -81,6 +81,8 @@ const (\nName = \"cgroup\"\nreadonlyFileMode = linux.FileMode(0444)\nwritableFileMode = linux.FileMode(0644)\n+ defaultDirMode = linux.FileMode(0555) | linux.ModeDirectory\n+\ndefaultMaxCachedDentries = uint64(1000)\n)\n@@ -297,7 +299,7 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nfs.kcontrollers = append(fs.kcontrollers, c)\n}\n- root := fs.newCgroupInode(ctx, creds, nil)\n+ root := fs.newCgroupInode(ctx, creds, nil, defaultDirMode)\nvar rootD kernfs.Dentry\nrootD.InitRoot(&fs.Filesystem, root)\nfs.root = &rootD\n@@ -346,7 +348,7 @@ func (fs *filesystem) prepareInitialCgroup(ctx context.Context, vfsObj *vfs.Virt\n// Have initial cgroup target, create the tree.\ncgDir := fs.root.Inode().(*cgroupInode)\nfor pit := initPath.Begin; pit.Ok(); pit = pit.Next() {\n- cgDirI, err := cgDir.NewDir(ctx, pit.String(), vfs.MkdirOptions{})\n+ cgDirI, err := cgDir.NewDir(ctx, pit.String(), vfs.MkdirOptions{Mode: defaultDirMode})\nif err != nil {\nreturn err\n}\n@@ -452,9 +454,10 @@ func (d *dir) NewDir(ctx context.Context, name string, opts vfs.MkdirOptions) (k\nif strings.Contains(name, \"\\n\") {\nreturn nil, linuxerr.EINVAL\n}\n+ mode := opts.Mode.Permissions() | linux.ModeDirectory\nreturn d.OrderedChildren.Inserter(name, func() kernfs.Inode {\nd.IncLinks(1)\n- return d.fs.newCgroupInode(ctx, auth.CredentialsFromContext(ctx), d.cgi)\n+ return d.fs.newCgroupInode(ctx, auth.CredentialsFromContext(ctx), d.cgi, mode)\n})\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/cgroup.cc",
"new_path": "test/syscalls/linux/cgroup.cc",
"diff": "@@ -457,7 +457,8 @@ TEST(Cgroup, DirSetStat) {\nCgroup child = ASSERT_NO_ERRNO_AND_VALUE(c.CreateChild(\"child\"));\nconst struct stat child_before =\nASSERT_NO_ERRNO_AND_VALUE(Stat(child.Path()));\n- EXPECT_THAT(child_before.st_mode, PermissionIs(0555)); // Default.\n+ // Mkdir passes 0755 by default.\n+ EXPECT_THAT(child_before.st_mode, PermissionIs(0755));\nASSERT_NO_ERRNO(Chmod(child.Path(), 0757));\nconst struct stat child_after = ASSERT_NO_ERRNO_AND_VALUE(Stat(child.Path()));\n@@ -468,6 +469,25 @@ TEST(Cgroup, DirSetStat) {\nEXPECT_THAT(parent_after.st_mode, PermissionIs(0755));\n}\n+TEST(Cgroup, MkdirWithPermissions) {\n+ SKIP_IF(!CgroupsAvailable());\n+ Mounter m(ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir()));\n+ Cgroup c = ASSERT_NO_ERRNO_AND_VALUE(m.MountCgroupfs(\"\"));\n+\n+ std::string child1_path = JoinPath(c.Path(), \"child1\");\n+ std::string child2_path = JoinPath(c.Path(), \"child2\");\n+\n+ ASSERT_NO_ERRNO(Mkdir(child1_path, 0444));\n+ const struct stat s1 = ASSERT_NO_ERRNO_AND_VALUE(Stat(child1_path));\n+ EXPECT_THAT(s1.st_mode, PermissionIs(0444));\n+ EXPECT_TRUE(S_ISDIR(s1.st_mode));\n+\n+ ASSERT_NO_ERRNO(Mkdir(child2_path, 0));\n+ const struct stat s2 = ASSERT_NO_ERRNO_AND_VALUE(Stat(child2_path));\n+ EXPECT_THAT(s2.st_mode, PermissionIs(0000));\n+ EXPECT_TRUE(S_ISDIR(s2.st_mode));\n+}\n+\nTEST(MemoryCgroup, MemoryUsageInBytes) {\nSKIP_IF(!CgroupsAvailable());\n"
}
] | Go | Apache License 2.0 | google/gvisor | cgroupfs: Mkdir should honour file mode.
PiperOrigin-RevId: 440199111 |
259,975 | 12.04.2022 10:17:08 | 25,200 | b3dc42bace4813d2833d3cabeba3539efe8d6acb | [benchmarks] Add profiles back to buildkite. | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -383,7 +383,7 @@ run_benchmark = \\\nbenchmark-platforms: load-benchmarks $(RUNTIME_BIN) ## Runs benchmarks for runc and all platforms.\n@set -xe; for PLATFORM in $$($(RUNTIME_BIN) help platforms); do \\\nexport PLATFORM; \\\n- $(call install_runtime,$${PLATFORM},--platform $${PLATFORM}); \\\n+ $(call install_runtime,$${PLATFORM},--platform $${PLATFORM} --profile); \\\n$(call run_benchmark,$${PLATFORM}); \\\ndone\n@$(call run_benchmark,runc)\n"
}
] | Go | Apache License 2.0 | google/gvisor | [benchmarks] Add profiles back to buildkite.
PiperOrigin-RevId: 441223389 |
259,853 | 12.04.2022 23:30:43 | 25,200 | edbd20302734797bc3283b6f4b7e1448ee8b691c | kvm: handle errors of updateSystemValues | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/kvm_amd64.go",
"new_path": "pkg/sentry/platform/kvm/kvm_amd64.go",
"diff": "@@ -219,7 +219,9 @@ func (c *cpuidEntries) Set(in cpuid.In, out cpuid.Out) {\n// updateGlobalOnce does global initialization. It has to be called only once.\nfunc updateGlobalOnce(fd int) error {\n- err := updateSystemValues(int(fd))\n+ if err := updateSystemValues(int(fd)); err != nil {\n+ return err\n+ }\nfs := cpuid.FeatureSet{\nFunction: &cpuidSupported,\n}\n@@ -238,5 +240,5 @@ func updateGlobalOnce(fd int) error {\nFunction: s,\n})\nphysicalInit()\n- return err\n+ return nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | kvm: handle errors of updateSystemValues
PiperOrigin-RevId: 441390130 |
260,009 | 13.04.2022 11:13:31 | 25,200 | 717f78b01497c17c9c52bed896b7877089c49bbc | Add additional init checks to ExponentialBucketer. | [
{
"change_type": "MODIFY",
"old_path": "pkg/metric/metric.go",
"new_path": "pkg/metric/metric.go",
"diff": "@@ -551,6 +551,9 @@ func NewExponentialBucketer(numFiniteBuckets int, width uint64, scale, growth fl\nif numFiniteBuckets < exponentialMinBuckets || numFiniteBuckets > exponentialMaxBuckets {\npanic(fmt.Sprintf(\"number of finite buckets must be in [%d, %d]\", exponentialMinBuckets, exponentialMaxBuckets))\n}\n+ if scale < 0 || growth < 0 {\n+ panic(fmt.Sprintf(\"scale and growth for exponential buckets must be >0, got scale=%f and growth=%f\", scale, growth))\n+ }\nb := &ExponentialBucketer{\nnumFiniteBuckets: numFiniteBuckets,\nwidth: float64(width),\n@@ -562,6 +565,9 @@ func NewExponentialBucketer(numFiniteBuckets int, width uint64, scale, growth fl\nb.lowerBounds[0] = 0\nfor i := 1; i <= numFiniteBuckets; i++ {\nb.lowerBounds[i] = int64(b.width*float64(i) + b.scale*math.Pow(b.growth, float64(i-1)))\n+ if b.lowerBounds[i] < 0 {\n+ panic(fmt.Sprintf(\"encountered bucket width overflow at bucket %d\", i))\n+ }\n}\nb.maxSample = b.lowerBounds[numFiniteBuckets] - 1\nreturn b\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/metric/metric_test.go",
"new_path": "pkg/metric/metric_test.go",
"diff": "@@ -830,6 +830,9 @@ func TestBucketerPanics(t *testing.T) {\n\"NewDurationBucketer @ 2\": func() {\nNewDurationBucketer(2, time.Second, time.Minute)\n},\n+ \"NewDurationBucketer @ 80\": func() {\n+ NewDurationBucketer(80, time.Microsecond, 50*time.Microsecond)\n+ },\n} {\nt.Run(name, func(t *testing.T) {\nvar recovered interface{}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add additional init checks to ExponentialBucketer.
PiperOrigin-RevId: 441529868 |
259,907 | 15.04.2022 15:05:42 | 25,200 | fed9f8ee8e821b2a7b27f2a90462de077e82f9ac | Do not hold transport.Endpoint.mu during mknod in unix bind implementations.
This is consistent with Linux, which calls mknod(), then takes
unix_sock::bindlock and then marks the socket as bound. On error, the mknod is
reverted. See net/unix/af_unix.c:unix_bind_bsd().
This helps break the following lock chain: kernfs.filesystemRWMutex ->
kernel.taskSetRWMutex -> mm.activeRWMutex -> transport.endpointMutex. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netlink/socket.go",
"new_path": "pkg/sentry/socket/netlink/socket.go",
"diff": "@@ -138,7 +138,7 @@ func NewSocket(t *kernel.Task, skType linux.SockType, protocol Protocol) (*Socke\n// Bind the endpoint for good measure so we can connect to it. The\n// bound address will never be exposed.\n- if err := ep.Bind(tcpip.FullAddress{Addr: \"dummy\"}, nil); err != nil {\n+ if err := ep.Bind(tcpip.FullAddress{Addr: \"dummy\"}); err != nil {\nep.Close(t)\nreturn nil, err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netlink/socket_vfs2.go",
"new_path": "pkg/sentry/socket/netlink/socket_vfs2.go",
"diff": "@@ -57,7 +57,7 @@ func NewVFS2(t *kernel.Task, skType linux.SockType, protocol Protocol) (*SocketV\n// Bind the endpoint for good measure so we can connect to it. The\n// bound address will never be exposed.\n- if err := ep.Bind(tcpip.FullAddress{Addr: \"dummy\"}, nil); err != nil {\n+ if err := ep.Bind(tcpip.FullAddress{Addr: \"dummy\"}); err != nil {\nep.Close(t)\nreturn nil, err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/transport/connectioned.go",
"new_path": "pkg/sentry/socket/unix/transport/connectioned.go",
"diff": "@@ -449,7 +449,7 @@ func (e *connectionedEndpoint) Accept(ctx context.Context, peerAddr *tcpip.FullA\n//\n// Bind will fail only if the socket is connected, bound or the passed address\n// is invalid (the empty string).\n-func (e *connectionedEndpoint) Bind(addr tcpip.FullAddress, commit func() *syserr.Error) *syserr.Error {\n+func (e *connectionedEndpoint) Bind(addr tcpip.FullAddress) *syserr.Error {\ne.Lock()\ndefer e.Unlock()\nif e.isBound() || e.ListeningLocked() {\n@@ -459,11 +459,6 @@ func (e *connectionedEndpoint) Bind(addr tcpip.FullAddress, commit func() *syser\n// The empty string is not permitted.\nreturn syserr.ErrBadLocalAddress\n}\n- if commit != nil {\n- if err := commit(); err != nil {\n- return err\n- }\n- }\n// Save the bound address.\ne.path = string(addr.Addr)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/transport/connectionless.go",
"new_path": "pkg/sentry/socket/unix/transport/connectionless.go",
"diff": "@@ -164,7 +164,7 @@ func (*connectionlessEndpoint) Accept(context.Context, *tcpip.FullAddress) (Endp\n//\n// Bind will fail only if the socket is connected, bound or the passed address\n// is invalid (the empty string).\n-func (e *connectionlessEndpoint) Bind(addr tcpip.FullAddress, commit func() *syserr.Error) *syserr.Error {\n+func (e *connectionlessEndpoint) Bind(addr tcpip.FullAddress) *syserr.Error {\ne.Lock()\ndefer e.Unlock()\nif e.isBound() {\n@@ -174,11 +174,6 @@ func (e *connectionlessEndpoint) Bind(addr tcpip.FullAddress, commit func() *sys\n// The empty string is not permitted.\nreturn syserr.ErrBadLocalAddress\n}\n- if commit != nil {\n- if err := commit(); err != nil {\n- return err\n- }\n- }\n// Save the bound address.\ne.path = string(addr.Addr)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/transport/unix.go",
"new_path": "pkg/sentry/socket/unix/transport/unix.go",
"diff": "@@ -166,11 +166,7 @@ type Endpoint interface {\n// Bind binds the endpoint to a specific local address and port.\n// Specifying a NIC is optional.\n- //\n- // An optional commit function will be executed atomically with respect\n- // to binding the endpoint. If this returns an error, the bind will not\n- // occur and the error will be propagated back to the caller.\n- Bind(address tcpip.FullAddress, commit func() *syserr.Error) *syserr.Error\n+ Bind(address tcpip.FullAddress) *syserr.Error\n// Type return the socket type, typically either SockStream, SockDgram\n// or SockSeqpacket.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/unix.go",
"new_path": "pkg/sentry/socket/unix/unix.go",
"diff": "@@ -26,6 +26,7 @@ import (\n\"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n\"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/hostarch\"\n+ \"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/marshal\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n@@ -284,9 +285,8 @@ func (s *SocketOperations) Bind(t *kernel.Task, sockaddr []byte) *syserr.Error {\nreturn syserr.ErrInvalidArgument\n}\n- return s.ep.Bind(tcpip.FullAddress{Addr: tcpip.Address(p)}, func() *syserr.Error {\n- // Is it abstract?\nif p[0] == 0 {\n+ // Abstract socket. See net/unix/af_unix.c:unix_bind_abstract().\nif t.IsNetworkNamespaced() {\nreturn syserr.ErrInvalidEndpointState\n}\n@@ -296,9 +296,18 @@ func (s *SocketOperations) Bind(t *kernel.Task, sockaddr []byte) *syserr.Error {\n// syserr.ErrPortInUse corresponds to EADDRINUSE.\nreturn syserr.ErrPortInUse\n}\n+ if err := s.ep.Bind(tcpip.FullAddress{Addr: tcpip.Address(p)}); err != nil {\n+ asn.Remove(name, s)\n+ return err\n+ }\n+ // The socket has been successfully bound. We can update the following.\ns.abstractName = name\ns.abstractNamespace = asn\n- } else {\n+ return nil\n+ }\n+\n+ // See net/unix/af_unix.c:unix_bind_bsd().\n+\n// The parent and name.\nvar d *fs.Dirent\nvar name string\n@@ -343,10 +352,13 @@ func (s *SocketOperations) Bind(t *kernel.Task, sockaddr []byte) *syserr.Error {\nreturn syserr.ErrPortInUse\n}\nchildDir.DecRef(t)\n+ if err := s.ep.Bind(tcpip.FullAddress{Addr: tcpip.Address(p)}); err != nil {\n+ if removeErr := d.Remove(t, t.FSContext().RootDirectory(), name, false /* dirPath */); removeErr != nil {\n+ log.Warningf(\"failed to remove socket file created for bind(%q): %v\", p, removeErr)\n+ }\n+ return err\n}\n-\nreturn nil\n- })\n}\n// extractEndpoint retrieves the transport.BoundEndpoint associated with a Unix\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/unix_vfs2.go",
"new_path": "pkg/sentry/socket/unix/unix_vfs2.go",
"diff": "@@ -20,6 +20,7 @@ import (\n\"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n\"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/hostarch\"\n+ \"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/marshal\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/sockfs\"\n@@ -198,9 +199,8 @@ func (s *SocketVFS2) Bind(t *kernel.Task, sockaddr []byte) *syserr.Error {\nreturn syserr.ErrInvalidArgument\n}\n- return s.ep.Bind(tcpip.FullAddress{Addr: tcpip.Address(p)}, func() *syserr.Error {\n- // Is it abstract?\nif p[0] == 0 {\n+ // Abstract socket. See net/unix/af_unix.c:unix_bind_abstract().\nif t.IsNetworkNamespaced() {\nreturn syserr.ErrInvalidEndpointState\n}\n@@ -210,9 +210,17 @@ func (s *SocketVFS2) Bind(t *kernel.Task, sockaddr []byte) *syserr.Error {\n// syserr.ErrPortInUse corresponds to EADDRINUSE.\nreturn syserr.ErrPortInUse\n}\n+ if err := s.ep.Bind(tcpip.FullAddress{Addr: tcpip.Address(p)}); err != nil {\n+ asn.Remove(name, s)\n+ return err\n+ }\n+ // The socket has been successfully bound. We can update the following.\ns.abstractName = name\ns.abstractNamespace = asn\n- } else {\n+ return nil\n+ }\n+\n+ // See net/unix/af_unix.c:unix_bind_bsd().\npath := fspath.Parse(p)\nroot := t.FSContext().RootDirectoryVFS2()\ndefer root.DecRef(t)\n@@ -232,18 +240,22 @@ func (s *SocketVFS2) Bind(t *kernel.Task, sockaddr []byte) *syserr.Error {\nreturn syserr.FromError(err)\n}\nerr = t.Kernel().VFS().MknodAt(t, t.Credentials(), &pop, &vfs.MknodOptions{\n- // File permissions correspond to net/unix/af_unix.c:unix_bind.\nMode: linux.FileMode(linux.S_IFSOCK | uint(stat.Mode)&^t.FSContext().Umask()),\nEndpoint: bep,\n})\nif linuxerr.Equals(linuxerr.EEXIST, err) {\nreturn syserr.ErrAddressInUse\n}\n+ if err != nil {\nreturn syserr.FromError(err)\n}\n-\n+ if err := s.ep.Bind(tcpip.FullAddress{Addr: tcpip.Address(p)}); err != nil {\n+ if unlinkErr := t.Kernel().VFS().UnlinkAt(t, t.Credentials(), &pop); unlinkErr != nil {\n+ log.Warningf(\"failed to unlink socket file created for bind(%q): %v\", p, unlinkErr)\n+ }\n+ return err\n+ }\nreturn nil\n- })\n}\n// Ioctl implements vfs.FileDescriptionImpl.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Do not hold transport.Endpoint.mu during mknod in unix bind implementations.
This is consistent with Linux, which calls mknod(), then takes
unix_sock::bindlock and then marks the socket as bound. On error, the mknod is
reverted. See net/unix/af_unix.c:unix_bind_bsd().
This helps break the following lock chain: kernfs.filesystemRWMutex ->
kernel.taskSetRWMutex -> mm.activeRWMutex -> transport.endpointMutex.
PiperOrigin-RevId: 442104624 |
259,985 | 18.04.2022 17:25:50 | 25,200 | 5f9bd8a53b208bad3fe3e5cace82c4521dc9c2b3 | cgroupfs: Synchronize access to cpuset controller bitmaps.
Reported-by: | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/cpuset.go",
"new_path": "pkg/sentry/fsimpl/cgroupfs/cpuset.go",
"diff": "@@ -65,6 +65,8 @@ func newCPUSetController(k *kernel.Kernel, fs *filesystem) *cpusetController {\n// Clone implements controller.Clone.\nfunc (c *cpusetController) Clone() controller {\n+ c.mu.Lock()\n+ defer c.mu.Unlock()\ncpus := c.cpus.Clone()\nmems := c.mems.Clone()\nnew := &cpusetController{\n"
}
] | Go | Apache License 2.0 | google/gvisor | cgroupfs: Synchronize access to cpuset controller bitmaps.
Reported-by: syzbot+98719e57f6acbe602b7f@syzkaller.appspotmail.com
PiperOrigin-RevId: 442672867 |
259,909 | 19.04.2022 11:18:32 | 25,200 | e380531bfba0d7c4ad3b4dd50d590cddaaac0c76 | Clean up tcp segment sender functions.
sendRaw is entirely used to just send flags, so change the function to
explicitly send empty segments. The single use case for sending data can
be taken care of in sendSegment. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/connect.go",
"new_path": "pkg/tcpip/transport/tcp/connect.go",
"diff": "@@ -290,7 +290,7 @@ func (h *handshake) checkAck(s *segment) bool {\n// If the segment acknowledgment is not acceptable, form a reset segment,\n// <SEQ=SEG.ACK><CTL=RST>\n// and send it.\n- h.ep.sendRaw(buffer.VectorisedView{}, header.TCPFlagRst, s.ackNumber, 0, 0)\n+ h.ep.sendEmptyRaw(header.TCPFlagRst, s.ackNumber, 0, 0)\nreturn false\n}\n@@ -346,7 +346,7 @@ func (h *handshake) synSentState(s *segment) tcpip.Error {\nh.state = handshakeCompleted\nh.transitionToStateEstablishedLocked(s)\n- h.ep.sendRaw(buffer.VectorisedView{}, header.TCPFlagAck, h.iss+1, h.ackNum, h.rcvWnd>>h.effectiveRcvWndScale())\n+ h.ep.sendEmptyRaw(header.TCPFlagAck, h.iss+1, h.ackNum, h.rcvWnd>>h.effectiveRcvWndScale())\nreturn nil\n}\n@@ -407,7 +407,7 @@ func (h *handshake) synRcvdState(s *segment) tcpip.Error {\n// segment and return.\"\nif !s.sequenceNumber.InWindow(h.ackNum, h.rcvWnd) {\nif h.ep.allowOutOfWindowAck() {\n- h.ep.sendRaw(buffer.VectorisedView{}, header.TCPFlagAck, h.iss+1, h.ackNum, h.rcvWnd)\n+ h.ep.sendEmptyRaw(header.TCPFlagAck, h.iss+1, h.ackNum, h.rcvWnd)\n}\nreturn nil\n}\n@@ -421,7 +421,7 @@ func (h *handshake) synRcvdState(s *segment) tcpip.Error {\nif s.flags.Contains(header.TCPFlagAck) {\nseq = s.ackNumber\n}\n- h.ep.sendRaw(buffer.VectorisedView{}, header.TCPFlagRst|header.TCPFlagAck, seq, ack, 0)\n+ h.ep.sendEmptyRaw(header.TCPFlagRst|header.TCPFlagAck, seq, ack, 0)\nif !h.active {\nreturn &tcpip.ErrInvalidEndpointState{}\n@@ -957,6 +957,11 @@ func (e *endpoint) makeOptions(sackBlocks []header.SACKBlock) []byte {\nreturn options[:offset]\n}\n+// sendEmptyRaw sends a TCP segment to the endpoint's peer.\n+func (e *endpoint) sendEmptyRaw(flags header.TCPFlags, seq, ack seqnum.Value, rcvWnd seqnum.Size) tcpip.Error {\n+ return e.sendRaw(buffer.VectorisedView{}, flags, seq, ack, rcvWnd)\n+}\n+\n// sendRaw sends a TCP segment to the endpoint's peer.\nfunc (e *endpoint) sendRaw(data buffer.VectorisedView, flags header.TCPFlags, seq, ack seqnum.Value, rcvWnd seqnum.Size) tcpip.Error {\nvar sackBlocks []header.SACKBlock\n@@ -1017,7 +1022,7 @@ func (e *endpoint) resetConnectionLocked(err tcpip.Error) {\nif !sndWndEnd.LessThan(e.snd.SndNxt) || e.snd.SndNxt.Size(sndWndEnd) < (1<<e.snd.SndWndScale) {\nresetSeqNum = e.snd.SndNxt\n}\n- e.sendRaw(buffer.VectorisedView{}, header.TCPFlagAck|header.TCPFlagRst, resetSeqNum, e.rcv.RcvNxt, 0)\n+ e.sendEmptyRaw(header.TCPFlagAck|header.TCPFlagRst, resetSeqNum, e.rcv.RcvNxt, 0)\n}\n// Don't purge read queues here. If there's buffered data, it's still allowed\n// to be read.\n@@ -1301,7 +1306,7 @@ func (e *endpoint) keepaliveTimerExpired() tcpip.Error {\n// seg.seq = snd.nxt-1.\ne.keepalive.unacked++\ne.keepalive.Unlock()\n- e.snd.sendSegmentFromView(buffer.VectorisedView{}, header.TCPFlagAck, e.snd.SndNxt-1)\n+ e.snd.sendEmptySegment(header.TCPFlagAck, e.snd.SndNxt-1)\ne.resetKeepaliveTimer(false)\nreturn nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/snd.go",
"new_path": "pkg/tcpip/transport/tcp/snd.go",
"diff": "@@ -336,7 +336,7 @@ func (s *sender) updateMaxPayloadSize(mtu, count int) {\n// sendAck sends an ACK segment.\n// +checklocks:s.ep.mu\nfunc (s *sender) sendAck() {\n- s.sendSegmentFromView(buffer.VectorisedView{}, header.TCPFlagAck, s.SndNxt)\n+ s.sendEmptySegment(header.TCPFlagAck, s.SndNxt)\n}\n// updateRTO updates the retransmit timeout when a new roud-trip time is\n@@ -879,13 +879,11 @@ func (s *sender) maybeSendSegment(seg *segment, limit int, end seqnum.Value) (se\n}\n// +checklocks:s.ep.mu\n-// +checklocksalias:s.ep.rcv.ep.mu=s.ep.mu\nfunc (s *sender) sendZeroWindowProbe() {\n- ack, win := s.ep.rcv.getSendParams()\ns.unackZeroWindowProbes++\n// Send a zero window probe with sequence number pointing to\n// the last acknowledged byte.\n- s.ep.sendRaw(buffer.VectorisedView{}, header.TCPFlagAck, s.SndUna-1, ack, win)\n+ s.sendEmptySegment(header.TCPFlagAck, s.SndUna-1)\n// Rearm the timer to continue probing.\ns.resendTimer.enable(s.RTO)\n}\n@@ -1675,6 +1673,13 @@ func (s *sender) sendSegmentFromView(data buffer.VectorisedView, flags header.TC\nreturn s.ep.sendRaw(data, flags, seq, rcvNxt, rcvWnd)\n}\n+// sendEmptySegment sends a new segment containing the given flags and sequence\n+// number.\n+// +checklocks:s.ep.mu\n+func (s *sender) sendEmptySegment(flags header.TCPFlags, seq seqnum.Value) tcpip.Error {\n+ return s.sendSegmentFromView(buffer.VectorisedView{}, flags, seq)\n+}\n+\n// maybeSendOutOfWindowAck sends an ACK if we are not being rate limited\n// currently.\n// +checklocks:s.ep.mu\n"
}
] | Go | Apache License 2.0 | google/gvisor | Clean up tcp segment sender functions.
sendRaw is entirely used to just send flags, so change the function to
explicitly send empty segments. The single use case for sending data can
be taken care of in sendSegment.
PiperOrigin-RevId: 442861994 |
259,985 | 19.04.2022 14:53:25 | 25,200 | f4e537843f49fadaa364ba7f210e68e267f59c3d | Drop MappingIdentity ref outside mm.mappingMu critical section.
Otherwise we get circular locking with various filesystem locks if the
dropped ref is the final ref. Mapping identities are typically file
descriptions on various filesystems, which in turn call mm functions
under the respective filesystem locks. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/lifecycle.go",
"new_path": "pkg/sentry/mm/lifecycle.go",
"diff": "@@ -61,6 +61,15 @@ func (mm *MemoryManager) Fork(ctx context.Context) (*MemoryManager, error) {\ndefer mm.AddressSpace().PostFork()\nmm.metadataMu.Lock()\ndefer mm.metadataMu.Unlock()\n+\n+ var droppedIDs []memmap.MappingIdentity\n+ // This must run after {mm,mm2}.mappingMu.Unlock().\n+ defer func() {\n+ for _, id := range droppedIDs {\n+ id.DecRef(ctx)\n+ }\n+ }()\n+\nmm.mappingMu.RLock()\ndefer mm.mappingMu.RUnlock()\nmm2 := &MemoryManager{\n@@ -109,7 +118,7 @@ func (mm *MemoryManager) Fork(ctx context.Context) (*MemoryManager, error) {\n// Inform the Mappable, if any, of the new mapping.\nif vma.mappable != nil {\nif err := vma.mappable.AddMapping(ctx, mm2, vmaAR, vma.off, vma.canWriteMappableLocked()); err != nil {\n- mm2.removeVMAsLocked(ctx, mm2.applicationAddrRange())\n+ _, droppedIDs = mm2.removeVMAsLocked(ctx, mm2.applicationAddrRange(), droppedIDs)\nreturn nil, err\n}\n}\n@@ -275,11 +284,16 @@ func (mm *MemoryManager) DecUsers(ctx context.Context) {\n}\nmm.activeMu.Unlock()\n+ var droppedIDs []memmap.MappingIdentity\nmm.mappingMu.Lock()\n- defer mm.mappingMu.Unlock()\n// If mm is being dropped before mm.SetMmapLayout was called,\n// mm.applicationAddrRange() will be empty.\nif ar := mm.applicationAddrRange(); ar.Length() != 0 {\n- mm.unmapLocked(ctx, ar)\n+ _, droppedIDs = mm.unmapLocked(ctx, ar, droppedIDs)\n+ }\n+ mm.mappingMu.Unlock()\n+\n+ for _, id := range droppedIDs {\n+ id.DecRef(ctx)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/shm.go",
"new_path": "pkg/sentry/mm/shm.go",
"diff": "@@ -19,6 +19,7 @@ import (\n\"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n\"gvisor.dev/gvisor/pkg/hostarch\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/shm\"\n+ \"gvisor.dev/gvisor/pkg/sentry/memmap\"\n)\n// DetachShm unmaps a sysv shared memory segment.\n@@ -29,6 +30,16 @@ func (mm *MemoryManager) DetachShm(ctx context.Context, addr hostarch.Addr) erro\n}\nvar detached *shm.Shm\n+ var vgap vmaGapIterator\n+\n+ var droppedIDs []memmap.MappingIdentity\n+ // This must run after mm.mappingMu.Unlock().\n+ defer func() {\n+ for _, id := range droppedIDs {\n+ id.DecRef(ctx)\n+ }\n+ }()\n+\nmm.mappingMu.Lock()\ndefer mm.mappingMu.Unlock()\n@@ -39,7 +50,8 @@ func (mm *MemoryManager) DetachShm(ctx context.Context, addr hostarch.Addr) erro\nvma := vseg.ValuePtr()\nif shm, ok := vma.mappable.(*shm.Shm); ok && vseg.Start() >= addr && uint64(vseg.Start()-addr) == vma.off {\ndetached = shm\n- vseg = mm.unmapLocked(ctx, vseg.Range()).NextSegment()\n+ vgap, droppedIDs = mm.unmapLocked(ctx, vseg.Range(), droppedIDs)\n+ vseg = vgap.NextSegment()\nbreak\n} else {\nvseg = vseg.NextSegment()\n@@ -56,7 +68,8 @@ func (mm *MemoryManager) DetachShm(ctx context.Context, addr hostarch.Addr) erro\nfor vseg.Ok() && vseg.End() <= end {\nvma := vseg.ValuePtr()\nif vma.mappable == detached && uint64(vseg.Start()-addr) == vma.off {\n- vseg = mm.unmapLocked(ctx, vseg.Range()).NextSegment()\n+ vgap, droppedIDs = mm.unmapLocked(ctx, vseg.Range(), droppedIDs)\n+ vseg = vgap.NextSegment()\n} else {\nvseg = vseg.NextSegment()\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/syscalls.go",
"new_path": "pkg/sentry/mm/syscalls.go",
"diff": "@@ -115,11 +115,12 @@ func (mm *MemoryManager) MMap(ctx context.Context, opts memmap.MMapOpts) (hostar\n}\n// Get the new vma.\n+ var droppedIDs []memmap.MappingIdentity\nmm.mappingMu.Lock()\nif opts.MLockMode < mm.defMLockMode {\nopts.MLockMode = mm.defMLockMode\n}\n- vseg, ar, err := mm.createVMALocked(ctx, opts)\n+ vseg, ar, droppedIDs, err := mm.createVMALocked(ctx, opts, droppedIDs)\nif err != nil {\nmm.mappingMu.Unlock()\nreturn 0, err\n@@ -148,6 +149,10 @@ func (mm *MemoryManager) MMap(ctx context.Context, opts memmap.MMapOpts) (hostar\nmm.mappingMu.Unlock()\n}\n+ for _, id := range droppedIDs {\n+ id.DecRef(ctx)\n+ }\n+\nreturn ar.Start, nil\n}\n@@ -264,9 +269,11 @@ func (mm *MemoryManager) MapStack(ctx context.Context) (hostarch.AddrRange, erro\nreturn hostarch.AddrRange{}, linuxerr.ENOMEM\n}\nstackStart := stackEnd - szaddr\n+ var droppedIDs []memmap.MappingIdentity\n+ var ar hostarch.AddrRange\n+ var err error\nmm.mappingMu.Lock()\n- defer mm.mappingMu.Unlock()\n- _, ar, err := mm.createVMALocked(ctx, memmap.MMapOpts{\n+ _, ar, droppedIDs, err = mm.createVMALocked(ctx, memmap.MMapOpts{\nLength: sz,\nAddr: stackStart,\nPerms: hostarch.ReadWrite,\n@@ -275,7 +282,11 @@ func (mm *MemoryManager) MapStack(ctx context.Context) (hostarch.AddrRange, erro\nGrowsDown: true,\nMLockMode: mm.defMLockMode,\nHint: \"[stack]\",\n- })\n+ }, droppedIDs)\n+ mm.mappingMu.Unlock()\n+ for _, id := range droppedIDs {\n+ id.DecRef(ctx)\n+ }\nreturn ar, err\n}\n@@ -296,9 +307,15 @@ func (mm *MemoryManager) MUnmap(ctx context.Context, addr hostarch.Addr, length\nreturn linuxerr.EINVAL\n}\n+ var droppedIDs []memmap.MappingIdentity\nmm.mappingMu.Lock()\n- defer mm.mappingMu.Unlock()\n- mm.unmapLocked(ctx, ar)\n+ _, droppedIDs = mm.unmapLocked(ctx, ar, droppedIDs)\n+ mm.mappingMu.Unlock()\n+\n+ for _, id := range droppedIDs {\n+ id.DecRef(ctx)\n+ }\n+\nreturn nil\n}\n@@ -350,6 +367,14 @@ func (mm *MemoryManager) MRemap(ctx context.Context, oldAddr hostarch.Addr, oldS\nreturn 0, linuxerr.EINVAL\n}\n+ var droppedIDs []memmap.MappingIdentity\n+ // This must run after mm.mappingMu.Unlock().\n+ defer func() {\n+ for _, id := range droppedIDs {\n+ id.DecRef(ctx)\n+ }\n+ }()\n+\nmm.mappingMu.Lock()\ndefer mm.mappingMu.Unlock()\n@@ -394,7 +419,7 @@ func (mm *MemoryManager) MRemap(ctx context.Context, oldAddr hostarch.Addr, oldS\n// If oldAddr+oldSize didn't overflow, oldAddr+newSize can't\n// either.\nnewEnd := oldAddr + hostarch.Addr(newSize)\n- mm.unmapLocked(ctx, hostarch.AddrRange{newEnd, oldEnd})\n+ _, droppedIDs = mm.unmapLocked(ctx, hostarch.AddrRange{newEnd, oldEnd}, droppedIDs)\n}\nreturn oldAddr, nil\n}\n@@ -411,7 +436,10 @@ func (mm *MemoryManager) MRemap(ctx context.Context, oldAddr hostarch.Addr, oldS\nif vma.mappable != nil {\nnewOffset = vseg.mappableRange().End\n}\n- vseg, ar, err := mm.createVMALocked(ctx, memmap.MMapOpts{\n+ var vseg vmaIterator\n+ var ar hostarch.AddrRange\n+ var err error\n+ vseg, ar, droppedIDs, err = mm.createVMALocked(ctx, memmap.MMapOpts{\nLength: newSize - oldSize,\nMappingIdentity: vma.id,\nMappable: vma.mappable,\n@@ -424,7 +452,7 @@ func (mm *MemoryManager) MRemap(ctx context.Context, oldAddr hostarch.Addr, oldS\nGrowsDown: vma.growsDown,\nMLockMode: vma.mlockMode,\nHint: vma.hint,\n- })\n+ }, droppedIDs)\nif err == nil {\nif vma.mlockMode == memmap.MLockEager {\nmm.populateVMA(ctx, vseg, ar, true)\n@@ -473,7 +501,7 @@ func (mm *MemoryManager) MRemap(ctx context.Context, oldAddr hostarch.Addr, oldS\n}\n// Unmap any mappings at the destination.\n- mm.unmapLocked(ctx, newAR)\n+ _, droppedIDs = mm.unmapLocked(ctx, newAR, droppedIDs)\n// If the sizes specify shrinking, unmap everything between the new and\n// old sizes at the source. Unmapping before the following checks is\n@@ -481,7 +509,7 @@ func (mm *MemoryManager) MRemap(ctx context.Context, oldAddr hostarch.Addr, oldS\n// vma_to_resize().\nif newSize < oldSize {\noldNewEnd := oldAddr + hostarch.Addr(newSize)\n- mm.unmapLocked(ctx, hostarch.AddrRange{oldNewEnd, oldEnd})\n+ _, droppedIDs = mm.unmapLocked(ctx, hostarch.AddrRange{oldNewEnd, oldEnd}, droppedIDs)\noldEnd = oldNewEnd\n}\n@@ -690,13 +718,17 @@ func (mm *MemoryManager) MProtect(addr hostarch.Addr, length uint64, realPerms h\n// BrkSetup sets mm's brk address to addr and its brk size to 0.\nfunc (mm *MemoryManager) BrkSetup(ctx context.Context, addr hostarch.Addr) {\n+ var droppedIDs []memmap.MappingIdentity\nmm.mappingMu.Lock()\n- defer mm.mappingMu.Unlock()\n// Unmap the existing brk.\nif mm.brk.Length() != 0 {\n- mm.unmapLocked(ctx, mm.brk)\n+ _, droppedIDs = mm.unmapLocked(ctx, mm.brk, droppedIDs)\n}\nmm.brk = hostarch.AddrRange{addr, addr}\n+ mm.mappingMu.Unlock()\n+ for _, id := range droppedIDs {\n+ id.DecRef(ctx)\n+ }\n}\n// Brk implements the semantics of Linux's brk(2), except that it returns an\n@@ -730,9 +762,21 @@ func (mm *MemoryManager) Brk(ctx context.Context, addr hostarch.Addr) (hostarch.\nreturn addr, linuxerr.EFAULT\n}\n+ var vseg vmaIterator\n+ var ar hostarch.AddrRange\n+ var err error\n+\n+ var droppedIDs []memmap.MappingIdentity\n+ // This must run after mm.mappingMu.Unlock().\n+ defer func() {\n+ for _, id := range droppedIDs {\n+ id.DecRef(ctx)\n+ }\n+ }()\n+\nswitch {\ncase oldbrkpg < newbrkpg:\n- vseg, ar, err := mm.createVMALocked(ctx, memmap.MMapOpts{\n+ vseg, ar, droppedIDs, err = mm.createVMALocked(ctx, memmap.MMapOpts{\nLength: uint64(newbrkpg - oldbrkpg),\nAddr: oldbrkpg,\nFixed: true,\n@@ -745,7 +789,7 @@ func (mm *MemoryManager) Brk(ctx context.Context, addr hostarch.Addr) (hostarch.\n// mm->def_flags.\nMLockMode: mm.defMLockMode,\nHint: \"[heap]\",\n- })\n+ }, droppedIDs)\nif err != nil {\naddr = mm.brk.End\nmm.mappingMu.Unlock()\n@@ -759,7 +803,7 @@ func (mm *MemoryManager) Brk(ctx context.Context, addr hostarch.Addr) (hostarch.\n}\ncase newbrkpg < oldbrkpg:\n- mm.unmapLocked(ctx, hostarch.AddrRange{newbrkpg, oldbrkpg})\n+ _, droppedIDs = mm.unmapLocked(ctx, hostarch.AddrRange{newbrkpg, oldbrkpg}, droppedIDs)\nfallthrough\ndefault:\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/vma.go",
"new_path": "pkg/sentry/mm/vma.go",
"diff": "@@ -28,10 +28,16 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/memmap\"\n)\n+// Caller provides the droppedIDs slice to collect dropped mapping\n+// identities. The caller must drop the references on these identities outside a\n+// mm.mappingMu critical section. droppedIDs has append-like semantics, multiple\n+// calls to functions that drop mapping identities within a scope should reuse\n+// the same slice.\n+//\n// Preconditions:\n// * mm.mappingMu must be locked for writing.\n// * opts must be valid as defined by the checks in MMap.\n-func (mm *MemoryManager) createVMALocked(ctx context.Context, opts memmap.MMapOpts) (vmaIterator, hostarch.AddrRange, error) {\n+func (mm *MemoryManager) createVMALocked(ctx context.Context, opts memmap.MMapOpts, droppedIDs []memmap.MappingIdentity) (vmaIterator, hostarch.AddrRange, []memmap.MappingIdentity, error) {\nif opts.MaxPerms != opts.MaxPerms.Effective() {\npanic(fmt.Sprintf(\"Non-effective MaxPerms %s cannot be enforced\", opts.MaxPerms))\n}\n@@ -48,7 +54,7 @@ func (mm *MemoryManager) createVMALocked(ctx context.Context, opts memmap.MMapOp\nif opts.Force && opts.Unmap && opts.Fixed {\naddr = opts.Addr\n} else {\n- return vmaIterator{}, hostarch.AddrRange{}, err\n+ return vmaIterator{}, hostarch.AddrRange{}, droppedIDs, err\n}\n}\nar, _ := addr.ToRange(opts.Length)\n@@ -59,7 +65,7 @@ func (mm *MemoryManager) createVMALocked(ctx context.Context, opts memmap.MMapOp\nnewUsageAS -= uint64(mm.vmas.SpanRange(ar))\n}\nif limitAS := limits.FromContext(ctx).Get(limits.AS).Cur; newUsageAS > limitAS {\n- return vmaIterator{}, hostarch.AddrRange{}, linuxerr.ENOMEM\n+ return vmaIterator{}, hostarch.AddrRange{}, droppedIDs, linuxerr.ENOMEM\n}\nif opts.MLockMode != memmap.MLockNone {\n@@ -67,14 +73,14 @@ func (mm *MemoryManager) createVMALocked(ctx context.Context, opts memmap.MMapOp\nif creds := auth.CredentialsFromContext(ctx); !creds.HasCapabilityIn(linux.CAP_IPC_LOCK, creds.UserNamespace.Root()) {\nmlockLimit := limits.FromContext(ctx).Get(limits.MemoryLocked).Cur\nif mlockLimit == 0 {\n- return vmaIterator{}, hostarch.AddrRange{}, linuxerr.EPERM\n+ return vmaIterator{}, hostarch.AddrRange{}, droppedIDs, linuxerr.EPERM\n}\nnewLockedAS := mm.lockedAS + opts.Length\nif opts.Unmap {\nnewLockedAS -= mm.mlockedBytesRangeLocked(ar)\n}\nif newLockedAS > mlockLimit {\n- return vmaIterator{}, hostarch.AddrRange{}, linuxerr.EAGAIN\n+ return vmaIterator{}, hostarch.AddrRange{}, droppedIDs, linuxerr.EAGAIN\n}\n}\n}\n@@ -84,7 +90,7 @@ func (mm *MemoryManager) createVMALocked(ctx context.Context, opts memmap.MMapOp\n// file->f_op->mmap().\nvar vgap vmaGapIterator\nif opts.Unmap {\n- vgap = mm.unmapLocked(ctx, ar)\n+ vgap, droppedIDs = mm.unmapLocked(ctx, ar, droppedIDs)\n} else {\nvgap = mm.vmas.FindGap(ar.Start)\n}\n@@ -94,7 +100,7 @@ func (mm *MemoryManager) createVMALocked(ctx context.Context, opts memmap.MMapOp\n// The expression for writable is vma.canWriteMappableLocked(), but we\n// don't yet have a vma.\nif err := opts.Mappable.AddMapping(ctx, mm, ar, opts.Offset, !opts.Private && opts.MaxPerms.Write); err != nil {\n- return vmaIterator{}, hostarch.AddrRange{}, err\n+ return vmaIterator{}, hostarch.AddrRange{}, droppedIDs, err\n}\n}\n@@ -128,7 +134,7 @@ func (mm *MemoryManager) createVMALocked(ctx context.Context, opts memmap.MMapOp\nmm.lockedAS += opts.Length\n}\n- return vseg, ar, nil\n+ return vseg, ar, droppedIDs, nil\n}\ntype findAvailableOpts struct {\n@@ -345,11 +351,17 @@ const guardBytes = 256 * hostarch.PageSize\n// unmapLocked unmaps all addresses in ar and returns the resulting gap in\n// mm.vmas.\n//\n+// Caller provides the droppedIDs slice to collect dropped mapping\n+// identities. The caller must drop the references on these identities outside a\n+// mm.mappingMu critical section. droppedIDs has append-like semantics, multiple\n+// calls to functions that drop mapping identities within a scope should reuse\n+// the same slice.\n+//\n// Preconditions:\n// * mm.mappingMu must be locked for writing.\n// * ar.Length() != 0.\n// * ar must be page-aligned.\n-func (mm *MemoryManager) unmapLocked(ctx context.Context, ar hostarch.AddrRange) vmaGapIterator {\n+func (mm *MemoryManager) unmapLocked(ctx context.Context, ar hostarch.AddrRange, droppedIDs []memmap.MappingIdentity) (vmaGapIterator, []memmap.MappingIdentity) {\nif checkInvariants {\nif !ar.WellFormed() || ar.Length() == 0 || !ar.IsPageAligned() {\npanic(fmt.Sprintf(\"invalid ar: %v\", ar))\n@@ -359,24 +371,28 @@ func (mm *MemoryManager) unmapLocked(ctx context.Context, ar hostarch.AddrRange)\n// AddressSpace mappings and pmas must be invalidated before\n// mm.removeVMAsLocked() => memmap.Mappable.RemoveMapping().\nmm.Invalidate(ar, memmap.InvalidateOpts{InvalidatePrivate: true})\n- return mm.removeVMAsLocked(ctx, ar)\n+ return mm.removeVMAsLocked(ctx, ar, droppedIDs)\n}\n-// removeVMAsLocked removes vmas for addresses in ar and returns the resulting\n-// gap in mm.vmas. It does not remove pmas or AddressSpace mappings; clients\n-// must do so before calling removeVMAsLocked.\n+// removeVMAsLocked removes vmas for addresses in ar and returns the\n+// resulting gap in mm.vmas.\n+//\n+// Caller provides the droppedIDs slice to collect dropped mapping\n+// identities. The caller must drop the references on these identities outside a\n+// mm.mappingMu critical section. droppedIDs has append-like semantics, multiple\n+// calls to functions that drop mapping identities within a scope should reuse\n+// the same slice.\n//\n// Preconditions:\n// * mm.mappingMu must be locked for writing.\n// * ar.Length() != 0.\n// * ar must be page-aligned.\n-func (mm *MemoryManager) removeVMAsLocked(ctx context.Context, ar hostarch.AddrRange) vmaGapIterator {\n+func (mm *MemoryManager) removeVMAsLocked(ctx context.Context, ar hostarch.AddrRange, droppedIDs []memmap.MappingIdentity) (vmaGapIterator, []memmap.MappingIdentity) {\nif checkInvariants {\nif !ar.WellFormed() || ar.Length() == 0 || !ar.IsPageAligned() {\npanic(fmt.Sprintf(\"invalid ar: %v\", ar))\n}\n}\n-\nvseg, vgap := mm.vmas.Find(ar.Start)\nif vgap.Ok() {\nvseg = vgap.NextSegment()\n@@ -389,7 +405,7 @@ func (mm *MemoryManager) removeVMAsLocked(ctx context.Context, ar hostarch.AddrR\nvma.mappable.RemoveMapping(ctx, mm, vmaAR, vma.off, vma.canWriteMappableLocked())\n}\nif vma.id != nil {\n- vma.id.DecRef(ctx)\n+ droppedIDs = append(droppedIDs, vma.id)\n}\nmm.usageAS -= uint64(vmaAR.Length())\nif vma.isPrivateDataLocked() {\n@@ -401,7 +417,7 @@ func (mm *MemoryManager) removeVMAsLocked(ctx context.Context, ar hostarch.AddrR\nvgap = mm.vmas.Remove(vseg)\nvseg = vgap.NextSegment()\n}\n- return vgap\n+ return vgap, droppedIDs\n}\n// canWriteMappableLocked returns true if it is possible for vma.mappable to be\n@@ -459,6 +475,9 @@ func (vmaSetFunctions) Merge(ar1 hostarch.AddrRange, vma1 vma, ar2 hostarch.Addr\n}\nif vma2.id != nil {\n+ // This DecRef() will never be the final ref, since the vma1 is\n+ // currently holding a ref to the same mapping identity. Thus, we don't\n+ // need to worry about whether we're in a mm.mappingMu critical section.\nvma2.id.DecRef(context.Background())\n}\nreturn vma1, true\n"
}
] | Go | Apache License 2.0 | google/gvisor | Drop MappingIdentity ref outside mm.mappingMu critical section.
Otherwise we get circular locking with various filesystem locks if the
dropped ref is the final ref. Mapping identities are typically file
descriptions on various filesystems, which in turn call mm functions
under the respective filesystem locks.
PiperOrigin-RevId: 442919016 |
259,907 | 21.04.2022 11:25:23 | 25,200 | 7bacbb9797dc5bb1c707bfaeef8447d91a27bec9 | Update runtime tests documentation with new versions. | [
{
"change_type": "MODIFY",
"old_path": "test/runtimes/README.md",
"new_path": "test/runtimes/README.md",
"diff": "@@ -27,23 +27,23 @@ The following `make` targets will run an entire runtime test suite locally.\nNote: java runtime test take 1+ hours with 16 cores.\nLanguage | Version | Running the test suite\n--------- | ------- | ---------------------------------\n-Go | 1.12 | `make go1.12-runtime-tests`\n-Java | 11 | `make java11-runtime-tests`\n-NodeJS | 12.4.0 | `make nodejs12.4.0-runtime-tests`\n-Php | 7.3.6 | `make php7.3.6-runtime-tests`\n-Python | 3.7.3 | `make python3.7.3-runtime-tests`\n+-------- | ------- | ----------------------------------\n+Go | 1.16 | `make go1.16-runtime-tests`\n+Java | 17 | `make java17-runtime-tests`\n+NodeJS | 16.13.2 | `make nodejs16.13.2-runtime-tests`\n+Php | 8.1.1 | `make php8.1.1-runtime-tests`\n+Python | 3.10.2 | `make python3.10.2-runtime-tests`\nTo run runtime tests individually from a given runtime, you must build or\ndownload the language image and call Docker directly with the test arguments.\nLanguage | Version | Download Image | Run Test(s)\n--------- | ------- | --------------------------------- | -----------\n-Go | 1.12 | `make load-runtimes_go1.12` | If the test name ends with `.go`, it is an on-disk test: <br> `docker run --runtime=runsc -it gvisor.dev/images/runtimes/go1.12 ( cd /usr/local/go/test ; go run run.go -v -- <TEST_NAME>... )` <br> Otherwise it is a tool test: <br> `docker run --runtime=runsc -it gvisor.dev/images/runtimes/go1.12 go tool dist test -v -no-rebuild ^TEST1$\\|^TEST2$...`\n-Java | 11 | `make load-runtimes_java11` | `docker run --runtime=runsc -it gvisor.dev/images/runtimes/java11 jtreg -agentvm -dir:/root/test/jdk -noreport -timeoutFactor:20 -verbose:summary <TEST_NAME>...`\n-NodeJS | 12.4.0 | `make load-runtimes_nodejs12.4.0` | `docker run --runtime=runsc -it gvisor.dev/images/runtimes/nodejs12.4.0 python tools/test.py --timeout=180 <TEST_NAME>...`\n-Php | 7.3.6 | `make load-runtimes_php7.3.6` | `docker run --runtime=runsc -it gvisor.dev/images/runtimes/php7.3.6 make test \"TESTS=<TEST_NAME>...\"`\n-Python | 3.7.3 | `make load-runtimes_python3.7.3` | `docker run --runtime=runsc -it gvisor.dev/images/runtimes/python3.7.3 ./python -m test <TEST_NAME>...`\n+-------- | ------- | ---------------------------------- | -----------\n+Go | 1.16 | `make load-runtimes_go1.16` | If the test name ends with `.go`, it is an on-disk test: <br> `docker run --runtime=runsc -it gvisor.dev/images/runtimes/go1.16 ( cd /usr/local/go/test ; go run run.go -v -- <TEST_NAME>... )` <br> Otherwise it is a tool test: <br> `docker run --runtime=runsc -it gvisor.dev/images/runtimes/go1.16 go tool dist test -v -no-rebuild ^TEST1$\\|^TEST2$...`\n+Java | 17 | `make load-runtimes_java17` | `docker run --runtime=runsc -it gvisor.dev/images/runtimes/java17 jtreg -agentvm -dir:/root/test/jdk -noreport -timeoutFactor:20 -verbose:summary <TEST_NAME>...`\n+NodeJS | 16.13.2 | `make load-runtimes_nodejs16.13.2` | `docker run --runtime=runsc -it gvisor.dev/images/runtimes/nodejs16.13.2 python tools/test.py --timeout=180 <TEST_NAME>...`\n+Php | 8.1.1 | `make load-runtimes_php8.1.1` | `docker run --runtime=runsc -it gvisor.dev/images/runtimes/php8.1.1 make test \"TESTS=<TEST_NAME>...\"`\n+Python | 3.10.2 | `make load-runtimes_python3.10.2` | `docker run --runtime=runsc -it gvisor.dev/images/runtimes/python3.10.2 ./python -m test <TEST_NAME>...`\n### Clean Up\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update runtime tests documentation with new versions.
PiperOrigin-RevId: 443431724 |
259,891 | 21.04.2022 12:30:20 | 25,200 | efb3b7c7e861815271d91821e463d57eba3d59d8 | fix nogo errors from checker SA4006 | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/benchmark_test.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/benchmark_test.go",
"diff": "@@ -230,7 +230,6 @@ func BenchmarkVFS2TmpfsStat(b *testing.B) {\nMode: 0644,\n})\nvd.DecRef(ctx)\n- vd = vfs.VirtualDentry{}\nif err != nil {\nb.Fatalf(\"failed to create file %q: %v\", filename, err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4_test.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4_test.go",
"diff": "@@ -2756,7 +2756,7 @@ func TestReceiveFragments(t *testing.T) {\n// Check IPv4 header in packet delivered by raw endpoint.\nbuf.Reset()\n- result, err = epRaw.Read(&buf, tcpip.ReadOptions{})\n+ _, err = epRaw.Read(&buf, tcpip.ReadOptions{})\nif err != nil {\nt.Fatalf(\"(i=%d) epRaw.Read: %s\", i, err)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | fix nogo errors from checker SA4006
PiperOrigin-RevId: 443448448 |
259,992 | 22.04.2022 09:50:53 | 25,200 | 2a238b23e7c2440110f436619b960ce77cefa04e | Remote checker
Add a generic checker that serializes Points protos to a remote process.
More details here:
Updates | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "examples/seccheck/BUILD",
"diff": "+load(\"//tools:defs.bzl\", \"cc_binary\")\n+\n+package(licenses = [\"notice\"])\n+\n+cc_binary(\n+ name = \"server_cc\",\n+ srcs = [\"server.cc\"],\n+ visibility = [\"//:sandbox\"],\n+ deps = [\n+ # any_cc_proto placeholder,\n+ \"//pkg/sentry/seccheck/points:points_cc_proto\",\n+ \"@com_google_absl//absl/strings\",\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "examples/seccheck/server.cc",
"diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <err.h>\n+#include <pthread.h>\n+#include <stdarg.h>\n+#include <stdio.h>\n+#include <sys/epoll.h>\n+#include <sys/ioctl.h>\n+#include <sys/socket.h>\n+#include <sys/un.h>\n+#include <unistd.h>\n+\n+#include <array>\n+#include <string>\n+#include <vector>\n+\n+#include \"google/protobuf/any.pb.h\"\n+#include \"absl/strings/string_view.h\"\n+#include \"pkg/sentry/seccheck/points/sentry.pb.h\"\n+\n+typedef std::function<void(const google::protobuf::Any& any)> Callback;\n+\n+constexpr size_t prefixLen = sizeof(\"type.googleapis.com/\") - 1;\n+constexpr size_t maxEventSize = 300 * 1024;\n+\n+bool quiet = false;\n+\n+#pragma pack(push, 1)\n+struct header {\n+ uint16_t header_size;\n+ uint32_t dropped_count;\n+};\n+#pragma pack(pop)\n+\n+void log(const char* fmt, ...) {\n+ if (!quiet) {\n+ va_list ap;\n+ va_start(ap, fmt);\n+ vprintf(fmt, ap);\n+ va_end(ap);\n+ }\n+}\n+\n+template <class T>\n+void unpack(const google::protobuf::Any& any) {\n+ T evt;\n+ if (!any.UnpackTo(&evt)) {\n+ err(1, \"UnpackTo(): %s\", any.DebugString().c_str());\n+ }\n+ auto name = any.type_url().substr(prefixLen);\n+ log(\"%.*s => %s\\n\", static_cast<int>(name.size()), name.data(),\n+ evt.ShortDebugString().c_str());\n+}\n+\n+std::map<std::string, Callback> dispatchers = {\n+ {\"gvisor.sentry.CloneInfo\", unpack<::gvisor::sentry::CloneInfo>},\n+ {\"gvisor.sentry.ExecveInfo\", unpack<::gvisor::sentry::ExecveInfo>},\n+ {\"gvisor.sentry.ExitNotifyParentInfo\",\n+ unpack<::gvisor::sentry::ExitNotifyParentInfo>},\n+};\n+\n+void unpack(const absl::string_view buf) {\n+ const header* hdr = reinterpret_cast<const header*>(&buf[0]);\n+ size_t payload_size = buf.size() - hdr->header_size;\n+ if (payload_size <= 0) {\n+ printf(\"Header size (%u) is larger than message %lu\\n\", hdr->header_size,\n+ buf.size());\n+ return;\n+ }\n+\n+ auto proto = buf.substr(hdr->header_size);\n+ if (proto.size() < payload_size) {\n+ printf(\"Message was truncated, size: %lu, expected: %zu\\n\", proto.size(),\n+ payload_size);\n+ return;\n+ }\n+\n+ google::protobuf::Any any;\n+ if (!any.ParseFromArray(proto.data(), proto.size())) {\n+ err(1, \"invalid proto message\");\n+ }\n+\n+ auto url = any.type_url();\n+ if (url.size() <= prefixLen) {\n+ printf(\"Invalid URL %s\\n\", any.type_url().data());\n+ return;\n+ }\n+ const std::string name(url.substr(prefixLen));\n+ Callback cb = dispatchers[name];\n+ if (cb == nullptr) {\n+ printf(\"No callback registered for %s. Skipping it...\\n\", name.c_str());\n+ } else {\n+ cb(any);\n+ }\n+}\n+\n+void* pollLoop(void* ptr) {\n+ const int poll_fd = *reinterpret_cast<int*>(&ptr);\n+ for (;;) {\n+ epoll_event evts[64];\n+ int nfds = epoll_wait(poll_fd, evts, 64, -1);\n+ if (nfds < 0) {\n+ if (errno == EINTR) {\n+ continue;\n+ }\n+ err(1, \"epoll_wait\");\n+ }\n+\n+ for (int i = 0; i < nfds; ++i) {\n+ if (evts[i].events & EPOLLIN) {\n+ int client = evts[i].data.fd;\n+ std::array<char, maxEventSize> buf;\n+ int bytes = read(client, buf.data(), buf.size());\n+ if (bytes < 0) {\n+ err(1, \"read\");\n+ } else if (bytes > 0) {\n+ unpack(absl::string_view(buf.data(), bytes));\n+ }\n+ }\n+ if ((evts[i].events & (EPOLLRDHUP | EPOLLHUP)) != 0) {\n+ int client = evts[i].data.fd;\n+ close(client);\n+ printf(\"Connection closed\\n\");\n+ }\n+ if (evts[i].events & EPOLLERR) {\n+ printf(\"error\\n\");\n+ }\n+ }\n+ }\n+}\n+\n+void startPollThread(int poll_fd) {\n+ pthread_t thread;\n+ if (pthread_create(&thread, nullptr, pollLoop,\n+ reinterpret_cast<void*>(poll_fd)) != 0) {\n+ err(1, \"pthread_create\");\n+ }\n+ pthread_detach(thread);\n+}\n+\n+extern \"C\" int main(int argc, char** argv) {\n+ for (int c = 0; (c = getopt(argc, argv, \"q\")) != -1;) {\n+ switch (c) {\n+ case 'q':\n+ quiet = true;\n+ break;\n+ default:\n+ exit(1);\n+ }\n+ }\n+\n+ if (!quiet) {\n+ setbuf(stdout, NULL);\n+ setbuf(stderr, NULL);\n+ }\n+ std::string path(\"/tmp/gvisor_events.sock\");\n+ if (optind < argc) {\n+ path = argv[optind];\n+ }\n+ if (path.empty()) {\n+ err(1, \"empty file name\");\n+ }\n+ printf(\"Socket address %s\\n\", path.c_str());\n+ unlink(path.c_str());\n+\n+ int sock = socket(AF_UNIX, SOCK_SEQPACKET, 0);\n+ if (sock < 0) {\n+ err(1, \"socket\");\n+ }\n+\n+ struct sockaddr_un addr;\n+ addr.sun_family = AF_UNIX;\n+ strncpy(addr.sun_path, path.c_str(), path.size() + 1);\n+ if (bind(sock, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr))) {\n+ err(1, \"bind\");\n+ }\n+ if (listen(sock, 5) < 0) {\n+ err(1, \"listen\");\n+ }\n+\n+ int epoll_fd = epoll_create(1);\n+ if (epoll_fd < 0) {\n+ err(1, \"epoll_create\");\n+ }\n+ startPollThread(epoll_fd);\n+\n+ for (;;) {\n+ int client = accept(sock, nullptr, nullptr);\n+ if (client < 0) {\n+ if (errno == EINTR) {\n+ continue;\n+ }\n+ err(1, \"accept\");\n+ }\n+ printf(\"Connection accepted\\n\");\n+\n+ struct epoll_event evt;\n+ evt.data.fd = client;\n+ evt.events = EPOLLIN;\n+ if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client, &evt) < 0) {\n+ err(1, \"epoll_ctl(ADD)\");\n+ }\n+ }\n+\n+ close(sock);\n+ unlink(path.c_str());\n+\n+ return 0;\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/seccheck/checkers/remote/BUILD",
"diff": "+load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_library(\n+ name = \"remote\",\n+ srcs = [\"remote.go\"],\n+ marshal = True,\n+ visibility = [\"//:sandbox\"],\n+ deps = [\n+ \"//pkg/cleanup\",\n+ \"//pkg/context\",\n+ \"//pkg/fd\",\n+ \"//pkg/log\",\n+ \"//pkg/sentry/seccheck\",\n+ \"//pkg/sentry/seccheck/points:points_go_proto\",\n+ \"@org_golang_google_protobuf//proto:go_default_library\",\n+ \"@org_golang_google_protobuf//types/known/anypb:go_default_library\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n+ ],\n+)\n+\n+go_test(\n+ name = \"remote_test\",\n+ size = \"small\",\n+ srcs = [\"remote_test.go\"],\n+ data = [\n+ \"//examples/seccheck:server_cc\",\n+ ],\n+ library = \":remote\",\n+ deps = [\n+ \"//pkg/cleanup\",\n+ \"//pkg/fd\",\n+ \"//pkg/sentry/seccheck\",\n+ \"//pkg/sentry/seccheck/points:points_go_proto\",\n+ \"//pkg/sync\",\n+ \"//pkg/test/testutil\",\n+ \"@com_github_cenkalti_backoff//:go_default_library\",\n+ \"@org_golang_google_protobuf//proto:go_default_library\",\n+ \"@org_golang_google_protobuf//types/known/anypb:go_default_library\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/seccheck/checkers/remote/remote.go",
"diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// Package remote defines a seccheck.Checker that serializes points to a remote\n+// process. Points are serialized using the protobuf format, asynchronously.\n+package remote\n+\n+import (\n+ \"fmt\"\n+ \"os\"\n+\n+ \"gvisor.dev/gvisor/pkg/log\"\n+\n+ \"golang.org/x/sys/unix\"\n+ \"google.golang.org/protobuf/proto\"\n+ \"gvisor.dev/gvisor/pkg/cleanup\"\n+ \"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/fd\"\n+ \"gvisor.dev/gvisor/pkg/sentry/seccheck\"\n+\n+ \"google.golang.org/protobuf/types/known/anypb\"\n+ pb \"gvisor.dev/gvisor/pkg/sentry/seccheck/points/points_go_proto\"\n+)\n+\n+// Remote sends a serialized point to a remote process asynchronously over a\n+// SOCK_SEQPACKET Unix-domain socket. Each message corresponds to a single\n+// serialized point proto, preceded by a standard header. If the point cannot\n+// be sent, e.g. buffer full, the point is dropped on the floor to avoid\n+// delaying/hanging indefinitely the application.\n+type Remote struct {\n+ seccheck.CheckerDefaults\n+\n+ endpoint *fd.FD\n+}\n+\n+var _ seccheck.Checker = (*Remote)(nil)\n+\n+func setup(path string) (*os.File, error) {\n+ log.Debugf(\"Remote sink connecting to %q\", path)\n+ socket, err := unix.Socket(unix.AF_UNIX, unix.SOCK_SEQPACKET, 0)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"socket(AF_UNIX, SOCK_SEQPACKET, 0): %w\", err)\n+ }\n+ f := os.NewFile(uintptr(socket), path)\n+ cu := cleanup.Make(func() {\n+ _ = f.Close()\n+ })\n+ defer cu.Clean()\n+\n+ addr := unix.SockaddrUnix{Name: path}\n+ if err := unix.Connect(int(f.Fd()), &addr); err != nil {\n+ return nil, fmt.Errorf(\"connect(%q): %w\", path, err)\n+ }\n+ cu.Release()\n+ return f, nil\n+}\n+\n+// New creates a new Remote checker.\n+func New(_ map[string]interface{}, endpoint *fd.FD) (seccheck.Checker, error) {\n+ if endpoint == nil {\n+ return nil, fmt.Errorf(\"remote sink requires an endpoint\")\n+ }\n+ // TODO(gvisor.dev/issue/4805): perform version handshake with remote:\n+ // 1. sentry and remote exchange versions\n+ // 2. sentry continues if remote >= min(sentry)\n+ // 3. remote continues if sentry >= min(remote).\n+ // min() being the minimal supported version. Let's say current sentry\n+ // supports batching but remote doesn't, sentry can chose to not batch or\n+ // refuse the connection.\n+ return &Remote{endpoint: endpoint}, nil\n+}\n+\n+// Header is used to describe the message being sent to the remote process.\n+//\n+// +marshal\n+type Header struct {\n+ // HeaderSize is the size of the header in bytes. The payload comes\n+ // immediatelly after the header. The length is needed to allow the header to\n+ // expand in the future without breaking remotes that do not yet understand\n+ // the new fields.\n+ HeaderSize uint16\n+ _ uint16\n+ // DroppedCount is the number of points that failed to be written and had to\n+ // be dropped. It wraps around after max(uint32).\n+ DroppedCount uint32\n+}\n+\n+// headerStructSize size of header struct in bytes.\n+const headerStructSize = 8\n+\n+// TODO(gvisor.dev/issue/4805) Any requires writing the full type URL to the\n+// message. We're not memory bandwidth bound, but having an enum event type in\n+// the header to identify the proto type would reduce message size and speed\n+// up event dispatch in the consumer.\n+func (r *Remote) writeAny(any *anypb.Any) error {\n+ out, err := proto.Marshal(any)\n+ if err != nil {\n+ return err\n+ }\n+ hdr := Header{\n+ HeaderSize: uint16(headerStructSize),\n+ }\n+ var hdrOut [headerStructSize]byte\n+ hdr.MarshalUnsafe(hdrOut[:])\n+\n+ // TODO(gvisor.dev/issue/4805): Change to non-blocking write. Count as dropped\n+ // if write fails.\n+ _, err = unix.Writev(r.endpoint.FD(), [][]byte{hdrOut[:], out})\n+ return err\n+}\n+\n+func (r *Remote) write(msg proto.Message) {\n+ any, err := anypb.New(msg)\n+ if err != nil {\n+ log.Debugf(\"anypd.New(%+v): %v\", msg, err)\n+ return\n+ }\n+ if err := r.writeAny(any); err != nil {\n+ log.Debugf(\"writeAny(%+v): %v\", any, err)\n+ return\n+ }\n+ return\n+}\n+\n+// Clone implements seccheck.Checker.\n+func (r *Remote) Clone(_ context.Context, _ seccheck.FieldSet, info *pb.CloneInfo) error {\n+ r.write(info)\n+ return nil\n+}\n+\n+// Execve implements seccheck.Checker.\n+func (r *Remote) Execve(_ context.Context, _ seccheck.FieldSet, info *pb.ExecveInfo) error {\n+ r.write(info)\n+ return nil\n+}\n+\n+// ExitNotifyParent implements seccheck.Checker.\n+func (r *Remote) ExitNotifyParent(_ context.Context, _ seccheck.FieldSet, info *pb.ExitNotifyParentInfo) error {\n+ r.write(info)\n+ return nil\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/seccheck/checkers/remote/remote_test.go",
"diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package remote\n+\n+import (\n+ \"bytes\"\n+ \"fmt\"\n+ \"io/ioutil\"\n+ \"os\"\n+ \"os/exec\"\n+ \"path/filepath\"\n+ \"strings\"\n+ \"testing\"\n+ \"time\"\n+\n+ \"github.com/cenkalti/backoff\"\n+ \"golang.org/x/sys/unix\"\n+ \"google.golang.org/protobuf/proto\"\n+ \"google.golang.org/protobuf/types/known/anypb\"\n+ \"gvisor.dev/gvisor/pkg/cleanup\"\n+ \"gvisor.dev/gvisor/pkg/fd\"\n+ \"gvisor.dev/gvisor/pkg/sentry/seccheck\"\n+ pb \"gvisor.dev/gvisor/pkg/sentry/seccheck/points/points_go_proto\"\n+ \"gvisor.dev/gvisor/pkg/sync\"\n+ \"gvisor.dev/gvisor/pkg/test/testutil\"\n+)\n+\n+func waitForFile(path string) error {\n+ return testutil.Poll(func() error {\n+ if _, err := os.Stat(path); err != nil {\n+ if os.IsNotExist(err) {\n+ return err\n+ }\n+ return &backoff.PermanentError{Err: err}\n+ }\n+ return nil\n+ }, 5*time.Second)\n+}\n+\n+type exampleServer struct {\n+ path string\n+ cmd *exec.Cmd\n+ out bytes.Buffer\n+}\n+\n+func newExampleServer(quiet bool) (*exampleServer, error) {\n+ exe, err := testutil.FindFile(\"examples/seccheck/server_cc\")\n+ if err != nil {\n+ return nil, fmt.Errorf(\"error finding server_cc: %v\", err)\n+ }\n+\n+ dir, err := os.MkdirTemp(os.TempDir(), \"remote\")\n+ if err != nil {\n+ return nil, fmt.Errorf(\"Setup(%q): %v\", dir, err)\n+ }\n+\n+ server := &exampleServer{path: filepath.Join(dir, \"remote.sock\")}\n+ server.cmd = exec.Command(exe, server.path)\n+ if quiet {\n+ server.cmd.Args = append(server.cmd.Args, \"-q\")\n+ }\n+ server.cmd.Stdout = &server.out\n+ server.cmd.Stderr = &server.out\n+ if err := server.cmd.Start(); err != nil {\n+ os.RemoveAll(dir)\n+ return nil, fmt.Errorf(\"error running %q: %v\", exe, err)\n+ }\n+\n+ if err := waitForFile(server.path); err != nil {\n+ server.stop()\n+ return nil, fmt.Errorf(\"error waiting for server file %q: %w\", server.path, err)\n+ }\n+ return server, nil\n+}\n+\n+func (s *exampleServer) stop() {\n+ _ = s.cmd.Process.Kill()\n+ _ = s.cmd.Wait()\n+ _ = os.Remove(s.path)\n+}\n+\n+type server struct {\n+ path string\n+ fd *fd.FD\n+ stopCh chan struct{}\n+\n+ mu sync.Mutex\n+ // +checklocks:mu\n+ points []*anypb.Any\n+}\n+\n+func newServer() (*server, error) {\n+ dir, err := ioutil.TempDir(os.TempDir(), \"remote\")\n+ if err != nil {\n+ return nil, err\n+ }\n+ server, err := newServerPath(filepath.Join(dir, \"remote.sock\"))\n+ if err != nil {\n+ _ = os.RemoveAll(dir)\n+ return nil, err\n+ }\n+ return server, nil\n+}\n+\n+func newServerPath(path string) (*server, error) {\n+ socket, err := unix.Socket(unix.AF_UNIX, unix.SOCK_SEQPACKET, 0)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"socket(AF_UNIX, SOCK_SEQPACKET, 0): %w\", err)\n+ }\n+ cu := cleanup.Make(func() {\n+ _ = unix.Close(socket)\n+ })\n+ defer cu.Clean()\n+\n+ sa := &unix.SockaddrUnix{Name: path}\n+ if err := unix.Bind(socket, sa); err != nil {\n+ return nil, fmt.Errorf(\"bind(%q): %w\", path, err)\n+ }\n+ if err := unix.Listen(socket, 5); err != nil {\n+ return nil, fmt.Errorf(\"listen(): %w\", err)\n+ }\n+\n+ server := &server{\n+ path: path,\n+ fd: fd.New(socket),\n+ stopCh: make(chan struct{}),\n+ }\n+ go server.run()\n+ cu.Release()\n+ return server, nil\n+}\n+\n+func (s *server) run() {\n+ defer func() {\n+ s.stopCh <- struct{}{}\n+ }()\n+ for {\n+ client, _, err := unix.Accept(s.fd.FD())\n+ if err != nil {\n+ panic(err)\n+ }\n+ go s.handleClient(client)\n+ }\n+}\n+\n+func (s *server) handleClient(client int) {\n+ defer unix.Close(client)\n+\n+ var buf = make([]byte, 1024*1024)\n+ for {\n+ read, err := unix.Read(client, buf)\n+ if err != nil {\n+ return\n+ }\n+ if read == 0 {\n+ return\n+ }\n+ if read <= headerStructSize {\n+ panic(\"invalid message\")\n+ }\n+ hdr := Header{}\n+ hdr.UnmarshalUnsafe(buf[0:headerStructSize])\n+ msg := &anypb.Any{}\n+ if err := proto.Unmarshal(buf[hdr.HeaderSize:read], msg); err != nil {\n+ panic(\"invalid proto\")\n+ }\n+ s.mu.Lock()\n+ s.points = append(s.points, msg)\n+ s.mu.Unlock()\n+ }\n+}\n+\n+func (s *server) count() int {\n+ s.mu.Lock()\n+ defer s.mu.Unlock()\n+ return len(s.points)\n+}\n+\n+func (s *server) getPoints() []*anypb.Any {\n+ s.mu.Lock()\n+ defer s.mu.Unlock()\n+ cpy := make([]*anypb.Any, len(s.points))\n+ copy(cpy, s.points)\n+ return cpy\n+}\n+\n+func (s *server) wait() {\n+ <-s.stopCh\n+}\n+\n+func (s *server) close() {\n+ _ = s.fd.Close()\n+ _ = os.Remove(s.path)\n+}\n+\n+func TestBasic(t *testing.T) {\n+ server, err := newServer()\n+ if err != nil {\n+ t.Fatalf(\"newServer(): %v\", err)\n+ }\n+ defer server.close()\n+\n+ endpoint, err := setup(server.path)\n+ if err != nil {\n+ t.Fatalf(\"setup(): %v\", err)\n+ }\n+ endpointFD, err := fd.NewFromFile(endpoint)\n+ if err != nil {\n+ _ = endpoint.Close()\n+ t.Fatalf(\"NewFromFile(): %v\", err)\n+ }\n+ _ = endpoint.Close()\n+\n+ r, err := New(nil, endpointFD)\n+ if err != nil {\n+ t.Fatalf(\"New(): %v\", err)\n+ }\n+\n+ info := &pb.ExitNotifyParentInfo{ExitStatus: 123}\n+ if err := r.ExitNotifyParent(nil, seccheck.FieldSet{}, info); err != nil {\n+ t.Fatalf(\"ExitNotifyParent: %v\", err)\n+ }\n+\n+ testutil.Poll(func() error {\n+ if server.count() == 0 {\n+ return fmt.Errorf(\"waiting for points to arrive\")\n+ }\n+ return nil\n+ }, 5*time.Second)\n+ if want, got := 1, server.count(); want != got {\n+ t.Errorf(\"wrong number of points, want: %d, got: %d\", want, got)\n+ }\n+ any := server.getPoints()[0]\n+\n+ got := &pb.ExitNotifyParentInfo{}\n+ if err := any.UnmarshalTo(got); err != nil {\n+ t.Errorf(\"any.UnmarshallTo(ExitNotifyParentInfo): %v\", err)\n+ }\n+ if !proto.Equal(info, got) {\n+ t.Errorf(\"Received point is different, want: %+v, got: %+v\", info, got)\n+ }\n+}\n+\n+// Test that the example C++ server works. It's easier to test from here and\n+// also changes that can break it will likely originate here.\n+func TestExample(t *testing.T) {\n+ server, err := newExampleServer(false)\n+ if err != nil {\n+ t.Fatalf(\"newExampleServer(): %v\", err)\n+ }\n+ defer server.stop()\n+\n+ endpoint, err := setup(server.path)\n+ if err != nil {\n+ t.Fatalf(\"setup(): %v\", err)\n+ }\n+ endpointFD, err := fd.NewFromFile(endpoint)\n+ if err != nil {\n+ _ = endpoint.Close()\n+ t.Fatalf(\"NewFromFile(): %v\", err)\n+ }\n+ _ = endpoint.Close()\n+\n+ r, err := New(nil, endpointFD)\n+ if err != nil {\n+ t.Fatalf(\"New(): %v\", err)\n+ }\n+\n+ info := pb.ExitNotifyParentInfo{ExitStatus: 123}\n+ if err := r.ExitNotifyParent(nil, seccheck.FieldSet{}, &info); err != nil {\n+ t.Fatalf(\"ExitNotifyParent: %v\", err)\n+ }\n+ check := func() error {\n+ if got := server.out.String(); !strings.Contains(got, \"gvisor.sentry.ExitNotifyParentInfo => exit_status: 123\") {\n+ return fmt.Errorf(\"ExitNotifyParentInfo point didn't get to the server, out: %q\", got)\n+ }\n+ return nil\n+ }\n+ if err := testutil.Poll(check, time.Second); err != nil {\n+ t.Errorf(err.Error())\n+ }\n+}\n+\n+func BenchmarkSmall(t *testing.B) {\n+ // Run server in a separate process just to isolate it as much as possible.\n+ server, err := newExampleServer(false)\n+ if err != nil {\n+ t.Fatalf(\"newExampleServer(): %v\", err)\n+ }\n+ defer server.stop()\n+\n+ endpoint, err := setup(server.path)\n+ if err != nil {\n+ t.Fatalf(\"setup(): %v\", err)\n+ }\n+ endpointFD, err := fd.NewFromFile(endpoint)\n+ if err != nil {\n+ _ = endpoint.Close()\n+ t.Fatalf(\"NewFromFile(): %v\", err)\n+ }\n+ _ = endpoint.Close()\n+\n+ r, err := New(nil, endpointFD)\n+ if err != nil {\n+ t.Fatalf(\"New(): %v\", err)\n+ }\n+\n+ t.ResetTimer()\n+ t.RunParallel(func(sub *testing.PB) {\n+ for sub.Next() {\n+ info := pb.ExitNotifyParentInfo{ExitStatus: 123}\n+ if err := r.ExitNotifyParent(nil, seccheck.FieldSet{}, &info); err != nil {\n+ t.Fatalf(\"ExitNotifyParent: %v\", err)\n+ }\n+ }\n+ })\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remote checker
Add a generic checker that serializes Points protos to a remote process.
More details here: https://docs.google.com/document/d/1RQQKzeFpO-zOoBHZLA-tr5Ed_bvAOLDqgGgKhqUff2A/
Updates #4805
PiperOrigin-RevId: 443690622 |
259,951 | 22.04.2022 10:06:13 | 25,200 | 6d77aa52b8848008e36356124f7af9360b555f17 | Remove unnecessary IsForwardedPacket condition | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/packet_buffer.go",
"new_path": "pkg/tcpip/stack/packet_buffer.go",
"diff": "@@ -176,9 +176,7 @@ func NewPacketBuffer(opts PacketBufferOptions) *PacketBuffer {\nfor _, v := range opts.Data.Views() {\npk.buf.AppendOwned(v)\n}\n- if opts.IsForwardedPacket {\npk.NetworkPacketInfo.IsForwardedPacket = opts.IsForwardedPacket\n- }\npk.InitRefs()\nreturn pk\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove unnecessary IsForwardedPacket condition
PiperOrigin-RevId: 443694489 |
259,962 | 22.04.2022 11:51:07 | 25,200 | 96c9cf74f5eb339f522f0242144f2967be87b5b9 | Return error when handshake fails.
performHandshake should return the last error in case
the handshake fails. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/accept.go",
"new_path": "pkg/tcpip/transport/tcp/accept.go",
"diff": "@@ -324,6 +324,12 @@ func (l *listenContext) performHandshake(s *segment, opts header.TCPSynOptions,\nep.Close()\nep.notifyAborted()\nep.drainClosingSegmentQueue()\n+ err := ep.LastError()\n+ if err == nil {\n+ // If err was nil then return the best error we can to indicate\n+ // a connection failure.\n+ err = &tcpip.ErrConnectionAborted{}\n+ }\nreturn nil, err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/test/e2e/BUILD",
"new_path": "pkg/tcpip/transport/tcp/test/e2e/BUILD",
"diff": "@@ -77,7 +77,9 @@ go_test(\n\"//pkg/refs\",\n\"//pkg/refsvfs2\",\n\"//pkg/tcpip\",\n+ \"//pkg/tcpip/checker\",\n\"//pkg/tcpip/header\",\n+ \"//pkg/tcpip/seqnum\",\n\"//pkg/tcpip/transport/tcp\",\n\"//pkg/tcpip/transport/tcp/testing/context\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/test/e2e/forwarder_test.go",
"new_path": "pkg/tcpip/transport/tcp/test/e2e/forwarder_test.go",
"diff": "@@ -22,7 +22,9 @@ import (\n\"gvisor.dev/gvisor/pkg/refs\"\n\"gvisor.dev/gvisor/pkg/refsvfs2\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/checker\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/seqnum\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/tcp\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/tcp/test/e2e\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/tcp/testing/context\"\n@@ -106,6 +108,67 @@ func TestForwarderDoesNotRejectECNFlags(t *testing.T) {\n}\n}\n+func TestForwarderFailedConnect(t *testing.T) {\n+ const mtu = 1200\n+ c := context.New(t, mtu)\n+ defer c.Cleanup()\n+\n+ s := c.Stack()\n+ ch := make(chan tcpip.Error, 1)\n+ f := tcp.NewForwarder(s, 65536, 10, func(r *tcp.ForwarderRequest) {\n+ var err tcpip.Error\n+ c.EP, err = r.CreateEndpoint(&c.WQ)\n+ ch <- err\n+ close(ch)\n+ r.Complete(false)\n+ })\n+ s.SetTransportProtocolHandler(tcp.ProtocolNumber, f.HandlePacket)\n+\n+ // Initiate a connection that will be forwarded by the Forwarder.\n+ // Send a SYN request.\n+ iss := seqnum.Value(context.TestInitialSequenceNumber)\n+ c.SendPacket(nil, &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: context.StackPort,\n+ Flags: header.TCPFlagSyn,\n+ SeqNum: iss,\n+ RcvWnd: 30000,\n+ })\n+\n+ // Receive the SYN-ACK reply. Make sure MSS and other expected options\n+ // are present.\n+ b := c.GetPacket()\n+ tcp := header.TCP(header.IPv4(b).Payload())\n+ c.IRS = seqnum.Value(tcp.SequenceNumber())\n+\n+ tcpCheckers := []checker.TransportChecker{\n+ checker.SrcPort(context.StackPort),\n+ checker.DstPort(context.TestPort),\n+ checker.TCPFlags(header.TCPFlagAck | header.TCPFlagSyn),\n+ checker.TCPAckNum(uint32(iss) + 1),\n+ }\n+ checker.IPv4(t, b, checker.TCP(tcpCheckers...))\n+\n+ // Now send an active RST to abort the handshake.\n+ c.SendPacket(nil, &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: context.StackPort,\n+ Flags: header.TCPFlagRst,\n+ SeqNum: iss + 1,\n+ RcvWnd: 0,\n+ })\n+\n+ // Wait for connect to fail.\n+ select {\n+ case err := <-ch:\n+ if err == nil {\n+ t.Fatalf(\"endpoint creation should have failed\")\n+ }\n+ case <-time.After(2 * time.Second):\n+ t.Fatalf(\"Timed out waiting for connection to fail\")\n+ }\n+}\n+\nfunc TestMain(m *testing.M) {\nrefs.SetLeakMode(refs.LeaksPanic)\ncode := m.Run()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Return error when handshake fails.
performHandshake should return the last error in case
the handshake fails.
PiperOrigin-RevId: 443721651 |
259,982 | 22.04.2022 13:17:12 | 25,200 | 49ae54c01067e77f1b1cd80e65358bf12a526456 | Fixing memory allocations for tmpfs size.
Fixing partial write memory allocation.
Accounting for memory allocation in hard links.
Adding test cases to check for hard link memory allocation for the same. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go",
"diff": "@@ -800,25 +800,6 @@ func (fs *filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\nif err := vfsObj.PrepareDeleteDentry(mntns, &child.vfsd); err != nil {\nreturn err\n}\n- // Remove pages used if child being removed is a SymLink or Regular File.\n- switch impl := child.inode.impl.(type) {\n- case *symlink:\n- if len(impl.target) >= shortSymlinkLen {\n- if err := fs.updatePagesUsed(uint64(len(impl.target)), 0); err != nil {\n- vfsObj.AbortDeleteDentry(&child.vfsd)\n- return err\n- }\n- }\n- case *regularFile:\n- impl.inode.mu.Lock()\n- if err := fs.updatePagesUsed(impl.size.Load(), 0); err != nil {\n- impl.inode.mu.Unlock()\n- vfsObj.AbortDeleteDentry(&child.vfsd)\n- return err\n- }\n- impl.inode.mu.Unlock()\n- }\n-\n// Generate inotify events. Note that this must take place before the link\n// count of the child is decremented, or else the watches may be dropped\n// before these events are added.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go",
"diff": "@@ -443,7 +443,8 @@ func (fd *regularFileFD) pwrite(ctx context.Context, src usermem.IOSequence, off\n// Locking f.inode.mu is sufficient for reading f.size.\noffset = int64(f.size.RacyLoad())\n}\n- if end := offset + srclen; end < offset {\n+ end := offset + srclen\n+ if end < offset {\n// Overflow.\nreturn 0, offset, linuxerr.EINVAL\n}\n@@ -452,15 +453,18 @@ func (fd *regularFileFD) pwrite(ctx context.Context, src usermem.IOSequence, off\nif err != nil {\nreturn 0, offset, err\n}\n+ maybeSizeInc := false\nsrc = src.TakeFirst64(srclen)\n- reservedSize := f.size.Load() + uint64(srclen)\n- if err = f.inode.fs.updatePagesUsed(f.size.Load(), reservedSize); err != nil {\n+ if uint64(end) > f.size.Load() {\n+ maybeSizeInc = true\n+ if err = f.inode.fs.updatePagesUsed(f.size.Load(), uint64(end)); err != nil {\nreturn 0, 0, err\n}\n+ }\nrw := getRegularFileReadWriter(f, offset)\nn, err := src.CopyInTo(ctx, rw)\n- if unwritten := srclen - n; unwritten != 0 {\n- if err := f.inode.fs.updatePagesUsed(reservedSize, f.size.Load()); err != nil {\n+ if unwritten := srclen - n; maybeSizeInc && unwritten != 0 {\n+ if err := f.inode.fs.updatePagesUsed(uint64(end), f.size.Load()); err != nil {\nreturn 0, 0, err\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"diff": "@@ -528,12 +528,26 @@ func (i *inode) tryIncRef() bool {\nfunc (i *inode) decRef(ctx context.Context) {\ni.refs.DecRef(func() {\ni.watches.HandleDeletion(ctx)\n- if regFile, ok := i.impl.(*regularFile); ok {\n+ // Remove pages used if child being removed is a SymLink or Regular File.\n+ switch impl := i.impl.(type) {\n+ case *symlink:\n+ if len(impl.target) >= shortSymlinkLen {\n+ if err := i.fs.updatePagesUsed(uint64(len(impl.target)), 0); err != nil {\n+ panic(fmt.Sprintf(\"Encountered error: %v while accounting tmpfs size.\", err))\n+ }\n+ }\n+ case *regularFile:\n+ impl.inode.mu.Lock()\n+ if err := i.fs.updatePagesUsed(impl.size.Load(), 0); err != nil {\n+ panic(fmt.Sprintf(\"Encountered error: %v while accounting tmpfs size.\", err))\n+ }\n+ impl.inode.mu.Unlock()\n// Release memory used by regFile to store data. Since regFile is\n// no longer usable, we don't need to grab any locks or update any\n// metadata.\n- regFile.data.DropAll(regFile.memFile)\n+ impl.data.DropAll(impl.memFile)\n}\n+\n})\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/mount.cc",
"new_path": "test/syscalls/linux/mount.cc",
"diff": "@@ -582,6 +582,38 @@ TEST(MountTest, TmpfsSymlinkAllocCheck) {\nEXPECT_THAT(symlink(target.c_str(), pathname.c_str()), SyscallSucceeds());\n}\n+// Tests memory allocation for Hard Links is not double allocated.\n+TEST(MountTest, TmpfsHardLinkAllocCheck) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN)));\n+ auto const dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ auto tmpfs_size_opt = absl::StrCat(\"size=\", kPageSize);\n+ auto const mount = ASSERT_NO_ERRNO_AND_VALUE(\n+ Mount(\"\", dir.path(), \"tmpfs\", 0, tmpfs_size_opt, 0));\n+ const std::string fileOne = JoinPath(dir.path(), \"foo1\");\n+ const std::string fileTwo = JoinPath(dir.path(), \"foo2\");\n+ auto const fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(fileOne, O_CREAT | O_RDWR, 0777));\n+ EXPECT_THAT(link(fileOne.c_str(), fileTwo.c_str()), SyscallSucceeds());\n+\n+ // Check that it starts at size zero.\n+ struct stat buf;\n+ ASSERT_THAT(fstat(fd.get(), &buf), SyscallSucceeds());\n+ EXPECT_EQ(buf.st_size, 0);\n+\n+ // Grow to 1 Page Size.\n+ ASSERT_THAT(fallocate(fd.get(), 0, 0, kPageSize), SyscallSucceeds());\n+ ASSERT_THAT(fstat(fd.get(), &buf), SyscallSucceeds());\n+ EXPECT_EQ(buf.st_size, kPageSize);\n+\n+ // Grow to size beyond tmpfs allocated bytes.\n+ ASSERT_THAT(fallocate(fd.get(), 0, 0, kPageSize + 1),\n+ SyscallFailsWithErrno(ENOSPC));\n+ ASSERT_THAT(fstat(fd.get(), &buf), SyscallSucceeds());\n+ EXPECT_EQ(buf.st_size, kPageSize);\n+ EXPECT_THAT(unlink(fileTwo.c_str()), SyscallSucceeds());\n+ EXPECT_THAT(unlink(fileOne.c_str()), SyscallSucceeds());\n+}\n+\n} // namespace\n} // namespace testing\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fixing memory allocations for tmpfs size.
Fixing partial write memory allocation.
Accounting for memory allocation in hard links.
Adding test cases to check for hard link memory allocation for the same.
PiperOrigin-RevId: 443742013 |
259,853 | 22.04.2022 15:33:42 | 25,200 | 772e9a4e9b7beac817c402cf05ef0cb9e3957366 | kvm: update a region length when it is extended to the left | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/physical_map.go",
"new_path": "pkg/sentry/platform/kvm/physical_map.go",
"diff": "@@ -115,6 +115,7 @@ func fillAddressSpace() (excludedRegions []region) {\nfor i := range excludedRegions {\nif excludedRegions[i].virtual == addr+current {\nexcludedRegions[i].virtual = addr\n+ excludedRegions[i].length += current\naddr = 0\nbreak\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | kvm: update a region length when it is extended to the left
PiperOrigin-RevId: 443774203 |
259,907 | 26.04.2022 13:08:42 | 25,200 | 68f30cbc5eacf57321dec85811e3be9cf6f28352 | Add test for using two epoll instances to track an FD using EPOLLONESHOT.
The underlying epoll bug was fixed in ("epoll: notify waiters if
ReadEvents adds events"). This adds a regression test for that. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -608,9 +608,11 @@ cc_binary(\n\"//test/util:epoll_util\",\n\"//test/util:eventfd_util\",\n\"//test/util:file_descriptor\",\n+ \"@com_google_absl//absl/synchronization\",\ngtest,\n\"//test/util:posix_error\",\n\"//test/util:signal_util\",\n+ \"//test/util:socket_util\",\n\"//test/util:temp_path\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/epoll.cc",
"new_path": "test/syscalls/linux/epoll.cc",
"diff": "#include <unistd.h>\n#include \"gtest/gtest.h\"\n+#include \"absl/synchronization/mutex.h\"\n#include \"test/util/epoll_util.h\"\n#include \"test/util/eventfd_util.h\"\n#include \"test/util/file_descriptor.h\"\n#include \"test/util/posix_error.h\"\n#include \"test/util/signal_util.h\"\n+#include \"test/util/socket_util.h\"\n#include \"test/util/temp_path.h\"\n#include \"test/util/test_util.h\"\n#include \"test/util/thread_util.h\"\n@@ -351,6 +353,98 @@ TEST(EpollTest, Oneshot) {\nSyscallSucceedsWithValue(0));\n}\n+// NOTE(b/228468030): This test aims to test epoll functionality when 2 epoll\n+// instances are used to track the same FD using EPOLLONESHOT.\n+TEST(EpollTest, DoubleEpollOneShot) {\n+ int sockets[2];\n+ ASSERT_THAT(socketpair(AF_UNIX, SOCK_STREAM, 0, sockets), SyscallSucceeds());\n+ auto epollfd1 = ASSERT_NO_ERRNO_AND_VALUE(NewEpollFD());\n+ auto epollfd2 = ASSERT_NO_ERRNO_AND_VALUE(NewEpollFD());\n+\n+ ASSERT_NO_ERRNO(RegisterEpollFD(epollfd1.get(), sockets[1],\n+ EPOLLIN | EPOLLONESHOT, kMagicConstant));\n+ ASSERT_NO_ERRNO(RegisterEpollFD(epollfd2.get(), sockets[1],\n+ EPOLLIN | EPOLLONESHOT, kMagicConstant));\n+\n+ const DisableSave ds; // May trigger spurious event.\n+\n+ constexpr char msg1[] = \"hello\";\n+ constexpr char msg2[] = \"world\";\n+ // For the purpose of this test, msg1 and msg2 should be equal in size.\n+ ASSERT_EQ(sizeof(msg1), sizeof(msg2));\n+ const auto msg_size = sizeof(msg1);\n+\n+ // Server and client here only communicate with `msg_size` sized messages.\n+ // When client sees msg2, it will shutdown. All other communication is msg1.\n+ const uint n = 1 << 14; // Arbitrary to trigger race.\n+ ScopedThread server([&sockets, &msg1, &msg2]() {\n+ char tmp[msg_size];\n+ for (uint i = 0; i < n; ++i) {\n+ // Read request.\n+ ASSERT_THAT(ReadFd(sockets[0], &tmp, sizeof(tmp)),\n+ SyscallSucceedsWithValue(sizeof(tmp)));\n+ EXPECT_EQ(strcmp(tmp, msg1), 0);\n+ // Respond to request.\n+ if (i < n - 2) {\n+ ASSERT_EQ(WriteFd(sockets[0], msg1, sizeof(msg1)), sizeof(msg1));\n+ } else {\n+ ASSERT_EQ(WriteFd(sockets[0], msg2, sizeof(msg2)), sizeof(msg2));\n+ }\n+ }\n+ });\n+\n+ // m is used to synchronize reads on sockets[1].\n+ absl::Mutex m;\n+\n+ auto clientFn = [&sockets, &msg1, &msg2, &m](FileDescriptor& epollfd) {\n+ char tmp[msg_size];\n+ bool rearm = false;\n+ while (true) {\n+ if (rearm) {\n+ // Rearm with EPOLLONESHOT.\n+ struct epoll_event event;\n+ event.events = EPOLLIN | EPOLLONESHOT;\n+ event.data.u64 = kMagicConstant;\n+ ASSERT_THAT(epoll_ctl(epollfd.get(), EPOLL_CTL_MOD, sockets[1], &event),\n+ SyscallSucceeds());\n+ }\n+\n+ // Make request.\n+ {\n+ absl::MutexLock lock(&m);\n+ ASSERT_EQ(WriteFd(sockets[1], msg1, sizeof(msg1)), sizeof(msg1));\n+ }\n+\n+ // Wait for response.\n+ struct epoll_event result[kFDsPerEpoll];\n+ ASSERT_THAT(\n+ RetryEINTR(epoll_wait)(epollfd.get(), result, kFDsPerEpoll, -1),\n+ SyscallSucceedsWithValue(1));\n+ EXPECT_EQ(result[0].data.u64, kMagicConstant);\n+ rearm = true;\n+\n+ // Read response.\n+ {\n+ absl::MutexLock lock(&m);\n+ ASSERT_THAT(ReadFd(sockets[1], &tmp, sizeof(tmp)),\n+ SyscallSucceedsWithValue(sizeof(tmp)));\n+ }\n+ if (strcmp(tmp, msg2) == 0) {\n+ break;\n+ }\n+ EXPECT_EQ(strcmp(tmp, msg1), 0);\n+ }\n+ };\n+\n+ ScopedThread client1([&epollfd1, &clientFn]() { clientFn(epollfd1); });\n+\n+ ScopedThread client2([&epollfd2, &clientFn]() { clientFn(epollfd2); });\n+\n+ server.Join();\n+ client1.Join();\n+ client2.Join();\n+}\n+\nTEST(EpollTest, EdgeTriggered) {\n// Test edge-triggered entry: make it edge-triggered, first wait should\n// return it, second one should time out, make it writable again, third wait\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add test for using two epoll instances to track an FD using EPOLLONESHOT.
The underlying epoll bug was fixed in fcd82c8ebf67 ("epoll: notify waiters if
ReadEvents adds events"). This adds a regression test for that.
PiperOrigin-RevId: 444645497 |
259,868 | 26.04.2022 13:33:59 | 25,200 | b5a59f96c8ece5ca47fed43b7fade4bd6d513777 | runsc: Ignore `EROFS` errors when setting up cgroups in `--rootless` mode.
This bypasses cgroup-related errors when running `runsc` in a container with
no permission to create its own cgroups. | [
{
"change_type": "MODIFY",
"old_path": "runsc/container/container.go",
"new_path": "runsc/container/container.go",
"diff": "@@ -1279,7 +1279,7 @@ func (c *Container) setupCgroupForSubcontainer(conf *config.Config, spec *specs.\nfunc cgroupInstall(conf *config.Config, cg cgroup.Cgroup, res *specs.LinuxResources) (cgroup.Cgroup, error) {\nif err := cg.Install(res); err != nil {\nswitch {\n- case errors.Is(err, unix.EACCES) && conf.Rootless:\n+ case (errors.Is(err, unix.EACCES) || errors.Is(err, unix.EROFS)) && conf.Rootless:\nlog.Warningf(\"Skipping cgroup configuration in rootless mode: %v\", err)\nreturn nil, nil\ndefault:\n"
}
] | Go | Apache License 2.0 | google/gvisor | runsc: Ignore `EROFS` errors when setting up cgroups in `--rootless` mode.
This bypasses cgroup-related errors when running `runsc` in a container with
no permission to create its own cgroups.
PiperOrigin-RevId: 444652251 |
259,982 | 26.04.2022 16:58:33 | 25,200 | ce91143bdc77ccdebf7aaae9ee8eb4843aa5f880 | Added integration tests for mounting tmpfs with size option enabled. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"diff": "@@ -202,7 +202,7 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nvar maxSizeInPages uint64\nif ok {\ndelete(mopts, \"size\")\n- maxSizeInBytes, err := strconv.ParseUint(maxSizeStr, 10, 64)\n+ maxSizeInBytes, err := parseSize(maxSizeStr)\nif err != nil {\nctx.Warningf(\"tmpfs.FilesystemType.GetFilesystem: invalid size: %q\", maxSizeStr)\nreturn nil, nil, linuxerr.EINVAL\n@@ -944,3 +944,33 @@ func (fd *fileDescription) RemoveXattr(ctx context.Context, name string) error {\nfunc (*fileDescription) Sync(context.Context) error {\nreturn nil\n}\n+\n+// parseSize converts size in string to an integer bytes.\n+// Supported suffixes in string are:K, M, G, T, P, E.\n+func parseSize(s string) (uint64, error) {\n+ suffix := s[len(s)-1]\n+ count := 1\n+ switch suffix {\n+ case 'e', 'E':\n+ count = count << 10\n+ fallthrough\n+ case 'p', 'P':\n+ count = count << 10\n+ fallthrough\n+ case 't', 'T':\n+ count = count << 10\n+ fallthrough\n+ case 'g', 'G':\n+ count = count << 10\n+ fallthrough\n+ case 'm', 'M':\n+ count = count << 10\n+ fallthrough\n+ case 'k', 'K':\n+ count = count << 10\n+ s = s[:len(s)-1]\n+ }\n+ bytes, err := strconv.ParseUint(s, 10, 64)\n+ bytes = bytes * uint64(count)\n+ return bytes, err\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs_test.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs_test.go",
"diff": "@@ -16,6 +16,7 @@ package tmpfs\nimport (\n\"fmt\"\n+ \"testing\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/atomicbitops\"\n@@ -155,3 +156,37 @@ func newPipeFD(ctx context.Context, mode linux.FileMode) (*vfs.FileDescription,\nreturn fd, cleanup, nil\n}\n+\n+func TestParseSize(t *testing.T) {\n+ var tests = []struct {\n+ s string\n+ want uint64\n+ wantError bool\n+ }{\n+ {\"500\", 500, false},\n+ {\"5k\", (5 * 1024), false},\n+ {\"5m\", (5 * 1024 * 1024), false},\n+ {\"5G\", (5 * 1024 * 1024 * 1024), false},\n+ {\"5t\", (5 * 1024 * 1024 * 1024 * 1024), false},\n+ {\"5P\", (5 * 1024 * 1024 * 1024 * 1024 * 1024), false},\n+ {\"5e\", (5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024), false},\n+ {\"5e3\", 0, true},\n+ }\n+ for _, tt := range tests {\n+ testname := fmt.Sprintf(\"%s\", tt.s)\n+ t.Run(testname, func(t *testing.T) {\n+ size, err := parseSize(tt.s)\n+ if tt.wantError && err == nil {\n+ t.Errorf(\"Invalid input: %v parsed\", tt.s)\n+ }\n+ if !tt.wantError {\n+ if err != nil {\n+ t.Errorf(\"Couldn't parse size, Error: %v\", err)\n+ }\n+ if size != tt.want {\n+ t.Errorf(\"got: %v, want %v\", size, tt.want)\n+ }\n+ }\n+ })\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/fs.go",
"new_path": "runsc/boot/fs.go",
"diff": "@@ -67,7 +67,7 @@ const (\n)\n// tmpfs has some extra supported options that we must pass through.\n-var tmpfsAllowedData = []string{\"mode\", \"uid\", \"gid\"}\n+var tmpfsAllowedData = []string{\"mode\", \"size\", \"uid\", \"gid\"}\nfunc addOverlay(ctx context.Context, lower *fs.Inode, name string, lowerFlags fs.MountSourceFlags) (*fs.Inode, error) {\n// Upper layer uses the same flags as lower, but it must be read-write.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/e2e/integration_test.go",
"new_path": "test/e2e/integration_test.go",
"diff": "@@ -911,3 +911,42 @@ func TestRevalidateSymlinkChain(t *testing.T) {\nt.Fatalf(\"Read wrong file, want: %q, got: %q\", want, got)\n}\n}\n+\n+// TestTmpMountWithSize checks when 'tmpfs' is mounted\n+// with size option the limit is not exceeded.\n+func TestTmpMountWithSize(t *testing.T) {\n+ ctx := context.Background()\n+ d := dockerutil.MakeContainer(ctx, t)\n+ defer d.CleanUp(ctx)\n+\n+ opts := dockerutil.RunOpts{\n+ Image: \"basic/alpine\",\n+ Mounts: []mount.Mount{\n+ {\n+ Type: mount.TypeTmpfs,\n+ Target: \"/tmp/foo\",\n+ TmpfsOptions: &mount.TmpfsOptions{\n+ SizeBytes: 4096,\n+ },\n+ },\n+ },\n+ }\n+ if err := d.Create(ctx, opts, \"sleep\", \"1000\"); err != nil {\n+ t.Fatalf(\"docker create failed: %v\", err)\n+ }\n+ if err := d.Start(ctx); err != nil {\n+ t.Fatalf(\"docker start failed: %v\", err)\n+ }\n+\n+ if _, err := d.Exec(ctx, dockerutil.ExecOpts{}, \"/bin/sh\", \"-c\", \"echo hello > /tmp/foo/test1.txt\"); err != nil {\n+ t.Fatalf(\"docker exec failed: %v\", err)\n+ }\n+ echoOutput, err := d.Exec(ctx, dockerutil.ExecOpts{}, \"/bin/sh\", \"-c\", \"echo world > /tmp/foo/test2.txt\")\n+ if err == nil {\n+ t.Fatalf(\"docker exec size check failed: %v\", err)\n+ }\n+ wantErr := \"No space left on device\"\n+ if !strings.Contains(echoOutput, wantErr) {\n+ t.Errorf(\"unexpected echo error:Expected: %v, Got: %v\", wantErr, echoOutput)\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Added integration tests for mounting tmpfs with size option enabled.
PiperOrigin-RevId: 444705540 |
259,891 | 27.04.2022 11:22:20 | 25,200 | 7124367b820889d0ac17eaf6fef2f595b6707ab9 | prohibit direct use of sync/atomic (u)int32 functions
Also adds the "// +checkalignedignore" escape hatch for packages to opt out of
checking.
See cl/439349432 for justification (https://github.com/google/gvisor/pull/7376). | [
{
"change_type": "MODIFY",
"old_path": "pkg/atomicbitops/atomicbitops.go",
"new_path": "pkg/atomicbitops/atomicbitops.go",
"diff": "//\n// All read-modify-write operations implemented by this package have\n// acquire-release memory ordering (like sync/atomic).\n+//\n+// +checkalignedignore\npackage atomicbitops\n// AndUint32 atomically applies bitwise AND operation to *addr with val.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sync/sync.go",
"new_path": "pkg/sync/sync.go",
"diff": "// license that can be found in the LICENSE file.\n// Package sync provides synchronization primitives.\n+//\n+// +checkalignedignore\npackage sync\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/checkaligned/checkaligned.go",
"new_path": "tools/checkaligned/checkaligned.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// Package checkaligned ensures that atomic (u)int64 operations happen\n+// Package checkaligned ensures that atomic (u)int operations happen\n// exclusively via the atomicbitops package.\n+//\n+// We support a \"// +checkalignedignore\" escape hatch in the package comment\n+// that disables checking throughout the package.\npackage checkaligned\nimport (\n\"fmt\"\n\"go/ast\"\n+ \"strings\"\n\"golang.org/x/tools/go/analysis\"\n)\n@@ -26,14 +30,14 @@ import (\n// Analyzer defines the entrypoint.\nvar Analyzer = &analysis.Analyzer{\nName: \"checkaligned\",\n- Doc: \"prohibits direct use of 64 bit atomic operations\",\n+ Doc: \"prohibits direct use of atomic int operations\",\nRun: run,\n}\n// blocklist lists prohibited identifiers in the atomic package.\n//\n-// TODO(b/228378998): We should do this for 32 bit values too. Can also further\n-// genericize this to ban other things we don't like (e.g. os.File).\n+// TODO(b/228378998): We can further genericize this to ban other things we\n+// don't like (e.g. os.File).\nvar blocklist = []string{\n\"AddInt64\",\n\"AddUint64\",\n@@ -45,13 +49,31 @@ var blocklist = []string{\n\"StoreUint64\",\n\"SwapInt64\",\n\"SwapUint64\",\n+\n+ \"AddInt32\",\n+ \"AddUint32\",\n+ \"CompareAndSwapInt32\",\n+ \"CompareAndSwapUint32\",\n+ \"LoadInt32\",\n+ \"LoadUint32\",\n+ \"StoreInt32\",\n+ \"StoreUint32\",\n+ \"SwapInt32\",\n+ \"SwapUint32\",\n}\nfunc run(pass *analysis.Pass) (interface{}, error) {\n- // atomicbitops uses 64 bit values safely.\n- if pass.Pkg.Name() == \"atomicbitops\" {\n+ // Check for the \"// +checkalignedignore\" escape hatch.\n+ for _, file := range pass.Files {\n+ if file.Doc == nil {\n+ continue\n+ }\n+ for _, comment := range file.Doc.List {\n+ if len(comment.Text) > 2 && strings.HasPrefix(comment.Text[2:], \" +checkalignedignore\") {\nreturn nil, nil\n}\n+ }\n+ }\nfor _, file := range pass.Files {\nast.Inspect(file, func(node ast.Node) bool {\n"
}
] | Go | Apache License 2.0 | google/gvisor | prohibit direct use of sync/atomic (u)int32 functions
Also adds the "// +checkalignedignore" escape hatch for packages to opt out of
checking.
See cl/439349432 for justification (https://github.com/google/gvisor/pull/7376).
PiperOrigin-RevId: 444918125 |
259,985 | 27.04.2022 14:03:59 | 25,200 | 5afe17a15d04cf16bd569ff9a9ee4699bbed81b8 | cgroupfs: Fix test race with task exit.
The PID controller isn't uncharged synchronously with task exit. The
test checks the PID is released after thread join, which races with
the task being reaped. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/cgroup.cc",
"new_path": "test/syscalls/linux/cgroup.cc",
"diff": "@@ -1214,7 +1214,8 @@ TEST(PIDsCgroup, LimitEnforced) {\nIsPosixErrorOkAndHolds(baseline + 1));\n// Exit the first thread and try create a thread again, which should succeed.\n- t1.Join();\n+ ASSERT_NO_ERRNO(child.PollControlFileForChangeAfter(\n+ \"pids.current\", absl::Seconds(30), [&t1]() { t1.Join(); }));\nASSERT_THAT(child.ReadIntegerControlFile(\"pids.current\"),\nIsPosixErrorOkAndHolds(baseline));\nNoopThreads t2(1);\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/cgroup_util.cc",
"new_path": "test/util/cgroup_util.cc",
"diff": "@@ -87,6 +87,12 @@ PosixErrorOr<absl::flat_hash_set<pid_t>> Cgroup::Tasks() const {\nPosixError Cgroup::PollControlFileForChange(absl::string_view name,\nabsl::Duration timeout) const {\n+ return PollControlFileForChangeAfter(name, timeout, []() {});\n+}\n+\n+PosixError Cgroup::PollControlFileForChangeAfter(\n+ absl::string_view name, absl::Duration timeout,\n+ std::function<void()> body) const {\nconst absl::Duration poll_interval = absl::Milliseconds(10);\nconst absl::Time deadline = absl::Now() + timeout;\nconst std::string alias_path = absl::StrFormat(\"[cg#%d]/%s\", id_, name);\n@@ -94,6 +100,8 @@ PosixError Cgroup::PollControlFileForChange(absl::string_view name,\nASSIGN_OR_RETURN_ERRNO(const int64_t initial_value,\nReadIntegerControlFile(name));\n+ body();\n+\nwhile (true) {\nASSIGN_OR_RETURN_ERRNO(const int64_t current_value,\nReadIntegerControlFile(name));\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/cgroup_util.h",
"new_path": "test/util/cgroup_util.h",
"diff": "@@ -78,6 +78,11 @@ class Cgroup {\nPosixError PollControlFileForChange(absl::string_view name,\nabsl::Duration timeout) const;\n+ // Waits for a control file's value to change after calling body.\n+ PosixError PollControlFileForChangeAfter(absl::string_view name,\n+ absl::Duration timeout,\n+ std::function<void()> body) const;\n+\n// Returns the thread ids of the leaders of thread groups managed by this\n// cgroup.\nPosixErrorOr<absl::flat_hash_set<pid_t>> Procs() const;\n"
}
] | Go | Apache License 2.0 | google/gvisor | cgroupfs: Fix test race with task exit.
The PID controller isn't uncharged synchronously with task exit. The
test checks the PID is released after thread join, which races with
the task being reaped.
PiperOrigin-RevId: 444960688 |
259,992 | 27.04.2022 15:27:22 | 25,200 | 93185b4eec042019bc9e892326b44e2405162501 | Add container/start Point
Updates | [
{
"change_type": "MODIFY",
"old_path": "examples/seccheck/BUILD",
"new_path": "examples/seccheck/BUILD",
"diff": "@@ -9,6 +9,7 @@ cc_binary(\ndeps = [\n# any_cc_proto placeholder,\n\"//pkg/sentry/seccheck/points:points_cc_proto\",\n+ \"@com_google_absl//absl/cleanup\",\n\"@com_google_absl//absl/strings\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "examples/seccheck/pod_init.json",
"new_path": "examples/seccheck/pod_init.json",
"diff": "\"trace_session\": {\n\"name\": \"Default\",\n\"points\": [\n+ {\n+ \"name\": \"container/start\"\n+ },\n{\n\"name\": \"sentry/clone\"\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "examples/seccheck/server.cc",
"new_path": "examples/seccheck/server.cc",
"diff": "#include <vector>\n#include \"google/protobuf/any.pb.h\"\n+#include \"absl/cleanup/cleanup.h\"\n#include \"absl/strings/string_view.h\"\n+#include \"pkg/sentry/seccheck/points/container.pb.h\"\n#include \"pkg/sentry/seccheck/points/sentry.pb.h\"\ntypedef std::function<void(const google::protobuf::Any& any)> Callback;\n@@ -65,6 +67,7 @@ void unpack(const google::protobuf::Any& any) {\n}\nstd::map<std::string, Callback> dispatchers = {\n+ {\"gvisor.container.Start\", unpack<::gvisor::container::Start>},\n{\"gvisor.sentry.CloneInfo\", unpack<::gvisor::sentry::CloneInfo>},\n{\"gvisor.sentry.ExecveInfo\", unpack<::gvisor::sentry::ExecveInfo>},\n{\"gvisor.sentry.ExitNotifyParentInfo\",\n@@ -179,6 +182,7 @@ extern \"C\" int main(int argc, char** argv) {\nif (sock < 0) {\nerr(1, \"socket\");\n}\n+ auto sock_closer = absl::MakeCleanup([sock] { close(sock); });\nstruct sockaddr_un addr;\naddr.sun_family = AF_UNIX;\n@@ -194,6 +198,7 @@ extern \"C\" int main(int argc, char** argv) {\nif (epoll_fd < 0) {\nerr(1, \"epoll_create\");\n}\n+ auto epoll_closer = absl::MakeCleanup([epoll_fd] { close(epoll_fd); });\nstartPollThread(epoll_fd);\nfor (;;) {\n@@ -213,9 +218,4 @@ extern \"C\" int main(int argc, char** argv) {\nerr(1, \"epoll_ctl(ADD)\");\n}\n}\n-\n- close(sock);\n- unlink(path.c_str());\n-\n- return 0;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/seccheck.go",
"new_path": "pkg/sentry/kernel/seccheck.go",
"diff": "@@ -33,10 +33,6 @@ func LoadSeccheckDataLocked(t *Task, mask seccheck.FieldMask, info *pb.ContextDa\nif mask.Contains(seccheck.FieldCtxtTime) {\ninfo.TimeNs = t.k.RealtimeClock().Now().Nanoseconds()\n}\n-\n- if t == nil {\n- return\n- }\nif mask.Contains(seccheck.FieldCtxtThreadID) {\ninfo.ThreadId = int32(t.k.tasks.Root.tids[t])\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/checkers/remote/remote.go",
"new_path": "pkg/sentry/seccheck/checkers/remote/remote.go",
"diff": "@@ -173,3 +173,8 @@ func (r *Remote) ExitNotifyParent(_ context.Context, _ seccheck.FieldSet, info *\nr.write(info)\nreturn nil\n}\n+\n+func (r *Remote) ContainerStart(_ context.Context, _ seccheck.FieldSet, info *pb.Start) error {\n+ r.write(info)\n+ return nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/metadata.go",
"new_path": "pkg/sentry/seccheck/metadata.go",
"diff": "@@ -21,6 +21,12 @@ import (\n\"gvisor.dev/gvisor/pkg/fd\"\n)\n+const (\n+ // ContainerStartFieldEnv is an optional field to collect list of environment\n+ // variables set for the container start process.\n+ ContainerStartFieldEnv Field = iota\n+)\n+\nvar points = map[string]PointDesc{}\nvar sinks = map[string]SinkDesc{}\n@@ -146,6 +152,18 @@ func validateFields(fields []FieldDesc) error {\n// These are all the points available in the system.\nfunc init() {\n+ // Points from the container namespace.\n+ registerPoint(PointDesc{\n+ ID: PointContainerStart,\n+ Name: \"container/start\",\n+ OptionalFields: []FieldDesc{\n+ {\n+ ID: ContainerStartFieldEnv,\n+ Name: \"env\",\n+ },\n+ },\n+ })\n+\n// Points from the sentry namespace.\nregisterPoint(PointDesc{\nID: PointClone,\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/points/BUILD",
"new_path": "pkg/sentry/seccheck/points/BUILD",
"diff": "@@ -8,6 +8,7 @@ proto_library(\nname = \"points\",\nsrcs = [\n\"common.proto\",\n+ \"container.proto\",\n\"sentry.proto\",\n],\n)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/seccheck/points/container.proto",
"diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+syntax = \"proto3\";\n+\n+package gvisor.container;\n+\n+import \"pkg/sentry/seccheck/points/common.proto\";\n+\n+message Start {\n+ gvisor.common.ContextData context_data = 1;\n+ string id = 2;\n+ string cwd = 3;\n+ repeated string args = 4;\n+ repeated string env = 5;\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/seccheck.go",
"new_path": "pkg/sentry/seccheck/seccheck.go",
"diff": "@@ -31,6 +31,7 @@ const (\nPointClone Point = iota\nPointExecve\nPointExitNotifyParent\n+ PointContainerStart\n// Add new Points above this line.\npointLength\n@@ -116,6 +117,7 @@ type Checker interface {\nClone(ctx context.Context, fields FieldSet, info *pb.CloneInfo) error\nExecve(ctx context.Context, fields FieldSet, info *pb.ExecveInfo) error\nExitNotifyParent(ctx context.Context, fields FieldSet, info *pb.ExitNotifyParentInfo) error\n+ ContainerStart(context.Context, FieldSet, *pb.Start) error\n}\n// CheckerDefaults may be embedded by implementations of Checker to obtain\n@@ -139,6 +141,11 @@ func (CheckerDefaults) ExitNotifyParent(context.Context, FieldSet, *pb.ExitNotif\nreturn nil\n}\n+// ContainerStart implements Checker.ContainerStart.\n+func (CheckerDefaults) ContainerStart(context.Context, FieldSet, *pb.Start) error {\n+ return nil\n+}\n+\n// PointReq indicates what Point a corresponding Checker runs at, and what\n// information it requires at those Points.\ntype PointReq struct {\n@@ -209,6 +216,16 @@ func (s *State) appendCheckerLocked(c Checker) {\ns.registrationSeq.EndWrite()\n}\n+// SendToCheckers iterates over all checkers and calls fn for each one of them.\n+func (s *State) SendToCheckers(fn func(c Checker) error) error {\n+ for _, c := range s.getCheckers() {\n+ if err := fn(c); err != nil {\n+ return err\n+ }\n+ }\n+ return nil\n+}\n+\n// GetFieldSet returns the FieldSet that has been configured for a given Point.\nfunc (s *State) GetFieldSet(p Point) FieldSet {\ns.registrationMu.RLock()\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/BUILD",
"new_path": "runsc/boot/BUILD",
"diff": "@@ -84,6 +84,7 @@ go_library(\n\"//pkg/sentry/platform\",\n\"//pkg/sentry/seccheck\",\n\"//pkg/sentry/seccheck/checkers/remote\",\n+ \"//pkg/sentry/seccheck/points:points_go_proto\",\n\"//pkg/sentry/socket/hostinet\",\n\"//pkg/sentry/socket/netfilter\",\n\"//pkg/sentry/socket/netlink\",\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader.go",
"new_path": "runsc/boot/loader.go",
"diff": "@@ -48,6 +48,8 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/loader\"\n\"gvisor.dev/gvisor/pkg/sentry/pgalloc\"\n\"gvisor.dev/gvisor/pkg/sentry/platform\"\n+ \"gvisor.dev/gvisor/pkg/sentry/seccheck\"\n+ pb \"gvisor.dev/gvisor/pkg/sentry/seccheck/points/points_go_proto\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/netfilter\"\n\"gvisor.dev/gvisor/pkg/sentry/syscalls/linux/vfs2\"\n\"gvisor.dev/gvisor/pkg/sentry/time\"\n@@ -642,6 +644,23 @@ func (l *Loader) run() error {\nif err != nil {\nreturn err\n}\n+\n+ if seccheck.Global.Enabled(seccheck.PointContainerStart) {\n+ evt := pb.Start{\n+ Id: l.sandboxID,\n+ Cwd: l.root.spec.Process.Cwd,\n+ Args: l.root.spec.Process.Args,\n+ }\n+ fields := seccheck.Global.GetFieldSet(seccheck.PointContainerStart)\n+ if fields.Local.Contains(seccheck.ContainerStartFieldEnv) {\n+ evt.Env = l.root.spec.Process.Env\n+ }\n+\n+ ctx := l.root.procArgs.NewContext(l.k)\n+ _ = seccheck.Global.SendToCheckers(func(c seccheck.Checker) error {\n+ return c.ContainerStart(ctx, fields, &evt)\n+ })\n+ }\n}\nep.tg = l.k.GlobalInit()\n@@ -770,6 +789,23 @@ func (l *Loader) startSubcontainer(spec *specs.Spec, conf *config.Config, cid st\nif err != nil {\nreturn err\n}\n+\n+ if seccheck.Global.Enabled(seccheck.PointContainerStart) {\n+ evt := pb.Start{\n+ Id: cid,\n+ Cwd: spec.Process.Cwd,\n+ Args: spec.Process.Args,\n+ }\n+ fields := seccheck.Global.GetFieldSet(seccheck.PointContainerStart)\n+ if fields.Local.Contains(seccheck.ContainerStartFieldEnv) {\n+ evt.Env = spec.Process.Env\n+ }\n+ ctx := info.procArgs.NewContext(l.k)\n+ _ = seccheck.Global.SendToCheckers(func(c seccheck.Checker) error {\n+ return c.ContainerStart(ctx, fields, &evt)\n+ })\n+ }\n+\nl.k.StartProcess(ep.tg)\nreturn nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add container/start Point
Updates #4805
PiperOrigin-RevId: 444983390 |
259,985 | 27.04.2022 16:29:04 | 25,200 | 92d84efb1099b60bcbdc79e740be1d24ce37612b | Ignore whitespace changes in seccheck test message. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/checkers/remote/remote_test.go",
"new_path": "pkg/sentry/seccheck/checkers/remote/remote_test.go",
"diff": "@@ -283,8 +283,11 @@ func TestExample(t *testing.T) {\nt.Fatalf(\"ExitNotifyParent: %v\", err)\n}\ncheck := func() error {\n- if got := server.out.String(); !strings.Contains(got, \"gvisor.sentry.ExitNotifyParentInfo => exit_status: 123\") {\n- return fmt.Errorf(\"ExitNotifyParentInfo point didn't get to the server, out: %q\", got)\n+ gotRaw := server.out.String()\n+ // Collapse whitespace.\n+ got := strings.Join(strings.Fields(gotRaw), \" \")\n+ if !strings.Contains(got, \"gvisor.sentry.ExitNotifyParentInfo => exit_status: 123\") {\n+ return fmt.Errorf(\"ExitNotifyParentInfo point didn't get to the server, out: %q, raw: %q\", got, gotRaw)\n}\nreturn nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Ignore whitespace changes in seccheck test message.
PiperOrigin-RevId: 444998438 |
259,891 | 27.04.2022 17:08:28 | 25,200 | 21e95c8a1c7b47df5ba7aa5704662a8e3126047f | make checkaligned error more helpful by printing type name to use | [
{
"change_type": "MODIFY",
"old_path": "tools/checkaligned/checkaligned.go",
"new_path": "tools/checkaligned/checkaligned.go",
"diff": "@@ -35,9 +35,6 @@ var Analyzer = &analysis.Analyzer{\n}\n// blocklist lists prohibited identifiers in the atomic package.\n-//\n-// TODO(b/228378998): We can further genericize this to ban other things we\n-// don't like (e.g. os.File).\nvar blocklist = []string{\n\"AddInt64\",\n\"AddUint64\",\n@@ -96,7 +93,15 @@ func run(pass *analysis.Pass) (interface{}, error) {\nfor _, blocked := range blocklist {\nif selExpr.Sel.Name == blocked {\n- pass.Reportf(selExpr.Pos(), fmt.Sprintf(\"don't call atomic.%s; use the atomicbitops package instead\", blocked))\n+ // All blocked functions end in Int32 or Uint32, which we can use to\n+ // suggest the correct type.\n+ typeNameLen := len(\"Int\")\n+ if unsigned := \"Uint\"; strings.Contains(blocked, unsigned) {\n+ typeNameLen = len(unsigned)\n+ }\n+ typeNameLen += 2 // Account for the \"32\" or \"64\" suffix.\n+ typeName := blocked[len(blocked)-typeNameLen:]\n+ pass.Reportf(selExpr.Pos(), fmt.Sprintf(\"don't call atomic.%s; use atomicbitops.%s instead\", blocked, typeName))\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | make checkaligned error more helpful by printing type name to use
PiperOrigin-RevId: 445007578 |
259,992 | 27.04.2022 18:01:40 | 25,200 | 548d12773965831811b2fe719df0c8c0da4e8a61 | Refactor code to use seccheck.SendToCheckers
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_clone.go",
"new_path": "pkg/sentry/kernel/task_clone.go",
"diff": "@@ -248,7 +248,9 @@ func (t *Task) Clone(args *linux.CloneArgs) (ThreadID, *SyscallControl, error) {\nif seccheck.Global.Enabled(seccheck.PointClone) {\nmask, info := getCloneSeccheckInfo(t, nt)\n- if err := seccheck.Global.Clone(t, mask, info); err != nil {\n+ if err := seccheck.Global.SendToCheckers(func(c seccheck.Checker) error {\n+ return c.Clone(t, mask, info)\n+ }); err != nil {\n// nt has been visible to the rest of the system since NewTask, so\n// it may be blocking execve or a group stop, have been notified\n// for group signal delivery, had children reparented to it, etc.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_exec.go",
"new_path": "pkg/sentry/kernel/task_exec.go",
"diff": "@@ -97,7 +97,9 @@ func (t *Task) Execve(newImage *TaskImage, argv, env []string, executable fsbrid\n// We can't clearly hold kernel package locks while stat'ing executable.\nif seccheck.Global.Enabled(seccheck.PointExecve) {\nmask, info := getExecveSeccheckInfo(t, argv, env, executable, pathname)\n- if err := seccheck.Global.Execve(t, mask, info); err != nil {\n+ if err := seccheck.Global.SendToCheckers(func(c seccheck.Checker) error {\n+ return c.Execve(t, mask, info)\n+ }); err != nil {\nnewImage.release()\nreturn nil, err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_exit.go",
"new_path": "pkg/sentry/kernel/task_exit.go",
"diff": "@@ -31,6 +31,7 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n+ \"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/seccheck\"\npb \"gvisor.dev/gvisor/pkg/sentry/seccheck/points/points_go_proto\"\n@@ -647,7 +648,11 @@ func (t *Task) exitNotifyLocked(fromPtraceDetach bool) {\n}\nif seccheck.Global.Enabled(seccheck.PointExitNotifyParent) {\nmask, info := getExitNotifyParentSeccheckInfo(t)\n- seccheck.Global.ExitNotifyParent(t, mask, info)\n+ if err := seccheck.Global.SendToCheckers(func(c seccheck.Checker) error {\n+ return c.ExitNotifyParent(t, mask, info)\n+ }); err != nil {\n+ log.Infof(\"Ignoring error from ExitNotifyParent point: %v\", err)\n+ }\n}\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/BUILD",
"new_path": "pkg/sentry/seccheck/BUILD",
"diff": "@@ -17,10 +17,7 @@ go_template_instance(\ngo_library(\nname = \"seccheck\",\nsrcs = [\n- \"clone.go\",\n\"config.go\",\n- \"execve.go\",\n- \"exit.go\",\n\"metadata.go\",\n\"seccheck.go\",\n\"seqatomic_checkerslice_unsafe.go\",\n"
},
{
"change_type": "DELETE",
"old_path": "pkg/sentry/seccheck/clone.go",
"new_path": null,
"diff": "-// Copyright 2021 The gVisor Authors.\n-//\n-// Licensed under the Apache License, Version 2.0 (the \"License\");\n-// you may not use this file except in compliance with the License.\n-// You may obtain a copy of the License at\n-//\n-// http://www.apache.org/licenses/LICENSE-2.0\n-//\n-// Unless required by applicable law or agreed to in writing, software\n-// distributed under the License is distributed on an \"AS IS\" BASIS,\n-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-// See the License for the specific language governing permissions and\n-// limitations under the License.\n-\n-package seccheck\n-\n-import (\n- \"gvisor.dev/gvisor/pkg/context\"\n- pb \"gvisor.dev/gvisor/pkg/sentry/seccheck/points/points_go_proto\"\n-)\n-\n-// Clone is called at the Clone checkpoint.\n-func (s *State) Clone(ctx context.Context, fields FieldSet, info *pb.CloneInfo) error {\n- for _, c := range s.getCheckers() {\n- if err := c.Clone(ctx, fields, info); err != nil {\n- return err\n- }\n- }\n- return nil\n-}\n"
},
{
"change_type": "DELETE",
"old_path": "pkg/sentry/seccheck/execve.go",
"new_path": null,
"diff": "-// Copyright 2021 The gVisor Authors.\n-//\n-// Licensed under the Apache License, Version 2.0 (the \"License\");\n-// you may not use this file except in compliance with the License.\n-// You may obtain a copy of the License at\n-//\n-// http://www.apache.org/licenses/LICENSE-2.0\n-//\n-// Unless required by applicable law or agreed to in writing, software\n-// distributed under the License is distributed on an \"AS IS\" BASIS,\n-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-// See the License for the specific language governing permissions and\n-// limitations under the License.\n-\n-package seccheck\n-\n-import (\n- \"gvisor.dev/gvisor/pkg/context\"\n- pb \"gvisor.dev/gvisor/pkg/sentry/seccheck/points/points_go_proto\"\n-)\n-\n-const (\n- // ExecveFieldBinaryInfo is an optional field to collect information about the\n- // binary being executed.\n- ExecveFieldBinaryInfo Field = iota\n-)\n-\n-// Execve is called at the Execve checkpoint.\n-func (s *State) Execve(ctx context.Context, mask FieldSet, info *pb.ExecveInfo) error {\n- for _, c := range s.getCheckers() {\n- if err := c.Execve(ctx, mask, info); err != nil {\n- return err\n- }\n- }\n- return nil\n-}\n"
},
{
"change_type": "DELETE",
"old_path": "pkg/sentry/seccheck/exit.go",
"new_path": null,
"diff": "-// Copyright 2021 The gVisor Authors.\n-//\n-// Licensed under the Apache License, Version 2.0 (the \"License\");\n-// you may not use this file except in compliance with the License.\n-// You may obtain a copy of the License at\n-//\n-// http://www.apache.org/licenses/LICENSE-2.0\n-//\n-// Unless required by applicable law or agreed to in writing, software\n-// distributed under the License is distributed on an \"AS IS\" BASIS,\n-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-// See the License for the specific language governing permissions and\n-// limitations under the License.\n-\n-package seccheck\n-\n-import (\n- \"gvisor.dev/gvisor/pkg/context\"\n- pb \"gvisor.dev/gvisor/pkg/sentry/seccheck/points/points_go_proto\"\n-)\n-\n-// ExitNotifyParent is called at the ExitNotifyParent checkpoint.\n-//\n-// The ExitNotifyParent checkpoint occurs when a zombied thread group leader,\n-// not waiting for exit acknowledgement from a non-parent ptracer, becomes the\n-// last non-dead thread in its thread group and notifies its parent of its\n-// exiting.\n-func (s *State) ExitNotifyParent(ctx context.Context, fields FieldSet, info *pb.ExitNotifyParentInfo) error {\n- for _, c := range s.getCheckers() {\n- if err := c.ExitNotifyParent(ctx, fields, info); err != nil {\n- return err\n- }\n- }\n- return nil\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/metadata.go",
"new_path": "pkg/sentry/seccheck/metadata.go",
"diff": "@@ -27,6 +27,12 @@ const (\nContainerStartFieldEnv Field = iota\n)\n+const (\n+ // ExecveFieldBinaryInfo is an optional field to collect information about the\n+ // binary being executed.\n+ ExecveFieldBinaryInfo Field = iota\n+)\n+\nvar points = map[string]PointDesc{}\nvar sinks = map[string]SinkDesc{}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/seccheck_test.go",
"new_path": "pkg/sentry/seccheck/seccheck_test.go",
"diff": "@@ -75,7 +75,9 @@ func TestCheckerRegistered(t *testing.T) {\nif !fields.Context.Contains(FieldCtxtCredentials) {\nt.Errorf(\"fields.Context.Contains(PointContextCredentials): got false, wanted true\")\n}\n- if err := s.Clone(context.Background(), fields, &pb.CloneInfo{}); err != nil {\n+ if err := s.SendToCheckers(func(c Checker) error {\n+ return c.Clone(context.Background(), fields, &pb.CloneInfo{})\n+ }); err != nil {\nt.Errorf(\"Clone(): got %v, wanted nil\", err)\n}\nif !checkerCalled {\n@@ -112,7 +114,9 @@ func TestMultipleCheckersRegistered(t *testing.T) {\n// CloneReq() should return the union of requested fields from all calls to\n// AppendChecker.\nfields := s.GetFieldSet(PointClone)\n- if err := s.Clone(context.Background(), fields, &pb.CloneInfo{}); err != nil {\n+ if err := s.SendToCheckers(func(c Checker) error {\n+ return c.Clone(context.Background(), fields, &pb.CloneInfo{})\n+ }); err != nil {\nt.Errorf(\"Clone(): got %v, wanted nil\", err)\n}\nfor i := range checkersCalled {\n@@ -151,7 +155,9 @@ func TestCheckpointReturnsFirstCheckerError(t *testing.T) {\nif !s.Enabled(PointClone) {\nt.Errorf(\"Enabled(PointClone): got false, wanted true\")\n}\n- if err := s.Clone(context.Background(), FieldSet{}, &pb.CloneInfo{}); err != errFirstChecker {\n+ if err := s.SendToCheckers(func(c Checker) error {\n+ return c.Clone(context.Background(), FieldSet{}, &pb.CloneInfo{})\n+ }); err != errFirstChecker {\nt.Errorf(\"Clone(): got %v, wanted %v\", err, errFirstChecker)\n}\nif !checkersCalled[0] {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Refactor code to use seccheck.SendToCheckers
Updates #4805
PiperOrigin-RevId: 445017536 |
259,966 | 28.04.2022 11:32:12 | 25,200 | 9f41bb6d6279c80907cd843d45f6c7a772f10c1a | Implement remaining multicast routing table operations.
In particular, this change adds support for AddInstalledRoute,
RemoveInstalledRoute, and GetLastUsedTimestamp.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/internal/multicast/BUILD",
"new_path": "pkg/tcpip/network/internal/multicast/BUILD",
"diff": "@@ -9,7 +9,6 @@ go_library(\n],\nvisibility = [\"//visibility:public\"],\ndeps = [\n- \"//pkg/atomicbitops\",\n\"//pkg/tcpip\",\n\"//pkg/tcpip/stack\",\n],\n@@ -21,7 +20,6 @@ go_test(\nsrcs = [\"route_table_test.go\"],\nlibrary = \":multicast\",\ndeps = [\n- \"//pkg/atomicbitops\",\n\"//pkg/refs\",\n\"//pkg/refsvfs2\",\n\"//pkg/tcpip\",\n@@ -42,6 +40,7 @@ go_test(\n\":multicast\",\n\"//pkg/refs\",\n\"//pkg/refsvfs2\",\n+ \"//pkg/tcpip\",\n\"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/faketime\",\n\"//pkg/tcpip/stack\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/internal/multicast/example_test.go",
"new_path": "pkg/tcpip/network/internal/multicast/example_test.go",
"diff": "@@ -18,9 +18,11 @@ import (\n\"fmt\"\n\"os\"\n\"testing\"\n+ \"time\"\n\"gvisor.dev/gvisor/pkg/refs\"\n\"gvisor.dev/gvisor/pkg/refsvfs2\"\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/faketime\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/internal/multicast\"\n@@ -28,17 +30,27 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/testutil\"\n)\n+const (\n+ defaultMinTTL = 10\n+ inputNICID tcpip.NICID = 1\n+ outgoingNICID tcpip.NICID = 2\n+)\n+\n// Example shows how to interact with a multicast RouteTable.\nfunc Example() {\naddress := testutil.MustParse4(\"192.168.1.1\")\n+ defaultOutgoingInterfaces := []multicast.OutgoingInterface{{ID: outgoingNICID, MinTTL: defaultMinTTL}}\nrouteKey := multicast.RouteKey{UnicastSource: address, MulticastDestination: address}\npkt := newPacketBuffer(\"hello\")\ndefer pkt.DecRef()\n+ clock := faketime.NewManualClock()\n+ clock.Advance(10 * time.Second)\n+\n// Create a route table from a specified config.\ntable := multicast.RouteTable{}\n- config := multicast.DefaultConfig(faketime.NewManualClock())\n+ config := multicast.DefaultConfig(clock)\nif err := table.Init(config); err != nil {\npanic(err)\n@@ -72,12 +84,48 @@ func Example() {\ndeliverPktLocally(pkt)\n}\n+ // To transition a pending route to the installed state, call:\n+ route := table.NewInstalledRoute(inputNICID, defaultOutgoingInterfaces)\n+ pendingRoute, ok := table.AddInstalledRoute(routeKey, route)\n+\n+ if !ok {\n+ return\n+ }\n+\n+ // If there was a pending route, then the caller is responsible for\n+ // flushing any pending packets.\n+ for !pendingRoute.IsEmpty() {\n+ pkt, err := pendingRoute.Dequeue()\n+ if err != nil {\n+ panic(fmt.Sprintf(\"pendingRoute.Dequeue() = (_, %s)\", err))\n+ }\n+ forwardPkt(pkt, route)\n+ }\n+\n+ // To obtain the last used time of the route, call:\n+ timestamp, found := table.GetLastUsedTimestamp(routeKey)\n+\n+ if !found {\n+ panic(fmt.Sprintf(\"table.GetLastUsedTimestamp(%#v) = (_, false)\", routeKey))\n+ }\n+\n+ fmt.Printf(\"Last used timestamp: %d\", timestamp.Nanoseconds())\n+\n+ // Finally, to remove an installed route, call:\n+ if removed := table.RemoveInstalledRoute(routeKey); !removed {\n+ panic(fmt.Sprintf(\"table.RemoveInstalledRoute(%#v) = false\", routeKey))\n+ }\n+\n// Output:\n// emitMissingRouteEvent\n// deliverPktLocally\n+ // forwardPkt\n+ // Last used timestamp: 10000000000\n}\n-func forwardPkt(*stack.PacketBuffer, *multicast.InstalledRoute) {}\n+func forwardPkt(*stack.PacketBuffer, *multicast.InstalledRoute) {\n+ fmt.Println(\"forwardPkt\")\n+}\nfunc emitMissingRouteEvent(multicast.RouteKey) {\nfmt.Println(\"emitMissingRouteEvent\")\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/internal/multicast/route_table.go",
"new_path": "pkg/tcpip/network/internal/multicast/route_table.go",
"diff": "@@ -19,9 +19,7 @@ import (\n\"errors\"\n\"fmt\"\n\"sync\"\n- \"time\"\n- \"gvisor.dev/gvisor/pkg/atomicbitops\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n)\n@@ -55,7 +53,7 @@ type RouteTable struct {\npendingMu sync.RWMutex\n// +checklocks:pendingMu\n- pendingRoutes map[RouteKey]pendingRoute\n+ pendingRoutes map[RouteKey]PendingRoute\nconfig Config\n}\n@@ -69,7 +67,7 @@ var (\n// Config, but is required.\nErrMissingClock = errors.New(\"clock must not be nil\")\n- // ErrAlreadyInitialized indicate that RouteTable.Init was already invoked.\n+ // ErrAlreadyInitialized indicates that RouteTable.Init was already invoked.\nErrAlreadyInitialized = errors.New(\"table is already initialized\")\n)\n@@ -86,8 +84,10 @@ type RouteKey struct {\ntype InstalledRoute struct {\nexpectedInputInterface tcpip.NICID\noutgoingInterfaces []OutgoingInterface\n- // +checkatomic\n- lastUsedTimestamp atomicbitops.Int64\n+\n+ lastUsedTimestampMu sync.RWMutex\n+ // +checklocks:lastUsedTimestampMu\n+ lastUsedTimestamp tcpip.MonotonicTime\n}\n// ExpectedInputInterface returns the expected input interface for the route.\n@@ -100,17 +100,27 @@ func (r *InstalledRoute) OutgoingInterfaces() []OutgoingInterface {\nreturn r.outgoingInterfaces\n}\n-// LastUsedTimestamp returns a Unix based timestamp in microseconds that\n-// corresponds to the last time the route was used or updated.\n-func (r *InstalledRoute) LastUsedTimestamp() int64 {\n- return r.lastUsedTimestamp.Load()\n+// LastUsedTimestamp returns a monotonic timestamp that corresponds to the last\n+// time the route was used or updated.\n+func (r *InstalledRoute) LastUsedTimestamp() tcpip.MonotonicTime {\n+ r.lastUsedTimestampMu.RLock()\n+ defer r.lastUsedTimestampMu.RUnlock()\n+\n+ return r.lastUsedTimestamp\n}\n// SetLastUsedTimestamp sets the time that the route was last used.\n//\n-// Callers should invoke this anytime the route is used to forward a packet.\n-func (r *InstalledRoute) SetLastUsedTimestamp(time time.Time) {\n- r.lastUsedTimestamp.Store(time.UnixMicro())\n+// The timestamp is only updated if it occurs after the currently set\n+// timestamp. Callers should invoke this anytime the route is used to forward a\n+// packet.\n+func (r *InstalledRoute) SetLastUsedTimestamp(monotonicTime tcpip.MonotonicTime) {\n+ r.lastUsedTimestampMu.Lock()\n+ defer r.lastUsedTimestampMu.Unlock()\n+\n+ if monotonicTime.After(r.lastUsedTimestamp) {\n+ r.lastUsedTimestamp = monotonicTime\n+ }\n}\n// OutgoingInterface represents an interface that packets should be forwarded\n@@ -124,23 +134,26 @@ type OutgoingInterface struct {\nMinTTL uint8\n}\n-// pendingRoute represents a route that is in the \"pending\" state.\n+// PendingRoute represents a route that is in the \"pending\" state.\n//\n// A route is in the pending state if an installed route does not yet exist\n// for the entry. For such routes, packets are added to an expiring queue until\n// a route is installed.\n-type pendingRoute struct {\n+type PendingRoute struct {\npackets []*stack.PacketBuffer\n}\n-func newPendingRoute(maxSize uint8) pendingRoute {\n- return pendingRoute{packets: make([]*stack.PacketBuffer, 0, maxSize)}\n+func newPendingRoute(maxSize uint8) PendingRoute {\n+ return PendingRoute{packets: make([]*stack.PacketBuffer, 0, maxSize)}\n}\n// Dequeue removes the first element in the queue and returns it.\n//\n// If the queue is empty, then an error will be returned.\n-func (p *pendingRoute) Dequeue() (*stack.PacketBuffer, error) {\n+//\n+// TODO(https://gvisor.dev/issue/7338): Remove this and instead just return the\n+// list of packets from AddInstalledRoute.\n+func (p *PendingRoute) Dequeue() (*stack.PacketBuffer, error) {\nif len(p.packets) == 0 {\nreturn nil, errors.New(\"dequeue called on queue empty\")\n}\n@@ -152,7 +165,7 @@ func (p *pendingRoute) Dequeue() (*stack.PacketBuffer, error) {\n// IsEmpty returns true if the queue contains no more elements. Otherwise,\n// returns false.\n-func (p *pendingRoute) IsEmpty() bool {\n+func (p *PendingRoute) IsEmpty() bool {\nreturn len(p.packets) == 0\n}\n@@ -205,7 +218,7 @@ func (r *RouteTable) Init(config Config) error {\nr.config = config\nr.installedRoutes = make(map[RouteKey]*InstalledRoute)\n- r.pendingRoutes = make(map[RouteKey]pendingRoute)\n+ r.pendingRoutes = make(map[RouteKey]PendingRoute)\nreturn nil\n}\n@@ -214,7 +227,7 @@ func (r *RouteTable) NewInstalledRoute(inputInterface tcpip.NICID, outgoingInter\nreturn &InstalledRoute{\nexpectedInputInterface: inputInterface,\noutgoingInterfaces: outgoingInterfaces,\n- lastUsedTimestamp: atomicbitops.FromInt64(r.config.Clock.Now().UnixMicro()),\n+ lastUsedTimestamp: r.config.Clock.NowMonotonic(),\n}\n}\n@@ -297,7 +310,7 @@ func (r *RouteTable) GetRouteOrInsertPending(key RouteKey, pkt *stack.PacketBuff\n}\n// +checklocks:r.pendingMu\n-func (r *RouteTable) getOrCreatePendingRouteRLocked(key RouteKey) (pendingRoute, PendingRouteState) {\n+func (r *RouteTable) getOrCreatePendingRouteRLocked(key RouteKey) (PendingRoute, PendingRouteState) {\nif pendingRoute, ok := r.pendingRoutes[key]; ok {\nreturn pendingRoute, PendingRouteStateAppended\n}\n@@ -305,3 +318,54 @@ func (r *RouteTable) getOrCreatePendingRouteRLocked(key RouteKey) (pendingRoute,\npendingRoute := newPendingRoute(r.config.MaxPendingQueueSize)\nreturn pendingRoute, PendingRouteStateInstalled\n}\n+\n+// AddInstalledRoute adds the provided route to the table.\n+//\n+// Returns true if the route was previously in the pending state. Otherwise,\n+// returns false.\n+//\n+// If the route was previously pending, then the caller is responsible for\n+// flushing the returned pending route packet queue. Conversely, if the route\n+// was not pending, then any existing installed route will be overwritten.\n+func (r *RouteTable) AddInstalledRoute(key RouteKey, route *InstalledRoute) (PendingRoute, bool) {\n+ r.installedMu.Lock()\n+ defer r.installedMu.Unlock()\n+ r.installedRoutes[key] = route\n+\n+ r.pendingMu.Lock()\n+ defer r.pendingMu.Unlock()\n+\n+ pendingRoute, ok := r.pendingRoutes[key]\n+ delete(r.pendingRoutes, key)\n+ return pendingRoute, ok\n+}\n+\n+// RemoveInstalledRoute deletes the installed route that matches the provided\n+// key.\n+//\n+// Returns true if a route was removed. Otherwise returns false.\n+func (r *RouteTable) RemoveInstalledRoute(key RouteKey) bool {\n+ r.installedMu.Lock()\n+ defer r.installedMu.Unlock()\n+\n+ if _, ok := r.installedRoutes[key]; ok {\n+ delete(r.installedRoutes, key)\n+ return true\n+ }\n+\n+ return false\n+}\n+\n+// GetLastUsedTimestamp returns a monotonic timestamp that represents the last\n+// time the route that matches the provided key was used or updated.\n+//\n+// Returns true if a matching route was found. Otherwise returns false.\n+func (r *RouteTable) GetLastUsedTimestamp(key RouteKey) (tcpip.MonotonicTime, bool) {\n+ r.installedMu.RLock()\n+ defer r.installedMu.RUnlock()\n+\n+ if route, ok := r.installedRoutes[key]; ok {\n+ return route.LastUsedTimestamp(), true\n+ }\n+ return tcpip.MonotonicTime{}, false\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/internal/multicast/route_table_test.go",
"new_path": "pkg/tcpip/network/internal/multicast/route_table_test.go",
"diff": "@@ -21,7 +21,6 @@ import (\n\"github.com/google/go-cmp/cmp\"\n\"github.com/google/go-cmp/cmp/cmpopts\"\n- \"gvisor.dev/gvisor/pkg/atomicbitops\"\n\"gvisor.dev/gvisor/pkg/refs\"\n\"gvisor.dev/gvisor/pkg/refsvfs2\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n@@ -35,6 +34,7 @@ const (\ndefaultMinTTL = 10\ninputNICID tcpip.NICID = 1\noutgoingNICID tcpip.NICID = 2\n+ defaultNICID tcpip.NICID = 3\n)\nvar (\n@@ -76,6 +76,18 @@ func defaultConfig(opts ...configOption) Config {\nreturn *c\n}\n+func installedRouteComparer(a *InstalledRoute, b *InstalledRoute) bool {\n+ if !cmp.Equal(a.OutgoingInterfaces(), b.OutgoingInterfaces()) {\n+ return false\n+ }\n+\n+ if a.ExpectedInputInterface() != b.ExpectedInputInterface() {\n+ return false\n+ }\n+\n+ return a.LastUsedTimestamp() == b.LastUsedTimestamp()\n+}\n+\nfunc TestInit(t *testing.T) {\ntests := []struct {\nname string\n@@ -130,19 +142,9 @@ func TestNewInstalledRoute(t *testing.T) {\n}\nroute := table.NewInstalledRoute(inputNICID, defaultOutgoingInterfaces)\n- expectedRoute := &InstalledRoute{expectedInputInterface: inputNICID, outgoingInterfaces: defaultOutgoingInterfaces, lastUsedTimestamp: atomicbitops.FromInt64(clock.Now().UnixMicro())}\n-\n- if diff := cmp.Diff(expectedRoute, route, cmp.Comparer(func(a *InstalledRoute, b *InstalledRoute) bool {\n- if !cmp.Equal(a.OutgoingInterfaces(), b.OutgoingInterfaces()) {\n- return false\n- }\n+ expectedRoute := &InstalledRoute{expectedInputInterface: inputNICID, outgoingInterfaces: defaultOutgoingInterfaces, lastUsedTimestamp: clock.NowMonotonic()}\n- if a.ExpectedInputInterface() != b.ExpectedInputInterface() {\n- return false\n- }\n-\n- return a.LastUsedTimestamp() == b.LastUsedTimestamp()\n- })); diff != \"\" {\n+ if diff := cmp.Diff(expectedRoute, route, cmp.Comparer(installedRouteComparer)); diff != \"\" {\nt.Errorf(\"installed route mismatch (-want +got):\\n%s\", diff)\n}\n}\n@@ -158,7 +160,7 @@ func TestPendingRouteStates(t *testing.T) {\ndefer pkt.DecRef()\n// Queue two pending packets for the same route. The PendingRouteState should\n// transition from PendingRouteStateInstalled to PendingRouteStateAppended.\n- for _, wantPendingRouteState := range [...]PendingRouteState{PendingRouteStateInstalled, PendingRouteStateAppended} {\n+ for _, wantPendingRouteState := range []PendingRouteState{PendingRouteStateInstalled, PendingRouteStateAppended} {\nrouteResult, err := table.GetRouteOrInsertPending(defaultRouteKey, pkt)\nif err != nil {\n@@ -178,6 +180,194 @@ func TestPendingRouteStates(t *testing.T) {\n}\n}\n+func TestAddInstalledRouteWithPending(t *testing.T) {\n+ table := RouteTable{}\n+ config := defaultConfig()\n+ if err := table.Init(config); err != nil {\n+ t.Fatalf(\"table.Init(%#v): %s\", config, err)\n+ }\n+\n+ wantPkt := newPacketBuffer(\"hello\")\n+ defer wantPkt.DecRef()\n+ // Queue a pending packet. This packet should later be returned in a\n+ // PendingRoute when table.AddInstalledRoute is invoked.\n+ _, err := table.GetRouteOrInsertPending(defaultRouteKey, wantPkt)\n+\n+ if err != nil {\n+ t.Fatalf(\"table.GetRouteOrInsertPending(%#v, %#v): %v\", defaultRouteKey, wantPkt, err)\n+ }\n+\n+ route := table.NewInstalledRoute(inputNICID, defaultOutgoingInterfaces)\n+\n+ pendingRoute, wasPending := table.AddInstalledRoute(defaultRouteKey, route)\n+ if !wasPending {\n+ t.Fatalf(\"got table.AddInstalledRoute(%#v, %#v) = (nil, false), want = (_, true)\", defaultRouteKey, route)\n+ }\n+\n+ // Verify that packets are properly dequeued from the PendingRoute.\n+ pkt, err := pendingRoute.Dequeue()\n+\n+ if err != nil {\n+ t.Fatalf(\"got pendingRoute.Dequeue() = (_, %v), want = (_, nil)\", err)\n+ }\n+\n+ if !cmp.Equal(wantPkt.Views(), pkt.Views()) {\n+ t.Errorf(\"got pendingRoute.Dequeue() = (%v, nil), want = (%v, nil)\", pkt.Views(), wantPkt.Views())\n+ }\n+\n+ if !pendingRoute.IsEmpty() {\n+ t.Errorf(\"got pendingRoute.IsEmpty() = false, want = true\")\n+ }\n+\n+ // Verify that the pending route is deleted (not returned on subsequent\n+ // calls to AddInstalledRoute).\n+ pendingRoute, wasPending = table.AddInstalledRoute(defaultRouteKey, route)\n+ if wasPending {\n+ t.Errorf(\"got table.AddInstalledRoute(%#v, %#v) = (%#v, true), want (_, false)\", defaultRouteKey, route, pendingRoute)\n+ }\n+}\n+\n+func TestAddInstalledRouteWithNoPending(t *testing.T) {\n+ table := RouteTable{}\n+ config := defaultConfig()\n+ if err := table.Init(config); err != nil {\n+ t.Fatalf(\"table.Init(%#v): %s\", config, err)\n+ }\n+\n+ firstRoute := table.NewInstalledRoute(inputNICID, defaultOutgoingInterfaces)\n+ secondRoute := table.NewInstalledRoute(defaultNICID, defaultOutgoingInterfaces)\n+\n+ pkt := newPacketBuffer(\"hello\")\n+ defer pkt.DecRef()\n+ for _, route := range [...]*InstalledRoute{firstRoute, secondRoute} {\n+ if pendingRoute, wasPending := table.AddInstalledRoute(defaultRouteKey, route); wasPending {\n+ t.Errorf(\"got table.AddInstalledRoute(%#v, %#v) = (%#v, true), want = (_, false)\", defaultRouteKey, route, pendingRoute)\n+ }\n+\n+ // AddInstalledRoute is invoked for the same routeKey two times. Verify\n+ // that the fetched InstalledRoute reflects the most recent invocation of\n+ // AddInstalledRoute.\n+ routeResult, err := table.GetRouteOrInsertPending(defaultRouteKey, pkt)\n+\n+ if err != nil {\n+ t.Fatalf(\"table.GetRouteOrInsertPending(%#v, %#v): %v\", defaultRouteKey, pkt, err)\n+ }\n+\n+ if routeResult.PendingRouteState != PendingRouteStateNone {\n+ t.Errorf(\"got routeResult.PendingRouteState = %s, want = PendingRouteStateNone\", routeResult.PendingRouteState)\n+ }\n+\n+ if diff := cmp.Diff(route, routeResult.InstalledRoute, cmp.Comparer(installedRouteComparer)); diff != \"\" {\n+ t.Errorf(\"route.InstalledRoute mismatch (-want +got):\\n%s\", diff)\n+ }\n+ }\n+}\n+\n+func TestRemoveInstalledRoute(t *testing.T) {\n+ table := RouteTable{}\n+ config := defaultConfig()\n+ if err := table.Init(config); err != nil {\n+ t.Fatalf(\"table.Init(%#v): %s\", config, err)\n+ }\n+\n+ route := table.NewInstalledRoute(inputNICID, defaultOutgoingInterfaces)\n+\n+ table.AddInstalledRoute(defaultRouteKey, route)\n+\n+ if removed := table.RemoveInstalledRoute(defaultRouteKey); !removed {\n+ t.Errorf(\"got table.RemoveInstalledRoute(%#v) = false, want = true\", defaultRouteKey)\n+ }\n+\n+ pkt := newPacketBuffer(\"hello\")\n+ defer pkt.DecRef()\n+\n+ result, err := table.GetRouteOrInsertPending(defaultRouteKey, pkt)\n+\n+ if err != nil {\n+ t.Fatalf(\"table.GetRouteOrInsertPending(%#v, %#v): %v\", defaultRouteKey, pkt, err)\n+ }\n+\n+ if result.InstalledRoute != nil {\n+ t.Errorf(\"got result.InstalledRoute = %v, want = nil\", result.InstalledRoute)\n+ }\n+}\n+\n+func TestRemoveInstalledRouteWithNoMatchingRoute(t *testing.T) {\n+ table := RouteTable{}\n+ config := defaultConfig()\n+ if err := table.Init(config); err != nil {\n+ t.Fatalf(\"table.Init(%#v): %s\", config, err)\n+ }\n+\n+ if removed := table.RemoveInstalledRoute(defaultRouteKey); removed {\n+ t.Errorf(\"got table.RemoveInstalledRoute(%#v) = true, want = false\", defaultRouteKey)\n+ }\n+}\n+\n+func TestGetLastUsedTimestampWithNoMatchingRoute(t *testing.T) {\n+ table := RouteTable{}\n+ config := defaultConfig()\n+ if err := table.Init(config); err != nil {\n+ t.Fatalf(\"table.Init(%#v): %s\", config, err)\n+ }\n+\n+ if _, found := table.GetLastUsedTimestamp(defaultRouteKey); found {\n+ t.Errorf(\"got table.GetLastUsedTimetsamp(%#v) = (_, true), want = (_, false)\", defaultRouteKey)\n+ }\n+}\n+\n+func TestSetLastUsedTimestamp(t *testing.T) {\n+ clock := faketime.NewManualClock()\n+ clock.Advance(10 * time.Second)\n+\n+ currentTime := clock.NowMonotonic()\n+ validLastUsedTime := currentTime.Add(10 * time.Second)\n+\n+ tests := []struct {\n+ name string\n+ lastUsedTime tcpip.MonotonicTime\n+ wantLastUsedTime tcpip.MonotonicTime\n+ }{\n+ {\n+ name: \"valid timestamp\",\n+ lastUsedTime: validLastUsedTime,\n+ wantLastUsedTime: validLastUsedTime,\n+ },\n+ {\n+ name: \"timestamp before\",\n+ lastUsedTime: currentTime.Add(-5 * time.Second),\n+ wantLastUsedTime: currentTime,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ table := RouteTable{}\n+ config := defaultConfig(withClock(clock))\n+ if err := table.Init(config); err != nil {\n+ t.Fatalf(\"table.Init(%#v): %s\", config, err)\n+ }\n+\n+ route := table.NewInstalledRoute(inputNICID, defaultOutgoingInterfaces)\n+\n+ table.AddInstalledRoute(defaultRouteKey, route)\n+\n+ route.SetLastUsedTimestamp(test.lastUsedTime)\n+\n+ // Verify that the updated timestamp is actually reflected in the RouteTable.\n+ timestamp, found := table.GetLastUsedTimestamp(defaultRouteKey)\n+\n+ if !found {\n+ t.Fatalf(\"got table.GetLastUsedTimestamp(%#v) = (_, false_), want = (_, true)\", defaultRouteKey)\n+ }\n+\n+ if got, want := timestamp.Nanoseconds(), test.wantLastUsedTime.Nanoseconds(); got != want {\n+ t.Errorf(\"got table.GetLastUsedTimestamp(%#v) = (%v, _), want (%v, _)\", defaultRouteKey, got, want)\n+ }\n+ })\n+ }\n+}\n+\nfunc TestMain(m *testing.M) {\nrefs.SetLeakMode(refs.LeaksPanic)\ncode := m.Run()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -71,6 +71,11 @@ type MonotonicTime struct {\nnanoseconds int64\n}\n+// Nanoseconds returns the monotonic time in nanoseconds.\n+func (mt MonotonicTime) Nanoseconds() int64 {\n+ return mt.nanoseconds\n+}\n+\n// Before reports whether the monotonic clock reading mt is before u.\nfunc (mt MonotonicTime) Before(u MonotonicTime) bool {\nreturn mt.nanoseconds < u.nanoseconds\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement remaining multicast routing table operations.
In particular, this change adds support for AddInstalledRoute,
RemoveInstalledRoute, and GetLastUsedTimestamp.
Updates #7338.
PiperOrigin-RevId: 445205505 |
259,992 | 28.04.2022 12:43:16 | 25,200 | e1c4bbccf9bd27883d3367cbdaad5236fdcb1958 | Add sentry/task_exit point
Updates | [
{
"change_type": "MODIFY",
"old_path": "examples/seccheck/pod_init.json",
"new_path": "examples/seccheck/pod_init.json",
"diff": "},\n{\n\"name\": \"sentry/clone\"\n+ },\n+ {\n+ \"name\": \"sentry/task_exit\"\n}\n],\n\"sinks\": [\n"
},
{
"change_type": "MODIFY",
"old_path": "examples/seccheck/server.cc",
"new_path": "examples/seccheck/server.cc",
"diff": "@@ -72,6 +72,7 @@ std::map<std::string, Callback> dispatchers = {\n{\"gvisor.sentry.ExecveInfo\", unpack<::gvisor::sentry::ExecveInfo>},\n{\"gvisor.sentry.ExitNotifyParentInfo\",\nunpack<::gvisor::sentry::ExitNotifyParentInfo>},\n+ {\"gvisor.sentry.TaskExit\", unpack<::gvisor::sentry::TaskExit>},\n};\nvoid unpack(const absl::string_view buf) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_exit.go",
"new_path": "pkg/sentry/kernel/task_exit.go",
"diff": "@@ -204,6 +204,21 @@ type runExitMain struct{}\nfunc (*runExitMain) execute(t *Task) taskRunState {\nt.traceExitEvent()\n+\n+ if seccheck.Global.Enabled(seccheck.PointTaskExit) {\n+ info := &pb.TaskExit{\n+ ExitStatus: int32(t.tg.exitStatus),\n+ }\n+ fields := seccheck.Global.GetFieldSet(seccheck.PointTaskExit)\n+ if !fields.Context.Empty() {\n+ info.ContextData = &pb.ContextData{}\n+ LoadSeccheckData(t, fields.Context, info.ContextData)\n+ }\n+ seccheck.Global.SendToCheckers(func(c seccheck.Checker) error {\n+ return c.TaskExit(t, fields, info)\n+ })\n+ }\n+\nlastExiter := t.exitThreadGroup()\nt.ResetKcov()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/checkers/remote/remote.go",
"new_path": "pkg/sentry/seccheck/checkers/remote/remote.go",
"diff": "@@ -174,6 +174,13 @@ func (r *Remote) ExitNotifyParent(_ context.Context, _ seccheck.FieldSet, info *\nreturn nil\n}\n+// TaskExit implements seccheck.Checker.\n+func (r *Remote) TaskExit(_ context.Context, _ seccheck.FieldSet, info *pb.TaskExit) error {\n+ r.write(info)\n+ return nil\n+}\n+\n+// ContainerStart implements seccheck.Checker.\nfunc (r *Remote) ContainerStart(_ context.Context, _ seccheck.FieldSet, info *pb.Start) error {\nr.write(info)\nreturn nil\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/metadata.go",
"new_path": "pkg/sentry/seccheck/metadata.go",
"diff": "@@ -192,4 +192,9 @@ func init() {\nName: \"sentry/exit_notify_parent\",\nContextFields: defaultContextFields,\n})\n+ registerPoint(PointDesc{\n+ ID: PointTaskExit,\n+ Name: \"sentry/task_exit\",\n+ ContextFields: defaultContextFields,\n+ })\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/points/sentry.proto",
"new_path": "pkg/sentry/seccheck/points/sentry.proto",
"diff": "@@ -65,3 +65,11 @@ message ExitNotifyParentInfo {\n// by wait*().\nint32 exit_status = 2;\n}\n+\n+message TaskExit {\n+ gvisor.common.ContextData context_data = 1;\n+\n+ // ExitStatus is the exiting thread group's exit status, as reported\n+ // by wait*().\n+ int32 exit_status = 2;\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/seccheck.go",
"new_path": "pkg/sentry/seccheck/seccheck.go",
"diff": "@@ -32,6 +32,7 @@ const (\nPointExecve\nPointExitNotifyParent\nPointContainerStart\n+ PointTaskExit\n// Add new Points above this line.\npointLength\n@@ -117,6 +118,7 @@ type Checker interface {\nClone(ctx context.Context, fields FieldSet, info *pb.CloneInfo) error\nExecve(ctx context.Context, fields FieldSet, info *pb.ExecveInfo) error\nExitNotifyParent(ctx context.Context, fields FieldSet, info *pb.ExitNotifyParentInfo) error\n+ TaskExit(context.Context, FieldSet, *pb.TaskExit) error\nContainerStart(context.Context, FieldSet, *pb.Start) error\n}\n@@ -146,6 +148,11 @@ func (CheckerDefaults) ContainerStart(context.Context, FieldSet, *pb.Start) erro\nreturn nil\n}\n+// TaskExit implements Checker.TaskExit.\n+func (CheckerDefaults) TaskExit(context.Context, FieldSet, *pb.TaskExit) error {\n+ return nil\n+}\n+\n// PointReq indicates what Point a corresponding Checker runs at, and what\n// information it requires at those Points.\ntype PointReq struct {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add sentry/task_exit point
Updates #4805
PiperOrigin-RevId: 445222912 |
259,966 | 28.04.2022 13:18:28 | 25,200 | ef4a4906936beec151cf92ed41649cd6d1ac8091 | Expire pending multicast packets/routes.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/internal/multicast/route_table.go",
"new_path": "pkg/tcpip/network/internal/multicast/route_table.go",
"diff": "@@ -19,6 +19,7 @@ import (\n\"errors\"\n\"fmt\"\n\"sync\"\n+ \"time\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n@@ -38,9 +39,6 @@ type RouteTable struct {\n// 3. This structure is similar to the Linux implementation:\n// https://github.com/torvalds/linux/blob/cffb2b72d3e/include/linux/mroute_base.h#L250\n- // TODO(https://gvisor.dev/issue/7338): Implement time based expiration of\n- // pending packets.\n-\n// The installedMu lock should typically be acquired before the pendingMu\n// lock. This ensures that installed routes can continue to be read even when\n// the pending routes are write locked.\n@@ -56,6 +54,10 @@ type RouteTable struct {\npendingRoutes map[RouteKey]PendingRoute\nconfig Config\n+\n+ // cleanupPendingRoutesTimer is a timer that triggers a routine to remove\n+ // pending routes that are expired.\n+ cleanupPendingRoutesTimer tcpip.Timer\n}\nvar (\n@@ -141,18 +143,21 @@ type OutgoingInterface struct {\n// a route is installed.\ntype PendingRoute struct {\npackets []*stack.PacketBuffer\n+\n+ // expiration is the timestamp at which the pending route should be expired.\n+ //\n+ // If this value is before the current time, then this pending route will\n+ // be dropped.\n+ expiration tcpip.MonotonicTime\n}\n-func newPendingRoute(maxSize uint8) PendingRoute {\n- return PendingRoute{packets: make([]*stack.PacketBuffer, 0, maxSize)}\n+func (p *PendingRoute) isExpired(currentTime tcpip.MonotonicTime) bool {\n+ return currentTime.After(p.expiration)\n}\n// Dequeue removes the first element in the queue and returns it.\n//\n// If the queue is empty, then an error will be returned.\n-//\n-// TODO(https://gvisor.dev/issue/7338): Remove this and instead just return the\n-// list of packets from AddInstalledRoute.\nfunc (p *PendingRoute) Dequeue() (*stack.PacketBuffer, error) {\nif len(p.packets) == 0 {\nreturn nil, errors.New(\"dequeue called on queue empty\")\n@@ -169,12 +174,28 @@ func (p *PendingRoute) IsEmpty() bool {\nreturn len(p.packets) == 0\n}\n-// DefaultMaxPendingQueueSize corresponds to the number of elements that can be\n-// in the packet queue for a pending route.\n+const (\n+ // DefaultMaxPendingQueueSize corresponds to the number of elements that can\n+ // be in the packet queue for a pending route.\n//\n// Matches the Linux default queue size:\n// https://github.com/torvalds/linux/blob/26291c54e11/net/ipv6/ip6mr.c#L1186\n-const DefaultMaxPendingQueueSize uint8 = 3\n+ DefaultMaxPendingQueueSize uint8 = 3\n+\n+ // DefaultPendingRouteExpiration is the default maximum lifetime of a pending\n+ // route.\n+ //\n+ // Matches the Linux default:\n+ // https://github.com/torvalds/linux/blob/26291c54e11/net/ipv6/ip6mr.c#L991\n+ DefaultPendingRouteExpiration time.Duration = 10 * time.Second\n+\n+ // DefaultCleanupInterval is the default frequency of the routine that\n+ // expires pending routes.\n+ //\n+ // Matches the Linux default:\n+ // https://github.com/torvalds/linux/blob/26291c54e11/net/ipv6/ip6mr.c#L793\n+ DefaultCleanupInterval time.Duration = 10 * time.Second\n+)\n// Config represents the options for configuring a RouteTable.\ntype Config struct {\n@@ -194,7 +215,10 @@ type Config struct {\n// DefaultConfig returns the default configuration for the table.\nfunc DefaultConfig(clock tcpip.Clock) Config {\n- return Config{MaxPendingQueueSize: DefaultMaxPendingQueueSize, Clock: clock}\n+ return Config{\n+ MaxPendingQueueSize: DefaultMaxPendingQueueSize,\n+ Clock: clock,\n+ }\n}\n// Init initializes the RouteTable with the provided config.\n@@ -219,9 +243,31 @@ func (r *RouteTable) Init(config Config) error {\nr.config = config\nr.installedRoutes = make(map[RouteKey]*InstalledRoute)\nr.pendingRoutes = make(map[RouteKey]PendingRoute)\n+\n+ r.cleanupPendingRoutesTimer = r.config.Clock.AfterFunc(DefaultCleanupInterval, r.cleanupPendingRoutes)\nreturn nil\n}\n+func (r *RouteTable) cleanupPendingRoutes() {\n+ currentTime := r.config.Clock.NowMonotonic()\n+ r.pendingMu.Lock()\n+ defer r.pendingMu.Unlock()\n+\n+ for key, route := range r.pendingRoutes {\n+ if route.isExpired(currentTime) {\n+ delete(r.pendingRoutes, key)\n+ }\n+ }\n+ r.cleanupPendingRoutesTimer.Reset(DefaultCleanupInterval)\n+}\n+\n+func (r *RouteTable) newPendingRoute() PendingRoute {\n+ return PendingRoute{\n+ packets: make([]*stack.PacketBuffer, 0, r.config.MaxPendingQueueSize),\n+ expiration: r.config.Clock.NowMonotonic().Add(DefaultPendingRouteExpiration),\n+ }\n+}\n+\n// NewInstalledRoute instatiates an installed route for the table.\nfunc (r *RouteTable) NewInstalledRoute(inputInterface tcpip.NICID, outgoingInterfaces []OutgoingInterface) *InstalledRoute {\nreturn &InstalledRoute{\n@@ -314,9 +360,7 @@ func (r *RouteTable) getOrCreatePendingRouteRLocked(key RouteKey) (PendingRoute,\nif pendingRoute, ok := r.pendingRoutes[key]; ok {\nreturn pendingRoute, PendingRouteStateAppended\n}\n-\n- pendingRoute := newPendingRoute(r.config.MaxPendingQueueSize)\n- return pendingRoute, PendingRouteStateInstalled\n+ return r.newPendingRoute(), PendingRouteStateInstalled\n}\n// AddInstalledRoute adds the provided route to the table.\n@@ -333,14 +377,19 @@ func (r *RouteTable) AddInstalledRoute(key RouteKey, route *InstalledRoute) (Pen\nr.installedRoutes[key] = route\nr.pendingMu.Lock()\n- defer r.pendingMu.Unlock()\n-\npendingRoute, ok := r.pendingRoutes[key]\ndelete(r.pendingRoutes, key)\n- return pendingRoute, ok\n+ r.pendingMu.Unlock()\n+\n+ // Ignore the pending route if it is expired. It may be in this state since\n+ // the cleanup process is only run periodically.\n+ if !ok || pendingRoute.isExpired(r.config.Clock.NowMonotonic()) {\n+ return PendingRoute{}, false\n+ }\n+ return pendingRoute, true\n}\n-// RemoveInstalledRoute deletes the installed route that matches the provided\n+// RemoveInstalledRoute deletes any installed route that matches the provided\n// key.\n//\n// Returns true if a route was removed. Otherwise returns false.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/internal/multicast/route_table_test.go",
"new_path": "pkg/tcpip/network/internal/multicast/route_table_test.go",
"diff": "@@ -180,50 +180,134 @@ func TestPendingRouteStates(t *testing.T) {\n}\n}\n-func TestAddInstalledRouteWithPending(t *testing.T) {\n+func TestPendingRouteExpiration(t *testing.T) {\n+ pkt := newPacketBuffer(\"foo\")\n+ defer pkt.DecRef()\n+\n+ testCases := []struct {\n+ name string\n+ advanceBeforeInsert time.Duration\n+ advanceAfterInsert time.Duration\n+ wantPendingRoute bool\n+ }{\n+ {\n+ name: \"not expired\",\n+ advanceBeforeInsert: DefaultCleanupInterval / 2,\n+ // The time is advanced far enough to run the cleanup routine, but not\n+ // far enough to expire the route.\n+ advanceAfterInsert: DefaultCleanupInterval,\n+ wantPendingRoute: true,\n+ },\n+ {\n+ name: \"expired\",\n+ // The cleanup routine will be run twice. The second invocation will\n+ // remove the expired route.\n+ advanceBeforeInsert: DefaultCleanupInterval / 2,\n+ advanceAfterInsert: DefaultCleanupInterval * 2,\n+ wantPendingRoute: false,\n+ },\n+ }\n+\n+ for _, test := range testCases {\n+ t.Run(test.name, func(t *testing.T) {\n+ clock := faketime.NewManualClock()\n+\ntable := RouteTable{}\n- config := defaultConfig()\n+ config := defaultConfig(withClock(clock))\n+\nif err := table.Init(config); err != nil {\nt.Fatalf(\"table.Init(%#v): %s\", config, err)\n}\n- wantPkt := newPacketBuffer(\"hello\")\n- defer wantPkt.DecRef()\n- // Queue a pending packet. This packet should later be returned in a\n- // PendingRoute when table.AddInstalledRoute is invoked.\n- _, err := table.GetRouteOrInsertPending(defaultRouteKey, wantPkt)\n+ clock.Advance(test.advanceBeforeInsert)\n- if err != nil {\n- t.Fatalf(\"table.GetRouteOrInsertPending(%#v, %#v): %v\", defaultRouteKey, wantPkt, err)\n+ if _, err := table.GetRouteOrInsertPending(defaultRouteKey, pkt); err != nil {\n+ t.Fatalf(\"table.GetRouteOrInsertPending(%#v, %#v): %v\", defaultRouteKey, pkt, err)\n}\n- route := table.NewInstalledRoute(inputNICID, defaultOutgoingInterfaces)\n+ clock.Advance(test.advanceAfterInsert)\n+\n+ table.pendingMu.RLock()\n+ _, ok := table.pendingRoutes[defaultRouteKey]\n+ table.pendingMu.RUnlock()\n+\n+ if test.wantPendingRoute != ok {\n+ t.Errorf(\"got table.pendingRoutes[%#v] = (_, %t), want = (_, %t)\", defaultRouteKey, ok, test.wantPendingRoute)\n+ }\n+ })\n+ }\n+}\n+\n+func TestAddInstalledRouteWithPending(t *testing.T) {\n+ pkt := newPacketBuffer(\"foo\")\n+ defer pkt.DecRef()\n+\n+ testCases := []struct {\n+ name string\n+ advance time.Duration\n+ want *stack.PacketBuffer\n+ }{\n+ {\n+ name: \"not expired\",\n+ advance: DefaultPendingRouteExpiration,\n+ want: pkt,\n+ },\n+ {\n+ name: \"expired\",\n+ advance: DefaultPendingRouteExpiration + 1,\n+ want: nil,\n+ },\n+ }\n+\n+ for _, test := range testCases {\n+ t.Run(test.name, func(t *testing.T) {\n+ clock := faketime.NewManualClock()\n+\n+ table := RouteTable{}\n+ config := defaultConfig(withClock(clock))\n+\n+ if err := table.Init(config); err != nil {\n+ t.Fatalf(\"table.Init(%#v): %s\", config, err)\n+ }\n+ // Disable the cleanup routine.\n+ table.cleanupPendingRoutesTimer.Stop()\n+\n+ if _, err := table.GetRouteOrInsertPending(defaultRouteKey, pkt); err != nil {\n+ t.Fatalf(\"table.GetRouteOrInsertPending(%#v, %#v): %v\", defaultRouteKey, pkt, err)\n+ }\n+\n+ clock.Advance(test.advance)\n+ route := table.NewInstalledRoute(inputNICID, defaultOutgoingInterfaces)\npendingRoute, wasPending := table.AddInstalledRoute(defaultRouteKey, route)\n+\n+ if test.want == nil {\n+ if wasPending {\n+ t.Errorf(\"got table.AddInstalledRoute(%#v, %#v) = (%#v, true), want = (_, false)\", defaultRouteKey, route, pendingRoute)\n+ }\n+ } else {\nif !wasPending {\nt.Fatalf(\"got table.AddInstalledRoute(%#v, %#v) = (nil, false), want = (_, true)\", defaultRouteKey, route)\n}\n- // Verify that packets are properly dequeued from the PendingRoute.\npkt, err := pendingRoute.Dequeue()\nif err != nil {\nt.Fatalf(\"got pendingRoute.Dequeue() = (_, %v), want = (_, nil)\", err)\n}\n- if !cmp.Equal(wantPkt.Views(), pkt.Views()) {\n- t.Errorf(\"got pendingRoute.Dequeue() = (%v, nil), want = (%v, nil)\", pkt.Views(), wantPkt.Views())\n+ if !cmp.Equal(test.want.Views(), pkt.Views()) {\n+ t.Errorf(\"got pkt = %v, want = %v\", pkt.Views(), test.want.Views())\n}\n-\n- if !pendingRoute.IsEmpty() {\n- t.Errorf(\"got pendingRoute.IsEmpty() = false, want = true\")\n}\n- // Verify that the pending route is deleted (not returned on subsequent\n- // calls to AddInstalledRoute).\n- pendingRoute, wasPending = table.AddInstalledRoute(defaultRouteKey, route)\n- if wasPending {\n- t.Errorf(\"got table.AddInstalledRoute(%#v, %#v) = (%#v, true), want (_, false)\", defaultRouteKey, route, pendingRoute)\n+ // Verify that the pending route is actually deleted.\n+ table.pendingMu.RLock()\n+ if pendingRoute, ok := table.pendingRoutes[defaultRouteKey]; ok {\n+ t.Errorf(\"got table.pendingRoutes[%#v] = (%#v, true), want (_, false)\", defaultRouteKey, pendingRoute)\n+ }\n+ table.pendingMu.RUnlock()\n+ })\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Expire pending multicast packets/routes.
Updates #7338.
PiperOrigin-RevId: 445231315 |
259,985 | 28.04.2022 13:42:29 | 25,200 | 47b5915a7b31922d83473156f4679a8891ee98e6 | Break Task.mu -> kernfs.Filesystem.mu lock chain when managing cgroups.
This led to circular locking since procfs aquires Task.mu while
holding kernfs.Filesystem.mu. The procfs case is harder to break, as
procfs needs to acquire an mm reference during a filesystem operation. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/kernfs.go",
"new_path": "pkg/sentry/fsimpl/kernfs/kernfs.go",
"diff": "// Lock ordering:\n//\n// kernfs.Filesystem.mu\n+// kernel.TaskSet.mu\n+// kernel.Task.mu\n// kernfs.Dentry.dirMu\n// vfs.VirtualFilesystem.mountMu\n// vfs.Dentry.mu\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/cgroup.go",
"new_path": "pkg/sentry/kernel/cgroup.go",
"diff": "@@ -91,6 +91,8 @@ type Cgroup struct {\nCgroupImpl\n}\n+// decRef drops a reference on the cgroup. This must happen outside a Task.mu\n+// critical section.\nfunc (c *Cgroup) decRef() {\nc.Dentry.DecRef(context.Background())\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/kernel.go",
"new_path": "pkg/sentry/kernel/kernel.go",
"diff": "@@ -1871,7 +1871,11 @@ func (k *Kernel) PopulateNewCgroupHierarchy(root Cgroup) {\n// hierarchy with the provided id. This is intended for use during hierarchy\n// teardown, as otherwise the tasks would be orphaned w.r.t to some controllers.\nfunc (k *Kernel) ReleaseCgroupHierarchy(hid uint32) {\n+ var releasedCGs []Cgroup\n+\nk.tasks.mu.RLock()\n+ // We'll have one cgroup per hierarchy per task.\n+ releasedCGs = make([]Cgroup, 0, len(k.tasks.Root.tids))\nk.tasks.forEachTaskLocked(func(t *Task) {\nif t.exitState != TaskExitNone {\nreturn\n@@ -1879,12 +1883,22 @@ func (k *Kernel) ReleaseCgroupHierarchy(hid uint32) {\nt.mu.Lock()\nfor cg := range t.cgroups {\nif cg.HierarchyID() == hid {\n- t.leaveCgroupLocked(cg)\n+ cg.Leave(t)\n+ delete(t.cgroups, cg)\n+ releasedCGs = append(releasedCGs, cg)\n+ // A task can't be part of multiple cgroups from the same\n+ // hierarchy, so we can skip checking the rest once we find a\n+ // match.\n+ break\n}\n}\nt.mu.Unlock()\n})\nk.tasks.mu.RUnlock()\n+\n+ for _, c := range releasedCGs {\n+ c.decRef()\n+ }\n}\nfunc (k *Kernel) ReplaceFSContextRoots(ctx context.Context, oldRoot vfs.VirtualDentry, newRoot vfs.VirtualDentry) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_cgroup.go",
"new_path": "pkg/sentry/kernel/task_cgroup.go",
"diff": "@@ -90,18 +90,16 @@ func (t *Task) enterCgroupIfNotYetLocked(c Cgroup) {\n// LeaveCgroups removes t out from all its cgroups.\nfunc (t *Task) LeaveCgroups() {\nt.mu.Lock()\n- defer t.mu.Unlock()\n- for c, _ := range t.cgroups {\n- t.leaveCgroupLocked(c)\n- }\n-}\n-\n-// +checklocks:t.mu\n-func (t *Task) leaveCgroupLocked(c Cgroup) {\n+ cgs := t.cgroups\n+ t.cgroups = nil\n+ for c := range cgs {\nc.Leave(t)\n- delete(t.cgroups, c)\n+ }\n+ t.mu.Unlock()\n+ for c := range cgs {\nc.decRef()\n}\n+}\n// +checklocks:t.mu\nfunc (t *Task) findCgroupWithMatchingHierarchyLocked(other Cgroup) (Cgroup, bool) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Break Task.mu -> kernfs.Filesystem.mu lock chain when managing cgroups.
This led to circular locking since procfs aquires Task.mu while
holding kernfs.Filesystem.mu. The procfs case is harder to break, as
procfs needs to acquire an mm reference during a filesystem operation.
PiperOrigin-RevId: 445237505 |
259,907 | 28.04.2022 18:45:28 | 25,200 | 71764f1b8c3d56bbcdf30e2617a480f8980d6bcd | Generalize lisafs testsuite for external users. | [
{
"change_type": "MODIFY",
"old_path": "pkg/lisafs/testsuite/testsuite.go",
"new_path": "pkg/lisafs/testsuite/testsuite.go",
"diff": "@@ -51,15 +51,20 @@ type Tester interface {\n// RunAllLocalFSTests runs all local FS tests as subtests.\nfunc RunAllLocalFSTests(t *testing.T, tester Tester) {\n- refs.SetLeakMode(refs.LeaksPanic)\nfor name, testFn := range localFSTests {\n- runServerClient(t, tester, name, testFn)\n+ mountPath, err := ioutil.TempDir(os.Getenv(\"TEST_TMPDIR\"), \"\")\n+ if err != nil {\n+ t.Fatalf(\"creation of temporary mountpoint failed: %v\", err)\n+ }\n+ RunTest(t, tester, name, testFn, mountPath)\n+ os.RemoveAll(mountPath)\n}\n}\n-type testFunc func(context.Context, *testing.T, Tester, lisafs.ClientFD)\n+// TestFunc describes the signature of a test method.\n+type TestFunc func(context.Context, *testing.T, Tester, lisafs.ClientFD)\n-var localFSTests map[string]testFunc = map[string]testFunc{\n+var localFSTests map[string]TestFunc = map[string]TestFunc{\n\"Stat\": testStat,\n\"RegularFileIO\": testRegularFileIO,\n\"RegularFileOpen\": testRegularFileOpen,\n@@ -75,13 +80,9 @@ var localFSTests map[string]testFunc = map[string]testFunc{\n\"Getdents\": testGetdents,\n}\n-func runServerClient(t *testing.T, tester Tester, testName string, testFn testFunc) {\n- mountPath, err := ioutil.TempDir(os.Getenv(\"TEST_TMPDIR\"), \"\")\n- if err != nil {\n- t.Fatalf(\"creation of temporary mountpoint failed: %v\", err)\n- }\n- defer os.RemoveAll(mountPath)\n-\n+// RunTest runs the passed test function as a subtest.\n+func RunTest(t *testing.T, tester Tester, testName string, testFn TestFunc, mountPath string) {\n+ refs.SetLeakMode(refs.LeaksPanic)\n// server should run with a umask of 0, because we want to preserve file\n// modes exactly for testing purposes.\nunix.Umask(0)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Generalize lisafs testsuite for external users.
PiperOrigin-RevId: 445300994 |
259,992 | 29.04.2022 10:29:46 | 25,200 | a1aa00f92298b1ae110a3977d3814e9ca463c072 | Remove TID from task start
This was used to map kernel.Task to goroutines before
kernel.Task.GoroutineID was available. It's not needed anymore. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/kernel.go",
"new_path": "pkg/sentry/kernel/kernel.go",
"diff": "@@ -1090,9 +1090,7 @@ func (k *Kernel) CreateProcess(args CreateProcessArgs) (*ThreadGroup, ThreadID,\n// StartProcess starts running a process that was created with CreateProcess.\nfunc (k *Kernel) StartProcess(tg *ThreadGroup) {\n- t := tg.Leader()\n- tid := k.tasks.Root.IDOfTask(t)\n- t.Start(tid)\n+ tg.Leader().Start()\n}\n// Start starts execution of all tasks in k.\n@@ -1122,8 +1120,8 @@ func (k *Kernel) Start() error {\n// Start task goroutines.\nk.tasks.mu.RLock()\ndefer k.tasks.mu.RUnlock()\n- for t, tid := range k.tasks.Root.tids {\n- t.Start(tid)\n+ for t := range k.tasks.Root.tids {\n+ t.Start()\n}\nreturn nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_clone.go",
"new_path": "pkg/sentry/kernel/task_clone.go",
"diff": "@@ -243,8 +243,7 @@ func (t *Task) Clone(args *linux.CloneArgs) (ThreadID, *SyscallControl, error) {\n// This has to happen last, because e.g. ptraceClone may send a SIGSTOP to\n// nt that it must receive before its task goroutine starts running.\n- tid := nt.k.tasks.Root.IDOfTask(nt)\n- defer nt.Start(tid)\n+ defer nt.Start()\nif args.Flags&linux.CLONE_THREAD == 0 && seccheck.Global.Enabled(seccheck.PointCloneProcess) {\nmask, info := getCloneSeccheckInfo(t, nt)\n@@ -288,7 +287,7 @@ func (t *Task) Clone(args *linux.CloneArgs) (ThreadID, *SyscallControl, error) {\nntid.CopyOut(t, hostarch.Addr(args.ParentTID))\n}\n- t.traceCloneEvent(tid)\n+ t.traceCloneEvent(nt.k.tasks.Root.IDOfTask(nt))\nkind := ptraceCloneKindClone\nif args.Flags&linux.CLONE_VFORK != 0 {\nkind = ptraceCloneKindVfork\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_run.go",
"new_path": "pkg/sentry/kernel/task_run.go",
"diff": "@@ -51,11 +51,7 @@ type taskRunState interface {\n}\n// run runs the task goroutine.\n-//\n-// threadID a dummy value set to the task's TID in the root PID namespace to\n-// make it visible in stack dumps. A goroutine for a given task can be identified\n-// searching for Task.run()'s argument value.\n-func (t *Task) run(threadID uintptr) {\n+func (t *Task) run() {\nt.goid.Store(goid.Get())\n// Construct t.blockingTimer here. We do this here because we can't\n@@ -103,8 +99,6 @@ func (t *Task) run(threadID uintptr) {\n// Deferring this store triggers a false positive in the race\n// detector (https://github.com/golang/go/issues/42599).\nt.goid.Store(0)\n- // Keep argument alive because stack trace for dead variables may not be correct.\n- runtime.KeepAlive(threadID)\nreturn\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_start.go",
"new_path": "pkg/sentry/kernel/task_start.go",
"diff": "@@ -347,11 +347,7 @@ func (ns *PIDNamespace) allocateTID() (ThreadID, error) {\n// Start starts the task goroutine. Start must be called exactly once for each\n// task returned by NewTask.\n-//\n-// 'tid' must be the task's TID in the root PID namespace and it's used for\n-// debugging purposes only (set as parameter to Task.run to make it visible\n-// in stack dumps).\n-func (t *Task) Start(tid ThreadID) {\n+func (t *Task) Start() {\n// If the task was restored, it may be \"starting\" after having already exited.\nif t.runState == nil {\nreturn\n@@ -364,6 +360,5 @@ func (t *Task) Start(tid ThreadID) {\n// Task is now running in system mode.\nt.accountTaskGoroutineLeave(TaskGoroutineNonexistent)\n- // Use the task's TID in the root PID namespace to make it visible in stack dumps.\n- go t.run(uintptr(tid)) // S/R-SAFE: synchronizes with saving through stops\n+ go t.run() // S/R-SAFE: synchronizes with saving through stops\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove TID from task start
This was used to map kernel.Task to goroutines before
kernel.Task.GoroutineID was available. It's not needed anymore.
PiperOrigin-RevId: 445452190 |
259,858 | 29.04.2022 16:49:03 | 25,200 | efdf8dd715649b3c47e7c24bafb3cb94bf4de1f8 | Don't push images or the website on tag builds.
Updates | [
{
"change_type": "MODIFY",
"old_path": ".buildkite/release.yaml",
"new_path": ".buildkite/release.yaml",
"diff": "@@ -9,21 +9,21 @@ _templates:\nlimit: 10\n- exit_status: \"*\"\nlimit: 2\n- # This is enforced by the environment hooks on the release agents\n- # as well, only the master branch may be built there.\n- if: build.branch == \"master\" || build.tag != null\nsteps:\n- <<: *common\nlabel: \":ship: Push all images (x86_64)\"\n+ if: build.branch == \"master\" && build.tag == null\ncommands:\n- make ARCH=x86_64 push-all-images\n- <<: *common\nlabel: \":ship: Push all images (aarch64)\"\n+ if: build.branch == \"master\" && build.tag == null\ncommands:\n- make ARCH=aarch64 push-all-images\n- <<: *common\nlabel: \":ship: Release\"\n+ if: build.branch == \"master\" || build.tag != null\ncommands:\n- make BAZEL_OPTIONS=--config=x86_64 artifacts/x86_64\n- make BAZEL_OPTIONS=--config=aarch64 artifacts/aarch64\n@@ -31,6 +31,7 @@ steps:\n- cd repo && gsutil cp -r . gs://gvisor/releases/\n- <<: *common\nlabel: \":ship: Website Deploy\"\n+ if: build.branch == \"master\" && build.tag == null\ncommands:\n# The built website image must be x86_64.\n- make BAZEL_OPTIONS=--config=x86_64 website-deploy\n"
}
] | Go | Apache License 2.0 | google/gvisor | Don't push images or the website on tag builds.
Updates #7327
PiperOrigin-RevId: 445535035 |
259,962 | 29.04.2022 17:31:00 | 25,200 | 2d9f1c33297f2803d4eca89ebfeff7cd9ac4138d | Add test to verify zero linger behavior. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ip_tcp_generic.cc",
"new_path": "test/syscalls/linux/socket_ip_tcp_generic.cc",
"diff": "@@ -885,6 +885,27 @@ TEST_P(TCPSocketPairTest, SetTCPLingerTimeoutZero) {\nAnyOf(Eq(kMaxTCPLingerTimeout), Eq(kOldMaxTCPLingerTimeout)));\n}\n+TEST_P(TCPSocketPairTest, SoLingerOptionWithReset) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ // Set and get SO_LINGER with zero timeout.\n+ struct linger sl;\n+ sl.l_onoff = 1;\n+ sl.l_linger = 0;\n+ ASSERT_THAT(\n+ setsockopt(sockets->first_fd(), SOL_SOCKET, SO_LINGER, &sl, sizeof(sl)),\n+ SyscallSucceeds());\n+ char buf[1000] = {};\n+ ASSERT_THAT(RetryEINTR(write)(sockets->first_fd(), buf, sizeof(buf)),\n+ SyscallSucceedsWithValue(sizeof(buf)));\n+\n+ ASSERT_THAT(close(sockets->release_first_fd()), SyscallSucceeds());\n+\n+ write(sockets->second_fd(), buf, sizeof(buf));\n+ ASSERT_THAT(RetryEINTR(read)(sockets->second_fd(), buf, sizeof(buf)),\n+ SyscallSucceedsWithValue(sizeof(buf)));\n+}\n+\nTEST_P(TCPSocketPairTest, SetTCPLingerTimeoutAboveMax) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add test to verify zero linger behavior.
PiperOrigin-RevId: 445541797 |
259,962 | 29.04.2022 17:31:17 | 25,200 | 19e9ee104a7920342d25705d1bf4de24c4d3faf5 | Bump default gonet.ListenTCP backlog to 4096.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/adapters/gonet/gonet.go",
"new_path": "pkg/tcpip/adapters/gonet/gonet.go",
"diff": "@@ -64,6 +64,14 @@ func NewTCPListener(s *stack.Stack, wq *waiter.Queue, ep tcpip.Endpoint) *TCPLis\n}\n}\n+// maxListenBacklog is set to be reasonably high for most uses of gonet. Go net\n+// package uses the value in /proc/sys/net/core/somaxconn file in Linux as the\n+// default listen backlog. The value below matches the default in common linux\n+// distros.\n+//\n+// See: https://cs.opensource.google/go/go/+/refs/tags/go1.18.1:src/net/sock_linux.go;drc=refs%2Ftags%2Fgo1.18.1;l=66\n+const maxListenBacklog = 4096\n+\n// ListenTCP creates a new TCPListener.\nfunc ListenTCP(s *stack.Stack, addr tcpip.FullAddress, network tcpip.NetworkProtocolNumber) (*TCPListener, error) {\n// Create a TCP endpoint, bind it, then start listening.\n@@ -83,7 +91,7 @@ func ListenTCP(s *stack.Stack, addr tcpip.FullAddress, network tcpip.NetworkProt\n}\n}\n- if err := ep.Listen(10); err != nil {\n+ if err := ep.Listen(maxListenBacklog); err != nil {\nep.Close()\nreturn nil, &net.OpError{\nOp: \"listen\",\n"
}
] | Go | Apache License 2.0 | google/gvisor | Bump default gonet.ListenTCP backlog to 4096.
Fixes #7379
PiperOrigin-RevId: 445541836 |
259,962 | 29.04.2022 17:37:20 | 25,200 | 2b0646de86b2506c0219433b821956bfa3a0a059 | Move datagram_test to transport_test package.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/datagram_test.go",
"new_path": "pkg/tcpip/transport/datagram_test.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// Package datagram_test has tests shared by datagram-based transport endpoints.\n-package datagram_test\n+// Package transport_test has tests shared by datagram-based transport endpoints.\n+package transport_test\nimport (\n\"fmt\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | Move datagram_test to transport_test package.
Fixes #7392
PiperOrigin-RevId: 445542709 |
259,992 | 02.05.2022 10:57:49 | 25,200 | 3b269001eba65cb87a731b26fe6dbdf2e9e82000 | Add container/start context fields
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/metadata.go",
"new_path": "pkg/sentry/seccheck/metadata.go",
"diff": "@@ -193,6 +193,7 @@ func init() {\nName: \"env\",\n},\n},\n+ ContextFields: defaultContextFields,\n})\n// Points from the sentry namespace.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/points/container.proto",
"new_path": "pkg/sentry/seccheck/points/container.proto",
"diff": "@@ -24,4 +24,6 @@ message Start {\nstring cwd = 3;\nrepeated string args = 4;\nrepeated string env = 5;\n+ // Set to true when TTY is enabled (e.g. -t docker flag).\n+ bool terminal = 6;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader.go",
"new_path": "runsc/boot/loader.go",
"diff": "@@ -639,8 +639,11 @@ func (l *Loader) run() error {\n// Create the root container init task. It will begin running\n// when the kernel is started.\n- var err error\n- _, ep.tty, ep.ttyVFS2, err = l.createContainerProcess(true, l.sandboxID, &l.root)\n+ var (\n+ tg *kernel.ThreadGroup\n+ err error\n+ )\n+ tg, ep.tty, ep.ttyVFS2, err = l.createContainerProcess(true, l.sandboxID, &l.root)\nif err != nil {\nreturn err\n}\n@@ -650,15 +653,18 @@ func (l *Loader) run() error {\nId: l.sandboxID,\nCwd: l.root.spec.Process.Cwd,\nArgs: l.root.spec.Process.Args,\n+ Terminal: l.root.spec.Process.Terminal,\n}\nfields := seccheck.Global.GetFieldSet(seccheck.PointContainerStart)\nif fields.Local.Contains(seccheck.ContainerStartFieldEnv) {\nevt.Env = l.root.spec.Process.Env\n}\n-\n- ctx := l.root.procArgs.NewContext(l.k)\n+ if !fields.Context.Empty() {\n+ evt.ContextData = &pb.ContextData{}\n+ kernel.LoadSeccheckData(tg.Leader(), fields.Context, evt.ContextData)\n+ }\n_ = seccheck.Global.SendToCheckers(func(c seccheck.Checker) error {\n- return c.ContainerStart(ctx, fields, &evt)\n+ return c.ContainerStart(context.Background(), fields, &evt)\n})\n}\n}\n@@ -795,14 +801,18 @@ func (l *Loader) startSubcontainer(spec *specs.Spec, conf *config.Config, cid st\nId: cid,\nCwd: spec.Process.Cwd,\nArgs: spec.Process.Args,\n+ Terminal: spec.Process.Terminal,\n}\nfields := seccheck.Global.GetFieldSet(seccheck.PointContainerStart)\nif fields.Local.Contains(seccheck.ContainerStartFieldEnv) {\nevt.Env = spec.Process.Env\n}\n- ctx := info.procArgs.NewContext(l.k)\n+ if !fields.Context.Empty() {\n+ evt.ContextData = &pb.ContextData{}\n+ kernel.LoadSeccheckData(ep.tg.Leader(), fields.Context, evt.ContextData)\n+ }\n_ = seccheck.Global.SendToCheckers(func(c seccheck.Checker) error {\n- return c.ContainerStart(ctx, fields, &evt)\n+ return c.ContainerStart(context.Background(), fields, &evt)\n})\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add container/start context fields
Updates #4805
PiperOrigin-RevId: 445976770 |
259,909 | 02.05.2022 11:38:55 | 25,200 | 32c474d82f653e0d25b77fb07f29f55a769802a0 | Allow multiple FUSE filesystems to share a connection.
Before this change FUSE connections were shared 1:1 with FUSE filesystems, which
is incorrect behavior. A FUSE FD should have a 1:1 relationship with a FUSE
connection, and any number of FUSE filesystems can use the same connection. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/fuse/BUILD",
"new_path": "pkg/sentry/fsimpl/fuse/BUILD",
"diff": "@@ -32,6 +32,7 @@ go_library(\n\"connection.go\",\n\"connection_control.go\",\n\"dev.go\",\n+ \"dev_state.go\",\n\"directory.go\",\n\"file.go\",\n\"fusefs.go\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/fuse/connection.go",
"new_path": "pkg/sentry/fsimpl/fuse/connection.go",
"diff": "@@ -202,6 +202,7 @@ func (conn *connection) loadInitializedChan(closed bool) {\n}\n// newFUSEConnection creates a FUSE connection to fuseFD.\n+// +checklocks:fuseFD.mu\nfunc newFUSEConnection(_ context.Context, fuseFD *DeviceFD, opts *filesystemOptions) (*connection, error) {\n// Mark the device as ready so it can be used.\n// FIXME(gvisor.dev/issue/4813): fuseFD's fields are accessed without\n@@ -210,12 +211,10 @@ func newFUSEConnection(_ context.Context, fuseFD *DeviceFD, opts *filesystemOpti\n// Create the writeBuf for the header to be stored in.\nhdrLen := uint32((*linux.FUSEHeaderOut)(nil).SizeBytes())\n- fuseFD.mu.Lock()\nfuseFD.writeBuf = make([]byte, hdrLen)\nfuseFD.completions = make(map[linux.FUSEOpID]*futureResponse)\nfuseFD.fullQueueCh = make(chan struct{}, opts.maxActiveRequests)\nfuseFD.writeCursor = 0\n- fuseFD.mu.Unlock()\nreturn &connection{\nfd: fuseFD,\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/fuse/connection_control.go",
"new_path": "pkg/sentry/fsimpl/fuse/connection_control.go",
"diff": "@@ -188,7 +188,7 @@ func (conn *connection) initProcessReply(out *linux.FUSEInitOut, hasSysAdminCap\n// It tries to acquire conn.fd.mu, conn.lock, conn.bgLock in order.\n// All possible requests waiting or blocking will be aborted.\n//\n-// Preconditions: conn.fd.mu is locked.\n+// +checklocks:conn.fd.mu\nfunc (conn *connection) Abort(ctx context.Context) {\nconn.mu.Lock()\nconn.asyncMu.Lock()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/fuse/connection_test.go",
"new_path": "pkg/sentry/fsimpl/fuse/connection_test.go",
"diff": "@@ -83,7 +83,9 @@ func TestConnectionAbort(t *testing.T) {\nfutNormal = append(futNormal, fut)\n}\n+ conn.fd.mu.Lock()\nconn.Abort(s.Ctx)\n+ conn.fd.mu.Unlock()\n// Abort should unblock the initialization channel.\n// Note: no test requests are actually blocked on `conn.initializedChan`.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/fuse/dev.go",
"new_path": "pkg/sentry/fsimpl/fuse/dev.go",
"diff": "@@ -58,77 +58,88 @@ type DeviceFD struct {\nvfs.DentryMetadataFileDescriptionImpl\nvfs.NoLockFD\n+ // waitQueue is used to notify interested parties when the device becomes\n+ // readable or writable.\n+ waitQueue waiter.Queue\n+\n+ // fullQueueCh is a channel used to synchronize the readers with the writers.\n+ // Writers (inbound requests to the filesystem) block if there are too many\n+ // unprocessed in-flight requests.\n+ fullQueueCh chan struct{} `state:\".(int)\"`\n+\n+ // mu protects all the queues, maps, buffers and cursors and nextOpID.\n+ mu sync.Mutex `state:\"nosave\"`\n+\n// nextOpID is used to create new requests.\n+ // +checklocks:mu\nnextOpID linux.FUSEOpID\n// queue is the list of requests that need to be processed by the FUSE server.\n+ // +checklocks:mu\nqueue requestList\n// numActiveRequests is the number of requests made by the Sentry that has\n// yet to be responded to.\n+ // +checklocks:mu\nnumActiveRequests uint64\n// completions is used to map a request to its response. A Writer will use this\n// to notify the caller of a completed response.\n+ // +checklocks:mu\ncompletions map[linux.FUSEOpID]*futureResponse\n+ // +checklocks:mu\nwriteCursor uint32\n// writeBuf is the memory buffer used to copy in the FUSE out header from\n// userspace.\n+ // +checklocks:mu\nwriteBuf []byte\n// writeCursorFR current FR being copied from server.\n+ // +checklocks:mu\nwriteCursorFR *futureResponse\n- // mu protects all the queues, maps, buffers and cursors and nextOpID.\n- mu sync.Mutex `state:\"nosave\"`\n-\n- // waitQueue is used to notify interested parties when the device becomes\n- // readable or writable.\n- waitQueue waiter.Queue\n-\n- // fullQueueCh is a channel used to synchronize the readers with the writers.\n- // Writers (inbound requests to the filesystem) block if there are too many\n- // unprocessed in-flight requests.\n- fullQueueCh chan struct{} `state:\".(int)\"`\n-\n- // fs is the FUSE filesystem that this FD is being used for. A reference is\n- // held on fs.\n- fs *filesystem\n-}\n-\n-func (fd *DeviceFD) saveFullQueueCh() int {\n- return cap(fd.fullQueueCh)\n-}\n-\n-func (fd *DeviceFD) loadFullQueueCh(capacity int) {\n- fd.fullQueueCh = make(chan struct{}, capacity)\n+ // conn is the FUSE connection that this FD is being used for.\n+ // +checklocks:mu\n+ conn *connection\n}\n// Release implements vfs.FileDescriptionImpl.Release.\nfunc (fd *DeviceFD) Release(ctx context.Context) {\n- if fd.fs != nil {\n- fd.fs.conn.mu.Lock()\n- fd.fs.conn.connected = false\n- fd.fs.conn.mu.Unlock()\n+ fd.mu.Lock()\n+ defer fd.mu.Unlock()\n+ if fd.conn != nil {\n+ fd.conn.mu.Lock()\n+ fd.conn.connected = false\n+ fd.conn.mu.Unlock()\n- fd.fs.VFSFilesystem().DecRef(ctx)\n- fd.fs = nil\n+ fd.conn.Abort(ctx) // +checklocksforce: fd.conn.fd.mu=fd.mu\n+ fd.waitQueue.Notify(waiter.ReadableEvents)\n+ fd.conn = nil\n}\n}\n-// filesystemIsInitialized returns true if fd.fs is set and the connection is\n-// initialized.\n-func (fd *DeviceFD) filesystemIsInitialized() bool {\n- // FIXME(gvisor.dev/issue/4813): Access to fd.fs should be synchronized.\n- return fd.fs != nil\n+// connected returns true if fd.conn is set and the connection has not been\n+// aborted.\n+// +checklocks:fd.mu\n+func (fd *DeviceFD) connected() bool {\n+ if fd.conn != nil {\n+ fd.conn.mu.Lock()\n+ defer fd.conn.mu.Unlock()\n+ return fd.conn.connected\n+ }\n+ return false\n}\n// PRead implements vfs.FileDescriptionImpl.PRead.\nfunc (fd *DeviceFD) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts vfs.ReadOptions) (int64, error) {\n- // Operations on /dev/fuse don't make sense until a FUSE filesystem is mounted.\n- if !fd.filesystemIsInitialized() {\n+ // Operations on /dev/fuse don't make sense until a FUSE filesystem is\n+ // mounted. If there is an active connection we know there is at least one\n+ // filesystem mounted.\n+ fd.mu.Lock()\n+ defer fd.mu.Unlock()\n+ if !fd.connected() {\nreturn 0, linuxerr.EPERM\n}\n@@ -137,8 +148,12 @@ func (fd *DeviceFD) PRead(ctx context.Context, dst usermem.IOSequence, offset in\n// Read implements vfs.FileDescriptionImpl.Read.\nfunc (fd *DeviceFD) Read(ctx context.Context, dst usermem.IOSequence, opts vfs.ReadOptions) (int64, error) {\n- // Operations on /dev/fuse don't make sense until a FUSE filesystem is mounted.\n- if !fd.filesystemIsInitialized() {\n+ // Operations on /dev/fuse don't make sense until a FUSE filesystem is\n+ // mounted. If there is an active connection we know there is at least one\n+ // filesystem mounted.\n+ fd.mu.Lock()\n+ defer fd.mu.Unlock()\n+ if !fd.connected() {\nreturn 0, linuxerr.EPERM\n}\n@@ -150,11 +165,9 @@ func (fd *DeviceFD) Read(ctx context.Context, dst usermem.IOSequence, opts vfs.R\ninHdrLen := uint32((*linux.FUSEHeaderIn)(nil).SizeBytes())\nwriteHdrLen := uint32((*linux.FUSEWriteIn)(nil).SizeBytes())\n- fd.mu.Lock()\n- defer fd.mu.Unlock()\n- fd.fs.conn.mu.Lock()\n- negotiatedMinBuffSize := inHdrLen + writeHdrLen + fd.fs.conn.maxWrite\n- fd.fs.conn.mu.Unlock()\n+ fd.conn.mu.Lock()\n+ negotiatedMinBuffSize := inHdrLen + writeHdrLen + fd.conn.maxWrite\n+ fd.conn.mu.Unlock()\nif minBuffSize < negotiatedMinBuffSize {\nminBuffSize = negotiatedMinBuffSize\n}\n@@ -231,8 +244,12 @@ func (fd *DeviceFD) readLocked(ctx context.Context, dst usermem.IOSequence, opts\n// PWrite implements vfs.FileDescriptionImpl.PWrite.\nfunc (fd *DeviceFD) PWrite(ctx context.Context, src usermem.IOSequence, offset int64, opts vfs.WriteOptions) (int64, error) {\n- // Operations on /dev/fuse don't make sense until a FUSE filesystem is mounted.\n- if !fd.filesystemIsInitialized() {\n+ // Operations on /dev/fuse don't make sense until a FUSE filesystem is\n+ // mounted. If there is an active connection we know there is at least one\n+ // filesystem mounted.\n+ fd.mu.Lock()\n+ defer fd.mu.Unlock()\n+ if !fd.connected() {\nreturn 0, linuxerr.EPERM\n}\n@@ -249,16 +266,13 @@ func (fd *DeviceFD) Write(ctx context.Context, src usermem.IOSequence, opts vfs.\n// writeLocked implements writing to the fuse device while locked with DeviceFD.mu.\n// +checklocks:fd.mu\nfunc (fd *DeviceFD) writeLocked(ctx context.Context, src usermem.IOSequence, opts vfs.WriteOptions) (int64, error) {\n- // Operations on /dev/fuse don't make sense until a FUSE filesystem is mounted.\n- if !fd.filesystemIsInitialized() {\n+ // Operations on /dev/fuse don't make sense until a FUSE filesystem is\n+ // mounted. If there is an active connection we know there is at least one\n+ // filesystem mounted.\n+ if !fd.connected() {\nreturn 0, linuxerr.EPERM\n}\n- // Return ENODEV if the filesystem is umounted.\n- if fd.fs.umounted {\n- return 0, linuxerr.ENODEV\n- }\n-\nvar cn, n int64\nhdrLen := uint32((*linux.FUSEHeaderOut)(nil).SizeBytes())\n@@ -363,7 +377,7 @@ func (fd *DeviceFD) Readiness(mask waiter.EventMask) waiter.EventMask {\nfunc (fd *DeviceFD) readinessLocked(mask waiter.EventMask) waiter.EventMask {\nvar ready waiter.EventMask\n- if !fd.filesystemIsInitialized() || fd.fs.umounted {\n+ if !fd.connected() {\nready |= waiter.EventErr\nreturn ready & mask\n}\n@@ -380,12 +394,16 @@ func (fd *DeviceFD) readinessLocked(mask waiter.EventMask) waiter.EventMask {\n// EventRegister implements waiter.Waitable.EventRegister.\nfunc (fd *DeviceFD) EventRegister(e *waiter.Entry) error {\n+ fd.mu.Lock()\n+ defer fd.mu.Unlock()\nfd.waitQueue.EventRegister(e)\nreturn nil\n}\n// EventUnregister implements waiter.Waitable.EventUnregister.\nfunc (fd *DeviceFD) EventUnregister(e *waiter.Entry) {\n+ fd.mu.Lock()\n+ defer fd.mu.Unlock()\nfd.waitQueue.EventUnregister(e)\n}\n@@ -396,8 +414,12 @@ func (fd *DeviceFD) Epollable() bool {\n// Seek implements vfs.FileDescriptionImpl.Seek.\nfunc (fd *DeviceFD) Seek(ctx context.Context, offset int64, whence int32) (int64, error) {\n- // Operations on /dev/fuse don't make sense until a FUSE filesystem is mounted.\n- if !fd.filesystemIsInitialized() {\n+ // Operations on /dev/fuse don't make sense until a FUSE filesystem is\n+ // mounted. If there is an active connection we know there is at least one\n+ // filesystem mounted.\n+ fd.mu.Lock()\n+ defer fd.mu.Unlock()\n+ if !fd.connected() {\nreturn 0, linuxerr.EPERM\n}\n@@ -406,7 +428,7 @@ func (fd *DeviceFD) Seek(ctx context.Context, offset int64, whence int32) (int64\n// sendResponse sends a response to the waiting task (if any).\n//\n-// Preconditions: fd.mu must be held.\n+// +checklocks:fd.mu\nfunc (fd *DeviceFD) sendResponse(ctx context.Context, fut *futureResponse) error {\n// Signal the task waiting on a response if any.\ndefer close(fut.ch)\n@@ -427,7 +449,7 @@ func (fd *DeviceFD) sendResponse(ctx context.Context, fut *futureResponse) error\n// sendError sends an error response to the waiting task (if any) by calling sendResponse().\n//\n-// Preconditions: fd.mu must be held.\n+// +checklocks:fd.mu\nfunc (fd *DeviceFD) sendError(ctx context.Context, errno int32, unique linux.FUSEOpID) error {\n// Return the error to the calling task.\noutHdrLen := uint32((*linux.FUSEHeaderOut)(nil).SizeBytes())\n@@ -451,12 +473,13 @@ func (fd *DeviceFD) sendError(ctx context.Context, errno int32, unique linux.FUS\n// asyncCallBack executes pre-defined callback function for async requests.\n// Currently used by: FUSE_INIT.\n+// +checklocks:fd.mu\nfunc (fd *DeviceFD) asyncCallBack(ctx context.Context, r *Response) error {\nswitch r.opcode {\ncase linux.FUSE_INIT:\ncreds := auth.CredentialsFromContext(ctx)\nrootUserNs := kernel.KernelFromContext(ctx).RootUserNamespace()\n- return fd.fs.conn.InitRecv(r, creds.HasCapabilityIn(linux.CAP_SYS_ADMIN, rootUserNs))\n+ return fd.conn.InitRecv(r, creds.HasCapabilityIn(linux.CAP_SYS_ADMIN, rootUserNs))\n// TODO(gvisor.dev/issue/3247): support async read: correctly process the response.\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fsimpl/fuse/dev_state.go",
"diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package fuse\n+\n+func (fd *DeviceFD) saveFullQueueCh() int {\n+ return cap(fd.fullQueueCh)\n+}\n+\n+func (fd *DeviceFD) loadFullQueueCh(capacity int) {\n+ fd.fullQueueCh = make(chan struct{}, capacity)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/fuse/dev_test.go",
"new_path": "pkg/sentry/fsimpl/fuse/dev_test.go",
"diff": "@@ -136,6 +136,29 @@ func TestFUSECommunication(t *testing.T) {\n}\n}\n+func TestReuseFd(t *testing.T) {\n+ s := setup(t)\n+ defer s.Destroy()\n+ k := kernel.KernelFromContext(s.Ctx)\n+ _, fd, err := newTestConnection(s, k, maxActiveRequestsDefault)\n+ if err != nil {\n+ t.Fatalf(\"newTestConnection: %v\", err)\n+ }\n+ fs1, err := newTestFilesystem(s, fd, maxActiveRequestsDefault)\n+ if err != nil {\n+ t.Fatalf(\"newTestFilesystem: %v\", err)\n+ }\n+ defer fs1.Release(s.Ctx)\n+ fs2, err := newTestFilesystem(s, fd, maxActiveRequestsDefault)\n+ if err != nil {\n+ t.Fatalf(\"newTestFilesystem: %v\", err)\n+ }\n+ defer fs2.Release(s.Ctx)\n+ if fs1.conn != fs2.conn {\n+ t.Errorf(\"second fs connection = %v, want = %v\", fs2.conn, fs1.conn)\n+ }\n+}\n+\n// CallTest makes a request to the server and blocks the invoking\n// goroutine until a server responds with a response. Doesn't block\n// a kernel.Task. Analogous to Connection.Call but used for testing.\n@@ -143,7 +166,7 @@ func CallTest(conn *connection, t *kernel.Task, r *Request, i uint32) (*Response\nconn.fd.mu.Lock()\n// Wait until we're certain that a new request can be processed.\n- for conn.fd.numActiveRequests == conn.fd.fs.opts.maxActiveRequests {\n+ for conn.fd.numActiveRequests == conn.maxActiveRequests {\nconn.fd.mu.Unlock()\nselect {\ncase <-conn.fd.fullQueueCh:\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/fuse/fusefs.go",
"new_path": "pkg/sentry/fsimpl/fuse/fusefs.go",
"diff": "@@ -31,7 +31,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n- \"gvisor.dev/gvisor/pkg/waiter\"\n)\n// Name is the default filesystem name.\n@@ -97,9 +96,6 @@ type filesystem struct {\n// opts is the options the fusefs is initialized with.\nopts *filesystemOptions\n-\n- // umounted is true if filesystem.Release() has been called.\n- umounted bool\n}\n// Name implements vfs.FilesystemType.Name.\n@@ -233,20 +229,25 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nreturn nil, nil, linuxerr.EINVAL\n}\n+ fuseFD.mu.Lock()\n+ connected := fuseFD.connected()\n// Create a new FUSE filesystem.\nfs, err := newFUSEFilesystem(ctx, vfsObj, &fsType, fuseFD, devMinor, &fsopts)\nif err != nil {\nlog.Warningf(\"%s.NewFUSEFilesystem: failed with error: %v\", fsType.Name(), err)\n+ fuseFD.mu.Unlock()\nreturn nil, nil, err\n}\n+ fuseFD.mu.Unlock()\n// Send a FUSE_INIT request to the FUSE daemon server before returning.\n// This call is not blocking.\n+ if !connected {\nif err := fs.conn.InitSend(creds, uint32(kernelTask.ThreadID())); err != nil {\nlog.Warningf(\"%s.InitSend: failed with error: %v\", fsType.Name(), err)\n- fs.VFSFilesystem().DecRef(ctx) // returned by newFUSEFilesystem\nreturn nil, nil, err\n}\n+ }\n// root is the fusefs root directory.\nroot := fs.newRoot(ctx, creds, fsopts.rootMode)\n@@ -255,45 +256,28 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\n}\n// newFUSEFilesystem creates a new FUSE filesystem.\n+// +checklocks:fuseFD.mu\nfunc newFUSEFilesystem(ctx context.Context, vfsObj *vfs.VirtualFilesystem, fsType *FilesystemType, fuseFD *DeviceFD, devMinor uint32, opts *filesystemOptions) (*filesystem, error) {\n+ if !fuseFD.connected() {\nconn, err := newFUSEConnection(ctx, fuseFD, opts)\nif err != nil {\nlog.Warningf(\"fuse.NewFUSEFilesystem: NewFUSEConnection failed with error: %v\", err)\nreturn nil, linuxerr.EINVAL\n}\n+ fuseFD.conn = conn\n+ }\nfs := &filesystem{\ndevMinor: devMinor,\nopts: opts,\n- conn: conn,\n+ conn: fuseFD.conn,\n}\nfs.VFSFilesystem().Init(vfsObj, fsType, fs)\n-\n- // FIXME(gvisor.dev/issue/4813): Doesn't conn or fs need to hold a\n- // reference on fuseFD, since conn uses fuseFD for communication with the\n- // server? Wouldn't doing so create a circular reference?\n- fs.VFSFilesystem().IncRef() // for fuseFD.fs\n-\n- fuseFD.mu.Lock()\n- fs.conn.mu.Lock()\n- fuseFD.fs = fs\n- fs.conn.mu.Unlock()\n- fuseFD.mu.Unlock()\n-\nreturn fs, nil\n}\n// Release implements vfs.FilesystemImpl.Release.\nfunc (fs *filesystem) Release(ctx context.Context) {\n- fs.conn.fd.mu.Lock()\n-\n- fs.umounted = true\n- fs.conn.Abort(ctx)\n- // Notify all the waiters on this fd.\n- fs.conn.fd.waitQueue.Notify(waiter.ReadableEvents)\n-\n- fs.conn.fd.mu.Unlock()\n-\nfs.Filesystem.VFSFilesystem().VirtualFilesystem().PutAnonBlockDevMinor(fs.devMinor)\nfs.Filesystem.Release(ctx)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/fuse/utils_test.go",
"new_path": "pkg/sentry/fsimpl/fuse/utils_test.go",
"diff": "package fuse\nimport (\n+ \"fmt\"\n\"testing\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n@@ -60,9 +61,37 @@ func newTestConnection(system *testutil.System, k *kernel.Kernel, maxActiveReque\nfsopts := filesystemOptions{\nmaxActiveRequests: maxActiveRequests,\n}\n- fs, err := newFUSEFilesystem(system.Ctx, system.VFS, &FilesystemType{}, fuseDev, 0, &fsopts)\n+ fuseDev.mu.Lock()\n+ conn, err := newFUSEConnection(system.Ctx, fuseDev, &fsopts)\nif err != nil {\nreturn nil, nil, err\n}\n- return fs.conn, &fuseDev.vfsfd, nil\n+ fuseDev.conn = conn\n+ fuseDev.mu.Unlock()\n+\n+ // Fake the connection being properly initialized for testing purposes.\n+ conn.mu.Lock()\n+ conn.connInitSuccess = true\n+ conn.mu.Unlock()\n+ return conn, &fuseDev.vfsfd, nil\n+}\n+\n+// newTestFilesystem creates a filesystem that the sentry can communicate with\n+// and the FD for the server to communicate with.\n+func newTestFilesystem(system *testutil.System, fd *vfs.FileDescription, maxActiveRequests uint64) (*filesystem, error) {\n+ fuseFD, ok := fd.Impl().(*DeviceFD)\n+ if !ok {\n+ return nil, fmt.Errorf(\"newTestFilesystem: FD is %T, not a FUSE device\", fd)\n+ }\n+ fsopts := filesystemOptions{\n+ maxActiveRequests: maxActiveRequests,\n+ }\n+\n+ fuseFD.mu.Lock()\n+ defer fuseFD.mu.Unlock()\n+ fs, err := newFUSEFilesystem(system.Ctx, system.VFS, &FilesystemType{}, fuseFD, 0, &fsopts)\n+ if err != nil {\n+ return nil, err\n+ }\n+ return fs, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/fuse/BUILD",
"new_path": "test/fuse/BUILD",
"diff": "@@ -76,3 +76,8 @@ syscall_test(\nfuse = \"True\",\ntest = \"//test/fuse/linux:setstat_test\",\n)\n+\n+syscall_test(\n+ fuse = \"True\",\n+ test = \"//test/fuse/linux:mount_test\",\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/fuse/linux/BUILD",
"new_path": "test/fuse/linux/BUILD",
"diff": "@@ -252,8 +252,12 @@ cc_binary(\nsrcs = [\"mount_test.cc\"],\ndeps = [\ngtest,\n+ \":fuse_base\",\n+ \"//test/util:fs_util\",\n+ \"//test/util:fuse_util\",\n\"//test/util:mount_util\",\n\"//test/util:temp_path\",\n+ \"//test/util:temp_umask\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "test/fuse/linux/fuse_base.cc",
"new_path": "test/fuse/linux/fuse_base.cc",
"diff": "#include <sys/uio.h>\n#include <unistd.h>\n+#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n#include \"absl/strings/str_format.h\"\n#include \"test/util/fuse_util.h\"\n@@ -149,13 +150,20 @@ void FuseTest::SetServerInodeLookup(const std::string& path, mode_t mode,\nWaitServerComplete();\n}\n-void FuseTest::MountFuse(const char* mountOpts) {\n- EXPECT_THAT(dev_fd_ = open(\"/dev/fuse\", O_RDWR), SyscallSucceeds());\n+void FuseTest::MountFuse(const char* mount_opts) {\n+ int dev_fd;\n+ EXPECT_THAT(dev_fd = open(\"/dev/fuse\", O_RDWR), SyscallSucceeds());\n+ std::string fmt_mount_opts = absl::StrFormat(\"fd=%d,%s\", dev_fd, mount_opts);\n+ TempPath mount_point = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ MountFuse(dev_fd, mount_point, fmt_mount_opts.c_str());\n+}\n- std::string mount_opts = absl::StrFormat(\"fd=%d,%s\", dev_fd_, mountOpts);\n- mount_point_ = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+void FuseTest::MountFuse(int fd, TempPath& mount_point,\n+ const char* mount_opts) {\n+ mount_point_ = std::move(mount_point);\n+ dev_fd_ = fd;\nEXPECT_THAT(mount(\"fuse\", mount_point_.path().c_str(), \"fuse\",\n- MS_NODEV | MS_NOSUID, mount_opts.c_str()),\n+ MS_NODEV | MS_NOSUID, mount_opts),\nSyscallSucceeds());\n}\n@@ -163,6 +171,7 @@ void FuseTest::UnmountFuse() {\nEXPECT_THAT(umount(mount_point_.path().c_str()), SyscallSucceeds());\nshutdown(sock_[0], SHUT_RDWR);\nfuse_server_->Join();\n+ EXPECT_THAT(close(dev_fd_), SyscallSucceeds());\n// TODO(gvisor.dev/issue/3330): ensure the process is terminated successfully.\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/fuse/linux/fuse_base.h",
"new_path": "test/fuse/linux/fuse_base.h",
"diff": "@@ -170,9 +170,14 @@ class FuseTest : public ::testing::Test {\nprotected:\nTempPath mount_point_;\n+ int dev_fd_;\n// Opens /dev/fuse and inherit the file descriptor for the FUSE server.\n- void MountFuse(const char* mountOpts = kMountOpts);\n+ void MountFuse(const char* mount_opts = kMountOpts);\n+\n+ // Mounts a fuse fs with a fuse fd connection at the specified point.\n+ void MountFuse(int fd, TempPath& mount_point,\n+ const char* mount_opts = kMountOpts);\n// Creates a socketpair for communication and forks FUSE server.\nvoid SetUpFuseServer(\n@@ -236,7 +241,6 @@ class FuseTest : public ::testing::Test {\n// Responds an error header to /dev/fuse when bad thing happens.\nvoid ServerRespondFuseError(uint64_t unique);\n- int dev_fd_;\nint sock_[2];\nstd::unique_ptr<ScopedThread> fuse_server_;\n"
},
{
"change_type": "MODIFY",
"old_path": "test/fuse/linux/mount_test.cc",
"new_path": "test/fuse/linux/mount_test.cc",
"diff": "#include <unistd.h>\n#include \"gtest/gtest.h\"\n+#include \"test/fuse/linux/fuse_base.h\"\n+#include \"test/util/fs_util.h\"\n+#include \"test/util/fuse_util.h\"\n#include \"test/util/mount_util.h\"\n#include \"test/util/temp_path.h\"\n+#include \"test/util/temp_umask.h\"\n#include \"test/util/test_util.h\"\nnamespace gvisor {\n@@ -27,6 +31,65 @@ namespace testing {\nnamespace {\n+class MountTest : public FuseTest {\n+ protected:\n+ void CheckFUSECreateFile(std::string_view test_file_path) {\n+ std::string_view test_file_name = Basename(test_file_path.data());\n+ const mode_t mode = S_IFREG | S_IRWXU | S_IRWXG | S_IRWXO;\n+ // Ensure the file doesn't exist.\n+ struct fuse_out_header out_header = {\n+ .len = sizeof(struct fuse_out_header),\n+ .error = -ENOENT,\n+ };\n+ auto iov_out = FuseGenerateIovecs(out_header);\n+ SetServerResponse(FUSE_LOOKUP, iov_out);\n+\n+ // creat(2) is equal to open(2) with open_flags O_CREAT | O_WRONLY |\n+ // O_TRUNC.\n+ const mode_t new_mask = S_IWGRP | S_IWOTH;\n+ const int open_flags = O_CREAT | O_WRONLY | O_TRUNC;\n+ out_header.error = 0;\n+ out_header.len = sizeof(struct fuse_out_header) +\n+ sizeof(struct fuse_entry_out) +\n+ sizeof(struct fuse_open_out);\n+ struct fuse_entry_out entry_payload = DefaultEntryOut(mode & ~new_mask, 2);\n+ struct fuse_open_out out_payload = {\n+ .fh = 1,\n+ .open_flags = open_flags,\n+ };\n+ iov_out = FuseGenerateIovecs(out_header, entry_payload, out_payload);\n+ SetServerResponse(FUSE_CREATE, iov_out);\n+\n+ int fd;\n+ TempUmask mask(new_mask);\n+ EXPECT_THAT(fd = creat(test_file_path.data(), mode), SyscallSucceeds());\n+ EXPECT_THAT(fcntl(fd, F_GETFL),\n+ SyscallSucceedsWithValue(open_flags & O_ACCMODE));\n+\n+ struct fuse_in_header in_header;\n+ struct fuse_create_in in_payload;\n+ std::vector<char> name(test_file_name.size() + 1);\n+ auto iov_in = FuseGenerateIovecs(in_header, in_payload, name);\n+\n+ // Skip the request of FUSE_LOOKUP.\n+ SkipServerActualRequest();\n+\n+ // Get the first FUSE_CREATE.\n+ GetServerActualRequest(iov_in);\n+ EXPECT_EQ(in_header.len, sizeof(in_header) + sizeof(in_payload) +\n+ test_file_name.size() + 1);\n+ EXPECT_EQ(in_header.opcode, FUSE_CREATE);\n+ EXPECT_EQ(in_payload.flags, open_flags);\n+ EXPECT_EQ(in_payload.mode, mode & ~new_mask);\n+ EXPECT_EQ(in_payload.umask, new_mask);\n+ EXPECT_EQ(std::string(name.data()), test_file_name);\n+\n+ EXPECT_THAT(close(fd), SyscallSucceeds());\n+ // Skip the FUSE_RELEASE.\n+ SkipServerActualRequest();\n+ }\n+};\n+\nTEST(FuseMount, Success) {\nconst FileDescriptor fd =\nASSERT_NO_ERRNO_AND_VALUE(Open(\"/dev/fuse\", O_WRONLY));\n@@ -93,6 +156,27 @@ TEST(FuseMount, BadFD) {\nSyscallFailsWithErrno(EINVAL));\n}\n+TEST_F(MountTest, ReuseFD) {\n+ std::string mopts =\n+ absl::StrFormat(\"fd=%d,user_id=%d,group_id=%d,rootmode=0777\", dev_fd_,\n+ getuid(), getgid());\n+\n+ const std::string test_file1_path =\n+ JoinPath(mount_point_.path().c_str(), \"testfile1\");\n+ CheckFUSECreateFile(test_file1_path);\n+\n+ auto mount_point1 = std::move(mount_point_);\n+\n+ auto dir2 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ MountFuse(dev_fd_, dir2, mopts.c_str());\n+\n+ std::string test_file2_path =\n+ JoinPath(mount_point_.path().c_str(), \"testfile2\");\n+ CheckFUSECreateFile(test_file2_path);\n+\n+ EXPECT_THAT(umount(mount_point1.path().c_str()), SyscallSucceeds());\n+}\n+\n} // namespace\n} // namespace testing\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow multiple FUSE filesystems to share a connection.
Before this change FUSE connections were shared 1:1 with FUSE filesystems, which
is incorrect behavior. A FUSE FD should have a 1:1 relationship with a FUSE
connection, and any number of FUSE filesystems can use the same connection.
PiperOrigin-RevId: 445988328 |
259,858 | 02.05.2022 12:34:27 | 25,200 | 87180c225b6756edde0b7fb742288233c6c722c4 | Stop clobbering the signed packages.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "tools/make_apt.sh",
"new_path": "tools/make_apt.sh",
"diff": "@@ -92,7 +92,7 @@ keyid=$(\nawk '{print $2;}')\nreadonly keyid\n-# Copy the packages into the root.\n+# Copy the packages into the pool.\nfor pkg in \"$@\"; do\nif ! [[ -f \"${pkg}\" ]]; then\ncontinue\n@@ -110,17 +110,22 @@ for pkg in \"$@\"; do\nversion=${version// /} # Ditto.\ndestdir=\"${root}/pool/${version}/binary-${arch}\"\n- # Copy & sign the package.\n+ # Copy & sign the package, only if not in the pool already.\nmkdir -p \"${destdir}\"\n+ if ! [[ -f \"${destdir}/${name}.deb\" ]]; then\n+ # Copy the file.\ncp -a -L \"$(dirname \"${pkg}\")/${name}.deb\" \"${destdir}\"\n- if [[ -f \"$(dirname \"${pkg}\")/${name}.changes\" ]]; then\n- cp -a -L \"$(dirname \"${pkg}\")/${name}.changes\" \"${destdir}\"\n- fi\n- chmod 0644 \"${destdir}\"/\"${name}\".*\n+ chmod 0644 \"${destdir}\"/\"${name}\".deb\n# Sign a package only if it isn't signed yet.\n# We use [*] here to expand the gpg_opts array into a single shell-word.\ndpkg-sig -g \"${gpg_opts[*]}\" --verify \"${destdir}/${name}.deb\" ||\ndpkg-sig -g \"${gpg_opts[*]}\" --sign builder -k \"${keyid}\" \"${destdir}/${name}.deb\"\n+ fi\n+ if [[ -f \"$(dirname \"${pkg}\")/${name}.changes\" ]] && ! [[ -f \"${destdir}/${name}.changes\" ]]; then\n+ # Copy the changes file.\n+ cp -a -L \"$(dirname \"${pkg}\")/${name}.changes\" \"${destdir}\"\n+ chmod 0644 \"${destdir}\"/\"${name}\".changes\n+ fi\ndone\n# Build the package list.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Stop clobbering the signed packages.
Fixes #5635
PiperOrigin-RevId: 446002436 |
259,898 | 02.05.2022 15:27:07 | 25,200 | 4ee0a226fe86226766ed02e36d69424214ac9def | Remove unnecessary cleanupLocked
handshakeFailed already calls cleanupLocked at the end, there's no need to
cleanup twice the same endpoint. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -2488,7 +2488,6 @@ func (e *endpoint) Shutdown(flags tcpip.ShutdownFlags) tcpip.Error {\n// method because that method is called during a close(2) (and closing a\n// connecting socket is not an error).\ne.handshakeFailed(&tcpip.ErrConnectionReset{})\n- e.cleanupLocked()\ne.waiterQueue.Notify(waiter.WritableEvents | waiter.EventHUp | waiter.EventErr)\nreturn nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove unnecessary cleanupLocked
handshakeFailed already calls cleanupLocked at the end, there's no need to
cleanup twice the same endpoint.
PiperOrigin-RevId: 446043917 |
259,891 | 16.09.2021 17:18:19 | 25,200 | 88b2fc0942ea567768eef5427d1c0630b8a83a9c | hostinet: allow getsockopt(SO_RCVTIMEO) and getsockopt(SO_SNDTIMEO)
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/hostinet/socket.go",
"new_path": "pkg/sentry/socket/hostinet/socket.go",
"diff": "@@ -401,6 +401,8 @@ func (s *socketOpsCommon) GetSockOpt(t *kernel.Task, level int, name int, optVal\noptlen = sizeofInt32\ncase linux.SO_LINGER:\noptlen = unix.SizeofLinger\n+ case linux.SO_RCVTIMEO, linux.SO_SNDTIMEO:\n+ optlen = linux.SizeOfTimeval\n}\ncase linux.SOL_TCP:\nswitch name {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/filter/config.go",
"new_path": "runsc/boot/filter/config.go",
"diff": "@@ -474,6 +474,16 @@ func hostInetFilters() seccomp.SyscallRules {\nseccomp.EqualTo(unix.SOL_SOCKET),\nseccomp.EqualTo(unix.SO_TIMESTAMP),\n},\n+ {\n+ seccomp.MatchAny{},\n+ seccomp.EqualTo(unix.SOL_SOCKET),\n+ seccomp.EqualTo(unix.SO_RCVTIMEO),\n+ },\n+ {\n+ seccomp.MatchAny{},\n+ seccomp.EqualTo(unix.SOL_SOCKET),\n+ seccomp.EqualTo(unix.SO_SNDTIMEO),\n+ },\n{\nseccomp.MatchAny{},\nseccomp.EqualTo(unix.SOL_TCP),\n"
}
] | Go | Apache License 2.0 | google/gvisor | hostinet: allow getsockopt(SO_RCVTIMEO) and getsockopt(SO_SNDTIMEO)
Fixes #6603 |
259,907 | 02.05.2022 17:36:40 | 25,200 | ea45573148e0656e5e3412f5a5db9cd823f5a2a0 | Update comments about tmpfs size.
Removed old TODO from VFS1. We will not support this option on VFS1.
Enhanced comments about how tmpfs pages are accounted for by write(2)s. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/tmpfs/tmpfs.go",
"new_path": "pkg/sentry/fs/tmpfs/tmpfs.go",
"diff": "@@ -40,7 +40,7 @@ var fsInfo = fs.Info{\n// of 0. To work around this, claim to have a very large but non-zero size,\n// chosen to ensure that BlockSize * Blocks does not overflow int64 (which\n// applications may also handle incorrectly).\n- // TODO(b/29637826): allow configuring a tmpfs size and enforce it.\n+ // NOTE(b/29637826): Support for configurable tmpfs size was added to VFS2.\nTotalBlocks: math.MaxInt64 / hostarch.PageSize,\nFreeBlocks: math.MaxInt64 / hostarch.PageSize,\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go",
"diff": "@@ -453,6 +453,10 @@ func (fd *regularFileFD) pwrite(ctx context.Context, src usermem.IOSequence, off\nif err != nil {\nreturn 0, offset, err\n}\n+\n+ // Reserve enough space assuming the entire write was successful. The\n+ // corresponding update to f.size is done in WriteFromBlocks() which is\n+ // called via src.CopyInTo() below.\nmaybeSizeInc := false\nsrc = src.TakeFirst64(srclen)\nif uint64(end) > f.size.Load() {\n@@ -461,9 +465,13 @@ func (fd *regularFileFD) pwrite(ctx context.Context, src usermem.IOSequence, off\nreturn 0, 0, err\n}\n}\n+\n+ // Perform the write.\nrw := getRegularFileReadWriter(f, offset)\nn, err := src.CopyInTo(ctx, rw)\n- if unwritten := srclen - n; maybeSizeInc && unwritten != 0 {\n+\n+ // Correct page accounting if this was a partial write.\n+ if maybeSizeInc && srclen-n != 0 {\nif err := f.inode.fs.updatePagesUsed(uint64(end), f.size.Load()); err != nil {\nreturn 0, 0, err\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update comments about tmpfs size.
- Removed old TODO from VFS1. We will not support this option on VFS1.
- Enhanced comments about how tmpfs pages are accounted for by write(2)s.
PiperOrigin-RevId: 446072121 |
260,004 | 03.05.2022 21:15:10 | 25,200 | da0c67b92a733ac4460791be41815ca33a9ceab1 | Use different flags for IPV6_RECVERR and IP_RECVERR | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/netstack.go",
"new_path": "pkg/sentry/socket/netstack/netstack.go",
"diff": "@@ -1447,7 +1447,7 @@ func getSockOptIPv6(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, name\nreturn nil, syserr.ErrInvalidArgument\n}\n- v := primitive.Int32(boolToInt32(ep.SocketOptions().GetRecvError()))\n+ v := primitive.Int32(boolToInt32(ep.SocketOptions().GetIPv6RecvError()))\nreturn &v, nil\ncase linux.IPV6_RECVORIGDSTADDR:\n@@ -1647,7 +1647,7 @@ func getSockOptIP(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, name in\nreturn nil, syserr.ErrInvalidArgument\n}\n- v := primitive.Int32(boolToInt32(ep.SocketOptions().GetRecvError()))\n+ v := primitive.Int32(boolToInt32(ep.SocketOptions().GetIPv4RecvError()))\nreturn &v, nil\ncase linux.IP_PKTINFO:\n@@ -2338,7 +2338,7 @@ func setSockOptIPv6(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, name\nif err != nil {\nreturn err\n}\n- ep.SocketOptions().SetRecvError(v != 0)\n+ ep.SocketOptions().SetIPv6RecvError(v != 0)\nreturn nil\ncase linux.IP6T_SO_SET_REPLACE:\n@@ -2555,7 +2555,7 @@ func setSockOptIP(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, name in\nif err != nil {\nreturn err\n}\n- ep.SocketOptions().SetRecvError(v != 0)\n+ ep.SocketOptions().SetIPv4RecvError(v != 0)\nreturn nil\ncase linux.IP_PKTINFO:\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/socketops.go",
"new_path": "pkg/tcpip/socketops.go",
"diff": "@@ -212,9 +212,13 @@ type SocketOptions struct {\n// the incoming packet should be returned as an ancillary message.\nreceiveOriginalDstAddress atomicbitops.Uint32\n- // recvErrEnabled determines whether extended reliable error message passing\n- // is enabled.\n- recvErrEnabled atomicbitops.Uint32\n+ // ipv4RecvErrEnabled determines whether extended reliable error message\n+ // passing is enabled for IPv4.\n+ ipv4RecvErrEnabled atomicbitops.Uint32\n+\n+ // ipv6RecvErrEnabled determines whether extended reliable error message\n+ // passing is enabled for IPv6.\n+ ipv6RecvErrEnabled atomicbitops.Uint32\n// errQueue is the per-socket error queue. It is protected by errQueueMu.\nerrQueueMu sync.Mutex `state:\"nosave\"`\n@@ -470,14 +474,27 @@ func (so *SocketOptions) SetReceiveOriginalDstAddress(v bool) {\nstoreAtomicBool(&so.receiveOriginalDstAddress, v)\n}\n-// GetRecvError gets value for IP*_RECVERR option.\n-func (so *SocketOptions) GetRecvError() bool {\n- return so.recvErrEnabled.Load() != 0\n+// GetIPv4RecvError gets value for IP_RECVERR option.\n+func (so *SocketOptions) GetIPv4RecvError() bool {\n+ return so.ipv4RecvErrEnabled.Load() != 0\n+}\n+\n+// SetIPv4RecvError sets value for IP_RECVERR option.\n+func (so *SocketOptions) SetIPv4RecvError(v bool) {\n+ storeAtomicBool(&so.ipv4RecvErrEnabled, v)\n+ if !v {\n+ so.pruneErrQueue()\n+ }\n+}\n+\n+// GetIPv6RecvError gets value for IPV6_RECVERR option.\n+func (so *SocketOptions) GetIPv6RecvError() bool {\n+ return so.ipv6RecvErrEnabled.Load() != 0\n}\n-// SetRecvError sets value for IP*_RECVERR option.\n-func (so *SocketOptions) SetRecvError(v bool) {\n- storeAtomicBool(&so.recvErrEnabled, v)\n+// SetIPv6RecvError sets value for IPV6_RECVERR option.\n+func (so *SocketOptions) SetIPv6RecvError(v bool) {\n+ storeAtomicBool(&so.ipv6RecvErrEnabled, v)\nif !v {\nso.pruneErrQueue()\n}\n@@ -627,7 +644,7 @@ func (so *SocketOptions) PeekErr() *SockError {\n// QueueErr inserts the error at the back of the error queue.\n//\n-// Preconditions: so.GetRecvError() == true.\n+// Preconditions: so.GetIPv4RecvError() or so.GetIPv6RecvError() is true.\nfunc (so *SocketOptions) QueueErr(err *SockError) {\nso.errQueueMu.Lock()\ndefer so.errQueueMu.Unlock()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/integration/link_resolution_test.go",
"new_path": "pkg/tcpip/tests/integration/link_resolution_test.go",
"diff": "@@ -324,7 +324,8 @@ func TestTCPLinkResolutionFailure(t *testing.T) {\ndefer clientEP.Close()\nsockOpts := clientEP.SocketOptions()\n- sockOpts.SetRecvError(true)\n+ sockOpts.SetIPv4RecvError(true)\n+ sockOpts.SetIPv6RecvError(true)\nremoteAddr := listenerAddr\nremoteAddr.Addr = test.remoteAddr\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -2840,8 +2840,17 @@ func (e *endpoint) onICMPError(err tcpip.Error, transErr stack.TransportError, p\ne.lastError = err\ne.lastErrorMu.Unlock()\n- // Update the error queue if IP_RECVERR is enabled.\n- if e.SocketOptions().GetRecvError() {\n+ var recvErr bool\n+ switch pkt.NetworkProtocolNumber {\n+ case header.IPv4ProtocolNumber:\n+ recvErr = e.SocketOptions().GetIPv4RecvError()\n+ case header.IPv6ProtocolNumber:\n+ recvErr = e.SocketOptions().GetIPv6RecvError()\n+ default:\n+ panic(fmt.Sprintf(\"unhandled network protocol number = %d\", pkt.NetworkProtocolNumber))\n+ }\n+\n+ if recvErr {\ne.SocketOptions().QueueErr(&tcpip.SockError{\nErr: err,\nCause: transErr,\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -401,7 +401,7 @@ func (e *endpoint) prepareForWrite(p tcpip.Payloader, opts tcpip.WriteOptions) (\n// errors aren't report to the error queue at all.\nif ctx.PacketInfo().NetProto == header.IPv6ProtocolNumber {\nso := e.SocketOptions()\n- if so.GetRecvError() {\n+ if so.GetIPv6RecvError() {\nso.QueueLocalErr(\n&tcpip.ErrMessageTooLong{},\ne.net.NetProto(),\n@@ -996,8 +996,17 @@ func (e *endpoint) onICMPError(err tcpip.Error, transErr stack.TransportError, p\ne.lastError = err\ne.lastErrorMu.Unlock()\n- // Update the error queue if IP_RECVERR is enabled.\n- if e.SocketOptions().GetRecvError() {\n+ var recvErr bool\n+ switch pkt.NetworkProtocolNumber {\n+ case header.IPv4ProtocolNumber:\n+ recvErr = e.SocketOptions().GetIPv4RecvError()\n+ case header.IPv6ProtocolNumber:\n+ recvErr = e.SocketOptions().GetIPv6RecvError()\n+ default:\n+ panic(fmt.Sprintf(\"unhandled network protocol number = %d\", pkt.NetworkProtocolNumber))\n+ }\n+\n+ if recvErr {\n// Linux passes the payload without the UDP header.\nvar payload []byte\nudp := header.UDP(pkt.Data().AsRange().ToOwnedView())\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/udp_socket.cc",
"new_path": "test/syscalls/linux/udp_socket.cc",
"diff": "@@ -811,6 +811,48 @@ TEST_P(UdpSocketTest, ConnectAndSendNoReceiver) {\n}\n#ifdef __linux__\n+TEST_P(UdpSocketTest, RecvErrorConnRefusedOtherAFSockOpt) {\n+ int got;\n+ socklen_t got_len = sizeof(got);\n+ if (GetParam() == AF_INET) {\n+ EXPECT_THAT(setsockopt(sock_.get(), SOL_IPV6, IPV6_RECVERR, &kSockOptOn,\n+ sizeof(kSockOptOn)),\n+ SyscallFailsWithErrno(ENOPROTOOPT));\n+ EXPECT_THAT(getsockopt(sock_.get(), SOL_IPV6, IPV6_RECVERR, &got, &got_len),\n+ SyscallFailsWithErrno(ENOTSUP));\n+ ASSERT_THAT(got_len, sizeof(got));\n+ return;\n+ }\n+ ASSERT_THAT(setsockopt(sock_.get(), SOL_IP, IP_RECVERR, &kSockOptOn,\n+ sizeof(kSockOptOn)),\n+ SyscallSucceeds());\n+ {\n+ EXPECT_THAT(getsockopt(sock_.get(), SOL_IP, IP_RECVERR, &got, &got_len),\n+ SyscallSucceeds());\n+ ASSERT_THAT(got_len, sizeof(got));\n+ EXPECT_THAT(got, kSockOptOn);\n+ }\n+\n+ // We will simulate an ICMP error and verify that we don't receive that error\n+ // via recvmsg(MSG_ERRQUEUE) since we set another address family's RECVERR\n+ // flag.\n+ ASSERT_NO_ERRNO(BindLoopback());\n+ ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());\n+ // Close the bind socket to release the port so that we get an ICMP error\n+ // when sending packets to it.\n+ ASSERT_THAT(close(bind_.release()), SyscallSucceeds());\n+\n+ // Send to an unbound port which should trigger a port unreachable error.\n+ char buf[1];\n+ EXPECT_THAT(send(sock_.get(), buf, sizeof(buf), 0),\n+ SyscallSucceedsWithValue(sizeof(buf)));\n+\n+ // Should not have the error since we did not set the right socket option.\n+ msghdr msg = {};\n+ EXPECT_THAT(recvmsg(sock_.get(), &msg, MSG_ERRQUEUE),\n+ SyscallFailsWithErrno(EAGAIN));\n+}\n+\nTEST_P(UdpSocketTest, RecvErrorConnRefused) {\n// We will simulate an ICMP error and verify that we do receive that error via\n// recvmsg(MSG_ERRQUEUE).\n@@ -829,6 +871,14 @@ TEST_P(UdpSocketTest, RecvErrorConnRefused) {\n}\nASSERT_THAT(setsockopt(sock_.get(), opt_level, opt_type, &v, optlen),\nSyscallSucceeds());\n+ {\n+ int got;\n+ socklen_t got_len = sizeof(got);\n+ EXPECT_THAT(getsockopt(sock_.get(), opt_level, opt_type, &got, &got_len),\n+ SyscallSucceeds());\n+ ASSERT_THAT(got_len, sizeof(got));\n+ EXPECT_THAT(got, kSockOptOn);\n+ }\n// Connect to loopback:bind_addr_ which should *hopefully* not be bound by an\n// UDP socket. There is no easy way to ensure that the UDP port is not bound\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use different flags for IPV6_RECVERR and IP_RECVERR
PiperOrigin-RevId: 446361103 |
259,885 | 04.05.2022 15:20:58 | 25,200 | b86c98c82bb219e9aa68b319a6aa582290a95c8b | Check file permissions before VFS2 overlayfs open. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/overlay/filesystem.go",
"new_path": "pkg/sentry/fsimpl/overlay/filesystem.go",
"diff": "@@ -782,7 +782,6 @@ func (fs *filesystem) MknodAt(ctx context.Context, rp *vfs.ResolvingPath, opts v\nfunc (fs *filesystem) OpenAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\nmayCreate := opts.Flags&linux.O_CREAT != 0\nmustCreate := opts.Flags&(linux.O_CREAT|linux.O_EXCL) == (linux.O_CREAT | linux.O_EXCL)\n- mayWrite := vfs.AccessTypesForOpenFlags(&opts).MayWrite()\nvar ds *[]*dentry\nfs.renameMu.RLock()\n@@ -803,15 +802,9 @@ func (fs *filesystem) OpenAt(ctx context.Context, rp *vfs.ResolvingPath, opts vf\nif mustCreate {\nreturn nil, linuxerr.EEXIST\n}\n- if start.isRegularFile() && mayWrite {\n- if err := rp.Mount().CheckBeginWrite(); err != nil {\n- return nil, err\n- }\n- defer rp.Mount().EndWrite()\n- if err := start.copyUpLocked(ctx); err != nil {\n+ if err := start.ensureOpenableLocked(ctx, rp, &opts); err != nil {\nreturn nil, err\n}\n- }\nstart.IncRef()\ndefer start.DecRef(ctx)\nunlock()\n@@ -861,45 +854,55 @@ afterTrailingSymlink:\nif rp.MustBeDir() && !child.isDir() {\nreturn nil, linuxerr.ENOTDIR\n}\n- if child.isRegularFile() && mayWrite {\n- if err := rp.Mount().CheckBeginWrite(); err != nil {\n- return nil, err\n- }\n- defer rp.Mount().EndWrite()\n- if err := child.copyUpLocked(ctx); err != nil {\n+ if err := child.ensureOpenableLocked(ctx, rp, &opts); err != nil {\nreturn nil, err\n}\n- }\nchild.IncRef()\ndefer child.DecRef(ctx)\nunlock()\nreturn child.openCopiedUp(ctx, rp, &opts)\n}\n-// Preconditions: If vfs.AccessTypesForOpenFlags(opts).MayWrite(), then d has\n-// been copied up.\n-func (d *dentry) openCopiedUp(ctx context.Context, rp *vfs.ResolvingPath, opts *vfs.OpenOptions) (*vfs.FileDescription, error) {\n+// Preconditions: filesystem.renameMu must be locked.\n+func (d *dentry) ensureOpenableLocked(ctx context.Context, rp *vfs.ResolvingPath, opts *vfs.OpenOptions) error {\nats := vfs.AccessTypesForOpenFlags(opts)\nif err := d.checkPermissions(rp.Credentials(), ats); err != nil {\n- return nil, err\n+ return err\n+ }\n+ switch d.mode.Load() & linux.S_IFMT {\n+ case linux.S_IFREG:\n+ if ats.MayWrite() {\n+ if err := rp.Mount().CheckBeginWrite(); err != nil {\n+ return err\n+ }\n+ defer rp.Mount().EndWrite()\n+ if err := d.copyUpLocked(ctx); err != nil {\n+ return err\n+ }\n}\n+ case linux.S_IFDIR:\n+ if ats.MayWrite() {\n+ return linuxerr.EISDIR\n+ }\n+ if opts.Flags&linux.O_CREAT != 0 {\n+ return linuxerr.EISDIR\n+ }\n+ if opts.Flags&linux.O_DIRECT != 0 {\n+ return linuxerr.EINVAL\n+ }\n+ }\n+ return nil\n+}\n+\n+// Preconditions: If vfs.AccessTypesForOpenFlags(opts).MayWrite(), then d has\n+// been copied up.\n+func (d *dentry) openCopiedUp(ctx context.Context, rp *vfs.ResolvingPath, opts *vfs.OpenOptions) (*vfs.FileDescription, error) {\nmnt := rp.Mount()\n// Directory FDs open FDs from each layer when directory entries are read,\n// so they don't require opening an FD from d.topLayer() up front.\nftype := d.mode.Load() & linux.S_IFMT\nif ftype == linux.S_IFDIR {\n- // Can't open directories with O_CREAT.\n- if opts.Flags&linux.O_CREAT != 0 {\n- return nil, linuxerr.EISDIR\n- }\n- // Can't open directories writably.\n- if ats.MayWrite() {\n- return nil, linuxerr.EISDIR\n- }\n- if opts.Flags&linux.O_DIRECT != 0 {\n- return nil, linuxerr.EINVAL\n- }\nfd := &directoryFD{}\nfd.LockFD.Init(&d.locks)\nif err := fd.vfsfd.Init(fd, opts.Flags, mnt, &d.vfsd, &vfs.FileDescriptionOptions{\n"
}
] | Go | Apache License 2.0 | google/gvisor | Check file permissions before VFS2 overlayfs open.
PiperOrigin-RevId: 446565359 |
260,004 | 05.05.2022 12:50:29 | 25,200 | bb36c43e97fdece0505d4a7df382af0fc4582b6d | Respect SO_SNDBUF for network datagram endpoints
Previously, SO_SNDBUF was effectively a no-op. The stack should make
sure that only SO_SNDBUF bytes are ever in-flight for any given
socket/endpoint.
Fuchsia Bug: | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/packet_buffer.go",
"new_path": "pkg/tcpip/stack/packet_buffer.go",
"diff": "@@ -53,6 +53,10 @@ type PacketBufferOptions struct {\n// IsForwardedPacket identifies that the PacketBuffer being created is for a\n// forwarded packet.\nIsForwardedPacket bool\n+\n+ // OnRelease is a function to be run when the packet buffer is no longer\n+ // referenced (released back to the pool).\n+ OnRelease func()\n}\n// A PacketBuffer contains all the data of a network packet.\n@@ -163,6 +167,10 @@ type PacketBuffer struct {\nNetworkPacketInfo NetworkPacketInfo\ntuple *tuple\n+\n+ // onRelease is a function to be run when the packet buffer is no longer\n+ // referenced (released back to the pool).\n+ onRelease func() `state:\"nosave\"`\n}\n// NewPacketBuffer creates a new PacketBuffer with opts.\n@@ -177,6 +185,7 @@ func NewPacketBuffer(opts PacketBufferOptions) *PacketBuffer {\npk.buf.AppendOwned(v)\n}\npk.NetworkPacketInfo.IsForwardedPacket = opts.IsForwardedPacket\n+ pk.onRelease = opts.OnRelease\npk.InitRefs()\nreturn pk\n}\n@@ -186,6 +195,10 @@ func NewPacketBuffer(opts PacketBufferOptions) *PacketBuffer {\n// pool.\nfunc (pk *PacketBuffer) DecRef() {\npk.packetBufferRefs.DecRef(func() {\n+ if pk.onRelease != nil {\n+ pk.onRelease()\n+ }\n+\npkPool.Put(pk)\n})\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/BUILD",
"new_path": "pkg/tcpip/transport/BUILD",
"diff": "@@ -19,6 +19,7 @@ go_test(\ndeps = [\n\":transport\",\n\"//pkg/tcpip\",\n+ \"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/link/loopback\",\n\"//pkg/tcpip/network/ipv4\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/datagram_test.go",
"new_path": "pkg/tcpip/transport/datagram_test.go",
"diff": "package transport_test\nimport (\n+ \"bytes\"\n\"fmt\"\n+ \"math\"\n\"testing\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/loopback\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv4\"\n@@ -126,3 +129,222 @@ func TestStateUpdates(t *testing.T) {\n})\n}\n}\n+\n+type mockEndpoint struct {\n+ disp stack.NetworkDispatcher\n+ pkts stack.PacketBufferList\n+}\n+\n+func (*mockEndpoint) MTU() uint32 {\n+ return math.MaxUint32\n+}\n+func (*mockEndpoint) Capabilities() stack.LinkEndpointCapabilities {\n+ return 0\n+}\n+func (*mockEndpoint) MaxHeaderLength() uint16 {\n+ return 0\n+}\n+func (*mockEndpoint) LinkAddress() tcpip.LinkAddress {\n+ var l tcpip.LinkAddress\n+ return l\n+}\n+func (e *mockEndpoint) WritePackets(pkts stack.PacketBufferList) (int, tcpip.Error) {\n+ pkts.IncRef()\n+ len := pkts.Len()\n+ for pkt := pkts.Front(); pkt != nil; pkt = pkt.Next() {\n+ e.pkts.PushBack(pkt)\n+ }\n+\n+ return len, nil\n+}\n+func (e *mockEndpoint) Attach(d stack.NetworkDispatcher) { e.disp = d }\n+func (e *mockEndpoint) IsAttached() bool { return e.disp != nil }\n+func (*mockEndpoint) Wait() {}\n+func (*mockEndpoint) ARPHardwareType() header.ARPHardwareType { return header.ARPHardwareNone }\n+func (*mockEndpoint) AddHeader(*stack.PacketBuffer) {}\n+func (e *mockEndpoint) releasePackets() {\n+ e.pkts.DecRef()\n+ e.pkts = stack.PacketBufferList{}\n+}\n+\n+func (e *mockEndpoint) pktsSize() int {\n+ s := 0\n+ for pkt := e.pkts.Front(); pkt != nil; pkt = pkt.Next() {\n+ s += pkt.Size() + pkt.AvailableHeaderBytes()\n+ }\n+ return s\n+}\n+\n+func TestSndBuf(t *testing.T) {\n+ const nicID = 1\n+\n+ buf := buffer.NewView(header.ICMPv4MinimumSize)\n+ header.ICMPv4(buf).SetType(header.ICMPv4Echo)\n+\n+ for _, test := range []struct {\n+ name string\n+ createEndpoint func(*stack.Stack, *waiter.Queue) (tcpip.Endpoint, error)\n+ }{\n+ {\n+ name: \"UDP\",\n+ createEndpoint: func(s *stack.Stack, wq *waiter.Queue) (tcpip.Endpoint, error) {\n+ ep, err := s.NewEndpoint(udp.ProtocolNumber, ipv4.ProtocolNumber, wq)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"s.NewEndpoint(%d, %d, _) failed: %s\", udp.ProtocolNumber, ipv4.ProtocolNumber, err)\n+ }\n+ return ep, nil\n+ },\n+ },\n+ {\n+ name: \"ICMP\",\n+ createEndpoint: func(s *stack.Stack, wq *waiter.Queue) (tcpip.Endpoint, error) {\n+ ep, err := s.NewEndpoint(icmp.ProtocolNumber4, ipv4.ProtocolNumber, wq)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"s.NewEndpoint(%d, %d, _) failed: %s\", icmp.ProtocolNumber4, ipv4.ProtocolNumber, err)\n+ }\n+ return ep, nil\n+ },\n+ },\n+ {\n+ name: \"RAW\",\n+ createEndpoint: func(s *stack.Stack, wq *waiter.Queue) (tcpip.Endpoint, error) {\n+ ep, err := s.NewRawEndpoint(udp.ProtocolNumber, ipv4.ProtocolNumber, wq, true /* associated */)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"s.NewRawEndpoint(%d, %d, _, true) failed: %s\", udp.ProtocolNumber, ipv4.ProtocolNumber, err)\n+ }\n+ return ep, nil\n+ },\n+ },\n+ } {\n+ t.Run(test.name, func(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol},\n+ TransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol, icmp.NewProtocol4},\n+ RawFactory: &raw.EndpointFactory{},\n+ })\n+ var e mockEndpoint\n+ defer e.releasePackets()\n+ if err := s.CreateNIC(nicID, &e); err != nil {\n+ t.Fatalf(\"s.CreateNIC(%d, _) failed: %s\", nicID, err)\n+ }\n+ var wq waiter.Queue\n+ ep, err := test.createEndpoint(s, &wq)\n+ if err != nil {\n+ t.Fatalf(\"test.createEndpoint(_) failed: %s\", err)\n+ }\n+ defer ep.Close()\n+\n+ addr := tcpip.ProtocolAddress{\n+ Protocol: ipv4.ProtocolNumber,\n+ AddressWithPrefix: testutil.MustParse4(\"1.2.3.4\").WithPrefix(),\n+ }\n+ if err := s.AddProtocolAddress(nicID, addr, stack.AddressProperties{}); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %#v, {}): %s\", nicID, addr, err)\n+ }\n+ s.SetRouteTable([]tcpip.Route{\n+ {\n+ Destination: header.IPv4EmptySubnet,\n+ NIC: nicID,\n+ },\n+ })\n+\n+ to := tcpip.FullAddress{NIC: nicID, Addr: testutil.MustParse4(\"1.0.0.1\"), Port: 12345}\n+ if err := ep.Connect(to); err != nil {\n+ t.Fatalf(\"ep.Connect(%#v): %s\", to, err)\n+ }\n+\n+ checkWriteFail := func() {\n+ t.Helper()\n+\n+ if got := ep.Readiness(waiter.WritableEvents); got != 0 {\n+ t.Fatalf(\"got ep.Readiness(0x%x) = 0x%x, want = 0x0\", waiter.WritableEvents, got)\n+ }\n+\n+ var r bytes.Reader\n+ r.Reset(buf[:])\n+ wantErr := &tcpip.ErrWouldBlock{}\n+ if n, err := ep.Write(&r, tcpip.WriteOptions{}); err != wantErr {\n+ t.Fatalf(\"got Write(...) = (%d, %s), want = (_, %s)\", n, err, wantErr)\n+ }\n+\n+ }\n+\n+ checkWrites := func() {\n+ t.Helper()\n+\n+ if got := ep.Readiness(waiter.WritableEvents); got != waiter.WritableEvents {\n+ t.Fatalf(\"got ep.Readiness(0x%x) = 0x%x, want = 0x%x\", waiter.WritableEvents, got, waiter.WritableEvents)\n+ }\n+\n+ var r bytes.Reader\n+ r.Reset(buf[:])\n+ if n, err := ep.Write(&r, tcpip.WriteOptions{}); err != nil {\n+ t.Fatalf(\"Write(...): %s\", err)\n+ } else if want := int64(len(buf)); n != want {\n+ t.Fatalf(\"got Write(...) = %d, want = %d\", n, want)\n+ }\n+\n+ // The next write should fail since the packet we sent before\n+ // is still held.\n+ checkWriteFail()\n+ }\n+\n+ we, ch := waiter.NewChannelEntry(waiter.WritableEvents)\n+ wq.EventRegister(&we)\n+ defer wq.EventUnregister(&we)\n+\n+ checkNoWritableEvent := func() {\n+ t.Helper()\n+\n+ select {\n+ case <-ch:\n+ t.Fatal(\"unexpected writable event\")\n+ default:\n+ }\n+ }\n+\n+ checkWritableEvent := func() {\n+ t.Helper()\n+\n+ select {\n+ case <-ch:\n+ default:\n+ t.Fatal(\"expected writable event\")\n+ }\n+ }\n+\n+ // As long as there is space in the send buffer, writes should succeed\n+ // so a send buffer of 1 allows at max 1 in-flight packet.\n+ ep.SocketOptions().SetSendBufferSize(1, true)\n+ checkWritableEvent()\n+ checkWrites()\n+ checkNoWritableEvent()\n+\n+ // Increase the size of the send buffer but still be full.\n+ inUseSize := int64(e.pktsSize())\n+ checkNoWritableEvent()\n+ ep.SocketOptions().SetSendBufferSize(inUseSize, true /* notify */)\n+ checkNoWritableEvent()\n+ checkWriteFail()\n+\n+ // Open up the send buffer by 1 byte.\n+ checkNoWritableEvent()\n+ ep.SocketOptions().SetSendBufferSize(inUseSize+1, true /* notify */)\n+ checkWritableEvent()\n+ checkWrites()\n+\n+ // We can resize the send buffer to a smaller size but it is still\n+ // full so we can't write.\n+ checkNoWritableEvent()\n+ ep.SocketOptions().SetSendBufferSize(1, true /* notify */)\n+ checkNoWritableEvent()\n+ checkWriteFail()\n+\n+ // Releasing the packets should open up the send buffer for the next\n+ // write.\n+ e.releasePackets()\n+ checkWritableEvent()\n+ checkWrites()\n+ })\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/icmp/endpoint.go",
"new_path": "pkg/tcpip/transport/icmp/endpoint.go",
"diff": "@@ -91,7 +91,7 @@ func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProt\nep.ops.InitHandler(ep, ep.stack, tcpip.GetStackSendBufferLimits, tcpip.GetStackReceiveBufferLimits)\nep.ops.SetSendBufferSize(32*1024, false /* notify */)\nep.ops.SetReceiveBufferSize(32*1024, false /* notify */)\n- ep.net.Init(s, netProto, transProto, &ep.ops)\n+ ep.net.Init(s, netProto, transProto, &ep.ops, waiterQueue)\n// Override with stack defaults.\nvar ss tcpip.SendBufferSizeOption\n@@ -105,6 +105,11 @@ func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProt\nreturn ep, nil\n}\n+// WakeupWriters implements tcpip.SocketOptionsHandler.\n+func (e *endpoint) WakeupWriters() {\n+ e.net.MaybeSignalWritable()\n+}\n+\n// UniqueID implements stack.TransportEndpoint.UniqueID.\nfunc (e *endpoint) UniqueID() uint64 {\nreturn e.uniqueID\n@@ -399,9 +404,10 @@ func send4(s *stack.Stack, ctx *network.WriteContext, ident uint16, data buffer.\nreturn &tcpip.ErrInvalidEndpointState{}\n}\n- pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n- ReserveHeaderBytes: header.ICMPv4MinimumSize + int(maxHeaderLength),\n- })\n+ pkt := ctx.TryNewPacketBuffer(header.ICMPv4MinimumSize+int(maxHeaderLength), buffer.VectorisedView{})\n+ if pkt == nil {\n+ return &tcpip.ErrWouldBlock{}\n+ }\ndefer pkt.DecRef()\nicmpv4 := header.ICMPv4(pkt.TransportHeader().Push(header.ICMPv4MinimumSize))\n@@ -440,9 +446,10 @@ func send6(s *stack.Stack, ctx *network.WriteContext, ident uint16, data buffer.\nreturn &tcpip.ErrInvalidEndpointState{}\n}\n- pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n- ReserveHeaderBytes: header.ICMPv6MinimumSize + int(maxHeaderLength),\n- })\n+ pkt := ctx.TryNewPacketBuffer(header.ICMPv6MinimumSize+int(maxHeaderLength), buffer.VectorisedView{})\n+ if pkt == nil {\n+ return &tcpip.ErrWouldBlock{}\n+ }\ndefer pkt.DecRef()\nicmpv6 := header.ICMPv6(pkt.TransportHeader().Push(header.ICMPv6MinimumSize))\n@@ -662,8 +669,11 @@ func (e *endpoint) GetRemoteAddress() (tcpip.FullAddress, tcpip.Error) {\n// Readiness returns the current readiness of the endpoint. For example, if\n// waiter.EventIn is set, the endpoint is immediately readable.\nfunc (e *endpoint) Readiness(mask waiter.EventMask) waiter.EventMask {\n- // The endpoint is always writable.\n- result := waiter.WritableEvents & mask\n+ var result waiter.EventMask\n+\n+ if e.net.HasSendSpace() {\n+ result |= waiter.WritableEvents & mask\n+ }\n// Determine if the endpoint is readable if requested.\nif (mask & waiter.ReadableEvents) != 0 {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/internal/network/BUILD",
"new_path": "pkg/tcpip/transport/internal/network/BUILD",
"diff": "@@ -17,9 +17,11 @@ go_library(\n\"//pkg/atomicbitops\",\n\"//pkg/sync\",\n\"//pkg/tcpip\",\n+ \"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/stack\",\n\"//pkg/tcpip/transport\",\n+ \"//pkg/waiter\",\n],\n)\n@@ -44,6 +46,7 @@ go_test(\n\"//pkg/tcpip/testutil\",\n\"//pkg/tcpip/transport\",\n\"//pkg/tcpip/transport/udp\",\n+ \"//pkg/waiter\",\n\"@com_github_google_go_cmp//cmp:go_default_library\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/internal/network/endpoint.go",
"new_path": "pkg/tcpip/transport/internal/network/endpoint.go",
"diff": "@@ -22,9 +22,11 @@ import (\n\"gvisor.dev/gvisor/pkg/atomicbitops\"\n\"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport\"\n+ \"gvisor.dev/gvisor/pkg/waiter\"\n)\n// Endpoint is a datagram-based endpoint. It only supports sending datagrams to\n@@ -37,6 +39,7 @@ type Endpoint struct {\nops *tcpip.SocketOptions\nnetProto tcpip.NetworkProtocolNumber\ntransProto tcpip.TransportProtocolNumber\n+ waiterQueue *waiter.Queue\nmu sync.RWMutex `state:\"nosave\"`\n// +checklocks:mu\n@@ -96,6 +99,14 @@ type Endpoint struct {\n//\n// Writes must be performed through setEndpointState.\nstate atomicbitops.Uint32\n+\n+ // Callers should not attempt to obtain sendBufferSizeInUseMu while holding\n+ // another lock on Endpoint.\n+ sendBufferSizeInUseMu sync.RWMutex `state:\"nosave\"`\n+ // sendBufferSizeInUse keeps track of the bytes in use by in-flight packets.\n+ //\n+ // +checklocks:sendBufferSizeInUseMu\n+ sendBufferSizeInUse int64 `state:\"nosave\"`\n}\n// +stateify savable\n@@ -105,7 +116,7 @@ type multicastMembership struct {\n}\n// Init initializes the endpoint.\n-func (e *Endpoint) Init(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, ops *tcpip.SocketOptions) {\n+func (e *Endpoint) Init(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, ops *tcpip.SocketOptions, waiterQueue *waiter.Queue) {\ne.mu.Lock()\nmemberships := e.multicastMemberships\ne.mu.Unlock()\n@@ -124,6 +135,7 @@ func (e *Endpoint) Init(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, tr\nops: ops,\nnetProto: netProto,\ntransProto: transProto,\n+ waiterQueue: waiterQueue,\ninfo: stack.TransportEndpointInfo{\nNetProto: netProto,\n@@ -217,11 +229,10 @@ func (e *Endpoint) calculateTTL(route *stack.Route) uint8 {\n// WriteContext holds the context for a write.\ntype WriteContext struct {\n- transProto tcpip.TransportProtocolNumber\n+ e *Endpoint\nroute *stack.Route\nttl uint8\ntos uint8\n- owner tcpip.PacketOwner\n}\n// Release releases held resources.\n@@ -249,21 +260,94 @@ func (c *WriteContext) PacketInfo() WritePacketInfo {\n}\n}\n+// TryNewPacketBuffer returns a new packet buffer iff the endpoint's send buffer\n+// is not full.\n+//\n+// If this method returns nil, the caller should wait for the endpoint to become\n+// writable.\n+func (c *WriteContext) TryNewPacketBuffer(reserveHdrBytes int, data buffer.VectorisedView) *stack.PacketBuffer {\n+ e := c.e\n+\n+ e.sendBufferSizeInUseMu.Lock()\n+ defer e.sendBufferSizeInUseMu.Unlock()\n+\n+ if !e.hasSendSpaceRLocked() {\n+ return nil\n+ }\n+\n+ // Note that we allow oversubscription - if there is any space at all in the\n+ // send buffer, we accept the full packet which may be larger than the space\n+ // available. This is because if the endpoint reports that it is writable,\n+ // a write operation should succeed.\n+ //\n+ // This matches Linux behaviour:\n+ // https://github.com/torvalds/linux/blob/38d741cb70b/include/net/sock.h#L2519\n+ // https://github.com/torvalds/linux/blob/38d741cb70b/net/core/sock.c#L2588\n+ pktSize := int64(reserveHdrBytes) + int64(data.Size())\n+ e.sendBufferSizeInUse += pktSize\n+\n+ return stack.NewPacketBuffer(stack.PacketBufferOptions{\n+ ReserveHeaderBytes: reserveHdrBytes,\n+ Data: data,\n+ OnRelease: func() {\n+ e.sendBufferSizeInUseMu.Lock()\n+ if got := e.sendBufferSizeInUse; got < pktSize {\n+ e.sendBufferSizeInUseMu.Unlock()\n+ panic(fmt.Sprintf(\"e.sendBufferSizeInUse=(%d) < pktSize(=%d)\", got, pktSize))\n+ }\n+ e.sendBufferSizeInUse -= pktSize\n+ signal := e.hasSendSpaceRLocked()\n+ e.sendBufferSizeInUseMu.Unlock()\n+\n+ // Let waiters know if we now have space in the send buffer.\n+ if signal {\n+ e.waiterQueue.Notify(waiter.WritableEvents)\n+ }\n+ },\n+ })\n+}\n+\n// WritePacket attempts to write the packet.\nfunc (c *WriteContext) WritePacket(pkt *stack.PacketBuffer, headerIncluded bool) tcpip.Error {\n- pkt.Owner = c.owner\n+ c.e.mu.RLock()\n+ pkt.Owner = c.e.owner\n+ c.e.mu.RUnlock()\nif headerIncluded {\nreturn c.route.WriteHeaderIncludedPacket(pkt)\n}\nreturn c.route.WritePacket(stack.NetworkHeaderParams{\n- Protocol: c.transProto,\n+ Protocol: c.e.transProto,\nTTL: c.ttl,\nTOS: c.tos,\n}, pkt)\n}\n+// MaybeSignalWritable signals waiters with writable events if the send buffer\n+// has space.\n+func (e *Endpoint) MaybeSignalWritable() {\n+ e.sendBufferSizeInUseMu.RLock()\n+ signal := e.hasSendSpaceRLocked()\n+ e.sendBufferSizeInUseMu.RUnlock()\n+\n+ if signal {\n+ e.waiterQueue.Notify(waiter.WritableEvents)\n+ }\n+}\n+\n+// HasSendSpace returns whether or not the send buffer has space.\n+func (e *Endpoint) HasSendSpace() bool {\n+ e.sendBufferSizeInUseMu.RLock()\n+ defer e.sendBufferSizeInUseMu.RUnlock()\n+ return e.hasSendSpaceRLocked()\n+}\n+\n+// +checklocksread:e.sendBufferSizeInUseMu\n+func (e *Endpoint) hasSendSpaceRLocked() bool {\n+ return e.ops.GetSendBufferSize() > e.sendBufferSizeInUse\n+}\n+\n// AcquireContextForWrite acquires a WriteContext.\nfunc (e *Endpoint) AcquireContextForWrite(opts tcpip.WriteOptions) (WriteContext, tcpip.Error) {\ne.mu.RLock()\n@@ -348,11 +432,10 @@ func (e *Endpoint) AcquireContextForWrite(opts tcpip.WriteOptions) (WriteContext\n}\nreturn WriteContext{\n- transProto: e.transProto,\n+ e: e,\nroute: route,\nttl: ttl,\ntos: tos,\n- owner: e.owner,\n}, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/internal/network/endpoint_test.go",
"new_path": "pkg/tcpip/transport/internal/network/endpoint_test.go",
"diff": "@@ -36,6 +36,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/transport\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/internal/network\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/udp\"\n+ \"gvisor.dev/gvisor/pkg/waiter\"\n)\nvar (\n@@ -150,7 +151,8 @@ func TestEndpointStateTransitions(t *testing.T) {\nvar ops tcpip.SocketOptions\nvar ep network.Endpoint\n- ep.Init(s, test.netProto, udp.ProtocolNumber, &ops)\n+ var wq waiter.Queue\n+ ep.Init(s, test.netProto, udp.ProtocolNumber, &ops, &wq)\ndefer ep.Close()\nif state := ep.State(); state != transport.DatagramEndpointStateInitial {\nt.Fatalf(\"got ep.State() = %s, want = %s\", state, transport.DatagramEndpointStateInitial)\n@@ -289,7 +291,8 @@ func TestBindNICID(t *testing.T) {\nvar ops tcpip.SocketOptions\nvar ep network.Endpoint\n- ep.Init(s, test.netProto, udp.ProtocolNumber, &ops)\n+ var wq waiter.Queue\n+ ep.Init(s, test.netProto, udp.ProtocolNumber, &ops, &wq)\ndefer ep.Close()\nif ep.WasBound() {\nt.Fatal(\"got ep.WasBound() = true, want = false\")\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/raw/endpoint.go",
"new_path": "pkg/tcpip/transport/raw/endpoint.go",
"diff": "@@ -133,7 +133,7 @@ func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProt\ne.ops.SetHeaderIncluded(!associated)\ne.ops.SetSendBufferSize(32*1024, false /* notify */)\ne.ops.SetReceiveBufferSize(32*1024, false /* notify */)\n- e.net.Init(s, netProto, transProto, &e.ops)\n+ e.net.Init(s, netProto, transProto, &e.ops, waiterQueue)\n// Override with stack defaults.\nvar ss tcpip.SendBufferSizeOption\n@@ -162,6 +162,11 @@ func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProt\nreturn e, nil\n}\n+// WakeupWriters implements tcpip.SocketOptionsHandler.\n+func (e *endpoint) WakeupWriters() {\n+ e.net.MaybeSignalWritable()\n+}\n+\n// HasNIC implements tcpip.SocketOptionsHandler.\nfunc (e *endpoint) HasNIC(id int32) bool {\nreturn e.stack.HasNIC(tcpip.NICID(id))\n@@ -353,10 +358,10 @@ func (e *endpoint) write(p tcpip.Payloader, opts tcpip.WriteOptions) (int64, tcp\nheader.PutChecksum(payloadBytes[ipv6ChecksumOffset:], ^xsum)\n}\n- pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n- ReserveHeaderBytes: int(ctx.PacketInfo().MaxHeaderLength),\n- Data: buffer.View(payloadBytes).ToVectorisedView(),\n- })\n+ pkt := ctx.TryNewPacketBuffer(int(ctx.PacketInfo().MaxHeaderLength), buffer.View(payloadBytes).ToVectorisedView())\n+ if pkt == nil {\n+ return 0, &tcpip.ErrWouldBlock{}\n+ }\ndefer pkt.DecRef()\nif err := ctx.WritePacket(pkt, e.ops.GetHeaderIncluded()); err != nil {\n@@ -443,8 +448,11 @@ func (*endpoint) GetRemoteAddress() (tcpip.FullAddress, tcpip.Error) {\n// Readiness implements tcpip.Endpoint.Readiness.\nfunc (e *endpoint) Readiness(mask waiter.EventMask) waiter.EventMask {\n- // The endpoint is always writable.\n- result := waiter.WritableEvents & mask\n+ var result waiter.EventMask\n+\n+ if e.net.HasSendSpace() {\n+ result |= waiter.WritableEvents & mask\n+ }\n// Determine whether the endpoint is readable.\nif (mask & waiter.ReadableEvents) != 0 {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -115,7 +115,7 @@ func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, waiterQue\ne.ops.SetMulticastLoop(true)\ne.ops.SetSendBufferSize(32*1024, false /* notify */)\ne.ops.SetReceiveBufferSize(32*1024, false /* notify */)\n- e.net.Init(s, netProto, header.UDPProtocolNumber, &e.ops)\n+ e.net.Init(s, netProto, header.UDPProtocolNumber, &e.ops, waiterQueue)\n// Override with stack defaults.\nvar ss tcpip.SendBufferSizeOption\n@@ -131,6 +131,11 @@ func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, waiterQue\nreturn e\n}\n+// WakeupWriters implements tcpip.SocketOptionsHandler.\n+func (e *endpoint) WakeupWriters() {\n+ e.net.MaybeSignalWritable()\n+}\n+\n// UniqueID implements stack.TransportEndpoint.\nfunc (e *endpoint) UniqueID() uint64 {\nreturn e.uniqueID\n@@ -453,10 +458,10 @@ func (e *endpoint) write(p tcpip.Payloader, opts tcpip.WriteOptions) (int64, tcp\ndefer udpInfo.ctx.Release()\npktInfo := udpInfo.ctx.PacketInfo()\n- pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n- ReserveHeaderBytes: header.UDPMinimumSize + int(pktInfo.MaxHeaderLength),\n- Data: udpInfo.data.ToVectorisedView(),\n- })\n+ pkt := udpInfo.ctx.TryNewPacketBuffer(header.UDPMinimumSize+int(pktInfo.MaxHeaderLength), udpInfo.data.ToVectorisedView())\n+ if pkt == nil {\n+ return 0, &tcpip.ErrWouldBlock{}\n+ }\ndefer pkt.DecRef()\n// Initialize the UDP header.\n@@ -857,8 +862,11 @@ func (e *endpoint) GetRemoteAddress() (tcpip.FullAddress, tcpip.Error) {\n// Readiness returns the current readiness of the endpoint. For example, if\n// waiter.EventIn is set, the endpoint is immediately readable.\nfunc (e *endpoint) Readiness(mask waiter.EventMask) waiter.EventMask {\n- // The endpoint is always writable.\n- result := waiter.WritableEvents & mask\n+ var result waiter.EventMask\n+\n+ if e.net.HasSendSpace() {\n+ result |= waiter.WritableEvents & mask\n+ }\n// Determine if the endpoint is readable if requested.\nif mask&waiter.ReadableEvents != 0 {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/udp_socket.cc",
"new_path": "test/syscalls/linux/udp_socket.cc",
"diff": "@@ -2393,6 +2393,47 @@ TEST_P(UdpSocketControlMessagesTest, SetAndReceivePktInfo) {\n}\n}\n+TEST_P(UdpSocketTest, SendPacketLargerThanSendBufOnNonBlockingSocket) {\n+ constexpr int kSendBufSize = 4096;\n+ ASSERT_THAT(setsockopt(sock_.get(), SOL_SOCKET, SO_SNDBUF, &kSendBufSize,\n+ sizeof(kSendBufSize)),\n+ SyscallSucceeds());\n+\n+ // Set sock to non-blocking.\n+ {\n+ int opts = 0;\n+ ASSERT_THAT(opts = fcntl(sock_.get(), F_GETFL), SyscallSucceeds());\n+ ASSERT_THAT(fcntl(sock_.get(), F_SETFL, opts | O_NONBLOCK),\n+ SyscallSucceeds());\n+ }\n+\n+ {\n+ sockaddr_storage addr = InetLoopbackAddr();\n+ ASSERT_NO_ERRNO(BindSocket(sock_.get(), AsSockAddr(&addr)));\n+ }\n+\n+ sockaddr_storage addr;\n+ socklen_t len = sizeof(sockaddr_storage);\n+ ASSERT_THAT(getsockname(sock_.get(), AsSockAddr(&addr), &len),\n+ SyscallSucceeds());\n+ ASSERT_EQ(len, addrlen_);\n+\n+ // We are allowed to send packets as large as we want as long as there is\n+ // space in the send buffer, even if the new packet will result in more bytes\n+ // being used than available in the send buffer.\n+ char buf[kSendBufSize + 1];\n+ ASSERT_THAT(\n+ sendto(sock_.get(), buf, sizeof(buf), 0, AsSockAddr(&addr), sizeof(addr)),\n+ SyscallSucceedsWithValue(sizeof(buf)));\n+\n+ // The second write may fail with EAGAIN if the previous send is still\n+ // in-flight.\n+ ASSERT_THAT(\n+ sendto(sock_.get(), buf, sizeof(buf), 0, AsSockAddr(&addr), sizeof(addr)),\n+ AnyOf(SyscallSucceedsWithValue(sizeof(buf)),\n+ SyscallFailsWithErrno(EAGAIN)));\n+}\n+\nINSTANTIATE_TEST_SUITE_P(AllInetTests, UdpSocketControlMessagesTest,\n::testing::Values(AddressFamily::kIpv4,\nAddressFamily::kIpv6,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Respect SO_SNDBUF for network datagram endpoints
Previously, SO_SNDBUF was effectively a no-op. The stack should make
sure that only SO_SNDBUF bytes are ever in-flight for any given
socket/endpoint.
Fuchsia Bug: https://fxbug.dev/99070
PiperOrigin-RevId: 446792223 |
259,992 | 06.05.2022 09:25:54 | 25,200 | a23e60af39011c95150a1184f80d97a599ac92fd | Fire clone point for thread creation
Thread creation tracking is required by Falco.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_clone.go",
"new_path": "pkg/sentry/kernel/task_clone.go",
"diff": "@@ -245,8 +245,8 @@ func (t *Task) Clone(args *linux.CloneArgs) (ThreadID, *SyscallControl, error) {\n// nt that it must receive before its task goroutine starts running.\ndefer nt.Start()\n- if args.Flags&linux.CLONE_THREAD == 0 && seccheck.Global.Enabled(seccheck.PointCloneProcess) {\n- mask, info := getCloneSeccheckInfo(t, nt)\n+ if seccheck.Global.Enabled(seccheck.PointClone) {\n+ mask, info := getCloneSeccheckInfo(t, nt, args.Flags)\nif err := seccheck.Global.SendToCheckers(func(c seccheck.Checker) error {\nreturn c.Clone(t, mask, info)\n}); err != nil {\n@@ -307,8 +307,8 @@ func (t *Task) Clone(args *linux.CloneArgs) (ThreadID, *SyscallControl, error) {\nreturn ntid, nil, nil\n}\n-func getCloneSeccheckInfo(t, nt *Task) (seccheck.FieldSet, *pb.CloneInfo) {\n- fields := seccheck.Global.GetFieldSet(seccheck.PointCloneProcess)\n+func getCloneSeccheckInfo(t, nt *Task, flags uint64) (seccheck.FieldSet, *pb.CloneInfo) {\n+ fields := seccheck.Global.GetFieldSet(seccheck.PointClone)\nt.k.tasks.mu.RLock()\ndefer t.k.tasks.mu.RUnlock()\n@@ -316,6 +316,7 @@ func getCloneSeccheckInfo(t, nt *Task) (seccheck.FieldSet, *pb.CloneInfo) {\nCreatedThreadId: int32(nt.k.tasks.Root.tids[nt]),\nCreatedThreadGroupId: int32(nt.k.tasks.Root.tgids[nt.tg]),\nCreatedThreadStartTimeNs: nt.startTime.Nanoseconds(),\n+ Flags: flags,\n}\nif !fields.Context.Empty() {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_exit.go",
"new_path": "pkg/sentry/kernel/task_exit.go",
"diff": "@@ -662,12 +662,9 @@ func (t *Task) exitNotifyLocked(fromPtraceDetach bool) {\nt.parent.tg.eventQueue.Notify(EventExit | EventChildGroupStop | EventGroupContinue)\n}\n- // We don't send exit events for threads because we don't send CloneProcessStart events\n- // for threads (clone calls with CLONE_THREAD set).\n- // We also don't send exit events for the root process because we don't send\n+ // We don't send exit events for the root process because we don't send\n// Clone or Exec events for the initial process.\n- shouldSendExit := t == t.tg.leader && t.tg != t.k.globalInit\n- if seccheck.Global.Enabled(seccheck.PointExitNotifyParent) && shouldSendExit {\n+ if t.tg != t.k.globalInit && seccheck.Global.Enabled(seccheck.PointExitNotifyParent) {\nmask, info := getExitNotifyParentSeccheckInfo(t)\nif err := seccheck.Global.SendToCheckers(func(c seccheck.Checker) error {\nreturn c.ExitNotifyParent(t, mask, info)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/metadata.go",
"new_path": "pkg/sentry/seccheck/metadata.go",
"diff": "@@ -24,7 +24,7 @@ import (\n// PointX represents the checkpoint X.\nconst (\n- PointCloneProcess Point = iota\n+ PointClone Point = iota\nPointContainerStart\nPointExecve\nPointExitNotifyParent\n@@ -225,7 +225,7 @@ func init() {\n// Points from the sentry namespace.\nregisterPoint(PointDesc{\n- ID: PointCloneProcess,\n+ ID: PointClone,\nName: \"sentry/clone\",\nContextFields: defaultContextFields,\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/points/sentry.proto",
"new_path": "pkg/sentry/seccheck/points/sentry.proto",
"diff": "@@ -22,13 +22,16 @@ import \"pkg/sentry/seccheck/points/common.proto\";\nmessage CloneInfo {\ngvisor.common.ContextData context_data = 1;\n- // CreatedThreadID is the thread's ID in the root PID namespace.\n+ // created_thread_id is the thread's ID in the root PID namespace.\nint32 created_thread_id = 3;\nint32 created_thread_group_id = 4;\n- // CreatedThreadStartTime is the thread's CLOCK_REALTIME start time.\n+ // created_thread_start_time_ns is the thread's CLOCK_REALTIME start time.\nint64 created_thread_start_time_ns = 5;\n+\n+ // flags are equivalent to the flags passed to clone(2).\n+ uint64 flags = 6;\n}\n// ExecveInfo contains information used by the Execve checkpoint.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/seccheck_test.go",
"new_path": "pkg/sentry/seccheck/seccheck_test.go",
"diff": "@@ -38,7 +38,7 @@ func (c *testChecker) Clone(ctx context.Context, fields FieldSet, info *pb.Clone\nfunc TestNoChecker(t *testing.T) {\nvar s State\n- if s.Enabled(PointCloneProcess) {\n+ if s.Enabled(PointClone) {\nt.Errorf(\"Enabled(PointClone): got true, wanted false\")\n}\n}\n@@ -46,7 +46,7 @@ func TestNoChecker(t *testing.T) {\nfunc TestCheckerNotRegisteredForPoint(t *testing.T) {\nvar s State\ns.AppendChecker(&testChecker{}, nil)\n- if s.Enabled(PointCloneProcess) {\n+ if s.Enabled(PointClone) {\nt.Errorf(\"Enabled(PointClone): got true, wanted false\")\n}\n}\n@@ -62,16 +62,16 @@ func TestCheckerRegistered(t *testing.T) {\n}\nreq := []PointReq{\n{\n- Pt: PointCloneProcess,\n+ Pt: PointClone,\nFields: FieldSet{Context: MakeFieldMask(FieldCtxtCredentials)},\n},\n}\ns.AppendChecker(checker, req)\n- if !s.Enabled(PointCloneProcess) {\n+ if !s.Enabled(PointClone) {\nt.Errorf(\"Enabled(PointClone): got false, wanted true\")\n}\n- fields := s.GetFieldSet(PointCloneProcess)\n+ fields := s.GetFieldSet(PointClone)\nif !fields.Context.Contains(FieldCtxtCredentials) {\nt.Errorf(\"fields.Context.Contains(PointContextCredentials): got false, wanted true\")\n}\n@@ -95,7 +95,7 @@ func TestMultipleCheckersRegistered(t *testing.T) {\n},\n}\nreqs := []PointReq{\n- {Pt: PointCloneProcess},\n+ {Pt: PointClone},\n}\ns.AppendChecker(checker, reqs)\n@@ -104,16 +104,16 @@ func TestMultipleCheckersRegistered(t *testing.T) {\nreturn nil\n}}\nreqs = []PointReq{\n- {Pt: PointCloneProcess},\n+ {Pt: PointClone},\n}\ns.AppendChecker(checker, reqs)\n- if !s.Enabled(PointCloneProcess) {\n+ if !s.Enabled(PointClone) {\nt.Errorf(\"Enabled(PointClone): got false, wanted true\")\n}\n// CloneReq() should return the union of requested fields from all calls to\n// AppendChecker.\n- fields := s.GetFieldSet(PointCloneProcess)\n+ fields := s.GetFieldSet(PointClone)\nif err := s.SendToCheckers(func(c Checker) error {\nreturn c.Clone(context.Background(), fields, &pb.CloneInfo{})\n}); err != nil {\n@@ -139,7 +139,7 @@ func TestCheckpointReturnsFirstCheckerError(t *testing.T) {\n},\n}\nreqs := []PointReq{\n- {Pt: PointCloneProcess},\n+ {Pt: PointClone},\n}\ns.AppendChecker(checker, reqs)\n@@ -152,7 +152,7 @@ func TestCheckpointReturnsFirstCheckerError(t *testing.T) {\n}\ns.AppendChecker(checker, reqs)\n- if !s.Enabled(PointCloneProcess) {\n+ if !s.Enabled(PointClone) {\nt.Errorf(\"Enabled(PointClone): got false, wanted true\")\n}\nif err := s.SendToCheckers(func(c Checker) error {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fire clone point for thread creation
Thread creation tracking is required by Falco.
Updates #4805
PiperOrigin-RevId: 447003670 |
260,009 | 06.05.2022 12:18:45 | 25,200 | 7574e4f6428591429ef68f6dbbc2534b99af64d0 | Add KVM specific metrics.
This change adds counter and timer metrics useful for analyzing the KVM
platform. | [
{
"change_type": "MODIFY",
"old_path": "pkg/metric/metric.go",
"new_path": "pkg/metric/metric.go",
"diff": "@@ -417,7 +417,7 @@ func MustCreateNewUint64NanosecondsMetric(name string, sync bool, description st\n// This must be called with the correct number of field values or it will panic.\n//go:nosplit\nfunc (m *Uint64Metric) Value(fieldValues ...string) uint64 {\n- key := m.fieldMapper.lookup(fieldValues...)\n+ key := m.fieldMapper.lookupConcat(fieldValues, nil)\nreturn m.fields[key].Load()\n}\n@@ -425,14 +425,15 @@ func (m *Uint64Metric) Value(fieldValues ...string) uint64 {\n// This must be called with the correct number of field values or it will panic.\n//go:nosplit\nfunc (m *Uint64Metric) Increment(fieldValues ...string) {\n- m.IncrementBy(1, fieldValues...)\n+ key := m.fieldMapper.lookupConcat(fieldValues, nil)\n+ m.fields[key].Add(1)\n}\n// IncrementBy increments the metric by v.\n// This must be called with the correct number of field values or it will panic.\n//go:nosplit\nfunc (m *Uint64Metric) IncrementBy(v uint64, fieldValues ...string) {\n- key := m.fieldMapper.lookup(fieldValues...)\n+ key := m.fieldMapper.lookupConcat(fieldValues, nil)\nm.fields[key].Add(v)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task.go",
"new_path": "pkg/sentry/kernel/task.go",
"diff": "@@ -24,6 +24,7 @@ import (\n\"gvisor.dev/gvisor/pkg/bpf\"\n\"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n\"gvisor.dev/gvisor/pkg/hostarch\"\n+ \"gvisor.dev/gvisor/pkg/metric\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n\"gvisor.dev/gvisor/pkg/sentry/inet\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n@@ -595,6 +596,19 @@ type Task struct {\nuserCounters *userCounters\n}\n+// Task related metrics\n+var (\n+ // syscallCounter is a metric that tracks how many syscalls the sentry has\n+ // executed.\n+ syscallCounter = metric.MustCreateNewUint64Metric(\n+ \"/task/syscalls\", false, \"The number of syscalls the sentry has executed for the user.\")\n+\n+ // faultCounter is a metric that tracks how many faults the sentry has had to\n+ // handle.\n+ faultCounter = metric.MustCreateNewUint64Metric(\n+ \"/task/faults\", false, \"The number of faults the sentry has handled.\")\n+)\n+\nfunc (t *Task) savePtraceTracer() *Task {\nreturn t.ptraceTracer.Load().(*Task)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_run.go",
"new_path": "pkg/sentry/kernel/task_run.go",
"diff": "@@ -261,6 +261,8 @@ func (app *runApp) execute(t *Task) taskRunState {\n// an application-generated signal and we should continue execution\n// normally.\nif at.Any() {\n+ faultCounter.Increment()\n+\nregion := trace.StartRegion(t.traceContext, faultRegion)\naddr := hostarch.Addr(info.Addr())\nerr := t.MemoryManager().HandleUserFault(t, addr, at, hostarch.Addr(t.Arch().Stack()))\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_syscall.go",
"new_path": "pkg/sentry/kernel/task_syscall.go",
"diff": "@@ -253,6 +253,7 @@ func (t *Task) doSyscall() taskRunState {\n}\n}\n+ syscallCounter.Increment()\nreturn t.doSyscallEnter(sysno, args)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/BUILD",
"new_path": "pkg/sentry/platform/kvm/BUILD",
"diff": "@@ -92,6 +92,7 @@ go_library(\n\"//pkg/cpuid\",\n\"//pkg/hostarch\",\n\"//pkg/log\",\n+ \"//pkg/metric\",\n\"//pkg/procid\",\n\"//pkg/ring0\",\n\"//pkg/ring0/pagetables\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/address_space_amd64.go",
"new_path": "pkg/sentry/platform/kvm/address_space_amd64.go",
"diff": "@@ -16,9 +16,11 @@ package kvm\n// invalidate is the implementation for Invalidate.\nfunc (as *addressSpace) invalidate() {\n+ timer := asInvalidateDuration.Start()\nas.dirtySet.forEach(as.machine, func(c *vCPU) {\nif c.active.get() == as { // If this happens to be active,\nc.BounceToKernel() // ... force a kernel transition.\n}\n})\n+ timer.Finish()\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/bluepill_unsafe.go",
"new_path": "pkg/sentry/platform/kvm/bluepill_unsafe.go",
"diff": "@@ -110,10 +110,12 @@ func bluepillHandler(context unsafe.Pointer) {\n}\nfor {\n+ hostExitCounter.Increment()\n_, _, errno := unix.RawSyscall(unix.SYS_IOCTL, uintptr(c.fd), _KVM_RUN, 0) // escapes: no.\nswitch errno {\ncase 0: // Expected case.\ncase unix.EINTR:\n+ interruptCounter.Increment()\n// First, we process whatever pending signal\n// interrupted KVM. Since we're in a signal handler\n// currently, all signals are masked and the signal\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/context.go",
"new_path": "pkg/sentry/platform/kvm/context.go",
"diff": "@@ -85,6 +85,7 @@ restart:\n// Increment the number of user exits.\ncpu.userExits.Add(1)\n+ userExitCounter.Increment()\n// Release resources.\nc.machine.Put(cpu)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine.go",
"new_path": "pkg/sentry/platform/kvm/machine.go",
"diff": "@@ -19,12 +19,14 @@ import (\n\"runtime\"\ngosync \"sync\"\n\"sync/atomic\"\n+ \"time\"\n\"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/atomicbitops\"\n\"gvisor.dev/gvisor/pkg/hostarch\"\n\"gvisor.dev/gvisor/pkg/log\"\n+ \"gvisor.dev/gvisor/pkg/metric\"\n\"gvisor.dev/gvisor/pkg/procid\"\n\"gvisor.dev/gvisor/pkg/ring0\"\n\"gvisor.dev/gvisor/pkg/ring0/pagetables\"\n@@ -101,6 +103,40 @@ const (\nvCPUWaiter uint32 = 1 << 2\n)\n+var (\n+ // hostExitCounter is a metric that tracks how many times the sentry\n+ // performed a host to guest world switch.\n+ hostExitCounter = metric.MustCreateNewUint64Metric(\n+ \"/kvm/host_exits\", false, \"The number of times the sentry performed a host to guest world switch.\")\n+\n+ // userExitCounter is a metric that tracks how many times the sentry has\n+ // had an exit from userspace. Analogous to vCPU.userExits.\n+ userExitCounter = metric.MustCreateNewUint64Metric(\n+ \"/kvm/user_exits\", false, \"The number of times the sentry has had an exit from userspace.\")\n+\n+ // interruptCounter is a metric that tracks how many times execution returned\n+ // to the KVM host to handle a pending signal.\n+ interruptCounter = metric.MustCreateNewUint64Metric(\n+ \"/kvm/interrupts\", false, \"The number of times the signal handler was invoked.\")\n+\n+ // mmapCallCounter is a metric that tracks how many times the function\n+ // seccompMmapSyscall has been called.\n+ mmapCallCounter = metric.MustCreateNewUint64Metric(\n+ \"/kvm/mmap_calls\", false, \"The number of times seccompMmapSyscall has been called.\")\n+\n+ // getVCPUFastPathDuration are durations of acquiring a VCPU\n+ // (using machine.Get()).\n+ getVCPUDuration = metric.MustRegisterTimerMetric(\"/kvm/get_vcpu\",\n+ metric.NewExponentialBucketer(20, uint64(time.Nanosecond*10), 1, 2),\n+ \"Duration of acquiring a VCPU, not including the fastest reuse path.\",\n+ metric.NewField(\"acquisition_type\", []string{\"fast_reused\", \"reused\", \"unused\", \"stolen\"}))\n+\n+ // asInvalidateDuration are durations of calling addressSpace.invalidate().\n+ asInvalidateDuration = metric.MustRegisterTimerMetric(\"/kvm/address_space_invalidate\",\n+ metric.NewExponentialBucketer(15, uint64(time.Nanosecond*100), 1, 2),\n+ \"Duration of calling addressSpace.invalidate().\")\n+)\n+\n// vCPU is a single KVM vCPU.\ntype vCPU struct {\n// CPU is the kernel CPU data.\n@@ -405,6 +441,8 @@ func (m *machine) Destroy() {\n// the corrent context in guest, the vCPU of it must be the same as what\n// Get() returns.\nfunc (m *machine) Get() *vCPU {\n+ timer := getVCPUDuration.Start()\n+\nm.mu.RLock()\nruntime.LockOSThread()\ntid := procid.Current()\n@@ -413,6 +451,7 @@ func (m *machine) Get() *vCPU {\nif c := m.vCPUsByTID[tid]; c != nil {\nc.lock()\nm.mu.RUnlock()\n+ timer.Finish(\"fast_reused\")\nreturn c\n}\n@@ -432,6 +471,7 @@ func (m *machine) Get() *vCPU {\nif c := m.vCPUsByTID[tid]; c != nil {\nc.lock()\nm.mu.Unlock()\n+ timer.Finish(\"reused\")\nreturn c\n}\n@@ -443,6 +483,7 @@ func (m *machine) Get() *vCPU {\nm.vCPUsByTID[tid] = c\nm.mu.Unlock()\nc.loadSegments(tid)\n+ timer.Finish(\"unused\")\nreturn c\n}\n}\n@@ -455,6 +496,7 @@ func (m *machine) Get() *vCPU {\nm.vCPUsByTID[tid] = c\nm.mu.Unlock()\nc.loadSegments(tid)\n+ timer.Finish(\"unused\")\nreturn c\n}\n@@ -481,6 +523,7 @@ func (m *machine) Get() *vCPU {\nm.vCPUsByTID[tid] = c\nm.mu.Unlock()\nc.loadSegments(tid)\n+ timer.Finish(\"stolen\")\nreturn c\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine_unsafe.go",
"new_path": "pkg/sentry/platform/kvm/machine_unsafe.go",
"diff": "@@ -202,6 +202,8 @@ func seccompMmapSync() {\n//\n//go:nosplit\nfunc seccompMmapHandler(context unsafe.Pointer) {\n+ mmapCallCounter.Increment()\n+\naddr, length, errno := seccompMmapSyscall(context)\nif errno != 0 {\nreturn\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add KVM specific metrics.
This change adds counter and timer metrics useful for analyzing the KVM
platform.
PiperOrigin-RevId: 447043888 |
260,004 | 06.05.2022 12:21:24 | 25,200 | a96653a412058405b541987dd0820c918c88c23d | Only return ErrNoBufferSpace if RECVERR is set
...to match Linux behaviour. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/BUILD",
"new_path": "pkg/tcpip/transport/BUILD",
"diff": "@@ -23,6 +23,7 @@ go_test(\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/link/loopback\",\n\"//pkg/tcpip/network/ipv4\",\n+ \"//pkg/tcpip/network/ipv6\",\n\"//pkg/tcpip/stack\",\n\"//pkg/tcpip/testutil\",\n\"//pkg/tcpip/transport/icmp\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/datagram_test.go",
"new_path": "pkg/tcpip/transport/datagram_test.go",
"diff": "@@ -26,6 +26,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/loopback\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv4\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/network/ipv6\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n\"gvisor.dev/gvisor/pkg/tcpip/testutil\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport\"\n@@ -133,6 +134,7 @@ func TestStateUpdates(t *testing.T) {\ntype mockEndpoint struct {\ndisp stack.NetworkDispatcher\npkts stack.PacketBufferList\n+ writeErr tcpip.Error\n}\nfunc (*mockEndpoint) MTU() uint32 {\n@@ -149,6 +151,10 @@ func (*mockEndpoint) LinkAddress() tcpip.LinkAddress {\nreturn l\n}\nfunc (e *mockEndpoint) WritePackets(pkts stack.PacketBufferList) (int, tcpip.Error) {\n+ if e.writeErr != nil {\n+ return 0, e.writeErr\n+ }\n+\npkts.IncRef()\nlen := pkts.Len()\nfor pkt := pkts.Front(); pkt != nil; pkt = pkt.Next() {\n@@ -348,3 +354,143 @@ func TestSndBuf(t *testing.T) {\n})\n}\n}\n+\n+func TestDeviceReturnErrNoBufferSpace(t *testing.T) {\n+ const nicID = 1\n+\n+ for _, networkTest := range []struct {\n+ name string\n+ netProto tcpip.NetworkProtocolNumber\n+ localAddr tcpip.Address\n+ remoteAddr tcpip.Address\n+ buf buffer.View\n+ }{\n+ {\n+ name: \"IPv4\",\n+ netProto: ipv4.ProtocolNumber,\n+ localAddr: testutil.MustParse4(\"1.2.3.4\"),\n+ remoteAddr: testutil.MustParse4(\"1.0.0.1\"),\n+ buf: func() buffer.View {\n+ buf := buffer.NewView(header.ICMPv4MinimumSize)\n+ header.ICMPv4(buf).SetType(header.ICMPv4Echo)\n+ return buf\n+ }(),\n+ },\n+ {\n+ name: \"IPv6\",\n+ netProto: ipv6.ProtocolNumber,\n+ localAddr: testutil.MustParse6(\"a::1\"),\n+ remoteAddr: testutil.MustParse6(\"a::2\"),\n+ buf: func() buffer.View {\n+ buf := buffer.NewView(header.ICMPv6MinimumSize)\n+ header.ICMPv6(buf).SetType(header.ICMPv6EchoRequest)\n+ return buf\n+ }(),\n+ },\n+ } {\n+ t.Run(networkTest.name, func(t *testing.T) {\n+ for _, test := range []struct {\n+ name string\n+ createEndpoint func(*stack.Stack) (tcpip.Endpoint, error)\n+ }{\n+ {\n+ name: \"UDP\",\n+ createEndpoint: func(s *stack.Stack) (tcpip.Endpoint, error) {\n+ ep, err := s.NewEndpoint(udp.ProtocolNumber, networkTest.netProto, &waiter.Queue{})\n+ if err != nil {\n+ return nil, fmt.Errorf(\"s.NewEndpoint(%d, %d, _) failed: %s\", udp.ProtocolNumber, networkTest.netProto, err)\n+ }\n+ return ep, nil\n+ },\n+ },\n+ {\n+ name: \"ICMP\",\n+ createEndpoint: func(s *stack.Stack) (tcpip.Endpoint, error) {\n+ proto := icmp.ProtocolNumber4\n+ if networkTest.netProto == ipv6.ProtocolNumber {\n+ proto = icmp.ProtocolNumber6\n+ }\n+ ep, err := s.NewEndpoint(proto, networkTest.netProto, &waiter.Queue{})\n+ if err != nil {\n+ return nil, fmt.Errorf(\"s.NewEndpoint(%d, %d, _) failed: %s\", proto, networkTest.netProto, err)\n+ }\n+ return ep, nil\n+ },\n+ },\n+ {\n+ name: \"RAW\",\n+ createEndpoint: func(s *stack.Stack) (tcpip.Endpoint, error) {\n+ ep, err := s.NewRawEndpoint(udp.ProtocolNumber, networkTest.netProto, &waiter.Queue{}, true /* associated */)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"s.NewRawEndpoint(%d, %d, _, true) failed: %s\", udp.ProtocolNumber, networkTest.netProto, err)\n+ }\n+ return ep, nil\n+ },\n+ },\n+ } {\n+ t.Run(test.name, func(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},\n+ TransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol, icmp.NewProtocol4, icmp.NewProtocol6},\n+ RawFactory: &raw.EndpointFactory{},\n+ })\n+ e := mockEndpoint{writeErr: &tcpip.ErrNoBufferSpace{}}\n+ defer e.releasePackets()\n+ if err := s.CreateNIC(nicID, &e); err != nil {\n+ t.Fatalf(\"s.CreateNIC(%d, _) failed: %s\", nicID, err)\n+ }\n+ ep, err := test.createEndpoint(s)\n+ if err != nil {\n+ t.Fatalf(\"test.createEndpoint(_) failed: %s\", err)\n+ }\n+ defer ep.Close()\n+\n+ addr := tcpip.ProtocolAddress{\n+ Protocol: networkTest.netProto,\n+ AddressWithPrefix: networkTest.localAddr.WithPrefix(),\n+ }\n+ if err := s.AddProtocolAddress(nicID, addr, stack.AddressProperties{}); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %#v, {}): %s\", nicID, addr, err)\n+ }\n+ s.SetRouteTable([]tcpip.Route{\n+ {\n+ Destination: header.IPv4EmptySubnet,\n+ NIC: nicID,\n+ },\n+ {\n+ Destination: header.IPv6EmptySubnet,\n+ NIC: nicID,\n+ },\n+ })\n+\n+ to := tcpip.FullAddress{NIC: nicID, Addr: networkTest.remoteAddr, Port: 12345}\n+ if err := ep.Connect(to); err != nil {\n+ t.Fatalf(\"ep.Connect(%#v): %s\", to, err)\n+ }\n+\n+ ops := ep.SocketOptions()\n+ checkWrite := func(netProto tcpip.NetworkProtocolNumber) {\n+ t.Helper()\n+\n+ var r bytes.Reader\n+ r.Reset(networkTest.buf)\n+ var wantErr tcpip.Error\n+ if netProto == networkTest.netProto {\n+ wantErr = &tcpip.ErrNoBufferSpace{}\n+ }\n+ if n, err := ep.Write(&r, tcpip.WriteOptions{}); err != wantErr {\n+ t.Fatalf(\"got Write(...) = (%d, %s), want = (_, %s)\", n, err, wantErr)\n+ }\n+ }\n+\n+ ops.SetIPv4RecvError(true)\n+ checkWrite(ipv4.ProtocolNumber)\n+\n+ ops.SetIPv4RecvError(false)\n+ ops.SetIPv6RecvError(true)\n+ checkWrite(ipv6.ProtocolNumber)\n+ })\n+ }\n+ })\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/internal/network/endpoint.go",
"new_path": "pkg/tcpip/transport/internal/network/endpoint.go",
"diff": "@@ -317,11 +317,33 @@ func (c *WriteContext) WritePacket(pkt *stack.PacketBuffer, headerIncluded bool)\nreturn c.route.WriteHeaderIncludedPacket(pkt)\n}\n- return c.route.WritePacket(stack.NetworkHeaderParams{\n+ err := c.route.WritePacket(stack.NetworkHeaderParams{\nProtocol: c.e.transProto,\nTTL: c.ttl,\nTOS: c.tos,\n}, pkt)\n+\n+ if _, ok := err.(*tcpip.ErrNoBufferSpace); ok {\n+ var recvErr bool\n+ switch netProto := c.route.NetProto(); netProto {\n+ case header.IPv4ProtocolNumber:\n+ recvErr = c.e.ops.GetIPv4RecvError()\n+ case header.IPv6ProtocolNumber:\n+ recvErr = c.e.ops.GetIPv6RecvError()\n+ default:\n+ panic(fmt.Sprintf(\"unhandled network protocol number = %d\", netProto))\n+ }\n+\n+ // Linux only returns ENOBUFS to the caller if IP{,V6}_RECVERR is set.\n+ //\n+ // https://github.com/torvalds/linux/blob/3e71713c9e75c/net/ipv4/udp.c#L969\n+ // https://github.com/torvalds/linux/blob/3e71713c9e75c/net/ipv6/udp.c#L1260\n+ if !recvErr {\n+ err = nil\n+ }\n+ }\n+\n+ return err\n}\n// MaybeSignalWritable signals waiters with writable events if the send buffer\n"
}
] | Go | Apache License 2.0 | google/gvisor | Only return ErrNoBufferSpace if RECVERR is set
...to match Linux behaviour.
PiperOrigin-RevId: 447044373 |
259,909 | 06.05.2022 14:39:41 | 25,200 | 592fc1bb5041f3ffbde54fa3c7132b0d73715223 | Convert fdbased link endpoints to use pkg/buffer instead of VectorizedViews. | [
{
"change_type": "MODIFY",
"old_path": "pkg/buffer/view.go",
"new_path": "pkg/buffer/view.go",
"diff": "@@ -33,6 +33,19 @@ type View struct {\npool pool\n}\n+// NewWithData creates a new view initialized with given data.\n+func NewWithData(b []byte) View {\n+ v := View{\n+ size: int64(len(b)),\n+ }\n+ if len(b) > 0 {\n+ buf := v.pool.getNoInit()\n+ buf.initWithData(b)\n+ v.data.PushBack(buf)\n+ }\n+ return v\n+}\n+\n// TrimFront removes the first count bytes from the buffer.\nfunc (v *View) TrimFront(count int64) {\nif count >= v.size {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/BUILD",
"new_path": "pkg/tcpip/link/fdbased/BUILD",
"diff": "@@ -15,9 +15,9 @@ go_library(\nvisibility = [\"//visibility:public\"],\ndeps = [\n\"//pkg/atomicbitops\",\n+ \"//pkg/buffer\",\n\"//pkg/sync\",\n\"//pkg/tcpip\",\n- \"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/link/rawfile\",\n\"//pkg/tcpip/stack\",\n@@ -31,10 +31,10 @@ go_test(\nsrcs = [\"endpoint_test.go\"],\nlibrary = \":fdbased\",\ndeps = [\n+ \"//pkg/buffer\",\n\"//pkg/refs\",\n\"//pkg/refsvfs2\",\n\"//pkg/tcpip\",\n- \"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/stack\",\n\"@com_github_google_go_cmp//cmp:go_default_library\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/endpoint.go",
"new_path": "pkg/tcpip/link/fdbased/endpoint.go",
"diff": "@@ -45,9 +45,9 @@ import (\n\"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/atomicbitops\"\n+ \"gvisor.dev/gvisor/pkg/buffer\"\n\"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n- \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/rawfile\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/endpoint_test.go",
"new_path": "pkg/tcpip/link/fdbased/endpoint_test.go",
"diff": "@@ -29,10 +29,10 @@ import (\n\"github.com/google/go-cmp/cmp\"\n\"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/buffer\"\n\"gvisor.dev/gvisor/pkg/refs\"\n\"gvisor.dev/gvisor/pkg/refsvfs2\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n- \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n)\n@@ -52,10 +52,10 @@ type packetInfo struct {\n}\ntype packetContents struct {\n- LinkHeader buffer.View\n- NetworkHeader buffer.View\n- TransportHeader buffer.View\n- Data buffer.View\n+ LinkHeader []byte\n+ NetworkHeader []byte\n+ TransportHeader []byte\n+ Data []byte\n}\nfunc checkPacketInfoEqual(t *testing.T, got, want packetInfo) {\n@@ -186,7 +186,7 @@ func testWritePacket(t *testing.T, plen int, eth bool, gsoMaxSize uint32, hash u\ndefer c.cleanup()\n// Build payload.\n- payload := buffer.NewView(plen)\n+ payload := make([]byte, plen)\nif _, err := rand.Read(payload); err != nil {\nt.Fatalf(\"rand.Read(payload): %s\", err)\n}\n@@ -195,7 +195,7 @@ func testWritePacket(t *testing.T, plen int, eth bool, gsoMaxSize uint32, hash u\nconst netHdrLen = 100\npkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\nReserveHeaderBytes: int(c.ep.MaxHeaderLength()) + netHdrLen,\n- Data: payload.ToVectorisedView(),\n+ Payload: buffer.NewWithData(payload),\n})\npkt.Hash = hash\n// Every PacketBuffer must have these set:\n@@ -212,7 +212,7 @@ func testWritePacket(t *testing.T, plen int, eth bool, gsoMaxSize uint32, hash u\n}\n// Write.\n- want := append(append(buffer.View(nil), b...), payload...)\n+ want := append(append([]byte{}, b...), payload...)\nconst l3HdrLen = header.IPv6MinimumSize\nif gsoMaxSize != 0 {\npkt.GSOOptions = stack.GSO{\n@@ -336,7 +336,6 @@ func TestPreserveSrcAddress(t *testing.T) {\n// the minimum size of the ethernet header.\n// TODO(b/153685824): Figure out if this should use c.ep.MaxHeaderLength().\nReserveHeaderBytes: header.EthernetMinimumSize,\n- Data: buffer.VectorisedView{},\n})\ndefer pkt.DecRef()\n// Every PacketBuffer must have these set:\n@@ -387,7 +386,7 @@ func TestDeliverPacket(t *testing.T) {\nwantPkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\nReserveHeaderBytes: header.EthernetMinimumSize,\n- Data: buffer.NewViewFromBytes(all).ToVectorisedView(),\n+ Payload: buffer.NewWithData(all),\n})\ndefer wantPkt.DecRef()\nif eth {\n@@ -498,12 +497,12 @@ func TestIovecBuffer(t *testing.T) {\n// later.\noldIovecs := append([]unix.Iovec(nil), iovecs...)\n- // Test the views that get pulled.\n- vv := b.pullViews(c.n)\n+ // Test the buffer that get pulled.\n+ buf := b.pullBuffer(c.n)\nvar lengths []int\n- for _, v := range vv.Views() {\n+ buf.Apply(func(v []byte) {\nlengths = append(lengths, len(v))\n- }\n+ })\nif !reflect.DeepEqual(lengths, c.wantLengths) {\nt.Errorf(\"Pulled view lengths = %v, want %v\", lengths, c.wantLengths)\n}\n@@ -550,11 +549,11 @@ func TestIovecBufferSkipVnetHdr(t *testing.T) {\nb := newIovecBuffer([]int{10, 20, 50, 50}, true)\n// Pretend a read happend.\nb.nextIovecs()\n- vv := b.pullViews(test.readN)\n- if got, want := vv.Size(), test.wantLen; got != want {\n+ buf := b.pullBuffer(test.readN)\n+ if got, want := int(buf.Size()), test.wantLen; got != want {\nt.Errorf(\"b.pullView(%d).Size() = %d; want %d\", test.readN, got, want)\n}\n- if got, want := len(vv.ToOwnedView()), test.wantLen; got != want {\n+ if got, want := len(buf.Flatten()), test.wantLen; got != want {\nt.Errorf(\"b.pullView(%d).ToOwnedView() has length %d; want %d\", test.readN, got, want)\n}\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/mmap.go",
"new_path": "pkg/tcpip/link/fdbased/mmap.go",
"diff": "@@ -22,8 +22,8 @@ import (\n\"fmt\"\n\"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n- \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/rawfile\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n@@ -186,7 +186,7 @@ func (d *packetMMapDispatcher) dispatch() (bool, tcpip.Error) {\n}\npbuf := stack.NewPacketBuffer(stack.PacketBufferOptions{\n- Data: buffer.View(pkt).ToVectorisedView(),\n+ Payload: buffer.NewWithData(pkt),\n})\ndefer pbuf.DecRef()\nif d.e.hdrSize > 0 {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/packet_dispatchers.go",
"new_path": "pkg/tcpip/link/fdbased/packet_dispatchers.go",
"diff": "@@ -21,19 +21,21 @@ import (\n\"fmt\"\n\"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n- \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/rawfile\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n)\n-// BufConfig defines the shape of the vectorised view used to read packets from the NIC.\n+// BufConfig defines the shape of the buffer used to read packets from the NIC.\nvar BufConfig = []int{128, 256, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768}\ntype iovecBuffer struct {\n- // views are the actual buffers that hold the packet contents.\n- views []buffer.View\n+ // buffer is the actual buffer that holds the packet contents. Some contents\n+ // are reused across calls to pullBuffer if number of requested bytes is\n+ // smaller than the number of bytes allocated in the buffer.\n+ buffer buffer.Buffer\n// iovecs are initialized with base pointers/len of the corresponding\n// entries in the views defined above, except when GSO is enabled\n@@ -48,15 +50,22 @@ type iovecBuffer struct {\n// skipsVnetHdr is true if virtioNetHdr is to skipped.\nskipsVnetHdr bool\n+\n+ // pulledIndex is the index of the last []byte buffer pulled from the\n+ // underlying buffer storage during a call to pullBuffers. It is -1\n+ // if no buffer is pulled.\n+ pulledIndex int\n}\nfunc newIovecBuffer(sizes []int, skipsVnetHdr bool) *iovecBuffer {\nb := &iovecBuffer{\n- views: make([]buffer.View, len(sizes)),\nsizes: sizes,\nskipsVnetHdr: skipsVnetHdr,\n+ // Setting pulledIndex to the length of sizes will allocate all\n+ // the buffers.\n+ pulledIndex: len(sizes),\n}\n- niov := len(b.views)\n+ niov := len(sizes)\nif b.skipsVnetHdr {\nniov++\n}\n@@ -75,45 +84,54 @@ func (b *iovecBuffer) nextIovecs() []unix.Iovec {\nb.iovecs[0].SetLen(virtioNetHdrSize)\nvnetHdrOff++\n}\n- for i := range b.views {\n- if b.views[i] != nil {\n+\n+ var buf buffer.Buffer\n+ for i, size := range b.sizes {\n+ if i > b.pulledIndex {\nbreak\n}\n- v := buffer.NewView(b.sizes[i])\n- b.views[i] = v\n+ v := make([]byte, size)\n+ buf.AppendOwned(v)\nb.iovecs[i+vnetHdrOff] = unix.Iovec{Base: &v[0]}\nb.iovecs[i+vnetHdrOff].SetLen(len(v))\n}\n+ buf.Merge(&b.buffer)\n+ b.buffer = buf\n+ b.pulledIndex = -1\nreturn b.iovecs\n}\n-func (b *iovecBuffer) pullViews(n int) buffer.VectorisedView {\n- var views []buffer.View\n+// pullBuffer extracts the enough underlying storage from b.buffer to hold n\n+// bytes. It removes this storage from b.buffer, returns a new buffer\n+// that holds the storage, and updates pulledIndex to indicate which part\n+// of b.buffer's storage must be reallocated during the next call to\n+// nextIovecs.\n+func (b *iovecBuffer) pullBuffer(n int) buffer.Buffer {\n+ var pulled buffer.Buffer\nc := 0\nif b.skipsVnetHdr {\n- c += virtioNetHdrSize\n+ c = virtioNetHdrSize\nif c >= n {\n// Nothing in the packet.\n- return buffer.NewVectorisedView(0, nil)\n+ return pulled\n}\n}\n- for i, v := range b.views {\n- c += len(v)\n+ // Remove the used views from the buffer.\n+ pulled = b.buffer.Clone()\n+ for _, size := range b.sizes {\n+ b.pulledIndex++\n+ c += size\n+ b.buffer.TrimFront(int64(size))\nif c >= n {\n- b.views[i].CapLength(len(v) - (c - n))\n- views = append([]buffer.View(nil), b.views[:i+1]...)\nbreak\n}\n}\n- // Remove the first len(views) used views from the state.\n- for i := range views {\n- b.views[i] = nil\n- }\nif b.skipsVnetHdr {\n// Exclude the size of the vnet header.\nn -= virtioNetHdrSize\n}\n- return buffer.NewVectorisedView(n, views)\n+ pulled.Truncate(int64(n))\n+ return pulled\n}\n// stopFd is an eventfd used to signal the stop of a dispatcher.\n@@ -179,7 +197,7 @@ func (d *readVDispatcher) dispatch() (bool, tcpip.Error) {\n}\npkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n- Data: d.buf.pullViews(n),\n+ Payload: d.buf.pullBuffer(n),\n})\ndefer pkt.DecRef()\n@@ -285,7 +303,7 @@ func (d *recvMMsgDispatcher) dispatch() (bool, tcpip.Error) {\nfor k := 0; k < nMsgs; k++ {\nn := int(d.msgHdrs[k].Len)\npkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n- Data: d.bufs[k].pullViews(n),\n+ Payload: d.bufs[k].pullBuffer(n),\n})\npkts.PushBack(pkt)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/packet_buffer.go",
"new_path": "pkg/tcpip/stack/packet_buffer.go",
"diff": "@@ -41,15 +41,22 @@ var pkPool = sync.Pool{\n}\n// PacketBufferOptions specifies options for PacketBuffer creation.\n+// TODO(b/230896518): Convert PacketBufferOptions.Data to be a buffer.Buffer\n+// instead of a VectorisedView and remove Payload.\ntype PacketBufferOptions struct {\n// ReserveHeaderBytes is the number of bytes to reserve for headers. Total\n// number of bytes pushed onto the headers must not exceed this value.\nReserveHeaderBytes int\n// Data is the initial unparsed data for the new packet. If set, it will be\n- // owned by the new packet.\n+ // owned by the new packet. If Data is set, Payload must be unset.\n+ // Deprecated: Use Payload instead.\nData tcpipbuffer.VectorisedView\n+ // Payload is the initial unparsed data for the new packet. If set, it will\n+ // be owned by the new packet. If Payload is set, Data must be unset.\n+ Payload buffer.Buffer\n+\n// IsForwardedPacket identifies that the PacketBuffer being created is for a\n// forwarded packet.\nIsForwardedPacket bool\n@@ -181,6 +188,12 @@ func NewPacketBuffer(opts PacketBufferOptions) *PacketBuffer {\npk.buf.AppendOwned(make([]byte, opts.ReserveHeaderBytes))\npk.reserved = opts.ReserveHeaderBytes\n}\n+ if opts.Payload.Size() > 0 {\n+ if len(opts.Data.Views()) != 0 {\n+ panic(\"opts.Data must not be set if using Payload\")\n+ }\n+ pk.buf.Merge(&opts.Payload)\n+ }\nfor _, v := range opts.Data.Views() {\npk.buf.AppendOwned(v)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Convert fdbased link endpoints to use pkg/buffer instead of VectorizedViews.
PiperOrigin-RevId: 447073885 |
259,992 | 06.05.2022 14:51:20 | 25,200 | 71add3739048a97ec27db0c01fc4e84c0a64f2ac | Move test server into a separate package
It will be used for tests in other packages.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/checkers/remote/BUILD",
"new_path": "pkg/sentry/seccheck/checkers/remote/BUILD",
"diff": "@@ -13,6 +13,7 @@ go_library(\n\"//pkg/fd\",\n\"//pkg/log\",\n\"//pkg/sentry/seccheck\",\n+ \"//pkg/sentry/seccheck/checkers/remote/header\",\n\"//pkg/sentry/seccheck/points:points_go_proto\",\n\"@org_golang_google_protobuf//proto:go_default_library\",\n\"@org_golang_x_sys//unix:go_default_library\",\n@@ -28,15 +29,13 @@ go_test(\n],\nlibrary = \":remote\",\ndeps = [\n- \"//pkg/cleanup\",\n\"//pkg/fd\",\n\"//pkg/sentry/seccheck\",\n+ \"//pkg/sentry/seccheck/checkers/remote/test\",\n\"//pkg/sentry/seccheck/points:points_go_proto\",\n- \"//pkg/sync\",\n\"//pkg/test/testutil\",\n\"@com_github_cenkalti_backoff//:go_default_library\",\n\"@org_golang_google_protobuf//proto:go_default_library\",\n\"@org_golang_google_protobuf//types/known/anypb:go_default_library\",\n- \"@org_golang_x_sys//unix:go_default_library\",\n],\n)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/seccheck/checkers/remote/header/BUILD",
"diff": "+load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_library(\n+ name = \"header\",\n+ srcs = [\"header.go\"],\n+ marshal = True,\n+ visibility = [\"//:sandbox\"],\n+)\n+\n+go_test(\n+ name = \"header_test\",\n+ size = \"small\",\n+ srcs = [\"header_test.go\"],\n+ library = \":header\",\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/seccheck/checkers/remote/header/header.go",
"diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// Package header contains the message header used in the remote checker.\n+package header\n+\n+// HeaderStructSize size of header struct in bytes.\n+const HeaderStructSize = 8\n+\n+// Header is used to describe the message being sent to the remote process.\n+//\n+// 0 --------- 16 ---------- 32 ----------- 64 -----------+\n+// | HeaderSize | MessageType | DroppedCount | Payload... |\n+// +---- 16 ----+---- 16 -----+----- 32 -----+------------+\n+//\n+// +marshal\n+type Header struct {\n+ // HeaderSize is the size of the header in bytes. The payload comes\n+ // immediatelly after the header. The length is needed to allow the header to\n+ // expand in the future without breaking remotes that do not yet understand\n+ // the new fields.\n+ HeaderSize uint16\n+\n+ // MessageType describes the payload. It must be one of the pb.MessageType\n+ // values and determine how the payload is interpreted. This is more efficient\n+ // than using protobuf.Any because Any uses the full protobuf name to identify\n+ // the type.\n+ MessageType uint16\n+\n+ // DroppedCount is the number of points that failed to be written and had to\n+ // be dropped. It wraps around after max(uint32).\n+ DroppedCount uint32\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/seccheck/checkers/remote/header/header_test.go",
"diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package header\n+\n+import \"testing\"\n+\n+func TestHeaderSize(t *testing.T) {\n+ hdr := Header{}\n+ if want, got := hdr.SizeBytes(), HeaderStructSize; want != got {\n+ t.Errorf(\"wrong const header size, want: %v, got: %v\", want, got)\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/checkers/remote/remote.go",
"new_path": "pkg/sentry/seccheck/checkers/remote/remote.go",
"diff": "@@ -20,14 +20,14 @@ import (\n\"fmt\"\n\"os\"\n- \"gvisor.dev/gvisor/pkg/log\"\n-\n\"golang.org/x/sys/unix\"\n\"google.golang.org/protobuf/proto\"\n\"gvisor.dev/gvisor/pkg/cleanup\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/fd\"\n+ \"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/seccheck\"\n+ \"gvisor.dev/gvisor/pkg/sentry/seccheck/checkers/remote/header\"\npb \"gvisor.dev/gvisor/pkg/sentry/seccheck/points/points_go_proto\"\n)\n@@ -101,45 +101,17 @@ func New(_ map[string]interface{}, endpoint *fd.FD) (seccheck.Checker, error) {\nreturn &Remote{endpoint: endpoint}, nil\n}\n-// Header is used to describe the message being sent to the remote process.\n-//\n-// 0 --------- 16 ---------- 32 ----------- 64 -----------+\n-// | HeaderSize | MessageType | DroppedCount | Payload... |\n-// +---- 16 ----+---- 16 -----+----- 32 -----+------------+\n-//\n-// +marshal\n-type Header struct {\n- // HeaderSize is the size of the header in bytes. The payload comes\n- // immediatelly after the header. The length is needed to allow the header to\n- // expand in the future without breaking remotes that do not yet understand\n- // the new fields.\n- HeaderSize uint16\n-\n- // MessageType describes the payload. It must be one of the pb.MessageType\n- // values and determine how the payload is interpreted. This is more efficient\n- // than using protobuf.Any because Any uses the full protobuf name to identify\n- // the type.\n- MessageType uint16\n-\n- // DroppedCount is the number of points that failed to be written and had to\n- // be dropped. It wraps around after max(uint32).\n- DroppedCount uint32\n-}\n-\n-// headerStructSize size of header struct in bytes.\n-const headerStructSize = 8\n-\nfunc (r *Remote) write(msg proto.Message, msgType pb.MessageType) {\nout, err := proto.Marshal(msg)\nif err != nil {\nlog.Debugf(\"Marshal(%+v): %v\", msg, err)\nreturn\n}\n- hdr := Header{\n- HeaderSize: uint16(headerStructSize),\n+ hdr := header.Header{\n+ HeaderSize: uint16(header.HeaderStructSize),\nMessageType: uint16(msgType),\n}\n- var hdrOut [headerStructSize]byte\n+ var hdrOut [header.HeaderStructSize]byte\nhdr.MarshalUnsafe(hdrOut[:])\n// TODO(gvisor.dev/issue/4805): Change to non-blocking write. Count as dropped\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/checkers/remote/remote_test.go",
"new_path": "pkg/sentry/seccheck/checkers/remote/remote_test.go",
"diff": "@@ -17,7 +17,6 @@ package remote\nimport (\n\"bytes\"\n\"fmt\"\n- \"io/ioutil\"\n\"os\"\n\"os/exec\"\n\"path/filepath\"\n@@ -26,14 +25,12 @@ import (\n\"time\"\n\"github.com/cenkalti/backoff\"\n- \"golang.org/x/sys/unix\"\n\"google.golang.org/protobuf/proto\"\n\"google.golang.org/protobuf/types/known/anypb\"\n- \"gvisor.dev/gvisor/pkg/cleanup\"\n\"gvisor.dev/gvisor/pkg/fd\"\n\"gvisor.dev/gvisor/pkg/sentry/seccheck\"\n+ \"gvisor.dev/gvisor/pkg/sentry/seccheck/checkers/remote/test\"\npb \"gvisor.dev/gvisor/pkg/sentry/seccheck/points/points_go_proto\"\n- \"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/test/testutil\"\n)\n@@ -91,133 +88,14 @@ func (s *exampleServer) stop() {\n_ = os.Remove(s.path)\n}\n-type server struct {\n- path string\n- fd *fd.FD\n- stopCh chan struct{}\n-\n- mu sync.Mutex\n- // +checklocks:mu\n- points []message\n-}\n-\n-type message struct {\n- msgType pb.MessageType\n- msg []byte\n-}\n-\n-func newServer() (*server, error) {\n- dir, err := ioutil.TempDir(os.TempDir(), \"remote\")\n- if err != nil {\n- return nil, err\n- }\n- server, err := newServerPath(filepath.Join(dir, \"remote.sock\"))\n- if err != nil {\n- _ = os.RemoveAll(dir)\n- return nil, err\n- }\n- return server, nil\n-}\n-\n-func newServerPath(path string) (*server, error) {\n- socket, err := unix.Socket(unix.AF_UNIX, unix.SOCK_SEQPACKET, 0)\n- if err != nil {\n- return nil, fmt.Errorf(\"socket(AF_UNIX, SOCK_SEQPACKET, 0): %w\", err)\n- }\n- cu := cleanup.Make(func() {\n- _ = unix.Close(socket)\n- })\n- defer cu.Clean()\n-\n- sa := &unix.SockaddrUnix{Name: path}\n- if err := unix.Bind(socket, sa); err != nil {\n- return nil, fmt.Errorf(\"bind(%q): %w\", path, err)\n- }\n- if err := unix.Listen(socket, 5); err != nil {\n- return nil, fmt.Errorf(\"listen(): %w\", err)\n- }\n-\n- server := &server{\n- path: path,\n- fd: fd.New(socket),\n- stopCh: make(chan struct{}),\n- }\n- go server.run()\n- cu.Release()\n- return server, nil\n-}\n-\n-func (s *server) run() {\n- defer func() {\n- s.stopCh <- struct{}{}\n- }()\n- for {\n- client, _, err := unix.Accept(s.fd.FD())\n- if err != nil {\n- panic(err)\n- }\n- go s.handleClient(client)\n- }\n-}\n-\n-func (s *server) handleClient(client int) {\n- defer unix.Close(client)\n-\n- var buf = make([]byte, 1024*1024)\n- for {\n- read, err := unix.Read(client, buf)\n- if err != nil {\n- return\n- }\n- if read == 0 {\n- return\n- }\n- if read <= headerStructSize {\n- panic(\"invalid message\")\n- }\n- hdr := Header{}\n- hdr.UnmarshalUnsafe(buf[0:headerStructSize])\n- msg := message{\n- msgType: pb.MessageType(hdr.MessageType),\n- msg: buf[hdr.HeaderSize:read],\n- }\n- s.mu.Lock()\n- s.points = append(s.points, msg)\n- s.mu.Unlock()\n- }\n-}\n-\n-func (s *server) count() int {\n- s.mu.Lock()\n- defer s.mu.Unlock()\n- return len(s.points)\n-}\n-\n-func (s *server) getPoints() []message {\n- s.mu.Lock()\n- defer s.mu.Unlock()\n- cpy := make([]message, len(s.points))\n- copy(cpy, s.points)\n- return cpy\n-}\n-\n-func (s *server) wait() {\n- <-s.stopCh\n-}\n-\n-func (s *server) close() {\n- _ = s.fd.Close()\n- _ = os.Remove(s.path)\n-}\n-\nfunc TestBasic(t *testing.T) {\n- server, err := newServer()\n+ server, err := test.NewServer()\nif err != nil {\nt.Fatalf(\"newServer(): %v\", err)\n}\n- defer server.close()\n+ defer server.Close()\n- endpoint, err := setup(server.path)\n+ endpoint, err := setup(server.Path)\nif err != nil {\nt.Fatalf(\"setup(): %v\", err)\n}\n@@ -238,27 +116,22 @@ func TestBasic(t *testing.T) {\nt.Fatalf(\"ExitNotifyParent: %v\", err)\n}\n- testutil.Poll(func() error {\n- if server.count() == 0 {\n- return fmt.Errorf(\"waiting for points to arrive\")\n- }\n- return nil\n- }, 5*time.Second)\n- if want, got := 1, server.count(); want != got {\n- t.Errorf(\"wrong number of points, want: %d, got: %d\", want, got)\n- }\n- pt := server.getPoints()[0]\n-\n- if want := pb.MessageType_MESSAGE_SENTRY_EXIT_NOTIFY_PARENT; pt.msgType != want {\n- t.Errorf(\"wrong message type, want: %v, got: %v\", want, pt.msgType)\n+ server.WaitForCount(1)\n+ pt := server.GetPoints()[0]\n+ if want := pb.MessageType_MESSAGE_SENTRY_EXIT_NOTIFY_PARENT; pt.MsgType != want {\n+ t.Errorf(\"wrong message type, want: %v, got: %v\", want, pt.MsgType)\n}\ngot := &pb.ExitNotifyParentInfo{}\n- if err := proto.Unmarshal(pt.msg, got); err != nil {\n+ if err := proto.Unmarshal(pt.Msg, got); err != nil {\nt.Errorf(\"proto.Unmarshal(ExitNotifyParentInfo): %v\", err)\n}\nif !proto.Equal(info, got) {\nt.Errorf(\"Received point is different, want: %+v, got: %+v\", info, got)\n}\n+ // Check that no more points were received.\n+ if want, got := 1, server.Count(); want != got {\n+ t.Errorf(\"wrong number of points, want: %d, got: %d\", want, got)\n+ }\n}\n// Test that the example C++ server works. It's easier to test from here and\n@@ -304,13 +177,6 @@ func TestExample(t *testing.T) {\n}\n}\n-func TestHeaderSize(t *testing.T) {\n- hdr := Header{}\n- if want, got := hdr.SizeBytes(), hdr.SizeBytes(); want != got {\n- t.Errorf(\"wrong const header size, want: %v, got: %v\", want, got)\n- }\n-}\n-\nfunc BenchmarkSmall(t *testing.B) {\n// Run server in a separate process just to isolate it as much as possible.\nserver, err := newExampleServer(false)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/seccheck/checkers/remote/test/BUILD",
"diff": "+load(\"//tools:defs.bzl\", \"go_library\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_library(\n+ name = \"test\",\n+ testonly = True,\n+ srcs = [\"server.go\"],\n+ visibility = [\"//:sandbox\"],\n+ deps = [\n+ \"//pkg/cleanup\",\n+ \"//pkg/log\",\n+ \"//pkg/sentry/seccheck/checkers/remote/header\",\n+ \"//pkg/sentry/seccheck/points:points_go_proto\",\n+ \"//pkg/sync\",\n+ \"//pkg/test/testutil\",\n+ \"//pkg/unet\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/seccheck/checkers/remote/test/server.go",
"diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// Package test provides functionality used to test the remote checker.\n+package test\n+\n+import (\n+ \"errors\"\n+ \"fmt\"\n+ \"io/ioutil\"\n+ \"os\"\n+ \"path/filepath\"\n+ \"time\"\n+\n+ \"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/cleanup\"\n+ \"gvisor.dev/gvisor/pkg/log\"\n+ \"gvisor.dev/gvisor/pkg/sentry/seccheck/checkers/remote/header\"\n+ pb \"gvisor.dev/gvisor/pkg/sentry/seccheck/points/points_go_proto\"\n+ \"gvisor.dev/gvisor/pkg/sync\"\n+ \"gvisor.dev/gvisor/pkg/test/testutil\"\n+ \"gvisor.dev/gvisor/pkg/unet\"\n+)\n+\n+// Server is the counterpart to the checkers.Remote. It receives connections\n+// remote checkers and stores all points that it receives.\n+type Server struct {\n+ Path string\n+ socket *unet.ServerSocket\n+\n+ mu sync.Mutex\n+\n+ // +checklocks:mu\n+ clients []*unet.Socket\n+\n+ // +checklocks:mu\n+ points []Message\n+}\n+\n+// Message corresponds to a single message sent from checkers.Remote.\n+type Message struct {\n+ // MsgType indicates what is the type of Msg.\n+ MsgType pb.MessageType\n+ // Msg is the payload to the message that can be decoded using MsgType.\n+ Msg []byte\n+}\n+\n+// NewServer creates a new server that listens to a UDS that it creates under\n+// os.TempDir.\n+func NewServer() (*Server, error) {\n+ dir, err := ioutil.TempDir(os.TempDir(), \"remote\")\n+ if err != nil {\n+ return nil, err\n+ }\n+ server, err := newServerPath(filepath.Join(dir, \"remote.sock\"))\n+ if err != nil {\n+ _ = os.RemoveAll(dir)\n+ return nil, err\n+ }\n+ return server, nil\n+}\n+\n+func newServerPath(path string) (*Server, error) {\n+ socket, err := unix.Socket(unix.AF_UNIX, unix.SOCK_SEQPACKET, 0)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"socket(AF_UNIX, SOCK_SEQPACKET, 0): %w\", err)\n+ }\n+ cu := cleanup.Make(func() {\n+ _ = unix.Close(socket)\n+ })\n+ defer cu.Clean()\n+\n+ sa := &unix.SockaddrUnix{Name: path}\n+ if err := unix.Bind(socket, sa); err != nil {\n+ return nil, fmt.Errorf(\"bind(%q): %w\", path, err)\n+ }\n+\n+ ss, err := unet.NewServerSocket(socket)\n+ if err != nil {\n+ return nil, err\n+ }\n+ cu.Add(func() { ss.Close() })\n+\n+ if err := ss.Listen(); err != nil {\n+ return nil, err\n+ }\n+\n+ server := &Server{\n+ Path: path,\n+ socket: ss,\n+ }\n+ go server.run()\n+ cu.Release()\n+ return server, nil\n+}\n+\n+func (s *Server) run() {\n+ for {\n+ client, err := s.socket.Accept()\n+ if err != nil {\n+ // EBADF returns when the socket closes.\n+ if !errors.Is(err, unix.EBADF) {\n+ log.Warningf(\"socket.Accept(): %v\", err)\n+ }\n+ return\n+ }\n+ s.mu.Lock()\n+ s.clients = append(s.clients, client)\n+ s.mu.Unlock()\n+ go s.handleClient(client)\n+ }\n+}\n+\n+func (s *Server) handleClient(client *unet.Socket) {\n+ defer func() {\n+ s.mu.Lock()\n+ for i, c := range s.clients {\n+ if c == client {\n+ s.clients = append(s.clients[:i], s.clients[i+1:]...)\n+ break\n+ }\n+ }\n+ s.mu.Unlock()\n+ _ = client.Close()\n+ }()\n+\n+ var buf = make([]byte, 1024*1024)\n+ for {\n+ read, err := client.Read(buf)\n+ if err != nil {\n+ return\n+ }\n+ if read == 0 {\n+ return\n+ }\n+ if read < header.HeaderStructSize {\n+ panic(\"invalid message\")\n+ }\n+ hdr := header.Header{}\n+ hdr.UnmarshalUnsafe(buf[0:header.HeaderStructSize])\n+ if read < int(hdr.HeaderSize) {\n+ panic(fmt.Sprintf(\"message truncated, header size: %d, readL %d\", hdr.HeaderSize, read))\n+ }\n+ msg := Message{\n+ MsgType: pb.MessageType(hdr.MessageType),\n+ Msg: buf[hdr.HeaderSize:read],\n+ }\n+ s.mu.Lock()\n+ s.points = append(s.points, msg)\n+ s.mu.Unlock()\n+ }\n+}\n+\n+// Count return the number of points it has received.\n+func (s *Server) Count() int {\n+ s.mu.Lock()\n+ defer s.mu.Unlock()\n+ return len(s.points)\n+}\n+\n+// GetPoints returns all points that it has received.\n+func (s *Server) GetPoints() []Message {\n+ s.mu.Lock()\n+ defer s.mu.Unlock()\n+ cpy := make([]Message, len(s.points))\n+ copy(cpy, s.points)\n+ return cpy\n+}\n+\n+// Close stops listenning and closes all connections.\n+func (s *Server) Close() {\n+ _ = s.socket.Close()\n+ s.mu.Lock()\n+ for _, client := range s.clients {\n+ _ = client.Close()\n+ }\n+ s.mu.Unlock()\n+ _ = os.Remove(s.Path)\n+}\n+\n+// WaitForCount waits for the number of points to reach the desired number for\n+// 5 seconds. It fails if not received in time.\n+func (s *Server) WaitForCount(count int) error {\n+ return testutil.Poll(func() error {\n+ if got := s.Count(); got < count {\n+ return fmt.Errorf(\"waiting for points %d to arrive, received %d\", count, got)\n+ }\n+ return nil\n+ }, 5*time.Second)\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Move test server into a separate package
It will be used for tests in other packages.
Updates #4805
PiperOrigin-RevId: 447076300 |
259,985 | 06.05.2022 16:04:18 | 25,200 | 409f32743b6e728ceb2c12da7252fa73b8df9131 | cgroupfs: Per cgroups(7), PID/TID 0 refers to the current task. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/base.go",
"new_path": "pkg/sentry/fsimpl/cgroupfs/base.go",
"diff": "@@ -363,7 +363,13 @@ func (d *cgroupProcsData) Write(ctx context.Context, fd *vfs.FileDescription, sr\nt := kernel.TaskFromContext(ctx)\ncurrPidns := t.ThreadGroup().PIDNamespace()\n- targetTG := currPidns.ThreadGroupWithID(kernel.ThreadID(tgid))\n+ var targetTG *kernel.ThreadGroup\n+ if tgid != 0 {\n+ targetTG = currPidns.ThreadGroupWithID(kernel.ThreadID(tgid))\n+ } else {\n+ targetTG = t.ThreadGroup()\n+ }\n+\nif targetTG == nil {\nreturn 0, linuxerr.EINVAL\n}\n@@ -405,7 +411,12 @@ func (d *tasksData) Write(ctx context.Context, fd *vfs.FileDescription, src user\nt := kernel.TaskFromContext(ctx)\ncurrPidns := t.ThreadGroup().PIDNamespace()\n- targetTask := currPidns.TaskWithID(kernel.ThreadID(tid))\n+ var targetTask *kernel.Task\n+ if tid != 0 {\n+ targetTask = currPidns.TaskWithID(kernel.ThreadID(tid))\n+ } else {\n+ targetTask = t\n+ }\nif targetTask == nil {\nreturn 0, linuxerr.EINVAL\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/cgroup.cc",
"new_path": "test/syscalls/linux/cgroup.cc",
"diff": "@@ -549,6 +549,42 @@ TEST(Cgroup, Rename) {\nEXPECT_THAT(Exists(child.Relpath(\"oldname\")), IsPosixErrorOkAndHolds(false));\n}\n+TEST(Cgroup, PIDZeroMovesSelf) {\n+ SKIP_IF(!CgroupsAvailable());\n+ Mounter m(ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir()));\n+ Cgroup c = ASSERT_NO_ERRNO_AND_VALUE(m.MountCgroupfs(\"\"));\n+ Cgroup child = ASSERT_NO_ERRNO_AND_VALUE(c.CreateChild(\"child\"));\n+\n+ // Source contains this process.\n+ EXPECT_NO_ERRNO(c.ContainsCallingProcess());\n+\n+ // Move to child by writing PID 0.\n+ ASSERT_NO_ERRNO(child.WriteIntegerControlFile(\"cgroup.procs\", 0));\n+\n+ // Destination now contains this process, and source does not.\n+ EXPECT_NO_ERRNO(child.ContainsCallingProcess());\n+ auto procs = ASSERT_NO_ERRNO_AND_VALUE(c.Procs());\n+ EXPECT_FALSE(procs.contains(getpid()));\n+}\n+\n+TEST(Cgroup, TIDZeroMovesSelf) {\n+ SKIP_IF(!CgroupsAvailable());\n+ Mounter m(ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir()));\n+ Cgroup c = ASSERT_NO_ERRNO_AND_VALUE(m.MountCgroupfs(\"\"));\n+ Cgroup child = ASSERT_NO_ERRNO_AND_VALUE(c.CreateChild(\"child\"));\n+\n+ // Source contains this thread.\n+ EXPECT_NO_ERRNO(c.ContainsCallingThread());\n+\n+ // Move to child by writing TID 0.\n+ ASSERT_NO_ERRNO(child.WriteIntegerControlFile(\"tasks\", 0));\n+\n+ // Destination now contains this thread, and source does not.\n+ EXPECT_NO_ERRNO(child.ContainsCallingThread());\n+ auto tasks = ASSERT_NO_ERRNO_AND_VALUE(c.Tasks());\n+ EXPECT_FALSE(tasks.contains(syscall(SYS_gettid)));\n+}\n+\nTEST(MemoryCgroup, MemoryUsageInBytes) {\nSKIP_IF(!CgroupsAvailable());\n"
}
] | Go | Apache License 2.0 | google/gvisor | cgroupfs: Per cgroups(7), PID/TID 0 refers to the current task.
PiperOrigin-RevId: 447090229 |
259,992 | 09.05.2022 10:30:54 | 25,200 | b3609b7167a76a11d42dad8d5b0fa77a9fd87974 | Fix race in remote_test.go | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/checkers/remote/remote_test.go",
"new_path": "pkg/sentry/seccheck/checkers/remote/remote_test.go",
"diff": "@@ -21,6 +21,7 @@ import (\n\"os/exec\"\n\"path/filepath\"\n\"strings\"\n+ \"sync\"\n\"testing\"\n\"time\"\n@@ -46,10 +47,28 @@ func waitForFile(path string) error {\n}, 5*time.Second)\n}\n+type syncBuffer struct {\n+ mu sync.Mutex\n+ // +checklocks:mu\n+ buf bytes.Buffer\n+}\n+\n+func (s *syncBuffer) Write(p []byte) (n int, err error) {\n+ s.mu.Lock()\n+ defer s.mu.Unlock()\n+ return s.buf.Write(p)\n+}\n+\n+func (s *syncBuffer) String() string {\n+ s.mu.Lock()\n+ defer s.mu.Unlock()\n+ return s.buf.String()\n+}\n+\ntype exampleServer struct {\npath string\ncmd *exec.Cmd\n- out bytes.Buffer\n+ out syncBuffer\n}\nfunc newExampleServer(quiet bool) (*exampleServer, error) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix race in remote_test.go
PiperOrigin-RevId: 447505504 |
259,868 | 09.05.2022 19:09:59 | 25,200 | 3c0fe6d08d5f318d14a6e1c355db5aa96feb31d5 | BuildKite: Remove duplicate `jq` from list of packages to install.
It is already listed earlier in the command line.
Ordinarily I wouldn't make a change for something this small, but I'm
going to use this change as a means to dip my toes with the BuildKite
build pipeline. | [
{
"change_type": "MODIFY",
"old_path": ".buildkite/hooks/pre-command",
"new_path": ".buildkite/hooks/pre-command",
"diff": "@@ -10,8 +10,7 @@ function install_pkgs() {\ndone\n}\ninstall_pkgs make linux-libc-dev graphviz jq curl binutils gnupg gnupg-agent \\\n- gcc pkg-config apt-transport-https ca-certificates software-properties-common \\\n- jq\n+ gcc pkg-config apt-transport-https ca-certificates software-properties-common\n# Install headers, only if available.\nif test -n \"$(apt-cache search --names-only \"^linux-headers-$(uname -r)$\")\"; then\n"
}
] | Go | Apache License 2.0 | google/gvisor | BuildKite: Remove duplicate `jq` from list of packages to install.
It is already listed earlier in the command line.
Ordinarily I wouldn't make a change for something this small, but I'm
going to use this change as a means to dip my toes with the BuildKite
build pipeline.
PiperOrigin-RevId: 447618014 |
259,891 | 10.05.2022 11:57:34 | 25,200 | a514a12c09e52d9962ac2e641dc5f804fc273abf | netstack: reduce allocations
Calls to IPTables.Check* functions were allocating on every single call, even
when IPTables were disabled. Changing from a method pointer to a function
pointer is enough to let the compiler know that nothing escapes and no
allocations are necessary. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables.go",
"new_path": "pkg/tcpip/stack/iptables.go",
"diff": "@@ -306,11 +306,11 @@ func (it *IPTables) shouldSkipOrPopulateTables(tables []checkTable, pkt *PacketB\nfunc (it *IPTables) CheckPrerouting(pkt *PacketBuffer, addressEP AddressableEndpoint, inNicName string) bool {\ntables := [...]checkTable{\n{\n- fn: it.check,\n+ fn: check,\ntableID: MangleID,\n},\n{\n- fn: it.checkNAT,\n+ fn: checkNAT,\ntableID: NATID,\n},\n}\n@@ -322,7 +322,7 @@ func (it *IPTables) CheckPrerouting(pkt *PacketBuffer, addressEP AddressableEndp\npkt.tuple = it.connections.getConnAndUpdate(pkt)\nfor _, table := range tables {\n- if !table.fn(table.table, Prerouting, pkt, nil /* route */, addressEP, inNicName, \"\" /* outNicName */) {\n+ if !table.fn(it, table.table, Prerouting, pkt, nil /* route */, addressEP, inNicName, \"\" /* outNicName */) {\nreturn false\n}\n}\n@@ -339,11 +339,11 @@ func (it *IPTables) CheckPrerouting(pkt *PacketBuffer, addressEP AddressableEndp\nfunc (it *IPTables) CheckInput(pkt *PacketBuffer, inNicName string) bool {\ntables := [...]checkTable{\n{\n- fn: it.checkNAT,\n+ fn: checkNAT,\ntableID: NATID,\n},\n{\n- fn: it.check,\n+ fn: check,\ntableID: FilterID,\n},\n}\n@@ -353,7 +353,7 @@ func (it *IPTables) CheckInput(pkt *PacketBuffer, inNicName string) bool {\n}\nfor _, table := range tables {\n- if !table.fn(table.table, Input, pkt, nil /* route */, nil /* addressEP */, inNicName, \"\" /* outNicName */) {\n+ if !table.fn(it, table.table, Input, pkt, nil /* route */, nil /* addressEP */, inNicName, \"\" /* outNicName */) {\nreturn false\n}\n}\n@@ -374,7 +374,7 @@ func (it *IPTables) CheckInput(pkt *PacketBuffer, inNicName string) bool {\nfunc (it *IPTables) CheckForward(pkt *PacketBuffer, inNicName, outNicName string) bool {\ntables := [...]checkTable{\n{\n- fn: it.check,\n+ fn: check,\ntableID: FilterID,\n},\n}\n@@ -384,7 +384,7 @@ func (it *IPTables) CheckForward(pkt *PacketBuffer, inNicName, outNicName string\n}\nfor _, table := range tables {\n- if !table.fn(table.table, Forward, pkt, nil /* route */, nil /* addressEP */, inNicName, outNicName) {\n+ if !table.fn(it, table.table, Forward, pkt, nil /* route */, nil /* addressEP */, inNicName, outNicName) {\nreturn false\n}\n}\n@@ -401,15 +401,15 @@ func (it *IPTables) CheckForward(pkt *PacketBuffer, inNicName, outNicName string\nfunc (it *IPTables) CheckOutput(pkt *PacketBuffer, r *Route, outNicName string) bool {\ntables := [...]checkTable{\n{\n- fn: it.check,\n+ fn: check,\ntableID: MangleID,\n},\n{\n- fn: it.checkNAT,\n+ fn: checkNAT,\ntableID: NATID,\n},\n{\n- fn: it.check,\n+ fn: check,\ntableID: FilterID,\n},\n}\n@@ -421,7 +421,7 @@ func (it *IPTables) CheckOutput(pkt *PacketBuffer, r *Route, outNicName string)\npkt.tuple = it.connections.getConnAndUpdate(pkt)\nfor _, table := range tables {\n- if !table.fn(table.table, Output, pkt, r, nil /* addressEP */, \"\" /* inNicName */, outNicName) {\n+ if !table.fn(it, table.table, Output, pkt, r, nil /* addressEP */, \"\" /* inNicName */, outNicName) {\nreturn false\n}\n}\n@@ -438,11 +438,11 @@ func (it *IPTables) CheckOutput(pkt *PacketBuffer, r *Route, outNicName string)\nfunc (it *IPTables) CheckPostrouting(pkt *PacketBuffer, r *Route, addressEP AddressableEndpoint, outNicName string) bool {\ntables := [...]checkTable{\n{\n- fn: it.check,\n+ fn: check,\ntableID: MangleID,\n},\n{\n- fn: it.checkNAT,\n+ fn: checkNAT,\ntableID: NATID,\n},\n}\n@@ -452,7 +452,7 @@ func (it *IPTables) CheckPostrouting(pkt *PacketBuffer, r *Route, addressEP Addr\n}\nfor _, table := range tables {\n- if !table.fn(table.table, Postrouting, pkt, r, addressEP, \"\" /* inNicName */, outNicName) {\n+ if !table.fn(it, table.table, Postrouting, pkt, r, addressEP, \"\" /* inNicName */, outNicName) {\nreturn false\n}\n}\n@@ -464,7 +464,13 @@ func (it *IPTables) CheckPostrouting(pkt *PacketBuffer, r *Route, addressEP Addr\nreturn true\n}\n-type checkTableFn func(table Table, hook Hook, pkt *PacketBuffer, r *Route, addressEP AddressableEndpoint, inNicName, outNicName string) bool\n+// Note: this used to omit the *IPTables parameter, but doing so caused\n+// unnecessary allocations.\n+type checkTableFn func(it *IPTables, table Table, hook Hook, pkt *PacketBuffer, r *Route, addressEP AddressableEndpoint, inNicName, outNicName string) bool\n+\n+func checkNAT(it *IPTables, table Table, hook Hook, pkt *PacketBuffer, r *Route, addressEP AddressableEndpoint, inNicName, outNicName string) bool {\n+ return it.checkNAT(table, hook, pkt, r, addressEP, inNicName, outNicName)\n+}\n// checkNAT runs the packet through the NAT table.\n//\n@@ -507,6 +513,10 @@ func (it *IPTables) checkNAT(table Table, hook Hook, pkt *PacketBuffer, r *Route\nreturn true\n}\n+func check(it *IPTables, table Table, hook Hook, pkt *PacketBuffer, r *Route, addressEP AddressableEndpoint, inNicName, outNicName string) bool {\n+ return it.check(table, hook, pkt, r, addressEP, inNicName, outNicName)\n+}\n+\n// check runs the packet through the rules in the specified table for the\n// hook. It returns true if the packet should continue to traverse through the\n// network stack or tables, or false when it must be dropped.\n"
}
] | Go | Apache License 2.0 | google/gvisor | netstack: reduce allocations
Calls to IPTables.Check* functions were allocating on every single call, even
when IPTables were disabled. Changing from a method pointer to a function
pointer is enough to let the compiler know that nothing escapes and no
allocations are necessary.
PiperOrigin-RevId: 447792280 |
259,853 | 10.05.2022 13:22:17 | 25,200 | 3aab92297af5c95b866e1be878a0230d5f97a9b6 | Add new locks with the correctness validator
All locks are separated into classes. The validator builds a dependency
graph and checks that it doesn't have cycles. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sync/locking/BUILD",
"diff": "+load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+load(\"//tools/go_generics:defs.bzl\", \"go_template\", \"go_template_instance\")\n+load(\"//pkg/sync/locking:locking.bzl\", \"declare_mutex\", \"declare_rwmutex\")\n+\n+package(\n+ default_visibility = [\"//:sandbox\"],\n+ licenses = [\"notice\"],\n+)\n+\n+go_library(\n+ name = \"locking\",\n+ srcs = [\n+ \"atomicptrmap_ancestors_unsafe.go\",\n+ \"atomicptrmap_class_unsafe.go\",\n+ \"atomicptrmap_goroutine_unsafe.go\",\n+ \"atomicptrmap_subclass_unsafe.go\",\n+ \"lockdep.go\",\n+ \"lockdep_norace.go\",\n+ \"locking.go\",\n+ ],\n+ marshal = False,\n+ stateify = False,\n+ visibility = [\"//:sandbox\"],\n+ deps = [\n+ \"//pkg/gohacks\",\n+ \"//pkg/goid\",\n+ \"//pkg/log\",\n+ \"//pkg/sync\",\n+ ],\n+)\n+\n+go_template_instance(\n+ name = \"atomicptrmap_goroutine\",\n+ out = \"atomicptrmap_goroutine_unsafe.go\",\n+ package = \"locking\",\n+ prefix = \"goroutineLocks\",\n+ template = \"//pkg/sync/atomicptrmap:generic_atomicptrmap\",\n+ types = {\n+ \"Key\": \"int64\",\n+ \"Value\": \"goroutineLocks\",\n+ },\n+)\n+\n+go_template_instance(\n+ name = \"atomicptrmap_class\",\n+ out = \"atomicptrmap_class_unsafe.go\",\n+ imports = {\n+ \"reflect\": \"reflect\",\n+ },\n+ package = \"locking\",\n+ prefix = \"class\",\n+ template = \"//pkg/sync/atomicptrmap:generic_atomicptrmap\",\n+ types = {\n+ \"Key\": \"*MutexClass\",\n+ \"Value\": \"reflect.Type\",\n+ },\n+)\n+\n+go_template_instance(\n+ name = \"atomicptrmap_subclass\",\n+ out = \"atomicptrmap_subclass_unsafe.go\",\n+ imports = {\n+ \"reflect\": \"reflect\",\n+ },\n+ package = \"locking\",\n+ prefix = \"subclass\",\n+ template = \"//pkg/sync/atomicptrmap:generic_atomicptrmap\",\n+ types = {\n+ \"Key\": \"uint32\",\n+ \"Value\": \"MutexClass\",\n+ },\n+)\n+\n+go_template_instance(\n+ name = \"atomicptrmap_ancestors\",\n+ out = \"atomicptrmap_ancestors_unsafe.go\",\n+ imports = {\n+ \"reflect\": \"reflect\",\n+ },\n+ package = \"locking\",\n+ prefix = \"ancestors\",\n+ template = \"//pkg/sync/atomicptrmap:generic_atomicptrmap\",\n+ types = {\n+ \"Key\": \"*MutexClass\",\n+ \"Value\": \"string\",\n+ },\n+)\n+\n+go_template(\n+ name = \"generic_mutex\",\n+ srcs = [\"generic_mutex.go\"],\n+ visibility = [\"//:sandbox\"],\n+)\n+\n+go_template(\n+ name = \"generic_rwmutex\",\n+ srcs = [\"generic_rwmutex.go\"],\n+ visibility = [\"//:sandbox\"],\n+)\n+\n+declare_mutex(\n+ name = \"mutex_test\",\n+ out = \"mutex_test.go\",\n+ package = \"locking_test\",\n+ prefix = \"test\",\n+)\n+\n+declare_rwmutex(\n+ name = \"mutex_test2\",\n+ out = \"mutex_test2.go\",\n+ package = \"locking_test\",\n+ prefix = \"test2\",\n+)\n+\n+declare_mutex(\n+ name = \"mutex_test3\",\n+ out = \"mutex_test3.go\",\n+ package = \"locking_test\",\n+ prefix = \"test3\",\n+)\n+\n+go_test(\n+ name = \"locking_test\",\n+ size = \"small\",\n+ srcs = [\n+ \"lockdep_nolockdep_test.go\",\n+ \"lockdep_test.go\",\n+ \"mutex_test.go\",\n+ \"mutex_test2.go\",\n+ \"mutex_test3.go\",\n+ ],\n+ deps = [\n+ \"//pkg/sync\",\n+ \"//pkg/sync/locking\",\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sync/locking/generic_mutex.go",
"diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package locking\n+\n+import (\n+ \"reflect\"\n+\n+ \"gvisor.dev/gvisor/pkg/sync\"\n+ \"gvisor.dev/gvisor/pkg/sync/locking\"\n+)\n+\n+// Mutex is sync.Mutex with the correctness validator.\n+type Mutex struct {\n+ mu sync.Mutex\n+}\n+\n+// Lock locks m.\n+// +checklocksignore\n+func (m *Mutex) Lock() {\n+ locking.AddGLock(genericMarkIndex, 0)\n+ m.mu.Lock()\n+}\n+\n+// NestedLock locks m knowing that another lock of the same type is held.\n+// +checklocksignore\n+func (m *Mutex) NestedLock() {\n+ locking.AddGLock(genericMarkIndex, 1)\n+ m.mu.Lock()\n+}\n+\n+// Unlock unlocks m.\n+// +checklocksignore\n+func (m *Mutex) Unlock() {\n+ locking.DelGLock(genericMarkIndex, 0)\n+ m.mu.Unlock()\n+}\n+\n+// NestedUnlock unlocks m knowing that another lock of the same type is held.\n+// +checklocksignore\n+func (m *Mutex) NestedUnlock() {\n+ locking.DelGLock(genericMarkIndex, 1)\n+ m.mu.Unlock()\n+}\n+\n+var genericMarkIndex *locking.MutexClass\n+\n+func init() {\n+ genericMarkIndex = locking.NewMutexClass(reflect.TypeOf(Mutex{}))\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sync/locking/generic_rwmutex.go",
"diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package locking\n+\n+import (\n+ \"reflect\"\n+\n+ \"gvisor.dev/gvisor/pkg/sync\"\n+ \"gvisor.dev/gvisor/pkg/sync/locking\"\n+)\n+\n+// RWMutex is sync.RWMutex with the correctness validator.\n+type RWMutex struct {\n+ mu sync.RWMutex\n+}\n+\n+// Lock locks m.\n+// +checklocksignore\n+func (m *RWMutex) Lock() {\n+ locking.AddGLock(genericMarkIndex, 0)\n+ m.mu.Lock()\n+}\n+\n+// NestedLock locks m knowing that another lock of the same type is held.\n+// +checklocksignore\n+func (m *RWMutex) NestedLock() {\n+ locking.AddGLock(genericMarkIndex, 1)\n+ m.mu.Lock()\n+}\n+\n+// Unlock unlocks m.\n+// +checklocksignore\n+func (m *RWMutex) Unlock() {\n+ m.mu.Unlock()\n+ locking.DelGLock(genericMarkIndex, 0)\n+}\n+\n+// NestedUnlock unlocks m knowing that another lock of the same type is held.\n+// +checklocksignore\n+func (m *RWMutex) NestedUnlock() {\n+ m.mu.Unlock()\n+ locking.DelGLock(genericMarkIndex, 1)\n+}\n+\n+// RLock locks m for reading.\n+// +checklocksignore\n+func (m *RWMutex) RLock() {\n+ locking.AddGLock(genericMarkIndex, 0)\n+ m.mu.RLock()\n+}\n+\n+// RUnlock undoes a single RLock call.\n+// +checklocksignore\n+func (m *RWMutex) RUnlock() {\n+ m.mu.RUnlock()\n+ locking.DelGLock(genericMarkIndex, 0)\n+}\n+\n+// RLockBypass locks m for reading without executing the validator.\n+// +checklocksignore\n+func (m *RWMutex) RLockBypass() {\n+ m.mu.RLock()\n+}\n+\n+// RUnlockBypass undoes a single RLockBypass call.\n+// +checklocksignore\n+func (m *RWMutex) RUnlockBypass() {\n+ m.mu.RUnlock()\n+}\n+\n+// DowngradeLock atomically unlocks rw for writing and locks it for reading.\n+// +checklocksignore\n+func (m *RWMutex) DowngradeLock() {\n+ m.mu.DowngradeLock()\n+}\n+\n+var genericMarkIndex *locking.MutexClass\n+\n+func init() {\n+ genericMarkIndex = locking.NewMutexClass(reflect.TypeOf(RWMutex{}))\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sync/locking/lockdep.go",
"diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+//go:build lockdep\n+// +build lockdep\n+\n+package locking\n+\n+import (\n+ \"fmt\"\n+ \"reflect\"\n+ \"strings\"\n+\n+ \"gvisor.dev/gvisor/pkg/goid\"\n+ \"gvisor.dev/gvisor/pkg/log\"\n+)\n+\n+var classMap classAtomicPtrMap\n+\n+// NewMutexClass allocates a new mutex class.\n+func NewMutexClass(t reflect.Type) *MutexClass {\n+ c := &MutexClass{}\n+ classMap.Store(c, &t)\n+ return c\n+}\n+\n+// MutexClass describes dependencies of a specific class.\n+type MutexClass struct {\n+ // ancestors are locks that are locked before the current class.\n+ ancestors ancestorsAtomicPtrMap\n+ // subclasses is the list of sub-classes that are used to handle nested locks.\n+ subclasses subclassAtomicPtrMap\n+}\n+\n+type goroutineLocks map[*MutexClass]bool\n+\n+var routineLocks goroutineLocksAtomicPtrMap\n+\n+// checkLock checks that class isn't in ancestors of prevClass.\n+func checkLock(class *MutexClass, prevClass *MutexClass, chain []*MutexClass) {\n+ chain = append(chain, prevClass)\n+ if c := prevClass.ancestors.Load(class); c != nil {\n+ var b strings.Builder\n+ fmt.Fprintf(&b, \"WARNING: circular locking detected: %s -> %s:\\n%s\\n\",\n+ *classMap.Load(chain[0]), *classMap.Load(class), log.Stacks(false))\n+\n+ fmt.Fprintf(&b, \"known lock chain: \")\n+ c := class\n+ for i := len(chain) - 1; i >= 0; i-- {\n+ fmt.Fprintf(&b, \"%s -> \", *classMap.Load(c))\n+ c = chain[i]\n+ }\n+ fmt.Fprintf(&b, \"%s\\n\", *classMap.Load(chain[0]))\n+ c = class\n+ for i := len(chain) - 1; i >= 0; i-- {\n+ fmt.Fprintf(&b, \"\\n====== %s -> %s =====\\n%s\",\n+ *classMap.Load(c), *classMap.Load(chain[i]), *chain[i].ancestors.Load(c))\n+ c = chain[i]\n+ }\n+ panic(b.String())\n+ }\n+ prevClass.ancestors.Range(func(parentClass *MutexClass, stacks *string) bool {\n+ // The recursion is fine here. If it fails, you need to reduce\n+ // a number of nested locks.\n+ checkLock(class, parentClass, chain)\n+ return true\n+ })\n+}\n+\n+// AddGLock records a lock to the current goroutine and updates dependences.\n+func AddGLock(class *MutexClass, subclass uint32) {\n+ gid := goid.Get()\n+\n+ if subclass != 0 {\n+ var c *MutexClass\n+ if c = class.subclasses.Load(subclass); c == nil {\n+ t := classMap.Load(class)\n+ c = NewMutexClass(*t)\n+ class.subclasses.Store(subclass, c)\n+ }\n+ class = c\n+ }\n+ currentLocks := routineLocks.Load(gid)\n+ if currentLocks == nil {\n+ locks := goroutineLocks(make(map[*MutexClass]bool))\n+ locks[class] = true\n+ routineLocks.Store(gid, &locks)\n+ return\n+ }\n+\n+ // Check dependencies and add locked mutexes to the ancestors list.\n+ for prevClass, _ := range *currentLocks {\n+ if prevClass == class {\n+ panic(fmt.Sprintf(\"nested locking: %s:\\n%s\", *classMap.Load(class), log.Stacks(false)))\n+ }\n+ checkLock(class, prevClass, nil)\n+\n+ if c := class.ancestors.Load(prevClass); c == nil {\n+ stacks := string(log.Stacks(false))\n+ class.ancestors.Store(prevClass, &stacks)\n+ }\n+ }\n+ (*currentLocks)[class] = true\n+\n+}\n+\n+// DelGLock deletes a lock from the current goroutine.\n+func DelGLock(class *MutexClass, subclass uint32) {\n+ if subclass != 0 {\n+ class = class.subclasses.Load(subclass)\n+ }\n+ gid := goid.Get()\n+ currentLocks := routineLocks.Load(gid)\n+ if currentLocks == nil {\n+ panic(\"the current goroutine doesn't have locks\")\n+ }\n+ if _, ok := (*currentLocks)[class]; !ok {\n+ panic(\"unlock of an unknow lock\")\n+ }\n+\n+ delete(*currentLocks, class)\n+ if len(*currentLocks) == 0 {\n+ routineLocks.Store(gid, nil)\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sync/locking/lockdep_nolockdep_test.go",
"diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+//go:build !lockdep\n+// +build !lockdep\n+\n+package locking_test\n+\n+import (\n+ \"testing\"\n+)\n+\n+// Ensure that lockdep is not enabled unless \"lockdep\" tag is set.\n+func TestDummy(t *testing.T) {\n+ m := testMutex{}\n+ m2 := test2RWMutex{}\n+ m.Lock()\n+ m2.Lock()\n+ t.Logf(\"m->m2\")\n+ m2.Unlock()\n+ m.Unlock()\n+ m2.Lock()\n+ m.Lock()\n+ t.Logf(\"m2->m\")\n+ m.Unlock()\n+ m2.Unlock()\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sync/locking/lockdep_norace.go",
"diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+//go:build !lockdep\n+// +build !lockdep\n+\n+package locking\n+\n+import (\n+ \"reflect\"\n+)\n+\n+type goroutineLocks map[*MutexClass]bool\n+\n+// MutexClass is a stub class without the lockdep tag.\n+type MutexClass struct{}\n+\n+// NewMutexClass is no-op without the lockdep tag.\n+func NewMutexClass(t reflect.Type) *MutexClass {\n+ return nil\n+}\n+\n+// AddGLock is no-op without the lockdep tag.\n+//go:inline\n+func AddGLock(class *MutexClass, subclass uint32) {}\n+\n+// DelGLock is no-op without the lockdep tag.\n+//go:inline\n+func DelGLock(class *MutexClass, subclass uint32) {}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sync/locking/lockdep_test.go",
"diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+//go:build lockdep\n+// +build lockdep\n+\n+package locking_test\n+\n+import (\n+ \"testing\"\n+)\n+\n+func TestReverse(t *testing.T) {\n+ m := testMutex{}\n+ m2 := test2RWMutex{}\n+ m.Lock()\n+ m2.Lock()\n+ m2.Unlock()\n+ m.Unlock()\n+\n+ defer func() {\n+ if r := recover(); r != nil {\n+ t.Logf(\"Got expected panic: %s\", r)\n+ }\n+ }()\n+\n+ m2.Lock()\n+ m.Lock()\n+ m.Unlock()\n+ m2.Unlock()\n+ t.Error(\"The reverse lock order hasn't been detected\")\n+}\n+\n+func TestIndirect(t *testing.T) {\n+ m1 := testMutex{}\n+ m2 := test2RWMutex{}\n+ m3 := test3Mutex{}\n+\n+ m1.Lock()\n+ m2.Lock()\n+ m2.Unlock()\n+ m1.Unlock()\n+ m2.Lock()\n+ m3.Lock()\n+ m3.Unlock()\n+ m2.Unlock()\n+ defer func() {\n+ if r := recover(); r != nil {\n+ t.Logf(\"Got expected panic: %s\", r)\n+ }\n+ }()\n+\n+ m3.Lock()\n+ m1.Lock()\n+ m1.Unlock()\n+ m3.Unlock()\n+ t.Error(\"The reverse lock order hasn't been detected\")\n+}\n+\n+func TestSame(t *testing.T) {\n+ defer func() {\n+ if r := recover(); r != nil {\n+ t.Logf(\"Got expected panic: %s\", r)\n+ }\n+ }()\n+\n+ m := testMutex{}\n+ m.Lock()\n+ m.Lock()\n+ m.Unlock()\n+ m.Unlock()\n+ t.Error(\"The same lock has been locked twice, and was not detected.\")\n+}\n+\n+func TestReverseNested(t *testing.T) {\n+ m1 := testMutex{}\n+ m2 := testMutex{}\n+ m1.Lock()\n+ m2.NestedLock()\n+ m1.Unlock()\n+ m2.NestedUnlock()\n+\n+ defer func() {\n+ if r := recover(); r != nil {\n+ t.Logf(\"Got expected panic: %s\", r)\n+ }\n+ }()\n+\n+ m2.NestedLock()\n+ m1.Lock()\n+ m1.NestedUnlock()\n+ m2.Unlock()\n+\n+ t.Error(\"The reverse lock order hasn't been detected\")\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sync/locking/locking.bzl",
"diff": "+\"\"\"Mutex-s rules.\"\"\"\n+\n+load(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\n+\n+def declare_mutex(package, name, out, prefix):\n+ go_template_instance(\n+ name = name,\n+ out = out,\n+ package = package,\n+ prefix = prefix,\n+ substrs = {\n+ \"genericMark\": \"prefix\",\n+ },\n+ template = \"//pkg/sync/locking:generic_mutex\",\n+ )\n+\n+def declare_rwmutex(package, name, out, prefix):\n+ go_template_instance(\n+ name = name,\n+ out = out,\n+ package = package,\n+ prefix = prefix,\n+ substrs = {\n+ \"genericMark\": \"prefix\",\n+ },\n+ template = \"//pkg/sync/locking:generic_rwmutex\",\n+ )\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sync/locking/locking.go",
"diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// Package locking implements lock primitives with the correctness validator.\n+//\n+// All mutexes are divided on classes and the validator check following conditions:\n+// * Mutexes of the same class are not taken more than once except cases when\n+// that is expected.\n+// * Mutexes are never locked in a reverse order. Lock dependencies are tracked\n+// on the class level.\n+//\n+// The validator is implemented in a very straightforward way. For each mutex\n+// class, we maintain the ancestors list of all classes that have ever been\n+// taken before the target one. For each goroutine, we have the list of\n+// currently locked mutexes. And finally, all lock methods check that\n+// ancestors of currently locked mutexes don't contain the target one.\n+package locking\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/BUILD",
"new_path": "runsc/BUILD",
"diff": "@@ -36,6 +36,7 @@ go_binary(\n\"main.go\",\n\"version.go\",\n],\n+ gotags = [\"lockdep\"],\nstatic = True,\nvisibility = [\n\"//visibility:public\",\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/bazel.mk",
"new_path": "tools/bazel.mk",
"diff": "@@ -202,6 +202,9 @@ clean: ## Cleans the bazel cache.\n@$(call clean)\n.PHONY: clean\n+runsc-race:\n+ @$(call build,--@io_bazel_rules_go//go/config:race runsc:runsc-race)\n+\ntestlogs: ## Returns the most recent set of test logs.\n@if test -f .build_events.json; then \\\ncat .build_events.json | jq -r \\\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/checklocks/analysis.go",
"new_path": "tools/checklocks/analysis.go",
"diff": "@@ -474,11 +474,12 @@ func (pc *passContext) checkFunctionCall(call callCommon, fn *types.Func, lff *l\n// Check if it's a method dispatch for something in the sync package.\n// See: https://godoc.org/golang.org/x/tools/go/ssa#Function\n- if fn.Pkg() != nil && fn.Pkg().Name() == \"sync\" && len(args) > 0 {\n+\n+ if (lockerRE.MatchString(fn.FullName()) || mutexRE.MatchString(fn.FullName())) && len(args) > 0 {\nrv := makeResolvedValue(args[0], nil)\nisExclusive := false\nswitch fn.Name() {\n- case \"Lock\":\n+ case \"Lock\", \"NestedLock\":\nisExclusive = true\nfallthrough\ncase \"RLock\":\n@@ -488,7 +489,7 @@ func (pc *passContext) checkFunctionCall(call callCommon, fn *types.Func, lff *l\npc.maybeFail(call.Pos(), \"%s already locked (locks: %s)\", s, ls.String())\n}\n}\n- case \"Unlock\":\n+ case \"Unlock\", \"NestedUnlock\":\nisExclusive = true\nfallthrough\ncase \"RUnlock\":\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/checklocks/facts.go",
"new_path": "tools/checklocks/facts.go",
"diff": "@@ -469,9 +469,9 @@ func (pc *passContext) findField(structType *types.Struct, fieldName string) (fl\n}\nvar (\n- mutexRE = regexp.MustCompile(\"((.*/)|^)sync.(CrossGoroutineMutex|Mutex)\")\n- rwMutexRE = regexp.MustCompile(\"((.*/)|^)sync.(CrossGoroutineRWMutex|RWMutex)\")\n- lockerRE = regexp.MustCompile(\"((.*/)|^)sync.Locker\")\n+ mutexRE = regexp.MustCompile(\".*Mutex\")\n+ rwMutexRE = regexp.MustCompile(\".*RWMutex\")\n+ lockerRE = regexp.MustCompile(\".*sync.Locker\")\n)\n// validateMutex validates the mutex type.\n@@ -482,6 +482,9 @@ func (pc *passContext) validateMutex(pos token.Pos, obj types.Object, exclusive\n// Check that it is indeed a mutex.\ns := obj.Type().String()\nswitch {\n+ case rwMutexRE.MatchString(s):\n+ // Safe for all cases.\n+ return true\ncase mutexRE.MatchString(s), lockerRE.MatchString(s):\n// Safe for exclusive cases.\nif !exclusive {\n@@ -489,9 +492,6 @@ func (pc *passContext) validateMutex(pos token.Pos, obj types.Object, exclusive\nreturn false\n}\nreturn true\n- case rwMutexRE.MatchString(s):\n- // Safe for all cases.\n- return true\ndefault:\n// Not a mutex at all?\npc.maybeFail(pos, \"field %s is not a Mutex or an RWMutex\", obj.Name())\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/go_generics/defs.bzl",
"new_path": "tools/go_generics/defs.bzl",
"diff": "@@ -93,6 +93,7 @@ def _go_template_instance_impl(ctx):\nargs += [(\"-t=%s=%s\" % (p[0], p[1])) for p in ctx.attr.types.items()]\nargs += [(\"-c=%s=%s\" % (p[0], p[1])) for p in ctx.attr.consts.items()]\nargs += [(\"-import=%s=%s\" % (p[0], p[1])) for p in ctx.attr.imports.items()]\n+ args += [(\"-s=%s=%s\" % (p[0], p[1])) for p in ctx.attr.substrs.items()]\nif ctx.attr.anon:\nargs.append(\"-anon\")\n@@ -119,6 +120,7 @@ go_template_instance = rule(\n\"types\": attr.string_dict(doc = \"the map from generic type names to concrete ones\"),\n\"consts\": attr.string_dict(doc = \"the map from constant names to their values\"),\n\"imports\": attr.string_dict(doc = \"the map from imports used in types/consts to their import paths\"),\n+ \"substrs\": attr.string_dict(doc = \"the map from sub-strings to their replacements\"),\n\"anon\": attr.bool(doc = \"whether anoymous fields should be processed\", mandatory = False, default = False),\n\"package\": attr.string(doc = \"the package for the generated source file\", mandatory = False),\n\"out\": attr.output(doc = \"output file\", mandatory = True),\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/go_generics/main.go",
"new_path": "tools/go_generics/main.go",
"diff": "@@ -117,6 +117,7 @@ var (\ntypes = make(mapValue)\nconsts = make(mapValue)\nimports = make(mapValue)\n+ substr = make(mapValue)\n)\n// mapValue implements flag.Value. We use a mapValue flag instead of a regular\n@@ -165,6 +166,7 @@ func main() {\nflag.Var(types, \"t\", \"rename type A to B when `A=B` is passed in. Multiple such mappings are allowed.\")\nflag.Var(consts, \"c\", \"reassign constant A to value B when `A=B` is passed in. Multiple such mappings are allowed.\")\nflag.Var(imports, \"import\", \"specifies the import libraries to use when types are not local. `name=path` specifies that 'name', used in types as name.type, refers to the package living in 'path'.\")\n+ flag.Var(substr, \"s\", \"replace sub-string A with B when `A=B` is passed in. Multiple such mappings are allowed.\")\nflag.Parse()\nif *input == \"\" || *output == \"\" {\n@@ -279,7 +281,12 @@ func main() {\nos.Exit(1)\n}\n- if err := ioutil.WriteFile(*output, buf.Bytes(), 0644); err != nil {\n+ byteBuf := buf.Bytes()\n+ for old, new := range substr {\n+ byteBuf = bytes.ReplaceAll(byteBuf, []byte(old), []byte(new))\n+ }\n+\n+ if err := ioutil.WriteFile(*output, byteBuf, 0644); err != nil {\nfmt.Fprintf(os.Stderr, \"%v\\n\", err)\nos.Exit(1)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add new locks with the correctness validator
All locks are separated into classes. The validator builds a dependency
graph and checks that it doesn't have cycles.
PiperOrigin-RevId: 447812244 |
259,891 | 10.05.2022 13:24:59 | 25,200 | f0737cc307f6e503cae1fb0063189e6ef8eebdb3 | netstack: use checkescape in iptables hot paths
These functions used to allocate even when iptables were disabled. Prevent that
from happening again.
Update to also use gVisor's sync package, as we were using the standard one. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables.go",
"new_path": "pkg/tcpip/stack/iptables.go",
"diff": "@@ -273,6 +273,10 @@ type checkTable struct {\n//\n// If IPTables should not be skipped, tables will be updated with the\n// specified table.\n+//\n+// This is called in the hot path even when iptables are disabled, so we ensure\n+// it does not allocate.\n+// +checkescape:heap,builtin\nfunc (it *IPTables) shouldSkipOrPopulateTables(tables []checkTable, pkt *PacketBuffer) bool {\nswitch pkt.NetworkProtocolNumber {\ncase header.IPv4ProtocolNumber, header.IPv6ProtocolNumber:\n@@ -303,6 +307,11 @@ func (it *IPTables) shouldSkipOrPopulateTables(tables []checkTable, pkt *PacketB\n// must be dropped if false is returned.\n//\n// Precondition: The packet's network and transport header must be set.\n+//\n+// This is called in the hot path even when iptables are disabled, so we ensure\n+// that it does not allocate. Note that called functions (e.g.\n+// getConnAndUpdate) can allocate.\n+// +checkescape\nfunc (it *IPTables) CheckPrerouting(pkt *PacketBuffer, addressEP AddressableEndpoint, inNicName string) bool {\ntables := [...]checkTable{\n{\n@@ -336,6 +345,11 @@ func (it *IPTables) CheckPrerouting(pkt *PacketBuffer, addressEP AddressableEndp\n// must be dropped if false is returned.\n//\n// Precondition: The packet's network and transport header must be set.\n+//\n+// This is called in the hot path even when iptables are disabled, so we ensure\n+// that it does not allocate. Note that called functions (e.g.\n+// getConnAndUpdate) can allocate.\n+// +checkescape\nfunc (it *IPTables) CheckInput(pkt *PacketBuffer, inNicName string) bool {\ntables := [...]checkTable{\n{\n@@ -371,6 +385,11 @@ func (it *IPTables) CheckInput(pkt *PacketBuffer, inNicName string) bool {\n// must be dropped if false is returned.\n//\n// Precondition: The packet's network and transport header must be set.\n+//\n+// This is called in the hot path even when iptables are disabled, so we ensure\n+// that it does not allocate. Note that called functions (e.g.\n+// getConnAndUpdate) can allocate.\n+// +checkescape\nfunc (it *IPTables) CheckForward(pkt *PacketBuffer, inNicName, outNicName string) bool {\ntables := [...]checkTable{\n{\n@@ -398,6 +417,11 @@ func (it *IPTables) CheckForward(pkt *PacketBuffer, inNicName, outNicName string\n// must be dropped if false is returned.\n//\n// Precondition: The packet's network and transport header must be set.\n+//\n+// This is called in the hot path even when iptables are disabled, so we ensure\n+// that it does not allocate. Note that called functions (e.g.\n+// getConnAndUpdate) can allocate.\n+// +checkescape\nfunc (it *IPTables) CheckOutput(pkt *PacketBuffer, r *Route, outNicName string) bool {\ntables := [...]checkTable{\n{\n@@ -435,6 +459,11 @@ func (it *IPTables) CheckOutput(pkt *PacketBuffer, r *Route, outNicName string)\n// must be dropped if false is returned.\n//\n// Precondition: The packet's network and transport header must be set.\n+//\n+// This is called in the hot path even when iptables are disabled, so we ensure\n+// that it does not allocate. Note that called functions (e.g.\n+// getConnAndUpdate) can allocate.\n+// +checkescape\nfunc (it *IPTables) CheckPostrouting(pkt *PacketBuffer, r *Route, addressEP AddressableEndpoint, outNicName string) bool {\ntables := [...]checkTable{\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables_types.go",
"new_path": "pkg/tcpip/stack/iptables_types.go",
"diff": "@@ -17,8 +17,8 @@ package stack\nimport (\n\"fmt\"\n\"strings\"\n- \"sync\"\n+ \"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n)\n"
}
] | Go | Apache License 2.0 | google/gvisor | netstack: use checkescape in iptables hot paths
These functions used to allocate even when iptables were disabled. Prevent that
from happening again.
Update to also use gVisor's sync package, as we were using the standard one.
PiperOrigin-RevId: 447812920 |
259,951 | 10.05.2022 13:30:17 | 25,200 | 944b941f9d4196dcd00aa2cce0bc1f087697718c | Allow martian packets on packet socket dgram tests
Before this change, this test fixture expected it to be enabled already
instead of updating the config.
The Teardown method also restore the initial configuration, so that
these tests do not permanently change the config of the machines that
run the tests. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/packet_socket_dgram.cc",
"new_path": "test/syscalls/linux/packet_socket_dgram.cc",
"diff": "@@ -122,6 +122,9 @@ class CookedPacketTest : public ::testing::TestWithParam<int> {\n// The socket used for both reading and writing.\nint socket_;\n+\n+ // The function to restore the original system configuration.\n+ std::function<PosixError()> restore_config_;\n};\nvoid CookedPacketTest::SetUp() {\n@@ -131,25 +134,17 @@ void CookedPacketTest::SetUp() {\nGTEST_SKIP();\n}\n- if (!IsRunningOnGvisor()) {\n- FileDescriptor acceptLocal = ASSERT_NO_ERRNO_AND_VALUE(\n- Open(\"/proc/sys/net/ipv4/conf/lo/accept_local\", O_RDONLY));\n- FileDescriptor routeLocalnet = ASSERT_NO_ERRNO_AND_VALUE(\n- Open(\"/proc/sys/net/ipv4/conf/lo/route_localnet\", O_RDONLY));\n- char enabled;\n- ASSERT_THAT(read(acceptLocal.get(), &enabled, 1),\n- SyscallSucceedsWithValue(1));\n- ASSERT_EQ(enabled, '1');\n- ASSERT_THAT(read(routeLocalnet.get(), &enabled, 1),\n- SyscallSucceedsWithValue(1));\n- ASSERT_EQ(enabled, '1');\n- }\n-\nASSERT_THAT(socket_ = socket(AF_PACKET, SOCK_DGRAM, htons(GetParam())),\nSyscallSucceeds());\n+\n+ restore_config_ = ASSERT_NO_ERRNO_AND_VALUE(AllowMartianPacketsOnLoopback());\n}\nvoid CookedPacketTest::TearDown() {\n+ if (restore_config_) {\n+ EXPECT_NO_ERRNO(restore_config_());\n+ }\n+\n// TearDown will be run even if we skip the test.\nif (ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability())) {\nEXPECT_THAT(close(socket_), SyscallSucceeds());\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/packet_socket_raw.cc",
"new_path": "test/syscalls/linux/packet_socket_raw.cc",
"diff": "#include <sys/types.h>\n#include <unistd.h>\n+#include <functional>\n+\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n#include \"absl/base/internal/endian.h\"\n@@ -96,6 +98,9 @@ class RawPacketTest : public ::testing::TestWithParam<int> {\n// The socket used for both reading and writing.\nint s_;\n+\n+ // The function to restore the original system configuration.\n+ std::function<PosixError()> restore_config_;\n};\nvoid RawPacketTest::SetUp() {\n@@ -105,49 +110,17 @@ void RawPacketTest::SetUp() {\nGTEST_SKIP();\n}\n- if (!IsRunningOnGvisor()) {\n- // Ensure that looped back packets aren't rejected by the kernel.\n- FileDescriptor acceptLocal = ASSERT_NO_ERRNO_AND_VALUE(\n- Open(\"/proc/sys/net/ipv4/conf/lo/accept_local\", O_RDWR));\n- FileDescriptor routeLocalnet = ASSERT_NO_ERRNO_AND_VALUE(\n- Open(\"/proc/sys/net/ipv4/conf/lo/route_localnet\", O_RDWR));\n- char enabled;\n- ASSERT_THAT(read(acceptLocal.get(), &enabled, 1),\n- SyscallSucceedsWithValue(1));\n- if (enabled != '1') {\n- enabled = '1';\n- ASSERT_THAT(lseek(acceptLocal.get(), 0, SEEK_SET),\n- SyscallSucceedsWithValue(0));\n- ASSERT_THAT(write(acceptLocal.get(), &enabled, 1),\n- SyscallSucceedsWithValue(1));\n- ASSERT_THAT(lseek(acceptLocal.get(), 0, SEEK_SET),\n- SyscallSucceedsWithValue(0));\n- ASSERT_THAT(read(acceptLocal.get(), &enabled, 1),\n- SyscallSucceedsWithValue(1));\n- ASSERT_EQ(enabled, '1');\n- }\n-\n- ASSERT_THAT(read(routeLocalnet.get(), &enabled, 1),\n- SyscallSucceedsWithValue(1));\n- if (enabled != '1') {\n- enabled = '1';\n- ASSERT_THAT(lseek(routeLocalnet.get(), 0, SEEK_SET),\n- SyscallSucceedsWithValue(0));\n- ASSERT_THAT(write(routeLocalnet.get(), &enabled, 1),\n- SyscallSucceedsWithValue(1));\n- ASSERT_THAT(lseek(routeLocalnet.get(), 0, SEEK_SET),\n- SyscallSucceedsWithValue(0));\n- ASSERT_THAT(read(routeLocalnet.get(), &enabled, 1),\n- SyscallSucceedsWithValue(1));\n- ASSERT_EQ(enabled, '1');\n- }\n- }\n-\nASSERT_THAT(s_ = socket(AF_PACKET, SOCK_RAW, htons(GetParam())),\nSyscallSucceeds());\n+\n+ restore_config_ = ASSERT_NO_ERRNO_AND_VALUE(AllowMartianPacketsOnLoopback());\n}\nvoid RawPacketTest::TearDown() {\n+ if (restore_config_) {\n+ EXPECT_NO_ERRNO(restore_config_());\n+ }\n+\n// TearDown will be run even if we skip the test.\nif (ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability())) {\nEXPECT_THAT(close(s_), SyscallSucceeds());\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/socket_util.cc",
"new_path": "test/util/socket_util.cc",
"diff": "#include <poll.h>\n#include <sys/socket.h>\n+#include <functional>\n#include <memory>\n+#include <stack>\n#include \"gtest/gtest.h\"\n#include \"absl/memory/memory.h\"\n@@ -1125,5 +1127,54 @@ PosixErrorOr<int> MaybeLimitEphemeralPorts() {\nreturn max - min;\n}\n+PosixErrorOr<std::function<PosixError()>> AllowMartianPacketsOnLoopback() {\n+ if (IsRunningOnGvisor()) {\n+ return std::function<PosixError()>([]() { return NoError(); });\n+ }\n+\n+ constexpr std::array<const char*, 2> files = {\n+ \"/proc/sys/net/ipv4/conf/lo/accept_local\",\n+ \"/proc/sys/net/ipv4/conf/lo/route_localnet\",\n+ };\n+ std::stack<std::pair<const char*, char>> initial_configs;\n+\n+ // Record and update the initial configurations.\n+ PosixError err = [&]() -> PosixError {\n+ for (const char* f : files) {\n+ ASSIGN_OR_RETURN_ERRNO(FileDescriptor fd, Open(f, O_RDWR));\n+ char initial_config;\n+ RETURN_ERROR_IF_SYSCALL_FAIL(\n+ read(fd.get(), &initial_config, sizeof(initial_config)));\n+\n+ constexpr char kEnabled = '1';\n+ RETURN_ERROR_IF_SYSCALL_FAIL(lseek(fd.get(), 0, SEEK_SET));\n+ RETURN_ERROR_IF_SYSCALL_FAIL(\n+ write(fd.get(), &kEnabled, sizeof(kEnabled)));\n+ initial_configs.push(std::make_pair(f, initial_config));\n+ }\n+ return NoError();\n+ }();\n+\n+ // Only define the restore function after we're done updating the config to\n+ // capture the initialized initial_configs std::stack.\n+ std::function<PosixError()> restore = [initial_configs]() mutable {\n+ while (!initial_configs.empty()) {\n+ std::pair<const char*, char> cfg = initial_configs.top();\n+ initial_configs.pop();\n+ ASSIGN_OR_RETURN_ERRNO(FileDescriptor fd, Open(cfg.first, O_WRONLY));\n+ RETURN_ERROR_IF_SYSCALL_FAIL(\n+ write(fd.get(), &cfg.second, sizeof(cfg.second)));\n+ }\n+ return NoError();\n+ };\n+\n+ if (!err.ok()) {\n+ restore().IgnoreError();\n+ return err;\n+ }\n+\n+ return restore;\n+}\n+\n} // namespace testing\n} // namespace gvisor\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/socket_util.h",
"new_path": "test/util/socket_util.h",
"diff": "@@ -592,6 +592,10 @@ void SetupTimeWaitClose(const TestAddress* listener,\n// returns the number of ephemeral ports.\nPosixErrorOr<int> MaybeLimitEphemeralPorts();\n+// AllowMartianPacketsOnLoopback tells the kernel to not drop martian packets,\n+// and returns a function to restore the original configuration.\n+PosixErrorOr<std::function<PosixError()>> AllowMartianPacketsOnLoopback();\n+\nnamespace internal {\nPosixErrorOr<int> TryPortAvailable(int port, AddressFamily family,\nSocketType type, bool reuse_addr);\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow martian packets on packet socket dgram tests
Before this change, this test fixture expected it to be enabled already
instead of updating the config.
The Teardown method also restore the initial configuration, so that
these tests do not permanently change the config of the machines that
run the tests.
PiperOrigin-RevId: 447814273 |
259,992 | 10.05.2022 17:06:14 | 25,200 | f62143f31fe5596241a844aead15aefe9db9c816 | Ensure that errors from the shim are properly translated
Golang wrapped errors are lost when they go through gRPC. Every
error returned from `task.TaskService` interface should be
translated using `errdefs.ToGRPC`.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/shim/proc/BUILD",
"new_path": "pkg/shim/proc/BUILD",
"diff": "@@ -23,7 +23,6 @@ go_library(\n\"//pkg/atomicbitops\",\n\"//pkg/cleanup\",\n\"//pkg/shim/runsc\",\n- \"//pkg/shim/utils\",\n\"@com_github_containerd_console//:go_default_library\",\n\"@com_github_containerd_containerd//errdefs:go_default_library\",\n\"@com_github_containerd_containerd//log:go_default_library\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/shim/proc/init_state.go",
"new_path": "pkg/shim/proc/init_state.go",
"diff": "@@ -23,7 +23,6 @@ import (\n\"github.com/containerd/containerd/pkg/process\"\nrunc \"github.com/containerd/go-runc\"\n\"golang.org/x/sys/unix\"\n- \"gvisor.dev/gvisor/pkg/shim/utils\"\n)\ntype stateTransition int\n@@ -236,6 +235,6 @@ func handleStoppedKill(signal uint32) error {\n// already been killed.\nreturn nil\ndefault:\n- return utils.ErrToGRPCf(errdefs.ErrNotFound, \"process not found\")\n+ return errdefs.ToGRPCf(errdefs.ErrNotFound, \"process not found\")\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/shim/service.go",
"new_path": "pkg/shim/service.go",
"diff": "@@ -69,8 +69,6 @@ var (\n}\n)\n-var _ = (taskAPI.TaskService)(&service{})\n-\nconst (\n// configFile is the default config file name. For containerd 1.2,\n// we assume that a config.toml should exist in the runtime root.\n@@ -189,6 +187,8 @@ type service struct {\nshimAddress string\n}\n+var _ shim.Shim = (*service)(nil)\n+\nfunc (s *service) newCommand(ctx context.Context, containerdBinary, containerdAddress string) (*exec.Cmd, error) {\nns, err := namespaces.NamespaceRequired(ctx)\nif err != nil {\n@@ -323,6 +323,11 @@ func (s *service) Cleanup(ctx context.Context) (*taskAPI.DeleteResponse, error)\n// Create creates a new initial process and container with the underlying OCI\n// runtime.\nfunc (s *service) Create(ctx context.Context, r *taskAPI.CreateTaskRequest) (*taskAPI.CreateTaskResponse, error) {\n+ resp, err := s.create(ctx, r)\n+ return resp, errdefs.ToGRPC(err)\n+}\n+\n+func (s *service) create(ctx context.Context, r *taskAPI.CreateTaskRequest) (*taskAPI.CreateTaskResponse, error) {\ns.mu.Lock()\ndefer s.mu.Unlock()\n@@ -481,10 +486,10 @@ func (s *service) Create(ctx context.Context, r *taskAPI.CreateTaskRequest) (*ta\n}\nprocess, err := newInit(r.Bundle, filepath.Join(r.Bundle, \"work\"), ns, s.platform, config, &s.opts, st.Rootfs)\nif err != nil {\n- return nil, utils.ErrToGRPC(err)\n+ return nil, err\n}\nif err := process.Create(ctx, config); err != nil {\n- return nil, utils.ErrToGRPC(err)\n+ return nil, err\n}\n// Set up OOM notification on the sandbox's cgroup. This is done on\n@@ -522,6 +527,11 @@ func (s *service) Create(ctx context.Context, r *taskAPI.CreateTaskRequest) (*ta\n// Start starts a process.\nfunc (s *service) Start(ctx context.Context, r *taskAPI.StartRequest) (*taskAPI.StartResponse, error) {\n+ resp, err := s.start(ctx, r)\n+ return resp, errdefs.ToGRPC(err)\n+}\n+\n+func (s *service) start(ctx context.Context, r *taskAPI.StartRequest) (*taskAPI.StartResponse, error) {\nlog.L.Debugf(\"Start, id: %s, execID: %s\", r.ID, r.ExecID)\np, err := s.getProcess(r.ExecID)\n@@ -540,6 +550,11 @@ func (s *service) Start(ctx context.Context, r *taskAPI.StartRequest) (*taskAPI.\n// Delete deletes the initial process and container.\nfunc (s *service) Delete(ctx context.Context, r *taskAPI.DeleteRequest) (*taskAPI.DeleteResponse, error) {\n+ resp, err := s.delete(ctx, r)\n+ return resp, errdefs.ToGRPC(err)\n+}\n+\n+func (s *service) delete(ctx context.Context, r *taskAPI.DeleteRequest) (*taskAPI.DeleteResponse, error) {\nlog.L.Debugf(\"Delete, id: %s, execID: %s\", r.ID, r.ExecID)\np, err := s.getProcess(r.ExecID)\n@@ -565,16 +580,21 @@ func (s *service) Delete(ctx context.Context, r *taskAPI.DeleteRequest) (*taskAP\n// Exec spawns an additional process inside the container.\nfunc (s *service) Exec(ctx context.Context, r *taskAPI.ExecProcessRequest) (*types.Empty, error) {\n+ resp, err := s.exec(ctx, r)\n+ return resp, errdefs.ToGRPC(err)\n+}\n+\n+func (s *service) exec(ctx context.Context, r *taskAPI.ExecProcessRequest) (*types.Empty, error) {\nlog.L.Debugf(\"Exec, id: %s, execID: %s\", r.ID, r.ExecID)\ns.mu.Lock()\np := s.processes[r.ExecID]\ns.mu.Unlock()\nif p != nil {\n- return nil, utils.ErrToGRPCf(errdefs.ErrAlreadyExists, \"id %s\", r.ExecID)\n+ return nil, errdefs.ToGRPCf(errdefs.ErrAlreadyExists, \"id %s\", r.ExecID)\n}\nif s.task == nil {\n- return nil, utils.ErrToGRPCf(errdefs.ErrFailedPrecondition, \"container must be created\")\n+ return nil, errdefs.ToGRPCf(errdefs.ErrFailedPrecondition, \"container must be created\")\n}\nprocess, err := s.task.Exec(ctx, s.bundle, &proc.ExecConfig{\nID: r.ExecID,\n@@ -585,7 +605,7 @@ func (s *service) Exec(ctx context.Context, r *taskAPI.ExecProcessRequest) (*typ\nSpec: r.Spec,\n})\nif err != nil {\n- return nil, utils.ErrToGRPC(err)\n+ return nil, err\n}\ns.mu.Lock()\ns.processes[r.ExecID] = process\n@@ -595,6 +615,11 @@ func (s *service) Exec(ctx context.Context, r *taskAPI.ExecProcessRequest) (*typ\n// ResizePty resizes the terminal of a process.\nfunc (s *service) ResizePty(ctx context.Context, r *taskAPI.ResizePtyRequest) (*types.Empty, error) {\n+ resp, err := s.resizePty(ctx, r)\n+ return resp, errdefs.ToGRPC(err)\n+}\n+\n+func (s *service) resizePty(ctx context.Context, r *taskAPI.ResizePtyRequest) (*types.Empty, error) {\nlog.L.Debugf(\"ResizePty, id: %s, execID: %s, dimension: %dx%d\", r.ID, r.ExecID, r.Height, r.Width)\np, err := s.getProcess(r.ExecID)\n@@ -606,13 +631,18 @@ func (s *service) ResizePty(ctx context.Context, r *taskAPI.ResizePtyRequest) (*\nHeight: uint16(r.Height),\n}\nif err := p.Resize(ws); err != nil {\n- return nil, utils.ErrToGRPC(err)\n+ return nil, err\n}\nreturn empty, nil\n}\n// State returns runtime state information for a process.\nfunc (s *service) State(ctx context.Context, r *taskAPI.StateRequest) (*taskAPI.StateResponse, error) {\n+ resp, err := s.state(ctx, r)\n+ return resp, errdefs.ToGRPC(err)\n+}\n+\n+func (s *service) state(ctx context.Context, r *taskAPI.StateRequest) (*taskAPI.StateResponse, error) {\nlog.L.Debugf(\"State, id: %s, execID: %s\", r.ID, r.ExecID)\np, err := s.getProcess(r.ExecID)\n@@ -653,10 +683,15 @@ func (s *service) State(ctx context.Context, r *taskAPI.StateRequest) (*taskAPI.\n// Pause the container.\nfunc (s *service) Pause(ctx context.Context, r *taskAPI.PauseRequest) (*types.Empty, error) {\n+ resp, err := s.pause(ctx, r)\n+ return resp, errdefs.ToGRPC(err)\n+}\n+\n+func (s *service) pause(ctx context.Context, r *taskAPI.PauseRequest) (*types.Empty, error) {\nlog.L.Debugf(\"Pause, id: %s\", r.ID)\nif s.task == nil {\nlog.L.Debugf(\"Pause error, id: %s: container not created\", r.ID)\n- return nil, utils.ErrToGRPCf(errdefs.ErrFailedPrecondition, \"container must be created\")\n+ return nil, errdefs.ToGRPCf(errdefs.ErrFailedPrecondition, \"container must be created\")\n}\nerr := s.task.Runtime().Pause(ctx, r.ID)\nif err != nil {\n@@ -667,10 +702,15 @@ func (s *service) Pause(ctx context.Context, r *taskAPI.PauseRequest) (*types.Em\n// Resume the container.\nfunc (s *service) Resume(ctx context.Context, r *taskAPI.ResumeRequest) (*types.Empty, error) {\n+ resp, err := s.resume(ctx, r)\n+ return resp, errdefs.ToGRPC(err)\n+}\n+\n+func (s *service) resume(ctx context.Context, r *taskAPI.ResumeRequest) (*types.Empty, error) {\nlog.L.Debugf(\"Resume, id: %s\", r.ID)\nif s.task == nil {\nlog.L.Debugf(\"Resume error, id: %s: container not created\", r.ID)\n- return nil, utils.ErrToGRPCf(errdefs.ErrFailedPrecondition, \"container must be created\")\n+ return nil, errdefs.ToGRPCf(errdefs.ErrFailedPrecondition, \"container must be created\")\n}\nerr := s.task.Runtime().Resume(ctx, r.ID)\nif err != nil {\n@@ -681,6 +721,11 @@ func (s *service) Resume(ctx context.Context, r *taskAPI.ResumeRequest) (*types.\n// Kill a process with the provided signal.\nfunc (s *service) Kill(ctx context.Context, r *taskAPI.KillRequest) (*types.Empty, error) {\n+ resp, err := s.kill(ctx, r)\n+ return resp, errdefs.ToGRPC(err)\n+}\n+\n+func (s *service) kill(ctx context.Context, r *taskAPI.KillRequest) (*types.Empty, error) {\nlog.L.Debugf(\"Kill, id: %s, execID: %s, signal: %d, all: %t\", r.ID, r.ExecID, r.Signal, r.All)\np, err := s.getProcess(r.ExecID)\n@@ -689,7 +734,7 @@ func (s *service) Kill(ctx context.Context, r *taskAPI.KillRequest) (*types.Empt\n}\nif err := p.Kill(ctx, r.Signal, r.All); err != nil {\nlog.L.Debugf(\"Kill failed: %v\", err)\n- return nil, utils.ErrToGRPC(err)\n+ return nil, err\n}\nlog.L.Debugf(\"Kill succeeded\")\nreturn empty, nil\n@@ -697,11 +742,16 @@ func (s *service) Kill(ctx context.Context, r *taskAPI.KillRequest) (*types.Empt\n// Pids returns all pids inside the container.\nfunc (s *service) Pids(ctx context.Context, r *taskAPI.PidsRequest) (*taskAPI.PidsResponse, error) {\n+ resp, err := s.pids(ctx, r)\n+ return resp, errdefs.ToGRPC(err)\n+}\n+\n+func (s *service) pids(ctx context.Context, r *taskAPI.PidsRequest) (*taskAPI.PidsResponse, error) {\nlog.L.Debugf(\"Pids, id: %s\", r.ID)\npids, err := s.getContainerPids(ctx, r.ID)\nif err != nil {\n- return nil, utils.ErrToGRPC(err)\n+ return nil, err\n}\nvar processes []*task.ProcessInfo\nfor _, pid := range pids {\n@@ -730,6 +780,11 @@ func (s *service) Pids(ctx context.Context, r *taskAPI.PidsRequest) (*taskAPI.Pi\n// CloseIO closes the I/O context of a process.\nfunc (s *service) CloseIO(ctx context.Context, r *taskAPI.CloseIORequest) (*types.Empty, error) {\n+ resp, err := s.closeIO(ctx, r)\n+ return resp, errdefs.ToGRPC(err)\n+}\n+\n+func (s *service) closeIO(ctx context.Context, r *taskAPI.CloseIORequest) (*types.Empty, error) {\nlog.L.Debugf(\"CloseIO, id: %s, execID: %s, stdin: %t\", r.ID, r.ExecID, r.Stdin)\np, err := s.getProcess(r.ExecID)\n@@ -747,11 +802,16 @@ func (s *service) CloseIO(ctx context.Context, r *taskAPI.CloseIORequest) (*type\n// Checkpoint checkpoints the container.\nfunc (s *service) Checkpoint(ctx context.Context, r *taskAPI.CheckpointTaskRequest) (*types.Empty, error) {\nlog.L.Debugf(\"Checkpoint, id: %s\", r.ID)\n- return empty, utils.ErrToGRPC(errdefs.ErrNotImplemented)\n+ return empty, errdefs.ToGRPC(errdefs.ErrNotImplemented)\n}\n// Connect returns shim information such as the shim's pid.\nfunc (s *service) Connect(ctx context.Context, r *taskAPI.ConnectRequest) (*taskAPI.ConnectResponse, error) {\n+ resp, err := s.connect(ctx, r)\n+ return resp, errdefs.ToGRPC(err)\n+}\n+\n+func (s *service) connect(ctx context.Context, r *taskAPI.ConnectRequest) (*taskAPI.ConnectResponse, error) {\nlog.L.Debugf(\"Connect, id: %s\", r.ID)\nvar pid int\n@@ -765,6 +825,11 @@ func (s *service) Connect(ctx context.Context, r *taskAPI.ConnectRequest) (*task\n}\nfunc (s *service) Shutdown(ctx context.Context, r *taskAPI.ShutdownRequest) (*types.Empty, error) {\n+ resp, err := s.shutdown(ctx, r)\n+ return resp, errdefs.ToGRPC(err)\n+}\n+\n+func (s *service) shutdown(ctx context.Context, r *taskAPI.ShutdownRequest) (*types.Empty, error) {\nlog.L.Debugf(\"Shutdown, id: %s\", r.ID)\ns.cancel()\nif s.shimAddress != \"\" {\n@@ -775,10 +840,15 @@ func (s *service) Shutdown(ctx context.Context, r *taskAPI.ShutdownRequest) (*ty\n}\nfunc (s *service) Stats(ctx context.Context, r *taskAPI.StatsRequest) (*taskAPI.StatsResponse, error) {\n+ resp, err := s.stats(ctx, r)\n+ return resp, errdefs.ToGRPC(err)\n+}\n+\n+func (s *service) stats(ctx context.Context, r *taskAPI.StatsRequest) (*taskAPI.StatsResponse, error) {\nlog.L.Debugf(\"Stats, id: %s\", r.ID)\nif s.task == nil {\nlog.L.Debugf(\"Stats error, id: %s: container not created\", r.ID)\n- return nil, utils.ErrToGRPCf(errdefs.ErrFailedPrecondition, \"container must be created\")\n+ return nil, errdefs.ToGRPCf(errdefs.ErrFailedPrecondition, \"container must be created\")\n}\nstats, err := s.task.Stats(ctx, s.id)\nif err != nil {\n@@ -852,11 +922,16 @@ func (s *service) Stats(ctx context.Context, r *taskAPI.StatsRequest) (*taskAPI.\n// Update updates a running container.\nfunc (s *service) Update(ctx context.Context, r *taskAPI.UpdateTaskRequest) (*types.Empty, error) {\n- return empty, utils.ErrToGRPC(errdefs.ErrNotImplemented)\n+ return empty, errdefs.ToGRPC(errdefs.ErrNotImplemented)\n}\n// Wait waits for a process to exit.\nfunc (s *service) Wait(ctx context.Context, r *taskAPI.WaitRequest) (*taskAPI.WaitResponse, error) {\n+ resp, err := s.wait(ctx, r)\n+ return resp, errdefs.ToGRPC(err)\n+}\n+\n+func (s *service) wait(ctx context.Context, r *taskAPI.WaitRequest) (*taskAPI.WaitResponse, error) {\nlog.L.Debugf(\"Wait, id: %s, execID: %s\", r.ID, r.ExecID)\np, err := s.getProcess(r.ExecID)\n@@ -949,14 +1024,14 @@ func (s *service) getProcess(execID string) (process.Process, error) {\nif execID == \"\" {\nif s.task == nil {\n- return nil, utils.ErrToGRPCf(errdefs.ErrFailedPrecondition, \"container must be created\")\n+ return nil, errdefs.ToGRPCf(errdefs.ErrFailedPrecondition, \"container must be created\")\n}\nreturn s.task, nil\n}\np := s.processes[execID]\nif p == nil {\n- return nil, utils.ErrToGRPCf(errdefs.ErrNotFound, \"process does not exist %s\", execID)\n+ return nil, errdefs.ToGRPCf(errdefs.ErrNotFound, \"process does not exist %s\", execID)\n}\nreturn p, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/shim/utils/BUILD",
"new_path": "pkg/shim/utils/BUILD",
"diff": "@@ -6,7 +6,6 @@ go_library(\nname = \"utils\",\nsrcs = [\n\"annotations.go\",\n- \"errors.go\",\n\"utils.go\",\n\"volumes.go\",\n],\n@@ -14,24 +13,13 @@ go_library(\n\"//pkg/shim:__subpackages__\",\n\"//shim:__subpackages__\",\n],\n- deps = [\n- \"@com_github_containerd_containerd//errdefs:go_default_library\",\n- \"@com_github_opencontainers_runtime_spec//specs-go:go_default_library\",\n- \"@org_golang_google_grpc//codes:go_default_library\",\n- \"@org_golang_google_grpc//status:go_default_library\",\n- ],\n+ deps = [\"@com_github_opencontainers_runtime_spec//specs-go:go_default_library\"],\n)\ngo_test(\nname = \"utils_test\",\nsize = \"small\",\n- srcs = [\n- \"errors_test.go\",\n- \"volumes_test.go\",\n- ],\n+ srcs = [\"volumes_test.go\"],\nlibrary = \":utils\",\n- deps = [\n- \"@com_github_containerd_containerd//errdefs:go_default_library\",\n- \"@com_github_opencontainers_runtime_spec//specs-go:go_default_library\",\n- ],\n+ deps = [\"@com_github_opencontainers_runtime_spec//specs-go:go_default_library\"],\n)\n"
},
{
"change_type": "DELETE",
"old_path": "pkg/shim/utils/errors.go",
"new_path": null,
"diff": "-// Copyright 2021 The gVisor Authors.\n-//\n-// Licensed under the Apache License, Version 2.0 (the \"License\");\n-// you may not use this file except in compliance with the License.\n-// You may obtain a copy of the License at\n-//\n-// https://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 utils\n-\n-import (\n- \"context\"\n- \"errors\"\n- \"fmt\"\n-\n- \"github.com/containerd/containerd/errdefs\"\n- \"google.golang.org/grpc/codes\"\n- \"google.golang.org/grpc/status\"\n-)\n-\n-// ErrToGRPC wraps containerd's ToGRPC error mapper which depends on\n-// github.com/pkg/errors to work correctly. Once we upgrade to containerd v1.4,\n-// this function can go away and we can use errdefs.ToGRPC directly instead.\n-//\n-// TODO(gvisor.dev/issue/6232): Remove after upgrading to containerd v1.4\n-func ErrToGRPC(err error) error {\n- return errToGRPCMsg(err, err.Error())\n-}\n-\n-// ErrToGRPCf maps the error to grpc error codes, assembling the formatting\n-// string and combining it with the target error string.\n-//\n-// TODO(gvisor.dev/issue/6232): Remove after upgrading to containerd v1.4\n-func ErrToGRPCf(err error, format string, args ...interface{}) error {\n- formatted := fmt.Sprintf(format, args...)\n- msg := fmt.Sprintf(\"%s: %s\", formatted, err.Error())\n- return errToGRPCMsg(err, msg)\n-}\n-\n-func errToGRPCMsg(err error, msg string) error {\n- if err == nil {\n- return nil\n- }\n- if _, ok := status.FromError(err); ok {\n- return err\n- }\n-\n- switch {\n- case errors.Is(err, errdefs.ErrInvalidArgument):\n- return status.Errorf(codes.InvalidArgument, msg)\n- case errors.Is(err, errdefs.ErrNotFound):\n- return status.Errorf(codes.NotFound, msg)\n- case errors.Is(err, errdefs.ErrAlreadyExists):\n- return status.Errorf(codes.AlreadyExists, msg)\n- case errors.Is(err, errdefs.ErrFailedPrecondition):\n- return status.Errorf(codes.FailedPrecondition, msg)\n- case errors.Is(err, errdefs.ErrUnavailable):\n- return status.Errorf(codes.Unavailable, msg)\n- case errors.Is(err, errdefs.ErrNotImplemented):\n- return status.Errorf(codes.Unimplemented, msg)\n- case errors.Is(err, context.Canceled):\n- return status.Errorf(codes.Canceled, msg)\n- case errors.Is(err, context.DeadlineExceeded):\n- return status.Errorf(codes.DeadlineExceeded, msg)\n- }\n-\n- return errdefs.ToGRPC(err)\n-}\n"
},
{
"change_type": "DELETE",
"old_path": "pkg/shim/utils/errors_test.go",
"new_path": null,
"diff": "-// Copyright 2021 The gVisor Authors.\n-//\n-// Licensed under the Apache License, Version 2.0 (the \"License\");\n-// you may not use this file except in compliance with the License.\n-// You may obtain a copy of the License at\n-//\n-// https://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 utils\n-\n-import (\n- \"fmt\"\n- \"testing\"\n-\n- \"github.com/containerd/containerd/errdefs\"\n-)\n-\n-func TestGRPCRoundTripsErrors(t *testing.T) {\n- for _, tc := range []struct {\n- name string\n- err error\n- test func(err error) bool\n- }{\n- {\n- name: \"passthrough\",\n- err: errdefs.ErrNotFound,\n- test: errdefs.IsNotFound,\n- },\n- {\n- name: \"wrapped\",\n- err: fmt.Errorf(\"oh no: %w\", errdefs.ErrNotFound),\n- test: errdefs.IsNotFound,\n- },\n- } {\n- t.Run(tc.name, func(t *testing.T) {\n- if err := errdefs.FromGRPC(ErrToGRPC(tc.err)); !tc.test(err) {\n- t.Errorf(\"errToGRPC got %+v\", err)\n- }\n- if err := errdefs.FromGRPC(ErrToGRPCf(tc.err, \"testing %s\", \"123\")); !tc.test(err) {\n- t.Errorf(\"errToGRPCf got %+v\", err)\n- }\n- })\n- }\n-}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Ensure that errors from the shim are properly translated
Golang wrapped errors are lost when they go through gRPC. Every
error returned from `task.TaskService` interface should be
translated using `errdefs.ToGRPC`.
Fixes #7504
PiperOrigin-RevId: 447863123 |
259,868 | 10.05.2022 17:27:53 | 25,200 | 6af4eedc21c2f4979a16203ce74fa61f007151f1 | runsc: Support `%ID%` substitution in more path flags than just `--debug-log`.
This allows things like CPU profiles to be written out to sandbox-specific
file paths. | [
{
"change_type": "MODIFY",
"old_path": "pkg/shim/runsc/utils.go",
"new_path": "pkg/shim/runsc/utils.go",
"diff": "@@ -36,20 +36,52 @@ func putBuf(b *bytes.Buffer) {\nbytesBufferPool.Put(b)\n}\n-// FormatRunscLogPath parses runsc config, and fill in %ID% in the log path.\n-func FormatRunscLogPath(id string, config map[string]string) {\n- if path, ok := config[\"debug-log\"]; ok {\n- config[\"debug-log\"] = strings.Replace(path, \"%ID%\", id, -1)\n+// pathLikeFlags are runsc flags which refer to paths to files.\n+var pathLikeFlags = []string{\n+ \"log\",\n+ \"panic-log\",\n+ \"debug-log\",\n+ \"coverage-report\",\n+ \"profile-block\",\n+ \"profile-cpu\",\n+ \"profile-heap\",\n+ \"profile-mutex\",\n+ \"trace\",\n+}\n+\n+// replaceID replaces %ID% in `path` with the given sandbox ID.\n+func replaceID(id string, path string) string {\n+ return strings.Replace(path, \"%ID%\", id, -1)\n+}\n+\n+// EmittedPaths returns a list of file paths that the sandbox may need to\n+// create using the given configuration. Useful to create parent directories.\n+func EmittedPaths(id string, config map[string]string) []string {\n+ var paths []string\n+ for _, cfgFlag := range pathLikeFlags {\n+ if path, ok := config[cfgFlag]; ok {\n+ paths = append(paths, replaceID(id, path))\n+ }\n+ }\n+ return paths\n+}\n+\n+// FormatRunscPaths fills in %ID% in path-like flags.\n+func FormatRunscPaths(id string, config map[string]string) {\n+ for _, cfgFlag := range pathLikeFlags {\n+ if path, ok := config[cfgFlag]; ok {\n+ config[cfgFlag] = replaceID(id, path)\n+ }\n}\n}\n// FormatShimLogPath creates the file path to the log file. It replaces %ID%\n// in the path with the provided \"id\". It also uses a default log name if the\n-// path end with '/'.\n+// path ends with '/'.\nfunc FormatShimLogPath(path string, id string) string {\nif strings.HasSuffix(path, \"/\") {\n// Default format: <path>/runsc-shim-<ID>.log\npath += \"runsc-shim-%ID%.log\"\n}\n- return strings.Replace(path, \"%ID%\", id, -1)\n+ return replaceID(id, path)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/shim/service.go",
"new_path": "pkg/shim/service.go",
"diff": "@@ -401,6 +401,11 @@ func (s *service) create(ctx context.Context, r *taskAPI.CreateTaskRequest) (*ta\n}\nlogrus.SetLevel(lvl)\n}\n+ for _, emittedPath := range runsc.EmittedPaths(s.id, s.opts.RunscConfig) {\n+ if err := os.MkdirAll(filepath.Dir(emittedPath), 0777); err != nil {\n+ return nil, fmt.Errorf(\"failed to create parent directories for file %v: %w\", emittedPath, err)\n+ }\n+ }\nif len(s.opts.LogPath) != 0 {\nlogPath := runsc.FormatShimLogPath(s.opts.LogPath, s.id)\nif err := os.MkdirAll(filepath.Dir(logPath), 0777); err != nil {\n@@ -1076,7 +1081,7 @@ func newInit(path, workDir, namespace string, platform stdio.Platform, r *proc.C\n}\n}\n- runsc.FormatRunscLogPath(r.ID, options.RunscConfig)\n+ runsc.FormatRunscPaths(r.ID, options.RunscConfig)\nruntime := proc.NewRunsc(options.Root, path, namespace, options.BinaryName, options.RunscConfig)\np := proc.New(r.ID, runtime, stdio.Stdio{\nStdin: r.Stdin,\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/config/config.go",
"new_path": "runsc/config/config.go",
"diff": "@@ -178,7 +178,7 @@ type Config struct {\n// Controls defines the controls that may be enabled.\nControls controlConfig `flag:\"controls\"`\n- // RestoreFile is the path to the saved container image\n+ // RestoreFile is the path to the saved container image.\nRestoreFile string\n// NumNetworkChannels controls the number of AF_PACKET sockets that map\n"
}
] | Go | Apache License 2.0 | google/gvisor | runsc: Support `%ID%` substitution in more path flags than just `--debug-log`.
This allows things like CPU profiles to be written out to sandbox-specific
file paths.
PiperOrigin-RevId: 447867091 |
259,853 | 10.05.2022 22:14:27 | 25,200 | 3f44cd556b7fda0c56b4665959c52afc5e425d88 | sentry/socket: don't release a connected enpoint under the endpoint mutex
It isn't required and can have side effects. For example, the current endpoint
can be in an SCM message that is queued to the connected endpoint. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/transport/connectionless.go",
"new_path": "pkg/sentry/socket/unix/transport/connectionless.go",
"diff": "@@ -59,10 +59,8 @@ func (e *connectionlessEndpoint) isBound() bool {\n// with it.\nfunc (e *connectionlessEndpoint) Close(ctx context.Context) {\ne.Lock()\n- if e.connected != nil {\n- e.connected.Release(ctx)\n+ connected := e.connected\ne.connected = nil\n- }\nif e.isBound() {\ne.path = \"\"\n@@ -73,6 +71,9 @@ func (e *connectionlessEndpoint) Close(ctx context.Context) {\ne.receiver = nil\ne.Unlock()\n+ if connected != nil {\n+ connected.Release(ctx)\n+ }\nr.CloseNotify()\nr.Release(ctx)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | sentry/socket: don't release a connected enpoint under the endpoint mutex
It isn't required and can have side effects. For example, the current endpoint
can be in an SCM message that is queued to the connected endpoint.
PiperOrigin-RevId: 447906621 |
259,891 | 11.05.2022 11:04:55 | 25,200 | 9bc06340b225f78d98f3955dbd26e451a0ffab74 | Describe what iptables checkescape covers specifically | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables.go",
"new_path": "pkg/tcpip/stack/iptables.go",
"diff": "@@ -275,8 +275,11 @@ type checkTable struct {\n// specified table.\n//\n// This is called in the hot path even when iptables are disabled, so we ensure\n-// it does not allocate.\n-// +checkescape:heap,builtin\n+// it does not allocate. We check recursively for heap allocations, but not for:\n+// - Stack splitting, which can allocate.\n+// - Calls to interfaces, which can allocate.\n+// - Calls to dynamic functions, which can allocate.\n+// +checkescape:hard\nfunc (it *IPTables) shouldSkipOrPopulateTables(tables []checkTable, pkt *PacketBuffer) bool {\nswitch pkt.NetworkProtocolNumber {\ncase header.IPv4ProtocolNumber, header.IPv6ProtocolNumber:\n"
}
] | Go | Apache License 2.0 | google/gvisor | Describe what iptables checkescape covers specifically
PiperOrigin-RevId: 448037248 |
259,858 | 11.05.2022 13:49:29 | 25,200 | 74f3befece71bd5fe3262a4309cd859494fcebb1 | Convert pipeline to use common metrics publisher. | [
{
"change_type": "MODIFY",
"old_path": "images/agent/Dockerfile",
"new_path": "images/agent/Dockerfile",
"diff": "@@ -2,11 +2,6 @@ FROM golang:1.15 as build-agent\nRUN git clone --depth=1 --branch=v3.25.0 https://github.com/buildkite/agent\nRUN cd agent && go build -i -o /buildkite-agent .\n-FROM golang:1.15 as build-agent-metrics\n-RUN git clone --depth=1 --branch=v5.2.0 https://github.com/buildkite/buildkite-agent-metrics\n-RUN cd buildkite-agent-metrics && go build -i -o /buildkite-agent-metrics .\n-\nFROM gcr.io/distroless/base-debian10\nCOPY --from=build-agent /buildkite-agent /\n-COPY --from=build-agent-metrics /buildkite-agent-metrics /\nCMD [\"/buildkite-agent\"]\n"
}
] | Go | Apache License 2.0 | google/gvisor | Convert pipeline to use common metrics publisher.
PiperOrigin-RevId: 448075984 |
259,982 | 11.05.2022 18:33:34 | 25,200 | a7cad2b092de8430562886ceaa57c14c6eec7763 | Tmpfs with size option enabled bug fix.
Adding test case to check empty size parsing in Linux.
If a value is not passed with size the mount(2) should return EINVAL.
Handling empty size parsing in gVisor. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"diff": "@@ -204,7 +204,7 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\ndelete(mopts, \"size\")\nmaxSizeInBytes, err := parseSize(maxSizeStr)\nif err != nil {\n- ctx.Warningf(\"tmpfs.FilesystemType.GetFilesystem: invalid size: %q\", maxSizeStr)\n+ ctx.Debugf(\"tmpfs.FilesystemType.GetFilesystem: parseSize() failed: %v\", err)\nreturn nil, nil, linuxerr.EINVAL\n}\n// Convert size in bytes to nearest Page Size bytes\n@@ -948,6 +948,9 @@ func (*fileDescription) Sync(context.Context) error {\n// parseSize converts size in string to an integer bytes.\n// Supported suffixes in string are:K, M, G, T, P, E.\nfunc parseSize(s string) (uint64, error) {\n+ if len(s) == 0 {\n+ return 0, fmt.Errorf(\"size parameter empty\")\n+ }\nsuffix := s[len(s)-1]\ncount := 1\nswitch suffix {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/mount.cc",
"new_path": "test/syscalls/linux/mount.cc",
"diff": "@@ -614,6 +614,14 @@ TEST(MountTest, TmpfsHardLinkAllocCheck) {\nEXPECT_THAT(unlink(fileOne.c_str()), SyscallSucceeds());\n}\n+// Tests memory allocation for empty size.\n+TEST(MountTest, TmpfsEmptySizeAllocCheck) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN)));\n+ auto const dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ ASSERT_THAT(mount(\"\", dir.path().c_str(), \"tmpfs\", 0, \"size\"),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\n} // namespace\n} // namespace testing\n"
}
] | Go | Apache License 2.0 | google/gvisor | Tmpfs with size option enabled bug fix.
Adding test case to check empty size parsing in Linux.
If a value is not passed with size the mount(2) should return EINVAL.
Handling empty size parsing in gVisor.
PiperOrigin-RevId: 448132149 |
259,858 | 12.05.2022 14:39:03 | 25,200 | 47b001caef9b26d1842bce8c59e5bbc2b96052ed | Set the default queue for the pipeline. | [
{
"change_type": "MODIFY",
"old_path": ".buildkite/pipeline.yaml",
"new_path": ".buildkite/pipeline.yaml",
"diff": "@@ -20,6 +20,9 @@ _templates:\nBENCHMARKS_PROJECT: gvisor-benchmarks\nBENCHMARKS_TABLE: benchmarks\nBENCHMARKS_UPLOAD: true\n+ agents:\n+ arch: \"amd64\"\n+ kvm: \"true\"\nnetstack_test: &netstack_test\nenv:\nPACKAGES: >\n@@ -39,8 +42,16 @@ _templates:\nsteps:\n# Run basic smoke tests before preceding to other tests.\n- <<: *common\n- label: \":fire: Smoke tests\"\n+ label: \":fire: Smoke tests (AMD64)\"\ncommand: make smoke-tests\n+ agents:\n+ arch: \"amd64\"\n+ - <<: *common\n+ label: \":fire: Smoke tests (ARM64)\"\n+ command: make smoke-tests\n+ agents:\n+ arch: \"arm64\"\n+\n- wait\n- <<: *common\nlabel: \":fire: Smoke race tests\"\n@@ -105,92 +116,137 @@ steps:\n- <<: *common\nlabel: \":docker: Images (x86_64)\"\ncommand: make ARCH=x86_64 load-all-images\n+ agents:\n+ arch: \"amd64\"\n- <<: *common\nlabel: \":docker: Images (aarch64)\"\ncommand: make ARCH=aarch64 load-all-images\n+ agents:\n+ arch: \"amd64\"\n# Basic unit tests.\n- <<: *common\nlabel: \":golang: Nogo tests\"\ncommand: make nogo-tests\n- <<: *common\n- label: \":test_tube: Unit tests\"\n+ label: \":test_tube: Unit tests (cgroupv1)\"\ncommand: make unit-tests\n+ agents:\n+ cgroup: \"v1\"\n+ arch: \"amd64\"\n- <<: *common\nlabel: \":test_tube: Unit tests (cgroupv2)\"\ncommand: make unit-tests\nagents:\n- queue: \"cgroupv2\"\n+ cgroup: \"v2\"\n+ arch: \"amd64\"\n- <<: *common\n- label: \":test_tube: Container tests\"\n+ label: \":test_tube: Container tests (cgroupv1)\"\ncommand: make container-tests\n+ agents:\n+ cgroup: \"v1\"\n+ kvm: \"true\"\n+ arch: \"amd64\"\n- <<: *common\nlabel: \":test_tube: Container tests (cgroupv2)\"\ncommand: make container-tests\nagents:\n- queue: \"cgroupv2\"\n+ cgroup: \"v2\"\n+ kvm: \"true\"\n+ arch: \"amd64\"\n# All system call tests.\n- <<: *common\n- label: \":toolbox: System call tests\"\n+ label: \":toolbox: System call tests (AMD64)\"\ncommand: make syscall-tests\nparallelism: 20\n+ agents:\n+ arch: \"amd64\"\n+ kvm: \"true\"\n- <<: *common\nlabel: \":muscle: System call tests (ARM64)\"\ncommand: make BAZEL_OPTIONS=--test_tag_filters=runsc_ptrace syscall-tests\nparallelism: 10\nagents:\n- queue: \"arm64\"\n+ arch: \"arm64\"\n# Integration tests.\n- <<: *common\n- label: \":docker: Docker tests\"\n+ label: \":docker: Docker tests (cgroupv1)\"\ncommand: make docker-tests\n+ agents:\n+ arch: \"amd64\"\n+ cgroup: \"v1\"\n- <<: *common\nlabel: \":docker: Docker tests (cgroupv2)\"\ncommand: make docker-tests\nagents:\n- queue: \"cgroupv2\"\n+ arch: \"amd64\"\n+ cgroup: \"v2\"\n- <<: *common\nlabel: \":goggles: Overlay tests\"\ncommand: make overlay-tests\n+ agents:\n+ arch: \"amd64\"\n- <<: *common\nlabel: \":safety_pin: Host network tests\"\ncommand: make hostnet-tests\n+ agents:\n+ arch: \"amd64\"\n- <<: *common\nlabel: \":satellite: SWGSO tests\"\ncommand: make swgso-tests\n+ agents:\n+ arch: \"amd64\"\n- <<: *common\nlabel: \":coffee: Do tests\"\ncommand: make do-tests\n+ agents:\n+ arch: \"amd64\"\n- <<: *common\nlabel: \":person_in_lotus_position: KVM tests\"\ncommand: make kvm-tests\n+ agents:\n+ arch: \"amd64\"\n- <<: *common\nlabel: \":weight_lifter: Fsstress test\"\ncommand: make fsstress-test\n+ agents:\n+ arch: \"amd64\"\n- <<: *common\nlabel: \":docker: Containerd 1.3.9 tests\"\ncommand: make containerd-test-1.3.9\n+ agents:\n+ arch: \"amd64\"\n- <<: *common\nlabel: \":docker: Containerd 1.4.3 tests\"\ncommand: make containerd-test-1.4.3\n+ agents:\n+ arch: \"amd64\"\n- <<: *common\n- label: \":docker: Containerd 1.5.4 tests\"\n+ label: \":docker: Containerd 1.5.4 tests (cgroupv1)\"\ncommand: make containerd-test-1.5.4\n+ agents:\n+ cgroup: \"v1\"\n+ arch: \"amd64\"\n- <<: *common\nlabel: \":docker: Containerd 1.5.4 tests (cgroupv2)\"\ncommand: make containerd-test-1.5.4\nagents:\n- queue: \"cgroupv2\"\n+ cgroup: \"v2\"\n+ arch: \"amd64\"\n- <<: *common\n- label: \":docker: Containerd 1.6.0-rc.4 tests\"\n+ label: \":docker: Containerd 1.6.0-rc.4 tests (cgroupv1)\"\ncommand: make containerd-test-1.6.0-rc.4\n+ agents:\n+ cgroup: \"v1\"\n+ arch: \"amd64\"\n- <<: *common\nlabel: \":docker: Containerd 1.6.0-rc.4 tests (cgroupv2)\"\ncommand: make containerd-test-1.6.0-rc.4\nagents:\n- queue: \"cgroupv2\"\n+ cgroup: \"v2\"\n+ arch: \"amd64\"\n# Check the website builds.\n- <<: *common\n@@ -213,22 +269,32 @@ steps:\nlabel: \":php: PHP runtime tests\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} php8.1.1-runtime-tests\nparallelism: 10\n+ agents:\n+ arch: \"amd64\"\n- <<: *common\nlabel: \":java: Java runtime tests\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} java17-runtime-tests\nparallelism: 40\n+ agents:\n+ arch: \"amd64\"\n- <<: *common\nlabel: \":golang: Go runtime tests\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} go1.16-runtime-tests\nparallelism: 10\n+ agents:\n+ arch: \"amd64\"\n- <<: *common\nlabel: \":node: NodeJS runtime tests\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} nodejs16.13.2-runtime-tests\nparallelism: 10\n+ agents:\n+ arch: \"amd64\"\n- <<: *common\nlabel: \":python: Python runtime tests\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} python3.10.2-runtime-tests\nparallelism: 10\n+ agents:\n+ arch: \"amd64\"\n# Runtime tests (LISAFS).\n- <<: *common\n@@ -236,36 +302,43 @@ steps:\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} php8.1.1-runtime-tests_lisafs\nparallelism: 10\nif: build.message =~ /lisafs/ || build.branch == \"master\"\n+ agents:\n+ arch: \"amd64\"\n- <<: *common\nlabel: \":java: Java runtime tests (LISAFS)\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} java17-runtime-tests_lisafs\nparallelism: 40\nif: build.message =~ /lisafs/ || build.branch == \"master\"\n+ agents:\n+ arch: \"amd64\"\n- <<: *common\nlabel: \":golang: Go runtime tests (LISAFS)\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} go1.16-runtime-tests_lisafs\nparallelism: 10\nif: build.message =~ /lisafs/ || build.branch == \"master\"\n+ agents:\n+ arch: \"amd64\"\n- <<: *common\nlabel: \":node: NodeJS runtime tests (LISAFS)\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} nodejs16.13.2-runtime-tests_lisafs\nparallelism: 10\nif: build.message =~ /lisafs/ || build.branch == \"master\"\n+ agents:\n+ arch: \"amd64\"\n- <<: *common\nlabel: \":python: Python runtime tests (LISAFS)\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} python3.10.2-runtime-tests_lisafs\nparallelism: 10\nif: build.message =~ /lisafs/ || build.branch == \"master\"\n-\n- # ARM tests.\n- - <<: *common\n- label: \":mechanical_arm: ARM\"\n- command: make arm-qemu-smoke-test\n+ agents:\n+ arch: \"amd64\"\n# Build everything.\n- <<: *common\nlabel: \":world_map: Build everything\"\ncommand: \"make build OPTIONS=--build_tag_filters=-nogo TARGETS=//...\"\n+ agents:\n+ arch: \"amd64\"\n# Run basic benchmarks smoke tests (no upload).\n- <<: *common\n@@ -273,6 +346,8 @@ steps:\ncommand: make benchmark-platforms BENCHMARKS_TARGETS=test/benchmarks/base:startup_test BENCHMARKS_FILTER=BenchmarkStartupEmpty BENCHMARKS_OPTIONS=-test.benchtime=1ns\n# Use the opposite of the benchmarks filter.\nif: build.branch != \"master\"\n+ agents:\n+ arch: \"amd64\"\n# Run all benchmarks.\n- <<: *benchmarks\n"
}
] | Go | Apache License 2.0 | google/gvisor | Set the default queue for the pipeline.
PiperOrigin-RevId: 448341915 |
259,907 | 12.05.2022 15:46:17 | 25,200 | 14c5686d5058e74a2e31bc1129cb63c92eae8d0c | Add instructions on how to clean up exclude file for runtime tests. | [
{
"change_type": "MODIFY",
"old_path": "test/runtimes/README.md",
"new_path": "test/runtimes/README.md",
"diff": "@@ -79,6 +79,34 @@ To bump the version of an existing runtime test:\n[exclude](exclude) file for the new version, and they will be skipped in\nfuture runs.\n+### Cleaning up exclude files\n+\n+Usually when the runtime is updated, a lot has changed. Tests may have been\n+deleted, modified (fixed or broken) or added. After you have an exclude list\n+from step 3 above with which all runtime tests pass, it is useful to clean up\n+the exclude files with the following steps:\n+\n+1. Check for the existence of tests in the runtime image. See how each runtime\n+ lists all its tests (see `ListTests()` implementations in `proctor/lib`\n+ directory). Then you can compare against that list and remove any excluded\n+ tests that don't exist anymore.\n+2. Run all excluded tests with runc (native) for each runtime. If the test\n+ fails, we can consider the test as broken. Such tests should be marked with\n+ `Broken test` in the reason column. These tests don't provide a\n+ compatibility gap signal for gvisor. We can happily ignore them. Some tests\n+ which were previously broken may not be unbroken and for them the reason\n+ field should be cleared.\n+3. Run all the unbroken and non-flaky tests on runsc (gVisor). If the test is\n+ now passing, then the test should be removed from the exclude list. This\n+ effectively increases our testing surface. Once upon a time, this test was\n+ failing. Now it is passing. Something was fixed in between. Enabling this\n+ test is equivalent to adding a regression test for the fix.\n+4. Some tests are excluded and marked flaky. Run these tests 100 times on runsc\n+ (gVisor). If it does not flake, then you can remove it from the exclude\n+ list.\n+5. Finally, close all corresponding bugs for tests that are now passing. These\n+ bugs are stale.\n+\nCreating new runtime tests for an entirely new language is similar to the above,\nexcept that Step 1 is a bit harder. You have to figure out how to download and\nrun the language tests in a Docker container. Once you have that, you must also\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add instructions on how to clean up exclude file for runtime tests.
PiperOrigin-RevId: 448356710 |
259,985 | 12.05.2022 16:05:56 | 25,200 | 7eec8dcf9a0135f9449d6a88763b66b71910acb7 | mm: Protect mm.dumpability with atomic access instead of mm.metadataMu.
Previously, this was a lock order violation, as mm.metadataMutex ->
mm.mappingRWMutex -> kernel.taskSetRWMutex is required when forking
the task image, and ptrace aquired kernel.taskSetRWMutex ->
mm.metadataMutex to check dumpability.
Ptrace doesn't require a critical section around the use of the
dumpability value. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/lifecycle.go",
"new_path": "pkg/sentry/mm/lifecycle.go",
"diff": "@@ -36,7 +36,7 @@ func NewMemoryManager(p platform.Platform, mfp pgalloc.MemoryFileProvider, sleep\nprivateRefs: &privateRefs{},\nusers: atomicbitops.FromInt32(1),\nauxv: arch.Auxv{},\n- dumpability: UserDumpable,\n+ dumpability: atomicbitops.FromInt32(int32(UserDumpable)),\naioManager: aioManager{contexts: make(map[uint64]*AIOContext)},\nsleepForActivation: sleepForActivation,\n}\n@@ -92,7 +92,7 @@ func (mm *MemoryManager) Fork(ctx context.Context) (*MemoryManager, error) {\nauxv: append(arch.Auxv(nil), mm.auxv...),\n// IncRef'd below, once we know that there isn't an error.\nexecutable: mm.executable,\n- dumpability: mm.dumpability,\n+ dumpability: atomicbitops.FromInt32(mm.dumpability.Load()),\naioManager: aioManager{contexts: make(map[uint64]*AIOContext)},\nsleepForActivation: mm.sleepForActivation,\nvdsoSigReturnAddr: mm.vdsoSigReturnAddr,\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/metadata.go",
"new_path": "pkg/sentry/mm/metadata.go",
"diff": "@@ -39,16 +39,12 @@ const (\n// Dumpability returns the dumpability.\nfunc (mm *MemoryManager) Dumpability() Dumpability {\n- mm.metadataMu.Lock()\n- defer mm.metadataMu.Unlock()\n- return mm.dumpability\n+ return Dumpability(mm.dumpability.Load())\n}\n// SetDumpability sets the dumpability.\nfunc (mm *MemoryManager) SetDumpability(d Dumpability) {\n- mm.metadataMu.Lock()\n- defer mm.metadataMu.Unlock()\n- mm.dumpability = d\n+ mm.dumpability.Store(int32(d))\n}\n// ArgvStart returns the start of the application argument vector.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/mm.go",
"new_path": "pkg/sentry/mm/mm.go",
"diff": "@@ -193,6 +193,11 @@ type MemoryManager struct {\ncaptureInvalidations bool `state:\"zerovalue\"`\ncapturedInvalidations []invalidateArgs `state:\"nosave\"`\n+ // dumpability describes if and how this MemoryManager may be dumped to\n+ // userspace. This is read under kernel.TaskSet.mu, so it can't be protected\n+ // by metadataMu.\n+ dumpability atomicbitops.Int32\n+\nmetadataMu sync.Mutex `state:\"nosave\"`\n// argv is the application argv. This is set up by the loader and may be\n@@ -220,12 +225,6 @@ type MemoryManager struct {\n// executable is protected by metadataMu.\nexecutable fsbridge.File\n- // dumpability describes if and how this MemoryManager may be dumped to\n- // userspace.\n- //\n- // dumpability is protected by metadataMu.\n- dumpability Dumpability\n-\n// aioManager keeps track of AIOContexts used for async IOs. AIOManager\n// must be cloned when CLONE_VM is used.\naioManager aioManager\n"
}
] | Go | Apache License 2.0 | google/gvisor | mm: Protect mm.dumpability with atomic access instead of mm.metadataMu.
Previously, this was a lock order violation, as mm.metadataMutex ->
mm.mappingRWMutex -> kernel.taskSetRWMutex is required when forking
the task image, and ptrace aquired kernel.taskSetRWMutex ->
mm.metadataMutex to check dumpability.
Ptrace doesn't require a critical section around the use of the
dumpability value.
PiperOrigin-RevId: 448360804 |
259,966 | 12.05.2022 16:06:53 | 25,200 | e916e4fde31b035f7776449073a7532ec352e9e9 | Remove the MonotonicTime.Nanoseconds() accessor.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/internal/multicast/example_test.go",
"new_path": "pkg/tcpip/network/internal/multicast/example_test.go",
"diff": "@@ -103,7 +103,7 @@ func Example() {\npanic(fmt.Sprintf(\"table.GetLastUsedTimestamp(%#v) = (_, false)\", routeKey))\n}\n- fmt.Printf(\"Last used timestamp: %d\", timestamp.Nanoseconds())\n+ fmt.Printf(\"Last used timestamp: %s\", timestamp)\n// Finally, to remove an installed route, call:\nif removed := table.RemoveInstalledRoute(routeKey); !removed {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/internal/multicast/route_table_test.go",
"new_path": "pkg/tcpip/network/internal/multicast/route_table_test.go",
"diff": "@@ -452,8 +452,8 @@ func TestSetLastUsedTimestamp(t *testing.T) {\nt.Fatalf(\"got table.GetLastUsedTimestamp(%#v) = (_, false_), want = (_, true)\", defaultRouteKey)\n}\n- if got, want := timestamp.Nanoseconds(), test.wantLastUsedTime.Nanoseconds(); got != want {\n- t.Errorf(\"got table.GetLastUsedTimestamp(%#v) = (%v, _), want (%v, _)\", defaultRouteKey, got, want)\n+ if timestamp != test.wantLastUsedTime {\n+ t.Errorf(\"got table.GetLastUsedTimestamp(%#v) = (%s, _), want = (%s, _)\", defaultRouteKey, timestamp, test.wantLastUsedTime)\n}\n})\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -71,9 +71,9 @@ type MonotonicTime struct {\nnanoseconds int64\n}\n-// Nanoseconds returns the monotonic time in nanoseconds.\n-func (mt MonotonicTime) Nanoseconds() int64 {\n- return mt.nanoseconds\n+// String implements Stringer.\n+func (mt MonotonicTime) String() string {\n+ return strconv.FormatInt(mt.nanoseconds, 10)\n}\n// Before reports whether the monotonic clock reading mt is before u.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove the MonotonicTime.Nanoseconds() accessor.
Updates #7338.
PiperOrigin-RevId: 448360987 |
259,985 | 12.05.2022 16:09:27 | 25,200 | 700014c960df86707bd8ddb907eeaf210b31e208 | cgroupfs: Allow explicit "/" as initial cgroup. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/cgroupfs.go",
"new_path": "pkg/sentry/fsimpl/cgroupfs/cgroupfs.go",
"diff": "@@ -364,10 +364,14 @@ func (fs *filesystem) prepareInitialCgroup(ctx context.Context, vfsObj *vfs.Virt\n}\nctx.Debugf(\"cgroupfs.FilesystemType.GetFilesystem: initial cgroup path: %v\", initPathStr)\ninitPath := fspath.Parse(initPathStr)\n- if !initPath.Absolute || !initPath.HasComponents() {\n+ if !initPath.Absolute {\nctx.Warningf(\"cgroupfs.FilesystemType.GetFilesystem: initial cgroup path invalid: %+v\", initPath)\nreturn linuxerr.EINVAL\n}\n+ if !initPath.HasComponents() {\n+ // Explicit \"/\" as initial cgroup, nothing to do.\n+ return nil\n+ }\nownerCreds := auth.CredentialsFromContext(ctx).Fork()\nif idata.InitialCgroup.SetOwner {\n"
}
] | Go | Apache License 2.0 | google/gvisor | cgroupfs: Allow explicit "/" as initial cgroup.
PiperOrigin-RevId: 448361452 |
260,009 | 12.05.2022 18:09:34 | 25,200 | db16575cb5fd54e1d910412c1d0a7c2492450fc1 | KVM machine.Get(): Use up vCPU pool before scanning for available ones.
Previously, we created vCPUs on demand, and so taking an unused vCPU from the
pool was expensive. Now, we pre-create all vCPUs at the start, so it makes
sense to use them all to reduce contention. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine.go",
"new_path": "pkg/sentry/platform/kvm/machine.go",
"diff": "@@ -476,29 +476,29 @@ func (m *machine) Get() *vCPU {\n}\nfor {\n- // Scan for an available vCPU.\n- for origTID, c := range m.vCPUsByTID {\n- if c.state.CompareAndSwap(vCPUReady, vCPUUser) {\n- delete(m.vCPUsByTID, origTID)\n+ // Get vCPU from the m.vCPUsByID pool.\n+ if m.usedVCPUs < m.maxVCPUs {\n+ c := m.vCPUsByID[m.usedVCPUs]\n+ m.usedVCPUs++\n+ c.lock()\nm.vCPUsByTID[tid] = c\nm.mu.Unlock()\nc.loadSegments(tid)\ntimer.Finish(\"unused\")\nreturn c\n}\n- }\n- // Get vCPU from the m.vCPUsByID pool.\n- if m.usedVCPUs < m.maxVCPUs {\n- c := m.vCPUsByID[m.usedVCPUs]\n- m.usedVCPUs++\n- c.lock()\n+ // Scan for an available vCPU.\n+ for origTID, c := range m.vCPUsByTID {\n+ if c.state.CompareAndSwap(vCPUReady, vCPUUser) {\n+ delete(m.vCPUsByTID, origTID)\nm.vCPUsByTID[tid] = c\nm.mu.Unlock()\nc.loadSegments(tid)\ntimer.Finish(\"unused\")\nreturn c\n}\n+ }\n// Scan for something not in user mode.\nfor origTID, c := range m.vCPUsByTID {\n"
}
] | Go | Apache License 2.0 | google/gvisor | KVM machine.Get(): Use up vCPU pool before scanning for available ones.
Previously, we created vCPUs on demand, and so taking an unused vCPU from the
pool was expensive. Now, we pre-create all vCPUs at the start, so it makes
sense to use them all to reduce contention.
PiperOrigin-RevId: 448382485 |
259,853 | 12.05.2022 18:09:36 | 25,200 | d44862f6725c585792e4181b74c74bc82a9d5886 | sentry/socket: use lockdep mutexes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/transport/BUILD",
"new_path": "pkg/sentry/socket/unix/transport/BUILD",
"diff": "@@ -3,6 +3,39 @@ load(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\npackage(licenses = [\"notice\"])\n+go_template_instance(\n+ name = \"queue_mutex\",\n+ out = \"queue_mutex.go\",\n+ package = \"transport\",\n+ prefix = \"queue\",\n+ substrs = {\n+ \"genericMark\": \"unixQueue\",\n+ },\n+ template = \"//pkg/sync/locking:generic_mutex\",\n+)\n+\n+go_template_instance(\n+ name = \"stream_queue_receiver_mutex\",\n+ out = \"stream_queue_receiver_mutex.go\",\n+ package = \"transport\",\n+ prefix = \"streamQueueReceiver\",\n+ substrs = {\n+ \"genericMark\": \"streamQueueReceiver\",\n+ },\n+ template = \"//pkg/sync/locking:generic_mutex\",\n+)\n+\n+go_template_instance(\n+ name = \"endpoint_mutex\",\n+ out = \"endpoint_mutex.go\",\n+ package = \"transport\",\n+ prefix = \"endpoint\",\n+ substrs = {\n+ \"genericMark\": \"unixEndpoint\",\n+ },\n+ template = \"//pkg/sync/locking:generic_mutex\",\n+)\n+\ngo_template_instance(\nname = \"transport_message_list\",\nout = \"transport_message_list.go\",\n@@ -44,13 +77,16 @@ go_library(\n\"connectioned_state.go\",\n\"connectionless.go\",\n\"connectionless_state.go\",\n+ \"endpoint_mutex.go\",\n\"host.go\",\n\"host_connected_endpoint_refs.go\",\n\"host_iovec.go\",\n\"host_unsafe.go\",\n\"queue.go\",\n+ \"queue_mutex.go\",\n\"queue_refs.go\",\n\"save_restore.go\",\n+ \"stream_queue_receiver_mutex.go\",\n\"transport_message_list.go\",\n\"unix.go\",\n],\n@@ -70,6 +106,7 @@ go_library(\n\"//pkg/sentry/inet\",\n\"//pkg/sentry/uniqueid\",\n\"//pkg/sync\",\n+ \"//pkg/sync/locking\",\n\"//pkg/syserr\",\n\"//pkg/tcpip\",\n\"//pkg/tcpip/buffer\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/transport/connectioned.go",
"new_path": "pkg/sentry/socket/unix/transport/connectioned.go",
"diff": "@@ -23,12 +23,18 @@ import (\n\"gvisor.dev/gvisor/pkg/fdnotifier\"\n\"gvisor.dev/gvisor/pkg/lisafs\"\n\"gvisor.dev/gvisor/pkg/sentry/uniqueid\"\n- \"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/syserr\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n+type locker interface {\n+ Lock()\n+ Unlock()\n+ NestedLock()\n+ NestedUnlock()\n+}\n+\n// A ConnectingEndpoint is a connectioned unix endpoint that is attempting to\n// establish a bidirectional connection with a BoundEndpoint.\ntype ConnectingEndpoint interface {\n@@ -51,7 +57,7 @@ type ConnectingEndpoint interface {\n// Locker protects the following methods. While locked, only the holder of\n// the lock can change the return value of the protected methods.\n- sync.Locker\n+ locker\n// Connected returns true iff the ConnectingEndpoint is in the connected\n// state. ConnectingEndpoints can only be connected to a single endpoint,\n@@ -292,27 +298,27 @@ func (e *connectionedEndpoint) BidirectionalConnect(ctx context.Context, ce Conn\n// Do a dance to safely acquire locks on both endpoints.\nif e.id < ce.ID() {\ne.Lock()\n- ce.Lock()\n+ ce.NestedLock()\n} else {\nce.Lock()\n- e.Lock()\n+ e.NestedLock()\n}\n// Check connecting state.\nif ce.Connected() {\n- e.Unlock()\n+ e.NestedUnlock()\nce.Unlock()\nreturn syserr.ErrAlreadyConnected\n}\nif ce.ListeningLocked() {\n- e.Unlock()\n+ e.NestedUnlock()\nce.Unlock()\nreturn syserr.ErrInvalidEndpointState\n}\n// Check bound state.\nif !e.ListeningLocked() {\n- e.Unlock()\n+ e.NestedUnlock()\nce.Unlock()\nreturn syserr.ErrConnectionRefused\n}\n@@ -363,7 +369,7 @@ func (e *connectionedEndpoint) BidirectionalConnect(ctx context.Context, ce Conn\n}\n// Notify can deadlock if we are holding these locks.\n- e.Unlock()\n+ e.NestedUnlock()\nce.Unlock()\n// Notify on both ends.\n@@ -373,9 +379,9 @@ func (e *connectionedEndpoint) BidirectionalConnect(ctx context.Context, ce Conn\nreturn nil\ndefault:\n// Busy; return EAGAIN per spec.\n- ne.Close(ctx)\n- e.Unlock()\n+ e.NestedUnlock()\nce.Unlock()\n+ ne.Close(ctx)\nreturn syserr.ErrTryAgain\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/transport/queue.go",
"new_path": "pkg/sentry/socket/unix/transport/queue.go",
"diff": "@@ -16,7 +16,6 @@ package transport\nimport (\n\"gvisor.dev/gvisor/pkg/context\"\n- \"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/syserr\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n@@ -32,7 +31,7 @@ type queue struct {\nReaderQueue *waiter.Queue\nWriterQueue *waiter.Queue\n- mu sync.Mutex `state:\"nosave\"`\n+ mu queueMutex `state:\"nosave\"`\nclosed bool\nunread bool\nused int64\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/transport/unix.go",
"new_path": "pkg/sentry/socket/unix/transport/unix.go",
"diff": "@@ -20,7 +20,6 @@ import (\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/lisafs\"\n\"gvisor.dev/gvisor/pkg/log\"\n- \"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/syserr\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n@@ -423,7 +422,7 @@ func (q *queueReceiver) Release(ctx context.Context) {\ntype streamQueueReceiver struct {\nqueueReceiver\n- mu sync.Mutex `state:\"nosave\"`\n+ mu streamQueueReceiverMutex `state:\"nosave\"`\nbuffer []byte\ncontrol ControlMessages\naddr tcpip.FullAddress\n@@ -765,7 +764,7 @@ type baseEndpoint struct {\n//\n// See the lock ordering comment in package kernel/epoll regarding when\n// this lock can safely be held.\n- sync.Mutex `state:\"nosave\"`\n+ endpointMutex `state:\"nosave\"`\n// receiver allows Messages to be received.\nreceiver Receiver\n"
}
] | Go | Apache License 2.0 | google/gvisor | sentry/socket: use lockdep mutexes
PiperOrigin-RevId: 448382489 |
259,966 | 13.05.2022 09:11:22 | 25,200 | add538a44f15b449f24f262cdd85844c2b26d6e2 | Run multicast cleanup routine only when needed.
Aside from saving resources, this is also a workaround for the case where
timers are bound after the netstack is initialized.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/internal/multicast/route_table.go",
"new_path": "pkg/tcpip/network/internal/multicast/route_table.go",
"diff": "@@ -52,12 +52,14 @@ type RouteTable struct {\npendingMu sync.RWMutex\n// +checklocks:pendingMu\npendingRoutes map[RouteKey]PendingRoute\n-\n- config Config\n-\n// cleanupPendingRoutesTimer is a timer that triggers a routine to remove\n// pending routes that are expired.\n+ // +checklocks:pendingMu\ncleanupPendingRoutesTimer tcpip.Timer\n+ // +checklocks:pendingMu\n+ isCleanupRoutineRunning bool\n+\n+ config Config\n}\nvar (\n@@ -231,7 +233,6 @@ func (r *RouteTable) Init(config Config) error {\nr.installedRoutes = make(map[RouteKey]*InstalledRoute)\nr.pendingRoutes = make(map[RouteKey]PendingRoute)\n- r.cleanupPendingRoutesTimer = r.config.Clock.AfterFunc(DefaultCleanupInterval, r.cleanupPendingRoutes)\nreturn nil\n}\n@@ -240,19 +241,39 @@ func (r *RouteTable) Init(config Config) error {\n// Calling this will stop the cleanup routine and release any packets owned by\n// the table.\nfunc (r *RouteTable) Close() {\n+ r.pendingMu.Lock()\n+ defer r.pendingMu.Unlock()\n+\nif r.cleanupPendingRoutesTimer != nil {\nr.cleanupPendingRoutesTimer.Stop()\n}\n- r.pendingMu.Lock()\n- defer r.pendingMu.Unlock()\n-\nfor key, route := range r.pendingRoutes {\ndelete(r.pendingRoutes, key)\nroute.releasePackets()\n}\n}\n+// maybeStopCleanupRoutine stops the pending routes cleanup routine if no\n+// pending routes exist.\n+//\n+// Returns true if the timer is not running. Otherwise, returns false.\n+//\n+// +checklocks:r.pendingMu\n+func (r *RouteTable) maybeStopCleanupRoutineLocked() bool {\n+ if !r.isCleanupRoutineRunning {\n+ return true\n+ }\n+\n+ if len(r.pendingRoutes) == 0 {\n+ r.cleanupPendingRoutesTimer.Stop()\n+ r.isCleanupRoutineRunning = false\n+ return true\n+ }\n+\n+ return false\n+}\n+\nfunc (r *RouteTable) cleanupPendingRoutes() {\ncurrentTime := r.config.Clock.NowMonotonic()\nr.pendingMu.Lock()\n@@ -264,8 +285,11 @@ func (r *RouteTable) cleanupPendingRoutes() {\nroute.releasePackets()\n}\n}\n+\n+ if stopped := r.maybeStopCleanupRoutineLocked(); !stopped {\nr.cleanupPendingRoutesTimer.Reset(DefaultCleanupInterval)\n}\n+}\nfunc (r *RouteTable) newPendingRoute() PendingRoute {\nreturn PendingRoute{\n@@ -358,6 +382,16 @@ func (r *RouteTable) GetRouteOrInsertPending(key RouteKey, pkt *stack.PacketBuff\npendingRoute.packets = append(pendingRoute.packets, pkt.Clone())\nr.pendingRoutes[key] = pendingRoute\n+ if !r.isCleanupRoutineRunning {\n+ // The cleanup routine isn't running, but should be. Start it.\n+ if r.cleanupPendingRoutesTimer == nil {\n+ r.cleanupPendingRoutesTimer = r.config.Clock.AfterFunc(DefaultCleanupInterval, r.cleanupPendingRoutes)\n+ } else {\n+ r.cleanupPendingRoutesTimer.Reset(DefaultCleanupInterval)\n+ }\n+ r.isCleanupRoutineRunning = true\n+ }\n+\nreturn GetRouteResult{PendingRouteState: pendingRouteState, InstalledRoute: nil}, nil\n}\n@@ -383,6 +417,9 @@ func (r *RouteTable) AddInstalledRoute(key RouteKey, route *InstalledRoute) []*s\nr.pendingMu.Lock()\npendingRoute, ok := r.pendingRoutes[key]\ndelete(r.pendingRoutes, key)\n+ // No need to reset the timer here. The cleanup routine is responsible for\n+ // doing so.\n+ _ = r.maybeStopCleanupRoutineLocked()\nr.pendingMu.Unlock()\n// Ignore the pending route if it is expired. It may be in this state since\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/internal/multicast/route_table_test.go",
"new_path": "pkg/tcpip/network/internal/multicast/route_table_test.go",
"diff": "@@ -126,7 +126,7 @@ func TestInit(t *testing.T) {\n}\nif !cmp.Equal(err, tc.wantErr, cmpopts.EquateErrors()) {\n- t.Errorf(\"got table.Init(%#v) = %s, want %s\", tc.config, err, tc.wantErr)\n+ t.Errorf(\"table.Init(%#v) = %s, want %s\", tc.config, err, tc.wantErr)\n}\n})\n}\n@@ -147,7 +147,7 @@ func TestNewInstalledRoute(t *testing.T) {\nexpectedRoute := &InstalledRoute{expectedInputInterface: inputNICID, outgoingInterfaces: defaultOutgoingInterfaces, lastUsedTimestamp: clock.NowMonotonic()}\nif diff := cmp.Diff(expectedRoute, route, cmp.Comparer(installedRouteComparer)); diff != \"\" {\n- t.Errorf(\"installed route mismatch (-want +got):\\n%s\", diff)\n+ t.Errorf(\"Installed route mismatch (-want +got):\\n%s\", diff)\n}\n}\n@@ -167,7 +167,7 @@ func TestPendingRouteStates(t *testing.T) {\nrouteResult, err := table.GetRouteOrInsertPending(defaultRouteKey, pkt)\nif err != nil {\n- t.Errorf(\"got table.GetRouteOrInsertPending(%#v, %#v) = (_, %v), want = (_, nil)\", defaultRouteKey, pkt, err)\n+ t.Errorf(\"table.GetRouteOrInsertPending(%#v, %#v) = (_, %v), want = (_, nil)\", defaultRouteKey, pkt, err)\n}\nexpectedResult := GetRouteResult{PendingRouteState: wantPendingRouteState}\n@@ -179,7 +179,7 @@ func TestPendingRouteStates(t *testing.T) {\n// Queuing a third packet should yield an error since the pending queue is\n// already at max capacity.\nif _, err := table.GetRouteOrInsertPending(defaultRouteKey, pkt); err != ErrNoBufferSpace {\n- t.Errorf(\"got table.GetRouteOrInsertPending(%#v, %#v) = (_, %v), want = (_, ErrNoBufferSpace)\", defaultRouteKey, pkt, err)\n+ t.Errorf(\"table.GetRouteOrInsertPending(%#v, %#v) = (_, %v), want = (_, ErrNoBufferSpace)\", defaultRouteKey, pkt, err)\n}\n}\n@@ -233,10 +233,14 @@ func TestPendingRouteExpiration(t *testing.T) {\ntable.pendingMu.RLock()\n_, ok := table.pendingRoutes[defaultRouteKey]\n+\n+ if table.isCleanupRoutineRunning != test.wantPendingRoute {\n+ t.Errorf(\"table.isCleanupRoutineRunning = %t, want = %t\", table.isCleanupRoutineRunning, test.wantPendingRoute)\n+ }\ntable.pendingMu.RUnlock()\nif test.wantPendingRoute != ok {\n- t.Errorf(\"got table.pendingRoutes[%#v] = (_, %t), want = (_, %t)\", defaultRouteKey, ok, test.wantPendingRoute)\n+ t.Errorf(\"table.pendingRoutes[%#v] = (_, %t), want = (_, %t)\", defaultRouteKey, ok, test.wantPendingRoute)\n}\n})\n}\n@@ -283,20 +287,21 @@ func TestAddInstalledRouteWithPending(t *testing.T) {\nif err := table.Init(config); err != nil {\nt.Fatalf(\"table.Init(%#v): %s\", config, err)\n}\n- // Disable the cleanup routine.\n- table.cleanupPendingRoutesTimer.Stop()\nif _, err := table.GetRouteOrInsertPending(defaultRouteKey, pkt); err != nil {\nt.Fatalf(\"table.GetRouteOrInsertPending(%#v, %#v): %v\", defaultRouteKey, pkt, err)\n}\n+ // Disable the cleanup routine.\n+ table.cleanupPendingRoutesTimer.Stop()\n+\nclock.Advance(test.advance)\nroute := table.NewInstalledRoute(inputNICID, defaultOutgoingInterfaces)\npendingPackets := table.AddInstalledRoute(defaultRouteKey, route)\nif diff := cmp.Diff(test.want, pendingPackets, cmpOpts...); diff != \"\" {\n- t.Errorf(\"tableAddInstalledRoute(%#v, %#v) mismatch (-want +got):\\n%s\", defaultRouteKey, route, diff)\n+ t.Errorf(\"table.AddInstalledRoute(%#v, %#v) mismatch (-want +got):\\n%s\", defaultRouteKey, route, diff)\n}\nfor _, pendingPkt := range pendingPackets {\n@@ -306,7 +311,7 @@ func TestAddInstalledRouteWithPending(t *testing.T) {\n// Verify that the pending route is actually deleted.\ntable.pendingMu.RLock()\nif pendingRoute, ok := table.pendingRoutes[defaultRouteKey]; ok {\n- t.Errorf(\"got table.pendingRoutes[%#v] = (%#v, true), want (_, false)\", defaultRouteKey, pendingRoute)\n+ t.Errorf(\"table.pendingRoutes[%#v] = (%#v, true), want (_, false)\", defaultRouteKey, pendingRoute)\n}\ntable.pendingMu.RUnlock()\n})\n@@ -341,7 +346,7 @@ func TestAddInstalledRouteWithNoPending(t *testing.T) {\n}\nif routeResult.PendingRouteState != PendingRouteStateNone {\n- t.Errorf(\"got routeResult.PendingRouteState = %s, want = PendingRouteStateNone\", routeResult.PendingRouteState)\n+ t.Errorf(\"routeResult.PendingRouteState = %s, want = PendingRouteStateNone\", routeResult.PendingRouteState)\n}\nif diff := cmp.Diff(route, routeResult.InstalledRoute, cmp.Comparer(installedRouteComparer)); diff != \"\" {\n@@ -363,7 +368,7 @@ func TestRemoveInstalledRoute(t *testing.T) {\ntable.AddInstalledRoute(defaultRouteKey, route)\nif removed := table.RemoveInstalledRoute(defaultRouteKey); !removed {\n- t.Errorf(\"got table.RemoveInstalledRoute(%#v) = false, want = true\", defaultRouteKey)\n+ t.Errorf(\"table.RemoveInstalledRoute(%#v) = false, want = true\", defaultRouteKey)\n}\npkt := newPacketBuffer(\"hello\")\n@@ -376,7 +381,7 @@ func TestRemoveInstalledRoute(t *testing.T) {\n}\nif result.InstalledRoute != nil {\n- t.Errorf(\"got result.InstalledRoute = %v, want = nil\", result.InstalledRoute)\n+ t.Errorf(\"result.InstalledRoute = %v, want = nil\", result.InstalledRoute)\n}\n}\n@@ -389,7 +394,7 @@ func TestRemoveInstalledRouteWithNoMatchingRoute(t *testing.T) {\n}\nif removed := table.RemoveInstalledRoute(defaultRouteKey); removed {\n- t.Errorf(\"got table.RemoveInstalledRoute(%#v) = true, want = false\", defaultRouteKey)\n+ t.Errorf(\"table.RemoveInstalledRoute(%#v) = true, want = false\", defaultRouteKey)\n}\n}\n@@ -402,7 +407,7 @@ func TestGetLastUsedTimestampWithNoMatchingRoute(t *testing.T) {\n}\nif _, found := table.GetLastUsedTimestamp(defaultRouteKey); found {\n- t.Errorf(\"got table.GetLastUsedTimetsamp(%#v) = (_, true), want = (_, false)\", defaultRouteKey)\n+ t.Errorf(\"table.GetLastUsedTimetsamp(%#v) = (_, true), want = (_, false)\", defaultRouteKey)\n}\n}\n@@ -449,11 +454,11 @@ func TestSetLastUsedTimestamp(t *testing.T) {\ntimestamp, found := table.GetLastUsedTimestamp(defaultRouteKey)\nif !found {\n- t.Fatalf(\"got table.GetLastUsedTimestamp(%#v) = (_, false_), want = (_, true)\", defaultRouteKey)\n+ t.Fatalf(\"table.GetLastUsedTimestamp(%#v) = (_, false_), want = (_, true)\", defaultRouteKey)\n}\nif timestamp != test.wantLastUsedTime {\n- t.Errorf(\"got table.GetLastUsedTimestamp(%#v) = (%s, _), want = (%s, _)\", defaultRouteKey, timestamp, test.wantLastUsedTime)\n+ t.Errorf(\"table.GetLastUsedTimestamp(%#v) = (%s, _), want = (%s, _)\", defaultRouteKey, timestamp, test.wantLastUsedTime)\n}\n})\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Run multicast cleanup routine only when needed.
Aside from saving resources, this is also a workaround for the case where
timers are bound after the netstack is initialized.
Updates #7338.
PiperOrigin-RevId: 448509194 |
259,992 | 13.05.2022 12:22:46 | 25,200 | fa2a88887d23ca5cb385e26ecad2b97448ed81ab | Deprecate --vfs2 flag and always enable by default
Also remove VFS1 dimension from runsc unit tests.
Updates
Startblock:
after 2022-05-30 | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/fs_test.go",
"new_path": "runsc/boot/fs_test.go",
"diff": "@@ -243,7 +243,7 @@ func TestGetMountAccessType(t *testing.T) {\nt.Fatalf(\"newPodMountHints failed: %v\", err)\n}\nmounter := containerMounter{hints: podHints}\n- conf := &config.Config{FileAccessMounts: config.FileAccessShared}\n+ conf := &config.Config{VFS2: true, FileAccessMounts: config.FileAccessShared}\nif got := mounter.getMountAccessType(conf, &specs.Mount{Source: source}); got != tst.want {\nt.Errorf(\"getMountAccessType(), want: %v, got: %v\", tst.want, got)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cli/main.go",
"new_path": "runsc/cli/main.go",
"diff": "@@ -224,7 +224,7 @@ func Main(version string) {\nlog.Infof(\"\\t\\tFileAccess: %v, overlay: %t\", conf.FileAccess, conf.Overlay)\nlog.Infof(\"\\t\\tNetwork: %v, logging: %t\", conf.Network, conf.LogPackets)\nlog.Infof(\"\\t\\tStrace: %t, max size: %d, syscalls: %s\", conf.Strace, conf.StraceLogSize, conf.StraceSyscalls)\n- log.Infof(\"\\t\\tVFS2 enabled: %t, LISAFS: %t\", conf.VFS2, conf.Lisafs)\n+ log.Infof(\"\\t\\tLISAFS: %t\", conf.Lisafs)\nlog.Infof(\"\\t\\tDebug: %v\", conf.Debug)\nlog.Infof(\"\\t\\tSystemd: %v\", conf.SystemdCgroup)\nlog.Infof(\"***************************\")\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/config/config.go",
"new_path": "runsc/config/config.go",
"diff": "@@ -205,8 +205,8 @@ type Config struct {\n// E.g. 0.2 CPU quota will result in 1, and 1.9 in 2.\nCPUNumFromQuota bool `flag:\"cpu-num-from-quota\"`\n- // Enables VFS2.\n- VFS2 bool `flag:\"vfs2\"`\n+ // DEPRECATED: VFS2 is always enabled and cannot be disabled.\n+ VFS2 bool\n// Enable lisafs.\nLisafs bool `flag:\"lisafs\"`\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/config/flags.go",
"new_path": "runsc/config/flags.go",
"diff": "@@ -80,9 +80,9 @@ func RegisterFlags(flagSet *flag.FlagSet) {\nflagSet.Bool(\"overlay\", false, \"wrap filesystem mounts with writable overlay. All modifications are stored in memory inside the sandbox.\")\nflagSet.Bool(\"verity\", false, \"specifies whether a verity file system will be mounted.\")\nflagSet.Bool(\"fsgofer-host-uds\", false, \"allow the gofer to mount Unix Domain Sockets.\")\n- flagSet.Bool(\"vfs2\", true, \"enables VFSv2. This uses the new VFS layer that is faster than the previous one.\")\n+ flagSet.Bool(\"vfs2\", true, \"DEPRECATED: this flag has no effect.\")\nflagSet.Bool(\"fuse\", false, \"TEST ONLY; use while FUSE in VFSv2 is landing. This allows the use of the new experimental FUSE filesystem.\")\n- flagSet.Bool(\"lisafs\", false, \"Enables lisafs protocol instead of 9P. This is only effective with VFS2.\")\n+ flagSet.Bool(\"lisafs\", false, \"Enables lisafs protocol instead of 9P.\")\nflagSet.Bool(\"cgroupfs\", false, \"Automatically mount cgroupfs.\")\nflagSet.Bool(\"ignore-cgroups\", false, \"don't configure cgroups.\")\n@@ -131,7 +131,7 @@ func checkOciSeccomp(name string, value string) error {\n// NewFromFlags creates a new Config with values coming from command line flags.\nfunc NewFromFlags(flagSet *flag.FlagSet) (*Config, error) {\n- conf := &Config{}\n+ conf := &Config{VFS2: true}\nobj := reflect.ValueOf(conf).Elem()\nst := obj.Type()\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/container_test.go",
"new_path": "runsc/container/container_test.go",
"diff": "@@ -409,7 +409,6 @@ func configs(t *testing.T, noOverlay bool) map[string]*config.Config {\nfor _, p := range ps {\nc := testutil.TestConfig(t)\nc.Platform = p\n- c.VFS2 = true\ncs[p] = c\n}\n@@ -419,19 +418,10 @@ func configs(t *testing.T, noOverlay bool) map[string]*config.Config {\nc := testutil.TestConfig(t)\nc.Platform = p\nc.Overlay = true\n- c.VFS2 = true\ncs[p+\"-overlay\"] = c\n}\n}\n- // FIXME(b/148134013): Delete with VFS1.\n- for _, p := range ps {\n- c := testutil.TestConfig(t)\n- c.Platform = p\n- c.VFS2 = false\n- cs[p+\"-vfs1\"] = c\n- }\n-\nreturn cs\n}\n@@ -687,19 +677,9 @@ func TestExePath(t *testing.T) {\n// Test the we can retrieve the application exit status from the container.\nfunc TestAppExitStatus(t *testing.T) {\n- doAppExitStatus(t, false)\n-}\n-\n-// This is TestAppExitStatus for VFSv2.\n-func TestAppExitStatusVFS2(t *testing.T) {\n- doAppExitStatus(t, true)\n-}\n-\n-func doAppExitStatus(t *testing.T, vfs2 bool) {\n// First container will succeed.\nsuccSpec := testutil.NewSpecWithArgs(\"true\")\nconf := testutil.TestConfig(t)\n- conf.VFS2 = vfs2\n_, bundleDir, cleanup, err := testutil.SetupContainer(succSpec, conf)\nif err != nil {\nt.Fatalf(\"error setting up container: %v\", err)\n@@ -1827,14 +1807,6 @@ func TestUIDMap(t *testing.T) {\n// TestAbbreviatedIDs checks that runsc supports using abbreviated container\n// IDs in place of full IDs.\nfunc TestAbbreviatedIDs(t *testing.T) {\n- doAbbreviatedIDsTest(t, false)\n-}\n-\n-func TestAbbreviatedIDsVFS2(t *testing.T) {\n- doAbbreviatedIDsTest(t, true)\n-}\n-\n-func doAbbreviatedIDsTest(t *testing.T, vfs2 bool) {\nrootDir, cleanup, err := testutil.SetupRootDir()\nif err != nil {\nt.Fatalf(\"error creating root dir: %v\", err)\n@@ -1843,7 +1815,6 @@ func doAbbreviatedIDsTest(t *testing.T, vfs2 bool) {\nconf := testutil.TestConfig(t)\nconf.RootDir = rootDir\n- conf.VFS2 = vfs2\ncids := []string{\n\"foo-\" + testutil.RandomContainerID(),\n@@ -1899,17 +1870,8 @@ func doAbbreviatedIDsTest(t *testing.T, vfs2 bool) {\n}\nfunc TestGoferExits(t *testing.T) {\n- doGoferExitTest(t, false)\n-}\n-\n-func TestGoferExitsVFS2(t *testing.T) {\n- doGoferExitTest(t, true)\n-}\n-\n-func doGoferExitTest(t *testing.T, vfs2 bool) {\nspec := testutil.NewSpecWithArgs(\"/bin/sleep\", \"10000\")\nconf := testutil.TestConfig(t)\n- conf.VFS2 = vfs2\n_, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)\nif err != nil {\n@@ -2085,17 +2047,8 @@ func TestWaitOnExitedSandbox(t *testing.T) {\n}\nfunc TestDestroyNotStarted(t *testing.T) {\n- doDestroyNotStartedTest(t, false)\n-}\n-\n-func TestDestroyNotStartedVFS2(t *testing.T) {\n- doDestroyNotStartedTest(t, true)\n-}\n-\n-func doDestroyNotStartedTest(t *testing.T, vfs2 bool) {\nspec := testutil.NewSpecWithArgs(\"/bin/sleep\", \"100\")\nconf := testutil.TestConfig(t)\n- conf.VFS2 = vfs2\n_, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)\nif err != nil {\nt.Fatalf(\"error setting up container: %v\", err)\n@@ -2119,18 +2072,9 @@ func doDestroyNotStartedTest(t *testing.T, vfs2 bool) {\n// TestDestroyStarting attempts to force a race between start and destroy.\nfunc TestDestroyStarting(t *testing.T) {\n- doDestroyStartingTest(t, false)\n-}\n-\n-func TestDestroyStartedVFS2(t *testing.T) {\n- doDestroyStartingTest(t, true)\n-}\n-\n-func doDestroyStartingTest(t *testing.T, vfs2 bool) {\nfor i := 0; i < 10; i++ {\nspec := testutil.NewSpecWithArgs(\"/bin/sleep\", \"100\")\nconf := testutil.TestConfig(t)\n- conf.VFS2 = vfs2\nrootDir, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)\nif err != nil {\nt.Fatalf(\"error setting up container: %v\", err)\n@@ -2407,14 +2351,8 @@ func TestTTYField(t *testing.T) {\n}\nfor _, test := range testCases {\n- for _, vfs2 := range []bool{false, true} {\n- name := test.name\n- if vfs2 {\n- name += \"-vfs2\"\n- }\n- t.Run(name, func(t *testing.T) {\n+ t.Run(test.name, func(t *testing.T) {\nconf := testutil.TestConfig(t)\n- conf.VFS2 = vfs2\n// We will run /bin/sleep, possibly with an open TTY.\ncmd := []string{\"/bin/sleep\", \"10000\"}\n@@ -2472,7 +2410,6 @@ func TestTTYField(t *testing.T) {\n})\n}\n}\n-}\n// Test that container can run even when there are corrupt state files in the\n// root directiry.\n@@ -2596,62 +2533,60 @@ func TestRlimitsExec(t *testing.T) {\n}\n// TestCat creates a file and checks that cat generates the expected output.\n-func TestCat(t *testing.T) {\n- f, err := ioutil.TempFile(testutil.TmpDir(), \"test-case\")\n- if err != nil {\n- t.Fatalf(\"ioutil.TempFile failed: %v\", err)\n- }\n- defer os.RemoveAll(f.Name())\n-\n- content := \"test-cat\"\n- if _, err := f.WriteString(content); err != nil {\n- t.Fatalf(\"f.WriteString(): %v\", err)\n- }\n- f.Close()\n-\n- spec, conf := sleepSpecConf(t)\n// TODO(gvisor.dev/issue/6742): Add VFS2 support.\n- conf.VFS2 = false\n-\n- _, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)\n- if err != nil {\n- t.Fatalf(\"error setting up container: %v\", err)\n- }\n- defer cleanup()\n-\n- args := Args{\n- ID: testutil.RandomContainerID(),\n- Spec: spec,\n- BundleDir: bundleDir,\n- }\n-\n- cont, err := New(conf, args)\n- if err != nil {\n- t.Fatalf(\"Creating container: %v\", err)\n- }\n- defer cont.Destroy()\n-\n- if err := cont.Start(conf); err != nil {\n- t.Fatalf(\"starting container: %v\", err)\n- }\n-\n- r, w, err := os.Pipe()\n- if err != nil {\n- t.Fatalf(\"os.Create(): %v\", err)\n- }\n-\n- if err := cont.Cat([]string{f.Name()}, w); err != nil {\n- t.Fatalf(\"error cat from container: %v\", err)\n- }\n-\n- buf := make([]byte, 1024)\n- if _, err := r.Read(buf); err != nil {\n- t.Fatalf(\"Read out: %v\", err)\n- }\n- if got, want := string(buf), content; !strings.Contains(got, want) {\n- t.Errorf(\"out got %s, want include %s\", buf, want)\n- }\n-}\n+// func TestCat(t *testing.T) {\n+// f, err := ioutil.TempFile(testutil.TmpDir(), \"test-case\")\n+// if err != nil {\n+// t.Fatalf(\"ioutil.TempFile failed: %v\", err)\n+// }\n+// defer os.RemoveAll(f.Name())\n+\n+// content := \"test-cat\"\n+// if _, err := f.WriteString(content); err != nil {\n+// t.Fatalf(\"f.WriteString(): %v\", err)\n+// }\n+// f.Close()\n+\n+// spec, conf := sleepSpecConf(t)\n+// _, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)\n+// if err != nil {\n+// t.Fatalf(\"error setting up container: %v\", err)\n+// }\n+// defer cleanup()\n+\n+// args := Args{\n+// ID: testutil.RandomContainerID(),\n+// Spec: spec,\n+// BundleDir: bundleDir,\n+// }\n+\n+// cont, err := New(conf, args)\n+// if err != nil {\n+// t.Fatalf(\"Creating container: %v\", err)\n+// }\n+// defer cont.Destroy()\n+\n+// if err := cont.Start(conf); err != nil {\n+// t.Fatalf(\"starting container: %v\", err)\n+// }\n+\n+// r, w, err := os.Pipe()\n+// if err != nil {\n+// t.Fatalf(\"os.Create(): %v\", err)\n+// }\n+\n+// if err := cont.Cat([]string{f.Name()}, w); err != nil {\n+// t.Fatalf(\"error cat from container: %v\", err)\n+// }\n+\n+// buf := make([]byte, 1024)\n+// if _, err := r.Read(buf); err != nil {\n+// t.Fatalf(\"Read out: %v\", err)\n+// }\n+// if got, want := string(buf), content; !strings.Contains(got, want) {\n+// t.Errorf(\"out got %s, want include %s\", buf, want)\n+// }\n+// }\n// TestUsage checks that usage generates the expected memory usage.\nfunc TestUsage(t *testing.T) {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/multi_container_test.go",
"new_path": "runsc/container/multi_container_test.go",
"diff": "@@ -1698,7 +1698,6 @@ func TestMultiContainerGoferKilled(t *testing.T) {\ndefer cleanup()\nconf := testutil.TestConfig(t)\n- conf.VFS2 = true\nconf.RootDir = rootDir\nsleep := []string{\"sleep\", \"100\"}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Deprecate --vfs2 flag and always enable by default
Also remove VFS1 dimension from runsc unit tests.
Updates #1624
Startblock:
after 2022-05-30
PiperOrigin-RevId: 448552271 |
259,992 | 13.05.2022 12:23:44 | 25,200 | e189fb68860820c1903dc12fe3c7670d9ceacde2 | Add version handshake before communication is stablished
Details on how it works is in wire.Handshake.
Updates | [
{
"change_type": "MODIFY",
"old_path": "examples/seccheck/server.cc",
"new_path": "examples/seccheck/server.cc",
"diff": "#include \"absl/cleanup/cleanup.h\"\n#include \"absl/strings/string_view.h\"\n+#include \"pkg/sentry/seccheck/points/common.pb.h\"\n#include \"pkg/sentry/seccheck/points/container.pb.h\"\n#include \"pkg/sentry/seccheck/points/sentry.pb.h\"\n#include \"pkg/sentry/seccheck/points/syscall.pb.h\"\n@@ -163,6 +164,41 @@ void startPollThread(int poll_fd) {\npthread_detach(thread);\n}\n+// handshake performs version exchange with client. See common.proto for details\n+// about the protocol.\n+bool handshake(int client_fd) {\n+ std::vector<char> buf(10240);\n+ int bytes = read(client_fd, buf.data(), buf.size());\n+ if (bytes < 0) {\n+ printf(\"Error receiving handshake message: %d\\n\", errno);\n+ return false;\n+ } else if (bytes == buf.size()) {\n+ // Protect against the handshake becoming larger than the buffer allocated\n+ // for it.\n+ printf(\"handshake message too big\\n\");\n+ return false;\n+ }\n+ ::gvisor::common::Handshake in = {};\n+ if (!in.ParseFromArray(buf.data(), bytes)) {\n+ printf(\"Error parsing handshake message\\n\");\n+ return false;\n+ }\n+\n+ constexpr uint32_t minSupportedVersion = 1;\n+ if (in.version() < minSupportedVersion) {\n+ printf(\"Client has unsupported version %u\\n\", in.version());\n+ return false;\n+ }\n+\n+ ::gvisor::common::Handshake out;\n+ out.set_version(1);\n+ if (!out.SerializeToFileDescriptor(client_fd)) {\n+ printf(\"Error sending handshake message: %d\\n\", errno);\n+ return false;\n+ }\n+ return true;\n+}\n+\nextern \"C\" int main(int argc, char** argv) {\nfor (int c = 0; (c = getopt(argc, argv, \"q\")) != -1;) {\nswitch (c) {\n@@ -221,6 +257,11 @@ extern \"C\" int main(int argc, char** argv) {\n}\nprintf(\"Connection accepted\\n\");\n+ if (!handshake(client)) {\n+ close(client);\n+ continue;\n+ }\n+\nstruct epoll_event evt;\nevt.data.fd = client;\nevt.events = EPOLLIN;\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/checkers/remote/BUILD",
"new_path": "pkg/sentry/seccheck/checkers/remote/BUILD",
"diff": "@@ -12,7 +12,7 @@ go_library(\n\"//pkg/fd\",\n\"//pkg/log\",\n\"//pkg/sentry/seccheck\",\n- \"//pkg/sentry/seccheck/checkers/remote/header\",\n+ \"//pkg/sentry/seccheck/checkers/remote/wire\",\n\"//pkg/sentry/seccheck/points:points_go_proto\",\n\"@org_golang_google_protobuf//proto:go_default_library\",\n\"@org_golang_x_sys//unix:go_default_library\",\n@@ -31,6 +31,7 @@ go_test(\n\"//pkg/fd\",\n\"//pkg/sentry/seccheck\",\n\"//pkg/sentry/seccheck/checkers/remote/test\",\n+ \"//pkg/sentry/seccheck/checkers/remote/wire\",\n\"//pkg/sentry/seccheck/points:points_go_proto\",\n\"//pkg/test/testutil\",\n\"@com_github_cenkalti_backoff//:go_default_library\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/checkers/remote/remote.go",
"new_path": "pkg/sentry/seccheck/checkers/remote/remote.go",
"diff": "package remote\nimport (\n+ \"errors\"\n\"fmt\"\n+ \"io\"\n\"os\"\n\"golang.org/x/sys/unix\"\n@@ -27,7 +29,7 @@ import (\n\"gvisor.dev/gvisor/pkg/fd\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/seccheck\"\n- \"gvisor.dev/gvisor/pkg/sentry/seccheck/checkers/remote/header\"\n+ \"gvisor.dev/gvisor/pkg/sentry/seccheck/checkers/remote/wire\"\npb \"gvisor.dev/gvisor/pkg/sentry/seccheck/points/points_go_proto\"\n)\n@@ -81,6 +83,38 @@ func setup(path string) (*os.File, error) {\nif err := unix.Connect(int(f.Fd()), &addr); err != nil {\nreturn nil, fmt.Errorf(\"connect(%q): %w\", path, err)\n}\n+\n+ // Perform handshake. See common.proto for details about the protocol.\n+ hsOut := pb.Handshake{Version: wire.CurrentVersion}\n+ out, err := proto.Marshal(&hsOut)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"marshalling handshake message: %w\", err)\n+ }\n+ if _, err := f.Write(out); err != nil {\n+ return nil, fmt.Errorf(\"sending handshake message: %w\", err)\n+ }\n+\n+ in := make([]byte, 10240)\n+ read, err := f.Read(in)\n+ if err != nil && !errors.Is(err, io.EOF) {\n+ return nil, fmt.Errorf(\"reading handshake message: %w\", err)\n+ }\n+ // Protect against the handshake becoming larger than the buffer allocated\n+ // for it.\n+ if read == len(in) {\n+ return nil, fmt.Errorf(\"handshake message too big\")\n+ }\n+ hsIn := pb.Handshake{}\n+ if err := proto.Unmarshal(in[:read], &hsIn); err != nil {\n+ return nil, fmt.Errorf(\"unmarshalling handshake message: %w\", err)\n+ }\n+\n+ // Check that remote version can be supported.\n+ const minSupportedVersion = 1\n+ if hsIn.Version < minSupportedVersion {\n+ return nil, fmt.Errorf(\"remote version (%d) is smaller than minimum supported (%d)\", hsIn.Version, minSupportedVersion)\n+ }\n+\ncu.Release()\nreturn f, nil\n}\n@@ -90,13 +124,6 @@ func New(_ map[string]interface{}, endpoint *fd.FD) (seccheck.Checker, error) {\nif endpoint == nil {\nreturn nil, fmt.Errorf(\"remote sink requires an endpoint\")\n}\n- // TODO(gvisor.dev/issue/4805): perform version handshake with remote:\n- // 1. sentry and remote exchange versions\n- // 2. sentry continues if remote >= min(sentry)\n- // 3. remote continues if sentry >= min(remote).\n- // min() being the minimal supported version. Let's say current sentry\n- // supports batching but remote doesn't, sentry can chose to not batch or\n- // refuse the connection.\nreturn &Remote{endpoint: endpoint}, nil\n}\n@@ -115,11 +142,11 @@ func (r *Remote) write(msg proto.Message, msgType pb.MessageType) {\nlog.Debugf(\"Marshal(%+v): %v\", msg, err)\nreturn\n}\n- hdr := header.Header{\n- HeaderSize: uint16(header.HeaderStructSize),\n+ hdr := wire.Header{\n+ HeaderSize: uint16(wire.HeaderStructSize),\nMessageType: uint16(msgType),\n}\n- var hdrOut [header.HeaderStructSize]byte\n+ var hdrOut [wire.HeaderStructSize]byte\nhdr.MarshalUnsafe(hdrOut[:])\n// TODO(gvisor.dev/issue/4805): Change to non-blocking write. Count as dropped\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/checkers/remote/remote_test.go",
"new_path": "pkg/sentry/seccheck/checkers/remote/remote_test.go",
"diff": "@@ -31,6 +31,7 @@ import (\n\"gvisor.dev/gvisor/pkg/fd\"\n\"gvisor.dev/gvisor/pkg/sentry/seccheck\"\n\"gvisor.dev/gvisor/pkg/sentry/seccheck/checkers/remote/test\"\n+ \"gvisor.dev/gvisor/pkg/sentry/seccheck/checkers/remote/wire\"\npb \"gvisor.dev/gvisor/pkg/sentry/seccheck/points/points_go_proto\"\n\"gvisor.dev/gvisor/pkg/test/testutil\"\n)\n@@ -153,6 +154,37 @@ func TestBasic(t *testing.T) {\n}\n}\n+func TestVersionUnsupported(t *testing.T) {\n+ server, err := test.NewServer()\n+ if err != nil {\n+ t.Fatalf(\"newServer(): %v\", err)\n+ }\n+ defer server.Close()\n+\n+ server.SetVersion(0)\n+\n+ _, err = setup(server.Path)\n+ if err == nil || !strings.Contains(err.Error(), \"remote version\") {\n+ t.Fatalf(\"Wrong error: %v\", err)\n+ }\n+}\n+\n+func TestVersionNewer(t *testing.T) {\n+ server, err := test.NewServer()\n+ if err != nil {\n+ t.Fatalf(\"newServer(): %v\", err)\n+ }\n+ defer server.Close()\n+\n+ server.SetVersion(wire.CurrentVersion + 10)\n+\n+ endpoint, err := setup(server.Path)\n+ if err != nil {\n+ t.Fatalf(\"setup(): %v\", err)\n+ }\n+ _ = endpoint.Close()\n+}\n+\n// Test that the example C++ server works. It's easier to test from here and\n// also changes that can break it will likely originate here.\nfunc TestExample(t *testing.T) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/checkers/remote/test/BUILD",
"new_path": "pkg/sentry/seccheck/checkers/remote/test/BUILD",
"diff": "@@ -10,11 +10,12 @@ go_library(\ndeps = [\n\"//pkg/cleanup\",\n\"//pkg/log\",\n- \"//pkg/sentry/seccheck/checkers/remote/header\",\n+ \"//pkg/sentry/seccheck/checkers/remote/wire\",\n\"//pkg/sentry/seccheck/points:points_go_proto\",\n\"//pkg/sync\",\n\"//pkg/test/testutil\",\n\"//pkg/unet\",\n+ \"@org_golang_google_protobuf//proto:go_default_library\",\n\"@org_golang_x_sys//unix:go_default_library\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/checkers/remote/test/server.go",
"new_path": "pkg/sentry/seccheck/checkers/remote/test/server.go",
"diff": "@@ -24,9 +24,10 @@ import (\n\"time\"\n\"golang.org/x/sys/unix\"\n+ \"google.golang.org/protobuf/proto\"\n\"gvisor.dev/gvisor/pkg/cleanup\"\n\"gvisor.dev/gvisor/pkg/log\"\n- \"gvisor.dev/gvisor/pkg/sentry/seccheck/checkers/remote/header\"\n+ \"gvisor.dev/gvisor/pkg/sentry/seccheck/checkers/remote/wire\"\npb \"gvisor.dev/gvisor/pkg/sentry/seccheck/points/points_go_proto\"\n\"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/test/testutil\"\n@@ -46,6 +47,8 @@ type Server struct {\n// +checklocks:mu\npoints []Message\n+\n+ version uint32\n}\n// Message corresponds to a single message sent from checkers.Remote.\n@@ -99,6 +102,7 @@ func newServerPath(path string) (*Server, error) {\nserver := &Server{\nPath: path,\nsocket: ss,\n+ version: wire.CurrentVersion,\n}\ngo server.run()\ncu.Release()\n@@ -115,6 +119,11 @@ func (s *Server) run() {\n}\nreturn\n}\n+ if err := s.handshake(client); err != nil {\n+ log.Warningf(err.Error())\n+ _ = client.Close()\n+ continue\n+ }\ns.mu.Lock()\ns.clients = append(s.clients, client)\ns.mu.Unlock()\n@@ -122,6 +131,33 @@ func (s *Server) run() {\n}\n}\n+// handshake performs version exchange with client. See common.proto for details\n+// about the protocol.\n+func (s *Server) handshake(client *unet.Socket) error {\n+ var in [1024]byte\n+ read, err := client.Read(in[:])\n+ if err != nil {\n+ return fmt.Errorf(\"reading handshake message: %w\", err)\n+ }\n+ hsIn := pb.Handshake{}\n+ if err := proto.Unmarshal(in[:read], &hsIn); err != nil {\n+ return fmt.Errorf(\"unmarshalling handshake message: %w\", err)\n+ }\n+ if hsIn.Version != wire.CurrentVersion {\n+ return fmt.Errorf(\"wrong version number, want: %d, got, %d\", wire.CurrentVersion, hsIn.Version)\n+ }\n+\n+ hsOut := pb.Handshake{Version: s.version}\n+ out, err := proto.Marshal(&hsOut)\n+ if err != nil {\n+ return fmt.Errorf(\"marshalling handshake message: %w\", err)\n+ }\n+ if _, err := client.Write(out); err != nil {\n+ return fmt.Errorf(\"sending handshake message: %w\", err)\n+ }\n+ return nil\n+}\n+\nfunc (s *Server) handleClient(client *unet.Socket) {\ndefer func() {\ns.mu.Lock()\n@@ -144,11 +180,11 @@ func (s *Server) handleClient(client *unet.Socket) {\nif read == 0 {\nreturn\n}\n- if read < header.HeaderStructSize {\n+ if read < wire.HeaderStructSize {\npanic(\"invalid message\")\n}\n- hdr := header.Header{}\n- hdr.UnmarshalUnsafe(buf[0:header.HeaderStructSize])\n+ hdr := wire.Header{}\n+ hdr.UnmarshalUnsafe(buf[0:wire.HeaderStructSize])\nif read < int(hdr.HeaderSize) {\npanic(fmt.Sprintf(\"message truncated, header size: %d, readL %d\", hdr.HeaderSize, read))\n}\n@@ -209,3 +245,8 @@ func (s *Server) WaitForCount(count int) error {\nreturn nil\n}, 5*time.Second)\n}\n+\n+// SetVersion sets the version to be used in handshake.\n+func (s *Server) SetVersion(newVersion uint32) {\n+ s.version = newVersion\n+}\n"
},
{
"change_type": "RENAME",
"old_path": "pkg/sentry/seccheck/checkers/remote/header/BUILD",
"new_path": "pkg/sentry/seccheck/checkers/remote/wire/BUILD",
"diff": "@@ -3,15 +3,15 @@ load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\npackage(licenses = [\"notice\"])\ngo_library(\n- name = \"header\",\n- srcs = [\"header.go\"],\n+ name = \"wire\",\n+ srcs = [\"wire.go\"],\nmarshal = True,\nvisibility = [\"//:sandbox\"],\n)\ngo_test(\n- name = \"header_test\",\n+ name = \"wire_test\",\nsize = \"small\",\n- srcs = [\"header_test.go\"],\n- library = \":header\",\n+ srcs = [\"wire_test.go\"],\n+ library = \":wire\",\n)\n"
},
{
"change_type": "RENAME",
"old_path": "pkg/sentry/seccheck/checkers/remote/header/header.go",
"new_path": "pkg/sentry/seccheck/checkers/remote/wire/wire.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// Package header contains the message header used in the remote checker.\n-package header\n+// Package wire defines structs used in the wire format for the remote checker.\n+package wire\n+\n+// CurrentVersion is the current wire and protocol version.\n+const CurrentVersion = 1\n// HeaderStructSize size of header struct in bytes.\nconst HeaderStructSize = 8\n"
},
{
"change_type": "RENAME",
"old_path": "pkg/sentry/seccheck/checkers/remote/header/header_test.go",
"new_path": "pkg/sentry/seccheck/checkers/remote/wire/wire_test.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-package header\n+package wire\nimport \"testing\"\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/points/common.proto",
"new_path": "pkg/sentry/seccheck/points/common.proto",
"diff": "@@ -16,6 +16,54 @@ syntax = \"proto3\";\npackage gvisor.common;\n+// Handshake message is used when establishing a connection. Version information\n+// is exchanged to determine if the communication can proceed. Each side reports\n+// a single version of the protocol that it supports. If they can't support the\n+// version reported by the peer, they must close the connection. If the peer\n+// version is higher (newer), it should continue to communicate, making the peer\n+// responsible to send messages that are compatible with your version. If the\n+// peer can't support it, the peer should close the connection.\n+//\n+// In short:\n+// 1. sentry and remote exchange versions\n+// 2. sentry continues if remote >= min(sentry)\n+// 3. remote continues if sentry >= min(remote)\n+//\n+// Suppose that peer A is at version 1 and peer B is at 2. Peer A sees that B is\n+// at a newer version and continues with communication. Peer B will see that A\n+// is at version 1 (older) and will check if it can send messages that are\n+// compatible with version 1. If yes, then the communication can continue. If\n+// not, A should close the connection.\n+//\n+// Here are 2 practical examples:\n+// 1. New field added to the header: this requires a change in protocol\n+// version (e.g. 1 => 2). However, if not essential to communication, the\n+// new field can be ignored by a peer that is still using version 1.\n+// Sentry version 1, remote version 2: remote doesn't get the new field,\n+// but can still receive messages.\n+// Sentry version 2, remote version 1: remote gets the new field, but\n+// ignores it since it's not aware the field exists yet. Note that remote\n+// must rely on header length to determine where the payload is.\n+//\n+// 2. Change in message format for batching: this requires a change in\n+// protocol version (2 => 3). Batching can only be used if both sides can\n+// handle it.\n+// Sentry version 2, remote version 3: remote gets a message at a time. If\n+// it still can do that, remote can accept that sentry is in version 2.\n+// Sentry version 3, remote version 2: remote is not able to process\n+// batched messages. If the sentry can still produce one message at a time\n+// the communication can continue, otherwise the sentry should close the\n+// connection.\n+//\n+// Note that addition of new message types do not require version changes.\n+// Server implementations should gracefully handle messages that it doesn't\n+// understand. Similarly, payload for message can change following protobuf\n+// rules for compatibilty. For example, adding new fields to a protobuf type\n+// doesn't require version bump.\n+message Handshake {\n+ uint32 version = 1;\n+}\n+\nmessage Credentials {\nuint32 real_uid = 1;\nuint32 effective_uid = 2;\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add version handshake before communication is stablished
Details on how it works is in wire.Handshake.
Updates #4805
PiperOrigin-RevId: 448552448 |
260,004 | 13.05.2022 13:51:56 | 25,200 | ae508f406429537e77252fcc7336460a7a653a87 | Track packets dropped by full device TX queue
QDisc/LinkEndpoint may drop packets if the device's send/transmit queue
is full.
BUG: | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/netstack.go",
"new_path": "pkg/sentry/socket/netstack/netstack.go",
"diff": "@@ -88,6 +88,7 @@ var Metrics = tcpip.Stats{\nPackets: mustCreateMetric(\"/netstack/nic/tx/packets\", \"Number of packets transmitted.\"),\nBytes: mustCreateMetric(\"/netstack/nic/tx/bytes\", \"Number of bytes transmitted.\"),\n},\n+ TxPacketsDroppedNoBufferSpace: mustCreateMetric(\"/netstack/nic/tx_packets_dropped_no_buffer_space\", \"Number of TX packets dropped as a result of no buffer space errors.\"),\nRx: tcpip.NICPacketStats{\nPackets: mustCreateMetric(\"/netstack/nic/rx/packets\", \"Number of packets received.\"),\nBytes: mustCreateMetric(\"/netstack/nic/rx/bytes\", \"Number of bytes received.\"),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic.go",
"new_path": "pkg/tcpip/stack/nic.go",
"diff": "@@ -394,6 +394,9 @@ func (n *nic) writePacket(pkt *PacketBuffer) tcpip.Error {\nfunc (n *nic) writeRawPacket(pkt *PacketBuffer) tcpip.Error {\nif err := n.qDisc.WritePacket(pkt); err != nil {\n+ if _, ok := err.(*tcpip.ErrNoBufferSpace); ok {\n+ n.stats.txPacketsDroppedNoBufferSpace.Increment()\n+ }\nreturn err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic_stats.go",
"new_path": "pkg/tcpip/stack/nic_stats.go",
"diff": "@@ -56,6 +56,7 @@ type multiCounterNICStats struct {\nunknownL4ProtocolRcvdPacketCounts tcpip.MultiIntegralStatCounterMap\nmalformedL4RcvdPackets tcpip.MultiCounterStat\ntx multiCounterNICPacketStats\n+ txPacketsDroppedNoBufferSpace tcpip.MultiCounterStat\nrx multiCounterNICPacketStats\ndisabledRx multiCounterNICPacketStats\nneighbor multiCounterNICNeighborStats\n@@ -66,6 +67,7 @@ func (m *multiCounterNICStats) init(a, b *tcpip.NICStats) {\nm.unknownL4ProtocolRcvdPacketCounts.Init(a.UnknownL4ProtocolRcvdPacketCounts, b.UnknownL4ProtocolRcvdPacketCounts)\nm.malformedL4RcvdPackets.Init(a.MalformedL4RcvdPackets, b.MalformedL4RcvdPackets)\nm.tx.init(&a.Tx, &b.Tx)\n+ m.txPacketsDroppedNoBufferSpace.Init(a.TxPacketsDroppedNoBufferSpace, b.TxPacketsDroppedNoBufferSpace)\nm.rx.init(&a.Rx, &b.Rx)\nm.disabledRx.init(&a.DisabledRx, &b.DisabledRx)\nm.neighbor.init(&a.Neighbor, &b.Neighbor)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -2103,6 +2103,13 @@ type NICStats struct {\n// Tx contains statistics about transmitted packets.\nTx NICPacketStats\n+ // TxPacketsDroppedNoBufferSpace is the number of packets dropepd due to the\n+ // NIC not having enough buffer space to send the packet.\n+ //\n+ // Packets may be dropped with a no buffer space error when the device TX\n+ // queue is full.\n+ TxPacketsDroppedNoBufferSpace *StatCounter\n+\n// Rx contains statistics about received packets.\nRx NICPacketStats\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/datagram_test.go",
"new_path": "pkg/tcpip/transport/datagram_test.go",
"diff": "@@ -468,7 +468,29 @@ func TestDeviceReturnErrNoBufferSpace(t *testing.T) {\nt.Fatalf(\"ep.Connect(%#v): %s\", to, err)\n}\n- ops := ep.SocketOptions()\n+ stackTxPacketsDroppedNoBufferSpace := s.Stats().NICs.TxPacketsDroppedNoBufferSpace\n+\n+ nicsInfo := s.NICInfo()\n+ nicInfo, ok := nicsInfo[nicID]\n+ if !ok {\n+ t.Fatalf(\"expected NICInfo for nicID=%d; got s.NICInfo() = %#v\", nicID, nicsInfo)\n+ }\n+ nicTxPacketsDroppedNoBufferSpace := nicInfo.Stats.TxPacketsDroppedNoBufferSpace\n+\n+ checkStats := func(want uint64) {\n+ t.Helper()\n+\n+ if got := stackTxPacketsDroppedNoBufferSpace.Value(); got != want {\n+ t.Errorf(\"got stackTxPacketsDroppedNoBufferSpace.Value() = %d, want = %d\", got, want)\n+ }\n+ if got := nicTxPacketsDroppedNoBufferSpace.Value(); got != want {\n+ t.Errorf(\"got nicTxPacketsDroppedNoBufferSpace.Value() = %d, want = %d\", got, want)\n+ }\n+ }\n+\n+ droppedPkts := uint64(0)\n+ checkStats(droppedPkts)\n+\ncheckWrite := func(netProto tcpip.NetworkProtocolNumber) {\nt.Helper()\n@@ -481,8 +503,12 @@ func TestDeviceReturnErrNoBufferSpace(t *testing.T) {\nif n, err := ep.Write(&r, tcpip.WriteOptions{}); err != wantErr {\nt.Fatalf(\"got Write(...) = (%d, %s), want = (_, %s)\", n, err, wantErr)\n}\n+\n+ droppedPkts++\n+ checkStats(droppedPkts)\n}\n+ ops := ep.SocketOptions()\nops.SetIPv4RecvError(true)\ncheckWrite(ipv4.ProtocolNumber)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Track packets dropped by full device TX queue
QDisc/LinkEndpoint may drop packets if the device's send/transmit queue
is full.
BUG: https://fxbug.dev/98974
PiperOrigin-RevId: 448570489 |
260,009 | 13.05.2022 14:22:01 | 25,200 | 3b83c30622c043d57a393b26018ad6a41b924684 | Fix regression in KVM due to metric in machine.Get().
Replaced timer metric with counter, which seems to give similar performance to
removing the metric outright. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine.go",
"new_path": "pkg/sentry/platform/kvm/machine.go",
"diff": "@@ -124,11 +124,10 @@ var (\nmmapCallCounter = metric.MustCreateNewUint64Metric(\n\"/kvm/mmap_calls\", false, \"The number of times seccompMmapSyscall has been called.\")\n- // getVCPUFastPathDuration are durations of acquiring a VCPU\n- // (using machine.Get()).\n- getVCPUDuration = metric.MustRegisterTimerMetric(\"/kvm/get_vcpu\",\n- metric.NewExponentialBucketer(20, uint64(time.Nanosecond*10), 1, 2),\n- \"Duration of acquiring a VCPU, not including the fastest reuse path.\",\n+ // getVCPUCounter is a metric that tracks how many times different paths of\n+ // machine.Get() are triggered.\n+ getVCPUCounter = metric.MustCreateNewUint64Metric(\n+ \"/kvm/get_vcpu\", false, \"The number of times that machine.Get() was called, split by path the function took.\",\nmetric.NewField(\"acquisition_type\", []string{\"fast_reused\", \"reused\", \"unused\", \"stolen\"}))\n// asInvalidateDuration are durations of calling addressSpace.invalidate().\n@@ -441,8 +440,6 @@ func (m *machine) Destroy() {\n// the corrent context in guest, the vCPU of it must be the same as what\n// Get() returns.\nfunc (m *machine) Get() *vCPU {\n- timer := getVCPUDuration.Start()\n-\nm.mu.RLock()\nruntime.LockOSThread()\ntid := procid.Current()\n@@ -451,7 +448,7 @@ func (m *machine) Get() *vCPU {\nif c := m.vCPUsByTID[tid]; c != nil {\nc.lock()\nm.mu.RUnlock()\n- timer.Finish(\"fast_reused\")\n+ getVCPUCounter.Increment(\"fast_reused\")\nreturn c\n}\n@@ -471,7 +468,7 @@ func (m *machine) Get() *vCPU {\nif c := m.vCPUsByTID[tid]; c != nil {\nc.lock()\nm.mu.Unlock()\n- timer.Finish(\"reused\")\n+ getVCPUCounter.Increment(\"reused\")\nreturn c\n}\n@@ -484,7 +481,7 @@ func (m *machine) Get() *vCPU {\nm.vCPUsByTID[tid] = c\nm.mu.Unlock()\nc.loadSegments(tid)\n- timer.Finish(\"unused\")\n+ getVCPUCounter.Increment(\"unused\")\nreturn c\n}\n@@ -495,7 +492,7 @@ func (m *machine) Get() *vCPU {\nm.vCPUsByTID[tid] = c\nm.mu.Unlock()\nc.loadSegments(tid)\n- timer.Finish(\"unused\")\n+ getVCPUCounter.Increment(\"unused\")\nreturn c\n}\n}\n@@ -523,7 +520,7 @@ func (m *machine) Get() *vCPU {\nm.vCPUsByTID[tid] = c\nm.mu.Unlock()\nc.loadSegments(tid)\n- timer.Finish(\"stolen\")\n+ getVCPUCounter.Increment(\"stolen\")\nreturn c\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix regression in KVM due to metric in machine.Get().
Replaced timer metric with counter, which seems to give similar performance to
removing the metric outright.
PiperOrigin-RevId: 448576866 |
260,000 | 16.05.2022 12:37:21 | 25,200 | ba4d6451635181d96a424d9a2644db4dba17084c | Add debug.SetTraceback for runsc-gofer
The -traceback flag sets the Debug.SetTraceback for runsc-sandbox.
We need this for gofer too. Fixes | [
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/gofer.go",
"new_path": "runsc/cmd/gofer.go",
"diff": "@@ -20,6 +20,7 @@ import (\n\"fmt\"\n\"os\"\n\"path/filepath\"\n+ \"runtime/debug\"\n\"strings\"\n\"github.com/google/subcommands\"\n@@ -99,6 +100,9 @@ func (g *Gofer) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\nconf := args[0].(*config.Config)\n+ // Set traceback level\n+ debug.SetTraceback(conf.Traceback)\n+\nspecFile := os.NewFile(uintptr(g.specFD), \"spec file\")\ndefer specFile.Close()\nspec, err := specutils.ReadSpecFromFile(g.bundleDir, specFile, conf)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add debug.SetTraceback for runsc-gofer
The -traceback flag sets the Debug.SetTraceback for runsc-sandbox.
We need this for gofer too. Fixes #7583 |
259,853 | 16.05.2022 15:09:21 | 25,200 | 58e9ba2724a7b8e07cdd4d2915119ee11d02f830 | buildkite: don't run docker tests on COS
On COS, buildkite agents are running inside docker containers and so
we can't modify a docker config and restart a docker daemon. | [
{
"change_type": "MODIFY",
"old_path": ".buildkite/hooks/pre-command",
"new_path": ".buildkite/hooks/pre-command",
"diff": "@@ -39,6 +39,9 @@ fi\n# Clear existing profiles.\nsudo rm -rf /tmp/profile\n+# Allow to read dmesg for all users. It is required for the syslog test.\n+sudo sysctl -w kernel.dmesg_restrict=0\n+\n# Download credentials, if a release agent.\nif test \"${BUILDKITE_AGENT_META_DATA_QUEUE}\" = \"release\"; then\n# Pull down secrets.\n"
},
{
"change_type": "MODIFY",
"old_path": ".buildkite/pipeline.yaml",
"new_path": ".buildkite/pipeline.yaml",
"diff": "@@ -177,27 +177,32 @@ steps:\nagents:\narch: \"amd64\"\ncgroup: \"v1\"\n+ os: \"ubuntu\"\n- <<: *common\nlabel: \":docker: Docker tests (cgroupv2)\"\ncommand: make docker-tests\nagents:\narch: \"amd64\"\ncgroup: \"v2\"\n+ os: \"ubuntu\"\n- <<: *common\nlabel: \":goggles: Overlay tests\"\ncommand: make overlay-tests\nagents:\narch: \"amd64\"\n+ os: \"ubuntu\"\n- <<: *common\nlabel: \":safety_pin: Host network tests\"\ncommand: make hostnet-tests\nagents:\narch: \"amd64\"\n+ os: \"ubuntu\"\n- <<: *common\nlabel: \":satellite: SWGSO tests\"\ncommand: make swgso-tests\nagents:\narch: \"amd64\"\n+ os: \"ubuntu\"\n- <<: *common\nlabel: \":coffee: Do tests\"\ncommand: make do-tests\n@@ -208,45 +213,53 @@ steps:\ncommand: make kvm-tests\nagents:\narch: \"amd64\"\n+ kvm: \"true\"\n- <<: *common\nlabel: \":weight_lifter: Fsstress test\"\ncommand: make fsstress-test\nagents:\narch: \"amd64\"\n+ os: \"ubuntu\"\n- <<: *common\nlabel: \":docker: Containerd 1.3.9 tests\"\ncommand: make containerd-test-1.3.9\nagents:\narch: \"amd64\"\n+ os: \"ubuntu\"\n- <<: *common\nlabel: \":docker: Containerd 1.4.3 tests\"\ncommand: make containerd-test-1.4.3\nagents:\narch: \"amd64\"\n+ os: \"ubuntu\"\n- <<: *common\nlabel: \":docker: Containerd 1.5.4 tests (cgroupv1)\"\ncommand: make containerd-test-1.5.4\nagents:\ncgroup: \"v1\"\narch: \"amd64\"\n+ os: \"ubuntu\"\n- <<: *common\nlabel: \":docker: Containerd 1.5.4 tests (cgroupv2)\"\ncommand: make containerd-test-1.5.4\nagents:\ncgroup: \"v2\"\narch: \"amd64\"\n+ os: \"ubuntu\"\n- <<: *common\nlabel: \":docker: Containerd 1.6.0-rc.4 tests (cgroupv1)\"\ncommand: make containerd-test-1.6.0-rc.4\nagents:\ncgroup: \"v1\"\narch: \"amd64\"\n+ os: \"ubuntu\"\n- <<: *common\nlabel: \":docker: Containerd 1.6.0-rc.4 tests (cgroupv2)\"\ncommand: make containerd-test-1.6.0-rc.4\nagents:\ncgroup: \"v2\"\narch: \"amd64\"\n+ os: \"ubuntu\"\n# Check the website builds.\n- <<: *common\n@@ -257,12 +270,18 @@ steps:\n- <<: *common\nlabel: \":table_tennis_paddle_and_ball: IPTables tests\"\ncommand: make iptables-tests\n+ agents:\n+ os: \"ubuntu\"\n- <<: *common\nlabel: \":construction_worker: Packetdrill tests\"\ncommand: make packetdrill-tests\n+ agents:\n+ os: \"ubuntu\"\n- <<: *common\nlabel: \":hammer: Packetimpact tests\"\ncommand: make packetimpact-tests\n+ agents:\n+ os: \"ubuntu\"\n# Runtime tests.\n- <<: *common\n@@ -271,30 +290,35 @@ steps:\nparallelism: 10\nagents:\narch: \"amd64\"\n+ os: \"ubuntu\"\n- <<: *common\nlabel: \":java: Java runtime tests\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} java17-runtime-tests\nparallelism: 40\nagents:\narch: \"amd64\"\n+ os: \"ubuntu\"\n- <<: *common\nlabel: \":golang: Go runtime tests\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} go1.16-runtime-tests\nparallelism: 10\nagents:\narch: \"amd64\"\n+ os: \"ubuntu\"\n- <<: *common\nlabel: \":node: NodeJS runtime tests\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} nodejs16.13.2-runtime-tests\nparallelism: 10\nagents:\narch: \"amd64\"\n+ os: \"ubuntu\"\n- <<: *common\nlabel: \":python: Python runtime tests\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} python3.10.2-runtime-tests\nparallelism: 10\nagents:\narch: \"amd64\"\n+ os: \"ubuntu\"\n# Runtime tests (LISAFS).\n- <<: *common\n@@ -304,6 +328,7 @@ steps:\nif: build.message =~ /lisafs/ || build.branch == \"master\"\nagents:\narch: \"amd64\"\n+ os: \"ubuntu\"\n- <<: *common\nlabel: \":java: Java runtime tests (LISAFS)\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} java17-runtime-tests_lisafs\n@@ -311,6 +336,7 @@ steps:\nif: build.message =~ /lisafs/ || build.branch == \"master\"\nagents:\narch: \"amd64\"\n+ os: \"ubuntu\"\n- <<: *common\nlabel: \":golang: Go runtime tests (LISAFS)\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} go1.16-runtime-tests_lisafs\n@@ -318,6 +344,7 @@ steps:\nif: build.message =~ /lisafs/ || build.branch == \"master\"\nagents:\narch: \"amd64\"\n+ os: \"ubuntu\"\n- <<: *common\nlabel: \":node: NodeJS runtime tests (LISAFS)\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} nodejs16.13.2-runtime-tests_lisafs\n@@ -325,6 +352,7 @@ steps:\nif: build.message =~ /lisafs/ || build.branch == \"master\"\nagents:\narch: \"amd64\"\n+ os: \"ubuntu\"\n- <<: *common\nlabel: \":python: Python runtime tests (LISAFS)\"\ncommand: make RUNTIME_LOG_DIR=/tmp/$${BUILDKITE_JOB_ID} python3.10.2-runtime-tests_lisafs\n@@ -332,6 +360,7 @@ steps:\nif: build.message =~ /lisafs/ || build.branch == \"master\"\nagents:\narch: \"amd64\"\n+ os: \"ubuntu\"\n# Build everything.\n- <<: *common\n"
}
] | Go | Apache License 2.0 | google/gvisor | buildkite: don't run docker tests on COS
On COS, buildkite agents are running inside docker containers and so
we can't modify a docker config and restart a docker daemon.
PiperOrigin-RevId: 449063929 |
259,853 | 16.05.2022 20:12:56 | 25,200 | 251f2c0561bd91db414658c37db8b25afa7cfc40 | mm: use lockdep mutexes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/BUILD",
"new_path": "pkg/sentry/mm/BUILD",
"diff": "load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\nload(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\n+load(\"//pkg/sync/locking:locking.bzl\", \"declare_mutex\", \"declare_rwmutex\")\npackage(licenses = [\"notice\"])\n+declare_mutex(\n+ name = \"aio_context_mutex\",\n+ out = \"aio_context_mutex.go\",\n+ package = \"mm\",\n+ prefix = \"aioContext\",\n+)\n+\n+declare_mutex(\n+ name = \"aio_manager_mutex\",\n+ out = \"aio_manager_mutex.go\",\n+ package = \"mm\",\n+ prefix = \"aioManager\",\n+)\n+\n+declare_rwmutex(\n+ name = \"mapping_mutex\",\n+ out = \"mapping_mutex.go\",\n+ package = \"mm\",\n+ prefix = \"mapping\",\n+)\n+\n+declare_rwmutex(\n+ name = \"active_mutex\",\n+ out = \"active_mutex.go\",\n+ package = \"mm\",\n+ prefix = \"active\",\n+)\n+\n+declare_mutex(\n+ name = \"metadata_mutex\",\n+ out = \"metadata_mutex.go\",\n+ package = \"mm\",\n+ prefix = \"metadata\",\n+)\n+\n+declare_mutex(\n+ name = \"private_refs_mutex\",\n+ out = \"private_refs_mutex.go\",\n+ package = \"mm\",\n+ prefix = \"privateRefs\",\n+)\n+\ngo_template_instance(\nname = \"file_refcount_set\",\nout = \"file_refcount_set.go\",\n@@ -98,19 +141,25 @@ go_template_instance(\ngo_library(\nname = \"mm\",\nsrcs = [\n+ \"active_mutex.go\",\n\"address_space.go\",\n\"aio_context.go\",\n+ \"aio_context_mutex.go\",\n\"aio_context_state.go\",\n+ \"aio_manager_mutex.go\",\n\"aio_mappable_refs.go\",\n\"debug.go\",\n\"file_refcount_set.go\",\n\"io.go\",\n\"io_list.go\",\n\"lifecycle.go\",\n+ \"mapping_mutex.go\",\n\"metadata.go\",\n+ \"metadata_mutex.go\",\n\"mm.go\",\n\"pma.go\",\n\"pma_set.go\",\n+ \"private_refs_mutex.go\",\n\"procfs.go\",\n\"save_restore.go\",\n\"shm.go\",\n@@ -144,6 +193,7 @@ go_library(\n\"//pkg/sentry/platform\",\n\"//pkg/sentry/usage\",\n\"//pkg/sync\",\n+ \"//pkg/sync/locking\",\n\"//pkg/tcpip/buffer\",\n\"//pkg/usermem\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/aio_context.go",
"new_path": "pkg/sentry/mm/aio_context.go",
"diff": "@@ -22,7 +22,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/memmap\"\n\"gvisor.dev/gvisor/pkg/sentry/pgalloc\"\n\"gvisor.dev/gvisor/pkg/sentry/usage\"\n- \"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n@@ -31,7 +30,7 @@ import (\n// +stateify savable\ntype aioManager struct {\n// mu protects below.\n- mu sync.Mutex `state:\"nosave\"`\n+ mu aioManagerMutex `state:\"nosave\"`\n// aioContexts is the set of asynchronous I/O contexts.\ncontexts map[uint64]*AIOContext\n@@ -108,7 +107,7 @@ type AIOContext struct {\nrequestReady chan struct{} `state:\"nosave\"`\n// mu protects below.\n- mu sync.Mutex `state:\"nosave\"`\n+ mu aioContextMutex `state:\"nosave\"`\n// results is the set of completed requests.\nresults ioList\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/debug.go",
"new_path": "pkg/sentry/mm/debug.go",
"diff": "@@ -40,10 +40,11 @@ func (mm *MemoryManager) String() string {\n// DebugString returns a string containing information about mm for debugging.\nfunc (mm *MemoryManager) DebugString(ctx context.Context) string {\n- mm.mappingMu.RLock()\n- defer mm.mappingMu.RUnlock()\n- mm.activeMu.RLock()\n- defer mm.activeMu.RUnlock()\n+ // FIXME(b/207524689): replace RLockBypass with RLock.\n+ mm.mappingMu.RLockBypass()\n+ defer mm.mappingMu.RUnlockBypass()\n+ mm.activeMu.RLockBypass()\n+ defer mm.activeMu.RUnlockBypass()\nreturn mm.debugStringLocked(ctx)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/lifecycle.go",
"new_path": "pkg/sentry/mm/lifecycle.go",
"diff": "@@ -141,8 +141,8 @@ func (mm *MemoryManager) Fork(ctx context.Context) (*MemoryManager, error) {\n// mm/memory.c:copy_page_range().)\nmm2.activeMu.Lock()\ndefer mm2.activeMu.Unlock()\n- mm.activeMu.Lock()\n- defer mm.activeMu.Unlock()\n+ mm.activeMu.NestedLock()\n+ defer mm.activeMu.NestedUnlock()\nif dontforks {\ndefer mm.pmas.MergeRange(mm.applicationAddrRange())\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/mm.go",
"new_path": "pkg/sentry/mm/mm.go",
"diff": "@@ -47,7 +47,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/memmap\"\n\"gvisor.dev/gvisor/pkg/sentry/pgalloc\"\n\"gvisor.dev/gvisor/pkg/sentry/platform\"\n- \"gvisor.dev/gvisor/pkg/sync\"\n)\n// MemoryManager implements a virtual address space.\n@@ -83,7 +82,7 @@ type MemoryManager struct {\nusers atomicbitops.Int32\n// mappingMu is analogous to Linux's struct mm_struct::mmap_sem.\n- mappingMu sync.RWMutex `state:\"nosave\"`\n+ mappingMu mappingRWMutex `state:\"nosave\"`\n// vmas stores virtual memory areas. Since vmas are stored by value,\n// clients should usually use vmaIterator.ValuePtr() instead of\n@@ -126,7 +125,7 @@ type MemoryManager struct {\n// activeMu is loosely analogous to Linux's struct\n// mm_struct::page_table_lock.\n- activeMu sync.RWMutex `state:\"nosave\"`\n+ activeMu activeRWMutex `state:\"nosave\"`\n// pmas stores platform mapping areas used to implement vmas. Since pmas\n// are stored by value, clients should usually use pmaIterator.ValuePtr()\n@@ -198,7 +197,7 @@ type MemoryManager struct {\n// by metadataMu.\ndumpability atomicbitops.Int32\n- metadataMu sync.Mutex `state:\"nosave\"`\n+ metadataMu metadataMutex `state:\"nosave\"`\n// argv is the application argv. This is set up by the loader and may be\n// modified by prctl(PR_SET_MM_ARG_START/PR_SET_MM_ARG_END). No\n@@ -482,7 +481,7 @@ type pma struct {\n// +stateify savable\ntype privateRefs struct {\n- mu sync.Mutex `state:\"nosave\"`\n+ mu privateRefsMutex `state:\"nosave\"`\n// refs maps offsets into MemoryManager.mfp.MemoryFile() to the number of\n// pmas (or, equivalently, MemoryManagers) that share ownership of the\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/procfs.go",
"new_path": "pkg/sentry/mm/procfs.go",
"diff": "@@ -60,8 +60,9 @@ func (mm *MemoryManager) NeedsUpdate(generation int64) bool {\n// ReadMapsDataInto is called by fsimpl/proc.mapsData.Generate to\n// implement /proc/[pid]/maps.\nfunc (mm *MemoryManager) ReadMapsDataInto(ctx context.Context, buf *bytes.Buffer) {\n- mm.mappingMu.RLock()\n- defer mm.mappingMu.RUnlock()\n+ // FIXME(b/207524689): replace RLockBypass with RLock.\n+ mm.mappingMu.RLockBypass()\n+ defer mm.mappingMu.RUnlockBypass()\nvar start hostarch.Addr\nfor vseg := mm.vmas.LowerBoundSegment(start); vseg.Ok(); vseg = vseg.NextSegment() {\n@@ -85,8 +86,9 @@ func (mm *MemoryManager) ReadMapsDataInto(ctx context.Context, buf *bytes.Buffer\n// ReadMapsSeqFileData is called by fs/proc.mapsData.ReadSeqFileData to\n// implement /proc/[pid]/maps.\nfunc (mm *MemoryManager) ReadMapsSeqFileData(ctx context.Context, handle seqfile.SeqHandle) ([]seqfile.SeqData, int64) {\n- mm.mappingMu.RLock()\n- defer mm.mappingMu.RUnlock()\n+ // FIXME(b/207524689): replace RLockBypass with RLock.\n+ mm.mappingMu.RLockBypass()\n+ defer mm.mappingMu.RUnlockBypass()\nvar data []seqfile.SeqData\nvar start hostarch.Addr\nif handle != nil {\n@@ -175,8 +177,9 @@ func (mm *MemoryManager) appendVMAMapsEntryLocked(ctx context.Context, vseg vmaI\n// ReadSmapsDataInto is called by fsimpl/proc.smapsData.Generate to\n// implement /proc/[pid]/maps.\nfunc (mm *MemoryManager) ReadSmapsDataInto(ctx context.Context, buf *bytes.Buffer) {\n- mm.mappingMu.RLock()\n- defer mm.mappingMu.RUnlock()\n+ // FIXME(b/207524689): replace RLockBypass with RLock.\n+ mm.mappingMu.RLockBypass()\n+ defer mm.mappingMu.RUnlockBypass()\nvar start hostarch.Addr\nfor vseg := mm.vmas.LowerBoundSegment(start); vseg.Ok(); vseg = vseg.NextSegment() {\n@@ -193,8 +196,9 @@ func (mm *MemoryManager) ReadSmapsDataInto(ctx context.Context, buf *bytes.Buffe\n// ReadSmapsSeqFileData is called by fs/proc.smapsData.ReadSeqFileData to\n// implement /proc/[pid]/smaps.\nfunc (mm *MemoryManager) ReadSmapsSeqFileData(ctx context.Context, handle seqfile.SeqHandle) ([]seqfile.SeqData, int64) {\n- mm.mappingMu.RLock()\n- defer mm.mappingMu.RUnlock()\n+ // FIXME(b/207524689): replace RLockBypass with RLock.\n+ mm.mappingMu.RLockBypass()\n+ defer mm.mappingMu.RUnlockBypass()\nvar data []seqfile.SeqData\nvar start hostarch.Addr\nif handle != nil {\n@@ -238,7 +242,8 @@ func (mm *MemoryManager) vmaSmapsEntryIntoLocked(ctx context.Context, vseg vmaIt\n// requiring it to be locked as a precondition, to reduce the latency\n// impact of reading /proc/[pid]/smaps on concurrent performance-sensitive\n// operations requiring activeMu for writing like faults.\n- mm.activeMu.RLock()\n+ // FIXME(b/207524689): replace RLockBypass with RLock.\n+ mm.activeMu.RLockBypass()\nvar rss uint64\nvar anon uint64\nvsegAR := vseg.Range()\n@@ -250,7 +255,7 @@ func (mm *MemoryManager) vmaSmapsEntryIntoLocked(ctx context.Context, vseg vmaIt\nanon += size\n}\n}\n- mm.activeMu.RUnlock()\n+ mm.activeMu.RUnlockBypass()\nfmt.Fprintf(b, \"Size: %8d kB\\n\", vseg.Range().Length()/1024)\nfmt.Fprintf(b, \"Rss: %8d kB\\n\", rss/1024)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/syscalls.go",
"new_path": "pkg/sentry/mm/syscalls.go",
"diff": "@@ -1285,8 +1285,9 @@ func (mm *MemoryManager) ResidentSetSize() uint64 {\n// MaxResidentSetSize returns the value advertised as mm's max RSS in bytes.\nfunc (mm *MemoryManager) MaxResidentSetSize() uint64 {\n- mm.activeMu.RLock()\n- defer mm.activeMu.RUnlock()\n+ // FIXME(b/229424837): Repalce RLockBypass with RLock.\n+ mm.activeMu.RLockBypass()\n+ defer mm.activeMu.RUnlockBypass()\nreturn mm.maxRSS\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | mm: use lockdep mutexes
PiperOrigin-RevId: 449117356 |
259,853 | 17.05.2022 22:48:10 | 25,200 | 2ed45d09645283d358d393b05661df72e6b0de50 | buildkite: run "Release tests" on amd64
This test fails on arm64:
ERROR: vdso/BUILD:12:8: Executing genrule //vdso:vdso failed: (Exit 1):
bash failed: error executing command /bin/bash -c ...
Use --sandbox_debug to see verbose messages from the sandbox
gcc: error: unrecognized command line option '-m64'
Target //runsc:runsc failed to build | [
{
"change_type": "MODIFY",
"old_path": ".buildkite/pipeline.yaml",
"new_path": ".buildkite/pipeline.yaml",
"diff": "@@ -111,6 +111,8 @@ steps:\n- make BAZEL_OPTIONS=--config=x86_64 artifacts/x86_64\n- make BAZEL_OPTIONS=--config=aarch64 artifacts/aarch64\n- make release\n+ agents:\n+ arch: \"amd64\"\n# Images tests.\n- <<: *common\n@@ -224,6 +226,7 @@ steps:\nlabel: \":docker: Containerd 1.3.9 tests\"\ncommand: make containerd-test-1.3.9\nagents:\n+ cgroup: \"v1\"\narch: \"amd64\"\nos: \"ubuntu\"\n- <<: *common\n"
}
] | Go | Apache License 2.0 | google/gvisor | buildkite: run "Release tests" on amd64
This test fails on arm64:
ERROR: vdso/BUILD:12:8: Executing genrule //vdso:vdso failed: (Exit 1):
bash failed: error executing command /bin/bash -c ...
Use --sandbox_debug to see verbose messages from the sandbox
gcc: error: unrecognized command line option '-m64'
Target //runsc:runsc failed to build
PiperOrigin-RevId: 449398920 |
259,907 | 18.05.2022 00:52:48 | 25,200 | bda5ce7977bd88379ba59291e2a9ef04a98ce239 | Simplify codebase.
Ran gofmt -w -s ./ | [
{
"change_type": "MODIFY",
"old_path": "pkg/cpuid/cpuid_test.go",
"new_path": "pkg/cpuid/cpuid_test.go",
"diff": "@@ -18,7 +18,7 @@ import \"testing\"\nfunc TestFeatureFromString(t *testing.T) {\n// Check that known features do match.\n- for feature, _ := range allFeatures {\n+ for feature := range allFeatures {\nf, ok := FeatureFromString(feature.String())\nif f != feature || !ok {\nt.Errorf(\"got %v, %v want %v, true\", f, ok, feature)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/lock/lock_test.go",
"new_path": "pkg/sentry/fs/lock/lock_test.go",
"diff": "@@ -92,15 +92,15 @@ func TestCanLock(t *testing.T) {\n// 0 1024 2048 3072 4096\nl := fill([]entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{1: OwnerInfo{}, 2: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{1: {}, 2: {}}},\nLockRange: LockRange{0, 1024},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{1: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{1: {}}},\nLockRange: LockRange{1024, 2048},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{1: OwnerInfo{}, 3: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{1: {}, 3: {}}},\nLockRange: LockRange{2048, 3072},\n},\n{\n@@ -217,7 +217,7 @@ func TestSetLock(t *testing.T) {\n// 0 max uint64\nafter: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{0, LockEOF},\n},\n},\n@@ -261,7 +261,7 @@ func TestSetLock(t *testing.T) {\n// 0 4096 max uint64\nafter: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{0, 4096},\n},\n{\n@@ -278,7 +278,7 @@ func TestSetLock(t *testing.T) {\n// 0 max uint64\nbefore: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{0, LockEOF},\n},\n},\n@@ -296,7 +296,7 @@ func TestSetLock(t *testing.T) {\nLockRange: LockRange{0, 4096},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{4096, LockEOF},\n},\n},\n@@ -327,7 +327,7 @@ func TestSetLock(t *testing.T) {\n// 0 max uint64\nbefore: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{0, LockEOF},\n},\n},\n@@ -345,7 +345,7 @@ func TestSetLock(t *testing.T) {\n// 0 max uint64\nbefore: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{0, LockEOF},\n},\n},\n@@ -359,11 +359,11 @@ func TestSetLock(t *testing.T) {\n// 0 4096 max uint64\nafter: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}, 1: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}, 1: {}}},\nLockRange: LockRange{0, 4096},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{4096, LockEOF},\n},\n},\n@@ -376,7 +376,7 @@ func TestSetLock(t *testing.T) {\n// 0 max uint64\nbefore: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{0, LockEOF},\n},\n},\n@@ -390,15 +390,15 @@ func TestSetLock(t *testing.T) {\n// 0 4096 8192 max uint64\nafter: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{0, 4096},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}, 1: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}, 1: {}}},\nLockRange: LockRange{4096, 8192},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{8192, LockEOF},\n},\n},\n@@ -411,7 +411,7 @@ func TestSetLock(t *testing.T) {\n// 0 1024 max uint64\nbefore: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{1024, LockEOF},\n},\n},\n@@ -425,7 +425,7 @@ func TestSetLock(t *testing.T) {\n// 0 max uint64\nafter: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{0, LockEOF},\n},\n},\n@@ -438,7 +438,7 @@ func TestSetLock(t *testing.T) {\n// 0 4096\nbefore: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{0, 4096},\n},\n},\n@@ -457,11 +457,11 @@ func TestSetLock(t *testing.T) {\n// 0 max uint64\nafter: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{0, 1024},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{1024, LockEOF},\n},\n},\n@@ -474,7 +474,7 @@ func TestSetLock(t *testing.T) {\n// 0 1024 max uint64\nbefore: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{1024, LockEOF},\n},\n},\n@@ -488,15 +488,15 @@ func TestSetLock(t *testing.T) {\n// 0 1024 4096 max uint64\nafter: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{1: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{1: {}}},\nLockRange: LockRange{0, 1024},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}, 1: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}, 1: {}}},\nLockRange: LockRange{1024, 4096},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{4096, LockEOF},\n},\n},\n@@ -509,15 +509,15 @@ func TestSetLock(t *testing.T) {\n// 0 1024 2048 4096 max uint64\nbefore: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}, 1: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}, 1: {}}},\nLockRange: LockRange{0, 1024},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{1024, 2048},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}, 2: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}, 2: {}}},\nLockRange: LockRange{4096, LockEOF},\n},\n},\n@@ -531,7 +531,7 @@ func TestSetLock(t *testing.T) {\n// 0 1024 4096 max uint64\nafter: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}, 1: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}, 1: {}}},\nLockRange: LockRange{0, 1024},\n},\n{\n@@ -539,7 +539,7 @@ func TestSetLock(t *testing.T) {\nLockRange: LockRange{1024, 4096},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}, 2: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}, 2: {}}},\nLockRange: LockRange{4096, LockEOF},\n},\n},\n@@ -552,15 +552,15 @@ func TestSetLock(t *testing.T) {\n// 0 1024 2048 4096 max uint64\nbefore: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}, 1: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}, 1: {}}},\nLockRange: LockRange{0, 1024},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{1024, 2048},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}, 2: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}, 2: {}}},\nLockRange: LockRange{4096, LockEOF},\n},\n},\n@@ -574,7 +574,7 @@ func TestSetLock(t *testing.T) {\n// 0 1024 3072 4096 max uint64\nafter: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}, 1: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}, 1: {}}},\nLockRange: LockRange{0, 1024},\n},\n{\n@@ -582,7 +582,7 @@ func TestSetLock(t *testing.T) {\nLockRange: LockRange{1024, 3072},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}, 2: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}, 2: {}}},\nLockRange: LockRange{4096, LockEOF},\n},\n},\n@@ -595,11 +595,11 @@ func TestSetLock(t *testing.T) {\n// 0 1024 2048\nbefore: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}, 1: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}, 1: {}}},\nLockRange: LockRange{0, 1024},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{1024, 2048},\n},\n},\n@@ -621,15 +621,15 @@ func TestSetLock(t *testing.T) {\nLockRange: LockRange{0, 1024},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{1024, 2048},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{2048, 4096},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{4096, LockEOF},\n},\n},\n@@ -725,7 +725,7 @@ func TestUnlock(t *testing.T) {\n// 0 max uint64\nbefore: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{1: OwnerInfo{}, 2: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{1: {}, 2: {}}},\nLockRange: LockRange{0, LockEOF},\n},\n},\n@@ -738,7 +738,7 @@ func TestUnlock(t *testing.T) {\n// 0 max uint64\nafter: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{1: OwnerInfo{}, 2: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{1: {}, 2: {}}},\nLockRange: LockRange{0, LockEOF},\n},\n},\n@@ -751,7 +751,7 @@ func TestUnlock(t *testing.T) {\n// 0 max uint64\nbefore: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{0, LockEOF},\n},\n},\n@@ -783,7 +783,7 @@ func TestUnlock(t *testing.T) {\n// 0 max uint64\nbefore: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{0, LockEOF},\n},\n},\n@@ -796,7 +796,7 @@ func TestUnlock(t *testing.T) {\n// 0 4096 max uint64\nafter: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{4096, LockEOF},\n},\n},\n@@ -835,7 +835,7 @@ func TestUnlock(t *testing.T) {\n// 0 max uint64\nbefore: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{0, LockEOF},\n},\n},\n@@ -848,7 +848,7 @@ func TestUnlock(t *testing.T) {\n// 0 4096\nafter: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}}},\nLockRange: LockRange{0, 4096},\n},\n},\n@@ -887,7 +887,7 @@ func TestUnlock(t *testing.T) {\n// 0 1024 4096 max uint64\nbefore: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}, 1: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}, 1: {}}},\nLockRange: LockRange{0, 1024},\n},\n{\n@@ -895,7 +895,7 @@ func TestUnlock(t *testing.T) {\nLockRange: LockRange{1024, 4096},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}, 1: OwnerInfo{}, 2: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}, 1: {}, 2: {}}},\nLockRange: LockRange{4096, LockEOF},\n},\n},\n@@ -908,11 +908,11 @@ func TestUnlock(t *testing.T) {\n// 0 1024 4096 max uint64\nafter: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{1: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{1: {}}},\nLockRange: LockRange{0, 1024},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{1: OwnerInfo{}, 2: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{1: {}, 2: {}}},\nLockRange: LockRange{4096, LockEOF},\n},\n},\n@@ -925,7 +925,7 @@ func TestUnlock(t *testing.T) {\n// 0 max uint64\nbefore: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}, 1: OwnerInfo{}, 2: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}, 1: {}, 2: {}}},\nLockRange: LockRange{0, LockEOF},\n},\n},\n@@ -938,15 +938,15 @@ func TestUnlock(t *testing.T) {\n// 0 1024 4096 max uint64\nafter: []entry{\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}, 1: OwnerInfo{}, 2: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}, 1: {}, 2: {}}},\nLockRange: LockRange{0, 1024},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{1: OwnerInfo{}, 2: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{1: {}, 2: {}}},\nLockRange: LockRange{1024, 4096},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}, 1: OwnerInfo{}, 2: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}, 1: {}, 2: {}}},\nLockRange: LockRange{4096, LockEOF},\n},\n},\n@@ -963,7 +963,7 @@ func TestUnlock(t *testing.T) {\nLockRange: LockRange{0, 1024},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}, 1: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}, 1: {}}},\nLockRange: LockRange{4096, LockEOF},\n},\n},\n@@ -980,7 +980,7 @@ func TestUnlock(t *testing.T) {\nLockRange: LockRange{0, 8},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}, 1: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}, 1: {}}},\nLockRange: LockRange{4096, LockEOF},\n},\n},\n@@ -997,7 +997,7 @@ func TestUnlock(t *testing.T) {\nLockRange: LockRange{0, 1024},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}, 1: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}, 1: {}}},\nLockRange: LockRange{4096, LockEOF},\n},\n},\n@@ -1014,11 +1014,11 @@ func TestUnlock(t *testing.T) {\nLockRange: LockRange{0, 1024},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{1: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{1: {}}},\nLockRange: LockRange{4096, 8192},\n},\n{\n- Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: OwnerInfo{}, 1: OwnerInfo{}}},\n+ Lock: Lock{Readers: map[UniqueID]OwnerInfo{0: {}, 1: {}}},\nLockRange: LockRange{8192, LockEOF},\n},\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/base.go",
"new_path": "pkg/sentry/fsimpl/cgroupfs/base.go",
"diff": "@@ -342,7 +342,7 @@ func (d *cgroupProcsData) Generate(ctx context.Context, buf *bytes.Buffer) error\n}\npgidList := make([]kernel.ThreadID, 0, len(pgids))\n- for pgid, _ := range pgids {\n+ for pgid := range pgids {\npgidList = append(pgidList, pgid)\n}\nsortTIDs(pgidList)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/cgroup.go",
"new_path": "pkg/sentry/kernel/cgroup.go",
"diff": "@@ -335,7 +335,7 @@ func (r *CgroupRegistry) Unregister(hid uint32) {\n// +checklocks:r.mu\nfunc (r *CgroupRegistry) unregisterLocked(hid uint32) {\nif h, ok := r.hierarchies[hid]; ok {\n- for name, _ := range h.controllers {\n+ for name := range h.controllers {\ndelete(r.controllers, name)\n}\ndelete(r.hierarchies, hid)\n@@ -352,7 +352,7 @@ func (r *CgroupRegistry) computeInitialGroups(inherit map[Cgroup]struct{}) map[C\ncgset := make(map[Cgroup]struct{})\n// Remember controllers from the inherited cgroups set...\n- for cg, _ := range inherit {\n+ for cg := range inherit {\ncg.IncRef() // Ref transferred to caller.\nfor _, ctl := range cg.Controllers() {\nctlSet[ctl.Type()] = ctl\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_cgroup.go",
"new_path": "pkg/sentry/kernel/task_cgroup.go",
"diff": "@@ -42,7 +42,7 @@ func (t *Task) EnterInitialCgroups(parent *Task) {\ndefer t.mu.Unlock()\n// Transfer ownership of joinSet refs to the task's cgset.\nt.cgroups = joinSet\n- for c, _ := range t.cgroups {\n+ for c := range t.cgroups {\n// Since t isn't in any cgroup yet, we can skip the check against\n// existing cgroups.\nc.Enter(t)\n@@ -59,7 +59,7 @@ func (t *Task) EnterCgroup(c Cgroup) error {\nt.mu.Lock()\ndefer t.mu.Unlock()\n- for oldCG, _ := range t.cgroups {\n+ for oldCG := range t.cgroups {\nif oldCG.HierarchyID() == c.HierarchyID() {\nlog.Warningf(\"Cannot enter new cgroup %v due to conflicting controllers. Try migrate instead?\", c)\nreturn linuxerr.EBUSY\n@@ -103,7 +103,7 @@ func (t *Task) LeaveCgroups() {\n// +checklocks:t.mu\nfunc (t *Task) findCgroupWithMatchingHierarchyLocked(other Cgroup) (Cgroup, bool) {\n- for c, _ := range t.cgroups {\n+ for c := range t.cgroups {\nif c.HierarchyID() != other.HierarchyID() {\ncontinue\n}\n@@ -191,7 +191,7 @@ func (t *Task) GenerateProcTaskCgroup(buf *bytes.Buffer) {\ndefer t.mu.Unlock()\ncgEntries := make([]taskCgroupEntry, 0, len(t.cgroups))\n- for c, _ := range t.cgroups {\n+ for c := range t.cgroups {\nctls := c.Controllers()\nctlNames := make([]string, 0, len(ctls))\nfor _, ctl := range ctls {\n@@ -215,7 +215,7 @@ func (t *Task) GenerateProcTaskCgroup(buf *bytes.Buffer) {\n// +checklocks:t.mu\nfunc (t *Task) chargeLocked(target *Task, ctl CgroupControllerType, res CgroupResourceType, value int64) error {\n- for c, _ := range t.cgroups {\n+ for c := range t.cgroups {\nif err := c.Charge(target, c.Dentry, ctl, res, value); err != nil {\nreturn err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/platform.go",
"new_path": "pkg/sentry/platform/platform.go",
"diff": "@@ -446,7 +446,7 @@ func Register(name string, platform Constructor) {\n// List lists available platforms.\nfunc List() (available []string) {\n- for name, _ := range platforms {\n+ for name := range platforms {\navailable = append(available, name)\n}\nreturn\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sync/locking/lockdep.go",
"new_path": "pkg/sync/locking/lockdep.go",
"diff": "@@ -100,7 +100,7 @@ func AddGLock(class *MutexClass, subclass uint32) {\n}\n// Check dependencies and add locked mutexes to the ancestors list.\n- for prevClass, _ := range *currentLocks {\n+ for prevClass := range *currentLocks {\nif prevClass == class {\npanic(fmt.Sprintf(\"nested locking: %s:\\n%s\", *classMap.Load(class), log.Stacks(false)))\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/checksum_test.go",
"new_path": "pkg/tcpip/header/checksum_test.go",
"diff": "@@ -41,22 +41,22 @@ func TestChecksumer(t *testing.T) {\n{\nname: \"OneOddView\",\ndata: [][]byte{\n- []byte{1, 9, 0, 5, 4},\n+ {1, 9, 0, 5, 4},\n},\nwant: 1294,\n},\n{\nname: \"TwoOddViews\",\ndata: [][]byte{\n- []byte{1, 9, 0, 5, 4},\n- []byte{4, 3, 7, 1, 2, 123},\n+ {1, 9, 0, 5, 4},\n+ {4, 3, 7, 1, 2, 123},\n},\nwant: 33819,\n},\n{\nname: \"OneEvenView\",\ndata: [][]byte{\n- []byte{1, 9, 0, 5},\n+ {1, 9, 0, 5},\n},\nwant: 270,\n},\n@@ -71,9 +71,9 @@ func TestChecksumer(t *testing.T) {\n{\nname: \"ThreeViews\",\ndata: [][]byte{\n- []byte{77, 11, 33, 0, 55, 44},\n- []byte{98, 1, 9, 0, 5, 4},\n- []byte{4, 3, 7, 1, 2, 123, 99},\n+ {77, 11, 33, 0, 55, 44},\n+ {98, 1, 9, 0, 5, 4},\n+ {4, 3, 7, 1, 2, 123, 99},\n},\nwant: 34236,\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4.go",
"diff": "@@ -1440,10 +1440,10 @@ func NewProtocolWithOptions(opts Options) stack.NetworkProtocolFactory {\n// Set ICMP rate limiting to Linux defaults.\n// See https://man7.org/linux/man-pages/man7/icmp.7.html.\np.icmpRateLimitedTypes = map[header.ICMPv4Type]struct{}{\n- header.ICMPv4DstUnreachable: struct{}{},\n- header.ICMPv4SrcQuench: struct{}{},\n- header.ICMPv4TimeExceeded: struct{}{},\n- header.ICMPv4ParamProblem: struct{}{},\n+ header.ICMPv4DstUnreachable: {},\n+ header.ICMPv4SrcQuench: {},\n+ header.ICMPv4TimeExceeded: {},\n+ header.ICMPv4ParamProblem: {},\n}\nreturn p\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/integration/loopback_test.go",
"new_path": "pkg/tcpip/tests/integration/loopback_test.go",
"diff": "@@ -739,19 +739,19 @@ func TestExternalLoopbackTraffic(t *testing.T) {\n}\ns.SetRouteTable([]tcpip.Route{\n- tcpip.Route{\n+ {\nDestination: header.IPv4EmptySubnet,\nNIC: nicID1,\n},\n- tcpip.Route{\n+ {\nDestination: header.IPv6EmptySubnet,\nNIC: nicID1,\n},\n- tcpip.Route{\n+ {\nDestination: ipv4Loopback.WithPrefix().Subnet(),\nNIC: nicID2,\n},\n- tcpip.Route{\n+ {\nDestination: header.IPv6Loopback.WithPrefix().Subnet(),\nNIC: nicID2,\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/trie/trie_test.go",
"new_path": "pkg/trie/trie_test.go",
"diff": "@@ -84,11 +84,11 @@ func TestAscendingSearch(t *testing.T) {\ntr.SetValue(\"abcde\", \"value abcde\")\nexpected := []Entry{\n- Entry{Key: \"a\", Value: \"value a\"},\n- Entry{Key: \"ab\", Value: \"value ab\"},\n- Entry{Key: \"abc\", Value: \"value abc\"},\n- Entry{Key: \"abcd\", Value: \"value abcd\"},\n- Entry{Key: \"abcde\", Value: \"value abcde\"}}\n+ {Key: \"a\", Value: \"value a\"},\n+ {Key: \"ab\", Value: \"value ab\"},\n+ {Key: \"abc\", Value: \"value abc\"},\n+ {Key: \"abcd\", Value: \"value abcd\"},\n+ {Key: \"abcde\", Value: \"value abcde\"}}\narr := collectPrefixes(tr, \"abcdef\")\nif d := cmp.Diff(expected, arr); d != \"\" {\nt.Errorf(\"collectPrefixes(tr, 'abcdef') returned diff (-want +got):\\n%s\", d)\n@@ -124,7 +124,7 @@ func TestRoot(t *testing.T) {\nt.Errorf(\"tr.Size() = %d; want 1\", tr.Size())\n}\n- expected := []Entry{Entry{Key: \"\", Value: \"root value\"}}\n+ expected := []Entry{{Key: \"\", Value: \"root value\"}}\narr := collectPrefixes(tr, \"foo\")\nif d := cmp.Diff(expected, arr); d != \"\" {\nt.Errorf(\"collectPrefixes(tr, 'foo') returned diff (-want +got):\\n%s\", d)\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/checklinkname/known.go",
"new_path": "tools/checklinkname/known.go",
"diff": "@@ -41,53 +41,53 @@ package checklinkname\n//\n// TODO(b/165820485): Add option to specific per-version signatures.\nvar knownLinknames = map[string]map[string]linknameSignatures{\n- \"runtime\": map[string]linknameSignatures{\n- \"entersyscall\": linknameSignatures{\n+ \"runtime\": {\n+ \"entersyscall\": {\nlocal: \"func()\",\n},\n- \"entersyscallblock\": linknameSignatures{\n+ \"entersyscallblock\": {\nlocal: \"func()\",\n},\n- \"exitsyscall\": linknameSignatures{\n+ \"exitsyscall\": {\nlocal: \"func()\",\n},\n- \"fastrand\": linknameSignatures{\n+ \"fastrand\": {\nlocal: \"func() uint32\",\n},\n- \"gopark\": linknameSignatures{\n+ \"gopark\": {\n// TODO(b/165820485): add verification of waitReason\n// size and reason and traceEv values.\nlocal: \"func(unlockf func(uintptr, unsafe.Pointer) bool, lock unsafe.Pointer, reason uint8, traceEv byte, traceskip int)\",\nremote: \"func(unlockf func(*runtime.g, unsafe.Pointer) bool, lock unsafe.Pointer, reason runtime.waitReason, traceEv byte, traceskip int)\",\n},\n- \"goready\": linknameSignatures{\n+ \"goready\": {\nlocal: \"func(gp uintptr, traceskip int)\",\nremote: \"func(gp *runtime.g, traceskip int)\",\n},\n- \"goyield\": linknameSignatures{\n+ \"goyield\": {\nlocal: \"func()\",\n},\n- \"memmove\": linknameSignatures{\n+ \"memmove\": {\nlocal: \"func(to unsafe.Pointer, from unsafe.Pointer, n uintptr)\",\n},\n- \"throw\": linknameSignatures{\n+ \"throw\": {\nlocal: \"func(s string)\",\n},\n- \"wakep\": linknameSignatures{\n+ \"wakep\": {\nlocal: \"func()\",\n},\n- \"nanotime\": linknameSignatures{\n+ \"nanotime\": {\nlocal: \"func() int64\",\n},\n},\n- \"sync\": map[string]linknameSignatures{\n- \"runtime_canSpin\": linknameSignatures{\n+ \"sync\": {\n+ \"runtime_canSpin\": {\nlocal: \"func(i int) bool\",\n},\n- \"runtime_doSpin\": linknameSignatures{\n+ \"runtime_doSpin\": {\nlocal: \"func()\",\n},\n- \"runtime_Semacquire\": linknameSignatures{\n+ \"runtime_Semacquire\": {\n// The only difference here is the parameter names. We\n// can't just change our local use to match remote, as\n// the stdlib runtime and sync packages also disagree\n@@ -96,20 +96,20 @@ var knownLinknames = map[string]map[string]linknameSignatures{\nlocal: \"func(addr *uint32)\",\nremote: \"func(s *uint32)\",\n},\n- \"runtime_Semrelease\": linknameSignatures{\n+ \"runtime_Semrelease\": {\n// See above.\nlocal: \"func(addr *uint32, handoff bool, skipframes int)\",\nremote: \"func(s *uint32, handoff bool, skipframes int)\",\n},\n},\n- \"syscall\": map[string]linknameSignatures{\n- \"runtime_BeforeFork\": linknameSignatures{\n+ \"syscall\": {\n+ \"runtime_BeforeFork\": {\nlocal: \"func()\",\n},\n- \"runtime_AfterFork\": linknameSignatures{\n+ \"runtime_AfterFork\": {\nlocal: \"func()\",\n},\n- \"runtime_AfterForkInChild\": linknameSignatures{\n+ \"runtime_AfterForkInChild\": {\nlocal: \"func()\",\n},\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/nogo/check/check.go",
"new_path": "tools/nogo/check/check.go",
"diff": "@@ -520,7 +520,7 @@ func (i *importer) checkPackage(path string, srcs []string) (*types.Package, Fin\nfactsMu.RLock()\ndefer factsMu.RUnlock()\n// Pull all local facts.\n- for obj, _ := range astFacts.Objects {\n+ for obj := range astFacts.Objects {\nfor typ := range localFactTypes {\nv := reflect.New(typ.Elem())\nif astFacts.ImportFact(obj, v.Interface().(analysis.Fact)) {\n@@ -746,7 +746,7 @@ func SplitPackages(srcs []string, srcRootPrefix string) map[string][]string {\n//\n// TODO(b/201686256): remove once tooling can handle type parameters.\nvar usesTypeParams = map[string]struct{}{\n- \"sync/atomic\": struct{}{}, // https://go.dev/issue/50860\n+ \"sync/atomic\": {}, // https://go.dev/issue/50860\n}\n// Bundle checks a bundle of files (typically the standard library).\n@@ -758,7 +758,7 @@ func Bundle(sources map[string][]string) (FindingSet, facts.Serializer, error) {\ncache: make(map[string]*importerEntry),\nimports: make(map[string]*types.Package),\n}\n- for pkg, _ := range sources {\n+ for pkg := range sources {\n// Was there an error processing this package?\nif _, err := i.importPackage(pkg); err != nil && err != ErrSkip {\nreturn nil, nil, err\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/nogo/config/config_test.go",
"new_path": "tools/nogo/config/config_test.go",
"diff": "@@ -54,7 +54,7 @@ func TestShouldReport(t *testing.T) {\n// has no effect on configuration below.\n},\nAnalyzers: map[string]AnalyzerConfig{\n- \"analyzer-suppressions\": AnalyzerConfig{\n+ \"analyzer-suppressions\": {\n// Suppress some.\n\"default-enabled\": &ItemConfig{\nExclude: []string{\"limited-exclude.go\"},\n@@ -63,7 +63,7 @@ func TestShouldReport(t *testing.T) {\n// Enable all.\n\"default-disabled\": nil,\n},\n- \"enabled-for-default-disabled\": AnalyzerConfig{\n+ \"enabled-for-default-disabled\": {\n\"default-disabled\": nil,\n\"default-disabled-omitted-from-global\": nil,\n},\n"
}
] | Go | Apache License 2.0 | google/gvisor | Simplify codebase.
Ran gofmt -w -s ./
PiperOrigin-RevId: 449415155 |
259,966 | 18.05.2022 08:27:50 | 25,200 | 98f5323163c41328aea6845a516d560bbfa8065b | Use testutil.MustParse4/6 instead of net.ParseIP in tcpip test utils.
Also dedupe the RemoteIPv4Addr.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/utils/BUILD",
"new_path": "pkg/tcpip/tests/utils/BUILD",
"diff": "@@ -4,6 +4,7 @@ package(licenses = [\"notice\"])\ngo_library(\nname = \"utils\",\n+ testonly = True,\nsrcs = [\"utils.go\"],\nvisibility = [\"//pkg/tcpip/tests:__subpackages__\"],\ndeps = [\n@@ -17,6 +18,7 @@ go_library(\n\"//pkg/tcpip/network/ipv4\",\n\"//pkg/tcpip/network/ipv6\",\n\"//pkg/tcpip/stack\",\n+ \"//pkg/tcpip/testutil\",\n\"//pkg/tcpip/transport/icmp\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/utils/utils.go",
"new_path": "pkg/tcpip/tests/utils/utils.go",
"diff": "package utils\nimport (\n- \"net\"\n\"testing\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n@@ -29,6 +28,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv4\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv6\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/testutil\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/icmp\"\n)\n@@ -59,14 +59,14 @@ const (\n// Common IP addresses used by tests.\nvar (\nIpv4Addr = tcpip.AddressWithPrefix{\n- Address: tcpip.Address(net.ParseIP(\"192.168.1.58\").To4()),\n+ Address: testutil.MustParse4(\"192.168.1.58\"),\nPrefixLen: 24,\n}\nIpv4Subnet = Ipv4Addr.Subnet()\nIpv4SubnetBcast = Ipv4Subnet.Broadcast()\nIpv6Addr = tcpip.AddressWithPrefix{\n- Address: tcpip.Address(net.ParseIP(\"200a::1\").To16()),\n+ Address: testutil.MustParse6(\"200a::1\"),\nPrefixLen: 64,\n}\nIpv6Subnet = Ipv6Addr.Subnet()\n@@ -75,49 +75,49 @@ var (\nIpv4Addr1 = tcpip.ProtocolAddress{\nProtocol: ipv4.ProtocolNumber,\nAddressWithPrefix: tcpip.AddressWithPrefix{\n- Address: tcpip.Address(net.ParseIP(\"192.168.0.1\").To4()),\n+ Address: testutil.MustParse4(\"192.168.0.1\"),\nPrefixLen: 24,\n},\n}\nIpv4Addr2 = tcpip.ProtocolAddress{\nProtocol: ipv4.ProtocolNumber,\nAddressWithPrefix: tcpip.AddressWithPrefix{\n- Address: tcpip.Address(net.ParseIP(\"192.168.0.2\").To4()),\n+ Address: testutil.MustParse4(\"192.168.0.2\"),\nPrefixLen: 8,\n},\n}\nIpv4Addr3 = tcpip.ProtocolAddress{\nProtocol: ipv4.ProtocolNumber,\nAddressWithPrefix: tcpip.AddressWithPrefix{\n- Address: tcpip.Address(net.ParseIP(\"192.168.0.3\").To4()),\n+ Address: testutil.MustParse4(\"192.168.0.3\"),\nPrefixLen: 8,\n},\n}\nIpv6Addr1 = tcpip.ProtocolAddress{\nProtocol: ipv6.ProtocolNumber,\nAddressWithPrefix: tcpip.AddressWithPrefix{\n- Address: tcpip.Address(net.ParseIP(\"a::1\").To16()),\n+ Address: testutil.MustParse6(\"a::1\"),\nPrefixLen: 64,\n},\n}\nIpv6Addr2 = tcpip.ProtocolAddress{\nProtocol: ipv6.ProtocolNumber,\nAddressWithPrefix: tcpip.AddressWithPrefix{\n- Address: tcpip.Address(net.ParseIP(\"a::2\").To16()),\n+ Address: testutil.MustParse6(\"a::2\"),\nPrefixLen: 64,\n},\n}\nIpv6Addr3 = tcpip.ProtocolAddress{\nProtocol: ipv6.ProtocolNumber,\nAddressWithPrefix: tcpip.AddressWithPrefix{\n- Address: tcpip.Address(net.ParseIP(\"a::3\").To16()),\n+ Address: testutil.MustParse6(\"a::3\"),\nPrefixLen: 64,\n},\n}\n// Remote addrs.\n- RemoteIPv4Addr = tcpip.Address(net.ParseIP(\"10.0.0.1\").To4())\n- RemoteIPv6Addr = tcpip.Address(net.ParseIP(\"200b::1\").To16())\n+ RemoteIPv4Addr = testutil.MustParse4(\"10.0.0.1\")\n+ RemoteIPv6Addr = testutil.MustParse6(\"200b::1\")\n)\n// Common ports for testing.\n@@ -131,56 +131,56 @@ var (\nHost1IPv4Addr = tcpip.ProtocolAddress{\nProtocol: ipv4.ProtocolNumber,\nAddressWithPrefix: tcpip.AddressWithPrefix{\n- Address: tcpip.Address(net.ParseIP(\"192.168.0.2\").To4()),\n+ Address: testutil.MustParse4(\"192.168.0.2\"),\nPrefixLen: 24,\n},\n}\nRouterNIC1IPv4Addr = tcpip.ProtocolAddress{\nProtocol: ipv4.ProtocolNumber,\nAddressWithPrefix: tcpip.AddressWithPrefix{\n- Address: tcpip.Address(net.ParseIP(\"192.168.0.1\").To4()),\n+ Address: testutil.MustParse4(\"192.168.0.1\"),\nPrefixLen: 24,\n},\n}\nRouterNIC2IPv4Addr = tcpip.ProtocolAddress{\nProtocol: ipv4.ProtocolNumber,\nAddressWithPrefix: tcpip.AddressWithPrefix{\n- Address: tcpip.Address(net.ParseIP(\"10.0.0.1\").To4()),\n+ Address: testutil.MustParse4(\"10.0.0.3\"),\nPrefixLen: 8,\n},\n}\nHost2IPv4Addr = tcpip.ProtocolAddress{\nProtocol: ipv4.ProtocolNumber,\nAddressWithPrefix: tcpip.AddressWithPrefix{\n- Address: tcpip.Address(net.ParseIP(\"10.0.0.2\").To4()),\n+ Address: testutil.MustParse4(\"10.0.0.2\"),\nPrefixLen: 8,\n},\n}\nHost1IPv6Addr = tcpip.ProtocolAddress{\nProtocol: ipv6.ProtocolNumber,\nAddressWithPrefix: tcpip.AddressWithPrefix{\n- Address: tcpip.Address(net.ParseIP(\"a::2\").To16()),\n+ Address: testutil.MustParse6(\"a::2\"),\nPrefixLen: 64,\n},\n}\nRouterNIC1IPv6Addr = tcpip.ProtocolAddress{\nProtocol: ipv6.ProtocolNumber,\nAddressWithPrefix: tcpip.AddressWithPrefix{\n- Address: tcpip.Address(net.ParseIP(\"a::1\").To16()),\n+ Address: testutil.MustParse6(\"a::1\"),\nPrefixLen: 64,\n},\n}\nRouterNIC2IPv6Addr = tcpip.ProtocolAddress{\nProtocol: ipv6.ProtocolNumber,\nAddressWithPrefix: tcpip.AddressWithPrefix{\n- Address: tcpip.Address(net.ParseIP(\"b::1\").To16()),\n+ Address: testutil.MustParse6(\"b::1\"),\nPrefixLen: 64,\n},\n}\nHost2IPv6Addr = tcpip.ProtocolAddress{\nProtocol: ipv6.ProtocolNumber,\nAddressWithPrefix: tcpip.AddressWithPrefix{\n- Address: tcpip.Address(net.ParseIP(\"b::2\").To16()),\n+ Address: testutil.MustParse6(\"b::2\"),\nPrefixLen: 64,\n},\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use testutil.MustParse4/6 instead of net.ParseIP in tcpip test utils.
Also dedupe the RemoteIPv4Addr.
Updates #7338.
PiperOrigin-RevId: 449488567 |
259,992 | 18.05.2022 10:38:10 | 25,200 | 59b059b59556c55a23a4a60f81724646a49ac402 | Update containerd to v1.4.12
Closes | [
{
"change_type": "MODIFY",
"old_path": "WORKSPACE",
"new_path": "WORKSPACE",
"diff": "@@ -719,8 +719,8 @@ go_repository(\nname = \"com_github_containerd_containerd\",\nbuild_file_proto_mode = \"disable\",\nimportpath = \"github.com/containerd/containerd\",\n- sum = \"h1:K2U/F4jGAMBqeUssfgJRbFuomLcS2Fxo1vR3UM/Mbh8=\",\n- version = \"v1.3.9\",\n+ sum = \"h1:V+SHzYmhng/iju6M5nFrpTTusrhidoxKTwdwLw+u4c4=\",\n+ version = \"v1.4.12\",\n)\ngo_repository(\n"
},
{
"change_type": "MODIFY",
"old_path": "go.mod",
"new_path": "go.mod",
"diff": "@@ -9,7 +9,7 @@ require (\ngithub.com/cenkalti/backoff v1.1.1-0.20190506075156-2146c9339422\ngithub.com/containerd/cgroups v1.0.1\ngithub.com/containerd/console v1.0.1\n- github.com/containerd/containerd v1.3.9\n+ github.com/containerd/containerd v1.4.12\ngithub.com/containerd/fifo v1.0.0\ngithub.com/containerd/go-runc v1.0.0\ngithub.com/containerd/typeurl v1.0.2\n"
},
{
"change_type": "MODIFY",
"old_path": "go.sum",
"new_path": "go.sum",
"diff": "@@ -91,6 +91,8 @@ github.com/containerd/console v1.0.1/go.mod h1:XUsP6YE/mKtz6bxc+I8UiKKTP04qjQL4q\ngithub.com/containerd/containerd v1.3.2/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA=\ngithub.com/containerd/containerd v1.3.9 h1:K2U/F4jGAMBqeUssfgJRbFuomLcS2Fxo1vR3UM/Mbh8=\ngithub.com/containerd/containerd v1.3.9/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA=\n+github.com/containerd/containerd v1.4.12 h1:V+SHzYmhng/iju6M5nFrpTTusrhidoxKTwdwLw+u4c4=\n+github.com/containerd/containerd v1.4.12/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA=\ngithub.com/containerd/continuity v0.0.0-20190426062206-aaeac12a7ffc/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y=\ngithub.com/containerd/continuity v0.2.1 h1:/EeEo2EtN3umhbbgCveyjifoMYg0pS+nMMEemaYw634=\ngithub.com/containerd/continuity v0.2.1/go.mod h1:wCYX+dRqZdImhGucXOqTQn05AhX6EUDaGEMUzTFFpLg=\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update containerd to v1.4.12
Closes #6232
PiperOrigin-RevId: 449518615 |
259,975 | 18.05.2022 11:48:26 | 25,200 | 671bd7b0f8971d77309fef5143cf2f92b696e52b | Don't clobber /etc/docker/config.json on debian updates. | [
{
"change_type": "MODIFY",
"old_path": "debian/postinst.sh",
"new_path": "debian/postinst.sh",
"diff": "@@ -20,7 +20,7 @@ fi\n# Update docker configuration.\nif [ -f /etc/docker/daemon.json ]; then\n- runsc install\n+ runsc install --clobber=false\nif systemctl is-active -q docker; then\nsystemctl reload docker || echo \"unable to reload docker; you must do so manually.\" >&2\nfi\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/BUILD",
"new_path": "runsc/cmd/BUILD",
"diff": "@@ -82,6 +82,7 @@ go_test(\n\"delete_test.go\",\n\"exec_test.go\",\n\"gofer_test.go\",\n+ \"install_test.go\",\n\"mitigate_test.go\",\n],\ndata = [\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/install.go",
"new_path": "runsc/cmd/install.go",
"diff": "@@ -22,6 +22,7 @@ import (\n\"log\"\n\"os\"\n\"path\"\n+ \"regexp\"\n\"github.com/google/subcommands\"\n\"gvisor.dev/gvisor/pkg/sentry/platform\"\n@@ -34,7 +35,10 @@ type Install struct {\nConfigFile string\nRuntime string\nExperimental bool\n+ Clobber bool\nCgroupDriver string\n+ executablePath string\n+ runtimeArgs []string\n}\n// Name implements subcommands.Command.Name.\n@@ -57,17 +61,18 @@ func (*Install) Usage() string {\nfunc (i *Install) SetFlags(fs *flag.FlagSet) {\nfs.StringVar(&i.ConfigFile, \"config_file\", \"/etc/docker/daemon.json\", \"path to Docker daemon config file\")\nfs.StringVar(&i.Runtime, \"runtime\", \"runsc\", \"runtime name\")\n- fs.BoolVar(&i.Experimental, \"experimental\", false, \"enable experimental features\")\n+ fs.BoolVar(&i.Experimental, \"experimental\", false, \"enable/disable experimental features\")\n+ fs.BoolVar(&i.Clobber, \"clobber\", true, \"clobber existing runtime configuration\")\nfs.StringVar(&i.CgroupDriver, \"cgroupdriver\", \"\", \"docker cgroup driver\")\n}\n// Execute implements subcommands.Command.Execute.\nfunc (i *Install) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {\n// Grab the name and arguments.\n- runtimeArgs := f.Args()\n+ i.runtimeArgs = f.Args()\ntestFlags := flag.NewFlagSet(\"test\", flag.ContinueOnError)\nconfig.RegisterFlags(testFlags)\n- testFlags.Parse(runtimeArgs)\n+ testFlags.Parse(i.runtimeArgs)\nconf, err := config.NewFromFlags(testFlags)\nif err != nil {\nlog.Fatalf(\"invalid runtime arguments: %v\", err)\n@@ -92,10 +97,34 @@ func (i *Install) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{})\nlog.Fatalf(\"Error reading current exectuable: %v\", err)\n}\n+ i.executablePath = path\n+\n+ installRW := configReaderWriter{\n+ read: defaultReadConfig,\n+ write: defaultWriteConfig,\n+ }\n+\n+ if err := doInstallConfig(i, installRW); err != nil {\n+ log.Fatalf(\"Install failed: %v\", err)\n+ }\n+\n+ // Success.\n+ log.Print(\"Successfully updated config.\")\n+ return subcommands.ExitSuccess\n+}\n+\n+func doInstallConfig(i *Install, rw configReaderWriter) error {\n// Load the configuration file.\n- c, err := readConfig(i.ConfigFile)\n+ configBytes, err := rw.read(i.ConfigFile)\nif err != nil {\n- log.Fatalf(\"Error reading config file %q: %v\", i.ConfigFile, err)\n+ return fmt.Errorf(\"error reading config file %q: %v\", i.ConfigFile, err)\n+ }\n+ // Unmarshal the configuration.\n+ c := make(map[string]interface{})\n+ if len(configBytes) > 0 {\n+ if err := json.Unmarshal(configBytes, &c); err != nil {\n+ return err\n+ }\n}\n// Add the given runtime.\n@@ -106,12 +135,25 @@ func (i *Install) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{})\nrts = make(map[string]interface{})\nc[\"runtimes\"] = rts\n}\n+ updateRuntime := func() {\nrts[i.Runtime] = struct {\nPath string `json:\"path,omitempty\"`\nRuntimeArgs []string `json:\"runtimeArgs,omitempty\"`\n}{\n- Path: path,\n- RuntimeArgs: runtimeArgs,\n+ Path: i.executablePath,\n+ RuntimeArgs: i.runtimeArgs,\n+ }\n+ }\n+ _, ok := rts[i.Runtime]\n+ switch {\n+ case !ok:\n+ log.Printf(\"Runtime %s not found: adding\\n\", i.Runtime)\n+ updateRuntime()\n+ case i.Clobber:\n+ log.Printf(\"Clobber is set. Overwriting runtime %s not found: adding\\n\", i.Runtime)\n+ updateRuntime()\n+ default:\n+ log.Printf(\"Not overwriting runtime %s\\n\", i.Runtime)\n}\n// Set experimental if required.\n@@ -119,24 +161,38 @@ func (i *Install) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{})\nc[\"experimental\"] = true\n}\n+ re := regexp.MustCompile(`^native.cgroupdriver=`)\n+ // Set the cgroupdriver if required.\nif i.CgroupDriver != \"\" {\nv, ok := c[\"exec-opts\"]\n- if ok {\n- opts := v.([]interface{})\n- c[\"exec-opts\"] = append(opts, fmt.Sprintf(\"native.cgroupdriver=%s\", i.CgroupDriver))\n- } else {\n+ if !ok {\nc[\"exec-opts\"] = []string{fmt.Sprintf(\"native.cgroupdriver=%s\", i.CgroupDriver)}\n+ } else {\n+ opts := v.([]interface{})\n+ newOpts := []interface{}{}\n+ for _, opt := range opts {\n+ if !i.Clobber {\n+ newOpts = opts\n+ break\n}\n+ o, ok := opt.(string)\n+ if !ok {\n+ continue\n}\n- // Write out the runtime.\n- if err := writeConfig(c, i.ConfigFile); err != nil {\n- log.Fatalf(\"Error writing config file %q: %v\", i.ConfigFile, err)\n+ if !re.MatchString(o) {\n+ newOpts = append(newOpts, o)\n+ }\n+ }\n+ c[\"exec-opts\"] = append(newOpts, fmt.Sprintf(\"native.cgroupdriver=%s\", i.CgroupDriver))\n+ }\n}\n- // Success.\n- log.Printf(\"Added runtime %q with arguments %v to %q.\", i.Runtime, runtimeArgs, i.ConfigFile)\n- return subcommands.ExitSuccess\n+ // Write out the runtime.\n+ if err := rw.write(c, i.ConfigFile); err != nil {\n+ return fmt.Errorf(\"error writing config file %q: %v\", i.ConfigFile, err)\n+ }\n+ return nil\n}\n// Uninstall implements subcommands.Command.\n@@ -170,48 +226,61 @@ func (u *Uninstall) SetFlags(fs *flag.FlagSet) {\n// Execute implements subcommands.Command.Execute.\nfunc (u *Uninstall) Execute(context.Context, *flag.FlagSet, ...interface{}) subcommands.ExitStatus {\nlog.Printf(\"Removing runtime %q from %q.\", u.Runtime, u.ConfigFile)\n+ if err := doUninstallConfig(u, configReaderWriter{\n+ read: defaultReadConfig,\n+ write: defaultWriteConfig,\n+ }); err != nil {\n+ log.Fatalf(\"Uninstall failed: %v\", err)\n+ }\n+ return subcommands.ExitSuccess\n+}\n- c, err := readConfig(u.ConfigFile)\n+func doUninstallConfig(u *Uninstall, rw configReaderWriter) error {\n+ configBytes, err := rw.read(u.ConfigFile)\nif err != nil {\n- log.Fatalf(\"Error reading config file %q: %v\", u.ConfigFile, err)\n+ return fmt.Errorf(\"error reading config file %q: %v\", u.ConfigFile, err)\n+ }\n+\n+ // Unmarshal the configuration.\n+ c := make(map[string]interface{})\n+ if len(configBytes) > 0 {\n+ if err := json.Unmarshal(configBytes, &c); err != nil {\n+ return err\n+ }\n}\nvar rts map[string]interface{}\nif i, ok := c[\"runtimes\"]; ok {\nrts = i.(map[string]interface{})\n} else {\n- log.Fatalf(\"runtime %q not found\", u.Runtime)\n+ return fmt.Errorf(\"runtime %q not found\", u.Runtime)\n}\nif _, ok := rts[u.Runtime]; !ok {\n- log.Fatalf(\"runtime %q not found\", u.Runtime)\n+ return fmt.Errorf(\"runtime %q not found\", u.Runtime)\n}\ndelete(rts, u.Runtime)\n- if err := writeConfig(c, u.ConfigFile); err != nil {\n- log.Fatalf(\"Error writing config file %q: %v\", u.ConfigFile, err)\n+ if err := rw.write(c, u.ConfigFile); err != nil {\n+ return fmt.Errorf(\"error writing config file %q: %v\", u.ConfigFile, err)\n}\n- return subcommands.ExitSuccess\n+ return nil\n+}\n+\n+type configReaderWriter struct {\n+ read func(string) ([]byte, error)\n+ write func(map[string]interface{}, string) error\n}\n-func readConfig(path string) (map[string]interface{}, error) {\n+func defaultReadConfig(path string) ([]byte, error) {\n// Read the configuration data.\nconfigBytes, err := ioutil.ReadFile(path)\nif err != nil && !os.IsNotExist(err) {\nreturn nil, err\n}\n-\n- // Unmarshal the configuration.\n- c := make(map[string]interface{})\n- if len(configBytes) > 0 {\n- if err := json.Unmarshal(configBytes, &c); err != nil {\n- return nil, err\n- }\n- }\n-\n- return c, nil\n+ return configBytes, nil\n}\n-func writeConfig(c map[string]interface{}, filename string) error {\n+func defaultWriteConfig(c map[string]interface{}, filename string) error {\n// Marshal the configuration.\nb, err := json.MarshalIndent(c, \"\", \" \")\nif err != nil {\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "runsc/cmd/install_test.go",
"diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package cmd\n+\n+import (\n+ \"encoding/json\"\n+ \"fmt\"\n+ \"testing\"\n+\n+ \"github.com/google/go-cmp/cmp\"\n+)\n+\n+type runtimeDef struct {\n+ path string\n+ runtimeArgs []string\n+}\n+\n+func (r *runtimeDef) MarshalJSON() ([]byte, error) {\n+ args, err := json.Marshal(r.runtimeArgs)\n+ if err != nil {\n+ return nil, err\n+ }\n+ str := fmt.Sprintf(`{\"path\": \"%s\", \"runtimeArgs\":%s}`, r.path, args)\n+ return []byte(str), nil\n+}\n+\n+func (r *runtimeDef) UnmarshalJSON(data []byte) error {\n+ var dat map[string]interface{}\n+ if err := json.Unmarshal(data, &dat); err != nil {\n+ return err\n+ }\n+ if p, ok := dat[\"path\"]; ok {\n+ r.path = p.(string)\n+ }\n+ if p, ok := dat[\"runtimeArgs\"]; ok {\n+ r.runtimeArgs = p.([]string)\n+ }\n+ return nil\n+}\n+\n+var defaultInput = map[string]interface{}{\n+ \"runtimes\": map[string]*runtimeDef{\n+ \"runtime1\": &runtimeDef{\n+ path: \"runtime1_path\",\n+ runtimeArgs: []string{\"some\", \"args\"},\n+ },\n+ \"other runtime\": &runtimeDef{\n+ path: \"other_runtime_path\",\n+ runtimeArgs: []string{\"some\", \"other\", \"args\"},\n+ },\n+ \"myRuntime\": &runtimeDef{\n+ path: \"myRuntimePath\",\n+ runtimeArgs: []string{\"super\", \"cool\", \"args\"},\n+ },\n+ },\n+ \"exec-opts\": []string{\"some-cgroup-driver=something\", \"native.cgroupdriver=init_driver\"},\n+}\n+\n+func TestInstall(t *testing.T) {\n+\n+ for _, tc := range []struct {\n+ name string\n+ i *Install\n+ input map[string]interface{}\n+ output map[string]interface{}\n+ }{\n+ {\n+ name: \"clobber\",\n+ i: &Install{\n+ Runtime: \"myRuntime\",\n+ Experimental: true,\n+ Clobber: true,\n+ CgroupDriver: \"my_driver\",\n+ executablePath: \"some_runsc_path\",\n+ runtimeArgs: []string{\"new\", \"cool\", \"args\"},\n+ },\n+ input: defaultInput,\n+ output: map[string]interface{}{\n+ \"runtimes\": map[string]*runtimeDef{\n+ \"runtime1\": &runtimeDef{\n+ path: \"runtime1_path\",\n+ runtimeArgs: []string{\"some\", \"args\"},\n+ },\n+ \"other runtime\": &runtimeDef{\n+ path: \"other_runtime_path\",\n+ runtimeArgs: []string{\"some\", \"other\", \"args\"},\n+ },\n+ \"myRuntime\": &runtimeDef{\n+ path: \"some_runsc_path\",\n+ runtimeArgs: []string{\"new\", \"cool\", \"args\"},\n+ },\n+ },\n+ \"exec-opts\": []string{\"some-cgroup-driver=something\", \"native.cgroupdriver=my_driver\"},\n+ \"experimental\": true,\n+ },\n+ },\n+ {\n+ name: \"no clobber\",\n+ i: &Install{\n+ Runtime: \"myRuntime\",\n+ Experimental: true,\n+ Clobber: false,\n+ CgroupDriver: \"my_driver\",\n+ executablePath: \"some_runsc_path\",\n+ runtimeArgs: []string{\"new\", \"cool\", \"args\"},\n+ },\n+ input: defaultInput,\n+ output: map[string]interface{}{\n+ \"runtimes\": map[string]*runtimeDef{\n+ \"runtime1\": &runtimeDef{\n+ path: \"runtime1_path\",\n+ runtimeArgs: []string{\"some\", \"args\"},\n+ },\n+ \"other runtime\": &runtimeDef{\n+ path: \"other_runtime_path\",\n+ runtimeArgs: []string{\"some\", \"other\", \"args\"},\n+ },\n+ \"myRuntime\": &runtimeDef{\n+ path: \"myRuntimePath\",\n+ runtimeArgs: []string{\"super\", \"cool\", \"args\"},\n+ },\n+ },\n+ \"exec-opts\": []string{\"some-cgroup-driver=something\", \"native.cgroupdriver=init_driver\", \"native.cgroupdriver=my_driver\"},\n+ \"experimental\": true,\n+ },\n+ },\n+ {\n+ name: \"new runtime\",\n+ i: &Install{\n+ Runtime: \"newRuntime\",\n+ Experimental: true,\n+ executablePath: \"newPath\",\n+ runtimeArgs: []string{\"new\", \"cool\", \"args\"},\n+ },\n+ input: defaultInput,\n+ output: map[string]interface{}{\n+ \"runtimes\": map[string]*runtimeDef{\n+ \"runtime1\": &runtimeDef{\n+ path: \"runtime1_path\",\n+ runtimeArgs: []string{\"some\", \"args\"},\n+ },\n+ \"newRuntime\": &runtimeDef{\n+ path: \"newPath\",\n+ runtimeArgs: []string{\"new\", \"cool\", \"args\"},\n+ },\n+ \"other runtime\": &runtimeDef{\n+ path: \"other_runtime_path\",\n+ runtimeArgs: []string{\"some\", \"other\", \"args\"},\n+ },\n+ \"myRuntime\": &runtimeDef{\n+ path: \"myRuntimePath\",\n+ runtimeArgs: []string{\"super\", \"cool\", \"args\"},\n+ },\n+ },\n+ \"exec-opts\": []string{\"some-cgroup-driver=something\", \"native.cgroupdriver=init_driver\"},\n+ \"experimental\": true,\n+ },\n+ },\n+ } {\n+ t.Run(tc.name, func(t *testing.T) {\n+\n+ mockRead := func(_ string) ([]byte, error) {\n+ return json.MarshalIndent(tc.input, \"\", \" \")\n+ }\n+\n+ got := []byte{}\n+ mockWrite := func(c map[string]interface{}, _ string) error {\n+ res, err := json.MarshalIndent(c, \"\", \" \")\n+ if err != nil {\n+ return err\n+ }\n+ got = res\n+ return nil\n+ }\n+\n+ rw := configReaderWriter{\n+ read: mockRead,\n+ write: mockWrite,\n+ }\n+\n+ if err := doInstallConfig(tc.i, rw); err != nil {\n+ t.Fatalf(\"Error updating config: %v\", err)\n+ }\n+\n+ want, err := json.MarshalIndent(tc.output, \"\", \" \")\n+ if err != nil {\n+ t.Fatalf(\"Failed to marshal output: %v\", err)\n+ }\n+\n+ if res := cmp.Diff(string(want), string(got)); res != \"\" {\n+ t.Fatalf(\"Mismatch output (-want +got): %s\", res)\n+ }\n+ })\n+ }\n+}\n+\n+func TestUninstall(t *testing.T) {\n+ for _, tc := range []struct {\n+ name string\n+ u *Uninstall\n+ input map[string]interface{}\n+ output map[string]interface{}\n+ wantErr bool\n+ }{\n+ {\n+ name: \"runtime found\",\n+ u: &Uninstall{\n+ Runtime: \"other runtime\",\n+ },\n+ input: defaultInput,\n+ output: map[string]interface{}{\n+ \"runtimes\": map[string]*runtimeDef{\n+ \"runtime1\": &runtimeDef{\n+ path: \"runtime1_path\",\n+ runtimeArgs: []string{\"some\", \"args\"},\n+ },\n+ \"myRuntime\": &runtimeDef{\n+ path: \"myRuntimePath\",\n+ runtimeArgs: []string{\"super\", \"cool\", \"args\"},\n+ },\n+ },\n+ \"exec-opts\": []string{\"some-cgroup-driver=something\", \"native.cgroupdriver=init_driver\"},\n+ },\n+ },\n+ {\n+ name: \"runtime not found\",\n+ u: &Uninstall{\n+ Runtime: \"not found runtime\",\n+ },\n+ input: defaultInput,\n+ wantErr: true,\n+ },\n+ } {\n+ t.Run(tc.name, func(t *testing.T) {\n+ mockRead := func(_ string) ([]byte, error) {\n+ return json.MarshalIndent(tc.input, \"\", \" \")\n+ }\n+\n+ got := []byte{}\n+ mockWrite := func(c map[string]interface{}, _ string) error {\n+ res, err := json.MarshalIndent(c, \"\", \" \")\n+ if err != nil {\n+ return err\n+ }\n+ got = res\n+ return nil\n+ }\n+\n+ rw := configReaderWriter{\n+ read: mockRead,\n+ write: mockWrite,\n+ }\n+\n+ err := doUninstallConfig(tc.u, rw)\n+ if tc.wantErr {\n+ if err == nil {\n+ t.Fatalf(\"Did not get an error when expected.\")\n+ }\n+ return\n+ }\n+ if err != nil {\n+ t.Fatalf(\"Error updating config: %v\", err)\n+ }\n+\n+ want, err := json.MarshalIndent(tc.output, \"\", \" \")\n+ if err != nil {\n+ t.Fatalf(\"Failed to marshal output: %v\", err)\n+ }\n+ if res := cmp.Diff(string(want), string(got)); res != \"\" {\n+ t.Fatalf(\"Mismatch output (-want +got-): %s\", res)\n+ }\n+ })\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Don't clobber /etc/docker/config.json on debian updates.
PiperOrigin-RevId: 449537553 |
259,858 | 18.05.2022 13:55:29 | 25,200 | b50636d376ec74287dfe35c25783d887d7682a06 | Add rsync to required packages. | [
{
"change_type": "MODIFY",
"old_path": ".buildkite/hooks/pre-command",
"new_path": ".buildkite/hooks/pre-command",
"diff": "@@ -10,7 +10,8 @@ function install_pkgs() {\ndone\n}\ninstall_pkgs make linux-libc-dev graphviz jq curl binutils gnupg gnupg-agent \\\n- gcc pkg-config apt-transport-https ca-certificates software-properties-common\n+ gcc pkg-config apt-transport-https ca-certificates software-properties-common \\\n+ rsync\n# Install headers, only if available.\nif test -n \"$(apt-cache search --names-only \"^linux-headers-$(uname -r)$\")\"; then\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add rsync to required packages.
PiperOrigin-RevId: 449569318 |
259,868 | 18.05.2022 14:11:00 | 25,200 | 4dcac904e1e491c0a701d4908a003f3b17e93b69 | Add `all_benchmarks` fileset containing all benchmark binaries. | [
{
"change_type": "MODIFY",
"old_path": "test/perf/linux/BUILD",
"new_path": "test/perf/linux/BUILD",
"diff": "@@ -5,6 +5,12 @@ package(\nlicenses = [\"notice\"],\n)\n+filegroup(\n+ name = \"all_benchmarks\",\n+ testonly = 1,\n+ data = [\":%s\" % f[:-3] for f in glob([\"*_benchmark.cc\"])],\n+)\n+\ncc_binary(\nname = \"getpid_benchmark\",\ntestonly = 1,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add `all_benchmarks` fileset containing all benchmark binaries.
PiperOrigin-RevId: 449573479 |
259,868 | 18.05.2022 15:11:55 | 25,200 | c9f8b165cfc5d2fdd56af488dfd1844d869de740 | Cache each thread group's TID within their own namespace.
This avoids requiring a lock in `ThreadGroup.ID`, which in turn breaks the
following lock cycle:
`kernel.taskSetRWMutex` -> `kernel.taskMutex` -> `mm.metadataMutex`
> `mm.mappingRWMutex` -> `kernel.taskSetRWMutex`
(Also, less locking within `createVMALocked` is probably for the better in
general.) | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_exit.go",
"new_path": "pkg/sentry/kernel/task_exit.go",
"diff": "@@ -692,6 +692,7 @@ func (t *Task) exitNotifyLocked(fromPtraceDetach bool) {\n// is via a call to release_task()).\nt.tg.leader.exitNotifyLocked(false)\n} else if tc == 0 {\n+ t.tg.pidWithinNS.Store(0)\nt.tg.processGroup.decRefWithParent(t.tg.parentPG())\n}\nif t.parent != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_start.go",
"new_path": "pkg/sentry/kernel/task_start.go",
"diff": "@@ -296,6 +296,7 @@ func (ts *TaskSet) assignTIDsLocked(t *Task) error {\n}\nreturn err\n}\n+ t.tg.pidWithinNS.Store(int32(t.tg.pidns.tgids[t.tg]))\nreturn nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/threads.go",
"new_path": "pkg/sentry/kernel/threads.go",
"diff": "@@ -17,6 +17,7 @@ package kernel\nimport (\n\"fmt\"\n+ \"gvisor.dev/gvisor/pkg/atomicbitops\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n@@ -325,6 +326,11 @@ type threadGroupNode struct {\n// member tasks. The pidns pointer is immutable.\npidns *PIDNamespace\n+ // pidWithinNS the thread ID of the leader of this thread group within pidns.\n+ // Useful to avoid using locks when determining a thread group leader's own\n+ // TID.\n+ pidWithinNS atomicbitops.Int32\n+\n// eventQueue is notified whenever a event of interest to Task.Wait occurs\n// in a child of this thread group, or a ptrace tracee of a task in this\n// thread group. Events are defined in task_exit.go.\n@@ -425,13 +431,10 @@ func (tg *ThreadGroup) MemberIDs(pidns *PIDNamespace) []ThreadID {\nreturn tasks\n}\n-// ID returns tg's leader's thread ID in its own PID namespace. If tg's leader\n-// is dead, ID returns 0.\n+// ID returns tg's leader's thread ID in its own PID namespace.\n+// If tg's leader is dead, ID returns 0.\nfunc (tg *ThreadGroup) ID() ThreadID {\n- tg.pidns.owner.mu.RLock()\n- id := tg.pidns.tgids[tg]\n- tg.pidns.owner.mu.RUnlock()\n- return id\n+ return ThreadID(tg.pidWithinNS.Load())\n}\n// A taskNode defines the relationship between a task and the rest of the\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -4462,9 +4462,15 @@ cc_binary(\nsrcs = [\"processes.cc\"],\nlinkstatic = 1,\ndeps = [\n+ gtest,\n\"//test/util:capability_util\",\n+ \"//test/util:multiprocess_util\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n+ \"//test/util:thread_util\",\n+ \"@com_google_absl//absl/flags:flag\",\n+ \"@com_google_absl//absl/strings:str_format\",\n+ \"@com_google_absl//absl/time\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/processes.cc",
"new_path": "test/syscalls/linux/processes.cc",
"diff": "#include <sys/syscall.h>\n#include <unistd.h>\n+#include \"gtest/gtest.h\"\n+#include \"absl/flags/flag.h\"\n+#include \"absl/strings/str_format.h\"\n+#include \"absl/time/clock.h\"\n+#include \"absl/time/time.h\"\n#include \"test/util/capability_util.h\"\n+#include \"test/util/multiprocess_util.h\"\n#include \"test/util/test_util.h\"\n+#include \"test/util/thread_util.h\"\n+\n+ABSL_FLAG(bool, processes_test_exec_swap, false,\n+ \"If true, run the ExecSwap function.\");\n+ABSL_FLAG(int, processes_test_exec_swap_pre_clone_pid, -1,\n+ \"Process ID from before clone; required when using \"\n+ \"--processes_test_exec_swap.\");\n+ABSL_FLAG(int, processes_test_exec_swap_pre_clone_tid, -1,\n+ \"Thread ID from before clone; required when using \"\n+ \"--processes_test_exec_swap.\");\n+ABSL_FLAG(int, processes_test_exec_swap_pre_exec_pid, -1,\n+ \"Process ID from before exec; required when using \"\n+ \"--processes_test_exec_swap.\");\n+ABSL_FLAG(int, processes_test_exec_swap_pre_exec_tid, -1,\n+ \"Thread ID from before exec; required when using \"\n+ \"--processes_test_exec_swap.\");\n+ABSL_FLAG(int, processes_test_exec_swap_pipe_fd, -1,\n+ \"File descriptor to write data to; required when using \"\n+ \"--processes_test_exec_swap.\");\nnamespace gvisor {\nnamespace testing {\n@@ -86,5 +111,213 @@ TEST(Processes, SetPGIDOfZombie) {\nEXPECT_EQ(status, 0);\n}\n+int WritePIDToPipe(void* arg) {\n+ int* pipe_fds = reinterpret_cast<int*>(arg);\n+ pid_t child_pid;\n+ TEST_PCHECK(child_pid = getpid());\n+ TEST_PCHECK(write(pipe_fds[1], &child_pid, sizeof(child_pid)) ==\n+ sizeof(child_pid));\n+ _exit(0);\n+}\n+\n+TEST(Processes, TheadSharesSamePID) {\n+ int pipe_fds[2];\n+ ASSERT_THAT(pipe(pipe_fds), SyscallSucceeds());\n+ pid_t test_pid;\n+ ASSERT_THAT(test_pid = getpid(), SyscallSucceeds());\n+ EXPECT_NE(test_pid, 0);\n+ struct clone_arg {\n+ char stack[256] __attribute__((aligned(16)));\n+ char stack_ptr[0];\n+ } ca;\n+ ASSERT_THAT(\n+ clone(WritePIDToPipe, ca.stack_ptr,\n+ CLONE_THREAD | CLONE_SIGHAND | CLONE_VM | CLONE_FS, pipe_fds),\n+ SyscallSucceeds());\n+ pid_t pid_from_child;\n+ TEST_PCHECK(read(pipe_fds[0], &pid_from_child, sizeof(pid_from_child)) ==\n+ sizeof(pid_from_child));\n+ int buf;\n+ TEST_PCHECK(read(pipe_fds[0], &buf, sizeof(buf)) ==\n+ 0); // Wait for cloned thread to exit\n+ ASSERT_THAT(close(pipe_fds[0]), SyscallSucceeds());\n+ ASSERT_THAT(close(pipe_fds[1]), SyscallSucceeds());\n+ EXPECT_EQ(test_pid, pid_from_child);\n+}\n+\n+// ExecSwapResult is used to carry PIDs and TIDs in ExecSwapThreadGroupLeader.\n+struct ExecSwapResult {\n+ int pipe_fd; // FD to write result data to.\n+\n+ // PID and TID before we call clone().\n+ pid_t pre_clone_pid;\n+ pid_t pre_clone_tid;\n+\n+ // PID and TID before the clone calls execv().\n+ pid_t pre_exec_pid;\n+ pid_t pre_exec_tid;\n+\n+ // PID and TID after the execv().\n+ pid_t post_exec_pid;\n+ pid_t post_exec_tid;\n+};\n+\n+// ExecSwapPostExec is the third part of the ExecSwapThreadGroupLeader test.\n+// It is called after the test has fork()'d, clone()'d, and exec()'d into this.\n+// It writes all the PIDs and TIDs from each part of the test to a pipe.\n+int ExecSwapPostExec() {\n+ std::cerr << \"Test exec'd.\" << std::endl;\n+ pid_t pid;\n+ TEST_PCHECK(pid = getpid());\n+ pid_t tid;\n+ TEST_PCHECK(tid = gettid());\n+ ExecSwapResult result;\n+ result.pipe_fd = absl::GetFlag(FLAGS_processes_test_exec_swap_pipe_fd);\n+ result.pre_clone_pid =\n+ absl::GetFlag(FLAGS_processes_test_exec_swap_pre_clone_pid);\n+ result.pre_clone_tid =\n+ absl::GetFlag(FLAGS_processes_test_exec_swap_pre_clone_tid);\n+ result.pre_exec_pid =\n+ absl::GetFlag(FLAGS_processes_test_exec_swap_pre_exec_pid);\n+ result.pre_exec_tid =\n+ absl::GetFlag(FLAGS_processes_test_exec_swap_pre_exec_tid);\n+ result.post_exec_pid = pid;\n+ result.post_exec_tid = tid;\n+ std::cerr << \"Test writing results to pipe FD.\" << std::endl;\n+ TEST_PCHECK(write(result.pipe_fd, &result, sizeof(result)) == sizeof(result));\n+ if (close(result.pipe_fd) != 0) {\n+ std::cerr << \"Failed to close pipe FD: \" << errno << std::endl;\n+ }\n+ std::cerr << \"Test results written out.\" << std::endl;\n+ return 0;\n+}\n+\n+// ExecSwapPreExec is the second part of the ExecSwapThreadGroupLeader test.\n+// It is called after the test has fork()'d and clone()'d.\n+// It calls exec() with flags that cause the test binary to run\n+// ExecSwapPostExec.\n+int ExecSwapPreExec(void* arg) {\n+ ExecSwapResult* result = reinterpret_cast<ExecSwapResult*>(arg);\n+ pid_t pid;\n+ TEST_PCHECK(pid = getpid());\n+ pid_t tid;\n+ TEST_PCHECK(tid = gettid());\n+\n+ ExecveArray const execve_argv = {\n+ \"/proc/self/exe\",\n+ \"--processes_test_exec_swap\",\n+ absl::StrFormat(\"--processes_test_exec_swap_pre_clone_pid=%d\",\n+ result->pre_clone_pid),\n+ absl::StrFormat(\"--processes_test_exec_swap_pre_clone_tid=%d\",\n+ result->pre_clone_tid),\n+ absl::StrFormat(\"--processes_test_exec_swap_pre_exec_pid=%d\", pid),\n+ absl::StrFormat(\"--processes_test_exec_swap_pre_exec_tid=%d\", tid),\n+ absl::StrFormat(\"--processes_test_exec_swap_pipe_fd=%d\", result->pipe_fd),\n+ };\n+ TEST_PCHECK(execv(\"/proc/self/exe\", execve_argv.get()));\n+ _exit(1); // Should be unreachable.\n+}\n+\n+// ExecSwapPreClone is the first part of the ExecSwapThreadGroupLeader test.\n+// It is called after the test has fork()'d.\n+// It calls clone() to run ExecSwapPreExec.\n+void ExecSwapPreClone(int* pipe_fds) {\n+ pid_t pid;\n+ ASSERT_THAT(pid = getpid(), SyscallSucceeds());\n+ pid_t tid;\n+ ASSERT_THAT(tid = gettid(), SyscallSucceeds());\n+ struct clone_arg {\n+ char stack[4096] __attribute__((aligned(16)));\n+ char stack_ptr[0];\n+ } ca;\n+ ExecSwapResult result;\n+ result.pipe_fd = pipe_fds[1];\n+ result.pre_clone_pid = pid;\n+ result.pre_clone_tid = tid;\n+ std::cerr << \"Test cloning.\" << std::endl;\n+ ASSERT_THAT(\n+ clone(ExecSwapPreExec, ca.stack_ptr,\n+ CLONE_THREAD | CLONE_SIGHAND | CLONE_VM | CLONE_FS, &result),\n+ SyscallSucceeds());\n+ // The clone thread will call exec, so just sit around here until it does.\n+ absl::SleepFor(absl::Milliseconds(500));\n+}\n+\n+TEST(Processes, ExecSwapThreadGroupLeader) {\n+ // This test verifies that a non-leading thread calling exec() replaces the\n+ // former leader of its thread group and adopts its thread ID.\n+ // This is the zeroth part of this test, which calls fork() to run\n+ // ExecSwapPreClone in a separate thread group.\n+\n+ int pipe_fds[2];\n+ ASSERT_THAT(pipe(pipe_fds), SyscallSucceeds());\n+ pid_t test_pid;\n+ ASSERT_THAT(test_pid = getpid(), SyscallSucceeds());\n+ pid_t test_tid;\n+ ASSERT_THAT(test_tid = gettid(), SyscallSucceeds());\n+ std::cerr << \"Test forking.\" << std::endl;\n+ pid_t fork_pid = fork();\n+ if (fork_pid == 0) {\n+ ExecSwapPreClone(pipe_fds);\n+ ASSERT_TRUE(false) << \"Did not get replaced by execed child\";\n+ }\n+\n+ std::cerr << \"Waiting for test results.\" << std::endl;\n+ ExecSwapResult result;\n+ TEST_PCHECK(read(pipe_fds[0], &result, sizeof(result)) == sizeof(result));\n+\n+ std::cerr << \"ExecSwap results:\" << std::endl;\n+ std::cerr << \" Parent test process PID / TID:\" << test_pid << \" / \"\n+ << test_tid << std::endl;\n+ std::cerr << \" Parent test child PID, as seen by parent:\" << fork_pid\n+ << std::endl;\n+ std::cerr << \" Pre-clone PID / TID: \" << result.pre_clone_pid << \" / \"\n+ << result.pre_clone_tid << std::endl;\n+ std::cerr << \" Pre-exec PID / TID: \" << result.pre_exec_pid << \" / \"\n+ << result.pre_exec_tid << std::endl;\n+ std::cerr << \" Post-exec PID / TID: \" << result.post_exec_pid << \" / \"\n+ << result.post_exec_tid << std::endl;\n+\n+ ASSERT_THAT(close(pipe_fds[0]), SyscallSucceeds());\n+ ASSERT_THAT(close(pipe_fds[1]), SyscallSucceeds());\n+\n+ // Test starts out as the thread group leader of itself.\n+ EXPECT_EQ(test_pid, test_tid);\n+\n+ // The child is a different thread group altogether.\n+ EXPECT_NE(test_pid, fork_pid);\n+ EXPECT_EQ(fork_pid, result.pre_clone_pid); // Sanity check.\n+\n+ // Before cloning, PID == TID, the child thread is leader of its thread group.\n+ EXPECT_EQ(result.pre_clone_pid, result.pre_clone_tid);\n+\n+ // PID should not change with clone.\n+ EXPECT_EQ(result.pre_clone_pid, result.pre_exec_pid);\n+\n+ // But TID should change with clone.\n+ EXPECT_NE(result.pre_clone_tid, result.pre_exec_tid);\n+\n+ // So we now have PID != TID.\n+ EXPECT_NE(result.pre_exec_pid, result.pre_exec_tid);\n+\n+ // exec'ing does not change the PID, even when done from non-leader thread.\n+ EXPECT_EQ(result.pre_exec_pid, result.post_exec_pid);\n+\n+ // After exec, the PID is back to matching TID.\n+ EXPECT_EQ(result.post_exec_pid, result.post_exec_tid);\n+\n+ // The TID matches the one from before clone.\n+ EXPECT_EQ(result.post_exec_tid, result.pre_clone_tid);\n+}\n+\n} // namespace testing\n} // namespace gvisor\n+\n+int main(int argc, char** argv) {\n+ gvisor::testing::TestInit(&argc, &argv);\n+\n+ if (absl::GetFlag(FLAGS_processes_test_exec_swap)) {\n+ return gvisor::testing::ExecSwapPostExec();\n+ }\n+ return gvisor::testing::RunAllTests();\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Cache each thread group's TID within their own namespace.
This avoids requiring a lock in `ThreadGroup.ID`, which in turn breaks the
following lock cycle:
`kernel.taskSetRWMutex` -> `kernel.taskMutex` -> `mm.metadataMutex`
-> `mm.mappingRWMutex` -> `kernel.taskSetRWMutex`
(Also, less locking within `createVMALocked` is probably for the better in
general.)
PiperOrigin-RevId: 449588573 |
259,992 | 19.05.2022 09:12:33 | 25,200 | 62dcc6f5b0c94b075111b02f6dc39555879bd6e5 | Add `--force` flag to `trace create` command
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/config.go",
"new_path": "pkg/sentry/seccheck/config.go",
"diff": "@@ -68,13 +68,20 @@ type SinkConfig struct {\n}\n// Create reads the session configuration and applies it to the system.\n-func Create(conf *SessionConfig) error {\n+func Create(conf *SessionConfig, force bool) error {\nlog.Debugf(\"Creating seccheck: %+v\", conf)\nsessionsMu.Lock()\ndefer sessionsMu.Unlock()\n+\nif _, ok := sessions[conf.Name]; ok {\n+ if !force {\nreturn fmt.Errorf(\"session %q already exists\", conf.Name)\n}\n+ if err := deleteLocked(conf.Name); err != nil {\n+ return err\n+ }\n+ log.Infof(\"Trace session %q was deleted to be replaced\", conf.Name)\n+ }\nif conf.Name != DefaultSessionName {\nreturn fmt.Errorf(`only a single \"Default\" session is supported`)\n}\n@@ -154,7 +161,11 @@ func setupSink(config SinkConfig) (*os.File, error) {\nfunc Delete(name string) error {\nsessionsMu.Lock()\ndefer sessionsMu.Unlock()\n+ return deleteLocked(name)\n+}\n+// +checklocks:sessionsMu\n+func deleteLocked(name string) error {\nsession := sessions[name]\nif session == nil {\nreturn fmt.Errorf(\"session %q not found\", name)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/controller.go",
"new_path": "runsc/boot/controller.go",
"diff": "@@ -604,6 +604,7 @@ func (cm *containerManager) Signal(args *SignalArgs, _ *struct{}) error {\n// CreateTraceSessionArgs are arguments to the CreateTraceSession method.\ntype CreateTraceSessionArgs struct {\nConfig seccheck.SessionConfig\n+ Force bool\nurpc.FilePayload\n}\n@@ -619,7 +620,7 @@ func (cm *containerManager) CreateTraceSession(args *CreateTraceSessionArgs, _ *\nargs.Config.Sinks[i].FD = fd\n}\n}\n- return seccheck.Create(&args.Config)\n+ return seccheck.Create(&args.Config, args.Force)\n}\n// DeleteTraceSession deletes an existing trace session.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/seccheck.go",
"new_path": "runsc/boot/seccheck.go",
"diff": "@@ -74,5 +74,5 @@ func (c *InitConfig) create(sinkFDs []int) error {\nc.TraceSession.Sinks[i].FD = fd.New(sinkFD)\n}\n}\n- return seccheck.Create(&c.TraceSession)\n+ return seccheck.Create(&c.TraceSession, false)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/trace/create.go",
"new_path": "runsc/cmd/trace/create.go",
"diff": "@@ -30,6 +30,7 @@ import (\n// create implements subcommands.Command for the \"create\" command.\ntype create struct {\nconfig string\n+ force bool\n}\n// Name implements subcommands.Command.\n@@ -51,6 +52,7 @@ func (*create) Usage() string {\n// SetFlags implements subcommands.Command.\nfunc (l *create) SetFlags(f *flag.FlagSet) {\nf.StringVar(&l.config, \"config\", \"\", \"path to the JSON file that describes the session being created\")\n+ f.BoolVar(&l.force, \"force\", false, \"deletes a conflicting session, if one exists\")\n}\n// Execute implements subcommands.Command.\n@@ -87,7 +89,7 @@ func (l *create) Execute(_ context.Context, f *flag.FlagSet, args ...interface{}\nutil.Fatalf(\"loading sandbox: %v\", err)\n}\n- if err := c.Sandbox.CreateTraceSession(sessionConfig); err != nil {\n+ if err := c.Sandbox.CreateTraceSession(sessionConfig, l.force); err != nil {\nutil.Fatalf(\"creating session: %v\", err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/trace_test.go",
"new_path": "runsc/container/trace_test.go",
"diff": "@@ -17,6 +17,7 @@ package container\nimport (\n\"encoding/json\"\n\"io/ioutil\"\n+ \"strings\"\n\"testing\"\n\"time\"\n@@ -28,6 +29,15 @@ import (\n\"gvisor.dev/gvisor/runsc/boot\"\n)\n+func remoteSinkConfig(endpoint string) seccheck.SinkConfig {\n+ return seccheck.SinkConfig{\n+ Name: \"remote\",\n+ Config: map[string]interface{}{\n+ \"endpoint\": endpoint,\n+ },\n+ }\n+}\n+\n// Test that setting up a trace session configuration in PodInitConfig creates\n// a session before container creation.\nfunc TestTraceStartup(t *testing.T) {\n@@ -56,14 +66,7 @@ func TestTraceStartup(t *testing.T) {\nContextFields: []string{\"container_id\"},\n},\n},\n- Sinks: []seccheck.SinkConfig{\n- {\n- Name: \"remote\",\n- Config: map[string]interface{}{\n- \"endpoint\": server.Path,\n- },\n- },\n- },\n+ Sinks: []seccheck.SinkConfig{remoteSinkConfig(server.Path)},\n},\n}\nencoder := json.NewEncoder(podInitConfig)\n@@ -144,16 +147,9 @@ func TestTraceLifecycle(t *testing.T) {\nContextFields: []string{\"container_id\"},\n},\n},\n- Sinks: []seccheck.SinkConfig{\n- {\n- Name: \"remote\",\n- Config: map[string]interface{}{\n- \"endpoint\": server.Path,\n- },\n- },\n- },\n+ Sinks: []seccheck.SinkConfig{remoteSinkConfig(server.Path)},\n}\n- if err := cont.Sandbox.CreateTraceSession(&session); err != nil {\n+ if err := cont.Sandbox.CreateTraceSession(&session, false); err != nil {\nt.Fatalf(\"CreateTraceSession(): %v\", err)\n}\n@@ -217,3 +213,87 @@ func TestTraceLifecycle(t *testing.T) {\nt.Errorf(\"point received after session was deleted: %+v\", server.GetPoints())\n}\n}\n+\n+func TestTraceForceCreate(t *testing.T) {\n+ spec, conf := sleepSpecConf(t)\n+ _, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)\n+ if err != nil {\n+ t.Fatalf(\"error setting up container: %v\", err)\n+ }\n+ defer cleanup()\n+\n+ // Create and start the container.\n+ args := Args{\n+ ID: testutil.RandomContainerID(),\n+ Spec: spec,\n+ BundleDir: bundleDir,\n+ }\n+ cont, err := New(conf, args)\n+ if err != nil {\n+ t.Fatalf(\"error creating container: %v\", err)\n+ }\n+ defer cont.Destroy()\n+ if err := cont.Start(conf); err != nil {\n+ t.Fatalf(\"error starting container: %v\", err)\n+ }\n+\n+ // Create a new trace session that will be overwritten.\n+ server, err := test.NewServer()\n+ if err != nil {\n+ t.Fatalf(\"newServer(): %v\", err)\n+ }\n+ defer server.Close()\n+\n+ session := seccheck.SessionConfig{\n+ Name: \"Default\",\n+ Points: []seccheck.PointConfig{\n+ {Name: \"sentry/exit_notify_parent\"},\n+ },\n+ Sinks: []seccheck.SinkConfig{remoteSinkConfig(server.Path)},\n+ }\n+ if err := cont.Sandbox.CreateTraceSession(&session, false); err != nil {\n+ t.Fatalf(\"CreateTraceSession(): %v\", err)\n+ }\n+\n+ // Trigger the configured point to check that trace session is enabled.\n+ if ws, err := execute(conf, cont, \"/bin/true\"); err != nil || ws != 0 {\n+ t.Fatalf(\"exec: true, ws: %v, err: %v\", ws, err)\n+ }\n+ if err := server.WaitForCount(1); err != nil {\n+ t.Fatalf(\"WaitForCount(1): %v\", err)\n+ }\n+ pt := server.GetPoints()[0]\n+ if want := pb.MessageType_MESSAGE_SENTRY_EXIT_NOTIFY_PARENT; pt.MsgType != want {\n+ t.Errorf(\"wrong message type, want: %v, got: %v\", want, pt.MsgType)\n+ }\n+ server.Reset()\n+\n+ // Check that creating the same session fails.\n+ if err := cont.Sandbox.CreateTraceSession(&session, false); err == nil || !strings.Contains(err.Error(), \"already exists\") {\n+ t.Errorf(\"CreateTraceSession() again failed with wrong error: %v\", err)\n+ }\n+\n+ // Re-create the session with a different point using force=true and check\n+ // that it overwrote the other trace session.\n+ session = seccheck.SessionConfig{\n+ Name: \"Default\",\n+ Points: []seccheck.PointConfig{\n+ {Name: \"sentry/task_exit\"},\n+ },\n+ Sinks: []seccheck.SinkConfig{remoteSinkConfig(server.Path)},\n+ }\n+ if err := cont.Sandbox.CreateTraceSession(&session, true); err != nil {\n+ t.Fatalf(\"CreateTraceSession(force): %v\", err)\n+ }\n+\n+ if ws, err := execute(conf, cont, \"/bin/true\"); err != nil || ws != 0 {\n+ t.Fatalf(\"exec: true, ws: %v, err: %v\", ws, err)\n+ }\n+ if err := server.WaitForCount(1); err != nil {\n+ t.Fatalf(\"WaitForCount(1): %v\", err)\n+ }\n+ pt = server.GetPoints()[0]\n+ if want := pb.MessageType_MESSAGE_SENTRY_TASK_EXIT; pt.MsgType != want {\n+ t.Errorf(\"wrong message type, want: %v, got: %v\", want, pt.MsgType)\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -390,7 +390,7 @@ func (s *Sandbox) Processes(cid string) ([]*control.Process, error) {\n}\n// CreateTraceSession creates a new trace session.\n-func (s *Sandbox) CreateTraceSession(config *seccheck.SessionConfig) error {\n+func (s *Sandbox) CreateTraceSession(config *seccheck.SessionConfig, force bool) error {\nlog.Debugf(\"Creating trace session in sandbox %q\", s.ID)\nsinkFiles, err := seccheck.SetupSinks(config.Sinks)\n@@ -411,6 +411,7 @@ func (s *Sandbox) CreateTraceSession(config *seccheck.SessionConfig) error {\narg := boot.CreateTraceSessionArgs{\nConfig: *config,\n+ Force: force,\nFilePayload: urpc.FilePayload{\nFiles: sinkFiles,\n},\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add `--force` flag to `trace create` command
Updates #4805
PiperOrigin-RevId: 449759478 |
259,907 | 19.05.2022 10:45:16 | 25,200 | cf039a68d8b6b5370506e576d3b5671457d802b6 | Add trace procfs command.
`runsc trace procfs` should dump a lot of relevant procfs information about
all the processes in the container. Falco will consume this.
For now the only procfs entry that the procfs dump returns is /proc/[pid]/exe.
Will incrementally add support for the remaining in separate changes.
Updates | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/BUILD",
"new_path": "runsc/boot/BUILD",
"diff": "@@ -121,6 +121,7 @@ go_library(\n\"//runsc/boot/filter\",\n\"//runsc/boot/platforms\",\n\"//runsc/boot/pprof\",\n+ \"//runsc/boot/procfs\",\n\"//runsc/config\",\n\"//runsc/specutils\",\n\"//runsc/specutils/seccomp\",\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/controller.go",
"new_path": "runsc/boot/controller.go",
"diff": "@@ -38,6 +38,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n\"gvisor.dev/gvisor/pkg/urpc\"\n\"gvisor.dev/gvisor/runsc/boot/pprof\"\n+ \"gvisor.dev/gvisor/runsc/boot/procfs\"\n\"gvisor.dev/gvisor/runsc/config\"\n\"gvisor.dev/gvisor/runsc/specutils\"\n)\n@@ -90,6 +91,9 @@ const (\n// ContMgrListTraceSessions lists a trace session.\nContMgrListTraceSessions = \"containerManager.ListTraceSessions\"\n+\n+ // ContMgrProcfsDump dumps sandbox procfs state.\n+ ContMgrProcfsDump = \"containerManager.ProcfsDump\"\n)\nconst (\n@@ -635,3 +639,21 @@ func (cm *containerManager) ListTraceSessions(_ *struct{}, out *[]seccheck.Sessi\nseccheck.List(out)\nreturn nil\n}\n+\n+// ProcfsDump dumps procfs state of the sandbox.\n+func (cm *containerManager) ProcfsDump(_ *struct{}, out *[]procfs.ProcessProcfsDump) error {\n+ log.Debugf(\"containerManager.ProcfsDump\")\n+ ts := cm.l.k.TaskSet()\n+ pidns := ts.Root\n+ *out = make([]procfs.ProcessProcfsDump, 0, len(cm.l.processes))\n+ for _, tg := range pidns.ThreadGroups() {\n+ pid := pidns.IDOfThreadGroup(tg)\n+ procDump, err := procfs.Dump(tg.Leader(), pid)\n+ if err != nil {\n+ log.Warningf(\"skipping procfs dump for PID %s: %v\", pid, err)\n+ continue\n+ }\n+ *out = append(*out, procDump)\n+ }\n+ return nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader.go",
"new_path": "runsc/boot/loader.go",
"diff": "@@ -139,7 +139,7 @@ type Loader struct {\n// processes are keyed with container ID and pid=0, while exec invocations\n// have the corresponding pid set.\n//\n- // processes is guardded by mu.\n+ // processes is guarded by mu.\nprocesses map[execID]*execProcess\n// mountHints provides extra information about mounts for containers that\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "runsc/boot/procfs/BUILD",
"diff": "+load(\"//tools:defs.bzl\", \"go_library\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_library(\n+ name = \"procfs\",\n+ srcs = [\"dump.go\"],\n+ visibility = [\"//runsc:__subpackages__\"],\n+ deps = [\n+ \"//pkg/context\",\n+ \"//pkg/log\",\n+ \"//pkg/sentry/kernel\",\n+ \"//pkg/sentry/mm\",\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "runsc/boot/procfs/dump.go",
"diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// Package procfs holds utilities for getting procfs information for sandboxed\n+// processes.\n+package procfs\n+\n+import (\n+ \"fmt\"\n+\n+ \"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/log\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/mm\"\n+)\n+\n+// ProcessProcfsDump contains the procfs dump for one process.\n+type ProcessProcfsDump struct {\n+ // PID is the process ID.\n+ PID int32 `json:\"pid,omitempty\"`\n+ // Exe is the symlink target of /proc/[pid]/exe.\n+ Exe string `json:\"exe,omitempty\"`\n+}\n+\n+// getMM returns t's MemoryManager. On success, the MemoryManager's users count\n+// is incremented, and must be decremented by the caller when it is no longer\n+// in use.\n+func getMM(t *kernel.Task) *mm.MemoryManager {\n+ var mm *mm.MemoryManager\n+ t.WithMuLocked(func(*kernel.Task) {\n+ mm = t.MemoryManager()\n+ })\n+ if mm == nil || !mm.IncUsers() {\n+ return nil\n+ }\n+ return mm\n+}\n+\n+func getExecutablePath(ctx context.Context, pid kernel.ThreadID, mm *mm.MemoryManager) string {\n+ exec := mm.Executable()\n+ if exec == nil {\n+ log.Warningf(\"No executable found for PID %s\", pid)\n+ return \"\"\n+ }\n+ defer exec.DecRef(ctx)\n+\n+ return exec.PathnameWithDeleted(ctx)\n+}\n+\n+// Dump returns a procfs dump for process pid. t must be a task in process pid.\n+func Dump(t *kernel.Task, pid kernel.ThreadID) (ProcessProcfsDump, error) {\n+ ctx := t.AsyncContext()\n+\n+ mm := getMM(t)\n+ if mm == nil {\n+ return ProcessProcfsDump{}, fmt.Errorf(\"no MM found for PID %s\", pid)\n+ }\n+ defer mm.DecUsers(ctx)\n+\n+ return ProcessProcfsDump{\n+ PID: int32(pid),\n+ Exe: getExecutablePath(ctx, pid, mm),\n+ }, nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/trace/BUILD",
"new_path": "runsc/cmd/trace/BUILD",
"diff": "@@ -9,12 +9,14 @@ go_library(\n\"delete.go\",\n\"list.go\",\n\"metadata.go\",\n+ \"procfs.go\",\n\"trace.go\",\n],\nvisibility = [\n\"//runsc:__subpackages__\",\n],\ndeps = [\n+ \"//pkg/log\",\n\"//pkg/sentry/seccheck\",\n\"//runsc/cmd/util\",\n\"//runsc/config\",\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "runsc/cmd/trace/procfs.go",
"diff": "+// Copyright 2022 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package trace\n+\n+import (\n+ \"context\"\n+ \"encoding/json\"\n+ \"fmt\"\n+\n+ \"github.com/google/subcommands\"\n+ \"gvisor.dev/gvisor/pkg/log\"\n+ \"gvisor.dev/gvisor/runsc/cmd/util\"\n+ \"gvisor.dev/gvisor/runsc/config\"\n+ \"gvisor.dev/gvisor/runsc/container\"\n+ \"gvisor.dev/gvisor/runsc/flag\"\n+)\n+\n+// procfs implements subcommands.Command for the \"procfs\" command.\n+type procfs struct {\n+}\n+\n+// Name implements subcommands.Command.\n+func (*procfs) Name() string {\n+ return \"procfs\"\n+}\n+\n+// Synopsis implements subcommands.Command.\n+func (*procfs) Synopsis() string {\n+ return \"dump procfs state for sandbox\"\n+}\n+\n+// Usage implements subcommands.Command.\n+func (*procfs) Usage() string {\n+ return `procfs <sandbox id> - get procfs dump for a trace session\n+`\n+}\n+\n+// SetFlags implements subcommands.Command.\n+func (*procfs) SetFlags(*flag.FlagSet) {}\n+\n+// Execute implements subcommands.Command.\n+func (*procfs) Execute(_ context.Context, f *flag.FlagSet, args ...interface{}) subcommands.ExitStatus {\n+ if f.NArg() != 1 {\n+ f.Usage()\n+ return subcommands.ExitUsageError\n+ }\n+\n+ id := f.Arg(0)\n+ conf := args[0].(*config.Config)\n+\n+ opts := container.LoadOpts{\n+ SkipCheck: true,\n+ RootContainer: true,\n+ }\n+ c, err := container.Load(conf.RootDir, container.FullID{ContainerID: id}, opts)\n+ if err != nil {\n+ util.Fatalf(\"loading sandbox: %v\", err)\n+ }\n+\n+ dump, err := c.Sandbox.ProcfsDump()\n+ if err != nil {\n+ util.Fatalf(\"procfs dump: %v\", err)\n+ }\n+\n+ fmt.Println(\"PROCFS DUMP\")\n+ for _, procDump := range dump {\n+ out, err := json.Marshal(procDump)\n+ if err != nil {\n+ log.Warningf(\"json.Marshal failed to marshal %+v: %v\", procDump, err)\n+ continue\n+ }\n+\n+ fmt.Println(\"\")\n+ fmt.Println(string(out))\n+ }\n+ return subcommands.ExitSuccess\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/trace/trace.go",
"new_path": "runsc/cmd/trace/trace.go",
"diff": "@@ -65,5 +65,6 @@ func createCommander(f *flag.FlagSet) *subcommands.Commander {\ncdr.Register(new(delete), \"\")\ncdr.Register(new(list), \"\")\ncdr.Register(new(metadata), \"\")\n+ cdr.Register(new(procfs), \"\")\nreturn cdr\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/trace_test.go",
"new_path": "runsc/container/trace_test.go",
"diff": "@@ -297,3 +297,47 @@ func TestTraceForceCreate(t *testing.T) {\nt.Errorf(\"wrong message type, want: %v, got: %v\", want, pt.MsgType)\n}\n}\n+\n+func TestProcfsDump(t *testing.T) {\n+ spec, conf := sleepSpecConf(t)\n+ _, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)\n+ if err != nil {\n+ t.Fatalf(\"error setting up container: %v\", err)\n+ }\n+ defer cleanup()\n+\n+ // Create and start the container.\n+ args := Args{\n+ ID: testutil.RandomContainerID(),\n+ Spec: spec,\n+ BundleDir: bundleDir,\n+ }\n+ cont, err := New(conf, args)\n+ if err != nil {\n+ t.Fatalf(\"error creating container: %v\", err)\n+ }\n+ defer cont.Destroy()\n+ if err := cont.Start(conf); err != nil {\n+ t.Fatalf(\"error starting container: %v\", err)\n+ }\n+\n+ procfsDump, err := cont.Sandbox.ProcfsDump()\n+ if err != nil {\n+ t.Fatalf(\"ProcfsDump() failed: %v\", err)\n+ }\n+\n+ // Sleep should be the only process running in the container.\n+ if len(procfsDump) != 1 {\n+ t.Fatalf(\"got incorrect number of proc results: %+v\", procfsDump)\n+ }\n+\n+ // Sleep should be PID 1.\n+ if procfsDump[0].PID != 1 {\n+ t.Errorf(\"expected sleep process to be pid 1, got %d\", procfsDump[0].PID)\n+ }\n+\n+ // Check that bin/sleep is part of the executable path.\n+ if wantExeSubStr := \"bin/sleep\"; !strings.HasSuffix(procfsDump[0].Exe, wantExeSubStr) {\n+ t.Errorf(\"expected %q to be part of execuable path %q\", wantExeSubStr, procfsDump[0].Exe)\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/BUILD",
"new_path": "runsc/sandbox/BUILD",
"diff": "@@ -30,6 +30,7 @@ go_library(\n\"//pkg/unet\",\n\"//pkg/urpc\",\n\"//runsc/boot\",\n+ \"//runsc/boot/procfs\",\n\"//runsc/cgroup\",\n\"//runsc/config\",\n\"//runsc/console\",\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -46,6 +46,7 @@ import (\n\"gvisor.dev/gvisor/pkg/unet\"\n\"gvisor.dev/gvisor/pkg/urpc\"\n\"gvisor.dev/gvisor/runsc/boot\"\n+ \"gvisor.dev/gvisor/runsc/boot/procfs\"\n\"gvisor.dev/gvisor/runsc/cgroup\"\n\"gvisor.dev/gvisor/runsc/config\"\n\"gvisor.dev/gvisor/runsc/console\"\n@@ -453,6 +454,22 @@ func (s *Sandbox) ListTraceSessions() ([]seccheck.SessionConfig, error) {\nreturn sessions, nil\n}\n+// ProcfsDump collects and returns a procfs dump for the sandbox.\n+func (s *Sandbox) ProcfsDump() ([]procfs.ProcessProcfsDump, error) {\n+ log.Debugf(\"Procfs dump %q\", s.ID)\n+ conn, err := s.sandboxConnect()\n+ if err != nil {\n+ return nil, err\n+ }\n+ defer conn.Close()\n+\n+ var procfsDump []procfs.ProcessProcfsDump\n+ if err := conn.Call(boot.ContMgrProcfsDump, nil, &procfsDump); err != nil {\n+ return nil, fmt.Errorf(\"getting sandbox %q stacks: %v\", s.ID, err)\n+ }\n+ return procfsDump, nil\n+}\n+\n// NewCGroup returns the sandbox's Cgroup, or an error if it does not have one.\nfunc (s *Sandbox) NewCGroup() (cgroup.Cgroup, error) {\nreturn cgroup.NewFromPid(s.Pid.load(), false /* useSystemd */)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add trace procfs command.
`runsc trace procfs` should dump a lot of relevant procfs information about
all the processes in the container. Falco will consume this.
For now the only procfs entry that the procfs dump returns is /proc/[pid]/exe.
Will incrementally add support for the remaining in separate changes.
Updates #4805
PiperOrigin-RevId: 449783478 |
259,907 | 19.05.2022 11:27:56 | 25,200 | 6fdeba8d7840f110ee36ef877ed6384674349868 | Add support for /prod/[pid]/cmdline and /proc/[pid]/environ to trace procfs.
This change exports some logic in fsimpl/proc so that runsc/boot can use it.
Added tests for these fields.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/task.go",
"new_path": "pkg/sentry/fsimpl/proc/task.go",
"diff": "@@ -54,10 +54,10 @@ func (fs *filesystem) newTaskInode(ctx context.Context, task *kernel.Task, pidns\ncontents := map[string]kernfs.Inode{\n\"auxv\": fs.newTaskOwnedInode(ctx, task, fs.NextIno(), 0444, &auxvData{task: task}),\n- \"cmdline\": fs.newTaskOwnedInode(ctx, task, fs.NextIno(), 0444, &cmdlineData{task: task, arg: cmdlineDataArg}),\n+ \"cmdline\": fs.newTaskOwnedInode(ctx, task, fs.NextIno(), 0444, &metadataData{task: task, metaType: Cmdline}),\n\"comm\": fs.newComm(ctx, task, fs.NextIno(), 0444),\n\"cwd\": fs.newCwdSymlink(ctx, task, fs.NextIno()),\n- \"environ\": fs.newTaskOwnedInode(ctx, task, fs.NextIno(), 0444, &cmdlineData{task: task, arg: environDataArg}),\n+ \"environ\": fs.newTaskOwnedInode(ctx, task, fs.NextIno(), 0444, &metadataData{task: task, metaType: Environ}),\n\"exe\": fs.newExeSymlink(ctx, task, fs.NextIno()),\n\"fd\": fs.newFDDirInode(ctx, task),\n\"fdinfo\": fs.newFDInfoDirInode(ctx, task),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/task_files.go",
"new_path": "pkg/sentry/fsimpl/proc/task_files.go",
"diff": "@@ -133,56 +133,35 @@ func (d *auxvData) Generate(ctx context.Context, buf *bytes.Buffer) error {\nreturn nil\n}\n-// execArgType enumerates the types of exec arguments that are exposed through\n-// proc.\n-type execArgType int\n+// MetadataType enumerates the types of metadata that is exposed through proc.\n+type MetadataType int\nconst (\n- cmdlineDataArg execArgType = iota\n- environDataArg\n-)\n-\n-// cmdlineData implements vfs.DynamicBytesSource for /proc/[pid]/cmdline.\n-//\n-// +stateify savable\n-type cmdlineData struct {\n- kernfs.DynamicBytesFile\n-\n- task *kernel.Task\n-\n- // arg is the type of exec argument this file contains.\n- arg execArgType\n-}\n-\n-var _ dynamicInode = (*cmdlineData)(nil)\n+ // Cmdline represents /proc/[pid]/cmdline.\n+ Cmdline MetadataType = iota\n-// Generate implements vfs.DynamicBytesSource.Generate.\n-func (d *cmdlineData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n- if d.task.ExitState() == kernel.TaskExitDead {\n- return linuxerr.ESRCH\n- }\n- m, err := getMMIncRef(d.task)\n- if err != nil {\n- // Return empty file.\n- return nil\n- }\n- defer m.DecUsers(ctx)\n+ // Environ represents /proc/[pid]/environ.\n+ Environ\n+)\n+// GetMetadata fetches the process's metadata of type t and writes it into\n+// buf. The process is identified by mm.\n+func GetMetadata(ctx context.Context, mm *mm.MemoryManager, buf *bytes.Buffer, t MetadataType) error {\n// Figure out the bounds of the exec arg we are trying to read.\nvar ar hostarch.AddrRange\n- switch d.arg {\n- case cmdlineDataArg:\n+ switch t {\n+ case Cmdline:\nar = hostarch.AddrRange{\n- Start: m.ArgvStart(),\n- End: m.ArgvEnd(),\n+ Start: mm.ArgvStart(),\n+ End: mm.ArgvEnd(),\n}\n- case environDataArg:\n+ case Environ:\nar = hostarch.AddrRange{\n- Start: m.EnvvStart(),\n- End: m.EnvvEnd(),\n+ Start: mm.EnvvStart(),\n+ End: mm.EnvvEnd(),\n}\ndefault:\n- panic(fmt.Sprintf(\"unknown exec arg type %v\", d.arg))\n+ panic(fmt.Sprintf(\"unknown exec arg type %v\", t))\n}\nif ar.Start == 0 || ar.End == 0 {\n// Don't attempt to read before the start/end are set up.\n@@ -193,7 +172,7 @@ func (d *cmdlineData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n// until Linux 4.9 (272ddc8b3735 \"proc: don't use FOLL_FORCE for reading\n// cmdline and environment\").\nwriter := &bufferWriter{buf: buf}\n- if n, err := m.CopyInTo(ctx, hostarch.AddrRangeSeqOf(ar), writer, usermem.IOOpts{}); n == 0 || err != nil {\n+ if n, err := mm.CopyInTo(ctx, hostarch.AddrRangeSeqOf(ar), writer, usermem.IOOpts{}); n == 0 || err != nil {\n// Nothing to copy or something went wrong.\nreturn err\n}\n@@ -201,7 +180,7 @@ func (d *cmdlineData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n// On Linux, if the NULL byte at the end of the argument vector has been\n// overwritten, it continues reading the environment vector as part of\n// the argument vector.\n- if d.arg == cmdlineDataArg && buf.Bytes()[buf.Len()-1] != 0 {\n+ if t == Cmdline && buf.Bytes()[buf.Len()-1] != 0 {\nif end := bytes.IndexByte(buf.Bytes(), 0); end != -1 {\n// If we found a NULL character somewhere else in argv, truncate the\n// return up to the NULL terminator (including it).\n@@ -211,8 +190,8 @@ func (d *cmdlineData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n// There is no NULL terminator in the string, return into envp.\narEnvv := hostarch.AddrRange{\n- Start: m.EnvvStart(),\n- End: m.EnvvEnd(),\n+ Start: mm.EnvvStart(),\n+ End: mm.EnvvEnd(),\n}\n// Upstream limits the returned amount to one page of slop.\n@@ -231,7 +210,7 @@ func (d *cmdlineData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n}\narEnvv.End = end\n}\n- if _, err := m.CopyInTo(ctx, hostarch.AddrRangeSeqOf(arEnvv), writer, usermem.IOOpts{}); err != nil {\n+ if _, err := mm.CopyInTo(ctx, hostarch.AddrRangeSeqOf(arEnvv), writer, usermem.IOOpts{}); err != nil {\nreturn err\n}\n@@ -246,6 +225,36 @@ func (d *cmdlineData) Generate(ctx context.Context, buf *bytes.Buffer) error {\nreturn nil\n}\n+// metadataData implements vfs.DynamicBytesSource for proc metadata fields like:\n+// - /proc/[pid]/cmdline\n+// - /proc/[pid]/environ\n+//\n+// +stateify savable\n+type metadataData struct {\n+ kernfs.DynamicBytesFile\n+\n+ task *kernel.Task\n+\n+ // arg is the type of exec argument this file contains.\n+ metaType MetadataType\n+}\n+\n+var _ dynamicInode = (*metadataData)(nil)\n+\n+// Generate implements vfs.DynamicBytesSource.Generate.\n+func (d *metadataData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+ if d.task.ExitState() == kernel.TaskExitDead {\n+ return linuxerr.ESRCH\n+ }\n+ m, err := getMMIncRef(d.task)\n+ if err != nil {\n+ // Return empty file.\n+ return nil\n+ }\n+ defer m.DecUsers(ctx)\n+ return GetMetadata(ctx, m, buf, d.metaType)\n+}\n+\n// +stateify savable\ntype commInode struct {\nkernfs.DynamicBytesFile\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/procfs/BUILD",
"new_path": "runsc/boot/procfs/BUILD",
"diff": "@@ -9,6 +9,7 @@ go_library(\ndeps = [\n\"//pkg/context\",\n\"//pkg/log\",\n+ \"//pkg/sentry/fsimpl/proc\",\n\"//pkg/sentry/kernel\",\n\"//pkg/sentry/mm\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/procfs/dump.go",
"new_path": "runsc/boot/procfs/dump.go",
"diff": "package procfs\nimport (\n+ \"bytes\"\n\"fmt\"\n+ \"strings\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/log\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/proc\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/mm\"\n)\n@@ -31,6 +34,10 @@ type ProcessProcfsDump struct {\nPID int32 `json:\"pid,omitempty\"`\n// Exe is the symlink target of /proc/[pid]/exe.\nExe string `json:\"exe,omitempty\"`\n+ // Args is /proc/[pid]/cmdline split into an array.\n+ Args []string `json:\"args,omitempty\"`\n+ // Env is /proc/[pid]/environ split into an array.\n+ Env []string `json:\"env,omitempty\"`\n}\n// getMM returns t's MemoryManager. On success, the MemoryManager's users count\n@@ -58,6 +65,18 @@ func getExecutablePath(ctx context.Context, pid kernel.ThreadID, mm *mm.MemoryMa\nreturn exec.PathnameWithDeleted(ctx)\n}\n+func getMetadataArray(ctx context.Context, pid kernel.ThreadID, mm *mm.MemoryManager, metaType proc.MetadataType) []string {\n+ buf := bytes.Buffer{}\n+ if err := proc.GetMetadata(ctx, mm, &buf, metaType); err != nil {\n+ log.Warningf(\"failed to get %v metadata for PID %s: %v\", metaType, pid, err)\n+ return nil\n+ }\n+ // As per proc(5), /proc/[pid]/cmdline may have \"a further null byte after\n+ // the last string\". Similarly, for /proc/[pid]/environ \"there may be a null\n+ // byte at the end\". So trim off the last null byte if it exists.\n+ return strings.Split(strings.TrimSuffix(buf.String(), \"\\000\"), \"\\000\")\n+}\n+\n// Dump returns a procfs dump for process pid. t must be a task in process pid.\nfunc Dump(t *kernel.Task, pid kernel.ThreadID) (ProcessProcfsDump, error) {\nctx := t.AsyncContext()\n@@ -71,5 +90,7 @@ func Dump(t *kernel.Task, pid kernel.ThreadID) (ProcessProcfsDump, error) {\nreturn ProcessProcfsDump{\nPID: int32(pid),\nExe: getExecutablePath(ctx, pid, mm),\n+ Args: getMetadataArray(ctx, pid, mm, proc.Cmdline),\n+ Env: getMetadataArray(ctx, pid, mm, proc.Environ),\n}, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/trace_test.go",
"new_path": "runsc/container/trace_test.go",
"diff": "@@ -300,6 +300,8 @@ func TestTraceForceCreate(t *testing.T) {\nfunc TestProcfsDump(t *testing.T) {\nspec, conf := sleepSpecConf(t)\n+ testEnv := \"GVISOR_IS_GREAT=true\"\n+ spec.Process.Env = append(spec.Process.Env, testEnv)\n_, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)\nif err != nil {\nt.Fatalf(\"error setting up container: %v\", err)\n@@ -340,4 +342,22 @@ func TestProcfsDump(t *testing.T) {\nif wantExeSubStr := \"bin/sleep\"; !strings.HasSuffix(procfsDump[0].Exe, wantExeSubStr) {\nt.Errorf(\"expected %q to be part of execuable path %q\", wantExeSubStr, procfsDump[0].Exe)\n}\n+\n+ if len(procfsDump[0].Args) != 2 {\n+ t.Errorf(\"expected 2 args, but got %+v\", procfsDump[0].Args)\n+ } else {\n+ if procfsDump[0].Args[0] != \"sleep\" || procfsDump[0].Args[1] != \"1000\" {\n+ t.Errorf(\"expected args %q but got %+v\", \"sleep 1000\", procfsDump[0].Args)\n+ }\n+ }\n+\n+ testEnvFound := false\n+ for _, env := range procfsDump[0].Env {\n+ if env == testEnv {\n+ testEnvFound = true\n+ }\n+ }\n+ if !testEnvFound {\n+ t.Errorf(\"expected to find %q env but did not find it, got env %+v\", testEnv, procfsDump[0].Env)\n+ }\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add support for /prod/[pid]/cmdline and /proc/[pid]/environ to trace procfs.
This change exports some logic in fsimpl/proc so that runsc/boot can use it.
Added tests for these fields.
Updates #4805
PiperOrigin-RevId: 449794552 |
259,868 | 19.05.2022 11:44:41 | 25,200 | 7db613ab1cd66fe63c60d18127bdc8c47b5643c6 | BuildKite: Always do a clean checkout of the repository. | [
{
"change_type": "MODIFY",
"old_path": ".buildkite/pipeline.yaml",
"new_path": ".buildkite/pipeline.yaml",
"diff": "@@ -38,6 +38,9 @@ _templates:\n./pkg/tcpip/transport/tcp\n./pkg/tcpip/transport/udp\n./pkg/waiter\n+env:\n+ # Force a clean checkout every time to avoid reuse of files between runs.\n+ BUILDKITE_CLEAN_CHECKOUT: true\nsteps:\n# Run basic smoke tests before preceding to other tests.\n"
},
{
"change_type": "MODIFY",
"old_path": ".buildkite/release.yaml",
"new_path": ".buildkite/release.yaml",
"diff": "@@ -10,6 +10,10 @@ _templates:\n- exit_status: \"*\"\nlimit: 2\n+env:\n+ # Force a clean checkout every time to avoid reuse of files between runs.\n+ BUILDKITE_CLEAN_CHECKOUT: true\n+\nsteps:\n- <<: *common\nlabel: \":ship: Push all images (x86_64)\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | BuildKite: Always do a clean checkout of the repository.
PiperOrigin-RevId: 449798496 |
259,853 | 19.05.2022 12:05:08 | 25,200 | 4d4b2b99c88bb6c97a7917d7682ec710eb537e99 | tmpfs: use lockdep mutexes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/BUILD",
"new_path": "pkg/sentry/fsimpl/tmpfs/BUILD",
"diff": "load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\nload(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\n+load(\"//pkg/sync/locking:locking.bzl\", \"declare_mutex\", \"declare_rwmutex\")\nlicenses([\"notice\"])\n@@ -37,6 +38,34 @@ go_template_instance(\n},\n)\n+declare_mutex(\n+ name = \"inode_mutex\",\n+ out = \"inode_mutex.go\",\n+ package = \"tmpfs\",\n+ prefix = \"inode\",\n+)\n+\n+declare_mutex(\n+ name = \"pages_used_mutex\",\n+ out = \"pages_used_mutex.go\",\n+ package = \"tmpfs\",\n+ prefix = \"pagesUsed\",\n+)\n+\n+declare_mutex(\n+ name = \"iter_mutex\",\n+ out = \"iter_mutex.go\",\n+ package = \"tmpfs\",\n+ prefix = \"iter\",\n+)\n+\n+declare_rwmutex(\n+ name = \"filesystem_mutex\",\n+ out = \"filesystem_mutex.go\",\n+ package = \"tmpfs\",\n+ prefix = \"filesystem\",\n+)\n+\ngo_library(\nname = \"tmpfs\",\nsrcs = [\n@@ -44,9 +73,13 @@ go_library(\n\"device_file.go\",\n\"directory.go\",\n\"filesystem.go\",\n+ \"filesystem_mutex.go\",\n\"fstree.go\",\n+ \"inode_mutex.go\",\n\"inode_refs.go\",\n+ \"iter_mutex.go\",\n\"named_pipe.go\",\n+ \"pages_used_mutex.go\",\n\"regular_file.go\",\n\"save_restore.go\",\n\"socket_file.go\",\n@@ -82,6 +115,7 @@ go_library(\n\"//pkg/sentry/vfs\",\n\"//pkg/sentry/vfs/memxattr\",\n\"//pkg/sync\",\n+ \"//pkg/sync/locking\",\n\"//pkg/usermem\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/directory.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/directory.go",
"diff": "@@ -21,7 +21,6 @@ import (\n\"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n- \"gvisor.dev/gvisor/pkg/sync\"\n)\n// +stateify savable\n@@ -44,7 +43,7 @@ type directory struct {\n// (with inode == nil) that represent the iteration position of\n// directoryFDs. childList is used to support directoryFD.IterDirents()\n// efficiently. childList is protected by iterMu.\n- iterMu sync.Mutex `state:\"nosave\"`\n+ iterMu iterMutex `state:\"nosave\"`\nchildList dentryList\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"diff": "@@ -45,7 +45,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/usage\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs/memxattr\"\n- \"gvisor.dev/gvisor/pkg/sync\"\n)\n// Name is the default filesystem name.\n@@ -81,7 +80,7 @@ type filesystem struct {\nusage usage.MemoryKind\n// mu serializes changes to the Dentry tree.\n- mu sync.RWMutex `state:\"nosave\"`\n+ mu filesystemRWMutex `state:\"nosave\"`\nnextInoMinusOne atomicbitops.Uint64 // accessed using atomic memory operations\n@@ -95,7 +94,7 @@ type filesystem struct {\n// pagesUsed is the pages used out of the tmpfs size.\n// pagesUsed is protected by pagesUsedMu.\n- pagesUsedMu sync.Mutex `state:\"nosave\"`\n+ pagesUsedMu pagesUsedMutex `state:\"nosave\"`\npagesUsed uint64\n}\n@@ -434,7 +433,7 @@ type inode struct {\n// Inode metadata. Writing multiple fields atomically requires holding\n// mu, othewise atomic operations can be used.\n- mu sync.Mutex `state:\"nosave\"`\n+ mu inodeMutex `state:\"nosave\"`\nmode atomicbitops.Uint32 // file type and mode\nnlink atomicbitops.Uint32 // protected by filesystem.mu instead of inode.mu\nuid atomicbitops.Uint32 // auth.KUID, but stored as raw uint32 for sync/atomic\n"
}
] | Go | Apache License 2.0 | google/gvisor | tmpfs: use lockdep mutexes
PiperOrigin-RevId: 449803147 |
259,907 | 19.05.2022 12:15:08 | 25,200 | ec422a66093e09d2884e3d504a453196a2af5403 | Add support for /proc/[pid]/cwd to trace procfs.
Added test for this field.
Updates | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/procfs/BUILD",
"new_path": "runsc/boot/procfs/BUILD",
"diff": "@@ -12,5 +12,6 @@ go_library(\n\"//pkg/sentry/fsimpl/proc\",\n\"//pkg/sentry/kernel\",\n\"//pkg/sentry/mm\",\n+ \"//pkg/sentry/vfs\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/procfs/dump.go",
"new_path": "runsc/boot/procfs/dump.go",
"diff": "@@ -26,6 +26,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/proc\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/mm\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n)\n// ProcessProcfsDump contains the procfs dump for one process.\n@@ -38,6 +39,8 @@ type ProcessProcfsDump struct {\nArgs []string `json:\"args,omitempty\"`\n// Env is /proc/[pid]/environ split into an array.\nEnv []string `json:\"env,omitempty\"`\n+ // CWD is the symlink target of /proc/[pid]/cwd.\n+ CWD string `json:\"cwd,omitempty\"`\n}\n// getMM returns t's MemoryManager. On success, the MemoryManager's users count\n@@ -77,6 +80,28 @@ func getMetadataArray(ctx context.Context, pid kernel.ThreadID, mm *mm.MemoryMan\nreturn strings.Split(strings.TrimSuffix(buf.String(), \"\\000\"), \"\\000\")\n}\n+func getCWD(ctx context.Context, t *kernel.Task, pid kernel.ThreadID) string {\n+ cwdDentry := t.FSContext().WorkingDirectoryVFS2()\n+ if !cwdDentry.Ok() {\n+ log.Warningf(\"No CWD dentry found for PID %s\", pid)\n+ return \"\"\n+ }\n+\n+ root := vfs.RootFromContext(ctx)\n+ if !root.Ok() {\n+ log.Warningf(\"no root could be found from context for PID %s\", pid)\n+ return \"\"\n+ }\n+ defer root.DecRef(ctx)\n+\n+ vfsObj := cwdDentry.Mount().Filesystem().VirtualFilesystem()\n+ name, err := vfsObj.PathnameWithDeleted(ctx, root, cwdDentry)\n+ if err != nil {\n+ log.Warningf(\"PathnameWithDeleted failed to find CWD: %v\", err)\n+ }\n+ return name\n+}\n+\n// Dump returns a procfs dump for process pid. t must be a task in process pid.\nfunc Dump(t *kernel.Task, pid kernel.ThreadID) (ProcessProcfsDump, error) {\nctx := t.AsyncContext()\n@@ -92,5 +117,6 @@ func Dump(t *kernel.Task, pid kernel.ThreadID) (ProcessProcfsDump, error) {\nExe: getExecutablePath(ctx, pid, mm),\nArgs: getMetadataArray(ctx, pid, mm, proc.Cmdline),\nEnv: getMetadataArray(ctx, pid, mm, proc.Environ),\n+ CWD: getCWD(ctx, t, pid),\n}, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/trace_test.go",
"new_path": "runsc/container/trace_test.go",
"diff": "@@ -302,6 +302,7 @@ func TestProcfsDump(t *testing.T) {\nspec, conf := sleepSpecConf(t)\ntestEnv := \"GVISOR_IS_GREAT=true\"\nspec.Process.Env = append(spec.Process.Env, testEnv)\n+ spec.Process.Cwd = \"/\"\n_, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)\nif err != nil {\nt.Fatalf(\"error setting up container: %v\", err)\n@@ -360,4 +361,8 @@ func TestProcfsDump(t *testing.T) {\nif !testEnvFound {\nt.Errorf(\"expected to find %q env but did not find it, got env %+v\", testEnv, procfsDump[0].Env)\n}\n+\n+ if spec.Process.Cwd != procfsDump[0].CWD {\n+ t.Errorf(\"expected CWD %q, got %q\", spec.Process.Cwd, procfsDump[0].CWD)\n+ }\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add support for /proc/[pid]/cwd to trace procfs.
Added test for this field.
Updates #4805
PiperOrigin-RevId: 449805258 |
259,966 | 19.05.2022 12:51:40 | 25,200 | 28eda96b005ea8130bd3cabd23db3640ec26c67b | Cleanup the multicast routing table.
This change does the following:
Uses shared types for the route key and multicast route.
Returns a bool instead of error from GetRouteOrInsertPending since only one
error type is possible.
Improves the naming of PendingRouteState using the suggestions in
cl/445157188.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/internal/multicast/example_test.go",
"new_path": "pkg/tcpip/network/internal/multicast/example_test.go",
"diff": "@@ -32,6 +32,7 @@ import (\nconst (\ndefaultMinTTL = 10\n+ defaultMTU = 1500\ninputNICID tcpip.NICID = 1\noutgoingNICID tcpip.NICID = 2\n)\n@@ -39,8 +40,9 @@ const (\n// Example shows how to interact with a multicast RouteTable.\nfunc Example() {\naddress := testutil.MustParse4(\"192.168.1.1\")\n- defaultOutgoingInterfaces := []multicast.OutgoingInterface{{ID: outgoingNICID, MinTTL: defaultMinTTL}}\n- routeKey := multicast.RouteKey{UnicastSource: address, MulticastDestination: address}\n+ defaultOutgoingInterfaces := []stack.MulticastRouteOutgoingInterface{{ID: outgoingNICID, MinTTL: defaultMinTTL}}\n+ routeKey := stack.UnicastSourceAndMulticastDestination{Source: address, Destination: address}\n+ multicastRoute := stack.MulticastRoute{inputNICID, defaultOutgoingInterfaces}\npkt := newPacketBuffer(\"hello\")\ndefer pkt.DecRef()\n@@ -59,34 +61,30 @@ func Example() {\n// Each entry in the table represents either an installed route or a pending\n// route. To insert a pending route, call:\n- result, err := table.GetRouteOrInsertPending(routeKey, pkt)\n+ result, hasBufferSpace := table.GetRouteOrInsertPending(routeKey, pkt)\n// Callers should handle a no buffer space error (e.g. only deliver the\n// packet locally).\n- if err == multicast.ErrNoBufferSpace {\n+ if !hasBufferSpace {\ndeliverPktLocally(pkt)\n}\n- if err != nil {\n- panic(err)\n- }\n-\n// Callers should handle the various pending route states.\n- switch result.PendingRouteState {\n- case multicast.PendingRouteStateNone:\n+ switch result.GetRouteResultState {\n+ case multicast.InstalledRouteFound:\n// The packet can be forwarded using the installed route.\nforwardPkt(pkt, result.InstalledRoute)\n- case multicast.PendingRouteStateInstalled:\n+ case multicast.NoRouteFoundAndPendingInserted:\n// The route has just entered the pending state.\nemitMissingRouteEvent(routeKey)\ndeliverPktLocally(pkt)\n- case multicast.PendingRouteStateAppended:\n+ case multicast.PacketQueuedInPendingRoute:\n// The route was already in the pending state.\ndeliverPktLocally(pkt)\n}\n// To transition a pending route to the installed state, call:\n- route := table.NewInstalledRoute(inputNICID, defaultOutgoingInterfaces)\n+ route := table.NewInstalledRoute(multicastRoute)\npendingPackets := table.AddInstalledRoute(routeKey, route)\n// If there was a pending route, then the caller is responsible for\n@@ -121,7 +119,7 @@ func forwardPkt(*stack.PacketBuffer, *multicast.InstalledRoute) {\nfmt.Println(\"forwardPkt\")\n}\n-func emitMissingRouteEvent(multicast.RouteKey) {\n+func emitMissingRouteEvent(stack.UnicastSourceAndMulticastDestination) {\nfmt.Println(\"emitMissingRouteEvent\")\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/internal/multicast/route_table.go",
"new_path": "pkg/tcpip/network/internal/multicast/route_table.go",
"diff": "@@ -47,11 +47,11 @@ type RouteTable struct {\n// Maintaining pointers ensures that the installed routes are exclusively\n// locked only when a route is being installed.\n// +checklocks:installedMu\n- installedRoutes map[RouteKey]*InstalledRoute\n+ installedRoutes map[stack.UnicastSourceAndMulticastDestination]*InstalledRoute\npendingMu sync.RWMutex\n// +checklocks:pendingMu\n- pendingRoutes map[RouteKey]PendingRoute\n+ pendingRoutes map[stack.UnicastSourceAndMulticastDestination]PendingRoute\n// cleanupPendingRoutesTimer is a timer that triggers a routine to remove\n// pending routes that are expired.\n// +checklocks:pendingMu\n@@ -75,35 +75,18 @@ var (\nErrAlreadyInitialized = errors.New(\"table is already initialized\")\n)\n-// RouteKey represents an entry key in the RouteTable.\n-type RouteKey struct {\n- UnicastSource tcpip.Address\n- MulticastDestination tcpip.Address\n-}\n-\n// InstalledRoute represents a route that is in the installed state.\n//\n// If a route is in the installed state, then it may be used to forward\n// multicast packets.\ntype InstalledRoute struct {\n- expectedInputInterface tcpip.NICID\n- outgoingInterfaces []OutgoingInterface\n+ stack.MulticastRoute\nlastUsedTimestampMu sync.RWMutex\n// +checklocks:lastUsedTimestampMu\nlastUsedTimestamp tcpip.MonotonicTime\n}\n-// ExpectedInputInterface returns the expected input interface for the route.\n-func (r *InstalledRoute) ExpectedInputInterface() tcpip.NICID {\n- return r.expectedInputInterface\n-}\n-\n-// OutgoingInterfaces returns the outgoing interfaces for the route.\n-func (r *InstalledRoute) OutgoingInterfaces() []OutgoingInterface {\n- return r.outgoingInterfaces\n-}\n-\n// LastUsedTimestamp returns a monotonic timestamp that corresponds to the last\n// time the route was used or updated.\nfunc (r *InstalledRoute) LastUsedTimestamp() tcpip.MonotonicTime {\n@@ -127,17 +110,6 @@ func (r *InstalledRoute) SetLastUsedTimestamp(monotonicTime tcpip.MonotonicTime)\n}\n}\n-// OutgoingInterface represents an interface that packets should be forwarded\n-// out of.\n-type OutgoingInterface struct {\n- // ID corresponds to the outgoing NIC.\n- ID tcpip.NICID\n-\n- // MinTTL represents the minumum TTL/HopLimit a multicast packet must have to\n- // be sent through the outgoing interface.\n- MinTTL uint8\n-}\n-\n// PendingRoute represents a route that is in the \"pending\" state.\n//\n// A route is in the pending state if an installed route does not yet exist\n@@ -230,8 +202,8 @@ func (r *RouteTable) Init(config Config) error {\n}\nr.config = config\n- r.installedRoutes = make(map[RouteKey]*InstalledRoute)\n- r.pendingRoutes = make(map[RouteKey]PendingRoute)\n+ r.installedRoutes = make(map[stack.UnicastSourceAndMulticastDestination]*InstalledRoute)\n+ r.pendingRoutes = make(map[stack.UnicastSourceAndMulticastDestination]PendingRoute)\nreturn nil\n}\n@@ -299,53 +271,47 @@ func (r *RouteTable) newPendingRoute() PendingRoute {\n}\n// NewInstalledRoute instantiates an installed route for the table.\n-func (r *RouteTable) NewInstalledRoute(inputInterface tcpip.NICID, outgoingInterfaces []OutgoingInterface) *InstalledRoute {\n+func (r *RouteTable) NewInstalledRoute(route stack.MulticastRoute) *InstalledRoute {\nreturn &InstalledRoute{\n- expectedInputInterface: inputInterface,\n- outgoingInterfaces: outgoingInterfaces,\n+ MulticastRoute: route,\nlastUsedTimestamp: r.config.Clock.NowMonotonic(),\n}\n}\n-// GetRouteResult represents the result of calling\n-// RouteTable.GetRouteOrInsertPending.\n+// GetRouteResult represents the result of calling GetRouteOrInsertPending.\ntype GetRouteResult struct {\n- // PendingRouteState represents the observed state of any applicable\n- // PendingRoute.\n- PendingRouteState\n+ // GetRouteResultState signals the result of calling GetRouteOrInsertPending.\n+ GetRouteResultState GetRouteResultState\n// InstalledRoute represents the existing installed route. This field will\n- // only be populated if the PendingRouteState is PendingRouteStateNone.\n- *InstalledRoute\n+ // only be populated if the GetRouteResultState is InstalledRouteFound.\n+ InstalledRoute *InstalledRoute\n}\n-// PendingRouteState represents the state of a PendingRoute as observed by the\n-// RouteTable.GetRouteOrInsertPending method.\n-type PendingRouteState uint8\n+// GetRouteResultState signals the result of calling GetRouteOrInsertPending.\n+type GetRouteResultState uint8\nconst (\n- // PendingRouteStateNone indicates that no pending route exists. In such a\n- // case, the GetRouteResult will contain an InstalledRoute.\n- PendingRouteStateNone PendingRouteState = iota\n+ // InstalledRouteFound indicates that an InstalledRoute was found.\n+ InstalledRouteFound GetRouteResultState = iota\n- // PendingRouteStateAppended indicates that the packet was queued in an\n+ // PacketQueuedInPendingRoute indicates that the packet was queued in an\n// existing pending route.\n- PendingRouteStateAppended\n+ PacketQueuedInPendingRoute\n- // PendingRouteStateInstalled indicates that a pending route was newly\n- // inserted into the RouteTable. In such a case, callers should typically\n- // emit a missing route event.\n- PendingRouteStateInstalled\n+ // NoRouteFoundAndPendingInserted indicates that no route was found and that\n+ // a pending route was newly inserted into the RouteTable.\n+ NoRouteFoundAndPendingInserted\n)\n-func (e PendingRouteState) String() string {\n+func (e GetRouteResultState) String() string {\nswitch e {\n- case PendingRouteStateNone:\n- return \"PendingRouteStateNone\"\n- case PendingRouteStateAppended:\n- return \"PendingRouteStateAppended\"\n- case PendingRouteStateInstalled:\n- return \"PendingRouteStateInstalled\"\n+ case InstalledRouteFound:\n+ return \"InstalledRouteFound\"\n+ case PacketQueuedInPendingRoute:\n+ return \"PacketQueuedInPendingRoute\"\n+ case NoRouteFoundAndPendingInserted:\n+ return \"NoRouteFoundAndPendingInserted\"\ndefault:\nreturn fmt.Sprintf(\"%d\", uint8(e))\n}\n@@ -355,29 +321,28 @@ func (e PendingRouteState) String() string {\n// the provided key.\n//\n// If no matching installed route is found, then the pkt is cloned and queued\n-// in a pending route. The GetRouteResult.PendingRouteState will indicate\n+// in a pending route. The GetRouteResult.GetRouteResultState will indicate\n// whether the pkt was queued in a new pending route or an existing one.\n//\n-// If the relevant pending route queue is at max capacity, then\n-// ErrNoBufferSpace is returned. In such a case, callers are typically expected\n-// to only deliver the pkt locally (if relevant).\n-func (r *RouteTable) GetRouteOrInsertPending(key RouteKey, pkt *stack.PacketBuffer) (GetRouteResult, error) {\n+// If the relevant pending route queue is at max capacity, then returns false.\n+// Otherwise, returns true.\n+func (r *RouteTable) GetRouteOrInsertPending(key stack.UnicastSourceAndMulticastDestination, pkt *stack.PacketBuffer) (GetRouteResult, bool) {\nr.installedMu.RLock()\ndefer r.installedMu.RUnlock()\nif route, ok := r.installedRoutes[key]; ok {\n- return GetRouteResult{PendingRouteState: PendingRouteStateNone, InstalledRoute: route}, nil\n+ return GetRouteResult{GetRouteResultState: InstalledRouteFound, InstalledRoute: route}, true\n}\nr.pendingMu.Lock()\ndefer r.pendingMu.Unlock()\n- pendingRoute, pendingRouteState := r.getOrCreatePendingRouteRLocked(key)\n+ pendingRoute, getRouteResultState := r.getOrCreatePendingRouteRLocked(key)\nif len(pendingRoute.packets) >= int(r.config.MaxPendingQueueSize) {\n// The incoming packet is rejected if the pending queue is already at max\n// capacity. This behavior matches the Linux implementation:\n// https://github.com/torvalds/linux/blob/ae085d7f936/net/ipv4/ipmr.c#L1147\n- return GetRouteResult{}, ErrNoBufferSpace\n+ return GetRouteResult{}, false\n}\npendingRoute.packets = append(pendingRoute.packets, pkt.Clone())\nr.pendingRoutes[key] = pendingRoute\n@@ -392,15 +357,15 @@ func (r *RouteTable) GetRouteOrInsertPending(key RouteKey, pkt *stack.PacketBuff\nr.isCleanupRoutineRunning = true\n}\n- return GetRouteResult{PendingRouteState: pendingRouteState, InstalledRoute: nil}, nil\n+ return GetRouteResult{GetRouteResultState: getRouteResultState, InstalledRoute: nil}, true\n}\n// +checklocks:r.pendingMu\n-func (r *RouteTable) getOrCreatePendingRouteRLocked(key RouteKey) (PendingRoute, PendingRouteState) {\n+func (r *RouteTable) getOrCreatePendingRouteRLocked(key stack.UnicastSourceAndMulticastDestination) (PendingRoute, GetRouteResultState) {\nif pendingRoute, ok := r.pendingRoutes[key]; ok {\n- return pendingRoute, PendingRouteStateAppended\n+ return pendingRoute, PacketQueuedInPendingRoute\n}\n- return r.newPendingRoute(), PendingRouteStateInstalled\n+ return r.newPendingRoute(), NoRouteFoundAndPendingInserted\n}\n// AddInstalledRoute adds the provided route to the table.\n@@ -409,7 +374,7 @@ func (r *RouteTable) getOrCreatePendingRouteRLocked(key RouteKey) (PendingRoute,\n// returned. The caller assumes ownership of these packets and is responsible\n// for forwarding and releasing them. If an installed route already exists for\n// the provided key, then it is overwritten.\n-func (r *RouteTable) AddInstalledRoute(key RouteKey, route *InstalledRoute) []*stack.PacketBuffer {\n+func (r *RouteTable) AddInstalledRoute(key stack.UnicastSourceAndMulticastDestination, route *InstalledRoute) []*stack.PacketBuffer {\nr.installedMu.Lock()\ndefer r.installedMu.Unlock()\nr.installedRoutes[key] = route\n@@ -436,7 +401,7 @@ func (r *RouteTable) AddInstalledRoute(key RouteKey, route *InstalledRoute) []*s\n// key.\n//\n// Returns true if a route was removed. Otherwise returns false.\n-func (r *RouteTable) RemoveInstalledRoute(key RouteKey) bool {\n+func (r *RouteTable) RemoveInstalledRoute(key stack.UnicastSourceAndMulticastDestination) bool {\nr.installedMu.Lock()\ndefer r.installedMu.Unlock()\n@@ -452,7 +417,7 @@ func (r *RouteTable) RemoveInstalledRoute(key RouteKey) bool {\n// time the route that matches the provided key was used or updated.\n//\n// Returns true if a matching route was found. Otherwise returns false.\n-func (r *RouteTable) GetLastUsedTimestamp(key RouteKey) (tcpip.MonotonicTime, bool) {\n+func (r *RouteTable) GetLastUsedTimestamp(key stack.UnicastSourceAndMulticastDestination) (tcpip.MonotonicTime, bool) {\nr.installedMu.RLock()\ndefer r.installedMu.RUnlock()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/internal/multicast/route_table_test.go",
"new_path": "pkg/tcpip/network/internal/multicast/route_table_test.go",
"diff": "@@ -32,6 +32,7 @@ import (\nconst (\ndefaultMinTTL = 10\n+ defaultMTU = 1500\ninputNICID tcpip.NICID = 1\noutgoingNICID tcpip.NICID = 2\ndefaultNICID tcpip.NICID = 3\n@@ -39,8 +40,9 @@ const (\nvar (\ndefaultAddress = testutil.MustParse4(\"192.168.1.1\")\n- defaultRouteKey = RouteKey{UnicastSource: defaultAddress, MulticastDestination: defaultAddress}\n- defaultOutgoingInterfaces = []OutgoingInterface{{ID: outgoingNICID, MinTTL: defaultMinTTL}}\n+ defaultRouteKey = stack.UnicastSourceAndMulticastDestination{Source: defaultAddress, Destination: defaultAddress}\n+ defaultOutgoingInterfaces = []stack.MulticastRouteOutgoingInterface{{ID: outgoingNICID, MinTTL: defaultMinTTL}}\n+ defaultRoute = stack.MulticastRoute{inputNICID, defaultOutgoingInterfaces}\n)\nfunc newPacketBuffer(body string) *stack.PacketBuffer {\n@@ -77,11 +79,11 @@ func defaultConfig(opts ...configOption) Config {\n}\nfunc installedRouteComparer(a *InstalledRoute, b *InstalledRoute) bool {\n- if !cmp.Equal(a.OutgoingInterfaces(), b.OutgoingInterfaces()) {\n+ if !cmp.Equal(a.OutgoingInterfaces, b.OutgoingInterfaces) {\nreturn false\n}\n- if a.ExpectedInputInterface() != b.ExpectedInputInterface() {\n+ if a.ExpectedInputInterface != b.ExpectedInputInterface {\nreturn false\n}\n@@ -143,15 +145,19 @@ func TestNewInstalledRoute(t *testing.T) {\nt.Fatalf(\"table.Init(%#v): %s\", config, err)\n}\n- route := table.NewInstalledRoute(inputNICID, defaultOutgoingInterfaces)\n- expectedRoute := &InstalledRoute{expectedInputInterface: inputNICID, outgoingInterfaces: defaultOutgoingInterfaces, lastUsedTimestamp: clock.NowMonotonic()}\n+ route := table.NewInstalledRoute(defaultRoute)\n+\n+ expectedRoute := &InstalledRoute{\n+ MulticastRoute: defaultRoute,\n+ lastUsedTimestamp: clock.NowMonotonic(),\n+ }\nif diff := cmp.Diff(expectedRoute, route, cmp.Comparer(installedRouteComparer)); diff != \"\" {\nt.Errorf(\"Installed route mismatch (-want +got):\\n%s\", diff)\n}\n}\n-func TestPendingRouteStates(t *testing.T) {\n+func TestGetRouteResultStates(t *testing.T) {\ntable := RouteTable{}\ndefer table.Close()\nconfig := defaultConfig(withMaxPendingQueueSize(2))\n@@ -161,16 +167,17 @@ func TestPendingRouteStates(t *testing.T) {\npkt := newPacketBuffer(\"hello\")\ndefer pkt.DecRef()\n- // Queue two pending packets for the same route. The PendingRouteState should\n- // transition from PendingRouteStateInstalled to PendingRouteStateAppended.\n- for _, wantPendingRouteState := range []PendingRouteState{PendingRouteStateInstalled, PendingRouteStateAppended} {\n- routeResult, err := table.GetRouteOrInsertPending(defaultRouteKey, pkt)\n+ // Queue two pending packets for the same route. The GetRouteResultState\n+ // should transition from NoRouteFoundAndPendingInserted to\n+ // PacketQueuedInPendingRoute.\n+ for _, wantPendingRouteState := range []GetRouteResultState{NoRouteFoundAndPendingInserted, PacketQueuedInPendingRoute} {\n+ routeResult, hasBufferSpace := table.GetRouteOrInsertPending(defaultRouteKey, pkt)\n- if err != nil {\n- t.Errorf(\"table.GetRouteOrInsertPending(%#v, %#v) = (_, %v), want = (_, nil)\", defaultRouteKey, pkt, err)\n+ if !hasBufferSpace {\n+ t.Errorf(\"table.GetRouteOrInsertPending(%#v, %#v) = (_, false), want = (_, true)\", defaultRouteKey, pkt)\n}\n- expectedResult := GetRouteResult{PendingRouteState: wantPendingRouteState}\n+ expectedResult := GetRouteResult{GetRouteResultState: wantPendingRouteState}\nif diff := cmp.Diff(expectedResult, routeResult); diff != \"\" {\nt.Errorf(\"table.GetRouteOrInsertPending(%#v, %#v) GetRouteResult mismatch (-want +got):\\n%s\", defaultRouteKey, pkt, diff)\n}\n@@ -178,8 +185,8 @@ func TestPendingRouteStates(t *testing.T) {\n// Queuing a third packet should yield an error since the pending queue is\n// already at max capacity.\n- if _, err := table.GetRouteOrInsertPending(defaultRouteKey, pkt); err != ErrNoBufferSpace {\n- t.Errorf(\"table.GetRouteOrInsertPending(%#v, %#v) = (_, %v), want = (_, ErrNoBufferSpace)\", defaultRouteKey, pkt, err)\n+ if _, hasBufferSpace := table.GetRouteOrInsertPending(defaultRouteKey, pkt); hasBufferSpace {\n+ t.Errorf(\"table.GetRouteOrInsertPending(%#v, %#v) = (_, true), want = (_, false)\", defaultRouteKey, pkt)\n}\n}\n@@ -225,8 +232,8 @@ func TestPendingRouteExpiration(t *testing.T) {\nclock.Advance(test.advanceBeforeInsert)\n- if _, err := table.GetRouteOrInsertPending(defaultRouteKey, pkt); err != nil {\n- t.Fatalf(\"table.GetRouteOrInsertPending(%#v, %#v): %v\", defaultRouteKey, pkt, err)\n+ if _, hasBufferSpace := table.GetRouteOrInsertPending(defaultRouteKey, pkt); !hasBufferSpace {\n+ t.Fatalf(\"table.GetRouteOrInsertPending(%#v, %#v): false\", defaultRouteKey, pkt)\n}\nclock.Advance(test.advanceAfterInsert)\n@@ -288,8 +295,8 @@ func TestAddInstalledRouteWithPending(t *testing.T) {\nt.Fatalf(\"table.Init(%#v): %s\", config, err)\n}\n- if _, err := table.GetRouteOrInsertPending(defaultRouteKey, pkt); err != nil {\n- t.Fatalf(\"table.GetRouteOrInsertPending(%#v, %#v): %v\", defaultRouteKey, pkt, err)\n+ if _, hasBufferSpace := table.GetRouteOrInsertPending(defaultRouteKey, pkt); !hasBufferSpace {\n+ t.Fatalf(\"table.GetRouteOrInsertPending(%#v, %#v): false\", defaultRouteKey, pkt)\n}\n// Disable the cleanup routine.\n@@ -297,7 +304,7 @@ func TestAddInstalledRouteWithPending(t *testing.T) {\nclock.Advance(test.advance)\n- route := table.NewInstalledRoute(inputNICID, defaultOutgoingInterfaces)\n+ route := table.NewInstalledRoute(defaultRoute)\npendingPackets := table.AddInstalledRoute(defaultRouteKey, route)\nif diff := cmp.Diff(test.want, pendingPackets, cmpOpts...); diff != \"\" {\n@@ -326,27 +333,29 @@ func TestAddInstalledRouteWithNoPending(t *testing.T) {\nt.Fatalf(\"table.Init(%#v): %s\", config, err)\n}\n- firstRoute := table.NewInstalledRoute(inputNICID, defaultOutgoingInterfaces)\n- secondRoute := table.NewInstalledRoute(defaultNICID, defaultOutgoingInterfaces)\n+ firstRoute := table.NewInstalledRoute(defaultRoute)\n+\n+ secondMulticastRoute := stack.MulticastRoute{defaultNICID, defaultOutgoingInterfaces}\n+ secondRoute := table.NewInstalledRoute(secondMulticastRoute)\npkt := newPacketBuffer(\"hello\")\ndefer pkt.DecRef()\nfor _, route := range [...]*InstalledRoute{firstRoute, secondRoute} {\nif pendingPackets := table.AddInstalledRoute(defaultRouteKey, route); pendingPackets != nil {\n- t.Errorf(\"got table.AddInstalledRoute(%#v, %#v) = %#v, want = false\", defaultRouteKey, route, pendingPackets)\n+ t.Errorf(\"table.AddInstalledRoute(%#v, %#v) = %#v, want = false\", defaultRouteKey, route, pendingPackets)\n}\n// AddInstalledRoute is invoked for the same routeKey two times. Verify\n// that the fetched InstalledRoute reflects the most recent invocation of\n// AddInstalledRoute.\n- routeResult, err := table.GetRouteOrInsertPending(defaultRouteKey, pkt)\n+ routeResult, hasBufferSpace := table.GetRouteOrInsertPending(defaultRouteKey, pkt)\n- if err != nil {\n- t.Fatalf(\"table.GetRouteOrInsertPending(%#v, %#v): %v\", defaultRouteKey, pkt, err)\n+ if !hasBufferSpace {\n+ t.Fatalf(\"table.GetRouteOrInsertPending(%#v, %#v): false\", defaultRouteKey, pkt)\n}\n- if routeResult.PendingRouteState != PendingRouteStateNone {\n- t.Errorf(\"routeResult.PendingRouteState = %s, want = PendingRouteStateNone\", routeResult.PendingRouteState)\n+ if routeResult.GetRouteResultState != InstalledRouteFound {\n+ t.Errorf(\"routeResult.GetRouteResultState = %s, want = InstalledRouteFound\", routeResult.GetRouteResultState)\n}\nif diff := cmp.Diff(route, routeResult.InstalledRoute, cmp.Comparer(installedRouteComparer)); diff != \"\" {\n@@ -363,7 +372,7 @@ func TestRemoveInstalledRoute(t *testing.T) {\nt.Fatalf(\"table.Init(%#v): %s\", config, err)\n}\n- route := table.NewInstalledRoute(inputNICID, defaultOutgoingInterfaces)\n+ route := table.NewInstalledRoute(defaultRoute)\ntable.AddInstalledRoute(defaultRouteKey, route)\n@@ -374,10 +383,10 @@ func TestRemoveInstalledRoute(t *testing.T) {\npkt := newPacketBuffer(\"hello\")\ndefer pkt.DecRef()\n- result, err := table.GetRouteOrInsertPending(defaultRouteKey, pkt)\n+ result, hasBufferSpace := table.GetRouteOrInsertPending(defaultRouteKey, pkt)\n- if err != nil {\n- t.Fatalf(\"table.GetRouteOrInsertPending(%#v, %#v): %v\", defaultRouteKey, pkt, err)\n+ if !hasBufferSpace {\n+ t.Fatalf(\"table.GetRouteOrInsertPending(%#v, %#v): false\", defaultRouteKey, pkt)\n}\nif result.InstalledRoute != nil {\n@@ -444,7 +453,7 @@ func TestSetLastUsedTimestamp(t *testing.T) {\nt.Fatalf(\"table.Init(%#v): %s\", config, err)\n}\n- route := table.NewInstalledRoute(inputNICID, defaultOutgoingInterfaces)\n+ route := table.NewInstalledRoute(defaultRoute)\ntable.AddInstalledRoute(defaultRouteKey, route)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/registration.go",
"new_path": "pkg/tcpip/stack/registration.go",
"diff": "@@ -757,6 +757,41 @@ type NetworkProtocol interface {\nParse(pkt *PacketBuffer) (proto tcpip.TransportProtocolNumber, hasTransportHdr bool, ok bool)\n}\n+// UnicastSourceAndMulticastDestination is a tuple that represents a unicast\n+// source address and a multicast destination address.\n+type UnicastSourceAndMulticastDestination struct {\n+ // Source represents a unicast source address.\n+ Source tcpip.Address\n+ // Destination represents a multicast destination address.\n+ Destination tcpip.Address\n+}\n+\n+// MulticastRouteOutgoingInterface represents an outgoing interface in a\n+// multicast route.\n+type MulticastRouteOutgoingInterface struct {\n+ // ID corresponds to the outgoing NIC.\n+ ID tcpip.NICID\n+\n+ // MinTTL represents the minumum TTL/HopLimit a multicast packet must have to\n+ // be sent through the outgoing interface.\n+ //\n+ // Note: a value of 0 allows all packets to be forwarded.\n+ MinTTL uint8\n+}\n+\n+// MulticastRoute is a multicast route.\n+type MulticastRoute struct {\n+ // ExpectedInputInterface is the interface on which packets using this route\n+ // are expected to ingress.\n+ ExpectedInputInterface tcpip.NICID\n+\n+ // OutgoingInterfaces is the set of interfaces that a multicast packet should\n+ // be forwarded out of.\n+ //\n+ // This field should not be empty.\n+ OutgoingInterfaces []MulticastRouteOutgoingInterface\n+}\n+\n// NetworkDispatcher contains the methods used by the network stack to deliver\n// inbound/outbound packets to the appropriate network/packet(if any) endpoints.\ntype NetworkDispatcher interface {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Cleanup the multicast routing table.
This change does the following:
- Uses shared types for the route key and multicast route.
- Returns a bool instead of error from GetRouteOrInsertPending since only one
error type is possible.
- Improves the naming of PendingRouteState using the suggestions in
cl/445157188.
Updates #7338.
PiperOrigin-RevId: 449812803 |
259,982 | 19.05.2022 18:23:59 | 25,200 | 1228e6c788a0a6f35b9792aaa1ffe20ac72ce1c6 | Adding tests to handle empty size & uint64 overflow in parsing size. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"diff": "@@ -972,7 +972,14 @@ func parseSize(s string) (uint64, error) {\ncount = count << 10\ns = s[:len(s)-1]\n}\n- bytes, err := strconv.ParseUint(s, 10, 64)\n- bytes = bytes * uint64(count)\n+ byteTmp, err := strconv.ParseUint(s, 10, 64)\n+ if err != nil {\n+ return 0, linuxerr.EINVAL\n+ }\n+ // Check for overflow.\n+ bytes := byteTmp * uint64(count)\n+ if byteTmp != 0 && bytes/byteTmp != uint64(count) {\n+ return 0, fmt.Errorf(\"size overflow\")\n+ }\nreturn bytes, err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs_test.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs_test.go",
"diff": "@@ -171,6 +171,8 @@ func TestParseSize(t *testing.T) {\n{\"5P\", (5 * 1024 * 1024 * 1024 * 1024 * 1024), false},\n{\"5e\", (5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024), false},\n{\"5e3\", 0, true},\n+ {\"\", 0, true},\n+ {\"9999999999999999P\", 0, true},\n}\nfor _, tt := range tests {\ntestname := fmt.Sprintf(\"%s\", tt.s)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Adding tests to handle empty size & uint64 overflow in parsing size.
PiperOrigin-RevId: 449876821 |
259,853 | 19.05.2022 21:31:53 | 25,200 | ad8960f60401953f9d57809bc3add378487bf039 | Allow to run packetdrill and fsstress tests on arm64 | [
{
"change_type": "RENAME",
"old_path": "images/basic/fsstress/Dockerfile.x86_64",
"new_path": "images/basic/fsstress/Dockerfile",
"diff": "@@ -5,7 +5,7 @@ RUN apk update && apk add git\nRUN git clone https://github.com/linux-test-project/ltp.git --depth 1\nWORKDIR /ltp\n-RUN ./travis/alpine.sh\n+RUN ./ci/alpine.sh\nRUN make autotools && ./configure\nRUN make -C testcases/kernel/fs/fsstress\nRUN cp ./testcases/kernel/fs/fsstress/fsstress /usr/bin\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetdrill/packetdrill_test.sh",
"new_path": "test/packetdrill/packetdrill_test.sh",
"diff": "@@ -117,7 +117,7 @@ declare -r CTRL_PORT=\"40000\"\n# Last bits of the test runner's IP address.\ndeclare -r TEST_RUNNER_NET_SUFFIX=\".20\"\ndeclare -r TIMEOUT=\"60\"\n-declare -r IMAGE_TAG=\"gcr.io/gvisor-presubmit/packetdrill\"\n+declare -r IMAGE_TAG=\"gvisor.dev/images/packetdrill\"\n# Make sure that docker is installed.\ndocker --version\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow to run packetdrill and fsstress tests on arm64
PiperOrigin-RevId: 449900552 |
259,853 | 20.05.2022 14:08:46 | 25,200 | bb1a83085b3b0aa230d6256d74f4c6322617020e | buildkite: allow to run containerd tests on arm64
k8s.gcr.io/busybox:latest doesn't have the arm variant, so
let's use the upstream busybox and create /etc/recolv.conf symlink. | [
{
"change_type": "MODIFY",
"old_path": ".buildkite/pipeline.yaml",
"new_path": ".buildkite/pipeline.yaml",
"diff": "@@ -236,35 +236,30 @@ steps:\nlabel: \":docker: Containerd 1.4.3 tests\"\ncommand: make containerd-test-1.4.3\nagents:\n- arch: \"amd64\"\nos: \"ubuntu\"\n- <<: *common\nlabel: \":docker: Containerd 1.5.4 tests (cgroupv1)\"\ncommand: make containerd-test-1.5.4\nagents:\ncgroup: \"v1\"\n- arch: \"amd64\"\nos: \"ubuntu\"\n- <<: *common\nlabel: \":docker: Containerd 1.5.4 tests (cgroupv2)\"\ncommand: make containerd-test-1.5.4\nagents:\ncgroup: \"v2\"\n- arch: \"amd64\"\nos: \"ubuntu\"\n- <<: *common\nlabel: \":docker: Containerd 1.6.0-rc.4 tests (cgroupv1)\"\ncommand: make containerd-test-1.6.0-rc.4\nagents:\ncgroup: \"v1\"\n- arch: \"amd64\"\nos: \"ubuntu\"\n- <<: *common\nlabel: \":docker: Containerd 1.6.0-rc.4 tests (cgroupv2)\"\ncommand: make containerd-test-1.6.0-rc.4\nagents:\ncgroup: \"v2\"\n- arch: \"amd64\"\nos: \"ubuntu\"\n# Check the website builds.\n"
},
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -312,7 +312,7 @@ fsstress-test: load-basic $(RUNTIME_BIN)\n.PHONY: fsstress-test\n# Specific containerd version tests.\n-containerd-test-%: load-basic_alpine load-basic_python load-basic_busybox load-basic_resolv load-basic_httpd load-basic_ubuntu $(RUNTIME_BIN)\n+containerd-test-%: load-basic_alpine load-basic_python load-basic_busybox load-basic_symlink-resolv load-basic_httpd load-basic_ubuntu $(RUNTIME_BIN)\n@$(call install_runtime,$(RUNTIME),) # Clear flags.\n@sudo tools/install_containerd.sh $*\nifeq (,$(STAGED_BINARIES))\n"
},
{
"change_type": "DELETE",
"old_path": "images/basic/resolv/Dockerfile",
"new_path": null,
"diff": "-FROM k8s.gcr.io/busybox:latest\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/basic/symlink-resolv/Dockerfile",
"diff": "+FROM busybox\n+\n+ADD resolv.tar /\n"
},
{
"change_type": "ADD",
"old_path": "images/basic/symlink-resolv/resolv.tar",
"new_path": "images/basic/symlink-resolv/resolv.tar",
"diff": "Binary files /dev/null and b/images/basic/symlink-resolv/resolv.tar differ\n"
},
{
"change_type": "MODIFY",
"old_path": "test/root/crictl_test.go",
"new_path": "test/root/crictl_test.go",
"diff": "@@ -181,8 +181,8 @@ func TestMountOverSymlinks(t *testing.T) {\n}\ndefer cleanup()\n- spec := SimpleSpec(\"busybox\", \"basic/resolv\", []string{\"sleep\", \"1000\"}, nil)\n- podID, contID, err := crictl.StartPodAndContainer(containerdRuntime, \"basic/resolv\", Sandbox(\"default\"), spec)\n+ spec := SimpleSpec(\"busybox\", \"basic/symlink-resolv\", []string{\"sleep\", \"1000\"}, nil)\n+ podID, contID, err := crictl.StartPodAndContainer(containerdRuntime, \"basic/symlink-resolv\", Sandbox(\"default\"), spec)\nif err != nil {\nt.Fatalf(\"start failed: %v\", err)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | buildkite: allow to run containerd tests on arm64
k8s.gcr.io/busybox:latest doesn't have the arm variant, so
let's use the upstream busybox and create /etc/recolv.conf symlink.
PiperOrigin-RevId: 450059917 |
259,909 | 23.05.2022 14:05:00 | 25,200 | 8f6b282acc44ddd459715a6f2db8aaafd6b5b11e | Fix data race in remote_test. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/checkers/remote/test/server.go",
"new_path": "pkg/sentry/seccheck/checkers/remote/test/server.go",
"diff": "@@ -48,6 +48,7 @@ type Server struct {\n// +checklocks:mu\npoints []Message\n+ // +checklocks:mu\nversion uint32\n}\n@@ -147,7 +148,10 @@ func (s *Server) handshake(client *unet.Socket) error {\nreturn fmt.Errorf(\"wrong version number, want: %d, got, %d\", wire.CurrentVersion, hsIn.Version)\n}\n- hsOut := pb.Handshake{Version: s.version}\n+ s.mu.Lock()\n+ v := s.version\n+ s.mu.Unlock()\n+ hsOut := pb.Handshake{Version: v}\nout, err := proto.Marshal(&hsOut)\nif err != nil {\nreturn fmt.Errorf(\"marshalling handshake message: %w\", err)\n@@ -248,5 +252,7 @@ func (s *Server) WaitForCount(count int) error {\n// SetVersion sets the version to be used in handshake.\nfunc (s *Server) SetVersion(newVersion uint32) {\n+ s.mu.Lock()\n+ defer s.mu.Unlock()\ns.version = newVersion\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix data race in remote_test.
PiperOrigin-RevId: 450520804 |