Commit Graph

50 Commits

Author SHA1 Message Date
Kevin Krakauer 370672e989 prohibit direct use of sync/atomic (u)int64 functions
All atomic 64 bit ints are changed to atomicbitops.(Ui|I)nt64. A nogo checker
enforces that sync/atomic 64 bit functions are not called.

For reviewers: the interesting changes are in the atomicbitops and checkaligned
packages.

Why do this?
- It is very easy to accidentally use atomic values without sync/atomic funcs.
- We have checkatomics, but this is optional and is forgotten in several places.
  - Using a type+checker to enforce this seems less error prone and simpler.
- We get NoCopy protection.
- Use of 64 bit atomics can break 32 bit builds. We have types to handle this
  without any runtime cost, so we might as well use them.

PiperOrigin-RevId: 440473398
2022-04-08 16:06:26 -07:00
Andrei Vagin be49295381 make: set --//tools/nogo:fast by default
nogo:fast is converted to nogo:full with the opposite meaning.
All nogo tests have to be always executed with this option.

Analyzing Go Standard Library takes about 10 minutes on buildkite,
but it is required only to run nogo tests.

PiperOrigin-RevId: 438343203
2022-03-30 10:53:28 -07:00
Michael Pratt 34623f4d75 Skip analysis of sync/atomic
https://go.dev/issue/50860 is adding Pointer[T] to sync/atomic,
which will trip up analyzers that don't handle generics. Skip
it for now.

Drop constraints, maps, slices, as they were dropped from the
standard library.

PiperOrigin-RevId: 437808952
2022-03-28 11:25:37 -07:00
Adin Scannell 6c2d9a2359 Allow disabling nogo stdlib facts.
Rebuilding the set of standard library facts can be time consuming. Allow this
to be disabled for faster iteration. This is done by provided a build setting
which can be toggled directly, for example:

bazel build --//tools/nogo:fast ...

PiperOrigin-RevId: 426562548
2022-02-04 22:41:23 -08:00
Adin Scannell a87bb4aae2 Ensure that nogo is enabled.
A recent change stopped using the correct file (the export data, not the
archive) and checklocks started failing. Unfortunately, this was suppressed,
since the filter command was not failing with findings.

This change fixes that problem and adds a test to ensure that this cannot
happen again. If nogo starts failing to identify problems, the sanity_test in
nogo/sanity will also start to fail.

This change also requires updating the WORKSPACE to the latest rules_go and
Go version, in order to pick up the fixed go_tools. The latest rules_go in
turn required an updated bazel, which in turn required a minor change in the
coverdata implementation.

Fixing the fact propagation brought forward a number of problems with caching
for bazel workers. Its unclear whether this was a core worker issue or whether
some caching was broken, but the situation was basically undebugable. Instead,
the way facts are stored and loaded is optimized to be able to remove the use
of workers altogether and ideally make nogo debuggable.

PiperOrigin-RevId: 426327186
2022-02-03 23:45:40 -08:00
Adin Scannell c18ec0b53c Fix race build error.
This adds a test to smoke-tests to ensure that the race build does not
break again. In debugging this issue, a race in the nogo tool itself
was discovered, and a related fix is included.

PiperOrigin-RevId: 424393624
2022-01-26 11:08:21 -08:00
Adin Scannell b92bb28e6a Fix release tags generation.
PiperOrigin-RevId: 424151576
2022-01-25 12:35:46 -08:00
Adin Scannell 0e492a2b5e Refactor nogo and provide facts render.
This change makes the core nogo package less of a "catch all", and splits
functionality into multiple packages. Instead of separate binaries for each
function, a single "cli" package is added with subcommands, and the core
starlark wrappers are also refactored to minimize redundancy.

The new "cli" package also adds support for a "render" command, which
allows factors to be rendered via a Go text template. This is useful for
debugging, but also allows code generation to be updated to use this
mechanism. This eliminates the use of a QEMU wrapper for the older
arch_genrule, and allows the use of a native bazel transition to extract
facts for the appropriate generated file. In other words, the correct facts
will be rendered for generating XXX_arm64.s, even on amd64.

PiperOrigin-RevId: 422846459
2022-01-19 10:26:27 -08:00
Michael Pratt c7e5b4bd67 Add hook to add addition build tags
PiperOrigin-RevId: 404025736
2021-10-18 12:16:53 -07:00
Michael Pratt c122663548 Skip analysis of standard library packages using generics
The upstream analysis packages we depend on do not yet support analysis of code
using Go 1.18 type parameter features, making analysis of the Go tip standard
library choke and crash. Skip these packages for now.

