diff options
39 files changed, 93 insertions, 296 deletions
diff --git a/dashboard/app/admin.go b/dashboard/app/admin.go index 3b9fac8a1..9ff871776 100644 --- a/dashboard/app/admin.go +++ b/dashboard/app/admin.go @@ -131,10 +131,7 @@ func dropEntities(c context.Context, keys []*db.Key, dryRun bool) error { return nil } for len(keys) != 0 { - batch := 100 - if batch > len(keys) { - batch = len(keys) - } + batch := min(len(keys), 100) if err := db.DeleteMulti(c, keys[:batch]); err != nil { return err } @@ -383,10 +380,7 @@ func updateHeadReproLevel(c context.Context, w http.ResponseWriter, r *http.Requ func updateBatch[T any](c context.Context, keys []*db.Key, transform func(key *db.Key, item *T)) error { for len(keys) != 0 { - batchSize := 20 - if batchSize > len(keys) { - batchSize = len(keys) - } + batchSize := min(len(keys), 20) batchKeys := keys[:batchSize] keys = keys[batchSize:] diff --git a/dashboard/app/api.go b/dashboard/app/api.go index 13a349431..b06c5ac07 100644 --- a/dashboard/app/api.go +++ b/dashboard/app/api.go @@ -906,12 +906,8 @@ func reportCrash(c context.Context, build *Build, req *dashapi.Crash) (*Bug, err bug.NumRepro++ bug.LastReproTime = now } - if bug.ReproLevel < reproLevel { - bug.ReproLevel = reproLevel - } - if bug.HeadReproLevel < reproLevel { - bug.HeadReproLevel = reproLevel - } + bug.ReproLevel = max(bug.ReproLevel, reproLevel) + bug.HeadReproLevel = max(bug.HeadReproLevel, reproLevel) if len(req.Report) != 0 { bug.HasReport = true } @@ -1231,28 +1227,16 @@ func apiManagerStats(c context.Context, ns string, payload io.Reader) (interface mgr.Link = req.Addr mgr.LastAlive = now mgr.CurrentUpTime = req.UpTime - if cur := int64(req.Corpus); cur > stats.MaxCorpus { - stats.MaxCorpus = cur - } - if cur := int64(req.PCs); cur > stats.MaxPCs { - stats.MaxPCs = cur - } - if cur := int64(req.Cover); cur > stats.MaxCover { - stats.MaxCover = cur - } - if cur := int64(req.CrashTypes); cur > stats.CrashTypes { - stats.CrashTypes = cur - } + stats.MaxCorpus = max(stats.MaxCorpus, int64(req.Corpus)) + stats.MaxPCs = max(stats.MaxPCs, int64(req.PCs)) + stats.MaxCover = max(stats.MaxCover, int64(req.Cover)) + stats.CrashTypes = max(stats.CrashTypes, int64(req.CrashTypes)) stats.TotalFuzzingTime += req.FuzzingTime stats.TotalCrashes += int64(req.Crashes) stats.SuppressedCrashes += int64(req.SuppressedCrashes) stats.TotalExecs += int64(req.Execs) - if cur := int64(req.TriagedCoverage); cur > stats.TriagedCoverage { - stats.TriagedCoverage = cur - } - if cur := int64(req.TriagedPCs); cur > stats.TriagedPCs { - stats.TriagedPCs = cur - } + stats.TriagedCoverage = max(stats.TriagedCoverage, int64(req.TriagedCoverage)) + stats.TriagedPCs = max(stats.TriagedPCs, int64(req.TriagedPCs)) return nil }) return nil, err diff --git a/dashboard/app/graphs.go b/dashboard/app/graphs.go index 32ee9aaf2..9ba5d6313 100644 --- a/dashboard/app/graphs.go +++ b/dashboard/app/graphs.go @@ -295,13 +295,8 @@ func createBugsGraph(c context.Context, bugs []*Bug) *uiGraph { m := make(map[int]*BugStats) maxWeek := 0 bugStatsFor := func(t time.Time) *BugStats { - week := int(now.Sub(t) / (30 * 24 * time.Hour)) - if week < 0 { - week = 0 - } - if maxWeek < week { - maxWeek = week - } + week := max(0, int(now.Sub(t)/(30*24*time.Hour))) + maxWeek = max(maxWeek, week) bs := m[week] if bs == nil { bs = new(BugStats) @@ -564,22 +559,19 @@ func createManagersGraph(c context.Context, ns string, selManagers, selMetrics [ // comparable across different managers. if len(selMetrics) > 1 { for metricIndex := range selMetrics { - max := float32(1) + maxVal := float32(1) for col := range graph.Columns { for mgrIndex := range selManagers { item := graph.Columns[col].Vals[mgrIndex*len(selMetrics)+metricIndex] if item.IsNull { continue } - val := item.Val - if max < val { - max = val - } + maxVal = max(maxVal, item.Val) } } for col := range graph.Columns { for mgrIndex := range selManagers { - graph.Columns[col].Vals[mgrIndex*len(selMetrics)+metricIndex].Val /= max * 100 + graph.Columns[col].Vals[mgrIndex*len(selMetrics)+metricIndex].Val /= maxVal * 100 } } } diff --git a/dashboard/app/main.go b/dashboard/app/main.go index 4dc3755cf..d765c8df9 100644 --- a/dashboard/app/main.go +++ b/dashboard/app/main.go @@ -1991,9 +1991,7 @@ func mergeUIBug(c context.Context, bug *uiBug, dup *Bug) { if bug.LastTime.Before(dup.LastTime) { bug.LastTime = dup.LastTime } - if bug.ReproLevel < dup.ReproLevel { - bug.ReproLevel = dup.ReproLevel - } + bug.ReproLevel = max(bug.ReproLevel, dup.ReproLevel) updateBugBadness(c, bug) } diff --git a/dashboard/app/reporting.go b/dashboard/app/reporting.go index e8355acab..9601d2718 100644 --- a/dashboard/app/reporting.go +++ b/dashboard/app/reporting.go @@ -366,20 +366,16 @@ func (bug *Bug) obsoletePeriod(c context.Context) time.Duration { days = days * 3 period = time.Hour * time.Duration(24*days) } - min, max := config.Obsoleting.MinPeriod, config.Obsoleting.MaxPeriod + minVal, maxVal := config.Obsoleting.MinPeriod, config.Obsoleting.MaxPeriod if config.Obsoleting.NonFinalMinPeriod != 0 && bug.Reporting[len(bug.Reporting)-1].Reported.IsZero() { - min, max = config.Obsoleting.NonFinalMinPeriod, config.Obsoleting.NonFinalMaxPeriod + minVal, maxVal = config.Obsoleting.NonFinalMinPeriod, config.Obsoleting.NonFinalMaxPeriod } if mgr := bug.managerConfig(c); mgr != nil && mgr.ObsoletingMinPeriod != 0 { - min, max = mgr.ObsoletingMinPeriod, mgr.ObsoletingMaxPeriod - } - if period < min { - period = min - } - if period > max { - period = max + minVal, maxVal = mgr.ObsoletingMinPeriod, mgr.ObsoletingMaxPeriod } + period = max(period, minVal) + period = min(period, maxVal) return period } @@ -1042,9 +1038,7 @@ func incomingCommandUpdate(c context.Context, now time.Time, cmd *dashapi.BugUpd merged := email.MergeEmailLists(strings.Split(bugReporting.CC, "|"), cmd.CC) bugReporting.CC = strings.Join(merged, "|") } - if bugReporting.ReproLevel < cmd.ReproLevel { - bugReporting.ReproLevel = cmd.ReproLevel - } + bugReporting.ReproLevel = max(bugReporting.ReproLevel, cmd.ReproLevel) if bug.Status != BugStatusDup { bug.DupOf = "" } diff --git a/dashboard/app/reporting_lists.go b/dashboard/app/reporting_lists.go index 473c24433..33e0c208d 100644 --- a/dashboard/app/reporting_lists.go +++ b/dashboard/app/reporting_lists.go @@ -289,9 +289,7 @@ func querySubsystemReport(c context.Context, subsystem *Subsystem, reporting *Re if takeNoRepro+len(withRepro) < config.BugsInReport { takeNoRepro = config.BugsInReport - len(withRepro) } - if takeNoRepro > len(noRepro) { - takeNoRepro = len(noRepro) - } + takeNoRepro = min(takeNoRepro, len(noRepro)) sort.Slice(noRepro, func(i, j int) bool { return noRepro[i].NumCrashes > noRepro[j].NumCrashes }) diff --git a/dashboard/app/stats.go b/dashboard/app/stats.go index b920f7821..f206895e5 100644 --- a/dashboard/app/stats.go +++ b/dashboard/app/stats.go @@ -102,10 +102,7 @@ func allBugInputs(c context.Context, ns string) ([]*bugInput, error) { func getAllMulti[T any](c context.Context, keys []*db.Key, objects []*T) (*db.Key, error) { const step = 1000 for from := 0; from < len(keys); from += step { - to := from + step - if to > len(keys) { - to = len(keys) - } + to := min(from+step, len(keys)) err := db.GetMulti(c, keys[from:to], objects[from:to]) if err == nil { continue diff --git a/pkg/ast/format.go b/pkg/ast/format.go index b16a62531..3e143596a 100644 --- a/pkg/ast/format.go +++ b/pkg/ast/format.go @@ -138,9 +138,7 @@ func (n *Struct) serialize(w io.Writer) { maxTabs := 0 for _, f := range n.Fields { tabs := (len(f.Name.Name) + tabWidth) / tabWidth - if maxTabs < tabs { - maxTabs = tabs - } + maxTabs = max(maxTabs, tabs) } for _, f := range n.Fields { if f.NewBlock { diff --git a/pkg/bisect/bisect.go b/pkg/bisect/bisect.go index 73a1971c8..ba022e514 100644 --- a/pkg/bisect/bisect.go +++ b/pkg/bisect/bisect.go @@ -928,9 +928,7 @@ func (env *env) postTestResult(res *testResult) { // Let's be conservative and only decrease our reproduction likelihood estimate. // As the estimate of each test() can also be flaky, only partially update the result. avg := (env.reproChance + res.badRatio) / 2.0 - if env.reproChance > avg { - env.reproChance = avg - } + env.reproChance = min(env.reproChance, avg) } } @@ -1086,7 +1084,7 @@ func pickReleaseTags(all []string) []string { } var ret []string // Take 2 latest sub releases. - takeSubReleases := minInts(2, len(subReleases)) + takeSubReleases := min(2, len(subReleases)) ret = append(ret, subReleases[:takeSubReleases]...) // If there are a lot of sub releases, also take the middle one. if len(subReleases) > 5 { @@ -1107,13 +1105,3 @@ func pickReleaseTags(all []string) []string { } return ret } - -func minInts(vals ...int) int { - ret := vals[0] - for i := 1; i < len(vals); i++ { - if vals[i] < ret { - ret = vals[i] - } - } - return ret -} diff --git a/pkg/bisect/minimize/slice.go b/pkg/bisect/minimize/slice.go index fee125542..d5fbc6c6a 100644 --- a/pkg/bisect/minimize/slice.go +++ b/pkg/bisect/minimize/slice.go @@ -257,10 +257,7 @@ func splitChunk[T any](chunk []T, parts int) [][]T { } var ret [][]T for i := 0; i < len(chunk); i += chunkSize { - end := i + chunkSize - if end > len(chunk) { - end = len(chunk) - } + end := min(i+chunkSize, len(chunk)) ret = append(ret, chunk[i:end]) } return ret diff --git a/pkg/compiler/gen.go b/pkg/compiler/gen.go index fb406b815..81e8f83bc 100644 --- a/pkg/compiler/gen.go +++ b/pkg/compiler/gen.go @@ -284,9 +284,7 @@ func (comp *compiler) layoutUnion(t *prog.UnionType) { " which is less than field %v size %v", structNode.Name.Name, sizeAttr, fld.Type.Name(), sz) } - if t.TypeSize < sz { - t.TypeSize = sz - } + t.TypeSize = max(t.TypeSize, sz) } if hasSize { t.TypeSize = sizeAttr @@ -313,9 +311,7 @@ func (comp *compiler) layoutStruct(t *prog.StructType) { size = 0 } size += f.Size() - if t.TypeSize < size { - t.TypeSize = size - } + t.TypeSize = max(t.TypeSize, size) } sizeAttr, hasSize := attrs[attrSize] if hasSize { @@ -348,9 +344,7 @@ func (comp *compiler) layoutStructFields(t *prog.StructType, varlen, packed bool fieldAlign := uint64(1) if !packed { fieldAlign = f.Alignment() - if structAlign < fieldAlign { - structAlign = fieldAlign - } + structAlign = max(structAlign, fieldAlign) } fullBitOffset := byteOffset*8 + bitOffset var fieldOffset uint64 diff --git a/pkg/compiler/types.go b/pkg/compiler/types.go index 906af199c..ae0864725 100644 --- a/pkg/compiler/types.go +++ b/pkg/compiler/types.go @@ -1007,9 +1007,7 @@ func init() { case *prog.UnionType: typ1.Fields = fields for _, f := range fields { - if a := f.Type.Alignment(); typ1.TypeAlign < a { - typ1.TypeAlign = a - } + typ1.TypeAlign = max(typ1.TypeAlign, f.Type.Alignment()) } case *prog.StructType: typ1.Fields = fields @@ -1028,10 +1026,7 @@ func init() { typ1.TypeAlign = 1 } else { for _, f := range fields { - a := f.Type.Alignment() - if typ1.TypeAlign < a { - typ1.TypeAlign = a - } + typ1.TypeAlign = max(typ1.TypeAlign, f.Type.Alignment()) } } } diff --git a/pkg/cover/backend/dwarf.go b/pkg/cover/backend/dwarf.go index 375a82dcc..eeb924a4b 100644 --- a/pkg/cover/backend/dwarf.go +++ b/pkg/cover/backend/dwarf.go @@ -405,21 +405,14 @@ func readTextRanges(debugInfo *dwarf.Data, module *vminfo.KernelModule, pcFix pc func symbolizeModule(target *targets.Target, interner *symbolizer.Interner, objDir, srcDir, buildDir string, splitBuildDelimiters []string, mod *vminfo.KernelModule, pcs []uint64) ([]Frame, error) { - procs := runtime.GOMAXPROCS(0) / 2 - if need := len(pcs) / 1000; procs > need { - procs = need - } + procs := min(runtime.GOMAXPROCS(0)/2, len(pcs)/1000) const ( minProcs = 1 maxProcs = 4 ) // addr2line on a beefy vmlinux takes up to 1.6GB of RAM, so don't create too many of them. - if procs > maxProcs { - procs = maxProcs - } - if procs < minProcs { - procs = minProcs - } + procs = min(procs, maxProcs) + procs = max(procs, minProcs) type symbolizerResult struct { frames []symbolizer.Frame err error @@ -449,10 +442,7 @@ func symbolizeModule(target *targets.Target, interner *symbolizer.Interner, objD }() } for i := 0; i < len(pcs); { - end := i + 100 - if end > len(pcs) { - end = len(pcs) - } + end := min(i+100, len(pcs)) pcchan <- pcs[i:end] i = end } diff --git a/pkg/cover/html.go b/pkg/cover/html.go index ba38cd884..2c8a1281e 100644 --- a/pkg/cover/html.go +++ b/pkg/cover/html.go @@ -160,10 +160,7 @@ func fileLineContents(file *file, lines [][]byte) lineCoverExport { start := 0 cover := append(lineCover[i+1], lineCoverChunk{End: backend.LineEnd}) for _, cov := range cover { - end := cov.End - 1 - if end > len(ln) { - end = len(ln) - } + end := min(cov.End-1, len(ln)) if end == start { continue } @@ -661,10 +658,7 @@ func fileContents(file *file, lines [][]byte, haveProgs bool) string { start := 0 cover := append(lineCover[i+1], lineCoverChunk{End: backend.LineEnd}) for _, cov := range cover { - end := cov.End - 1 - if end > len(ln) { - end = len(ln) - } + end := min(cov.End-1, len(ln)) if end == start { continue } @@ -708,9 +702,7 @@ func perLineCoverage(covered, uncovered []backend.Range) map[int][]lineCoverChun func mergeRange(lines map[int][]lineCoverChunk, r backend.Range, covered bool) { // Don't panic on broken debug info, it is frequently broken. - if r.EndLine < r.StartLine { - r.EndLine = r.StartLine - } + r.EndLine = max(r.EndLine, r.StartLine) if r.EndLine == r.StartLine && r.EndCol <= r.StartCol { r.EndCol = backend.LineEnd } @@ -750,10 +742,7 @@ func mergeLine(chunks []lineCoverChunk, start, end int, covered bool) []lineCove if chunkStart < start { res = append(res, lineCoverChunk{start, chunk.Covered, chunk.Uncovered}) } - mid := end - if mid > chunk.End { - mid = chunk.End - } + mid := min(end, chunk.End) res = append(res, lineCoverChunk{mid, chunk.Covered || covered, chunk.Uncovered || !covered}) if chunk.End > end { res = append(res, lineCoverChunk{chunk.End, chunk.Covered, chunk.Uncovered}) diff --git a/pkg/instance/instance.go b/pkg/instance/instance.go index f2f024216..411568e65 100644 --- a/pkg/instance/instance.go +++ b/pkg/instance/instance.go @@ -273,9 +273,7 @@ func (env *env) Test(numVMs int, reproSyz, reproOpts, reproC []byte) ([]EnvTestR return nil, fmt.Errorf("failed to create VM pool: %w", err) } defer vmPool.Close() - if n := vmPool.Count(); numVMs > n { - numVMs = n - } + numVMs = min(numVMs, vmPool.Count()) res := make(chan EnvTestResult, numVMs) for i := 0; i < numVMs; i++ { inst := &inst{ diff --git a/pkg/report/report.go b/pkg/report/report.go index d14e22f51..0006cb92b 100644 --- a/pkg/report/report.go +++ b/pkg/report/report.go @@ -219,11 +219,9 @@ func (reporter *Reporter) ParseFrom(output []byte, minReportPos int) *Report { if pos := bytes.IndexByte(rep.Output[rep.StartPos:], '\n'); pos != -1 { rep.SkipPos = rep.StartPos + pos } - if rep.EndPos < rep.SkipPos { - // This generally should not happen. - // But openbsd does some hacks with /r/n which may lead to off-by-one EndPos. - rep.EndPos = rep.SkipPos - } + // This generally should not happen. + // But openbsd does some hacks with /r/n which may lead to off-by-one EndPos. + rep.EndPos = max(rep.EndPos, rep.SkipPos) return rep } diff --git a/pkg/stat/set.go b/pkg/stat/set.go index 4982362d9..f6e327d92 100644 --- a/pkg/stat/set.go +++ b/pkg/stat/set.go @@ -233,9 +233,7 @@ func (s *set) New(name, desc string, opts ...any) *Val { lines: make(map[string]*line), } } - if s.graphs[v.graph].level < v.level { - s.graphs[v.graph].level = v.level - } + s.graphs[v.graph].level = max(s.graphs[v.graph].level, v.level) s.graphs[v.graph].stacked = stacked } return v @@ -345,9 +343,7 @@ func (s *set) tick() { *pv += float64(val-v.prev) / float64(s.historyScale) v.prev = val } else { - if *pv < float64(val) { - *pv = float64(val) - } + *pv = max(*pv, float64(val)) } } } diff --git a/pkg/vcs/linux.go b/pkg/vcs/linux.go index d348dd71e..c0b96aaa4 100644 --- a/pkg/vcs/linux.go +++ b/pkg/vcs/linux.go @@ -109,9 +109,7 @@ func gitReleaseTagToInt(tag string, includeRC bool) uint64 { if v1 < 0 { return 0 } - if v3 < 0 { - v3 = 0 - } + v3 = max(v3, 0) if rc >= 0 { if !includeRC { return 0 diff --git a/prog/alloc.go b/prog/alloc.go index a4b7b7f1f..0af8c5bde 100644 --- a/prog/alloc.go +++ b/prog/alloc.go @@ -151,15 +151,9 @@ func (va *vmaAlloc) alloc(r *randGen, size uint64) uint64 { } else { page = va.used[r.rand(len(va.used))] if size > 1 && r.bin() { - off := r.rand(int(size)) - if off > page { - off = page - } - page -= off - } - if page+size > va.numPages { - page = va.numPages - size + page -= min(r.rand(int(size)), page) } + page = min(page, va.numPages-size) } if page >= va.numPages || size > va.numPages || page+size > va.numPages { panic(fmt.Sprintf("vmaAlloc: bad page=%v size=%v numPages=%v", page, size, va.numPages)) diff --git a/prog/collide.go b/prog/collide.go index 67cca6ecb..3c8a076a1 100644 --- a/prog/collide.go +++ b/prog/collide.go @@ -105,18 +105,10 @@ func DupCallCollide(origProg *Prog, rand *rand.Rand) (*Prog, error) { // For 1-call programs the behavior is similar to DoubleExecCollide. return nil, fmt.Errorf("the prog is too small for the transformation") } - // By default let's duplicate 1/3 calls in the original program. - insert := len(origProg.Calls) / 3 - if insert == 0 { - // .. but always at least one. - insert = 1 - } - if insert > maxAsyncPerProg { - insert = maxAsyncPerProg - } - if insert+len(origProg.Calls) > MaxCalls { - insert = MaxCalls - len(origProg.Calls) - } + // By default let's duplicate 1/3 calls in the original program (but at least one). + insert := max(len(origProg.Calls)/3, 1) + insert = min(insert, maxAsyncPerProg) + insert = min(insert, MaxCalls-len(origProg.Calls)) if insert == 0 { return nil, fmt.Errorf("no calls could be duplicated") } diff --git a/prog/collide_test.go b/prog/collide_test.go index 54ac156ab..01c860a2b 100644 --- a/prog/collide_test.go +++ b/prog/collide_test.go @@ -182,10 +182,8 @@ dup(r2) }, } _, rs, iters := initTest(t) - if iters > 100 { - // Let's save resources -- we don't need that many for these small tests. - iters = 100 - } + // Let's save resources -- we don't need that many for these small tests. + iters = min(iters, 100) r := rand.New(rs) for _, test := range tests { target, err := GetTarget(test.os, test.arch) diff --git a/prog/decodeexec.go b/prog/decodeexec.go index 81c70cb2b..e6921c314 100644 --- a/prog/decodeexec.go +++ b/prog/decodeexec.go @@ -293,9 +293,7 @@ func (dec *execDecoder) commitCall() { dec.numVars = dec.call.Index + 1 } for _, copyout := range dec.call.Copyout { - if dec.numVars < copyout.Index+1 { - dec.numVars = copyout.Index + 1 - } + dec.numVars = max(dec.numVars, copyout.Index+1) } dec.calls = append(dec.calls, dec.call) dec.call = ExecCall{} diff --git a/prog/encoding.go b/prog/encoding.go index b614e247e..41a03d9fd 100644 --- a/prog/encoding.go +++ b/prog/encoding.go @@ -882,12 +882,8 @@ func (p *parser) parseAddr() (uint64, uint64, error) { } if !p.unsafe { maxMem := target.NumPages * target.PageSize - if vmaSize > maxMem { - vmaSize = maxMem - } - if addr > maxMem-vmaSize { - addr = maxMem - vmaSize - } + vmaSize = min(vmaSize, maxMem) + addr = min(addr, maxMem-vmaSize) } } p.Parse(')') diff --git a/prog/export_test.go b/prog/export_test.go index 54992dba1..0b1b8c599 100644 --- a/prog/export_test.go +++ b/prog/export_test.go @@ -47,11 +47,7 @@ func testEachTarget(t *testing.T, fn func(t *testing.T, target *Target)) { func testEachTargetRandom(t *testing.T, fn func(t *testing.T, target *Target, rs rand.Source, iters int)) { t.Parallel() targets := AllTargets() - iters := testutil.IterCount() - iters /= len(targets) - if iters < 3 { - iters = 3 - } + iters := max(testutil.IterCount()/len(targets), 3) rs0 := testutil.RandSource(t) for _, target := range targets { target := target diff --git a/prog/heatmap.go b/prog/heatmap.go index 2bfbceacc..5063d51ea 100644 --- a/prog/heatmap.go +++ b/prog/heatmap.go @@ -44,10 +44,7 @@ func (hm *GenericHeatmap) NumMutations() int { // + up to 4 mutations at random so that even small images can get more than one. n += hm.r.Intn(5) // But don't do too many as it will most likely corrupt the image. - if max := 10; n > max { - n = max - } - return n + return min(n, 10) } func (hm *GenericHeatmap) ChooseLocation() int { diff --git a/prog/heatmap_test.go b/prog/heatmap_test.go index 62a0c45e5..66f3d5e68 100644 --- a/prog/heatmap_test.go +++ b/prog/heatmap_test.go @@ -94,10 +94,7 @@ func (hm *GenericHeatmap) debugPrint(t *testing.T, data []byte, regions []region // Print data. t.Logf("data: len = %d", len(data)) for j := 0; j < len(data); j += granularity { - end := j + granularity - if end > len(data) { - end = len(data) - } + end := min(j+granularity, len(data)) t.Logf("%8d: %x", j*granularity, data[j:end]) } t.Log("\n") diff --git a/prog/hints.go b/prog/hints.go index a02d2d123..90ebab179 100644 --- a/prog/hints.go +++ b/prog/hints.go @@ -208,10 +208,7 @@ replacerLoop: func checkDataArg(arg *DataArg, compMap CompMap, exec func() bool) { bytes := make([]byte, 8) data := arg.Data() - size := len(data) - if size > maxDataLength { - size = maxDataLength - } + size := min(len(data), maxDataLength) for i := 0; i < size; i++ { original := make([]byte, 8) copy(original, data[i:]) @@ -307,10 +304,7 @@ func shrinkExpand(v uint64, compMap CompMap, bitsize uint64, image bool) []uint6 mutant = v & ((1 << size) - 1) } else { width = -iwidth - size = uint64(width) * 8 - if size > bitsize { - size = bitsize - } + size = min(uint64(width)*8, bitsize) if v&(1<<(size-1)) == 0 { continue } diff --git a/prog/mutation.go b/prog/mutation.go index c6cd3c7cf..eb9e8285d 100644 --- a/prog/mutation.go +++ b/prog/mutation.go @@ -60,9 +60,7 @@ func (p *Prog) MutateWithOpts(rs rand.Source, ncalls int, ct *ChoiceTable, noMut } totalWeight := opts.weight() r := newRand(p.Target, rs) - if ncalls < len(p.Calls) { - ncalls = len(p.Calls) - } + ncalls = max(ncalls, len(p.Calls)) ctx := &mutator{ p: p, r: r, @@ -454,12 +452,8 @@ func mutateBufferSize(r *randGen, arg *DataArg, minLen, maxLen uint64) { for oldSize := arg.Size(); oldSize == arg.Size(); { arg.size += uint64(r.Intn(33)) - 16 // Cast to int64 to prevent underflows. - if int64(arg.size) < int64(minLen) { - arg.size = minLen - } - if arg.size > maxLen { - arg.size = maxLen - } + arg.size = uint64(max(int64(arg.size), int64(minLen))) + arg.size = min(arg.size, maxLen) } } @@ -780,10 +774,7 @@ var mutateDataFuncs = [...]func(r *randGen, data []byte, minLen, maxLen uint64) if len(data) == 0 || uint64(len(data)) >= maxLen { return data, false } - n := r.Intn(16) + 1 - if r := int(maxLen) - len(data); n > r { - n = r - } + n := min(r.Intn(16)+1, int(maxLen)-len(data)) pos := r.Intn(len(data)) for i := 0; i < n; i++ { data = append(data, 0) @@ -802,10 +793,7 @@ var mutateDataFuncs = [...]func(r *randGen, data []byte, minLen, maxLen uint64) if len(data) == 0 { return data, false } - n := r.Intn(16) + 1 - if n > len(data) { - n = len(data) - } + n := min(r.Intn(16)+1, len(data)) pos := 0 if n < len(data) { pos = r.Intn(len(data) - n) @@ -825,10 +813,7 @@ var mutateDataFuncs = [...]func(r *randGen, data []byte, minLen, maxLen uint64) return data, false } const max = 256 - n := max - r.biasedRand(max, 10) - if r := int(maxLen) - len(data); n > r { - n = r - } + n := min(max-r.biasedRand(max, 10), int(maxLen)-len(data)) for i := 0; i < n; i++ { data = append(data, byte(r.rand(256))) } diff --git a/prog/prio.go b/prog/prio.go index 142ad36b4..a18008271 100644 --- a/prog/prio.go +++ b/prog/prio.go @@ -7,6 +7,7 @@ import ( "fmt" "math" "math/rand" + "slices" "sort" ) @@ -61,12 +62,7 @@ func (target *Target) calcStaticPriorities() [][]int32 { } // The value assigned for self-priority (call wrt itself) have to be high, but not too high. for c0, pp := range prios { - var max int32 - for _, p := range pp { - if p > max { - max = p - } - } + max := slices.Max(pp) if max == 0 { pp[c0] = 1 } else { diff --git a/prog/prog.go b/prog/prog.go index ec899e35f..c9bd05baa 100644 --- a/prog/prog.go +++ b/prog/prog.go @@ -272,9 +272,7 @@ func (arg *GroupArg) Size() uint64 { offset += typ.AlignAttr - offset%typ.AlignAttr } } - if size < offset { - size = offset - } + size = max(size, offset) } return size case *ArrayType: diff --git a/prog/rand.go b/prog/rand.go index 3e22cb845..957cf7112 100644 --- a/prog/rand.go +++ b/prog/rand.go @@ -323,11 +323,7 @@ func (r *randGen) randFilenameLength() int { off = -off } lens := r.target.SpecialFileLenghts - res := lens[r.Intn(len(lens))] + off - if res < 0 { - res = 0 - } - return res + return max(lens[r.Intn(len(lens))]+off, 0) } func (r *randGen) randFromMap(m map[string]bool) string { diff --git a/prog/rotation.go b/prog/rotation.go index 8ec9f1947..85513e8c8 100644 --- a/prog/rotation.go +++ b/prog/rotation.go @@ -110,17 +110,10 @@ func MakeRotator(target *Target, calls map[*Syscall]bool, rnd *rand.Rand) *Rotat // However, we assume that 200 syscalls is enough for a fuzzing session, // so we cap at that level to make fuzzing more targeted. r.goal = len(calls) * 19 / 20 - if r.goal < 1 { - r.goal = 1 - } - if max := 200; r.goal > max { - r.goal = max - } + r.goal = max(r.goal, 1) + r.goal = min(r.goal, 200) // How many syscalls that don't use any resources we want to add? - r.nresourceless = r.goal * len(r.resourceless) / len(calls) - if r.nresourceless < 1 { - r.nresourceless = 1 - } + r.nresourceless = max(1, r.goal*len(r.resourceless)/len(calls)) return r } diff --git a/sys/openbsd/init.go b/sys/openbsd/init.go index 2a2aeae4c..5d0c3a77c 100644 --- a/sys/openbsd/init.go +++ b/sys/openbsd/init.go @@ -196,12 +196,8 @@ func (arch *arch) neutralizeRlimit(c *prog.Call) { for _, arg := range args { switch v := arg.(type) { case *prog.ConstArg: - if v.Val < rlimitMin { - v.Val = rlimitMin - } - if v.Val > rlimitMax { - v.Val = rlimitMax - } + v.Val = max(v.Val, rlimitMin) + v.Val = min(v.Val, rlimitMax) } } } diff --git a/sys/targets/targets.go b/sys/targets/targets.go index fa2f6f0e2..c571d1165 100644 --- a/sys/targets/targets.go +++ b/sys/targets/targets.go @@ -825,10 +825,7 @@ func (target *Target) Timeouts(slowdown int) Timeouts { } timeouts := target.timeouts timeouts.Slowdown = slowdown - timeouts.Scale = time.Duration(slowdown) - if timeouts.Scale > 3 { - timeouts.Scale = 3 - } + timeouts.Scale = min(time.Duration(slowdown), 3) if timeouts.Syscall == 0 { timeouts.Syscall = 50 * time.Millisecond } diff --git a/syz-hub/state/state.go b/syz-hub/state/state.go index 4d25c20a3..0bed36a91 100644 --- a/syz-hub/state/state.go +++ b/syz-hub/state/state.go @@ -134,9 +134,7 @@ func loadDB(file, name string, progs bool) (*db.DB, uint64, error) { continue } } - if maxSeq < rec.Seq { - maxSeq = rec.Seq - } + maxSeq = max(maxSeq, rec.Seq) } if err := db.Flush(); err != nil { return nil, 0, fmt.Errorf("failed to flush corpus database: %w", err) @@ -157,16 +155,12 @@ func (st *State) createManager(name string) (*Manager, error) { ownRepros: make(map[string]bool), } mgr.corpusSeq = loadSeqFile(mgr.corpusSeqFile) - if st.corpusSeq < mgr.corpusSeq { - st.corpusSeq = mgr.corpusSeq - } + st.corpusSeq = max(st.corpusSeq, mgr.corpusSeq) mgr.reproSeq = loadSeqFile(mgr.reproSeqFile) if mgr.reproSeq == 0 { mgr.reproSeq = st.reproSeq } - if st.reproSeq < mgr.reproSeq { - st.reproSeq = mgr.reproSeq - } + st.reproSeq = max(st.reproSeq, mgr.reproSeq) domainData, _ := os.ReadFile(mgr.domainFile) mgr.Domain = string(domainData) corpus, _, err := loadDB(mgr.corpusFile, name, false) diff --git a/tools/syz-check/check.go b/tools/syz-check/check.go index 6a0b4378b..f42512c02 100644 --- a/tools/syz-check/check.go +++ b/tools/syz-check/check.go @@ -726,7 +726,7 @@ func attrSize(policy nlaPolicy) (int, int, int) { return -1, -1, -1 } -func typeMinMaxValue(payload prog.Type) (min, max uint64, ok bool) { +func typeMinMaxValue(payload prog.Type) (minVal, maxVal uint64, ok bool) { switch typ := payload.(type) { case *prog.ConstType: return typ.Val, typ.Val, true @@ -736,16 +736,12 @@ func typeMinMaxValue(payload prog.Type) (min, max uint64, ok bool) { } return 0, ^uint64(0), true case *prog.FlagsType: - min, max := ^uint64(0), uint64(0) + minVal, maxVal := ^uint64(0), uint64(0) for _, v := range typ.Vals { - if min > v { - min = v - } - if max < v { - max = v - } + minVal = min(minVal, v) + maxVal = max(maxVal, v) } - return min, max, true + return minVal, maxVal, true } return 0, 0, false } diff --git a/tools/syz-testbed/stats.go b/tools/syz-testbed/stats.go index 6044bfe3d..9f338f4bb 100644 --- a/tools/syz-testbed/stats.go +++ b/tools/syz-testbed/stats.go @@ -217,10 +217,7 @@ func (group RunResultGroup) minResultLength() int { results := group.SyzManagerResults() ret := len(results[0].StatRecords) for _, result := range results { - currLen := len(result.StatRecords) - if currLen < ret { - ret = currLen - } + ret = min(ret, len(result.StatRecords)) } return ret } @@ -445,9 +445,7 @@ func (mon *monitor) appendOutput(out []byte) (*report.Report, bool) { } mon.matchPos-- } - if mon.matchPos < 0 { - mon.matchPos = 0 - } + mon.matchPos = max(mon.matchPos, 0) return nil, false } @@ -510,14 +508,8 @@ func (mon *monitor) createReport(defaultError string) *report.Report { Type: typ, } } - start := rep.StartPos - mon.beforeContext - if start < 0 { - start = 0 - } - end := rep.EndPos + afterContext - if end > len(rep.Output) { - end = len(rep.Output) - } + start := max(rep.StartPos-mon.beforeContext, 0) + end := min(rep.EndPos+afterContext, len(rep.Output)) rep.Output = rep.Output[start:end] rep.StartPos -= start rep.EndPos -= start diff --git a/vm/vmimpl/console.go b/vm/vmimpl/console.go index a2dedeb5c..200c44f73 100644 --- a/vm/vmimpl/console.go +++ b/vm/vmimpl/console.go @@ -61,10 +61,7 @@ func (t *tty) Read(buf []byte) (int, error) { return 0, io.EOF } n, err := syscall.Read(t.fd, buf) - if n < 0 { - n = 0 - } - return n, err + return max(n, 0), err } func (t *tty) Close() error { |
