From 36ab779e2f29a6d1ecd26e940a79ca15307d74df Mon Sep 17 00:00:00 2001 From: Jing Date: Thu, 3 Sep 2026 12:55:12 -0700 Subject: [PATCH] Add a set of formatting and spelling checks - gofmt Go formatting - clang-format C and C++ formatting in Google style - actionlint GitHub Actions workflow syntax - codespell spelling in documentation and source code - buildifier BUILD file format A `Lint` GitHub Actions workflow runs the suite on pull requests and on pushes to master. Fix #14565 FUTURE_COPYBARA_INTEGRATE_REVIEW=https://github.com/google/gvisor/pull/14489 from milantracy:lint fad88ce01735a7c0554fb71c9d9a4878973cf951 PiperOrigin-RevId: 975878109 --- .buildkite/pipeline.yaml | 8 + .clang-format | 16 + .codespellrc | 3 - .github/workflows/lint.yml | 31 ++ Makefile | 16 +- g3doc/user_guide/fuse.md | 2 +- g3doc/user_guide/rootfs_snapshot.md | 2 +- images/basic/integrationtest/link_test.c | 2 +- pkg/aio/aio.go | 2 +- pkg/lisafs/client.go | 2 +- pkg/sentry/devices/nvproxy/frontend.go | 6 +- .../devices/nvproxy/nvconf/caps_test.go | 2 +- pkg/sentry/devices/tundev/tundev.go | 2 +- pkg/sentry/fdimport/fdimport.go | 2 +- pkg/sentry/fsimpl/gofer/directfs_inode.go | 2 +- pkg/sentry/fsimpl/gofer/lisafs_inode.go | 2 +- pkg/sentry/fsimpl/sys/rdma.go | 2 +- pkg/sentry/kernel/task_start.go | 2 +- pkg/sentry/memmap/memmap.go | 4 +- pkg/sentry/platform/kvm/bluepill_amd64.go | 2 +- pkg/sentry/platform/kvm/physical_map_arm64.go | 2 +- pkg/sentry/platform/platform.go | 2 +- pkg/sentry/platform/slimvm/machine.go | 4 +- pkg/sentry/platform/slimvm/machine_amd64.go | 2 +- pkg/sentry/platform/systrap/subprocess.go | 2 +- .../systrap/sysmsg/sighandler_arm64.c | 7 +- .../seccheck/sinks/remote/server/server.go | 2 +- pkg/sentry/state/stateio/stateio_impl_util.go | 2 +- pkg/sentry/vfs/mount.go | 2 +- pkg/tcpip/header/ipv4.go | 2 +- pkg/tcpip/header/ndp_test.go | 2 +- pkg/tcpip/link/sharedmem/pipe/tx.go | 2 +- .../internal/fragmentation/reassembler.go | 2 +- pkg/tcpip/network/ipv4/icmp.go | 2 +- pkg/tcpip/nftables/nftables.go | 2 +- pkg/tcpip/nftables/nftables_test.go | 2 +- pkg/tcpip/nftables/nftables_types.go | 2 +- pkg/tcpip/stack/stack_test.go | 2 +- pkg/tcpip/tcpip.go | 2 +- pkg/tcpip/transport/tcp/endpoint.go | 2 +- pkg/tcpip/transport/tcp/endpoint_state.go | 2 +- pkg/tcpip/transport/tcp/protocol.go | 2 +- pkg/tcpip/transport/tcp/test/e2e/tcp_test.go | 2 +- pkg/tcpip/transport/tcp/timer.go | 6 +- runsc/checkpointgofer/gcs/parallelwriter.go | 2 +- runsc/container/container.go | 2 +- runsc/container/container_test.go | 2 +- runsc/container/multi_container_test.go | 2 +- runsc/container/state_file.go | 2 +- test/cmd/test_app/fds.go | 4 +- test/cmd/test_app/main.go | 12 +- test/cmd/test_app/zombies.go | 2 +- test/e2e/exec_test.go | 2 +- test/metricclient/metricclient.go | 4 +- test/packetimpact/README.md | 6 +- test/packetimpact/testbench/dut.go | 12 +- test/packetimpact/testbench/layers.go | 2 +- .../tests/icmpv4_socket_send_recv_test.go | 4 +- .../tests/tcp_network_unreachable_test.go | 2 +- .../tests/tcp_unacc_seq_ack_test.go | 2 +- .../tcp_zero_window_probe_retransmit_test.go | 4 +- .../tests/tcp_zero_window_probe_test.go | 4 +- .../tcp_zero_window_probe_usertimeout_test.go | 4 +- test/runner/gtest/gtest.go | 2 +- test/syscalls/linux/flock.cc | 2 +- test/syscalls/linux/partial_bad_buffer.cc | 2 +- test/syscalls/linux/ping_socket.cc | 3 +- test/syscalls/linux/ptrace.cc | 3 +- test/syscalls/linux/raw_socket.cc | 5 +- .../linux/socket_generic_test_cases.cc | 64 +-- test/syscalls/linux/socket_inet_loopback.cc | 2 +- test/syscalls/linux/socket_ip_tcp_generic.cc | 2 +- test/syscalls/linux/socket_ip_unbound.cc | 2 +- test/syscalls/linux/socket_netlink.cc | 16 +- test/syscalls/linux/socket_stream_blocking.cc | 4 +- test/syscalls/linux/socket_unix_cmsg.cc | 12 +- test/syscalls/linux/socket_unix_non_stream.cc | 4 +- test/syscalls/linux/socket_unix_stream.cc | 4 +- .../linux/socket_unix_unbound_stream.cc | 16 +- test/syscalls/linux/stat.cc | 2 +- test/util/multiprocess_util.h | 3 +- test/util/proc_util.h | 13 +- tools/.codespellrc | 56 +++ tools/bazel.mk | 5 + tools/checkescape/checkescape.go | 2 +- tools/lint.sh | 376 ++++++++++++++++++ tools/nogo/check/check.go | 2 +- website/cmd/server/main.go | 2 +- website/cmd/syscalldocs/main.go | 2 +- 89 files changed, 645 insertions(+), 204 deletions(-) create mode 100644 .clang-format delete mode 100644 .codespellrc create mode 100644 .github/workflows/lint.yml create mode 100644 tools/.codespellrc create mode 100755 tools/lint.sh diff --git a/.buildkite/pipeline.yaml b/.buildkite/pipeline.yaml index 027dc17e83f..b32cf24dbb5 100644 --- a/.buildkite/pipeline.yaml +++ b/.buildkite/pipeline.yaml @@ -69,6 +69,14 @@ env: SYSCALL_TEST_FILTERS: '' steps: + # Source-level lint checks. + - <<: *common + <<: *source_test + label: ":lipstick: Lint" + command: make lint + agents: + queue: "default" + # Run basic smoke tests before preceding to other tests. - <<: *common <<: *source_test diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000000..b07565754cf --- /dev/null +++ b/.clang-format @@ -0,0 +1,16 @@ +# Copyright 2026 The gVisor Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# gVisor's C and C++ sources follow the Google C++ style guide. +BasedOnStyle: Google diff --git a/.codespellrc b/.codespellrc deleted file mode 100644 index ae96b9796e4..00000000000 --- a/.codespellrc +++ /dev/null @@ -1,3 +0,0 @@ -[codespell] -skip = ./.git,tags,go.mod,go.sum,./test/image/latin10k.txt,./website/assets/images -ignore-words-list = savable,adin diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 00000000000..a1e8967689e --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,31 @@ +# Runs the source-level lint suite. See tools/lint.sh. +name: Lint + +"on": + pull_request: + branches: + - master + push: + branches: + - master + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false + + - uses: actions/setup-go@44694675825211faa026b3c33043df3e48a5fa00 # v6.0.0 + with: + go-version-file: 'go.mod' + + - run: make lint diff --git a/Makefile b/Makefile index 4a181f87f58..f4ca087d4c0 100644 --- a/Makefile +++ b/Makefile @@ -906,6 +906,16 @@ tag: ## Creates and pushes a release tag. @tools/tag_release.sh "$(RELEASE_COMMIT)" "$(RELEASE_NAME)" "$(RELEASE_NOTES)" .PHONY: tag -codespell: - codespell -.PHONY: codespell +## +## Lint targets. +## +## These run the source-level linters that live outside the Bazel build. +## Deep Go analysis is owned by gVisor nogo. +## +lint: ## Runs the source linters. + @tools/lint.sh +.PHONY: lint + +lint-fix: ## Reformats sources in place. + @tools/lint.sh --fix +.PHONY: lint-fix diff --git a/g3doc/user_guide/fuse.md b/g3doc/user_guide/fuse.md index 164c71ee2e3..43aa6e1cf1a 100644 --- a/g3doc/user_guide/fuse.md +++ b/g3doc/user_guide/fuse.md @@ -19,7 +19,7 @@ The external FUSE server feature allows a host-side process to serve a FUSE filesystem into a gVisor sandbox. The host process and the sandbox communicate over a Unix socketpair using the standard FUSE protocol. This approach avoids the performance penalty incurred by context switching through the I/O proxy -mechansim that's otherwise used to expose host filesystems. +mechanism that's otherwise used to expose host filesystems. ### How It Works diff --git a/g3doc/user_guide/rootfs_snapshot.md b/g3doc/user_guide/rootfs_snapshot.md index 2dfea3d302e..6a7124304f0 100644 --- a/g3doc/user_guide/rootfs_snapshot.md +++ b/g3doc/user_guide/rootfs_snapshot.md @@ -81,7 +81,7 @@ Enable the flag `allow-rootfs-tar-annotation` to runtimeArgs, e.g. Since the tar file path is provided via OCI spec's annotation, it is compatible with Docker client when the runtime is gVisor. You can pass the annotation via -Docker commad and observe the file change as: +Docker command and observe the file change as: ``` $ docker run --rm --runtime=runsc --annotation "dev.gvisor.tar.rootfs.upper"="/tmp/rootfs.tar" alpine cat /dir/file diff --git a/images/basic/integrationtest/link_test.c b/images/basic/integrationtest/link_test.c index 45ab00abef4..23eb0963c1d 100644 --- a/images/basic/integrationtest/link_test.c +++ b/images/basic/integrationtest/link_test.c @@ -65,7 +65,7 @@ int main(int argc, char** argv) { new_stat.st_nlink); } - // Check taht contents are the same. + // Check that contents are the same. fd = open(kNewPath, O_RDONLY); if (fd < 0) { errx(1, "open(%s) failed", kNewPath); diff --git a/pkg/aio/aio.go b/pkg/aio/aio.go index e41f1e1147e..c2c054e022d 100644 --- a/pkg/aio/aio.go +++ b/pkg/aio/aio.go @@ -31,7 +31,7 @@ import ( // Queues are not safe to use concurrently in multiple goroutines. type Queue interface { // Destroy cancels all inflight operations and releases resources owned by - // the Queue. Destroy waits for cancelation, so the Queue will not access + // the Queue. Destroy waits for cancellation, so the Queue will not access // memory corresponding to inflight operations after Destroy returns. Destroy() diff --git a/pkg/lisafs/client.go b/pkg/lisafs/client.go index d72da710a51..9c7dbcb5ad9 100644 --- a/pkg/lisafs/client.go +++ b/pkg/lisafs/client.go @@ -140,7 +140,7 @@ func (c *Client) StartChannels() error { } channelsWg.Wait() - // Check that atleast 1 channel is created. This is not required by lisafs + // Check that at least 1 channel is created. This is not required by lisafs // protocol. It exists to flag server side issues in channel creation. c.channelsMu.Lock() numChannels := len(c.channels) diff --git a/pkg/sentry/devices/nvproxy/frontend.go b/pkg/sentry/devices/nvproxy/frontend.go index 3dda8ecc9a3..95e86be980e 100644 --- a/pkg/sentry/devices/nvproxy/frontend.go +++ b/pkg/sentry/devices/nvproxy/frontend.go @@ -234,7 +234,7 @@ func (fd *frontendFD) Ioctl(ctx context.Context, uio usermem.IO, sysno uintptr, } // nr determines the argument type. - // Implementors: + // Implementers: // - To map nr to a symbol, look in // src/nvidia/arch/nvalloc/unix/include/nv_escape.h, // kernel-open/common/inc/nv-ioctl-numbers.h, and @@ -905,7 +905,7 @@ func rmControl(fi *frontendIoctlState) (uintptr, error) { // Consequently, its parameters cannot reasonably contain pointers. return rmControlSimple(fi, &ioctlParams) } - // Implementors: + // Implementers: // - Top two bytes of Cmd specifies class; third byte specifies category; // fourth byte specifies "message ID" (command within class/category). // e.g. 0x800288: @@ -1223,7 +1223,7 @@ func rmAlloc(fi *frontendIoctlState) (uintptr, error) { if log.IsLogging(log.Debug) { fi.ctx.Debugf("nvproxy: allocation class %v", ioctlParams.HClass) } - // Implementors: + // Implementers: // - To map hClass to a symbol, look in // src/nvidia/generated/g_allclasses.h. // - See src/nvidia/src/kernel/rmapi/resource_list.h for table mapping class diff --git a/pkg/sentry/devices/nvproxy/nvconf/caps_test.go b/pkg/sentry/devices/nvproxy/nvconf/caps_test.go index c552723ab02..e043713d5a4 100644 --- a/pkg/sentry/devices/nvproxy/nvconf/caps_test.go +++ b/pkg/sentry/devices/nvproxy/nvconf/caps_test.go @@ -21,7 +21,7 @@ import ( // TestNVIDIAFlagsSkipsPrivilegedCaps is a regression test for the // container-startup bug seen when NVIDIA_DRIVER_CAPABILITIES=all is combined -// with --nvproxy-allowed-driver-capabilities using priviledged capabilities. +// with --nvproxy-allowed-driver-capabilities using privileged capabilities. // // In that configuration, NVProxyDriverCapsFromEnv returns the full allowed set, // which includes CapProfiling. nvproxySetup then calls NVIDIAFlags() on that set diff --git a/pkg/sentry/devices/tundev/tundev.go b/pkg/sentry/devices/tundev/tundev.go index 7d2be6e9479..5b4c1104288 100644 --- a/pkg/sentry/devices/tundev/tundev.go +++ b/pkg/sentry/devices/tundev/tundev.go @@ -103,7 +103,7 @@ func (fd *tunFD) Ioctl(ctx context.Context, uio usermem.IO, sysno uintptr, args flags, err := netstack.LinuxToTUNFlags(linuxFlags) if err != nil { if warnRateLimiter.Allow() { - ctx.Warningf("Unsuported tun flags: %x", linuxFlags) + ctx.Warningf("Unsupported tun flags: %x", linuxFlags) } } return 0, fd.device.SetIff(ctx, stack.Stack, req.Name(), flags) diff --git a/pkg/sentry/fdimport/fdimport.go b/pkg/sentry/fdimport/fdimport.go index ec4d82c68c4..2b48e8e6e91 100644 --- a/pkg/sentry/fdimport/fdimport.go +++ b/pkg/sentry/fdimport/fdimport.go @@ -97,7 +97,7 @@ func Import(ctx context.Context, fdTable *kernel.FDTable, fds map[int]*fd.FD, op // FDs. ttyFile = appFile } else { - // Re-use the existing TTY file, as all three stdio FDs must point to + // Reuse the existing TTY file, as all three stdio FDs must point to // the same fs.File in order to share TTY state, specifically the // foreground process group id. appFile = ttyFile diff --git a/pkg/sentry/fsimpl/gofer/directfs_inode.go b/pkg/sentry/fsimpl/gofer/directfs_inode.go index 9275b4b6eab..57feebac797 100644 --- a/pkg/sentry/fsimpl/gofer/directfs_inode.go +++ b/pkg/sentry/fsimpl/gofer/directfs_inode.go @@ -138,7 +138,7 @@ func (fs *filesystem) newDirectfsDentry(controlFD int) (*dentry, error) { // and its inode together in the heap. This will help reduce allocations and memory // fragmentation. This is more cache friendly too. // Obviously in case of hard link and if the inode already exists, - // we just re-use the inode and heap allocate just the dentry struct. + // we just reuse the inode and heap allocate just the dentry struct. temp := struct { d dentry i directfsInode diff --git a/pkg/sentry/fsimpl/gofer/lisafs_inode.go b/pkg/sentry/fsimpl/gofer/lisafs_inode.go index 048f6aefce9..b3f317e2f84 100644 --- a/pkg/sentry/fsimpl/gofer/lisafs_inode.go +++ b/pkg/sentry/fsimpl/gofer/lisafs_inode.go @@ -120,7 +120,7 @@ func (fs *filesystem) newLisafsDentry(ctx context.Context, ino *lisafs.Inode) (* // and its inode together in the heap. This will help reduce allocations and memory // fragmentation. This is more cache friendly too. // Obviously in case of hard link and if the inode already exists, - // we just re-use the inode and heap allocate just the dentry struct. + // we just reuse the inode and heap allocate just the dentry struct. temp := struct { d dentry i lisafsInode diff --git a/pkg/sentry/fsimpl/sys/rdma.go b/pkg/sentry/fsimpl/sys/rdma.go index 3c705352fe8..c27f85e2946 100644 --- a/pkg/sentry/fsimpl/sys/rdma.go +++ b/pkg/sentry/fsimpl/sys/rdma.go @@ -338,7 +338,7 @@ func (fs *filesystem) addPorts(ib *rdmaDirTree, dev *rdma.Device) { // /sys/class/pci_bus symlink. NCCL resolves GPU and NIC positions via // "/sys/class/pci_bus//../../". // -// Precondtion: rdma.IsBDF(path.Base(leaf)) == true +// Precondition: rdma.IsBDF(path.Base(leaf)) == true func (fs *filesystem) addPCIBus(root *rdmaDirTree, leaf string, classPCIBus map[string]string) { base := path.Base(leaf) i := strings.LastIndex(base, ":") diff --git a/pkg/sentry/kernel/task_start.go b/pkg/sentry/kernel/task_start.go index 6dded04e19a..88969387c7f 100644 --- a/pkg/sentry/kernel/task_start.go +++ b/pkg/sentry/kernel/task_start.go @@ -321,7 +321,7 @@ func (ts *TaskSet) newTask(ctx context.Context, cfg *TaskConfig) (*Task, error) // current->signal->tty, which differs from the parent's under // CLONE_PARENT. if srcT != nil { - inhTTY = srcT.tg.GetTTY() // Takes a ref, balanced in defer, or transfered to tg.tty. + inhTTY = srcT.tg.GetTTY() // Takes a ref, balanced in defer, or transferred to tg.tty. } // For the standard, non-cloneIntoCgroup fork case, we have to do this diff --git a/pkg/sentry/memmap/memmap.go b/pkg/sentry/memmap/memmap.go index a7a86a526d1..9f7fb52b0b3 100644 --- a/pkg/sentry/memmap/memmap.go +++ b/pkg/sentry/memmap/memmap.go @@ -264,7 +264,7 @@ type MappingIdentity interface { // int64(mr.Start), int64(mr.End-1), fs.SyncData). // (fs.FileOperations.Fsync() takes an inclusive end, but mr.End is // exclusive, hence mr.End-1.) It is defined rather than Fsync so that - // implementors don't need to depend on the fs package for fs.SyncType. + // implementers don't need to depend on the fs package for fs.SyncType. Msync(ctx context.Context, mr MappableRange) error } @@ -454,7 +454,7 @@ type File interface { // * fr.Length() > 0. // * At least one reference must be held on all pages in fr. (The File // interface does not provide a way to acquire an initial reference; - // implementors may define mechanisms for doing so.) + // implementers may define mechanisms for doing so.) IncRef(fr FileRange, memCgID uint32) // DecRef decrements the reference count on all pages in fr. diff --git a/pkg/sentry/platform/kvm/bluepill_amd64.go b/pkg/sentry/platform/kvm/bluepill_amd64.go index 6afaa03ac8b..b81a71d17c5 100644 --- a/pkg/sentry/platform/kvm/bluepill_amd64.go +++ b/pkg/sentry/platform/kvm/bluepill_amd64.go @@ -122,7 +122,7 @@ func (c *vCPU) KernelSyscall() { // 3. HLT does a VM-exit to bluepillHandler, which returns from the // signal handler using vCPU.registers, directly to the SYSCALL // instruction. - // 4. Later, when we want to re-use the vCPU (perhaps on a different + // 4. Later, when we want to reuse the vCPU (perhaps on a different // host thread), we set the new thread's registers in vCPU.registers // (as opposed to setting the KVM registers with KVM_SET_REGS). // 5. KVM_RUN thus enters the guest with the old register state, diff --git a/pkg/sentry/platform/kvm/physical_map_arm64.go b/pkg/sentry/platform/kvm/physical_map_arm64.go index 1f8dcf43c91..32184968671 100644 --- a/pkg/sentry/platform/kvm/physical_map_arm64.go +++ b/pkg/sentry/platform/kvm/physical_map_arm64.go @@ -16,7 +16,7 @@ package kvm const ( reservedMemory = 0 - // 5-level page tables are not implemeted on arm64. + // 5-level page tables are not implemented on arm64. extendedAddressSpaceAllowed = false ) diff --git a/pkg/sentry/platform/platform.go b/pkg/sentry/platform/platform.go index 22c8dc1d80b..a8769e1ca16 100644 --- a/pkg/sentry/platform/platform.go +++ b/pkg/sentry/platform/platform.go @@ -404,7 +404,7 @@ type AddressSpace interface { // AddressSpaceIO supports IO through the memory mappings installed in an // AddressSpace. // -// AddressSpaceIO implementors are responsible for ensuring that address ranges +// AddressSpaceIO implementers are responsible for ensuring that address ranges // are application-mappable. type AddressSpaceIO interface { // CopyOut copies len(src) bytes from src to the memory mapped at addr. It diff --git a/pkg/sentry/platform/slimvm/machine.go b/pkg/sentry/platform/slimvm/machine.go index e8cc8f1beb1..fb1b9cae5e2 100644 --- a/pkg/sentry/platform/slimvm/machine.go +++ b/pkg/sentry/platform/slimvm/machine.go @@ -150,7 +150,7 @@ type vCPU struct { // newVCPU creates and returns a new vCPU. It returns nil when the per-machine // vCPU limit (m.maxVCPUs) is exhausted. // -// Precondtion: mu must be held. +// Precondition: mu must be held. func (m *machine) newVCPU() *vCPU { id, ok := m.allocateVCPUID() if !ok { @@ -443,7 +443,7 @@ func (c *vCPU) unlock() { // when next time this vCPU enter guest ring3, bit of vCPUWaiter // may not be cleard, this will cause the following BounceToKernel // to this vCPU hang at waitUntilNot. - // Halt may workaroud this issue, because halt process will reset + // Halt may workaround this issue, because halt process will reset // vCPU status into vCPUUser, and notify all waiter for vCPU state // change, but if there is no exception or syscall in this period, // BounceToKernel will hang at waitUntilNot. diff --git a/pkg/sentry/platform/slimvm/machine_amd64.go b/pkg/sentry/platform/slimvm/machine_amd64.go index 24111178f31..06ae5c11edf 100644 --- a/pkg/sentry/platform/slimvm/machine_amd64.go +++ b/pkg/sentry/platform/slimvm/machine_amd64.go @@ -254,7 +254,7 @@ func (c *vCPU) SwitchToUser(switchOpts ring0.SwitchOpts, info *linux.SignalInfo) // to produce vCPU bounce stalls. switchOpts.PageTables.PrefaultRootTable() - // Enable CPUID Faulting featue if the CPU supported. + // Enable CPUID Faulting feature if the CPU supported. if c.cpuidFaultingEnable == 0 { ring0.SetCPUIDFaulting(true) c.cpuidFaultingEnable = 1 diff --git a/pkg/sentry/platform/systrap/subprocess.go b/pkg/sentry/platform/systrap/subprocess.go index 4de8f9a83d6..20fc061ccef 100644 --- a/pkg/sentry/platform/systrap/subprocess.go +++ b/pkg/sentry/platform/systrap/subprocess.go @@ -338,7 +338,7 @@ func (s *subprocess) handlePtraceSyscallRequest(req any) { // The create function will be called in the latter case, which is guaranteed // to happen with the runtime thread locked. // -// seccompNotify indicates a ways of comunications with syscall threads. +// seccompNotify indicates a ways of communications with syscall threads. // If it is false, futex-s are used. Otherwise, seccomp-unotify is used. // seccomp-unotify can't be used for the source pool process, because it is a // parent of all other stub processes, but only one filter can be installed diff --git a/pkg/sentry/platform/systrap/sysmsg/sighandler_arm64.c b/pkg/sentry/platform/systrap/sysmsg/sighandler_arm64.c index bd85aee8bf9..746f649fffc 100644 --- a/pkg/sentry/platform/systrap/sysmsg/sighandler_arm64.c +++ b/pkg/sentry/platform/systrap/sysmsg/sighandler_arm64.c @@ -51,7 +51,8 @@ long __syscall(long n, long a1, long a2, long a3, long a4, long a5, long a6) { register long x5 __asm__("x5") = a6; __asm__ __volatile__("svc #0" : "=r"(x0) - : "r"(x8), "0"(x0), "r"(x1), "r"(x2), "r"(x3), "r"(x4), "r"(x5) + : "r"(x8), "0"(x0), "r"(x1), "r"(x2), "r"(x3), "r"(x4), + "r"(x5) : "memory", "cc"); return x0; } @@ -75,7 +76,7 @@ long sys_futex(uint32_t *addr, int op, int val, struct __kernel_timespec *tv, static void gregs_to_ptregs(ucontext_t *ucontext, struct user_regs_struct *ptregs) { // Set all registers. - for (int i = 0; i < 31; i++ ) { + for (int i = 0; i < 31; i++) { ptregs->regs[i] = ucontext->uc_mcontext.regs[i]; } ptregs->sp = ucontext->uc_mcontext.sp; @@ -85,7 +86,7 @@ static void gregs_to_ptregs(ucontext_t *ucontext, static void ptregs_to_gregs(ucontext_t *ucontext, struct user_regs_struct *ptregs) { - for (int i = 0; i < 31; i++ ) { + for (int i = 0; i < 31; i++) { ucontext->uc_mcontext.regs[i] = ptregs->regs[i]; } ucontext->uc_mcontext.sp = ptregs->sp; diff --git a/pkg/sentry/seccheck/sinks/remote/server/server.go b/pkg/sentry/seccheck/sinks/remote/server/server.go index 2e285c5dcc9..1f984b1af52 100644 --- a/pkg/sentry/seccheck/sinks/remote/server/server.go +++ b/pkg/sentry/seccheck/sinks/remote/server/server.go @@ -64,7 +64,7 @@ func (c client) close() { } // CommonServer provides common functionality to connect and process messages -// from different clients. Implementors decide how clients and messages are +// from different clients. Implementers decide how clients and messages are // handled, e.g. counting messages for testing. type CommonServer struct { // Endpoint is the path to the socket that the server listens to. diff --git a/pkg/sentry/state/stateio/stateio_impl_util.go b/pkg/sentry/state/stateio/stateio_impl_util.go index aae20254296..50a6f55bab1 100644 --- a/pkg/sentry/state/stateio/stateio_impl_util.go +++ b/pkg/sentry/state/stateio/stateio_impl_util.go @@ -18,7 +18,7 @@ import ( "golang.org/x/sys/unix" ) -// This file contains utilities for implementors of AsyncReader and +// This file contains utilities for implementers of AsyncReader and // AsyncWriter. // NoRegisterClientFD implements AsyncReader.NeedRegisterDestinationFD, diff --git a/pkg/sentry/vfs/mount.go b/pkg/sentry/vfs/mount.go index 40b03b80c0a..c461b1476df 100644 --- a/pkg/sentry/vfs/mount.go +++ b/pkg/sentry/vfs/mount.go @@ -1744,7 +1744,7 @@ func (vfs *VirtualFilesystem) GenerateProcMountInfo(ctx context.Context, taskRoo continue } if mp := vfs.getMountPromise(mntRootVD); mp != nil && !mp.resolved.Load() { - // If the caller is reponsible for resolving the mount promise, + // If the caller is responsible for resolving the mount promise, // blocking below in StatAt will result in deadlock. Some // applications expect mount promises to appear in /proc/mountinfo // (b/388102869), so generate fake information to avoid this. diff --git a/pkg/tcpip/header/ipv4.go b/pkg/tcpip/header/ipv4.go index a0f1cabbbaa..cca3c2459c7 100644 --- a/pkg/tcpip/header/ipv4.go +++ b/pkg/tcpip/header/ipv4.go @@ -170,7 +170,7 @@ var ( // https://www.iana.org/assignments/multicast-addresses/multicast-addresses.xhtml. IPv4AllSystems = tcpip.AddrFrom4([4]byte{0xe0, 0x00, 0x00, 0x01}) - // IPv4Broadcast is the broadcast address of the IPv4 procotol. + // IPv4Broadcast is the broadcast address of the IPv4 protocol. IPv4Broadcast = tcpip.AddrFrom4([4]byte{0xff, 0xff, 0xff, 0xff}) // IPv4Any is the non-routable IPv4 "any" meta address. diff --git a/pkg/tcpip/header/ndp_test.go b/pkg/tcpip/header/ndp_test.go index 26ab5e9ff80..319876f17b8 100644 --- a/pkg/tcpip/header/ndp_test.go +++ b/pkg/tcpip/header/ndp_test.go @@ -1630,7 +1630,7 @@ func TestNDPOptionsIterCheck(t *testing.T) { // TestNDPOptionsIter tests that we can iterator over a valid NDPOptions. Note, // this test does not actually check any of the option's getters, it simply // checks the option Type and Body. We have other tests that tests the option -// field gettings given an option body and don't need to duplicate those tests +// field getters given an option body and don't need to duplicate those tests // here. func TestNDPOptionsIter(t *testing.T) { buf := []byte{ diff --git a/pkg/tcpip/link/sharedmem/pipe/tx.go b/pkg/tcpip/link/sharedmem/pipe/tx.go index 2a14d5d497f..7e9f01b6f83 100644 --- a/pkg/tcpip/link/sharedmem/pipe/tx.go +++ b/pkg/tcpip/link/sharedmem/pipe/tx.go @@ -51,7 +51,7 @@ func (t *Tx) Capacity(recordSize uint64) uint64 { } // Push reserves "payloadSize" bytes for transmission in the pipe. The caller -// populates the returned slice with the data to be transferred and enventually +// populates the returned slice with the data to be transferred and eventually // calls Flush() to make the data visible to the reader, or Abort() to make the // pipe forget all Push() calls since the last Flush(). // diff --git a/pkg/tcpip/network/internal/fragmentation/reassembler.go b/pkg/tcpip/network/internal/fragmentation/reassembler.go index 88b61f1b43c..19758e4e767 100644 --- a/pkg/tcpip/network/internal/fragmentation/reassembler.go +++ b/pkg/tcpip/network/internal/fragmentation/reassembler.go @@ -141,7 +141,7 @@ func (r *reassembler) process(first, last uint16, more bool, proto uint8, pkt *s return nil, 0, false, 0, ErrFragmentOverlap } // Incoming fragment is a duplicate. - // Not dropping packet incase of duplicates. + // Not dropping packet in case of duplicates. continue } diff --git a/pkg/tcpip/network/ipv4/icmp.go b/pkg/tcpip/network/ipv4/icmp.go index 55d925949eb..d3c9e9cdf98 100644 --- a/pkg/tcpip/network/ipv4/icmp.go +++ b/pkg/tcpip/network/ipv4/icmp.go @@ -489,7 +489,7 @@ func (e *endpoint) sendICMPEchoReply(replyData *buffer.View, ipHdr header.IPv4, // message, the source and destination addresses are simply reversed, // the type code changed to 0, and the checksum recomputed. // - // This was interpreted by early implementors to mean that all options must + // This was interpreted by early implementers to mean that all options must // be copied from the echo request IP header to the echo reply IP header // and this behaviour is still relied upon by some applications. // diff --git a/pkg/tcpip/nftables/nftables.go b/pkg/tcpip/nftables/nftables.go index aee75871092..ae2ac5bd275 100644 --- a/pkg/tcpip/nftables/nftables.go +++ b/pkg/tcpip/nftables/nftables.go @@ -1495,7 +1495,7 @@ func (c *Chain) checkLoops(source *Chain, depth int) *syserr.AnnotatedError { return syserr.NewAnnotatedError(syserr.ErrTooManyLinks, fmt.Sprintf("chain %s has exceeded the nested jump limit of %d", c.name, nestedJumpLimit)) } - // Jumping to the same chain is not allowed and although implicitly checked, we explcitly + // Jumping to the same chain is not allowed and although implicitly checked, we explicitly // check it here for clarity. if c == source { return syserr.NewAnnotatedError(syserr.ErrTooManyLinks, fmt.Sprintf("chain %s cannot jump to itself", c.name)) diff --git a/pkg/tcpip/nftables/nftables_test.go b/pkg/tcpip/nftables/nftables_test.go index 04d2b77b54d..0101d230bce 100644 --- a/pkg/tcpip/nftables/nftables_test.go +++ b/pkg/tcpip/nftables/nftables_test.go @@ -6213,7 +6213,7 @@ func TestCompatAddrtypeMatchEvaluation(t *testing.T) { wantVerdict: VC(linux.NFT_BREAK), }, { - name: "destination mis-match", + name: "destination mismatch", matchInfo: addrTypeMatchInfo{ checkSrc: true, sourceMask: linux.XT_ADDRTYPE_BROADCAST, diff --git a/pkg/tcpip/nftables/nftables_types.go b/pkg/tcpip/nftables/nftables_types.go index ff432fffadb..1ba75f017e8 100644 --- a/pkg/tcpip/nftables/nftables_types.go +++ b/pkg/tcpip/nftables/nftables_types.go @@ -1071,7 +1071,7 @@ type nftSet struct { // or the combined length of all the sub-keys. keyLen uint8 // dataLen is the length of the data; - // incase of a verdict set, this is not required. + // in case of a verdict set, this is not required. dataLen uint8 // handle is the NFTables unique identifier for this set. handle uint64 diff --git a/pkg/tcpip/stack/stack_test.go b/pkg/tcpip/stack/stack_test.go index 5a4d9dbe12f..700aabe27c3 100644 --- a/pkg/tcpip/stack/stack_test.go +++ b/pkg/tcpip/stack/stack_test.go @@ -1062,7 +1062,7 @@ func TestRouteWithDownNIC(t *testing.T) { nic2Dst := tcpip.AddrFrom4Slice([]byte("\x06\x00\x00\x00")) nic1RouteMTU := 1500 nic2RouteMTU := 1460 - // These are set in setup function, because they depend on protocl being used. + // These are set in setup function, because they depend on protocol being used. nic1RouteMTUAtNetworkLayer := 0 nic2RouteMTUAtNetworkLayer := 0 diff --git a/pkg/tcpip/tcpip.go b/pkg/tcpip/tcpip.go index de038f3fa90..e295f759e2b 100644 --- a/pkg/tcpip/tcpip.go +++ b/pkg/tcpip/tcpip.go @@ -850,7 +850,7 @@ type Endpoint interface { // protocol-specific and is primarily used for diagnostics. State() uint32 - // ModerateRecvBuf should be called everytime data is copied to the user + // ModerateRecvBuf should be called every time data is copied to the user // space. This allows for dynamic tuning of recv buffer space for a // given socket. // diff --git a/pkg/tcpip/transport/tcp/endpoint.go b/pkg/tcpip/transport/tcp/endpoint.go index 2a1ace93d77..375649bd97d 100644 --- a/pkg/tcpip/transport/tcp/endpoint.go +++ b/pkg/tcpip/transport/tcp/endpoint.go @@ -339,7 +339,7 @@ func (sq *sndQueueInfo) CloneState(other *TCPSndBufState) { // lock from say a syscall goroutine we can implement a bit of spinning if we // know that the lock is not held by another syscall goroutine. Background // processors should never hold the lock for long and we can avoid an expensive -// sleep/wakeup by spinning for a shortwhile. +// sleep/wakeup by spinning for a short while. // // For more details please see the detailed documentation on // e.LockUser/e.UnlockUser methods. diff --git a/pkg/tcpip/transport/tcp/endpoint_state.go b/pkg/tcpip/transport/tcp/endpoint_state.go index d2a8c6d6ea8..f4102ec7955 100644 --- a/pkg/tcpip/transport/tcp/endpoint_state.go +++ b/pkg/tcpip/transport/tcp/endpoint_state.go @@ -288,7 +288,7 @@ func (e *Endpoint) Restore(s *stack.Stack) { connectedLoading.Wait() e.LockUser() // All endpoints will be moved to initial state after - // restore. Set endpoint to its originial listen state. + // restore. Set endpoint to its original listen state. e.setEndpointState(StateListen) // Initialize the listening context. rcvWnd := seqnum.Size(e.receiveBufferAvailable()) diff --git a/pkg/tcpip/transport/tcp/protocol.go b/pkg/tcpip/transport/tcp/protocol.go index 18ff8f4eb16..a3c8295b1ff 100644 --- a/pkg/tcpip/transport/tcp/protocol.go +++ b/pkg/tcpip/transport/tcp/protocol.go @@ -201,7 +201,7 @@ func (p *protocol) HandleUnknownDestinationPacket(id stack.TransportEndpointID, func (p *protocol) tsOffset(src, dst tcpip.Address) tcp.TSOffset { // Initialize a random tsOffset that will be added to the recentTS - // everytime the timestamp is sent when the Timestamp option is enabled. + // every time the timestamp is sent when the Timestamp option is enabled. // // See https://tools.ietf.org/html/rfc7323#section-5.4 for details on // why this is required. diff --git a/pkg/tcpip/transport/tcp/test/e2e/tcp_test.go b/pkg/tcpip/transport/tcp/test/e2e/tcp_test.go index 6448c82656d..184f74b4e8d 100644 --- a/pkg/tcpip/transport/tcp/test/e2e/tcp_test.go +++ b/pkg/tcpip/transport/tcp/test/e2e/tcp_test.go @@ -7253,7 +7253,7 @@ func TestReceiveBufferAutoTuningApplicationLimited(t *testing.T) { // Introduce a 25ms latency by delaying the first byte. latency := 25 * time.Millisecond time.Sleep(latency) - // Send an initial payload with atleast segment overhead size. The receive + // Send an initial payload with at least segment overhead size. The receive // window would not grow for smaller segments. rawEP.SendPacketWithTS(make([]byte, tcp.SegOverheadSize), tsVal) diff --git a/pkg/tcpip/transport/tcp/timer.go b/pkg/tcpip/transport/tcp/timer.go index 7111789d5cb..3c59e109b46 100644 --- a/pkg/tcpip/transport/tcp/timer.go +++ b/pkg/tcpip/transport/tcp/timer.go @@ -39,13 +39,13 @@ const ( // timer is a timer implementation that reduces the interactions with the // clock timer infrastructure by letting timers run (and potentially // eventually expire) even if they are stopped. It makes it cheaper to -// disable/reenable timers at the expense of spurious wakes. This is useful for -// cases when the same timer is disabled/reenabled repeatedly with relatively +// disable/re-enable timers at the expense of spurious wakes. This is useful for +// cases when the same timer is disabled/re-enabled repeatedly with relatively // long timeouts farther into the future. // // TCP retransmit timers benefit from this because they the timeouts are long // (currently at least 200ms), and get disabled when acks are received, and -// reenabled when new pending segments are sent. +// re-enabled when new pending segments are sent. // // It is advantageous to avoid interacting with the clock because it acquires // a global mutex and performs O(log n) operations, where n is the global number diff --git a/runsc/checkpointgofer/gcs/parallelwriter.go b/runsc/checkpointgofer/gcs/parallelwriter.go index ba6fef207e3..795bae149b6 100644 --- a/runsc/checkpointgofer/gcs/parallelwriter.go +++ b/runsc/checkpointgofer/gcs/parallelwriter.go @@ -941,7 +941,7 @@ func (w *ParallelWriter) deleterMain(ctx context.Context) { return case obj := <-w.delete: // Use context.Background() here since we don't want ParallelWriter - // cancelation or closure to cancel deletions. + // cancellation or closure to cancel deletions. if err := obj.Delete(context.Background()); err != nil { log.Warningf("Deletion of %s failed: %v", obj.ObjectName(), err) } diff --git a/runsc/container/container.go b/runsc/container/container.go index f6004850478..f0661cbdf4a 100644 --- a/runsc/container/container.go +++ b/runsc/container/container.go @@ -1560,7 +1560,7 @@ func (c *Container) createGoferProcess(conf *config.Config, mountHints *boot.Pod // shown as `exe`. cmd.Args[0] = "runsc-gofer" - // Tranfer FDs that need to be present before the "gofer" command. + // Transfer FDs that need to be present before the "gofer" command. // Start at 3 because 0, 1, and 2 are taken by stdin/out/err. nextFD := donations.Transfer(cmd, 3) diff --git a/runsc/container/container_test.go b/runsc/container/container_test.go index 809e945f23d..b4865eafdc6 100644 --- a/runsc/container/container_test.go +++ b/runsc/container/container_test.go @@ -5011,7 +5011,7 @@ func TestMountEROFS(t *testing.T) { t.Fatalf("error starting container: %v", err) } - // When running this test inside a user namespace without host root mapped, like bazel is wont to + // When running this test inside a user namespace without host root mapped, as bazel tends to // do, /bin/umount appears as a setuid binary owned by (host) overflow-uid inside the container, // and thus would rob the execing process of its exalted (sandbox) root EUID. So we make a copy. copiedUmount := filepath.Join(testutil.TmpDir(), "umount") diff --git a/runsc/container/multi_container_test.go b/runsc/container/multi_container_test.go index 9b9b37efea0..7f5aa2c3ce8 100644 --- a/runsc/container/multi_container_test.go +++ b/runsc/container/multi_container_test.go @@ -3455,7 +3455,7 @@ func TestFSCheckpointCommand(t *testing.T) { // Helper to add mount hints. addMountHint := func(spec *specs.Spec, name, source string, share string) { // Adding a "bind" mount type annotation with share=container will cause - // the bind mount to be overlayed with medium=self. + // the bind mount to be overlaid with medium=self. spec.Annotations["dev.gvisor.spec.mount."+name+".source"] = source spec.Annotations["dev.gvisor.spec.mount."+name+".share"] = share spec.Annotations["dev.gvisor.spec.mount."+name+".type"] = "bind" diff --git a/runsc/container/state_file.go b/runsc/container/state_file.go index 5e030aadef3..a3f186b5066 100644 --- a/runsc/container/state_file.go +++ b/runsc/container/state_file.go @@ -50,7 +50,7 @@ type LoadOpts struct { // Exact tells whether the search should be exact. See Load() for more. Exact bool - // SkipCheck tells Load() to skip checking if container is runnning. + // SkipCheck tells Load() to skip checking if container is running. SkipCheck bool // TryLock tells Load() to fail if the container state file cannot be locked, diff --git a/test/cmd/test_app/fds.go b/test/cmd/test_app/fds.go index 76736e75163..8bd0306c52b 100644 --- a/test/cmd/test_app/fds.go +++ b/test/cmd/test_app/fds.go @@ -39,7 +39,7 @@ func (*fdSender) Name() string { return "fd_sender" } -// Synopsis implements subcommands.Command.Synopsys. +// Synopsis implements subcommands.Command.Synopsis. func (*fdSender) Synopsis() string { return "creates a file and sends the FD over the socket" } @@ -106,7 +106,7 @@ func (*fdReceiver) Name() string { return "fd_receiver" } -// Synopsis implements subcommands.Command.Synopsys. +// Synopsis implements subcommands.Command.Synopsis. func (*fdReceiver) Synopsis() string { return "reads an FD from a unix socket, and then does things to it" } diff --git a/test/cmd/test_app/main.go b/test/cmd/test_app/main.go index 207a06e9dbf..5babc781ade 100644 --- a/test/cmd/test_app/main.go +++ b/test/cmd/test_app/main.go @@ -90,7 +90,7 @@ func (*fsTreeCreator) Name() string { return "fsTreeCreate" } -// Synopsis implements subcommands.Command.Synopsys. +// Synopsis implements subcommands.Command.Synopsis. func (*fsTreeCreator) Synopsis() string { return "creates a filesystem tree of a certain depth, with a certain number of files on each level and each file with a certain size and type, under a certain directory." } @@ -170,7 +170,7 @@ func (*fsTreeVerify) Name() string { return "fsTreeVerify" } -// Synopsis implements subcommands.Command.Synopsys. +// Synopsis implements subcommands.Command.Synopsis. func (*fsTreeVerify) Synopsis() string { return "verifies a filesystem tree created by fsTreeCreate with the same arguments" } @@ -241,9 +241,9 @@ func (*uds) Name() string { return "uds" } -// Synopsis implements subcommands.Command.Synopsys. +// Synopsis implements subcommands.Command.Synopsis. func (*uds) Synopsis() string { - return "creates unix domain socket client and server. Client sends a contant flow of sequential numbers. Server prints them to --file" + return "creates unix domain socket client and server. Client sends a constant flow of sequential numbers. Server prints them to --file" } // Usage implements subcommands.Command.Usage. @@ -387,7 +387,7 @@ func (*taskTreePGID) Name() string { return "task-tree-pgid" } -// Synopsis implements subcommands.Command.Synopsys. +// Synopsis implements subcommands.Command.Synopsis. func (*taskTreePGID) Synopsis() string { return "creates a child+grandchild in a new process group" } @@ -446,7 +446,7 @@ func (*gvisorDetect) Name() string { return "gvisor-detect" } -// Synopsis implements subcommands.Command.Synopsys. +// Synopsis implements subcommands.Command.Synopsis. func (*gvisorDetect) Synopsis() string { return "checks if the process is running inside gVisor by checking for the marker file" } diff --git a/test/cmd/test_app/zombies.go b/test/cmd/test_app/zombies.go index ee37306ceef..bae83ce135c 100644 --- a/test/cmd/test_app/zombies.go +++ b/test/cmd/test_app/zombies.go @@ -58,7 +58,7 @@ func (*zombieTest) Name() string { return "zombie_test" } -// Synopsis implements subcommands.Command.Synopsys. +// Synopsis implements subcommands.Command.Synopsis. func (*zombieTest) Synopsis() string { return "creates an orphaned grandchild and expects to be reparented and reaped." } diff --git a/test/e2e/exec_test.go b/test/e2e/exec_test.go index bd679e5329a..2280b84369f 100644 --- a/test/e2e/exec_test.go +++ b/test/e2e/exec_test.go @@ -55,7 +55,7 @@ func TestExecCapabilities(t *testing.T) { // Check that capability. caps := []string{"CapInh", "CapPrm", "CapEff", "CapBnd"} - // Expected capabilities for non-root usres. + // Expected capabilities for non-root users. wantCaps := map[string]string{} // For the root user. for _, cap := range caps { diff --git a/test/metricclient/metricclient.go b/test/metricclient/metricclient.go index 775a0601ee3..6e28352ee65 100644 --- a/test/metricclient/metricclient.go +++ b/test/metricclient/metricclient.go @@ -197,7 +197,7 @@ func (c *MetricClient) SpawnServer(ctx context.Context, baseConf *config.Config, RandomizationFactor: 0.1, Clock: backoff.SystemClock, }, bindCtx) - // Overriden metric server address with the address this metric client is configured to use. + // Overridden metric server address with the address this metric client is configured to use. // This should be the same but may contain string replacements (e.g. "%ID%"). overriddenConf := *baseConf overriddenConf.MetricServer = c.addr @@ -247,7 +247,7 @@ func (c *MetricClient) SpawnServer(ctx context.Context, baseConf *config.Config, } // ShutdownServer asks the metrics server to shut itself down. -// It blocks until the server process has exitted or the context expires. +// It blocks until the server process has exited or the context expires. func (c *MetricClient) ShutdownServer(ctx context.Context) error { c.mu.Lock() defer c.mu.Unlock() diff --git a/test/packetimpact/README.md b/test/packetimpact/README.md index 5bcadb76adc..7d2318a6726 100644 --- a/test/packetimpact/README.md +++ b/test/packetimpact/README.md @@ -181,7 +181,7 @@ framework. The test bench framework is based on three basic utilities: To keep the interface to the DUT consistent and easy-to-use, each POSIX command supported by the posix_server is wrapped in functions with signatures similar to the ones in the [Go unix package](https://godoc.org/golang.org/x/sys/unix). This -way all the details of endianess and (un)marshalling of go structs such as +way all the details of endianness and (un)marshalling of go structs such as [unix.Timeval](https://godoc.org/golang.org/x/sys/unix#Timeval) is handled in one place. This also makes it straight-forward to convert tests that use `unix.` or `syscall.` calls to `dut.` calls. @@ -658,8 +658,8 @@ than cast is to a `Connection` and call `Send` on that cast result. ## Putting it all together -Here's what te start of a packetimpact unit test looks like. This test creates a -TCP connection with the DUT. There are added comments for explanation in this +Here's what the start of a packetimpact unit test looks like. This test creates +a TCP connection with the DUT. There are added comments for explanation in this document but a real test might not include them in order to stay even more concise. diff --git a/test/packetimpact/testbench/dut.go b/test/packetimpact/testbench/dut.go index 7e89ba2b39f..6bd2f9ec417 100644 --- a/test/packetimpact/testbench/dut.go +++ b/test/packetimpact/testbench/dut.go @@ -333,7 +333,7 @@ func (dut *DUT) getSockOpt(ctx context.Context, t *testing.T, sockfd, level, opt // GetSockOpt calls getsockopt on the DUT and causes a fatal test failure if it // doesn't succeed. If more control over the timeout or error handling is -// needed, use GetSockOptWithErrno. Because endianess and the width of values +// needed, use GetSockOptWithErrno. Because endianness and the width of values // might differ between the testbench and DUT architectures, prefer to use a // more specific GetSockOptXxx function. func (dut *DUT) GetSockOpt(t *testing.T, sockfd, level, optname, optlen int32) []byte { @@ -346,7 +346,7 @@ func (dut *DUT) GetSockOpt(t *testing.T, sockfd, level, optname, optlen int32) [ return optval } -// GetSockOptWithErrno calls getsockopt on the DUT. Because endianess and the +// GetSockOptWithErrno calls getsockopt on the DUT. Because endianness and the // width of values might differ between the testbench and DUT architectures, // prefer to use a more specific GetSockOptXxxWithErrno function. func (dut *DUT) GetSockOptWithErrno(ctx context.Context, t *testing.T, sockfd, level, optname, optlen int32) (int32, []byte, error) { @@ -414,7 +414,7 @@ func (dut *DUT) GetSockOptTimevalWithErrno(ctx context.Context, t *testing.T, so return ret, timeval, errno } -// GetSockOptTCPInfo retreives TCPInfo for the given socket descriptor. +// GetSockOptTCPInfo retrieves TCPInfo for the given socket descriptor. func (dut *DUT) GetSockOptTCPInfo(t *testing.T, sockfd int32) linux.TCPInfo { t.Helper() @@ -425,7 +425,7 @@ func (dut *DUT) GetSockOptTCPInfo(t *testing.T, sockfd int32) linux.TCPInfo { return info } -// GetSockOptTCPInfoWithErrno retreives TCPInfo with any errno. +// GetSockOptTCPInfoWithErrno retrieves TCPInfo with any errno. func (dut *DUT) GetSockOptTCPInfoWithErrno(ctx context.Context, t *testing.T, sockfd int32) (int32, linux.TCPInfo, error) { t.Helper() @@ -623,7 +623,7 @@ func (dut *DUT) setSockOpt(ctx context.Context, t *testing.T, sockfd, level, opt // SetSockOpt calls setsockopt on the DUT and causes a fatal test failure if it // doesn't succeed. If more control over the timeout or error handling is -// needed, use SetSockOptWithErrno. Because endianess and the width of values +// needed, use SetSockOptWithErrno. Because endianness and the width of values // might differ between the testbench and DUT architectures, prefer to use a // more specific SetSockOptXxx function. func (dut *DUT) SetSockOpt(t *testing.T, sockfd, level, optname int32, optval []byte) { @@ -635,7 +635,7 @@ func (dut *DUT) SetSockOpt(t *testing.T, sockfd, level, optname int32, optval [] } } -// SetSockOptWithErrno calls setsockopt on the DUT. Because endianess and the +// SetSockOptWithErrno calls setsockopt on the DUT. Because endianness and the // width of values might differ between the testbench and DUT architectures, // prefer to use a more specific SetSockOptXxxWithErrno function. func (dut *DUT) SetSockOptWithErrno(ctx context.Context, t *testing.T, sockfd, level, optname int32, optval []byte) (int32, error) { diff --git a/test/packetimpact/testbench/layers.go b/test/packetimpact/testbench/layers.go index 01f1b70497f..b45d9396754 100644 --- a/test/packetimpact/testbench/layers.go +++ b/test/packetimpact/testbench/layers.go @@ -1353,7 +1353,7 @@ func (ls *Layers) linkLayers() { } // ToBytes converts the Layers into bytes. It creates a linked list of the Layer -// structs and then concatentates the output of ToBytes on each Layer. +// structs and then concatenates the output of ToBytes on each Layer. func (ls *Layers) ToBytes() ([]byte, error) { ls.linkLayers() outBytes := []byte{} diff --git a/test/packetimpact/tests/icmpv4_socket_send_recv_test.go b/test/packetimpact/tests/icmpv4_socket_send_recv_test.go index 8e02f85a7da..ac5dac9051f 100644 --- a/test/packetimpact/tests/icmpv4_socket_send_recv_test.go +++ b/test/packetimpact/tests/icmpv4_socket_send_recv_test.go @@ -99,8 +99,8 @@ func (test *icmpV4Test) Send(t *testing.T, dut testbench.DUT, bindTo, sendTo net } expectNetworkUnreachable := true - // We don't expect ENETUNREACH if any of the follwing is true: - // 1. bindTo is specfied. + // We don't expect ENETUNREACH if any of the following is true: + // 1. bindTo is specified. if !bindTo.Equal(net.IPv4zero) { expectNetworkUnreachable = false } diff --git a/test/packetimpact/tests/tcp_network_unreachable_test.go b/test/packetimpact/tests/tcp_network_unreachable_test.go index 1fb81f37e94..5037ae9bf4b 100644 --- a/test/packetimpact/tests/tcp_network_unreachable_test.go +++ b/test/packetimpact/tests/tcp_network_unreachable_test.go @@ -162,7 +162,7 @@ func TestTCPEstablishedUnreachable(t *testing.T) { } // TestTCPSynSentUnreachable6 verifies that TCP connections fail immediately when -// an ICMP destination unreachable message is sent in response to the inital +// an ICMP destination unreachable message is sent in response to the initial // SYN. func TestTCPSynSentUnreachable6(t *testing.T) { // Create the DUT and connection. diff --git a/test/packetimpact/tests/tcp_unacc_seq_ack_test.go b/test/packetimpact/tests/tcp_unacc_seq_ack_test.go index 389bfc62950..76d27f30b1b 100644 --- a/test/packetimpact/tests/tcp_unacc_seq_ack_test.go +++ b/test/packetimpact/tests/tcp_unacc_seq_ack_test.go @@ -108,7 +108,7 @@ func TestPassiveCloseUnaccSeqAck(t *testing.T) { conn.Connect(t) acceptFD, _ := dut.Accept(t, listenFD) - // Send a FIN to DUT to intiate the passive close. + // Send a FIN to DUT to initiate the passive close. conn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagAck | header.TCPFlagFin)}) gotTCP, err := conn.Expect(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagAck)}, time.Second) if err != nil { diff --git a/test/packetimpact/tests/tcp_zero_window_probe_retransmit_test.go b/test/packetimpact/tests/tcp_zero_window_probe_retransmit_test.go index 22b17a39e58..da2b45acb3d 100644 --- a/test/packetimpact/tests/tcp_zero_window_probe_retransmit_test.go +++ b/test/packetimpact/tests/tcp_zero_window_probe_retransmit_test.go @@ -58,7 +58,7 @@ func TestZeroWindowProbeRetransmit(t *testing.T) { // exponentially increasing intervals. The timeout intervals are function // of the recorded first zero probe transmission duration. // - // Advertize zero receive window along with a payload. + // Advertise zero receive window along with a payload. conn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagAck | header.TCPFlagPsh), WindowSize: testbench.Uint16(0)}, samplePayload) if _, err := conn.ExpectData(t, &testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagAck)}, nil, time.Second); err != nil { t.Fatalf("expected packet was not received: %s", err) @@ -106,7 +106,7 @@ func TestZeroWindowProbeRetransmit(t *testing.T) { // Acknowledge the zero-window probes from the dut. conn.Send(t, testbench.TCP{AckNum: ackProbe, Flags: testbench.TCPFlags(header.TCPFlagAck), WindowSize: testbench.Uint16(0)}) } - // Advertize non-zero window. + // Advertise non-zero window. conn.Send(t, testbench.TCP{AckNum: ackProbe, Flags: testbench.TCPFlags(header.TCPFlagAck)}) // Expect the dut to recover and transmit data. if _, err := conn.ExpectData(t, &testbench.TCP{SeqNum: ackProbe}, samplePayload, time.Second); err != nil { diff --git a/test/packetimpact/tests/tcp_zero_window_probe_test.go b/test/packetimpact/tests/tcp_zero_window_probe_test.go index 8b90fcbe9a2..defd4ac925a 100644 --- a/test/packetimpact/tests/tcp_zero_window_probe_test.go +++ b/test/packetimpact/tests/tcp_zero_window_probe_test.go @@ -61,7 +61,7 @@ func TestZeroWindowProbe(t *testing.T) { // Test 1: Check for receive of a zero window probe, record the duration for // probe to be sent. // - // Advertize zero window to the dut. + // Advertise zero window to the dut. conn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagAck), WindowSize: testbench.Uint16(0)}) // Expected sequence number of the zero window probe. @@ -92,7 +92,7 @@ func TestZeroWindowProbe(t *testing.T) { // Test 2: Check if the dut recovers on advertizing non-zero receive window. // and sends out the sample payload after the send window opens. // - // Advertize non-zero window to the dut and ack the zero window probe. + // Advertise non-zero window to the dut and ack the zero window probe. conn.Send(t, testbench.TCP{AckNum: ackProbe, Flags: testbench.TCPFlags(header.TCPFlagAck)}) // Expect the dut to recover and transmit data. if _, err := conn.ExpectData(t, &testbench.TCP{SeqNum: ackProbe}, samplePayload, time.Second); err != nil { diff --git a/test/packetimpact/tests/tcp_zero_window_probe_usertimeout_test.go b/test/packetimpact/tests/tcp_zero_window_probe_usertimeout_test.go index 1ce4d22b79d..6a3ab3ee237 100644 --- a/test/packetimpact/tests/tcp_zero_window_probe_usertimeout_test.go +++ b/test/packetimpact/tests/tcp_zero_window_probe_usertimeout_test.go @@ -59,7 +59,7 @@ func TestZeroWindowProbeUserTimeout(t *testing.T) { // Test 1: Check for receive of a zero window probe, record the duration for // probe to be sent. // - // Advertize zero window to the dut. + // Advertise zero window to the dut. conn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagAck), WindowSize: testbench.Uint16(0)}) // Expected sequence number of the zero window probe. @@ -80,7 +80,7 @@ func TestZeroWindowProbeUserTimeout(t *testing.T) { // // Reduce the retransmit timeout. dut.SetSockOptInt(t, acceptFd, unix.IPPROTO_TCP, unix.TCP_USER_TIMEOUT, int32(startProbeDuration.Milliseconds())) - // Advertize zero window again. + // Advertise zero window again. conn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagAck), WindowSize: testbench.Uint16(0)}) // Ask the dut to send out data that would trigger zero window probe retransmissions. dut.Send(t, acceptFd, sampleData, 0) diff --git a/test/runner/gtest/gtest.go b/test/runner/gtest/gtest.go index 5ced2655314..c95d53a6fc4 100644 --- a/test/runner/gtest/gtest.go +++ b/test/runner/gtest/gtest.go @@ -47,7 +47,7 @@ type TestCase struct { Name string // all indicates that this will run without flags. This takes - // precendence over benchmark below. + // precedence over benchmark below. all bool // benchmark indicates that this is a benchmark. In this case, the diff --git a/test/syscalls/linux/flock.cc b/test/syscalls/linux/flock.cc index b4f4316f2a2..f95e79cb946 100644 --- a/test/syscalls/linux/flock.cc +++ b/test/syscalls/linux/flock.cc @@ -439,7 +439,7 @@ TEST_F(FlockTest, TestDupFdUnlockRelease) { * operation on any of these duplicate descriptors, or when all such * descriptors have been closed. */ - // This test will verify that an explict unlock on a dupped FD will release + // This test will verify that an explicit unlock on a dupped FD will release // the underlying lock unlike the previous case where close on a dup was // not enough to release the lock. ASSERT_THAT(flock(test_file_fd_.get(), LOCK_EX | LOCK_NB), diff --git a/test/syscalls/linux/partial_bad_buffer.cc b/test/syscalls/linux/partial_bad_buffer.cc index f305d1b8e7d..911b0ffc795 100644 --- a/test/syscalls/linux/partial_bad_buffer.cc +++ b/test/syscalls/linux/partial_bad_buffer.cc @@ -387,7 +387,7 @@ TEST_F(PartialBadBufferTest, SendMsgTCP) { ASSERT_THAT(RetryEINTR(read)(recv_socket.get(), buffer.data(), kPageSize), SyscallSucceedsWithValue(kPageSize)); - // Sleep for a shortwhile to ensure that we have time to process the + // Sleep for a short while to ensure that we have time to process the // ACKs. This is not strictly required unless running under gotsan which is a // lot slower and can result in the next write to write only 1 byte instead of // our intended kPageSize + 1. diff --git a/test/syscalls/linux/ping_socket.cc b/test/syscalls/linux/ping_socket.cc index bb8e3281bbd..09562b3d856 100644 --- a/test/syscalls/linux/ping_socket.cc +++ b/test/syscalls/linux/ping_socket.cc @@ -586,8 +586,7 @@ std::string TestDescription( auto [socket_factory, test_case] = info.param; std::string name = absl::StrJoin( {socket_factory.description, test_case.bind_to.description}, "_"); - absl::c_replace_if( - name, [](char c) { return !std::isalnum(c); }, '_'); + absl::c_replace_if(name, [](char c) { return !std::isalnum(c); }, '_'); return name; } diff --git a/test/syscalls/linux/ptrace.cc b/test/syscalls/linux/ptrace.cc index 88388b13dc0..b02e8977066 100644 --- a/test/syscalls/linux/ptrace.cc +++ b/test/syscalls/linux/ptrace.cc @@ -1167,8 +1167,7 @@ TEST(PtraceTest, GetSigMask) { // Install a signal handler for kBlockSignal to avoid termination and block // it. - TEST_PCHECK(signal( - kBlockSignal, +[](int signo) {}) != SIG_ERR); + TEST_PCHECK(signal(kBlockSignal, +[](int signo) {}) != SIG_ERR); MaybeSave(); TEST_PCHECK(sigprocmask(SIG_SETMASK, &blocked, nullptr) == 0); MaybeSave(); diff --git a/test/syscalls/linux/raw_socket.cc b/test/syscalls/linux/raw_socket.cc index 58a2f4de56f..f70e835ee53 100644 --- a/test/syscalls/linux/raw_socket.cc +++ b/test/syscalls/linux/raw_socket.cc @@ -763,8 +763,9 @@ TEST_P(RawSocketTest, RecvBufLimits) { // Set a receive timeout so that we don't block forever on reads if the test // fails. - struct timeval tv { - .tv_sec = 1, .tv_usec = 0, + struct timeval tv{ + .tv_sec = 1, + .tv_usec = 0, }; ASSERT_THAT(setsockopt(s_, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)), SyscallSucceeds()); diff --git a/test/syscalls/linux/socket_generic_test_cases.cc b/test/syscalls/linux/socket_generic_test_cases.cc index b28f6484987..1654cf0c38d 100644 --- a/test/syscalls/linux/socket_generic_test_cases.cc +++ b/test/syscalls/linux/socket_generic_test_cases.cc @@ -486,9 +486,7 @@ TEST_P(AllSocketPairTest, GetSndBufSucceeds) { TEST_P(AllSocketPairTest, RecvTimeoutReadSucceeds) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); - struct timeval tv { - .tv_sec = 0, .tv_usec = 10 - }; + struct timeval tv{.tv_sec = 0, .tv_usec = 10}; EXPECT_THAT( setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)), SyscallSucceeds()); @@ -501,9 +499,7 @@ TEST_P(AllSocketPairTest, RecvTimeoutReadSucceeds) { TEST_P(AllSocketPairTest, RecvTimeoutRecvSucceeds) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); - struct timeval tv { - .tv_sec = 0, .tv_usec = 10 - }; + struct timeval tv{.tv_sec = 0, .tv_usec = 10}; EXPECT_THAT( setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)), SyscallSucceeds()); @@ -516,9 +512,7 @@ TEST_P(AllSocketPairTest, RecvTimeoutRecvSucceeds) { TEST_P(AllSocketPairTest, RecvTimeoutRecvOneSecondSucceeds) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); - struct timeval tv { - .tv_sec = 1, .tv_usec = 0 - }; + struct timeval tv{.tv_sec = 1, .tv_usec = 0}; EXPECT_THAT( setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)), SyscallSucceeds()); @@ -531,9 +525,7 @@ TEST_P(AllSocketPairTest, RecvTimeoutRecvOneSecondSucceeds) { TEST_P(AllSocketPairTest, RecvTimeoutRecvmsgSucceeds) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); - struct timeval tv { - .tv_sec = 0, .tv_usec = 10 - }; + struct timeval tv{.tv_sec = 0, .tv_usec = 10}; EXPECT_THAT( setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)), SyscallSucceeds()); @@ -609,9 +601,7 @@ TEST_P(AllSocketPairTest, SetGetSendTimeoutLargerArg) { TEST_P(AllSocketPairTest, SendTimeoutAllowsWrite) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); - struct timeval tv { - .tv_sec = 0, .tv_usec = 10 - }; + struct timeval tv{.tv_sec = 0, .tv_usec = 10}; EXPECT_THAT( setsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)), SyscallSucceeds()); @@ -624,9 +614,7 @@ TEST_P(AllSocketPairTest, SendTimeoutAllowsWrite) { TEST_P(AllSocketPairTest, SendTimeoutAllowsSend) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); - struct timeval tv { - .tv_sec = 0, .tv_usec = 10 - }; + struct timeval tv{.tv_sec = 0, .tv_usec = 10}; EXPECT_THAT( setsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)), SyscallSucceeds()); @@ -639,9 +627,7 @@ TEST_P(AllSocketPairTest, SendTimeoutAllowsSend) { TEST_P(AllSocketPairTest, SendTimeoutAllowsSendmsg) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); - struct timeval tv { - .tv_sec = 0, .tv_usec = 10 - }; + struct timeval tv{.tv_sec = 0, .tv_usec = 10}; EXPECT_THAT( setsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)), SyscallSucceeds()); @@ -707,9 +693,7 @@ TEST_P(AllSocketPairTest, SetGetRecvTimeoutLargerArg) { TEST_P(AllSocketPairTest, RecvTimeoutRecvmsgOneSecondSucceeds) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); - struct timeval tv { - .tv_sec = 1, .tv_usec = 0 - }; + struct timeval tv{.tv_sec = 1, .tv_usec = 0}; EXPECT_THAT( setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)), SyscallSucceeds()); @@ -729,8 +713,8 @@ TEST_P(AllSocketPairTest, RecvTimeoutRecvmsgOneSecondSucceeds) { TEST_P(AllSocketPairTest, RecvTimeoutUsecTooLarge) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); - struct timeval tv { - .tv_sec = 0, .tv_usec = 2000000 // 2 seconds. + struct timeval tv{ + .tv_sec = 0, .tv_usec = 2000000 // 2 seconds. }; EXPECT_THAT( setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)), @@ -740,8 +724,8 @@ TEST_P(AllSocketPairTest, RecvTimeoutUsecTooLarge) { TEST_P(AllSocketPairTest, SendTimeoutUsecTooLarge) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); - struct timeval tv { - .tv_sec = 0, .tv_usec = 2000000 // 2 seconds. + struct timeval tv{ + .tv_sec = 0, .tv_usec = 2000000 // 2 seconds. }; EXPECT_THAT( setsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)), @@ -751,9 +735,7 @@ TEST_P(AllSocketPairTest, SendTimeoutUsecTooLarge) { TEST_P(AllSocketPairTest, RecvTimeoutUsecNeg) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); - struct timeval tv { - .tv_sec = 0, .tv_usec = -1 - }; + struct timeval tv{.tv_sec = 0, .tv_usec = -1}; EXPECT_THAT( setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)), SyscallFailsWithErrno(EDOM)); @@ -762,9 +744,7 @@ TEST_P(AllSocketPairTest, RecvTimeoutUsecNeg) { TEST_P(AllSocketPairTest, SendTimeoutUsecNeg) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); - struct timeval tv { - .tv_sec = 0, .tv_usec = -1 - }; + struct timeval tv{.tv_sec = 0, .tv_usec = -1}; EXPECT_THAT( setsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)), SyscallFailsWithErrno(EDOM)); @@ -773,9 +753,7 @@ TEST_P(AllSocketPairTest, SendTimeoutUsecNeg) { TEST_P(AllSocketPairTest, RecvTimeoutNegSecRead) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); - struct timeval tv { - .tv_sec = -1, .tv_usec = 0 - }; + struct timeval tv{.tv_sec = -1, .tv_usec = 0}; EXPECT_THAT( setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)), SyscallSucceeds()); @@ -788,9 +766,7 @@ TEST_P(AllSocketPairTest, RecvTimeoutNegSecRead) { TEST_P(AllSocketPairTest, RecvTimeoutNegSecRecv) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); - struct timeval tv { - .tv_sec = -1, .tv_usec = 0 - }; + struct timeval tv{.tv_sec = -1, .tv_usec = 0}; EXPECT_THAT( setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)), SyscallSucceeds()); @@ -803,9 +779,7 @@ TEST_P(AllSocketPairTest, RecvTimeoutNegSecRecv) { TEST_P(AllSocketPairTest, RecvTimeoutNegSecRecvmsg) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); - struct timeval tv { - .tv_sec = -1, .tv_usec = 0 - }; + struct timeval tv{.tv_sec = -1, .tv_usec = 0}; EXPECT_THAT( setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)), SyscallSucceeds()); @@ -851,9 +825,7 @@ TEST_P(AllSocketPairTest, RecvWaitAllDontWait) { TEST_P(AllSocketPairTest, RecvTimeoutWaitAll) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); - struct timeval tv { - .tv_sec = 1, .tv_usec = 0 - }; + struct timeval tv{.tv_sec = 1, .tv_usec = 0}; EXPECT_THAT(setsockopt(sockets->second_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)), SyscallSucceeds()); diff --git a/test/syscalls/linux/socket_inet_loopback.cc b/test/syscalls/linux/socket_inet_loopback.cc index 12ecedc6629..d504bf43aee 100644 --- a/test/syscalls/linux/socket_inet_loopback.cc +++ b/test/syscalls/linux/socket_inet_loopback.cc @@ -1213,7 +1213,7 @@ TEST_P(SocketInetLoopbackTest, TCPResetAfterClose) { // have timed out and closed the socket. EXPECT_THAT(RetryEINTR(send)(accepted.get(), &data, sizeof(data), 0), SyscallSucceeds()); - // Sleep for a shortwhile to get a RST back. + // Sleep for a short while to get a RST back. absl::SleepFor(absl::Seconds(1)); // Try writing again and we should get an EPIPE back. diff --git a/test/syscalls/linux/socket_ip_tcp_generic.cc b/test/syscalls/linux/socket_ip_tcp_generic.cc index bcc9e3b259b..e0578fd6ae1 100644 --- a/test/syscalls/linux/socket_ip_tcp_generic.cc +++ b/test/syscalls/linux/socket_ip_tcp_generic.cc @@ -204,7 +204,7 @@ TEST_P(TCPSocketPairTest, RSTSentOnCloseWithUnreadDataAllowsReadBuffered) { SyscallFailsWithErrno(ECONNRESET)); } -// This test will verify that a clean shutdown (FIN) is preformed when there +// This test will verify that a clean shutdown (FIN) is performed when there // is unread data but only the write side is closed. TEST_P(TCPSocketPairTest, FINSentOnShutdownWrWithUnreadData) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); diff --git a/test/syscalls/linux/socket_ip_unbound.cc b/test/syscalls/linux/socket_ip_unbound.cc index 0f756e1b197..5c1dfe7e030 100644 --- a/test/syscalls/linux/socket_ip_unbound.cc +++ b/test/syscalls/linux/socket_ip_unbound.cc @@ -297,7 +297,7 @@ TEST_P(IPUnboundSocketTest, LargeTOSOptionSize) { SyscallSucceedsWithValue(0)); int get = -1; socklen_t get_sz = i; - // We expect the system call handler to only copy atmost sizeof(int) bytes + // We expect the system call handler to only copy at most sizeof(int) bytes // as asserted by the check below. Hence, we do not expect the copy to // overflow in getsockopt. ASSERT_THAT(getsockopt(socket->get(), t.level, t.option, &get, &get_sz), diff --git a/test/syscalls/linux/socket_netlink.cc b/test/syscalls/linux/socket_netlink.cc index f5b6aad4f90..e03147cf4b8 100644 --- a/test/syscalls/linux/socket_netlink.cc +++ b/test/syscalls/linux/socket_netlink.cc @@ -152,15 +152,11 @@ TEST_P(NetlinkTest, GetSendTimeout) { ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_NETLINK, SOCK_RAW, protocol)); // tv_usec should be a multiple of 4000 to work on most systems. - struct timeval tv_to_set { - .tv_sec = 1, .tv_usec = 40000 - }; + struct timeval tv_to_set{.tv_sec = 1, .tv_usec = 40000}; EXPECT_THAT(setsockopt(fd.get(), SOL_SOCKET, SO_SNDTIMEO, &tv_to_set, sizeof(tv_to_set)), SyscallSucceeds()); - struct timeval tv { - .tv_sec = -1, .tv_usec = -1 - }; + struct timeval tv{.tv_sec = -1, .tv_usec = -1}; socklen_t len = sizeof(tv); EXPECT_THAT(getsockopt(fd.get(), SOL_SOCKET, SO_SNDTIMEO, &tv, &len), SyscallSucceeds()); @@ -175,15 +171,11 @@ TEST_P(NetlinkTest, GetReceiveTimeout) { ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_NETLINK, SOCK_RAW, protocol)); // tv_usec should be a multiple of 4000 to work on most systems. - struct timeval tv_to_set { - .tv_sec = 1, .tv_usec = 8000 - }; + struct timeval tv_to_set{.tv_sec = 1, .tv_usec = 8000}; EXPECT_THAT(setsockopt(fd.get(), SOL_SOCKET, SO_RCVTIMEO, &tv_to_set, sizeof(tv_to_set)), SyscallSucceeds()); - struct timeval tv { - .tv_sec = -1, .tv_usec = -1 - }; + struct timeval tv{.tv_sec = -1, .tv_usec = -1}; socklen_t len = sizeof(tv); EXPECT_THAT(getsockopt(fd.get(), SOL_SOCKET, SO_RCVTIMEO, &tv, &len), SyscallSucceeds()); diff --git a/test/syscalls/linux/socket_stream_blocking.cc b/test/syscalls/linux/socket_stream_blocking.cc index 7ea484e890d..eb39e8aad3d 100644 --- a/test/syscalls/linux/socket_stream_blocking.cc +++ b/test/syscalls/linux/socket_stream_blocking.cc @@ -143,9 +143,7 @@ TEST_P(BlockingStreamSocketPairTest, RecvLessThanBufferWaitAll) { TEST_P(BlockingStreamSocketPairTest, SendTimeout) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); - struct timeval tv { - .tv_sec = 0, .tv_usec = 10 - }; + struct timeval tv{.tv_sec = 0, .tv_usec = 10}; EXPECT_THAT( setsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)), SyscallSucceeds()); diff --git a/test/syscalls/linux/socket_unix_cmsg.cc b/test/syscalls/linux/socket_unix_cmsg.cc index 33eb841c0b9..9b1ce201a9f 100644 --- a/test/syscalls/linux/socket_unix_cmsg.cc +++ b/test/syscalls/linux/socket_unix_cmsg.cc @@ -886,9 +886,7 @@ TEST_P(UnixSocketPairCmsgTest, SendNullCredsBeforeSoPassCredRecvEnd) { EXPECT_EQ(0, memcmp(sent_data, received_data, sizeof(sent_data))); - struct ucred want_creds { - 0, 65534, 65534 - }; + struct ucred want_creds{0, 65534, 65534}; EXPECT_EQ(want_creds.pid, received_creds.pid); EXPECT_EQ(want_creds.uid, received_creds.uid); @@ -1009,9 +1007,7 @@ TEST_P(UnixSocketPairCmsgTest, WriteBeforeSoPassCredRecvEnd) { EXPECT_EQ(0, memcmp(sent_data, received_data, sizeof(sent_data))); - struct ucred want_creds { - 0, 65534, 65534 - }; + struct ucred want_creds{0, 65534, 65534}; EXPECT_EQ(want_creds.pid, received_creds.pid); EXPECT_EQ(want_creds.uid, received_creds.uid); @@ -1461,9 +1457,7 @@ TEST_P(UnixSocketPairCmsgTest, FDPassBeforeSoPassCred) { EXPECT_EQ(0, memcmp(sent_data, received_data, sizeof(sent_data))); - struct ucred want_creds { - 0, 65534, 65534 - }; + struct ucred want_creds{0, 65534, 65534}; EXPECT_EQ(want_creds.pid, received_creds.pid); EXPECT_EQ(want_creds.uid, received_creds.uid); diff --git a/test/syscalls/linux/socket_unix_non_stream.cc b/test/syscalls/linux/socket_unix_non_stream.cc index c017cfdd026..d4b6f04bedd 100644 --- a/test/syscalls/linux/socket_unix_non_stream.cc +++ b/test/syscalls/linux/socket_unix_non_stream.cc @@ -233,9 +233,7 @@ TEST_P(UnixNonStreamSocketPairTest, FragmentedRecvMsg) { TEST_P(UnixNonStreamSocketPairTest, SendTimeout) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); - struct timeval tv { - .tv_sec = 0, .tv_usec = 10 - }; + struct timeval tv{.tv_sec = 0, .tv_usec = 10}; EXPECT_THAT( setsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)), SyscallSucceeds()); diff --git a/test/syscalls/linux/socket_unix_stream.cc b/test/syscalls/linux/socket_unix_stream.cc index dd53208a84a..3333c2aa31d 100644 --- a/test/syscalls/linux/socket_unix_stream.cc +++ b/test/syscalls/linux/socket_unix_stream.cc @@ -59,9 +59,7 @@ TEST_P(StreamUnixSocketPairTest, RecvmsgOneSideClosed) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); // Set timeout so that it will not wait for ever. - struct timeval tv { - .tv_sec = 0, .tv_usec = 10 - }; + struct timeval tv{.tv_sec = 0, .tv_usec = 10}; EXPECT_THAT(setsockopt(sockets->second_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)), SyscallSucceeds()); diff --git a/test/syscalls/linux/socket_unix_unbound_stream.cc b/test/syscalls/linux/socket_unix_unbound_stream.cc index b10062bc283..94994288477 100644 --- a/test/syscalls/linux/socket_unix_unbound_stream.cc +++ b/test/syscalls/linux/socket_unix_unbound_stream.cc @@ -331,9 +331,7 @@ TEST_P(UnixStreamSocketPairTest, CredsNotCoalescedUp) { EXPECT_EQ(0, memcmp(sent_data1, received_data, sizeof(sent_data1))); - struct ucred want_creds { - 0, 65534, 65534 - }; + struct ucred want_creds{0, 65534, 65534}; EXPECT_EQ(want_creds.pid, received_creds.pid); EXPECT_EQ(want_creds.uid, received_creds.uid); @@ -462,9 +460,7 @@ TEST_P(UnixStreamSocketPairTest, CoalescedCreds1) { EXPECT_EQ(0, memcmp(sent_data2, received_data + sizeof(sent_data1), sizeof(sent_data2))); - struct ucred want_creds { - 0, 65534, 65534 - }; + struct ucred want_creds{0, 65534, 65534}; EXPECT_EQ(want_creds.pid, received_creds.pid); EXPECT_EQ(want_creds.uid, received_creds.uid); @@ -533,9 +529,7 @@ TEST_P(UnixStreamSocketPairTest, NonCoalescedDifferingCreds1) { EXPECT_EQ(0, memcmp(sent_data1, received_data1, sizeof(sent_data1))); - struct ucred want_creds1 { - 0, 65534, 65534 - }; + struct ucred want_creds1{0, 65534, 65534}; EXPECT_EQ(want_creds1.pid, received_creds1.pid); EXPECT_EQ(want_creds1.uid, received_creds1.uid); @@ -605,9 +599,7 @@ TEST_P(UnixStreamSocketPairTest, NonCoalescedDifferingCreds2) { EXPECT_EQ(0, memcmp(sent_data2, received_data2, sizeof(sent_data2))); - struct ucred want_creds2 { - 0, 65534, 65534 - }; + struct ucred want_creds2{0, 65534, 65534}; EXPECT_EQ(want_creds2.pid, received_creds2.pid); EXPECT_EQ(want_creds2.uid, received_creds2.uid); diff --git a/test/syscalls/linux/stat.cc b/test/syscalls/linux/stat.cc index 71f0be3ef00..f5623386748 100644 --- a/test/syscalls/linux/stat.cc +++ b/test/syscalls/linux/stat.cc @@ -471,7 +471,7 @@ TEST_F(StatTest, LinkCountsWithRegularFileChild) { // // It is marked NoSave because we don't support saving unlinked files. TEST_F(StatTest, ZeroLinksOpenFdRegularFileChild_NoSave) { - // Setting the enviornment variable GVISOR_GOFER_UNCACHED to any value + // Setting the environment variable GVISOR_GOFER_UNCACHED to any value // will prevent this test from running, see the tmpfs lifecycle. // // We need to support this because when a file is unlinked and we forward diff --git a/test/util/multiprocess_util.h b/test/util/multiprocess_util.h index 155d578976a..2cbb96226a0 100644 --- a/test/util/multiprocess_util.h +++ b/test/util/multiprocess_util.h @@ -100,8 +100,7 @@ inline PosixErrorOr ForkAndExec(const std::string& filename, const ExecveArray& argv, const ExecveArray& envv, pid_t* child, int* execve_errno) { - return ForkAndExec( - filename, argv, envv, [] {}, child, execve_errno); + return ForkAndExec(filename, argv, envv, [] {}, child, execve_errno); } // Equivalent to ForkAndExec, except using dirfd and flags with execveat. diff --git a/test/util/proc_util.h b/test/util/proc_util.h index c5ca9760dd5..0f171b0dd82 100644 --- a/test/util/proc_util.h +++ b/test/util/proc_util.h @@ -178,13 +178,12 @@ MATCHER_P(ContainsMappings, mappings, // the major, minor, and inode fields. bool all_present = true; std::for_each(mappings.begin(), mappings.end(), [&](const ProcMapsEntry& e1) { - auto it = - absl::c_find_if(maps, [&e1](const ProcMapsEntry& e2) { - return e1.start == e2.start && e1.end == e2.end && - e1.readable == e2.readable && e1.writable == e2.writable && - e1.executable == e2.executable && e1.priv == e2.priv && - e1.offset == e2.offset && e1.filename == e2.filename; - }); + auto it = absl::c_find_if(maps, [&e1](const ProcMapsEntry& e2) { + return e1.start == e2.start && e1.end == e2.end && + e1.readable == e2.readable && e1.writable == e2.writable && + e1.executable == e2.executable && e1.priv == e2.priv && + e1.offset == e2.offset && e1.filename == e2.filename; + }); if (it == maps.end()) { // It wasn't found. if (all_present) { diff --git a/tools/.codespellrc b/tools/.codespellrc new file mode 100644 index 00000000000..0a8678213af --- /dev/null +++ b/tools/.codespellrc @@ -0,0 +1,56 @@ +[codespell] +skip = .git,tags,go.mod,go.sum,*/latin10k.txt,*website/assets/images/* +# One entry per line; indentation continues the value. Lowercase entries match +# case-insensitively; entries with a capital letter match that casing only. +ignore-words-list = + # maintainer given names, see MAINTAINERS.md. + adin, + parth, + # Go identifiers and struct fields that codespell reads as prose. + addOpt, + appAR, + appendEnd, + canBe, + copyin, + FileTest, + FillIn, + nowns, + offsetP, + openIn, + pevents, + prevEnd, + readIn, + refErr, + savable, + sReturns, + startIn, + writeN, + # short local variables and loop indices. + fo, + nd, + ot, + ser, + te, + tru, + # abbreviations that are correct in context. + cacl, + flate, + hart, + iif, + ist, + mmaped, + PENDIN, + reord, + VAs, + # AtLeast is version.AtLeast; lowercase "atleast" stays a typo. + AtLeast, + # truncated words in test data and expected output. + hel, + packe, + protestors, + retrival, + stopp, + # as in "raison d'etre". + raison, + # verbatim text from the Contributor Covenant. + socio-economic, diff --git a/tools/bazel.mk b/tools/bazel.mk index f2f32e5bbe8..2c77a93fa73 100644 --- a/tools/bazel.mk +++ b/tools/bazel.mk @@ -42,6 +42,11 @@ ## ## To opt out of these wrappers, set DOCKER_BUILD=false. DOCKER_BUILD := true +ifneq ($(MAKECMDGOALS),) +ifeq ($(filter-out help lint lint-%,$(MAKECMDGOALS)),) +DOCKER_BUILD := false +endif +endif ifeq ($(DOCKER_BUILD),true) -include bazel-server-inc endif diff --git a/tools/checkescape/checkescape.go b/tools/checkescape/checkescape.go index c687c5df5fb..8b6a989239a 100644 --- a/tools/checkescape/checkescape.go +++ b/tools/checkescape/checkescape.go @@ -738,7 +738,7 @@ func run(pass *analysis.Pass, binary io.Reader) (any, error) { } // If this package is the atomic package, the implementation - // may be replaced by instrinsics that don't have analysis. + // may be replaced by intrinsics that don't have analysis. if x.Pkg != nil && x.Pkg.Pkg.Path() == "sync/atomic" { return } diff --git a/tools/lint.sh b/tools/lint.sh new file mode 100755 index 00000000000..52cfa60c0d1 --- /dev/null +++ b/tools/lint.sh @@ -0,0 +1,376 @@ +#!/bin/bash + +# Copyright 2026 The gVisor Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# lint.sh runs gVisor's source-level lint checks. It runs without Bazel or a +# builder container. Deep Go analysis is owned by gVisor nogo. +# +# Usage: +# tools/lint.sh # run every check +# tools/lint.sh gofmt clang-format # run only the named checks +# tools/lint.sh --fix # rewrite files in place where a check can +# +# Environment: +# LINT_CACHE_DIR where to cache downloaded linters +# (default: ~/.cache/gvisor/lint) + +set -euo pipefail + +declare REPO_DIR +REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +readonly REPO_DIR +cd "${REPO_DIR}" + +declare -r CACHE_DIR="${LINT_CACHE_DIR:-${HOME}/.cache/gvisor/lint}" + +# Every check, in run order, named as tools/lint.sh accepts it. +declare -ra ALL_CHECKS=(gofmt clang-format buildifier actions spelling) +# Only the formatters can rewrite a file; the rest have no safe autofix. +declare -ra FIXABLE_CHECKS=(gofmt clang-format buildifier) + +declare -r ACTIONLINT_VERSION="1.7.7" +declare -r CODESPELL_VERSION="2.3.0" +declare -r CLANG_FORMAT_VERSION="20.1.8" +# Keep in sync with images/default/Dockerfile. +declare -r BUILDIFIER_VERSION="8.5.1" + +# The codespell wheel is architecture-independent. +declare -r CODESPELL_URL="https://files.pythonhosted.org/packages/0e/20/b6019add11e84f821184234cea0ad91442373489ef7ccfa3d73a71b908fa/codespell-${CODESPELL_VERSION}-py3-none-any.whl" +declare -r CODESPELL_SHA256="a9c7cef2501c9cfede2110fd6d4e5e62296920efe9abfb84648df866e47f58d1" + +case "$(uname -m)" in + x86_64|amd64) + declare -r ACTIONLINT_ARCH="amd64" + declare -r ACTIONLINT_SHA256="023070a287cd8cccd71515fedc843f1985bf96c436b7effaecce67290e7e0757" + declare -r BUILDIFIER_ARCH="amd64" + declare -r BUILDIFIER_SHA256="887377fc64d23a850f4d18a077b5db05b19913f4b99b270d193f3c7334b5a9a7" + declare -r CLANG_FORMAT_URL="https://files.pythonhosted.org/packages/a6/77/786aa0fc8a75d8ce94966bb33e44c63fec1964cbf343ee862ed6a5be38c1/clang_format-${CLANG_FORMAT_VERSION}-py2.py3-none-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl" + declare -r CLANG_FORMAT_SHA256="7c6bcb7e01ba4f05a4c980fda147b330f7e4833c2aea8c92a0c2df9573ae7afe" + ;; + aarch64|arm64) + declare -r ACTIONLINT_ARCH="arm64" + declare -r ACTIONLINT_SHA256="401942f9c24ed71e4fe71b76c7d638f66d8633575c4016efd2977ce7c28317d0" + declare -r BUILDIFIER_ARCH="arm64" + declare -r BUILDIFIER_SHA256="947bf6700d708026b2057b09bea09abbc3cafc15d9ecea35bb3885c4b09ccd04" + declare -r CLANG_FORMAT_URL="https://files.pythonhosted.org/packages/06/60/7c2ff3019599ad985d0a61f74ba8226d538c72485b0e3d25b1899601a9f5/clang_format-${CLANG_FORMAT_VERSION}-py2.py3-none-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl" + declare -r CLANG_FORMAT_SHA256="34de32fe53452a07497793d5faf3fd03f7cf8b960b915417471ae81227461a39" + ;; + *) + echo "lint: unsupported architecture $(uname -m)" >&2 + exit 1 + ;; +esac + +# FIX is set by --fix; checks that can rewrite files consult it. +declare FIX=0 + +# fetch downloads a file and verifies its checksum, +# leaving in place only if the checksum matches. +fetch() { + local -r url="$1" want="$2" out="$3" + local -r tmp="$(mktemp "${out}.XXXXXX")" + if ! curl --fail --silent --show-error --location --retry 3 \ + --max-time 300 --output "${tmp}" "${url}"; then + rm -f "${tmp}" + echo "lint: failed to download ${url}" >&2 + return 1 + fi + local got + got="$(sha256sum "${tmp}" | cut -d' ' -f1)" + if [[ "${got}" != "${want}" ]]; then + rm -f "${tmp}" + echo "lint: checksum mismatch for ${url}" >&2 + echo "lint: want ${want}" >&2 + echo "lint: got ${got}" >&2 + return 1 + fi + mv "${tmp}" "${out}" +} + +install_actionlint() { + local -r bin="${CACHE_DIR}/actionlint-${ACTIONLINT_VERSION}" + if [[ ! -x "${bin}" ]]; then + local -r tarball="${CACHE_DIR}/actionlint.tar.gz" + local -r dir="${CACHE_DIR}/actionlint.d" + fetch "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_linux_${ACTIONLINT_ARCH}.tar.gz" \ + "${ACTIONLINT_SHA256}" "${tarball}" + rm -rf "${dir}" && mkdir -p "${dir}" + tar -xzf "${tarball}" -C "${dir}" + mv "${dir}/actionlint" "${bin}" + rm -rf "${dir}" "${tarball}" + fi + echo "${bin}" +} + +install_buildifier() { + local -r bin="${CACHE_DIR}/buildifier-${BUILDIFIER_VERSION}" + if [[ ! -x "${bin}" ]]; then + fetch "https://github.com/bazelbuild/buildtools/releases/download/v${BUILDIFIER_VERSION}/buildifier-linux-${BUILDIFIER_ARCH}" \ + "${BUILDIFIER_SHA256}" "${bin}" + chmod +x "${bin}" + fi + echo "${bin}" +} + +install_codespell() { + local -r dir="${CACHE_DIR}/codespell-${CODESPELL_VERSION}" + if [[ ! -d "${dir}" ]]; then + local -r wheel="${CACHE_DIR}/codespell.whl" + fetch "${CODESPELL_URL}" "${CODESPELL_SHA256}" "${wheel}" + rm -rf "${dir}.tmp" && mkdir -p "${dir}.tmp" + unzip -q "${wheel}" -d "${dir}.tmp" + mv "${dir}.tmp" "${dir}" + rm -f "${wheel}" + fi + echo "${dir}" +} + +install_clang_format() { + local -r bin="${CACHE_DIR}/clang-format-${CLANG_FORMAT_VERSION}" + if [[ ! -x "${bin}" ]]; then + local -r wheel="${CACHE_DIR}/clang-format.whl" + local -r dir="${CACHE_DIR}/clang-format.d" + fetch "${CLANG_FORMAT_URL}" "${CLANG_FORMAT_SHA256}" "${wheel}" + rm -rf "${dir}" && mkdir -p "${dir}" + unzip -q "${wheel}" -d "${dir}" + mv "${dir}/clang_format/data/bin/clang-format" "${bin}" + chmod +x "${bin}" + rm -rf "${dir}" "${wheel}" + fi + echo "${bin}" +} + +find_gofmt() { + if command -v gofmt >/dev/null 2>&1; then + command -v gofmt + return 0 + fi + if command -v go >/dev/null 2>&1; then + local -r candidate="$(go env GOROOT)/bin/gofmt" + if [[ -x "${candidate}" ]]; then + echo "${candidate}" + return 0 + fi + fi + echo "lint: gofmt not found; install Go or put gofmt on PATH" >&2 + return 1 +} + +# Only tracked files, to skip bazel-* symlinks and other build output. +go_files() { git ls-files -z -- '*.go'; } +doc_files() { git ls-files -z -- '*.md' '*.html'; } +cc_files() { git ls-files -z -- '*.c' '*.cc' '*.h'; } +bazel_files() { + git ls-files -z -- 'BUILD' '*/BUILD' '*.bzl' 'WORKSPACE' 'MODULE.bazel' +} + +declare -a FAILED=() +declare -a PASSED=() + +# report records a check result for the final summary. +report() { + if [[ "$2" -eq 0 ]]; then + PASSED+=("$1") + else + FAILED+=("$1") + fi +} + +check_gofmt() { + local gofmt + gofmt="$(find_gofmt)" || return 1 + if [[ "${FIX}" -eq 1 ]]; then + go_files | xargs -0 "${gofmt}" -w -l + return 0 + fi + local unformatted + unformatted="$(go_files | xargs -0 "${gofmt}" -l)" + if [[ -n "${unformatted}" ]]; then + # -d shows what would change; -l alone only names the files. + echo "${unformatted}" | xargs -d '\n' "${gofmt}" -d + echo + echo "Run \`make lint-fix\` to reformat these files." >&2 + return 1 + fi +} + +# The style lives in //.clang-format; clang-format finds it by walking up +# from each file, so no style is passed here. +check_clang_format() { + # Without the config, clang-format silently falls back to LLVM style. + if [[ ! -f "${REPO_DIR}/.clang-format" ]]; then + echo "lint: .clang-format is missing from the repository root" >&2 + return 1 + fi + local clang_format + clang_format="$(install_clang_format)" + # clang-format is single-threaded and each file is independent. + local -r jobs="$(nproc 2>/dev/null || echo 1)" + if [[ "${FIX}" -eq 1 ]]; then + cc_files | xargs -0 -P "${jobs}" -n 32 "${clang_format}" -i + return 0 + fi + # --dry-run reports one diagnostic per hunk; collapse it to a file list. + local warnings status=0 + warnings="$(cc_files | + xargs -0 -P "${jobs}" -n 32 "${clang_format}" --dry-run -Werror 2>&1)" || + status=$? + if [[ "${status}" -ne 0 ]]; then + # -Werror reports these as "error:" rather than "warning:". + local file + while IFS= read -r file; do + [[ -n "${file}" ]] || continue + diff -u --label "${file}" --label "${file} (formatted)" \ + "${file}" <("${clang_format}" "${file}") || true + done < <(printf '%s\n' "${warnings}" | + sed -n 's/^\(.*\):[0-9]\+:[0-9]\+: \(warning\|error\): .*/\1/p' | sort -u) + echo + echo "Run \`make lint-fix\` to reformat these files." >&2 + return 1 + fi +} + +# Formatting only. buildifier --lint reports semantic issues (native rule +# loads, duplicated names) that are out of scope for a formatting check. +check_buildifier() { + local buildifier + buildifier="$(install_buildifier)" + if [[ "${FIX}" -eq 1 ]]; then + bazel_files | xargs -0 "${buildifier}" --mode=fix + return 0 + fi + local unformatted + unformatted="$(bazel_files | xargs -0 "${buildifier}" --mode=check 2>&1 | + sed -n 's/^\(.*\) # reformat$/\1/p')" + if [[ -n "${unformatted}" ]]; then + local file + while IFS= read -r file; do + # -path lets buildifier infer the file type from stdin, so the diff + # matches what --mode=fix would write. + diff -u --label "${file}" --label "${file} (formatted)" \ + "${file}" <("${buildifier}" -path="${file}" < "${file}") || true + done <<< "${unformatted}" + echo + echo "Run \`make lint-fix\` to reformat these files." >&2 + return 1 + fi +} + +check_actions() { + local actionlint + actionlint="$(install_actionlint)" + # Empty values stop actionlint picking up external checkers from PATH. + "${actionlint}" -no-color -oneline -shellcheck= -pyflakes= +} + +check_spelling() { + local codespell_dir + codespell_dir="$(install_codespell)" + # Source is included, so identifiers codespell reads as prose (offsetP, + # FillIn, ...) need entries in tools/.codespellrc. + { doc_files; go_files; cc_files; } | + PYTHONPATH="${codespell_dir}" xargs -0 python3 -m codespell_lib \ + --config "${REPO_DIR}/tools/.codespellrc" +} + +contains() { + local -r needle="$1" + shift + local item + for item in "$@"; do + if [[ "${item}" == "${needle}" ]]; then + return 0 + fi + done + return 1 +} + +run_check() { + local -r name="$1" fn="$2" desc="$3" + echo "==> ${desc}" >&2 + local status=0 + "${fn}" || status=$? + report "${name}" "${status}" +} + +main() { + mkdir -p "${CACHE_DIR}" + + local -a args=() + local arg + for arg in "$@"; do + case "${arg}" in + --fix) FIX=1 ;; + *) args+=("${arg}") ;; + esac + done + + local -a checks=("${args[@]+"${args[@]}"}") + if [[ "${#checks[@]}" -eq 0 ]]; then + checks=("${ALL_CHECKS[@]}") + fi + + local c + for c in "${checks[@]}"; do + if ! contains "${c}" "${ALL_CHECKS[@]}"; then + echo "lint: unknown check '${c}'" >&2 + echo "lint: known checks: ${ALL_CHECKS[*]}" >&2 + exit 1 + fi + done + + if [[ "${FIX}" -eq 1 ]]; then + local -a fixable=() + for c in "${checks[@]}"; do + if contains "${c}" "${FIXABLE_CHECKS[@]}"; then + fixable+=("${c}") + fi + done + checks=("${fixable[@]+"${fixable[@]}"}") + if [[ "${#checks[@]}" -eq 0 ]]; then + echo "lint: --fix applies only to ${FIXABLE_CHECKS[*]}" >&2 + exit 1 + fi + fi + + local check + for check in "${checks[@]}"; do + case "${check}" in + gofmt) run_check gofmt check_gofmt "gofmt" ;; + clang-format) run_check clang-format check_clang_format "clang-format" ;; + buildifier) run_check buildifier check_buildifier "buildifier" ;; + actions) run_check actions check_actions "actionlint" ;; + spelling) run_check spelling check_spelling "codespell" ;; + esac + done + + echo "==> Lint summary" >&2 + local name + for name in "${PASSED[@]+"${PASSED[@]}"}"; do + echo " PASS ${name}" >&2 + done + for name in "${FAILED[@]+"${FAILED[@]}"}"; do + echo " FAIL ${name}" >&2 + done + if [[ "${#FAILED[@]}" -gt 0 ]]; then + echo >&2 + echo "lint: ${#FAILED[@]} check(s) failed." >&2 + exit 1 + fi + echo >&2 + echo "lint: all checks passed." >&2 +} + +main "$@" diff --git a/tools/nogo/check/check.go b/tools/nogo/check/check.go index a534dd5d9ad..e31f869ebe8 100644 --- a/tools/nogo/check/check.go +++ b/tools/nogo/check/check.go @@ -856,7 +856,7 @@ func SplitStdPackages(srcs []string, srcRootPrefix string) (map[string][]string, sources := make(map[string][]string) for _, filename := range srcs { if !strings.HasPrefix(filename, srcRootPrefix) { - continue // Superflouous file. + continue // Superfluous file. } d := path.Dir(filename) if len(srcRootPrefix) >= len(d) { diff --git a/website/cmd/server/main.go b/website/cmd/server/main.go index 11699f805d0..de1b3b447a5 100644 --- a/website/cmd/server/main.go +++ b/website/cmd/server/main.go @@ -200,7 +200,7 @@ func hostRedirectHandler(h http.Handler) http.Handler { }) } -// prefixRedirectHandler returns a handler that redirects to the given formated url. +// prefixRedirectHandler returns a handler that redirects to the given formatted url. func prefixRedirectHandler(prefix string, info prefixInfo) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if p := r.URL.Path; p == prefix { diff --git a/website/cmd/syscalldocs/main.go b/website/cmd/syscalldocs/main.go index 90b8d0295e5..1dfb1ebeb37 100644 --- a/website/cmd/syscalldocs/main.go +++ b/website/cmd/syscalldocs/main.go @@ -31,7 +31,7 @@ import ( // CompatibilityInfo is the collection of all information. type CompatibilityInfo map[string]map[string]ArchInfo -// ArchInfo is compatbility doc for an architecture. +// ArchInfo is compatibility doc for an architecture. type ArchInfo struct { // Syscalls maps syscall number for the architecture to the doc. Syscalls map[uintptr]SyscallDoc `json:"syscalls"`