PiperOrigin-RevId: 400030256
2021-09-30 14:49:19 -07:00
Michael Pratt e0bf522502 Declare default outputs from nogo_stdlib
nogo_stdlib propogate facts and findings to downstream nogo_aspects via
NogoStdlibInfo. This all works fine except one case: directly building a
nogo_stdlib. e.g., bazel build //tools/nogo:stdlib.

In this case, nothing is requesting the NogoStdlibInfo, and thus the target has
nothing to do. This can be rather confusing when trying to debug failures in
:stdlib, as building :stdlib does nothing.

Fix this by declaring the facts and findings as default outputs from
nogo_stdlib. Now direct bazel build will request these outputs and actually
trigger the analysis. Standard aspect builds are unaffected.

PiperOrigin-RevId: 391580126
2021-08-18 12:10:09 -07:00
gVisor bot ebf76b30cb Internal change.
PiperOrigin-RevId: 391331401
2021-08-17 11:05:59 -07:00
Michael Pratt 62ea5c0a22 checklinkname: rudimentary type-checking of linkname directives
This CL introduces a 'checklinkname' analyzer, which provides rudimentary
type-checking that verifies that function signatures on the local and remote
sides of //go:linkname directives match expected values.

If the Go standard library changes the definitions of any of these function,
checklinkname will flag the change as a finding, providing an error informing
the gVisor team to adapt to the upstream changes. This allows us to eliminate
the majority of gVisor's forward-looking negative build tags, as we can catch
mismatches in testing [1].

The remaining forward-looking negative build tags are covering shared struct
definitions, which I hope to add to checklinkname in a future CL.

[1] Of course, semantics/requirements can change without the signature
changing, so we still must be careful, but this covers the common case.

PiperOrigin-RevId: 387873847
2021-07-30 13:42:15 -07:00
Michael Pratt a42d3fd0ae Fix per-analyzer overrides of default-disabled groups
Currently behavior of config groups with `default: false` is buggy. The
intention is that adding an empty suppression section for that group to a
specific analyzer config should enable reporting for that analyzer. i.e.,

```
groups:
  - name: foo
    regex: "^foo/"
    default: false
global:
  ...
analyzers:
  asmdecl:
    foo: # Enabled.
```

This should enable the foo group only for asmdecl. Unfortunately, today the
actual behavior depends on the contents of the `global:` section. If `global:`
contains an entry for foo, then it will work as described. If `global:` does
_not_ contain an entry for foo, then the group default (disabled) always
applies and the individual analyzer options have no effect.

The cause of this is confusion in `AnalyzerConfig.shouldReport`, which doesn't
distinguish between explicit suppression via a global suppression/exclude and
simply having no configuration at all. Make this more explicit, so that the no
configuration case can continue to per-analyzer configuration before falling
back to the group default.

The last test case in the added test fails without this change.

This re-enables several opted-in analyzers for external dependencies, which
have gained a few more false positives to suppress.

PiperOrigin-RevId: 386904725
2021-07-26 10:26:43 -07:00
Jamie Liu 1ad3822200 Add go:build directives as required by Go 1.17's gofmt.
PiperOrigin-RevId: 385894869
2021-07-20 16:28:45 -07:00
Adin Scannell 16b751b6c6 Mix checklocks and atomic analyzers.
This change makes the checklocks analyzer considerable more powerful, adding:
* The ability to traverse complex structures, e.g. to have multiple nested
  fields as part of the annotation.
* The ability to resolve simple anonymous functions and closures, and perform
  lock analysis across these invocations. This does not apply to closures that
  are passed elsewhere, since it is not possible to know the context in which
  they might be invoked.
* The ability to annotate return values in addition to receivers and other
  parameters, with the same complex structures noted above.
* Ignoring locking semantics for "fresh" objects, i.e. objects that are
  allocated in the local frame (typically a new-style function).
* Sanity checking of locking state across block transitions and returns, to
  ensure that no unexpected locks are held.

Note that initially, most of these findings are excluded by a comprehensive
nogo.yaml. The findings that are included are fundamental lock violations.
The changes here should be relatively low risk, minor refactorings to either
include necessary annotations to simplify the code structure (in general
removing closures in favor of methods) so that the analyzer can be easily
track the lock state.

This change additional includes two changes to nogo itself:
* Sanity checking of all types to ensure that the binary and ast-derived
  types have a consistent objectpath, to prevent the bug above from occurring
  silently (and causing much confusion). This also requires a trick in
  order to ensure that serialized facts are consumable downstream. This can
  be removed with https://go-review.googlesource.com/c/tools/+/331789 merged.
* A minor refactoring to isolation the objdump settings in its own package.
  This was originally used to implement the sanity check above, but this
  information is now being passed another way. The minor refactor is preserved
  however, since it cleans up the code slightly and is minimal risk.

PiperOrigin-RevId: 382613300
2021-07-01 15:07:56 -07:00
Adin Scannell 5b7b7daa42 nogo: enable bazel workers and other optimizations.
This is a suite of changes intended to dramatically speed up nogo speed.

First, there are minor changes that help efficiency significantly.

* Gob-based encoding is used internally, and JSON only used for the final
  set of findings. This is done to preserve the existing format (which is
  consumed by external tooling), and to facilitate manual debugging.

* Unnecessary regex compilation is elided in the configuration, and care is
  taken for merges to prevent redundant entries. I'm not sure quite sure how,
  but it turns out that this was consumed a significant amount of time,
  presumably compiling the same regexes over and over again.

Second, this change enables bazel workers for nogo analyzers.

Workers enable persistent processes instead of creating and tearing down a
sandbox every invocation. A library is introduced to abstraction these details,
and allow the tools to still be written using standard flags, etc.

The key here is that these binaries and the core of nogo become aware of
caches with worker.Cache. This allows us to save significant time loading the
same set of files and findings over and over again. These caches are keyed by
the digests that are provided by bazel, and are capped in overall size.

Note that the worker package attempts to capture output during each run, but
tools are no longer permitted to write to stdout. This necessitated dropping
some spurious output from checklocks.

PiperOrigin-RevId: 370505732
2021-04-26 11:42:49 -07:00
Adin Scannell f373f67048 Improve nogo action cache-ability.
Presently, the standard library facts are not serialized in a deterministic
order. This means that they have the possibility to change on each iteration,
requiring a large scale re-analysis of all downstream actions, which includes
all packages.

Improve cache-ability of nogo actions by improving the determinism of the both
facts and findings. Internally, default facts should be serialized as a sorted
list for this reason already.

PiperOrigin-RevId: 370188259
2021-04-23 17:33:32 -07:00
Adin Scannell 8192cccda6 Clean test tags.
PiperOrigin-RevId: 369505182
2021-04-20 13:11:25 -07:00
Adin Scannell 5ac79e1545 Drop unused escapes information.
PiperOrigin-RevId: 367517305
2021-04-08 15:19:02 -07:00
gVisor bot a0c1674478 Internal change.
PiperOrigin-RevId: 366555466
2021-04-02 20:02:26 -07:00
Bhasker Hariharan 3e69f5d088 Add checklocks analyzer.
This validates that struct fields if annotated with "// checklocks:mu" where
"mu" is a mutex field in the same struct then access to the field is only
done with "mu" locked.

All types that are guarded by a mutex must be annotated with

// +checklocks:<mutex field name>

For more details please refer to README.md.

PiperOrigin-RevId: 360729328
2021-03-03 12:24:21 -08:00
Adin Scannell 3817c7349d Remove go_tool_library references.
This is required only for the built-in bazel nogo functionality.
Since we roll these targets manually via the wrappers, we don't need
to use go_tool_library. The inconsistent use of these targets leads
to conflicting instantiations of go_default_library and go_tool_library,
which both contain the same output files.

PiperOrigin-RevId: 355184975
2021-02-02 09:37:09 -08:00
Adin Scannell 2a5d3c248f Add YAML validation for configuration files.
For validation, the "on" key in existing YAML files is changed to a literal
string. In the YAML spec, on is a keyword which encodes a boolean value, so
without relying on a specific implementation the YAML files are technically
not encoding an object that complies with the specification.

PiperOrigin-RevId: 350172147
2021-01-05 10:43:04 -08:00
Adin Scannell 4cba3904f4 Remove existing nogo exceptions.
PiperOrigin-RevId: 347047550
2020-12-11 12:06:49 -08:00
Adin Scannell b4b42a5fce Traversal embedded libraries, even for go_library rules.
PiperOrigin-RevId: 339570821
2020-10-28 17:28:03 -07:00
Adin Scannell 7926a9e28d Add nogo configuration.
This splits the nogo rules into a separate configuration yaml file, and
allows for multiple files to be provided.

Because attrs cannot be passed down to aspects, this required that all
findings are propagated up the aspect Provider. This doesn't mean that
any extra work must be done, just that this information must be carried
through the graph, and some additional starlark complexity is required.

PiperOrigin-RevId: 339076357
2020-10-26 11:11:46 -07:00
Ting-Yu Wang 8dfbec28a4 Fix nogo tests in //pkg/sentry/socket/...
PiperOrigin-RevId: 338784921
2020-10-23 19:24:09 -07:00
Jamie Liu 227fd9f1b0 //pkg/state fixes for VFS2.
- When encodeState.resolve() determines that the resolved reflect.Value is
  contained by a previously-resolved object, set wire.Ref.Type to the
  containing object's type (existing.obj.Type()) rather than the contained
  value's type (obj.Type()).

- When encodeState.resolve() determines that the resolved reflect.Value
  contains a previously-resolved object, handle cases where the new object
  contains *multiple* previously-resolved objects. (This may cause
  previously-allocated object IDs to become unused; to facilitate this, change
  encodeState.pending to a map, and change the wire format to prefix each
  object with its object ID.)

- Add encodeState.encodedStructs to avoid redundant encoding of structs, since
  deduplication of objects via encodeState.resolve() doesn't work for objects
  instantiated by StateSave() and passed to SaveValue() (i.e. fields tagged
  `state:".(whatever)"`).

- Make unexported array fields deserializable via slices that refer to them by
  casting away their unexportedness in decodeState.decodeObject().

Updates #1663

PiperOrigin-RevId: 338727687
2020-10-23 12:53:20 -07:00
Dean Deng 9ca66ec598 Rewrite reference leak checker without finalizers.
Our current reference leak checker uses finalizers to verify whether an object
has reached zero references before it is garbage collected. There are multiple
problems with this mechanism, so a rewrite is in order.

With finalizers, there is no way to guarantee that a finalizer will run before
the program exits. When an unreachable object with a finalizer is garbage
collected, its finalizer will be added to a queue and run asynchronously. The
best we can do is run garbage collection upon sandbox exit to make sure that
all finalizers are enqueued.

Furthermore, if there is a chain of finalized objects, e.g. A points to B
points to C, garbage collection needs to run multiple times before all of the
finalizers are enqueued. The first GC run will register the finalizer for A but
not free it. It takes another GC run to free A, at which point B's finalizer
can be registered. As a result, we need to run GC as many times as the length
of the longest such chain to have a somewhat reliable leak checker.

Finally, a cyclical chain of structs pointing to one another will never be
garbage collected if a finalizer is set. This is a well-known issue with Go
finalizers (https://github.com/golang/go/issues/7358). Using leak checking on
filesystem objects that produce cycles will not work and even result in memory
leaks.

The new leak checker stores reference counted objects in a global map when
leak check is enabled and removes them once they are destroyed. At sandbox
exit, any remaining objects in the map are considered as leaked. This provides
a deterministic way of detecting leaks without relying on the complexities of
finalizers and garbage collection.

This approach has several benefits over the former, including:
- Always detects leaks of objects that should be destroyed very close to
  sandbox exit. The old checker very rarely detected these leaks, because it
  relied on garbage collection to be run in a short window of time.
- Panics if we forgot to enable leak check on a ref-counted object (we will try
  to remove it from the map when it is destroyed, but it will never have been
  added).
- Can store extra logging information in the map values without adding to the
  size of the ref count struct itself. With the size of just an int64, the ref
  count object remains compact, meaning frequent operations like IncRef/DecRef
  are more cache-efficient.
- Can aggregate leak results in a single report after the sandbox exits.
  Instead of having warnings littered in the log, which were
  non-deterministically triggered by garbage collection, we can print all
  warning messages at once. Note that this could also be a limitation--the
  sandbox must exit properly for leaks to be detected.

Some basic benchmarking indicates that this change does not significantly
affect performance when leak checking is enabled, which is understandable
since registering/unregistering is only done once for each filesystem object.

Updates #1486.

PiperOrigin-RevId: 338685972
2020-10-23 09:17:02 -07:00
Ting-Yu Wang 16ba350314 Fix nogo test in //pkg/tcpip/...
PiperOrigin-RevId: 338168977
2020-10-20 17:22:28 -07:00
Adin Scannell 54e989ec3a Remove legacy bazel configurations.
Using the newer bazel rules necessitates a transition from proto1 to
proto2. In order to resolve the incompatibility between proto2 and
gogoproto, the cri runtimeoptions proto must be vendored.

Further, some of the semantics of bazel caching changed during the
transition. It is now necessary to:

- Ensure that :gopath depends only on pure library targets, as the
  propagation of go_binary build attributes (pure, static) will
  affected the generated files (though content remains the same,
  there are conflicts with respect to the gopath).
- Update bazel.mk to include the possibility of binaries in the
  bazel-out directory, as it will now put runsc and others there.
  This required some refinements to the mechanism of extracting
  paths, since some the existing regex resulted in false positives.
- Change nogo rules to prevent escape generation on binary targets.
  For some reason, the newer version of bazel attempted to run the
  nogo analysis on the binary targets, which fails due to the fact
  that objdump does not work on the final binary. This must be due
  to a change in the semantics of aspects in bazel3.

PiperOrigin-RevId: 337958324
2020-10-19 16:28:40 -07:00
Adin Scannell 9a3d8973c4 Refactor shared starlark files.
PiperOrigin-RevId: 337581114
2020-10-16 14:44:03 -07:00
Adin Scannell b0da31b921 Refactor nogo to better support ARM.
PiperOrigin-RevId: 337544107
2020-10-16 11:26:58 -07:00
Adin Scannell 14a003c60f Cache errors when processing stdlib with nogo.
PiperOrigin-RevId: 337515664
2020-10-16 09:05:18 -07:00
Adin Scannell 6229be5e48 Minor nogo restructuring.
PiperOrigin-RevId: 336343819
2020-10-09 12:33:44 -07:00
Adin Scannell 5124ce579d Minor nogo cleanup.
PiperOrigin-RevId: 336126583
2020-10-08 11:24:21 -07:00
Adin Scannell a55bd73d48 Add staticcheck and staticstyle analyzers.
This change also adds support to go_stateify for detecting an appropriate
receiver name, avoiding a large number of false positives.

PiperOrigin-RevId: 335994587
2020-10-07 18:29:05 -07:00
Adin Scannell 994c90e2d2 Add nogo check annotations to GitHub.
When nogo checks are violated, they will automatically posted
as annotations on the specific GitHub commit. This allows us
to ensure analysis & style rules and have them called out.

PiperOrigin-RevId: 334447285
2020-09-29 13:16:54 -07:00
Michael Pratt 490e5c83bd Make nogo more robust to variety of stdlib layouts.
PiperOrigin-RevId: 331206424
2020-09-11 13:07:30 -07:00
Adin Scannell 101c97d6f8 Change nogo failures to test failures, instead of build failures.
PiperOrigin-RevId: 329408633
2020-08-31 17:09:20 -07:00
Adin Scannell 983a55aa06 Support stdlib analyzers with nogo.
This immediately revealed an escape analysis violation (!), where
the sync.Map was being used in a context that escapes were not
allowed. This is a relatively minor fix and is included.

PiperOrigin-RevId: 328611237
2020-08-26 14:42:35 -07:00
Adin Scannell b0c53f8475 Add nogo support to go_binary and go_test targets.
Updates #3374

PiperOrigin-RevId: 328378700
2020-08-25 12:18:25 -07:00
Adin Scannell 90021e775a Add bzl_library rules for .bzl files without one.
PiperOrigin-RevId: 325280924
2020-08-06 12:10:49 -07:00
Michael Pratt 14839e027f Internal change
PiperOrigin-RevId: 322788791
2020-07-23 08:14:26 -07:00
gVisor bot c81ac8ec3b Merge pull request #2672 from amscanne:shim-integrated
PiperOrigin-RevId: 321053634
2020-07-13 16:10:58 -07:00
Michael Pratt 3970c12743 Remove various uses of 'whitelist'
Updates #2972

PiperOrigin-RevId: 317113059
2020-06-18 09:03:39 -07:00
Michael Pratt 6d806ee719 Remove various uses of 'blacklist'
Updates #2972

PiperOrigin-RevId: 316942245
2020-06-17 12:34:33 -07:00
Andrei Vagin 0c586946ea Specify a memory file in platform.New().
PiperOrigin-RevId: 307941984
2020-04-22 17:50:10 -07:00
Adin Scannell c615aafa21 Add internal nogo analysis & checkescape tool.
See tools/nogo/README.md.

The checkescape tool is able to perform recursive escape analysis, using the
actual generated binary to confirm the results produced by the compiler itself.

As an initial use case, this replaces the manual escape analysis tests used for
go_marshal, and validates that the CopyIn and CopyOut paths will not require
any allocation or stack splits.

Updates #2243

PiperOrigin-RevId: 307532986
2020-04-20 20:58:20 -07:00